+
+
+
+
\ No newline at end of file
diff --git a/app/index_backup.html b/app/index_backup.html
new file mode 100644
index 0000000..e2636ea
--- /dev/null
+++ b/app/index_backup.html
@@ -0,0 +1,216 @@
+
+
+
+
+ Ninja Store - Items
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/app/node_modules/formidable/.npmignore b/app/node_modules/formidable/.npmignore
new file mode 100644
index 0000000..4fbabb3
--- /dev/null
+++ b/app/node_modules/formidable/.npmignore
@@ -0,0 +1,4 @@
+/test/tmp/
+*.upload
+*.un~
+*.http
diff --git a/app/node_modules/formidable/.travis.yml b/app/node_modules/formidable/.travis.yml
new file mode 100644
index 0000000..f1d0f13
--- /dev/null
+++ b/app/node_modules/formidable/.travis.yml
@@ -0,0 +1,4 @@
+language: node_js
+node_js:
+ - 0.4
+ - 0.6
diff --git a/app/node_modules/formidable/Makefile b/app/node_modules/formidable/Makefile
new file mode 100644
index 0000000..8945872
--- /dev/null
+++ b/app/node_modules/formidable/Makefile
@@ -0,0 +1,14 @@
+SHELL := /bin/bash
+
+test:
+ @./test/run.js
+
+build: npm test
+
+npm:
+ npm install .
+
+clean:
+ rm test/tmp/*
+
+.PHONY: test clean build
diff --git a/app/node_modules/formidable/Readme.md b/app/node_modules/formidable/Readme.md
new file mode 100644
index 0000000..a5ca104
--- /dev/null
+++ b/app/node_modules/formidable/Readme.md
@@ -0,0 +1,311 @@
+# Formidable
+
+[](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/app/node_modules/formidable/TODO b/app/node_modules/formidable/TODO
new file mode 100644
index 0000000..e1107f2
--- /dev/null
+++ b/app/node_modules/formidable/TODO
@@ -0,0 +1,3 @@
+- Better bufferMaxSize handling approach
+- Add tests for JSON parser pull request and merge it
+- Implement QuerystringParser the same way as MultipartParser
diff --git a/app/node_modules/formidable/benchmark/bench-multipart-parser.js b/app/node_modules/formidable/benchmark/bench-multipart-parser.js
new file mode 100644
index 0000000..bff41f1
--- /dev/null
+++ b/app/node_modules/formidable/benchmark/bench-multipart-parser.js
@@ -0,0 +1,70 @@
+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/app/node_modules/formidable/example/post.js b/app/node_modules/formidable/example/post.js
new file mode 100644
index 0000000..f6c15a6
--- /dev/null
+++ b/app/node_modules/formidable/example/post.js
@@ -0,0 +1,43 @@
+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/app/node_modules/formidable/example/upload.js b/app/node_modules/formidable/example/upload.js
new file mode 100644
index 0000000..050cdd9
--- /dev/null
+++ b/app/node_modules/formidable/example/upload.js
@@ -0,0 +1,48 @@
+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/app/node_modules/formidable/index.js b/app/node_modules/formidable/index.js
new file mode 100644
index 0000000..be41032
--- /dev/null
+++ b/app/node_modules/formidable/index.js
@@ -0,0 +1 @@
+module.exports = require('./lib/formidable');
\ No newline at end of file
diff --git a/app/node_modules/formidable/lib/file.js b/app/node_modules/formidable/lib/file.js
new file mode 100644
index 0000000..dad8d5f
--- /dev/null
+++ b/app/node_modules/formidable/lib/file.js
@@ -0,0 +1,73 @@
+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/app/node_modules/formidable/lib/incoming_form.js b/app/node_modules/formidable/lib/incoming_form.js
new file mode 100644
index 0000000..060eac2
--- /dev/null
+++ b/app/node_modules/formidable/lib/incoming_form.js
@@ -0,0 +1,384 @@
+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/app/node_modules/formidable/lib/index.js b/app/node_modules/formidable/lib/index.js
new file mode 100644
index 0000000..7a6e3e1
--- /dev/null
+++ b/app/node_modules/formidable/lib/index.js
@@ -0,0 +1,3 @@
+var IncomingForm = require('./incoming_form').IncomingForm;
+IncomingForm.IncomingForm = IncomingForm;
+module.exports = IncomingForm;
diff --git a/app/node_modules/formidable/lib/multipart_parser.js b/app/node_modules/formidable/lib/multipart_parser.js
new file mode 100644
index 0000000..9ca567c
--- /dev/null
+++ b/app/node_modules/formidable/lib/multipart_parser.js
@@ -0,0 +1,312 @@
+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/app/node_modules/formidable/lib/querystring_parser.js b/app/node_modules/formidable/lib/querystring_parser.js
new file mode 100644
index 0000000..63f109e
--- /dev/null
+++ b/app/node_modules/formidable/lib/querystring_parser.js
@@ -0,0 +1,25 @@
+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/app/node_modules/formidable/lib/util.js b/app/node_modules/formidable/lib/util.js
new file mode 100644
index 0000000..e9493e9
--- /dev/null
+++ b/app/node_modules/formidable/lib/util.js
@@ -0,0 +1,6 @@
+// Backwards compatibility ...
+try {
+ module.exports = require('util');
+} catch (e) {
+ module.exports = require('sys');
+}
diff --git a/app/node_modules/formidable/node-gently/Makefile b/app/node_modules/formidable/node-gently/Makefile
new file mode 100644
index 0000000..01f7140
--- /dev/null
+++ b/app/node_modules/formidable/node-gently/Makefile
@@ -0,0 +1,4 @@
+test:
+ @find test/simple/test-*.js | xargs -n 1 -t node
+
+.PHONY: test
\ No newline at end of file
diff --git a/app/node_modules/formidable/node-gently/Readme.md b/app/node_modules/formidable/node-gently/Readme.md
new file mode 100644
index 0000000..f8f0c66
--- /dev/null
+++ b/app/node_modules/formidable/node-gently/Readme.md
@@ -0,0 +1,167 @@
+# 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/app/node_modules/formidable/node-gently/example/dog.js b/app/node_modules/formidable/node-gently/example/dog.js
new file mode 100644
index 0000000..022fae0
--- /dev/null
+++ b/app/node_modules/formidable/node-gently/example/dog.js
@@ -0,0 +1,22 @@
+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/app/node_modules/formidable/node-gently/example/event_emitter.js b/app/node_modules/formidable/node-gently/example/event_emitter.js
new file mode 100644
index 0000000..7def134
--- /dev/null
+++ b/app/node_modules/formidable/node-gently/example/event_emitter.js
@@ -0,0 +1,11 @@
+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/app/node_modules/formidable/node-gently/index.js b/app/node_modules/formidable/node-gently/index.js
new file mode 100644
index 0000000..69122bd
--- /dev/null
+++ b/app/node_modules/formidable/node-gently/index.js
@@ -0,0 +1 @@
+module.exports = require('./lib/gently');
\ No newline at end of file
diff --git a/app/node_modules/formidable/node-gently/lib/gently/gently.js b/app/node_modules/formidable/node-gently/lib/gently/gently.js
new file mode 100644
index 0000000..8af0e1e
--- /dev/null
+++ b/app/node_modules/formidable/node-gently/lib/gently/gently.js
@@ -0,0 +1,184 @@
+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/app/node_modules/formidable/node-gently/lib/gently/index.js b/app/node_modules/formidable/node-gently/lib/gently/index.js
new file mode 100644
index 0000000..64c1977
--- /dev/null
+++ b/app/node_modules/formidable/node-gently/lib/gently/index.js
@@ -0,0 +1 @@
+module.exports = require('./gently');
\ No newline at end of file
diff --git a/app/node_modules/formidable/node-gently/package.json b/app/node_modules/formidable/node-gently/package.json
new file mode 100644
index 0000000..9c1b7a0
--- /dev/null
+++ b/app/node_modules/formidable/node-gently/package.json
@@ -0,0 +1,14 @@
+{
+ "name": "gently",
+ "version": "0.9.2",
+ "directories": {
+ "lib": "./lib/gently"
+ },
+ "main": "./lib/gently/index",
+ "dependencies": {},
+ "devDependencies": {},
+ "engines": {
+ "node": "*"
+ },
+ "optionalDependencies": {}
+}
diff --git a/app/node_modules/formidable/node-gently/test/common.js b/app/node_modules/formidable/node-gently/test/common.js
new file mode 100644
index 0000000..978b5c5
--- /dev/null
+++ b/app/node_modules/formidable/node-gently/test/common.js
@@ -0,0 +1,8 @@
+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/app/node_modules/formidable/node-gently/test/simple/test-gently.js b/app/node_modules/formidable/node-gently/test/simple/test-gently.js
new file mode 100644
index 0000000..4f8fe2d
--- /dev/null
+++ b/app/node_modules/formidable/node-gently/test/simple/test-gently.js
@@ -0,0 +1,348 @@
+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/app/node_modules/formidable/package.json b/app/node_modules/formidable/package.json
new file mode 100644
index 0000000..c8f8f01
--- /dev/null
+++ b/app/node_modules/formidable/package.json
@@ -0,0 +1,29 @@
+{
+ "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": {},
+ "_id": "formidable@1.0.11",
+ "_engineSupported": true,
+ "_npmVersion": "1.1.21",
+ "_nodeVersion": "v0.6.18",
+ "_defaultsLoaded": true,
+ "_from": "formidable"
+}
diff --git a/app/node_modules/formidable/test/common.js b/app/node_modules/formidable/test/common.js
new file mode 100644
index 0000000..eb432ad
--- /dev/null
+++ b/app/node_modules/formidable/test/common.js
@@ -0,0 +1,19 @@
+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/app/node_modules/formidable/test/fixture/file/funkyfilename.txt b/app/node_modules/formidable/test/fixture/file/funkyfilename.txt
new file mode 100644
index 0000000..e7a4785
--- /dev/null
+++ b/app/node_modules/formidable/test/fixture/file/funkyfilename.txt
@@ -0,0 +1 @@
+I am a text file with a funky name!
diff --git a/app/node_modules/formidable/test/fixture/file/plain.txt b/app/node_modules/formidable/test/fixture/file/plain.txt
new file mode 100644
index 0000000..9b6903e
--- /dev/null
+++ b/app/node_modules/formidable/test/fixture/file/plain.txt
@@ -0,0 +1 @@
+I am a plain text file
diff --git a/app/node_modules/formidable/test/fixture/http/special-chars-in-filename/info.md b/app/node_modules/formidable/test/fixture/http/special-chars-in-filename/info.md
new file mode 100644
index 0000000..3c9dbe3
--- /dev/null
+++ b/app/node_modules/formidable/test/fixture/http/special-chars-in-filename/info.md
@@ -0,0 +1,3 @@
+* 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/app/node_modules/formidable/test/fixture/js/no-filename.js b/app/node_modules/formidable/test/fixture/js/no-filename.js
new file mode 100644
index 0000000..0bae449
--- /dev/null
+++ b/app/node_modules/formidable/test/fixture/js/no-filename.js
@@ -0,0 +1,3 @@
+module.exports['generic.http'] = [
+ {type: 'file', name: 'upload', filename: '', fixture: 'plain.txt'},
+];
diff --git a/app/node_modules/formidable/test/fixture/js/special-chars-in-filename.js b/app/node_modules/formidable/test/fixture/js/special-chars-in-filename.js
new file mode 100644
index 0000000..eb76fdc
--- /dev/null
+++ b/app/node_modules/formidable/test/fixture/js/special-chars-in-filename.js
@@ -0,0 +1,21 @@
+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/app/node_modules/formidable/test/fixture/multipart.js b/app/node_modules/formidable/test/fixture/multipart.js
new file mode 100644
index 0000000..a476169
--- /dev/null
+++ b/app/node_modules/formidable/test/fixture/multipart.js
@@ -0,0 +1,72 @@
+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/app/node_modules/formidable/test/integration/test-fixtures.js b/app/node_modules/formidable/test/integration/test-fixtures.js
new file mode 100644
index 0000000..66ad259
--- /dev/null
+++ b/app/node_modules/formidable/test/integration/test-fixtures.js
@@ -0,0 +1,89 @@
+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/app/node_modules/formidable/test/legacy/common.js b/app/node_modules/formidable/test/legacy/common.js
new file mode 100644
index 0000000..2b98598
--- /dev/null
+++ b/app/node_modules/formidable/test/legacy/common.js
@@ -0,0 +1,24 @@
+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/app/node_modules/formidable/test/legacy/integration/test-multipart-parser.js b/app/node_modules/formidable/test/legacy/integration/test-multipart-parser.js
new file mode 100644
index 0000000..75232aa
--- /dev/null
+++ b/app/node_modules/formidable/test/legacy/integration/test-multipart-parser.js
@@ -0,0 +1,80 @@
+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/app/node_modules/formidable/test/legacy/simple/test-file.js b/app/node_modules/formidable/test/legacy/simple/test-file.js
new file mode 100644
index 0000000..52ceedb
--- /dev/null
+++ b/app/node_modules/formidable/test/legacy/simple/test-file.js
@@ -0,0 +1,104 @@
+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/app/node_modules/formidable/test/legacy/simple/test-incoming-form.js b/app/node_modules/formidable/test/legacy/simple/test-incoming-form.js
new file mode 100644
index 0000000..84de439
--- /dev/null
+++ b/app/node_modules/formidable/test/legacy/simple/test-incoming-form.js
@@ -0,0 +1,727 @@
+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/app/node_modules/formidable/test/legacy/simple/test-multipart-parser.js b/app/node_modules/formidable/test/legacy/simple/test-multipart-parser.js
new file mode 100644
index 0000000..d8dc968
--- /dev/null
+++ b/app/node_modules/formidable/test/legacy/simple/test-multipart-parser.js
@@ -0,0 +1,50 @@
+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/app/node_modules/formidable/test/legacy/simple/test-querystring-parser.js b/app/node_modules/formidable/test/legacy/simple/test-querystring-parser.js
new file mode 100644
index 0000000..54d3e2d
--- /dev/null
+++ b/app/node_modules/formidable/test/legacy/simple/test-querystring-parser.js
@@ -0,0 +1,45 @@
+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/app/node_modules/formidable/test/legacy/system/test-multi-video-upload.js b/app/node_modules/formidable/test/legacy/system/test-multi-video-upload.js
new file mode 100644
index 0000000..479e46d
--- /dev/null
+++ b/app/node_modules/formidable/test/legacy/system/test-multi-video-upload.js
@@ -0,0 +1,75 @@
+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/app/node_modules/formidable/test/run.js b/app/node_modules/formidable/test/run.js
new file mode 100644
index 0000000..50b2361
--- /dev/null
+++ b/app/node_modules/formidable/test/run.js
@@ -0,0 +1,2 @@
+#!/usr/bin/env node
+require('urun')(__dirname)
diff --git a/app/node_modules/formidable/test/unit/test-incoming-form.js b/app/node_modules/formidable/test/unit/test-incoming-form.js
new file mode 100644
index 0000000..fe2ac1c
--- /dev/null
+++ b/app/node_modules/formidable/test/unit/test-incoming-form.js
@@ -0,0 +1,63 @@
+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/app/node_modules/formidable/tool/record.js b/app/node_modules/formidable/tool/record.js
new file mode 100644
index 0000000..9f1cef8
--- /dev/null
+++ b/app/node_modules/formidable/tool/record.js
@@ -0,0 +1,47 @@
+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/app/node_modules/mongoskin/.npmignore b/app/node_modules/mongoskin/.npmignore
new file mode 100644
index 0000000..3c3629e
--- /dev/null
+++ b/app/node_modules/mongoskin/.npmignore
@@ -0,0 +1 @@
+node_modules
diff --git a/app/node_modules/mongoskin/History.md b/app/node_modules/mongoskin/History.md
new file mode 100644
index 0000000..6a6ee24
--- /dev/null
+++ b/app/node_modules/mongoskin/History.md
@@ -0,0 +1,47 @@
+0.3.4 / 2011-03-24
+ * fix global leaks
+
+0.3.3 / 2011-03-15
+==================
+ * Add rootCollection option to SkinGridStore.exist
+
+0.3.2 / 2011-03-01
+==================
+ * exports all classes of node-mongodb-native
+
+0.3.1 / 2011-02-26
+==================
+ * bug fix #33
+
+0.3.0 / 2011-01-19
+==================
+ * add ReplSet support
+ * bug fix
+
+0.2.3 / 2011-01-03
+==================
+ * add db.toObjectID
+ * fix #25 for node-mongodb-native update
+
+0.2.2 / 2011-12-02
+==================
+ * add bind support for embeded collections, e.g. db.bind('system.js')
+ * add method `toId` to SkinDB
+ * add property `ObjectID`, `bson_serializer` to SkinDB.
+ * SkinCollection.prototype.id is now deprecated.
+
+0.2.1 / 2011-11-18
+==================
+ * add ObjectId support for XXXXById
+
+0.2.0 / 2011-11-06
+==================
+ * add SkinDB.gridfs
+
+0.1.3 / 2011-05-24
+==================
+ * add SkinCollection.removeById
+
+0.1.2 / 2011-04-30
+==================
+ * add mongoskin.router
diff --git a/app/node_modules/mongoskin/Readme.md b/app/node_modules/mongoskin/Readme.md
new file mode 100644
index 0000000..a4d9547
--- /dev/null
+++ b/app/node_modules/mongoskin/Readme.md
@@ -0,0 +1,570 @@
+## This project is a wrapper of node-mongodb-native
+
+* node-mongodb-native document http://christkv.github.com/node-mongodb-native/
+
+## How to validate input?
+
+I wrote a middleware to validate post data, [node-iform](https://github.com/guileen/node-iform)
+base on [node-validator](https://github.com/chriso/node-validator)
+
+
+
+# Mongoskin document
+
+* [Nodejs mongodb drivers comparation](#comparation)
+* [Install](#install)
+* [Quick Start](#quickstart)
+ * [Connect easier](#quickstart-1)
+ * [Server options and BSON options](#quickstart-2)
+ * [Similar API with node-mongodb-native](#quickstart-3)
+ * [Cursor easier](#quickstart-4)
+ * [MVC helper](#quickstart-5)
+* [Documentation](#documentation)
+ * [Module](#module)
+ * [SkinServer](#skinserver)
+ * [SkinDb](#skindb)
+ * [SkinCollection](#skincollection)
+ * [Additional methods](#additional-collection-op)
+ * [Collection operation](#inherit-collection-op)
+ * [Indexes](#inherit-indexes)
+ * [Querying](#inherit-query)
+ * [Aggregation](#inherit-aggregation)
+ * [Inserting](#inherit-inserting)
+ * [Updating](#inherit-updating)
+ * [Removing](#inherit-removing)
+ * [SkinCursor](#skincursor)
+
+
+
+Nodejs Mongodb Driver Comparison
+========
+
+node-mongodb-native
+--------
+
+One of the most powerful Mongo drivers is node-mongodb-native. Most other drivers build
+on top of it, including mongoskin. Unfortunately, it has an awkward interface with too many
+callbacks. Also, mongoskin needs a way to hold a Collection instance as an MVC model.
+
+See [mongodb-native](https://github.com/christkv/node-mongodb-native/tree/master/docs)
+
+mongoose
+--------
+
+Mongoose provides an ORM way to hold Collection instance as Model,
+ you should define schema first. But why mongodb need schema?
+ Some guys like me, want to write code from application layer but not database layer,
+ and we can use any fields without define it before.
+
+ Mongoose provide a DAL that you can do validation, and write your middlewares.
+ But some guys like me would like to validate manually, I think it is the tao of mongodb.
+
+ If you don't thinks so, [Mongoose-ORM](https://github.com/LearnBoost/mongoose) is probably your choice.
+
+mongoskin
+--------
+
+Mongoskin is an easy to use driver of mongodb for nodejs,
+ it is similar with mongo shell, powerful like node-mongodb-native,
+ and support additional javascript method binding, which make it can act as a Model(in document way).
+
+It will provide full features of [node-mongodb-native](https://github.com/christkv/node-mongodb-native),
+ and make it [future](http://en.wikipedia.org/wiki/Future_%28programming%29).
+
+If you need validation, you can use [node-iform](https://github.com/guileen/node-iform).
+
+[Back to index](#index)
+
+
+
+Install
+========
+
+ npm install mongoskin
+
+[Back to index](#index)
+
+
+
+
+Quick Start
+========
+
+ **Is mongoskin synchronized?**
+
+Nope! It is asynchronized, it use the [future pattern](http://en.wikipedia.org/wiki/Future_%28programming%29).
+**Mongoskin** is the future layer above [node-mongodb-native](https://github.com/christkv/node-mongodb-native)
+
+
+
+Connect easier
+--------
+You can connect to mongodb easier now.
+
+ var mongo = require('mongoskin');
+ mongo.db('localhost:27017/testdb').collection('blog').find().toArray(function(err, items){
+ console.dir(items);
+ })
+
+
+
+Server options and BSON options
+--------
+You can also set `auto_reconnect` options querystring.
+And native_parser options will automatically set if native_parser is avariable.
+
+ var mongo = require('mongoskin'),
+ db = mongo.db('localhost:27017/test?auto_reconnect');
+
+
+
+Similar API with node-mongodb-native
+--------
+You can do everything that node-mongodb-native can do.
+
+ db.createCollection(...);
+ db.collection('user').ensureIndex([['username', 1]], true, function(err, replies){});
+ db.collection('posts').hint = 'slug';
+ db.collection('posts').findOne({slug: 'whats-up'}, function(err, post){
+ // do something
+ });
+
+
+
+Cursor easier
+--------
+
+ db.collection('posts').find().toArray(function(err, posts){
+ // do something
+ });
+
+
+
+MVC helper
+--------
+
+You can bind **additional methods** for collection.
+It is very useful if you want to use MVC patterns with nodejs and mongodb.
+You can also invoke collection by properties after bind,
+it could simplfy your `require`.
+
+ db.bind('posts', {
+ findTop10 : function(fn){
+ this.find({}, {limit:10, sort:[['views', -1]]}).toArray(fn);
+ },
+ removeTagWith : function(tag, fn){
+ this.remove({tags:tag},fn);
+ }
+ });
+
+ db.bind('comments');
+
+ db.collection('posts').removeTagWith('delete', function(err, replies){
+ //do something
+ });
+
+ db.posts.findTop10(function(err, topPosts){
+ //do something
+ });
+
+ db.comments.find().toArray(function(err, comments){
+ //do something
+ });
+
+[Back to index](#index)
+
+
+
+
+Documentation
+========
+
+for more information, see the source.
+
+[Back to index](#index)
+
+
+
+
+Module
+--------
+
+### MongoSkin Url format
+
+ [*://][username:password@]host[:port][/database][?auto_reconnect[=true|false]]`
+
+e.g.
+
+ localhost/blog
+ mongo://admin:pass@127.0.0.1:27017/blog?auto_reconnect
+ 127.0.0.1?auto_reconnect=false
+
+### db(databaseUrl, db_options)
+
+Get or create instance of [SkinDb](#skindb).
+
+ var db = mongoskin.db('localhost:27017/testdb?auto_reconnect=true&poolSize=5');
+
+for ReplSet server
+
+ var db = mongoskin.db(['192.168.0.1:27017/?auto_reconnect=true',
+ '192.168.0.2:27017/?auto_reconnect=true',
+ '192.168.0.3:27017/?auto_reconnect=true'],
+ {
+ database: 'testdb',
+ retryMiliSeconds: 2000
+ })
+
+### router(select)
+
+select is function(collectionName) returns a database instance, means router collectionName to that database.
+
+ var db = mongo.router(function(coll_name){
+ switch(coll_name) {
+ case 'user':
+ case 'message':
+ return mongo.db('192.168.1.3/auth_db');
+ default:
+ return mongo.db('192.168.1.2/app_db');
+ }
+ });
+ db.bind('user', require('./shared-user-methods'));
+ var users = db.user; //auth_db.user
+ var messages = db.collection('message'); // auth_db.message
+ var products = db.collection('product'); //app_db.product
+
+### classes extends frome node-mongodb-native
+
+* BSONPure
+* BSONNative
+* BinaryParser
+* Binary
+* Code
+* DBRef
+* Double
+* MaxKey
+* MinKey
+* ObjectID
+* Symbol
+* Timestamp
+* Long
+* BaseCommand
+* DbCommand
+* DeleteCommand
+* GetMoreCommand
+* InsertCommand
+* KillCursorCommand
+* QueryCommand
+* UpdateCommand
+* MongoReply
+* Admin
+* Collection
+* Connection
+* Server
+* ReplSetServers
+* Cursor
+* Db
+* connect
+* Grid
+* Chunk
+* GridStore
+* native
+* pure
+
+
+[Back to index](#index)
+
+
+
+SkinServer
+--------
+
+### SkinServer(server)
+
+Construct SkinServer from native Server instance.
+
+### db(dbname, username=null, password=null)
+
+Construct [SkinDb](#skindb) from SkinServer.
+
+[Back to index](#index)
+
+
+
+SkinDb
+--------
+
+### SkinDb(db, username=null, password=null)
+
+Construct SkinDb.
+
+### open(callback)
+
+Connect to database, retrieval native
+[Db](https://github.com/christkv/node-mongodb-native/blob/master/lib/mongodb/db.js#L17)
+instance, callback is function(err, db).
+
+### collection(collectionName)
+
+Retrieval [SkinCollection](#skincollection) instance of specified collection name.
+
+
+
+### bind(collectionName)
+
+### bind(collectionName, SkinCollection)
+
+### bind(collectionName, extendObject1, extendObject2 ...)
+
+Bind [SkinCollection](#skincollection) to db properties as a shortcut to db.collection(name).
+You can also bind additional methods to the SkinCollection, it is useful when
+you want to reuse a complex operation. This will also affect
+db.collection(name) method.
+
+e.g.
+
+ db.bind('book', {
+ firstBook: function(fn){
+ this.findOne(fn);
+ }
+ });
+ db.book.firstBook(function(err, book){});
+
+### all the methods from Db.prototype
+
+See [Db](https://github.com/christkv/node-mongodb-native/blob/master/lib/mongodb/db.js#L17) of node-mongodb-native for more information.
+
+[Back to index](#index)
+
+
+
+SkinCollection
+--------
+
+See [Collection](https://github.com/christkv/node-mongodb-native/blob/master/lib/mongodb/collection.js#L45) of node-mongodb-native for more information.
+
+
+### open(callback)
+
+Retrieval native
+[Collection](https://github.com/christkv/node-mongodb-native/blob/master/lib/mongodb/collection.js#L45)
+instance, callback is function(err, collection).
+
+### id(hex)
+
+Equivalent to
+
+ db.bson_serializer.ObjectID.createFromHexString(hex);
+
+See [ObjectID.createFromHexString](https://github.com/christkv/node-mongodb-native/blob/master/lib/mongodb/bson/bson.js#L548)
+
+
+
+
+### Collection operation
+
+ checkCollectionName(collectionName)
+ options(callback)
+ rename(collectionName, callback)
+ drop(callback)
+
+
+
+### Indexes
+
+ createIndex (fieldOrSpec, unique, callback)
+ ensureIndex (fieldOrSpec, unique, callback)
+ indexInformation (callback)
+ dropIndex (indexName, callback)
+ dropIndexes (callback)
+
+See [mongodb-native indexes](https://github.com/christkv/node-mongodb-native/blob/master/docs/indexes.md)
+
+
+
+### Queries
+
+See [mongodb-native queries](https://github.com/christkv/node-mongodb-native/blob/master/docs/queries.md)
+
+#### findItems(..., callback)
+
+Equivalent to
+
+ collection.find(..., function(err, cursor){
+ cursor.toArray(callback);
+ });
+
+See [Collection.find](https://github.com/christkv/node-mongodb-native/blob/master/lib/mongodb/collection.js#L348)
+
+#### findEach(..., callback)
+
+Equivalent to
+
+ collection.find(..., function(err, cursor){
+ cursor.each(callback);
+ });
+
+See [Collection.find](https://github.com/christkv/node-mongodb-native/blob/master/lib/mongodb/collection.js#L348)
+
+#### findById(id, ..., callback)
+
+Equivalent to
+
+ collection.findOne({_id, ObjectID.createFromHexString(id)}, ..., callback);
+
+See [Collection.findOne](https://github.com/christkv/node-mongodb-native/blob/master/lib/mongodb/collection.js#L417)
+
+#### find(...)
+
+If the last parameter is function, it is equivalent to native
+[Collection.find](https://github.com/christkv/node-mongodb-native/blob/master/lib/mongodb/collection.js#L348)
+method, else it will return a future [SkinCursor](#skincursor).
+
+e.g.
+
+ // callback
+ db.book.find({}, function(err, cursor){/* do something */});
+ // future SkinCursor
+ db.book.find().toArray(function(err, books){/* do something */});
+
+
+
+#### normalizeHintField(hint)
+
+#### find
+
+ /**
+ * Various argument possibilities
+ * 1 callback
+ * 2 selector, callback,
+ * 2 callback, options // really?!
+ * 3 selector, fields, callback
+ * 3 selector, options, callback
+ * 4,selector, fields, options, callback
+ * 5 selector, fields, skip, limit, callback
+ * 6 selector, fields, skip, limit, timeout, callback
+ *
+ * Available options:
+ * limit, sort, fields, skip, hint, explain, snapshot, timeout, tailable, batchSize
+ */
+
+#### findAndModify(query, sort, update, options, callback)
+
+ /**
+ Fetch and update a collection
+ query: a filter for the query
+ sort: if multiple docs match, choose the first one in the specified sort order as the object to manipulate
+ update: an object describing the modifications to the documents selected by the query
+ options:
+ remove: set to a true to remove the object before returning
+ new: set to true if you want to return the modified object rather than the original. Ignored for remove.
+ upsert: true/false (perform upsert operation)
+ **/
+
+#### findOne(queryObject, options, callback)
+
+
+
+### Aggregation
+
+#### mapReduce(map, reduce, options, callback)
+
+ e.g. ```
+ var map = function(){
+ emit(test(this.timestamp.getYear()), 1);
+ }
+
+ var reduce = function(k, v){
+ count = 0;
+ for(i = 0; i < v.length; i++) {
+ count += v[i];
+ }
+ return count;
+ }
+ collection.mapReduce(map, reduce, {scope:{test:new client.bson_serializer.Code(t.toString())}}, function(err, collection) {
+ collection.find(function(err, cursor) {
+ cursor.toArray(function(err, results) {
+ test.equal(2, results[0].value)
+ finished_test({test_map_reduce_functions_scope:'ok'});
+ })
+ })
+ ```
+
+#### group(keys, condition, initial, reduce, command, callback)
+
+ e.g. `collection.group([], {}, {"count":0}, "function (obj, prev) { prev.count++; }", true, function(err, results) {`
+
+#### count(query, callback)
+#### distinct(key, query, callback)
+
+
+
+### Inserting
+
+#### insert(docs, options, callback)
+
+
+
+### Updating
+
+#### save(doc, options, callback)
+
+ /**
+ Update a single document in this collection.
+ spec - a associcated array containing the fields that need to be present in
+ the document for the update to succeed
+
+ document - an associated array with the fields to be updated or in the case of
+ a upsert operation the fields to be inserted.
+
+ Options:
+ upsert - true/false (perform upsert operation)
+ multi - true/false (update all documents matching spec)
+ safe - true/false (perform check if the operation failed, required extra call to db)
+ **/
+
+#### update(spec, document, options, callback)
+
+#### updateById(_id, ..., callback)
+
+Equivalent to
+
+ collection.update({_id, ObjectID.createFromHexString(id)}, ..., callback);
+
+See [Collection.update](https://github.com/christkv/node-mongodb-native/blob/master/docs/insert.md)
+
+
+
+
+### Removing
+
+#### remove(selector, options, callback)
+
+#### removeById(_id, options, callback)
+
+[Back to index](#index)
+
+
+
+SkinCursor
+---------
+
+See [Cursor](https://github.com/christkv/node-mongodb-native/blob/master/lib/mongodb/cursor.js#L1)
+of node-mongodb-native for more information.
+
+All these methods will return the SkinCursor itself.
+
+ sort(keyOrList, [direction], [callback])
+ limit(limit, [callback])
+ skip(skip, [callback])
+ batchSize(skip, [callback])
+
+ toArray(callback)
+ each(callback)
+ count(callback)
+ nextObject(callback)
+ getMore(callback)
+ explain(callback)
+
+
+[Back to index](#index)
diff --git a/app/node_modules/mongoskin/docs/docco.css b/app/node_modules/mongoskin/docs/docco.css
new file mode 100644
index 0000000..5aa0a8d
--- /dev/null
+++ b/app/node_modules/mongoskin/docs/docco.css
@@ -0,0 +1,186 @@
+/*--------------------- 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;
+}
+h1, h2, h3, h4, h5, h6 {
+ margin: 0px 0 15px 0;
+}
+ h1 {
+ margin-top: 40px;
+ }
+#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: 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/app/node_modules/mongoskin/examples/admin.js b/app/node_modules/mongoskin/examples/admin.js
new file mode 100644
index 0000000..f32eee5
--- /dev/null
+++ b/app/node_modules/mongoskin/examples/admin.js
@@ -0,0 +1,9 @@
+var db = require('./config').db;
+
+db.admin.listDatabases(function(err, result){
+ if(err) {
+ console.traceError(err);
+ }
+ console.log(result);
+ db.close();
+})
diff --git a/app/node_modules/mongoskin/examples/close.js b/app/node_modules/mongoskin/examples/close.js
new file mode 100644
index 0000000..73fafaa
--- /dev/null
+++ b/app/node_modules/mongoskin/examples/close.js
@@ -0,0 +1,15 @@
+var db = require('./config').db;
+
+db.collection('test').findOne({}, function(err, data) {
+ if(!err) {
+ console.log('db has open');
+ console.log(data);
+ }
+});
+
+process.on('SIGINT', function() {
+ console.log('Recieve SIGINT');
+ db.close(function(){
+ console.log('database has closed');
+ })
+})
diff --git a/app/node_modules/mongoskin/examples/config.js b/app/node_modules/mongoskin/examples/config.js
new file mode 100644
index 0000000..79ae8e1
--- /dev/null
+++ b/app/node_modules/mongoskin/examples/config.js
@@ -0,0 +1,5 @@
+var mongoskin = require('../lib/mongoskin/');
+
+require('myconsole').replace();
+
+exports.db = mongoskin.db('localhost/test');
diff --git a/app/node_modules/mongoskin/examples/generateId.js b/app/node_modules/mongoskin/examples/generateId.js
new file mode 100644
index 0000000..6acb4bf
--- /dev/null
+++ b/app/node_modules/mongoskin/examples/generateId.js
@@ -0,0 +1,31 @@
+var redis = require('redis').createClient()
+ , shorten = require('shorten')(redis)
+ , async = require('async')
+ , db = require('./config').db
+ ;
+
+db.bind('user');
+
+function log(err) {
+ if(err) {
+ console.log(err.stack);
+ }
+}
+
+function createUser(user, callback) {
+
+ async.waterfall([
+ function(fn) {
+ shorten.nextId('user', fn);
+ }
+ , function(uid, fn) {
+ user.uid = uid;
+ db.user.save(user, fn);
+ }
+ ], callback);
+
+}
+
+for(var i = 0; i<10; i++) {
+ createUser({name: 'user' + i}, log);
+}
diff --git a/app/node_modules/mongoskin/examples/gridfs.js b/app/node_modules/mongoskin/examples/gridfs.js
new file mode 100644
index 0000000..ce476a3
--- /dev/null
+++ b/app/node_modules/mongoskin/examples/gridfs.js
@@ -0,0 +1,13 @@
+var db = require('./config').db;
+
+db.gridfs().open('test.txt', 'w', function(err, gs) {
+ gs.write('blablabla', function(err, reply) {
+ gs.close(function(err, reply){
+ db.gridfs().open('test.txt', 'r' ,function(err, gs) {
+ gs.read(function(err, reply){
+ console.log(reply.toString());
+ });
+ });
+ });
+ });
+});
diff --git a/app/node_modules/mongoskin/examples/insert.js b/app/node_modules/mongoskin/examples/insert.js
new file mode 100644
index 0000000..bba4c58
--- /dev/null
+++ b/app/node_modules/mongoskin/examples/insert.js
@@ -0,0 +1,8 @@
+var db = require('./config').db;
+
+db.collection('test').insert({foo: 'bar'}, function(err, result) {
+ console.log(result);
+ db.collection('test').drop();
+ db.close();
+
+});
diff --git a/app/node_modules/mongoskin/examples/replset.js b/app/node_modules/mongoskin/examples/replset.js
new file mode 100644
index 0000000..4e3dc61
--- /dev/null
+++ b/app/node_modules/mongoskin/examples/replset.js
@@ -0,0 +1,10 @@
+var mongoskin = require('../lib/mongoskin/');
+
+var db = mongoskin.db(['127.0.0.1:27017'], {
+ database: 'test'
+});
+
+db.open(function(err, data) {
+ console.log(err && err.stack);
+ console.log(data);
+});
diff --git a/app/node_modules/mongoskin/examples/update.js b/app/node_modules/mongoskin/examples/update.js
new file mode 100644
index 0000000..9a048ce
--- /dev/null
+++ b/app/node_modules/mongoskin/examples/update.js
@@ -0,0 +1,19 @@
+var db = require('./config').db;
+var articles = db.collection('articles');
+articles.insert({foo: 'bar', val: 'val1'}, function(err, result) {
+
+ console.log(result);
+ articles.update({foo:'bar'}, {foo: 'bar', val:'val2'}, {safe: true}, function(err, result) {
+
+ console.log(result);
+ articles.find({foo: 'bar'}).toArray(function(err, docs){
+
+ console.log(docs);
+ articles.drop();
+ db.close();
+
+ });
+
+ })
+
+});
diff --git a/app/node_modules/mongoskin/index.js b/app/node_modules/mongoskin/index.js
new file mode 100644
index 0000000..caf8197
--- /dev/null
+++ b/app/node_modules/mongoskin/index.js
@@ -0,0 +1 @@
+module.exports = require('./lib/mongoskin');
diff --git a/app/node_modules/mongoskin/integration/integration_tests.js b/app/node_modules/mongoskin/integration/integration_tests.js
new file mode 100644
index 0000000..7a34db7
--- /dev/null
+++ b/app/node_modules/mongoskin/integration/integration_tests.js
@@ -0,0 +1,203 @@
+GLOBAL.DEBUG = true;
+
+var assert = require('assert'),
+ mongo = require('../lib/mongoskin');
+
+console.log('======== test MongoSkin.db ========');
+(function(){
+ var username = 'testuser',
+ password = 'password';
+
+ db = mongo.db('localhost/test');
+ db.open(function(err, db) {
+ assert.ok(!err);
+ assert.ok(db, err && err.stack);
+ db.addUser(username, password, function(err, result){
+ var authdb = mongo.db(username + ':' + password +'@localhost/test');
+ authdb.open(function(err, db){
+ assert.ok(!err, err && err.stack);
+ });
+ var faildb = mongo.db(username + ':wrongpassword@localhost/test');
+ faildb.open(function(err, db){
+ assert.ok(err, 'should not auth');
+ assert.ok(!db, 'should not return db');
+ });
+ });
+ });
+})();
+
+(function(){
+ db = mongo.db('db://admin:admin@localhost:27017/test?auto_reconnect');
+ db.open(function(err, db){
+ assert.ok(err instanceof Error);
+ })
+})();
+
+var bindToBlog = {
+ first: function(fn) {
+ this.findOne(fn);
+ }
+};
+
+console.log('======== test MongoSkin.router ========');
+var testdb1 = mongo.db('localhost/test1');
+var testdb2 = mongo.db('localhost/test2');
+var router = mongo.router(function(name){
+ switch(name){
+ case 'user':
+ case 'message':
+ return testdb1;
+ default:
+ return testdb2;
+ }
+});
+assert.equal(router.collection('user'), testdb1.collection('user'), 'user should router to testdb1');
+assert.equal(router.collection('message'), testdb1.collection('message'), 'message should router to testdb1');
+assert.equal(router.collection('others'), testdb2.collection('others'), 'others should router to testdb2');
+router.bind('user');
+router.bind('others');
+assert.equal(router.user, testdb1.user, 'user property should router to testdb1');
+assert.equal(router.others, testdb2.others, 'user property should router to testdb1');
+
+console.log('======== test MongoSkin.bind ========');
+var db = mongo.db('localhost/test_mongoskin');
+db.bind('blog', bindToBlog);
+db.bind('users');
+assert.equal(db.blog.first, bindToBlog.first);
+assert.ok(db.users);
+
+console.log('======== test SkinDb bson ========');
+assert.ok(db.ObjectID.createFromHexString('a7b79d4dca9d730000000000'));
+
+console.log('======== test SkinDb.bind ========');
+db.bind('blog2', bindToBlog);
+db.bind('user2');
+assert.equal(db.blog2.first, bindToBlog.first);
+assert.ok(db.user2);
+
+console.log('======== test SkinDb.open ========');
+(function(){
+ var db1, db2;
+ db.open(function(err, db) {
+ assert.ok(db, err && err.stack);
+ db1 = db;
+ assert.equal(db1.state, 'connected');
+ if (db2) {
+ assert.equal(db1, db2, 'should alwayse be the same instance in db.open.');
+ }
+ });
+
+ db.open(function(err, db) {
+ assert.ok(db, err && err.stack);
+ db2 = db;
+ assert.equal(db2.state, 'connected');
+ if (db1) {
+ assert.equal(db1, db2, 'should alwayse be the same instance in db.open.');
+ }
+ });
+
+})()
+
+console.log('======== test normal method of SkinDb ========');
+db.createCollection('test_createCollection', function(err, collection) {
+ assert.equal(db.db.state, 'connected');
+ assert.ok(collection, err && err.stack);
+});
+
+
+console.log('======== test SkinDb.collection ========');
+assert.equal(db.blog, db.collection('blog'));
+
+console.log('======== test SkinCollection.open ========');
+var coll1, coll2;
+db.blog.open(function(err, coll) {
+ assert.ok(coll, err && err.stack);
+ coll1 = coll;
+ if (coll2) {
+ assert.equal(coll1, coll2, 'should be the same instance in collection.open');
+ }
+});
+
+db.blog.open(function(err, coll) {
+ assert.ok(coll, err && err.stack);
+ coll2 = coll;
+ if (coll1) {
+ assert.equal(coll1, coll2, 'should be the same instance in collection.open');
+ }
+});
+
+console.log('======== test normal method of SkinCollection ========');
+db.collection('test_normal').ensureIndex([['a',1]], function(err, replies){
+ assert.ok(replies, err && err.stack);
+});
+
+console.log('======== test SkinCollection.drop ========');
+db.collection('test_find').drop(function(err, replies){
+ assert.ok(!err, err && err.stack);
+});
+
+console.log('======== test SkinCollection.find ========');
+collection = db.collection('test_find');
+collection.insert([{a:1},{a:2},{a:3},{a:4}], function(err, replies){
+ assert.ok(replies, err && err.stack);
+ console.log('======== test SkinCollection.findById ========');
+ collection.findById(replies[0]._id.toString(), function(err, item){
+ assert.equal(item.a, 1);
+ console.log('======== test SkinCollection.removeById ========');
+ collection.removeById(replies[0]._id.toString(), function(err, reply){
+ assert.ok(!err, err && err.stack);
+ collection.findById(replies[0]._id.toString(), function(err, item){
+ assert.ok(!err);
+ assert.ok(!item);
+ });
+ });
+ });
+});
+
+
+ collection.findItems(function(err, items){
+ assert.ok(items, err && err.stack);
+ console.log('found '+ items.length + ' items');
+ });
+ collection.findEach(function(err, item){
+ assert.ok(!err, err && err.stack);
+ });
+ collection.find(function(err, cursor){
+ assert.ok(cursor, err && err.stack);
+ });
+
+ console.log('======== test SkinCursor ========');
+ collection.find().toArray(function(err, items){
+ console.log('======== test find cursor toArray========');
+ assert.ok(items, err && err.stack);
+ });
+ collection.find().each(function(err, item){
+ console.log('======== test find cursor each========');
+ assert.ok(!err, err && err.stack);
+ });
+ collection.find().sort({a:-1}).limit(2).skip(1).toArray(function(err, items){
+ console.log('======== test cursor sort() limit() skip() ========');
+ assert.ok(!err, err && err.stack);
+ console.dir(items);
+ });
+
+console.log('======== deep future test ========');
+(function(){
+ var db2 = mongo.db('localhost/test-mongoskin01');
+ db2.collection('blog').find().toArray(function(err, items){
+ assert.ok(!err, err && err.stack);
+ })
+})();
+
+(function(){
+ var db2 = mongo.db('unknownhost/test-mongoskin01');
+ db2.collection('blog').find().toArray(function(err, items){
+ assert.ok(err);
+ })
+})();
+/*
+console.log('======== test SkinDb.close ========');
+db.close();
+assert.equal(db.db.state, 'notConnected');
+*/
+
diff --git a/app/node_modules/mongoskin/lib/mongoskin/admin.js b/app/node_modules/mongoskin/lib/mongoskin/admin.js
new file mode 100644
index 0000000..bb422c0
--- /dev/null
+++ b/app/node_modules/mongoskin/lib/mongoskin/admin.js
@@ -0,0 +1,35 @@
+var Admin = require('mongodb').Admin
+ , utils = require('./utils');
+
+var SkinAdmin = exports.SkinAdmin = function(skinDb) {
+ this.skinDb = skinDb;
+}
+
+SkinAdmin.prototype.open = function(callback) {
+ if(this.admin) return callback(null, this.admin);
+ this.skinDb.open(function(err, db){
+ if(err) return callback(err);
+ this.admin = new Admin(db);
+ callback(null, this.admin);
+ })
+}
+
+var bindSkin = function(name, method) {
+ SkinAdmin.prototype[name] = function() {
+ var args = arguments.length > 0 ? Array.prototype.slice.call(arguments, 0) : [];
+ return this.open(function(err, admin) {
+ if (err) {
+ utils.error(err, args, 'SkinAdmin.' + name);
+ } else {
+ method.apply(admin, args);
+ }
+ });
+ };
+};
+
+for (var name in Admin.prototype) {
+ var method = Admin.prototype[name];
+ bindSkin(name, method);
+}
+
+exports.SkinAdmin = SkinAdmin;
diff --git a/app/node_modules/mongoskin/lib/mongoskin/collection.js b/app/node_modules/mongoskin/lib/mongoskin/collection.js
new file mode 100644
index 0000000..c22646f
--- /dev/null
+++ b/app/node_modules/mongoskin/lib/mongoskin/collection.js
@@ -0,0 +1,227 @@
+/**
+ bind these methods from Collection.prototype to Provider
+
+ methods:
+ insert
+ checkCollectionName
+ remove
+ rename
+ save
+ update
+ distinct
+ count
+ drop
+ findAndModify
+ find
+ normalizeHintField
+ findOne
+ createIndex
+ ensureIndex
+ indexInformation
+ dropIndex
+ dropIndexes
+ mapReduce
+ group
+ options
+*/
+var __slice = Array.prototype.slice,
+ events = require('events'),
+ Collection = require('mongodb').Collection,
+ SkinCursor = require('./cursor').SkinCursor,
+ utils = require('./utils'),
+ STATE_CLOSE = 0,
+ STATE_OPENNING = 1,
+ STATE_OPEN = 2;
+
+/**
+ * Construct SkinCollection from SkinDb and collectionName
+ * use skinDb.collection('name') usually
+ *
+ * @param skinDb
+ * @param collectionName
+ *
+ */
+var SkinCollection = exports.SkinCollection = function(skinDb, collectionName) {
+ this.skinDb = skinDb;
+ this.ObjectID = this.skinDb.ObjectID;
+ this.collectionName = collectionName;
+ this.collection;
+ this.state = STATE_CLOSE;
+ this.internalHint;
+ var that = this;
+ this.__defineGetter__('hint', function() { return this.internalHint; });
+ this.__defineSetter__('hint', function(value) {
+ this.internalHint = value;
+ this.open(function(err, collection) {
+ collection.hint = value;
+ that.internalHint = collection.hint;
+ });
+ });
+
+ this.emitter = new events.EventEmitter();
+};
+
+/**
+ * bind method of mongodb.Collection to mongoskin.SkinCollection
+ */
+var bindSkin = function(name, method) {
+ SkinCollection.prototype[name] = function() {
+ var args = arguments.length > 0 ? __slice.call(arguments, 0) : [];
+ this.open(function(err, collection) {
+ if (err) {
+ utils.error(err, args, 'SkinCollection.' + name);
+ } else {
+ method.apply(collection, args);
+ }
+ });
+ };
+};
+
+for (var name in Collection.prototype) {
+ var method = Collection.prototype[name];
+ bindSkin(name, method);
+}
+
+/*
+ * find is a special method, because it could return a SkinCursor instance
+ */
+SkinCollection.prototype._find = SkinCollection.prototype.find;
+
+/**
+ * retrieve mongodb.Collection
+ */
+SkinCollection.prototype.open = function(fn) {
+ switch (this.state) {
+ case STATE_OPEN:
+ return fn(null, this.collection);
+ case STATE_OPENNING:
+ return this.emitter.once('open', fn);
+ case STATE_CLOSE:
+ default:
+ var that = this;
+ this.emitter.once('open', fn);
+ this.state = STATE_OPENNING;
+ this.skinDb.open(function(err, db) {
+ if (err) {
+ that.state = STATE_CLOSE;
+ return that.emitter.emit('open', err, null);
+ }
+ that.skinDb.db.collection(that.collectionName, function(err, collection) {
+ if (collection) {
+ that.state = STATE_OPEN;
+ that.collection = collection;
+ if (that.hint) {
+ that.collection.hint = that.hit;
+ }
+ }else {
+ that.state = STATE_CLOSE;
+ }
+ that.emitter.emit('open', err, collection);
+ });
+ });
+ }
+};
+
+SkinCollection.prototype.close = function(){
+ this.state = STATE_CLOSE;
+};
+
+SkinCollection.prototype.drop = function(fn) {
+ this.skinDb.dropCollection(this.collectionName, fn);
+ this.close();
+};
+
+/**
+ * same args as find, but use Array as callback result but not use Cursor
+ *
+ * findItems(args, function(err, items){});
+ *
+ * same as
+ *
+ * find(args, function(err, cursor){cursor.toArray(err, items){}});
+ *
+ */
+SkinCollection.prototype.findItems = function() {
+ var args = __slice.call(arguments),
+ fn = args[args.length - 1];
+
+ args[args.length - 1] = function(err, cursor) {
+ if (err) {
+ fn(err);
+ } else {
+ cursor.toArray(fn);
+ }
+ }
+
+ this._find.apply(this, args);
+};
+
+/**
+ * find and cursor.each
+ */
+SkinCollection.prototype.findEach = function() {
+ var args = __slice.call(arguments),
+ fn = args[args.length - 1];
+
+ args[args.length - 1] = function(err, cursor) {
+ if (err) {
+ fn(err);
+ } else {
+ cursor.each(fn);
+ }
+ }
+
+ this._find.apply(this, args);
+};
+
+/**
+ * @deprecated use SkinDb.id instead
+ */
+SkinCollection.prototype.id = function(hex) {
+ return this.skinDb.toId(hex);
+};
+
+/**
+ * use hex id as first argument, support ObjectID and String id
+ *
+ * @param {String/ObjectID} id
+ * @param {Function} callback
+ * @return {Object} cursor
+ * @api public
+ */
+SkinCollection.prototype.findById = function() {
+ var args = __slice.call(arguments);
+ args[0] = {_id: this.skinDb.toId(args[0])};
+ this.findOne.apply(this, args);
+};
+
+/**
+ * use hex id as first argument
+ */
+SkinCollection.prototype.updateById = function() {
+ var args = __slice.call(arguments);
+ args[0] = {_id: this.skinDb.toId(args[0])};
+ this.update.apply(this, args);
+};
+
+/**
+ * use hex id as first argument
+ */
+SkinCollection.prototype.removeById = function() {
+ var args = __slice.call(arguments);
+ args[0] = {_id: this.skinDb.toId(args[0])};
+ this.remove.apply(this, args);
+};
+
+/**
+ * if last argument is not a function, then returns a SkinCursor
+ */
+SkinCollection.prototype.find = function() {
+ var args = arguments.length > 0 ? __slice.call(arguments, 0) : [];
+ if (args.length > 0 && typeof(args[args.length - 1]) === 'function') {
+ this._find.apply(this, args);
+ }else {
+ return new SkinCursor(null, this, args);
+ }
+};
+
diff --git a/app/node_modules/mongoskin/lib/mongoskin/cursor.js b/app/node_modules/mongoskin/lib/mongoskin/cursor.js
new file mode 100644
index 0000000..6642426
--- /dev/null
+++ b/app/node_modules/mongoskin/lib/mongoskin/cursor.js
@@ -0,0 +1,77 @@
+var __slice = Array.prototype.slice,
+ events = require('events'),
+ Cursor = require('mongodb').Cursor,
+ utils = require('./utils'),
+ STATE_CLOSE = 0,
+ STATE_OPENNING = 1,
+ STATE_OPEN = 2;
+
+var SkinCursor = exports.SkinCursor = function(cursor, skinCollection, args ) {
+ this.cursor = cursor;
+ this.skinCollection = skinCollection;
+ this.args = args;
+ this.emitter = new events.EventEmitter();
+ if (!cursor) {
+ this.state = STATE_CLOSE;
+ }else {
+ this.state = STATE_OPEN;
+ }
+}
+
+SkinCursor.prototype.open = function(fn) {
+ switch (this.state) {
+ case STATE_OPEN:
+ return fn(null, this.cursor);
+ case STATE_OPENNING:
+ return this.emitter.once('open', fn);
+ case STATE_CLOSE:
+ default:
+ var that = this;
+ this.emitter.once('open', fn);
+ this.state = STATE_OPENNING;
+ this.skinCollection.open(function(err, collection) {
+ if (err) {
+ that.state = STATE_CLOSE;
+ that.emitter.emit('open', err);
+ return
+ }
+ // copy args
+ var args = that.args.slice();
+ args.push(function(err, cursor) {
+ if (cursor) {
+ that.state = STATE_OPEN;
+ that.cursor = cursor;
+ }
+ that.emitter.emit('open', err, cursor);
+ });
+
+ collection.find.apply(collection, args);
+ });
+ }
+};
+
+var bindSkin = function(name, method) {
+ SkinCursor.prototype[name] = function() {
+ var args = arguments.length > 0 ? __slice.call(arguments, 0) : [];
+ this.open(function(err, cursor) {
+ if (err) {
+ utils.error(err, args, 'SkinCursor.' + name);
+ } else {
+ method.apply(cursor, args);
+ }
+ });
+ return this;
+ };
+};
+
+[
+ // callbacks
+ 'toArray','each','count','nextObject','getMore', 'explain',
+ // self return
+ 'sort','limit','skip','batchSize',
+ // unsupported
+ //'rewind', 'close' ,...
+].forEach(function(name) {
+ var method = Cursor.prototype[name];
+ bindSkin(name, method);
+});
diff --git a/app/node_modules/mongoskin/lib/mongoskin/db.js b/app/node_modules/mongoskin/lib/mongoskin/db.js
new file mode 100644
index 0000000..eedce09
--- /dev/null
+++ b/app/node_modules/mongoskin/lib/mongoskin/db.js
@@ -0,0 +1,205 @@
+var __slice = Array.prototype.slice,
+ mongodb = require('mongodb'),
+ events = require('events'),
+ utils = require('./utils'),
+ SkinAdmin = require('./admin').SkinAdmin,
+ SkinCollection = require('./collection').SkinCollection,
+ SkinGridStore = require('./gridfs').SkinGridStore,
+ Db = mongodb.Db,
+
+ STATE_CLOSE = 0,
+ STATE_OPENNING = 1,
+ STATE_OPEN = 2;
+
+var _extend = function(destination, source) {
+ for (var property in source) {
+ destination[property] = source[property];
+ }
+ return destination;
+};
+
+var SkinDb = exports.SkinDb = function(db, username, password) {
+ this.db = db;
+ this.username = username;
+ this.password = password;
+ this.state = STATE_CLOSE;
+ this.emitter = new events.EventEmitter();
+ this.admin = new SkinAdmin(this);
+ this._collections = {};
+ this.bson_serializer = db.bson_serializer;
+ this.ObjectID = mongodb.ObjectID /* 0.9.7-3-2 */ || db.bson_serializer.ObjectID /* <= 0.9.7 */;
+};
+
+SkinDb.prototype.toObjectID = SkinDb.prototype.toId = function(hex) {
+ if(hex instanceof this.ObjectID) {
+ return hex;
+ }
+ return this.ObjectID.createFromHexString(hex);
+};
+
+
+/**
+ * retrieve native_db
+ *
+ * @param fn function(err, native_db)
+ *
+ */
+SkinDb.prototype.open = function(fn) {
+ switch (this.state) {
+
+ case STATE_OPEN:
+ return fn(null, this.db);
+
+ case STATE_OPENNING:
+ // if call 'open' method multi times before opened
+ return this.emitter.once('open', fn);
+
+ case STATE_CLOSE:
+ default:
+ var that = this;
+ var onDbOpen = function(err, db) {
+ if (!err && db) {
+ that.state = STATE_OPEN;
+ that.db = db;
+ }else {
+ db = null;
+ that.state = STATE_CLOSE;
+ }
+ that.emitter.emit('open', err, db);
+ };
+
+ this.emitter.once('open', fn);
+ this.state = STATE_OPENNING;
+
+ this.db.open(function(err, db) {
+ if (db && that.username) {
+ //do authenticate
+ db.authenticate(that.username, that.password, function(err) {
+ onDbOpen(err, db);
+ });
+ } else {
+ onDbOpen(err, db);
+ }
+ });
+ }
+};
+
+/**
+ * Close skinDb
+ */
+SkinDb.prototype.close = function(callback) {
+ if (this.state === STATE_CLOSE) {
+ return callback && callback();
+ }else if (this.state === STATE_OPEN) {
+ this.state = STATE_CLOSE;
+ this.db.close(callback);
+ }else if (this.state === STATE_OPENNING) {
+ var that = this;
+ this.emitter.once('open', function(err, db) {
+ that.state = STATE_CLOSE;
+ db.close(callback);
+ });
+ }
+};
+
+/**
+ * create or retrieval skin collection
+ */
+SkinDb.prototype.collection = function(name) {
+ var collection = this._collections[name];
+ if (!collection) {
+ this._collections[name] = collection = new SkinCollection(this, name);
+ }
+ return collection;
+};
+
+/**
+ * gridfs
+ */
+SkinDb.prototype.gridfs = function() {
+ return this.skinGridStore || (this.skinGridStore = new SkinGridStore(this));
+}
+
+/**
+ * bind additional method to SkinCollection
+ *
+ * 1. collectionName
+ * 2. collectionName, extends1, extends2,... extendsn
+ * 3. collectionName, SkinCollection
+ */
+SkinDb.prototype.bind = function() {
+ var args = __slice.call(arguments),
+ name = args[0];
+
+ if (typeof name !== 'string' || name.length === 0) {
+ throw new Error('Must provide name parameter for bind.');
+ }
+ if (args.length === 1) {
+ return this.bind(name, this.collection(name));
+ }
+ if (args.length === 2 && args[1].constructor === SkinCollection) {
+ this._collections[name] = args[1];
+ Object.defineProperty(this, name, {
+ value: args[1],
+ writable: false,
+ enumerable: true
+ });
+ // support bind for system.js
+ var names = name.split('.');
+ if(names.length > 1){
+ var prev = this, next;
+ for(var i =0; i 0 ? __slice.call(arguments, 0) : [];
+ return this.open(function(err, db) {
+ if (err) {
+ utils.error(err, args, 'SkinDb.' + name);
+ } else {
+ return method.apply(db, args);
+ }
+ });
+ };
+};
+
+//bind method of mongodb.Db to SkinDb
+for (var name in Db.prototype) {
+ if(!name || name[0] == '_' || name == 'state') continue;
+ var method = Db.prototype[name];
+ if (name !== 'bind' && name !== 'open' && name !== 'collection' && name !== 'admin') {
+ bindSkin(name, method);
+ }
+}
+
diff --git a/app/node_modules/mongoskin/lib/mongoskin/gridfs.js b/app/node_modules/mongoskin/lib/mongoskin/gridfs.js
new file mode 100644
index 0000000..8f72bbc
--- /dev/null
+++ b/app/node_modules/mongoskin/lib/mongoskin/gridfs.js
@@ -0,0 +1,41 @@
+var GridStore = require('mongodb').GridStore;
+
+/**
+ * @param filename: filename or ObjectId
+ */
+var SkinGridStore = exports.SkinGridStore = function(skinDb) {
+ this.skinDb = skinDb;
+}
+
+/**
+ * @param id
+ * @param filename
+ * @param mode
+ * @param options
+ * @param callback
+ * callback(err, gridStoreObject)
+ */
+SkinGridStore.prototype.open = function(id, filename, mode, options, callback){
+ var args = Array.prototype.slice.call(arguments);
+ var callback = args.pop();
+ this.skinDb.open(function(err, db) {
+ new GridStore(db, args[0], args[1], args[2], args[3]).open(callback);
+ });
+}
+
+/**
+ * @param filename: filename or ObjectId
+ */
+SkinGridStore.prototype.unlink = SkinGridStore.prototype.remove = function(filename, callback){
+ this.skinDb.open(function(err, db) {
+ GridStore.unlink(db, filename, callback);
+ });
+}
+
+SkinGridStore.prototype.exist = function(filename, rootCollection, callback){
+ this.skinDb.open(function(err, db) {
+ GridStore.exist(db, filename, rootCollection, callback);
+ });
+}
+
+exports.SkinGridStore = SkinGridStore;
diff --git a/app/node_modules/mongoskin/lib/mongoskin/index.js b/app/node_modules/mongoskin/lib/mongoskin/index.js
new file mode 100644
index 0000000..68fa6de
--- /dev/null
+++ b/app/node_modules/mongoskin/lib/mongoskin/index.js
@@ -0,0 +1,150 @@
+var url = require('url'),
+ Router = require('./router').Router,
+ mongo = require('mongodb'),
+ SkinServer = require('./server').SkinServer,
+ SkinDb =require('./db').SkinDb,
+ Db = mongo.Db,
+ Server = mongo.Server,
+ ReplSetServers = mongo.ReplSetServers,
+ BSONNative = mongo.BSONNative,
+ DEFAULT_PORT = 27017;
+
+function toBool(value) {
+ return value !== undefined && value != 'false' && value != 'no' && value != 'off';
+}
+
+/**
+ * parse the database url to config
+ *
+ * [*://]username:password@host[:port]/database?options
+ *
+ */
+var parseUrl = function(serverUrl) {
+ var serverUrl = /\w+:\/\//.test(serverUrl) ? serverUrl : 'db://' + serverUrl,
+ uri = url.parse(serverUrl, true),
+ config = {},
+ serverOptions = uri.query,
+ reconnect = serverOptions['auto_reconnect'];
+
+ config.host = uri.hostname;
+ config.port = Number(uri.port) || DEFAULT_PORT;
+ if(uri.pathname) {
+ config.database = uri.pathname.replace(/\//g, '');
+ }
+ config.options = {};
+ config.options['auto_reconnect'] = toBool(serverOptions['auto_reconnect']);
+ config.options['poolSize'] = parseInt(serverOptions['poolSize'] || 1);
+ if (uri && uri.auth) {
+ var auth = uri.auth,
+ separator = auth.indexOf(':');
+ config.username = auth.substr(0, separator);
+ config.password = auth.substr(separator + 1);
+ }
+ return config;
+};
+
+/**
+ * constructor Server from url
+ *
+ */
+var parseServer = function(serverUrl) {
+ var config = parseUrl(serverUrl);
+ return new Server(config.host, config.port, config.options);
+};
+
+/*
+ * exports mongo classes ObjectID Long Code DbRef ... to mongoskin
+ */
+for(var key in mongo) {
+ exports[key] = mongo[key];
+}
+
+/**
+ * constructor SkinDb from serverUrls
+ *
+ * repliSet: mongoskin.db(serverUrls, rs_options, db_options)
+ *
+ * mongoskin.db(['192.168.0.1:27017/', '192.168.0.2/?auto_reconnect', '192.168.0.3/?auto_reconnect'], {
+ * database: 'mydb'
+ * })
+ *
+ * single Server: mongoskin.db(dbUrl, db_options)
+ *
+ * mongoskin.db('192.168.0.1:27017/mydb')
+ *
+ */
+exports.db = function(serverUrl, options) {
+ if(!options) {
+ options = {};
+ }
+
+ var server, database;
+
+ if(Array.isArray(serverUrl)) {
+ if(!options.database) {
+ throw new Error('Please provide a database in options to connect.');
+ }
+ database = options.database;
+
+ var len = serverUrl.length;
+ var servers = [];
+ for(var i = 0; i < len; i++) {
+ var config = parseUrl(serverUrl[i]);
+ if(config.database || config.username) {
+ console.log('MONGOSKIN:WARN: database or username found in RepliSet server URL, ' + serverUrl[i]);
+ }
+ servers.push( new Server(config.host, config.port, config.options) );
+ }
+ server = new ReplSetServers(servers);
+ } else {
+ var config = parseUrl(serverUrl);
+ if (!config.database) {
+ throw new Error('Please provide a database to connect to.');
+ }
+ database = config.database;
+
+ server = new Server(config.host, config.port, config.options);
+
+ if(options.username === undefined) {
+ options.username = config.username;
+ options.password = config.password;
+ }
+ }
+
+ var skinServer = new SkinServer(server);
+ return skinServer.db(database, options);
+};
+
+/**
+ * select different db by collection name
+ *
+ * @param select function(name) returns SkinDb
+ *
+ * var router = mongoskin.router(function(name){
+ * select(name){
+ * case 'user':
+ * case 'group':
+ * return authDb;
+ * default:
+ * return appDb;
+ * }
+ * });
+ *
+ * router.collection('user')
+ *
+ */
+exports.router = function(select) {
+ return new Router(select);
+};
+
+/*
+ * export Skin classes from ./db ./collection ./cursor ./admin
+ */
+['server', 'db', 'collection', 'cursor', 'admin'].forEach(function(path) {
+ var foo, module, name;
+ module = require('./' + path);
+ for (name in module) {
+ foo = module[name];
+ exports[name] = foo;
+ }
+});
diff --git a/app/node_modules/mongoskin/lib/mongoskin/router.js b/app/node_modules/mongoskin/lib/mongoskin/router.js
new file mode 100644
index 0000000..2b94d14
--- /dev/null
+++ b/app/node_modules/mongoskin/lib/mongoskin/router.js
@@ -0,0 +1,24 @@
+var Router = exports.Router = function(select) {
+ this._select = select;
+ this._collections = {};
+}
+
+Router.prototype.bind = function() {
+ var args = Array.prototype.slice.call(arguments),
+ name = args[0];
+
+ var database = this._select(name);
+ var coll = database.bind.apply(database, args);
+
+ this._collections[name] = coll;
+ Object.defineProperty(this, name, {
+ value: coll,
+ writable: false,
+ enumerable: true
+ });
+
+};
+
+Router.prototype.collection = function(name) {
+ return this._collections[name] || (this._collections[name] = this._select(name).collection(name));
+};
diff --git a/app/node_modules/mongoskin/lib/mongoskin/server.js b/app/node_modules/mongoskin/lib/mongoskin/server.js
new file mode 100644
index 0000000..1eb8563
--- /dev/null
+++ b/app/node_modules/mongoskin/lib/mongoskin/server.js
@@ -0,0 +1,42 @@
+var __slice = Array.prototype.slice,
+ mongodb = require('mongodb'),
+ Db = mongodb.Db,
+ Server = mongodb.Server,
+ SkinDb = require('./db').SkinDb;
+
+/**
+ * Construct SkinServer with native Server
+ *
+ * @param server
+ */
+var SkinServer = exports.SkinServer = function(server) {
+ this.server = server;
+ this._cache_ = [];
+};
+
+/**
+ * Create SkinDb from a SkinServer
+ *
+ * @param name database name
+ *
+ * @return SkinDb
+ *
+ * TODO add options
+ */
+SkinServer.prototype.db = function(name, options) {
+ var key = (username || '') + '@' + name;
+ var skinDb = this._cache_[key];
+ if (!skinDb || skinDb.fail) {
+ var username = options.username,
+ password = options.password;
+ delete options.username;
+ delete options.password;
+ if(options.native_parser === undefined) {
+ options.native_parser = !! mongodb.BSONNative;
+ }
+ var db = new Db(name, this.server, options);
+ skinDb = new SkinDb(db, username, password);
+ this._cache_[key] = skinDb;
+ }
+ return skinDb;
+};
diff --git a/app/node_modules/mongoskin/lib/mongoskin/utils.js b/app/node_modules/mongoskin/lib/mongoskin/utils.js
new file mode 100644
index 0000000..9fdd4a5
--- /dev/null
+++ b/app/node_modules/mongoskin/lib/mongoskin/utils.js
@@ -0,0 +1,8 @@
+exports.error = function(err, args, name) {
+ var cb = args.pop();
+ if(cb && typeof cb === 'function') {
+ cb(err)
+ } else {
+ console.error("Error occured with no callback to handle it while calling " + name, err);
+ }
+}
diff --git a/app/node_modules/mongoskin/node_modules/mongodb/.travis.yml b/app/node_modules/mongoskin/node_modules/mongodb/.travis.yml
new file mode 100644
index 0000000..90b208a
--- /dev/null
+++ b/app/node_modules/mongoskin/node_modules/mongodb/.travis.yml
@@ -0,0 +1,5 @@
+language: node_js
+node_js:
+ - 0.4
+ - 0.6
+ - 0.7 # development version of 0.8, may be unstable
\ No newline at end of file
diff --git a/app/node_modules/mongoskin/node_modules/mongodb/Makefile b/app/node_modules/mongoskin/node_modules/mongodb/Makefile
new file mode 100644
index 0000000..de11cbe
--- /dev/null
+++ b/app/node_modules/mongoskin/node_modules/mongodb/Makefile
@@ -0,0 +1,71 @@
+NODE = node
+NPM = npm
+NODEUNIT = node_modules/nodeunit/bin/nodeunit
+DOX = node_modules/dox/bin/dox
+name = all
+
+total: build_native
+
+build_native:
+ # $(MAKE) -C ./external-libs/bson all
+
+build_native_debug:
+ $(MAKE) -C ./external-libs/bson all_debug
+
+build_native_clang:
+ $(MAKE) -C ./external-libs/bson clang
+
+build_native_clang_debug:
+ $(MAKE) -C ./external-libs/bson clang_debug
+
+clean_native:
+ $(MAKE) -C ./external-libs/bson clean
+
+test: build_native
+ @echo "\n == Run All tests minus replicaset tests=="
+ $(NODE) dev/tools/test_all.js --noreplicaset --boot
+
+test_pure: build_native
+ @echo "\n == Run All tests minus replicaset tests=="
+ $(NODE) dev/tools/test_all.js --noreplicaset --boot --noactive
+
+test_junit: build_native
+ @echo "\n == Run All tests minus replicaset tests=="
+ $(NODE) dev/tools/test_all.js --junit --noreplicaset
+
+test_nodeunit_pure:
+ @echo "\n == Execute Test Suite using Pure JS BSON Parser == "
+ @$(NODEUNIT) test/ test/gridstore test/bson
+
+test_js:
+ @$(NODEUNIT) $(TESTS)
+
+test_nodeunit_replicaset_pure:
+ @echo "\n == Execute Test Suite using Pure JS BSON Parser == "
+ @$(NODEUNIT) test/replicaset
+
+test_nodeunit_native:
+ @echo "\n == Execute Test Suite using Native BSON Parser == "
+ @TEST_NATIVE=TRUE $(NODEUNIT) test/ test/gridstore test/bson
+
+test_nodeunit_replicaset_native:
+ @echo "\n == Execute Test Suite using Native BSON Parser == "
+ @TEST_NATIVE=TRUE $(NODEUNIT) test/replicaset
+
+test_all: build_native
+ @echo "\n == Run All tests =="
+ $(NODE) dev/tools/test_all.js --boot
+
+test_all_junit: build_native
+ @echo "\n == Run All tests =="
+ $(NODE) dev/tools/test_all.js --junit --boot
+
+clean:
+ rm ./external-libs/bson/bson.node
+ rm -r ./external-libs/bson/build
+
+generate_docs:
+ $(NODE) dev/tools/build-docs.js
+ make --directory=./docs/sphinx-docs --file=Makefile html
+
+.PHONY: total
diff --git a/app/node_modules/mongoskin/node_modules/mongodb/external-libs/bson/Makefile b/app/node_modules/mongoskin/node_modules/mongodb/external-libs/bson/Makefile
new file mode 100644
index 0000000..ad877d4
--- /dev/null
+++ b/app/node_modules/mongoskin/node_modules/mongodb/external-libs/bson/Makefile
@@ -0,0 +1,45 @@
+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
+ @$(NODE) --expose-gc test/test_bson.js
+ @$(NODE) --expose-gc test/test_full_bson.js
+ # @$(NODE) --expose-gc test/test_stackless_bson.js
+
+all_debug:
+ rm -rf build .lock-wscript bson.node
+ node-waf --debug configure build
+ cp -R ./build/Release/bson.node . || true
+ @$(NODE) --expose-gc test/test_bson.js
+ @$(NODE) --expose-gc test/test_full_bson.js
+ # @$(NODE) --expose-gc test/test_stackless_bson.js
+
+test:
+ @$(NODE) --expose-gc test/test_bson.js
+ @$(NODE) --expose-gc test/test_full_bson.js
+ # @$(NODE) --expose-gc test/test_stackless_bson.js
+
+clang:
+ rm -rf build .lock-wscript bson.node
+ CXX=clang node-waf configure build
+ cp -R ./build/Release/bson.node . || true
+ @$(NODE) --expose-gc test/test_bson.js
+ @$(NODE) --expose-gc test/test_full_bson.js
+ # @$(NODE) --expose-gc test/test_stackless_bson.js
+
+clang_debug:
+ rm -rf build .lock-wscript bson.node
+ CXX=clang node-waf --debug configure build
+ cp -R ./build/Release/bson.node . || true
+ @$(NODE) --expose-gc test/test_bson.js
+ @$(NODE) --expose-gc test/test_full_bson.js
+ # @$(NODE) --expose-gc test/test_stackless_bson.js
+
+clean:
+ rm -rf build .lock-wscript bson.node
+
+.PHONY: all
\ No newline at end of file
diff --git a/app/node_modules/mongoskin/node_modules/mongodb/external-libs/bson/bson.cc b/app/node_modules/mongoskin/node_modules/mongodb/external-libs/bson/bson.cc
new file mode 100644
index 0000000..8906eea
--- /dev/null
+++ b/app/node_modules/mongoskin/node_modules/mongodb/external-libs/bson/bson.cc
@@ -0,0 +1,2165 @@
+#include
+#include
+#include
+
+#ifdef __clang__
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wunused-parameter"
+#endif
+
+#include
+
+#ifdef __clang__
+#pragma clang diagnostic pop
+#endif
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#include "bson.h"
+
+using namespace v8;
+using namespace node;
+using namespace std;
+
+// BSON DATA TYPES
+const uint32_t BSON_DATA_NUMBER = 1;
+const uint32_t BSON_DATA_STRING = 2;
+const uint32_t BSON_DATA_OBJECT = 3;
+const uint32_t BSON_DATA_ARRAY = 4;
+const uint32_t BSON_DATA_BINARY = 5;
+const uint32_t BSON_DATA_OID = 7;
+const uint32_t BSON_DATA_BOOLEAN = 8;
+const uint32_t BSON_DATA_DATE = 9;
+const uint32_t BSON_DATA_NULL = 10;
+const uint32_t BSON_DATA_REGEXP = 11;
+const uint32_t BSON_DATA_CODE = 13;
+const uint32_t BSON_DATA_SYMBOL = 14;
+const uint32_t BSON_DATA_CODE_W_SCOPE = 15;
+const uint32_t BSON_DATA_INT = 16;
+const uint32_t BSON_DATA_TIMESTAMP = 17;
+const uint32_t BSON_DATA_LONG = 18;
+const uint32_t BSON_DATA_MIN_KEY = 0xff;
+const uint32_t BSON_DATA_MAX_KEY = 0x7f;
+
+const int32_t BSON_INT32_MAX = (int32_t)2147483647L;
+const int32_t BSON_INT32_MIN = (int32_t)(-1) * 2147483648L;
+
+const int64_t BSON_INT64_MAX = ((int64_t)1 << 63) - 1;
+const int64_t BSON_INT64_MIN = (int64_t)-1 << 63;
+
+const int64_t JS_INT_MAX = (int64_t)1 << 53;
+const int64_t JS_INT_MIN = (int64_t)-1 << 53;
+
+static Handle VException(const char *msg) {
+ HandleScope scope;
+ return ThrowException(Exception::Error(String::New(msg)));
+ };
+
+Persistent BSON::constructor_template;
+
+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);
+
+ // Experimental
+ // NODE_SET_PROTOTYPE_METHOD(constructor_template, "calculateObjectSize2", CalculateObjectSize2);
+ // NODE_SET_PROTOTYPE_METHOD(constructor_template, "serialize2", BSONSerialize2);
+ // NODE_SET_METHOD(constructor_template->GetFunction(), "serialize2", BSONSerialize2);
+
+ target->ForceSet(String::NewSymbol("BSON"), constructor_template->GetFunction());
+}
+
+// Create a new instance of BSON and assing 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();
+
+ // Setup pre-allocated comparision objects
+ bson->_bsontypeString = Persistent::New(String::New("_bsontype"));
+ bson->_longLowString = Persistent::New(String::New("low_"));
+ bson->_longHighString = Persistent::New(String::New("high_"));
+ bson->_objectIDidString = Persistent::New(String::New("id"));
+ bson->_binaryPositionString = Persistent::New(String::New("position"));
+ bson->_binarySubTypeString = Persistent::New(String::New("sub_type"));
+ bson->_binaryBufferString = Persistent::New(String::New("buffer"));
+ bson->_doubleValueString = Persistent::New(String::New("value"));
+ bson->_symbolValueString = Persistent::New(String::New("value"));
+ bson->_dbRefRefString = Persistent::New(String::New("$ref"));
+ bson->_dbRefIdRefString = Persistent::New(String::New("$id"));
+ bson->_dbRefDbRefString = Persistent::New(String::New("$db"));
+ bson->_dbRefNamespaceString = Persistent::New(String::New("namespace"));
+ bson->_dbRefDbString = Persistent::New(String::New("db"));
+ bson->_dbRefOidString = Persistent::New(String::New("oid"));
+
+ // total number of found classes
+ uint32_t numberOfClasses = 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(String::New("Long"))) {
+ bson->longConstructor = Persistent::New(func);
+ bson->longString = Persistent::New(String::New("Long"));
+ numberOfClasses = numberOfClasses + 1;
+ } else if(functionName->StrictEquals(String::New("ObjectID"))) {
+ bson->objectIDConstructor = Persistent::New(func);
+ bson->objectIDString = Persistent::New(String::New("ObjectID"));
+ numberOfClasses = numberOfClasses + 1;
+ } else if(functionName->StrictEquals(String::New("Binary"))) {
+ bson->binaryConstructor = Persistent::New(func);
+ bson->binaryString = Persistent::New(String::New("Binary"));
+ numberOfClasses = numberOfClasses + 1;
+ } else if(functionName->StrictEquals(String::New("Code"))) {
+ bson->codeConstructor = Persistent::New(func);
+ bson->codeString = Persistent::New(String::New("Code"));
+ numberOfClasses = numberOfClasses + 1;
+ } else if(functionName->StrictEquals(String::New("DBRef"))) {
+ bson->dbrefConstructor = Persistent::New(func);
+ bson->dbrefString = Persistent::New(String::New("DBRef"));
+ numberOfClasses = numberOfClasses + 1;
+ } else if(functionName->StrictEquals(String::New("Symbol"))) {
+ bson->symbolConstructor = Persistent::New(func);
+ bson->symbolString = Persistent::New(String::New("Symbol"));
+ numberOfClasses = numberOfClasses + 1;
+ } else if(functionName->StrictEquals(String::New("Double"))) {
+ bson->doubleConstructor = Persistent::New(func);
+ bson->doubleString = Persistent::New(String::New("Double"));
+ numberOfClasses = numberOfClasses + 1;
+ } else if(functionName->StrictEquals(String::New("Timestamp"))) {
+ bson->timestampConstructor = Persistent::New(func);
+ bson->timestampString = Persistent::New(String::New("Timestamp"));
+ numberOfClasses = numberOfClasses + 1;
+ } else if(functionName->StrictEquals(String::New("MinKey"))) {
+ bson->minKeyConstructor = Persistent::New(func);
+ bson->minKeyString = Persistent::New(String::New("MinKey"));
+ numberOfClasses = numberOfClasses + 1;
+ } else if(functionName->StrictEquals(String::New("MaxKey"))) {
+ bson->maxKeyConstructor = Persistent::New(func);
+ bson->maxKeyString = Persistent::New(String::New("MaxKey"));
+ numberOfClasses = numberOfClasses + 1;
+ }
+ }
+
+ // Check if we have the right number of constructors otherwise throw an error
+ if(numberOfClasses != 10) {
+ // Destroy object
+ delete(bson);
+ // Fire exception
+ 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");
+ }
+}
+
+void BSON::write_int32(char *data, uint32_t value) {
+ // Write the int to the char*
+ memcpy(data, &value, 4);
+}
+
+void BSON::write_double(char *data, double value) {
+ // Write the double to the char*
+ memcpy(data, &value, 8);
+}
+
+void BSON::write_int64(char *data, int64_t value) {
+ // Write the int to the char*
+ memcpy(data, &value, 8);
+}
+
+char *BSON::check_key(Local key) {
+ // Allocate space for they key string
+ char *key_str = (char *)malloc(key->Utf8Length() * sizeof(char) + 1);
+ // Error string
+ char *error_str = (char *)malloc(256 * sizeof(char));
+ // Decode the key
+ ssize_t len = DecodeBytes(key, BINARY);
+ DecodeWrite(key_str, len, key, BINARY);
+ *(key_str + key->Utf8Length()) = '\0';
+ // Check if we have a valid key
+ if(key->Utf8Length() > 0 && *(key_str) == '$') {
+ // Create the string
+ sprintf(error_str, "key %s must not start with '$'", key_str);
+ // Free up memory
+ free(key_str);
+ // Throw exception with string
+ throw error_str;
+ } else if(key->Utf8Length() > 0 && strchr(key_str, '.') != NULL) {
+ // Create the string
+ sprintf(error_str, "key %s must not contain '.'", key_str);
+ // Free up memory
+ free(key_str);
+ // Throw exception with string
+ throw error_str;
+ }
+ // Free allocated space
+ free(key_str);
+ free(error_str);
+ // Return No check key error
+ return NULL;
+}
+
+const char* BSON::ToCString(const v8::String::Utf8Value& value) {
+ return *value ? *value : "";
+}
+
+Handle BSON::decodeDBref(BSON *bson, Local ref, Local oid, Local db) {
+ HandleScope scope;
+ Local argv[] = {ref, oid, db};
+ Handle dbrefObj = bson->dbrefConstructor->NewInstance(3, argv);
+ return scope.Close(dbrefObj);
+}
+
+Handle BSON::decodeCode(BSON *bson, char *code, Handle scope_object) {
+ HandleScope scope;
+
+ Local argv[] = {String::New(code), scope_object->ToObject()};
+ Handle codeObj = bson->codeConstructor->NewInstance(2, argv);
+ return scope.Close(codeObj);
+}
+
+Handle BSON::decodeBinary(BSON *bson, uint32_t sub_type, uint32_t number_of_bytes, char *data) {
+ HandleScope scope;
+
+ // Create a buffer object that wraps the raw stream
+ Buffer *bufferObj = Buffer::New(data, number_of_bytes);
+ // Arguments to be passed to create the binary
+ Handle argv[] = {bufferObj->handle_, Uint32::New(sub_type)};
+ // Return the buffer handle
+ Local
+ index = index + position;
+ } else if(bson->doubleString->StrictEquals(constructorString)) {
+ // Save the string at the offset provided
+ *(serialized_object + originalIndex) = BSON_DATA_NUMBER;
+
+ // Unpack the double
+ Local doubleObject = value->ToObject();
+
+ // Fetch the double value
+ Local doubleValue = doubleObject->Get(bson->_doubleValueString)->ToNumber();
+ // Write the double to the char array
+ BSON::write_double((serialized_object + index), doubleValue->NumberValue());
+ // Adjust index for double
+ index = index + 8;
+ } else if(bson->symbolString->StrictEquals(constructorString)) {
+ // Save the string at the offset provided
+ *(serialized_object + originalIndex) = BSON_DATA_SYMBOL;
+ // Unpack symbol object
+ Local symbolObj = value->ToObject();
+
+ // Grab the actual string
+ Local str = symbolObj->Get(bson->_symbolValueString)->ToString();
+ // Let's fetch the int value
+ int utf8_length = str->Utf8Length();
+
+ // If the Utf8 length is different from the string length then we
+ // have a UTF8 encoded string, otherwise write it as ascii
+ if(utf8_length != str->Length()) {
+ // Write the integer to the char *
+ BSON::write_int32((serialized_object + index), utf8_length + 1);
+ // Adjust the index
+ index = index + 4;
+ // Write string to char in utf8 format
+ str->WriteUtf8((serialized_object + index), utf8_length);
+ // Add the null termination
+ *(serialized_object + index + utf8_length) = '\0';
+ // Adjust the index
+ index = index + utf8_length + 1;
+ } else {
+ // Write the integer to the char *
+ BSON::write_int32((serialized_object + index), str->Length() + 1);
+ // Adjust the index
+ index = index + 4;
+ // Write string to char in utf8 format
+ written = DecodeWrite((serialized_object + index), str->Length(), str, BINARY);
+ // Add the null termination
+ *(serialized_object + index + str->Length()) = '\0';
+ // Adjust the index
+ index = index + str->Length() + 1;
+ }
+ } else if(bson->codeString->StrictEquals(constructorString)) {
+ // Unpack the object and encode
+ Local obj = value->ToObject();
+ // Get the function
+ Local function = obj->Get(String::New("code"))->ToString();
+ // Get the scope object
+ Local scope = obj->Get(String::New("scope"))->ToObject();
+
+ #if NODE_MAJOR_VERSION == 0 && NODE_MINOR_VERSION < 6
+ uint32_t propertyNameLength = scope->GetPropertyNames()->Length();
+ #else
+ uint32_t propertyNameLength = scope->GetOwnPropertyNames()->Length();
+ #endif
+
+ // Set the right type if we have a scope or not
+ if(propertyNameLength > 0) {
+ // Set basic data code object with scope object
+ *(serialized_object + originalIndex) = BSON_DATA_CODE_W_SCOPE;
+
+ // Calculate the size of the whole object
+ uint32_t scopeSize = BSON::calculate_object_size(bson, scope, false);
+ // Decode the function length
+ ssize_t len = DecodeBytes(function, UTF8);
+ // Calculate total size
+ uint32_t size = 4 + len + 1 + 4 + scopeSize;
+
+ // Write the total size
+ BSON::write_int32((serialized_object + index), size);
+ // Adjust the index
+ index = index + 4;
+
+ // Write the function size
+ BSON::write_int32((serialized_object + index), len + 1);
+ // Adjust the index
+ index = index + 4;
+
+ // Write the data into the serialization stream
+ ssize_t written = DecodeWrite((serialized_object + index), len, function, UTF8);
+ assert(written == len);
+ // Write \0 for string
+ *(serialized_object + index + len) = 0x00;
+ // Adjust the index with the length of the function
+ index = index + len + 1;
+ // Write the scope object
+ BSON::serialize(bson, (serialized_object + index), 0, Null(), scope, check_key, serializeFunctions);
+ // Adjust the index
+ index = index + scopeSize;
+ } else {
+ // Set basic data code object
+ *(serialized_object + originalIndex) = BSON_DATA_CODE;
+ // Decode the function
+ ssize_t len = DecodeBytes(function, BINARY);
+ // Write the size of the code string + 0 byte end of cString
+ BSON::write_int32((serialized_object + index), len + 1);
+ // Adjust the index
+ index = index + 4;
+
+ // Write the data into the serialization stream
+ ssize_t written = DecodeWrite((serialized_object + index), len, function, BINARY);
+ assert(written == len);
+ // Write \0 for string
+ *(serialized_object + index + len) = 0x00;
+ // Adjust the index
+ index = index + len + 1;
+ }
+ } else if(bson->dbrefString->StrictEquals(constructorString)) {
+ // Unpack the dbref
+ Local dbref = value->ToObject();
+ // Create an object containing the right namespace variables
+ Local obj = Object::New();
+
+ // Build the new object
+ obj->Set(bson->_dbRefRefString, dbref->Get(bson->_dbRefNamespaceString));
+ obj->Set(bson->_dbRefIdRefString, dbref->Get(bson->_dbRefOidString));
+ if(!dbref->Get(bson->_dbRefDbString)->IsNull() && !dbref->Get(bson->_dbRefDbString)->IsUndefined()) obj->Set(bson->_dbRefDbRefString, dbref->Get(bson->_dbRefDbString));
+
+ // Encode the variable
+ index = BSON::serialize(bson, serialized_object, originalIndex, name, obj, false, serializeFunctions);
+ } else if(bson->minKeyString->StrictEquals(constructorString)) {
+ // Save the string at the offset provided
+ *(serialized_object + originalIndex) = BSON_DATA_MIN_KEY;
+ } else if(bson->maxKeyString->StrictEquals(constructorString)) {
+ *(serialized_object + originalIndex) = BSON_DATA_MAX_KEY;
+ }
+ } else if(value->IsObject()) {
+ if(!name->IsNull()) {
+ // Save the string at the offset provided
+ *(serialized_object + index) = BSON_DATA_OBJECT;
+ // Adjust writing position for the first byte
+ index = index + 1;
+ // Convert name to char*
+ ssize_t len = DecodeBytes(name, UTF8);
+ ssize_t written = DecodeWrite((serialized_object + index), len, name, UTF8);
+ assert(written == len);
+ // Add null termiation for the string
+ *(serialized_object + index + len) = '\0';
+ // Adjust the index
+ index = index + len + 1;
+ }
+
+ // Unwrap the object
+ Local object = value->ToObject();
+
+ #if NODE_MAJOR_VERSION == 0 && NODE_MINOR_VERSION < 6
+ Local property_names = object->GetPropertyNames();
+ #else
+ Local property_names = object->GetOwnPropertyNames();
+ #endif
+
+ // Calculate size of the total object
+ uint32_t object_size = BSON::calculate_object_size(bson, value, serializeFunctions);
+ // Write the size
+ BSON::write_int32((serialized_object + index), object_size);
+ // Adjust size
+ index = index + 4;
+
+ // Process all the properties on the object
+ for(uint32_t i = 0; i < property_names->Length(); i++) {
+ // Fetch the property name
+ Local property_name = property_names->Get(i)->ToString();
+ // Fetch the object for the property
+ Local property = object->Get(property_name);
+ // Write the next serialized object
+ // printf("========== !property->IsFunction() || (property->IsFunction() && serializeFunctions) = %d\n", !property->IsFunction() || (property->IsFunction() && serializeFunctions) == true ? 1 : 0);
+ if(!property->IsFunction() || (property->IsFunction() && serializeFunctions)) {
+ // Convert name to char*
+ ssize_t len = DecodeBytes(property_name, UTF8);
+ // char *data = new char[len];
+ char *data = (char *)malloc(len + 1);
+ *(data + len) = '\0';
+ ssize_t written = DecodeWrite(data, len, property_name, UTF8);
+ assert(written == len);
+ // Serialize the content
+ index = BSON::serialize(bson, serialized_object, index, property_name, property, check_key, serializeFunctions);
+ // Free up memory of data
+ free(data);
+ }
+ }
+ // Pad the last item
+ *(serialized_object + index) = '\0';
+ index = index + 1;
+
+ // Null out reminding fields if we have a toplevel object and nested levels
+ if(name->IsNull()) {
+ for(uint32_t i = 0; i < (object_size - index); i++) {
+ *(serialized_object + index + i) = '\0';
+ }
+ }
+ }
+
+ return index;
+}
+
+Handle BSON::SerializeWithBufferAndIndex(const Arguments &args) {
+ HandleScope scope;
+
+ //BSON.serializeWithBufferAndIndex = function serializeWithBufferAndIndex(object, checkKeys, 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]");
+
+ // Unpack the BSON parser instance
+ BSON *bson = ObjectWrap::Unwrap(args.This());
+
+ // Define pointer to data
+ char *data;
+ uint32_t length;
+ // Unpack the object
+ Local obj = args[2]->ToObject();
+
+ // Unpack the buffer object and get pointers to structures
+ #if NODE_MAJOR_VERSION == 0 && NODE_MINOR_VERSION < 3
+ Buffer *buffer = ObjectWrap::Unwrap(obj);
+ data = buffer->data();
+ length = buffer->length();
+ #else
+ data = Buffer::Data(obj);
+ length = Buffer::Length(obj);
+ #endif
+
+ uint32_t object_size = 0;
+ // Calculate the total size of the document in binary form to ensure we only allocate memory once
+ if(args.Length() == 5) {
+ object_size = BSON::calculate_object_size(bson, args[0], args[4]->BooleanValue());
+ } else {
+ object_size = BSON::calculate_object_size(bson, args[0], false);
+ }
+
+ // Unpack the index variable
+ Local indexObject = args[3]->ToUint32();
+ uint32_t index = indexObject->Value();
+
+ // Allocate the memory needed for the serializtion
+ char *serialized_object = (char *)malloc(object_size * sizeof(char));
+
+ // Catch any errors
+ try {
+ // Check if we have a boolean value
+ bool check_key = false;
+ if(args.Length() >= 4 && args[1]->IsBoolean()) {
+ check_key = args[1]->BooleanValue();
+ }
+
+ bool serializeFunctions = false;
+ if(args.Length() == 5) {
+ serializeFunctions = args[4]->BooleanValue();
+ }
+
+ // Serialize the object
+ BSON::serialize(bson, serialized_object, 0, Null(), args[0], check_key, serializeFunctions);
+ } catch(char *err_msg) {
+ // Free up serialized object space
+ free(serialized_object);
+ V8::AdjustAmountOfExternalAllocatedMemory(-object_size);
+ // Throw exception with the string
+ Handle error = VException(err_msg);
+ // free error message
+ free(err_msg);
+ // Return error
+ return error;
+ }
+
+ for(uint32_t i = 0; i < object_size; i++) {
+ *(data + index + i) = *(serialized_object + i);
+ }
+
+ return scope.Close(Uint32::New(index + object_size - 1));
+}
+
+Handle BSON::BSONDeserializeStream(const Arguments &args) {
+ HandleScope scope;
+
+ // At least 3 arguments required
+ if(args.Length() < 5) 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
+ char *data;
+ uint32_t length;
+ Local obj = args[0]->ToObject();
+ uint32_t numberOfDocuments = args[2]->ToUint32()->Value();
+ uint32_t index = args[1]->ToUint32()->Value();
+ uint32_t resultIndex = args[4]->ToUint32()->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);
+ data = buffer->data();
+ length = buffer->length();
+ #else
+ data = Buffer::Data(obj);
+ length = Buffer::Length(obj);
+ #endif
+
+ // Fetch the documents
+ Local documents = args[3]->ToObject();
+
+ for(uint32_t i = 0; i < numberOfDocuments; i++) {
+ // Decode the size of the BSON data structure
+ uint32_t size = BSON::deserialize_int32(data, index);
+
+ // Get result
+ Handle result = BSON::deserialize(bson, data, size, index, NULL);
+
+ // Add result to array
+ documents->Set(i + resultIndex, result);
+
+ // Adjust the index for next pass
+ index = index + size;
+ }
+
+ // Return new index of parsing
+ return scope.Close(Uint32::New(index));
+}
+
+// Exporting function
+extern "C" void init(Handle target) {
+ HandleScope scope;
+ BSON::Initialize(target);
+}
+
+// NODE_MODULE(bson, BSON::Initialize);
+// NODE_MODULE(l, Long::Initialize);
diff --git a/app/node_modules/mongoskin/node_modules/mongodb/external-libs/bson/bson.h b/app/node_modules/mongoskin/node_modules/mongodb/external-libs/bson/bson.h
new file mode 100644
index 0000000..dcf21d1
--- /dev/null
+++ b/app/node_modules/mongoskin/node_modules/mongodb/external-libs/bson/bson.h
@@ -0,0 +1,105 @@
+#ifndef BSON_H_
+#define BSON_H_
+
+#include
+#include
+#include
+
+using namespace v8;
+using namespace node;
+
+class BSON : public ObjectWrap {
+ public:
+ BSON() : ObjectWrap() {}
+ ~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);
+
+ // Experimental
+ static Handle CalculateObjectSize2(const Arguments &args);
+ static Handle BSONSerialize2(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);
+ static uint32_t serialize(BSON *bson, char *serialized_object, uint32_t index, Handle name, Handle value, bool check_key, bool serializeFunctions);
+
+ static char* extract_string(char *data, uint32_t offset);
+ static const char* ToCString(const v8::String::Utf8Value& value);
+ static uint32_t calculate_object_size(BSON *bson, Handle object, bool serializeFunctions);
+
+ static void write_int32(char *data, uint32_t value);
+ static void write_int64(char *data, int64_t value);
+ static void write_double(char *data, double value);
+ static uint16_t deserialize_int8(char *data, uint32_t offset);
+ static uint32_t deserialize_int32(char* data, uint32_t offset);
+ static char *check_key(Local key);
+
+ // 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 comparision 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;
+
+ // Decode JS function
+ static Handle decodeLong(BSON *bson, char *data, uint32_t index);
+ static Handle decodeTimestamp(BSON *bson, char *data, uint32_t index);
+ static Handle decodeOid(BSON *bson, char *oid);
+ static Handle decodeBinary(BSON *bson, uint32_t sub_type, uint32_t number_of_bytes, char *data);
+ static Handle decodeCode(BSON *bson, char *code, Handle scope);
+ static Handle decodeDBref(BSON *bson, Local ref, Local oid, Local db);
+
+ // Experimental
+ static uint32_t calculate_object_size2(Handle object);
+ static uint32_t serialize2(char *serialized_object, uint32_t index, Handle name, Handle value, uint32_t object_size, bool check_key);
+};
+
+#endif // BSON_H_
diff --git a/app/node_modules/mongoskin/node_modules/mongodb/external-libs/bson/index.js b/app/node_modules/mongoskin/node_modules/mongodb/external-libs/bson/index.js
new file mode 100644
index 0000000..2c66dee
--- /dev/null
+++ b/app/node_modules/mongoskin/node_modules/mongodb/external-libs/bson/index.js
@@ -0,0 +1,20 @@
+var bson = require('./bson');
+exports.BSON = bson.BSON;
+exports.Long = require('../../lib/mongodb/bson/long').Long;
+exports.ObjectID = require('../../lib/mongodb/bson/objectid').ObjectID;
+exports.DBRef = require('../../lib/mongodb/bson/db_ref').DBRef;
+exports.Code = require('../../lib/mongodb/bson/code').Code;
+exports.Timestamp = require('../../lib/mongodb/bson/timestamp').Timestamp;
+exports.Binary = require('../../lib/mongodb/bson/binary').Binary;
+exports.Double = require('../../lib/mongodb/bson/double').Double;
+exports.MaxKey = require('../../lib/mongodb/bson/max_key').MaxKey;
+exports.MinKey = require('../../lib/mongodb/bson/min_key').MinKey;
+exports.Symbol = require('../../lib/mongodb/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/app/node_modules/mongoskin/node_modules/mongodb/external-libs/bson/test/test_bson.js b/app/node_modules/mongoskin/node_modules/mongodb/external-libs/bson/test/test_bson.js
new file mode 100644
index 0000000..706f1df
--- /dev/null
+++ b/app/node_modules/mongoskin/node_modules/mongodb/external-libs/bson/test/test_bson.js
@@ -0,0 +1,349 @@
+var sys = require('util'),
+ debug = require('util').debug,
+ inspect = require('util').inspect,
+ Buffer = require('buffer').Buffer,
+ BSON = require('../bson').BSON,
+ Buffer = require('buffer').Buffer,
+ BSONJS = require('../../../lib/mongodb/bson/bson').BSON,
+ BinaryParser = require('../../../lib/mongodb/bson/binary_parser').BinaryParser,
+ Long = require('../../../lib/mongodb/bson/long').Long,
+ ObjectID = require('../../../lib/mongodb/bson/bson').ObjectID,
+ Binary = require('../../../lib/mongodb/bson/bson').Binary,
+ Code = require('../../../lib/mongodb/bson/bson').Code,
+ DBRef = require('../../../lib/mongodb/bson/bson').DBRef,
+ Symbol = require('../../../lib/mongodb/bson/bson').Symbol,
+ Double = require('../../../lib/mongodb/bson/bson').Double,
+ MaxKey = require('../../../lib/mongodb/bson/bson').MaxKey,
+ MinKey = require('../../../lib/mongodb/bson/bson').MinKey,
+ Timestamp = require('../../../lib/mongodb/bson/bson').Timestamp,
+ assert = require('assert');
+
+if(process.env['npm_package_config_native'] != null) return;
+
+sys.puts("=== EXECUTING TEST_BSON ===");
+
+// Should fail due to illegal key
+assert.throws(function() { new ObjectID('foo'); })
+assert.throws(function() { new ObjectID('foo'); })
+
+// Parsers
+var bsonC = new BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]);
+var bsonJS = new BSONJS([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]);
+
+// Simple serialization and deserialization of edge value
+var doc = {doc:0x1ffffffffffffe};
+var simple_string_serialized = bsonC.serialize(doc, false, true);
+assert.deepEqual(simple_string_serialized, bsonJS.serialize(doc, false, true));
+assert.deepEqual(bsonJS.deserialize(new Buffer(simple_string_serialized, 'binary')), bsonC.deserialize(simple_string_serialized));
+
+var doc = {doc:-0x1ffffffffffffe};
+var simple_string_serialized = bsonC.serialize(doc, false, true);
+assert.deepEqual(simple_string_serialized, bsonJS.serialize(doc, false, true));
+assert.deepEqual(bsonJS.deserialize(new Buffer(simple_string_serialized, 'binary')), bsonC.deserialize(simple_string_serialized));
+
+//
+// Assert correct toJSON
+//
+var a = Long.fromNumber(10);
+assert.equal(10, a);
+
+var a = Long.fromNumber(9223372036854775807);
+assert.equal(9223372036854775807, a);
+
+// Simple serialization and deserialization test for a Single String value
+var doc = {doc:'Serialize'};
+var simple_string_serialized = bsonC.serialize(doc, true, false);
+
+assert.deepEqual(simple_string_serialized, bsonJS.serialize(doc, false, true));
+assert.deepEqual(bsonJS.deserialize(new Buffer(simple_string_serialized, 'binary')), bsonC.deserialize(simple_string_serialized));
+
+// Nested doc
+var doc = {a:{b:{c:1}}};
+var simple_string_serialized = bsonC.serialize(doc, false, true);
+
+assert.deepEqual(simple_string_serialized, bsonJS.serialize(doc, false, true));
+assert.deepEqual(bsonJS.deserialize(new Buffer(simple_string_serialized, 'binary')), bsonC.deserialize(simple_string_serialized));
+
+// Simple integer serialization/deserialization test, including testing boundary conditions
+var doc = {doc:-1};
+var simple_string_serialized = bsonC.serialize(doc, false, true);
+assert.deepEqual(simple_string_serialized, bsonJS.serialize(doc, false, true));
+assert.deepEqual(bsonJS.deserialize(new Buffer(simple_string_serialized, 'binary')), bsonC.deserialize(simple_string_serialized));
+
+var doc = {doc:2147483648};
+var simple_string_serialized = bsonC.serialize(doc, false, true);
+assert.deepEqual(bsonJS.deserialize(new Buffer(simple_string_serialized, 'binary')), bsonC.deserialize(simple_string_serialized));
+
+var doc = {doc:-2147483648};
+var simple_string_serialized = bsonC.serialize(doc, false, true);
+assert.deepEqual(simple_string_serialized, bsonJS.serialize(doc, false, true));
+assert.deepEqual(bsonJS.deserialize(new Buffer(simple_string_serialized, 'binary')), bsonC.deserialize(simple_string_serialized));
+
+// Simple serialization and deserialization test for a Long value
+var doc = {doc:Long.fromNumber(9223372036854775807)};
+var simple_string_serialized = bsonC.serialize(doc, false, true);
+assert.deepEqual(simple_string_serialized, bsonJS.serialize({doc:Long.fromNumber(9223372036854775807)}, false, true));
+assert.deepEqual(bsonJS.deserialize(new Buffer(simple_string_serialized, 'binary')), bsonC.deserialize(simple_string_serialized));
+
+var doc = {doc:Long.fromNumber(-9223372036854775807)};
+var simple_string_serialized = bsonC.serialize(doc, false, true);
+assert.deepEqual(simple_string_serialized, bsonJS.serialize({doc:Long.fromNumber(-9223372036854775807)}, false, true));
+assert.deepEqual(bsonJS.deserialize(new Buffer(simple_string_serialized, 'binary')), bsonC.deserialize(simple_string_serialized));
+
+// Simple serialization and deserialization for a Float value
+var doc = {doc:2222.3333};
+var simple_string_serialized = bsonC.serialize(doc, false, true);
+assert.deepEqual(simple_string_serialized, bsonJS.serialize(doc, false, true));
+assert.deepEqual(bsonJS.deserialize(new Buffer(simple_string_serialized, 'binary')), bsonC.deserialize(simple_string_serialized));
+
+var doc = {doc:-2222.3333};
+var simple_string_serialized = bsonC.serialize(doc, false, true);
+assert.deepEqual(simple_string_serialized, bsonJS.serialize(doc, false, true));
+assert.deepEqual(bsonJS.deserialize(new Buffer(simple_string_serialized, 'binary')), bsonC.deserialize(simple_string_serialized));
+
+// Simple serialization and deserialization for a null value
+var doc = {doc:null};
+var simple_string_serialized = bsonC.serialize(doc, false, true);
+assert.deepEqual(simple_string_serialized, bsonJS.serialize(doc, false, true));
+assert.deepEqual(bsonJS.deserialize(new Buffer(simple_string_serialized, 'binary')), bsonC.deserialize(simple_string_serialized));
+
+// Simple serialization and deserialization for a boolean value
+var doc = {doc:true};
+var simple_string_serialized = bsonC.serialize(doc, false, true);
+assert.deepEqual(simple_string_serialized, bsonJS.serialize(doc, false, true));
+assert.deepEqual(bsonJS.deserialize(new Buffer(simple_string_serialized, 'binary')), bsonC.deserialize(simple_string_serialized));
+
+// Simple serialization and deserialization for a date value
+var date = new Date();
+var doc = {doc:date};
+var simple_string_serialized = bsonC.serialize(doc, false, true);
+assert.deepEqual(simple_string_serialized, bsonJS.serialize(doc, false, true));
+assert.deepEqual(bsonJS.deserialize(new Buffer(simple_string_serialized, 'binary')), bsonC.deserialize(simple_string_serialized));
+
+// Simple serialization and deserialization for a boolean value
+var doc = {doc:/abcd/mi};
+var simple_string_serialized = bsonC.serialize(doc, false, true);
+assert.deepEqual(simple_string_serialized, bsonJS.serialize(doc, false, true));
+assert.equal(bsonJS.deserialize(new Buffer(simple_string_serialized, 'binary')).doc.toString(), bsonC.deserialize(simple_string_serialized).doc.toString());
+
+var doc = {doc:/abcd/};
+var simple_string_serialized = bsonC.serialize(doc, false, true);
+assert.deepEqual(simple_string_serialized, bsonJS.serialize(doc, false, true));
+assert.equal(bsonJS.deserialize(new Buffer(simple_string_serialized, 'binary')).doc.toString(), bsonC.deserialize(simple_string_serialized).doc.toString());
+
+// Simple serialization and deserialization for a objectId value
+var doc = {doc:new ObjectID()};
+var simple_string_serialized = bsonC.serialize(doc, false, true);
+var doc2 = {doc:ObjectID.createFromHexString(doc.doc.toHexString())};
+
+assert.deepEqual(simple_string_serialized, bsonJS.serialize(doc2, false, true));
+assert.deepEqual(bsonJS.deserialize(new Buffer(simple_string_serialized, 'binary')).doc.toString(), bsonC.deserialize(simple_string_serialized).doc.toString());
+
+// Simple serialization and deserialization for a Binary value
+var binary = new Binary();
+var string = 'binstring'
+for(var index = 0; index < string.length; index++) { binary.put(string.charAt(index)); }
+
+var Binary = new Binary();
+var string = 'binstring'
+for(var index = 0; index < string.length; index++) { Binary.put(string.charAt(index)); }
+
+var simple_string_serialized = bsonC.serialize({doc:binary}, false, true);
+assert.deepEqual(simple_string_serialized, bsonJS.serialize({doc:Binary}, false, true));
+assert.deepEqual(bsonJS.deserialize(new Buffer(simple_string_serialized, 'binary')).doc.value(), bsonC.deserialize(simple_string_serialized).doc.value());
+
+// Simple serialization and deserialization for a Code value
+var code = new Code('this.a > i', {'i': 1});
+var Code = new Code('this.a > i', {'i': 1});
+var simple_string_serialized_2 = bsonJS.serialize({doc:Code}, false, true);
+var simple_string_serialized = bsonC.serialize({doc:code}, false, true);
+
+assert.deepEqual(simple_string_serialized, simple_string_serialized_2);
+assert.deepEqual(bsonJS.deserialize(new Buffer(simple_string_serialized_2, 'binary')).doc.scope, bsonC.deserialize(simple_string_serialized).doc.scope);
+
+// Simple serialization and deserialization for an Object
+var simple_string_serialized = bsonC.serialize({doc:{a:1, b:{c:2}}}, false, true);
+var simple_string_serialized_2 = bsonJS.serialize({doc:{a:1, b:{c:2}}}, false, true);
+assert.deepEqual(simple_string_serialized, simple_string_serialized_2)
+assert.deepEqual(bsonJS.deserialize(new Buffer(simple_string_serialized_2, 'binary')).doc, bsonC.deserialize(simple_string_serialized).doc);
+
+// Simple serialization and deserialization for an Array
+var simple_string_serialized = bsonC.serialize({doc:[9, 9, 1, 2, 3, 1, 1, 1, 1, 1, 1, 1]}, false, true);
+var simple_string_serialized_2 = bsonJS.serialize({doc:[9, 9, 1, 2, 3, 1, 1, 1, 1, 1, 1, 1]}, false, true);
+
+assert.deepEqual(simple_string_serialized, simple_string_serialized_2)
+assert.deepEqual(bsonJS.deserialize(new Buffer(simple_string_serialized_2, 'binary')).doc, bsonC.deserialize(simple_string_serialized).doc);
+
+// Simple serialization and deserialization for a DBRef
+var oid = new ObjectID()
+var oid2 = new ObjectID.createFromHexString(oid.toHexString())
+var simple_string_serialized = bsonJS.serialize({doc:new DBRef('namespace', oid2, 'integration_tests_')}, false, true);
+var simple_string_serialized_2 = bsonC.serialize({doc:new DBRef('namespace', oid, 'integration_tests_')}, false, true);
+
+assert.deepEqual(simple_string_serialized, simple_string_serialized_2)
+// Ensure we have the same values for the dbref
+var object_js = bsonJS.deserialize(new Buffer(simple_string_serialized_2, 'binary'));
+var object_c = bsonC.deserialize(simple_string_serialized);
+
+assert.equal(object_js.doc.namespace, object_c.doc.namespace);
+assert.equal(object_js.doc.oid.toHexString(), object_c.doc.oid.toHexString());
+assert.equal(object_js.doc.db, object_c.doc.db);
+
+// Serialized document
+var bytes = [47,0,0,0,2,110,97,109,101,0,6,0,0,0,80,97,116,116,121,0,16,97,103,101,0,34,0,0,0,7,95,105,100,0,76,100,12,23,11,30,39,8,89,0,0,1,0];
+var serialized_data = '';
+// Convert to chars
+for(var i = 0; i < bytes.length; i++) {
+ serialized_data = serialized_data + BinaryParser.fromByte(bytes[i]);
+}
+var object = bsonC.deserialize(new Buffer(serialized_data, 'binary'));
+assert.equal('Patty', object.name)
+assert.equal(34, object.age)
+assert.equal('4c640c170b1e270859000001', object._id.toHexString())
+
+// Serialize utf8
+var doc = { "name" : "本荘由利地域に洪水警報", "name1" : "öüóőúéáűíÖÜÓŐÚÉÁŰÍ", "name2" : "abcdedede"};
+var simple_string_serialized = bsonC.serialize(doc, false, true);
+var simple_string_serialized2 = bsonJS.serialize(doc, false, true);
+assert.deepEqual(simple_string_serialized, simple_string_serialized2)
+
+var object = bsonC.deserialize(simple_string_serialized);
+assert.equal(doc.name, object.name)
+assert.equal(doc.name1, object.name1)
+assert.equal(doc.name2, object.name2)
+
+// Serialize object with array
+var doc = {b:[1, 2, 3]};
+var simple_string_serialized = bsonC.serialize(doc, false, true);
+var simple_string_serialized_2 = bsonJS.serialize(doc, false, true);
+assert.deepEqual(simple_string_serialized, simple_string_serialized_2)
+
+var object = bsonC.deserialize(simple_string_serialized);
+assert.deepEqual(doc, object)
+
+// Test equality of an object ID
+var object_id = new ObjectID();
+var object_id_2 = new ObjectID();
+assert.ok(object_id.equals(object_id));
+assert.ok(!(object_id.equals(object_id_2)))
+
+// Test same serialization for Object ID
+var object_id = new ObjectID();
+var object_id2 = ObjectID.createFromHexString(object_id.toString())
+var simple_string_serialized = bsonJS.serialize({doc:object_id}, false, true);
+var simple_string_serialized_2 = bsonC.serialize({doc:object_id2}, false, true);
+
+assert.equal(simple_string_serialized_2.length, simple_string_serialized.length);
+assert.deepEqual(simple_string_serialized, simple_string_serialized_2)
+var object = bsonJS.deserialize(new Buffer(simple_string_serialized_2, 'binary'));
+var object2 = bsonC.deserialize(simple_string_serialized);
+assert.equal(object.doc.id, object2.doc.id)
+
+// JS Object
+var c1 = { _id: new ObjectID, comments: [], title: 'number 1' };
+var c2 = { _id: new ObjectID, comments: [], title: 'number 2' };
+var doc = {
+ numbers: []
+ , owners: []
+ , comments: [c1, c2]
+ , _id: new ObjectID
+};
+
+var simple_string_serialized = bsonJS.serialize(doc, false, true);
+
+// C++ Object
+var c1 = { _id: ObjectID.createFromHexString(c1._id.toHexString()), comments: [], title: 'number 1' };
+var c2 = { _id: ObjectID.createFromHexString(c2._id.toHexString()), comments: [], title: 'number 2' };
+var doc = {
+ numbers: []
+ , owners: []
+ , comments: [c1, c2]
+ , _id: ObjectID.createFromHexString(doc._id.toHexString())
+};
+
+var simple_string_serialized_2 = bsonC.serialize(doc, false, true);
+
+for(var i = 0; i < simple_string_serialized_2.length; i++) {
+ // debug(i + "[" + simple_string_serialized_2[i] + "] = [" + simple_string_serialized[i] + "]")
+ assert.equal(simple_string_serialized_2[i], simple_string_serialized[i]);
+}
+
+// Deserialize the string
+var doc1 = bsonJS.deserialize(new Buffer(simple_string_serialized_2));
+var doc2 = bsonC.deserialize(new Buffer(simple_string_serialized_2));
+assert.equal(doc._id.id, doc1._id.id)
+assert.equal(doc._id.id, doc2._id.id)
+assert.equal(doc1._id.id, doc2._id.id)
+
+var doc = {
+ _id: 'testid',
+ key1: { code: 'test1', time: {start:1309323402727,end:1309323402727}, x:10, y:5 },
+ key2: { code: 'test1', time: {start:1309323402727,end:1309323402727}, x:10, y:5 }
+};
+
+var simple_string_serialized = bsonJS.serialize(doc, false, true);
+var simple_string_serialized_2 = bsonC.serialize(doc, false, true);
+
+// Deserialize the string
+var doc1 = bsonJS.deserialize(new Buffer(simple_string_serialized_2));
+var doc2 = bsonC.deserialize(new Buffer(simple_string_serialized_2));
+assert.deepEqual(doc2, doc1)
+assert.deepEqual(doc, doc2)
+assert.deepEqual(doc, doc1)
+
+// Serialize function
+var doc = {
+ _id: 'testid',
+ key1: function() {}
+}
+
+var simple_string_serialized = bsonJS.serialize(doc, false, true, true);
+var simple_string_serialized_2 = bsonC.serialize(doc, false, true, true);
+
+// Deserialize the string
+var doc1 = bsonJS.deserialize(new Buffer(simple_string_serialized_2));
+var doc2 = bsonC.deserialize(new Buffer(simple_string_serialized_2));
+assert.equal(doc1.key1.code.toString(), doc2.key1.code.toString())
+
+var doc = {"user_id":"4e9fc8d55883d90100000003","lc_status":{"$ne":"deleted"},"owner_rating":{"$exists":false}};
+var simple_string_serialized = bsonJS.serialize(doc, false, true, true);
+var simple_string_serialized_2 = bsonC.serialize(doc, false, true, true);
+
+// Should serialize to the same value
+assert.equal(simple_string_serialized_2.toString('base64'), simple_string_serialized.toString('base64'))
+var doc1 = bsonJS.deserialize(simple_string_serialized_2);
+var doc2 = bsonC.deserialize(simple_string_serialized);
+assert.deepEqual(doc1, doc2)
+
+// Hex Id
+var hexId = new ObjectID().toString();
+var docJS = {_id: ObjectID.createFromHexString(hexId), 'funds.remaining': {$gte: 1.222}, 'transactions.id': {$ne: ObjectID.createFromHexString(hexId)}};
+var docC = {_id: ObjectID.createFromHexString(hexId), 'funds.remaining': {$gte: 1.222}, 'transactions.id': {$ne: ObjectID.createFromHexString(hexId)}};
+var docJSBin = bsonJS.serialize(docJS, false, true, true);
+var docCBin = bsonC.serialize(docC, false, true, true);
+assert.equal(docCBin.toString('base64'), docJSBin.toString('base64'));
+
+// // Complex document serialization
+// doc = {"DateTime": "Tue Nov 40 2011 17:27:55 GMT+0000 (WEST)","isActive": true,"Media": {"URL": "http://videos.sapo.pt/Tc85NsjaKjj8o5aV7Ubb"},"Title": "Lisboa fecha a ganhar 0.19%","SetPosition": 60,"Type": "videos","Thumbnail": [{"URL": "http://rd3.videos.sapo.pt/Tc85NsjaKjj8o5aV7Ubb/pic/320x240","Dimensions": {"Height": 240,"Width": 320}}],"Source": {"URL": "http://videos.sapo.pt","SetID": "1288","SourceID": "http://videos.sapo.pt/tvnet/rss2","SetURL": "http://noticias.sapo.pt/videos/tv-net_1288/","ItemID": "Tc85NsjaKjj8o5aV7Ubb","Name": "SAPO VÃdeos"},"Category": "Tec_ciencia","Description": "Lisboa fecha a ganhar 0.19%","GalleryID": new ObjectID("4eea2a634ce8573200000000"),"InternalRefs": {"RegisterDate": "Thu Dec 15 2011 17:12:51 GMT+0000 (WEST)","ChangeDate": "Thu Dec 15 2011 17:12:51 GMT+0000 (WEST)","Hash": 332279244514},"_id": new ObjectID("4eea2a96e52778160000003a")}
+// var docJSBin = bsonJS.serialize(docJS, false, true, true);
+// var docCBin = bsonC.serialize(docC, false, true, true);
+//
+//
+
+// // Force garbage collect
+// global.gc();
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/app/node_modules/mongoskin/node_modules/mongodb/external-libs/bson/test/test_full_bson.js b/app/node_modules/mongoskin/node_modules/mongodb/external-libs/bson/test/test_full_bson.js
new file mode 100644
index 0000000..2a6506c
--- /dev/null
+++ b/app/node_modules/mongoskin/node_modules/mongodb/external-libs/bson/test/test_full_bson.js
@@ -0,0 +1,218 @@
+var sys = require('util'),
+ fs = require('fs'),
+ Buffer = require('buffer').Buffer,
+ BSON = require('../bson').BSON,
+ Buffer = require('buffer').Buffer,
+ assert = require('assert'),
+ BinaryParser = require('../../../lib/mongodb/bson/binary_parser').BinaryParser,
+ BSONJS = require('../../../lib/mongodb/bson/bson').BSON,
+ Long = require('../../../lib/mongodb/bson/long').Long,
+ ObjectID = require('../../../lib/mongodb/bson/bson').ObjectID,
+ Binary = require('../../../lib/mongodb/bson/bson').Binary,
+ Code = require('../../../lib/mongodb/bson/bson').Code,
+ DBRef = require('../../../lib/mongodb/bson/bson').DBRef,
+ Symbol = require('../../../lib/mongodb/bson/bson').Symbol,
+ Double = require('../../../lib/mongodb/bson/bson').Double,
+ MaxKey = require('../../../lib/mongodb/bson/bson').MaxKey,
+ MinKey = require('../../../lib/mongodb/bson/bson').MinKey,
+ Timestamp = require('../../../lib/mongodb/bson/bson').Timestamp;
+
+if(process.env['npm_package_config_native'] != null) return;
+
+sys.puts("=== EXECUTING TEST_FULL_BSON ===");
+
+// Parsers
+var bsonC = new BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]);
+var bsonJS = new BSONJS([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]);
+
+// Should Correctly Deserialize object
+var bytes = [95,0,0,0,2,110,115,0,42,0,0,0,105,110,116,101,103,114,97,116,105,111,110,95,116,101,115,116,115,95,46,116,101,115,116,95,105,110,100,101,120,95,105,110,102,111,114,109,97,116,105,111,110,0,8,117,110,105,113,117,101,0,0,3,107,101,121,0,12,0,0,0,16,97,0,1,0,0,0,0,2,110,97,109,101,0,4,0,0,0,97,95,49,0,0];
+var serialized_data = '';
+// Convert to chars
+for(var i = 0; i < bytes.length; i++) {
+ serialized_data = serialized_data + BinaryParser.fromByte(bytes[i]);
+}
+var object = bsonC.deserialize(serialized_data);
+assert.equal("a_1", object.name);
+assert.equal(false, object.unique);
+assert.equal(1, object.key.a);
+
+// Should Correctly Deserialize object with all types
+var bytes = [26,1,0,0,7,95,105,100,0,161,190,98,75,118,169,3,0,0,3,0,0,4,97,114,114,97,121,0,26,0,0,0,16,48,0,1,0,0,0,16,49,0,2,0,0,0,16,50,0,3,0,0,0,0,2,115,116,114,105,110,103,0,6,0,0,0,104,101,108,108,111,0,3,104,97,115,104,0,19,0,0,0,16,97,0,1,0,0,0,16,98,0,2,0,0,0,0,9,100,97,116,101,0,161,190,98,75,0,0,0,0,7,111,105,100,0,161,190,98,75,90,217,18,0,0,1,0,0,5,98,105,110,97,114,121,0,7,0,0,0,2,3,0,0,0,49,50,51,16,105,110,116,0,42,0,0,0,1,102,108,111,97,116,0,223,224,11,147,169,170,64,64,11,114,101,103,101,120,112,0,102,111,111,98,97,114,0,105,0,8,98,111,111,108,101,97,110,0,1,15,119,104,101,114,101,0,25,0,0,0,12,0,0,0,116,104,105,115,46,120,32,61,61,32,51,0,5,0,0,0,0,3,100,98,114,101,102,0,37,0,0,0,2,36,114,101,102,0,5,0,0,0,116,101,115,116,0,7,36,105,100,0,161,190,98,75,2,180,1,0,0,2,0,0,0,10,110,117,108,108,0,0];
+var serialized_data = '';
+// Convert to chars
+for(var i = 0; i < bytes.length; i++) {
+ serialized_data = serialized_data + BinaryParser.fromByte(bytes[i]);
+}
+
+var object = bsonJS.deserialize(new Buffer(serialized_data, 'binary'));
+assert.equal("hello", object.string);
+assert.deepEqual([1, 2, 3], object.array);
+assert.equal(1, object.hash.a);
+assert.equal(2, object.hash.b);
+assert.ok(object.date != null);
+assert.ok(object.oid != null);
+assert.ok(object.binary != null);
+assert.equal(42, object.int);
+assert.equal(33.3333, object.float);
+assert.ok(object.regexp != null);
+assert.equal(true, object.boolean);
+assert.ok(object.where != null);
+assert.ok(object.dbref != null);
+assert.ok(object['null'] == null);
+
+// Should Serialize and Deserialze String
+var test_string = {hello: 'world'}
+var serialized_data = bsonC.serialize(test_string)
+assert.deepEqual(test_string, bsonC.deserialize(serialized_data));
+
+// Should Correctly Serialize and Deserialize Integer
+var test_number = {doc: 5}
+var serialized_data = bsonC.serialize(test_number)
+assert.deepEqual(test_number, bsonC.deserialize(serialized_data));
+
+// Should Correctly Serialize and Deserialize null value
+var test_null = {doc:null}
+var serialized_data = bsonC.serialize(test_null)
+var object = bsonC.deserialize(serialized_data);
+assert.deepEqual(test_null, object);
+
+// Should Correctly Serialize and Deserialize undefined value
+var test_undefined = {doc:undefined}
+var serialized_data = bsonC.serialize(test_undefined)
+var object = bsonJS.deserialize(new Buffer(serialized_data, 'binary'));
+assert.equal(null, object.doc)
+
+// Should Correctly Serialize and Deserialize Number
+var test_number = {doc: 5.5}
+var serialized_data = bsonC.serialize(test_number)
+assert.deepEqual(test_number, bsonC.deserialize(serialized_data));
+
+// Should Correctly Serialize and Deserialize Integer
+var test_int = {doc: 42}
+var serialized_data = bsonC.serialize(test_int)
+assert.deepEqual(test_int, bsonC.deserialize(serialized_data));
+
+test_int = {doc: -5600}
+serialized_data = bsonC.serialize(test_int)
+assert.deepEqual(test_int, bsonC.deserialize(serialized_data));
+
+test_int = {doc: 2147483647}
+serialized_data = bsonC.serialize(test_int)
+assert.deepEqual(test_int, bsonC.deserialize(serialized_data));
+
+test_int = {doc: -2147483648}
+serialized_data = bsonC.serialize(test_int)
+assert.deepEqual(test_int, bsonC.deserialize(serialized_data));
+
+// Should Correctly Serialize and Deserialize Object
+var doc = {doc: {age: 42, name: 'Spongebob', shoe_size: 9.5}}
+var serialized_data = bsonC.serialize(doc)
+assert.deepEqual(doc, bsonC.deserialize(serialized_data));
+
+// Should Correctly Serialize and Deserialize Array
+var doc = {doc: [1, 2, 'a', 'b']}
+var serialized_data = bsonC.serialize(doc)
+assert.deepEqual(doc, bsonC.deserialize(serialized_data));
+
+// Should Correctly Serialize and Deserialize Array with added on functions
+var doc = {doc: [1, 2, 'a', 'b']}
+var serialized_data = bsonC.serialize(doc)
+assert.deepEqual(doc, bsonC.deserialize(serialized_data));
+
+// Should Correctly Serialize and Deserialize A Boolean
+var doc = {doc: true}
+var serialized_data = bsonC.serialize(doc)
+assert.deepEqual(doc, bsonC.deserialize(serialized_data));
+
+// Should Correctly Serialize and Deserialize a Date
+var date = new Date()
+//(2009, 11, 12, 12, 00, 30)
+date.setUTCDate(12)
+date.setUTCFullYear(2009)
+date.setUTCMonth(11 - 1)
+date.setUTCHours(12)
+date.setUTCMinutes(0)
+date.setUTCSeconds(30)
+var doc = {doc: date}
+var serialized_data = bsonC.serialize(doc)
+assert.deepEqual(doc, bsonC.deserialize(serialized_data));
+
+// // Should Correctly Serialize and Deserialize Oid
+var doc = {doc: new ObjectID()}
+var serialized_data = bsonC.serialize(doc)
+assert.deepEqual(doc.doc.toHexString(), bsonC.deserialize(serialized_data).doc.toHexString())
+
+// Should Correctly encode Empty Hash
+var test_code = {}
+var serialized_data = bsonC.serialize(test_code)
+assert.deepEqual(test_code, bsonC.deserialize(serialized_data));
+
+// Should Correctly Serialize and Deserialize Ordered Hash
+var doc = {doc: {b:1, a:2, c:3, d:4}}
+var serialized_data = bsonC.serialize(doc)
+var decoded_hash = bsonC.deserialize(serialized_data).doc
+var keys = []
+for(name in decoded_hash) keys.push(name)
+assert.deepEqual(['b', 'a', 'c', 'd'], keys)
+
+// Should Correctly Serialize and Deserialize Regular Expression
+// Serialize the regular expression
+var doc = {doc: /foobar/mi}
+var serialized_data = bsonC.serialize(doc)
+var doc2 = bsonC.deserialize(serialized_data);
+assert.equal(doc.doc.toString(), doc2.doc.toString())
+
+// Should Correctly Serialize and Deserialize a Binary object
+var bin = new Binary()
+var string = 'binstring'
+for(var index = 0; index < string.length; index++) {
+ bin.put(string.charAt(index))
+}
+var doc = {doc: bin}
+var serialized_data = bsonC.serialize(doc)
+var deserialized_data = bsonC.deserialize(serialized_data);
+assert.equal(doc.doc.value(), deserialized_data.doc.value())
+
+// Should Correctly Serialize and Deserialize a big Binary object
+var data = fs.readFileSync("../../test/gridstore/test_gs_weird_bug.png", 'binary');
+var bin = new Binary()
+bin.write(data)
+var doc = {doc: bin}
+var serialized_data = bsonC.serialize(doc)
+var deserialized_data = bsonC.deserialize(serialized_data);
+assert.equal(doc.doc.value(), deserialized_data.doc.value())
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/app/node_modules/mongoskin/node_modules/mongodb/external-libs/bson/test/test_stackless_bson.js b/app/node_modules/mongoskin/node_modules/mongodb/external-libs/bson/test/test_stackless_bson.js
new file mode 100644
index 0000000..f271cac
--- /dev/null
+++ b/app/node_modules/mongoskin/node_modules/mongodb/external-libs/bson/test/test_stackless_bson.js
@@ -0,0 +1,132 @@
+var Buffer = require('buffer').Buffer,
+ BSON = require('../bson').BSON,
+ Buffer = require('buffer').Buffer,
+ BSONJS = require('../../../lib/mongodb/bson/bson').BSON,
+ BinaryParser = require('../../../lib/mongodb/bson/binary_parser').BinaryParser,
+ Long = require('../../../lib/mongodb/bson/long').Long,
+ ObjectID = require('../../../lib/mongodb/bson/bson').ObjectID,
+ Binary = require('../../../lib/mongodb/bson/bson').Binary,
+ Code = require('../../../lib/mongodb/bson/bson').Code,
+ DBRef = require('../../../lib/mongodb/bson/bson').DBRef,
+ Symbol = require('../../../lib/mongodb/bson/bson').Symbol,
+ Double = require('../../../lib/mongodb/bson/bson').Double,
+ MaxKey = require('../../../lib/mongodb/bson/bson').MaxKey,
+ MinKey = require('../../../lib/mongodb/bson/bson').MinKey,
+ Timestamp = require('../../../lib/mongodb/bson/bson').Timestamp;
+ assert = require('assert');
+
+if(process.env['npm_package_config_native'] != null) return;
+
+console.log("=== EXECUTING TEST_STACKLESS_BSON ===");
+
+// Parsers
+var bsonC = new BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]);
+var bsonJS = new BSONJS([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]);
+
+// Number of iterations for the benchmark
+var COUNT = 10000;
+// var COUNT = 1;
+// Sample simple doc
+var doc = {key:"Hello world", key2:"šđžčćŠĐŽČĆ", key3:'客家话', key4:'how are you doing dog!!'};
+// var doc = {};
+// for(var i = 0; i < 100; i++) {
+// doc['string' + i] = "dumdyms fsdfdsfdsfdsfsdfdsfsdfsdfsdfsdfsdfsdfsdffsfsdfs";
+// }
+
+// // Calculate size
+console.log(bsonC.calculateObjectSize2(doc));
+console.log(bsonJS.calculateObjectSize(doc));
+// assert.equal(bsonJS.calculateObjectSize(doc), bsonC.calculateObjectSize2(doc));
+
+// ----------------------------------------------------------------------------
+// ----------------------------------------------------------------------------
+// Benchmark calculateObjectSize
+// ----------------------------------------------------------------------------
+// ----------------------------------------------------------------------------
+
+// Benchmark 1 JS BSON
+console.log(COUNT + "x (objectBSON = bsonC.calculateObjectSize(object))")
+start = new Date
+
+for (j=COUNT; --j>=0; ) {
+ var objectBSON = bsonJS.calculateObjectSize(doc);
+}
+
+end = new Date
+var opsprsecond = COUNT / ((end - start)/1000);
+console.log("time = ", end - start, "ms -", COUNT / ((end - start)/1000), " ops/sec");
+
+// Benchmark 2 C++ BSON calculateObjectSize
+console.log(COUNT + "x (objectBSON = bsonC.calculateObjectSize(object))")
+start = new Date
+
+for (j=COUNT; --j>=0; ) {
+ var objectBSON = bsonC.calculateObjectSize(doc);
+}
+
+end = new Date
+var opsprsecond = COUNT / ((end - start)/1000);
+console.log("time = ", end - start, "ms -", COUNT / ((end - start)/1000), " ops/sec");
+
+// Benchmark 3 C++ BSON calculateObjectSize2
+console.log(COUNT + "x (objectBSON = bsonC.calculateObjectSize2(object))")
+start = new Date
+
+for (j=COUNT; --j>=0; ) {
+ var objectBSON = bsonC.calculateObjectSize2(doc);
+}
+
+end = new Date
+var opsprsecond = COUNT / ((end - start)/1000);
+console.log("time = ", end - start, "ms -", COUNT / ((end - start)/1000), " ops/sec");
+
+// // Serialize the content
+// var _serializedDoc1 = bsonJS.serialize(doc, true, false);
+// var _serializedDoc2 = bsonC.serialize2(doc, true, false);
+// console.dir(_serializedDoc1);
+// console.dir(_serializedDoc2);
+// assert.equal(_serializedDoc1.toString('base64'), _serializedDoc2.toString('base64'))
+//
+//
+// // Benchmark 1
+// console.log(COUNT + "x (objectBSON = bsonC.serialize(object))")
+// start = new Date
+//
+// for (j=COUNT; --j>=0; ) {
+// // var objectBSON = bsonC.serialize2(doc, true, false);
+// var objectBSON = bsonJS.serialize(doc, true, false);
+// }
+//
+// end = new Date
+// var opsprsecond = COUNT / ((end - start)/1000);
+// console.log("bson size (bytes): ", objectbsonC.length);
+// console.log("time = ", end - start, "ms -", COUNT / ((end - start)/1000), " ops/sec");
+// console.log("MB/s = " + ((opsprsecond*objectbsonC.length)/1024));
+//
+// // Benchmark 2
+// console.log(COUNT + "x (objectBSON = bsonC.serialize(object))")
+// start = new Date
+//
+// for (j=COUNT; --j>=0; ) {
+// var objectBSON = bsonC.serialize2(doc, true, false);
+// }
+//
+// end = new Date
+// var opsprsecond = COUNT / ((end - start)/1000);
+// console.log("bson size (bytes): ", objectbsonC.length);
+// console.log("time = ", end - start, "ms -", COUNT / ((end - start)/1000), " ops/sec");
+// console.log("MB/s = " + ((opsprsecond*objectbsonC.length)/1024));
+//
+// // Benchmark 3
+// console.log(COUNT + "x (objectBSON = bsonC.serialize(object))")
+// start = new Date
+//
+// for (j=COUNT; --j>=0; ) {
+// var objectBSON = bsonC.serialize(doc, true, false);
+// }
+//
+// end = new Date
+// var opsprsecond = COUNT / ((end - start)/1000);
+// console.log("bson size (bytes): ", objectbsonC.length);
+// console.log("time = ", end - start, "ms -", COUNT / ((end - start)/1000), " ops/sec");
+// console.log("MB/s = " + ((opsprsecond*objectbsonC.length)/1024));
diff --git a/app/node_modules/mongoskin/node_modules/mongodb/external-libs/bson/wscript b/app/node_modules/mongoskin/node_modules/mongodb/external-libs/bson/wscript
new file mode 100644
index 0000000..40f5317
--- /dev/null
+++ b/app/node_modules/mongoskin/node_modules/mongodb/external-libs/bson/wscript
@@ -0,0 +1,39 @@
+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/app/node_modules/mongoskin/node_modules/mongodb/index.js b/app/node_modules/mongoskin/node_modules/mongodb/index.js
new file mode 100644
index 0000000..4f59e9d
--- /dev/null
+++ b/app/node_modules/mongoskin/node_modules/mongodb/index.js
@@ -0,0 +1 @@
+module.exports = require('./lib/mongodb');
diff --git a/app/node_modules/mongoskin/node_modules/mongodb/install.js b/app/node_modules/mongoskin/node_modules/mongodb/install.js
new file mode 100644
index 0000000..f9f2a57
--- /dev/null
+++ b/app/node_modules/mongoskin/node_modules/mongodb/install.js
@@ -0,0 +1,40 @@
+var spawn = require('child_process').spawn,
+ exec = require('child_process').exec;
+
+process.stdout.write("================================================================================\n");
+process.stdout.write("= =\n");
+process.stdout.write("= To install with C++ bson parser do =\n");
+process.stdout.write("= =\n");
+process.stdout.write("================================================================================\n");
+
+// Check if we want to build the native code
+var build_native = process.env['npm_package_config_native'] != null ? process.env['npm_package_config_native'] : 'false';
+build_native = build_native == 'true' ? true : false;
+// If we are building the native bson extension ensure we use gmake if available
+if(build_native) {
+ // Check if we need to use gmake
+ exec('which gmake', function(err, stdout, stderr) {
+ // Set up spawn command
+ var make = null;
+ // No gmake build using make
+ if(err != null) {
+ make = spawn('make', ['total']);
+ } else {
+ make = spawn('gmake', ['total']);
+ }
+
+ // Execute spawn
+ make.stdout.on('data', function(data) {
+ process.stdout.write(data);
+ })
+
+ make.stderr.on('data', function(data) {
+ process.stdout.write(data);
+ })
+
+ make.on('exit', function(code) {
+ process.stdout.write('child process exited with code ' + code + "\n");
+ })
+ });
+}
+
diff --git a/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/admin.js b/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/admin.js
new file mode 100644
index 0000000..cb008a3
--- /dev/null
+++ b/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/admin.js
@@ -0,0 +1,390 @@
+/*!
+ * Module dependencies.
+ */
+var Collection = require('./collection').Collection,
+ Cursor = require('./cursor').Cursor,
+ DbCommand = require('./commands/db_command').DbCommand;
+
+/**
+ * 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 Callback function of format `function(err, result) {}`.
+ * @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 Callback function of format `function(err, result) {}`.
+ * @return {null} Returns no result
+ * @api private
+ */
+Admin.prototype.serverInfo = function(callback) {
+ var self = this;
+ var command = {buildinfo:1};
+ this.command(command, 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 returns the server status.
+ * @return {null}
+ * @api public
+ */
+Admin.prototype.serverStatus = function(callback) {
+ var self = this;
+
+ this.command({serverStatus: 1}, function(err, result) {
+ if (err == null && result.documents[0].ok == 1) {
+ callback(null, result.documents[0]);
+ } else {
+ if (err) {
+ callback(err, false);
+ } else {
+ callback(self.wrap(result.documents[0]), false);
+ }
+ }
+ });
+};
+
+/**
+ * Retrieve the current profiling Level for MongoDB
+ *
+ * @param {Function} callback Callback function of format `function(err, result) {}`.
+ * @return {null} Returns no result
+ * @api public
+ */
+Admin.prototype.profilingLevel = function(callback) {
+ var self = this;
+ var command = {profile:-1};
+
+ this.command(command, function(err, doc) {
+ doc = doc.documents[0];
+
+ if(err == null && (doc.ok == 1 || typeof doc.was === 'number')) {
+ var was = doc.was;
+ if(was == 0) {
+ callback(null, "off");
+ } else if(was == 1) {
+ callback(null, "slow_only");
+ } else if(was == 2) {
+ callback(null, "all");
+ } else {
+ 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 {Object} [options] Optional parameters to the command.
+ * @param {Function} callback Callback function of format `function(err, result) {}`.
+ * @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();
+ options = args.length ? args.shift() : {};
+ // Set self
+ var self = this;
+ var databaseName = this.db.databaseName;
+ this.db.databaseName = 'admin';
+ this.db.executeDbCommand({ping:1}, options, function(err, result) {
+ self.db.databaseName = databaseName;
+ return callback(err, result);
+ })
+}
+
+/**
+ * Authenticate against MongoDB
+ *
+ * @param {String} username The user name for the authentication.
+ * @param {String} password The password for the authentication.
+ * @param {Function} callback Callback function of format `function(err, result) {}`.
+ * @return {null} Returns no result
+ * @api public
+ */
+Admin.prototype.authenticate = function(username, password, callback) {
+ var self = this;
+ var databaseName = this.db.databaseName;
+ this.db.databaseName = 'admin';
+ this.db.authenticate(username, password, function(err, result) {
+ self.db.databaseName = databaseName;
+ return callback(err, result);
+ })
+}
+
+/**
+ * Logout current authenticated user
+ *
+ * @param {Object} [options] Optional parameters to the command.
+ * @param {Function} callback Callback function of format `function(err, result) {}`.
+ * @return {null} Returns no result
+ * @api public
+ */
+Admin.prototype.logout = function(callback) {
+ var self = this;
+ var databaseName = this.db.databaseName;
+ this.db.databaseName = 'admin';
+ this.db.logout(function(err, result) {
+ return callback(err, result);
+ })
+
+ self.db.databaseName = databaseName;
+}
+
+/**
+ * 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 Callback function of format `function(err, result) {}`.
+ * @return {null} Returns no result
+ * @api public
+ */
+Admin.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() : {};
+
+ var self = this;
+ var databaseName = this.db.databaseName;
+ this.db.databaseName = 'admin';
+ this.db.addUser(username, password, options, function(err, result) {
+ self.db.databaseName = databaseName;
+ return callback(err, result);
+ })
+}
+
+/**
+ * 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 Callback function of format `function(err, result) {}`.
+ * @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() : {};
+
+ var self = this;
+ var databaseName = this.db.databaseName;
+ this.db.databaseName = 'admin';
+ this.db.removeUser(username, options, function(err, result) {
+ self.db.databaseName = databaseName;
+ return callback(err, result);
+ })
+}
+
+/**
+ * Set the current profiling level of MongoDB
+ *
+ * @param {String} level The new profiling level (off, slow_only, all)
+ * @param {Function} callback Callback function of format `function(err, result) {}`.
+ * @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;
+ // Execute the command to set the profiling level
+ this.command(command, function(err, doc) {
+ doc = doc.documents[0];
+
+ if(err == null && (doc.ok == 1 || typeof doc.was === 'number')) {
+ return callback(null, level);
+ } else {
+ return err != null ? callback(err, null) : callback(new Error("Error with profile command"), null);
+ }
+ });
+};
+
+/**
+ * Retrive the current profiling information for MongoDB
+ *
+ * @param {Function} callback Callback function of format `function(err, result) {}`.
+ * @return {null} Returns no result
+ * @api public
+ */
+Admin.prototype.profilingInfo = function(callback) {
+ var self = this;
+ var databaseName = this.db.databaseName;
+ this.db.databaseName = 'admin';
+
+ try {
+ new Cursor(this.db, new Collection(this.db, DbCommand.SYSTEM_PROFILE_COLLECTION), {}).toArray(function(err, items) {
+ return callback(err, items);
+ });
+ } catch (err) {
+ return callback(err, null);
+ }
+
+ self.db.databaseName = databaseName;
+};
+
+/**
+ * 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 Callback function of format `function(err, result) {}`.
+ * @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, result) {
+ // Ensure change before event loop executes
+ return callback != null ? callback(err, result) : 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 Callback function of format `function(err, result) {}`.
+ * @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);
+ } else if(doc.result != null && doc.result.constructor != String) {
+ return callback(new Error("Error with validation data"), null);
+ } else if(doc.result != null && doc.result.match(/exception|corrupt/) != null) {
+ return callback(new Error("Error: invalid collection " + collectionName), null);
+ } else if(doc.valid != null && !doc.valid) {
+ return callback(new Error("Error: invalid collection " + collectionName), null);
+ } else {
+ return callback(null, doc);
+ }
+ });
+};
+
+/**
+ * List the available databases
+ *
+ * @param {Function} callback Callback function of format `function(err, result) {}`.
+ * @return {null} Returns no result
+ * @api public
+ */
+Admin.prototype.listDatabases = function(callback) {
+ // Execute the listAllDatabases command
+ this.db.executeDbAdminCommand({listDatabases:1}, {}, function(err, result) {
+ if(err != null) {
+ callback(err, null);
+ } else {
+ callback(null, result.documents[0]);
+ }
+ });
+}
+
+/**
+ * Get ReplicaSet status
+ *
+ * @param {Function} callback returns the replica set status (if available).
+ * @return {null}
+ * @api public
+ */
+Admin.prototype.replSetGetStatus = function(callback) {
+ var self = this;
+
+ this.command({replSetGetStatus:1}, function(err, result) {
+ if (err == null && result.documents[0].ok == 1) {
+ callback(null, result.documents[0]);
+ } else {
+ if (err) {
+ callback(err, false);
+ } else {
+ callback(self.db.wrap(result.documents[0]), false);
+ }
+ }
+ });
+};
+
+/**
+ * @ignore
+ */
+exports.Admin = Admin;
diff --git a/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/collection.js b/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/collection.js
new file mode 100644
index 0000000..26b5c97
--- /dev/null
+++ b/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/collection.js
@@ -0,0 +1,1517 @@
+/**
+ * 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
+ *
+ * Options
+ * - **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.pkFactory = pkFactory == null
+ ? ObjectID
+ : pkFactory;
+
+ var self = this;
+}
+
+/**
+ * Inserts a single document or a an array of documents into MongoDB.
+ *
+ * Options
+ * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB.
+ * - **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.
+ *
+ * @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 `safe` or `strict` mode
+ * @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 '.'");
+ }
+};
+
+/**
+ * Removes documents specified by `selector` from the db.
+ *
+ * Options
+ * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB.
+ * - **single** {Boolean, default:false}, removes the first document found.
+ *
+ * @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 safe remove
+ * @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);
+
+ // Create a delete command
+ var deleteCommand = new DeleteCommand(
+ this.db
+ , this.db.databaseName + "." + this.collectionName
+ , selector
+ , flags);
+
+ var self = this;
+ var errorOptions = options.safe != null ? options.safe : null;
+ errorOptions = errorOptions == null && this.opts.safe != null ? this.opts.safe : errorOptions;
+ errorOptions = errorOptions == null && this.db.strict != null ? this.db.strict : errorOptions;
+
+ // If we have a write concern set and no callback throw error
+ if(errorOptions && errorOptions['safe'] != false && typeof callback !== 'function') throw new Error("safe cannot be used without a callback");
+ // Execute the command, do not add a callback as it's async
+ if (options && options.safe || this.opts.safe != null || this.db.strict) {
+ // 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(self.db.wrap(error[0]));
+ } else {
+ callback(null, error[0].n);
+ }
+ });
+ } 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.
+ *
+ * @param {String} newName the new name of the collection.
+ * @param {Function} callback the callback accepting the result
+ * @return {null}
+ * @api public
+ */
+Collection.prototype.rename = function rename (newName, callback) {
+ var self = this;
+ // 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), function(err, result) {
+ if(err == null && result.documents[0].ok == 1) {
+ if(callback != null) {
+ // Set current object to point to the new name
+ self.collectionName = newName;
+ // Return the current collection
+ callback(null, self);
+ }
+ } else if(result.documents[0].errmsg != null) {
+ if(callback != null) {
+ err != null ? callback(err, null) : callback(self.db.wrap(result.documents[0]), 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'];
+ }
+
+ // 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;
+ }
+
+ // Pass in options
+ var insertCommand = new InsertCommand(
+ self.db
+ , self.db.databaseName + "." + self.collectionName, true, 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) {
+ doc['_id'] = self.pkFactory.createPk();
+ }
+
+ insertCommand.add(doc);
+ }
+
+ // Collect errorOptions
+ var errorOptions = options.safe != null ? options.safe : null;
+ errorOptions = errorOptions == null && self.opts.safe != null ? self.opts.safe : errorOptions;
+ errorOptions = errorOptions == null && self.db.strict != null ? self.db.strict : errorOptions;
+
+ // If we have a write concern set and no callback throw error
+ if(errorOptions && errorOptions['safe'] != false && typeof callback !== 'function') throw new Error("safe cannot be used without a callback");
+
+ // Default command options
+ var commandOptions = {};
+ // If safe is defined check for error message
+ if(errorOptions && errorOptions != false) {
+ // 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(self.db.wrap(error[0]));
+ } else {
+ callback(null, docs);
+ }
+ });
+ } else {
+ 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
+ * - **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;
+
+ var errorOptions = options.safe != null ? options.safe : false;
+ errorOptions = errorOptions == null && this.opts.safe != null ? this.opts.safe : errorOptions;
+ // Extract the id, if we have one we need to do a update command
+ var id = doc['_id'];
+
+ if(id) {
+ this.update({ _id: id }, doc, { upsert: true, safe: errorOptions }, callback);
+ } else {
+ this.insert(doc, { safe: errorOptions }, 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
+ * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB.
+ * - **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.
+ *
+ * @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 a safe update
+ * @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;
+
+ // 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;
+ }
+
+ var updateCommand = new UpdateCommand(
+ this.db
+ , this.db.databaseName + "." + this.collectionName
+ , selector
+ , document
+ , options);
+
+ var self = this;
+ // Unpack the error options if any
+ var errorOptions = (options && options.safe != null) ? options.safe : null;
+ errorOptions = errorOptions == null && this.opts.safe != null ? this.opts.safe : errorOptions;
+ errorOptions = errorOptions == null && this.db.strict != null ? this.db.strict : errorOptions;
+
+ // If we have a write concern set and no callback throw error
+ if(errorOptions && errorOptions['safe'] != false && typeof callback !== 'function') throw new Error("safe cannot be used without a callback");
+
+ // If we are executing in strict mode or safe both the update and the safe command must happen on the same line
+ if(errorOptions && errorOptions != false) {
+ // 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._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(self.db.wrap(error[0]));
+ } else {
+ // Perform the callback
+ callback(null, error[0].n, error[0]);
+ }
+ });
+ } 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.
+ *
+ * @param {String} key key to run distinct against.
+ * @param {Object} [query] option query to narrow the returned objects.
+ * @param {Function} callback must be provided.
+ * @return {null}
+ * @api public
+ */
+Collection.prototype.distinct = function distinct(key, query, callback) {
+ if ('function' === typeof query) callback = query, query = {};
+
+ var mapCommandHash = {
+ distinct: this.collectionName
+ , query: query
+ , key: key
+ };
+
+ var cmd = DbCommand.createDbSlaveOkCommand(this.db, mapCommandHash);
+
+ this.db._executeQueryCommand(cmd, {read:true}, function (err, result) {
+ if (err) {
+ return callback(err);
+ }
+
+ if (result.documents[0].ok != 1) {
+ return callback(new Error(result.documents[0].errmsg));
+ }
+
+ callback(null, result.documents[0].values);
+ });
+};
+
+/**
+ * Count number of matching documents in the db to a query.
+ *
+ * @param {Object} [query] query to filter by before performing count.
+ * @param {Function} callback must be provided.
+ * @return {null}
+ * @api public
+ */
+Collection.prototype.count = function count (query, callback) {
+ if ('function' === typeof query) callback = query, query = {};
+
+ var final_query = {
+ count: this.collectionName
+ , query: query
+ , fields: null
+ };
+
+ var queryOptions = QueryCommand.OPTS_NO_CURSOR_TIMEOUT;
+ if (this.slaveOk || this.db.slaveOk) {
+ queryOptions |= QueryCommand.OPTS_SLAVE;
+ }
+
+ var queryCommand = new QueryCommand(
+ this.db
+ , this.db.databaseName + ".$cmd"
+ , queryOptions
+ , 0
+ , -1
+ , final_query
+ , null
+ );
+
+ var self = this;
+ this.db._executeQueryCommand(queryCommand, {read:true}, function (err, result) {
+ result = result && result.documents;
+ if(!callback) return;
+
+ if (err) {
+ callback(err);
+ } else if (result[0].ok != 1 || result[0].errmsg) {
+ callback(self.db.wrap(result[0]));
+ } else {
+ callback(null, result[0].n);
+ }
+ });
+};
+
+
+/**
+ * Drop the collection
+ *
+ * @param {Function} [callback] provide a callback to be notified when command finished executing
+ * @return {null}
+ * @api public
+ */
+Collection.prototype.drop = function drop(callback) {
+ this.db.dropCollection(this.collectionName, callback);
+};
+
+/**
+ * Find and update a document.
+ *
+ * Options
+ * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB.
+ * - **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.
+ *
+ * @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] returns results.
+ * @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;
+ }
+
+ // Unpack the error options if any
+ var errorOptions = (options && options.safe != null) ? options.safe : null;
+ errorOptions = errorOptions == null && this.opts.safe != null ? this.opts.safe : errorOptions;
+ errorOptions = errorOptions == null && this.db.strict != null ? this.db.strict : errorOptions;
+
+ // Commands to send
+ var commands = [];
+ // Add the find and modify command
+ commands.push(DbCommand.createDbSlaveOkCommand(this.db, queryObject, options));
+ // If we have safe defined we need to return both call results
+ var chainedCommands = errorOptions != null ? true : false;
+ // Add error command if we have one
+ if(chainedCommands) {
+ commands.push(DbCommand.createGetLastErrorCommand(errorOptions, this.db));
+ }
+
+ // Fire commands and
+ this.db._executeQueryCommand(commands, function(err, result) {
+ result = result && result.documents;
+
+ if(err != null) {
+ callback(err);
+ } else if(result[0].err != null) {
+ callback(self.db.wrap(result[0]), null);
+ } else if(result[0].errmsg != null && !result[0].errmsg.match(eErrorMessages)) {
+ // Workaround due to 1.8.X returning an error on no matching object
+ // while 2.0.X does not not, making 2.0.X behaviour standard
+ callback(self.db.wrap(result[0]), null, result[0]);
+ } else {
+ return callback(null, result[0].value, result[0]);
+ }
+ });
+}
+
+/**
+ * Find and remove a document
+ *
+ * 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] returns results.
+ * @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, 'batchSize' : 1, 'raw' : 1, 'read' : 1
+ , 'returnKey' : 1, 'maxScan' : 1, 'min' : 1, 'max' : 1, 'showDiskLoc' : 1, 'comment' : 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.
+ * - **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.
+ * - **read** {Boolean, default:false}, Tell the query to read from a secondary server.
+ *
+ * @param {Object} query query object to locate the object to modify
+ * @param {Object} [options] additional options during update.
+ * @param {Function} [callback] optional callback for cursor.
+ * @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 = {_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;
+ var o = options;
+
+ // callback for backward compatibility
+ if(callback) {
+ // TODO refactor Cursor args
+ callback(null, new Cursor(this.db, this, selector, fields, o.skip, o.limit
+ , o.sort, o.hint, o.explain, o.snapshot, o.timeout, o.tailable, o.batchSize
+ , o.slaveOk, o.raw, o.read, o.returnKey, o.maxScan, o.min, o.max, o.showDiskLoc, o.comment));
+ } else {
+ return new Cursor(this.db, this, selector, fields, o.skip, o.limit
+ , o.sort, o.hint, o.explain, o.snapshot, o.timeout, o.tailable, o.batchSize
+ , o.slaveOk, o.raw, o.read, o.returnKey, o.maxScan, o.min, o.max, o.showDiskLoc, o.comment);
+ }
+};
+
+/**
+ * Normalizes a `hint` argument.
+ *
+ * @param {String|Object|Array} hint
+ * @return {Object}
+ * @api private
+ */
+var normalizeHintField = function normalizeHintField(hint) {
+ var finalHint = null;
+
+ if (null != hint) {
+ switch (hint.constructor) {
+ case String:
+ finalHint = {};
+ finalHint[hint] = 1;
+ break;
+ case Object:
+ finalHint = {};
+ for (var name in hint) {
+ finalHint[name] = hint[name];
+ }
+ break;
+ case Array:
+ finalHint = {};
+ hint.forEach(function(param) {
+ finalHint[param] = 1;
+ });
+ break;
+ }
+ }
+
+ 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.
+ * - **read** {Boolean, default:false}, Tell the query to read from a secondary server.
+ *
+ * @param {Object} query query object to locate the object to modify
+ * @param {Object} [options] additional options during update.
+ * @param {Function} [callback] optional callback for cursor.
+ * @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.toArray(function(err, items) {
+ if(err != null) return callback(err instanceof Error ? err : self.db.wrap(new Error(err)), null);
+ if(items.length == 1) return callback(null, items[0]);
+ callback(null, null);
+ });
+};
+
+/**
+ * Creates an index on the collection.
+ *
+ * Options
+ * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a
+ * - **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.
+ *
+ * @param {Object} fieldOrSpec fieldOrSpec that defines the index.
+ * @param {Object} [options] additional options during update.
+ * @param {Function} callback for results.
+ * @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 = options.safe != null ? options.safe : null;
+ errorOptions = errorOptions == null && this.opts.safe != null ? this.opts.safe : errorOptions;
+ errorOptions = errorOptions == null && this.db.strict != null ? this.db.strict : errorOptions;
+
+ // If we have a write concern set and no callback throw error
+ if(errorOptions != null && errorOptions != false && (typeof callback !== 'function' && typeof options !== 'function')) throw new Error("safe cannot be used without a 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
+ * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a
+ * - **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.
+ *
+ * @param {Object} fieldOrSpec fieldOrSpec that defines the index.
+ * @param {Object} [options] additional options during update.
+ * @param {Function} callback for results.
+ * @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 = {};
+ }
+
+ // Collect errorOptions
+ var errorOptions = options.safe != null ? options.safe : null;
+ errorOptions = errorOptions == null && this.opts.safe != null ? this.opts.safe : errorOptions;
+ errorOptions = errorOptions == null && this.db.strict != null ? this.db.strict : errorOptions;
+
+ // If we have a write concern set and no callback throw error
+ if(errorOptions != null && errorOptions != false && (typeof callback !== 'function' && typeof options !== 'function')) throw new Error("safe cannot be used without a callback");
+
+ // 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 returns the index information.
+ * @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 returns the results.
+ * @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 returns the results.
+ * @return {null}
+ * @api public
+ */
+Collection.prototype.dropAllIndexes = function dropIndexes (callback) {
+ this.db.dropIndex(this.collectionName, '*', function (err, result) {
+ if(err != null) {
+ callback(err, false);
+ } else if(result.documents[0].errmsg == null) {
+ callback(null, true);
+ } else {
+ callback(new Error(result.documents[0].errmsg), false);
+ }
+ });
+};
+
+/**
+ * Drops all indexes from this collection.
+ *
+ * @deprecated
+ * @param {Function} callback returns the results.
+ * @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 returns the results.
+ * @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, default:*{inline:1}*}, 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.
+ *
+ * @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 returns the result of the map reduce job, (error, results, [stats])
+ * @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) {
+ mapCommandHash[name] = options[name];
+ }
+
+ var self = this;
+ var cmd = DbCommand.createDbSlaveOkCommand(this.db, mapCommandHash);
+
+ this.db._executeQueryCommand(cmd, {read:true}, function (err, result) {
+ if (err) {
+ return callback(err);
+ }
+
+ //
+ if (1 != result.documents[0].ok || result.documents[0].err || result.documents[0].errmsg) {
+ return callback(self.db.wrap(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);
+ }
+
+ // Create a collection object that wraps the result collection
+ self.db.collection(result.documents[0].result, function (err, collection) {
+ // If we wish for no verbosity
+ if(options['verbose'] == null || !options['verbose']) {
+ return callback(err, collection);
+ }
+
+ // 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;
+ // Return stats as third set of values
+ callback(err, collection, stats);
+ });
+ });
+};
+
+/**
+ * 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
+ *
+ * @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 {Function} callback returns the results.
+ * @return {null}
+ * @api public
+ */
+Collection.prototype.group = function group(keys, condition, initial, reduce, finalize, command, 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;
+
+ // 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 = 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) {
+ 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);
+
+ this.db._executeQueryCommand(cmd, {read:true}, function (err, result) {
+ if(err != null) return callback(err);
+
+ var document = result.documents[0];
+ if (null == document.retval) {
+ return callback(new Error("group command failed: " + document.errmsg));
+ }
+
+ callback(null, document.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 returns option results.
+ * @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 returns if collection is capped.
+ * @return {null}
+ * @api public
+ */
+Collection.prototype.isCapped = function isCapped(callback) {
+ this.options(function(err, document) {
+ if(err != null) {
+ callback(err);
+ } else {
+ callback(null, 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 returns if the indexes exist.
+ * @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.
+ *
+ * @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 returns matching documents.
+ * @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'];
+
+ // Execute the command
+ this.db.command(commandObject, callback);
+}
+
+/**
+ * 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.
+ *
+ * @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 returns matching documents.
+ * @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'];
+
+ // Execute the command
+ this.db.command(commandObject, callback);
+}
+
+/**
+ * Retrieve all the indexes on the collection.
+ *
+ * @param {Function} callback returns index information.
+ * @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
+ *
+ * @param {Array|Objects} pipline a pipleline containing all the object for the execution.
+ * @param {Function} callback returns matching documents.
+ * @return {null}
+ * @api public
+ */
+Collection.prototype.aggregate = function(pipeline, callback) {
+ var args = Array.prototype.slice.call(arguments, 0);
+ callback = args.pop();
+ var self = this;
+
+ // Check if we have more than one argument then just make the pipeline
+ // the remaining arguments
+ if(args.length > 1) {
+ pipeline = args;
+ }
+
+ // Build the command
+ var command = { aggregate : this.collectionName, pipeline : pipeline};
+ // Execute the command
+ this.db.command(command, function(err, result) {
+ if(err) {
+ callback(err);
+ } else if(result['err'] || result['errmsg']) {
+ callback(self.db.wrap(result));
+ } else {
+ callback(null, result.result);
+ }
+ });
+}
+
+/**
+ * Get all the collection statistics.
+ *
+ * Options
+ * - **scale** {Number}, divide the returned sizes by scale value.
+ *
+ * @param {Objects} [options] options for the map reduce job.
+ * @param {Function} callback returns statistical information for the collection.
+ * @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'];
+
+ // Execute the command
+ this.db.command(commandObject, callback);
+}
+
+/**
+ * @ignore
+ */
+Object.defineProperty(Collection.prototype, "hint", {
+ enumerable: true
+ , get: function () {
+ return this.internalHint;
+ }
+ , set: function (v) {
+ this.internalHint = normalizeHintField(v);
+ }
+});
+
+/**
+ * Expose.
+ */
+exports.Collection = Collection;
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/commands/base_command.js b/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/commands/base_command.js
new file mode 100644
index 0000000..6e531d3
--- /dev/null
+++ b/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/commands/base_command.js
@@ -0,0 +1,27 @@
+/**
+ Base object used for common functionality
+**/
+var BaseCommand = exports.BaseCommand = function() {
+};
+
+var id = 1;
+BaseCommand.prototype.getRequestId = function() {
+ if (!this.requestId) this.requestId = id++;
+ return this.requestId;
+};
+
+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/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/commands/db_command.js b/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/commands/db_command.js
new file mode 100644
index 0000000..3d69051
--- /dev/null
+++ b/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/commands/db_command.js
@@ -0,0 +1,207 @@
+var QueryCommand = require('./query_command').QueryCommand,
+ InsertCommand = require('./insert_command').InsertCommand,
+ inherits = require('util').inherits,
+ 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;
+
+ // 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";
+
+// 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) {
+ 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) {
+ // 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, db.databaseName + "." + 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) {
+ var renameCollection = db.databaseName + "." + fromCollectionName;
+ var toCollection = db.databaseName + "." + toCollectionName;
+ return new DbCommand(db, "admin." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, {'renameCollection':renameCollection, 'to':toCollection}, 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]
+ }
+ }
+
+ // 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 (fieldOrSpec.constructor === String) { // 'type'
+ indexes.push(fieldOrSpec + '_' + 1);
+ fieldHash[fieldOrSpec] = 1;
+ } else if (fieldOrSpec.constructor === Array) { // [{location:'2d'}, ...]
+ fieldOrSpec.forEach(function(f) {
+ if (f.constructor === String) { // [{location:'2d'}, 'type']
+ indexes.push(f + '_' + 1);
+ fieldHash[f] = 1;
+ } else if (f.constructor === Array) { // [['location', '2d'],['type', 1]]
+ indexes.push(f[0] + '_' + (f[1] || 1));
+ fieldHash[f[0]] = f[1] || 1;
+ } else if (f.constructor === Object) { // [{location:'2d'}, {type:1}]
+ keys = Object.keys(f);
+ keys.forEach(function(k) {
+ indexes.push(k + '_' + f[k]);
+ fieldHash[k] = f[k];
+ });
+ } else {
+ // undefined
+ }
+ });
+ } else if (fieldOrSpec.constructor === Object) { // {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 = indexes.join("_");
+ // Build the selector
+ 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);
+ // Add all the fields to the selector
+ for(var i = 0; i < keys.length; i++) {
+ selector[keys[i]] = options[keys[i]];
+ }
+
+ // If we don't have the unique property set on the selector
+ if(selector['unique'] == null) selector['unique'] = finalUnique;
+ // Create the insert command for the index and return the document
+ return new InsertCommand(db, db.databaseName + "." + DbCommand.SYSTEM_INDEX_COLLECTION, false).add(selector);
+};
+
+DbCommand.logoutCommand = function(db, command_hash) {
+ return new DbCommand(db, db.databaseName + "." + 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) {
+ return new DbCommand(db, db.databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, 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.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);
+};
\ No newline at end of file
diff --git a/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/commands/delete_command.js b/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/commands/delete_command.js
new file mode 100644
index 0000000..e6ae20a
--- /dev/null
+++ b/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/commands/delete_command.js
@@ -0,0 +1,114 @@
+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() {
+ // 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);
+ // 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/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/commands/get_more_command.js b/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/commands/get_more_command.js
new file mode 100644
index 0000000..d3aac02
--- /dev/null
+++ b/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/commands/get_more_command.js
@@ -0,0 +1,83 @@
+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() {
+ // 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/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/commands/insert_command.js b/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/commands/insert_command.js
new file mode 100644
index 0000000..3036a02
--- /dev/null
+++ b/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/commands/insert_command.js
@@ -0,0 +1,141 @@
+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;
+ }
+
+ // 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() {
+ // 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);
+ }
+ }
+
+ // 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/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/commands/kill_cursor_command.js b/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/commands/kill_cursor_command.js
new file mode 100644
index 0000000..d8ccb0c
--- /dev/null
+++ b/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/commands/kill_cursor_command.js
@@ -0,0 +1,98 @@
+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/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/commands/query_command.js b/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/commands/query_command.js
new file mode 100644
index 0000000..e417968
--- /dev/null
+++ b/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/commands/query_command.js
@@ -0,0 +1,210 @@
+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;
+ this.query = query;
+ this.returnFieldSelector = returnFieldSelector;
+ this.db = db;
+
+ // 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;
+
+/*
+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() {
+ 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;
+ }
+
+ // 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;
\ No newline at end of file
diff --git a/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/commands/update_command.js b/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/commands/update_command.js
new file mode 100644
index 0000000..9829dea
--- /dev/null
+++ b/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/commands/update_command.js
@@ -0,0 +1,174 @@
+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;
+
+ // 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() {
+ // 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);
+
+ // 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, 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;
+};
+
+// Constants
+UpdateCommand.DB_UPSERT = 0;
+UpdateCommand.DB_MULTI_UPDATE = 1;
\ No newline at end of file
diff --git a/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/connection/connection.js b/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/connection/connection.js
new file mode 100644
index 0000000..176101b
--- /dev/null
+++ b/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/connection/connection.js
@@ -0,0 +1,414 @@
+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};
+ // Id for the connection
+ this.id = id;
+ // State of the connection
+ this.connected = false;
+
+ //
+ // Connection parsing state
+ //
+ this.maxBsonSize = socketOptions.maxBsonSize ? socketOptions.maxBsonSize : Connection.DEFAULT_MAX_BSON_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);
+}
+
+// Set max bson size
+Connection.DEFAULT_MAX_BSON_SIZE = 1024 * 1024 * 4;
+
+// Inherit event emitter so we can emit stuff wohoo
+inherits(Connection, EventEmitter);
+
+Connection.prototype.start = function() {
+ // If we have a normal connection
+ if(this.socketOptions.ssl) {
+ // Create a new stream
+ this.connection = new net.Socket();
+ // Set options on the socket
+ this.connection.setTimeout(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 pair for tls with server, accept self-signed certificates as well
+ var pair = this.pair = tls.createSecurePair(false);
+ // Set up encrypted streams
+ this.pair.encrypted.pipe(this.connection);
+ this.connection.pipe(this.pair.encrypted);
+
+ // Setup clearText stream
+ this.writeSteam = this.pair.cleartext;
+ // Add all handlers to the socket to manage it
+ this.pair.on("secure", connectHandler(this));
+ this.pair.cleartext.on("data", createDataHandler(this));
+ // Add handlers
+ this.connection.on("error", errorHandler(this));
+ // this.connection.on("connect", connectHandler(this));
+ this.connection.on("end", endHandler(this));
+ this.connection.on("timeout", timeoutHandler(this));
+ this.connection.on("drain", drainHandler(this));
+ this.writeSteam.on("close", closeHandler(this));
+ // Start socket
+ this.connection.connect(this.socketOptions.port, this.socketOptions.host);
+ } else {
+ // Create new connection instance
+ this.connection = net.createConnection(this.socketOptions.port, this.socketOptions.host);
+ // Set options on the socket
+ this.connection.setTimeout(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++) {
+ var binaryCommand = command[i].toBinary()
+ if(binaryCommand.length > this.maxBsonSize) return callback(new Error("Document exceeds maximal allowed bson size of " + this.maxBsonSize + " bytes"));
+ if(this.logger != null && this.logger.doDebug) this.logger.debug("writing command to mongodb", binaryCommand);
+ var r = this.writeSteam.write(binaryCommand);
+ }
+ } else {
+ var binaryCommand = command.toBinary()
+ if(binaryCommand.length > this.maxBsonSize) return callback(new Error("Document exceeds maximal allowed bson size of " + this.maxBsonSize + " bytes"));
+ if(this.logger != null && this.logger.doDebug) this.logger.debug("writing command to mongodb", binaryCommand);
+ var r = this.writeSteam.write(binaryCommand);
+ }
+ } 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();
+}
+
+// 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() {
+ // Set connected
+ self.connected = true;
+ // 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: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() {
+ 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) {
+ // 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/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/connection/connection_pool.js b/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/connection/connection_pool.js
new file mode 100644
index 0000000..ee62d3f
--- /dev/null
+++ b/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/connection/connection_pool.js
@@ -0,0 +1,250 @@
+var utils = require('./connection_utils'),
+ inherits = require('util').inherits,
+ net = require('net'),
+ EventEmitter = require('events').EventEmitter,
+ inherits = require('util').inherits,
+ MongoReply = require("../responses/mongo_reply").MongoReply,
+ Connection = require("./connection").Connection;
+
+var ConnectionPool = exports.ConnectionPool = function(host, port, poolSize, bson, socketOptions) {
+ if(typeof host !== 'string' || typeof port !== 'number') throw "host and port must be specified [" + host + ":" + port + "]";
+ // 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.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;
+
+ // 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;
+}
+
+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;
+ }
+}
+
+// Start a function
+var _connect = function(_self) {
+ return new function() {
+ var connectionStatus = _self._poolState;
+ // 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) {
+ // We need to open another connection, make sure it's in the next
+ // tick so we don't get a cascade of errors
+ process.nextTick(function() {
+ _connect(_self);
+ });
+ }
+ });
+
+ var numberOfErrors = 0
+
+ // Error handler
+ connection.on("error", function(err, connection) {
+ numberOfErrors++;
+ // If we are already disconnected ignore the event
+ if(connectionStatus != 'disconnected' && _self.listeners("error").length > 0) {
+ _self.emit("error", err);
+ }
+
+ // Set disconnected
+ connectionStatus = 'disconnected';
+ // Set disconnected
+ _self._poolState = 'disconnected';
+ // Stop
+ _self.stop();
+ });
+
+ // Close handler
+ connection.on("close", function() {
+ // If we are already disconnected ignore the event
+ if(connectionStatus !== 'disconnected' && _self.listeners("close").length > 0) {
+ _self.emit("close");
+ }
+
+ // Set disconnected
+ connectionStatus = 'disconnected';
+ // 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(connectionStatus !== 'disconnected' && _self.listeners("timeout").length > 0) {
+ _self.emit("timeout", err);
+ }
+
+ // Set disconnected
+ connectionStatus = 'disconnected';
+ // Set disconnected
+ _self._poolState = 'disconnected';
+ // Stop
+ _self.stop();
+ });
+
+ // Parse error, needs a complete shutdown of the pool
+ connection.on("parseError", function() {
+ // If we are already disconnected ignore the event
+ if(connectionStatus !== 'disconnected' && _self.listeners("parseError").length > 0) {
+ _self.emit("parseError", new Error("parseError occured"));
+ }
+
+ // Set disconnected
+ connectionStatus = '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';
+}
+
+// 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/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/connection/connection_utils.js b/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/connection/connection_utils.js
new file mode 100644
index 0000000..5910924
--- /dev/null
+++ b/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/connection/connection_utils.js
@@ -0,0 +1,23 @@
+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/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/connection/repl_set.js b/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/connection/repl_set.js
new file mode 100644
index 0000000..1985b0f
--- /dev/null
+++ b/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/connection/repl_set.js
@@ -0,0 +1,1230 @@
+var Connection = require('./connection').Connection,
+ DbCommand = require('../commands/db_command').DbCommand,
+ MongoReply = require('../responses/mongo_reply').MongoReply,
+ debug = require('util').debug,
+ EventEmitter = require('events').EventEmitter,
+ inherits = require('util').inherits,
+ inspect = require('util').inspect,
+ Server = require('./server').Server,
+ PingStrategy = require('./strategies/ping_strategy').PingStrategy,
+ StatisticsStrategy = require('./strategies/statistics_strategy').StatisticsStrategy;
+
+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;
+
+/**
+ * ReplSet constructor provides replicaset functionality
+ *
+ * Options
+ * - **ha** {Boolean, default:false}, 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.
+ * - **readPreference** {String}, the prefered read preference (Server.READ_PRIMARY, Server.READ_SECONDARY, Server.READ_SECONDARY_ONLY).
+ * - **read_secondary** {Boolean, deprecated}, allow reads from secondary.
+ * - **strategy** {String, default:null}, selection strategy for reads choose between (ping and statistical, default is round-robin)
+ *
+ * @class Represents a Replicaset Configuration
+ * @param {Array} list of server objects participating in the replicaset.
+ * @param {Object} [options] additional options for the collection.
+ */
+var ReplSet = exports.ReplSet = function(servers, options) {
+ // Set up basic
+ if(!(this instanceof ReplSet))
+ return new ReplSet(servers, options);
+
+ // Set up event emitter
+ EventEmitter.call(this);
+
+ var self = this;
+ // Contains the master server entry
+ this.options = options == null ? {} : options;
+ this.reconnectWait = this.options["reconnectWait"] != null ? this.options["reconnectWait"] : 1000;
+ this.retries = this.options["retries"] != null ? this.options["retries"] : 30;
+ this.replicaSet = this.options["rs_name"];
+
+ // Are we allowing reads from secondaries ?
+ this.readSecondary = this.options["read_secondary"];
+ this.slaveOk = true;
+ this.closedConnectionCount = 0;
+ this._used = false;
+
+ // Default poolSize for new server instances
+ this.poolSize = this.options.poolSize == null ? 1 : this.options.poolSize;
+ this._currentServerChoice = 0;
+
+ // Set up ssl connections
+ this.ssl = this.options.ssl == null ? false : this.options.ssl;
+
+ // Just keeps list of events we allow
+ this.eventHandlers = {error:[], parseError:[], poolReady:[], message:[], close:[], timeout:[]};
+ // Internal state of server connection
+ this._serverState = 'disconnected';
+ // Read preference
+ this._readPreference = null;
+ // Number of initalized severs
+ this._numberOfServersLeftToInitialize = 0;
+ // Do we record server stats or not
+ this.recordQueryStats = false;
+
+ // Get the readPreference
+ var readPreference = this.options['readPreference'];
+ // Read preference setting
+ if(readPreference != null) {
+ if(readPreference != Server.READ_PRIMARY && readPreference != Server.READ_SECONDARY_ONLY
+ && readPreference != Server.READ_SECONDARY) {
+ throw new Error("Illegal readPreference mode specified, " + readPreference);
+ }
+
+ // Set read Preference
+ this._readPreference = readPreference;
+ } else {
+ this._readPreference = null;
+ }
+
+ // Strategy for picking a secondary
+ // this.strategy = this.options['strategy'] == null ? 'statistical' : this.options['strategy'];
+ this.strategy = this.options['strategy'];
+ // Make sure strategy is one of the two allowed
+ if(this.strategy != null && (this.strategy != 'ping' && this.strategy != 'statistical')) throw new Error("Only ping or statistical strategies allowed");
+ // Let's set up our strategy object for picking secodaries
+ if(this.strategy == 'ping') {
+ // Create a new instance
+ this.strategyInstance = new PingStrategy(this);
+ } else if(this.strategy == 'statistical') {
+ // Set strategy as statistical
+ this.strategyInstance = new StatisticsStrategy(this);
+ // Add enable query information
+ this.enableRecordQueryStats(true);
+ }
+
+ // Set default connection pool options
+ this.socketOptions = this.options.socketOptions != null ? this.options.socketOptions : {};
+
+ // 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.debug == 'function')
+ ? this.options.logger : {error:function(message, object) {}, log:function(message, object) {}, debug:function(message, object) {}};
+
+ // Ensure all the instances are of type server and auto_reconnect is false
+ if(!Array.isArray(servers) || servers.length == 0) {
+ throw Error("The parameter must be an array of servers and contain at least one server");
+ } else if(Array.isArray(servers) || servers.length > 0) {
+ var count = 0;
+ servers.forEach(function(server) {
+ if(server instanceof Server) count = count + 1;
+ // Ensure no server has reconnect on
+ server.options.auto_reconnect = false;
+ });
+
+ if(count < servers.length) {
+ throw Error("All server entries must be of type Server");
+ } else {
+ this.servers = servers;
+ }
+ }
+
+ // Enabled ha
+ this.haEnabled = this.options['ha'] == null ? false : this.options['ha'];
+ // How often are we checking for new servers in the replicaset
+ this.replicasetStatusCheckInterval = this.options['haInterval'] == null ? 2000 : this.options['haInterval'];
+ this._replicasetTimeoutId = null;
+};
+
+/**
+ * @ignore
+ */
+inherits(ReplSet, EventEmitter);
+
+/**
+ * @ignore
+ */
+// Allow setting the read preference at the replicaset level
+ReplSet.prototype.setReadPreference = function(preference) {
+ // Set read preference
+ this._readPreference = preference;
+ // Ensure slaveOk is correct for secodnaries read preference and tags
+ if((this._readPreference == Server.READ_SECONDARY || this._readPreference == Server.READ_SECONDARY_ONLY)
+ || (this._readPreference != null && typeof this._readPreference == 'object')) {
+ this.slaveOk = true;
+ }
+}
+
+/**
+ * @ignore
+ */
+// Return the used state
+ReplSet.prototype._isUsed = function() {
+ return this._used;
+}
+
+/**
+ * @ignore
+ */
+ReplSet.prototype.setTarget = function(target) {
+ this.target = target;
+};
+
+/**
+ * @ignore
+ */
+ReplSet.prototype.isConnected = function() {
+ // Return the state of the replicaset server
+ return this.primary != null && this._state.master != null && this._state.master.isConnected();
+}
+
+/**
+ * @ignore
+ */
+Server.prototype.isSetMember = function() {
+ return false;
+}
+
+/**
+ * @ignore
+ */
+ReplSet.prototype.isPrimary = function(config) {
+ return this.readSecondary && this.secondaries.length > 0 ? false : true;
+}
+
+/**
+ * @ignore
+ */
+ReplSet.prototype.isReadPrimary = ReplSet.prototype.isPrimary;
+
+/**
+ * @ignore
+ */
+// Clean up dead connections
+var cleanupConnections = ReplSet.cleanupConnections = function(connections, addresses, byTags) {
+ // Ensure we don't have entries in our set with dead connections
+ var keys = Object.keys(connections);
+ for(var i = 0; i < keys.length; i++) {
+ var server = connections[keys[i]];
+ // If it's not connected remove it from the list
+ if(!server.isConnected()) {
+ // Remove from connections and addresses
+ delete connections[keys[i]];
+ delete addresses[keys[i]];
+ // Clean up tags if needed
+ if(server.tags != null && typeof server.tags === 'object') {
+ cleanupTags(server, byTags);
+ }
+ }
+ }
+}
+
+/**
+ * @ignore
+ */
+var cleanupTags = ReplSet._cleanupTags = function(server, byTags) {
+ var serverTagKeys = Object.keys(server.tags);
+ // Iterate over all server tags and remove any instances for that tag that matches the current
+ // server
+ for(var i = 0; i < serverTagKeys.length; i++) {
+ // Fetch the value for the tag key
+ var value = server.tags[serverTagKeys[i]];
+
+ // If we got an instance of the server
+ if(byTags[serverTagKeys[i]] != null
+ && byTags[serverTagKeys[i]][value] != null
+ && Array.isArray(byTags[serverTagKeys[i]][value])) {
+ // List of clean servers
+ var cleanInstances = [];
+ // We got instances for the particular tag set
+ var instances = byTags[serverTagKeys[i]][value];
+ for(var j = 0, jlen = instances.length; j < jlen; j++) {
+ var serverInstance = instances[j];
+ // If we did not find an instance add it to the clean instances
+ if((serverInstance.host + ":" + serverInstance.port) !== (server.host + ":" + server.port)) {
+ cleanInstances.push(serverInstance);
+ }
+ }
+
+ // Update the byTags list
+ byTags[serverTagKeys[i]][value] = cleanInstances;
+ }
+ }
+}
+
+/**
+ * @ignore
+ */
+ReplSet.prototype.allServerInstances = function() {
+ var self = this;
+ // 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]]);
+ }
+
+ // Arbiter keys
+ var keys = Object.keys(self._state.arbiters);
+ // Add all arbiters
+ for(var i = 0; i < keys.length; i++) {
+ allServers.push(self._state.arbiters[keys[i]]);
+ }
+
+ // Passive keys
+ var keys = Object.keys(self._state.passives);
+ // Add all arbiters
+ for(var i = 0; i < keys.length; i++) {
+ allServers.push(self._state.passives[keys[i]]);
+ }
+
+ // Return complete list of all servers
+ return allServers;
+}
+
+/**
+ * @ignore
+ */
+// Ensure no callback is left hanging when we have an error
+var __executeAllCallbacksWithError = function(dbInstance, error) {
+ var keys = Object.keys(dbInstance._callBackStore._notReplied);
+ // Iterate over all callbacks
+ for(var i = 0; i < keys.length; i++) {
+ // Delete info object
+ delete dbInstance._callBackStore._notReplied[keys[i]];
+ // Emit the error
+ dbInstance._callBackStore.emit(keys[i], error);
+ }
+}
+
+/**
+ * @ignore
+ */
+ReplSet.prototype.connect = function(parent, options, callback) {
+ var self = this;
+ var dateStamp = new Date().getTime();
+ if('function' === typeof options) callback = options, options = {};
+ if(options == null) options = {};
+ if(!('function' === typeof callback)) callback = null;
+
+ // Keep reference to parent
+ this.db = parent;
+ // Set server state to connecting
+ this._serverState = 'connecting';
+ // Reference to the instance
+ var replSetSelf = this;
+ var serverConnections = this.servers;
+ // Ensure parent can do a slave query if it's set
+ parent.slaveOk = this.slaveOk ? this.slaveOk : parent.slaveOk;
+ // Number of total servers that need to initialized (known servers)
+ this._numberOfServersLeftToInitialize = serverConnections.length;
+
+ // Clean up state
+ replSetSelf._state = {'master':null, 'secondaries':{}, 'arbiters':{}, 'passives':{}, 'errors':{}, 'addresses':{}, 'byTags':{}, 'setName':null, 'errorMessages':[], 'members':[]};
+
+ // Create a connection handler
+ // self.connectionHandler = null != self.connectionHandler ? self.connectionHandler : function(instanceServer) {
+ self.connectionHandler = function(instanceServer) {
+ return function(err, result) {
+ // Remove a server from the list of intialized servers we need to perform
+ self._numberOfServersLeftToInitialize = self._numberOfServersLeftToInitialize - 1;
+
+ if(err != null) {
+ self._state.errors[instanceServer.name] = instanceServer;
+ }
+
+ // Add enable query information
+ instanceServer.enableRecordQueryStats(replSetSelf.recordQueryStats);
+
+ if(err == null && result.documents[0].hosts != null) {
+ // Fetch the isMaster command result
+ var document = result.documents[0];
+ // Break out the results
+ var setName = document.setName;
+ var isMaster = document.ismaster;
+ var secondary = document.secondary;
+ var passive = document.passive;
+ var arbiterOnly = document.arbiterOnly;
+ var hosts = Array.isArray(document.hosts) ? document.hosts : [];
+ var arbiters = Array.isArray(document.arbiters) ? document.arbiters : [];
+ var passives = Array.isArray(document.passives) ? document.passives : [];
+ var tags = document.tags ? document.tags : {};
+ var primary = document.primary;
+
+ // Ensure we are keying on the same name for lookups as mongodb might return
+ // dns name and the driver is using ip's
+ // Rename the connection so we are keying on the name used by mongod
+ var userProvidedServerString = instanceServer.host + ":" + instanceServer.port;
+ var me = document.me || userProvidedServerString;
+
+ // If we have user provided entries already, switch them to avoid additional
+ // open connections
+ if(replSetSelf._state['addresses'][userProvidedServerString]) {
+ // Fetch server
+ var server = replSetSelf._state['addresses'][userProvidedServerString];
+ // Remove entry
+ delete replSetSelf._state['addresses'][userProvidedServerString];
+ // Remove other entries
+ if(replSetSelf._state['secondaries'][userProvidedServerString]) {
+ delete replSetSelf._state['secondaries'][userProvidedServerString];
+ replSetSelf._state['secondaries'][me] = server;
+ } else if(replSetSelf._state['passives'][userProvidedServerString]) {
+ delete replSetSelf._state['passives'][userProvidedServerString];
+ replSetSelf._state['passives'][me] = server;
+ } else if(replSetSelf._state['arbiters'][userProvidedServerString]) {
+ delete replSetSelf._state['arbiters'][userProvidedServerString];
+ replSetSelf._state['arbiters'][me] = server;
+ }
+
+ // Set name of the server
+ server.name = me;
+ // Add the existing one to the replicaset list of addresses
+ replSetSelf._state['addresses'][me] = server;
+ } else {
+ instanceServer.name = me;
+ }
+
+ // Only add server to our internal list if it's a master, secondary or arbiter
+ if(isMaster == true || secondary == true || arbiterOnly == true) {
+ // Handle a closed connection
+ replSetSelf.closeHandler = function(err, server) {
+ var closeServers = function() {
+ // Set the state to disconnected
+ parent._state = 'disconnected';
+ // Shut down the replicaset for now and Fire off all the callbacks sitting with no reply
+ if(replSetSelf._serverState == 'connected') {
+ // Close the replicaset
+ replSetSelf.close(function() {
+ __executeAllCallbacksWithError(parent, err);
+ // Ensure single callback only
+ if(callback != null) {
+ // Single callback only
+ var internalCallback = callback;
+ callback = null;
+ // Return the error
+ internalCallback(err, null);
+ } else {
+ // If the parent has listeners trigger an event
+ if(parent.listeners("close").length > 0) {
+ parent.emit("close", err);
+ }
+ }
+ });
+ }
+ }
+
+ // Check if this is the primary server, then disconnect otherwise keep going
+ if(replSetSelf._state.master != null) {
+ var primaryAddress = replSetSelf._state.master.host + ":" + replSetSelf._state.master.port;
+ // var errorServerAddress = server.host + ":" + server.port;
+ var errorServerAddress = server.name;
+
+ // Only shut down the set if we have a primary server error
+ if(primaryAddress == errorServerAddress) {
+ closeServers();
+ } else {
+ // Remove from the list of servers
+ delete replSetSelf._state.addresses[errorServerAddress];
+ // Locate one of the lists and remove
+ if(replSetSelf._state.secondaries[errorServerAddress] != null) {
+ delete replSetSelf._state.secondaries[errorServerAddress];
+ } else if(replSetSelf._state.arbiters[errorServerAddress] != null) {
+ delete replSetSelf._state.arbiters[errorServerAddress];
+ } else if(replSetSelf._state.passives[errorServerAddress] != null) {
+ delete replSetSelf._state.passives[errorServerAddress];
+ }
+
+ // Check if we are reading from Secondary only
+ if(replSetSelf._readPreference == Server.READ_SECONDARY_ONLY && Object.keys(replSetSelf._state.secondaries).length == 0) {
+ closeServers();
+ }
+ }
+ } else {
+ closeServers();
+ }
+ }
+
+ // Handle a connection timeout
+ replSetSelf.timeoutHandler = function(err, server) {
+ var closeServers = function() {
+ // Set the state to disconnected
+ parent._state = 'disconnected';
+ // Shut down the replicaset for now and Fire off all the callbacks sitting with no reply
+ if(replSetSelf._serverState == 'connected') {
+ // Close the replicaset
+ replSetSelf.close(function() {
+ __executeAllCallbacksWithError(parent, err);
+ // Ensure single callback only
+ if(callback != null) {
+ // Single callback only
+ var internalCallback = callback;
+ callback = null;
+ // Return the error
+ internalCallback(new Error("connection timed out"), null);
+ } else {
+ // If the parent has listeners trigger an event
+ if(parent.listeners("error").length > 0) {
+ parent.emit("timeout", new Error("connection timed out"));
+ }
+ }
+ });
+ }
+ }
+
+ // Check if this is the primary server, then disconnect otherwise keep going
+ if(replSetSelf._state.master != null) {
+ var primaryAddress = replSetSelf._state.master.host + ":" + replSetSelf._state.master.port;
+ var errorServerAddress = server.name;
+
+ // Only shut down the set if we have a primary server error
+ if(primaryAddress == errorServerAddress) {
+ closeServers();
+ } else {
+ // Remove from the list of servers
+ delete replSetSelf._state.addresses[errorServerAddress];
+ // Locate one of the lists and remove
+ if(replSetSelf._state.secondaries[errorServerAddress] != null) {
+ delete replSetSelf._state.secondaries[errorServerAddress];
+ } else if(replSetSelf._state.arbiters[errorServerAddress] != null) {
+ delete replSetSelf._state.arbiters[errorServerAddress];
+ } else if(replSetSelf._state.passives[errorServerAddress] != null) {
+ delete replSetSelf._state.passives[errorServerAddress];
+ }
+
+ // Check if we are reading from Secondary only
+ if(replSetSelf._readPreference == Server.READ_SECONDARY_ONLY && Object.keys(replSetSelf._state.secondaries).length == 0) {
+ closeServers();
+ }
+ }
+ } else {
+ closeServers();
+ }
+ }
+
+ // Handle an error
+ replSetSelf.errorHandler = function(err, server) {
+ var closeServers = function() {
+ // Set the state to disconnected
+ parent._state = 'disconnected';
+ // Shut down the replicaset for now and Fire off all the callbacks sitting with no reply
+ if(replSetSelf._serverState == 'connected') {
+ // Close the replicaset
+ replSetSelf.close(function() {
+ __executeAllCallbacksWithError(parent, err);
+ // Ensure single callback only
+ if(callback != null) {
+ // Single callback only
+ var internalCallback = callback;
+ callback = null;
+ // Return the error
+ internalCallback(err, null);
+ } else {
+ // If the parent has listeners trigger an event
+ if(parent.listeners("error").length > 0) {
+ parent.emit("error", err);
+ }
+ }
+ });
+ }
+ }
+
+ // Check if this is the primary server, then disconnect otherwise keep going
+ if(replSetSelf._state.master != null) {
+ var primaryAddress = replSetSelf._state.master.host + ":" + replSetSelf._state.master.port;
+ var errorServerAddress = server.name;
+ // var errorServerAddress = server.host + ":" + server.port;
+
+ // Only shut down the set if we have a primary server error
+ if(primaryAddress == errorServerAddress) {
+ closeServers();
+ } else {
+ // Remove from the list of servers
+ delete replSetSelf._state.addresses[errorServerAddress];
+ // Locate one of the lists and remove
+ if(replSetSelf._state.secondaries[errorServerAddress] != null) {
+ delete replSetSelf._state.secondaries[errorServerAddress];
+ } else if(replSetSelf._state.arbiters[errorServerAddress] != null) {
+ delete replSetSelf._state.arbiters[errorServerAddress];
+ } else if(replSetSelf._state.passives[errorServerAddress] != null) {
+ delete replSetSelf._state.passives[errorServerAddress];
+ }
+
+ // Check if we are reading from Secondary only
+ if(replSetSelf._readPreference == Server.READ_SECONDARY_ONLY && Object.keys(replSetSelf._state.secondaries).length == 0) {
+ closeServers();
+ }
+ }
+ } else {
+ closeServers();
+ }
+ }
+
+ // Ensure we don't have duplicate handlers
+ instanceServer.removeAllListeners("close");
+ instanceServer.removeAllListeners("error");
+ instanceServer.removeAllListeners("timeout");
+
+ // Add error handler to the instance of the server
+ instanceServer.on("close", replSetSelf.closeHandler);
+ // Add error handler to the instance of the server
+ instanceServer.on("error", replSetSelf.errorHandler);
+ // instanceServer.on("timeout", errorHandler);
+ instanceServer.on("timeout", replSetSelf.timeoutHandler);
+ // Add tag info
+ instanceServer.tags = tags;
+
+ // For each tag in tags let's add the instance Server to the list for that tag
+ if(tags != null && typeof tags === 'object') {
+ var tagKeys = Object.keys(tags);
+ // For each tag file in the server add it to byTags
+ for(var i = 0; i < tagKeys.length; i++) {
+ var value = tags[tagKeys[i]];
+ // Check if we have a top level tag object
+ if(replSetSelf._state.byTags[tagKeys[i]] == null) replSetSelf._state.byTags[tagKeys[i]] = {};
+ // For the value check if we have an array of server instances
+ if(!Array.isArray(replSetSelf._state.byTags[tagKeys[i]][value])) replSetSelf._state.byTags[tagKeys[i]][value] = [];
+ // Check that the instance is not already registered there
+ var valueArray = replSetSelf._state.byTags[tagKeys[i]][value];
+ var found = false;
+
+ // Iterate over all values
+ for(var j = 0; j < valueArray.length; j++) {
+ if(valueArray[j].host == instanceServer.host && valueArray[j].port == instanceServer.port) {
+ found = true;
+ break;
+ }
+ }
+
+ // If it was not found push the instance server to the list
+ if(!found) valueArray.push(instanceServer);
+ }
+ }
+
+ // Remove from error list
+ delete replSetSelf._state.errors[me];
+
+ // Add our server to the list of finished servers
+ replSetSelf._state.addresses[me] = instanceServer;
+
+ // Assign the set name
+ if(replSetSelf.replicaSet == null) {
+ replSetSelf._state.setName = setName;
+ } else if(replSetSelf.replicaSet != setName && replSetSelf._serverState != 'disconnected') {
+ replSetSelf._state.errorMessages.push(new Error("configured mongodb replicaset does not match provided replicaset [" + setName + "] != [" + replSetSelf.replicaSet + "]"));
+ // Set done
+ replSetSelf._serverState = 'disconnected';
+ // ensure no callbacks get called twice
+ var internalCallback = callback;
+ callback = null;
+ // Return error message ignoring rest of calls
+ return internalCallback(replSetSelf._state.errorMessages[0], parent);
+ }
+
+ // Let's add the server to our list of server types
+ if(secondary == true && (passive == false || passive == null)) {
+ replSetSelf._state.secondaries[me] = instanceServer;
+ } else if(arbiterOnly == true) {
+ replSetSelf._state.arbiters[me] = instanceServer;
+ } else if(secondary == true && passive == true) {
+ replSetSelf._state.passives[me] = instanceServer;
+ } else if(isMaster == true) {
+ replSetSelf._state.master = instanceServer;
+ } else if(isMaster == false && primary != null && replSetSelf._state.addresses[primary]) {
+ replSetSelf._state.master = replSetSelf._state.addresses[primary];
+ }
+
+ // Let's go throught all the "possible" servers in the replicaset
+ var candidateServers = hosts.concat(arbiters).concat(passives);
+
+ // If we have new servers let's add them
+ for(var i = 0; i < candidateServers.length; i++) {
+ // Fetch the server string
+ var candidateServerString = candidateServers[i];
+ // Add the server if it's not defined and not already errored out
+ if(null == replSetSelf._state.addresses[candidateServerString]
+ && null == replSetSelf._state.errors[candidateServerString]) {
+ // Split the server string
+ var parts = candidateServerString.split(/:/);
+ if(parts.length == 1) {
+ parts = [parts[0], Connection.DEFAULT_PORT];
+ }
+
+ // Default empty socket options object
+ var socketOptions = {};
+ // If a socket option object exists clone it
+ if(replSetSelf.socketOptions != null) {
+ var keys = Object.keys(replSetSelf.socketOptions);
+ for(var i = 0; i < keys.length;i++) socketOptions[keys[i]] = replSetSelf.socketOptions[keys[i]];
+ }
+
+ // Add host information to socket options
+ socketOptions['host'] = parts[0];
+ socketOptions['port'] = parseInt(parts[1]);
+
+ // Create a new server instance
+ var newServer = new Server(parts[0], parseInt(parts[1]), {auto_reconnect:false, 'socketOptions':socketOptions
+ , logger:replSetSelf.logger, ssl:replSetSelf.ssl, poolSize:replSetSelf.poolSize});
+ // Set the replicaset instance
+ newServer.replicasetInstance = replSetSelf;
+
+ // Add handlers
+ newServer.on("close", replSetSelf.closeHandler);
+ newServer.on("timeout", replSetSelf.timeoutHandler);
+ newServer.on("error", replSetSelf.errorHandler);
+
+ // Add server to list, ensuring we don't get a cascade of request to the same server
+ replSetSelf._state.addresses[candidateServerString] = newServer;
+
+ // Add a new server to the total number of servers that need to initialized before we are done
+ self._numberOfServersLeftToInitialize = self._numberOfServersLeftToInitialize + 1;
+
+ // Let's set up a new server instance
+ newServer.connect(parent, {returnIsMasterResults: true, eventReceiver:newServer}, self.connectionHandler(newServer));
+ }
+ }
+ } else {
+ // Remove the instance from out list of servers
+ delete replSetSelf._state.addresses[me];
+ }
+ } else {
+ delete replSetSelf._state.addresses[instanceServer.host + ":" + instanceServer.port];
+ }
+
+ // If done finish up
+ if((self._numberOfServersLeftToInitialize == 0) && replSetSelf._serverState === 'connecting' && replSetSelf._state.errorMessages.length == 0) {
+ // Set db as connected
+ replSetSelf._serverState = 'connected';
+ // If we don't expect a master let's call back, otherwise we need a master before
+ // the connection is successful
+ if(replSetSelf.masterNotNeeded || replSetSelf._state.master != null) {
+ // If we have a read strategy boot it
+ if(replSetSelf.strategyInstance != null) {
+ // Ensure we have a proper replicaset defined
+ replSetSelf.strategyInstance.replicaset = replSetSelf;
+ // Start strategy
+ replSetSelf.strategyInstance.start(function(err) {
+ // ensure no callbacks get called twice
+ var internalCallback = callback;
+ callback = null;
+ // Start up ha
+ if(replSetSelf.haEnabled && null == replSetSelf._replicasetTimeoutId) {
+ replSetSelf._replicasetTimeoutId = setTimeout(replSetSelf.replicasetCheckFunction, replSetSelf.replicasetStatusCheckInterval);
+ }
+ // Perform callback
+ internalCallback(null, parent);
+ })
+ } else {
+ // ensure no callbacks get called twice
+ var internalCallback = callback;
+ callback = null;
+ // Start up ha
+ if(replSetSelf.haEnabled && null == replSetSelf._replicasetTimeoutId) {
+ replSetSelf._replicasetTimeoutId = setTimeout(replSetSelf.replicasetCheckFunction, replSetSelf.replicasetStatusCheckInterval);
+ }
+ // Perform callback
+ internalCallback(null, parent);
+ }
+ } else if(replSetSelf.readSecondary == true && Object.keys(replSetSelf._state.secondaries).length > 0) {
+ // If we have a read strategy boot it
+ if(replSetSelf.strategyInstance != null) {
+ // Ensure we have a proper replicaset defined
+ replSetSelf.strategyInstance.replicaset = replSetSelf;
+ // Start strategy
+ replSetSelf.strategyInstance.start(function(err) {
+ // ensure no callbacks get called twice
+ var internalCallback = callback;
+ callback = null;
+ // Start up ha
+ if(replSetSelf.haEnabled && null == replSetSelf._replicasetTimeoutId) {
+ replSetSelf._replicasetTimeoutId = setTimeout(replSetSelf.replicasetCheckFunction, replSetSelf.replicasetStatusCheckInterval);
+ }
+ // Perform callback
+ internalCallback(null, parent);
+ })
+ } else {
+ // ensure no callbacks get called twice
+ var internalCallback = callback;
+ callback = null;
+ // Start up ha
+ if(replSetSelf.haEnabled && null == replSetSelf._replicasetTimeoutId) {
+ replSetSelf._replicasetTimeoutId = setTimeout(replSetSelf.replicasetCheckFunction, replSetSelf.replicasetStatusCheckInterval);
+ }
+ // Perform callback
+ internalCallback(null, parent);
+ }
+ } else if(replSetSelf.readSecondary == true && Object.keys(replSetSelf._state.secondaries).length == 0) {
+ replSetSelf._serverState = 'disconnected';
+ // ensure no callbacks get called twice
+ var internalCallback = callback;
+ callback = null;
+ // Force close all server instances
+ replSetSelf.close();
+ // Perform callback
+ internalCallback(new Error("no secondary server found"), null);
+ } else if(typeof callback === 'function') {
+ replSetSelf._serverState = 'disconnected';
+ // ensure no callbacks get called twice
+ var internalCallback = callback;
+ callback = null;
+ // Force close all server instances
+ replSetSelf.close();
+ // Perform callback
+ internalCallback(new Error("no primary server found"), null);
+ }
+ } else if((self._numberOfServersLeftToInitialize == 0) && replSetSelf._state.errorMessages.length > 0 && replSetSelf._serverState != 'disconnected') {
+ // Set done
+ replSetSelf._serverState = 'disconnected';
+ // ensure no callbacks get called twice
+ var internalCallback = callback;
+ callback = null;
+ // Force close all server instances
+ replSetSelf.close();
+ // Callback to signal we are done
+ internalCallback(replSetSelf._state.errorMessages[0], null);
+ }
+ }
+ }
+
+ // Ensure we have all registered servers in our set
+ for(var i = 0; i < serverConnections.length; i++) {
+ replSetSelf._state.addresses[serverConnections[i].host + ':' + serverConnections[i].port] = serverConnections[i];
+ }
+
+ // Initialize all the connections
+ for(var i = 0; i < serverConnections.length; i++) {
+ // Set up the logger for the server connection
+ serverConnections[i].logger = replSetSelf.logger;
+ // Default empty socket options object
+ var socketOptions = {};
+ // If a socket option object exists clone it
+ if(this.socketOptions != null && typeof this.socketOptions === 'object') {
+ var keys = Object.keys(this.socketOptions);
+ for(var j = 0; j < keys.length;j++) socketOptions[keys[j]] = this.socketOptions[keys[j]];
+ }
+
+ // If ssl is specified
+ if(replSetSelf.ssl) serverConnections[i].ssl = true;
+
+ // Add host information to socket options
+ socketOptions['host'] = serverConnections[i].host;
+ socketOptions['port'] = serverConnections[i].port;
+
+ // Set the socket options
+ serverConnections[i].socketOptions = socketOptions;
+ // Set the replicaset instance
+ serverConnections[i].replicasetInstance = replSetSelf;
+ // Connect to server
+ serverConnections[i].connect(parent, {returnIsMasterResults: true, eventReceiver:serverConnections[i]}, self.connectionHandler(serverConnections[i]));
+ }
+
+ // The checking function
+ this.replicasetCheckFunction = function() {
+ try {
+ // Retrieve a reader connection
+ var con = self.checkoutReader();
+ // If we have a connection and we have a db object
+ if(con != null && Array.isArray(self.dbInstances) && self.dbInstances.length > 0) {
+ var dbInstance = self.dbInstances[0];
+ dbInstance.admin().command({replSetGetStatus:1}, {connection:con}, function(err, result) {
+ // Paranoid android
+ if(null == err && null != result && null != result["documents"] && result["documents"].length > 0) {
+ // For each member we need to check if we have a new connection that needs to be established
+ var members = result['documents'][0]['members'];
+
+ if(null != members) {
+ // The total members we check
+ var newServers = 0;
+ // Iterate over all existing members
+ for(var i = 0, jlen = members.length; i < jlen; i++) {
+ // Get a member
+ var member = members[i];
+ // If the node is healthy and it does not exist in the current replicaset, add it to the
+ // current setup
+ if(null != self._state && 0 != member['health'] && null == self._state['addresses'][member['name']]) {
+ // We need to add a server to the connection, this means going through the notions of establishing
+ // A completely new connection
+ // Found a new server
+ newServers = newServers + 1;
+
+ // Split the server string
+ var parts = member.name.split(/:/);
+ if(parts.length == 1) {
+ parts = [parts[0], Connection.DEFAULT_PORT];
+ }
+
+ // Default empty socket options object
+ var socketOptions = {};
+ // If a socket option object exists clone it
+ if(self.socketOptions != null) {
+ var keys = Object.keys(self.socketOptions);
+ for(var k = 0; k < keys.length;k++) socketOptions[keys[i]] = self.socketOptions[keys[i]];
+ }
+
+ // Add host information to socket options
+ socketOptions['host'] = parts[0];
+ socketOptions['port'] = parseInt(parts[1]);
+
+ // Create a new server instance
+ var newServer = new Server(parts[0], parseInt(parts[1]), {auto_reconnect:false, 'socketOptions':socketOptions
+ , logger:self.logger, ssl:self.ssl, poolSize:self.poolSize});
+ // Set the replicaset instance
+ newServer.replicasetInstance = self;
+
+ // Add handlers
+ newServer.on("close", self.closeHandler);
+ newServer.on("timeout", self.timeoutHandler);
+ newServer.on("error", self.errorHandler);
+
+ // Add a new server to the total number of servers that need to initialized before we are done
+ var newServerCallback = self.connectionHandler(newServer);
+
+ // Let's set up a new server instance
+ newServer.connect(self.db, {returnIsMasterResults: true, eventReceiver:newServer}, function(err, result) {
+ // Remove from number of newServers
+ newServers = newServers - 1;
+ // Call the setup
+ newServerCallback(err, result);
+ // If we have 0 new servers let's go back to rechecking
+ if(newServers <= 0) {
+ setTimeout(self.replicasetCheckFunction, self.replicasetStatusCheckInterval);
+ }
+ });
+ }
+ }
+
+ // If we have no new servers check status again
+ if(newServers == 0) {
+ setTimeout(self.replicasetCheckFunction, self.replicasetStatusCheckInterval);
+ }
+ }
+ }
+ });
+ }
+ } catch(err) {
+ setTimeout(self.replicasetCheckFunction, self.replicasetStatusCheckInterval);
+ }
+ };
+}
+
+/**
+ * @ignore
+ */
+ReplSet.prototype.checkoutWriter = function() {
+ // Establish connection
+ var connection = this._state.master != null ? this._state.master.checkoutWriter() : null;
+ // Return the connection
+ return connection;
+}
+
+/**
+ * @ignore
+ */
+ReplSet.prototype.checkoutReader = function() {
+ var connection = null;
+ // 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.readSecondary == true || this._readPreference == Server.READ_SECONDARY || this._readPreference == Server.READ_SECONDARY_ONLY) && Object.keys(this._state.secondaries).length > 0) {
+ // Checkout a secondary server from the passed in set of servers
+ if(this.strategyInstance != null) {
+ connection = this.strategyInstance.checkoutSecondary();
+ } else {
+ // Pick a random key
+ var keys = Object.keys(this._state.secondaries);
+ this._currentServerChoice = this._currentServerChoice % keys.length;
+ var key = keys[this._currentServerChoice++];
+ connection = this._state.secondaries[key].checkoutReader();
+ }
+ } else if(this._readPreference == Server.READ_SECONDARY_ONLY && Object.keys(this._state.secondaries).length == 0) {
+ connection = null;
+ } else if(this._readPreference != null && typeof this._readPreference === 'object') {
+ // Get all tag keys (used to try to find a server that is valid)
+ var keys = Object.keys(this._readPreference);
+ // final instance server
+ var instanceServer = null;
+ // for each key look for an avilable instance
+ for(var i = 0; i < keys.length; i++) {
+ // Grab subkey value
+ var value = this._readPreference[keys[i]];
+
+ // Check if we have any servers for the tag, if we do pick a random one
+ if(this._state.byTags[keys[i]] != null
+ && this._state.byTags[keys[i]][value] != null
+ && Array.isArray(this._state.byTags[keys[i]][value])
+ && this._state.byTags[keys[i]][value].length > 0) {
+ // Let's grab an available server from the list using a random pick
+ var serverInstances = this._state.byTags[keys[i]][value];
+ // Set instance to return
+ instanceServer = serverInstances[Math.floor(Math.random() * serverInstances.length)];
+ break;
+ }
+ }
+
+ // Return the instance of the server
+ connection = instanceServer != null ? instanceServer.checkoutReader() : this.checkoutWriter();
+ } else {
+ connection = this.checkoutWriter();
+ }
+
+ // Return the connection
+ return connection;
+}
+
+/**
+ * @ignore
+ */
+ReplSet.prototype.allRawConnections = function() {
+ // Neeed to build a complete list of all raw connections, start with master server
+ var allConnections = [];
+ // Get connection object
+ var allMasterConnections = this._state.master.connectionPool.getAllConnections();
+ // Add all connections to list
+ allConnections = allConnections.concat(allMasterConnections);
+
+ // If we have read secondary let's add all secondary servers
+ if(this.readSecondary && Object.keys(this._state.secondaries).length > 0) {
+ // Get all the keys
+ var keys = Object.keys(this._state.secondaries);
+ // For each of the secondaries grab the connections
+ for(var i = 0; i < keys.length; i++) {
+ // Get connection object
+ var secondaryPoolConnections = this._state.secondaries[keys[i]].connectionPool.getAllConnections();
+ // Add all connections to list
+ allConnections = allConnections.concat(secondaryPoolConnections);
+ }
+ }
+
+ // Return all the conections
+ return allConnections;
+}
+
+/**
+ * @ignore
+ */
+ReplSet.prototype.enableRecordQueryStats = function(enable) {
+ // Set the global enable record query stats
+ this.recordQueryStats = enable;
+ // Ensure all existing servers already have the flag set, even if the
+ // connections are up already or we have not connected yet
+ if(this._state != null && this._state.addresses != null) {
+ var keys = Object.keys(this._state.addresses);
+ // Iterate over all server instances and set the enableRecordQueryStats flag
+ for(var i = 0; i < keys.length; i++) {
+ this._state.addresses[keys[i]].enableRecordQueryStats(enable);
+ }
+ } else if(Array.isArray(this.servers)) {
+ for(var i = 0; i < this.servers.length; i++) {
+ this.servers[i].enableRecordQueryStats(enable);
+ }
+ }
+}
+
+/**
+ * @ignore
+ */
+ReplSet.prototype.disconnect = function(callback) {
+ this.close(callback);
+}
+
+/**
+ * @ignore
+ */
+ReplSet.prototype.close = function(callback) {
+ var self = this;
+ // Set server status as disconnected
+ this._serverState = 'disconnected';
+ // Get all the server instances and close them
+ var allServers = [];
+ // Make sure we have servers
+ if(this._state['addresses'] != null) {
+ var keys = Object.keys(this._state.addresses);
+ for(var i = 0; i < keys.length; i++) {
+ allServers.push(this._state.addresses[keys[i]]);
+ }
+ }
+
+ // Let's process all the closing
+ var numberOfServersToClose = allServers.length;
+
+ // Remove all the listeners
+ self.removeAllListeners();
+
+ // Special case where there are no servers
+ if(allServers.length == 0 && typeof callback === 'function') return callback(null, null);
+
+ // Close the servers
+ for(var i = 0; i < allServers.length; i++) {
+ var server = allServers[i];
+ if(server.isConnected()) {
+ // Close each server
+ server.close(function() {
+ numberOfServersToClose = numberOfServersToClose - 1;
+ // Clear out state if we are done
+ if(numberOfServersToClose == 0) {
+ // Clear out state
+ self._state = {'master':null, 'secondaries':{}, 'arbiters':{}, 'passives':{}, 'errors':{}, 'addresses':{}, 'byTags':{}, 'setName':null, 'errorMessages':[], 'members':[]};
+ }
+
+ // If we are finished perform the call back
+ if(numberOfServersToClose == 0 && typeof callback === 'function') {
+ callback(null);
+ }
+ })
+ } else {
+ numberOfServersToClose = numberOfServersToClose - 1;
+ // If we have no more servers perform the callback
+ if(numberOfServersToClose == 0 && typeof callback === 'function') {
+ callback(null);
+ }
+ }
+ }
+}
+
+/**
+ * Auto Reconnect property
+ * @ignore
+ */
+Object.defineProperty(ReplSet.prototype, "autoReconnect", { enumerable: true
+ , get: function () {
+ return true;
+ }
+});
+
+/**
+ * Get Read Preference method
+ * @ignore
+ */
+Object.defineProperty(ReplSet.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;
+ }
+ }
+});
+
+/**
+ * Db Instances
+ * @ignore
+ */
+Object.defineProperty(ReplSet.prototype, "dbInstances", {enumerable:true
+ , get: function() {
+ var servers = this.allServerInstances();
+ return servers[0].dbInstances;
+ }
+})
+
+/**
+ * Just make compatible with server.js
+ * @ignore
+ */
+Object.defineProperty(ReplSet.prototype, "host", { enumerable: true
+ , get: function () {
+ if (this.primary != null) return this.primary.host;
+ }
+});
+
+/**
+ * Just make compatible with server.js
+ * @ignore
+ */
+Object.defineProperty(ReplSet.prototype, "port", { enumerable: true
+ , get: function () {
+ if (this.primary != null) return this.primary.port;
+ }
+});
+
+/**
+ * Get status of read
+ * @ignore
+ */
+Object.defineProperty(ReplSet.prototype, "read", { enumerable: true
+ , get: function () {
+ return this.secondaries.length > 0 ? this.secondaries[0] : null;
+ }
+});
+
+/**
+ * Get list of secondaries
+ * @ignore
+ */
+Object.defineProperty(ReplSet.prototype, "secondaries", {enumerable: true
+ , get: function() {
+ var keys = Object.keys(this._state.secondaries);
+ var array = new Array(keys.length);
+ // Convert secondaries to array
+ for(var i = 0; i < keys.length; i++) {
+ array[i] = this._state.secondaries[keys[i]];
+ }
+ return array;
+ }
+});
+
+/**
+ * Get list of all secondaries including passives
+ * @ignore
+ */
+Object.defineProperty(ReplSet.prototype, "allSecondaries", {enumerable: true
+ , get: function() {
+ return this.secondaries.concat(this.passives);
+ }
+});
+
+/**
+ * Get list of arbiters
+ * @ignore
+ */
+Object.defineProperty(ReplSet.prototype, "arbiters", {enumerable: true
+ , get: function() {
+ var keys = Object.keys(this._state.arbiters);
+ var array = new Array(keys.length);
+ // Convert arbiters to array
+ for(var i = 0; i < keys.length; i++) {
+ array[i] = this._state.arbiters[keys[i]];
+ }
+ return array;
+ }
+});
+
+/**
+ * Get list of passives
+ * @ignore
+ */
+Object.defineProperty(ReplSet.prototype, "passives", {enumerable: true
+ , get: function() {
+ var keys = Object.keys(this._state.passives);
+ var array = new Array(keys.length);
+ // Convert arbiters to array
+ for(var i = 0; i < keys.length; i++) {
+ array[i] = this._state.passives[keys[i]];
+ }
+ return array;
+ }
+});
+
+/**
+ * Master connection property
+ * @ignore
+ */
+Object.defineProperty(ReplSet.prototype, "primary", { enumerable: true
+ , get: function () {
+ return this._state != null ? this._state.master : null;
+ }
+});
+
+/**
+ * @ignore
+ */
+// Backward compatibility
+exports.ReplSetServers = ReplSet;
diff --git a/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/connection/server.js b/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/connection/server.js
new file mode 100644
index 0000000..8ee6452
--- /dev/null
+++ b/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/connection/server.js
@@ -0,0 +1,745 @@
+var Connection = require('./connection').Connection,
+ DbCommand = require('../commands/db_command').DbCommand,
+ MongoReply = require('../responses/mongo_reply').MongoReply,
+ ConnectionPool = require('./connection_pool').ConnectionPool,
+ EventEmitter = require('events').EventEmitter,
+ inherits = require('util').inherits;
+
+/**
+ * Class representing a single MongoDB Server connection
+ *
+ * Options
+ * - **readPreference** {String, default:null}, set's the read preference (Server.READ_PRIMAR, Server.READ_SECONDARY_ONLY, Server.READ_SECONDARY)
+ * - **ssl** {Boolean, default:false}, use ssl connection (needs to have a mongod server with ssl support)
+ * - **slaveOk** {Boolean, default:false}, legacy option allowing reads from secondary, use **readPrefrence** instead.
+ * - **poolSize** {Number, default:1}, number of connections in the connection pool, set to 1 as default for legacy reasons.
+ * - **socketOptions** {Object, default:null}, an object containing socket options to use (noDelay:(boolean), keepAlive:(number), timeout:(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.
+ *
+ * @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 event emitter
+ EventEmitter.call(this);
+ // Set up Server instance
+ if(!(this instanceof Server)) return new Server(host, port, options);
+
+ 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 ? 1 : this.options.poolSize;
+ this.ssl = this.options.ssl == null ? false : this.options.ssl;
+ this.slaveOk = this.options["slave_ok"];
+ this._used = false;
+
+ // Get the readPreference
+ var readPreference = this.options['readPreference'];
+ // Read preference setting
+ if(readPreference != null) {
+ if(readPreference != Server.READ_PRIMARY && readPreference != Server.READ_SECONDARY_ONLY
+ && readPreference != Server.READ_SECONDARY) {
+ throw new Error("Illegal readPreference mode specified, " + readPreference);
+ }
+
+ // 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 : {};
+ // Set ssl up if it's defined
+ if(this.ssl) {
+ this.socketOptions.ssl = true;
+ }
+
+ // 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';
+ // this._timeout = false;
+ // Contains state information about server connection
+ this._state = {'runtimeStats': {'queryStats':new RunningStats()}};
+ // Do we record server stats or not
+ this.recordQueryStats = false;
+};
+
+/**
+ * @ignore
+ */
+// Inherit simple event emitter
+inherits(Server, EventEmitter);
+// Read Preferences
+Server.READ_PRIMARY = 'primary';
+Server.READ_SECONDARY = 'secondary';
+Server.READ_SECONDARY_ONLY = 'secondaryOnly';
+// Always ourselves
+Server.prototype.setReadPreference = function() {}
+
+/**
+ * @ignore
+ */
+Server.prototype._isUsed = function() {
+ return this._used;
+}
+
+/**
+ * @ignore
+ */
+Server.prototype.close = function(callback) {
+ // 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);
+ }
+
+ // Set server status as disconnected
+ this._serverState = 'disconnected';
+ // Peform callback if present
+ if(typeof callback === 'function') callback();
+};
+
+/**
+ * @ignore
+ */
+Server.prototype.isConnected = function() {
+ return this._serverState == 'connected';
+}
+
+/**
+ * @ignore
+ */
+Server.prototype.allServerInstances = function() {
+ return [this];
+}
+
+/**
+ * @ignore
+ */
+Server.prototype.isSetMember = function() {
+ return this['replicasetInstance'] != null;
+}
+
+/**
+ * @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;
+
+ // 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;
+ }
+
+ // Let's connect
+ var server = this;
+ // Let's us override the main receiver of events
+ var eventReceiver = options.eventReceiver != null ? options.eventReceiver : this;
+ // Creating dbInstance
+ this.dbInstance = dbInstance;
+ // Save reference to dbInstance
+ this.dbInstances = [dbInstance];
+
+ // Set server state to connecting
+ this._serverState = 'connecting';
+ // Ensure dbInstance can do a slave query if it's set
+ dbInstance.slaveOk = this.slaveOk ? this.slaveOk : dbInstance.slaveOk;
+ // Create connection Pool instance with the current BSON serializer
+ var connectionPool = new ConnectionPool(this.host, this.port, this.poolSize, dbInstance.bson, this.socketOptions);
+ // Set logger on pool
+ connectionPool.logger = this.logger;
+
+ // Set up a new pool using default settings
+ server.connectionPool = connectionPool;
+
+ // 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(err, reply) {
+ // ensure no callbacks get called twice
+ var internalCallback = callback;
+ callback = null;
+ // 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.master = reply.documents[0].ismaster == 1 ? true : false;
+ server.connectionPool.setMaxBsonSize(reply.documents[0].maxBsonObjectSize);
+ // Set server as connected
+ server.connected = true;
+ // Save document returned so we can query it
+ server.isMasterDoc = reply.documents[0];
+
+ // If we have it set to returnIsMasterResults
+ if(returnIsMasterResults) {
+ internalCallback(null, reply);
+ } else {
+ internalCallback(null, dbInstance);
+ }
+ };
+
+ // Let's us override the main connect callback
+ var connectHandler = options.connectHandler == null ? connectCallback : 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();
+ // Set server state to connected
+ server._serverState = 'connected';
+
+ // Register handler for messages
+ dbInstance._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 = null;
+ var dbInstanceObject = null;
+
+ // Locate a callback instance and remove any additional ones
+ for(var i = 0; i < server.dbInstances.length; i++) {
+ var dbInstanceObjectTemp = server.dbInstances[i];
+ var hasHandler = dbInstanceObjectTemp._hasHandler(mongoReply.responseTo.toString());
+ // Assign the first one we find and remove any duplicate ones
+ if(hasHandler && callbackInfo == null) {
+ callbackInfo = dbInstanceObjectTemp._findHandler(mongoReply.responseTo.toString());
+ dbInstanceObject = dbInstanceObjectTemp;
+ } else if(hasHandler) {
+ dbInstanceObjectTemp._removeHandler(mongoReply.responseTo.toString());
+ }
+ }
+
+ // Only execute callback if we have a caller
+ if(callbackInfo.callback && Array.isArray(callbackInfo.info.chained)) {
+ // Check if callback has already been fired (missing chain command)
+ var chained = callbackInfo.info.chained;
+ var numberOfFoundCallbacks = 0;
+ for(var i = 0; i < chained.length; i++) {
+ if(dbInstanceObject._hasHandler(chained[i])) numberOfFoundCallbacks++;
+ }
+
+ // If we have already fired then clean up rest of chain and move on
+ if(numberOfFoundCallbacks != chained.length) {
+ for(var i = 0; i < chained.length; i++) {
+ dbInstanceObject._removeHandler(chained[i]);
+ }
+
+ // Just return from function
+ return;
+ }
+
+ // Parse the body
+ mongoReply.parseBody(message, connectionPool.bson, callbackInfo.info.raw, function(err) {
+ var callbackInfo = dbInstanceObject._findHandler(mongoReply.responseTo.toString());
+ // If we have an error let's execute the callback and clean up all other
+ // chained commands
+ var firstResult = mongoReply && mongoReply.documents;
+ // Check for an error, if we have one let's trigger the callback and clean up
+ // The chained callbacks
+ if(firstResult[0].err != null || firstResult[0].errmsg != null) {
+ // Trigger the callback for the error
+ dbInstanceObject._callHandler(mongoReply.responseTo, mongoReply, null);
+ } else {
+ var chainedIds = callbackInfo.info.chained;
+
+ if(chainedIds.length > 0 && chainedIds[chainedIds.length - 1] == mongoReply.responseTo) {
+ // Cleanup all other chained calls
+ chainedIds.pop();
+ // Remove listeners
+ for(var i = 0; i < chainedIds.length; i++) dbInstanceObject._removeHandler(chainedIds[i]);
+ // Call the handler
+ dbInstanceObject._callHandler(mongoReply.responseTo, callbackInfo.info.results.shift(), null);
+ } else{
+ // Add the results to all the results
+ for(var i = 0; i < chainedIds.length; i++) {
+ var handler = dbInstanceObject._findHandler(chainedIds[i]);
+ // Check if we have an object, if it's the case take the current object commands and
+ // and add this one
+ if(handler.info != null) {
+ handler.info.results = Array.isArray(callbackInfo.info.results) ? callbackInfo.info.results : [];
+ handler.info.results.push(mongoReply);
+ }
+ }
+ }
+ }
+ });
+ } else if(callbackInfo.callback) {
+ // Parse the body
+ mongoReply.parseBody(message, connectionPool.bson, callbackInfo.info.raw, function(err) {
+ // 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);
+ }
+
+ // Trigger the callback
+ dbInstanceObject._callHandler(mongoReply.responseTo, mongoReply, null);
+ });
+ }
+ }
+ } catch (err) {
+ // Throw error in next tick
+ process.nextTick(function() {
+ throw err;
+ })
+ }
+ });
+
+ // Handle timeout
+ connectionPool.on("timeout", function(err) {
+ // If pool connection is already closed
+ if(server._serverState === 'disconnected') return;
+ // Set server state to disconnected
+ server._serverState = 'disconnected';
+ // // Close the pool
+ // connectionPool.stop();
+ // 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);
+ } 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
+ _fireCallbackErrors(server, err);
+ // Emit error
+ _emitAcrossAllDbInstances(server, eventReceiver, "timeout", err, server);
+ }
+ });
+
+ // Handle errors
+ connectionPool.on("error", function(message) {
+ // If pool connection is already closed
+ if(server._serverState === 'disconnected') return;
+ // Set server state to disconnected
+ server._serverState = 'disconnected';
+ // If we have a callback return the error
+ if(typeof callback === 'function') {// && !server.isSetMember()) {
+ // ensure no callbacks get called twice
+ var internalCallback = callback;
+ callback = null;
+ // Perform callback
+ internalCallback(new Error(message && message.err ? message.err : message), null);
+ } else if(server.isSetMember()) {
+ if(server.listeners["error"] && server.listeners["error"].length > 0) server.emit("error", new Error(message && message.err ? message.err : message), server);
+ } else {
+ if(eventReceiver.listeners["error"] && eventReceiver.listeners["error"].length > 0) eventReceiver.emit("error", new Error(message && message.err ? message.err : message), server);
+ }
+
+ // If we are a single server connection fire errors correctly
+ if(!server.isSetMember()) {
+ // Fire all callback errors
+ _fireCallbackErrors(server, new Error(message && message.err ? message.err : message));
+ // Emit error
+ _emitAcrossAllDbInstances(server, eventReceiver, "error", new Error(message && message.err ? message.err : message), server);
+ }
+ });
+
+ // Handle close events
+ connectionPool.on("close", function() {
+ // If pool connection is already closed
+ if(server._serverState === 'disconnected') return;
+ // Set server state to disconnected
+ server._serverState = 'disconnected';
+ // // Close the pool
+ // 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"), null);
+ } 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
+ _fireCallbackErrors(server, new Error("connection closed"));
+ // Emit error
+ _emitAcrossAllDbInstances(server, eventReceiver, "close", server);
+ }
+ });
+
+ // 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') return;
+ // Set server state to disconnected
+ server._serverState = 'disconnected';
+ // // Close the pool
+ // connectionPool.stop();
+ // 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);
+ } 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
+ _fireCallbackErrors(server, new Error("connection closed due to parseError"));
+ // Emit error
+ _emitAcrossAllDbInstances(server, eventReceiver, "parseError", server);
+ }
+ });
+
+ // Boot up connection poole, pass in a locator of callbacks
+ connectionPool.start();
+}
+
+/**
+ * Fire all the errors
+ * @ignore
+ */
+var _fireCallbackErrors = function(server, err) {
+ // Locate all the possible callbacks that need to return
+ for(var i = 0; i < server.dbInstances.length; i++) {
+ // Fetch the db Instance
+ var dbInstance = server.dbInstances[i];
+ // Check all callbacks
+ var keys = Object.keys(dbInstance._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 = dbInstance._callBackStore._notReplied[keys[j]];
+ // Check if we have a chained command (findAndModify)
+ if(info && info['chained'] && Array.isArray(info['chained']) && info['chained'].length > 0) {
+ var chained = info['chained'];
+ // Only callback once and the last one is the right one
+ var finalCallback = chained.pop();
+ // console.dir(finalCallback)
+ if(info.connection.socketOptions.host === server.host && info.connection.socketOptions.port === server.port) {
+ dbInstance._callBackStore.emit(finalCallback, err, null);
+ }
+
+ // Put back the final callback to ensure we don't call all commands in the chain
+ chained.push(finalCallback);
+
+ // Remove all chained callbacks
+ for(var i = 0; i < chained.length; i++) {
+ delete dbInstance._callBackStore._notReplied[chained[i]];
+ }
+ } else {
+ if(info && info.connection.socketOptions.host === server.host && info.connection.socketOptions.port === server.port) {
+ dbInstance._callBackStore.emit(keys[j], err, null);
+ }
+ }
+ }
+ }
+}
+
+/**
+ * @ignore
+ */
+var _emitAcrossAllDbInstances = function(server, filterDb, event, message, object) {
+ // Emit close event across all db instances sharing the sockets
+ var allServerInstances = server.allServerInstances();
+ // Fetch the first server instance
+ var serverInstance = allServerInstances[0];
+ // For all db instances signal all db instances
+ if(Array.isArray(serverInstance.dbInstances) && serverInstance.dbInstances.length > 1) {
+ for(var i = 0; i < serverInstance.dbInstances.length; i++) {
+ var dbInstance = serverInstance.dbInstances[i];
+ // Check if it's our current db instance and skip if it is
+ if(filterDb == null || filterDb.databaseName !== dbInstance.databaseName || filterDb.tag !== dbInstance.tag) {
+ dbInstance.emit(event, message, object);
+ }
+ }
+ }
+}
+
+/**
+ * @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['arbiterOnly'] == true) {
+ return new Error("Cannot write to an arbiter");
+ } if(self.isMasterDoc['secondary'] == true) {
+ return new Error("Cannot write to a secondary");
+ } else if(read == true && self._readPreference == Server.READ_SECONDARY_ONLY && self.isMasterDoc['ismaster'] == true) {
+ return new Error("Cannot read from primary when secondary only specified");
+ }
+
+ // 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) {
+ return this.connectionPool.checkoutConnection();
+ } 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['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 == Server.READ_PRIMARY && self.isMasterDoc['ismaster'] != true) {
+ return new Error("Read preference is " + Server.READ_PRIMARY + " and server is not master");
+ } else if(self._readPreference == Server.READ_SECONDARY_ONLY && self.isMasterDoc['ismaster'] == true) {
+ return new Error("Cannot read from primary when secondary only specified");
+ }
+ }
+
+ // Return no error
+ return null;
+}
+
+/**
+ * @ignore
+ */
+Server.prototype.checkoutReader = function() {
+ // 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) {
+ return this.connectionPool.checkoutConnection();
+ } 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/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/connection/strategies/ping_strategy.js b/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/connection/strategies/ping_strategy.js
new file mode 100644
index 0000000..6bb36cf
--- /dev/null
+++ b/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/connection/strategies/ping_strategy.js
@@ -0,0 +1,125 @@
+var Server = require("../server").Server;
+
+// 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) {
+ this.replicaset = replicaset;
+ this.state = 'disconnected';
+ // Class instance
+ this.Db = require("../../db").Db;
+}
+
+// Starts any needed code
+PingStrategy.prototype.start = function(callback) {
+ 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';
+ // Call the callback
+ callback(null, null);
+}
+
+PingStrategy.prototype.checkoutSecondary = function() {
+ // Get all secondary server keys
+ var keys = Object.keys(this.replicaset._state.secondaries);
+ // Contains the picked instance
+ var minimumPingMs = null;
+ var selectedInstance = null;
+ // Pick server key by the lowest ping time
+ for(var i = 0; i < keys.length; i++) {
+ // Fetch a server
+ var server = this.replicaset._state.secondaries[keys[i]];
+ // If we don't have a ping time use it
+ if(server.runtimeStats['pingMs'] == null) {
+ // Set to 0 ms for the start
+ server.runtimeStats['pingMs'] = 0;
+ // Pick server
+ selectedInstance = server;
+ break;
+ } else {
+ // If the next server's ping time is less than the current one choose than one
+ if(minimumPingMs == null || server.runtimeStats['pingMs'] < minimumPingMs) {
+ minimumPingMs = server.runtimeStats['pingMs'];
+ selectedInstance = server;
+ }
+ }
+ }
+
+ // Return the selected instance
+ return selectedInstance != null ? selectedInstance.checkoutReader() : null;
+}
+
+PingStrategy.prototype._pingServer = function(callback) {
+ var self = this;
+
+ // Ping server function
+ var pingFunction = function() {
+ if(self.state == 'disconnected') return;
+ var addresses = self.replicaset._state != null && self.replicaset._state.addresses != null ? self.replicaset._state.addresses : null;
+ // Grab all servers
+ var serverKeys = Object.keys(addresses);
+ // Number of server entries
+ var numberOfEntries = serverKeys.length;
+ // We got keys
+ for(var i = 0; i < serverKeys.length; i++) {
+ // We got a server instance
+ var server = addresses[serverKeys[i]];
+ // Create a new server object, avoid using internal connections as they might
+ // be in an illegal state
+ new function(serverInstance) {
+ var server = new Server(serverInstance.host, serverInstance.port, {poolSize:1, timeout:500});
+ var db = new self.Db(self.replicaset.db.databaseName, server);
+ // Add error listener
+ db.on("error", function(err) {
+ // Adjust the number of checks
+ numberOfEntries = numberOfEntries - 1;
+ // Close connection
+ db.close();
+ // If we are done with all results coming back trigger ping again
+ if(numberOfEntries == 0 && self.state == 'connected') {
+ setTimeout(pingFunction, 1000);
+ }
+ })
+
+ // Open the db instance
+ db.open(function(err, p_db) {
+ if(err != null) {
+ db.close();
+ } else {
+ // Startup time of the command
+ var startTime = new Date().getTime();
+ // Execute ping on this connection
+ p_db.executeDbCommand({ping:1}, function(err, result) {
+ // Adjust the number of checks
+ numberOfEntries = numberOfEntries - 1;
+ // Get end time of the command
+ var endTime = new Date().getTime();
+ // Store the ping time in the server instance state variable, if there is one
+ if(serverInstance != null && serverInstance.runtimeStats != null && serverInstance.isConnected()) {
+ serverInstance.runtimeStats['pingMs'] = (endTime - startTime);
+ }
+
+ // Close server
+ p_db.close();
+ // If we are done with all results coming back trigger ping again
+ if(numberOfEntries == 0 && self.state == 'connected') {
+ setTimeout(pingFunction, 1000);
+ }
+ })
+ }
+ })
+ }(server);
+ }
+ }
+
+ // Start pingFunction
+ setTimeout(pingFunction, 1000);
+ // Do the callback
+ callback(null);
+}
diff --git a/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/connection/strategies/statistics_strategy.js b/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/connection/strategies/statistics_strategy.js
new file mode 100644
index 0000000..0c8b1c0
--- /dev/null
+++ b/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/connection/strategies/statistics_strategy.js
@@ -0,0 +1,40 @@
+// 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;
+}
+
+// Starts any needed code
+StatisticsStrategy.prototype.start = function(callback) {
+ callback(null, null);
+}
+
+StatisticsStrategy.prototype.stop = function(callback) {
+ // Remove reference to replicaset
+ this.replicaset = null;
+ // Perform callback
+ callback(null, null);
+}
+
+StatisticsStrategy.prototype.checkoutSecondary = function() {
+ // Get all secondary server keys
+ var keys = Object.keys(this.replicaset._state.secondaries);
+ // Contains the picked instance
+ var minimumSscore = null;
+ var selectedInstance = null;
+
+ // Pick server key by the lowest ping time
+ for(var i = 0; i < keys.length; i++) {
+ // Fetch a server
+ var server = this.replicaset._state.secondaries[keys[i]];
+ // Pick server by lowest Sscore
+ if(minimumSscore == null || (server.queryStats.sScore < minimumSscore)) {
+ minimumSscore = server.queryStats.sScore;
+ selectedInstance = server;
+ }
+ }
+
+ // Return the selected instance
+ return selectedInstance != null ? selectedInstance.checkoutReader() : null;
+}
diff --git a/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/cursor.js b/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/cursor.js
new file mode 100644
index 0000000..76a0152
--- /dev/null
+++ b/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/cursor.js
@@ -0,0 +1,729 @@
+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,
+ CursorStream = require('./cursorstream'),
+ utils = require('./utils');
+
+/**
+ * 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.
+ *
+ * @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 {Number} skip number of documents to skip.
+ * @param {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.
+ * @param {String|Array|Object} sort the required sorting for the query.
+ * @param {Object} hint force the query to use a specific index.
+ * @param {Boolean} explain return the explaination of the query.
+ * @param {Boolean} snapshot Snapshot mode assures no duplicates are returned.
+ * @param {Boolean} timeout allow the query to timeout.
+ * @param {Boolean} tailable allow the cursor to be tailable.
+ * @param {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.
+ * @param {Boolean} raw return all query documents as raw buffers (default false).
+ * @param {Boolean} read specify override of read from source (primary/secondary).
+ * @param {Boolean} returnKey only return the index key.
+ * @param {Number} maxScan limit the number of items to scan.
+ * @param {Number} min set index bounds.
+ * @param {Number} max set index bounds.
+ * @param {Boolean} showDiskLoc show disk location of results.
+ * @param {String} comment you can put a $comment field on a query to make looking in the profiler logs simpler.
+ */
+function Cursor(db, collection, selector, fields, skip, limit
+ , sort, hint, explain, snapshot, timeout, tailable, batchSize, slaveOk, raw, read
+ , returnKey, maxScan, min, max, showDiskLoc, comment) {
+ this.db = db;
+ this.collection = collection;
+ this.selector = selector;
+ this.fields = fields;
+ this.skipValue = skip == null ? 0 : skip;
+ this.limitValue = limit == null ? 0 : limit;
+ this.sortValue = sort;
+ this.hint = hint;
+ this.explainValue = explain;
+ this.snapshot = snapshot;
+ this.timeout = timeout == null ? true : timeout;
+ this.tailable = tailable;
+ this.batchSizeValue = batchSize == null ? 0 : batchSize;
+ this.slaveOk = slaveOk == null ? collection.slaveOk : slaveOk;
+ this.raw = raw == null ? false : raw;
+ this.read = read == null ? true : read;
+ this.returnKey = returnKey;
+ this.maxScan = maxScan;
+ this.min = min;
+ this.max = max;
+ this.showDiskLoc = showDiskLoc;
+ this.comment = comment;
+
+ this.totalNumberOfRecords = 0;
+ this.items = [];
+ this.cursorId = Long.fromInt(0);
+
+ // State variables for the cursor
+ this.state = Cursor.INIT;
+ // Keep track of the current query run
+ this.queryRun = false;
+ this.getMoreTimer = false;
+ 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 paramter will contain the Error object if an error occured, or null otherwise. The second paramter 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) {
+ var items = [];
+
+ this.each(function(err, item) {
+ if(err != null) return callback(err, null);
+
+ if (item != null) {
+ items.push(item);
+ } else {
+ var resultItems = items;
+ items = null;
+ self.items = [];
+ // Returns items
+ callback(err, resultItems);
+ }
+ });
+ } else {
+ callback(new Error("Cursor is closed"), null);
+ }
+};
+
+/**
+ * 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 paramter will contain the Error object if an error occured, or null otherwise. While the second paramter will contain the document.
+ * @return {null}
+ * @api public
+ */
+Cursor.prototype.each = function(callback) {
+ var self = this;
+
+ if (!callback) {
+ throw new Error('callback is mandatory');
+ }
+
+ if(this.state != Cursor.CLOSED) {
+ //FIX: stack overflow (on deep callback) (cred: https://github.com/limp/node-mongodb-native/commit/27da7e4b2af02035847f262b29837a94bbbf6ce2)
+ process.nextTick(function(){
+ var s = new Date()
+ // 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);
+ self.each(callback);
+ } else {
+ // Close the cursor if done
+ self.state = Cursor.CLOSED;
+ callback(err, null);
+ }
+ });
+ });
+ } else {
+ callback(new Error("Cursor is closed"), null);
+ }
+};
+
+/**
+ * Determines how many result the query for this cursor will return
+ *
+ * @param {Function} callback this will be after executing this method. The first paramter will contain the Error object if an error occured, or null otherwise. While the second paramter will contain the number of results or null if an error occured.
+ * @return {null}
+ * @api public
+ */
+Cursor.prototype.count = function(callback) {
+ this.collection.count(this.selector, 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 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(self.slaveOk) {
+ queryOptions |= QueryCommand.OPTS_SLAVE;
+ }
+
+ // 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.explainValue != null) specialSelector['$explain'] = true;
+ 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;
+
+ // 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(callback) {
+ var self = this;
+
+ if(self.state == Cursor.INIT) {
+ var cmd;
+ try {
+ cmd = generateQueryCommand(self);
+ } catch (err) {
+ return callback(err, null);
+ }
+
+ var commandHandler = function(err, result) {
+ if(err != null && result == null) return callback(err, null);
+
+ if(!err && result.documents[0] && result.documents[0]['$err']) {
+ return self.close(function() {callback(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]);
+ }
+
+ result = null;
+ self.nextObject(callback);
+ };
+
+ self.db._executeQueryCommand(cmd, {read:self.read, raw:self.raw}, commandHandler);
+ 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, callback) {
+ var limit = 0;
+
+ 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
+ );
+
+ var options = { read: self.read, raw: self.raw };
+
+ // Execute the command
+ self.db._executeQueryCommand(getMoreCommand, options, function(err, result) {
+ try {
+ if(err != null) callback(err, null);
+
+ 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);
+ }
+ }
+
+ self.items = self.items.concat(result.documents);
+ // result = null;
+ callback(null, self.items.shift());
+ } else if(self.tailable && !isDead) {
+ self.getMoreTimer = setTimeout(function() {getMore(self, callback);}, 500);
+ } else {
+ self.close(function() {callback(null, null);});
+ }
+
+ result = null;
+ } catch(err) {
+ callback(err, null);
+ }
+ });
+
+ getMoreCommand = null;
+ } catch(err) {
+ var handleClose = function() {
+ callback(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, this.skipValue, limit,
+ this.sortValue, this.hint, true, this.snapshot, this.timeout, this.tailable, this.batchSizeValue);
+ // Fetch the explaination document
+ cursor.nextObject(function(err, item) {
+ if(err != null) return callback(err, null);
+ // close the cursor
+ cursor.close(function(err, result) {
+ if(err != null) return callback(err, null);
+ callback(null, item);
+ });
+ });
+};
+
+/**
+ * Returns a stream object that can be used to listen to and stream records
+ * (**Use the CursorStream object instead as this is deprected**)
+ *
+ * Options
+ * - **fetchSize** {Number} the number of records to fetch in each batch (steam specific batchSize).
+ *
+ * Events
+ * - **data** {function(item) {}} the data event triggers when a document is ready.
+ * - **error** {function(err) {}} the error event triggers if an error happens.
+ * - **end** {function() {}} the end event triggers when there is no more documents available.
+ *
+ * @param {Object} [options] additional options for streamRecords.
+ * @return {EventEmitter} returns a stream object.
+ * @api public
+ */
+Cursor.prototype.streamRecords = function(options) {
+ var args = Array.prototype.slice.call(arguments, 0);
+ options = args.length ? args.shift() : {};
+
+ var
+ self = this,
+ stream = new process.EventEmitter(),
+ recordLimitValue = this.limitValue || 0,
+ emittedRecordCount = 0,
+ queryCommand = generateQueryCommand(self);
+
+ // see http://www.mongodb.org/display/DOCS/Mongo+Wire+Protocol
+ queryCommand.numberToReturn = options.fetchSize ? options.fetchSize : 500;
+ // Execute the query
+ execute(queryCommand);
+
+ function execute(command) {
+ self.db._executeQueryCommand(command, {read:self.read, raw:self.raw}, function(err,result) {
+ if(err) {
+ stream.emit('error', err);
+ self.close(function(){});
+ return;
+ }
+
+ if (!self.queryRun && result) {
+ self.queryRun = true;
+ self.cursorId = result.cursorId;
+ self.state = Cursor.OPEN;
+ self.getMoreCommand = new GetMoreCommand(self.db, self.collectionName, queryCommand.numberToReturn, result.cursorId);
+ }
+
+ var resflagsMap = {
+ CursorNotFound:1<<0,
+ QueryFailure:1<<1,
+ ShardConfigStale:1<<2,
+ AwaitCapable:1<<3
+ };
+
+ if(result.documents && result.documents.length && !(result.responseFlag & resflagsMap.QueryFailure)) {
+ try {
+ result.documents.forEach(function(doc){
+ if(recordLimitValue && emittedRecordCount>=recordLimitValue) {
+ throw("done");
+ }
+ emittedRecordCount++;
+ stream.emit('data', doc);
+ });
+ } catch(err) {
+ if (err != "done") { throw err; }
+ else {
+ self.close(function(){
+ stream.emit('end', recordLimitValue);
+ });
+ self.close(function(){});
+ return;
+ }
+ }
+ // rinse & repeat
+ execute(self.getMoreCommand);
+ } else {
+ self.close(function(){
+ stream.emit('end', recordLimitValue);
+ });
+ }
+ });
+ }
+
+ return stream;
+};
+
+/**
+ * Returns a Node ReadStream interface for this cursor.
+ *
+ * @return {CursorStream} returns a stream object.
+ * @api public
+ */
+Cursor.prototype.stream = function stream () {
+ return new CursorStream(this);
+}
+
+/**
+ * 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]);
+ this.db._executeQueryCommand(command, {read:self.read, raw:self.raw}, null);
+ } catch(err) {}
+ }
+
+ // 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;
+
+/**
+ * @ignore
+ * @api private
+ */
+exports.Cursor = Cursor;
diff --git a/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/cursorstream.js b/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/cursorstream.js
new file mode 100644
index 0000000..fd2ff65
--- /dev/null
+++ b/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/cursorstream.js
@@ -0,0 +1,141 @@
+/**
+ * Module dependecies.
+ */
+var Stream = require('stream').Stream;
+
+/**
+ * CursorStream
+ *
+ * Returns a stream interface for the **cursor**.
+ *
+ * Events
+ * - **data** {function(item) {}} the data event triggers when a document is ready.
+ * - **error** {function(err) {}} the error event triggers if an error happens.
+ * - **end** {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) {
+ if(!(this instanceof CursorStream)) return new CursorStream(cursor);
+
+ Stream.call(this);
+
+ this.readable = true;
+ this.paused = false;
+ this._cursor = cursor;
+ this._destroyed = null;
+
+ // 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;
+
+ // nextTick is necessary to avoid stack overflows when
+ // dealing with large result sets.
+ process.nextTick(function () {
+ 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) return this.destroy();
+
+ this.emit('data', doc);
+ this._next();
+}
+
+/**
+ * Pauses the stream.
+ *
+ * @api public
+ */
+CursorStream.prototype.pause = function () {
+ this.paused = true;
+}
+
+/**
+ * Resumes the stream.
+ *
+ * @api public
+ */
+CursorStream.prototype.resume = function () {
+ this.paused = false;
+ this._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/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/db.js b/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/db.js
new file mode 100644
index 0000000..981377c
--- /dev/null
+++ b/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/db.js
@@ -0,0 +1,1835 @@
+/**
+ * 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').ReplSet,
+ Cursor = require('./cursor').Cursor,
+ EventEmitter = require('events').EventEmitter,
+ inherits = require('util').inherits,
+ crypto = require('crypto');
+
+/**
+ * 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 = {};
+}
+
+/**
+ * @ignore
+ */
+inherits(CallbackStore, EventEmitter);
+
+/**
+ * Create a new Db instance.
+ *
+ * Options
+ * - **strict** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, execute insert with a getLastError command returning the result of the insert command.
+ * - **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.
+ * - **slaveOk** {Boolean, default:false}, allow reads from secondaries.
+ * - **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.
+ * - **reaper** {Boolean, default:false}, enables the reaper, timing out calls that never return.
+ * - **reaperInterval** {Number, default:10000}, number of miliseconds between reaper wakups.
+ * - **reaperTimeout** {Number, default:30000}, the amount of time before a callback times out.
+ * - **retryMiliSeconds** {Number, default:5000}, number of miliseconds between retries.
+ * - **numberOfRetries** {Number, default:5}, number of retries off connection.
+ *
+ * @class Represents a Collection
+ * @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);
+ 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 && typeof this.serverConfig == 'object' && 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;
+ }
+
+ // 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 : new 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]);
+ // Backward compatibility to access types
+ this.bson_deserializer = bsonLib;
+ this.bson_serializer = bsonLib;
+ } 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(err);
+ }
+
+ // 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 strict
+ this.strict = this.options.strict == null ? false : this.options.strict;
+ this.notReplied ={};
+ this.isInitializing = true;
+ this.auths = [];
+ this.openCalled = false;
+
+ // Command queue, keeps a list of incoming commands that need to be executed once the connection is up
+ this.commands = [];
+
+ // Contains all the callbacks
+ this._callBackStore = new CallbackStore();
+
+ // 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) {}};
+ // Allow slaveOk
+ this.slaveOk = this.options["slave_ok"] == null ? false : this.options["slave_ok"];
+
+ var self = this;
+ // Associate the logger with the server config
+ this.serverConfig.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);
+ }
+
+ // Reaper enable setting
+ this.reaperEnabled = this.options.reaper != null ? this.options.reaper : false;
+ this._lastReaperTimestamp = new Date().getTime();
+
+ // Retry information
+ this.retryMiliSeconds = this.options.retryMiliSeconds != null ? this.options.retryMiliSeconds : 5000;
+ this.numberOfRetries = this.options.numberOfRetries != null ? this.options.numberOfRetries : 5;
+
+ // Reaper information
+ this.reaperInterval = this.options.reaperInterval != null ? this.options.reaperInterval : 10000;
+ this.reaperTimeout = this.options.reaperTimeout != null ? this.options.reaperTimeout : 30000;
+
+ // get self
+ var self = this;
+};
+
+/**
+ * The reaper cleans up any callbacks that have not returned inside the space set by
+ * the parameter reaperTimeout, it will only attempt to reap if the time since last reap
+ * is bigger or equal to the reaperInterval value
+ * @ignore
+ */
+var reaper = function(dbInstance, reaperInterval, reaperTimeout) {
+ // Get current time, compare to reaper interval
+ var currentTime = new Date().getTime();
+ // Now calculate current time difference to check if it's time to reap
+ if((currentTime - dbInstance._lastReaperTimestamp) >= reaperInterval) {
+ // Save current timestamp for next reaper iteration
+ dbInstance._lastReaperTimestamp = currentTime;
+ // Get all non-replied to messages
+ var keys = Object.keys(dbInstance._callBackStore._notReplied);
+ // Iterate over all callbacks
+ for(var i = 0; i < keys.length; i++) {
+ // Fetch the current key
+ var key = keys[i];
+ // Get info element
+ var info = dbInstance._callBackStore._notReplied[key];
+ // If it's timed out let's remove the callback and return an error
+ if((currentTime - info.start) > reaperTimeout) {
+ // Cleanup
+ delete dbInstance._callBackStore._notReplied[key];
+ // Perform callback in next Tick
+ process.nextTick(function() {
+ dbInstance._callBackStore.emit(key, new Error("operation timed out"), null);
+ });
+ }
+ }
+ // Return reaping was done
+ return true;
+ } else {
+ // No reaping done
+ return false;
+ }
+}
+
+/**
+ * @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");
+
+ 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 returns index information.
+ * @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");
+ }
+
+ // 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.connect(self, {firstCall: true}, function(err, result) {
+ if(err != null) {
+ // Return error from connection
+ return callback(err, null);
+ }
+ // Set the status of the server
+ self._state = 'connected';
+ // Callback
+ return callback(null, self);
+ });
+ } else {
+ return callback(Error("Server parameter must be of type Server or ReplSet"), null);
+ }
+};
+
+/**
+ * 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;
+ // Create a new db instance
+ var newDbInstance = new Db(dbName, this.serverConfig, options);
+ // Add the instance to the list of approved db instances
+ var allServerInstances = this.serverConfig.allServerInstances();
+ // Add ourselves to all server callback instances
+ for(var i = 0; i < allServerInstances.length; i++) {
+ var server = allServerInstances[i];
+ server.dbInstances.push(newDbInstance);
+ }
+ // Return new db object
+ return newDbInstance;
+}
+
+/**
+ * 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] returns the results.
+ * @return {null}
+ * @api public
+ */
+Db.prototype.close = function(forceClose, callback) {
+ var self = this;
+ // Unpack calls
+ var args = Array.prototype.slice.call(arguments, 0);
+ callback = args.pop();
+ // Ensure we force close all connections
+ this._applicationClosed = args.length ? args.shift() : false;
+ // Remove all listeners and close the connection
+ this.serverConfig.close(function(err, result) {
+ // Emit the close event
+ if(typeof callback !== 'function') self.emit("close");
+
+ // Emit close event across all db instances sharing the sockets
+ var allServerInstances = self.serverConfig.allServerInstances();
+ // Fetch the first server instance
+ if(Array.isArray(allServerInstances) && allServerInstances.length > 0) {
+ var server = allServerInstances[0];
+ // For all db instances signal all db instances
+ if(Array.isArray(server.dbInstances) && server.dbInstances.length > 1) {
+ for(var i = 0; i < server.dbInstances.length; i++) {
+ var dbInstance = server.dbInstances[i];
+ // Check if it's our current db instance and skip if it is
+ if(dbInstance.databaseName !== self.databaseName && dbInstance.tag !== self.tag) {
+ server.dbInstances[i].emit("close");
+ }
+ }
+ }
+ }
+
+ // Remove all listeners
+ self.removeAllEventListeners();
+ // 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 returns option results.
+ * @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
+ *
+ * @param {String} [collectionName] the collection name we wish to filter by.
+ * @param {Function} callback returns option results.
+ * @return {null}
+ * @api public
+ */
+Db.prototype.collectionNames = function(collectionName, callback) {
+ if(callback == null && typeof collectionName == 'function') { callback = collectionName; collectionName = null; }
+ var self = this;
+ // 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 = [];
+ // Remove any collections that are not part of the db or a system db signed with $
+ documents.forEach(function(document) {
+ if(!(document.name.indexOf(self.databaseName) == -1 || document.name.indexOf('$') != -1))
+ filtered_documents.push(document);
+ });
+ // Return filtered items
+ callback(null, filtered_documents);
+ });
+ });
+};
+
+/**
+ * Fetch a specific collection (containing the actual collection information)
+ *
+ * Options
+ * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB.
+ * - **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.
+ *
+ * @param {String} collectionName the collection name we wish to access.
+ * @param {Object} [options] returns option results.
+ * @param {Function} [callback] returns the results.
+ * @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.safe || this.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 strict 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 returns the results.
+ * @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 returns the results.
+ * @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'];
+ }
+
+ // Iterate through all the fields of the index
+ new Cursor(this, new Collection(this, DbCommand.SYSTEM_COMMAND_COLLECTION), selector, options, 0, -1).nextObject(function(err, result) {
+ if(err != null) return callback(err, null);
+
+ if(result.ok == 1) {
+ callback(null, result.retval);
+ } else {
+ callback(new Error("eval failed: " + result.errmsg), null); return;
+ }
+ });
+};
+
+/**
+ * Dereference a dbref, against a db
+ *
+ * @param {DBRef} dbRef db reference object we wish to resolve.
+ * @param {Function} callback returns the results.
+ * @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
+ db.collection(dbRef.namespace, function(err, collection) {
+ if(err != null) return callback(err, null);
+
+ 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 returns the results.
+ * @return {null}
+ * @api public
+ */
+Db.prototype.logout = function(callback) {
+ var self = this;
+ // Let's generate the logout command object
+ var logoutCommand = DbCommand.logoutCommand(self, {logout:1});
+ self._executeQueryCommand(logoutCommand, {onAll:true}, function(err, result) {
+ // Reset auth
+ self.auths = [];
+ // Handle any errors
+ if(err == null && result.documents[0].ok == 1) {
+ callback(null, true);
+ } else {
+ err != null ? callback(err, false) : callback(new Error(result.documents[0].errmsg), false);
+ }
+ });
+}
+
+/**
+ * Authenticate a user against the server.
+ *
+ * @param {String} username username.
+ * @param {String} password password.
+ * @param {Function} callback returns the results.
+ * @return {null}
+ * @api public
+ */
+Db.prototype.authenticate = function(username, password, callback) {
+ var self = this;
+
+ // Push the new auth if we have no previous record
+ self.auths = [{'username':username, 'password':password}];
+ // Get the amount of connections in the pool to ensure we have authenticated all comments
+ var numberOfConnections = this.serverConfig.allRawConnections().length;
+ var errorObject = null;
+
+ // Execute all four
+ this._executeQueryCommand(DbCommand.createGetNonceCommand(self), {onAll:true}, 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
+ self._executeQueryCommand(DbCommand.createAuthenticationCommand(self, username, password, nonce), {connection:connection}, function(err, result) {
+ // Ensure we save any error
+ if(err) {
+ errorObject = err;
+ } else if(result.documents[0].err != null || result.documents[0].errmsg != null){
+ errorObject = self.wrap(result.documents[0]);
+ }
+
+ // Count down
+ numberOfConnections = numberOfConnections - 1;
+
+ // If we are done with the callbacks return
+ if(numberOfConnections <= 0) {
+ if(errorObject == null && result.documents[0].ok == 1) {
+ callback(errorObject, true);
+ } else {
+ callback(errorObject, false);
+ }
+ }
+ });
+ }
+ });
+};
+
+/**
+ * Add a user to the database.
+ *
+ * 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 returns the results.
+ * @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() : {};
+
+ // Figure out the safe mode settings
+ var safe = self.strict != null && self.strict == false ? true : self.strict;
+ // 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 ? true : safe;
+
+ // 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
+ this.collection(DbCommand.SYSTEM_USER_COLLECTION, function(err, collection) {
+ collection.find({user: username}).toArray(function(err, documents) {
+ // We got an error (f.ex not authorized)
+ if(err != null) return callback(err, null);
+ // We have a user, let's update the password
+ if(documents.length > 0) {
+ collection.update({user: username},{user: username, pwd: userPassword}, {safe:safe}, function(err, results) {
+ callback(err, documents);
+ });
+ } else {
+ collection.insert({user: username, pwd: userPassword}, {safe:safe}, function(err, documents) {
+ callback(err, documents);
+ });
+ }
+ });
+ });
+};
+
+/**
+ * Remove a user from a database
+ *
+ * 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 returns the results.
+ * @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.strict != null && self.strict == false ? true : self.strict;
+ // 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 ? true : safe;
+
+ // Fetch a user collection
+ this.collection(DbCommand.SYSTEM_USER_COLLECTION, function(err, collection) {
+ collection.findOne({user: username}, function(err, user) {
+ if(user != null) {
+ collection.remove({user: username}, {safe:safe}, 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
+ * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB.
+ * - **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.
+ * - **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:false}, create an index on the _id field of the document, not created automatically on capped collections.
+ *
+ * @param {String} collectionName the collection name we wish to access.
+ * @param {Object} [options] returns option results.
+ * @param {Function} callback returns the results.
+ * @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.strict != null && self.strict == false ? true : self.strict;
+ // 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 ? true : 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 strict mode) or return the existing collection
+ if(found && ((options && options.safe) || self.strict)) {
+ return callback(new Error("Collection " + collectionName + " already exists. Currently in strict 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}, function(err, result) {
+ var document = result.documents[0];
+ // If we have no error let's return the collection
+ if(err == null && document.ok == 1) {
+ try {
+ var collection = new Collection(self, collectionName, self.pkFactory, options);
+ } catch(err) {
+ return callback(err, null);
+ }
+ return callback(null, collection);
+ } else {
+ err != null ? callback(err, null) : callback(self.wrap(document), null);
+ }
+ });
+ });
+};
+
+/**
+ * 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 returns the results.
+ * @return {null}
+ * @api public
+ */
+Db.prototype.command = function(selector, callback) {
+ var cursor = new Cursor(this, new Collection(this, DbCommand.SYSTEM_COMMAND_COLLECTION), selector, {}, 0, -1, null, null, null, null, QueryCommand.OPTS_NO_CURSOR_TIMEOUT);
+ cursor.nextObject(callback);
+};
+
+/**
+ * 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 returns the results.
+ * @return {null}
+ * @api public
+ */
+Db.prototype.dropCollection = function(collectionName, callback) {
+ var self = this;
+
+ // Drop the collection
+ this._executeQueryCommand(DbCommand.createDropCollectionCommand(this, collectionName), function(err, result) {
+ if(err == null && result.documents[0].ok == 1) {
+ if(callback != null) return callback(null, true);
+ } else {
+ if(callback != null) err != null ? callback(err, null) : callback(self.wrap(result.documents[0]), null);
+ }
+ });
+};
+
+/**
+ * Rename a collection.
+ *
+ * @param {String} fromCollection the name of the current collection we wish to rename.
+ * @param {String} toCollection the new name of the collection.
+ * @param {Function} callback returns the results.
+ * @return {null}
+ * @api public
+ */
+Db.prototype.renameCollection = function(fromCollection, toCollection, callback) {
+ var self = this;
+
+ // Execute the command, return the new renamed collection if successful
+ this._executeQueryCommand(DbCommand.createRenameCollectionCommand(this, fromCollection, toCollection), function(err, result) {
+ if(err == null && result.documents[0].ok == 1) {
+ if(callback != null) return callback(null, new Collection(self, toCollection, self.pkFactory));
+ } else {
+ if(callback != null) err != null ? callback(err, null) : callback(self.wrap(result.documents[0]), null);
+ }
+ });
+};
+
+/**
+ * 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 returns the results.
+ * @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 returns the results.
+ * @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, callback);
+};
+
+/**
+ * Runs a command on the database as admin.
+ * @ignore
+ * @api private
+ */
+Db.prototype.executeDbAdminCommand = function(command_hash, options, callback) {
+ if(callback == null) { callback = options; options = {}; }
+ this._executeQueryCommand(DbCommand.createAdminDbCommand(this, command_hash), options, callback);
+};
+
+/**
+ * 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 returns the results.
+ * @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) {
+ callback(err, error.documents);
+ });
+};
+
+/**
+ * Creates an index on the collection.
+ *
+ * Options
+ * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB.
+ * - **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.
+ *
+ * @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 for results.
+ * @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;
+
+ // Collect errorOptions
+ var errorOptions = options.safe != null ? options.safe : null;
+ errorOptions = errorOptions == null && self.strict != null ? self.strict : errorOptions;
+
+ // If we have a write concern set and no callback throw error
+ if(errorOptions != null && errorOptions != false && (typeof callback !== 'function' && typeof options !== 'function')) throw new Error("safe cannot be used without a 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(errorOptions && errorOptions != false) {
+ // 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(self.wrap(result[0]));
+ } else {
+ callback(null, command.documents[0].name);
+ }
+ });
+ } 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
+ * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a
+ * - **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.
+ *
+ * @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 for results.
+ * @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 = {};
+ }
+
+ // Collect errorOptions
+ var errorOptions = options.safe != null ? options.safe : null;
+ errorOptions = errorOptions == null && self.strict != null ? self.strict : errorOptions;
+
+ // If we have a write concern set and no callback throw error
+ if(errorOptions != null && errorOptions != false && (typeof callback !== 'function' && typeof options !== 'function')) throw new Error("safe cannot be used without a 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(errorOptions && errorOptions != false) {
+ // 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]];
+ }
+ }
+
+ 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(self.wrap(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.
+ *
+ * @param {Function} callback for results.
+ * @return {null}
+ * @api public
+ */
+Db.prototype.cursorInfo = function(callback) {
+ this._executeQueryCommand(DbCommand.createDbSlaveOkCommand(this, {'cursorInfo':1}), function(err, result) {
+ callback(err, result.documents[0]);
+ });
+};
+
+/**
+ * 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 for results.
+ * @return {null}
+ * @api public
+ */
+Db.prototype.dropIndex = function(collectionName, indexName, callback) {
+ this._executeQueryCommand(DbCommand.createDropIndexCommand(this, collectionName, indexName), 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 returns the results.
+ * @api public
+**/
+Db.prototype.reIndex = function(collectionName, callback) {
+ this._executeQueryCommand(DbCommand.createReIndexCommand(this, collectionName), function(err, result) {
+ if(err != null) {
+ callback(err, false);
+ } else if(result.documents[0].errmsg == null) {
+ callback(null, true);
+ } else {
+ callback(new Error(result.documents[0].errmsg), false);
+ }
+ });
+};
+
+/**
+ * Retrieves this collections index info.
+ *
+ * Options
+ * - **full** {Boolean, default:false}, returns the full raw index information.
+ *
+ * @param {String} collectionName the name of the collection.
+ * @param {Object} [options] additional options during update.
+ * @param {Function} callback returns the index information.
+ * @return {null}
+ * @api public
+ */
+Db.prototype.indexInformation = function(collectionName, options, callback) {
+ // Unpack calls
+ /*var args = Array.prototype.slice.call(arguments, 0);
+ callback = args.pop();
+ collectionName = args.length ? args.shift() : null;
+ options = args.length ? args.shift() : {};*/
+
+ 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)} : {};
+ // Iterate through all the fields of the index
+ new Cursor(this, new Collection(this, DbCommand.SYSTEM_INDEX_COLLECTION), selector).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 returns the index information.
+ * @return {null}
+ * @api public
+ */
+Db.prototype.dropDatabase = function(callback) {
+ var self = this;
+
+ this._executeQueryCommand(DbCommand.createDropDatabaseCommand(this), function(err, result) {
+ if (err == null && result.documents[0].ok == 1) {
+ callback(null, true);
+ } else {
+ if (err) {
+ callback(err, false);
+ } else {
+ callback(self.wrap(result.documents[0]), false);
+ }
+ }
+ });
+};
+
+/**
+ * Register a handler
+ * @ignore
+ * @api private
+ */
+Db.prototype._registerHandler = function(db_command, raw, connection, callback) {
+ // If we have an array of commands, chain them
+ var chained = Array.isArray(db_command);
+
+ // If they are chained we need to add a special handler situation
+ if(chained) {
+ // List off chained id's
+ var chainedIds = [];
+ // Add all id's
+ for(var i = 0; i < db_command.length; i++) chainedIds.push(db_command[i].getRequestId().toString());
+
+ // Register all the commands together
+ for(var i = 0; i < db_command.length; i++) {
+ var command = db_command[i];
+ // Add the callback to the store
+ this._callBackStore.once(command.getRequestId(), callback);
+ // Add the information about the reply
+ this._callBackStore._notReplied[command.getRequestId().toString()] = {start: new Date().getTime(), 'raw': raw, chained:chainedIds, connection:connection};
+ }
+ } else {
+ // 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};
+ }
+}
+
+/**
+ *
+ * @ignore
+ * @api private
+ */
+Db.prototype._callHandler = function(id, document, err) {
+ // 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];
+ // Emit to the callback of the object
+ this._callBackStore.emit(id, err, document, info.connection);
+ }
+}
+
+/**
+ *
+ * @ignore
+ * @api private
+ */
+Db.prototype._hasHandler = function(id) {
+ // If there is a callback peform it
+ return this._callBackStore.listeners(id).length >= 1;
+}
+
+/**
+ *
+ * @ignore
+ * @api private
+ */
+Db.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 != null) delete this._callBackStore._events[id];
+}
+
+/**
+ *
+ * @ignore
+ * @api private
+ */
+Db.prototype._findHandler = function(id) {
+ var info = this._callBackStore._notReplied[id];
+ // Return the callback
+ return {info:info, callback:(this._callBackStore.listeners(id).length >= 1)}
+}
+
+/**
+ * @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;
+
+ // If we got a callback object
+ if(typeof callback === 'function' && !onAll) {
+ // Fetch either a reader or writer dependent on the specified read option
+ var connection = read == true || read === 'secondary' ? self.serverConfig.checkoutReader() : self.serverConfig.checkoutWriter(true);
+ // Override connection if needed
+ connection = specifiedConnection != null ? specifiedConnection : connection;
+ // Ensure we have a valid connection
+ if(connection == null) {
+ return callback(new Error("no open connections"));
+ } else if(connection instanceof Error) {
+ return callback(connection);
+ }
+
+ // Perform reaping of any dead connection
+ if(self.reaperEnabled) reaper(self, self.reaperInterval, self.reaperTimeout);
+
+ // Register the handler in the data structure
+ self._registerHandler(db_command, raw, connection, callback);
+
+ // 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
+ self._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];
+ // Override connection if needed
+ connection = specifiedConnection != null ? specifiedConnection : connection;
+ // 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._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._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 == true || read === 'secondary' ? self.serverConfig.checkoutReader() : self.serverConfig.checkoutWriter();
+ // Override connection if needed
+ connection = specifiedConnection != null ? specifiedConnection : connection;
+ // Ensure we have a valid connection
+ if(connection == null || connection instanceof Error) return null;
+ // Write the message out
+ connection.write(db_command, function(err) {
+ if(err != null) {
+ // Emit the error
+ self.emit("error", err);
+ }
+ });
+ }
+}
+
+/**
+ * @ignore
+ */
+var __retryCommandOnFailure = function(self, retryInMilliseconds, numberOfTimes, command, db_command, options, callback) {
+ if(this._state == 'connected' || this._state == 'disconnected') this._state = 'connecting';
+ // Number of retries done
+ var numberOfRetriesDone = numberOfTimes;
+ // Retry function, execute once
+ var retryFunction = function(_self, _numberOfRetriesDone, _retryInMilliseconds, _numberOfTimes, _command, _db_command, _options, _callback) {
+ _self.serverConfig.connect(_self, {}, function(err, result) {
+ // Adjust the number of retries left
+ _numberOfRetriesDone = _numberOfRetriesDone - 1;
+ // Definitively restart
+ if(err != null && _numberOfRetriesDone > 0) {
+ _self._state = 'connecting';
+ // Force close the current connections
+ _self.serverConfig.close(function(err) {
+ // Retry the connect
+ setTimeout(function() {
+ retryFunction(_self, _numberOfRetriesDone, _retryInMilliseconds, _numberOfTimes, _command, _db_command, _options, _callback);
+ }, _retryInMilliseconds);
+ });
+ } else if(err != null && _numberOfRetriesDone <= 0) {
+ _self._state = 'disconnected';
+ // Force close the current connections
+ _self.serverConfig.close(function(_err) {
+ // Force close the current connections
+ if(typeof _callback == 'function') _callback(err, null);
+ });
+ } else if(err == null && _self.serverConfig.isConnected() == true && Array.isArray(_self.auths) && _self.auths.length > 0) {
+ _self._state = 'connected';
+ // Get number of auths we need to execute
+ var numberOfAuths = _self.auths.length;
+ // Apply all auths
+ for(var i = 0; i < _self.auths.length; i++) {
+ _self.authenticate(_self.auths[i].username, _self.auths[i].password, function(err, authenticated) {
+ numberOfAuths = numberOfAuths - 1;
+
+ // If we have no more authentications to replay
+ if(numberOfAuths == 0) {
+ if(err != null || !authenticated) {
+ if(typeof _callback == 'function') _callback(err, null);
+ return;
+ } else {
+ // Execute command
+ command(_self, _db_command, _options, _callback);
+
+ // Execute any backed up commands
+ process.nextTick(function() {
+ // Execute any backed up commands
+ while(_self.commands.length > 0) {
+ // Fetch the command
+ var command = _self.commands.shift();
+ // Execute based on type
+ if(command['type'] == 'query') {
+ __executeQueryCommand(_self, command['db_command'], command['options'], command['callback']);
+ } else if(command['type'] == 'insert') {
+ __executeInsertCommand(_self, command['db_command'], command['options'], command['callback']);
+ }
+ }
+ });
+ }
+ }
+ });
+ }
+ } else if(err == null && _self.serverConfig.isConnected() == true) {
+ _self._state = 'connected';
+ // Execute command
+ command(_self, _db_command, _options, _callback);
+
+ process.nextTick(function() {
+ // Execute any backed up commands
+ while(_self.commands.length > 0) {
+ // Fetch the command
+ var command = _self.commands.shift();
+ // Execute based on type
+ if(command['type'] == 'query') {
+ __executeQueryCommand(_self, command['db_command'], command['options'], command['callback']);
+ } else if(command['type'] == 'insert') {
+ __executeInsertCommand(_self, command['db_command'], command['options'], command['callback']);
+ }
+ }
+ });
+ } else {
+ _self._state = 'connecting';
+ // Force close the current connections
+ _self.serverConfig.close(function(err) {
+ // Retry the connect
+ setTimeout(function() {
+ retryFunction(_self, _numberOfRetriesDone, _retryInMilliseconds, _numberOfTimes, _command, _db_command, _options, _callback);
+ }, _retryInMilliseconds);
+ });
+ }
+ });
+ };
+
+ // Execute function first time
+ retryFunction(self, numberOfRetriesDone, retryInMilliseconds, numberOfTimes, command, db_command, options, callback);
+}
+
+/**
+ * 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 = {};
+ }
+
+ // 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 the pool is not connected, attemp to reconnect to send the message
+ if(this._state == 'connecting' && this.serverConfig.autoReconnect) {
+ process.nextTick(function() {
+ self.commands.push({type:'query', 'db_command':db_command, 'options':options, 'callback':callback});
+ })
+ } else if(!this.serverConfig.isConnected() && this.serverConfig.autoReconnect) {
+ this._state = 'connecting';
+ // Retry command
+ __retryCommandOnFailure(this, this.retryMiliSeconds, this.numberOfRetries, __executeQueryCommand, db_command, options, callback);
+ } else if(!this.serverConfig.isConnected() && !this.serverConfig.autoReconnect && callback) {
+ // Fire an error to the callback if we are not connected and don't do reconnect
+ callback(new Error("no open connections"), null);
+ } else {
+ __executeQueryCommand(self, db_command, options, callback)
+ }
+};
+
+/**
+ * @ignore
+ */
+var __executeInsertCommand = function(self, db_command, options, callback) {
+ // Always checkout a writer for this kind of operations
+ var connection = self.serverConfig.checkoutWriter();
+ // Get strict 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);
+ }
+
+ // We are expecting a check right after the actual operation
+ if(safe != null && safe != false) {
+ // 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._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);
+
+ // 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 reaping
+ if(self.reaperEnabled) reaper(self, self.reaperInterval, self.reaperTimeout);
+ // Perform the callback
+ callback(err, null);
+ } else if(typeof callback === 'function'){
+ // Call the handler with an error
+ self._callHandler(db_command[1].getRequestId(), null, err);
+ } else {
+ 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 (typeof callback === 'undefined') {
+ callback = options;
+ 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 the pool is not connected, attemp to reconnect to send the message
+ if(self._state == 'connecting' && this.serverConfig.autoReconnect) {
+ process.nextTick(function() {
+ self.commands.push({type:'insert', 'db_command':db_command, 'options':options, 'callback':callback});
+ })
+ } else if(!this.serverConfig.isConnected() && this.serverConfig.autoReconnect) {
+ this._state = 'connecting';
+ // Retry command
+ __retryCommandOnFailure(this, this.retryMiliSeconds, this.numberOfRetries, __executeInsertCommand, db_command, options, callback);
+ } else if(!this.serverConfig.isConnected() && !this.serverConfig.autoReconnect && callback) {
+ // Fire an error to the callback if we are not connected and don't do reconnect
+ if(callback) 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
+ * @ignore
+ * @api private
+ */
+Db.prototype.wrap = function(error) {
+ var msg = error.err || error.errmsg || error;
+ var e = new Error(msg);
+ e.name = 'MongoError';
+
+ // Get all object keys
+ var keys = Object.keys(error);
+ // Populate error object with properties
+ for(var i = 0; i < keys.length; i++) {
+ e[keys[i]] = error[keys[i]];
+ }
+
+ return e;
+}
+
+/**
+ * Default URL
+ *
+ * @classconstant DEFAULT_URL
+ **/
+Db.DEFAULT_URL = 'mongodb://localhost:27017/default';
+
+/**
+ * Connect to MongoDB using a url as documented at
+ *
+ * www.mongodb.org/display/DOCS/Connections
+ *
+ * Options
+ * - **uri_decode_auth** {Boolean, default:false} uri decode the user name and password for authentication
+ *
+ * @param {String} url connection url for MongoDB.
+ * @param {Object} [options] optional options for insert command
+ * @param {Function} callback callback returns the initialized db.
+ * @return {null}
+ * @api public
+ */
+Db.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 || {};
+ var serverOptions = options.server || {};
+ var replSetServersOptions = options.replSet || options.replSetServers || {};
+ var dbOptions = options.db || {};
+
+ var urlRE = new RegExp('^mongo(?:db)?://(?:|([^@/]*)@)([^@/]*)(?:|/([^?]*)(?:|\\?([^?]*)))$');
+ var match = (url || Db.DEFAULT_URL).match(urlRE);
+ if (!match)
+ throw Error("URL must be in the format mongodb://user:pass@host:port/dbname");
+
+ var authPart = match[1] || '';
+ var auth = authPart.split(':', 2);
+ if(options['uri_decode_auth']){
+ auth[0] = decodeURIComponent(auth[0]);
+ if(auth[1]){
+ auth[1] = decodeURIComponent(auth[1]);
+ }
+ }
+ var hostPart = match[2];
+ var dbname = match[3] || 'default';
+ var urlOptions = (match[4] || '').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];
+
+ // Server options:
+ if (name == 'slaveOk' || name == 'slave_ok')
+ serverOptions.slave_ok = (value == 'true');
+ if (name == 'poolSize')
+ serverOptions.poolSize = Number(value);
+ if (name == 'autoReconnect' || name == 'auto_reconnect')
+ serverOptions.auto_reconnect = (value == 'true');
+ if (name == 'ssl' || name == 'ssl')
+ serverOptions.ssl = (value == 'true');
+
+ // ReplSet options:
+ if (name == 'replicaSet' || name == 'rs_name')
+ replSetServersOptions.rs_name = value;
+ if (name == 'reconnectWait')
+ replSetServersOptions.reconnectWait = Number(value);
+ if (name == 'retries')
+ replSetServersOptions.retries = Number(value);
+ if (name == 'readSecondary' || name == 'read_secondary')
+ replSetServersOptions.read_secondary = (value == 'true');
+
+ // DB options:
+ if (name == 'safe')
+ dbOptions.safe = (value == 'true');
+ // Not supported by Db: safe, w, wtimeoutMS, fsync, journal, connectTimeoutMS, socketTimeoutMS
+ if (name == 'nativeParser' || name == 'native_parser')
+ dbOptions.native_parser = (value == 'true');
+ if (name == 'strict')
+ dbOptions.strict = (value == 'true');
+ });
+
+ var servers = hostPart.split(',').map(function(h) {
+ var hostPort = h.split(':', 2);
+ return new Server(hostPort[0] || 'localhost', hostPort[1] != null ? parseInt(hostPort[1]) : 27017, serverOptions);
+ });
+
+ var server;
+ if (servers.length == 1) {
+ server = servers[0];
+ } else {
+ server = new ReplSet(servers, replSetServersOptions);
+ }
+
+ var db = new Db(dbname, server, dbOptions);
+ if(options.noOpen)
+ return db;
+
+ // If callback is null throw an exception
+ if(callback == null) throw new Error("no callback function provided");
+
+ db.open(function(err, db){
+ if(err == null && authPart){
+ db.authenticate(auth[0], auth[1], function(err, success){
+ if(success){
+ callback(null, db);
+ } else {
+ callback(err ? err : new Error('Could not authenticate user ' + auth[0]), db);
+ }
+ });
+ } else {
+ callback(err, db);
+ }
+ });
+}
+
+/**
+ * State of the db connection
+ * @ignore
+ */
+Object.defineProperty(Db.prototype, "state", { enumerable: true
+ , get: function () {
+ return this.serverConfig._serverState;
+ }
+});
+
+/**
+ * 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/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/gridfs/chunk.js b/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/gridfs/chunk.js
new file mode 100644
index 0000000..40f1bfd
--- /dev/null
+++ b/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/gridfs/chunk.js
@@ -0,0 +1,209 @@
+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) {
+ if(!(this instanceof Chunk)) return new Chunk(file, mongoObject);
+
+ this.file = file;
+ var self = this;
+ var mongoObjectFinal = mongoObject == null ? {} : mongoObject;
+
+ 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 + 1) >= 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) {
+ collection.remove({'_id':self.objectId}, {safe:true}, function(err, result) {
+ if(self.data.length() > 0) {
+ self.buildMongoObject(function(mongoObject) {
+ collection.insert(mongoObject, {safe:true}, function(err, collection) {
+ callback(null, 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 = {'_id': this.objectId,
+ 'files_id': this.file.fileId,
+ 'n': this.chunkNumber,
+ 'data': this.data};
+ 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/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/gridfs/grid.js b/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/gridfs/grid.js
new file mode 100644
index 0000000..d42c3d6
--- /dev/null
+++ b/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/gridfs/grid.js
@@ -0,0 +1,98 @@
+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
+ *
+ * @param {Buffer} data buffer with Binary Data.
+ * @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
+ */
+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'];
+ // Create gridstore
+ var gridStore = new GridStore(this.db, 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 {ObjectID} id ObjectID for file.
+ * @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
+ */
+Grid.prototype.get = function(id, callback) {
+ // Validate that we have a valid ObjectId
+ if(!(id instanceof ObjectID)) return callback(new Error("Not a valid ObjectID", null));
+ // Create gridstore
+ var gridStore = new GridStore(this.db, id, "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 {ObjectID} id ObjectID for file.
+ * @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
+ */
+Grid.prototype.delete = function(id, callback) {
+ // Validate that we have a valid ObjectId
+ if(!(id instanceof ObjectID)) return callback(new Error("Not a valid ObjectID", null));
+ // 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/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/gridfs/gridstore.js b/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/gridfs/gridstore.js
new file mode 100644
index 0000000..e3c1aa6
--- /dev/null
+++ b/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/gridfs/gridstore.js
@@ -0,0 +1,1092 @@
+/**
+ * @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'),
+ util = require('util'),
+ ReadStream = require('./readstream').ReadStream;
+
+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}**.
+ * - **chunk_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.
+ *
+ * @class Represents the GridStore.
+ * @param {Db} db A database instance to interact with.
+ * @param {ObjectID} id an unique ObjectID for this file
+ * @param {String} [filename] optional a 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. Recognized keys:
+ * @return {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;
+ var _filename = filename;
+
+ if(typeof filename == 'string' && typeof mode == 'string') {
+ _filename = filename;
+ } else if(typeof filename == 'string' && typeof mode == 'object' && mode != null) {
+ var _mode = mode;
+ mode = filename;
+ options = _mode;
+ _filename = id;
+ } else if(typeof filename == 'string' && mode == null) {
+ mode = filename;
+ _filename = id;
+ }
+
+ // set grid referencetype
+ this.referenceBy = typeof id == 'string' ? 0 : 1;
+ this.filename = _filename;
+ this.fileId = typeof id == 'string' ? new ObjectID() : id;
+
+ // Set up the rest
+ this.mode = mode == null ? "r" : mode;
+ this.options = options == null ? {} : options;
+ this.root = this.options['root'] == null ? exports.GridStore.DEFAULT_ROOT_COLLECTION : this.options['root'];
+ this.position = 0;
+ // Set default chunk size
+ this.internalChunkSize = this.options['chunkSize'] == null ? Chunk.DEFAULT_CHUNK_SIZE : this.options['chunkSize'];
+ // Previous chunk size
+ this.previousChunkSize = 0;
+}
+
+/**
+ * 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) {
+ // Get chunk collection
+ self.chunkCollection(function(err, chunkCollection) {
+ // Ensure index on chunk collection
+ chunkCollection.ensureIndex([['files_id', 1], ['n', 1]], function(err, index) {
+ _open(self, callback);
+ });
+ });
+ });
+ } else {
+ _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, function(err, cursor) {
+ // Fetch the file
+ cursor.nextObject(function(err, doc) {
+ // Check if the collection for the files exists otherwise prepare the new one
+ if(doc != null) {
+ self.fileId = doc._id;
+ 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 {
+ // self.fileId =
+ // self.fileId = self.fileId instanceof ObjectID ? self.fileId : new ObjectID();
+ 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;
+ }
+
+ // Process the mode of the object
+ if(self.mode == "r") {
+ nthChunk(self, 0, function(err, chunk) {
+ self.currentChunk = chunk;
+ self.position = 0;
+ callback(null, self);
+ });
+ } else if(self.mode == "w") {
+ // Delete any existing chunks
+ deleteChunks(self, function(err, result) {
+ self.currentChunk = new Chunk(self, {'n':0});
+ 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) {
+ // Set the current chunk
+ self.currentChunk = chunk == null ? new Chunk(self, {'n':0}) : 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) {
+ // No file exists set up write mode
+ if(self.mode == "w") {
+ // Delete any existing chunks
+ deleteChunks(self, function(err, result) {
+ self.currentChunk = new Chunk(self, {'n':0});
+ 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) {
+ // Set the current chunk
+ self.currentChunk = chunk == null ? new Chunk(self, {'n':0}) : 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);
+ });
+ }
+ });
+ }
+ });
+};
+
+/**
+ * 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', 0666, function (err, fd) {
+ // TODO Handle err
+ self.writeFile(fd, callback);
+ });
+ return;
+ }
+
+ self.open(function (err, self) {
+ fs.fstat(file, function (err, stats) {
+ 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) {
+ offset = offset + bytesRead;
+ // Create a new chunk for the data
+ var chunk = new Chunk(self, {n:index++});
+ chunk.write(data, function(err, chunk) {
+ chunk.save(function(err, result) {
+ 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) {
+ return callback(null, result);
+ })
+ } else {
+ return process.nextTick(writeChunk);
+ }
+ });
+ });
+ });
+ }
+
+ // Process the first write
+ process.nextTick(writeChunk);
+ });
+ });
+};
+
+/**
+ * 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(data, close, callback) {
+ // If we have a buffer write it using the writeBuffer method
+ if(Buffer.isBuffer(data)) {
+ return writeBuffer(this, data, close, callback);
+ } else {
+ // Wrap the string in a buffer and write
+ return writeBuffer(this, new Buffer(data, 'binary'), close, callback);
+ }
+};
+
+/**
+ * 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)});
+ 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)});
+ // 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) {
+ 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 = self.previousChunkSize;
+ // 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;
+ }
+
+ // console.log("============================== self.currentChunk.chunkNumber :: " + self.currentChunk.chunkNumber)
+ // console.log("============================== self.currentChunk.position :: " + self.currentChunk.position)
+ // console.log(self.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) {
+ self.collection(function(err, files) {
+ // Build the mongo object
+ if(self.uploadDate != null) {
+ files.remove({'_id':self.fileId}, {safe:true}, function(err, collection) {
+ buildMongoObject(self, function(mongoObject) {
+ files.save(mongoObject, {safe:true}, function(err, doc) {
+ callback(err, mongoObject);
+ });
+ });
+ });
+ } else {
+ self.uploadDate = new Date();
+ buildMongoObject(self, function(mongoObject) {
+ files.save(mongoObject, {safe:true}, function(err, doc) {
+ callback(err, mongoObject);
+ });
+ });
+ }
+ });
+ });
+ } else {
+ self.collection(function(err, files) {
+ self.uploadDate = new Date();
+ buildMongoObject(self, function(mongoObject) {
+ files.save(mongoObject, {safe:true}, function(err, doc) {
+ callback(err, mongoObject);
+ });
+ });
+ });
+ }
+ } else if(self.mode[0] == "r") {
+ callback(null, null);
+ } else {
+ 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) {
+ collection.find({'files_id':self.fileId, 'n':chunkNumber}, function(err, cursor) {
+ cursor.nextObject(function(err, chunk) {
+ var finalChunk = chunk == null ? {} : chunk;
+ callback(null, new Chunk(self, finalChunk));
+ });
+ });
+ });
+};
+
+/**
+ *
+ * @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!==null) {
+ callback(err, false);
+ }
+ collection.remove({'files_id':self.fileId}, {safe:true}, function(err, result) {
+ 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) {
+ callback("at deleteChunks: "+err);
+ return;
+ }
+
+ self.collection(function(err, collection) {
+ if(err!==null) {
+ callback("at collection: "+err);
+ return;
+ }
+
+ collection.remove({'_id':self.fileId}, {safe:true}, function(err, collection) {
+ 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) {
+ 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) {
+ self.currentChunk = new Chunk(self, {'n': 0});
+ self.position = 0;
+ callback(null, self);
+ });
+ } else {
+ self.currentChunk(0, function(err, chunk) {
+ 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 + 1 + 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 = 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 {
+ // console.dir(self.currentChunk)
+ 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(chunk.length() > 0) {
+ self.currentChunk = chunk;
+ self.read(length, finalBuffer, callback);
+ } else {
+ finalBuffer._index > 0 ? callback(null, finalBuffer) : 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;
+ 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;
+ }
+
+ 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(null, self);
+ });
+ };
+
+ if(self.mode[0] == 'w') {
+ self.currentChunk.save(function(err, chunk) {
+ 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(null, 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.
+ *
+ * @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, callback) {
+ var args = Array.prototype.slice.call(arguments, 2);
+ callback = args.pop();
+ rootCollection = args.length ? args.shift() : null;
+
+ // Fetch collection
+ var rootCollectionFinal = rootCollection != null ? rootCollection : GridStore.DEFAULT_ROOT_COLLECTION;
+ db.collection(rootCollectionFinal + ".files", function(err, collection) {
+ // 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, function(err, cursor) {
+ cursor.nextObject(function(err, item) {
+ 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;
+ }
+
+ // 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) {
+ collection.find(function(err, cursor) {
+ cursor.each(function(err, item) {
+ if(item != null) {
+ items.push(byId ? item._id : item.filename);
+ } else {
+ callback(null, 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) {
+ // 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) {
+ gridStore.read(length, function(err, data) {
+ callback(err, data);
+ });
+ });
+ } else {
+ gridStore.read(length, function(err, data) {
+ callback(err, data);
+ });
+ }
+ });
+};
+
+/**
+ * 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) {
+ gridStore.readlines(finalSeperator, function(err, lines) {
+ callback(err, lines);
+ });
+ });
+};
+
+/**
+ * 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], function(result) {
+ if(--tc == 0) {
+ callback(null, self);
+ }
+ });
+ }
+ } else {
+ new GridStore(db, names, "w", options).open(function(err, gridStore) {
+ deleteChunks(gridStore, function(err, result) {
+ gridStore.collection(function(err, collection) {
+ 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;
+ }
+});
+
+/**
+ * @ignore
+ * @api private
+ */
+exports.GridStore = GridStore;
diff --git a/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/gridfs/readstream.js b/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/gridfs/readstream.js
new file mode 100644
index 0000000..2d3e574
--- /dev/null
+++ b/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/gridfs/readstream.js
@@ -0,0 +1,179 @@
+var Stream = require('stream').Stream,
+ util = require('util');
+
+/**
+ * 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.paused = false;
+ this.readable = true;
+ this.pendingChunk = null;
+ this.executing = false;
+
+ var self = this;
+ process.nextTick(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.length() - gstore.currentChunk.position + 1 + self.completedLength) >= self.finalLength) {
+ toRead = self.finalLength - self.completedLength;
+ self.executing = false;
+ last = true;
+ } else {
+ toRead = gstore.currentChunk.length();
+ }
+
+ var data = gstore.currentChunk.readSlice(toRead);
+
+ if(data != null) {
+ 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;
+ if(self.pendingChunk != null) {
+ self.currentChunk = self.pendingChunk;
+ process.nextTick(function() {
+ self._execute();
+ });
+ } else {
+ self.readable = false;
+ self.emit("close");
+ }
+};
+
+exports.ReadStream = ReadStream;
diff --git a/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/index.js b/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/index.js
new file mode 100644
index 0000000..b368fe8
--- /dev/null
+++ b/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/index.js
@@ -0,0 +1,151 @@
+try {
+ exports.BSONPure = require('bson').BSONPure;
+ exports.BSONNative = require('bson').BSONNative;
+} catch(err) {
+ // do nothing
+}
+
+[ 'commands/base_command'
+ , 'commands/db_command'
+ , 'commands/delete_command'
+ , 'commands/get_more_command'
+ , 'commands/insert_command'
+ , 'commands/kill_cursor_command'
+ , 'commands/query_command'
+ , 'commands/update_command'
+ , 'responses/mongo_reply'
+ , 'admin'
+ , 'collection'
+ , 'connection/connection'
+ , 'connection/server'
+ , 'connection/repl_set'
+ , 'cursor'
+ , 'db'
+ , '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;
+});
+
+// Exports all the classes for the PURE JS BSON Parser
+exports.pure = function() {
+ var classes = {};
+ // Map all the classes
+ [ 'commands/base_command'
+ , 'commands/db_command'
+ , 'commands/delete_command'
+ , 'commands/get_more_command'
+ , 'commands/insert_command'
+ , 'commands/kill_cursor_command'
+ , 'commands/query_command'
+ , 'commands/update_command'
+ , 'responses/mongo_reply'
+ , 'admin'
+ , 'collection'
+ , 'connection/connection'
+ , 'connection/server'
+ , 'connection/repl_set'
+ , 'cursor'
+ , 'db'
+ , 'gridfs/grid'
+ , 'gridfs/chunk'
+ , 'gridfs/gridstore'].forEach(function (path) {
+ var module = require('./' + path);
+ for (var i in module) {
+ classes[i] = module[i];
+ }
+ });
+
+ // backwards compat
+ classes.ReplSetServers = exports.ReplSet;
+
+ // Add BSON Classes
+ classes.Binary = require('bson').Binary;
+ classes.Code = require('bson').Code;
+ classes.DBRef = require('bson').DBRef;
+ classes.Double = require('bson').Double;
+ classes.Long = require('bson').Long;
+ classes.MinKey = require('bson').MinKey;
+ classes.MaxKey = require('bson').MaxKey;
+ classes.ObjectID = require('bson').ObjectID;
+ classes.Symbol = require('bson').Symbol;
+ classes.Timestamp = require('bson').Timestamp;
+
+ // Add BSON Parser
+ classes.BSON = require('bson').BSONPure.BSON;
+
+ // Return classes list
+ return classes;
+}
+
+// Exports all the classes for the PURE JS BSON Parser
+exports.native = function() {
+ var classes = {};
+ // Map all the classes
+ [ 'commands/base_command'
+ , 'commands/db_command'
+ , 'commands/delete_command'
+ , 'commands/get_more_command'
+ , 'commands/insert_command'
+ , 'commands/kill_cursor_command'
+ , 'commands/query_command'
+ , 'commands/update_command'
+ , 'responses/mongo_reply'
+ , 'admin'
+ , 'collection'
+ , 'connection/connection'
+ , 'connection/server'
+ , 'connection/repl_set'
+ , 'cursor'
+ , 'db'
+ , 'gridfs/grid'
+ , 'gridfs/chunk'
+ , 'gridfs/gridstore'].forEach(function (path) {
+ var module = require('./' + path);
+ for (var i in module) {
+ classes[i] = module[i];
+ }
+ });
+
+ // Add BSON Classes
+ classes.Binary = require('bson').Binary;
+ classes.Code = require('bson').Code;
+ classes.DBRef = require('bson').DBRef;
+ classes.Double = require('bson').Double;
+ classes.Long = require('bson').Long;
+ classes.MinKey = require('bson').MinKey;
+ classes.MaxKey = require('bson').MaxKey;
+ classes.ObjectID = require('bson').ObjectID;
+ classes.Symbol = require('bson').Symbol;
+ classes.Timestamp = require('bson').Timestamp;
+
+ // backwards compat
+ classes.ReplSetServers = exports.ReplSet;
+
+ // Add BSON Parser
+ classes.BSON = require('bson').BSONNative.BSON;
+
+ // Return classes list
+ return classes;
+}
diff --git a/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/responses/mongo_reply.js b/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/responses/mongo_reply.js
new file mode 100644
index 0000000..74396fa
--- /dev/null
+++ b/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/responses/mongo_reply.js
@@ -0,0 +1,131 @@
+var Long = require('bson').Long;
+
+/**
+ 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;
+ // Just set a doc limit for deserializing
+ var docLimitSize = 1024*20;
+
+ // If our message length is very long, let's switch to process.nextTick for messages
+ if(this.messageLength > docLimitSize) {
+ var batchSize = this.numberReturned;
+ this.documents = new Array(this.numberReturned);
+
+ // Just walk down until we get a positive number >= 1
+ for(var i = 50; i > 0; i--) {
+ if((this.numberReturned/i) >= 1) {
+ batchSize = i;
+ break;
+ }
+ }
+
+ // Actual main creator of the processFunction setting internal state to control the flow
+ var parseFunction = function(_self, _binary_reply, _batchSize, _numberReturned) {
+ var object_index = 0;
+ // Internal loop process that will use nextTick to ensure we yield some time
+ var processFunction = function() {
+ // Adjust batchSize if we have less results left than batchsize
+ if((_numberReturned - object_index) < _batchSize) {
+ _batchSize = _numberReturned - object_index;
+ }
+
+ // If raw just process the entries
+ if(raw) {
+ // Iterate over the batch
+ for(var i = 0; i < _batchSize; i++) {
+ // Are we done ?
+ if(object_index <= _numberReturned) {
+ // Read the size of the bson object
+ var bsonObjectSize = _binary_reply[_self.index] | _binary_reply[_self.index + 1] << 8 | _binary_reply[_self.index + 2] << 16 | _binary_reply[_self.index + 3] << 24;
+ // If we are storing the raw responses to pipe straight through
+ _self.documents[object_index] = binary_reply.slice(_self.index, _self.index + bsonObjectSize);
+ // Adjust binary index to point to next block of binary bson data
+ _self.index = _self.index + bsonObjectSize;
+ // Update number of docs parsed
+ object_index = object_index + 1;
+ }
+ }
+ } else {
+ // Parse documents
+ _self.index = bson.deserializeStream(binary_reply, _self.index, _batchSize, _self.documents, object_index);
+ // Adjust index
+ object_index = object_index + _batchSize;
+ }
+
+ // If we hav more documents process NextTick
+ if(object_index < _numberReturned) {
+ process.nextTick(processFunction);
+ } else {
+ callback(null);
+ }
+ }
+
+ // Return the process function
+ return processFunction;
+ }(this, binary_reply, batchSize, this.numberReturned)();
+ } else {
+ // Let's unpack all the bson documents, deserialize them and store them
+ for(var object_index = 0; object_index < this.numberReturned; object_index++) {
+ // 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)));
+ }
+ // Adjust binary index to point to next block of binary bson data
+ this.index = this.index + bsonObjectSize;
+ }
+
+ callback(null);
+ }
+}
+
+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/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/utils.js b/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/utils.js
new file mode 100644
index 0000000..07a0ab0
--- /dev/null
+++ b/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/utils.js
@@ -0,0 +1,74 @@
+/**
+ * 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];
+}
diff --git a/app/node_modules/mongoskin/node_modules/mongodb/node_modules/bson/.travis.yml b/app/node_modules/mongoskin/node_modules/mongodb/node_modules/bson/.travis.yml
new file mode 100644
index 0000000..90b208a
--- /dev/null
+++ b/app/node_modules/mongoskin/node_modules/mongodb/node_modules/bson/.travis.yml
@@ -0,0 +1,5 @@
+language: node_js
+node_js:
+ - 0.4
+ - 0.6
+ - 0.7 # development version of 0.8, may be unstable
\ No newline at end of file
diff --git a/app/node_modules/mongoskin/node_modules/mongodb/node_modules/bson/Makefile b/app/node_modules/mongoskin/node_modules/mongodb/node_modules/bson/Makefile
new file mode 100644
index 0000000..88b1ddc
--- /dev/null
+++ b/app/node_modules/mongoskin/node_modules/mongodb/node_modules/bson/Makefile
@@ -0,0 +1,31 @@
+NODE = node
+NPM = npm
+NODEUNIT = node_modules/nodeunit/bin/nodeunit
+name = all
+
+total: build_native
+
+test: build_native
+ $(NODEUNIT) ./test/node
+ TEST_NATIVE=TRUE $(NODEUNIT) ./test/node
+
+build_native:
+ $(MAKE) -C ./ext all
+
+build_native_debug:
+ $(MAKE) -C ./ext all_debug
+
+build_native_clang:
+ $(MAKE) -C ./ext clang
+
+build_native_clang_debug:
+ $(MAKE) -C ./ext clang_debug
+
+clean_native:
+ $(MAKE) -C ./ext clean
+
+clean:
+ rm ./ext/bson.node
+ rm -r ./ext/build
+
+.PHONY: total
diff --git a/app/node_modules/mongoskin/node_modules/mongodb/node_modules/bson/README b/app/node_modules/mongoskin/node_modules/mongodb/node_modules/bson/README
new file mode 100644
index 0000000..e69de29
diff --git a/app/node_modules/mongoskin/node_modules/mongodb/node_modules/bson/ext/Makefile b/app/node_modules/mongoskin/node_modules/mongodb/node_modules/bson/ext/Makefile
new file mode 100644
index 0000000..435999e
--- /dev/null
+++ b/app/node_modules/mongoskin/node_modules/mongodb/node_modules/bson/ext/Makefile
@@ -0,0 +1,28 @@
+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/app/node_modules/mongoskin/node_modules/mongodb/node_modules/bson/ext/bson.cc b/app/node_modules/mongoskin/node_modules/mongodb/node_modules/bson/ext/bson.cc
new file mode 100644
index 0000000..18092b9
--- /dev/null
+++ b/app/node_modules/mongoskin/node_modules/mongodb/node_modules/bson/ext/bson.cc
@@ -0,0 +1,2055 @@
+#include
+#include
+#include
+
+#ifdef __clang__
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wunused-parameter"
+#endif
+
+#include
+
+#ifdef __clang__
+#pragma clang diagnostic pop
+#endif
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#include "bson.h"
+
+using namespace v8;
+using namespace node;
+using namespace std;
+
+// BSON DATA TYPES
+const uint32_t BSON_DATA_NUMBER = 1;
+const uint32_t BSON_DATA_STRING = 2;
+const uint32_t BSON_DATA_OBJECT = 3;
+const uint32_t BSON_DATA_ARRAY = 4;
+const uint32_t BSON_DATA_BINARY = 5;
+const uint32_t BSON_DATA_OID = 7;
+const uint32_t BSON_DATA_BOOLEAN = 8;
+const uint32_t BSON_DATA_DATE = 9;
+const uint32_t BSON_DATA_NULL = 10;
+const uint32_t BSON_DATA_REGEXP = 11;
+const uint32_t BSON_DATA_CODE = 13;
+const uint32_t BSON_DATA_SYMBOL = 14;
+const uint32_t BSON_DATA_CODE_W_SCOPE = 15;
+const uint32_t BSON_DATA_INT = 16;
+const uint32_t BSON_DATA_TIMESTAMP = 17;
+const uint32_t BSON_DATA_LONG = 18;
+const uint32_t BSON_DATA_MIN_KEY = 0xff;
+const uint32_t BSON_DATA_MAX_KEY = 0x7f;
+
+const int32_t BSON_INT32_MAX = (int32_t)2147483647L;
+const int32_t BSON_INT32_MIN = (int32_t)(-1) * 2147483648L;
+
+const int64_t BSON_INT64_MAX = ((int64_t)1 << 63) - 1;
+const int64_t BSON_INT64_MIN = (int64_t)-1 << 63;
+
+const int64_t JS_INT_MAX = (int64_t)1 << 53;
+const int64_t JS_INT_MIN = (int64_t)-1 << 53;
+
+static Handle VException(const char *msg) {
+ HandleScope scope;
+ return ThrowException(Exception::Error(String::New(msg)));
+ };
+
+Persistent BSON::constructor_template;
+
+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);
+ // Set up the function on the Class
+ target->ForceSet(String::NewSymbol("BSON"), constructor_template->GetFunction());
+}
+
+// Create a new instance of BSON and assing 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();
+
+ // Setup pre-allocated comparision objects
+ bson->_bsontypeString = Persistent::New(String::New("_bsontype"));
+ bson->_longLowString = Persistent::New(String::New("low_"));
+ bson->_longHighString = Persistent::New(String::New("high_"));
+ bson->_objectIDidString = Persistent::New(String::New("id"));
+ bson->_binaryPositionString = Persistent::New(String::New("position"));
+ bson->_binarySubTypeString = Persistent::New(String::New("sub_type"));
+ bson->_binaryBufferString = Persistent::New(String::New("buffer"));
+ bson->_doubleValueString = Persistent::New(String::New("value"));
+ bson->_symbolValueString = Persistent::New(String::New("value"));
+ bson->_dbRefRefString = Persistent::New(String::New("$ref"));
+ bson->_dbRefIdRefString = Persistent::New(String::New("$id"));
+ bson->_dbRefDbRefString = Persistent::New(String::New("$db"));
+ bson->_dbRefNamespaceString = Persistent::New(String::New("namespace"));
+ bson->_dbRefDbString = Persistent::New(String::New("db"));
+ bson->_dbRefOidString = Persistent::New(String::New("oid"));
+ bson->_toBsonString = Persistent::New(String::New("toBSON"));
+
+ // total number of found classes
+ uint32_t numberOfClasses = 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(String::New("Long"))) {
+ bson->longConstructor = Persistent::New(func);
+ bson->longString = Persistent::New(String::New("Long"));
+ numberOfClasses = numberOfClasses + 1;
+ } else if(functionName->StrictEquals(String::New("ObjectID"))) {
+ bson->objectIDConstructor = Persistent::New(func);
+ bson->objectIDString = Persistent::New(String::New("ObjectID"));
+ numberOfClasses = numberOfClasses + 1;
+ } else if(functionName->StrictEquals(String::New("Binary"))) {
+ bson->binaryConstructor = Persistent::New(func);
+ bson->binaryString = Persistent::New(String::New("Binary"));
+ numberOfClasses = numberOfClasses + 1;
+ } else if(functionName->StrictEquals(String::New("Code"))) {
+ bson->codeConstructor = Persistent::New(func);
+ bson->codeString = Persistent::New(String::New("Code"));
+ numberOfClasses = numberOfClasses + 1;
+ } else if(functionName->StrictEquals(String::New("DBRef"))) {
+ bson->dbrefConstructor = Persistent::New(func);
+ bson->dbrefString = Persistent::New(String::New("DBRef"));
+ numberOfClasses = numberOfClasses + 1;
+ } else if(functionName->StrictEquals(String::New("Symbol"))) {
+ bson->symbolConstructor = Persistent::New(func);
+ bson->symbolString = Persistent::New(String::New("Symbol"));
+ numberOfClasses = numberOfClasses + 1;
+ } else if(functionName->StrictEquals(String::New("Double"))) {
+ bson->doubleConstructor = Persistent::New(func);
+ bson->doubleString = Persistent::New(String::New("Double"));
+ numberOfClasses = numberOfClasses + 1;
+ } else if(functionName->StrictEquals(String::New("Timestamp"))) {
+ bson->timestampConstructor = Persistent::New(func);
+ bson->timestampString = Persistent::New(String::New("Timestamp"));
+ numberOfClasses = numberOfClasses + 1;
+ } else if(functionName->StrictEquals(String::New("MinKey"))) {
+ bson->minKeyConstructor = Persistent::New(func);
+ bson->minKeyString = Persistent::New(String::New("MinKey"));
+ numberOfClasses = numberOfClasses + 1;
+ } else if(functionName->StrictEquals(String::New("MaxKey"))) {
+ bson->maxKeyConstructor = Persistent::New(func);
+ bson->maxKeyString = Persistent::New(String::New("MaxKey"));
+ numberOfClasses = numberOfClasses + 1;
+ }
+ }
+
+ // Check if we have the right number of constructors otherwise throw an error
+ if(numberOfClasses != 10) {
+ // Destroy object
+ delete(bson);
+ // Fire exception
+ 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");
+ }
+}
+
+void BSON::write_int32(char *data, uint32_t value) {
+ // Write the int to the char*
+ memcpy(data, &value, 4);
+}
+
+void BSON::write_double(char *data, double value) {
+ // Write the double to the char*
+ memcpy(data, &value, 8);
+}
+
+void BSON::write_int64(char *data, int64_t value) {
+ // Write the int to the char*
+ memcpy(data, &value, 8);
+}
+
+char *BSON::check_key(Local key) {
+ // Allocate space for they key string
+ char *key_str = (char *)malloc(key->Utf8Length() * sizeof(char) + 1);
+ // Error string
+ char *error_str = (char *)malloc(256 * sizeof(char));
+ // Decode the key
+ ssize_t len = DecodeBytes(key, BINARY);
+ DecodeWrite(key_str, len, key, BINARY);
+ *(key_str + key->Utf8Length()) = '\0';
+ // Check if we have a valid key
+ if(key->Utf8Length() > 0 && *(key_str) == '$') {
+ // Create the string
+ sprintf(error_str, "key %s must not start with '$'", key_str);
+ // Free up memory
+ free(key_str);
+ // Throw exception with string
+ throw error_str;
+ } else if(key->Utf8Length() > 0 && strchr(key_str, '.') != NULL) {
+ // Create the string
+ sprintf(error_str, "key %s must not contain '.'", key_str);
+ // Free up memory
+ free(key_str);
+ // Throw exception with string
+ throw error_str;
+ }
+ // Free allocated space
+ free(key_str);
+ free(error_str);
+ // Return No check key error
+ return NULL;
+}
+
+const char* BSON::ToCString(const v8::String::Utf8Value& value) {
+ return *value ? *value : "";
+}
+
+Handle BSON::decodeDBref(BSON *bson, Local ref, Local oid, Local db) {
+ HandleScope scope;
+ Local argv[] = {ref, oid, db};
+ Handle dbrefObj = bson->dbrefConstructor->NewInstance(3, argv);
+ return scope.Close(dbrefObj);
+}
+
+Handle BSON::decodeCode(BSON *bson, char *code, Handle scope_object) {
+ HandleScope scope;
+
+ Local argv[] = {String::New(code), scope_object->ToObject()};
+ Handle codeObj = bson->codeConstructor->NewInstance(2, argv);
+ return scope.Close(codeObj);
+}
+
+Handle BSON::decodeBinary(BSON *bson, uint32_t sub_type, uint32_t number_of_bytes, char *data) {
+ HandleScope scope;
+
+ // Create a buffer object that wraps the raw stream
+ Buffer *bufferObj = Buffer::New(data, number_of_bytes);
+ // Arguments to be passed to create the binary
+ Handle argv[] = {bufferObj->handle_, Uint32::New(sub_type)};
+ // Return the buffer handle
+ Local bufferObjHandle = bson->binaryConstructor->NewInstance(2, argv);
+ // Close the scope
+ return scope.Close(bufferObjHandle);
+}
+
+Handle BSON::decodeOid(BSON *bson, char *oid) {
+ HandleScope scope;
+
+ // Encode the string (string - null termiating character)
+ Local bin_value = Encode(oid, 12, BINARY)->ToString();
+
+ // Return the id object
+ Local argv[] = {bin_value};
+ Local oidObj = bson->objectIDConstructor->NewInstance(1, argv);
+ return scope.Close(oidObj);
+}
+
+Handle BSON::decodeLong(BSON *bson, char *data, uint32_t index) {
+ HandleScope scope;
+
+ // Decode the integer value
+ int32_t lowBits = 0;
+ int32_t highBits = 0;
+ memcpy(&lowBits, (data + index), 4);
+ memcpy(&highBits, (data + index + 4), 4);
+
+ // Decode 64bit value
+ int64_t value = 0;
+ memcpy(&value, (data + index), 8);
+
+ // If value is < 2^53 and >-2^53
+ if((highBits < 0x200000 || (highBits == 0x200000 && lowBits == 0)) && highBits >= -0x200000) {
+ int64_t finalValue = 0;
+ memcpy(&finalValue, (data + index), 8);
+ return scope.Close(Number::New(finalValue));
+ }
+
+ // Instantiate the js object and pass it back
+ Local argv[] = {Int32::New(lowBits), Int32::New(highBits)};
+ Local longObject = bson->longConstructor->NewInstance(2, argv);
+ return scope.Close(longObject);
+}
+
+Handle BSON::decodeTimestamp(BSON *bson, char *data, uint32_t index) {
+ HandleScope scope;
+
+ // Decode the integer value
+ int32_t lowBits = 0;
+ int32_t highBits = 0;
+ memcpy(&lowBits, (data + index), 4);
+ memcpy(&highBits, (data + index + 4), 4);
+
+ // Build timestamp
+ Local argv[] = {Int32::New(lowBits), Int32::New(highBits)};
+ Handle timestamp_obj = bson->timestampConstructor->NewInstance(2, argv);
+ return scope.Close(timestamp_obj);
+}
+
+// Search for 0 terminated C string and return the string
+char* BSON::extract_string(char *data, uint32_t offset) {
+ char *prt = strchr((data + offset), '\0');
+ if(prt == NULL) return NULL;
+ // Figure out the length of the string
+ uint32_t length = (prt - data) - offset;
+ // Allocate memory for the new string
+ char *string_name = (char *)malloc((length * sizeof(char)) + 1);
+ // Copy the variable into the string_name
+ strncpy(string_name, (data + offset), length);
+ // Ensure the string is null terminated
+ *(string_name + length) = '\0';
+ // Return the unpacked string
+ return string_name;
+}
+
+// Decode a byte
+uint16_t BSON::deserialize_int8(char *data, uint32_t offset) {
+ uint16_t value = 0;
+ value |= *(data + offset + 0);
+ return value;
+}
+
+// Requires a 4 byte char array
+uint32_t BSON::deserialize_int32(char* data, uint32_t offset) {
+ uint32_t value = 0;
+ memcpy(&value, (data + offset), 4);
+ return value;
+}
+
+//------------------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------------------------
+//------------------------------------------------------------------------------------------------
+Handle BSON::BSONDeserialize(const Arguments &args) {
+ HandleScope scope;
+
+ // Ensure that we have an parameter
+ if(Buffer::HasInstance(args[0]) && args.Length() > 1) return VException("One argument required - buffer1.");
+ if(args[0]->IsString() && args.Length() > 1) return VException("One argument required - string1.");
+ // Throw an exception if the argument is not of type Buffer
+ if(!Buffer::HasInstance(args[0]) && !args[0]->IsString()) return VException("Argument must be a Buffer or String.");
+
+ // Define pointer to data
+ char *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);
+ data = buffer->data();
+ uint32_t length = buffer->length();
+ #else
+ data = Buffer::Data(obj);
+ uint32_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");
+ }
+
+ // Deserialize the data
+ return BSON::deserialize(bson, data, length, 0, NULL);
+ } 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
+ data = (char *)malloc(len);
+ // Write the data to the buffer from the string object
+ ssize_t written = DecodeWrite(data, len, args[0], BINARY);
+ // Assert that we wrote the same number of bytes as we have length
+ assert(written == len);
+ // Get result
+ Handle result = BSON::deserialize(bson, data, len, 0, NULL);
+ // Free memory
+ free(data);
+ // Deserialize the content
+ return result;
+ }
+}
+
+// Deserialize the stream
+Handle BSON::deserialize(BSON *bson, char *data, uint32_t inDataLength, uint32_t startIndex, bool is_array_item) {
+ HandleScope scope;
+ // Holds references to the objects that are going to be returned
+ Local return_data = Object::New();
+ Local return_array = Array::New();
+ // The current index in the char data
+ uint32_t index = startIndex;
+ // Decode the size of the BSON data structure
+ uint32_t size = BSON::deserialize_int32(data, index);
+
+ // If we have an illegal message size
+ if(size > inDataLength) return VException("corrupt bson message");
+
+ // Data length
+ uint32_t dataLength = index + size;
+
+ // Adjust the index to point to next piece
+ index = index + 4;
+
+ // While we have data left let's decode
+ while(index < dataLength) {
+ // Read the first to bytes to indicate the type of object we are decoding
+ uint8_t type = BSON::deserialize_int8(data, index);
+ // Adjust index to skip type byte
+ index = index + 1;
+
+ if(type == BSON_DATA_STRING) {
+ // Read the null terminated index String
+ char *string_name = BSON::extract_string(data, index);
+ if(string_name == NULL) return VException("Invalid C String found.");
+ // Let's create a new string
+ index = index + strlen(string_name) + 1;
+ // Handle array value if applicable
+ uint32_t insert_index = 0;
+ if(is_array_item) {
+ insert_index = atoi(string_name);
+ }
+
+ // Read the length of the string (next 4 bytes)
+ uint32_t string_size = BSON::deserialize_int32(data, index);
+ // Adjust index to point to start of string
+ index = index + 4;
+ // Decode the string and add zero terminating value at the end of the string
+ char *value = (char *)malloc((string_size * sizeof(char)));
+ strncpy(value, (data + index), string_size);
+ // Encode the string (string - null termiating character)
+ Local utf8_encoded_str = Encode(value, string_size - 1, UTF8)->ToString();
+ // Add the value to the data
+ if(is_array_item) {
+ return_array->Set(Number::New(insert_index), utf8_encoded_str);
+ } else {
+ return_data->ForceSet(String::New(string_name), utf8_encoded_str);
+ }
+
+ // Adjust index
+ index = index + string_size;
+ // Free up the memory
+ free(value);
+ free(string_name);
+ } else if(type == BSON_DATA_INT) {
+ // Read the null terminated index String
+ char *string_name = BSON::extract_string(data, index);
+ if(string_name == NULL) return VException("Invalid C String found.");
+ // Let's create a new string
+ index = index + strlen(string_name) + 1;
+ // Handle array value if applicable
+ uint32_t insert_index = 0;
+ if(is_array_item) {
+ insert_index = atoi(string_name);
+ }
+
+ // Decode the integer value
+ uint32_t value = 0;
+ memcpy(&value, (data + index), 4);
+
+ // Adjust the index for the size of the value
+ index = index + 4;
+ // Add the element to the object
+ if(is_array_item) {
+ return_array->Set(Integer::New(insert_index), Integer::New(value));
+ } else {
+ return_data->ForceSet(String::New(string_name), Integer::New(value));
+ }
+ // Free up the memory
+ free(string_name);
+ } else if(type == BSON_DATA_TIMESTAMP) {
+ // Read the null terminated index String
+ char *string_name = BSON::extract_string(data, index);
+ if(string_name == NULL) return VException("Invalid C String found.");
+ // Let's create a new string
+ index = index + strlen(string_name) + 1;
+ // Handle array value if applicable
+ uint32_t insert_index = 0;
+ if(is_array_item) {
+ insert_index = atoi(string_name);
+ }
+
+ // Add the element to the object
+ if(is_array_item) {
+ return_array->Set(Number::New(insert_index), BSON::decodeTimestamp(bson, data, index));
+ } else {
+ return_data->ForceSet(String::New(string_name), BSON::decodeTimestamp(bson, data, index));
+ }
+
+ // Adjust the index for the size of the value
+ index = index + 8;
+
+ // Free up the memory
+ free(string_name);
+ } else if(type == BSON_DATA_LONG) {
+ // Read the null terminated index String
+ char *string_name = BSON::extract_string(data, index);
+ if(string_name == NULL) return VException("Invalid C String found.");
+ // Let's create a new string
+ index = index + strlen(string_name) + 1;
+ // Handle array value if applicable
+ uint32_t insert_index = 0;
+ if(is_array_item) {
+ insert_index = atoi(string_name);
+ }
+
+ // Add the element to the object
+ if(is_array_item) {
+ return_array->Set(Number::New(insert_index), BSON::decodeLong(bson, data, index));
+ } else {
+ return_data->ForceSet(String::New(string_name), BSON::decodeLong(bson, data, index));
+ }
+
+ // Adjust the index for the size of the value
+ index = index + 8;
+
+ // Free up the memory
+ free(string_name);
+ } else if(type == BSON_DATA_NUMBER) {
+ // Read the null terminated index String
+ char *string_name = BSON::extract_string(data, index);
+ if(string_name == NULL) return VException("Invalid C String found.");
+ // Let's create a new string
+ index = index + strlen(string_name) + 1;
+ // Handle array value if applicable
+ uint32_t insert_index = 0;
+ if(is_array_item) {
+ insert_index = atoi(string_name);
+ }
+
+ // Decode the integer value
+ double value = 0;
+ memcpy(&value, (data + index), 8);
+ // Adjust the index for the size of the value
+ index = index + 8;
+
+ // Add the element to the object
+ if(is_array_item) {
+ return_array->Set(Number::New(insert_index), Number::New(value));
+ } else {
+ return_data->ForceSet(String::New(string_name), Number::New(value));
+ }
+ // Free up the memory
+ free(string_name);
+ } else if(type == BSON_DATA_MIN_KEY) {
+ // Read the null terminated index String
+ char *string_name = BSON::extract_string(data, index);
+ if(string_name == NULL) return VException("Invalid C String found.");
+ // Let's create a new string
+ index = index + strlen(string_name) + 1;
+ // Handle array value if applicable
+ uint32_t insert_index = 0;
+ if(is_array_item) {
+ insert_index = atoi(string_name);
+ }
+
+ // Create new MinKey
+ Local minKey = bson->minKeyConstructor->NewInstance();
+ // Add the element to the object
+ if(is_array_item) {
+ return_array->Set(Number::New(insert_index), minKey);
+ } else {
+ return_data->ForceSet(String::New(string_name), minKey);
+ }
+ // Free up the memory
+ free(string_name);
+ } else if(type == BSON_DATA_MAX_KEY) {
+ // Read the null terminated index String
+ char *string_name = BSON::extract_string(data, index);
+ if(string_name == NULL) return VException("Invalid C String found.");
+ // Let's create a new string
+ index = index + strlen(string_name) + 1;
+ // Handle array value if applicable
+ uint32_t insert_index = 0;
+ if(is_array_item) {
+ insert_index = atoi(string_name);
+ }
+
+ // Create new MinKey
+ Local maxKey = bson->maxKeyConstructor->NewInstance();
+ // Add the element to the object
+ if(is_array_item) {
+ return_array->Set(Number::New(insert_index), maxKey);
+ } else {
+ return_data->ForceSet(String::New(string_name), maxKey);
+ }
+ // Free up the memory
+ free(string_name);
+ } else if(type == BSON_DATA_NULL) {
+ // Read the null terminated index String
+ char *string_name = BSON::extract_string(data, index);
+ if(string_name == NULL) return VException("Invalid C String found.");
+ // Let's create a new string
+ index = index + strlen(string_name) + 1;
+ // Handle array value if applicable
+ uint32_t insert_index = 0;
+ if(is_array_item) {
+ insert_index = atoi(string_name);
+ }
+
+ // Add the element to the object
+ if(is_array_item) {
+ return_array->Set(Number::New(insert_index), Null());
+ } else {
+ return_data->ForceSet(String::New(string_name), Null());
+ }
+ // Free up the memory
+ free(string_name);
+ } else if(type == BSON_DATA_BOOLEAN) {
+ // Read the null terminated index String
+ char *string_name = BSON::extract_string(data, index);
+ if(string_name == NULL) return VException("Invalid C String found.");
+ // Let's create a new string
+ index = index + strlen(string_name) + 1;
+ // Handle array value if applicable
+ uint32_t insert_index = 0;
+ if(is_array_item) {
+ insert_index = atoi(string_name);
+ }
+
+ // Decode the boolean value
+ char bool_value = *(data + index);
+ // Adjust the index for the size of the value
+ index = index + 1;
+
+ // Add the element to the object
+ if(is_array_item) {
+ return_array->Set(Number::New(insert_index), bool_value == 1 ? Boolean::New(true) : Boolean::New(false));
+ } else {
+ return_data->ForceSet(String::New(string_name), bool_value == 1 ? Boolean::New(true) : Boolean::New(false));
+ }
+ // Free up the memory
+ free(string_name);
+ } else if(type == BSON_DATA_DATE) {
+ // Read the null terminated index String
+ char *string_name = BSON::extract_string(data, index);
+ if(string_name == NULL) return VException("Invalid C String found.");
+ // Let's create a new string
+ index = index + strlen(string_name) + 1;
+ // Handle array value if applicable
+ uint32_t insert_index = 0;
+ if(is_array_item) {
+ insert_index = atoi(string_name);
+ }
+
+ // Decode the value 64 bit integer
+ int64_t value = 0;
+ memcpy(&value, (data + index), 8);
+ // Adjust the index for the size of the value
+ index = index + 8;
+ // Add the element to the object
+ if(is_array_item) {
+ return_array->Set(Number::New(insert_index), Date::New((double)value));
+ } else {
+ return_data->ForceSet(String::New(string_name), Date::New((double)value));
+ }
+ // Free up the memory
+ free(string_name);
+ } else if(type == BSON_DATA_REGEXP) {
+ // Read the null terminated index String
+ char *string_name = BSON::extract_string(data, index);
+ if(string_name == NULL) return VException("Invalid C String found.");
+ // Let's create a new string
+ index = index + strlen(string_name) + 1;
+ // Handle array value if applicable
+ uint32_t insert_index = 0;
+ if(is_array_item) {
+ insert_index = atoi(string_name);
+ }
+
+ // Length variable
+ int32_t length_regexp = 0;
+ char chr;
+
+ // Locate end of the regexp expression \0
+ while((chr = *(data + index + length_regexp)) != '\0') {
+ length_regexp = length_regexp + 1;
+ }
+
+ // Contains the reg exp
+ char *reg_exp = (char *)malloc(length_regexp * sizeof(char) + 2);
+ // Copy the regexp from the data to the char *
+ memcpy(reg_exp, (data + index), (length_regexp + 1));
+ // Adjust the index to skip the first part of the regular expression
+ index = index + length_regexp + 1;
+
+ // Reset the length
+ int32_t options_length = 0;
+ // Locate the end of the options for the regexp terminated with a '\0'
+ while((chr = *(data + index + options_length)) != '\0') {
+ options_length = options_length + 1;
+ }
+
+ // Contains the reg exp
+ char *options = (char *)malloc(options_length * sizeof(char) + 1);
+ // Copy the options from the data to the char *
+ memcpy(options, (data + index), (options_length + 1));
+ // Adjust the index to skip the option part of the regular expression
+ index = index + options_length + 1;
+ // ARRRRGH Google does not expose regular expressions through the v8 api
+ // Have to use Script to instantiate the object (slower)
+
+ // Generate the string for execution in the string context
+ int flag = 0;
+
+ for(int i = 0; i < options_length; i++) {
+ // Multiline
+ if(*(options + i) == 'm') {
+ flag = flag | 4;
+ } else if(*(options + i) == 'i') {
+ flag = flag | 2;
+ }
+ }
+
+ // Add the element to the object
+ if(is_array_item) {
+ return_array->Set(Number::New(insert_index), RegExp::New(String::New(reg_exp), (v8::RegExp::Flags)flag));
+ } else {
+ return_data->ForceSet(String::New(string_name), RegExp::New(String::New(reg_exp), (v8::RegExp::Flags)flag));
+ }
+
+ // Free memory
+ free(reg_exp);
+ free(options);
+ free(string_name);
+ } else if(type == BSON_DATA_OID) {
+ // Read the null terminated index String
+ char *string_name = BSON::extract_string(data, index);
+ if(string_name == NULL) return VException("Invalid C String found.");
+ // Let's create a new string
+ index = index + strlen(string_name) + 1;
+ // Handle array value if applicable
+ uint32_t insert_index = 0;
+ if(is_array_item) {
+ insert_index = atoi(string_name);
+ }
+
+ // The id string
+ char *oid_string = (char *)malloc(12 * sizeof(char));
+ // Copy the options from the data to the char *
+ memcpy(oid_string, (data + index), 12);
+
+ // Adjust the index
+ index = index + 12;
+
+ // Add the element to the object
+ if(is_array_item) {
+ return_array->Set(Number::New(insert_index), BSON::decodeOid(bson, oid_string));
+ } else {
+ return_data->ForceSet(String::New(string_name), BSON::decodeOid(bson, oid_string));
+ }
+
+ // Free memory
+ free(oid_string);
+ free(string_name);
+ } else if(type == BSON_DATA_BINARY) {
+ // Read the null terminated index String
+ char *string_name = BSON::extract_string(data, index);
+ if(string_name == NULL) return VException("Invalid C String found.");
+ // Let's create a new string
+ index = index + strlen(string_name) + 1;
+ // Handle array value if applicable
+ uint32_t insert_index = 0;
+ if(is_array_item) {
+ insert_index = atoi(string_name);
+ }
+
+ // Read the binary data size
+ uint32_t number_of_bytes = BSON::deserialize_int32(data, index);
+ // Adjust the index
+ index = index + 4;
+ // Decode the subtype, ensure it's positive
+ uint32_t sub_type = (int)*(data + index) & 0xff;
+ // Adjust the index
+ index = index + 1;
+ // Copy the binary data into a buffer
+ char *buffer = (char *)malloc(number_of_bytes * sizeof(char) + 1);
+ memcpy(buffer, (data + index), number_of_bytes);
+ *(buffer + number_of_bytes) = '\0';
+
+ // Adjust the index
+ index = index + number_of_bytes;
+
+ // Add the element to the object
+ if(is_array_item) {
+ return_array->Set(Number::New(insert_index), BSON::decodeBinary(bson, sub_type, number_of_bytes, buffer));
+ } else {
+ return_data->ForceSet(String::New(string_name), BSON::decodeBinary(bson, sub_type, number_of_bytes, buffer));
+ }
+ // Free memory
+ free(buffer);
+ free(string_name);
+ } else if(type == BSON_DATA_SYMBOL) {
+ // Read the null terminated index String
+ char *string_name = BSON::extract_string(data, index);
+ if(string_name == NULL) return VException("Invalid C String found.");
+ // Let's create a new string
+ index = index + strlen(string_name) + 1;
+ // Handle array value if applicable
+ uint32_t insert_index = 0;
+ if(is_array_item) {
+ insert_index = atoi(string_name);
+ }
+
+ // Read the length of the string (next 4 bytes)
+ uint32_t string_size = BSON::deserialize_int32(data, index);
+ // Adjust index to point to start of string
+ index = index + 4;
+ // Decode the string and add zero terminating value at the end of the string
+ char *value = (char *)malloc((string_size * sizeof(char)));
+ strncpy(value, (data + index), string_size);
+ // Encode the string (string - null termiating character)
+ Local utf8_encoded_str = Encode(value, string_size - 1, UTF8)->ToString();
+
+ // Wrap up the string in a Symbol Object
+ Local argv[] = {utf8_encoded_str};
+ Handle symbolObj = bson->symbolConstructor->NewInstance(1, argv);
+
+ // Add the value to the data
+ if(is_array_item) {
+ return_array->Set(Number::New(insert_index), symbolObj);
+ } else {
+ return_data->ForceSet(String::New(string_name), symbolObj);
+ }
+
+ // Adjust index
+ index = index + string_size;
+ // Free up the memory
+ free(value);
+ free(string_name);
+ } else if(type == BSON_DATA_CODE) {
+ // Read the null terminated index String
+ char *string_name = BSON::extract_string(data, index);
+ if(string_name == NULL) return VException("Invalid C String found.");
+ // Let's create a new string
+ index = index + strlen(string_name) + 1;
+ // Handle array value if applicable
+ uint32_t insert_index = 0;
+ if(is_array_item) {
+ insert_index = atoi(string_name);
+ }
+
+ // Read the string size
+ uint32_t string_size = BSON::deserialize_int32(data, index);
+ // Adjust the index
+ index = index + 4;
+ // Read the string
+ char *code = (char *)malloc(string_size * sizeof(char) + 1);
+ // Copy string + terminating 0
+ memcpy(code, (data + index), string_size);
+
+ // Define empty scope object
+ Handle scope_object = Object::New();
+
+ // Define the try catch block
+ TryCatch try_catch;
+ // Decode the code object
+ Handle obj = BSON::decodeCode(bson, code, scope_object);
+ // If an error was thrown push it up the chain
+ if(try_catch.HasCaught()) {
+ free(string_name);
+ free(code);
+ // Rethrow exception
+ return try_catch.ReThrow();
+ }
+
+ // Add the element to the object
+ if(is_array_item) {
+ return_array->Set(Number::New(insert_index), obj);
+ } else {
+ return_data->ForceSet(String::New(string_name), obj);
+ }
+
+ // Clean up memory allocation
+ free(code);
+ free(string_name);
+ } else if(type == BSON_DATA_CODE_W_SCOPE) {
+ // Read the null terminated index String
+ char *string_name = BSON::extract_string(data, index);
+ if(string_name == NULL) return VException("Invalid C String found.");
+ // Let's create a new string
+ index = index + strlen(string_name) + 1;
+ // Handle array value if applicable
+ uint32_t insert_index = 0;
+ if(is_array_item) {
+ insert_index = atoi(string_name);
+ }
+
+ // Total number of bytes after array index
+ uint32_t total_code_size = BSON::deserialize_int32(data, index);
+ // Adjust the index
+ index = index + 4;
+ // Read the string size
+ uint32_t string_size = BSON::deserialize_int32(data, index);
+ // Adjust the index
+ index = index + 4;
+ // Read the string
+ char *code = (char *)malloc(string_size * sizeof(char) + 1);
+ // Copy string + terminating 0
+ memcpy(code, (data + index), string_size);
+ // Adjust the index
+ index = index + string_size;
+ // Get the scope object (bson object)
+ uint32_t bson_object_size = total_code_size - string_size - 8;
+ // Allocate bson object buffer and copy out the content
+ char *bson_buffer = (char *)malloc(bson_object_size * sizeof(char));
+ memcpy(bson_buffer, (data + index), bson_object_size);
+ // Adjust the index
+ index = index + bson_object_size;
+ // Parse the bson object
+ Handle scope_object = BSON::deserialize(bson, bson_buffer, inDataLength, 0, false);
+ // Define the try catch block
+ TryCatch try_catch;
+ // Decode the code object
+ Handle obj = BSON::decodeCode(bson, code, scope_object);
+ // If an error was thrown push it up the chain
+ if(try_catch.HasCaught()) {
+ // Clean up memory allocation
+ free(string_name);
+ free(bson_buffer);
+ free(code);
+ // Rethrow exception
+ return try_catch.ReThrow();
+ }
+
+ // Add the element to the object
+ if(is_array_item) {
+ return_array->Set(Number::New(insert_index), obj);
+ } else {
+ return_data->ForceSet(String::New(string_name), obj);
+ }
+
+ // Clean up memory allocation
+ free(code);
+ free(bson_buffer);
+ free(string_name);
+ } else if(type == BSON_DATA_OBJECT) {
+ // If this is the top level object we need to skip the undecoding
+ // Read the null terminated index String
+ char *string_name = BSON::extract_string(data, index);
+ if(string_name == NULL) return VException("Invalid C String found.");
+ // Let's create a new string
+ index = index + strlen(string_name) + 1;
+ // Handle array value if applicable
+ uint32_t insert_index = 0;
+ if(is_array_item) {
+ insert_index = atoi(string_name);
+ }
+
+ // Get the object size
+ uint32_t bson_object_size = BSON::deserialize_int32(data, index);
+ // Define the try catch block
+ TryCatch try_catch;
+ // Decode the code object
+ Handle obj = BSON::deserialize(bson, data + index, inDataLength, 0, false);
+ // Adjust the index
+ index = index + bson_object_size;
+ // If an error was thrown push it up the chain
+ if(try_catch.HasCaught()) {
+ // Rethrow exception
+ return try_catch.ReThrow();
+ }
+
+ // Add the element to the object
+ if(is_array_item) {
+ return_array->Set(Number::New(insert_index), obj);
+ } else {
+ return_data->ForceSet(String::New(string_name), obj);
+ }
+
+ // Clean up memory allocation
+ free(string_name);
+ } else if(type == BSON_DATA_ARRAY) {
+ // Read the null terminated index String
+ char *string_name = BSON::extract_string(data, index);
+ if(string_name == NULL) return VException("Invalid C String found.");
+ // Let's create a new string
+ index = index + strlen(string_name) + 1;
+ // Handle array value if applicable
+ uint32_t insert_index = 0;
+ if(is_array_item) {
+ insert_index = atoi(string_name);
+ }
+
+ // Get the size
+ uint32_t array_size = BSON::deserialize_int32(data, index);
+ // Define the try catch block
+ TryCatch try_catch;
+
+ // Decode the code object
+ Handle obj = BSON::deserialize(bson, data + index, inDataLength, 0, true);
+ // If an error was thrown push it up the chain
+ if(try_catch.HasCaught()) {
+ // Rethrow exception
+ return try_catch.ReThrow();
+ }
+ // Adjust the index for the next value
+ index = index + array_size;
+ // Add the element to the object
+ if(is_array_item) {
+ return_array->Set(Number::New(insert_index), obj);
+ } else {
+ return_data->ForceSet(String::New(string_name), obj);
+ }
+ // Clean up memory allocation
+ free(string_name);
+ }
+ }
+
+ // Check if we have a db reference
+ if(!is_array_item && return_data->Has(String::New("$ref")) && return_data->Has(String::New("$id"))) {
+ Handle dbrefValue = BSON::decodeDBref(bson, return_data->Get(String::New("$ref")), return_data->Get(String::New("$id")), return_data->Get(String::New("$db")));
+ return scope.Close(dbrefValue);
+ }
+
+ // Return the data object to javascript
+ if(is_array_item) {
+ return scope.Close(return_array);
+ } else {
+ return scope.Close(return_data);
+ }
+}
+
+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]");
+
+ // Unpack the BSON parser instance
+ BSON *bson = ObjectWrap::Unwrap(args.This());
+
+ uint32_t object_size = 0;
+
+ // Unpack the object
+ Local object = args[0]->ToObject();
+ // Final object
+ Local finalObject;
+
+ // Check if we have a method toBSON on the object
+ if(object->Has(bson->_toBsonString)) {
+ // Fetch the function
+ Local fun = Local::Cast(object->Get(String::New("toBSON")));
+ // Execute the function and get back the object
+ Handle args[] = {};
+ finalObject = fun->Call(object, 0, args);
+ } else {
+ finalObject = object;
+ }
+
+ // Calculate the total size of the document in binary form to ensure we only allocate memory once
+ // With serialize function
+ if(args.Length() == 4) {
+ object_size = BSON::calculate_object_size(bson, finalObject, args[3]->BooleanValue());
+ } else {
+ object_size = BSON::calculate_object_size(bson, finalObject, false);
+ }
+
+ // Allocate the memory needed for the serializtion
+ char *serialized_object = (char *)malloc(object_size * sizeof(char));
+ // Catch any errors
+ try {
+ // Check if we have a boolean value
+ bool check_key = false;
+ if(args.Length() >= 3 && args[1]->IsBoolean()) {
+ check_key = args[1]->BooleanValue();
+ }
+
+ // Check if we have a boolean value
+ bool serializeFunctions = false;
+ if(args.Length() == 4 && args[1]->IsBoolean()) {
+ serializeFunctions = args[3]->BooleanValue();
+ }
+
+ // Serialize the object
+ BSON::serialize(bson, serialized_object, 0, Null(), finalObject, check_key, serializeFunctions);
+ } catch(char *err_msg) {
+ // Free up serialized object space
+ free(serialized_object);
+ V8::AdjustAmountOfExternalAllocatedMemory(-object_size);
+ // Throw exception with the string
+ Handle error = VException(err_msg);
+ // free error message
+ free(err_msg);
+ // Return error
+ return error;
+ }
+
+ // Write the object size
+ BSON::write_int32((serialized_object), object_size);
+
+ // If we have 3 arguments
+ if(args.Length() == 3 || args.Length() == 4) {
+ // Local asBuffer = args[2]->ToBoolean();
+ Buffer *buffer = Buffer::New(serialized_object, object_size);
+ // Release the serialized string
+ free(serialized_object);
+ return scope.Close(buffer->handle_);
+ } else {
+ // Encode the string (string - null termiating character)
+ Local bin_value = Encode(serialized_object, object_size, BINARY)->ToString();
+ // Return the serialized content
+ 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());
+
+ // Unpack the object
+ Local object = args[0]->ToObject();
+ // Final object
+ Local finalObject;
+
+ // Check if we have a method toBSON on the object
+ if(object->Has(bson->_toBsonString)) {
+ // Fetch the function
+ Local fun = Local::Cast(object->Get(String::New("toBSON")));
+ // Execute the function and get back the object
+ Handle args[] = {};
+ finalObject = fun->Call(object, 0, args);
+ } else {
+ finalObject = object;
+ }
+
+ // Object size
+ uint32_t object_size = 0;
+ // Check if we have our argument, calculate size of the object
+ if(args.Length() >= 2) {
+ object_size = BSON::calculate_object_size(bson, finalObject, args[1]->BooleanValue());
+ } else {
+ object_size = BSON::calculate_object_size(bson, finalObject, false);
+ }
+
+ // Return the object size
+ return scope.Close(Uint32::New(object_size));
+}
+
+uint32_t BSON::calculate_object_size(BSON *bson, Handle value, bool serializeFunctions) {
+ uint32_t object_size = 0;
+
+ // If we have an object let's unwrap it and calculate the sub sections
+ if(value->IsString()) {
+ // Let's calculate the size the string adds, length + type(1 byte) + size(4 bytes)
+ object_size += value->ToString()->Utf8Length() + 1 + 4;
+ } else if(value->IsNumber()) {
+ // Check if we have a float value or a long value
+ Local number = value->ToNumber();
+ double d_number = number->NumberValue();
+ int64_t l_number = number->IntegerValue();
+ // Check if we have a double value and not a int64
+ double d_result = d_number - l_number;
+ // If we have a value after subtracting the integer value we have a float
+ if(d_result > 0 || d_result < 0) {
+ object_size = object_size + 8;
+ } else if(l_number <= BSON_INT32_MAX && l_number >= BSON_INT32_MIN) {
+ object_size = object_size + 4;
+ } else {
+ object_size = object_size + 8;
+ }
+ } else if(value->IsBoolean()) {
+ object_size = object_size + 1;
+ } else if(value->IsDate()) {
+ object_size = object_size + 8;
+ } else if(value->IsRegExp()) {
+ // Fetch the string for the regexp
+ Handle regExp = Handle::Cast(value);
+ ssize_t len = DecodeBytes(regExp->GetSource(), UTF8);
+ int flags = regExp->GetFlags();
+
+ // global
+ if((flags & (1 << 0)) != 0) len++;
+ // ignorecase
+ if((flags & (1 << 1)) != 0) len++;
+ //multiline
+ if((flags & (1 << 2)) != 0) len++;
+ // if((flags & (1 << 2)) != 0) len++;
+ // Calculate the space needed for the regexp: size of string - 2 for the /'ses +2 for null termiations
+ object_size = object_size + len + 2;
+ } else if(value->IsNull() || value->IsUndefined()) {
+ } else if(value->IsArray()) {
+ // Cast to array
+ Local array = Local::Cast(value->ToObject());
+ // Turn length into string to calculate the size of all the strings needed
+ char *length_str = (char *)malloc(256 * sizeof(char));
+ // Calculate the size of each element
+ for(uint32_t i = 0; i < array->Length(); i++) {
+ // Add "index" string size for each element
+ sprintf(length_str, "%d", i);
+ // Add the size of the string length
+ uint32_t label_length = strlen(length_str) + 1;
+ // Add the type definition size for each item
+ object_size = object_size + label_length + 1;
+ // Add size of the object
+ uint32_t object_length = BSON::calculate_object_size(bson, array->Get(Integer::New(i)), serializeFunctions);
+ object_size = object_size + object_length;
+ }
+ // Add the object size
+ object_size = object_size + 4 + 1;
+ // Free up memory
+ free(length_str);
+ } else if(value->IsFunction()) {
+ if(serializeFunctions) {
+ object_size += value->ToString()->Utf8Length() + 4 + 1;
+ }
+ } else if(value->ToObject()->Has(bson->_bsontypeString)) {
+ // Handle holder
+ Local constructorString = value->ToObject()->GetConstructorName();
+
+ // BSON type object, avoid non-needed checking unless we have a type
+ if(bson->longString->StrictEquals(constructorString)) {
+ object_size = object_size + 8;
+ } else if(bson->timestampString->StrictEquals(constructorString)) {
+ object_size = object_size + 8;
+ } else if(bson->objectIDString->StrictEquals(constructorString)) {
+ object_size = object_size + 12;
+ } else if(bson->binaryString->StrictEquals(constructorString)) {
+ // Unpack the object and encode
+ Local positionObj = value->ToObject()->Get(String::New("position"))->ToUint32();
+ // Adjust the object_size, binary content lengt + total size int32 + binary size int32 + subtype
+ object_size += positionObj->Value() + 4 + 1;
+ } else if(bson->codeString->StrictEquals(constructorString)) {
+ // Unpack the object and encode
+ Local obj = value->ToObject();
+ // Get the function
+ Local function = obj->Get(String::New("code"))->ToString();
+ // Get the scope object
+ Local scope = obj->Get(String::New("scope"))->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
+
+ // Check if the scope has any parameters
+ // Let's calculate the size the code object adds adds
+ if(propertyNameLength > 0) {
+ object_size += function->Utf8Length() + 4 + BSON::calculate_object_size(bson, scope, serializeFunctions) + 4 + 1;
+ } else {
+ object_size += function->Utf8Length() + 4 + 1;
+ }
+ } else if(bson->dbrefString->StrictEquals(constructorString)) {
+ // Unpack the dbref
+ Local dbref = value->ToObject();
+ // Create an object containing the right namespace variables
+ Local obj = Object::New();
+ // Build the new object
+ obj->Set(bson->_dbRefRefString, dbref->Get(bson->_dbRefNamespaceString));
+ obj->Set(bson->_dbRefIdRefString, dbref->Get(bson->_dbRefOidString));
+ if(!dbref->Get(bson->_dbRefDbString)->IsNull() && !dbref->Get(bson->_dbRefDbString)->IsUndefined()) obj->Set(bson->_dbRefDbRefString, dbref->Get(bson->_dbRefDbString));
+ // Calculate size
+ object_size += BSON::calculate_object_size(bson, obj, serializeFunctions);
+ } else if(bson->minKeyString->StrictEquals(constructorString) || bson->maxKeyString->Equals(constructorString)) {
+ } else if(bson->symbolString->StrictEquals(constructorString)) {
+ // Get string
+ Local str = value->ToObject()->Get(String::New("value"))->ToString();
+ // Get the utf8 length
+ int utf8_length = str->Utf8Length();
+ // Check if we have a utf8 encoded string or not
+ if(utf8_length != str->Length()) {
+ // Let's calculate the size the string adds, length + type(1 byte) + size(4 bytes)
+ object_size += str->Utf8Length() + 1 + 4;
+ } else {
+ object_size += str->Length() + 1 + 4;
+ }
+ } else if(bson->doubleString->StrictEquals(constructorString)) {
+ object_size = object_size + 8;
+ }
+ } else if(value->IsObject()) {
+ // Unwrap the object
+ Local object = value->ToObject();
+
+ #if NODE_MAJOR_VERSION == 0 && NODE_MINOR_VERSION < 6
+ Local property_names = object->GetPropertyNames();
+ #else
+ Local property_names = object->GetOwnPropertyNames();
+ #endif
+
+ // Length of the property
+ uint32_t propertyLength = property_names->Length();
+
+ // Process all the properties on the object
+ for(uint32_t index = 0; index < propertyLength; index++) {
+ // Fetch the property name
+ Local property_name = property_names->Get(index)->ToString();
+
+ // Fetch the object for the property
+ Local property = object->Get(property_name);
+ // Get size of property (property + property name length + 1 for terminating 0)
+ if(!property->IsFunction() || (property->IsFunction() && serializeFunctions)) {
+ // Convert name to char*
+ object_size += BSON::calculate_object_size(bson, property, serializeFunctions) + property_name->Utf8Length() + 1 + 1;
+ }
+ }
+
+ object_size = object_size + 4 + 1;
+ }
+
+ return object_size;
+}
+
+uint32_t BSON::serialize(BSON *bson, char *serialized_object, uint32_t index, Handle name, Handle value, bool check_key, bool serializeFunctions) {
+ // Scope for method execution
+ HandleScope scope;
+
+ // If we have a name check that key is valid
+ if(!name->IsNull() && check_key) {
+ if(BSON::check_key(name->ToString()) != NULL) return -1;
+ }
+
+ // If we have an object let's serialize it
+ if(value->IsString()) {
+ // Save the string at the offset provided
+ *(serialized_object + index) = BSON_DATA_STRING;
+ // Adjust writing position for the first byte
+ index = index + 1;
+ // Convert name to char*
+ ssize_t len = DecodeBytes(name, UTF8);
+ ssize_t written = DecodeWrite((serialized_object + index), len, name, UTF8);
+ assert(written == len);
+ // Add null termiation for the string
+ *(serialized_object + index + len) = '\0';
+ // Adjust the index
+ index = index + len + 1;
+
+ // Write the actual string into the char array
+ Local str = value->ToString();
+ // Let's fetch the int value
+ uint32_t utf8_length = str->Utf8Length();
+
+ // Write the integer to the char *
+ BSON::write_int32((serialized_object + index), utf8_length + 1);
+ // Adjust the index
+ index = index + 4;
+ // Write string to char in utf8 format
+ str->WriteUtf8((serialized_object + index), utf8_length);
+ // Add the null termination
+ *(serialized_object + index + utf8_length) = '\0';
+ // Adjust the index
+ index = index + utf8_length + 1;
+ } else if(value->IsNumber()) {
+ uint32_t first_pointer = index;
+ // Save the string at the offset provided
+ *(serialized_object + index) = BSON_DATA_INT;
+ // Adjust writing position for the first byte
+ index = index + 1;
+ // Convert name to char*
+ ssize_t len = DecodeBytes(name, UTF8);
+ ssize_t written = DecodeWrite((serialized_object + index), len, name, UTF8);
+ assert(written == len);
+ // Add null termiation for the string
+ *(serialized_object + index + len) = '\0';
+ // Adjust the index
+ index = index + len + 1;
+
+ Local number = value->ToNumber();
+ // Get the values
+ double d_number = number->NumberValue();
+ int64_t l_number = number->IntegerValue();
+
+ // Check if we have a double value and not a int64
+ double d_result = d_number - l_number;
+ // If we have a value after subtracting the integer value we have a float
+ if(d_result > 0 || d_result < 0) {
+ // Write the double to the char array
+ BSON::write_double((serialized_object + index), d_number);
+ // Adjust type to be double
+ *(serialized_object + first_pointer) = BSON_DATA_NUMBER;
+ // Adjust index for double
+ index = index + 8;
+ } else if(l_number <= BSON_INT32_MAX && l_number >= BSON_INT32_MIN) {
+ // Smaller than 32 bit, write as 32 bit value
+ BSON::write_int32(serialized_object + index, value->ToInt32()->Value());
+ // Adjust the size of the index
+ index = index + 4;
+ } else if(l_number <= JS_INT_MAX && l_number >= JS_INT_MIN) {
+ // Write the double to the char array
+ BSON::write_double((serialized_object + index), d_number);
+ // Adjust type to be double
+ *(serialized_object + first_pointer) = BSON_DATA_NUMBER;
+ // Adjust index for double
+ index = index + 8;
+ } else {
+ BSON::write_double((serialized_object + index), d_number);
+ // Adjust type to be double
+ *(serialized_object + first_pointer) = BSON_DATA_NUMBER;
+ // Adjust the size of the index
+ index = index + 8;
+ }
+ } else if(value->IsBoolean()) {
+ // Save the string at the offset provided
+ *(serialized_object + index) = BSON_DATA_BOOLEAN;
+ // Adjust writing position for the first byte
+ index = index + 1;
+ // Convert name to char*
+ ssize_t len = DecodeBytes(name, UTF8);
+ ssize_t written = DecodeWrite((serialized_object + index), len, name, UTF8);
+ assert(written == len);
+ // Add null termiation for the string
+ *(serialized_object + index + len) = '\0';
+ // Adjust the index
+ index = index + len + 1;
+
+ // Save the boolean value
+ *(serialized_object + index) = value->BooleanValue() ? '\1' : '\0';
+ // Adjust the index
+ index = index + 1;
+ } else if(value->IsDate()) {
+ // Save the string at the offset provided
+ *(serialized_object + index) = BSON_DATA_DATE;
+ // Adjust writing position for the first byte
+ index = index + 1;
+ // Convert name to char*
+ ssize_t len = DecodeBytes(name, UTF8);
+ ssize_t written = DecodeWrite((serialized_object + index), len, name, UTF8);
+ assert(written == len);
+ // Add null termiation for the string
+ *(serialized_object + index + len) = '\0';
+ // Adjust the index
+ index = index + len + 1;
+
+ // Fetch the Integer value
+ int64_t integer_value = value->IntegerValue();
+ BSON::write_int64((serialized_object + index), integer_value);
+ // Adjust the index
+ index = index + 8;
+ } else if(value->IsNull() || value->IsUndefined()) {
+ // Save the string at the offset provided
+ *(serialized_object + index) = BSON_DATA_NULL;
+ // Adjust writing position for the first byte
+ index = index + 1;
+ // Convert name to char*
+ ssize_t len = DecodeBytes(name, UTF8);
+ ssize_t written = DecodeWrite((serialized_object + index), len, name, UTF8);
+ assert(written == len);
+ // Add null termiation for the string
+ *(serialized_object + index + len) = '\0';
+ // Adjust the index
+ index = index + len + 1;
+ } else if(value->IsArray()) {
+ // Cast to array
+ Local array = Local::Cast(value->ToObject());
+ // Turn length into string to calculate the size of all the strings needed
+ char *length_str = (char *)malloc(256 * sizeof(char));
+ // Save the string at the offset provided
+ *(serialized_object + index) = BSON_DATA_ARRAY;
+ // Adjust writing position for the first byte
+ index = index + 1;
+ // Convert name to char*
+ ssize_t len = DecodeBytes(name, UTF8);
+ ssize_t written = DecodeWrite((serialized_object + index), len, name, UTF8);
+ assert(written == len);
+ // Add null termiation for the string
+ *(serialized_object + index + len) = '\0';
+ // Adjust the index
+ index = index + len + 1;
+ // Object size
+ uint32_t object_size = BSON::calculate_object_size(bson, value, serializeFunctions);
+ // Write the size of the object
+ BSON::write_int32((serialized_object + index), object_size);
+ // Adjust the index
+ index = index + 4;
+ // Write out all the elements
+ for(uint32_t i = 0; i < array->Length(); i++) {
+ // Add "index" string size for each element
+ sprintf(length_str, "%d", i);
+ // Encode the values
+ index = BSON::serialize(bson, serialized_object, index, String::New(length_str), array->Get(Integer::New(i)), check_key, serializeFunctions);
+ // Write trailing '\0' for object
+ *(serialized_object + index) = '\0';
+ }
+
+ // Pad the last item
+ *(serialized_object + index) = '\0';
+ index = index + 1;
+ // Free up memory
+ free(length_str);
+ } else if(value->IsRegExp()) {
+ // Save the string at the offset provided
+ *(serialized_object + index) = BSON_DATA_REGEXP;
+ // Adjust writing position for the first byte
+ index = index + 1;
+ // Convert name to char*
+ ssize_t len = DecodeBytes(name, UTF8);
+ ssize_t written = DecodeWrite((serialized_object + index), len, name, UTF8);
+ // Add null termiation for the string
+ *(serialized_object + index + len) = '\0';
+ // Adjust the index
+ index = index + len + 1;
+
+ // Fetch the string for the regexp
+ Handle regExp = Handle::Cast(value);
+ len = DecodeBytes(regExp->GetSource(), UTF8);
+ written = DecodeWrite((serialized_object + index), len, regExp->GetSource(), UTF8);
+ int flags = regExp->GetFlags();
+ // Add null termiation for the string
+ *(serialized_object + index + len) = '\0';
+ // Adjust the index
+ index = index + len + 1;
+
+ // global
+ if((flags & (1 << 0)) != 0) {
+ *(serialized_object + index) = 's';
+ index = index + 1;
+ }
+
+ // ignorecase
+ if((flags & (1 << 1)) != 0) {
+ *(serialized_object + index) = 'i';
+ index = index + 1;
+ }
+
+ //multiline
+ if((flags & (1 << 2)) != 0) {
+ *(serialized_object + index) = 'm';
+ index = index + 1;
+ }
+
+ // Add null termiation for the string
+ *(serialized_object + index) = '\0';
+ // Adjust the index
+ index = index + 1;
+ } else if(value->IsFunction()) {
+ if(serializeFunctions) {
+ // Save the string at the offset provided
+ *(serialized_object + index) = BSON_DATA_CODE;
+
+ // Adjust writing position for the first byte
+ index = index + 1;
+ // Convert name to char*
+ ssize_t len = DecodeBytes(name, UTF8);
+ ssize_t written = DecodeWrite((serialized_object + index), len, name, UTF8);
+ // Add null termiation for the string
+ *(serialized_object + index + len) = '\0';
+ // Adjust the index
+ index = index + len + 1;
+
+ // Function String
+ Local function = value->ToString();
+
+ // Decode the function
+ len = DecodeBytes(function, BINARY);
+ // Write the size of the code string + 0 byte end of cString
+ BSON::write_int32((serialized_object + index), len + 1);
+ // Adjust the index
+ index = index + 4;
+
+ // Write the data into the serialization stream
+ written = DecodeWrite((serialized_object + index), len, function, BINARY);
+ // Write \0 for string
+ *(serialized_object + index + len) = 0x00;
+ // Adjust the index
+ index = index + len + 1;
+ }
+ } else if(value->ToObject()->Has(bson->_bsontypeString)) {
+ // Handle holder
+ Local constructorString = value->ToObject()->GetConstructorName();
+ uint32_t originalIndex = index;
+ // Adjust writing position for the first byte
+ index = index + 1;
+ // Convert name to char*
+ ssize_t len = DecodeBytes(name, UTF8);
+ ssize_t written = DecodeWrite((serialized_object + index), len, name, UTF8);
+ // Add null termiation for the string
+ *(serialized_object + index + len) = 0x00;
+ // Adjust the index
+ index = index + len + 1;
+
+ // BSON type object, avoid non-needed checking unless we have a type
+ if(bson->longString->StrictEquals(constructorString)) {
+ // Save the string at the offset provided
+ *(serialized_object + originalIndex) = BSON_DATA_LONG;
+ // Object reference
+ Local longObject = value->ToObject();
+
+ // Fetch the low and high bits
+ int32_t lowBits = longObject->Get(bson->_longLowString)->ToInt32()->Value();
+ int32_t highBits = longObject->Get(bson->_longHighString)->ToInt32()->Value();
+
+ // Write the content to the char array
+ BSON::write_int32((serialized_object + index), lowBits);
+ BSON::write_int32((serialized_object + index + 4), highBits);
+ // Adjust the index
+ index = index + 8;
+ } else if(bson->timestampString->StrictEquals(constructorString)) {
+ // Save the string at the offset provided
+ *(serialized_object + originalIndex) = BSON_DATA_TIMESTAMP;
+ // Object reference
+ Local timestampObject = value->ToObject();
+
+ // Fetch the low and high bits
+ int32_t lowBits = timestampObject->Get(bson->_longLowString)->ToInt32()->Value();
+ int32_t highBits = timestampObject->Get(bson->_longHighString)->ToInt32()->Value();
+
+ // Write the content to the char array
+ BSON::write_int32((serialized_object + index), lowBits);
+ BSON::write_int32((serialized_object + index + 4), highBits);
+ // Adjust the index
+ index = index + 8;
+ } else if(bson->objectIDString->StrictEquals(constructorString)) {
+ // Save the string at the offset provided
+ *(serialized_object + originalIndex) = BSON_DATA_OID;
+ // Convert to object
+ Local objectIDObject = value->ToObject();
+ // Let's grab the id
+ Local idString = objectIDObject->Get(bson->_objectIDidString)->ToString();
+ // Let's decode the raw chars from the string
+ len = DecodeBytes(idString, BINARY);
+ written = DecodeWrite((serialized_object + index), len, idString, BINARY);
+ // Adjust the index
+ index = index + 12;
+ } else if(bson->binaryString->StrictEquals(constructorString)) {
+ // Save the string at the offset provided
+ *(serialized_object + originalIndex) = BSON_DATA_BINARY;
+
+ // Let's get the binary object
+ Local binaryObject = value->ToObject();
+
+ // Grab the size(position of the binary)
+ uint32_t position = value->ToObject()->Get(bson->_binaryPositionString)->ToUint32()->Value();
+ // Grab the subtype
+ uint32_t subType = value->ToObject()->Get(bson->_binarySubTypeString)->ToUint32()->Value();
+ // Grab the buffer object
+ Local bufferObj = value->ToObject()->Get(bson->_binaryBufferString)->ToObject();
+
+ // Buffer data pointers
+ char *data;
+ uint32_t length;
+
+ // Unpack the buffer variable
+ #if NODE_MAJOR_VERSION == 0 && NODE_MINOR_VERSION < 3
+ Buffer *buffer = ObjectWrap::Unwrap(bufferObj);
+ data = buffer->data();
+ length = buffer->length();
+ #else
+ data = Buffer::Data(bufferObj);
+ length = Buffer::Length(bufferObj);
+ #endif
+
+ // Write the size of the buffer out
+ BSON::write_int32((serialized_object + index), position);
+ // Adjust index
+ index = index + 4;
+ // Write subtype
+ *(serialized_object + index) = (char)subType;
+ // Adjust index
+ index = index + 1;
+ // Write binary content
+ memcpy((serialized_object + index), data, position);
+ // Adjust index.rar">_
+ index = index + position;
+ } else if(bson->doubleString->StrictEquals(constructorString)) {
+ // Save the string at the offset provided
+ *(serialized_object + originalIndex) = BSON_DATA_NUMBER;
+
+ // Unpack the double
+ Local doubleObject = value->ToObject();
+
+ // Fetch the double value
+ Local doubleValue = doubleObject->Get(bson->_doubleValueString)->ToNumber();
+ // Write the double to the char array
+ BSON::write_double((serialized_object + index), doubleValue->NumberValue());
+ // Adjust index for double
+ index = index + 8;
+ } else if(bson->symbolString->StrictEquals(constructorString)) {
+ // Save the string at the offset provided
+ *(serialized_object + originalIndex) = BSON_DATA_SYMBOL;
+ // Unpack symbol object
+ Local