diff --git a/README.md b/README.md index 73d2f0a..faf41c6 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,8 @@ # MEAN Stack RESTful API Tutorial - Contact List App
+
This repo contains the code for a RESTful API Contact List App that was built using the MEAN stack:
some html
'); - * - * @param {string|number|boolean|object|Buffer} body - * @api public - */ - -res.send = function send(body) { - var chunk = body; - var encoding; - var len; - var req = this.req; - var type; - - // settings - var app = this.app; - - // allow status / body - if (arguments.length === 2) { - // res.send(body, status) backwards compat - if (typeof arguments[0] !== 'number' && typeof arguments[1] === 'number') { - deprecate('res.send(body, status): Use res.status(status).send(body) instead'); - this.statusCode = arguments[1]; - } else { - deprecate('res.send(status, body): Use res.status(status).send(body) instead'); - this.statusCode = arguments[0]; - chunk = arguments[1]; - } - } - - // disambiguate res.send(status) and res.send(status, num) - if (typeof chunk === 'number' && arguments.length === 1) { - // res.send(status) will set status message as text string - if (!this.get('Content-Type')) { - this.type('txt'); - } - - deprecate('res.send(status): Use res.sendStatus(status) instead'); - this.statusCode = chunk; - chunk = http.STATUS_CODES[chunk]; - } - - switch (typeof chunk) { - // string defaulting to html - case 'string': - if (!this.get('Content-Type')) { - this.type('html'); - } - break; - case 'boolean': - case 'number': - case 'object': - if (chunk === null) { - chunk = ''; - } else if (Buffer.isBuffer(chunk)) { - if (!this.get('Content-Type')) { - this.type('bin'); - } - } else { - return this.json(chunk); - } - break; - } - - // write strings in utf-8 - if (typeof chunk === 'string') { - encoding = 'utf8'; - type = this.get('Content-Type'); - - // reflect this in content-type - if (typeof type === 'string') { - this.set('Content-Type', setCharset(type, 'utf-8')); - } - } - - // populate Content-Length - if (chunk !== undefined) { - if (!Buffer.isBuffer(chunk)) { - // convert chunk to Buffer; saves later double conversions - chunk = new Buffer(chunk, encoding); - encoding = undefined; - } - - len = chunk.length; - this.set('Content-Length', len); - } - - // method check - var isHead = req.method === 'HEAD'; - - // ETag support - if (len !== undefined && (isHead || req.method === 'GET')) { - var etag = app.get('etag fn'); - if (etag && !this.get('ETag')) { - etag = etag(chunk, encoding); - etag && this.set('ETag', etag); - } - } - - // freshness - if (req.fresh) this.statusCode = 304; - - // strip irrelevant headers - if (204 == this.statusCode || 304 == this.statusCode) { - this.removeHeader('Content-Type'); - this.removeHeader('Content-Length'); - this.removeHeader('Transfer-Encoding'); - chunk = ''; - } - - if (isHead) { - // skip body for HEAD - this.end(); - } else { - // respond - this.end(chunk, encoding); - } - - return this; -}; - -/** - * Send JSON response. - * - * Examples: - * - * res.json(null); - * res.json({ user: 'tj' }); - * - * @param {string|number|boolean|object} obj - * @api public - */ - -res.json = function json(obj) { - var val = obj; - - // allow status / body - if (arguments.length === 2) { - // res.json(body, status) backwards compat - if (typeof arguments[1] === 'number') { - deprecate('res.json(obj, status): Use res.status(status).json(obj) instead'); - this.statusCode = arguments[1]; - } else { - deprecate('res.json(status, obj): Use res.status(status).json(obj) instead'); - this.statusCode = arguments[0]; - val = arguments[1]; - } - } - - // settings - var app = this.app; - var replacer = app.get('json replacer'); - var spaces = app.get('json spaces'); - var body = JSON.stringify(val, replacer, spaces); - - // content-type - if (!this.get('Content-Type')) { - this.set('Content-Type', 'application/json'); - } - - return this.send(body); -}; - -/** - * Send JSON response with JSONP callback support. - * - * Examples: - * - * res.jsonp(null); - * res.jsonp({ user: 'tj' }); - * - * @param {string|number|boolean|object} obj - * @api public - */ - -res.jsonp = function jsonp(obj) { - var val = obj; - - // allow status / body - if (arguments.length === 2) { - // res.json(body, status) backwards compat - if (typeof arguments[1] === 'number') { - deprecate('res.jsonp(obj, status): Use res.status(status).json(obj) instead'); - this.statusCode = arguments[1]; - } else { - deprecate('res.jsonp(status, obj): Use res.status(status).jsonp(obj) instead'); - this.statusCode = arguments[0]; - val = arguments[1]; - } - } - - // settings - var app = this.app; - var replacer = app.get('json replacer'); - var spaces = app.get('json spaces'); - var body = JSON.stringify(val, replacer, spaces); - var callback = this.req.query[app.get('jsonp callback name')]; - - // content-type - if (!this.get('Content-Type')) { - this.set('X-Content-Type-Options', 'nosniff'); - this.set('Content-Type', 'application/json'); - } - - // fixup callback - if (Array.isArray(callback)) { - callback = callback[0]; - } - - // jsonp - if (typeof callback === 'string' && callback.length !== 0) { - this.charset = 'utf-8'; - this.set('X-Content-Type-Options', 'nosniff'); - this.set('Content-Type', 'text/javascript'); - - // restrict callback charset - callback = callback.replace(/[^\[\]\w$.]/g, ''); - - // replace chars not allowed in JavaScript that are in JSON - body = body - .replace(/\u2028/g, '\\u2028') - .replace(/\u2029/g, '\\u2029'); - - // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse" - // the typeof check is just to reduce client error noise - body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');'; - } - - return this.send(body); -}; - -/** - * Send given HTTP status code. - * - * Sets the response status to `statusCode` and the body of the - * response to the standard description from node's http.STATUS_CODES - * or the statusCode number if no description. - * - * Examples: - * - * res.sendStatus(200); - * - * @param {number} statusCode - * @api public - */ - -res.sendStatus = function sendStatus(statusCode) { - var body = http.STATUS_CODES[statusCode] || String(statusCode); - - this.statusCode = statusCode; - this.type('txt'); - - return this.send(body); -}; - -/** - * Transfer the file at the given `path`. - * - * Automatically sets the _Content-Type_ response header field. - * The callback `fn(err)` is invoked when the transfer is complete - * or when an error occurs. Be sure to check `res.sentHeader` - * if you wish to attempt responding, as the header and some data - * may have already been transferred. - * - * Options: - * - * - `maxAge` defaulting to 0 (can be string converted by `ms`) - * - `root` root directory for relative filenames - * - `headers` object of headers to serve with file - * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them - * - * Other options are passed along to `send`. - * - * Examples: - * - * The following example illustrates how `res.sendFile()` may - * be used as an alternative for the `static()` middleware for - * dynamic situations. The code backing `res.sendFile()` is actually - * the same code, so HTTP cache support etc is identical. - * - * app.get('/user/:uid/photos/:file', function(req, res){ - * var uid = req.params.uid - * , file = req.params.file; - * - * req.user.mayViewFilesFrom(uid, function(yes){ - * if (yes) { - * res.sendFile('/uploads/' + uid + '/' + file); - * } else { - * res.send(403, 'Sorry! you cant see that.'); - * } - * }); - * }); - * - * @api public - */ - -res.sendFile = function sendFile(path, options, fn) { - var req = this.req; - var res = this; - var next = req.next; - - if (!path) { - throw new TypeError('path argument is required to res.sendFile'); - } - - // support function as second arg - if (typeof options === 'function') { - fn = options; - options = {}; - } - - options = options || {}; - - if (!options.root && !isAbsolute(path)) { - throw new TypeError('path must be absolute or specify root to res.sendFile'); - } - - // create file stream - var pathname = encodeURI(path); - var file = send(req, pathname, options); - - // transfer - sendfile(res, file, options, function (err) { - if (fn) return fn(err); - if (err && err.code === 'EISDIR') return next(); - - // next() all but write errors - if (err && err.code !== 'ECONNABORT' && err.syscall !== 'write') { - next(err); - } - }); -}; - -/** - * Transfer the file at the given `path`. - * - * Automatically sets the _Content-Type_ response header field. - * The callback `fn(err)` is invoked when the transfer is complete - * or when an error occurs. Be sure to check `res.sentHeader` - * if you wish to attempt responding, as the header and some data - * may have already been transferred. - * - * Options: - * - * - `maxAge` defaulting to 0 (can be string converted by `ms`) - * - `root` root directory for relative filenames - * - `headers` object of headers to serve with file - * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them - * - * Other options are passed along to `send`. - * - * Examples: - * - * The following example illustrates how `res.sendfile()` may - * be used as an alternative for the `static()` middleware for - * dynamic situations. The code backing `res.sendfile()` is actually - * the same code, so HTTP cache support etc is identical. - * - * app.get('/user/:uid/photos/:file', function(req, res){ - * var uid = req.params.uid - * , file = req.params.file; - * - * req.user.mayViewFilesFrom(uid, function(yes){ - * if (yes) { - * res.sendfile('/uploads/' + uid + '/' + file); - * } else { - * res.send(403, 'Sorry! you cant see that.'); - * } - * }); - * }); - * - * @api public - */ - -res.sendfile = function(path, options, fn){ - var req = this.req; - var res = this; - var next = req.next; - - // support function as second arg - if (typeof options === 'function') { - fn = options; - options = {}; - } - - options = options || {}; - - // create file stream - var file = send(req, path, options); - - // transfer - sendfile(res, file, options, function (err) { - if (fn) return fn(err); - if (err && err.code === 'EISDIR') return next(); - - // next() all but write errors - if (err && err.code !== 'ECONNABORT' && err.syscall !== 'write') { - next(err); - } - }); -}; - -res.sendfile = deprecate.function(res.sendfile, - 'res.sendfile: Use res.sendFile instead'); - -/** - * Transfer the file at the given `path` as an attachment. - * - * Optionally providing an alternate attachment `filename`, - * and optional callback `fn(err)`. The callback is invoked - * when the data transfer is complete, or when an error has - * ocurred. Be sure to check `res.headersSent` if you plan to respond. - * - * This method uses `res.sendfile()`. - * - * @api public - */ - -res.download = function download(path, filename, fn) { - // support function as second arg - if (typeof filename === 'function') { - fn = filename; - filename = null; - } - - filename = filename || path; - - // set Content-Disposition when file is sent - var headers = { - 'Content-Disposition': contentDisposition(filename) - }; - - // Resolve the full path for sendFile - var fullPath = resolve(path); - - return this.sendFile(fullPath, { headers: headers }, fn); -}; - -/** - * Set _Content-Type_ response header with `type` through `mime.lookup()` - * when it does not contain "/", or set the Content-Type to `type` otherwise. - * - * Examples: - * - * res.type('.html'); - * res.type('html'); - * res.type('json'); - * res.type('application/json'); - * res.type('png'); - * - * @param {String} type - * @return {ServerResponse} for chaining - * @api public - */ - -res.contentType = -res.type = function(type){ - return this.set('Content-Type', ~type.indexOf('/') - ? type - : mime.lookup(type)); -}; - -/** - * Respond to the Acceptable formats using an `obj` - * of mime-type callbacks. - * - * This method uses `req.accepted`, an array of - * acceptable types ordered by their quality values. - * When "Accept" is not present the _first_ callback - * is invoked, otherwise the first match is used. When - * no match is performed the server responds with - * 406 "Not Acceptable". - * - * Content-Type is set for you, however if you choose - * you may alter this within the callback using `res.type()` - * or `res.set('Content-Type', ...)`. - * - * res.format({ - * 'text/plain': function(){ - * res.send('hey'); - * }, - * - * 'text/html': function(){ - * res.send('hey
'); - * }, - * - * 'appliation/json': function(){ - * res.send({ message: 'hey' }); - * } - * }); - * - * In addition to canonicalized MIME types you may - * also use extnames mapped to these types: - * - * res.format({ - * text: function(){ - * res.send('hey'); - * }, - * - * html: function(){ - * res.send('hey
'); - * }, - * - * json: function(){ - * res.send({ message: 'hey' }); - * } - * }); - * - * By default Express passes an `Error` - * with a `.status` of 406 to `next(err)` - * if a match is not made. If you provide - * a `.default` callback it will be invoked - * instead. - * - * @param {Object} obj - * @return {ServerResponse} for chaining - * @api public - */ - -res.format = function(obj){ - var req = this.req; - var next = req.next; - - var fn = obj.default; - if (fn) delete obj.default; - var keys = Object.keys(obj); - - var key = req.accepts(keys); - - this.vary("Accept"); - - if (key) { - this.set('Content-Type', normalizeType(key).value); - obj[key](req, this, next); - } else if (fn) { - fn(); - } else { - var err = new Error('Not Acceptable'); - err.status = 406; - err.types = normalizeTypes(keys).map(function(o){ return o.value }); - next(err); - } - - return this; -}; - -/** - * Set _Content-Disposition_ header to _attachment_ with optional `filename`. - * - * @param {String} filename - * @return {ServerResponse} - * @api public - */ - -res.attachment = function attachment(filename) { - if (filename) { - this.type(extname(filename)); - } - - this.set('Content-Disposition', contentDisposition(filename)); - - return this; -}; - -/** - * Append additional header `field` with value `val`. - * - * Example: - * - * res.append('Link', ['' + statusCodes[status] + '. Redirecting to ' + u + '
'; - }, - - default: function(){ - body = ''; - } - }); - - // Respond - this.statusCode = status; - this.set('Content-Length', Buffer.byteLength(body)); - - if (this.req.method === 'HEAD') { - this.end(); - } - - this.end(body); -}; - -/** - * Add `field` to Vary. If already present in the Vary set, then - * this call is simply ignored. - * - * @param {Array|String} field - * @return {ServerResponse} for chaining - * @api public - */ - -res.vary = function(field){ - // checks for back-compat - if (!field || (Array.isArray(field) && !field.length)) { - deprecate('res.vary(): Provide a field name'); - return this; - } - - vary(this, field); - - return this; -}; - -/** - * Render `view` with the given `options` and optional callback `fn`. - * When a callback function is given a response will _not_ be made - * automatically, otherwise a response of _200_ and _text/html_ is given. - * - * Options: - * - * - `cache` boolean hinting to the engine it should cache - * - `filename` filename of the view being rendered - * - * @api public - */ - -res.render = function(view, options, fn){ - options = options || {}; - var self = this; - var req = this.req; - var app = req.app; - - // support callback function as second arg - if ('function' == typeof options) { - fn = options, options = {}; - } - - // merge res.locals - options._locals = self.locals; - - // default callback to respond - fn = fn || function(err, str){ - if (err) return req.next(err); - self.send(str); - }; - - // render - app.render(view, options, fn); -}; - -// pipe the send file stream -function sendfile(res, file, options, callback) { - var done = false; - var streaming; - - // request aborted - function onaborted() { - if (done) return; - done = true; - - var err = new Error('Request aborted'); - err.code = 'ECONNABORT'; - callback(err); - } - - // directory - function ondirectory() { - if (done) return; - done = true; - - var err = new Error('EISDIR, read'); - err.code = 'EISDIR'; - callback(err); - } - - // errors - function onerror(err) { - if (done) return; - done = true; - callback(err); - } - - // ended - function onend() { - if (done) return; - done = true; - callback(); - } - - // file - function onfile() { - streaming = false; - } - - // finished - function onfinish(err) { - if (err) return onerror(err); - if (done) return; - - setImmediate(function () { - if (streaming !== false && !done) { - onaborted(); - return; - } - - if (done) return; - done = true; - callback(); - }); - } - - // streaming - function onstream() { - streaming = true; - } - - file.on('directory', ondirectory); - file.on('end', onend); - file.on('error', onerror); - file.on('file', onfile); - file.on('stream', onstream); - onFinished(res, onfinish); - - if (options.headers) { - // set headers on successful transfer - file.on('headers', function headers(res) { - var obj = options.headers; - var keys = Object.keys(obj); - - for (var i = 0; i < keys.length; i++) { - var k = keys[i]; - res.setHeader(k, obj[k]); - } - }); - } - - // pipe - file.pipe(res); -} diff --git a/node_modules/express/lib/router/index.js b/node_modules/express/lib/router/index.js deleted file mode 100644 index 209f881..0000000 --- a/node_modules/express/lib/router/index.js +++ /dev/null @@ -1,630 +0,0 @@ - -/** - * Module dependencies. - */ - -var Route = require('./route'); -var Layer = require('./layer'); -var methods = require('methods'); -var mixin = require('utils-merge'); -var debug = require('debug')('express:router'); -var deprecate = require('depd')('express'); -var parseUrl = require('parseurl'); -var utils = require('../utils'); - -/** - * Module variables. - */ - -var objectRegExp = /^\[object (\S+)\]$/; -var slice = Array.prototype.slice; -var toString = Object.prototype.toString; - -/** - * Initialize a new `Router` with the given `options`. - * - * @param {Object} options - * @return {Router} which is an callable function - * @api public - */ - -var proto = module.exports = function(options) { - options = options || {}; - - function router(req, res, next) { - router.handle(req, res, next); - } - - // mixin Router class functions - router.__proto__ = proto; - - router.params = {}; - router._params = []; - router.caseSensitive = options.caseSensitive; - router.mergeParams = options.mergeParams; - router.strict = options.strict; - router.stack = []; - - return router; -}; - -/** - * Map the given param placeholder `name`(s) to the given callback. - * - * Parameter mapping is used to provide pre-conditions to routes - * which use normalized placeholders. For example a _:user_id_ parameter - * could automatically load a user's information from the database without - * any additional code, - * - * The callback uses the same signature as middleware, the only difference - * being that the value of the placeholder is passed, in this case the _id_ - * of the user. Once the `next()` function is invoked, just like middleware - * it will continue on to execute the route, or subsequent parameter functions. - * - * Just like in middleware, you must either respond to the request or call next - * to avoid stalling the request. - * - * app.param('user_id', function(req, res, next, id){ - * User.find(id, function(err, user){ - * if (err) { - * return next(err); - * } else if (!user) { - * return next(new Error('failed to load user')); - * } - * req.user = user; - * next(); - * }); - * }); - * - * @param {String} name - * @param {Function} fn - * @return {app} for chaining - * @api public - */ - -proto.param = function param(name, fn) { - // param logic - if (typeof name === 'function') { - deprecate('router.param(fn): Refactor to use path params'); - this._params.push(name); - return; - } - - // apply param functions - var params = this._params; - var len = params.length; - var ret; - - if (name[0] === ':') { - deprecate('router.param(' + JSON.stringify(name) + ', fn): Use router.param(' + JSON.stringify(name.substr(1)) + ', fn) instead'); - name = name.substr(1); - } - - for (var i = 0; i < len; ++i) { - if (ret = params[i](name, fn)) { - fn = ret; - } - } - - // ensure we end up with a - // middleware function - if ('function' != typeof fn) { - throw new Error('invalid param() call for ' + name + ', got ' + fn); - } - - (this.params[name] = this.params[name] || []).push(fn); - return this; -}; - -/** - * Dispatch a req, res into the router. - * - * @api private - */ - -proto.handle = function(req, res, done) { - var self = this; - - debug('dispatching %s %s', req.method, req.url); - - var search = 1 + req.url.indexOf('?'); - var pathlength = search ? search - 1 : req.url.length; - var fqdn = req.url[0] !== '/' && 1 + req.url.substr(0, pathlength).indexOf('://'); - var protohost = fqdn ? req.url.substr(0, req.url.indexOf('/', 2 + fqdn)) : ''; - var idx = 0; - var removed = ''; - var slashAdded = false; - var paramcalled = {}; - - // store options for OPTIONS request - // only used if OPTIONS request - var options = []; - - // middleware and routes - var stack = self.stack; - - // manage inter-router variables - var parentParams = req.params; - var parentUrl = req.baseUrl || ''; - done = restore(done, req, 'baseUrl', 'next', 'params'); - - // setup next layer - req.next = next; - - // for options requests, respond with a default if nothing else responds - if (req.method === 'OPTIONS') { - done = wrap(done, function(old, err) { - if (err || options.length === 0) return old(err); - sendOptionsResponse(res, options, old); - }); - } - - // setup basic req values - req.baseUrl = parentUrl; - req.originalUrl = req.originalUrl || req.url; - - next(); - - function next(err) { - var layerError = err === 'route' - ? null - : err; - - // remove added slash - if (slashAdded) { - req.url = req.url.substr(1); - slashAdded = false; - } - - // restore altered req.url - if (removed.length !== 0) { - req.baseUrl = parentUrl; - req.url = protohost + removed + req.url.substr(protohost.length); - removed = ''; - } - - // no more matching layers - if (idx >= stack.length) { - setImmediate(done, layerError); - return; - } - - // get pathname of request - var path = getPathname(req); - - if (path == null) { - return done(layerError); - } - - // find next matching layer - var layer; - var match; - var route; - - while (match !== true && idx < stack.length) { - layer = stack[idx++]; - match = matchLayer(layer, path); - route = layer.route; - - if (typeof match !== 'boolean') { - // hold on to layerError - layerError = layerError || match; - } - - if (match !== true) { - continue; - } - - if (!route) { - // process non-route handlers normally - continue; - } - - if (layerError) { - // routes do not match with a pending error - match = false; - continue; - } - - var method = req.method; - var has_method = route._handles_method(method); - - // build up automatic options response - if (!has_method && method === 'OPTIONS') { - appendMethods(options, route._options()); - } - - // don't even bother matching route - if (!has_method && method !== 'HEAD') { - match = false; - continue; - } - } - - // no match - if (match !== true) { - return done(layerError); - } - - // store route for dispatch on change - if (route) { - req.route = route; - } - - // Capture one-time layer values - req.params = self.mergeParams - ? mergeParams(layer.params, parentParams) - : layer.params; - var layerPath = layer.path; - - // this should be done for the layer - self.process_params(layer, paramcalled, req, res, function (err) { - if (err) { - return next(layerError || err); - } - - if (route) { - return layer.handle_request(req, res, next); - } - - trim_prefix(layer, layerError, layerPath, path); - }); - } - - function trim_prefix(layer, layerError, layerPath, path) { - var c = path[layerPath.length]; - if (c && '/' !== c && '.' !== c) return next(layerError); - - // Trim off the part of the url that matches the route - // middleware (.use stuff) needs to have the path stripped - if (layerPath.length !== 0) { - debug('trim prefix (%s) from url %s', layerPath, req.url); - removed = layerPath; - req.url = protohost + req.url.substr(protohost.length + removed.length); - - // Ensure leading slash - if (!fqdn && req.url[0] !== '/') { - req.url = '/' + req.url; - slashAdded = true; - } - - // Setup base URL (no trailing slash) - req.baseUrl = parentUrl + (removed[removed.length - 1] === '/' - ? removed.substring(0, removed.length - 1) - : removed); - } - - debug('%s %s : %s', layer.name, layerPath, req.originalUrl); - - if (layerError) { - layer.handle_error(layerError, req, res, next); - } else { - layer.handle_request(req, res, next); - } - } -}; - -/** - * Process any parameters for the layer. - * - * @api private - */ - -proto.process_params = function(layer, called, req, res, done) { - var params = this.params; - - // captured parameters from the layer, keys and values - var keys = layer.keys; - - // fast track - if (!keys || keys.length === 0) { - return done(); - } - - var i = 0; - var name; - var paramIndex = 0; - var key; - var paramVal; - var paramCallbacks; - var paramCalled; - - // process params in order - // param callbacks can be async - function param(err) { - if (err) { - return done(err); - } - - if (i >= keys.length ) { - return done(); - } - - paramIndex = 0; - key = keys[i++]; - - if (!key) { - return done(); - } - - name = key.name; - paramVal = req.params[name]; - paramCallbacks = params[name]; - paramCalled = called[name]; - - if (paramVal === undefined || !paramCallbacks) { - return param(); - } - - // param previously called with same value or error occurred - if (paramCalled && (paramCalled.error || paramCalled.match === paramVal)) { - // restore value - req.params[name] = paramCalled.value; - - // next param - return param(paramCalled.error); - } - - called[name] = paramCalled = { - error: null, - match: paramVal, - value: paramVal - }; - - paramCallback(); - } - - // single param callbacks - function paramCallback(err) { - var fn = paramCallbacks[paramIndex++]; - - // store updated value - paramCalled.value = req.params[key.name]; - - if (err) { - // store error - paramCalled.error = err; - param(err); - return; - } - - if (!fn) return param(); - - try { - fn(req, res, paramCallback, paramVal, key.name); - } catch (e) { - paramCallback(e); - } - } - - param(); -}; - -/** - * Use the given middleware function, with optional path, defaulting to "/". - * - * Use (like `.all`) will run for any http METHOD, but it will not add - * handlers for those methods so OPTIONS requests will not consider `.use` - * functions even if they could respond. - * - * The other difference is that _route_ path is stripped and not visible - * to the handler function. The main effect of this feature is that mounted - * handlers can operate without any code changes regardless of the "prefix" - * pathname. - * - * @api public - */ - -proto.use = function use(fn) { - var offset = 0; - var path = '/'; - - // default path to '/' - // disambiguate router.use([fn]) - if (typeof fn !== 'function') { - var arg = fn; - - while (Array.isArray(arg) && arg.length !== 0) { - arg = arg[0]; - } - - // first arg is the path - if (typeof arg !== 'function') { - offset = 1; - path = fn; - } - } - - var callbacks = utils.flatten(slice.call(arguments, offset)); - - if (callbacks.length === 0) { - throw new TypeError('Router.use() requires middleware functions'); - } - - callbacks.forEach(function (fn) { - if (typeof fn !== 'function') { - throw new TypeError('Router.use() requires middleware function but got a ' + gettype(fn)); - } - - // add the middleware - debug('use %s %s', path, fn.name || '
Please support me on [GitTip](https://www.gittip.com/alexgorbatchev/). I've spend days developing and grooming this module and hope to spend more time. If you have bitcoin, please use the QR code or this wallet address [`1CZyBREeHTmy8C5zVGHZHPwqBuWFmEuUCQ`](https://blockchain.info/address/1CZyBREeHTmy8C5zVGHZHPwqBuWFmEuUCQ):
-
-## Installation
-
- npm install crc
-
-## Running tests
-
- $ npm install
- $ npm test
-
-## Usage Example
-
-Calculate a CRC32:
-
- var crc = require('crc');
-
- crc.crc32('hello').toString(16);
- # => "3610a686"
-
-Calculate a CRC32 of a file:
-
- crc.crc32(fs.readFileSync('README.md', 'utf8')).toString(16);
- # => "127ad531"
-
-Or using a `Buffer`:
-
- crc.crc32(fs.readFileSync('README.md')).toString(16);
- # => "127ad531"
-
-Incrementally calculate a CRC32:
-
- value = crc32('one');
- value = crc32('two', value);
- value = crc32('three', value);
- value.toString(16);
- # => "09e1c092"
-
-## Thanks!
-
-[pycrc](http://www.tty1.net/pycrc/) library is which the source of all of the CRC tables.
-
-# License
-
-The MIT License (MIT)
-
-Copyright (c) 2014 Alex Gorbatchev
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-THE SOFTWARE.
diff --git a/node_modules/express/node_modules/etag/node_modules/crc/lib/crc.js b/node_modules/express/node_modules/etag/node_modules/crc/lib/crc.js
deleted file mode 100644
index 1c342b7..0000000
--- a/node_modules/express/node_modules/etag/node_modules/crc/lib/crc.js
+++ /dev/null
@@ -1,71 +0,0 @@
-// Generated by CoffeeScript 1.7.1
-var CRC, hex;
-
-hex = require('./hex');
-
-module.exports = CRC = (function() {
- CRC.prototype.INIT_CRC = 0x00;
-
- CRC.prototype.XOR_MASK = 0x00;
-
- CRC.prototype.WIDTH = 0;
-
- CRC.prototype.pack = function(crc) {
- return '';
- };
-
- CRC.prototype.each_byte = function(buf, cb) {
- var i, _i, _ref, _results;
- if (!Buffer.isBuffer(buf)) {
- buf = Buffer(buf);
- }
- _results = [];
- for (i = _i = 0, _ref = buf.length - 1; 0 <= _ref ? _i <= _ref : _i >= _ref; i = 0 <= _ref ? ++_i : --_i) {
- _results.push(cb(buf[i]));
- }
- return _results;
- };
-
- function CRC() {
- this.crc = this.INIT_CRC;
- }
-
- CRC.prototype.digest_length = function() {
- return Math.ceil(this.WIDTH / 8.0);
- };
-
- CRC.prototype.update = function(data) {};
-
- CRC.prototype.reset = function() {
- return this.crc = this.INIT_CRC;
- };
-
- CRC.prototype.checksum = function(signed) {
- var sum;
- if (signed == null) {
- signed = true;
- }
- sum = this.crc ^ this.XOR_MASK;
- if (signed) {
- sum = sum >>> 0;
- }
- return sum;
- };
-
- CRC.prototype.finish = function() {
- return this.pack(this.checksum());
- };
-
- CRC.prototype.hexdigest = function(value) {
- var result;
- if (value != null) {
- this.update(value);
- }
- result = this.finish();
- this.reset();
- return result;
- };
-
- return CRC;
-
-})();
diff --git a/node_modules/express/node_modules/etag/node_modules/crc/lib/crc1.js b/node_modules/express/node_modules/etag/node_modules/crc/lib/crc1.js
deleted file mode 100644
index f094567..0000000
--- a/node_modules/express/node_modules/etag/node_modules/crc/lib/crc1.js
+++ /dev/null
@@ -1,21 +0,0 @@
-// Generated by CoffeeScript 1.7.1
-var Buffer, create;
-
-Buffer = require('buffer').Buffer;
-
-create = require('./create');
-
-module.exports = create('crc1', function(buf, previous) {
- var accum, byte, crc, _i, _len;
- if (!Buffer.isBuffer(buf)) {
- buf = Buffer(buf);
- }
- crc = ~~previous;
- accum = 0;
- for (_i = 0, _len = buf.length; _i < _len; _i++) {
- byte = buf[_i];
- accum += byte;
- }
- crc += accum % 256;
- return crc % 256;
-});
diff --git a/node_modules/express/node_modules/etag/node_modules/crc/lib/crc16.js b/node_modules/express/node_modules/etag/node_modules/crc/lib/crc16.js
deleted file mode 100644
index a09cd1e..0000000
--- a/node_modules/express/node_modules/etag/node_modules/crc/lib/crc16.js
+++ /dev/null
@@ -1,25 +0,0 @@
-// Generated by CoffeeScript 1.7.1
-var Buffer, TABLE, create;
-
-Buffer = require('buffer').Buffer;
-
-create = require('./create');
-
-TABLE = [0x0000, 0xc0c1, 0xc181, 0x0140, 0xc301, 0x03c0, 0x0280, 0xc241, 0xc601, 0x06c0, 0x0780, 0xc741, 0x0500, 0xc5c1, 0xc481, 0x0440, 0xcc01, 0x0cc0, 0x0d80, 0xcd41, 0x0f00, 0xcfc1, 0xce81, 0x0e40, 0x0a00, 0xcac1, 0xcb81, 0x0b40, 0xc901, 0x09c0, 0x0880, 0xc841, 0xd801, 0x18c0, 0x1980, 0xd941, 0x1b00, 0xdbc1, 0xda81, 0x1a40, 0x1e00, 0xdec1, 0xdf81, 0x1f40, 0xdd01, 0x1dc0, 0x1c80, 0xdc41, 0x1400, 0xd4c1, 0xd581, 0x1540, 0xd701, 0x17c0, 0x1680, 0xd641, 0xd201, 0x12c0, 0x1380, 0xd341, 0x1100, 0xd1c1, 0xd081, 0x1040, 0xf001, 0x30c0, 0x3180, 0xf141, 0x3300, 0xf3c1, 0xf281, 0x3240, 0x3600, 0xf6c1, 0xf781, 0x3740, 0xf501, 0x35c0, 0x3480, 0xf441, 0x3c00, 0xfcc1, 0xfd81, 0x3d40, 0xff01, 0x3fc0, 0x3e80, 0xfe41, 0xfa01, 0x3ac0, 0x3b80, 0xfb41, 0x3900, 0xf9c1, 0xf881, 0x3840, 0x2800, 0xe8c1, 0xe981, 0x2940, 0xeb01, 0x2bc0, 0x2a80, 0xea41, 0xee01, 0x2ec0, 0x2f80, 0xef41, 0x2d00, 0xedc1, 0xec81, 0x2c40, 0xe401, 0x24c0, 0x2580, 0xe541, 0x2700, 0xe7c1, 0xe681, 0x2640, 0x2200, 0xe2c1, 0xe381, 0x2340, 0xe101, 0x21c0, 0x2080, 0xe041, 0xa001, 0x60c0, 0x6180, 0xa141, 0x6300, 0xa3c1, 0xa281, 0x6240, 0x6600, 0xa6c1, 0xa781, 0x6740, 0xa501, 0x65c0, 0x6480, 0xa441, 0x6c00, 0xacc1, 0xad81, 0x6d40, 0xaf01, 0x6fc0, 0x6e80, 0xae41, 0xaa01, 0x6ac0, 0x6b80, 0xab41, 0x6900, 0xa9c1, 0xa881, 0x6840, 0x7800, 0xb8c1, 0xb981, 0x7940, 0xbb01, 0x7bc0, 0x7a80, 0xba41, 0xbe01, 0x7ec0, 0x7f80, 0xbf41, 0x7d00, 0xbdc1, 0xbc81, 0x7c40, 0xb401, 0x74c0, 0x7580, 0xb541, 0x7700, 0xb7c1, 0xb681, 0x7640, 0x7200, 0xb2c1, 0xb381, 0x7340, 0xb101, 0x71c0, 0x7080, 0xb041, 0x5000, 0x90c1, 0x9181, 0x5140, 0x9301, 0x53c0, 0x5280, 0x9241, 0x9601, 0x56c0, 0x5780, 0x9741, 0x5500, 0x95c1, 0x9481, 0x5440, 0x9c01, 0x5cc0, 0x5d80, 0x9d41, 0x5f00, 0x9fc1, 0x9e81, 0x5e40, 0x5a00, 0x9ac1, 0x9b81, 0x5b40, 0x9901, 0x59c0, 0x5880, 0x9841, 0x8801, 0x48c0, 0x4980, 0x8941, 0x4b00, 0x8bc1, 0x8a81, 0x4a40, 0x4e00, 0x8ec1, 0x8f81, 0x4f40, 0x8d01, 0x4dc0, 0x4c80, 0x8c41, 0x4400, 0x84c1, 0x8581, 0x4540, 0x8701, 0x47c0, 0x4680, 0x8641, 0x8201, 0x42c0, 0x4380, 0x8341, 0x4100, 0x81c1, 0x8081, 0x4040];
-
-if (typeof Int32Array !== 'undefined') {
- TABLE = new Int32Array(TABLE);
-}
-
-module.exports = create('crc-16', function(buf, previous) {
- var byte, crc, _i, _len;
- if (!Buffer.isBuffer(buf)) {
- buf = Buffer(buf);
- }
- crc = ~~previous;
- for (_i = 0, _len = buf.length; _i < _len; _i++) {
- byte = buf[_i];
- crc = (TABLE[(crc ^ byte) & 0xff] ^ (crc >> 8)) & 0xffff;
- }
- return crc;
-});
diff --git a/node_modules/express/node_modules/etag/node_modules/crc/lib/crc16_ccitt.js b/node_modules/express/node_modules/etag/node_modules/crc/lib/crc16_ccitt.js
deleted file mode 100644
index 0bdb0bf..0000000
--- a/node_modules/express/node_modules/etag/node_modules/crc/lib/crc16_ccitt.js
+++ /dev/null
@@ -1,25 +0,0 @@
-// Generated by CoffeeScript 1.7.1
-var Buffer, TABLE, create;
-
-Buffer = require('buffer').Buffer;
-
-create = require('./create');
-
-TABLE = [0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de, 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823, 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a, 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41, 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49, 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f, 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067, 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e, 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d, 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c, 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634, 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0];
-
-if (typeof Int32Array !== 'undefined') {
- TABLE = new Int32Array(TABLE);
-}
-
-module.exports = create('ccitt', function(buf, previous) {
- var byte, crc, _i, _len;
- if (!Buffer.isBuffer(buf)) {
- buf = Buffer(buf);
- }
- crc = previous != null ? ~~previous : 0xffff;
- for (_i = 0, _len = buf.length; _i < _len; _i++) {
- byte = buf[_i];
- crc = (TABLE[((crc >> 8) ^ byte) & 0xff] ^ (crc << 8)) & 0xffff;
- }
- return crc;
-});
diff --git a/node_modules/express/node_modules/etag/node_modules/crc/lib/crc16_modbus.js b/node_modules/express/node_modules/etag/node_modules/crc/lib/crc16_modbus.js
deleted file mode 100644
index 52a536a..0000000
--- a/node_modules/express/node_modules/etag/node_modules/crc/lib/crc16_modbus.js
+++ /dev/null
@@ -1,25 +0,0 @@
-// Generated by CoffeeScript 1.7.1
-var Buffer, TABLE, create;
-
-Buffer = require('buffer').Buffer;
-
-create = require('./create');
-
-TABLE = [0x0000, 0xc0c1, 0xc181, 0x0140, 0xc301, 0x03c0, 0x0280, 0xc241, 0xc601, 0x06c0, 0x0780, 0xc741, 0x0500, 0xc5c1, 0xc481, 0x0440, 0xcc01, 0x0cc0, 0x0d80, 0xcd41, 0x0f00, 0xcfc1, 0xce81, 0x0e40, 0x0a00, 0xcac1, 0xcb81, 0x0b40, 0xc901, 0x09c0, 0x0880, 0xc841, 0xd801, 0x18c0, 0x1980, 0xd941, 0x1b00, 0xdbc1, 0xda81, 0x1a40, 0x1e00, 0xdec1, 0xdf81, 0x1f40, 0xdd01, 0x1dc0, 0x1c80, 0xdc41, 0x1400, 0xd4c1, 0xd581, 0x1540, 0xd701, 0x17c0, 0x1680, 0xd641, 0xd201, 0x12c0, 0x1380, 0xd341, 0x1100, 0xd1c1, 0xd081, 0x1040, 0xf001, 0x30c0, 0x3180, 0xf141, 0x3300, 0xf3c1, 0xf281, 0x3240, 0x3600, 0xf6c1, 0xf781, 0x3740, 0xf501, 0x35c0, 0x3480, 0xf441, 0x3c00, 0xfcc1, 0xfd81, 0x3d40, 0xff01, 0x3fc0, 0x3e80, 0xfe41, 0xfa01, 0x3ac0, 0x3b80, 0xfb41, 0x3900, 0xf9c1, 0xf881, 0x3840, 0x2800, 0xe8c1, 0xe981, 0x2940, 0xeb01, 0x2bc0, 0x2a80, 0xea41, 0xee01, 0x2ec0, 0x2f80, 0xef41, 0x2d00, 0xedc1, 0xec81, 0x2c40, 0xe401, 0x24c0, 0x2580, 0xe541, 0x2700, 0xe7c1, 0xe681, 0x2640, 0x2200, 0xe2c1, 0xe381, 0x2340, 0xe101, 0x21c0, 0x2080, 0xe041, 0xa001, 0x60c0, 0x6180, 0xa141, 0x6300, 0xa3c1, 0xa281, 0x6240, 0x6600, 0xa6c1, 0xa781, 0x6740, 0xa501, 0x65c0, 0x6480, 0xa441, 0x6c00, 0xacc1, 0xad81, 0x6d40, 0xaf01, 0x6fc0, 0x6e80, 0xae41, 0xaa01, 0x6ac0, 0x6b80, 0xab41, 0x6900, 0xa9c1, 0xa881, 0x6840, 0x7800, 0xb8c1, 0xb981, 0x7940, 0xbb01, 0x7bc0, 0x7a80, 0xba41, 0xbe01, 0x7ec0, 0x7f80, 0xbf41, 0x7d00, 0xbdc1, 0xbc81, 0x7c40, 0xb401, 0x74c0, 0x7580, 0xb541, 0x7700, 0xb7c1, 0xb681, 0x7640, 0x7200, 0xb2c1, 0xb381, 0x7340, 0xb101, 0x71c0, 0x7080, 0xb041, 0x5000, 0x90c1, 0x9181, 0x5140, 0x9301, 0x53c0, 0x5280, 0x9241, 0x9601, 0x56c0, 0x5780, 0x9741, 0x5500, 0x95c1, 0x9481, 0x5440, 0x9c01, 0x5cc0, 0x5d80, 0x9d41, 0x5f00, 0x9fc1, 0x9e81, 0x5e40, 0x5a00, 0x9ac1, 0x9b81, 0x5b40, 0x9901, 0x59c0, 0x5880, 0x9841, 0x8801, 0x48c0, 0x4980, 0x8941, 0x4b00, 0x8bc1, 0x8a81, 0x4a40, 0x4e00, 0x8ec1, 0x8f81, 0x4f40, 0x8d01, 0x4dc0, 0x4c80, 0x8c41, 0x4400, 0x84c1, 0x8581, 0x4540, 0x8701, 0x47c0, 0x4680, 0x8641, 0x8201, 0x42c0, 0x4380, 0x8341, 0x4100, 0x81c1, 0x8081, 0x4040];
-
-if (typeof Int32Array !== 'undefined') {
- TABLE = new Int32Array(TABLE);
-}
-
-module.exports = create('crc-16-modbus', function(buf, previous) {
- var byte, crc, _i, _len;
- if (!Buffer.isBuffer(buf)) {
- buf = Buffer(buf);
- }
- crc = previous != null ? ~~previous : 0xffff;
- for (_i = 0, _len = buf.length; _i < _len; _i++) {
- byte = buf[_i];
- crc = (TABLE[(crc ^ byte) & 0xff] ^ (crc >> 8)) & 0xffff;
- }
- return crc;
-});
diff --git a/node_modules/express/node_modules/etag/node_modules/crc/lib/crc24.js b/node_modules/express/node_modules/etag/node_modules/crc/lib/crc24.js
deleted file mode 100644
index ff67bc1..0000000
--- a/node_modules/express/node_modules/etag/node_modules/crc/lib/crc24.js
+++ /dev/null
@@ -1,25 +0,0 @@
-// Generated by CoffeeScript 1.7.1
-var Buffer, TABLE, create;
-
-Buffer = require('buffer').Buffer;
-
-create = require('./create');
-
-TABLE = [0x000000, 0x864cfb, 0x8ad50d, 0x0c99f6, 0x93e6e1, 0x15aa1a, 0x1933ec, 0x9f7f17, 0xa18139, 0x27cdc2, 0x2b5434, 0xad18cf, 0x3267d8, 0xb42b23, 0xb8b2d5, 0x3efe2e, 0xc54e89, 0x430272, 0x4f9b84, 0xc9d77f, 0x56a868, 0xd0e493, 0xdc7d65, 0x5a319e, 0x64cfb0, 0xe2834b, 0xee1abd, 0x685646, 0xf72951, 0x7165aa, 0x7dfc5c, 0xfbb0a7, 0x0cd1e9, 0x8a9d12, 0x8604e4, 0x00481f, 0x9f3708, 0x197bf3, 0x15e205, 0x93aefe, 0xad50d0, 0x2b1c2b, 0x2785dd, 0xa1c926, 0x3eb631, 0xb8faca, 0xb4633c, 0x322fc7, 0xc99f60, 0x4fd39b, 0x434a6d, 0xc50696, 0x5a7981, 0xdc357a, 0xd0ac8c, 0x56e077, 0x681e59, 0xee52a2, 0xe2cb54, 0x6487af, 0xfbf8b8, 0x7db443, 0x712db5, 0xf7614e, 0x19a3d2, 0x9fef29, 0x9376df, 0x153a24, 0x8a4533, 0x0c09c8, 0x00903e, 0x86dcc5, 0xb822eb, 0x3e6e10, 0x32f7e6, 0xb4bb1d, 0x2bc40a, 0xad88f1, 0xa11107, 0x275dfc, 0xdced5b, 0x5aa1a0, 0x563856, 0xd074ad, 0x4f0bba, 0xc94741, 0xc5deb7, 0x43924c, 0x7d6c62, 0xfb2099, 0xf7b96f, 0x71f594, 0xee8a83, 0x68c678, 0x645f8e, 0xe21375, 0x15723b, 0x933ec0, 0x9fa736, 0x19ebcd, 0x8694da, 0x00d821, 0x0c41d7, 0x8a0d2c, 0xb4f302, 0x32bff9, 0x3e260f, 0xb86af4, 0x2715e3, 0xa15918, 0xadc0ee, 0x2b8c15, 0xd03cb2, 0x567049, 0x5ae9bf, 0xdca544, 0x43da53, 0xc596a8, 0xc90f5e, 0x4f43a5, 0x71bd8b, 0xf7f170, 0xfb6886, 0x7d247d, 0xe25b6a, 0x641791, 0x688e67, 0xeec29c, 0x3347a4, 0xb50b5f, 0xb992a9, 0x3fde52, 0xa0a145, 0x26edbe, 0x2a7448, 0xac38b3, 0x92c69d, 0x148a66, 0x181390, 0x9e5f6b, 0x01207c, 0x876c87, 0x8bf571, 0x0db98a, 0xf6092d, 0x7045d6, 0x7cdc20, 0xfa90db, 0x65efcc, 0xe3a337, 0xef3ac1, 0x69763a, 0x578814, 0xd1c4ef, 0xdd5d19, 0x5b11e2, 0xc46ef5, 0x42220e, 0x4ebbf8, 0xc8f703, 0x3f964d, 0xb9dab6, 0xb54340, 0x330fbb, 0xac70ac, 0x2a3c57, 0x26a5a1, 0xa0e95a, 0x9e1774, 0x185b8f, 0x14c279, 0x928e82, 0x0df195, 0x8bbd6e, 0x872498, 0x016863, 0xfad8c4, 0x7c943f, 0x700dc9, 0xf64132, 0x693e25, 0xef72de, 0xe3eb28, 0x65a7d3, 0x5b59fd, 0xdd1506, 0xd18cf0, 0x57c00b, 0xc8bf1c, 0x4ef3e7, 0x426a11, 0xc426ea, 0x2ae476, 0xaca88d, 0xa0317b, 0x267d80, 0xb90297, 0x3f4e6c, 0x33d79a, 0xb59b61, 0x8b654f, 0x0d29b4, 0x01b042, 0x87fcb9, 0x1883ae, 0x9ecf55, 0x9256a3, 0x141a58, 0xefaaff, 0x69e604, 0x657ff2, 0xe33309, 0x7c4c1e, 0xfa00e5, 0xf69913, 0x70d5e8, 0x4e2bc6, 0xc8673d, 0xc4fecb, 0x42b230, 0xddcd27, 0x5b81dc, 0x57182a, 0xd154d1, 0x26359f, 0xa07964, 0xace092, 0x2aac69, 0xb5d37e, 0x339f85, 0x3f0673, 0xb94a88, 0x87b4a6, 0x01f85d, 0x0d61ab, 0x8b2d50, 0x145247, 0x921ebc, 0x9e874a, 0x18cbb1, 0xe37b16, 0x6537ed, 0x69ae1b, 0xefe2e0, 0x709df7, 0xf6d10c, 0xfa48fa, 0x7c0401, 0x42fa2f, 0xc4b6d4, 0xc82f22, 0x4e63d9, 0xd11cce, 0x575035, 0x5bc9c3, 0xdd8538];
-
-if (typeof Int32Array !== 'undefined') {
- TABLE = new Int32Array(TABLE);
-}
-
-module.exports = create('crc-24', function(buf, previous) {
- var byte, crc, _i, _len;
- if (!Buffer.isBuffer(buf)) {
- buf = Buffer(buf);
- }
- crc = previous != null ? ~~previous : 0xb704ce;
- for (_i = 0, _len = buf.length; _i < _len; _i++) {
- byte = buf[_i];
- crc = (TABLE[((crc >> 16) ^ byte) & 0xff] ^ (crc << 8)) & 0xffffff;
- }
- return crc;
-});
diff --git a/node_modules/express/node_modules/etag/node_modules/crc/lib/crc32.js b/node_modules/express/node_modules/etag/node_modules/crc/lib/crc32.js
deleted file mode 100644
index 20bc024..0000000
--- a/node_modules/express/node_modules/etag/node_modules/crc/lib/crc32.js
+++ /dev/null
@@ -1,25 +0,0 @@
-// Generated by CoffeeScript 1.7.1
-var Buffer, TABLE, create;
-
-Buffer = require('buffer').Buffer;
-
-create = require('./create');
-
-TABLE = [0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d];
-
-if (typeof Int32Array !== 'undefined') {
- TABLE = new Int32Array(TABLE);
-}
-
-module.exports = create('crc-32', function(buf, previous) {
- var byte, crc, _i, _len;
- if (!Buffer.isBuffer(buf)) {
- buf = Buffer(buf);
- }
- crc = previous === 0 ? 0 : ~~previous ^ -1;
- for (_i = 0, _len = buf.length; _i < _len; _i++) {
- byte = buf[_i];
- crc = TABLE[(crc ^ byte) & 0xff] ^ (crc >>> 8);
- }
- return crc ^ -1;
-});
diff --git a/node_modules/express/node_modules/etag/node_modules/crc/lib/crc8.js b/node_modules/express/node_modules/etag/node_modules/crc/lib/crc8.js
deleted file mode 100644
index 6ebe77c..0000000
--- a/node_modules/express/node_modules/etag/node_modules/crc/lib/crc8.js
+++ /dev/null
@@ -1,25 +0,0 @@
-// Generated by CoffeeScript 1.7.1
-var Buffer, TABLE, create;
-
-Buffer = require('buffer').Buffer;
-
-create = require('./create');
-
-TABLE = [0x00, 0x07, 0x0e, 0x09, 0x1c, 0x1b, 0x12, 0x15, 0x38, 0x3f, 0x36, 0x31, 0x24, 0x23, 0x2a, 0x2d, 0x70, 0x77, 0x7e, 0x79, 0x6c, 0x6b, 0x62, 0x65, 0x48, 0x4f, 0x46, 0x41, 0x54, 0x53, 0x5a, 0x5d, 0xe0, 0xe7, 0xee, 0xe9, 0xfc, 0xfb, 0xf2, 0xf5, 0xd8, 0xdf, 0xd6, 0xd1, 0xc4, 0xc3, 0xca, 0xcd, 0x90, 0x97, 0x9e, 0x99, 0x8c, 0x8b, 0x82, 0x85, 0xa8, 0xaf, 0xa6, 0xa1, 0xb4, 0xb3, 0xba, 0xbd, 0xc7, 0xc0, 0xc9, 0xce, 0xdb, 0xdc, 0xd5, 0xd2, 0xff, 0xf8, 0xf1, 0xf6, 0xe3, 0xe4, 0xed, 0xea, 0xb7, 0xb0, 0xb9, 0xbe, 0xab, 0xac, 0xa5, 0xa2, 0x8f, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9d, 0x9a, 0x27, 0x20, 0x29, 0x2e, 0x3b, 0x3c, 0x35, 0x32, 0x1f, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0d, 0x0a, 0x57, 0x50, 0x59, 0x5e, 0x4b, 0x4c, 0x45, 0x42, 0x6f, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7d, 0x7a, 0x89, 0x8e, 0x87, 0x80, 0x95, 0x92, 0x9b, 0x9c, 0xb1, 0xb6, 0xbf, 0xb8, 0xad, 0xaa, 0xa3, 0xa4, 0xf9, 0xfe, 0xf7, 0xf0, 0xe5, 0xe2, 0xeb, 0xec, 0xc1, 0xc6, 0xcf, 0xc8, 0xdd, 0xda, 0xd3, 0xd4, 0x69, 0x6e, 0x67, 0x60, 0x75, 0x72, 0x7b, 0x7c, 0x51, 0x56, 0x5f, 0x58, 0x4d, 0x4a, 0x43, 0x44, 0x19, 0x1e, 0x17, 0x10, 0x05, 0x02, 0x0b, 0x0c, 0x21, 0x26, 0x2f, 0x28, 0x3d, 0x3a, 0x33, 0x34, 0x4e, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5c, 0x5b, 0x76, 0x71, 0x78, 0x7f, 0x6a, 0x6d, 0x64, 0x63, 0x3e, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2c, 0x2b, 0x06, 0x01, 0x08, 0x0f, 0x1a, 0x1d, 0x14, 0x13, 0xae, 0xa9, 0xa0, 0xa7, 0xb2, 0xb5, 0xbc, 0xbb, 0x96, 0x91, 0x98, 0x9f, 0x8a, 0x8d, 0x84, 0x83, 0xde, 0xd9, 0xd0, 0xd7, 0xc2, 0xc5, 0xcc, 0xcb, 0xe6, 0xe1, 0xe8, 0xef, 0xfa, 0xfd, 0xf4, 0xf3];
-
-if (typeof Int32Array !== 'undefined') {
- TABLE = new Int32Array(TABLE);
-}
-
-module.exports = create('crc-8', function(buf, previous) {
- var byte, crc, _i, _len;
- if (!Buffer.isBuffer(buf)) {
- buf = Buffer(buf);
- }
- crc = ~~previous;
- for (_i = 0, _len = buf.length; _i < _len; _i++) {
- byte = buf[_i];
- crc = TABLE[(crc ^ byte) & 0xff] & 0xff;
- }
- return crc;
-});
diff --git a/node_modules/express/node_modules/etag/node_modules/crc/lib/crc8_1wire.js b/node_modules/express/node_modules/etag/node_modules/crc/lib/crc8_1wire.js
deleted file mode 100644
index b561246..0000000
--- a/node_modules/express/node_modules/etag/node_modules/crc/lib/crc8_1wire.js
+++ /dev/null
@@ -1,25 +0,0 @@
-// Generated by CoffeeScript 1.7.1
-var Buffer, TABLE, create;
-
-Buffer = require('buffer').Buffer;
-
-create = require('./create');
-
-TABLE = [0x00, 0x5e, 0xbc, 0xe2, 0x61, 0x3f, 0xdd, 0x83, 0xc2, 0x9c, 0x7e, 0x20, 0xa3, 0xfd, 0x1f, 0x41, 0x9d, 0xc3, 0x21, 0x7f, 0xfc, 0xa2, 0x40, 0x1e, 0x5f, 0x01, 0xe3, 0xbd, 0x3e, 0x60, 0x82, 0xdc, 0x23, 0x7d, 0x9f, 0xc1, 0x42, 0x1c, 0xfe, 0xa0, 0xe1, 0xbf, 0x5d, 0x03, 0x80, 0xde, 0x3c, 0x62, 0xbe, 0xe0, 0x02, 0x5c, 0xdf, 0x81, 0x63, 0x3d, 0x7c, 0x22, 0xc0, 0x9e, 0x1d, 0x43, 0xa1, 0xff, 0x46, 0x18, 0xfa, 0xa4, 0x27, 0x79, 0x9b, 0xc5, 0x84, 0xda, 0x38, 0x66, 0xe5, 0xbb, 0x59, 0x07, 0xdb, 0x85, 0x67, 0x39, 0xba, 0xe4, 0x06, 0x58, 0x19, 0x47, 0xa5, 0xfb, 0x78, 0x26, 0xc4, 0x9a, 0x65, 0x3b, 0xd9, 0x87, 0x04, 0x5a, 0xb8, 0xe6, 0xa7, 0xf9, 0x1b, 0x45, 0xc6, 0x98, 0x7a, 0x24, 0xf8, 0xa6, 0x44, 0x1a, 0x99, 0xc7, 0x25, 0x7b, 0x3a, 0x64, 0x86, 0xd8, 0x5b, 0x05, 0xe7, 0xb9, 0x8c, 0xd2, 0x30, 0x6e, 0xed, 0xb3, 0x51, 0x0f, 0x4e, 0x10, 0xf2, 0xac, 0x2f, 0x71, 0x93, 0xcd, 0x11, 0x4f, 0xad, 0xf3, 0x70, 0x2e, 0xcc, 0x92, 0xd3, 0x8d, 0x6f, 0x31, 0xb2, 0xec, 0x0e, 0x50, 0xaf, 0xf1, 0x13, 0x4d, 0xce, 0x90, 0x72, 0x2c, 0x6d, 0x33, 0xd1, 0x8f, 0x0c, 0x52, 0xb0, 0xee, 0x32, 0x6c, 0x8e, 0xd0, 0x53, 0x0d, 0xef, 0xb1, 0xf0, 0xae, 0x4c, 0x12, 0x91, 0xcf, 0x2d, 0x73, 0xca, 0x94, 0x76, 0x28, 0xab, 0xf5, 0x17, 0x49, 0x08, 0x56, 0xb4, 0xea, 0x69, 0x37, 0xd5, 0x8b, 0x57, 0x09, 0xeb, 0xb5, 0x36, 0x68, 0x8a, 0xd4, 0x95, 0xcb, 0x29, 0x77, 0xf4, 0xaa, 0x48, 0x16, 0xe9, 0xb7, 0x55, 0x0b, 0x88, 0xd6, 0x34, 0x6a, 0x2b, 0x75, 0x97, 0xc9, 0x4a, 0x14, 0xf6, 0xa8, 0x74, 0x2a, 0xc8, 0x96, 0x15, 0x4b, 0xa9, 0xf7, 0xb6, 0xe8, 0x0a, 0x54, 0xd7, 0x89, 0x6b, 0x35];
-
-if (typeof Int32Array !== 'undefined') {
- TABLE = new Int32Array(TABLE);
-}
-
-module.exports = create('dallas-1-wire', function(buf, previous) {
- var byte, crc, _i, _len;
- if (!Buffer.isBuffer(buf)) {
- buf = Buffer(buf);
- }
- crc = ~~previous;
- for (_i = 0, _len = buf.length; _i < _len; _i++) {
- byte = buf[_i];
- crc = TABLE[(crc ^ byte) & 0xff] & 0xff;
- }
- return crc;
-});
diff --git a/node_modules/express/node_modules/etag/node_modules/crc/lib/create.js b/node_modules/express/node_modules/etag/node_modules/crc/lib/create.js
deleted file mode 100644
index 2d856bd..0000000
--- a/node_modules/express/node_modules/etag/node_modules/crc/lib/create.js
+++ /dev/null
@@ -1,11 +0,0 @@
-// Generated by CoffeeScript 1.7.1
-module.exports = function(model, calc) {
- var fn;
- fn = function(buf, previous) {
- return calc(buf, previous) >>> 0;
- };
- fn.signed = calc;
- fn.unsigned = fn;
- fn.model = model;
- return fn;
-};
diff --git a/node_modules/express/node_modules/etag/node_modules/crc/lib/hex.js b/node_modules/express/node_modules/etag/node_modules/crc/lib/hex.js
deleted file mode 100644
index 0a6aa4c..0000000
--- a/node_modules/express/node_modules/etag/node_modules/crc/lib/hex.js
+++ /dev/null
@@ -1,9 +0,0 @@
-// Generated by CoffeeScript 1.7.1
-module.exports = function(number) {
- var result;
- result = number.toString(16);
- while (result.length % 2) {
- result = "0" + result;
- }
- return result;
-};
diff --git a/node_modules/express/node_modules/etag/node_modules/crc/lib/index.js b/node_modules/express/node_modules/etag/node_modules/crc/lib/index.js
deleted file mode 100644
index 15ac34c..0000000
--- a/node_modules/express/node_modules/etag/node_modules/crc/lib/index.js
+++ /dev/null
@@ -1,11 +0,0 @@
-// Generated by CoffeeScript 1.7.1
-module.exports = {
- crc1: require('./crc1'),
- crc8: require('./crc8'),
- crc81wire: require('./crc8_1wire'),
- crc16: require('./crc16'),
- crc16ccitt: require('./crc16_ccitt'),
- crc16modbus: require('./crc16_modbus'),
- crc24: require('./crc24'),
- crc32: require('./crc32')
-};
diff --git a/node_modules/express/node_modules/etag/node_modules/crc/package.json b/node_modules/express/node_modules/etag/node_modules/crc/package.json
deleted file mode 100644
index 1b2418a..0000000
--- a/node_modules/express/node_modules/etag/node_modules/crc/package.json
+++ /dev/null
@@ -1,57 +0,0 @@
-{
- "name": "crc",
- "version": "3.2.1",
- "description": "Various CRC JavaScript implementations",
- "keywords": [
- "crc"
- ],
- "main": "./lib/index.js",
- "scripts": {
- "test": "mocha test/*.spec.coffee",
- "pretest": "coffee --bare --output ./lib --compile ./src/*.coffee"
- },
- "author": {
- "name": "Alex Gorbatchev",
- "url": "https://github.com/alexgorbatchev"
- },
- "devDependencies": {
- "beautify-benchmark": "^0.2.4",
- "benchmark": "^1.0.0",
- "buffer-crc32": "^0.2.3",
- "chai": "~1.9.1",
- "coffee-errors": "~0.8.6",
- "coffee-script": "~1.7.1",
- "mocha": "*",
- "seedrandom": "^2.3.6"
- },
- "homepage": "https://github.com/alexgorbatchev/node-crc",
- "bugs": {
- "url": "https://github.com/alexgorbatchev/node-crc/issues"
- },
- "repository": {
- "type": "git",
- "url": "git://github.com/alexgorbatchev/node-crc.git"
- },
- "license": "MIT",
- "gitHead": "71caf362b061992bfe4ca8706ee264e764d2e88e",
- "_id": "crc@3.2.1",
- "_shasum": "5d9c8fb77a245cd5eca291e5d2d005334bab0082",
- "_from": "crc@3.2.1",
- "_npmVersion": "1.4.13",
- "_npmUser": {
- "name": "alexgorbatchev",
- "email": "alex.gorbatchev@gmail.com"
- },
- "maintainers": [
- {
- "name": "alexgorbatchev",
- "email": "alex.gorbatchev@gmail.com"
- }
- ],
- "dist": {
- "shasum": "5d9c8fb77a245cd5eca291e5d2d005334bab0082",
- "tarball": "http://registry.npmjs.org/crc/-/crc-3.2.1.tgz"
- },
- "directories": {},
- "_resolved": "https://registry.npmjs.org/crc/-/crc-3.2.1.tgz"
-}
diff --git a/node_modules/express/node_modules/etag/package.json b/node_modules/express/node_modules/etag/package.json
deleted file mode 100644
index 57e6f57..0000000
--- a/node_modules/express/node_modules/etag/package.json
+++ /dev/null
@@ -1,75 +0,0 @@
-{
- "name": "etag",
- "description": "Create simple ETags",
- "version": "1.5.1",
- "contributors": [
- {
- "name": "Douglas Christopher Wilson",
- "email": "doug@somethingdoug.com"
- },
- {
- "name": "David Björklund",
- "email": "david.bjorklund@gmail.com"
- }
- ],
- "license": "MIT",
- "keywords": [
- "etag",
- "http",
- "res"
- ],
- "repository": {
- "type": "git",
- "url": "https://github.com/jshttp/etag"
- },
- "dependencies": {
- "crc": "3.2.1"
- },
- "devDependencies": {
- "benchmark": "1.0.0",
- "beautify-benchmark": "0.2.4",
- "istanbul": "0.3.2",
- "mocha": "~1.21.4",
- "seedrandom": "~2.3.6"
- },
- "files": [
- "LICENSE",
- "HISTORY.md",
- "index.js"
- ],
- "engines": {
- "node": ">= 0.6"
- },
- "scripts": {
- "bench": "node benchmark/index.js",
- "test": "mocha --reporter spec --bail --check-leaks test/",
- "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/",
- "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/"
- },
- "gitHead": "27335e2265388109e50a9f037452081dc8a8260f",
- "bugs": {
- "url": "https://github.com/jshttp/etag/issues"
- },
- "homepage": "https://github.com/jshttp/etag",
- "_id": "etag@1.5.1",
- "_shasum": "54c50de04ee42695562925ac566588291be7e9ea",
- "_from": "etag@~1.5.1",
- "_npmVersion": "1.4.21",
- "_npmUser": {
- "name": "dougwilson",
- "email": "doug@somethingdoug.com"
- },
- "maintainers": [
- {
- "name": "dougwilson",
- "email": "doug@somethingdoug.com"
- }
- ],
- "dist": {
- "shasum": "54c50de04ee42695562925ac566588291be7e9ea",
- "tarball": "http://registry.npmjs.org/etag/-/etag-1.5.1.tgz"
- },
- "directories": {},
- "_resolved": "https://registry.npmjs.org/etag/-/etag-1.5.1.tgz",
- "readme": "ERROR: No README data found!"
-}
diff --git a/node_modules/express/node_modules/finalhandler/HISTORY.md b/node_modules/express/node_modules/finalhandler/HISTORY.md
deleted file mode 100644
index 6f5cb71..0000000
--- a/node_modules/express/node_modules/finalhandler/HISTORY.md
+++ /dev/null
@@ -1,57 +0,0 @@
-0.3.3 / 2015-01-01
-==================
-
- * deps: debug@~2.1.1
- * deps: on-finished@~2.2.0
-
-0.3.2 / 2014-10-22
-==================
-
- * deps: on-finished@~2.1.1
- - Fix handling of pipelined requests
-
-0.3.1 / 2014-10-16
-==================
-
- * deps: debug@~2.1.0
- - Implement `DEBUG_FD` env variable support
-
-0.3.0 / 2014-09-17
-==================
-
- * Terminate in progress response only on error
- * Use `on-finished` to determine request status
-
-0.2.0 / 2014-09-03
-==================
-
- * Set `X-Content-Type-Options: nosniff` header
- * deps: debug@~2.0.0
-
-0.1.0 / 2014-07-16
-==================
-
- * Respond after request fully read
- - prevents hung responses and socket hang ups
- * deps: debug@1.0.4
-
-0.0.3 / 2014-07-11
-==================
-
- * deps: debug@1.0.3
- - Add support for multiple wildcards in namespaces
-
-0.0.2 / 2014-06-19
-==================
-
- * Handle invalid status codes
-
-0.0.1 / 2014-06-05
-==================
-
- * deps: debug@1.0.2
-
-0.0.0 / 2014-06-05
-==================
-
- * Extracted from connect/express
diff --git a/node_modules/express/node_modules/finalhandler/LICENSE b/node_modules/express/node_modules/finalhandler/LICENSE
deleted file mode 100644
index eda2305..0000000
--- a/node_modules/express/node_modules/finalhandler/LICENSE
+++ /dev/null
@@ -1,22 +0,0 @@
-(The MIT License)
-
-Copyright (c) 2014 Douglas Christopher Wilson
-
-## Introduction
-
-This is a node.js driver for MongoDB. It's a port (or close to a port) of the library for ruby at http://github.com/mongodb/mongo-ruby-driver/.
-
-A simple example of inserting a document.
-
-```javascript
- var MongoClient = require('mongodb').MongoClient
- , format = require('util').format;
-
- MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
- if(err) throw err;
-
- var collection = db.collection('test_insert');
- collection.insert({a:2}, function(err, docs) {
-
- collection.count(function(err, count) {
- console.log(format("count = %s", count));
- });
-
- // Locate all the entries using find
- collection.find().toArray(function(err, results) {
- console.dir(results);
- // Let's close the db
- db.close();
- });
- });
- })
-```
-
-## Data types
-
-To store and retrieve the non-JSON MongoDb primitives ([ObjectID](http://www.mongodb.org/display/DOCS/Object+IDs), Long, Binary, [Timestamp](http://www.mongodb.org/display/DOCS/Timestamp+data+type), [DBRef](http://www.mongodb.org/display/DOCS/Database+References#DatabaseReferences-DBRef), Code).
-
-In particular, every document has a unique `_id` which can be almost any type, and by default a 12-byte ObjectID is created. ObjectIDs can be represented as 24-digit hexadecimal strings, but you must convert the string back into an ObjectID before you can use it in the database. For example:
-
-```javascript
- // Get the objectID type
- var ObjectID = require('mongodb').ObjectID;
-
- var idString = '4e4e1638c85e808431000003';
- collection.findOne({_id: new ObjectID(idString)}, console.log) // ok
- collection.findOne({_id: idString}, console.log) // wrong! callback gets undefined
-```
-
-Here are the constructors the non-Javascript BSON primitive types:
-
-```javascript
- // Fetch the library
- var mongo = require('mongodb');
- // Create new instances of BSON types
- new mongo.Long(numberString)
- new mongo.ObjectID(hexString)
- new mongo.Timestamp() // the actual unique number is generated on insert.
- new mongo.DBRef(collectionName, id, dbName)
- new mongo.Binary(buffer) // takes a string or Buffer
- new mongo.Code(code, [context])
- new mongo.Symbol(string)
- new mongo.MinKey()
- new mongo.MaxKey()
- new mongo.Double(number) // Force double storage
-```
-
-### The C/C++ bson parser/serializer
-
-If you are running a version of this library has the C/C++ parser compiled, to enable the driver to use the C/C++ bson parser pass it the option native_parser:true like below
-
-```javascript
- // using native_parser:
- MongoClient.connect('mongodb://127.0.0.1:27017/test'
- , {db: {native_parser: true}}, function(err, db) {})
-```
-
-The C++ parser uses the js objects both for serialization and deserialization.
-
-## GitHub information
-
-The source code is available at http://github.com/mongodb/node-mongodb-native.
-You can either clone the repository or download a tarball of the latest release.
-
-Once you have the source you can test the driver by running
-
- $ make test
-
-in the main directory. You will need to have a mongo instance running on localhost for the integration tests to pass.
-
-## Examples
-
-For examples look in the examples/ directory. You can execute the examples using node.
-
- $ cd examples
- $ node queries.js
-
-## GridStore
-
-The GridStore class allows for storage of binary files in mongoDB using the mongoDB defined files and chunks collection definition.
-
-For more information have a look at [Gridstore](https://github.com/mongodb/node-mongodb-native/blob/master/docs/gridfs.md)
-
-## Replicasets
-
-For more information about how to connect to a replicaset have a look at the extensive documentation [Documentation](http://mongodb.github.com/node-mongodb-native/)
-
-### Primary Key Factories
-
-Defining your own primary key factory allows you to generate your own series of id's
-(this could f.ex be to use something like ISBN numbers). The generated the id needs to be a 12 byte long "string".
-
-Simple example below
-
-```javascript
- var MongoClient = require('mongodb').MongoClient
- , format = require('util').format;
-
- // Custom factory (need to provide a 12 byte array);
- CustomPKFactory = function() {}
- CustomPKFactory.prototype = new Object();
- CustomPKFactory.createPk = function() {
- return new ObjectID("aaaaaaaaaaaa");
- }
-
- MongoClient.connect('mongodb://127.0.0.1:27017/test', {'pkFactory':CustomPKFactory}, function(err, db) {
- if(err) throw err;
-
- db.dropDatabase(function(err, done) {
-
- db.createCollection('test_custom_key', function(err, collection) {
-
- collection.insert({'a':1}, function(err, docs) {
-
- collection.find({'_id':new ObjectID("aaaaaaaaaaaa")}).toArray(function(err, items) {
- console.dir(items);
- // Let's close the db
- db.close();
- });
- });
- });
- });
- });
-```
-
-## Documentation
-
-If this document doesn't answer your questions, see the source of
-[Collection](https://github.com/mongodb/node-mongodb-native/blob/master/lib/mongodb/collection.js)
-or [Cursor](https://github.com/mongodb/node-mongodb-native/blob/master/lib/mongodb/cursor.js),
-or the documentation at MongoDB for query and update formats.
-
-### Find
-
-The find method is actually a factory method to create
-Cursor objects. A Cursor lazily uses the connection the first time
-you call `nextObject`, `each`, or `toArray`.
-
-The basic operation on a cursor is the `nextObject` method
-that fetches the next matching document from the database. The convenience
-methods `each` and `toArray` call `nextObject` until the cursor is exhausted.
-
-Signatures:
-
-```javascript
- var cursor = collection.find(query, [fields], options);
- cursor.sort(fields).limit(n).skip(m).
-
- cursor.nextObject(function(err, doc) {});
- cursor.each(function(err, doc) {});
- cursor.toArray(function(err, docs) {});
-
- cursor.rewind() // reset the cursor to its initial state.
-```
-
-Useful chainable methods of cursor. These can optionally be options of `find` instead of method calls:
-
- * `.limit(n).skip(m)` to control paging.
- * `.sort(fields)` Order by the given fields. There are several equivalent syntaxes:
- * `.sort({field1: -1, field2: 1})` descending by field1, then ascending by field2.
- * `.sort([['field1', 'desc'], ['field2', 'asc']])` same as above
- * `.sort([['field1', 'desc'], 'field2'])` same as above
- * `.sort('field1')` ascending by field1
-
-Other options of `find`:
-
-* `fields` the fields to fetch (to avoid transferring the entire document)
-* `tailable` if true, makes the cursor [tailable](http://www.mongodb.org/display/DOCS/Tailable+Cursors).
-* `batchSize` The number of the subset of results to request the database
-to return for every request. This should initially be greater than 1 otherwise
-the database will automatically close the cursor. The batch size can be set to 1
-with `batchSize(n, function(err){})` after performing the initial query to the database.
-* `hint` See [Optimization: hint](http://www.mongodb.org/display/DOCS/Optimization#Optimization-Hint).
-* `explain` turns this into an explain query. You can also call
-`explain()` on any cursor to fetch the explanation.
-* `snapshot` prevents documents that are updated while the query is active
-from being returned multiple times. See more
-[details about query snapshots](http://www.mongodb.org/display/DOCS/How+to+do+Snapshotted+Queries+in+the+Mongo+Database).
-* `timeout` if false, asks MongoDb not to time out this cursor after an
-inactivity period.
-
-For information on how to create queries, see the
-[MongoDB section on querying](http://www.mongodb.org/display/DOCS/Querying).
-
-```javascript
- var MongoClient = require('mongodb').MongoClient
- , format = require('util').format;
-
- MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
- if(err) throw err;
-
- var collection = db
- .collection('test')
- .find({})
- .limit(10)
- .toArray(function(err, docs) {
- console.dir(docs);
- });
- });
-```
-
-### Insert
-
-Signature:
-
-```javascript
- collection.insert(docs, options, [callback]);
-```
-
-where `docs` can be a single document or an array of documents.
-
-Useful options:
-
-* `w:1` Should always set if you have a callback.
-
-See also: [MongoDB docs for insert](http://www.mongodb.org/display/DOCS/Inserting).
-
-```javascript
- var MongoClient = require('mongodb').MongoClient
- , format = require('util').format;
-
- MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
- if(err) throw err;
-
- db.collection('test').insert({hello: 'world'}, {w:1}, function(err, objects) {
- if (err) console.warn(err.message);
- if (err && err.message.indexOf('E11000 ') !== -1) {
- // this _id was already inserted in the database
- }
- });
- });
-```
-
-Note that there's no reason to pass a callback to the insert or update commands
-unless you use the `w:1` option. If you don't specify `w:1`, then
-your callback will be called immediately.
-
-### Update: update and insert (upsert)
-
-The update operation will update the first document that matches your query
-(or all documents that match if you use `multi:true`).
-If `w:1`, `upsert` is not set, and no documents match, your callback will return 0 documents updated.
-
-See the [MongoDB docs](http://www.mongodb.org/display/DOCS/Updating) for
-the modifier (`$inc`, `$set`, `$push`, etc.) formats.
-
-Signature:
-
-```javascript
- collection.update(criteria, objNew, options, [callback]);
-```
-
-Useful options:
-
-* `w:1` Should always set if you have a callback.
-* `multi:true` If set, all matching documents are updated, not just the first.
-* `upsert:true` Atomically inserts the document if no documents matched.
-
-Example for `update`:
-
-```javascript
- var MongoClient = require('mongodb').MongoClient
- , format = require('util').format;
-
- MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
- if(err) throw err;
-
- db.collection('test').update({hi: 'here'}, {$set: {hi: 'there'}}, {w:1}, function(err) {
- if (err) console.warn(err.message);
- else console.log('successfully updated');
- });
- });
-```
-
-### Find and modify
-
-`findAndModify` is like `update`, but it also gives the updated document to
-your callback. But there are a few key differences between findAndModify and
-update:
-
- 1. The signatures differ.
- 2. You can only findAndModify a single item, not multiple items.
-
-Signature:
-
-```javascript
- collection.findAndModify(query, sort, update, options, callback)
-```
-
-The sort parameter is used to specify which object to operate on, if more than
-one document matches. It takes the same format as the cursor sort (see
-Connection.find above).
-
-See the
-[MongoDB docs for findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command)
-for more details.
-
-Useful options:
-
-* `remove:true` set to a true to remove the object before returning
-* `new:true` set to true if you want to return the modified object rather than the original. Ignored for remove.
-* `upsert:true` Atomically inserts the document if no documents matched.
-
-Example for `findAndModify`:
-
-```javascript
- var MongoClient = require('mongodb').MongoClient
- , format = require('util').format;
-
- MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
- if(err) throw err;
- db.collection('test').findAndModify({hello: 'world'}, [['_id','asc']], {$set: {hi: 'there'}}, {}, function(err, object) {
- if (err) console.warn(err.message);
- else console.dir(object); // undefined if no matching object exists.
- });
- });
-```
-
-### Save
-
-The `save` method is a shorthand for upsert if the document contains an
-`_id`, or an insert if there is no `_id`.
-
-## Release Notes
-
-See HISTORY
-
-## Credits
-
-1. [10gen](http://github.com/mongodb/mongo-ruby-driver/)
-2. [Google Closure Library](http://code.google.com/closure/library/)
-3. [Jonas Raoni Soares Silva](http://jsfromhell.com/classes/binary-parser)
-
-## Contributors
-
-Aaron Heckmann, Christoph Pojer, Pau Ramon Revilla, Nathan White, Emmerman, Seth LaForge, Boris Filipov, Stefan Schärmeli, Tedde Lundgren, renctan, Sergey Ukustov, Ciaran Jessup, kuno, srimonti, Erik Abele, Pratik Daga, Slobodan Utvic, Kristina Chodorow, Yonathan Randolph, Brian Noguchi, Sam Epstein, James Harrison Fisher, Vladimir Dronnikov, Ben Hockey, Henrik Johansson, Simon Weare, Alex Gorbatchev, Shimon Doodkin, Kyle Mueller, Eran Hammer-Lahav, Marcin Ciszak, François de Metz, Vinay Pulim, nstielau, Adam Wiggins, entrinzikyl, Jeremy Selier, Ian Millington, Public Keating, andrewjstone, Christopher Stott, Corey Jewett, brettkiefer, Rob Holland, Senmiao Liu, heroic, gitfy
-
-## License
-
- Copyright 2009 - 2013 MongoDb Inc.
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-
diff --git a/node_modules/mongojs/node_modules/mongodb/index.js b/node_modules/mongojs/node_modules/mongodb/index.js
deleted file mode 100644
index 4f59e9d..0000000
--- a/node_modules/mongojs/node_modules/mongodb/index.js
+++ /dev/null
@@ -1 +0,0 @@
-module.exports = require('./lib/mongodb');
diff --git a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/admin.js b/node_modules/mongojs/node_modules/mongodb/lib/mongodb/admin.js
deleted file mode 100644
index c1f6eb5..0000000
--- a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/admin.js
+++ /dev/null
@@ -1,340 +0,0 @@
-/*!
- * Module dependencies.
- */
-var Collection = require('./collection').Collection,
- Cursor = require('./cursor').Cursor,
- DbCommand = require('./commands/db_command').DbCommand,
- utils = require('./utils');
-
-/**
- * Allows the user to access the admin functionality of MongoDB
- *
- * @class Represents the Admin methods of MongoDB.
- * @param {Object} db Current db instance we wish to perform Admin operations on.
- * @return {Function} Constructor for Admin type.
- */
-function Admin(db) {
- if(!(this instanceof Admin)) return new Admin(db);
-
- /**
- * Retrieve the server information for the current
- * instance of the db client
- *
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from buildInfo or null if an error occured.
- * @return {null} Returns no result
- * @api public
- */
- this.buildInfo = function(callback) {
- this.serverInfo(callback);
- }
-
- /**
- * Retrieve the server information for the current
- * instance of the db client
- *
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from serverInfo or null if an error occured.
- * @return {null} Returns no result
- * @api private
- */
- this.serverInfo = function(callback) {
- db.executeDbAdminCommand({buildinfo:1}, function(err, doc) {
- if(err != null) return callback(err, null);
- return callback(null, doc.documents[0]);
- });
- }
-
- /**
- * Retrieve this db's server status.
- *
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from serverStatus or null if an error occured.
- * @return {null}
- * @api public
- */
- this.serverStatus = function(callback) {
- var self = this;
-
- db.executeDbAdminCommand({serverStatus: 1}, function(err, doc) {
- if(err == null && doc.documents[0].ok === 1) {
- callback(null, doc.documents[0]);
- } else {
- if(err) return callback(err, false);
- return callback(utils.toError(doc.documents[0]), false);
- }
- });
- };
-
- /**
- * Retrieve the current profiling Level for MongoDB
- *
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from profilingLevel or null if an error occured.
- * @return {null} Returns no result
- * @api public
- */
- this.profilingLevel = function(callback) {
- var self = this;
-
- db.executeDbAdminCommand({profile:-1}, function(err, doc) {
- doc = doc.documents[0];
-
- if(err == null && doc.ok === 1) {
- var was = doc.was;
- if(was == 0) return callback(null, "off");
- if(was == 1) return callback(null, "slow_only");
- if(was == 2) return callback(null, "all");
- return callback(new Error("Error: illegal profiling level value " + was), null);
- } else {
- err != null ? callback(err, null) : callback(new Error("Error with profile command"), null);
- }
- });
- };
-
- /**
- * Ping the MongoDB server and retrieve results
- *
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from ping or null if an error occured.
- * @return {null} Returns no result
- * @api public
- */
- this.ping = function(options, callback) {
- // Unpack calls
- var args = Array.prototype.slice.call(arguments, 0);
- db.executeDbAdminCommand({ping: 1}, args.pop());
- }
-
- /**
- * Authenticate against MongoDB
- *
- * @param {String} username The user name for the authentication.
- * @param {String} password The password for the authentication.
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from authenticate or null if an error occured.
- * @return {null} Returns no result
- * @api public
- */
- this.authenticate = function(username, password, callback) {
- db.authenticate(username, password, {authdb: 'admin'}, function(err, doc) {
- return callback(err, doc);
- })
- }
-
- /**
- * Logout current authenticated user
- *
- * @param {Object} [options] Optional parameters to the command.
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from logout or null if an error occured.
- * @return {null} Returns no result
- * @api public
- */
- this.logout = function(callback) {
- db.logout({authdb: 'admin'}, function(err, doc) {
- return callback(err, doc);
- })
- }
-
- /**
- * Add a user to the MongoDB server, if the user exists it will
- * overwrite the current password
- *
- * Options
- * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write
- * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option)
- * - **fsync**, (Boolean, default:false) write waits for fsync before returning, from MongoDB 2.6 on, fsync cannot be combined with journal
- * - **j**, (Boolean, default:false) write waits for journal sync before returning
- *
- * @param {String} username The user name for the authentication.
- * @param {String} password The password for the authentication.
- * @param {Object} [options] additional options during update.
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from addUser or null if an error occured.
- * @return {null} Returns no result
- * @api public
- */
- this.addUser = function(username, password, options, callback) {
- var args = Array.prototype.slice.call(arguments, 2);
- callback = args.pop();
- options = args.length ? args.shift() : {};
- // Set the db name to admin
- options.dbName = 'admin';
- // Add user
- db.addUser(username, password, options, function(err, doc) {
- return callback(err, doc);
- })
- }
- /**
- * Remove a user from the MongoDB server
- *
- * Options
- * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write
- * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option)
- * - **fsync**, (Boolean, default:false) write waits for fsync before returning, from MongoDB 2.6 on, fsync cannot be combined with journal
- * - **j**, (Boolean, default:false) write waits for journal sync before returning
- *
- * @param {String} username The user name for the authentication.
- * @param {Object} [options] additional options during update.
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from removeUser or null if an error occured.
- * @return {null} Returns no result
- * @api public
- */
- this.removeUser = function(username, options, callback) {
- var self = this;
- var args = Array.prototype.slice.call(arguments, 1);
- callback = args.pop();
- options = args.length ? args.shift() : {};
- options.dbName = 'admin';
-
- db.removeUser(username, options, function(err, doc) {
- return callback(err, doc);
- })
- }
-
- /**
- * Set the current profiling level of MongoDB
- *
- * @param {String} level The new profiling level (off, slow_only, all)
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from setProfilingLevel or null if an error occured.
- * @return {null} Returns no result
- * @api public
- */
- this.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;
-
- db.executeDbAdminCommand(command, function(err, doc) {
- doc = doc.documents[0];
-
- if(err == null && doc.ok === 1)
- return callback(null, level);
- return err != null ? callback(err, null) : callback(new Error("Error with profile command"), null);
- });
- };
-
- /**
- * Retrive the current profiling information for MongoDB
- *
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from profilingInfo or null if an error occured.
- * @return {null} Returns no result
- * @api public
- */
- this.profilingInfo = function(callback) {
- try {
- new Cursor(db, new Collection(db, DbCommand.SYSTEM_PROFILE_COLLECTION), {}, {}, {dbName: 'admin'}).toArray(function(err, items) {
- return callback(err, items);
- });
- } catch (err) {
- return callback(err, null);
- }
- };
-
- /**
- * Execute a db command against the Admin database
- *
- * @param {Object} command A command object `{ping:1}`.
- * @param {Object} [options] Optional parameters to the command.
- * @param {Function} callback this will be called after executing this method. The command always return the whole result of the command as the second parameter.
- * @return {null} Returns no result
- * @api public
- */
- this.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
- db.executeDbAdminCommand(command, options, function(err, doc) {
- // Ensure change before event loop executes
- return callback != null ? callback(err, doc) : null;
- });
- }
-
- /**
- * Validate an existing collection
- *
- * @param {String} collectionName The name of the collection to validate.
- * @param {Object} [options] Optional parameters to the command.
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from validateCollection or null if an error occured.
- * @return {null} Returns no result
- * @api public
- */
- this.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]];
- }
- }
-
- db.command(command, function(err, doc) {
- if(err != null) return callback(err, null);
-
- if(doc.ok === 0)
- return callback(new Error("Error with validate command"), null);
- if(doc.result != null && doc.result.constructor != String)
- return callback(new Error("Error with validation data"), null);
- if(doc.result != null && doc.result.match(/exception|corrupt/) != null)
- return callback(new Error("Error: invalid collection " + collectionName), null);
- if(doc.valid != null && !doc.valid)
- return callback(new Error("Error: invalid collection " + collectionName), null);
-
- return callback(null, doc);
- });
- };
-
- /**
- * List the available databases
- *
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from listDatabases or null if an error occured.
- * @return {null} Returns no result
- * @api public
- */
- this.listDatabases = function(callback) {
- // Execute the listAllDatabases command
- db.executeDbAdminCommand({listDatabases:1}, {}, function(err, doc) {
- if(err != null) return callback(err, null);
- return callback(null, doc.documents[0]);
- });
- }
-
- /**
- * Get ReplicaSet status
- *
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from replSetGetStatus or null if an error occured.
- * @return {null}
- * @api public
- */
- this.replSetGetStatus = function(callback) {
- var self = this;
-
- db.executeDbAdminCommand({replSetGetStatus:1}, function(err, doc) {
- if(err == null && doc.documents[0].ok === 1)
- return callback(null, doc.documents[0]);
- if(err) return callback(err, false);
- return callback(utils.toError(doc.documents[0]), false);
- });
- };
-};
-
-/**
- * @ignore
- */
-exports.Admin = Admin;
diff --git a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/aggregation_cursor.js b/node_modules/mongojs/node_modules/mongodb/lib/mongodb/aggregation_cursor.js
deleted file mode 100644
index 10b4e49..0000000
--- a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/aggregation_cursor.js
+++ /dev/null
@@ -1,185 +0,0 @@
-var ReadPreference = require('./connection/read_preference').ReadPreference
- , Readable = require('stream').Readable
- , CommandCursor = require('./command_cursor').CommandCursor
- , utils = require('./utils')
- , shared = require('./collection/shared')
- , inherits = require('util').inherits;
-
-var AggregationCursor = function(collection, serverCapabilities, options) {
- var pipe = [];
- var self = this;
- var results = null;
- var _cursor_options = {};
- // Ensure we have options set up
- options = options == null ? {} : options;
-
- // If a pipeline was provided
- pipe = Array.isArray(options.pipe) ? options.pipe : pipe;
- // Set passed in batchSize if provided
- if(typeof options.batchSize == 'number') _cursor_options.batchSize = options.batchSize;
- // Get the read Preference
- var readPreference = shared._getReadConcern(collection, options);
-
- // Set up
- Readable.call(this, {objectMode: true});
-
- // Contains connection
- var connection = null;
-
- // Set the read preference
- var _options = {
- readPreference: readPreference
- };
-
- // Actual command
- var command = {
- aggregate: collection.collectionName
- , pipeline: pipe
- , cursor: _cursor_options
- }
-
- // If allowDiskUse is set
- if(typeof options.allowDiskUse == 'boolean')
- command.allowDiskUse = options.allowDiskUse;
-
- // Command cursor (if we support one)
- var commandCursor = new CommandCursor(collection.db, collection, command);
-
- this.explain = function(callback) {
- if(typeof callback != 'function')
- throw utils.toError("AggregationCursor explain requires a callback function");
-
- // Add explain options
- _options.explain = true;
- // Execute aggregation pipeline
- collection.aggregate(pipe, _options, function(err, results) {
- if(err) return callback(err, null);
- callback(null, results);
- });
- }
-
- this.get = function(callback) {
- if(typeof callback != 'function')
- throw utils.toError("AggregationCursor get requires a callback function");
- // Checkout a connection
- var _connection = collection.db.serverConfig.checkoutReader(_options.readPreference);
- // Fall back
- if(!_connection.serverCapabilities.hasAggregationCursor) {
- return collection.aggregate(pipe, _options, function(err, results) {
- if(err) return callback(err);
- callback(null, results);
- });
- }
-
- // Execute get using command Cursor
- commandCursor.get({connection: _connection}, callback);
- }
-
- this.getOne = function(callback) {
- if(typeof callback != 'function')
- throw utils.toError("AggregationCursor getOne requires a callback function");
- // Set the limit to 1
- pipe.push({$limit: 1});
- // For now we have no cursor command so let's just wrap existing results
- collection.aggregate(pipe, _options, function(err, results) {
- if(err) return callback(err);
- callback(null, results[0]);
- });
- }
-
- this.each = function(callback) {
- // Checkout a connection if we have none
- if(!connection)
- connection = collection.db.serverConfig.checkoutReader(_options.readPreference);
-
- // Fall back
- if(!connection.serverCapabilities.hasAggregationCursor) {
- collection.aggregate(pipe, _options, function(err, _results) {
- if(err) return callback(err);
-
- while(_results.length > 0) {
- callback(null, _results.shift());
- }
-
- callback(null, null);
- });
- }
-
- // Execute each using command Cursor
- commandCursor.each({connection: connection}, callback);
- }
-
- this.next = function(callback) {
- if(typeof callback != 'function')
- throw utils.toError("AggregationCursor next requires a callback function");
-
- // Checkout a connection if we have none
- if(!connection)
- connection = collection.db.serverConfig.checkoutReader(_options.readPreference);
-
- // Fall back
- if(!connection.serverCapabilities.hasAggregationCursor) {
- if(!results) {
- // For now we have no cursor command so let's just wrap existing results
- return collection.aggregate(pipe, _options, function(err, _results) {
- if(err) return callback(err);
- results = _results;
-
- // Ensure we don't issue undefined
- var item = results.shift();
- callback(null, item ? item : null);
- });
- }
-
- // Ensure we don't issue undefined
- var item = results.shift();
- // Return the item
- return callback(null, item ? item : null);
- }
-
- // Execute next using command Cursor
- commandCursor.next({connection: connection}, callback);
- }
-
- //
- // Close method
- //
- this.close = function(callback) {
- if(typeof callback != 'function')
- throw utils.toError("AggregationCursor close requires a callback function");
-
- // Checkout a connection if we have none
- if(!connection)
- connection = collection.db.serverConfig.checkoutReader(_options.readPreference);
-
- // Fall back
- if(!connection.serverCapabilities.hasAggregationCursor) {
- return callback(null, null);
- }
-
- // Execute next using command Cursor
- commandCursor.close(callback);
- }
-
- //
- // Stream method
- //
- this._read = function(n) {
- self.next(function(err, result) {
- if(err) {
- self.emit('error', err);
- return self.push(null);
- }
-
- self.push(result);
- });
- }
-}
-
-// Inherit from Readable
-if(Readable != null) {
- inherits(AggregationCursor, Readable);
-}
-
-// Exports the Aggregation Framework
-exports.AggregationCursor = AggregationCursor;
diff --git a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/auth/mongodb_cr.js b/node_modules/mongojs/node_modules/mongodb/lib/mongodb/auth/mongodb_cr.js
deleted file mode 100644
index 4f95a6c..0000000
--- a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/auth/mongodb_cr.js
+++ /dev/null
@@ -1,80 +0,0 @@
-var DbCommand = require('../commands/db_command').DbCommand
- , utils = require('../utils')
- , crypto = require('crypto');
-
-var authenticate = function(db, username, password, authdb, options, callback) {
- var numberOfConnections = 0;
- var errorObject = null;
- var numberOfValidConnections = 0;
- var credentialsValid = false;
-
- if(options['connection'] != null) {
- //if a connection was explicitly passed on options, then we have only one...
- numberOfConnections = 1;
- } else {
- // Get the amount of connections in the pool to ensure we have authenticated all comments
- numberOfConnections = db.serverConfig.allRawConnections().length;
- options['onAll'] = true;
- }
-
- // Return connection option
- options.returnConnection = true;
-
- // Execute nonce command
- db.command({'getnonce':1}, options, function(err, result, connection) {
- // Execute on all the connections
- if(err == null) {
- // Nonce used to make authentication request with md5 hash
- var nonce = result.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 cmd
- var cmd = {'authenticate':1, 'user':username, 'nonce':nonce, 'key':key};
-
- // Execute command
- db.db(authdb).command(cmd, {connection:connection}, function(err, result) {
- // Count down
- numberOfConnections = numberOfConnections - 1;
-
- // Ensure we save any error
- if(err) {
- errorObject = err;
- } else {
- credentialsValid = true;
- numberOfValidConnections = numberOfValidConnections + 1;
- }
-
- // Work around the case where the number of connections are 0
- if(numberOfConnections <= 0 && typeof callback == 'function') {
- var internalCallback = callback;
- callback = null;
-
- if(errorObject == null && credentialsValid) {
- db.serverConfig.auth.add('MONGODB-CR', db.databaseName, username, password, authdb);
- // Return callback
- internalCallback(errorObject, true);
- } else if(numberOfValidConnections > 0 && numberOfValidConnections != numberOfConnections
- && credentialsValid) {
- // One or more servers failed on auth (f.ex secondary hanging on foreground indexing)
- db.serverConfig.auth.add('MONGODB-CR', db.databaseName, username, password, authdb);
- // Return callback
- internalCallback(errorObject, true);
- } else {
- internalCallback(errorObject, false);
- }
- }
- });
- }
- });
-}
-
-exports.authenticate = authenticate;
\ No newline at end of file
diff --git a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/auth/mongodb_gssapi.js b/node_modules/mongojs/node_modules/mongodb/lib/mongodb/auth/mongodb_gssapi.js
deleted file mode 100644
index 24f6164..0000000
--- a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/auth/mongodb_gssapi.js
+++ /dev/null
@@ -1,171 +0,0 @@
-var DbCommand = require('../commands/db_command').DbCommand
- , utils = require('../utils')
- , format = require('util').format;
-
-// Kerberos class
-var Kerberos = null;
-var MongoAuthProcess = null;
-// Try to grab the Kerberos class
-try {
- Kerberos = require('kerberos').Kerberos
- // Authentication process for Mongo
- MongoAuthProcess = require('kerberos').processes.MongoAuthProcess
-} catch(err) {}
-
-var authenticate = function(db, username, password, authdb, options, callback) {
- var numberOfConnections = 0;
- var errorObject = null;
- var numberOfValidConnections = 0;
- var credentialsValid = false;
-
- // We don't have the Kerberos library
- if(Kerberos == null) return callback(new Error("Kerberos library is not installed"));
-
- if(options['connection'] != null) {
- //if a connection was explicitly passed on options, then we have only one...
- numberOfConnections = 1;
- } else {
- // Get the amount of connections in the pool to ensure we have authenticated all comments
- numberOfConnections = db.serverConfig.allRawConnections().length;
- options['onAll'] = true;
- }
-
- // Grab all the connections
- var connections = options['connection'] != null ? [options['connection']] : db.serverConfig.allRawConnections();
- var gssapiServiceName = options['gssapiServiceName'] || 'mongodb';
-
- // Authenticate all connections
- for(var i = 0; i < numberOfConnections; i++) {
-
- // Start Auth process for a connection
- GSSAPIInitialize(db, username, password, authdb, gssapiServiceName, connections[i], function(err, result) {
- // Adjust number of connections left to connect
- numberOfConnections = numberOfConnections - 1;
-
- // Ensure we save any error
- if(err) {
- errorObject = err;
- } else {
- credentialsValid = true;
- numberOfValidConnections = numberOfValidConnections + 1;
- }
-
- // Work around the case where the number of connections are 0
- if(numberOfConnections <= 0 && typeof callback == 'function') {
- var internalCallback = callback;
- callback = null;
-
- // We are done
- if(errorObject == null && numberOfConnections == 0) {
- // We authenticated correctly save the credentials
- db.serverConfig.auth.add('GSSAPI', db.databaseName, username, password, authdb, gssapiServiceName);
- // Return valid callback
- return internalCallback(null, true);
- } else if(numberOfValidConnections > 0 && numberOfValidConnections != numberOfConnections
- && credentialsValid) {
- // We authenticated correctly save the credentials
- db.serverConfig.auth.add('GSSAPI', db.databaseName, username, password, authdb, gssapiServiceName);
- // Return valid callback
- return internalCallback(null, true);
- } else {
- return internalCallback(errorObject, false);
- }
- }
- });
- }
-}
-
-//
-// Initialize step
-var GSSAPIInitialize = function(db, username, password, authdb, gssapiServiceName, connection, callback) {
- // Create authenticator
- var mongo_auth_process = new MongoAuthProcess(connection.socketOptions.host, connection.socketOptions.port, gssapiServiceName);
-
- // Perform initialization
- mongo_auth_process.init(username, password, function(err, context) {
- if(err) return callback(err, false);
-
- // Perform the first step
- mongo_auth_process.transition('', function(err, payload) {
- if(err) return callback(err, false);
-
- // Call the next db step
- MongoDBGSSAPIFirstStep(mongo_auth_process, payload, db, username, password, authdb, connection, callback);
- });
- });
-}
-
-//
-// Perform first step against mongodb
-var MongoDBGSSAPIFirstStep = function(mongo_auth_process, payload, db, username, password, authdb, connection, callback) {
- // Build the sasl start command
- var command = {
- saslStart: 1
- , mechanism: 'GSSAPI'
- , payload: payload
- , autoAuthorize: 1
- };
-
- // Execute first sasl step
- db._executeQueryCommand(DbCommand.createDbCommand(db, command, {}, '$external'), {connection:connection}, function(err, doc) {
- if(err) return callback(err, false);
- // Get the payload
- doc = doc.documents[0];
- var db_payload = doc.payload;
-
- mongo_auth_process.transition(doc.payload, function(err, payload) {
- if(err) return callback(err, false);
-
- // MongoDB API Second Step
- MongoDBGSSAPISecondStep(mongo_auth_process, payload, doc, db, username, password, authdb, connection, callback);
- });
- });
-}
-
-//
-// Perform first step against mongodb
-var MongoDBGSSAPISecondStep = function(mongo_auth_process, payload, doc, db, username, password, authdb, connection, callback) {
- // Build Authentication command to send to MongoDB
- var command = {
- saslContinue: 1
- , conversationId: doc.conversationId
- , payload: payload
- };
-
- // Execute the command
- db._executeQueryCommand(DbCommand.createDbCommand(db, command, {}, '$external'), {connection:connection}, function(err, doc) {
- if(err) return callback(err, false);
-
- // Get the result document
- doc = doc.documents[0];
-
- // Call next transition for kerberos
- mongo_auth_process.transition(doc.payload, function(err, payload) {
- if(err) return callback(err, false);
-
- // Call the last and third step
- MongoDBGSSAPIThirdStep(mongo_auth_process, payload, doc, db, username, password, authdb, connection, callback);
- });
- });
-}
-
-var MongoDBGSSAPIThirdStep = function(mongo_auth_process, payload, doc, db, username, password, authdb, connection, callback) {
- // Build final command
- var command = {
- saslContinue: 1
- , conversationId: doc.conversationId
- , payload: payload
- };
-
- // Let's finish the auth process against mongodb
- db._executeQueryCommand(DbCommand.createDbCommand(db, command, {}, '$external'), {connection:connection}, function(err, doc) {
- if(err) return callback(err, false);
-
- mongo_auth_process.transition(null, function(err, payload) {
- if(err) return callback(err, false);
- callback(null, true);
- });
- });
-}
-
-exports.authenticate = authenticate;
\ No newline at end of file
diff --git a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/auth/mongodb_plain.js b/node_modules/mongojs/node_modules/mongodb/lib/mongodb/auth/mongodb_plain.js
deleted file mode 100644
index ee7449e..0000000
--- a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/auth/mongodb_plain.js
+++ /dev/null
@@ -1,78 +0,0 @@
-var DbCommand = require('../commands/db_command').DbCommand
- , utils = require('../utils')
- , crypto = require('crypto')
- , Binary = require('bson').Binary
- , format = require('util').format;
-
-var authenticate = function(db, username, password, options, callback) {
- var numberOfConnections = 0;
- var errorObject = null;
- var numberOfValidConnections = 0;
- var credentialsValid = false;
-
- if(options['connection'] != null) {
- //if a connection was explicitly passed on options, then we have only one...
- numberOfConnections = 1;
- } else {
- // Get the amount of connections in the pool to ensure we have authenticated all comments
- numberOfConnections = db.serverConfig.allRawConnections().length;
- options['onAll'] = true;
- }
-
- // Create payload
- var payload = new Binary(format("\x00%s\x00%s", username, password));
-
- // Let's start the sasl process
- var command = {
- saslStart: 1
- , mechanism: 'PLAIN'
- , payload: payload
- , autoAuthorize: 1
- };
-
- // Grab all the connections
- var connections = options['connection'] != null ? [options['connection']] : db.serverConfig.allRawConnections();
-
- // Authenticate all connections
- for(var i = 0; i < numberOfConnections; i++) {
- var connection = connections[i];
- // Execute first sasl step
- db._executeQueryCommand(DbCommand.createDbCommand(db, command, {}, '$external'), {connection:connection}, function(err, result) {
- // Count down
- numberOfConnections = numberOfConnections - 1;
-
- // Ensure we save any error
- if(err) {
- errorObject = err;
- } else if(result.documents[0].err != null || result.documents[0].errmsg != null){
- errorObject = utils.toError(result.documents[0]);
- } else {
- credentialsValid = true;
- numberOfValidConnections = numberOfValidConnections + 1;
- }
-
- // Work around the case where the number of connections are 0
- if(numberOfConnections <= 0 && typeof callback == 'function') {
- var internalCallback = callback;
- callback = null;
-
- if(errorObject == null && credentialsValid) {
- // We authenticated correctly save the credentials
- db.serverConfig.auth.add('PLAIN', db.databaseName, username, password);
- // Return callback
- internalCallback(errorObject, true);
- } else if(numberOfValidConnections > 0 && numberOfValidConnections != numberOfConnections
- && credentialsValid) {
- // We authenticated correctly save the credentials
- db.serverConfig.auth.add('PLAIN', db.databaseName, username, password);
- // Return callback
- internalCallback(errorObject, true);
- } else {
- internalCallback(errorObject, false);
- }
- }
- });
- }
-}
-
-exports.authenticate = authenticate;
\ No newline at end of file
diff --git a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/auth/mongodb_scram.js b/node_modules/mongojs/node_modules/mongodb/lib/mongodb/auth/mongodb_scram.js
deleted file mode 100644
index 1476522..0000000
--- a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/auth/mongodb_scram.js
+++ /dev/null
@@ -1,247 +0,0 @@
-var DbCommand = require('../commands/db_command').DbCommand
- , utils = require('../utils')
- , crypto = require('crypto')
- , Binary = require('bson').Binary
- , f = require('util').format;
-
-var authenticate = function(db, username, password, authdb, options, callback) {
- var numberOfConnections = 0;
- var errorObject = null;
- var numberOfValidConnections = 0;
- var credentialsValid = false;
-
- // Grab all the connections
- var connections = options['connection'] != null ? [options['connection']] : db.serverConfig.allRawConnections().slice(0);
- if(connections.length > 1) {
- options['onAll'] = true;
- }
-
- // Total connections
- var count = connections.length;
- if(count == 0) return callback(null, null);
-
- // Valid connections
- var numberOfValidConnections = 0;
- var credentialsValid = false;
- var errorObject = null;
-
- // For each connection we need to authenticate
- while(connections.length > 0) {
- // Execute MongoCR
- var executeScram = function(connection) {
- // Clean up the user
- username = username.replace('=', "=3D").replace(',', '=2C');
-
- // Create a random nonce
- var nonce = crypto.randomBytes(24).toString('base64');
- // var nonce = 'MsQUY9iw0T9fx2MUEz6LZPwGuhVvWAhc'
- var firstBare = f("n=%s,r=%s", username, nonce);
-
- // Build command structure
- var cmd = {
- saslStart: 1
- , mechanism: 'SCRAM-SHA-1'
- , payload: new Binary(f("n,,%s", firstBare))
- , autoAuthorize: 1
- }
-
- // Handle the error
- var handleError = function(err, r) {
- if(err) {
- errorObject = err; return false;
- } else if(r['$err']) {
- errorObject = r; return false;
- } else if(r['errmsg']) {
- errorObject = r; return false;
- } else {
- credentialsValid = true;
- numberOfValidConnections = numberOfValidConnections + 1;
- }
-
- return true
- }
-
- // Finish up
- var finish = function(_count, _numberOfValidConnections) {
- if(_count == 0 && _numberOfValidConnections > 0) {
- db.serverConfig.auth.add('SCRAM-SHA-1', db.databaseName, username, password, authdb);
- // Return correct authentication
- return callback(null, true);
- } else if(_count == 0) {
- if(errorObject == null) errorObject = utils.toError(f("failed to authenticate using scram"));
- return callback(errorObject, false);
- }
- }
-
- var handleEnd = function(_err, _r) {
- // Handle any error
- handleError(_err, _r)
- // Adjust the number of connections
- count = count - 1;
- // Execute the finish
- finish(count, numberOfValidConnections);
- }
-
- // Execute start sasl command
- db.db(authdb).command(cmd, { connection: connection }, function(err, r) {
- // Do we have an error, handle it
- if(handleError(err, r) == false) {
- count = count - 1;
-
- if(count == 0 && numberOfValidConnections > 0) {
- // Store the auth details
- addAuthSession(new AuthSession(db, username, password));
- // Return correct authentication
- return callback(null, true);
- } else if(count == 0) {
- if(errorObject == null) errorObject = utils.toError(f("failed to authenticate using scram"));
- return callback(errorObject, false);
- }
-
- return;
- }
-
- // Get the dictionary
- var dict = parsePayload(r.payload.value())
-
- // Unpack dictionary
- var iterations = parseInt(dict.i, 10);
- var salt = dict.s;
- var rnonce = dict.r;
-
- // Set up start of proof
- var withoutProof = f("c=biws,r=%s", rnonce);
- var passwordDig = passwordDigest(username, password);
- var saltedPassword = hi(passwordDig
- , new Buffer(salt, 'base64')
- , iterations);
-
- // Create the client key
- var hmac = crypto.createHmac('sha1', saltedPassword);
- hmac.update(new Buffer("Client Key"));
- var clientKey = hmac.digest();
-
- // Create the stored key
- var hash = crypto.createHash('sha1');
- hash.update(clientKey);
- var storedKey = hash.digest();
-
- // Create the authentication message
- var authMsg = [firstBare, r.payload.value().toString('base64'), withoutProof].join(',');
-
- // Create client signature
- var hmac = crypto.createHmac('sha1', storedKey);
- hmac.update(new Buffer(authMsg));
- var clientSig = hmac.digest();
-
- // Create client proof
- var clientProof = f("p=%s", new Buffer(xor(clientKey, clientSig)).toString('base64'));
-
- // Create client final
- var clientFinal = [withoutProof, clientProof].join(',');
-
- // Generate server key
- var hmac = crypto.createHmac('sha1', saltedPassword);
- hmac.update(new Buffer('Server Key'))
- var serverKey = hmac.digest();
-
- // Generate server signature
- var hmac = crypto.createHmac('sha1', serverKey);
- hmac.update(new Buffer(authMsg))
- var serverSig = hmac.digest();
-
- //
- // Create continue message
- var cmd = {
- saslContinue: 1
- , conversationId: r.conversationId
- , payload: new Binary(new Buffer(clientFinal))
- }
-
- //
- // Execute sasl continue
- db.db(authdb).command(cmd, { connection: connection }, function(err, r) {
- if(r.done == false) {
- var cmd = {
- saslContinue: 1
- , conversationId: r.conversationId
- , payload: new Buffer(0)
- }
-
- db.db(authdb).command(cmd, { connection: connection }, function(err, r) {
- handleEnd(err, r);
- });
- } else {
- handleEnd(err, r);
- }
- });
- });
- }
-
- // Get the connection
- executeScram(connections.shift());
- }
-}
-
-var parsePayload = function(payload) {
- var dict = {};
- var parts = payload.split(',');
-
- for(var i = 0; i < parts.length; i++) {
- var valueParts = parts[i].split('=');
- dict[valueParts[0]] = valueParts[1];
- }
-
- return dict;
-}
-
-var passwordDigest = function(username, password) {
- if(typeof username != 'string') throw utils.toError("username must be a string");
- if(typeof password != 'string') throw utils.toError("password must be a string");
- if(password.length == 0) throw utils.toError("password cannot be empty");
- // Use node md5 generator
- var md5 = crypto.createHash('md5');
- // Generate keys used for authentication
- md5.update(username + ":mongo:" + password);
- return md5.digest('hex');
-}
-
-// XOR two buffers
-var xor = function(a, b) {
- if (!Buffer.isBuffer(a)) a = new Buffer(a)
- if (!Buffer.isBuffer(b)) b = new Buffer(b)
- var res = []
- if (a.length > b.length) {
- for (var i = 0; i < b.length; i++) {
- res.push(a[i] ^ b[i])
- }
- } else {
- for (var i = 0; i < a.length; i++) {
- res.push(a[i] ^ b[i])
- }
- }
- return new Buffer(res);
-}
-
-// Create a final digest
-var hi = function(data, salt, iterations) {
- // Create digest
- var digest = function(msg) {
- var hmac = crypto.createHmac('sha1', data);
- hmac.update(msg);
- var result = hmac.digest()
- return result;
- }
-
- // Create variables
- salt = Buffer.concat([salt, new Buffer('\x00\x00\x00\x01')])
- var ui = u1 = digest(salt);
- for(var i = 0; i < iterations - 1; i++) {
- u1 = digest(u1);
- ui = xor(ui, u1);
- }
-
- return ui;
-}
-
-exports.authenticate = authenticate;
diff --git a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/auth/mongodb_sspi.js b/node_modules/mongojs/node_modules/mongodb/lib/mongodb/auth/mongodb_sspi.js
deleted file mode 100644
index 66ff776..0000000
--- a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/auth/mongodb_sspi.js
+++ /dev/null
@@ -1,155 +0,0 @@
-var DbCommand = require('../commands/db_command').DbCommand
- , utils = require('../utils')
- , format = require('util').format;
-
-// Kerberos class
-var Kerberos = null;
-var MongoAuthProcess = null;
-// Try to grab the Kerberos class
-try {
- Kerberos = require('kerberos').Kerberos
- // Authentication process for Mongo
- MongoAuthProcess = require('kerberos').processes.MongoAuthProcess
-} catch(err) {}
-
-var authenticate = function(db, username, password, authdb, options, callback) {
- var numberOfConnections = 0;
- var errorObject = null;
- var numberOfValidConnections = 0;
- var credentialsValid = false;
-
- // We don't have the Kerberos library
- if(Kerberos == null) return callback(new Error("Kerberos library is not installed"));
-
- if(options['connection'] != null) {
- //if a connection was explicitly passed on options, then we have only one...
- numberOfConnections = 1;
- } else {
- // Get the amount of connections in the pool to ensure we have authenticated all comments
- numberOfConnections = db.serverConfig.allRawConnections().length;
- options['onAll'] = true;
- }
-
- // Set the sspi server name
- var gssapiServiceName = options['gssapiServiceName'] || 'mongodb';
-
- // Grab all the connections
- var connections = db.serverConfig.allRawConnections();
-
- // Authenticate all connections
- for(var i = 0; i < numberOfConnections; i++) {
- // Start Auth process for a connection
- SSIPAuthenticate(db, username, password, authdb, gssapiServiceName, connections[i], function(err, result) {
- // Adjust number of connections left to connect
- numberOfConnections = numberOfConnections - 1;
-
- // Ensure we save any error
- if(err) {
- errorObject = err;
- } else {
- credentialsValid = true;
- numberOfValidConnections = numberOfValidConnections + 1;
- }
-
- // Work around the case where the number of connections are 0
- if(numberOfConnections <= 0 && typeof callback == 'function') {
- var internalCallback = callback;
- callback = null;
-
- if(errorObject == null) {
- // We authenticated correctly save the credentials
- db.serverConfig.auth.add('GSSAPI', db.databaseName, username, password, authdb, gssapiServiceName);
- // Return valid callback
- return internalCallback(null, true);
- } else if(numberOfValidConnections > 0 && numberOfValidConnections != numberOfConnections
- && credentialsValid) {
- // We authenticated correctly save the credentials
- db.serverConfig.auth.add('GSSAPI', db.databaseName, username, password, authdb, gssapiServiceName);
- // Return valid callback
- return internalCallback(null, true);
- } else {
- return internalCallback(errorObject, false);
- }
- }
- });
- }
-}
-
-var SSIPAuthenticate = function(db, username, password, authdb, service_name, connection, callback) {
- // --------------------------------------------------------------
- // Async Version
- // --------------------------------------------------------------
- var command = {
- saslStart: 1
- , mechanism: 'GSSAPI'
- , payload: ''
- , autoAuthorize: 1
- };
-
- // Create authenticator
- var mongo_auth_process = new MongoAuthProcess(connection.socketOptions.host, connection.socketOptions.port, service_name);
-
- // Execute first sasl step
- db._executeQueryCommand(DbCommand.createDbCommand(db, command, {}, '$external'), {connection:connection}, function(err, doc) {
- if(err) return callback(err);
- doc = doc.documents[0];
-
- mongo_auth_process.init(username, password, function(err) {
- if(err) return callback(err);
-
- mongo_auth_process.transition(doc.payload, function(err, payload) {
- if(err) return callback(err);
-
- // Perform the next step against mongod
- var command = {
- saslContinue: 1
- , conversationId: doc.conversationId
- , payload: payload
- };
-
- // Execute the command
- db._executeQueryCommand(DbCommand.createDbCommand(db, command, {}, '$external'), {connection:connection}, function(err, doc) {
- if(err) return callback(err);
- doc = doc.documents[0];
-
- mongo_auth_process.transition(doc.payload, function(err, payload) {
- if(err) return callback(err);
-
- // Perform the next step against mongod
- var command = {
- saslContinue: 1
- , conversationId: doc.conversationId
- , payload: payload
- };
-
- // Execute the command
- db._executeQueryCommand(DbCommand.createDbCommand(db, command, {}, '$external'), {connection:connection}, function(err, doc) {
- if(err) return callback(err);
- doc = doc.documents[0];
-
- mongo_auth_process.transition(doc.payload, function(err, payload) {
- // Perform the next step against mongod
- var command = {
- saslContinue: 1
- , conversationId: doc.conversationId
- , payload: payload
- };
-
- // Execute the command
- db._executeQueryCommand(DbCommand.createDbCommand(db, command, {}, '$external'), {connection:connection}, function(err, doc) {
- if(err) return callback(err);
- doc = doc.documents[0];
-
- if(doc.done) return callback(null, true);
- callback(new Error("Authentication failed"), false);
- });
- });
- });
- });
- });
- });
- });
- });
-}
-
-exports.authenticate = authenticate;
\ No newline at end of file
diff --git a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/auth/mongodb_x509.js b/node_modules/mongojs/node_modules/mongodb/lib/mongodb/auth/mongodb_x509.js
deleted file mode 100644
index 8b8b7c2..0000000
--- a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/auth/mongodb_x509.js
+++ /dev/null
@@ -1,68 +0,0 @@
-var DbCommand = require('../commands/db_command').DbCommand
- , utils = require('../utils')
- , Binary = require('bson').Binary
- , format = require('util').format;
-
-var authenticate = function(db, username, password, options, callback, t) {
- var numberOfConnections = 0;
- var errorObject = null;
- var numberOfValidConnections = 0;
- var credentialsValid = false;
- options = options || {};
-
- if(options['connection'] != null) {
- //if a connection was explicitly passed on options, then we have only one...
- numberOfConnections = 1;
- } else {
- // Get the amount of connections in the pool to ensure we have authenticated all comments
- numberOfConnections = db.serverConfig.allRawConnections().length;
- options['onAll'] = true;
- }
-
- // Let's start the sasl process
- var command = {
- authenticate: 1
- , mechanism: 'MONGODB-X509'
- , user: username
- };
-
- // Grab all the connections
- var connections = options['connection'] != null ? [options['connection']] : db.serverConfig.allRawConnections();
-
- // Authenticate all connections
- for(var i = 0; i < numberOfConnections; i++) {
- var connection = connections[i];
- // Execute first sasl step
- db._executeQueryCommand(DbCommand.createDbCommand(db, command, {}, '$external'), {connection:connection}, function(err, result) {
- // Count down
- numberOfConnections = numberOfConnections - 1;
-
- // Ensure we save any error
- if(err) {
- errorObject = err;
- } else if(result.documents[0].err != null || result.documents[0].errmsg != null){
- errorObject = utils.toError(result.documents[0]);
- } else {
- credentialsValid = true;
- numberOfValidConnections = numberOfValidConnections + 1;
- }
-
- // Work around the case where the number of connections are 0
- if(numberOfConnections <= 0 && typeof callback == 'function') {
- var internalCallback = callback;
- callback = null;
-
- if(errorObject == null && credentialsValid) {
- // We authenticated correctly save the credentials
- db.serverConfig.auth.add('MONGODB-X509', db.databaseName, username, password);
- // Return callback
- internalCallback(errorObject, true);
- } else {
- internalCallback(errorObject, false);
- }
- }
- });
- }
-}
-
-exports.authenticate = authenticate;
\ No newline at end of file
diff --git a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/collection.js b/node_modules/mongojs/node_modules/mongodb/lib/mongodb/collection.js
deleted file mode 100644
index b8e8a70..0000000
--- a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/collection.js
+++ /dev/null
@@ -1,676 +0,0 @@
-/**
- * Module dependencies.
- * @ignore
- */
-var InsertCommand = require('./commands/insert_command').InsertCommand
- , QueryCommand = require('./commands/query_command').QueryCommand
- , DeleteCommand = require('./commands/delete_command').DeleteCommand
- , UpdateCommand = require('./commands/update_command').UpdateCommand
- , DbCommand = require('./commands/db_command').DbCommand
- , ObjectID = require('bson').ObjectID
- , Code = require('bson').Code
- , Cursor = require('./cursor').Cursor
- , utils = require('./utils')
- , shared = require('./collection/shared')
- , core = require('./collection/core')
- , query = require('./collection/query')
- , index = require('./collection/index')
- , geo = require('./collection/geo')
- , commands = require('./collection/commands')
- , aggregation = require('./collection/aggregation')
- , unordered = require('./collection/batch/unordered')
- , ordered = require('./collection/batch/ordered');
-
-/**
- * Create a new Collection instance (INTERNAL TYPE, do not instantiate directly)
- *
- * Options
- * - **readPreference** {String}, the prefered read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
- * - **slaveOk** {Boolean, default:false}, Allow reads from secondaries.
- * - **serializeFunctions** {Boolean, default:false}, serialize functions on the document.
- * - **raw** {Boolean, default:false}, perform all operations using raw bson objects.
- * - **pkFactory** {Object}, object overriding the basic ObjectID primary key generation.
- *
- * @class Represents a Collection
- * @param {Object} db db instance.
- * @param {String} collectionName collection name.
- * @param {Object} [pkFactory] alternative primary key factory.
- * @param {Object} [options] additional options for the collection.
- * @return {Object} a collection instance.
- */
-function Collection (db, collectionName, pkFactory, options) {
- if(!(this instanceof Collection)) return new Collection(db, collectionName, pkFactory, options);
-
- shared.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;
-
- // Assign the right collection level readPreference
- if(options && options.readPreference) {
- this.readPreference = options.readPreference;
- } else if(this.db.options.readPreference) {
- this.readPreference = this.db.options.readPreference;
- } else if(this.db.serverConfig.options.readPreference) {
- this.readPreference = this.db.serverConfig.options.readPreference;
- }
-
- // Set custom primary key factory if provided
- this.pkFactory = pkFactory == null
- ? ObjectID
- : pkFactory;
-
- // Server Capabilities
- this.serverCapabilities = this.db.serverConfig._serverCapabilities;
-}
-
-/**
- * Inserts a single document or a an array of documents into MongoDB.
- *
- * Options
- * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write
- * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option)
- * - **fsync**, (Boolean, default:false) write waits for fsync before returning, from MongoDB 2.6 on, fsync cannot be combined with journal
- * - **j**, (Boolean, default:false) write waits for journal sync before returning
- * - **continueOnError/keepGoing** {Boolean, default:false}, keep inserting documents even if one document has an error, *mongodb 1.9.1 >*.
- * - **serializeFunctions** {Boolean, default:false}, serialize functions on the document.
- * - **forceServerObjectId** {Boolean, default:false}, let server assign ObjectId instead of the driver
- * - **checkKeys** {Boolean, default:true}, allows for disabling of document key checking (WARNING OPENS YOU UP TO INJECTION ATTACKS)
- * - **fullResult** {Boolean, default:false}, returns the full result document (document returned will differ by server version)
- *
- * @param {Array|Object} docs
- * @param {Object} [options] optional options for insert command
- * @param {Function} [callback] optional callback for the function, must be provided when using a writeconcern
- * @return {Collection}
- * @api public
- */
-Collection.prototype.insert = function() { return core.insert; }();
-
-/**
- * Removes documents specified by `selector` from the db.
- *
- * Options
- * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write
- * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option)
- * - **fsync**, (Boolean, default:false) write waits for fsync before returning, from MongoDB 2.6 on, fsync cannot be combined with journal
- * - **j**, (Boolean, default:false) write waits for journal sync before returning
- * - **single** {Boolean, default:false}, removes the first document found.
- * - **fullResult** {Boolean, default:false}, returns the full result document (document returned will differ by server version)
- *
- * @param {Object} [selector] optional select, no selector is equivalent to removing all documents.
- * @param {Object} [options] additional options during remove.
- * @param {Function} [callback] must be provided if you performing a remove with a writeconcern
- * @return {null}
- * @api public
- */
-Collection.prototype.remove = function() { return core.remove; }();
-
-/**
- * Renames the collection.
- *
- * Options
- * - **dropTarget** {Boolean, default:false}, drop the target name collection if it previously exists.
- *
- * @param {String} newName the new name of the collection.
- * @param {Object} [options] returns option results.
- * @param {Function} callback the callback accepting the result
- * @return {null}
- * @api public
- */
-Collection.prototype.rename = function() { return commands.rename; }();
-
-/**
- * Save a document. Simple full document replacement function. Not recommended for efficiency, use atomic
- * operators and update instead for more efficient operations.
- *
- * Options
- * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write
- * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option)
- * - **fsync**, (Boolean, default:false) write waits for fsync before returning, from MongoDB 2.6 on, fsync cannot be combined with journal
- * - **j**, (Boolean, default:false) write waits for journal sync before returning
- *
- * @param {Object} [doc] the document to save
- * @param {Object} [options] additional options during remove.
- * @param {Function} [callback] must be provided if you performing an update with a writeconcern
- * @return {null}
- * @api public
- */
-Collection.prototype.save = function() { return core.save; }();
-
-/**
- * Updates documents.
- *
- * Options
- * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write
- * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option)
- * - **fsync**, (Boolean, default:false) write waits for fsync before returning, from MongoDB 2.6 on, fsync cannot be combined with journal
- * - **j**, (Boolean, default:false) write waits for journal sync before returning
- * - **upsert** {Boolean, default:false}, perform an upsert operation.
- * - **multi** {Boolean, default:false}, update all documents matching the selector.
- * - **serializeFunctions** {Boolean, default:false}, serialize functions on the document.
- * - **checkKeys** {Boolean, default:true}, allows for disabling of document key checking (WARNING OPENS YOU UP TO INJECTION ATTACKS)
- * - **fullResult** {Boolean, default:false}, returns the full result document (document returned will differ by server version)
- *
- * @param {Object} selector the query to select the document/documents to be updated
- * @param {Object} document the fields/vals to be updated, or in the case of an upsert operation, inserted.
- * @param {Object} [options] additional options during update.
- * @param {Function} [callback] must be provided if you performing an update with a writeconcern
- * @return {null}
- * @api public
- */
-Collection.prototype.update = function() { return core.update; }();
-
-/**
- * The distinct command returns returns a list of distinct values for the given key across a collection.
- *
- * Options
- * - **readPreference** {String}, the preferred read preference, require('mongodb').ReadPreference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
- *
- * @param {String} key key to run distinct against.
- * @param {Object} [query] option query to narrow the returned objects.
- * @param {Object} [options] additional options during update.
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from distinct or null if an error occured.
- * @return {null}
- * @api public
- */
-Collection.prototype.distinct = function() { return commands.distinct; }();
-
-/**
- * Count number of matching documents in the db to a query.
- *
- * Options
- * - **skip** {Number}, The number of documents to skip for the count.
- * - **limit** {Number}, The limit of documents to count.
- * - **readPreference** {String}, the preferred read preference, require('mongodb').ReadPreference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
- *
- * @param {Object} [query] query to filter by before performing count.
- * @param {Object} [options] additional options during count.
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the count method or null if an error occured.
- * @return {null}
- * @api public
- */
-Collection.prototype.count = function() { return commands.count; }();
-
-/**
- * Drop the collection
- *
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the drop method or null if an error occured.
- * @return {null}
- * @api public
- */
-Collection.prototype.drop = function drop(callback) {
- this.db.dropCollection(this.collectionName, callback);
-};
-
-/**
- * Find and update a document.
- *
- * Options
- * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write
- * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option)
- * - **fsync**, (Boolean, default:false) write waits for fsync before returning, from MongoDB 2.6 on, fsync cannot be combined with journal
- * - **j**, (Boolean, default:false) write waits for journal sync before returning
- * - **remove** {Boolean, default:false}, set to true to remove the object before returning.
- * - **upsert** {Boolean, default:false}, perform an upsert operation.
- * - **new** {Boolean, default:false}, set to true if you want to return the modified object rather than the original. Ignored for remove.
- *
- * @param {Object} query query object to locate the object to modify
- * @param {Array} sort - if multiple docs match, choose the first one in the specified sort order as the object to manipulate
- * @param {Object} doc - the fields/vals to be updated
- * @param {Object} [options] additional options during update.
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the findAndModify method or null if an error occured.
- * @return {null}
- * @api public
- */
-Collection.prototype.findAndModify = function() { return core.findAndModify; }();
-
-/**
- * Find and remove a document
- *
- * Options
- * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write
- * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option)
- * - **fsync**, (Boolean, default:false) write waits for fsync before returning, from MongoDB 2.6 on, fsync cannot be combined with journal
- * - **j**, (Boolean, default:false) write waits for journal sync before returning
- *
- * @param {Object} query query object to locate the object to modify
- * @param {Array} sort - if multiple docs match, choose the first one in the specified sort order as the object to manipulate
- * @param {Object} [options] additional options during update.
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the findAndRemove method or null if an error occured.
- * @return {null}
- * @api public
- */
-Collection.prototype.findAndRemove = function() { return core.findAndRemove; }();
-
-/**
- * Creates a cursor for a query that can be used to iterate over results from MongoDB
- *
- * Various argument possibilities
- * - callback?
- * - selector, callback?,
- * - selector, fields, callback?
- * - selector, options, callback?
- * - selector, fields, options, callback?
- * - selector, fields, skip, limit, callback?
- * - selector, fields, skip, limit, timeout, callback?
- *
- * Options
- * - **limit** {Number, default:0}, sets the limit of documents returned in the query.
- * - **sort** {Array | Object}, set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc.
- * - **fields** {Object}, the fields to return in the query. Object of fields to include or exclude (not both), {'a':1}
- * - **skip** {Number, default:0}, set to skip N documents ahead in your query (useful for pagination).
- * - **hint** {Object}, tell the query to use specific indexes in the query. Object of indexes to use, {'_id':1}
- * - **explain** {Boolean, default:false}, explain the query instead of returning the data.
- * - **snapshot** {Boolean, default:false}, snapshot query.
- * - **timeout** {Boolean, default:false}, specify if the cursor can timeout.
- * - **tailable** {Boolean, default:false}, specify if the cursor is tailable.
- * - **tailableRetryInterval** {Number, default:100}, specify the miliseconds between getMores on tailable cursor.
- * - **numberOfRetries** {Number, default:5}, specify the number of times to retry the tailable cursor.
- * - **awaitdata** {Boolean, default:false} allow the cursor to wait for data, only applicable for tailable cursor.
- * - **oplogReplay** {Boolean, default:false} sets an internal flag, only applicable for tailable cursor.
- * - **exhaust** {Boolean, default:false} have the server send all the documents at once as getMore packets, not recommended.
- * - **batchSize** {Number, default:0}, set the batchSize for the getMoreCommand when iterating over the query results.
- * - **returnKey** {Boolean, default:false}, only return the index key.
- * - **maxScan** {Number}, Limit the number of items to scan.
- * - **min** {Number}, Set index bounds.
- * - **max** {Number}, Set index bounds.
- * - **showDiskLoc** {Boolean, default:false}, Show disk location of results.
- * - **comment** {String}, You can put a $comment field on a query to make looking in the profiler logs simpler.
- * - **raw** {Boolean, default:false}, Return all BSON documents as Raw Buffer documents.
- * - **readPreference** {String}, the preferred read preference, require('mongodb').ReadPreference ((ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
- * - **numberOfRetries** {Number, default:5}, if using awaidata specifies the number of times to retry on timeout.
- * - **partial** {Boolean, default:false}, specify if the cursor should return partial results when querying against a sharded system
- * - **maxTimeMS** {Number}, number of miliseconds to wait before aborting the query.
- *
- * @param {Object|ObjectID} query query object to locate the object to modify
- * @param {Object} [options] additional options during update.
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the find method or null if an error occured.
- * @return {Cursor} returns a cursor to the query
- * @api public
- */
-Collection.prototype.find = function() { return query.find; }();
-
-/**
- * Finds a single document based on the query
- *
- * Various argument possibilities
- * - callback?
- * - selector, callback?,
- * - selector, fields, callback?
- * - selector, options, callback?
- * - selector, fields, options, callback?
- * - selector, fields, skip, limit, callback?
- * - selector, fields, skip, limit, timeout, callback?
- *
- * Options
- * - **limit** {Number, default:0}, sets the limit of documents returned in the query.
- * - **sort** {Array | Object}, set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc.
- * - **fields** {Object}, the fields to return in the query. Object of fields to include or exclude (not both), {'a':1}
- * - **skip** {Number, default:0}, set to skip N documents ahead in your query (useful for pagination).
- * - **hint** {Object}, tell the query to use specific indexes in the query. Object of indexes to use, {'_id':1}
- * - **explain** {Boolean, default:false}, explain the query instead of returning the data.
- * - **snapshot** {Boolean, default:false}, snapshot query.
- * - **timeout** {Boolean, default:false}, specify if the cursor can timeout.
- * - **tailable** {Boolean, default:false}, specify if the cursor is tailable.
- * - **batchSize** {Number, default:0}, set the batchSize for the getMoreCommand when iterating over the query results.
- * - **returnKey** {Boolean, default:false}, only return the index key.
- * - **maxScan** {Number}, Limit the number of items to scan.
- * - **min** {Number}, Set index bounds.
- * - **max** {Number}, Set index bounds.
- * - **showDiskLoc** {Boolean, default:false}, Show disk location of results.
- * - **comment** {String}, You can put a $comment field on a query to make looking in the profiler logs simpler.
- * - **raw** {Boolean, default:false}, Return all BSON documents as Raw Buffer documents.
- * - **readPreference** {String}, the preferred read preference, require('mongodb').ReadPreference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
- * - **partial** {Boolean, default:false}, specify if the cursor should return partial results when querying against a sharded system
- * - **maxTimeMS** {Number}, number of miliseconds to wait before aborting the query.
- *
- * @param {Object|ObjectID} query query object to locate the object to modify
- * @param {Object} [options] additional options during update.
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the findOne method or null if an error occured.
- * @return {Cursor} returns a cursor to the query
- * @api public
- */
-Collection.prototype.findOne = function() { return query.findOne; }();
-
-/**
- * Creates an index on the collection.
- *
- * Options
- * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write
- * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option)
- * - **fsync**, (Boolean, default:false) write waits for fsync before returning, from MongoDB 2.6 on, fsync cannot be combined with journal
- * - **j**, (Boolean, default:false) write waits for journal sync before returning
- * - **unique** {Boolean, default:false}, creates an unique index.
- * - **sparse** {Boolean, default:false}, creates a sparse index.
- * - **background** {Boolean, default:false}, creates the index in the background, yielding whenever possible.
- * - **min** {Number}, for geospatial indexes set the lower bound for the co-ordinates.
- * - **max** {Number}, for geospatial indexes set the high bound for the co-ordinates.
- * - **v** {Number}, specify the format version of the indexes.
- * - **expireAfterSeconds** {Number}, allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher)
- * - **name** {String}, override the autogenerated index name (useful if the resulting name is larger than 128 bytes)
- *
- * @param {Object} fieldOrSpec fieldOrSpec that defines the index.
- * @param {Object} [options] additional options during update.
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the createIndex method or null if an error occured.
- * @return {null}
- * @api public
- */
-Collection.prototype.createIndex = function() { return index.createIndex; }();
-
-/**
- * Ensures that an index exists, if it does not it creates it
- *
- * Options
- * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write
- * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option)
- * - **fsync**, (Boolean, default:false) write waits for fsync before returning, from MongoDB 2.6 on, fsync cannot be combined with journal
- * - **j**, (Boolean, default:false) write waits for journal sync before returning
- * - **unique** {Boolean, default:false}, creates an unique index.
- * - **sparse** {Boolean, default:false}, creates a sparse index.
- * - **background** {Boolean, default:false}, creates the index in the background, yielding whenever possible.
- * - **min** {Number}, for geospatial indexes set the lower bound for the co-ordinates.
- * - **max** {Number}, for geospatial indexes set the high bound for the co-ordinates.
- * - **v** {Number}, specify the format version of the indexes.
- * - **expireAfterSeconds** {Number}, allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher)
- * - **name** {String}, override the autogenerated index name (useful if the resulting name is larger than 128 bytes)
- *
- * @param {Object} fieldOrSpec fieldOrSpec that defines the index.
- * @param {Object} [options] additional options during update.
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the ensureIndex method or null if an error occured.
- * @return {null}
- * @api public
- */
-Collection.prototype.ensureIndex = function() { return index.ensureIndex; }();
-
-/**
- * Retrieves this collections index info.
- *
- * Options
- * - **full** {Boolean, default:false}, returns the full raw index information.
- *
- * @param {Object} [options] additional options during update.
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the indexInformation method or null if an error occured.
- * @return {null}
- * @api public
- */
-Collection.prototype.indexInformation = function() { return index.indexInformation; }();
-
-/**
- * Drops an index from this collection.
- *
- * @param {String} name
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the dropIndex method or null if an error occured.
- * @return {null}
- * @api public
- */
-Collection.prototype.dropIndex = function dropIndex (name, options, callback) {
- if(typeof options == 'function') {
- callback = options;
- options = {};
- }
- // Execute dropIndex command
- this.db.dropIndex(this.collectionName, name, options, callback);
-};
-
-/**
- * Drops all indexes from this collection.
- *
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the dropAllIndexes method or null if an error occured.
- * @return {null}
- * @api public
- */
-Collection.prototype.dropAllIndexes = function() { return index.dropAllIndexes; }();
-
-/**
- * Drops all indexes from this collection.
- *
- * @deprecated
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the dropIndexes method or null if an error occured.
- * @return {null}
- * @api private
- */
-Collection.prototype.dropIndexes = function() { return Collection.prototype.dropAllIndexes; }();
-
-/**
- * Reindex all indexes on the collection
- * Warning: reIndex is a blocking operation (indexes are rebuilt in the foreground) and will be slow for large collections.
- *
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the reIndex method or null if an error occured.
- * @return {null}
- * @api public
-**/
-Collection.prototype.reIndex = function(options, callback) {
- if(typeof options == 'function') {
- callback = options;
- options = {};
- }
- // Execute reIndex
- this.db.reIndex(this.collectionName, options, callback);
-}
-
-/**
- * Run Map Reduce across a collection. Be aware that the inline option for out will return an array of results not a collection.
- *
- * Options
- * - **out** {Object}, sets the output target for the map reduce job. *{inline:1} | {replace:'collectionName'} | {merge:'collectionName'} | {reduce:'collectionName'}*
- * - **query** {Object}, query filter object.
- * - **sort** {Object}, sorts the input objects using this key. Useful for optimization, like sorting by the emit key for fewer reduces.
- * - **limit** {Number}, number of objects to return from collection.
- * - **keeptemp** {Boolean, default:false}, keep temporary data.
- * - **finalize** {Function | String}, finalize function.
- * - **scope** {Object}, can pass in variables that can be access from map/reduce/finalize.
- * - **jsMode** {Boolean, default:false}, it is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X.
- * - **verbose** {Boolean, default:false}, provide statistics on job execution time.
- * - **readPreference** {String, only for inline results}, the preferred read preference, require('mongodb').ReadPreference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
- *
- * @param {Function|String} map the mapping function.
- * @param {Function|String} reduce the reduce function.
- * @param {Objects} [options] options for the map reduce job.
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the mapReduce method or null if an error occured.
- * @return {null}
- * @api public
- */
-Collection.prototype.mapReduce = function() { return aggregation.mapReduce; }();
-
-/**
- * Run a group command across a collection
- *
- * Options
- * - **readPreference** {String}, the preferred read preference, require('mongodb').ReadPreference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
- *
- * @param {Object|Array|Function|Code} keys an object, array or function expressing the keys to group by.
- * @param {Object} condition an optional condition that must be true for a row to be considered.
- * @param {Object} initial initial value of the aggregation counter object.
- * @param {Function|Code} reduce the reduce function aggregates (reduces) the objects iterated
- * @param {Function|Code} finalize an optional function to be run on each item in the result set just before the item is returned.
- * @param {Boolean} command specify if you wish to run using the internal group command or using eval, default is true.
- * @param {Object} [options] additional options during update.
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the group method or null if an error occured.
- * @return {null}
- * @api public
- */
-Collection.prototype.group = function() { return aggregation.group; }();
-
-/**
- * Returns the options of the collection.
- *
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the options method or null if an error occured.
- * @return {null}
- * @api public
- */
-Collection.prototype.options = function() { return commands.options; }();
-
-/**
- * Returns if the collection is a capped collection
- *
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the isCapped method or null if an error occured.
- * @return {null}
- * @api public
- */
-Collection.prototype.isCapped = function() { return commands.isCapped; }();
-
-/**
- * Checks if one or more indexes exist on the collection
- *
- * @param {String|Array} indexNames check if one or more indexes exist on the collection.
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the indexExists method or null if an error occured.
- * @return {null}
- * @api public
- */
-Collection.prototype.indexExists = function() { return index.indexExists; }();
-
-/**
- * Execute the geoNear command to search for items in the collection
- *
- * Options
- * - **num** {Number}, max number of results to return.
- * - **minDistance** {Number}, include results starting at minDistance from a point (2.6 or higher)
- * - **maxDistance** {Number}, include results up to maxDistance from the point.
- * - **distanceMultiplier** {Number}, include a value to multiply the distances with allowing for range conversions.
- * - **query** {Object}, filter the results by a query.
- * - **spherical** {Boolean, default:false}, perform query using a spherical model.
- * - **uniqueDocs** {Boolean, default:false}, the closest location in a document to the center of the search region will always be returned MongoDB > 2.X.
- * - **includeLocs** {Boolean, default:false}, include the location data fields in the top level of the results MongoDB > 2.X.
- * - **readPreference** {String}, the preferred read preference, require('mongodb').ReadPreference ((ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
- *
- * @param {Number} x point to search on the x axis, ensure the indexes are ordered in the same order.
- * @param {Number} y point to search on the y axis, ensure the indexes are ordered in the same order.
- * @param {Objects} [options] options for the map reduce job.
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the geoNear method or null if an error occured.
- * @return {null}
- * @api public
- */
-Collection.prototype.geoNear = function() { return geo.geoNear; }();
-
-/**
- * Execute a geo search using a geo haystack index on a collection.
- *
- * Options
- * - **maxDistance** {Number}, include results up to maxDistance from the point.
- * - **search** {Object}, filter the results by a query.
- * - **limit** {Number}, max number of results to return.
- * - **readPreference** {String}, the preferred read preference, require('mongodb').ReadPreference ((ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
- *
- * @param {Number} x point to search on the x axis, ensure the indexes are ordered in the same order.
- * @param {Number} y point to search on the y axis, ensure the indexes are ordered in the same order.
- * @param {Objects} [options] options for the map reduce job.
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the geoHaystackSearch method or null if an error occured.
- * @return {null}
- * @api public
- */
-Collection.prototype.geoHaystackSearch = function() { return geo.geoHaystackSearch; }();
-
-/**
- * Retrieve all the indexes on the collection.
- *
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the indexes method or null if an error occured.
- * @return {null}
- * @api public
- */
-Collection.prototype.indexes = function indexes(callback) {
- this.db.indexInformation(this.collectionName, {full:true}, callback);
-}
-
-/**
- * Execute an aggregation framework pipeline against the collection, needs MongoDB >= 2.2
- *
- * Options
- * - **readPreference** {String}, the preferred read preference, require('mongodb').ReadPreference ((ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
- * - **cursor** {Object}, return the query as cursor, on 2.6 > it returns as a real cursor on pre 2.6 it returns as an emulated cursor.
- * - **cursor.batchSize** {Number}, the batchSize for the cursor
- * - **out** {String}, the collection name to where to write the results from the aggregation (MongoDB 2.6 or higher). Warning any existing collection will be overwritten.
- * - **explain** {Boolean, default:false}, explain returns the aggregation execution plan (requires mongodb 2.6 >).
- * - **allowDiskUse** {Boolean, default:false}, allowDiskUse lets the server know if it can use disk to store temporary results for the aggregation (requires mongodb 2.6 >).
- *
- * @param {Array} array containing all the aggregation framework commands for the execution.
- * @param {Object} [options] additional options during update.
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the aggregate method or null if an error occured.
- * @return {null}
- * @api public
- */
-Collection.prototype.aggregate = function() { return aggregation.aggregate; }();
-
-/**
- * Get all the collection statistics.
- *
- * Options
- * - **scale** {Number}, divide the returned sizes by scale value.
- * - **readPreference** {String}, the preferred read preference, require('mongodb').ReadPreference ((ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
- *
- * @param {Objects} [options] options for the stats command.
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the stats method or null if an error occured.
- * @return {null}
- * @api public
- */
-Collection.prototype.stats = function() { return commands.stats; }();
-
-/**
- * Initiate a Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order.
- *
- * Options
- * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write
- * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option)
- * - **fsync**, (Boolean, default:false) write waits for fsync before returning, from MongoDB 2.6 on, fsync cannot be combined with journal
- * - **j**, (Boolean, default:false) write waits for journal sync before returning
- *
- * @param {Objects} [options] options for the initializeUnorderedBatch
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. The second argument will be a UnorderedBulkOperation object.
- * @return {UnorderedBulkOperation}
- * @api public
- */
-Collection.prototype.initializeUnorderedBulkOp = function() { return unordered.initializeUnorderedBulkOp; }();
-
-/**
- * Initiate an In order bulk write operation, operations will be serially executed in the order they are added, creating a new operation for each switch in types.
- *
- * Options
- * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write
- * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option)
- * - **fsync**, (Boolean, default:false) write waits for fsync before returning, from MongoDB 2.6 on, fsync cannot be combined with journal
- * - **j**, (Boolean, default:false) write waits for journal sync before returning
- *
- * @param {Objects} [options] options for the initializeOrderedBulkOp
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. The second argument will be a OrderedBulkOperation object.
- * @return {OrderedBulkOperation}
- * @api public
- */
-Collection.prototype.initializeOrderedBulkOp = function() { return ordered.initializeOrderedBulkOp; }();
-
-/**
- * Return N number of parallel cursors for a collection allowing parallel reading of entire collection. There are
- * no ordering guarantees for returned results.
- *
- * Options
- * - **readPreference** {String}, the prefered read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
- * - **batchSize** {Number, default:0}, set the batchSize for the getMoreCommand when iterating over the query results.
- * - **numCursors**, {Number, 1} the maximum number of parallel command cursors to return (the number of returned cursors will be in the range 1:numCursors)
- *
- * @param {Objects} [options] options for the initializeOrderedBulkOp
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. The second argument will be an array of CommandCursor instances.
- * @return {OrderedBulkOperation}
- * @api public
- */
-Collection.prototype.parallelCollectionScan = function() { return query.parallelCollectionScan; }();
-
-/**
- * @ignore
- */
-Object.defineProperty(Collection.prototype, "hint", {
- enumerable: true
- , get: function () {
- return this.internalHint;
- }
- , set: function (v) {
- this.internalHint = shared.normalizeHintField(v);
- }
-});
-
-/**
- * Expose.
- */
-exports.Collection = Collection;
diff --git a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/collection/aggregation.js b/node_modules/mongojs/node_modules/mongodb/lib/mongodb/collection/aggregation.js
deleted file mode 100644
index 0c46407..0000000
--- a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/collection/aggregation.js
+++ /dev/null
@@ -1,318 +0,0 @@
-var shared = require('./shared')
- , utils = require('../utils')
- , AggregationCursor = require('../aggregation_cursor').AggregationCursor
- , Code = require('bson').Code
- , DbCommand = require('../commands/db_command').DbCommand;
-
-/**
- * Functions that are passed as scope args must
- * be converted to Code instances.
- * @ignore
- */
-function processScope (scope) {
- if (!utils.isObject(scope)) {
- return scope;
- }
-
- var keys = Object.keys(scope);
- var i = keys.length;
- var key;
- var new_scope = {};
-
- while (i--) {
- key = keys[i];
- if ('function' == typeof scope[key]) {
- new_scope[key] = new Code(String(scope[key]));
- } else {
- new_scope[key] = processScope(scope[key]);
- }
- }
-
- return new_scope;
-}
-
-var pipe = function() {
- return new AggregationCursor(this, this.serverCapabilities);
-}
-
-var mapReduce = function mapReduce (map, reduce, options, callback) {
- if ('function' === typeof options) callback = options, options = {};
- // Out must allways be defined (make sure we don't break weirdly on pre 1.8+ servers)
- if(null == options.out) {
- throw new Error("the out option parameter must be defined, see mongodb docs for possible values");
- }
-
- if ('function' === typeof map) {
- map = map.toString();
- }
-
- if ('function' === typeof reduce) {
- reduce = reduce.toString();
- }
-
- if ('function' === typeof options.finalize) {
- options.finalize = options.finalize.toString();
- }
-
- var mapCommandHash = {
- mapreduce: this.collectionName
- , map: map
- , reduce: reduce
- };
-
- // Add any other options passed in
- for (var name in options) {
- if ('scope' == name) {
- mapCommandHash[name] = processScope(options[name]);
- } else {
- mapCommandHash[name] = options[name];
- }
- }
-
- // Set read preference if we set one
- var readPreference = shared._getReadConcern(this, options);
-
- // If we have a read preference and inline is not set as output fail hard
- if((readPreference != false && readPreference != 'primary')
- && options['out'] && (options['out'].inline != 1 && options['out'] != 'inline')) {
- readPreference = 'primary';
- }
-
- // self
- var self = this;
- var cmd = DbCommand.createDbCommand(this.db, mapCommandHash);
-
- this.db._executeQueryCommand(cmd, {readPreference:readPreference}, function (err, result) {
- if(err) return callback(err);
- if(!result || !result.documents || result.documents.length == 0)
- return callback(Error("command failed to return results"), null)
-
- // Check if we have an error
- if(1 != result.documents[0].ok || result.documents[0].err || result.documents[0].errmsg) {
- return callback(utils.toError(result.documents[0]));
- }
-
- // Create statistics value
- var stats = {};
- if(result.documents[0].timeMillis) stats['processtime'] = result.documents[0].timeMillis;
- if(result.documents[0].counts) stats['counts'] = result.documents[0].counts;
- if(result.documents[0].timing) stats['timing'] = result.documents[0].timing;
-
- // invoked with inline?
- if(result.documents[0].results) {
- // If we wish for no verbosity
- if(options['verbose'] == null || !options['verbose']) {
- return callback(null, result.documents[0].results);
- }
- return callback(null, result.documents[0].results, stats);
- }
-
- // The returned collection
- var collection = null;
-
- // If we have an object it's a different db
- if(result.documents[0].result != null && typeof result.documents[0].result == 'object') {
- var doc = result.documents[0].result;
- collection = self.db.db(doc.db).collection(doc.collection);
- } else {
- // Create a collection object that wraps the result collection
- collection = self.db.collection(result.documents[0].result)
- }
-
- // If we wish for no verbosity
- if(options['verbose'] == null || !options['verbose']) {
- return callback(err, collection);
- }
-
- // Return stats as third set of values
- callback(err, collection, stats);
- });
-};
-
-/**
- * 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();
-
-var group = function group(keys, condition, initial, reduce, finalize, command, options, callback) {
- var args = Array.prototype.slice.call(arguments, 3);
- callback = args.pop();
- // Fetch all commands
- reduce = args.length ? args.shift() : null;
- finalize = args.length ? args.shift() : null;
- command = args.length ? args.shift() : null;
- options = args.length ? args.shift() || {} : {};
-
- // Make sure we are backward compatible
- if(!(typeof finalize == 'function')) {
- command = finalize;
- finalize = null;
- }
-
- if (!Array.isArray(keys) && keys instanceof Object && typeof(keys) !== 'function' && !(keys instanceof Code)) {
- keys = Object.keys(keys);
- }
-
- if(typeof reduce === 'function') {
- reduce = reduce.toString();
- }
-
- if(typeof finalize === 'function') {
- finalize = finalize.toString();
- }
-
- // Set up the command as default
- command = command == null ? true : command;
-
- // Execute using the command
- if(command) {
- var reduceFunction = reduce instanceof Code
- ? reduce
- : new Code(reduce);
-
- var selector = {
- group: {
- 'ns': this.collectionName
- , '$reduce': reduceFunction
- , 'cond': condition
- , 'initial': initial
- , 'out': "inline"
- }
- };
-
- // if finalize is defined
- if(finalize != null) selector.group['finalize'] = finalize;
- // Set up group selector
- if ('function' === typeof keys || keys instanceof Code) {
- selector.group.$keyf = keys instanceof Code
- ? keys
- : new Code(keys);
- } else {
- var hash = {};
- keys.forEach(function (key) {
- hash[key] = 1;
- });
- selector.group.key = hash;
- }
-
- // Set read preference if we set one
- var readPreference = shared._getReadConcern(this, options);
- // Execute command
- this.db.command(selector, {readPreference: readPreference}, function(err, result) {
- if(err) return callback(err, null);
- callback(null, result.retval);
- });
- } else {
- // Create execution scope
- var scope = reduce != null && reduce instanceof Code
- ? reduce.scope
- : {};
-
- scope.ns = this.collectionName;
- scope.keys = keys;
- scope.condition = condition;
- scope.initial = initial;
-
- // Pass in the function text to execute within mongodb.
- var groupfn = groupFunction.replace(/ reduce;/, reduce.toString() + ';');
-
- this.db.eval(new Code(groupfn, scope), function (err, results) {
- if (err) return callback(err, null);
- callback(null, results.result || results);
- });
- }
-};
-
-var aggregate = function(pipeline, options, callback) {
- var args = Array.prototype.slice.call(arguments, 0);
- callback = args.pop();
- var self = this;
-
- // If we have any of the supported options in the options object
- var opts = args[args.length - 1];
- options = opts.readPreference
- || opts.explain
- || opts.cursor
- || opts.out
- || opts.allowDiskUse ? args.pop() : {}
- // If the callback is the option (as for cursor override it)
- if(typeof callback == 'object' && callback != null) options = callback;
-
- // Convert operations to an array
- if(!Array.isArray(args[0])) {
- pipeline = [];
- // Push all the operations to the pipeline
- for(var i = 0; i < args.length; i++) pipeline.push(args[i]);
- }
-
- // Is the user requesting a cursor
- if(options.cursor != null && options.out == null) {
- // Set the aggregation cursor options
- var agg_cursor_options = options.cursor;
- agg_cursor_options.pipe = pipeline;
- agg_cursor_options.allowDiskUse = options.allowDiskUse == null ? false : options.allowDiskUse;
- // Return the aggregation cursor
- return new AggregationCursor(this, this.serverCapabilities, agg_cursor_options);
- }
-
- // If out was specified
- if(typeof options.out == 'string') {
- pipeline.push({$out: options.out});
- }
-
- // Build the command
- var command = { aggregate : this.collectionName, pipeline : pipeline};
- // If we have allowDiskUse defined
- if(options.allowDiskUse) command.allowDiskUse = options.allowDiskUse;
-
- // Ensure we have the right read preference inheritance
- options.readPreference = shared._getReadConcern(this, options);
- // If explain has been specified add it
- if(options.explain) command.explain = options.explain;
- // Execute the command
- this.db.command(command, options, function(err, result) {
- if(err) {
- callback(err);
- } else if(result['err'] || result['errmsg']) {
- callback(utils.toError(result));
- } else if(typeof result == 'object' && result['serverPipeline']) {
- callback(null, result['serverPipeline']);
- } else if(typeof result == 'object' && result['stages']) {
- callback(null, result['stages']);
- } else {
- callback(null, result.result);
- }
- });
-}
-
-exports.mapReduce = mapReduce;
-exports.group = group;
-exports.aggregate = aggregate;
-exports.pipe = pipe;
\ No newline at end of file
diff --git a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/collection/batch/common.js b/node_modules/mongojs/node_modules/mongodb/lib/mongodb/collection/batch/common.js
deleted file mode 100644
index c31c364..0000000
--- a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/collection/batch/common.js
+++ /dev/null
@@ -1,439 +0,0 @@
-var utils = require('../../utils');
-
-// Error codes
-var UNKNOWN_ERROR = 8;
-var INVALID_BSON_ERROR = 22;
-var WRITE_CONCERN_ERROR = 64;
-var MULTIPLE_ERROR = 65;
-
-// Insert types
-var INSERT = 1;
-var UPDATE = 2;
-var REMOVE = 3
-
-/**
- * Helper function to define properties
- */
-var defineReadOnlyProperty = function(self, name, value) {
- Object.defineProperty(self, name, {
- enumerable: true
- , get: function() {
- return value;
- }
- });
-}
-
-/**
- * Keeps the state of a unordered batch so we can rewrite the results
- * correctly after command execution
- */
-var Batch = function(batchType, originalZeroIndex) {
- this.originalZeroIndex = originalZeroIndex;
- this.currentIndex = 0;
- this.originalIndexes = [];
- this.batchType = batchType;
- this.operations = [];
- this.size = 0;
-}
-
-/**
- * Wraps a legacy operation so we can correctly rewrite it's error
- */
-var LegacyOp = function(batchType, operation, index) {
- this.batchType = batchType;
- this.index = index;
- this.operation = operation;
-}
-
-/**
- * Create a new BatchWriteResult instance (INTERNAL TYPE, do not instantiate directly)
- *
- * @class Represents a BatchWriteResult
- * @property **ok** {boolean} did bulk operation correctly execute
- * @property **nInserted** {number} number of inserted documents
- * @property **nUpdated** {number} number of documents updated logically
- * @property **nUpserted** {number} number of upserted documents
- * @property **nModified** {number} number of documents updated physically on disk
- * @property **nRemoved** {number} number of removed documents
- * @param {Object} batchResult internal data structure with results.
- * @return {BatchWriteResult} a BatchWriteResult instance
- */
-var BatchWriteResult = function(bulkResult) {
- defineReadOnlyProperty(this, "ok", bulkResult.ok);
- defineReadOnlyProperty(this, "nInserted", bulkResult.nInserted);
- defineReadOnlyProperty(this, "nUpserted", bulkResult.nUpserted);
- defineReadOnlyProperty(this, "nMatched", bulkResult.nMatched);
- defineReadOnlyProperty(this, "nModified", bulkResult.nModified);
- defineReadOnlyProperty(this, "nRemoved", bulkResult.nRemoved);
-
- /**
- * Return an array of upserted ids
- *
- * @return {Array}
- * @api public
- */
- this.getUpsertedIds = function() {
- return bulkResult.upserted;
- }
-
- /**
- * Return the upserted id at position x
- *
- * @param {Number} index the number of the upserted id to return, returns undefined if no result for passed in index
- * @return {Array}
- * @api public
- */
- this.getUpsertedIdAt = function(index) {
- return bulkResult.upserted[index];
- }
-
- /**
- * Return raw internal result
- *
- * @return {Object}
- * @api public
- */
- this.getRawResponse = function() {
- return bulkResult;
- }
-
- /**
- * Returns true if the bulk operation contains a write error
- *
- * @return {Boolean}
- * @api public
- */
- this.hasWriteErrors = function() {
- return bulkResult.writeErrors.length > 0;
- }
-
- /**
- * Returns the number of write errors off the bulk operation
- *
- * @return {Number}
- * @api public
- */
- this.getWriteErrorCount = function() {
- return bulkResult.writeErrors.length;
- }
-
- /**
- * Returns a specific write error object
- *
- * @return {WriteError}
- * @api public
- */
- this.getWriteErrorAt = function(index) {
- if(index < bulkResult.writeErrors.length) {
- return bulkResult.writeErrors[index];
- }
- return null;
- }
-
- /**
- * Retrieve all write errors
- *
- * @return {Array}
- * @api public
- */
- this.getWriteErrors = function() {
- return bulkResult.writeErrors;
- }
-
- /**
- * Retrieve lastOp if available
- *
- * @return {Array}
- * @api public
- */
- this.getLastOp = function() {
- return bulkResult.lastOp;
- }
-
- /**
- * Retrieve the write concern error if any
- *
- * @return {WriteConcernError}
- * @api public
- */
- this.getWriteConcernError = function() {
- if(bulkResult.writeConcernErrors.length == 0) {
- return null;
- } else if(bulkResult.writeConcernErrors.length == 1) {
- // Return the error
- return bulkResult.writeConcernErrors[0];
- } else {
-
- // Combine the errors
- var errmsg = "";
- for(var i = 0; i < bulkResult.writeConcernErrors.length; i++) {
- var err = bulkResult.writeConcernErrors[i];
- errmsg = errmsg + err.errmsg;
-
- // TODO: Something better
- if(i == 0) errmsg = errmsg + " and ";
- }
-
- return new WriteConcernError({ errmsg : errmsg, code : WRITE_CONCERN_ERROR });
- }
- }
-
- this.toJSON = function() {
- return bulkResult;
- }
-
- this.toString = function() {
- return "BatchWriteResult(" + this.toJSON(bulkResult) + ")";
- }
-
- this.isOk = function() {
- return bulkResult.ok == 1;
- }
-}
-
-/**
- * Wraps a write concern error
- */
-var WriteConcernError = function(err) {
- if(!(this instanceof WriteConcernError)) return new WriteConcernError(err);
-
- // Define properties
- defineReadOnlyProperty(this, "code", err.code);
- defineReadOnlyProperty(this, "errmsg", err.errmsg);
-
- this.toJSON = function() {
- return {code: err.code, errmsg: err.errmsg};
- }
-
- this.toString = function() {
- return "WriteConcernError(" + err.errmsg + ")";
- }
-}
-
-/**
- * Wraps the error
- */
-var WriteError = function(err) {
- if(!(this instanceof WriteError)) return new WriteError(err);
-
- // Define properties
- defineReadOnlyProperty(this, "code", err.code);
- defineReadOnlyProperty(this, "index", err.index);
- defineReadOnlyProperty(this, "errmsg", err.errmsg);
-
- //
- // Define access methods
- this.getOperation = function() {
- return err.op;
- }
-
- this.toJSON = function() {
- return {code: err.code, index: err.index, errmsg: err.errmsg, op: err.op};
- }
-
- this.toString = function() {
- return "WriteError(" + JSON.stringify(this.toJSON()) + ")";
- }
-}
-
-/**
- * Merges results into shared data structure
- */
-var mergeBatchResults = function(ordered, batch, bulkResult, err, result) {
- // If we have an error set the result to be the err object
- if(err) {
- result = err;
- }
-
- // Do we have a top level error stop processing and return
- if(result.ok == 0 && bulkResult.ok == 1) {
- bulkResult.ok = 0;
- bulkResult.error = utils.toError(result);
- return;
- } else if(result.ok == 0 && bulkResult.ok == 0) {
- return;
- }
-
- // Add lastop if available
- if(result.lastOp) {
- bulkResult.lastOp = result.lastOp;
- }
-
- // If we have an insert Batch type
- if(batch.batchType == INSERT && result.n) {
- bulkResult.nInserted = bulkResult.nInserted + result.n;
- }
-
- // If we have an insert Batch type
- if(batch.batchType == REMOVE && result.n) {
- bulkResult.nRemoved = bulkResult.nRemoved + result.n;
- }
-
- var nUpserted = 0;
-
- // We have an array of upserted values, we need to rewrite the indexes
- if(Array.isArray(result.upserted)) {
- nUpserted = result.upserted.length;
-
- for(var i = 0; i < result.upserted.length; i++) {
- bulkResult.upserted.push({
- index: result.upserted[i].index + batch.originalZeroIndex
- , _id: result.upserted[i]._id
- });
- }
- } else if(result.upserted) {
-
- nUpserted = 1;
-
- bulkResult.upserted.push({
- index: batch.originalZeroIndex
- , _id: result.upserted
- });
- }
-
- // If we have an update Batch type
- if(batch.batchType == UPDATE && result.n) {
- var nModified = result.nModified;
- bulkResult.nUpserted = bulkResult.nUpserted + nUpserted;
- bulkResult.nMatched = bulkResult.nMatched + (result.n - nUpserted);
-
- if(typeof nModified == 'number') {
- bulkResult.nModified = bulkResult.nModified + nModified;
- } else {
- bulkResult.nModified = null;
- }
- }
-
- if(Array.isArray(result.writeErrors)) {
- for(var i = 0; i < result.writeErrors.length; i++) {
-
- var writeError = {
- index: batch.originalZeroIndex + result.writeErrors[i].index
- , code: result.writeErrors[i].code
- , errmsg: result.writeErrors[i].errmsg
- , op: batch.operations[result.writeErrors[i].index]
- };
-
- bulkResult.writeErrors.push(new WriteError(writeError));
- }
- }
-
- if(result.writeConcernError) {
- bulkResult.writeConcernErrors.push(new WriteConcernError(result.writeConcernError));
- }
-}
-
-//
-// Merge a legacy result into the master results
-var mergeLegacyResults = function(_ordered, _op, _batch, _results, _result, _index) {
- // If we have an error already
- if(_results.ok == 0) return false;
- // Handle error
- if((_result.errmsg || _result.err || _result instanceof Error) && _result.wtimeout != true) {
- // && ((_result.wtimeout == null && _result.jnote == null && _result.wnote == null)) || _result.err == "norepl") {
- var code = _result.code || UNKNOWN_ERROR; // Returned error code or unknown code
- var errmsg = _result.errmsg || _result.err;
- errmsg = errmsg || _result.message;
-
- // Result is replication issue, rewrite error to match write command
- if(_result.wnote || _result.wtimeout || _result.jnote) {
- // Set the code to replication error
- code = WRITE_CONCERN_ERROR;
- // Ensure we get the right error message
- errmsg = _result.wnote || errmsg;
- errmsg = _result.jnote || errmsg;
- }
-
- //
- // We have an error that is a show stopper, 16544 and 13 are auth errors that should stop processing
- if(_result.wnote
- || _result.jnote == "journaling not enabled on this server"
- || _result.err == "norepl"
- || _result.code == 16544
- || _result.code == 13) {
- _results.ok = 0;
- _results.error = utils.toError({code: code, errmsg: errmsg});
- return false;
- }
-
- // Create a write error
- var errResult = new WriteError({
- index: _index
- , code: code
- , errmsg: errmsg
- , op: _op
- });
-
- // Err details
- _results.writeErrors.push(errResult);
-
- // Check if we any errors
- if(_ordered == true
- && _result.jnote == null
- && _result.wnote == null
- && _result.wtimeout == null) {
- return false;
- }
- } else if(_batch.batchType == INSERT) {
- _results.nInserted = _results.nInserted + 1;
- } else if(_batch.batchType == UPDATE) {
- // If we have an upserted value or if the user provided a custom _id value
- if(_result.upserted || (!_result.updatedExisting && _result.upserted == null)) {
- _results.nUpserted = _results.nUpserted + 1;
- } else {
- _results.nMatched = _results.nMatched + _result.n;
- _results.nModified = null;
- }
- } else if(_batch.batchType == REMOVE) {
- _results.nRemoved = _results.nRemoved + _result;
- }
-
- // We have a write concern error, add a write concern error to the results
- if(_result.wtimeout != null || _result.jnote != null || _result.wnote != null) {
- var error = _result.err || _result.errmsg || _result.wnote || _result.jnote || _result.wtimeout;
- var code = _result.code || WRITE_CONCERN_ERROR;
- // Push a write concern error to the list
- _results.writeConcernErrors.push(new WriteConcernError({errmsg: error, code: code}));
- }
-
- // We have an upserted field (might happen with a write concern error)
- if(_result.upserted) {
- _results.upserted.push({
- index: _index
- , _id: _result.upserted
- })
- } else if(!_result.updatedExisting && _result.upserted == null && _op.q && _op.q._id) {
- _results.upserted.push({
- index: _index
- , _id: _op.q._id
- })
- }
-}
-
-//
-// Clone the options
-var cloneOptions = function(options) {
- var clone = {};
- var keys = Object.keys(options);
- for(var i = 0; i < keys.length; i++) {
- clone[keys[i]] = options[keys[i]];
- }
-
- return clone;
-}
-
-// Exports symbols
-exports.BatchWriteResult = BatchWriteResult;
-exports.WriteError = WriteError;
-exports.Batch = Batch;
-exports.LegacyOp = LegacyOp;
-exports.mergeBatchResults = mergeBatchResults;
-exports.cloneOptions = cloneOptions;
-exports.mergeLegacyResults = mergeLegacyResults;
-exports.INVALID_BSON_ERROR = INVALID_BSON_ERROR;
-exports.WRITE_CONCERN_ERROR = WRITE_CONCERN_ERROR;
-exports.MULTIPLE_ERROR = MULTIPLE_ERROR;
-exports.UNKNOWN_ERROR = UNKNOWN_ERROR;
-exports.INSERT = INSERT;
-exports.UPDATE = UPDATE;
-exports.REMOVE = REMOVE;
\ No newline at end of file
diff --git a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/collection/batch/ordered.js b/node_modules/mongojs/node_modules/mongodb/lib/mongodb/collection/batch/ordered.js
deleted file mode 100644
index 6fe275f..0000000
--- a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/collection/batch/ordered.js
+++ /dev/null
@@ -1,530 +0,0 @@
-var shared = require('../shared')
- , common = require('./common')
- , utils = require('../../utils')
- , hasWriteCommands = utils.hasWriteCommands
- , WriteError = common.WriteError
- , BatchWriteResult = common.BatchWriteResult
- , LegacyOp = common.LegacyOp
- , ObjectID = require('bson').ObjectID
- , Batch = common.Batch
- , mergeBatchResults = common.mergeBatchResults;
-
-/**
- * Create a new OrderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly)
- *
- * Options
- * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write
- * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option)
- * - **fsync**, (Boolean, default:false) write waits for fsync before returning, from MongoDB 2.6 on, fsync cannot be combined with journal
- * - **j**, (Boolean, default:false) write waits for journal sync before returning
- *
- * @class Represents a OrderedBulkOperation
- * @param {Object} collection collection instance.
- * @param {Object} [options] additional options for the collection.
- * @return {Object} a ordered bulk operation instance.
- */
-function OrderedBulkOperation (collection, options) {
- options = options == null ? {} : options;
- // TODO Bring from driver information in isMaster
- var self = this;
- var executed = false;
-
- // Current item
- var currentOp = null;
-
- // Handle to the bson serializer, used to calculate running sizes
- var db = collection.db;
- var bson = db.bson;
-
- // Namespace for the operation
- var namespace = collection.collectionName;
-
- // Set max byte size
- var maxWriteBatchSize = db.serverConfig.checkoutWriter().maxWriteBatchSize || 1000;
- var maxBatchSizeBytes = db.serverConfig.checkoutWriter().maxBsonSize;
-
- // Get the write concern
- var writeConcern = shared._getWriteConcern(collection, options);
-
- // Current batch
- var currentBatch = null;
- var currentIndex = 0;
- var currentBatchSize = 0;
- var currentBatchSizeBytes = 0;
- var batches = [];
-
- // Final results
- var bulkResult = {
- ok: 1
- , writeErrors: []
- , writeConcernErrors: []
- , nInserted: 0
- , nUpserted: 0
- , nMatched: 0
- , nModified: 0
- , nRemoved: 0
- , upserted: []
- };
-
- // Specify a full class so we can generate documentation correctly
- var FindOperators = function() {
- /**
- * Add a single update document to the bulk operation
- *
- * @param {Object} doc update operations
- * @return {OrderedBulkOperation}
- * @api public
- */
- this.update = function(updateDocument) {
- // Perform upsert
- var upsert = typeof currentOp.upsert == 'boolean' ? currentOp.upsert : false;
-
- // Establish the update command
- var document = {
- q: currentOp.selector
- , u: updateDocument
- , multi: true
- , upsert: upsert
- }
-
- // Clear out current Op
- currentOp = null;
- // Add the update document to the list
- return addToOperationsList(self, common.UPDATE, document);
- }
-
- /**
- * Add a single update one document to the bulk operation
- *
- * @param {Object} doc update operations
- * @return {OrderedBulkOperation}
- * @api public
- */
- this.updateOne = function(updateDocument) {
- // Perform upsert
- var upsert = typeof currentOp.upsert == 'boolean' ? currentOp.upsert : false;
-
- // Establish the update command
- var document = {
- q: currentOp.selector
- , u: updateDocument
- , multi: false
- , upsert: upsert
- }
-
- // Clear out current Op
- currentOp = null;
- // Add the update document to the list
- return addToOperationsList(self, common.UPDATE, document);
- }
-
- /**
- * Add a replace one operation to the bulk operation
- *
- * @param {Object} doc the new document to replace the existing one with
- * @return {OrderedBulkOperation}
- * @api public
- */
- this.replaceOne = function(updateDocument) {
- this.updateOne(updateDocument);
- }
-
- /**
- * Upsert modifier for update bulk operation
- *
- * @return {OrderedBulkOperation}
- * @api public
- */
- this.upsert = function() {
- currentOp.upsert = true;
- return this;
- }
-
- /**
- * Add a remove one operation to the bulk operation
- *
- * @param {Object} doc selector for the removal of documents
- * @return {OrderedBulkOperation}
- * @api public
- */
- this.removeOne = function() {
- // Establish the update command
- var document = {
- q: currentOp.selector
- , limit: 1
- }
-
- // Clear out current Op
- currentOp = null;
- // Add the remove document to the list
- return addToOperationsList(self, common.REMOVE, document);
- }
-
- /**
- * Add a remove operation to the bulk operation
- *
- * @param {Object} doc selector for the single document to remove
- * @return {OrderedBulkOperation}
- * @api public
- */
- this.remove = function() {
- // Establish the update command
- var document = {
- q: currentOp.selector
- , limit: 0
- }
-
- // Clear out current Op
- currentOp = null;
- // Add the remove document to the list
- return addToOperationsList(self, common.REMOVE, document);
- }
- }
-
- /**
- * Add a single insert document to the bulk operation
- *
- * @param {Object} doc the document to insert
- * @return {OrderedBulkOperation}
- * @api public
- */
- this.insert = function(document) {
- if(document._id == null) document._id = new ObjectID();
- return addToOperationsList(self, common.INSERT, document);
- }
-
- var getOrderedCommand = function(_self, _namespace, _docType, _operationDocuments) {
- // Set up the types of operation
- if(_docType == common.INSERT) {
- return {
- insert: _namespace
- , documents: _operationDocuments
- , ordered:true
- }
- } else if(_docType == common.UPDATE) {
- return {
- update: _namespace
- , updates: _operationDocuments
- , ordered:true
- };
- } else if(_docType == common.REMOVE) {
- return {
- delete: _namespace
- , deletes: _operationDocuments
- , ordered:true
- };
- }
- }
-
- // Add to internal list of documents
- var addToOperationsList = function(_self, docType, document) {
- // Get the bsonSize
- var bsonSize = bson.calculateObjectSize(document, false);
- // Throw error if the doc is bigger than the max BSON size
- if(bsonSize >= maxBatchSizeBytes) throw utils.toError("document is larger than the maximum size " + maxBatchSizeBytes);
- // Create a new batch object if we don't have a current one
- if(currentBatch == null) currentBatch = new Batch(docType, currentIndex);
-
- // Check if we need to create a new batch
- if(((currentBatchSize + 1) >= maxWriteBatchSize)
- || ((currentBatchSizeBytes + currentBatchSizeBytes) >= maxBatchSizeBytes)
- || (currentBatch.batchType != docType)) {
- // Save the batch to the execution stack
- batches.push(currentBatch);
-
- // Create a new batch
- currentBatch = new Batch(docType, currentIndex);
-
- // Reset the current size trackers
- currentBatchSize = 0;
- currentBatchSizeBytes = 0;
- } else {
- // Update current batch size
- currentBatchSize = currentBatchSize + 1;
- currentBatchSizeBytes = currentBatchSizeBytes + bsonSize;
- }
-
- // We have an array of documents
- if(Array.isArray(document)) {
- throw utils.toError("operation passed in cannot be an Array");
- } else {
- currentBatch.originalIndexes.push(currentIndex);
- currentBatch.operations.push(document)
- currentIndex = currentIndex + 1;
- }
-
- // Return self
- return _self;
- }
-
- /**
- * Initiate a find operation for an update/updateOne/remove/removeOne/replaceOne
- *
- * @param {Object} doc
- * @return {OrderedBulkOperation}
- * @api public
- */
- this.find = function(selector) {
- if (!selector) {
- throw utils.toError("Bulk find operation must specify a selector");
- }
-
- // Save a current selector
- currentOp = {
- selector: selector
- }
-
- return new FindOperators();
- }
-
- //
- // Execute next write command in a chain
- var executeCommands = function(callback) {
- if(batches.length == 0) {
- return callback(null, new BatchWriteResult(bulkResult));
- }
-
- // Ordered execution of the command
- var batch = batches.shift();
-
- // Build the command
- var cmd = null;
-
- // Generate the right update
- if(batch.batchType == common.UPDATE) {
- cmd = { update: namespace, updates: batch.operations, ordered: true }
- } else if(batch.batchType == common.INSERT) {
- cmd = { insert: namespace, documents: batch.operations, ordered: true }
- } else if(batch.batchType == common.REMOVE) {
- cmd = { delete: namespace, deletes: batch.operations, ordered: true }
- }
-
- // If we have a write concern
- if(writeConcern != null) {
- cmd.writeConcern = writeConcern;
- }
-
- // Execute it
- db.command(cmd, function(err, result) {
- // Merge the results together
- var mergeResult = mergeBatchResults(true, batch, bulkResult, err, result);
- if(mergeResult != null) {
- return callback(null, new BatchWriteResult(bulkResult));
- }
-
- // If we had a serious error
- if(bulkResult.ok == 0) {
- return callback(bulkResult.error, null);
- }
-
- // If we are ordered and have errors and they are
- // not all replication errors terminate the operation
- if(bulkResult.writeErrors.length > 0) {
- return callback(null, new BatchWriteResult(bulkResult));
- }
-
- // Execute the next command in line
- executeCommands(callback);
- });
- }
-
- //
- // Execute the inserts
- var executeInserts = function(_collection, _batch, _result, _callback) {
- if(_batch.operations.length == 0) {
- return _callback(null, _result);
- }
-
- // Get the first update
- var document = _batch.operations.shift();
- var index = _batch.originalIndexes.shift();
-
- // Options for the update operation
- var options = writeConcern || {};
-
- // Execute the update
- _collection.insert(document, options, function(err, r) {
- // If we have don't have w:0 merge the result
- if(options.w == null || options.w != 0) {
- // Merge the results in
- var result = common.mergeLegacyResults(true, document, _batch, bulkResult, err || r, index);
-
- if(result == false) {
- return _callback(null, new BatchWriteResult(bulkResult));
- }
- }
-
- // Update the index
- _batch.currentIndex = _batch.currentIndex + 1;
-
- // Execute the next insert
- executeInserts(_collection, _batch, _result, _callback);
- });
- }
-
- //
- // Execute updates
- var executeUpdates = function(_collection, _batch, _result, _callback) {
- if(_batch.operations.length == 0) {
- return _callback(null, _result);
- }
-
- // Get the first update
- var update = _batch.operations.shift();
- var index = _batch.originalIndexes.shift();
-
- // Options for the update operation
- var options = writeConcern != null ? common.cloneOptions(writeConcern) : {};
-
- // Add any additional options
- if(update.multi) options.multi = update.multi;
- if(update.upsert) options.upsert = update.upsert;
-
- // Execute the update
- _collection.update(update.q, update.u, options, function(err, r, full) {
- // If we have don't have w:0 merge the result
- if(options.w == null || options.w != 0) {
- // Merge the results in
- var result = common.mergeLegacyResults(true, update, _batch, bulkResult, err || full, index);
- if(result == false) {
- return _callback(null, new BatchWriteResult(bulkResult));
- }
- }
-
- // Update the index
- _batch.currentIndex = _batch.currentIndex + 1;
-
- // Execute the next insert
- executeUpdates(_collection, _batch, _result, _callback);
- });
- }
-
- //
- // Execute updates
- var executeRemoves = function(_collection, _batch, _result, _callback) {
- if(_batch.operations.length == 0) {
- return _callback(null, _result);
- }
-
- // Get the first update
- var remove = _batch.operations.shift();
- var index = _batch.originalIndexes.shift();
-
- // Options for the update operation
- var options = writeConcern != null ? common.cloneOptions(writeConcern) : {};
-
- // Add any additional options
- options.single = remove.limit == 1 ? true : false;
-
- // Execute the update
- _collection.remove(remove.q, options, function(err, r) {
- // If we have don't have w:0 merge the result
- if(options.w == null || options.w != 0) {
- // Merge the results in
- var result = common.mergeLegacyResults(true, remove, _batch, bulkResult, err || r, index);
- if(result == false) {
- return _callback(null, new BatchWriteResult(bulkResult));
- }
- }
-
- // Update the index
- _batch.currentIndex = _batch.currentIndex + 1;
-
- // Execute the next insert
- executeRemoves(_collection, _batch, _result, _callback);
- });
- }
-
- //
- // Execute all operation in backwards compatible fashion
- var backwardsCompatibilityExecuteCommands = function(callback) {
- if(batches.length == 0) {
- return callback(null, new BatchWriteResult(bulkResult));
- }
-
- // Ordered execution of the command
- var batch = batches.shift();
-
- // Process the legacy operations
- var processLegacyOperations = function(err, results) {
- // If we have any errors stop executing
- if(bulkResult.writeErrors.length > 0) {
- return callback(null, new BatchWriteResult(bulkResult));
- }
-
- // If we have a top level error stop
- if(bulkResult.ok == 0) {
- return callback(bulkResult.error, null);
- }
-
- // Execute the next step
- backwardsCompatibilityExecuteCommands(callback);
- }
-
- // Execute an insert batch
- if(batch.batchType == common.INSERT) {
- return executeInserts(collection, batch, {n: 0}, processLegacyOperations);
- }
-
- // Execute an update batch
- if(batch.batchType == common.UPDATE) {
- return executeUpdates(collection, batch, {n: 0}, processLegacyOperations);
- }
-
- // Execute an update batch
- if(batch.batchType == common.REMOVE) {
- return executeRemoves(collection, batch, {n: 0}, processLegacyOperations);
- }
- }
-
- /**
- * Execute the ordered bulk operation
- *
- * Options
- * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write
- * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option)
- * - **fsync**, (Boolean, default:false) write waits for fsync before returning, from MongoDB 2.6 on, fsync cannot be combined with journal
- * - **j**, (Boolean, default:false) write waits for journal sync before returning
- *
- * @param {Object} [options] additional options during update.
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from from the ordered bulk operation.
- * @return {null}
- * @api public
- */
- this.execute = function(_writeConcern, callback) {
- if(executed) throw new utils.toError("batch cannot be re-executed");
- if(typeof _writeConcern == 'function') {
- callback = _writeConcern;
- } else {
- writeConcern = _writeConcern;
- }
-
- // If we have current batch
- if(currentBatch) batches.push(currentBatch);
-
- // If we have no operations in the bulk raise an error
- if(batches.length == 0) {
- throw utils.toError("Invalid Operation, No operations in bulk");
- }
-
- // Check if we support bulk commands, override if needed to use legacy ops
- if(hasWriteCommands(db.serverConfig.checkoutWriter()))
- return executeCommands(callback);
-
- // Set nModified to null as we don't support this field
- bulkResult.nModified = null;
-
- // Run in backward compatibility mode
- backwardsCompatibilityExecuteCommands(callback);
- }
-}
-
-/**
- * Returns an unordered batch object
- *
- */
-var initializeOrderedBulkOp = function(options) {
- return new OrderedBulkOperation(this, options);
-}
-
-exports.initializeOrderedBulkOp = initializeOrderedBulkOp;
\ No newline at end of file
diff --git a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/collection/batch/unordered.js b/node_modules/mongojs/node_modules/mongodb/lib/mongodb/collection/batch/unordered.js
deleted file mode 100644
index 0024708..0000000
--- a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/collection/batch/unordered.js
+++ /dev/null
@@ -1,576 +0,0 @@
-var shared = require('../shared')
- , common = require('./common')
- , utils = require('../../utils')
- , hasWriteCommands = utils.hasWriteCommands
- , WriteError = common.WriteError
- , BatchWriteResult = common.BatchWriteResult
- , LegacyOp = common.LegacyOp
- , ObjectID = require('bson').ObjectID
- , Batch = common.Batch
- , mergeBatchResults = common.mergeBatchResults;
-
-/**
- * Create a new UnorderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly)
- *
- * Options
- * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write
- * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option)
- * - **fsync**, (Boolean, default:false) write waits for fsync before returning, from MongoDB 2.6 on, fsync cannot be combined with journal
- * - **j**, (Boolean, default:false) write waits for journal sync before returning
- *
- * @class Represents a UnorderedBulkOperation
- * @param {Object} collection collection instance.
- * @param {Object} [options] additional options for the collection.
- * @return {Object} a ordered bulk operation instance.
- */
-var UnorderedBulkOperation = function(collection, options) {
- options = options == null ? {} : options;
-
- // Contains reference to self
- var self = this;
- // Get the namesspace for the write operations
- var namespace = collection.collectionName;
- // Used to mark operation as executed
- var executed = false;
-
- // Current item
- // var currentBatch = null;
- var currentOp = null;
- var currentIndex = 0;
- var currentBatchSize = 0;
- var currentBatchSizeBytes = 0;
- var batches = [];
-
- // The current Batches for the different operations
- var currentInsertBatch = null;
- var currentUpdateBatch = null;
- var currentRemoveBatch = null;
-
- // Handle to the bson serializer, used to calculate running sizes
- var db = collection.db;
- var bson = db.bson;
-
- // Set max byte size
- var maxBatchSizeBytes = db.serverConfig.checkoutWriter().maxBsonSize;
- var maxWriteBatchSize = db.serverConfig.checkoutWriter().maxWriteBatchSize || 1000;
-
- // Get the write concern
- var writeConcern = shared._getWriteConcern(collection, options);
-
- // Final results
- var bulkResult = {
- ok: 1
- , writeErrors: []
- , writeConcernErrors: []
- , nInserted: 0
- , nUpserted: 0
- , nMatched: 0
- , nModified: 0
- , nRemoved: 0
- , upserted: []
- };
-
- // Specify a full class so we can generate documentation correctly
- var FindOperators = function() {
- /**
- * Add a single update document to the bulk operation
- *
- * @param {Object} doc update operations
- * @return {UnorderedBulkOperation}
- * @api public
- */
- this.update = function(updateDocument) {
- // Perform upsert
- var upsert = typeof currentOp.upsert == 'boolean' ? currentOp.upsert : false;
-
- // Establish the update command
- var document = {
- q: currentOp.selector
- , u: updateDocument
- , multi: true
- , upsert: upsert
- }
-
- // Clear out current Op
- currentOp = null;
- // Add the update document to the list
- return addToOperationsList(self, common.UPDATE, document);
- }
-
- /**
- * Add a single update one document to the bulk operation
- *
- * @param {Object} doc update operations
- * @return {UnorderedBulkOperation}
- * @api public
- */
- this.updateOne = function(updateDocument) {
- // Perform upsert
- var upsert = typeof currentOp.upsert == 'boolean' ? currentOp.upsert : false;
-
- // Establish the update command
- var document = {
- q: currentOp.selector
- , u: updateDocument
- , multi: false
- , upsert: upsert
- }
-
- // Clear out current Op
- currentOp = null;
- // Add the update document to the list
- return addToOperationsList(self, common.UPDATE, document);
- }
-
- /**
- * Add a replace one operation to the bulk operation
- *
- * @param {Object} doc the new document to replace the existing one with
- * @return {UnorderedBulkOperation}
- * @api public
- */
- this.replaceOne = function(updateDocument) {
- this.updateOne(updateDocument);
- }
-
- /**
- * Upsert modifier for update bulk operation
- *
- * @return {UnorderedBulkOperation}
- * @api public
- */
- this.upsert = function() {
- currentOp.upsert = true;
- return this;
- }
-
- /**
- * Add a remove one operation to the bulk operation
- *
- * @param {Object} doc selector for the removal of documents
- * @return {UnorderedBulkOperation}
- * @api public
- */
- this.removeOne = function() {
- // Establish the update command
- var document = {
- q: currentOp.selector
- , limit: 1
- }
-
- // Clear out current Op
- currentOp = null;
- // Add the remove document to the list
- return addToOperationsList(self, common.REMOVE, document);
- }
-
- /**
- * Add a remove operation to the bulk operation
- *
- * @param {Object} doc selector for the single document to remove
- * @return {UnorderedBulkOperation}
- * @api public
- */
- this.remove = function() {
- // Establish the update command
- var document = {
- q: currentOp.selector
- , limit: 0
- }
-
- // Clear out current Op
- currentOp = null;
- // Add the remove document to the list
- return addToOperationsList(self, common.REMOVE, document);
- }
- }
-
- //
- // Add to the operations list
- //
- var addToOperationsList = function(_self, docType, document) {
- // Get the bsonSize
- var bsonSize = bson.calculateObjectSize(document, false);
- // Throw error if the doc is bigger than the max BSON size
- if(bsonSize >= maxBatchSizeBytes) throw utils.toError("document is larger than the maximum size " + maxBatchSizeBytes);
- // Holds the current batch
- var currentBatch = null;
- // Get the right type of batch
- if(docType == common.INSERT) {
- currentBatch = currentInsertBatch;
- } else if(docType == common.UPDATE) {
- currentBatch = currentUpdateBatch;
- } else if(docType == common.REMOVE) {
- currentBatch = currentRemoveBatch;
- }
-
- // Create a new batch object if we don't have a current one
- if(currentBatch == null) currentBatch = new Batch(docType, currentIndex);
-
- // Check if we need to switch batch type
- if(currentBatch.batchType != docType) {
- // Save current batch
- batches.push(currentBatch);
- // Create a new batch
- currentBatch = new Batch(docType, currentIndex);
-
- // Reset the current size trackers
- currentBatchSize = 0;
- currentBatchSizeBytes = 0;
- }
-
- // Check if we need to create a new batch
- if(((currentBatchSize + 1) >= maxWriteBatchSize)
- || ((currentBatchSizeBytes + currentBatchSizeBytes) >= maxBatchSizeBytes)
- || (currentBatch.batchType != docType)) {
- // Save the batch to the execution stack
- batches.push(currentBatch);
-
- // Create a new batch
- currentBatch = new Batch(docType, currentIndex);
-
- // Reset the current size trackers
- currentBatchSize = 0;
- currentBatchSizeBytes = 0;
- } else {
- // Update current batch size
- currentBatchSize = currentBatchSize + 1;
- currentBatchSizeBytes = currentBatchSizeBytes + bsonSize;
- }
-
- // We have an array of documents
- if(Array.isArray(document)) {
- throw utils.toError("operation passed in cannot be an Array");
- } else {
- currentBatch.operations.push(document);
- currentBatch.originalIndexes.push(currentIndex);
- currentIndex = currentIndex + 1;
- }
-
- // Save back the current Batch to the right type
- if(docType == common.INSERT) {
- currentInsertBatch = currentBatch;
- } else if(docType == common.UPDATE) {
- currentUpdateBatch = currentBatch;
- } else if(docType == common.REMOVE) {
- currentRemoveBatch = currentBatch;
- }
-
- // Update current batch size
- currentBatchSize = currentBatchSize + 1;
- currentBatchSizeBytes = currentBatchSizeBytes + bsonSize;
-
- // Return self
- return _self;
- }
-
- /**
- * Add a single insert document to the bulk operation
- *
- * @param {Object} doc the document to insert
- * @return {UnorderedBulkOperation}
- * @api public
- */
- this.insert = function(document) {
- if(document._id == null) document._id = new ObjectID();
- return addToOperationsList(self, common.INSERT, document);
- }
-
- /**
- * Initiate a find operation for an update/updateOne/remove/removeOne/replaceOne
- *
- * @param {Object} selector the selector used to locate documents for the operation
- * @return {UnorderedBulkOperation}
- * @api public
- */
- this.find = function(selector) {
- if (!selector) {
- throw utils.toError("Bulk find operation must specify a selector");
- }
-
- // Save a current selector
- currentOp = {
- selector: selector
- }
-
- return new FindOperators();
- }
-
- //
- // Execute the command
- var executeBatch = function(batch, callback) {
- // Contains the command we are going to execute
- var cmd = null;
-
- // Generate the right update
- if(batch.batchType == common.UPDATE) {
- cmd = { update: namespace, updates: batch.operations, ordered: false }
- } else if(batch.batchType == common.INSERT) {
- cmd = { insert: namespace, documents: batch.operations, ordered: false }
- } else if(batch.batchType == common.REMOVE) {
- cmd = { delete: namespace, deletes: batch.operations, ordered: false }
- }
-
- // If we have a write concern
- if(writeConcern != null) {
- cmd.writeConcern = writeConcern;
- }
-
- // Execute the write command
- db.command(cmd, function(err, result) {
- callback(null, mergeBatchResults(false, batch, bulkResult, err, result));
- });
- }
-
- //
- // Execute all the commands
- var executeBatches = function(callback) {
- var numberOfCommandsToExecute = batches.length;
- // Execute over all the batches
- for(var i = 0; i < batches.length; i++) {
- executeBatch(batches[i], function(err, result) {
- numberOfCommandsToExecute = numberOfCommandsToExecute - 1;
-
- // Execute
- if(numberOfCommandsToExecute == 0) {
- // If we have an error stop
- if(bulkResult.ok == 0 && callback) {
- return callback(bulkResult.error, null);
- }
-
- callback(null, new BatchWriteResult(bulkResult));
- }
- });
- }
- }
-
- /**
- * Execute the unordered bulk operation
- *
- * Options
- * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write
- * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option)
- * - **fsync**, (Boolean, default:false) write waits for fsync before returning, from MongoDB 2.6 on, fsync cannot be combined with journal
- * - **j**, (Boolean, default:false) write waits for journal sync before returning
- *
- * @param {Object} [options] additional options during update.
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from from the unordered bulk operation.
- * @return {null}
- * @api public
- */
- this.execute = function(_writeConcern, callback) {
- if(executed) throw utils.toError("batch cannot be re-executed");
- if(typeof _writeConcern == 'function') {
- callback = _writeConcern;
- } else {
- writeConcern = _writeConcern;
- }
-
- // If we have current batch
- if(currentInsertBatch) batches.push(currentInsertBatch);
- if(currentUpdateBatch) batches.push(currentUpdateBatch);
- if(currentRemoveBatch) batches.push(currentRemoveBatch);
-
- // If we have no operations in the bulk raise an error
- if(batches.length == 0) {
- throw utils.toError("Invalid Operation, No operations in bulk");
- }
-
- // Check if we support bulk commands
- if(hasWriteCommands(db.serverConfig.checkoutWriter()))
- return executeBatches(function(err, result) {
- callback(err, result);
- });
-
- // Set nModified to null as we don't support this field
- bulkResult.nModified = null;
-
- // Run in backward compatibility mode
- backwardsCompatibilityExecuteCommands(function(err, result) {
- callback(err, result);
- });
- }
-
- //
- // Execute the inserts
- var executeInserts = function(_collection, _batch, _result, _callback) {
- var totalNumberOfInserts = _batch.operations.length;
-
- // Options for the update operation
- var batchOptions = writeConcern || {};
-
- // Execute the op
- var executeLegacyInsert = function(_i, _op, _options, __callback) {
- // Execute the update
- _collection.insert(_op.operation, _options, function(err, r) {
- // If we have don't have w:0 merge the result
- if(_options.w == null || _options.w != 0) {
- // Merge the results in
- var result = common.mergeLegacyResults(false, _op.operation, _batch, bulkResult, err || r, _op.index);
- if(result == false) {
- return _callback(null, new BatchWriteResult(bulkResult));
- }
- }
-
- __callback(null, _result);
- });
- }
-
- // Execute all the insert operations
- for(var i = 0; i < _batch.operations.length; i++) {
- var legacyOp = new LegacyOp(_batch.batchType, _batch.operations[i], _batch.originalIndexes[i]);
- executeLegacyInsert(i, legacyOp, batchOptions, function(err, result) {
- totalNumberOfInserts = totalNumberOfInserts - 1;
-
- // No more inserts
- if(totalNumberOfInserts == 0) {
- _callback(null, _result);
- }
- });
- }
- }
-
- //
- // Execute updates
- var executeUpdates = function(_collection, _batch, _result, _callback) {
- var totalNumberOfUpdates = _batch.operations.length;
- // Options for the update operation
- var batchOptions = writeConcern || {};
-
- // Execute the op
- var executeLegacyUpdate = function(_i, _op, _options, __callback) {
- var options = common.cloneOptions(batchOptions);
-
- // Add any additional options
- if(_op.operation.multi != null) options.multi = _op.operation.multi ? true : false;
- if(_op.operation.upsert != null) options.upsert = _op.operation.upsert;
-
- // Execute the update
- _collection.update(_op.operation.q, _op.operation.u, options, function(err, r, full) {
- // If we have don't have w:0 merge the result
- if(options.w == null || options.w != 0) {
- // Merge the results in
- var result = common.mergeLegacyResults(false, _op.operation, _batch, bulkResult, err || full, _op.index);
- if(result == false) {
- return _callback(null, new BatchWriteResult(bulkResult));
- }
- }
-
- return __callback(null, _result);
- });
- }
-
- // Execute all the insert operations
- for(var i = 0; i < _batch.operations.length; i++) {
- var legacyOp = new LegacyOp(_batch.batchType, _batch.operations[i], _batch.originalIndexes[i]);
- executeLegacyUpdate(i, legacyOp, options, function(err, result) {
- totalNumberOfUpdates = totalNumberOfUpdates - 1;
-
- // No more inserts
- if(totalNumberOfUpdates == 0) {
- _callback(null, _result);
- }
- });
- }
- }
-
- //
- // Execute updates
- var executeRemoves = function(_collection, _batch, _result, _callback) {
- var totalNumberOfRemoves = _batch.operations.length;
- // Options for the update operation
- var batchOptions = writeConcern || {};
-
- // Execute the op
- var executeLegacyRemove = function(_i, _op, _options, __callback) {
- var options = common.cloneOptions(batchOptions);
-
- // Add any additional options
- if(_op.operation.limit != null) options.single = _op.operation.limit == 1 ? true : false;
-
- // Execute the update
- _collection.remove(_op.operation.q, options, function(err, r) {
- // If we have don't have w:0 merge the result
- if(options.w == null || options.w != 0) {
- // Merge the results in
- var result = common.mergeLegacyResults(false, _op.operation, _batch, bulkResult, err || r, _op.index);
- if(result == false) {
- return _callback(null, new BatchWriteResult(bulkResult));
- }
- }
-
- return __callback(null, _result);
- });
- }
-
- // Execute all the insert operations
- for(var i = 0; i < _batch.operations.length; i++) {
- var legacyOp = new LegacyOp(_batch.batchType, _batch.operations[i], _batch.originalIndexes[i]);
- executeLegacyRemove(i, legacyOp, options, function(err, result) {
- totalNumberOfRemoves = totalNumberOfRemoves - 1;
-
- // No more inserts
- if(totalNumberOfRemoves == 0) {
- _callback(null, _result);
- }
- });
- }
- }
-
- //
- // Execute all operation in backwards compatible fashion
- var backwardsCompatibilityExecuteCommands = function(callback) {
- if(batches.length == 0) {
- return callback(null, new BatchWriteResult(bulkResult));
- }
-
- // Ordered execution of the command
- var batch = batches.shift();
-
- // Process the legacy operations
- var processLegacyOperations = function(err, results) {
- // Merge the results together
- var mergeResult = mergeBatchResults(false, batch, bulkResult, err, results);
- if(mergeResult != null) {
- return callback(null, mergeResult)
- }
-
- // If we have an error stop
- if(bulkResult.ok == 0 && callback) {
- var internalCallback = callback;
- callback = null;
- return internalCallback(bulkResult.error, null);
- } else if(bulkResult.ok == 0 && callback == null) {
- return;
- }
-
- // Execute the next step
- backwardsCompatibilityExecuteCommands(callback);
- }
-
- // Execute an insert batch
- if(batch.batchType == common.INSERT) {
- return executeInserts(collection, batch, {n: 0}, processLegacyOperations);
- }
-
- // Execute an update batch
- if(batch.batchType == common.UPDATE) {
- return executeUpdates(collection, batch, {n: 0}, processLegacyOperations);
- }
-
- // Execute an update batch
- if(batch.batchType == common.REMOVE) {
- return executeRemoves(collection, batch, {n: 0}, processLegacyOperations);
- }
- }
-}
-
-/**
- * Returns an unordered batch object
- *
- */
-var initializeUnorderedBulkOp = function(options) {
- return new UnorderedBulkOperation(this, options);
-}
-
-exports.initializeUnorderedBulkOp = initializeUnorderedBulkOp;
\ No newline at end of file
diff --git a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/collection/commands.js b/node_modules/mongojs/node_modules/mongodb/lib/mongodb/collection/commands.js
deleted file mode 100644
index 91632d0..0000000
--- a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/collection/commands.js
+++ /dev/null
@@ -1,139 +0,0 @@
-var shared = require('./shared')
- , utils = require('../utils')
- , f = require('util').format
- , DbCommand = require('../commands/db_command').DbCommand;
-
-var stats = function stats(options, callback) {
- var args = Array.prototype.slice.call(arguments, 0);
- callback = args.pop();
- // Fetch all commands
- options = args.length ? args.shift() || {} : {};
-
- // Build command object
- var commandObject = {
- collStats:this.collectionName,
- }
-
- // Check if we have the scale value
- if(options['scale'] != null) commandObject['scale'] = options['scale'];
-
- // Ensure we have the right read preference inheritance
- options.readPreference = shared._getReadConcern(this, options);
-
- // Execute the command
- this.db.command(commandObject, options, callback);
-}
-
-var count = function count(query, options, callback) {
- var args = Array.prototype.slice.call(arguments, 0);
- callback = args.pop();
- query = args.length ? args.shift() || {} : {};
- options = args.length ? args.shift() || {} : {};
- var skip = options.skip;
- var limit = options.limit;
- var hint = options.hint;
- var maxTimeMS = options.maxTimeMS;
-
- // Final query
- var cmd = {
- 'count': this.collectionName
- , 'query': query
- , 'fields': null
- };
-
- // Add limit and skip if defined
- if(typeof skip == 'number') cmd.skip = skip;
- if(typeof limit == 'number') cmd.limit = limit;
- if(hint) cmd.hint = hint;
-
- // Ensure we have the right read preference inheritance
- options.readPreference = shared._getReadConcern(this, options);
-
- // Execute the command
- this.db.command(cmd, options, function(err, result) {
- if(err) return callback(err);
- callback(null, result.n);
- });
-};
-
-var distinct = function distinct(key, query, options, callback) {
- var args = Array.prototype.slice.call(arguments, 1);
- callback = args.pop();
- query = args.length ? args.shift() || {} : {};
- options = args.length ? args.shift() || {} : {};
- var maxTimeMS = options.maxTimeMS;
-
- var cmd = {
- 'distinct': this.collectionName
- , 'key': key
- , 'query': query
- };
-
- // Ensure we have the right read preference inheritance
- options.readPreference = shared._getReadConcern(this, options);
-
- // Execute the command
- this.db.command(cmd, options, function(err, result) {
- if(err) return callback(err);
- callback(null, result.values);
- });
-};
-
-var rename = function rename (newName, options, callback) {
- var self = this;
- if(typeof options == 'function') {
- callback = options;
- options = {}
- }
-
- // Get collection class
- var Collection = require('../collection').Collection;
- // Ensure the new name is valid
- shared.checkCollectionName(newName);
-
- // Build the command
- var renameCollection = self.db.databaseName + "." + self.collectionName;
- var toCollection = self.db.databaseName + "." + newName;
- var dropTarget = typeof options.dropTarget == 'boolean' ? options.dropTarget : false;
- var cmd = {'renameCollection':renameCollection, 'to':toCollection, 'dropTarget':dropTarget};
-
- // Execute against admin
- self.db.admin().command(cmd, options, function(err, result) {
- if(err) return callback(err, null);
- var doc = result.documents[0];
- // We have an error
- if(doc.errmsg) return callback(utils.toError(doc), null);
- try {
- return callback(null, new Collection(self.db, newName, self.db.pkFactory));
- } catch(err) {
- return callback(utils.toError(err), null);
- }
- });
-};
-
-var options = function options(callback) {
- var self = this;
-
- self.db.listCollections(self.collectionName, function(err, collections) {
- if(err) return callback(err);
- if(collections.length == 0) return callback(utils.toError(f("collection %s.%s not found", self.db.databaseName, self.collectionName)));
- callback(err, collections[0].options || null);
- });
-};
-
-var isCapped = function isCapped(callback) {
- this.options(function(err, document) {
- if(err != null) {
- callback(err);
- } else {
- callback(null, document && document.capped);
- }
- });
-};
-
-exports.stats = stats;
-exports.count = count;
-exports.distinct = distinct;
-exports.rename = rename;
-exports.options = options;
-exports.isCapped = isCapped;
\ No newline at end of file
diff --git a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/collection/core.js b/node_modules/mongojs/node_modules/mongodb/lib/mongodb/collection/core.js
deleted file mode 100644
index 76583a9..0000000
--- a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/collection/core.js
+++ /dev/null
@@ -1,800 +0,0 @@
-var InsertCommand = require('../commands/insert_command').InsertCommand
- , DeleteCommand = require('../commands/delete_command').DeleteCommand
- , UpdateCommand = require('../commands/update_command').UpdateCommand
- , DbCommand = require('../commands/db_command').DbCommand
- , utils = require('../utils')
- , hasWriteCommands = require('../utils').hasWriteCommands
- , shared = require('./shared');
-
-/**
- * Precompiled regexes
- * @ignore
- **/
-var eErrorMessages = /No matching object found/;
-
-// ***************************************************
-// Insert function
-// ***************************************************
-var insert = function insert (docs, options, callback) {
- if ('function' === typeof options) callback = options, options = {};
- if(options == null) options = {};
- if(!('function' === typeof callback)) callback = null;
-
- // Get a connection
- var connection = this.db.serverConfig.checkoutWriter();
- var useLegacyOps = options.useLegacyOps == null || options.useLegacyOps == false ? false : true;
- // If we support write commands let's perform the insert using it
- if(!useLegacyOps && hasWriteCommands(connection)
- && !Buffer.isBuffer(docs)
- && !(Array.isArray(docs) && docs.length > 0 && Buffer.isBuffer(docs[0]))) {
- insertWithWriteCommands(this, Array.isArray(docs) ? docs : [docs], options, callback);
- return this
- }
-
- // Backwards compatibility
- insertAll(this, Array.isArray(docs) ? docs : [docs], options, callback);
- return this;
-};
-
-//
-// Uses the new write commands available from 2.6 >
-//
-var insertWithWriteCommands = function(self, docs, options, callback) {
- // Get the intended namespace for the operation
- var namespace = self.collectionName;
-
- // Ensure we have no \x00 bytes in the name causing wrong parsing
- if(!!~namespace.indexOf("\x00")) {
- return callback(new Error("namespace cannot contain a null character"), null);
- }
-
- // Check if we have passed in continue on error
- var continueOnError = typeof options['keepGoing'] == 'boolean'
- ? options['keepGoing'] : false;
- continueOnError = typeof options['continueOnError'] == 'boolean'
- ? options['continueOnError'] : continueOnError;
-
- // Do we serialzie functions
- var serializeFunctions = typeof options.serializeFunctions != 'boolean'
- ? self.serializeFunctions : options.serializeFunctions;
-
- // Checkout a write connection
- var connection = self.db.serverConfig.checkoutWriter();
-
- // Do we return the actual result document
- var fullResult = typeof options.fullResult == 'boolean' ? options.fullResult : false;
-
- // Collect errorOptions
- var errorOptions = shared._getWriteConcern(self, options);
-
- // If we have a write command with no callback and w:0 fail
- if(errorOptions.w && errorOptions.w != 0 && callback == null) {
- throw new Error("writeConcern requires callback")
- }
-
- // Add the documents and decorate them with id's if they have none
- for(var index = 0, len = docs.length; index < len; ++index) {
- var doc = docs[index];
-
- // Add id to each document if it's not already defined
- if (!(Buffer.isBuffer(doc))
- && doc['_id'] == null
- && self.db.forceServerObjectId != true
- && options.forceServerObjectId != true) {
- doc['_id'] = self.pkFactory.createPk();
- }
- }
-
- // Single document write
- if(docs.length == 1) {
- // Create the write command
- var write_command = {
- insert: namespace
- , writeConcern: errorOptions
- , ordered: !continueOnError
- , documents: docs
- }
-
- // Execute the write command
- return self.db.command(write_command
- , { connection:connection
- , checkKeys: typeof options.checkKeys == 'boolean' ? options.checkKeys : true
- , serializeFunctions: serializeFunctions
- , writeCommand: true }
- , function(err, result) {
- if(errorOptions.w == 0 && typeof callback == 'function') return callback(null, null);
- if(errorOptions.w == 0) return;
- if(callback == null) return;
- if(err != null) {
- return callback(err, null);
- }
-
- // Result has an error
- if(!result.ok || Array.isArray(result.writeErrors) && result.writeErrors.length > 0) {
- var error = utils.toError(result.writeErrors[0].errmsg);
- error.code = result.writeErrors[0].code;
- error.err = result.writeErrors[0].errmsg;
-
- if (fullResult) return callback(error, result != null ? result.getRawResponse() : null);
- // Return the error
- return callback(error, null);
- }
-
- if(fullResult) return callback(null, result);
- // Return the results for a whole batch
- callback(null, docs)
- });
- } else {
- try {
- // Multiple document write (use bulk)
- var bulk = !continueOnError ? self.initializeOrderedBulkOp() : self.initializeUnorderedBulkOp();
- // Add all the documents
- for(var i = 0; i < docs.length;i++) {
- bulk.insert(docs[i]);
- }
-
- // Execute the command
- bulk.execute(errorOptions, function(err, result) {
- if(errorOptions.w == 0 && typeof callback == 'function') return callback(null, null);
- if(errorOptions.w == 0) return;
- if(callback == null) return;
- if(err) return callback(err, null);
- if(result.hasWriteErrors()) {
- var error = result.getWriteErrors()[0];
- error.code = result.getWriteErrors()[0].code;
- error.err = result.getWriteErrors()[0].errmsg;
-
- if (fullResult) return callback(error, result != null ? result.getRawResponse() : null);
- // Return the error
- return callback(error, null);
- }
-
- if(fullResult) return callback(null, result != null ? result.getRawResponse() : null);
- // Return the results for a whole batch
- callback(null, docs)
- });
- } catch(err) {
- callback(utils.toError(err), null);
- }
- }
-}
-
-//
-// Uses pre 2.6 OP_INSERT wire protocol
-//
-var insertAll = function insertAll (self, docs, options, callback) {
- if('function' === typeof options) callback = options, options = {};
- if(options == null) options = {};
- if(!('function' === typeof callback)) callback = null;
-
- // Insert options (flags for insert)
- var insertFlags = {};
- // If we have a mongodb version >= 1.9.1 support keepGoing attribute
- if(options['keepGoing'] != null) {
- insertFlags['keepGoing'] = options['keepGoing'];
- }
-
- // If we have a mongodb version >= 1.9.1 support keepGoing attribute
- if(options['continueOnError'] != null) {
- insertFlags['continueOnError'] = options['continueOnError'];
- }
-
- // DbName
- var dbName = options['dbName'];
- // If no dbname defined use the db one
- if(dbName == null) {
- dbName = self.db.databaseName;
- }
-
- // Either use override on the function, or go back to default on either the collection
- // level or db
- if(options['serializeFunctions'] != null) {
- insertFlags['serializeFunctions'] = options['serializeFunctions'];
- } else {
- insertFlags['serializeFunctions'] = self.serializeFunctions;
- }
-
- // Get checkKeys value
- var checkKeys = typeof options.checkKeys != 'boolean' ? true : options.checkKeys;
-
- // Do we return the actual result document
- var fullResult = typeof options.fullResult == 'boolean' ? options.fullResult : false;
-
- // Pass in options
- var insertCommand = new InsertCommand(
- self.db
- , dbName + "." + self.collectionName, checkKeys, insertFlags);
-
- // Add the documents and decorate them with id's if they have none
- for(var index = 0, len = docs.length; index < len; ++index) {
- var doc = docs[index];
-
- // Add id to each document if it's not already defined
- if (!(Buffer.isBuffer(doc))
- && doc['_id'] == null
- && self.db.forceServerObjectId != true
- && options.forceServerObjectId != true) {
- doc['_id'] = self.pkFactory.createPk();
- }
-
- insertCommand.add(doc);
- }
-
- // Collect errorOptions
- var errorOptions = shared._getWriteConcern(self, options);
- // Default command options
- var commandOptions = {};
- // If safe is defined check for error message
- if(shared._hasWriteConcern(errorOptions) && typeof callback == 'function') {
- // 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]];
- }
- }
-
- // If we have a passed in connection use it
- if(options.connection) {
- commandOptions.connection = options.connection;
- }
-
- // 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, handleWriteResults(function (err, results) {
- if(err) return callback(err, null);
- if(results == null) return callback(new Error("command failed to return result"));
- if(fullResult) return callback(null, results);
- callback(null, docs);
- }));
- } else if(shared._hasWriteConcern(errorOptions) && callback == null) {
- throw new Error("Cannot use a writeConcern without a provided callback");
- } else {
- // Execute the call without a write concern
- var result = self.db._executeInsertCommand(insertCommand, commandOptions);
- // If no callback just return
- if(!callback) return;
- // If error return error
- if(result instanceof Error) {
- return callback(result);
- }
-
- // Otherwise just return
- return callback(null, docs);
- }
-};
-
-// ***************************************************
-// Remove function
-// ***************************************************
-var removeWithWriteCommands = function(self, selector, options, callback) {
- if('function' === typeof selector) {
- callback = selector;
- selector = options = {};
- } else if ('function' === typeof options) {
- callback = options;
- options = {};
- }
-
- // Get the intended namespace for the operation
- var namespace = self.collectionName;
-
- // Ensure we have no \x00 bytes in the name causing wrong parsing
- if(!!~namespace.indexOf("\x00")) {
- return callback(new Error("namespace cannot contain a null character"), null);
- }
-
- // Set default empty selector if none
- selector = selector == null ? {} : selector;
-
- // Check if we have passed in continue on error
- var continueOnError = typeof options['keepGoing'] == 'boolean'
- ? options['keepGoing'] : false;
- continueOnError = typeof options['continueOnError'] == 'boolean'
- ? options['continueOnError'] : continueOnError;
-
- // Do we serialzie functions
- var serializeFunctions = typeof options.serializeFunctions != 'boolean'
- ? self.serializeFunctions : options.serializeFunctions;
-
- // Checkout a write connection
- var connection = self.db.serverConfig.checkoutWriter();
-
- // Figure out the value of top
- var limit = options.single == true ? 1 : 0;
- var upsert = typeof options.upsert == 'boolean' ? options.upsert : false;
-
- // Do we return the actual result document
- var fullResult = typeof options.fullResult == 'boolean' ? options.fullResult : false;
-
- // Collect errorOptions
- var errorOptions = shared._getWriteConcern(self, options);
-
- // If we have a write command with no callback and w:0 fail
- if(errorOptions.w && errorOptions.w != 0 && callback == null) {
- throw new Error("writeConcern requires callback")
- }
-
- // Create the write command
- var write_command = {
- delete: namespace,
- writeConcern: errorOptions,
- ordered: !continueOnError,
- deletes: [{
- q : selector,
- limit: limit
- }]
- }
-
- // Execute the write command
- self.db.command(write_command
- , { connection:connection
- , checkKeys: false
- , serializeFunctions: serializeFunctions
- , writeCommand: true }
- , function(err, result) {
- if(errorOptions.w == 0 && typeof callback == 'function') return callback(null, null);
- if(errorOptions.w == 0) return;
- if(callback == null) return;
- if(err != null) {
- return callback(err, null);
- }
-
- // Result has an error
- if(!result.ok || Array.isArray(result.writeErrors) && result.writeErrors.length > 0) {
- var error = utils.toError(result.writeErrors[0].errmsg);
- error.code = result.writeErrors[0].code;
- error.err = result.writeErrors[0].errmsg;
- // Return the error
- return callback(error, null);
- }
-
- if(fullResult) return callback(null, result);
- // Backward compatibility format
- var r = backWardsCompatibiltyResults(result, 'remove');
- // Return the results for a whole batch
- callback(null, r.n, r)
- });
-}
-
-var remove = function remove(selector, options, callback) {
- if('function' === typeof options) callback = options, options = null;
- if(options == null) options = {};
- if(!('function' === typeof callback)) callback = null;
-
- // Get a connection
- var connection = this.db.serverConfig.checkoutWriter();
- var useLegacyOps = options.useLegacyOps == null || options.useLegacyOps == false ? false : true;
-
- // If we support write commands let's perform the insert using it
- if(!useLegacyOps && hasWriteCommands(connection) && !Buffer.isBuffer(selector)) {
- return removeWithWriteCommands(this, 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);
-
- // Do we return the actual result document
- var fullResult = typeof options.fullResult == 'boolean' ? options.fullResult : false;
-
- // DbName
- var dbName = options['dbName'];
- // If no dbname defined use the db one
- if(dbName == null) {
- dbName = this.db.databaseName;
- }
-
- // Create a delete command
- var deleteCommand = new DeleteCommand(
- this.db
- , dbName + "." + this.collectionName
- , selector
- , flags);
-
- var self = this;
- var errorOptions = shared._getWriteConcern(self, options);
-
- // Execute the command, do not add a callback as it's async
- if(shared._hasWriteConcern(errorOptions) && typeof callback == 'function') {
- // Insert options
- var commandOptions = {};
- // 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]];
- }
- }
-
- // If we have a passed in connection use it
- if(options.connection) {
- commandOptions.connection = options.connection;
- }
-
- // 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, handleWriteResults(function (err, results) {
- if(err) return callback(err, null);
- if(results == null) return callback(new Error("command failed to return result"));
- if(fullResult) return callback(null, results);
- callback(null, results[0].n);
- }));
- } else if(shared._hasWriteConcern(errorOptions) && callback == null) {
- throw new Error("Cannot use a writeConcern without a provided callback");
- } else {
- var result = this.db._executeRemoveCommand(deleteCommand);
- // If no callback just return
- if (!callback) return;
- // If error return error
- if (result instanceof Error) {
- return callback(result);
- }
- // Otherwise just return
- return callback();
- }
-};
-
-// ***************************************************
-// Save function
-// ***************************************************
-var save = function save(doc, options, callback) {
- if('function' === typeof options) callback = options, options = null;
- if(options == null) options = {};
- if(!('function' === typeof callback)) callback = null;
- // Throw an error if attempting to perform a bulk operation
- if(Array.isArray(doc)) throw new Error("doc parameter must be a single document");
- // Extract the id, if we have one we need to do a update command
- var id = doc['_id'];
- var commandOptions = shared._getWriteConcern(this, options);
- if(options.connection) commandOptions.connection = options.connection;
- if(typeof options.fullResult == 'boolean') commandOptions.fullResult = options.fullResult;
-
- if(id != null) {
- commandOptions.upsert = true;
- this.update({ _id: id }, doc, commandOptions, callback);
- } else {
- this.insert(doc, commandOptions, callback && function (err, docs) {
- if(err) return callback(err, null);
-
- if(Array.isArray(docs)) {
- callback(err, docs[0]);
- } else {
- callback(err, docs);
- }
- });
- }
-};
-
-// ***************************************************
-// Update document function
-// ***************************************************
-var updateWithWriteCommands = function(self, selector, document, options, callback) {
- if('function' === typeof options) callback = options, options = null;
- if(options == null) options = {};
- if(!('function' === typeof callback)) callback = null;
-
- // Get the intended namespace for the operation
- var namespace = self.collectionName;
-
- // Ensure we have no \x00 bytes in the name causing wrong parsing
- if(!!~namespace.indexOf("\x00")) {
- return callback(new Error("namespace cannot contain a null character"), null);
- }
-
- // If we are not providing a selector or document throw
- if(selector == null || typeof selector != 'object')
- return callback(new Error("selector must be a valid JavaScript object"));
- if(document == null || typeof document != 'object')
- return callback(new Error("document must be a valid JavaScript object"));
-
- // Check if we have passed in continue on error
- var continueOnError = typeof options['keepGoing'] == 'boolean'
- ? options['keepGoing'] : false;
- continueOnError = typeof options['continueOnError'] == 'boolean'
- ? options['continueOnError'] : continueOnError;
-
- // Do we serialzie functions
- var serializeFunctions = typeof options.serializeFunctions != 'boolean'
- ? self.serializeFunctions : options.serializeFunctions;
-
- // Checkout a write connection
- var connection = self.db.serverConfig.checkoutWriter();
-
- // Figure out the value of top
- var multi = typeof options.multi == 'boolean' ? options.multi : false;
- var upsert = typeof options.upsert == 'boolean' ? options.upsert : false;
-
- // Do we return the actual result document
- var fullResult = typeof options.fullResult == 'boolean' ? options.fullResult : false;
-
- // Collect errorOptions
- var errorOptions = shared._getWriteConcern(self, options);
-
- // If we have a write command with no callback and w:0 fail
- if(errorOptions.w && errorOptions.w != 0 && callback == null) {
- throw new Error("writeConcern requires callback")
- }
-
- // Create the write command
- var write_command = {
- update: namespace,
- writeConcern: errorOptions,
- ordered: !continueOnError,
- updates: [{
- q : selector,
- u: document,
- multi: multi,
- upsert: upsert
- }]
- }
-
- // Check if we have a checkKeys override
- var checkKeys = typeof options.checkKeys == 'boolean' ? options.checkKeys : false;
-
- // Execute the write command
- self.db.command(write_command
- , { connection:connection
- , checkKeys: checkKeys
- , serializeFunctions: serializeFunctions
- , writeCommand: true }
- , function(err, result) {
- if(errorOptions.w == 0 && typeof callback == 'function') return callback(null, null);
- if(errorOptions.w == 0) return;
- if(callback == null) return;
-
- if(errorOptions.w == 0 && typeof callback == 'function') return callback(null, null);
- if(errorOptions.w == 0) return;
- if(callback == null) return;
- if(err != null) {
- return callback(err, null);
- }
-
- // Result has an error
- if(!result.ok || Array.isArray(result.writeErrors) && result.writeErrors.length > 0) {
- var error = utils.toError(result.writeErrors[0].errmsg);
- error.code = result.writeErrors[0].code;
- error.err = result.writeErrors[0].errmsg;
- return callback(error, null);
- }
-
- if(fullResult) return callback(null, result);
- // Backward compatibility format
- var r = backWardsCompatibiltyResults(result, 'update');
- // Return the results for a whole batch
- callback(null, r.n, r)
- });
-}
-
-var backWardsCompatibiltyResults = function(result, op) {
- // Upserted
- var upsertedValue = null;
- var finalResult = null;
- var updatedExisting = true;
-
- // We have a single document upserted result
- if(Array.isArray(result.upserted) || result.upserted != null) {
- updatedExisting = false;
- upsertedValue = result.upserted;
- }
-
- // Final result
- if(op == 'remove' || op == 'insert') {
- finalResult = {ok: true, n: result.n}
- } else {
- finalResult = {ok: true, n: result.n, updatedExisting: updatedExisting}
- }
-
- if(upsertedValue != null) finalResult.upserted = upsertedValue;
- return finalResult;
-}
-
-var handleWriteResults = function handleWriteResults(callback) {
- return function(err, error) {
- var documents = error && error.documents;
- if(!callback) return;
- // We have an error
- if(err) return callback(err, null);
- // If no document something is terribly wrong
- if(error == null) return callback(utils.toError("MongoDB did not return a response"));
- // Handle the case where no result was returned
- if(error != null && documents == null) {
- if(typeof error.err == 'string') {
- return callback(utils.toError(error.err));
- } else if(typeof error.errmsg == 'string') {
- return callback(utils.toError(error.errmsg));
- } else {
- return callback(utils.toError("Unknown MongoDB error"));
- }
- }
-
- // Handler normal cases
- if(documents[0].err || documents[0].errmsg) {
- callback(utils.toError(documents[0]));
- } else if(documents[0].jnote || documents[0].wtimeout) {
- callback(utils.toError(documents[0]));
- } else {
- callback(err, documents);
- }
- }
-}
-
-var 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;
-
- // Get a connection
- var connection = options.connection || this.db.serverConfig.checkoutWriter();
- var useLegacyOps = options.useLegacyOps == null || options.useLegacyOps == false ? false : true;
- // If we support write commands let's perform the insert using it
- if(!useLegacyOps && hasWriteCommands(connection) && !Buffer.isBuffer(selector) && !Buffer.isBuffer(document)) {
- return updateWithWriteCommands(this, selector, document, options, callback);
- }
-
- // DbName
- var dbName = options['dbName'];
- // If no dbname defined use the db one
- if(dbName == null) {
- dbName = this.db.databaseName;
- }
-
- // If we are not providing a selector or document throw
- if(selector == null || typeof selector != 'object') return callback(new Error("selector must be a valid JavaScript object"));
- if(document == null || typeof document != 'object') return callback(new Error("document must be a valid JavaScript object"));
-
- // Do we return the actual result document
- var fullResult = typeof options.fullResult == 'boolean' ? options.fullResult : false;
-
- // Either use override on the function, or go back to default on either the collection
- // level or db
- if(options['serializeFunctions'] != null) {
- options['serializeFunctions'] = options['serializeFunctions'];
- } else {
- options['serializeFunctions'] = this.serializeFunctions;
- }
-
- // Build the options command
- var updateCommand = new UpdateCommand(
- this.db
- , dbName + "." + this.collectionName
- , selector
- , document
- , options);
-
- var self = this;
- // Unpack the error options if any
- var errorOptions = shared._getWriteConcern(this, options);
- // If safe is defined check for error message
- if(shared._hasWriteConcern(errorOptions) && typeof callback == 'function') {
- // Insert options
- var commandOptions = {};
- // 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]];
- }
- }
-
- // If we have a passed in connection use it
- if(options.connection) {
- commandOptions.connection = options.connection;
- }
-
- // 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, handleWriteResults(function(err, results) {
- if(err) return callback(err, null);
- if(results == null) return callback(new Error("command failed to return result"));
- if(fullResult) return callback(null, results);
- callback(null, results[0].n, results[0]);
- }));
- } else if(shared._hasWriteConcern(errorOptions) && callback == null) {
- throw new Error("Cannot use a writeConcern without a provided callback");
- } else {
- // Execute update
- var result = this.db._executeUpdateCommand(updateCommand);
- // If no callback just return
- if (!callback) return;
- // If error return error
- if (result instanceof Error) {
- return callback(result);
- }
-
- // Otherwise just return
- return callback();
- }
-};
-
-// ***************************************************
-// findAndModify function
-// ***************************************************
-var 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);
- if (sort) {
- queryObject.sort = 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;
- }
-
- // Checkout a write connection
- options.connection = self.db.serverConfig.checkoutWriter();
-
- // 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;
- }
-
- // No check on the documents
- options.checkKeys = false;
-
- // Execute the command
- this.db.command(queryObject
- , options, function(err, result) {
- if(err) return callback(err, null);
- return callback(null, result.value, result);
- });
-}
-
-// ***************************************************
-// findAndRemove function
-// ***************************************************
-var 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);
-}
-
-// Map methods
-exports.insert = insert;
-exports.remove = remove;
-exports.save = save;
-exports.update = update;
-exports.findAndModify = findAndModify;
-exports.findAndRemove = findAndRemove;
diff --git a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/collection/geo.js b/node_modules/mongojs/node_modules/mongodb/lib/mongodb/collection/geo.js
deleted file mode 100644
index e64f2f5..0000000
--- a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/collection/geo.js
+++ /dev/null
@@ -1,71 +0,0 @@
-var shared = require('./shared')
- , utils = require('../utils');
-
-var geoNear = function geoNear(x, y, options, callback) {
- var point = typeof(x) == 'object' && x
- , args = Array.prototype.slice.call(arguments, point?1:2);
-
- callback = args.pop();
- // Fetch all commands
- options = args.length ? args.shift() || {} : {};
-
- // Build command object
- var commandObject = {
- geoNear:this.collectionName,
- near: point || [x, y]
- }
-
- // Ensure we have the right read preference inheritance
- options.readPreference = shared._getReadConcern(this, options);
-
- // Remove read preference from hash if it exists
- commandObject = utils.decorateCommand(commandObject, options, {readPreference: true});
-
- // Execute the command
- this.db.command(commandObject, options, function (err, res) {
- if (err) {
- callback(err);
- } else if (res.err || res.errmsg) {
- callback(utils.toError(res));
- } else {
- // should we only be returning res.results here? Not sure if the user
- // should see the other return information
- callback(null, res);
- }
- });
-}
-
-var 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]
- }
-
- // Remove read preference from hash if it exists
- commandObject = utils.decorateCommand(commandObject, options, {readPreference: true});
-
- // Ensure we have the right read preference inheritance
- options.readPreference = shared._getReadConcern(this, options);
-
- // Execute the command
- this.db.command(commandObject, options, function (err, res) {
- if (err) {
- callback(err);
- } else if (res.err || res.errmsg) {
- callback(utils.toError(res));
- } else {
- // should we only be returning res.results here? Not sure if the user
- // should see the other return information
- callback(null, res);
- }
- });
-}
-
-exports.geoNear = geoNear;
-exports.geoHaystackSearch = geoHaystackSearch;
diff --git a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/collection/index.js b/node_modules/mongojs/node_modules/mongodb/lib/mongodb/collection/index.js
deleted file mode 100644
index dda9cc8..0000000
--- a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/collection/index.js
+++ /dev/null
@@ -1,72 +0,0 @@
-var _getWriteConcern = require('./shared')._getWriteConcern;
-
-var createIndex = function createIndex (fieldOrSpec, options, callback) {
- // Clean up call
- var args = Array.prototype.slice.call(arguments, 1);
- callback = args.pop();
- options = args.length ? args.shift() || {} : {};
- options = typeof callback === 'function' ? options : callback;
- options = options == null ? {} : options;
-
- // Collect errorOptions
- var errorOptions = _getWriteConcern(this, options);
- // Execute create index
- this.db.createIndex(this.collectionName, fieldOrSpec, options, callback);
-};
-
-var 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);
- }
- });
-}
-
-var dropAllIndexes = function dropIndexes (callback) {
- this.db.dropIndex(this.collectionName, '*', function (err, result) {
- if(err) return callback(err, false);
- callback(null, true);
- });
-};
-
-var 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);
-};
-
-var ensureIndex = function ensureIndex (fieldOrSpec, options, callback) {
- // Clean up call
- if (typeof callback === 'undefined' && typeof options === 'function') {
- callback = options;
- options = {};
- }
-
- if (options == null) {
- options = {};
- }
-
- // Execute create index
- this.db.ensureIndex(this.collectionName, fieldOrSpec, options, callback);
-};
-
-exports.createIndex = createIndex;
-exports.indexExists = indexExists;
-exports.dropAllIndexes = dropAllIndexes;
-exports.indexInformation = indexInformation;
-exports.ensureIndex = ensureIndex;
diff --git a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/collection/query.js b/node_modules/mongojs/node_modules/mongodb/lib/mongodb/collection/query.js
deleted file mode 100644
index 1aa6260..0000000
--- a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/collection/query.js
+++ /dev/null
@@ -1,218 +0,0 @@
-var ObjectID = require('bson').ObjectID
- , Long = require('bson').Long
- , DbCommand = require('../commands/db_command').DbCommand
- , CommandCursor = require('../command_cursor').CommandCursor
- , Scope = require('../scope').Scope
- , shared = require('./shared')
- , utils = require('../utils');
-
-var testForFields = {
- limit: 1, sort: 1, fields:1, skip: 1, hint: 1, explain: 1, snapshot: 1, timeout: 1, tailable: 1, tailableRetryInterval: 1
- , numberOfRetries: 1, awaitdata: 1, exhaust: 1, batchSize: 1, returnKey: 1, maxScan: 1, min: 1, max: 1, showDiskLoc: 1
- , comment: 1, raw: 1, readPreference: 1, partial: 1, read: 1, dbName: 1, oplogReplay: 1, connection: 1
-};
-
-//
-// Find method
-//
-var 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.keys(fields);
- var is_option = false;
-
- for(var i = 0; i < fieldKeys.length; i++) {
- if(testForFields[fieldKeys[i]] != null) {
- is_option = true;
- break;
- }
- }
-
- if(is_option) {
- options = fields;
- fields = undefined;
- } else {
- options = {};
- }
- } else if(len === 2 && Array.isArray(fields) && !Array.isArray(fields[0])) {
- var newFields = {};
- // Rewrite the array
- for(var i = 0; i < fields.length; i++) {
- newFields[fields[i]] = 1;
- }
- // Set the fields
- fields = newFields;
- }
-
- if(3 === len) {
- options = args[2];
- }
-
- // Ensure selector is not null
- selector = selector == null ? {} : selector;
- // Validate correctness off the selector
- var object = selector;
- if(Buffer.isBuffer(object)) {
- var object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24;
- if(object_size != object.length) {
- var error = new Error("query selector raw message size does not match message header size [" + object.length + "] != [" + object_size + "]");
- error.name = 'MongoError';
- throw error;
- }
- }
-
- // Validate correctness of the field selector
- var object = fields;
- if(Buffer.isBuffer(object)) {
- var object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24;
- if(object_size != object.length) {
- var error = new Error("query fields raw message size does not match message header size [" + object.length + "] != [" + object_size + "]");
- error.name = 'MongoError';
- throw error;
- }
- }
-
- // Check special case where we are using an objectId
- if(selector instanceof ObjectID || (selector != null && selector._bsontype == 'ObjectID')) {
- selector = {_id:selector};
- }
-
- // If it's a serialized fields field we need to just let it through
- // user be warned it better be good
- if(options && options.fields && !(Buffer.isBuffer(options.fields))) {
- fields = {};
-
- if(Array.isArray(options.fields)) {
- if(!options.fields.length) {
- fields['_id'] = 1;
- } else {
- for (var i = 0, l = options.fields.length; i < l; i++) {
- fields[options.fields[i]] = 1;
- }
- }
- } else {
- fields = options.fields;
- }
- }
-
- if (!options) options = {};
-
- var newOptions = {};
- // Make a shallow copy of options
- for (var key in options) {
- newOptions[key] = options[key];
- }
-
- newOptions.skip = len > 3 ? args[2] : options.skip ? options.skip : 0;
- newOptions.limit = len > 3 ? args[3] : options.limit ? options.limit : 0;
- newOptions.raw = options.raw != null && typeof options.raw === 'boolean' ? options.raw : this.raw;
- newOptions.hint = options.hint != null ? shared.normalizeHintField(options.hint) : this.internalHint;
- newOptions.timeout = len == 5 ? args[4] : typeof options.timeout === 'undefined' ? undefined : options.timeout;
- // If we have overridden slaveOk otherwise use the default db setting
- newOptions.slaveOk = options.slaveOk != null ? options.slaveOk : this.db.slaveOk;
-
- // Set option
- var o = newOptions;
- // Support read/readPreference
- if(o["read"] != null) o["readPreference"] = o["read"];
- // If no readPreference specified set the collection level readPreference
- o.readPreference = o.readPreference ? o.readPreference : this.readPreference;
- // If still no readPreference specified set the db level
- o.readPreference = o.readPreference ? o.readPreference : this.db.options.readPreference;
- // Set slaveok if needed
- if(o.readPreference == "secondary" || o.read == "secondaryOnly") o.slaveOk = true;
-
- // Ensure the query is an object
- if(selector != null && typeof selector != 'object') {
- throw utils.toError("query selector must be an object");
- }
-
- // Set the selector
- o.selector = selector;
-
- // Create precursor
- var scope = new Scope(this, {}, fields, o);
- // Callback for backward compatibility
- if(callback) return callback(null, scope.find(selector));
- // Return the pre cursor object
- return scope.find(selector);
-};
-
-var findOne = function findOne () {
- var self = this;
- var args = Array.prototype.slice.call(arguments, 0);
- var callback = args.pop();
- var cursor = this.find.apply(this, args).limit(-1).batchSize(1);
-
- // Return the item
- cursor.nextObject(function(err, item) {
- if(err != null) return callback(utils.toError(err), null);
- callback(null, item);
- });
-};
-
-var parallelCollectionScan = function parallelCollectionScan (options, callback) {
- var self = this;
-
- if(typeof options == 'function') {
- callback = options;
- options = {numCursors: 1};
- }
-
- // Set number of cursors to 1
- options.numCursors = options.numCursors || 1;
- options.batchSize = options.batchSize || 1000;
-
- // Set read preference if we set one
- options.readPreference = shared._getReadConcern(this, options);
-
- // Create command object
- var commandObject = {
- parallelCollectionScan: this.collectionName
- , numCursors: options.numCursors
- }
-
- // Execute the command
- this.db.command(commandObject, options, function(err, result) {
- if(err) return callback(err, null);
- if(result == null) return callback(new Error("no result returned for parallelCollectionScan"), null);
-
- var cursors = [];
- // Create command cursors for each item
- for(var i = 0; i < result.cursors.length; i++) {
- var rawId = result.cursors[i].cursor.id
- // Convert cursorId to Long if needed
- var cursorId = typeof rawId == 'number' ? Long.fromNumber(rawId) : rawId;
-
- // Command cursor options
- var commandOptions = {
- batchSize: options.batchSize
- , cursorId: cursorId
- , items: result.cursors[i].cursor.firstBatch
- }
-
- // Add a command cursor
- cursors.push(new CommandCursor(self.db, self, {}, commandOptions));
- }
-
- callback(null, cursors);
- });
-}
-
-exports.find = find;
-exports.findOne = findOne;
-exports.parallelCollectionScan = parallelCollectionScan;
diff --git a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/collection/shared.js b/node_modules/mongojs/node_modules/mongodb/lib/mongodb/collection/shared.js
deleted file mode 100644
index 77eae03..0000000
--- a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/collection/shared.js
+++ /dev/null
@@ -1,120 +0,0 @@
-// ***************************************************
-// Write concerns
-// ***************************************************
-var _hasWriteConcern = function(errorOptions) {
- return errorOptions == true
- || errorOptions.w > 0
- || errorOptions.w == 'majority'
- || errorOptions.j == true
- || errorOptions.journal == true
- || errorOptions.fsync == true
-}
-
-var _setWriteConcernHash = function(options) {
- var finalOptions = {};
- if(options.w != null) finalOptions.w = options.w;
- if(options.journal == true) finalOptions.j = options.journal;
- if(options.j == true) finalOptions.j = options.j;
- if(options.fsync == true) finalOptions.fsync = options.fsync;
- if(options.wtimeout != null) finalOptions.wtimeout = options.wtimeout;
- return finalOptions;
-}
-
-var _getWriteConcern = function(self, options) {
- // Final options
- var finalOptions = {w:1};
- // Local options verification
- if(options.w != null || typeof options.j == 'boolean' || typeof options.journal == 'boolean' || typeof options.fsync == 'boolean') {
- finalOptions = _setWriteConcernHash(options);
- } else if(typeof options.safe == "boolean") {
- finalOptions = {w: (options.safe ? 1 : 0)};
- } else if(options.safe != null && typeof options.safe == 'object') {
- finalOptions = _setWriteConcernHash(options.safe);
- } else if(self.opts.w != null || typeof self.opts.j == 'boolean' || typeof self.opts.journal == 'boolean' || typeof self.opts.fsync == 'boolean') {
- finalOptions = _setWriteConcernHash(self.opts);
- } else if(typeof self.opts.safe == "boolean") {
- finalOptions = {w: (self.opts.safe ? 1 : 0)};
- } else if(self.db.safe.w != null || typeof self.db.safe.j == 'boolean' || typeof self.db.safe.journal == 'boolean' || typeof self.db.safe.fsync == 'boolean') {
- finalOptions = _setWriteConcernHash(self.db.safe);
- } else if(self.db.options.w != null || typeof self.db.options.j == 'boolean' || typeof self.db.options.journal == 'boolean' || typeof self.db.options.fsync == 'boolean') {
- finalOptions = _setWriteConcernHash(self.db.options);
- } else if(typeof self.db.safe == "boolean") {
- finalOptions = {w: (self.db.safe ? 1 : 0)};
- }
-
- // Ensure we don't have an invalid combination of write concerns
- if(finalOptions.w < 1
- && (finalOptions.journal == true || finalOptions.j == true || finalOptions.fsync == true)) throw new Error("No acknowlegement using w < 1 cannot be combined with journal:true or fsync:true");
-
- // Return the options
- return finalOptions;
-}
-
-var _getReadConcern = function(self, options) {
- if(options.readPreference) return options.readPreference;
- if(self.readPreference) return self.readPreference;
- if(self.db.readPreference) return self.readPreference;
- return 'primary';
-}
-
-/**
- * @ignore
- */
-var checkCollectionName = function checkCollectionName (collectionName) {
- if('string' !== typeof collectionName) {
- throw Error("collection name must be a String");
- }
-
- if(!collectionName || collectionName.indexOf('..') != -1) {
- throw Error("collection names cannot be empty");
- }
-
- if(collectionName.indexOf('$') != -1 &&
- collectionName.match(/((^\$cmd)|(oplog\.\$main))/) == null) {
- throw Error("collection names must not contain '$'");
- }
-
- if(collectionName.match(/^\.|\.$/) != null) {
- throw Error("collection names must not start or end with '.'");
- }
-
- // Validate that we are not passing 0x00 in the colletion name
- if(!!~collectionName.indexOf("\x00")) {
- throw new Error("collection names cannot contain a null character");
- }
-};
-
-
-/**
- * Normalizes a `hint` argument.
- *
- * @param {String|Object|Array} hint
- * @return {Object}
- * @api private
- */
-var normalizeHintField = function normalizeHintField(hint) {
- var finalHint = null;
-
- if(typeof hint == 'string') {
- finalHint = hint;
- } else if(Array.isArray(hint)) {
- finalHint = {};
-
- hint.forEach(function(param) {
- finalHint[param] = 1;
- });
- } else if(hint != null && typeof hint == 'object') {
- finalHint = {};
- for (var name in hint) {
- finalHint[name] = hint[name];
- }
- }
-
- return finalHint;
-};
-
-exports._getWriteConcern = _getWriteConcern;
-exports._hasWriteConcern = _hasWriteConcern;
-exports._getReadConcern = _getReadConcern;
-exports.checkCollectionName = checkCollectionName;
-exports.normalizeHintField = normalizeHintField;
\ No newline at end of file
diff --git a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/command_cursor.js b/node_modules/mongojs/node_modules/mongodb/lib/mongodb/command_cursor.js
deleted file mode 100644
index d248b22..0000000
--- a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/command_cursor.js
+++ /dev/null
@@ -1,362 +0,0 @@
-var Long = require('bson').Long
- , Readable = require('stream').Readable || require('readable-stream').Readable
- , GetMoreCommand = require('./commands/get_more_command').GetMoreCommand
- , inherits = require('util').inherits;
-
-var CommandCursor = function(db, collection, command, options) {
- // Ensure empty options if no options passed
- options = options || {};
-
- // Set up
- Readable.call(this, {objectMode: true});
-
- // Default cursor id is 0
- var cursorId = options.cursorId || Long.fromInt(0);
- var zeroCursor = Long.fromInt(0);
- var state = 'init';
- var batchSize = options.batchSize || 0;
-
- // Hardcode batch size
- if(command && command.cursor) {
- batchSize = command.cursor.batchSize || 0;
- }
-
- // BatchSize
- var raw = options.raw || false;
- var readPreference = options.readPreference || 'primary';
-
- // Checkout a connection
- var connection = db.serverConfig.checkoutReader(readPreference);
- // MaxTimeMS
- var maxTimeMS = options.maxTimeMS;
-
- // Contains all the items
- var items = options.items || null;
-
- // Execute getmore
- var getMore = function(callback) {
- // Resolve more of the cursor using the getMore command
- var getMoreCommand = new GetMoreCommand(db
- , db.databaseName + "." + collection.collectionName
- , batchSize
- , cursorId
- );
-
- // Set up options
- var command_options = { connection:connection };
-
- // Execute the getMore Command
- db._executeQueryCommand(getMoreCommand, command_options, function(err, result) {
- if(err) {
- items = [];
- state = 'closed';
- return callback(err);
- }
-
- // Return all the documents
- callback(null, result);
- });
- }
-
- var exhaustGetMore = function(callback) {
- getMore(function(err, result) {
- if(err) {
- items = [];
- state = 'closed';
- return callback(err, null);
- }
-
- // Add the items
- items = items.concat(result.documents);
-
- // Set the cursor id
- cursorId = result.cursorId;
- if(typeof cursorId == 'number') cursorId = Long.fromNumber(cursorId);
-
- // If the cursor is done
- if(result.cursorId.equals(zeroCursor)) {
- return callback(null, items);
- }
-
- // Check the cursor id
- exhaustGetMore(callback);
- });
- }
-
- var exhaustGetMoreEach = function(callback) {
- getMore(function(err, result) {
- if(err) {
- items = [];
- state = 'closed';
- return callback(err, null);
- }
-
- // Add the items
- items = result.documents;
-
- // Emit all the items in the first batch
- while(items.length > 0) {
- callback(null, items.shift());
- }
-
- // Set the cursor id
- cursorId = result.cursorId;
- if(typeof cursorId == 'number') cursorId = Long.fromNumber(cursorId);
-
- // If the cursor is done
- if(result.cursorId.equals(zeroCursor)) {
- state = "closed";
- return callback(null, null);
- }
-
- // Check the cursor id
- exhaustGetMoreEach(callback);
- });
- }
-
- //
- // Get all the elements
- //
- this.get = function(options, callback) {
- if(typeof options == 'function') {
- callback = options;
- options = {};
- }
-
- // Set the connection to the passed in one if it's provided
- connection = options.connection ? options.connection : connection;
-
- // Command options
- var _options = {connection:connection};
- if(typeof maxTimeMS == 'number') _options.maxTimeMS = maxTimeMS;
-
- // If we have a cursor Id already not equal to 0 we are just going to
- // exhaust the cursor
- if(cursorId.notEquals(zeroCursor)) {
- // If no items set an empty array
- items = items || [];
- // Exhaust the cursor
- return exhaustGetMore(callback);
- }
-
- // Execute the internal command first
- db.command(command, _options, function(err, result) {
- if(err) {
- state = 'closed';
- return callback(err, null);
- }
-
- // Retrieve the cursor id
- cursorId = result.cursor.id;
- if(typeof cursorId == 'number') cursorId = Long.fromNumber(cursorId);
-
- // Validate cursorId
- if(cursorId.equals(zeroCursor)) {
- return callback(null, result.cursor.firstBatch);
- };
-
- // Add to the items
- items = result.cursor.firstBatch;
- // Execute the getMore
- exhaustGetMore(callback);
- });
- }
-
- //
- // Iterate over all the items
- //
- this.each = function(options, callback) {
- if(typeof options == 'function') {
- callback = options;
- options = {};
- }
-
- // If it's a closed cursor return error
- if(this.isClosed()) return callback(new Error("cursor is closed"));
- // Set the connection to the passed in one if it's provided
- connection = options.connection ? options.connection : connection;
-
- // Command options
- var _options = {connection:connection};
- if(typeof maxTimeMS == 'number') _options.maxTimeMS = maxTimeMS;
-
- // If we have a cursor Id already not equal to 0 we are just going to
- // exhaust the cursor
- if(cursorId.notEquals(zeroCursor)) {
- // If no items set an empty array
- items = items || [];
-
- // Emit all the items in the first batch
- while(items.length > 0) {
- callback(null, items.shift());
- }
-
- // Exhaust the cursor
- return exhaustGetMoreEach(callback);
- }
-
- // Execute the internal command first
- db.command(command, _options, function(err, result) {
- if(err) {
- state = 'closed';
- return callback(err, null);
- }
-
- // Get all the items
- items = result.cursor.firstBatch;
-
- // Emit all the items in the first batch
- while(items.length > 0) {
- callback(null, items.shift());
- }
-
- // Retrieve the cursor id
- cursorId = result.cursor.id;
- if(typeof cursorId == 'number') cursorId = Long.fromNumber(cursorId);
-
- // If no cursor we just finish up the current batch of items
- if(cursorId.equals(zeroCursor)) {
- state = 'closed';
- return callback(null, null);
- }
-
- // Emit each until no more getMore's
- exhaustGetMoreEach(callback);
- });
- }
-
- //
- // Get the next object
- //
- this.next = function(options, callback) {
- if(typeof options == 'function') {
- callback = options;
- options = {};
- }
-
- // If it's a closed cursor return error
- if(this.isClosed()) return callback(new Error("cursor is closed"));
-
- // Set the connection to the passed in one if it's provided
- connection = options.connection ? options.connection : connection;
-
- // Command options
- var _options = {connection:connection};
- if(typeof maxTimeMS == 'number') _options.maxTimeMS = maxTimeMS;
-
- // If we have a cursor Id already not equal to 0 we are just going to
- // going to bypass the command execution
- if(cursorId.notEquals(zeroCursor)) {
- items = items || [];
- }
-
- // Execute the internal command first
- if(!items) {
- db.command(command, _options, function(err, result) {
- if(err) {
- state = 'closed';
- return callback(err, null);
- }
-
- // Retrieve the cursor id
- cursorId = result.cursor.id;
- if(typeof cursorId == 'number') cursorId = Long.fromNumber(cursorId);
- // Get the first batch results
- items = result.cursor.firstBatch;
- // We have items return the first one
- if(items.length > 0) {
- callback(null, items.shift());
- } else {
- state = 'closed';
- callback(null, null);
- }
- });
- } else if(items.length > 0) {
- callback(null, items.shift());
- } else if(items.length == 0 && cursorId.equals(zeroCursor)) {
- state = 'closed';
- callback(null, null);
- } else {
- // Execute a getMore
- getMore(function(err, result) {
- if(err) {
- state = 'closed';
- return callback(err, null);
- }
-
- // Set the cursor id
- cursorId = result.cursorId;
- if(typeof cursorId == 'number') cursorId = Long.fromNumber(cursorId);
-
- // Add the items
- items = items.concat(result.documents);
- // If no more items
- if(items.length == 0) {
- state = 'closed';
- return callback(null, null);
- }
-
- // Return the item
- return callback(null, items.shift());
- })
- }
- }
-
- // Validate if the cursor is closed
- this.isClosed = function() {
- return state == 'closed';
- }
-
- // Allow us to set the MaxTimeMS
- this.maxTimeMS = function(_maxTimeMS) {
- maxTimeMS = _maxTimeMS;
- }
-
- // Close the cursor sending a kill cursor command if needed
- this.close = function(callback) {
- // Close the cursor if not needed
- if(cursorId instanceof Long && cursorId.greaterThan(Long.fromInt(0))) {
- try {
- var command = new KillCursorCommand(this.db, [cursorId]);
- // Added an empty callback to ensure we don't throw any null exceptions
- db._executeQueryCommand(command, {connection:connection});
- } catch(err) {}
- }
-
- // Null out the connection
- connection = null;
- // Reset cursor id
- cursorId = Long.fromInt(0);
- // Set to closed status
- state = 'closed';
- // Clear out all the items
- items = null;
-
- if(callback) {
- callback(null, null);
- }
- }
-
- //
- // Stream method
- //
- this._read = function(n) {
- var self = this;
- // Read the next command cursor doc
- self.next(function(err, result) {
- if(err) {
- self.emit('error', err);
- return self.push(null);
- }
-
- self.push(result);
- });
- }
-}
-
-// Inherit from Readable
-if(Readable != null) {
- inherits(CommandCursor, Readable);
-}
-
-exports.CommandCursor = CommandCursor;
\ No newline at end of file
diff --git a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/commands/base_command.js b/node_modules/mongojs/node_modules/mongodb/lib/mongodb/commands/base_command.js
deleted file mode 100644
index 9558582..0000000
--- a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/commands/base_command.js
+++ /dev/null
@@ -1,29 +0,0 @@
-/**
- Base object used for common functionality
-**/
-var BaseCommand = exports.BaseCommand = function BaseCommand() {
-};
-
-var id = 1;
-BaseCommand.prototype.getRequestId = function getRequestId() {
- if (!this.requestId) this.requestId = id++;
- return this.requestId;
-};
-
-BaseCommand.prototype.setMongosReadPreference = function setMongosReadPreference(readPreference, tags) {}
-
-BaseCommand.prototype.updateRequestId = function() {
- this.requestId = id++;
- return this.requestId;
-};
-
-// OpCodes
-BaseCommand.OP_REPLY = 1;
-BaseCommand.OP_MSG = 1000;
-BaseCommand.OP_UPDATE = 2001;
-BaseCommand.OP_INSERT = 2002;
-BaseCommand.OP_GET_BY_OID = 2003;
-BaseCommand.OP_QUERY = 2004;
-BaseCommand.OP_GET_MORE = 2005;
-BaseCommand.OP_DELETE = 2006;
-BaseCommand.OP_KILL_CURSORS = 2007;
\ No newline at end of file
diff --git a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/commands/db_command.js b/node_modules/mongojs/node_modules/mongodb/lib/mongodb/commands/db_command.js
deleted file mode 100644
index 39bdb6e..0000000
--- a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/commands/db_command.js
+++ /dev/null
@@ -1,101 +0,0 @@
-var QueryCommand = require('./query_command').QueryCommand,
- InsertCommand = require('./insert_command').InsertCommand,
- inherits = require('util').inherits,
- utils = require('../utils'),
- crypto = require('crypto');
-
-/**
- Db Command
-**/
-var DbCommand = exports.DbCommand = function(dbInstance, collectionName, queryOptions, numberToSkip, numberToReturn, query, returnFieldSelector, options) {
- QueryCommand.call(this);
- this.collectionName = collectionName;
- this.queryOptions = queryOptions;
- this.numberToSkip = numberToSkip;
- this.numberToReturn = numberToReturn;
- this.query = query;
- this.returnFieldSelector = returnFieldSelector;
- this.db = dbInstance;
-
- // Set the slave ok bit
- if(this.db && this.db.slaveOk) {
- this.queryOptions |= QueryCommand.OPTS_SLAVE;
- }
-
- // Make sure we don't get a null exception
- options = options == null ? {} : options;
-
- // Allow for overriding the BSON checkKeys function
- this.checkKeys = typeof options['checkKeys'] == 'boolean' ? options["checkKeys"] : true;
-
- // Let us defined on a command basis if we want functions to be serialized or not
- if(options['serializeFunctions'] != null && options['serializeFunctions']) {
- this.serializeFunctions = true;
- }
-};
-
-inherits(DbCommand, QueryCommand);
-
-// Constants
-DbCommand.SYSTEM_NAMESPACE_COLLECTION = "system.namespaces";
-DbCommand.SYSTEM_INDEX_COLLECTION = "system.indexes";
-DbCommand.SYSTEM_PROFILE_COLLECTION = "system.profile";
-DbCommand.SYSTEM_USER_COLLECTION = "system.users";
-DbCommand.SYSTEM_COMMAND_COLLECTION = "$cmd";
-DbCommand.SYSTEM_JS_COLLECTION = "system.js";
-
-// New commands
-DbCommand.NcreateIsMasterCommand = function(db, databaseName) {
- return new DbCommand(db, databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, {'ismaster':1}, null);
-};
-
-// Provide constructors for different db commands
-DbCommand.createIsMasterCommand = function(db) {
- return new DbCommand(db, db.databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, {'ismaster':1}, null);
-};
-
-DbCommand.createGetLastErrorCommand = function(options, db) {
- if (typeof db === 'undefined') {
- db = options;
- options = {};
- }
- // Final command
- var command = {'getlasterror':1};
- // If we have an options Object let's merge in the fields (fsync/wtimeout/w)
- if('object' === typeof options) {
- for(var name in options) {
- command[name] = options[name]
- }
- }
-
- // Special case for w == 1, remove the w
- if(1 == command.w) {
- delete command.w;
- }
-
- // Execute command
- return new DbCommand(db, db.databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, command, null);
-};
-
-DbCommand.createGetLastStatusCommand = DbCommand.createGetLastErrorCommand;
-
-DbCommand.createDbCommand = function(db, command_hash, options, auth_db) {
- var db_name = (auth_db ? auth_db : db.databaseName) + "." + DbCommand.SYSTEM_COMMAND_COLLECTION;
- options = options == null ? {checkKeys: false} : options;
- return new DbCommand(db, db_name, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, command_hash, null, options);
-};
-
-DbCommand.createAdminDbCommand = function(db, command_hash) {
- return new DbCommand(db, "admin." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, command_hash, null);
-};
-
-DbCommand.createAdminDbCommandSlaveOk = function(db, command_hash) {
- return new DbCommand(db, "admin." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT | QueryCommand.OPTS_SLAVE, 0, -1, command_hash, null);
-};
-
-DbCommand.createDbSlaveOkCommand = function(db, command_hash, options) {
- options = options == null ? {checkKeys: false} : options;
- var dbName = options.dbName ? options.dbName : db.databaseName;
- var flags = options.slaveOk ? QueryCommand.OPTS_NO_CURSOR_TIMEOUT | QueryCommand.OPTS_SLAVE : QueryCommand.OPTS_NO_CURSOR_TIMEOUT;
- return new DbCommand(db, dbName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, flags, 0, -1, command_hash, null, options);
-};
diff --git a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/commands/delete_command.js b/node_modules/mongojs/node_modules/mongodb/lib/mongodb/commands/delete_command.js
deleted file mode 100644
index 61a37ed..0000000
--- a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/commands/delete_command.js
+++ /dev/null
@@ -1,129 +0,0 @@
-var BaseCommand = require('./base_command').BaseCommand,
- inherits = require('util').inherits;
-
-/**
- Insert Document Command
-**/
-var DeleteCommand = exports.DeleteCommand = function(db, collectionName, selector, flags) {
- BaseCommand.call(this);
-
- // Validate correctness off the selector
- var object = selector;
- if(Buffer.isBuffer(object)) {
- var object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24;
- if(object_size != object.length) {
- var error = new Error("delete raw message size does not match message header size [" + object.length + "] != [" + object_size + "]");
- error.name = 'MongoError';
- throw error;
- }
- }
-
- this.flags = flags;
- this.collectionName = collectionName;
- this.selector = selector;
- this.db = db;
-};
-
-inherits(DeleteCommand, BaseCommand);
-
-DeleteCommand.OP_DELETE = 2006;
-
-/*
-struct {
- MsgHeader header; // standard message header
- int32 ZERO; // 0 - reserved for future use
- cstring fullCollectionName; // "dbname.collectionname"
- int32 ZERO; // 0 - reserved for future use
- mongo.BSON selector; // query object. See below for details.
-}
-*/
-DeleteCommand.prototype.toBinary = function(bsonSettings) {
- // Validate that we are not passing 0x00 in the colletion name
- if(!!~this.collectionName.indexOf("\x00")) {
- throw new Error("namespace cannot contain a null character");
- }
-
- // Calculate total length of the document
- var totalLengthOfCommand = 4 + Buffer.byteLength(this.collectionName) + 1 + 4 + this.db.bson.calculateObjectSize(this.selector, false, true) + (4 * 4);
-
- // Enforce maximum bson size
- if(!bsonSettings.disableDriverBSONSizeCheck
- && totalLengthOfCommand > bsonSettings.maxBsonSize)
- throw new Error("Document exceeds maximum allowed bson size of " + bsonSettings.maxBsonSize + " bytes");
-
- if(bsonSettings.disableDriverBSONSizeCheck
- && totalLengthOfCommand > bsonSettings.maxMessageSizeBytes)
- throw new Error("Command exceeds maximum message size of " + bsonSettings.maxMessageSizeBytes + " bytes");
-
- // Let's build the single pass buffer command
- var _index = 0;
- var _command = new Buffer(totalLengthOfCommand);
- // Write the header information to the buffer
- _command[_index + 3] = (totalLengthOfCommand >> 24) & 0xff;
- _command[_index + 2] = (totalLengthOfCommand >> 16) & 0xff;
- _command[_index + 1] = (totalLengthOfCommand >> 8) & 0xff;
- _command[_index] = totalLengthOfCommand & 0xff;
- // Adjust index
- _index = _index + 4;
- // Write the request ID
- _command[_index + 3] = (this.requestId >> 24) & 0xff;
- _command[_index + 2] = (this.requestId >> 16) & 0xff;
- _command[_index + 1] = (this.requestId >> 8) & 0xff;
- _command[_index] = this.requestId & 0xff;
- // Adjust index
- _index = _index + 4;
- // Write zero
- _command[_index++] = 0;
- _command[_index++] = 0;
- _command[_index++] = 0;
- _command[_index++] = 0;
- // Write the op_code for the command
- _command[_index + 3] = (DeleteCommand.OP_DELETE >> 24) & 0xff;
- _command[_index + 2] = (DeleteCommand.OP_DELETE >> 16) & 0xff;
- _command[_index + 1] = (DeleteCommand.OP_DELETE >> 8) & 0xff;
- _command[_index] = DeleteCommand.OP_DELETE & 0xff;
- // Adjust index
- _index = _index + 4;
-
- // Write zero
- _command[_index++] = 0;
- _command[_index++] = 0;
- _command[_index++] = 0;
- _command[_index++] = 0;
-
- // Write the collection name to the command
- _index = _index + _command.write(this.collectionName, _index, 'utf8') + 1;
- _command[_index - 1] = 0;
-
- // Write the flags
- _command[_index + 3] = (this.flags >> 24) & 0xff;
- _command[_index + 2] = (this.flags >> 16) & 0xff;
- _command[_index + 1] = (this.flags >> 8) & 0xff;
- _command[_index] = this.flags & 0xff;
- // Adjust index
- _index = _index + 4;
-
- // Document binary length
- var documentLength = 0
-
- // Serialize the selector
- // If we are passing a raw buffer, do minimal validation
- if(Buffer.isBuffer(this.selector)) {
- documentLength = this.selector.length;
- // Copy the data into the current buffer
- this.selector.copy(_command, _index);
- } else {
- documentLength = this.db.bson.serializeWithBufferAndIndex(this.selector, false, _command, _index) - _index + 1;
- }
-
- // Write the length to the document
- _command[_index + 3] = (documentLength >> 24) & 0xff;
- _command[_index + 2] = (documentLength >> 16) & 0xff;
- _command[_index + 1] = (documentLength >> 8) & 0xff;
- _command[_index] = documentLength & 0xff;
- // Update index in buffer
- _index = _index + documentLength;
- // Add terminating 0 for the object
- _command[_index - 1] = 0;
- return _command;
-};
\ No newline at end of file
diff --git a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/commands/get_more_command.js b/node_modules/mongojs/node_modules/mongodb/lib/mongodb/commands/get_more_command.js
deleted file mode 100644
index 1b6b172..0000000
--- a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/commands/get_more_command.js
+++ /dev/null
@@ -1,88 +0,0 @@
-var BaseCommand = require('./base_command').BaseCommand,
- inherits = require('util').inherits,
- binaryutils = require('../utils');
-
-/**
- Get More Document Command
-**/
-var GetMoreCommand = exports.GetMoreCommand = function(db, collectionName, numberToReturn, cursorId) {
- BaseCommand.call(this);
-
- this.collectionName = collectionName;
- this.numberToReturn = numberToReturn;
- this.cursorId = cursorId;
- this.db = db;
-};
-
-inherits(GetMoreCommand, BaseCommand);
-
-GetMoreCommand.OP_GET_MORE = 2005;
-
-GetMoreCommand.prototype.toBinary = function() {
- // Validate that we are not passing 0x00 in the colletion name
- if(!!~this.collectionName.indexOf("\x00")) {
- throw new Error("namespace cannot contain a null character");
- }
-
- // Calculate total length of the document
- var totalLengthOfCommand = 4 + Buffer.byteLength(this.collectionName) + 1 + 4 + 8 + (4 * 4);
- // Let's build the single pass buffer command
- var _index = 0;
- var _command = new Buffer(totalLengthOfCommand);
- // Write the header information to the buffer
- _command[_index++] = totalLengthOfCommand & 0xff;
- _command[_index++] = (totalLengthOfCommand >> 8) & 0xff;
- _command[_index++] = (totalLengthOfCommand >> 16) & 0xff;
- _command[_index++] = (totalLengthOfCommand >> 24) & 0xff;
-
- // Write the request ID
- _command[_index++] = this.requestId & 0xff;
- _command[_index++] = (this.requestId >> 8) & 0xff;
- _command[_index++] = (this.requestId >> 16) & 0xff;
- _command[_index++] = (this.requestId >> 24) & 0xff;
-
- // Write zero
- _command[_index++] = 0;
- _command[_index++] = 0;
- _command[_index++] = 0;
- _command[_index++] = 0;
-
- // Write the op_code for the command
- _command[_index++] = GetMoreCommand.OP_GET_MORE & 0xff;
- _command[_index++] = (GetMoreCommand.OP_GET_MORE >> 8) & 0xff;
- _command[_index++] = (GetMoreCommand.OP_GET_MORE >> 16) & 0xff;
- _command[_index++] = (GetMoreCommand.OP_GET_MORE >> 24) & 0xff;
-
- // Write zero
- _command[_index++] = 0;
- _command[_index++] = 0;
- _command[_index++] = 0;
- _command[_index++] = 0;
-
- // Write the collection name to the command
- _index = _index + _command.write(this.collectionName, _index, 'utf8') + 1;
- _command[_index - 1] = 0;
-
- // Number of documents to return
- _command[_index++] = this.numberToReturn & 0xff;
- _command[_index++] = (this.numberToReturn >> 8) & 0xff;
- _command[_index++] = (this.numberToReturn >> 16) & 0xff;
- _command[_index++] = (this.numberToReturn >> 24) & 0xff;
-
- // Encode the cursor id
- var low_bits = this.cursorId.getLowBits();
- // Encode low bits
- _command[_index++] = low_bits & 0xff;
- _command[_index++] = (low_bits >> 8) & 0xff;
- _command[_index++] = (low_bits >> 16) & 0xff;
- _command[_index++] = (low_bits >> 24) & 0xff;
-
- var high_bits = this.cursorId.getHighBits();
- // Encode high bits
- _command[_index++] = high_bits & 0xff;
- _command[_index++] = (high_bits >> 8) & 0xff;
- _command[_index++] = (high_bits >> 16) & 0xff;
- _command[_index++] = (high_bits >> 24) & 0xff;
- // Return command
- return _command;
-};
\ No newline at end of file
diff --git a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/commands/insert_command.js b/node_modules/mongojs/node_modules/mongodb/lib/mongodb/commands/insert_command.js
deleted file mode 100644
index c6e51e9..0000000
--- a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/commands/insert_command.js
+++ /dev/null
@@ -1,161 +0,0 @@
-var BaseCommand = require('./base_command').BaseCommand,
- inherits = require('util').inherits;
-
-/**
- Insert Document Command
-**/
-var InsertCommand = exports.InsertCommand = function(db, collectionName, checkKeys, options) {
- BaseCommand.call(this);
-
- this.collectionName = collectionName;
- this.documents = [];
- this.checkKeys = checkKeys == null ? true : checkKeys;
- this.db = db;
- this.flags = 0;
- this.serializeFunctions = false;
-
- // Ensure valid options hash
- options = options == null ? {} : options;
-
- // Check if we have keepGoing set -> set flag if it's the case
- if(options['keepGoing'] != null && options['keepGoing']) {
- // This will finish inserting all non-index violating documents even if it returns an error
- this.flags = 1;
- }
-
- // Check if we have keepGoing set -> set flag if it's the case
- if(options['continueOnError'] != null && options['continueOnError']) {
- // This will finish inserting all non-index violating documents even if it returns an error
- this.flags = 1;
- }
-
- // Let us defined on a command basis if we want functions to be serialized or not
- if(options['serializeFunctions'] != null && options['serializeFunctions']) {
- this.serializeFunctions = true;
- }
-};
-
-inherits(InsertCommand, BaseCommand);
-
-// OpCodes
-InsertCommand.OP_INSERT = 2002;
-
-InsertCommand.prototype.add = function(document) {
- if(Buffer.isBuffer(document)) {
- var object_size = document[0] | document[1] << 8 | document[2] << 16 | document[3] << 24;
- if(object_size != document.length) {
- var error = new Error("insert raw message size does not match message header size [" + document.length + "] != [" + object_size + "]");
- error.name = 'MongoError';
- throw error;
- }
- }
-
- this.documents.push(document);
- return this;
-};
-
-/*
-struct {
- MsgHeader header; // standard message header
- int32 ZERO; // 0 - reserved for future use
- cstring fullCollectionName; // "dbname.collectionname"
- BSON[] documents; // one or more documents to insert into the collection
-}
-*/
-InsertCommand.prototype.toBinary = function(bsonSettings) {
- // Validate that we are not passing 0x00 in the colletion name
- if(!!~this.collectionName.indexOf("\x00")) {
- throw new Error("namespace cannot contain a null character");
- }
-
- // Calculate total length of the document
- var totalLengthOfCommand = 4 + Buffer.byteLength(this.collectionName) + 1 + (4 * 4);
- // var docLength = 0
- for(var i = 0; i < this.documents.length; i++) {
- if(Buffer.isBuffer(this.documents[i])) {
- totalLengthOfCommand += this.documents[i].length;
- } else {
- // Calculate size of document
- totalLengthOfCommand += this.db.bson.calculateObjectSize(this.documents[i], this.serializeFunctions, true);
- }
- }
-
- // Enforce maximum bson size
- if(!bsonSettings.disableDriverBSONSizeCheck
- && totalLengthOfCommand > bsonSettings.maxBsonSize)
- throw new Error("Document exceeds maximum allowed bson size of " + bsonSettings.maxBsonSize + " bytes");
-
- if(bsonSettings.disableDriverBSONSizeCheck
- && totalLengthOfCommand > bsonSettings.maxMessageSizeBytes)
- throw new Error("Command exceeds maximum message size of " + bsonSettings.maxMessageSizeBytes + " bytes");
-
- // Let's build the single pass buffer command
- var _index = 0;
- var _command = new Buffer(totalLengthOfCommand);
- // Write the header information to the buffer
- _command[_index + 3] = (totalLengthOfCommand >> 24) & 0xff;
- _command[_index + 2] = (totalLengthOfCommand >> 16) & 0xff;
- _command[_index + 1] = (totalLengthOfCommand >> 8) & 0xff;
- _command[_index] = totalLengthOfCommand & 0xff;
- // Adjust index
- _index = _index + 4;
- // Write the request ID
- _command[_index + 3] = (this.requestId >> 24) & 0xff;
- _command[_index + 2] = (this.requestId >> 16) & 0xff;
- _command[_index + 1] = (this.requestId >> 8) & 0xff;
- _command[_index] = this.requestId & 0xff;
- // Adjust index
- _index = _index + 4;
- // Write zero
- _command[_index++] = 0;
- _command[_index++] = 0;
- _command[_index++] = 0;
- _command[_index++] = 0;
- // Write the op_code for the command
- _command[_index + 3] = (InsertCommand.OP_INSERT >> 24) & 0xff;
- _command[_index + 2] = (InsertCommand.OP_INSERT >> 16) & 0xff;
- _command[_index + 1] = (InsertCommand.OP_INSERT >> 8) & 0xff;
- _command[_index] = InsertCommand.OP_INSERT & 0xff;
- // Adjust index
- _index = _index + 4;
- // Write flags if any
- _command[_index + 3] = (this.flags >> 24) & 0xff;
- _command[_index + 2] = (this.flags >> 16) & 0xff;
- _command[_index + 1] = (this.flags >> 8) & 0xff;
- _command[_index] = this.flags & 0xff;
- // Adjust index
- _index = _index + 4;
- // Write the collection name to the command
- _index = _index + _command.write(this.collectionName, _index, 'utf8') + 1;
- _command[_index - 1] = 0;
-
- // Write all the bson documents to the buffer at the index offset
- for(var i = 0; i < this.documents.length; i++) {
- // Document binary length
- var documentLength = 0
- var object = this.documents[i];
-
- // Serialize the selector
- // If we are passing a raw buffer, do minimal validation
- if(Buffer.isBuffer(object)) {
- documentLength = object.length;
- // Copy the data into the current buffer
- object.copy(_command, _index);
- } else {
- // Serialize the document straight to the buffer
- documentLength = this.db.bson.serializeWithBufferAndIndex(object, this.checkKeys, _command, _index, this.serializeFunctions) - _index + 1;
- }
-
- // Write the length to the document
- _command[_index + 3] = (documentLength >> 24) & 0xff;
- _command[_index + 2] = (documentLength >> 16) & 0xff;
- _command[_index + 1] = (documentLength >> 8) & 0xff;
- _command[_index] = documentLength & 0xff;
- // Update index in buffer
- _index = _index + documentLength;
- // Add terminating 0 for the object
- _command[_index - 1] = 0;
- }
-
- return _command;
-};
diff --git a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/commands/kill_cursor_command.js b/node_modules/mongojs/node_modules/mongodb/lib/mongodb/commands/kill_cursor_command.js
deleted file mode 100644
index d8ccb0c..0000000
--- a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/commands/kill_cursor_command.js
+++ /dev/null
@@ -1,98 +0,0 @@
-var BaseCommand = require('./base_command').BaseCommand,
- inherits = require('util').inherits,
- binaryutils = require('../utils');
-
-/**
- Insert Document Command
-**/
-var KillCursorCommand = exports.KillCursorCommand = function(db, cursorIds) {
- BaseCommand.call(this);
-
- this.cursorIds = cursorIds;
- this.db = db;
-};
-
-inherits(KillCursorCommand, BaseCommand);
-
-KillCursorCommand.OP_KILL_CURSORS = 2007;
-
-/*
-struct {
- MsgHeader header; // standard message header
- int32 ZERO; // 0 - reserved for future use
- int32 numberOfCursorIDs; // number of cursorIDs in message
- int64[] cursorIDs; // array of cursorIDs to close
-}
-*/
-KillCursorCommand.prototype.toBinary = function() {
- // Calculate total length of the document
- var totalLengthOfCommand = 4 + 4 + (4 * 4) + (this.cursorIds.length * 8);
- // Let's build the single pass buffer command
- var _index = 0;
- var _command = new Buffer(totalLengthOfCommand);
- // Write the header information to the buffer
- _command[_index + 3] = (totalLengthOfCommand >> 24) & 0xff;
- _command[_index + 2] = (totalLengthOfCommand >> 16) & 0xff;
- _command[_index + 1] = (totalLengthOfCommand >> 8) & 0xff;
- _command[_index] = totalLengthOfCommand & 0xff;
- // Adjust index
- _index = _index + 4;
- // Write the request ID
- _command[_index + 3] = (this.requestId >> 24) & 0xff;
- _command[_index + 2] = (this.requestId >> 16) & 0xff;
- _command[_index + 1] = (this.requestId >> 8) & 0xff;
- _command[_index] = this.requestId & 0xff;
- // Adjust index
- _index = _index + 4;
- // Write zero
- _command[_index++] = 0;
- _command[_index++] = 0;
- _command[_index++] = 0;
- _command[_index++] = 0;
- // Write the op_code for the command
- _command[_index + 3] = (KillCursorCommand.OP_KILL_CURSORS >> 24) & 0xff;
- _command[_index + 2] = (KillCursorCommand.OP_KILL_CURSORS >> 16) & 0xff;
- _command[_index + 1] = (KillCursorCommand.OP_KILL_CURSORS >> 8) & 0xff;
- _command[_index] = KillCursorCommand.OP_KILL_CURSORS & 0xff;
- // Adjust index
- _index = _index + 4;
-
- // Write zero
- _command[_index++] = 0;
- _command[_index++] = 0;
- _command[_index++] = 0;
- _command[_index++] = 0;
-
- // Number of cursors to kill
- var numberOfCursors = this.cursorIds.length;
- _command[_index + 3] = (numberOfCursors >> 24) & 0xff;
- _command[_index + 2] = (numberOfCursors >> 16) & 0xff;
- _command[_index + 1] = (numberOfCursors >> 8) & 0xff;
- _command[_index] = numberOfCursors & 0xff;
- // Adjust index
- _index = _index + 4;
-
- // Encode all the cursors
- for(var i = 0; i < this.cursorIds.length; i++) {
- // Encode the cursor id
- var low_bits = this.cursorIds[i].getLowBits();
- // Encode low bits
- _command[_index + 3] = (low_bits >> 24) & 0xff;
- _command[_index + 2] = (low_bits >> 16) & 0xff;
- _command[_index + 1] = (low_bits >> 8) & 0xff;
- _command[_index] = low_bits & 0xff;
- // Adjust index
- _index = _index + 4;
-
- var high_bits = this.cursorIds[i].getHighBits();
- // Encode high bits
- _command[_index + 3] = (high_bits >> 24) & 0xff;
- _command[_index + 2] = (high_bits >> 16) & 0xff;
- _command[_index + 1] = (high_bits >> 8) & 0xff;
- _command[_index] = high_bits & 0xff;
- // Adjust index
- _index = _index + 4;
- }
-
- return _command;
-};
\ No newline at end of file
diff --git a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/commands/query_command.js b/node_modules/mongojs/node_modules/mongodb/lib/mongodb/commands/query_command.js
deleted file mode 100644
index 196c9f1..0000000
--- a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/commands/query_command.js
+++ /dev/null
@@ -1,296 +0,0 @@
-var BaseCommand = require('./base_command').BaseCommand,
- inherits = require('util').inherits;
-
-/**
- Insert Document Command
-**/
-var QueryCommand = exports.QueryCommand = function(db, collectionName, queryOptions, numberToSkip, numberToReturn, query, returnFieldSelector, options) {
- BaseCommand.call(this);
-
- // Validate correctness off the selector
- var object = query,
- object_size;
- if(Buffer.isBuffer(object)) {
- object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24;
- if(object_size != object.length) {
- var error = new Error("query selector raw message size does not match message header size [" + object.length + "] != [" + object_size + "]");
- error.name = 'MongoError';
- throw error;
- }
- }
-
- object = returnFieldSelector;
- if(Buffer.isBuffer(object)) {
- object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24;
- if(object_size != object.length) {
- var error = new Error("query fields raw message size does not match message header size [" + object.length + "] != [" + object_size + "]");
- error.name = 'MongoError';
- throw error;
- }
- }
-
- // Make sure we don't get a null exception
- options = options == null ? {} : options;
- // Set up options
- this.collectionName = collectionName;
- this.queryOptions = queryOptions;
- this.numberToSkip = numberToSkip;
- this.numberToReturn = numberToReturn;
-
- // Ensure we have no null query
- query = query == null ? {} : query;
- // Wrap query in the $query parameter so we can add read preferences for mongos
- this.query = query;
- this.returnFieldSelector = returnFieldSelector;
- this.db = db;
-
- // Force the slave ok flag to be set if we are not using primary read preference
- if(this.db && this.db.slaveOk) {
- this.queryOptions |= QueryCommand.OPTS_SLAVE;
- }
-
- // If checkKeys set
- this.checkKeys = typeof options.checkKeys == 'boolean' ? options.checkKeys : false;
-
- // Let us defined on a command basis if we want functions to be serialized or not
- if(options['serializeFunctions'] != null && options['serializeFunctions']) {
- this.serializeFunctions = true;
- }
-};
-
-inherits(QueryCommand, BaseCommand);
-
-QueryCommand.OP_QUERY = 2004;
-
-/*
- * Adds the read prefrence to the current command
- */
-QueryCommand.prototype.setMongosReadPreference = function(readPreference, tags) {
- // No read preference specified
- if(readPreference == false) return;
- // If we have readPreference set to true set to secondary prefered
- if(readPreference == true) {
- readPreference = 'secondaryPreferred';
- } else if(readPreference == 'false') {
- readPreference = 'primary';
- }
-
- // If we have primary read preference ignore it
- if(readPreference == 'primary'
- || readPreference.mode == 'primary') return;
-
- // Force the slave ok flag to be set if we are not using primary read preference
- if(readPreference != false && readPreference != 'primary') {
- this.queryOptions |= QueryCommand.OPTS_SLAVE;
- }
-
- // Backward compatibility, ensure $query only set on read preference so 1.8.X works
- if((readPreference != null || tags != null) && this.query['$query'] == null) {
- this.query = {'$query': this.query};
- }
-
- // If we have no readPreference set and no tags, check if the slaveOk bit is set
- if(readPreference == null && tags == null) {
- // If we have a slaveOk bit set the read preference for MongoS
- if(this.queryOptions & QueryCommand.OPTS_SLAVE) {
- this.query['$readPreference'] = {mode: 'secondary'}
- } else {
- this.query['$readPreference'] = {mode: 'primary'}
- }
- }
-
- // Build read preference object
- if(typeof readPreference == 'object' && readPreference['_type'] == 'ReadPreference') {
- this.query['$readPreference'] = readPreference.toObject();
- } else if(readPreference != null) {
- // Add the read preference
- this.query['$readPreference'] = {mode: readPreference};
-
- // If we have tags let's add them
- if(tags != null) {
- this.query['$readPreference']['tags'] = tags;
- }
- }
-}
-
-/*
-struct {
- MsgHeader header; // standard message header
- int32 opts; // query options. See below for details.
- cstring fullCollectionName; // "dbname.collectionname"
- int32 numberToSkip; // number of documents to skip when returning results
- int32 numberToReturn; // number of documents to return in the first OP_REPLY
- BSON query ; // query object. See below for details.
- [ BSON returnFieldSelector; ] // OPTIONAL : selector indicating the fields to return. See below for details.
-}
-*/
-QueryCommand.prototype.toBinary = function(bsonSettings) {
- // Validate that we are not passing 0x00 in the colletion name
- if(!!~this.collectionName.indexOf("\x00")) {
- throw new Error("namespace cannot contain a null character");
- }
-
- // Total length of the command
- var totalLengthOfCommand = 0;
- // Calculate total length of the document
- if(Buffer.isBuffer(this.query)) {
- totalLengthOfCommand = 4 + Buffer.byteLength(this.collectionName) + 1 + 4 + 4 + this.query.length + (4 * 4);
- } else {
- totalLengthOfCommand = 4 + Buffer.byteLength(this.collectionName) + 1 + 4 + 4 + this.db.bson.calculateObjectSize(this.query, this.serializeFunctions, true) + (4 * 4);
- }
-
- // Calculate extra fields size
- if(this.returnFieldSelector != null && !(Buffer.isBuffer(this.returnFieldSelector))) {
- if(Object.keys(this.returnFieldSelector).length > 0) {
- totalLengthOfCommand += this.db.bson.calculateObjectSize(this.returnFieldSelector, this.serializeFunctions, true);
- }
- } else if(Buffer.isBuffer(this.returnFieldSelector)) {
- totalLengthOfCommand += this.returnFieldSelector.length;
- }
-
- // Enforce maximum bson size
- if(!bsonSettings.disableDriverBSONSizeCheck
- && totalLengthOfCommand > bsonSettings.maxBsonSize)
- throw new Error("Document exceeds maximum allowed bson size of " + bsonSettings.maxBsonSize + " bytes");
-
- if(bsonSettings.disableDriverBSONSizeCheck
- && totalLengthOfCommand > bsonSettings.maxMessageSizeBytes)
- throw new Error("Command exceeds maximum message size of " + bsonSettings.maxMessageSizeBytes + " bytes");
-
- // Let's build the single pass buffer command
- var _index = 0;
- var _command = new Buffer(totalLengthOfCommand);
- // Write the header information to the buffer
- _command[_index + 3] = (totalLengthOfCommand >> 24) & 0xff;
- _command[_index + 2] = (totalLengthOfCommand >> 16) & 0xff;
- _command[_index + 1] = (totalLengthOfCommand >> 8) & 0xff;
- _command[_index] = totalLengthOfCommand & 0xff;
- // Adjust index
- _index = _index + 4;
- // Write the request ID
- _command[_index + 3] = (this.requestId >> 24) & 0xff;
- _command[_index + 2] = (this.requestId >> 16) & 0xff;
- _command[_index + 1] = (this.requestId >> 8) & 0xff;
- _command[_index] = this.requestId & 0xff;
- // Adjust index
- _index = _index + 4;
- // Write zero
- _command[_index++] = 0;
- _command[_index++] = 0;
- _command[_index++] = 0;
- _command[_index++] = 0;
- // Write the op_code for the command
- _command[_index + 3] = (QueryCommand.OP_QUERY >> 24) & 0xff;
- _command[_index + 2] = (QueryCommand.OP_QUERY >> 16) & 0xff;
- _command[_index + 1] = (QueryCommand.OP_QUERY >> 8) & 0xff;
- _command[_index] = QueryCommand.OP_QUERY & 0xff;
- // Adjust index
- _index = _index + 4;
-
- // Write the query options
- _command[_index + 3] = (this.queryOptions >> 24) & 0xff;
- _command[_index + 2] = (this.queryOptions >> 16) & 0xff;
- _command[_index + 1] = (this.queryOptions >> 8) & 0xff;
- _command[_index] = this.queryOptions & 0xff;
- // Adjust index
- _index = _index + 4;
-
- // Write the collection name to the command
- _index = _index + _command.write(this.collectionName, _index, 'utf8') + 1;
- _command[_index - 1] = 0;
-
- // Write the number of documents to skip
- _command[_index + 3] = (this.numberToSkip >> 24) & 0xff;
- _command[_index + 2] = (this.numberToSkip >> 16) & 0xff;
- _command[_index + 1] = (this.numberToSkip >> 8) & 0xff;
- _command[_index] = this.numberToSkip & 0xff;
- // Adjust index
- _index = _index + 4;
-
- // Write the number of documents to return
- _command[_index + 3] = (this.numberToReturn >> 24) & 0xff;
- _command[_index + 2] = (this.numberToReturn >> 16) & 0xff;
- _command[_index + 1] = (this.numberToReturn >> 8) & 0xff;
- _command[_index] = this.numberToReturn & 0xff;
- // Adjust index
- _index = _index + 4;
-
- // Document binary length
- var documentLength = 0
- var object = this.query;
-
- // Serialize the selector
- if(Buffer.isBuffer(object)) {
- documentLength = object.length;
- // Copy the data into the current buffer
- object.copy(_command, _index);
- } else {
- // If $query we need to check for a valid document
- if(this.query['$query']) {
- this.db.bson.serializeWithBufferAndIndex(object['$query'], this.checkKeys, _command, _index, this.serializeFunctions) - _index + 1;
- // Cannot check keys due to $query
- this.checkKeys = false;
- }
-
- // 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_REPLAY = 8;
-QueryCommand.OPTS_NO_CURSOR_TIMEOUT = 16;
-QueryCommand.OPTS_AWAIT_DATA = 32;
-QueryCommand.OPTS_EXHAUST = 64;
-QueryCommand.OPTS_PARTIAL = 128;
\ No newline at end of file
diff --git a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/commands/update_command.js b/node_modules/mongojs/node_modules/mongodb/lib/mongodb/commands/update_command.js
deleted file mode 100644
index daa3cba..0000000
--- a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/commands/update_command.js
+++ /dev/null
@@ -1,189 +0,0 @@
-var BaseCommand = require('./base_command').BaseCommand,
- inherits = require('util').inherits;
-
-/**
- Update Document Command
-**/
-var UpdateCommand = exports.UpdateCommand = function(db, collectionName, spec, document, options) {
- BaseCommand.call(this);
-
- var object = spec;
- if(Buffer.isBuffer(object)) {
- var object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24;
- if(object_size != object.length) {
- var error = new Error("update spec raw message size does not match message header size [" + object.length + "] != [" + object_size + "]");
- error.name = 'MongoError';
- throw error;
- }
- }
-
- var object = document;
- if(Buffer.isBuffer(object)) {
- var object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24;
- if(object_size != object.length) {
- var error = new Error("update document raw message size does not match message header size [" + object.length + "] != [" + object_size + "]");
- error.name = 'MongoError';
- throw error;
- }
- }
-
- this.collectionName = collectionName;
- this.spec = spec;
- this.document = document;
- this.db = db;
- this.serializeFunctions = false;
- this.checkKeys = typeof options.checkKeys != 'boolean' ? false : options.checkKeys;
-
- // Generate correct flags
- var db_upsert = 0;
- var db_multi_update = 0;
- db_upsert = options != null && options['upsert'] != null ? (options['upsert'] == true ? 1 : 0) : db_upsert;
- db_multi_update = options != null && options['multi'] != null ? (options['multi'] == true ? 1 : 0) : db_multi_update;
-
- // Flags
- this.flags = parseInt(db_multi_update.toString() + db_upsert.toString(), 2);
- // Let us defined on a command basis if we want functions to be serialized or not
- if(options['serializeFunctions'] != null && options['serializeFunctions']) {
- this.serializeFunctions = true;
- }
-};
-
-inherits(UpdateCommand, BaseCommand);
-
-UpdateCommand.OP_UPDATE = 2001;
-
-/*
-struct {
- MsgHeader header; // standard message header
- int32 ZERO; // 0 - reserved for future use
- cstring fullCollectionName; // "dbname.collectionname"
- int32 flags; // bit vector. see below
- BSON spec; // the query to select the document
- BSON document; // the document data to update with or insert
-}
-*/
-UpdateCommand.prototype.toBinary = function(bsonSettings) {
- // Validate that we are not passing 0x00 in the colletion name
- if(!!~this.collectionName.indexOf("\x00")) {
- throw new Error("namespace cannot contain a null character");
- }
-
- // Calculate total length of the document
- var totalLengthOfCommand = 4 + Buffer.byteLength(this.collectionName) + 1 + 4 + this.db.bson.calculateObjectSize(this.spec, false, true) +
- this.db.bson.calculateObjectSize(this.document, this.serializeFunctions, true) + (4 * 4);
-
- // Enforce maximum bson size
- if(!bsonSettings.disableDriverBSONSizeCheck
- && totalLengthOfCommand > bsonSettings.maxBsonSize)
- throw new Error("Document exceeds maximum allowed bson size of " + bsonSettings.maxBsonSize + " bytes");
-
- if(bsonSettings.disableDriverBSONSizeCheck
- && totalLengthOfCommand > bsonSettings.maxMessageSizeBytes)
- throw new Error("Command exceeds maximum message size of " + bsonSettings.maxMessageSizeBytes + " bytes");
-
- // Let's build the single pass buffer command
- var _index = 0;
- var _command = new Buffer(totalLengthOfCommand);
- // Write the header information to the buffer
- _command[_index + 3] = (totalLengthOfCommand >> 24) & 0xff;
- _command[_index + 2] = (totalLengthOfCommand >> 16) & 0xff;
- _command[_index + 1] = (totalLengthOfCommand >> 8) & 0xff;
- _command[_index] = totalLengthOfCommand & 0xff;
- // Adjust index
- _index = _index + 4;
- // Write the request ID
- _command[_index + 3] = (this.requestId >> 24) & 0xff;
- _command[_index + 2] = (this.requestId >> 16) & 0xff;
- _command[_index + 1] = (this.requestId >> 8) & 0xff;
- _command[_index] = this.requestId & 0xff;
- // Adjust index
- _index = _index + 4;
- // Write zero
- _command[_index++] = 0;
- _command[_index++] = 0;
- _command[_index++] = 0;
- _command[_index++] = 0;
- // Write the op_code for the command
- _command[_index + 3] = (UpdateCommand.OP_UPDATE >> 24) & 0xff;
- _command[_index + 2] = (UpdateCommand.OP_UPDATE >> 16) & 0xff;
- _command[_index + 1] = (UpdateCommand.OP_UPDATE >> 8) & 0xff;
- _command[_index] = UpdateCommand.OP_UPDATE & 0xff;
- // Adjust index
- _index = _index + 4;
-
- // Write zero
- _command[_index++] = 0;
- _command[_index++] = 0;
- _command[_index++] = 0;
- _command[_index++] = 0;
-
- // Write the collection name to the command
- _index = _index + _command.write(this.collectionName, _index, 'utf8') + 1;
- _command[_index - 1] = 0;
-
- // Write the update flags
- _command[_index + 3] = (this.flags >> 24) & 0xff;
- _command[_index + 2] = (this.flags >> 16) & 0xff;
- _command[_index + 1] = (this.flags >> 8) & 0xff;
- _command[_index] = this.flags & 0xff;
- // Adjust index
- _index = _index + 4;
-
- // Document binary length
- var documentLength = 0
- var object = this.spec;
-
- // Serialize the selector
- // If we are passing a raw buffer, do minimal validation
- if(Buffer.isBuffer(object)) {
- var object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24;
- if(object_size != object.length) throw new Error("raw message size does not match message header size [" + object.length + "] != [" + object_size + "]");
- documentLength = object.length;
- // Copy the data into the current buffer
- object.copy(_command, _index);
- } else {
- documentLength = this.db.bson.serializeWithBufferAndIndex(object, this.checkKeys, _command, _index, false) - _index + 1;
- }
-
- // Write the length to the document
- _command[_index + 3] = (documentLength >> 24) & 0xff;
- _command[_index + 2] = (documentLength >> 16) & 0xff;
- _command[_index + 1] = (documentLength >> 8) & 0xff;
- _command[_index] = documentLength & 0xff;
- // Update index in buffer
- _index = _index + documentLength;
- // Add terminating 0 for the object
- _command[_index - 1] = 0;
-
- // Document binary length
- var documentLength = 0
- var object = this.document;
-
- // Serialize the document
- // If we are passing a raw buffer, do minimal validation
- if(Buffer.isBuffer(object)) {
- var object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24;
- if(object_size != object.length) throw new Error("raw message size does not match message header size [" + object.length + "] != [" + object_size + "]");
- documentLength = object.length;
- // Copy the data into the current buffer
- object.copy(_command, _index);
- } else {
- documentLength = this.db.bson.serializeWithBufferAndIndex(object, false, _command, _index, this.serializeFunctions) - _index + 1;
- }
-
- // Write the length to the document
- _command[_index + 3] = (documentLength >> 24) & 0xff;
- _command[_index + 2] = (documentLength >> 16) & 0xff;
- _command[_index + 1] = (documentLength >> 8) & 0xff;
- _command[_index] = documentLength & 0xff;
- // Update index in buffer
- _index = _index + documentLength;
- // Add terminating 0 for the object
- _command[_index - 1] = 0;
-
- return _command;
-};
-
-// Constants
-UpdateCommand.DB_UPSERT = 0;
-UpdateCommand.DB_MULTI_UPDATE = 1;
\ No newline at end of file
diff --git a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/base.js b/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/base.js
deleted file mode 100644
index b4bc8e4..0000000
--- a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/base.js
+++ /dev/null
@@ -1,510 +0,0 @@
-var EventEmitter = require('events').EventEmitter
- , inherits = require('util').inherits
- , utils = require('../utils')
- , mongodb_cr_authenticate = require('../auth/mongodb_cr.js').authenticate
- , mongodb_gssapi_authenticate = require('../auth/mongodb_gssapi.js').authenticate
- , mongodb_sspi_authenticate = require('../auth/mongodb_sspi.js').authenticate
- , mongodb_plain_authenticate = require('../auth/mongodb_plain.js').authenticate
- , mongodb_x509_authenticate = require('../auth/mongodb_x509.js').authenticate
- , mongodb_scram_authenticate = require('../auth/mongodb_scram.js').authenticate;
-
-var id = 0;
-
-/**
- * Internal class for callback storage
- * @ignore
- */
-var CallbackStore = function() {
- // Make class an event emitter
- EventEmitter.call(this);
- // Add a info about call variable
- this._notReplied = {};
- this.id = id++;
-}
-
-/**
- * @ignore
- */
-inherits(CallbackStore, EventEmitter);
-
-CallbackStore.prototype.notRepliedToIds = function() {
- return Object.keys(this._notReplied);
-}
-
-CallbackStore.prototype.callbackInfo = function(id) {
- return this._notReplied[id];
-}
-
-/**
- * Internal class for holding non-executed commands
- * @ignore
- */
-var NonExecutedOperationStore = function(config) {
- var commands = {
- read: []
- , write_reads: []
- , write: []
- };
-
- // Execute all callbacks
- var fireCallbacksWithError = function(error, commands) {
- while(commands.length > 0) {
- var command = commands.shift();
- if(typeof command.callback == 'function') {
- command.callback(error);
- }
- }
- }
-
- this.count = function() {
- return commands.read.length
- + commands.write_reads.length
- + commands.write.length;
- }
-
- this.write = function(op) {
- commands.write.push(op);
- }
-
- this.read_from_writer = function(op) {
- commands.write_reads.push(op);
- }
-
- this.read = function(op) {
- commands.read.push(op);
- }
-
- this.validateBufferLimit = function(numberToFailOn) {
- if(numberToFailOn == -1 || numberToFailOn == null)
- return true;
-
- // Error passed back
- var error = utils.toError("No connection operations buffering limit of " + numberToFailOn + " reached");
-
- // If we have passed the number of items to buffer we need to fail
- if(numberToFailOn < this.count()) {
- // Fail all of the callbacks
- fireCallbacksWithError(error, commands.read);
- fireCallbacksWithError(error, commands.write_reads);
- fireCallbacksWithError(error, commands.write);
-
- // Report back that the buffer has been filled
- return false;
- }
-
- // There is still some room to go
- return true;
- }
-
- this.execute_queries = function(executeInsertCommand) {
- var connection = config.checkoutReader();
- if(connection == null || connection instanceof Error) return;
-
- // Write out all the queries
- while(commands.read.length > 0) {
- // Get the next command
- var command = commands.read.shift();
- command.options.connection = connection;
- // Execute the next command
- command.executeQueryCommand(command.db, command.db_command, command.options, command.callback);
- }
- }
-
- this.execute_writes = function() {
- var connection = config.checkoutWriter();
- if(connection == null || connection instanceof Error) return;
-
- // Write out all the queries to the primary
- while(commands.write_reads.length > 0) {
- // Get the next command
- var command = commands.write_reads.shift();
- command.options.connection = connection;
- // Execute the next command
- command.executeQueryCommand(command.db, command.db_command, command.options, command.callback);
- }
-
- // Execute all write operations
- while(commands.write.length > 0) {
- // Get the next command
- var command = commands.write.shift();
- // Set the connection
- command.options.connection = connection;
- // Execute the next command
- command.executeInsertCommand(command.db, command.db_command, command.options, command.callback);
- }
- }
-}
-
-/**
- * Internal class for authentication storage
- * @ignore
- */
-var AuthStore = function() {
- var _auths = [];
-
- this.add = function(authMechanism, dbName, username, password, authdbName, gssapiServiceName) {
- // Check for duplicates
- if(!this.contains(dbName)) {
- // Base config
- var config = {
- 'username':username
- , 'password':password
- , 'db': dbName
- , 'authMechanism': authMechanism
- , 'gssapiServiceName': gssapiServiceName
- };
-
- // Add auth source if passed in
- if(typeof authdbName == 'string') {
- config['authdb'] = authdbName;
- }
-
- // Push the config
- _auths.push(config);
- }
- }
-
- this.contains = function(dbName) {
- for(var i = 0; i < _auths.length; i++) {
- if(_auths[i].db == dbName) return true;
- }
-
- return false;
- }
-
- this.remove = function(dbName) {
- var newAuths = [];
-
- // Filter out all the login details
- for(var i = 0; i < _auths.length; i++) {
- if(_auths[i].db != dbName) newAuths.push(_auths[i]);
- }
-
- // Set the filtered list
- _auths = newAuths;
- }
-
- this.get = function(index) {
- return _auths[index];
- }
-
- this.length = function() {
- return _auths.length;
- }
-
- this.toArray = function() {
- return _auths.slice(0);
- }
-}
-
-/**
- * Internal class for storing db references
- * @ignore
- */
-var DbStore = function() {
- var _dbs = [];
-
- this.add = function(db) {
- var found = false;
-
- // Only add if it does not exist already
- for(var i = 0; i < _dbs.length; i++) {
- if(db.databaseName == _dbs[i].databaseName) found = true;
- }
-
- // Only add if it does not already exist
- if(!found) {
- _dbs.push(db);
- }
- }
-
- this.reset = function() {
- _dbs = [];
- }
-
- this.db = function() {
- return _dbs;
- }
-
- this.fetch = function(databaseName) {
- // Only add if it does not exist already
- for(var i = 0; i < _dbs.length; i++) {
- if(databaseName == _dbs[i].databaseName)
- return _dbs[i];
- }
-
- return null;
- }
-
- this.emit = function(event, message, object, reset, filterDb, rethrow_if_no_listeners) {
- var emitted = false;
-
- // Not emitted and we have enabled rethrow, let process.uncaughtException
- // deal with the issue
- if(!emitted && rethrow_if_no_listeners) {
- return process.nextTick(function() {
- throw message;
- })
- }
-
- // Emit the events
- for(var i = 0; i < _dbs.length; i++) {
- if(_dbs[i].listeners(event).length > 0) {
- if(filterDb == null || filterDb.databaseName !== _dbs[i].databaseName
- || filterDb.tag !== _dbs[i].tag) {
- _dbs[i].emit(event, message, object == null ? _dbs[i] : object);
- emitted = true;
- }
- }
- }
-
- // Emit error message
- if(message
- && event == 'error'
- && !emitted
- && rethrow_if_no_listeners
- && object && object.db) {
- process.nextTick(function() {
- object.db.emit(event, message, null);
- })
- }
- }
-}
-
-var Base = function Base() {
- EventEmitter.call(this);
-
- // Callback store is part of connection specification
- if(Base._callBackStore == null) {
- Base._callBackStore = new CallbackStore();
- }
-
- // Create a new callback store
- this._callBackStore = new CallbackStore();
- // All commands not being executed
- this._commandsStore = new NonExecutedOperationStore(this);
- // Create a new auth store
- this.auth = new AuthStore();
- // Contains all the dbs attached to this server config
- this._dbStore = new DbStore();
-}
-
-/**
- * @ignore
- */
-inherits(Base, EventEmitter);
-
-/**
- * @ignore
- */
-Base.prototype._apply_auths = function(db, callback) {
- _apply_auths_serially(this, db, this.auth.toArray(), callback);
-}
-
-var _apply_auths_serially = function(self, db, auths, callback) {
- if(auths.length == 0) return callback(null, null);
- // Get the first auth
- var auth = auths.shift();
- var connections = self.allRawConnections();
- var connectionsLeft = connections.length;
- var options = {};
-
- if(auth.authMechanism == 'GSSAPI') {
- // We have the kerberos library, execute auth process
- if(process.platform == 'win32') {
- mongodb_sspi_authenticate(db, auth.username, auth.password, auth.authdb, options, callback);
- } else {
- mongodb_gssapi_authenticate(db, auth.username, auth.password, auth.authdb, options, callback);
- }
- } else if(auth.authMechanism == 'MONGODB-CR') {
- mongodb_cr_authenticate(db, auth.username, auth.password, auth.authdb, options, callback);
- } else if(auth.authMechanism == 'SCRAM-SHA-1') {
- mongodb_scram_authenticate(db, auth.username, auth.password, auth.authdb, options, callback);
- } else if(auth.authMechanism == 'PLAIN') {
- mongodb_plain_authenticate(db, auth.username, auth.password, auth.authdb, options, callback);
- } else if(auth.authMechanism == 'MONGODB-X509') {
- mongodb_x509_authenticate(db, auth.username, auth.password, options, callback);
- }
-}
-
-/**
- * Fire all the errors
- * @ignore
- */
-Base.prototype.__executeAllCallbacksWithError = function(err) {
- // Check all callbacks
- var keys = Object.keys(this._callBackStore._notReplied);
- // For each key check if it's a callback that needs to be returned
- for(var j = 0; j < keys.length; j++) {
- var info = this._callBackStore._notReplied[keys[j]];
- // Execute callback with error
- this._callBackStore.emit(keys[j], err, null);
- // Remove the key
- delete this._callBackStore._notReplied[keys[j]];
- // Force cleanup _events, node.js seems to set it as a null value
- if(this._callBackStore._events) {
- delete this._callBackStore._events[keys[j]];
- }
- }
-}
-
-/**
- * Fire all the errors
- * @ignore
- */
-Base.prototype.__executeAllServerSpecificErrorCallbacks = function(host, port, err) {
- // Check all callbacks
- var keys = Object.keys(this._callBackStore._notReplied);
- // For each key check if it's a callback that needs to be returned
- for(var j = 0; j < keys.length; j++) {
- var info = this._callBackStore._notReplied[keys[j]];
-
- if(info && info.connection) {
- // Unpack the connection settings
- var _host = info.connection.socketOptions.host;
- var _port = info.connection.socketOptions.port;
- // If the server matches execute the callback with the error
- if(_port == port && _host == host) {
- this._callBackStore.emit(keys[j], err, null);
- // Remove the key
- delete this._callBackStore._notReplied[keys[j]];
- // Force cleanup _events, node.js seems to set it as a null value
- if(this._callBackStore._events) {
- delete this._callBackStore._events[keys[j]];
- }
- }
- }
- }
-}
-
-/**
- * Register a handler
- * @ignore
- * @api private
- */
-Base.prototype._registerHandler = function(db_command, raw, connection, exhaust, callback) {
- // Check if we have exhausted
- if(typeof exhaust == 'function') {
- callback = exhaust;
- exhaust = false;
- }
-
- // Add the callback to the list of handlers
- this._callBackStore.once(db_command.getRequestId(), callback);
- // Add the information about the reply
- this._callBackStore._notReplied[db_command.getRequestId().toString()] = {start: new Date().getTime(), 'raw': raw, connection:connection, exhaust:exhaust};
-}
-
-/**
- * Re-Register a handler, on the cursor id f.ex
- * @ignore
- * @api private
- */
-Base.prototype._reRegisterHandler = function(newId, object, callback) {
- // Add the callback to the list of handlers
- this._callBackStore.once(newId, object.callback.listener);
- // Add the information about the reply
- this._callBackStore._notReplied[newId] = object.info;
-}
-
-/**
- *
- * @ignore
- * @api private
- */
-Base.prototype._flushAllCallHandlers = function(err) {
- var keys = Object.keys(this._callBackStore._notReplied);
-
- for(var i = 0; i < keys.length; i++) {
- this._callHandler(keys[i], null, err);
- }
-}
-
-/**
- *
- * @ignore
- * @api private
- */
-Base.prototype._callHandler = function(id, document, err) {
- var self = this;
-
- // If there is a callback peform it
- if(this._callBackStore.listeners(id).length >= 1) {
- // Get info object
- var info = this._callBackStore._notReplied[id];
- // Delete the current object
- delete this._callBackStore._notReplied[id];
- // Call the handle directly don't emit
- var callback = this._callBackStore.listeners(id)[0].listener;
- // Remove the listeners
- this._callBackStore.removeAllListeners(id);
- // Force key deletion because it nulling it not deleting in 0.10.X
- if(this._callBackStore._events) {
- delete this._callBackStore._events[id];
- }
-
- try {
- // Execute the callback if one was provided
- if(typeof callback == 'function') callback(err, document, info.connection);
- } catch(err) {
- self._emitAcrossAllDbInstances(self, null, "error", utils.toError(err), self, true, true);
- }
- }
-}
-
-/**
- *
- * @ignore
- * @api private
- */
-Base.prototype._hasHandler = function(id) {
- return this._callBackStore.listeners(id).length >= 1;
-}
-
-/**
- *
- * @ignore
- * @api private
- */
-Base.prototype._removeHandler = function(id) {
- // Remove the information
- if(this._callBackStore._notReplied[id] != null) delete this._callBackStore._notReplied[id];
- // Remove the callback if it's registered
- this._callBackStore.removeAllListeners(id);
- // Force cleanup _events, node.js seems to set it as a null value
- if(this._callBackStore._events) {
- delete this._callBackStore._events[id];
- }
-}
-
-/**
- *
- * @ignore
- * @api private
- */
-Base.prototype._findHandler = function(id) {
- var info = this._callBackStore._notReplied[id];
- // Return the callback
- return {info:info, callback:(this._callBackStore.listeners(id).length >= 1) ? this._callBackStore.listeners(id)[0] : null}
-}
-
-/**
- *
- * @ignore
- * @api private
- */
-Base.prototype._emitAcrossAllDbInstances = function(server, filterDb, event, message, object, resetConnection, rethrow_if_no_listeners) {
- if(resetConnection) {
- var dbs = this._dbStore.db();
-
- for(var i = 0; i < dbs.length; i++) {
- if(typeof dbs[i].openCalled != 'undefined')
- dbs[i].openCalled = false;
- }
- }
-
- // Fire event
- this._dbStore.emit(event, message, object, resetConnection, filterDb, rethrow_if_no_listeners);
-}
-
-exports.Base = Base;
\ No newline at end of file
diff --git a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/connection.js b/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/connection.js
deleted file mode 100644
index 2e11d83..0000000
--- a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/connection.js
+++ /dev/null
@@ -1,562 +0,0 @@
-var utils = require('./connection_utils'),
- inherits = require('util').inherits,
- net = require('net'),
- EventEmitter = require('events').EventEmitter,
- inherits = require('util').inherits,
- binaryutils = require('../utils'),
- tls = require('tls');
-
-var Connection = exports.Connection = function(id, socketOptions) {
- var self = this;
- // Set up event emitter
- EventEmitter.call(this);
- // Store all socket options
- this.socketOptions = socketOptions ? socketOptions : {host:'localhost', port:27017, domainSocket:false};
- // Set keep alive default if not overriden
- if(this.socketOptions.keepAlive == null && (process.platform !== "sunos" || process.platform !== "win32")) this.socketOptions.keepAlive = 100;
- // Id for the connection
- this.id = id;
- // State of the connection
- this.connected = false;
- // Set if this is a domain socket
- this.domainSocket = this.socketOptions.domainSocket;
-
- // Supported min and max wire protocol
- this.minWireVersion = 0;
- this.maxWireVersion = 2;
-
- //
- // Connection parsing state
- //
- this.maxBsonSize = socketOptions.maxBsonSize ? socketOptions.maxBsonSize : Connection.DEFAULT_MAX_BSON_SIZE;
- this.maxMessageSizeBytes = socketOptions.maxMessageSizeBytes ? socketOptions.maxMessageSizeBytes : Connection.DEFAULT_MAX_MESSAGE_SIZE;
- this.maxNumberOfDocsInBatch = socketOptions.maxWriteBatchSize ? socketOptions.maxWriteBatchSize : Connection.DEFAULT_MAX_WRITE_BATCH_SIZE;
- // Contains the current message bytes
- this.buffer = null;
- // Contains the current message size
- this.sizeOfMessage = 0;
- // Contains the readIndex for the messaage
- this.bytesRead = 0;
- // Contains spill over bytes from additional messages
- this.stubBuffer = 0;
-
- // Just keeps list of events we allow
- this.eventHandlers = {error:[], parseError:[], poolReady:[], message:[], close:[], timeout:[], end:[]};
-
- // Just keeps list of events we allow
- resetHandlers(this, false);
-
- // Bson object
- this.maxBsonSettings = {
- disableDriverBSONSizeCheck: this.socketOptions['disableDriverBSONSizeCheck'] || false
- , maxBsonSize: this.maxBsonSize
- , maxMessageSizeBytes: this.maxMessageSizeBytes
- }
-
- // Allow setting the socketTimeoutMS on all connections
- // to work around issues such as secondaries blocking due to compaction
- Object.defineProperty(this, "socketTimeoutMS", {
- enumerable: true
- , get: function () { return self.socketOptions.socketTimeoutMS; }
- , set: function (value) {
- // Set the socket timeoutMS value
- self.socketOptions.socketTimeoutMS = value;
- // Set the physical connection timeout
- self.connection.setTimeout(self.socketOptions.socketTimeoutMS);
- }
- });
-}
-
-// Set max bson size
-Connection.DEFAULT_MAX_BSON_SIZE = 1024 * 1024 * 4;
-// Set default to max bson to avoid overflow or bad guesses
-Connection.DEFAULT_MAX_MESSAGE_SIZE = Connection.DEFAULT_MAX_BSON_SIZE;
-// Max default write bulk ops
-Connection.DEFAULT_MAX_WRITE_BATCH_SIZE = 2000;
-
-// Inherit event emitter so we can emit stuff wohoo
-inherits(Connection, EventEmitter);
-
-Connection.prototype.start = function() {
- var self = this;
-
- // If we have a normal connection
- if(this.socketOptions.ssl) {
- // Create new connection instance
- if(this.domainSocket) {
- this.connection = net.createConnection(this.socketOptions.host);
- } else {
- this.connection = net.createConnection(this.socketOptions.port, this.socketOptions.host);
- }
- if(this.logger != null && this.logger.doDebug){
- this.logger.debug("opened connection", this.socketOptions);
- }
-
- // Set options on the socket
- this.connection.setTimeout(this.socketOptions.connectTimeoutMS != null ? this.socketOptions.connectTimeoutMS : this.socketOptions.timeout);
- // Work around for 0.4.X
- if(process.version.indexOf("v0.4") == -1) this.connection.setNoDelay(this.socketOptions.noDelay);
- // Set keep alive if defined
- if(process.version.indexOf("v0.4") == -1) {
- if(this.socketOptions.keepAlive > 0) {
- this.connection.setKeepAlive(true, this.socketOptions.keepAlive);
- } else {
- this.connection.setKeepAlive(false);
- }
- }
-
- // Check if the driver should validate the certificate
- var validate_certificates = this.socketOptions.sslValidate == true ? true : false;
-
- // Create options for the tls connection
- var tls_options = {
- socket: this.connection
- , rejectUnauthorized: false
- }
-
- // If we wish to validate the certificate we have provided a ca store
- if(validate_certificates) {
- tls_options.ca = this.socketOptions.sslCA;
- }
-
- // If we have a certificate to present
- if(this.socketOptions.sslCert) {
- tls_options.cert = this.socketOptions.sslCert;
- tls_options.key = this.socketOptions.sslKey;
- }
-
- // If the driver has been provided a private key password
- if(this.socketOptions.sslPass) {
- tls_options.passphrase = this.socketOptions.sslPass;
- }
-
- // Contains the cleartext stream
- var cleartext = null;
- // Attempt to establish a TLS connection to the server
- try {
- cleartext = tls.connect(this.socketOptions.port, this.socketOptions.host, tls_options, function() {
- // If we have a ssl certificate validation error return an error
- if(cleartext.authorizationError && validate_certificates) {
- // Emit an error
- return self.emit("error", cleartext.authorizationError, self, {ssl:true});
- }
-
- // Connect to the server
- connectHandler(self)();
- })
- } catch(err) {
- return self.emit("error", "SSL connection failed", self, {ssl:true});
- }
-
- // Save the output stream
- this.writeSteam = cleartext;
-
- // Set up data handler for the clear stream
- cleartext.on("data", createDataHandler(this));
- // Do any handling of end event of the stream
- cleartext.on("end", endHandler(this));
- cleartext.on("error", errorHandler(this));
-
- // Handle any errors
- this.connection.on("error", errorHandler(this));
- // Handle timeout
- this.connection.on("timeout", timeoutHandler(this));
- // Handle drain event
- this.connection.on("drain", drainHandler(this));
- // Handle the close event
- this.connection.on("close", closeHandler(this));
- } else {
- // Create new connection instance
- if(this.domainSocket) {
- this.connection = net.createConnection(this.socketOptions.host);
- } else {
- this.connection = net.createConnection(this.socketOptions.port, this.socketOptions.host);
- }
- if(this.logger != null && this.logger.doDebug){
- this.logger.debug("opened connection", this.socketOptions);
- }
-
- // Set options on the socket
- this.connection.setTimeout(this.socketOptions.connectTimeoutMS != null ? this.socketOptions.connectTimeoutMS : this.socketOptions.timeout);
- // Work around for 0.4.X
- if(process.version.indexOf("v0.4") == -1) this.connection.setNoDelay(this.socketOptions.noDelay);
- // Set keep alive if defined
- if(process.version.indexOf("v0.4") == -1) {
- if(this.socketOptions.keepAlive > 0) {
- this.connection.setKeepAlive(true, this.socketOptions.keepAlive);
- } else {
- this.connection.setKeepAlive(false);
- }
- }
-
- // Set up write stream
- this.writeSteam = this.connection;
- // Add handlers
- this.connection.on("error", errorHandler(this));
- // Add all handlers to the socket to manage it
- this.connection.on("connect", connectHandler(this));
- // this.connection.on("end", endHandler(this));
- this.connection.on("data", createDataHandler(this));
- this.connection.on("timeout", timeoutHandler(this));
- this.connection.on("drain", drainHandler(this));
- this.connection.on("close", closeHandler(this));
- }
-}
-
-/**
- * @ignore
- */
-Connection.prototype.setSocketOptions = function(options) {
- options = options || {};
-
- if(typeof options.connectTimeoutMS == 'number') {
- this.socketOptions.connectTimeoutMS = options.connectTimeoutMS;
- }
-
- if(typeof options.socketTimeoutMS == 'number') {
- this.socketOptions.socketTimeoutMS = options.socketTimeoutMS;
- // Set the current socket timeout
- this.connection.setTimeout(options.socketTimeoutMS);
- }
-}
-
-// Check if the sockets are live
-Connection.prototype.isConnected = function() {
- return this.connected && !this.connection.destroyed && this.connection.writable;
-}
-
-// Validate if the driver supports this server
-Connection.prototype.isCompatible = function() {
- if(this.serverCapabilities == null) return true;
- // Is compatible with backward server
- if(this.serverCapabilities.minWireVersion == 0
- && this.serverCapabilities.maxWireVersion ==0) return true;
-
- // Check if we overlap
- if(this.serverCapabilities.minWireVersion >= this.minWireVersion
- && this.serverCapabilities.maxWireVersion <= this.maxWireVersion) return true;
-
- // Not compatible
- return false;
-}
-
-// Write the data out to the socket
-Connection.prototype.write = function(command, callback) {
- try {
- // If we have a list off commands to be executed on the same socket
- if(Array.isArray(command)) {
- for(var i = 0; i < command.length; i++) {
- try {
- // Pass in the bson validation settings (validate early)
- var binaryCommand = command[i].toBinary(this.maxBsonSettings);
-
- if(this.logger != null && this.logger.doDebug)
- this.logger.debug("writing command to mongodb", {binary: binaryCommand, json: command[i]});
-
- this.writeSteam.write(binaryCommand);
- } catch(err) {
- return callback(err, null);
- }
- }
- } else {
- try {
- // Pass in the bson validation settings (validate early)
- var binaryCommand = command.toBinary(this.maxBsonSettings);
- // Do we have a logger active log the event
- if(this.logger != null && this.logger.doDebug)
- this.logger.debug("writing command to mongodb", {binary: binaryCommand, json: command});
- // Write the binary command out to socket
- this.writeSteam.write(binaryCommand);
- } catch(err) {
- return callback(err, null);
- }
- }
- } catch (err) {
- if(typeof callback === 'function') callback(err);
- }
-}
-
-// Force the closure of the connection
-Connection.prototype.close = function() {
- // clear out all the listeners
- resetHandlers(this, true);
- // Add a dummy error listener to catch any weird last moment errors (and ignore them)
- this.connection.on("error", function() {})
- // destroy connection
- this.connection.destroy();
- if(this.logger != null && this.logger.doDebug){
- this.logger.debug("closed connection", this.connection);
- }
-}
-
-// Reset all handlers
-var resetHandlers = function(self, clearListeners) {
- self.eventHandlers = {error:[], connect:[], close:[], end:[], timeout:[], parseError:[], message:[]};
-
- // If we want to clear all the listeners
- if(clearListeners && self.connection != null) {
- var keys = Object.keys(self.eventHandlers);
- // Remove all listeners
- for(var i = 0; i < keys.length; i++) {
- self.connection.removeAllListeners(keys[i]);
- }
- }
-}
-
-//
-// Handlers
-//
-
-// Connect handler
-var connectHandler = function(self) {
- return function(data) {
- // Set connected
- self.connected = true;
- // Now that we are connected set the socket timeout
- self.connection.setTimeout(self.socketOptions.socketTimeoutMS != null ? self.socketOptions.socketTimeoutMS : self.socketOptions.timeout);
- // Emit the connect event with no error
- self.emit("connect", null, self);
- }
-}
-
-var createDataHandler = exports.Connection.createDataHandler = function(self) {
- // We need to handle the parsing of the data
- // and emit the messages when there is a complete one
- return function(data) {
- // Parse until we are done with the data
- while(data.length > 0) {
- // If we still have bytes to read on the current message
- if(self.bytesRead > 0 && self.sizeOfMessage > 0) {
- // Calculate the amount of remaining bytes
- var remainingBytesToRead = self.sizeOfMessage - self.bytesRead;
- // Check if the current chunk contains the rest of the message
- if(remainingBytesToRead > data.length) {
- // Copy the new data into the exiting buffer (should have been allocated when we know the message size)
- data.copy(self.buffer, self.bytesRead);
- // Adjust the number of bytes read so it point to the correct index in the buffer
- self.bytesRead = self.bytesRead + data.length;
-
- // Reset state of buffer
- data = new Buffer(0);
- } else {
- // Copy the missing part of the data into our current buffer
- data.copy(self.buffer, self.bytesRead, 0, remainingBytesToRead);
- // Slice the overflow into a new buffer that we will then re-parse
- data = data.slice(remainingBytesToRead);
-
- // Emit current complete message
- try {
- var emitBuffer = self.buffer;
- // Reset state of buffer
- self.buffer = null;
- self.sizeOfMessage = 0;
- self.bytesRead = 0;
- self.stubBuffer = null;
- // Emit the buffer
- self.emit("message", emitBuffer, self);
- } catch(err) {
- var errorObject = {err:"socketHandler", trace:err, bin:self.buffer, parseState:{
- sizeOfMessage:self.sizeOfMessage,
- bytesRead:self.bytesRead,
- stubBuffer:self.stubBuffer}};
- if(self.logger != null && self.logger.doError) self.logger.error("parseError", errorObject);
- // We got a parse Error fire it off then keep going
- self.emit("parseError", errorObject, self);
- }
- }
- } else {
- // Stub buffer is kept in case we don't get enough bytes to determine the
- // size of the message (< 4 bytes)
- if(self.stubBuffer != null && self.stubBuffer.length > 0) {
-
- // If we have enough bytes to determine the message size let's do it
- if(self.stubBuffer.length + data.length > 4) {
- // Prepad the data
- var newData = new Buffer(self.stubBuffer.length + data.length);
- self.stubBuffer.copy(newData, 0);
- data.copy(newData, self.stubBuffer.length);
- // Reassign for parsing
- data = newData;
-
- // Reset state of buffer
- self.buffer = null;
- self.sizeOfMessage = 0;
- self.bytesRead = 0;
- self.stubBuffer = null;
-
- } else {
-
- // Add the the bytes to the stub buffer
- var newStubBuffer = new Buffer(self.stubBuffer.length + data.length);
- // Copy existing stub buffer
- self.stubBuffer.copy(newStubBuffer, 0);
- // Copy missing part of the data
- data.copy(newStubBuffer, self.stubBuffer.length);
- // Exit parsing loop
- data = new Buffer(0);
- }
- } else {
- if(data.length > 4) {
- // Retrieve the message size
- var sizeOfMessage = binaryutils.decodeUInt32(data, 0);
- // If we have a negative sizeOfMessage emit error and return
- if(sizeOfMessage < 0 || sizeOfMessage > self.maxMessageSizeBytes) {
- var errorObject = {err:"socketHandler", trace:'', bin:self.buffer, parseState:{
- sizeOfMessage: sizeOfMessage,
- bytesRead: self.bytesRead,
- stubBuffer: self.stubBuffer}};
- if(self.logger != null && self.logger.doError) self.logger.error("parseError", errorObject);
- // We got a parse Error fire it off then keep going
- self.emit("parseError", errorObject, self);
- return;
- }
-
- // Ensure that the size of message is larger than 0 and less than the max allowed
- if(sizeOfMessage > 4 && sizeOfMessage < self.maxBsonSize && sizeOfMessage > data.length) {
- self.buffer = new Buffer(sizeOfMessage);
- // Copy all the data into the buffer
- data.copy(self.buffer, 0);
- // Update bytes read
- self.bytesRead = data.length;
- // Update sizeOfMessage
- self.sizeOfMessage = sizeOfMessage;
- // Ensure stub buffer is null
- self.stubBuffer = null;
- // Exit parsing loop
- data = new Buffer(0);
-
- } else if(sizeOfMessage > 4 && sizeOfMessage < self.maxBsonSize && sizeOfMessage == data.length) {
- try {
- var emitBuffer = data;
- // Reset state of buffer
- self.buffer = null;
- self.sizeOfMessage = 0;
- self.bytesRead = 0;
- self.stubBuffer = null;
- // Exit parsing loop
- data = new Buffer(0);
- // Emit the message
- self.emit("message", emitBuffer, self);
- } catch (err) {
- var errorObject = {err:"socketHandler", trace:err, bin:self.buffer, parseState:{
- sizeOfMessage:self.sizeOfMessage,
- bytesRead:self.bytesRead,
- stubBuffer:self.stubBuffer}};
- if(self.logger != null && self.logger.doError) self.logger.error("parseError", errorObject);
- // We got a parse Error fire it off then keep going
- self.emit("parseError", errorObject, self);
- }
- } else if(sizeOfMessage <= 4 || sizeOfMessage > self.maxBsonSize) {
- var errorObject = {err:"socketHandler", trace:null, bin:data, parseState:{
- sizeOfMessage:sizeOfMessage,
- bytesRead:0,
- buffer:null,
- stubBuffer:null}};
- if(self.logger != null && self.logger.doError) self.logger.error("parseError", errorObject);
- // We got a parse Error fire it off then keep going
- self.emit("parseError", errorObject, self);
-
- // Clear out the state of the parser
- self.buffer = null;
- self.sizeOfMessage = 0;
- self.bytesRead = 0;
- self.stubBuffer = null;
- // Exit parsing loop
- data = new Buffer(0);
-
- } else {
- try {
- var emitBuffer = data.slice(0, sizeOfMessage);
- // Reset state of buffer
- self.buffer = null;
- self.sizeOfMessage = 0;
- self.bytesRead = 0;
- self.stubBuffer = null;
- // Copy rest of message
- data = data.slice(sizeOfMessage);
- // Emit the message
- self.emit("message", emitBuffer, self);
- } catch (err) {
- var errorObject = {err:"socketHandler", trace:err, bin:self.buffer, parseState:{
- sizeOfMessage:sizeOfMessage,
- bytesRead:self.bytesRead,
- stubBuffer:self.stubBuffer}};
- if(self.logger != null && self.logger.doError) self.logger.error("parseError", errorObject);
- // We got a parse Error fire it off then keep going
- self.emit("parseError", errorObject, self);
- }
-
- }
- } else {
- // Create a buffer that contains the space for the non-complete message
- self.stubBuffer = new Buffer(data.length)
- // Copy the data to the stub buffer
- data.copy(self.stubBuffer, 0);
- // Exit parsing loop
- data = new Buffer(0);
- }
- }
- }
- }
- }
-}
-
-var endHandler = function(self) {
- return function() {
- // Set connected to false
- self.connected = false;
- // Emit end event
- self.emit("end", {err: 'connection received Fin packet from [' + self.socketOptions.host + ':' + self.socketOptions.port + ']'}, self);
- }
-}
-
-var timeoutHandler = function(self) {
- return function() {
- // Set connected to false
- self.connected = false;
- // Emit timeout event
- self.emit("timeout", {err: 'connection to [' + self.socketOptions.host + ':' + self.socketOptions.port + '] timed out'}, self);
- }
-}
-
-var drainHandler = function(self) {
- return function() {
- }
-}
-
-var errorHandler = function(self) {
- return function(err) {
- self.connection.destroy();
- // Set connected to false
- self.connected = false;
- // Emit error
- self.emit("error", {err: 'failed to connect to [' + self.socketOptions.host + ':' + self.socketOptions.port + ']'}, self);
- }
-}
-
-var closeHandler = function(self) {
- return function(hadError) {
- // If we have an error during the connection phase
- if(hadError && !self.connected) {
- // Set disconnected
- self.connected = false;
- // Emit error
- self.emit("error", {err: 'failed to connect to [' + self.socketOptions.host + ':' + self.socketOptions.port + ']'}, self);
- } else {
- // Set disconnected
- self.connected = false;
- // Emit close
- self.emit("close", {err: 'connection closed to [' + self.socketOptions.host + ':' + self.socketOptions.port + ']'}, self);
- }
- }
-}
-
-// Some basic defaults
-Connection.DEFAULT_PORT = 27017;
-
-
-
-
-
-
-
diff --git a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/connection_pool.js b/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/connection_pool.js
deleted file mode 100644
index e669354..0000000
--- a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/connection_pool.js
+++ /dev/null
@@ -1,305 +0,0 @@
-var utils = require('./connection_utils'),
- inherits = require('util').inherits,
- net = require('net'),
- timers = require('timers'),
- EventEmitter = require('events').EventEmitter,
- inherits = require('util').inherits,
- MongoReply = require("../responses/mongo_reply").MongoReply,
- Connection = require("./connection").Connection;
-
-// Set processor, setImmediate if 0.10 otherwise nextTick
-var processor = require('../utils').processor();
-
-var ConnectionPool = exports.ConnectionPool = function(host, port, poolSize, bson, socketOptions) {
- if(typeof host !== 'string') {
- throw new Error("host must be specified [" + host + "]");
- }
-
- // Set up event emitter
- EventEmitter.call(this);
-
- // Keep all options for the socket in a specific collection allowing the user to specify the
- // Wished upon socket connection parameters
- this.socketOptions = typeof socketOptions === 'object' ? socketOptions : {};
- this.socketOptions.host = host;
- this.socketOptions.port = port;
- this.socketOptions.domainSocket = false;
- this.bson = bson;
- // PoolSize is always + 1 for special reserved "measurment" socket (like ping, stats etc)
- this.poolSize = poolSize;
- this.minPoolSize = Math.floor(this.poolSize / 2) + 1;
-
- // Check if the host is a socket
- if(host.match(/^\//)) {
- this.socketOptions.domainSocket = true;
- } else if(typeof port === 'string') {
- try {
- port = parseInt(port, 10);
- } catch(err) {
- new Error("port must be specified or valid integer[" + port + "]");
- }
- } else if(typeof port !== 'number') {
- throw new Error("port must be specified [" + port + "]");
- }
-
- // Set default settings for the socket options
- utils.setIntegerParameter(this.socketOptions, 'timeout', 0);
- // Delay before writing out the data to the server
- utils.setBooleanParameter(this.socketOptions, 'noDelay', true);
- // Delay before writing out the data to the server
- utils.setIntegerParameter(this.socketOptions, 'keepAlive', 0);
- // Set the encoding of the data read, default is binary == null
- utils.setStringParameter(this.socketOptions, 'encoding', null);
- // Allows you to set a throttling bufferSize if you need to stop overflows
- utils.setIntegerParameter(this.socketOptions, 'bufferSize', 0);
-
- // Internal structures
- this.openConnections = [];
- // Assign connection id's
- this.connectionId = 0;
-
- // Current index for selection of pool connection
- this.currentConnectionIndex = 0;
- // The pool state
- this._poolState = 'disconnected';
- // timeout control
- this._timeout = false;
- // Time to wait between connections for the pool
- this._timeToWait = 10;
-}
-
-inherits(ConnectionPool, EventEmitter);
-
-ConnectionPool.prototype.setMaxBsonSize = function(maxBsonSize) {
- if(maxBsonSize == null){
- maxBsonSize = Connection.DEFAULT_MAX_BSON_SIZE;
- }
-
- for(var i = 0; i < this.openConnections.length; i++) {
- this.openConnections[i].maxBsonSize = maxBsonSize;
- this.openConnections[i].maxBsonSettings.maxBsonSize = maxBsonSize;
- }
-}
-
-ConnectionPool.prototype.setMaxMessageSizeBytes = function(maxMessageSizeBytes) {
- if(maxMessageSizeBytes == null){
- maxMessageSizeBytes = Connection.DEFAULT_MAX_MESSAGE_SIZE;
- }
-
- for(var i = 0; i < this.openConnections.length; i++) {
- this.openConnections[i].maxMessageSizeBytes = maxMessageSizeBytes;
- this.openConnections[i].maxBsonSettings.maxMessageSizeBytes = maxMessageSizeBytes;
- }
-}
-
-ConnectionPool.prototype.setMaxWriteBatchSize = function(maxWriteBatchSize) {
- if(maxWriteBatchSize == null){
- maxWriteBatchSize = Connection.DEFAULT_MAX_WRITE_BATCH_SIZE;
- }
-
- for(var i = 0; i < this.openConnections.length; i++) {
- this.openConnections[i].maxWriteBatchSize = maxWriteBatchSize;
- }
-}
-
-// Start a function
-var _connect = function(_self) {
- // return new function() {
- // Create a new connection instance
- var connection = new Connection(_self.connectionId++, _self.socketOptions);
- // Set logger on pool
- connection.logger = _self.logger;
- // Connect handler
- connection.on("connect", function(err, connection) {
- // Add connection to list of open connections
- _self.openConnections.push(connection);
- // If the number of open connections is equal to the poolSize signal ready pool
- if(_self.openConnections.length === _self.poolSize && _self._poolState !== 'disconnected') {
- // Set connected
- _self._poolState = 'connected';
- // Emit pool ready
- _self.emit("poolReady");
- } else if(_self.openConnections.length < _self.poolSize) {
- // Wait a little bit of time to let the close event happen if the server closes the connection
- // so we don't leave hanging connections around
- if(typeof _self._timeToWait == 'number') {
- setTimeout(function() {
- // If we are still connecting (no close events fired in between start another connection)
- if(_self._poolState == 'connecting') {
- _connect(_self);
- }
- }, _self._timeToWait);
- } else {
- processor(function() {
- // If we are still connecting (no close events fired in between start another connection)
- if(_self._poolState == 'connecting') {
- _connect(_self);
- }
- });
- }
- }
- });
-
- var numberOfErrors = 0
-
- // Error handler
- connection.on("error", function(err, connection, error_options) {
- numberOfErrors++;
- // If we are already disconnected ignore the event
- if(_self._poolState != 'disconnected' && _self.listeners("error").length > 0) {
- _self.emit("error", err, connection, error_options);
- }
-
- // Close the connection
- connection.close();
- // Set pool as disconnected
- _self._poolState = 'disconnected';
- // Stop the pool
- _self.stop();
- });
-
- // Close handler
- connection.on("close", function() {
- // If we are already disconnected ignore the event
- if(_self._poolState !== 'disconnected' && _self.listeners("close").length > 0) {
- _self.emit("close");
- }
-
- // Set disconnected
- _self._poolState = 'disconnected';
- // Stop
- _self.stop();
- });
-
- // Timeout handler
- connection.on("timeout", function(err, connection) {
- // If we are already disconnected ignore the event
- if(_self._poolState !== 'disconnected' && _self.listeners("timeout").length > 0) {
- _self.emit("timeout", err);
- }
-
- // Close the connection
- connection.close();
- // Set disconnected
- _self._poolState = 'disconnected';
- _self.stop();
- });
-
- // Parse error, needs a complete shutdown of the pool
- connection.on("parseError", function() {
- // If we are already disconnected ignore the event
- if(_self._poolState !== 'disconnected' && _self.listeners("parseError").length > 0) {
- _self.emit("parseError", new Error("parseError occured"));
- }
-
- // Set disconnected
- _self._poolState = 'disconnected';
- _self.stop();
- });
-
- connection.on("message", function(message) {
- _self.emit("message", message);
- });
-
- // Start connection in the next tick
- connection.start();
- // }();
-}
-
-
-// Start method, will throw error if no listeners are available
-// Pass in an instance of the listener that contains the api for
-// finding callbacks for a given message etc.
-ConnectionPool.prototype.start = function() {
- var markerDate = new Date().getTime();
- var self = this;
-
- if(this.listeners("poolReady").length == 0) {
- throw "pool must have at least one listener ready that responds to the [poolReady] event";
- }
-
- // Set pool state to connecting
- this._poolState = 'connecting';
- this._timeout = false;
-
- _connect(self);
-}
-
-// Restart a connection pool (on a close the pool might be in a wrong state)
-ConnectionPool.prototype.restart = function() {
- // Close all connections
- this.stop(false);
- // Now restart the pool
- this.start();
-}
-
-// Stop the connections in the pool
-ConnectionPool.prototype.stop = function(removeListeners) {
- removeListeners = removeListeners == null ? true : removeListeners;
- // Set disconnected
- this._poolState = 'disconnected';
-
- // Clear all listeners if specified
- if(removeListeners) {
- this.removeAllEventListeners();
- }
-
- // Close all connections
- for(var i = 0; i < this.openConnections.length; i++) {
- this.openConnections[i].close();
- }
-
- // Clean up
- this.openConnections = [];
-}
-
-// Check the status of the connection
-ConnectionPool.prototype.isConnected = function() {
- // return this._poolState === 'connected';
- return this.openConnections.length > 0 && this.openConnections[0].isConnected();
-}
-
-// Checkout a connection from the pool for usage, or grab a specific pool instance
-ConnectionPool.prototype.checkoutConnection = function(id) {
- var index = (this.currentConnectionIndex++ % (this.openConnections.length));
- var connection = this.openConnections[index];
- return connection;
-}
-
-ConnectionPool.prototype.getAllConnections = function() {
- return this.openConnections;
-}
-
-// Remove all non-needed event listeners
-ConnectionPool.prototype.removeAllEventListeners = function() {
- this.removeAllListeners("close");
- this.removeAllListeners("error");
- this.removeAllListeners("timeout");
- this.removeAllListeners("connect");
- this.removeAllListeners("end");
- this.removeAllListeners("parseError");
- this.removeAllListeners("message");
- this.removeAllListeners("poolReady");
-}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/connection_utils.js b/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/connection_utils.js
deleted file mode 100644
index 5910924..0000000
--- a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/connection_utils.js
+++ /dev/null
@@ -1,23 +0,0 @@
-exports.setIntegerParameter = function(object, field, defaultValue) {
- if(object[field] == null) {
- object[field] = defaultValue;
- } else if(typeof object[field] !== "number" && object[field] !== parseInt(object[field], 10)) {
- throw "object field [" + field + "] must be a numeric integer value, attempted to set to [" + object[field] + "] type of [" + typeof object[field] + "]";
- }
-}
-
-exports.setBooleanParameter = function(object, field, defaultValue) {
- if(object[field] == null) {
- object[field] = defaultValue;
- } else if(typeof object[field] !== "boolean") {
- throw "object field [" + field + "] must be a boolean value, attempted to set to [" + object[field] + "] type of [" + typeof object[field] + "]";
- }
-}
-
-exports.setStringParameter = function(object, field, defaultValue) {
- if(object[field] == null) {
- object[field] = defaultValue;
- } else if(typeof object[field] !== "string") {
- throw "object field [" + field + "] must be a string value, attempted to set to [" + object[field] + "] type of [" + typeof object[field] + "]";
- }
-}
\ No newline at end of file
diff --git a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/mongos.js b/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/mongos.js
deleted file mode 100644
index 1a1b9d9..0000000
--- a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/mongos.js
+++ /dev/null
@@ -1,570 +0,0 @@
-var ReadPreference = require('./read_preference').ReadPreference
- , Base = require('./base').Base
- , Server = require('./server').Server
- , format = require('util').format
- , timers = require('timers')
- , utils = require('../utils')
- , inherits = require('util').inherits;
-
-// Set processor, setImmediate if 0.10 otherwise nextTick
-var processor = require('../utils').processor();
-
-/**
- * Mongos constructor provides a connection to a mongos proxy including failover to additional servers
- *
- * Options
- * - **socketOptions** {Object, default:null}, an object containing socket options to use (noDelay:(boolean), keepAlive:(number), connectTimeoutMS:(number), socketTimeoutMS:(number))
- * - **ha** {Boolean, default:true}, turn on high availability, attempts to reconnect to down proxies
- * - **haInterval** {Number, default:2000}, time between each replicaset status check.
- *
- * @class Represents a Mongos connection with failover to backup proxies
- * @param {Array} list of mongos server objects
- * @param {Object} [options] additional options for the mongos connection
- */
-var Mongos = function Mongos(servers, options) {
- // Set up basic
- if(!(this instanceof Mongos))
- return new Mongos(servers, options);
-
- // Set up event emitter
- Base.call(this);
-
- // Throw error on wrong setup
- if(servers == null || !Array.isArray(servers) || servers.length == 0)
- throw new Error("At least one mongos proxy must be in the array");
-
- // Ensure we have at least an empty options object
- this.options = options == null ? {} : options;
- // Set default connection pool options
- this.socketOptions = this.options.socketOptions != null ? this.options.socketOptions : {};
- // Enabled ha
- this.haEnabled = this.options['ha'] == null ? true : this.options['ha'];
- this._haInProgress = false;
- // How often are we checking for new servers in the replicaset
- this.mongosStatusCheckInterval = this.options['haInterval'] == null ? 1000 : this.options['haInterval'];
- // Save all the server connections
- this.servers = servers;
- // Servers we need to attempt reconnect with
- this.downServers = {};
- // Servers that are up
- this.upServers = {};
- // Up servers by ping time
- this.upServersByUpTime = {};
- // Emit open setup
- this.emitOpen = this.options.emitOpen || true;
- // Just contains the current lowest ping time and server
- this.lowestPingTimeServer = null;
- this.lowestPingTime = 0;
- // Connection timeout
- this._connectTimeoutMS = this.socketOptions.connectTimeoutMS
- ? this.socketOptions.connectTimeoutMS
- : 1000;
-
- // Add options to servers
- for(var i = 0; i < this.servers.length; i++) {
- var server = this.servers[i];
- server._callBackStore = this._callBackStore;
- server.auto_reconnect = false;
- // Default empty socket options object
- var socketOptions = {host: server.host, port: server.port};
- // If a socket option object exists clone it
- if(this.socketOptions != null) {
- var keys = Object.keys(this.socketOptions);
- for(var k = 0; k < keys.length;k++) socketOptions[keys[i]] = this.socketOptions[keys[i]];
- }
-
- // Set socket options
- server.socketOptions = socketOptions;
- }
-
- // Allow setting the socketTimeoutMS on all connections
- // to work around issues such as secondaries blocking due to compaction
- utils.setSocketTimeoutProperty(this, this.socketOptions);
-}
-
-/**
- * @ignore
- */
-inherits(Mongos, Base);
-
-/**
- * @ignore
- */
-Mongos.prototype.isMongos = function() {
- return true;
-}
-
-/**
- * @ignore
- */
-Mongos.prototype.connect = function(db, options, callback) {
- if('function' === typeof options) callback = options, options = {};
- if(options == null) options = {};
- if(!('function' === typeof callback)) callback = null;
- var self = this;
-
- // Keep reference to parent
- this.db = db;
- // Set server state to connecting
- this._serverState = 'connecting';
- // Number of total servers that need to initialized (known servers)
- this._numberOfServersLeftToInitialize = this.servers.length;
- // Connect handler
- var connectHandler = function(_server) {
- return function(err, result) {
- self._numberOfServersLeftToInitialize = self._numberOfServersLeftToInitialize - 1;
-
- // Add the server to the list of servers that are up
- if(!err) {
- self.upServers[format("%s:%s", _server.host, _server.port)] = _server;
- }
-
- // We are done connecting
- if(self._numberOfServersLeftToInitialize == 0) {
- // If we have no valid mongos server instances error out
- if(Object.keys(self.upServers).length == 0) {
- // return self.emit("connectionError", new Error("No valid mongos instances found"));
- return callback(new Error("No valid mongos instances found"), null);
- }
-
- // Start ha function if it exists
- if(self.haEnabled) {
- // Setup the ha process
- if(self._replicasetTimeoutId != null) clearInterval(self._replicasetTimeoutId);
- self._replicasetTimeoutId = setInterval(self.mongosCheckFunction, self.mongosStatusCheckInterval);
- }
-
- // Set the mongos to connected
- self._serverState = "connected";
-
- // Emit the open event
- if(self.emitOpen)
- self._emitAcrossAllDbInstances(self, null, "open", null, null, null);
-
- self._emitAcrossAllDbInstances(self, null, "fullsetup", null, null, null);
- // Callback
- callback(null, self.db);
- }
- }
- };
-
- // Error handler
- var errorOrCloseHandler = function(_server) {
- return function(err, result) {
- // Emit left event, signaling mongos left the ha
- self.emit('left', 'mongos', _server);
- // Execute all the callbacks with errors
- self.__executeAllCallbacksWithError(err);
- // Check if we have the server
- var found = false;
-
- // Get the server name
- var server_name = format("%s:%s", _server.host, _server.port);
- // Add the downed server
- self.downServers[server_name] = _server;
- // Remove the current server from the list
- delete self.upServers[server_name];
-
- // Emit close across all the attached db instances
- if(Object.keys(self.upServers).length == 0) {
- self._emitAcrossAllDbInstances(self, null, "close", new Error("mongos disconnected, no valid proxies contactable over tcp"), null, null);
- }
- }
- }
-
- // Mongo function
- this.mongosCheckFunction = function() {
- // Set as not waiting for check event
- self._haInProgress = true;
-
- // Servers down
- var numberOfServersLeft = Object.keys(self.downServers).length;
-
- // Check downed servers
- if(numberOfServersLeft > 0) {
- for(var name in self.downServers) {
- // Pop a downed server
- var downServer = self.downServers[name];
- // Set up the connection options for a Mongos
- var options = {
- auto_reconnect: false,
- returnIsMasterResults: true,
- slaveOk: true,
- poolSize: downServer.poolSize,
- socketOptions: {
- connectTimeoutMS: self._connectTimeoutMS,
- socketTimeoutMS: self._socketTimeoutMS
- }
- }
-
- // Create a new server object
- var newServer = new Server(downServer.host, downServer.port, options);
- // Setup the connection function
- var connectFunction = function(_db, _server, _options, _callback) {
- return function() {
- // Attempt to connect
- _server.connect(_db, _options, function(err, result) {
- numberOfServersLeft = numberOfServersLeft - 1;
-
- if(err) {
- return _callback(err, _server);
- } else {
- // Set the new server settings
- _server._callBackStore = self._callBackStore;
-
- // Add server event handlers
- _server.on("close", errorOrCloseHandler(_server));
- _server.on("timeout", errorOrCloseHandler(_server));
- _server.on("error", errorOrCloseHandler(_server));
-
- // Get a read connection
- var _connection = _server.checkoutReader();
- // Get the start time
- var startTime = new Date().getTime();
-
- // Execute ping command to mark each server with the expected times
- self.db.command({ping:1}
- , {failFast:true, connection:_connection}, function(err, result) {
- // Get the start time
- var endTime = new Date().getTime();
- // Mark the server with the ping time
- _server.runtimeStats['pingMs'] = endTime - startTime;
-
- // If we have any buffered commands let's signal reconnect event
- if(self._commandsStore.count() > 0) {
- self.emit('reconnect');
- }
-
- // Execute any waiting reads
- self._commandsStore.execute_writes();
- self._commandsStore.execute_queries();
- // Callback
- return _callback(null, _server);
- });
- }
- });
- }
- }
-
- // Attempt to connect to the database
- connectFunction(self.db, newServer, options, function(err, _server) {
- // If we have an error
- if(err) {
- self.downServers[format("%s:%s", _server.host, _server.port)] = _server;
- }
-
- // Connection function
- var connectionFunction = function(_auth, _connection, _callback) {
- var pending = _auth.length();
-
- for(var j = 0; j < pending; j++) {
- // Get the auth object
- var _auth = _auth.get(j);
- // Unpack the parameter
- var username = _auth.username;
- var password = _auth.password;
- var options = {
- authMechanism: _auth.authMechanism
- , authSource: _auth.authdb
- , connection: _connection
- };
-
- // If we have changed the service name
- if(_auth.gssapiServiceName)
- options.gssapiServiceName = _auth.gssapiServiceName;
-
- // Hold any error
- var _error = null;
- // Authenticate against the credentials
- self.db.authenticate(username, password, options, function(err, result) {
- _error = err != null ? err : _error;
- // Adjust the pending authentication
- pending = pending - 1;
- // Finished up
- if(pending == 0) _callback(_error ? _error : null, _error ? false : true);
- });
- }
- }
-
- // Run auths against the connections
- if(self.auth.length() > 0) {
- var connections = _server.allRawConnections();
- var pendingAuthConn = connections.length;
-
- // No connections we are done
- if(connections.length == 0) {
- // Set ha done
- if(numberOfServersLeft == 0) {
- self._haInProgress = false;
- }
- }
-
- // Final error object
- var finalError = null;
- // Go over all the connections
- for(var j = 0; j < connections.length; j++) {
-
- // Execute against all the connections
- connectionFunction(self.auth, connections[j], function(err, result) {
- // Pending authentication
- pendingAuthConn = pendingAuthConn - 1 ;
-
- // Save error if any
- finalError = err ? err : finalError;
-
- // If we are done let's finish up
- if(pendingAuthConn == 0) {
- // Set ha done
- if(numberOfServersLeft == 0) {
- self._haInProgress = false;
- }
-
- if(!err) {
- add_server(self, _server);
- }
-
- // If we have any buffered commands let's signal reconnect event
- if(self._commandsStore.count() > 0) {
- self.emit('reconnect');
- }
-
- // Execute any waiting reads
- self._commandsStore.execute_writes();
- self._commandsStore.execute_queries();
- }
- });
- }
- } else {
- if(!err) {
- add_server(self, _server);
- }
-
- // Set ha done
- if(numberOfServersLeft == 0) {
- self._haInProgress = false;
-
- // If we have any buffered commands let's signal reconnect event
- if(self._commandsStore.count() > 0) {
- self.emit('reconnect');
- }
-
- // Execute any waiting reads
- self._commandsStore.execute_writes();
- self._commandsStore.execute_queries();
- }
- }
- })();
- }
- } else {
- self._haInProgress = false;
- }
- }
-
- // Connect all the server instances
- for(var i = 0; i < this.servers.length; i++) {
- // Get the connection
- var server = this.servers[i];
- server.mongosInstance = this;
- // Add server event handlers
- server.on("close", errorOrCloseHandler(server));
- server.on("timeout", errorOrCloseHandler(server));
- server.on("error", errorOrCloseHandler(server));
-
- // Configuration
- var options = {
- slaveOk: true,
- poolSize: server.poolSize,
- socketOptions: { connectTimeoutMS: self._connectTimeoutMS },
- returnIsMasterResults: true
- }
-
- // Connect the instance
- server.connect(self.db, options, connectHandler(server));
- }
-}
-
-/**
- * @ignore
- * Add a server to the list of up servers and sort them by ping time
- */
-var add_server = function(self, _server) {
- // Emit a new server joined
- self.emit('joined', "mongos", null, _server);
- // Get the server url
- var server_key = format("%s:%s", _server.host, _server.port);
- // Push to list of valid server
- self.upServers[server_key] = _server;
- // Remove the server from the list of downed servers
- delete self.downServers[server_key];
-
- // Sort the keys by ping time
- var keys = Object.keys(self.upServers);
- var _upServersSorted = {};
- var _upServers = []
-
- // Get all the servers
- for(var name in self.upServers) {
- _upServers.push(self.upServers[name]);
- }
-
- // Sort all the server
- _upServers.sort(function(a, b) {
- return a.runtimeStats['pingMs'] > b.runtimeStats['pingMs'];
- });
-
- // Rebuild the upServer
- for(var i = 0; i < _upServers.length; i++) {
- _upServersSorted[format("%s:%s", _upServers[i].host, _upServers[i].port)] = _upServers[i];
- }
-
- // Set the up servers
- self.upServers = _upServersSorted;
-}
-
-/**
- * @ignore
- * Just return the currently picked active connection
- */
-Mongos.prototype.allServerInstances = function() {
- return this.servers;
-}
-
-/**
- * @ignore
- */
-Mongos.prototype.setSocketOptions = function(options) {
- var servers = this.allServerInstances();
- for(var i = 0; i < servers.length; i++) {
- servers[i].setSocketOptions(options);
- }
-}
-
-/**
- * Always ourselves
- * @ignore
- */
-Mongos.prototype.setReadPreference = function() {}
-
-/**
- * @ignore
- */
-Mongos.prototype.allRawConnections = function() {
- // Neeed to build a complete list of all raw connections, start with master server
- var allConnections = [];
- // Get all connected connections
- for(var name in this.upServers) {
- allConnections = allConnections.concat(this.upServers[name].allRawConnections());
- }
- // Return all the conections
- return allConnections;
-}
-
-/**
- * @ignore
- */
-Mongos.prototype.isConnected = function() {
- return Object.keys(this.upServers).length > 0;
-}
-
-/**
- * @ignore
- */
-Mongos.prototype.isAutoReconnect = function() {
- return true;
-}
-
-/**
- * @ignore
- */
-Mongos.prototype.canWrite = Mongos.prototype.isConnected;
-
-/**
- * @ignore
- */
-Mongos.prototype.canRead = Mongos.prototype.isConnected;
-
-/**
- * @ignore
- */
-Mongos.prototype.isDestroyed = function() {
- return this._serverState == 'destroyed';
-}
-
-/**
- * @ignore
- */
-Mongos.prototype.checkoutWriter = function() {
- // Checkout a writer
- var keys = Object.keys(this.upServers);
- if(keys.length == 0) return null;
- return this.upServers[keys[0]].checkoutWriter();
-}
-
-/**
- * @ignore
- */
-Mongos.prototype.checkoutReader = function(read) {
- // If read is set to null default to primary
- read = read || 'primary'
- // If we have a read preference object unpack it
- if(read != null && typeof read == 'object' && read['_type'] == 'ReadPreference') {
- // Validate if the object is using a valid mode
- if(!read.isValid()) throw new Error("Illegal readPreference mode specified, " + JSON.stringify(read));
- } else if(!ReadPreference.isValid(read)) {
- throw new Error("Illegal readPreference mode specified, " + JSON.stringify(read));
- }
-
- // Checkout a writer
- var keys = Object.keys(this.upServers);
- if(keys.length == 0) return null;
- return this.upServers[keys[0]].checkoutWriter();
-}
-
-/**
- * @ignore
- */
-Mongos.prototype.close = function(callback) {
- var self = this;
- // Set server status as disconnected
- this._serverState = 'destroyed';
- // Number of connections to close
- var numberOfConnectionsToClose = self.servers.length;
- // If we have a ha process running kill it
- if(self._replicasetTimeoutId != null) clearInterval(self._replicasetTimeoutId);
- self._replicasetTimeoutId = null;
-
- // Emit close event
- processor(function() {
- self._emitAcrossAllDbInstances(self, null, "close", null, null, true)
- });
-
- // Flush out any remaining call handlers
- self._flushAllCallHandlers(utils.toError("Connection Closed By Application"));
-
- // No up servers just return
- if(Object.keys(this.upServers) == 0) {
- return callback(null);
- }
-
- // Close all the up servers
- for(var name in this.upServers) {
- this.upServers[name].close(function(err, result) {
- numberOfConnectionsToClose = numberOfConnectionsToClose - 1;
-
- // Callback if we have one defined
- if(numberOfConnectionsToClose == 0 && typeof callback == 'function') {
- callback(null);
- }
- });
- }
-}
-
-/**
- * @ignore
- * Return the used state
- */
-Mongos.prototype._isUsed = function() {
- return this._used;
-}
-
-exports.Mongos = Mongos;
\ No newline at end of file
diff --git a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/read_preference.js b/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/read_preference.js
deleted file mode 100644
index 6caafa9..0000000
--- a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/read_preference.js
+++ /dev/null
@@ -1,67 +0,0 @@
-/**
- * A class representation of the Read Preference.
- *
- * Read Preferences
- * - **ReadPreference.PRIMARY**, Read from primary only. All operations produce an error (throw an exception where applicable) if primary is unavailable. Cannot be combined with tags (This is the default.).
- * - **ReadPreference.PRIMARY_PREFERRED**, Read from primary if available, otherwise a secondary.
- * - **ReadPreference.SECONDARY**, Read from secondary if available, otherwise error.
- * - **ReadPreference.SECONDARY_PREFERRED**, Read from a secondary if available, otherwise read from the primary.
- * - **ReadPreference.NEAREST**, All modes read from among the nearest candidates, but unlike other modes, NEAREST will include both the primary and all secondaries in the random selection.
- *
- * @class Represents a Read Preference.
- * @param {String} the read preference type
- * @param {Object} tags
- * @return {ReadPreference}
- */
-var ReadPreference = function(mode, tags) {
- if(!(this instanceof ReadPreference))
- return new ReadPreference(mode, tags);
- this._type = 'ReadPreference';
- this.mode = mode;
- this.tags = tags;
-}
-
-/**
- * @ignore
- */
-ReadPreference.isValid = function(_mode) {
- return (_mode == ReadPreference.PRIMARY || _mode == ReadPreference.PRIMARY_PREFERRED
- || _mode == ReadPreference.SECONDARY || _mode == ReadPreference.SECONDARY_PREFERRED
- || _mode == ReadPreference.NEAREST
- || _mode == true || _mode == false || _mode == null);
-}
-
-/**
- * @ignore
- */
-ReadPreference.prototype.isValid = function(mode) {
- var _mode = typeof mode == 'string' ? mode : this.mode;
- return ReadPreference.isValid(_mode);
-}
-
-/**
- * @ignore
- */
-ReadPreference.prototype.toObject = function() {
- var object = {mode:this.mode};
-
- if(this.tags != null) {
- object['tags'] = this.tags;
- }
-
- return object;
-}
-
-/**
- * @ignore
- */
-ReadPreference.PRIMARY = 'primary';
-ReadPreference.PRIMARY_PREFERRED = 'primaryPreferred';
-ReadPreference.SECONDARY = 'secondary';
-ReadPreference.SECONDARY_PREFERRED = 'secondaryPreferred';
-ReadPreference.NEAREST = 'nearest'
-
-/**
- * @ignore
- */
-exports.ReadPreference = ReadPreference;
\ No newline at end of file
diff --git a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/repl_set/ha.js b/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/repl_set/ha.js
deleted file mode 100644
index 1a0353b..0000000
--- a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/repl_set/ha.js
+++ /dev/null
@@ -1,449 +0,0 @@
-var DbCommand = require('../../commands/db_command').DbCommand
- , format = require('util').format;
-
-var HighAvailabilityProcess = function(replset, options) {
- this.replset = replset;
- this.options = options;
- this.server = null;
- this.state = HighAvailabilityProcess.INIT;
- this.selectedIndex = 0;
-}
-
-HighAvailabilityProcess.INIT = 'init';
-HighAvailabilityProcess.RUNNING = 'running';
-HighAvailabilityProcess.STOPPED = 'stopped';
-
-HighAvailabilityProcess.prototype.start = function() {
- var self = this;
- if(this.replset._state
- && Object.keys(this.replset._state.addresses).length == 0) {
- if(this.server) this.server.close();
- this.state = HighAvailabilityProcess.STOPPED;
- return;
- }
-
- if(this.server) this.server.close();
- // Start the running
- this._haProcessInProcess = false;
- this.state = HighAvailabilityProcess.RUNNING;
-
- // Get all possible reader servers
- var candidate_servers = this.replset._state.getAllReadServers();
- if(candidate_servers.length == 0) {
- return;
- }
-
- // Select a candidate server for the connection
- var server = candidate_servers[this.selectedIndex % candidate_servers.length];
- this.selectedIndex = this.selectedIndex + 1;
-
- // Unpack connection options
- var connectTimeoutMS = self.options.connectTimeoutMS || 10000;
- var socketTimeoutMS = self.options.socketTimeoutMS || 30000;
-
- // Just ensure we don't have a full cycle dependency
- var Db = require('../../db').Db
- var Server = require('../server').Server;
-
- // Set up a new server instance
- var newServer = new Server(server.host, server.port, {
- auto_reconnect: false
- , returnIsMasterResults: true
- , poolSize: 1
- , socketOptions: {
- connectTimeoutMS: connectTimeoutMS,
- socketTimeoutMS: socketTimeoutMS,
- keepAlive: 100
- }
- , ssl: self.replset.options.ssl
- , sslValidate: self.replset.options.sslValidate
- , sslCA: self.replset.options.sslCA
- , sslCert: self.replset.options.sslCert
- , sslKey: self.replset.options.sslKey
- , sslPass: self.replset.options.sslPass
- });
-
- // Create new dummy db for app
- self.db = new Db('local', newServer, {w:1});
-
- // Set up the event listeners
- newServer.once("error", _handle(this, newServer));
- newServer.once("close", _handle(this, newServer));
- newServer.once("timeout", _handle(this, newServer));
- newServer.name = format("%s:%s", server.host, server.port);
-
- // Let's attempt a connection over here
- newServer.connect(self.db, function(err, result, _server) {
- // Emit ha_connect
- self.replset.emit("ha_connect", err, result, _server);
-
- if(self.state == HighAvailabilityProcess.STOPPED) {
- _server.close();
- }
-
- if(err) {
- // Close the server
- _server.close();
- // Check if we can even do HA (is there anything running)
- if(Object.keys(self.replset._state.addresses).length == 0) {
- return;
- }
-
- // Let's boot the ha timeout settings
- setTimeout(function() {
- self.start();
- }, self.options.haInterval);
- } else {
- self.server = _server;
- // Let's boot the ha timeout settings
- setTimeout(_timeoutHandle(self), self.options.haInterval);
- }
- });
-}
-
-HighAvailabilityProcess.prototype.stop = function() {
- this.state = HighAvailabilityProcess.STOPPED;
- if(this.server) this.server.close();
-}
-
-var _timeoutHandle = function(self) {
- return function() {
- if(self.state == HighAvailabilityProcess.STOPPED) {
- // Stop all server instances
- for(var name in self.replset._state.addresses) {
- self.replset._state.addresses[name].close();
- delete self.replset._state.addresses[name];
- }
-
- // Finished pinging
- return;
- }
-
- // If the server is connected
- if(self.server.isConnected() && !self._haProcessInProcess) {
- // Start HA process
- self._haProcessInProcess = true;
- // Execute is master command
- self.db._executeQueryCommand(DbCommand.createIsMasterCommand(self.db),
- {failFast:true, connection: self.server.checkoutReader()}
- , function(err, res) {
- // Emit ha event
- self.replset.emit("ha_ismaster", err, res);
-
- // If we have an error close
- if(err) {
- self.server.close();
- // Re-run loop
- return setTimeout(_timeoutHandle(self), self.options.haInterval);
- }
-
- // Master document
- var master = res.documents[0];
- var hosts = master.hosts || [];
- var reconnect_servers = [];
- var state = self.replset._state;
-
- // We are in recovery mode, let's remove the current server
- if(!master.ismaster
- && !master.secondary
- && state.addresses[master.me]) {
- self.server.close();
- state.addresses[master.me].close();
- delete state.secondaries[master.me];
- // Re-run loop
- return setTimeout(_timeoutHandle(self), self.options.haInterval);
- }
-
- // We have a new master different front he current one
- if((master.primary && state.master == null)
- || (master.primary && state.master.name != master.primary)) {
-
- // Locate the primary and set it
- if(state.addresses[master.primary]) {
- if(state.master) state.master.close();
- delete state.secondaries[master.primary];
- state.master = state.addresses[master.primary];
- }
-
- // Emit joined event due to primary change
- self.replset.emit('joined', "primary", master, state.master);
-
- // Set up the changes
- if(state.master != null && state.master.isMasterDoc != null) {
- state.master.isMasterDoc.ismaster = true;
- state.master.isMasterDoc.secondary = false;
- } else if(state.master != null) {
- state.master.isMasterDoc = master;
- state.master.isMasterDoc.ismaster = true;
- state.master.isMasterDoc.secondary = false;
- }
-
- // If we have any buffered commands let's signal reconnect event
- if(self.replset._commandsStore.count() > 0) {
- self.replset.emit('reconnect');
- }
-
- // Execute any waiting commands (queries or writes)
- self.replset._commandsStore.execute_queries();
- self.replset._commandsStore.execute_writes();
- }
-
- // For all the hosts let's check that we have connections
- for(var i = 0; i < hosts.length; i++) {
- var host = hosts[i];
-
- // Check if we need to reconnect to a server
- if(state.addresses[host] == null) {
- reconnect_servers.push(host);
- } else if(state.addresses[host] && !state.addresses[host].isConnected()) {
- state.addresses[host].close();
- delete state.secondaries[host];
- reconnect_servers.push(host);
- }
- }
-
- // Let's reconnect to any server needed
- if(reconnect_servers.length > 0) {
- _reconnect_servers(self, reconnect_servers);
- } else {
- self._haProcessInProcess = false
- return setTimeout(_timeoutHandle(self), self.options.haInterval);
- }
- });
- } else if(!self.server.isConnected()) {
- setTimeout(function() {
- return self.start();
- }, self.options.haInterval);
- } else {
- setTimeout(_timeoutHandle(self), self.options.haInterval);
- }
- }
-}
-
-var _reconnect_servers = function(self, reconnect_servers) {
- if(reconnect_servers.length == 0) {
- self._haProcessInProcess = false
- return setTimeout(_timeoutHandle(self), self.options.haInterval);
- }
-
- // Unpack connection options
- var connectTimeoutMS = self.options.connectTimeoutMS || 10000;
- var socketTimeoutMS = self.options.socketTimeoutMS || 0;
-
- // Server class
- var Db = require('../../db').Db
- var Server = require('../server').Server;
- // Get the host
- var host = reconnect_servers.shift();
- // Split it up
- var _host = host.split(":")[0];
- var _port = parseInt(host.split(":")[1], 10);
-
- // Set up a new server instance
- var newServer = new Server(_host, _port, {
- auto_reconnect: false
- , returnIsMasterResults: true
- , poolSize: self.options.poolSize
- , socketOptions: {
- connectTimeoutMS: connectTimeoutMS,
- socketTimeoutMS: socketTimeoutMS
- }
- , ssl: self.replset.options.ssl
- , sslValidate: self.replset.options.sslValidate
- , sslCA: self.replset.options.sslCA
- , sslCert: self.replset.options.sslCert
- , sslKey: self.replset.options.sslKey
- , sslPass: self.replset.options.sslPass
- });
-
- // Create new dummy db for app
- var db = new Db('local', newServer, {w:1});
- var state = self.replset._state;
-
- // Set up the event listeners
- newServer.once("error", _repl_set_handler("error", self.replset, newServer));
- newServer.once("close", _repl_set_handler("close", self.replset, newServer));
- newServer.once("timeout", _repl_set_handler("timeout", self.replset, newServer));
-
- // Set shared state
- newServer.name = host;
- newServer._callBackStore = self.replset._callBackStore;
- newServer.replicasetInstance = self.replset;
- newServer.enableRecordQueryStats(self.replset.recordQueryStats);
-
- // Let's attempt a connection over here
- newServer.connect(db, function(err, result, _server) {
- // Emit ha_connect
- self.replset.emit("ha_connect", err, result, _server);
-
- if(self.state == HighAvailabilityProcess.STOPPED) {
- _server.close();
- }
-
- // If we connected let's check what kind of server we have
- if(!err) {
- _apply_auths(self, db, _server, function(err, result) {
- if(err) {
- _server.close();
- // Process the next server
- return setTimeout(function() {
- _reconnect_servers(self, reconnect_servers);
- }, self.options.haInterval);
- }
-
- var doc = _server.isMasterDoc;
- // Fire error on any unknown callbacks for this server
- self.replset.__executeAllServerSpecificErrorCallbacks(_server.socketOptions.host, _server.socketOptions.port, err);
-
- if(doc.ismaster) {
- // Emit primary added
- self.replset.emit('joined', "primary", doc, _server);
-
- // If it was a secondary remove it
- if(state.secondaries[doc.me]) {
- delete state.secondaries[doc.me];
- }
-
- // Override any server in list of addresses
- state.addresses[doc.me] = _server;
- // Set server as master
- state.master = _server;
-
- // If we have any buffered commands let's signal reconnect event
- if(self.replset._commandsStore.count() > 0) {
- self.replset.emit('reconnect');
- }
-
- // Execute any waiting writes
- self.replset._commandsStore.execute_writes();
- } else if(doc.secondary) {
- // Emit secondary added
- self.replset.emit('joined', "secondary", doc, _server);
- // Add the secondary to the state
- state.secondaries[doc.me] = _server;
- // Override any server in list of addresses
- state.addresses[doc.me] = _server;
-
- // If we have any buffered commands let's signal reconnect event
- if(self.replset._commandsStore.count() > 0) {
- self.replset.emit('reconnect');
- }
-
- // Execute any waiting reads
- self.replset._commandsStore.execute_queries();
- } else {
- _server.close();
- }
-
- // Set any tags on the instance server
- _server.name = doc.me;
- _server.tags = doc.tags;
- // Process the next server
- setTimeout(function() {
- _reconnect_servers(self, reconnect_servers);
- }, self.options.haInterval);
- });
- } else {
- _server.close();
- self.replset.__executeAllServerSpecificErrorCallbacks(_server.socketOptions.host, _server.socketOptions.port, err);
-
- setTimeout(function() {
- _reconnect_servers(self, reconnect_servers);
- }, self.options.haInterval);
- }
- });
-}
-
-var _apply_auths = function(self, _db, _server, _callback) {
- if(self.replset.auth.length() == 0) return _callback(null);
- // Apply any authentication needed
- if(self.replset.auth.length() > 0) {
- var pending = self.replset.auth.length();
- var connections = _server.allRawConnections();
- var pendingAuthConn = connections.length;
-
- // Connection function
- var connectionFunction = function(_auth, _connection, __callback) {
- var pending = _auth.length();
-
- for(var j = 0; j < pending; j++) {
- // Get the auth object
- var _auth = _auth.get(j);
- // Unpack the parameter
- var username = _auth.username;
- var password = _auth.password;
- var options = {
- authMechanism: _auth.authMechanism
- , authSource: _auth.authdb
- , connection: _connection
- };
-
- // If we have changed the service name
- if(_auth.gssapiServiceName)
- options.gssapiServiceName = _auth.gssapiServiceName;
-
- // Hold any error
- var _error = null;
-
- // Authenticate against the credentials
- _db.authenticate(username, password, options, function(err, result) {
- _error = err != null ? err : _error;
- // Adjust the pending authentication
- pending = pending - 1;
- // Finished up
- if(pending == 0) __callback(_error ? _error : null, _error ? false : true);
- });
- }
- }
-
- // Final error object
- var finalError = null;
- // Iterate over all the connections
- for(var i = 0; i < connections.length; i++) {
- connectionFunction(self.replset.auth, connections[i], function(err, result) {
- // Pending authentication
- pendingAuthConn = pendingAuthConn - 1 ;
-
- // Save error if any
- finalError = err ? err : finalError;
-
- // If we are done let's finish up
- if(pendingAuthConn == 0) {
- _callback(null);
- }
- });
- }
- }
-}
-
-var _handle = function(self, server) {
- return function(err) {
- server.close();
- }
-}
-
-var _repl_set_handler = function(event, self, server) {
- var ReplSet = require('./repl_set').ReplSet;
-
- return function(err, doc) {
- server.close();
-
- // The event happened to a primary
- // Remove it from play
- if(self._state.isPrimary(server)) {
- self._state.master == null;
- self._serverState = ReplSet.REPLSET_READ_ONLY;
- } else if(self._state.isSecondary(server)) {
- delete self._state.secondaries[server.name];
- }
-
- // Unpack variables
- var host = server.socketOptions.host;
- var port = server.socketOptions.port;
-
- // Fire error on any unknown callbacks
- self.__executeAllServerSpecificErrorCallbacks(host, port, err);
- }
-}
-
-exports.HighAvailabilityProcess = HighAvailabilityProcess;
diff --git a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/repl_set/options.js b/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/repl_set/options.js
deleted file mode 100644
index 8b3d72b..0000000
--- a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/repl_set/options.js
+++ /dev/null
@@ -1,126 +0,0 @@
-var PingStrategy = require('./strategies/ping_strategy').PingStrategy
- , StatisticsStrategy = require('./strategies/statistics_strategy').StatisticsStrategy
- , ReadPreference = require('../read_preference').ReadPreference;
-
-var Options = function(options) {
- options = options || {};
- this._options = options;
- this.ha = options.ha || true;
- this.haInterval = options.haInterval || 2000;
- this.reconnectWait = options.reconnectWait || 1000;
- this.retries = options.retries || 30;
- this.rs_name = options.rs_name;
- this.socketOptions = options.socketOptions || {};
- this.readPreference = options.readPreference;
- this.readSecondary = options.read_secondary;
- this.poolSize = options.poolSize == null ? 5 : options.poolSize;
- this.strategy = options.strategy || 'ping';
- this.secondaryAcceptableLatencyMS = options.secondaryAcceptableLatencyMS || 15;
- this.connectArbiter = options.connectArbiter || false;
- this.connectWithNoPrimary = options.connectWithNoPrimary || false;
- this.logger = options.logger;
- this.ssl = options.ssl || false;
- this.sslValidate = options.sslValidate || false;
- this.sslCA = options.sslCA;
- this.sslCert = options.sslCert;
- this.sslKey = options.sslKey;
- this.sslPass = options.sslPass;
- this.emitOpen = options.emitOpen || true;
-}
-
-Options.prototype.init = function() {
- if(this.sslValidate && (!Array.isArray(this.sslCA) || this.sslCA.length == 0)) {
- throw new Error("The driver expects an Array of CA certificates in the sslCA parameter when enabling sslValidate");
- }
-
- // Make sure strategy is one of the two allowed
- if(this.strategy != null && (this.strategy != 'ping' && this.strategy != 'statistical' && this.strategy != 'none'))
- throw new Error("Only ping or statistical strategies allowed");
-
- if(this.strategy == null) this.strategy = 'ping';
-
- // Set logger if strategy exists
- if(this.strategyInstance) this.strategyInstance.logger = this.logger;
-
- // Unpack read Preference
- var readPreference = this.readPreference;
- // Validate correctness of Read preferences
- if(readPreference != null) {
- if(readPreference != ReadPreference.PRIMARY && readPreference != ReadPreference.PRIMARY_PREFERRED
- && readPreference != ReadPreference.SECONDARY && readPreference != ReadPreference.SECONDARY_PREFERRED
- && readPreference != ReadPreference.NEAREST && typeof readPreference != 'object' && readPreference['_type'] != 'ReadPreference') {
- throw new Error("Illegal readPreference mode specified, " + JSON.stringify(readPreference));
- }
-
- this.readPreference = readPreference;
- } else {
- this.readPreference = null;
- }
-
- // Ensure read_secondary is set correctly
- if(this.readSecondary != null)
- this.readSecondary = this.readPreference == ReadPreference.PRIMARY
- || this.readPreference == false
- || this.readPreference == null ? false : true;
-
- // Ensure correct slave set
- if(this.readSecondary) this.slaveOk = true;
-
- // Set up logger if any set
- this.logger = this.logger != null
- && (typeof this.logger.debug == 'function')
- && (typeof this.logger.error == 'function')
- && (typeof this.logger.debug == 'function')
- ? this.logger : {error:function(message, object) {}, log:function(message, object) {}, debug:function(message, object) {}};
-
- // Connection timeout
- this.connectTimeoutMS = typeof this.socketOptions.connectTimeoutMS == 'number'
- ? this.socketOptions.connectTimeoutMS
- : 1000;
-
- // Socket connection timeout
- this.socketTimeoutMS = typeof this.socketOptions.socketTimeoutMS == 'number'
- ? this.socketOptions.socketTimeoutMS
- : 30000;
-}
-
-Options.prototype.decorateAndClean = function(servers, callBackStore) {
- var self = this;
-
- // var de duplicate list
- var uniqueServers = {};
- // De-duplicate any servers in the seed list
- for(var i = 0; i < servers.length; i++) {
- var server = servers[i];
- // If server does not exist set it
- if(uniqueServers[server.host + ":" + server.port] == null) {
- uniqueServers[server.host + ":" + server.port] = server;
- }
- }
-
- // Let's set the deduplicated list of servers
- var finalServers = [];
- // Add the servers
- for(var key in uniqueServers) {
- finalServers.push(uniqueServers[key]);
- }
-
- finalServers.forEach(function(server) {
- // Ensure no server has reconnect on
- server.options.auto_reconnect = false;
- // Set up ssl options
- server.ssl = self.ssl;
- server.sslValidate = self.sslValidate;
- server.sslCA = self.sslCA;
- server.sslCert = self.sslCert;
- server.sslKey = self.sslKey;
- server.sslPass = self.sslPass;
- server.poolSize = self.poolSize;
- // Set callback store
- server._callBackStore = callBackStore;
- });
-
- return finalServers;
-}
-
-exports.Options = Options;
diff --git a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/repl_set/repl_set.js b/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/repl_set/repl_set.js
deleted file mode 100644
index b7d5a35..0000000
--- a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/repl_set/repl_set.js
+++ /dev/null
@@ -1,829 +0,0 @@
-var ReadPreference = require('../read_preference').ReadPreference
- , DbCommand = require('../../commands/db_command').DbCommand
- , inherits = require('util').inherits
- , format = require('util').format
- , timers = require('timers')
- , Server = require('../server').Server
- , utils = require('../../utils')
- , PingStrategy = require('./strategies/ping_strategy').PingStrategy
- , StatisticsStrategy = require('./strategies/statistics_strategy').StatisticsStrategy
- , Options = require('./options').Options
- , ReplSetState = require('./repl_set_state').ReplSetState
- , HighAvailabilityProcess = require('./ha').HighAvailabilityProcess
- , Base = require('../base').Base;
-
-var STATE_STARTING_PHASE_1 = 0;
-var STATE_PRIMARY = 1;
-var STATE_SECONDARY = 2;
-var STATE_RECOVERING = 3;
-var STATE_FATAL_ERROR = 4;
-var STATE_STARTING_PHASE_2 = 5;
-var STATE_UNKNOWN = 6;
-var STATE_ARBITER = 7;
-var STATE_DOWN = 8;
-var STATE_ROLLBACK = 9;
-
-// Set processor, setImmediate if 0.10 otherwise nextTick
-var processor = require('../../utils').processor();
-
-/**
- * ReplSet constructor provides replicaset functionality
- *
- * Options
- * - **ha** {Boolean, default:true}, turn on high availability.
- * - **haInterval** {Number, default:2000}, time between each replicaset status check.
- * - **reconnectWait** {Number, default:1000}, time to wait in miliseconds before attempting reconnect.
- * - **retries** {Number, default:30}, number of times to attempt a replicaset reconnect.
- * - **rs_name** {String}, the name of the replicaset to connect to.
- * - **socketOptions** {Object, default:null}, an object containing socket options to use (noDelay:(boolean), keepAlive:(number), connectTimeoutMS:(number), socketTimeoutMS:(number))
- * - **strategy** {String, default:'ping'}, selection strategy for reads choose between (ping, statistical and none, default is ping)
- * - **secondaryAcceptableLatencyMS** {Number, default:15}, sets the range of servers to pick when using NEAREST (lowest ping ms + the latency fence, ex: range of 1 to (1 + 15) ms)
- * - **connectWithNoPrimary** {Boolean, default:false}, sets if the driver should connect even if no primary is available
- * - **connectArbiter** {Boolean, default:false}, sets if the driver should connect to arbiters or not.
- * - **logger** {Object, default:null}, an object representing a logger that you want to use, needs to support functions debug, log, error **({error:function(message, object) {}, log:function(message, object) {}, debug:function(message, object) {}})**.
- * - **poolSize** {Number, default:5}, number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons.
- * - **ssl** {Boolean, default:false}, use ssl connection (needs to have a mongod server with ssl support)
- * - **sslValidate** {Boolean, default:false}, validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher)
- * - **sslCA** {Array, default:null}, Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher)
- * - **sslCert** {Buffer/String, default:null}, String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher)
- * - **sslKey** {Buffer/String, default:null}, String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher)
- * - **sslPass** {Buffer/String, default:null}, String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher)
- *
- * @class Represents a
- Replicaset Configuration
- * @param {Array} list of server objects participating in the replicaset.
- * @param {Object} [options] additional options for the replicaset connection.
- */
-var ReplSet = exports.ReplSet = function(servers, options) {
- // Set up basic
- if(!(this instanceof ReplSet))
- return new ReplSet(servers, options);
-
- // Set up event emitter
- Base.call(this);
-
- // Ensure we have a list of servers
- if(!Array.isArray(servers)) throw Error("The parameter must be an array of servers and contain at least one server");
- // Ensure no Mongos's
- for(var i = 0; i < servers.length; i++) {
- if(!(servers[i] instanceof Server)) throw new Error("list of servers must be of type Server");
- }
-
- // Save the options
- this.options = new Options(options);
- // Ensure basic validation of options
- this.options.init();
-
- // Server state
- this._serverState = ReplSet.REPLSET_DISCONNECTED;
- // Add high availability process
- this._haProcess = new HighAvailabilityProcess(this, this.options);
-
- // Let's iterate over all the provided server objects and decorate them
- this.servers = this.options.decorateAndClean(servers, this._callBackStore);
- // Throw error if no seed servers
- if(this.servers.length == 0) throw new Error("No valid seed servers in the array");
-
- // Let's set up our strategy object for picking secondaries
- if(this.options.strategy == 'ping') {
- // Create a new instance
- this.strategyInstance = new PingStrategy(this, this.options.secondaryAcceptableLatencyMS);
- } else if(this.options.strategy == 'statistical') {
- // Set strategy as statistical
- this.strategyInstance = new StatisticsStrategy(this);
- // Add enable query information
- this.enableRecordQueryStats(true);
- }
-
- this.emitOpen = this.options.emitOpen || true;
- // Set up a clean state
- this._state = new ReplSetState(this);
- // Current round robin selected server
- this._currentServerChoice = 0;
- // Ensure up the server callbacks
- for(var i = 0; i < this.servers.length; i++) {
- this.servers[i]._callBackStore = this._callBackStore;
- this.servers[i].name = format("%s:%s", this.servers[i].host, this.servers[i].port)
- this.servers[i].replicasetInstance = this;
- this.servers[i].options.auto_reconnect = false;
- this.servers[i].inheritReplSetOptionsFrom(this);
- }
-
- // Allow setting the socketTimeoutMS on all connections
- // to work around issues such as secondaries blocking due to compaction
- utils.setSocketTimeoutProperty(this, this.options.socketOptions);
-}
-
-/**
- * @ignore
- */
-inherits(ReplSet, Base);
-
-// Replicaset states
-ReplSet.REPLSET_CONNECTING = 'connecting';
-ReplSet.REPLSET_DISCONNECTED = 'disconnected';
-ReplSet.REPLSET_CONNECTED = 'connected';
-ReplSet.REPLSET_RECONNECTING = 'reconnecting';
-ReplSet.REPLSET_DESTROYED = 'destroyed';
-ReplSet.REPLSET_READ_ONLY = 'readonly';
-
-ReplSet.prototype.isAutoReconnect = function() {
- return true;
-}
-
-ReplSet.prototype.canWrite = function() {
- return this._state.master && this._state.master.isConnected();
-}
-
-ReplSet.prototype.canRead = function(read) {
- if((read == ReadPreference.PRIMARY
- || (typeof read == 'object' && read.mode == ReadPreference.PRIMARY)
- || read == null || read == false) && (this._state.master == null || !this._state.master.isConnected())) return false;
- return Object.keys(this._state.secondaries).length > 0;
-}
-
-/**
- * @ignore
- */
-ReplSet.prototype.enableRecordQueryStats = function(enable) {
- // Set the global enable record query stats
- this.recordQueryStats = enable;
-
- // Enable all the servers
- for(var i = 0; i < this.servers.length; i++) {
- this.servers[i].enableRecordQueryStats(enable);
- }
-}
-
-/**
- * @ignore
- */
-ReplSet.prototype.setSocketOptions = function(options) {
- var servers = this.allServerInstances();
-
- if(typeof options.socketTimeoutMS == 'number') {
- this.options.socketOptions.socketTimeoutMS = options.socketTimeoutMS;
- }
-
- if(typeof options.connectTimeoutMS == 'number')
- this.options.socketOptions.connectTimeoutMS = options.connectTimeoutMS;
-
- for(var i = 0; i < servers.length; i++) {
- servers[i].setSocketOptions(options);
- }
-}
-
-/**
- * @ignore
- */
-ReplSet.prototype.setReadPreference = function(preference) {
- this.options.readPreference = preference;
-}
-
-ReplSet.prototype.connect = function(parent, options, callback) {
- if(this._serverState != ReplSet.REPLSET_DISCONNECTED)
- return callback(new Error("in process of connection"));
-
- // If no callback throw
- if(!(typeof callback == 'function'))
- throw new Error("cannot call ReplSet.prototype.connect with no callback function");
-
- var self = this;
- // Save db reference
- this.options.db = parent;
- // Set replicaset as connecting
- this._serverState = ReplSet.REPLSET_CONNECTING
- // Copy all the servers to our list of seeds
- var candidateServers = this.servers.slice(0);
- // Pop the first server
- var server = candidateServers.pop();
- server.name = format("%s:%s", server.host, server.port);
- // Set up the options
- var opts = {
- returnIsMasterResults: true,
- eventReceiver: server
- }
-
- // Register some event listeners
- this.once("fullsetup", function(err, db, replset) {
- // Set state to connected
- self._serverState = ReplSet.REPLSET_CONNECTED;
- // Stop any process running
- if(self._haProcess) self._haProcess.stop();
- // Start the HA process
- self._haProcess.start();
-
- // Emit fullsetup
- processor(function() {
- if(self.emitOpen)
- self._emitAcrossAllDbInstances(self, null, "open", null, null, null);
-
- self._emitAcrossAllDbInstances(self, null, "fullsetup", null, null, null);
- });
-
- // If we have a strategy defined start it
- if(self.strategyInstance) {
- self.strategyInstance.start();
- }
-
- // Finishing up the call
- callback(err, db, replset);
- });
-
- // Errors
- this.once("connectionError", function(err, result) {
- callback(err, result);
- });
-
- // Attempt to connect to the server
- server.connect(this.options.db, opts, _connectHandler(this, candidateServers, server));
-}
-
-ReplSet.prototype.close = function(callback) {
- var self = this;
- // Set as destroyed
- this._serverState = ReplSet.REPLSET_DESTROYED;
- // Stop the ha
- this._haProcess.stop();
-
- // If we have a strategy stop it
- if(this.strategyInstance) {
- this.strategyInstance.stop();
- }
-
- // Kill all servers available
- for(var name in this._state.addresses) {
- this._state.addresses[name].close();
- }
-
- // Clean out the state
- this._state = new ReplSetState(this);
-
- // Emit close event
- processor(function() {
- self._emitAcrossAllDbInstances(self, null, "close", null, null, true)
- });
-
- // Flush out any remaining call handlers
- self._flushAllCallHandlers(utils.toError("Connection Closed By Application"));
-
- // Callback
- if(typeof callback == 'function')
- return callback(null, null);
-}
-
-/**
- * Creates a new server for the `replset` based on `host`.
- *
- * @param {String} host - host:port pair (localhost:27017)
- * @param {ReplSet} replset - the ReplSet instance
- * @return {Server}
- * @ignore
- */
-var createServer = function(self, host, options) {
- // copy existing socket options to new server
- var socketOptions = {}
- if(options.socketOptions) {
- var keys = Object.keys(options.socketOptions);
- for(var k = 0; k < keys.length; k++) {
- socketOptions[keys[k]] = options.socketOptions[keys[k]];
- }
- }
-
- var parts = host.split(/:/);
- if(1 === parts.length) {
- parts[1] = Connection.DEFAULT_PORT;
- }
-
- socketOptions.host = parts[0];
- socketOptions.port = parseInt(parts[1], 10);
-
- var serverOptions = {
- readPreference: options.readPreference,
- socketOptions: socketOptions,
- poolSize: options.poolSize,
- logger: options.logger,
- auto_reconnect: false,
- ssl: options.ssl,
- sslValidate: options.sslValidate,
- sslCA: options.sslCA,
- sslCert: options.sslCert,
- sslKey: options.sslKey,
- sslPass: options.sslPass
- }
-
- var server = new Server(socketOptions.host, socketOptions.port, serverOptions);
- // Set up shared state
- server._callBackStore = self._callBackStore;
- server.replicasetInstance = self;
- server.enableRecordQueryStats(self.recordQueryStats);
- // Set up event handlers
- server.on("close", _handler("close", self, server));
- server.on("error", _handler("error", self, server));
- server.on("timeout", _handler("timeout", self, server));
- return server;
-}
-
-var _handler = function(event, self, server) {
- return function(err, doc) {
- // The event happened to a primary
- // Remove it from play
- if(self._state.isPrimary(server)) {
- // Emit that the primary left the replicaset
- self.emit('left', 'primary', server);
- // Get the current master
- var current_master = self._state.master;
- self._state.master = null;
- self._serverState = ReplSet.REPLSET_READ_ONLY;
-
- if(current_master != null) {
- // Unpack variables
- var host = current_master.socketOptions.host;
- var port = current_master.socketOptions.port;
-
- // Fire error on any unknown callbacks
- self.__executeAllServerSpecificErrorCallbacks(host, port, err);
- }
- } else if(self._state.isSecondary(server)) {
- // Emit that a secondary left the replicaset
- self.emit('left', 'secondary', server);
- // Delete from the list
- delete self._state.secondaries[server.name];
- }
-
- // If there is no more connections left and the setting is not destroyed
- // set to disconnected
- if(Object.keys(self._state.addresses).length == 0
- && self._serverState != ReplSet.REPLSET_DESTROYED) {
- self._serverState = ReplSet.REPLSET_DISCONNECTED;
-
- // Emit close across all the attached db instances
- self._dbStore.emit("close", new Error("replicaset disconnected, no valid servers contactable over tcp"), null, true);
- }
-
- // Unpack variables
- var host = server.socketOptions.host;
- var port = server.socketOptions.port;
-
- // Fire error on any unknown callbacks
- self.__executeAllServerSpecificErrorCallbacks(host, port, err);
- }
-}
-
-var locateNewServers = function(self, state, candidateServers, ismaster) {
- // Retrieve the host
- var hosts = ismaster.hosts;
- // In candidate servers
- var inCandidateServers = function(name, candidateServers) {
- for(var i = 0; i < candidateServers.length; i++) {
- if(candidateServers[i].name == name) return true;
- }
-
- return false;
- }
-
- // New servers
- var newServers = [];
- if(Array.isArray(hosts)) {
- // Let's go over all the hosts
- for(var i = 0; i < hosts.length; i++) {
- if(!state.contains(hosts[i])
- && !inCandidateServers(hosts[i], candidateServers)) {
- newServers.push(createServer(self, hosts[i], self.options));
- }
- }
- }
-
- // Return list of possible new servers
- return newServers;
-}
-
-var _connectHandler = function(self, candidateServers, instanceServer) {
- return function(err, doc) {
- // If we have an error add to the list
- if(err) {
- self._state.errors[instanceServer.name] = instanceServer;
- } else {
- delete self._state.errors[instanceServer.name];
- }
-
- if(!err) {
- var ismaster = doc.documents[0]
-
- // Error the server if
- if(!ismaster.ismaster
- && !ismaster.secondary) {
- self._state.errors[instanceServer.name] = instanceServer;
- }
- }
-
-
- // No error let's analyse the ismaster command
- if(!err && self._state.errors[instanceServer.name] == null) {
- var ismaster = doc.documents[0]
-
- // If no replicaset name exists set the current one
- if(self.options.rs_name == null) {
- self.options.rs_name = ismaster.setName;
- }
-
- // If we have a member that is not part of the set let's finish up
- if(typeof ismaster.setName == 'string' && ismaster.setName != self.options.rs_name) {
- return self.emit("connectionError", new Error("Replicaset name " + ismaster.setName + " does not match specified name " + self.options.rs_name));
- }
-
- // Add the error handlers
- instanceServer.on("close", _handler("close", self, instanceServer));
- instanceServer.on("error", _handler("error", self, instanceServer));
- instanceServer.on("timeout", _handler("timeout", self, instanceServer));
-
- // Set any tags on the instance server
- instanceServer.name = ismaster.me;
- instanceServer.tags = ismaster.tags;
-
- // Add the server to the list
- self._state.addServer(instanceServer, ismaster);
-
- // Check if we have more servers to add (only check when done with initial set)
- if(candidateServers.length == 0) {
- // Get additional new servers that are not currently in set
- var new_servers = locateNewServers(self, self._state, candidateServers, ismaster);
-
- // Locate any new servers that have not errored out yet
- for(var i = 0; i < new_servers.length; i++) {
- if(self._state.errors[new_servers[i].name] == null) {
- candidateServers.push(new_servers[i])
- }
- }
- }
- }
-
- // If the candidate server list is empty and no valid servers
- if(candidateServers.length == 0 &&
- !self._state.hasValidServers()) {
- return self.emit("connectionError", new Error("No valid replicaset instance servers found"));
- } else if(candidateServers.length == 0) {
- if(!self.options.connectWithNoPrimary && (self._state.master == null || !self._state.master.isConnected())) {
- return self.emit("connectionError", new Error("No primary found in set"));
- }
- return self.emit("fullsetup", null, self.options.db, self);
- }
-
- // Let's connect the next server
- var nextServer = candidateServers.pop();
-
- // Set up the options
- var opts = {
- returnIsMasterResults: true,
- eventReceiver: nextServer
- }
-
- // Attempt to connect to the server
- nextServer.connect(self.options.db, opts, _connectHandler(self, candidateServers, nextServer));
- }
-}
-
-ReplSet.prototype.isDestroyed = function() {
- return this._serverState == ReplSet.REPLSET_DESTROYED;
-}
-
-ReplSet.prototype.isConnected = function(read) {
- var isConnected = false;
-
- if(read == null || read == ReadPreference.PRIMARY || read == false)
- isConnected = this._state.master != null && this._state.master.isConnected();
-
- if((read == ReadPreference.PRIMARY_PREFERRED || read == ReadPreference.SECONDARY_PREFERRED || read == ReadPreference.NEAREST)
- && ((this._state.master != null && this._state.master.isConnected())
- || (this._state && this._state.secondaries && Object.keys(this._state.secondaries).length > 0))) {
- isConnected = true;
- } else if(read == ReadPreference.SECONDARY) {
- isConnected = this._state && this._state.secondaries && Object.keys(this._state.secondaries).length > 0;
- }
-
- // No valid connection return false
- return isConnected;
-}
-
-ReplSet.prototype.isMongos = function() {
- return false;
-}
-
-ReplSet.prototype.checkoutWriter = function() {
- if(this._state.master) return this._state.master.checkoutWriter();
- return new Error("no writer connection available");
-}
-
-ReplSet.prototype.processIsMaster = function(_server, _ismaster) {
- // Server in recovery mode, remove it from available servers
- if(!_ismaster.ismaster && !_ismaster.secondary) {
- // Locate the actual server
- var server = this._state.addresses[_server.name];
- // Close the server, simulating the closing of the connection
- // to get right removal semantics
- if(server) server.close();
- // Execute any callback errors
- _handler(null, this, server)(new Error("server is in recovery mode"));
- }
-}
-
-ReplSet.prototype.allRawConnections = function() {
- var connections = [];
-
- for(var name in this._state.addresses) {
- connections = connections.concat(this._state.addresses[name].allRawConnections());
- }
-
- return connections;
-}
-
-/**
- * @ignore
- */
-ReplSet.prototype.allServerInstances = function() {
- var self = this;
- // If no state yet return empty
- if(!self._state) return [];
- // Close all the servers (concatenate entire list of servers first for ease)
- var allServers = self._state.master != null ? [self._state.master] : [];
-
- // Secondary keys
- var keys = Object.keys(self._state.secondaries);
- // Add all secondaries
- for(var i = 0; i < keys.length; i++) {
- allServers.push(self._state.secondaries[keys[i]]);
- }
-
- // Return complete list of all servers
- return allServers;
-}
-
-/**
- * @ignore
- */
-ReplSet.prototype.checkoutReader = function(readPreference, tags) {
- var connection = null;
-
- // If we have a read preference object unpack it
- if(typeof readPreference == 'object' && readPreference['_type'] == 'ReadPreference') {
- // Validate if the object is using a valid mode
- if(!readPreference.isValid()) throw new Error("Illegal readPreference mode specified, " + JSON.stringify(readPreference.mode));
- // Set the tag
- tags = readPreference.tags;
- readPreference = readPreference.mode;
- } else if(typeof readPreference == 'object' && readPreference['_type'] != 'ReadPreference') {
- return new Error("read preferences must be either a string or an instance of ReadPreference");
- }
-
- // Set up our read Preference, allowing us to override the readPreference
- var finalReadPreference = readPreference != null ? readPreference : this.options.readPreference;
-
- // Ensure we unpack a reference
- if(finalReadPreference != null && typeof finalReadPreference == 'object' && finalReadPreference['_type'] == 'ReadPreference') {
- // Validate if the object is using a valid mode
- if(!finalReadPreference.isValid()) throw new Error("Illegal readPreference mode specified, " + JSON.stringify(finalReadPreference.mode));
- // Set the tag
- tags = finalReadPreference.tags;
- readPreference = finalReadPreference.mode;
- }
-
- // Finalize the read preference setup
- finalReadPreference = finalReadPreference == true ? ReadPreference.SECONDARY_PREFERRED : finalReadPreference;
- finalReadPreference = finalReadPreference == null ? ReadPreference.PRIMARY : finalReadPreference;
-
- // If we are reading from a primary
- if(finalReadPreference == 'primary') {
- // If we provide a tags set send an error
- if(typeof tags == 'object' && tags != null) {
- return new Error("PRIMARY cannot be combined with tags");
- }
-
- // If we provide a tags set send an error
- if(this._state.master == null) {
- return new Error("No replica set primary available for query with ReadPreference PRIMARY");
- }
-
- // Checkout a writer
- return this.checkoutWriter();
- }
-
- // If we have specified to read from a secondary server grab a random one and read
- // from it, otherwise just pass the primary connection
- if((this.options.readSecondary || finalReadPreference == ReadPreference.SECONDARY_PREFERRED || finalReadPreference == ReadPreference.SECONDARY) && Object.keys(this._state.secondaries).length > 0) {
- // If we have tags, look for servers matching the specific tag
- if(this.strategyInstance != null) {
- // Only pick from secondaries
- var _secondaries = [];
- for(var key in this._state.secondaries) {
- _secondaries.push(this._state.secondaries[key]);
- }
-
- if(finalReadPreference == ReadPreference.SECONDARY) {
- // Check out the nearest from only the secondaries
- connection = this.strategyInstance.checkoutConnection(tags, _secondaries);
- } else {
- connection = this.strategyInstance.checkoutConnection(tags, _secondaries);
- // No candidate servers that match the tags, error
- if(connection == null || connection instanceof Error) {
- // No secondary server avilable, attemp to checkout a primary server
- connection = this.checkoutWriter();
- // If no connection return an error
- if(connection == null || connection instanceof Error) {
- return new Error("No replica set members available for query");
- }
- }
- }
- } else if(tags != null && typeof tags == 'object') {
- // Get connection
- connection = _pickFromTags(this, tags);// = function(self, readPreference, tags) {
- // No candidate servers that match the tags, error
- if(connection == null) {
- return new Error("No replica set members available for query");
- }
- } else {
- connection = _roundRobin(this, tags);
- }
- } else if(finalReadPreference == ReadPreference.PRIMARY_PREFERRED) {
- // Check if there is a primary available and return that if possible
- connection = this.checkoutWriter();
- // If no connection available checkout a secondary
- if(connection == null || connection instanceof Error) {
- // If we have tags, look for servers matching the specific tag
- if(tags != null && typeof tags == 'object') {
- // Get connection
- connection = _pickFromTags(this, tags);// = function(self, readPreference, tags) {
- // No candidate servers that match the tags, error
- if(connection == null) {
- return new Error("No replica set members available for query");
- }
- } else {
- connection = _roundRobin(this, tags);
- }
- }
- } else if(finalReadPreference == ReadPreference.SECONDARY_PREFERRED) {
- // If we have tags, look for servers matching the specific tag
- if(this.strategyInstance != null) {
- connection = this.strategyInstance.checkoutConnection(tags);
-
- // No candidate servers that match the tags, error
- if(connection == null || connection instanceof Error) {
- // No secondary server avilable, attemp to checkout a primary server
- connection = this.checkoutWriter();
- // If no connection return an error
- if(connection == null || connection instanceof Error) {
- var preferenceName = finalReadPreference == ReadPreference.SECONDARY ? 'secondary' : finalReadPreference;
- return new Error("No replica set member available for query with ReadPreference " + preferenceName + " and tags " + JSON.stringify(tags));
- }
- }
- } else if(tags != null && typeof tags == 'object') {
- // Get connection
- connection = _pickFromTags(this, tags);// = function(self, readPreference, tags) {
- // No candidate servers that match the tags, error
- if(connection == null) {
- // No secondary server avilable, attemp to checkout a primary server
- connection = this.checkoutWriter();
- // If no connection return an error
- if(connection == null || connection instanceof Error) {
- var preferenceName = finalReadPreference == ReadPreference.SECONDARY ? 'secondary' : finalReadPreference;
- return new Error("No replica set member available for query with ReadPreference " + preferenceName + " and tags " + JSON.stringify(tags));
- }
- }
- }
- } else if(finalReadPreference == ReadPreference.NEAREST && this.strategyInstance != null) {
- connection = this.strategyInstance.checkoutConnection(tags);
- } else if(finalReadPreference == ReadPreference.NEAREST && this.strategyInstance == null) {
- return new Error("A strategy for calculating nearness must be enabled such as ping or statistical");
- } else if(finalReadPreference == ReadPreference.SECONDARY && Object.keys(this._state.secondaries).length == 0) {
- if(tags != null && typeof tags == 'object') {
- var preferenceName = finalReadPreference == ReadPreference.SECONDARY ? 'secondary' : finalReadPreference;
- return new Error("No replica set member available for query with ReadPreference " + preferenceName + " and tags " + JSON.stringify(tags));
- } else {
- return new Error("No replica set secondary available for query with ReadPreference SECONDARY");
- }
- } else {
- connection = this.checkoutWriter();
- }
-
- // Return the connection
- return connection;
-}
-
-/**
- * @ignore
- */
-var _pickFromTags = function(self, tags) {
- // If we have an array or single tag selection
- var tagObjects = Array.isArray(tags) ? tags : [tags];
- // Iterate over all tags until we find a candidate server
- for(var _i = 0; _i < tagObjects.length; _i++) {
- // Grab a tag object
- var tagObject = tagObjects[_i];
- // Matching keys
- var matchingKeys = Object.keys(tagObject);
- // Match all the servers that match the provdided tags
- var keys = Object.keys(self._state.secondaries);
- var candidateServers = [];
-
- for(var i = 0; i < keys.length; i++) {
- var server = self._state.secondaries[keys[i]];
- // If we have tags match
- if(server.tags != null) {
- var matching = true;
- // Ensure we have all the values
- for(var j = 0; j < matchingKeys.length; j++) {
- if(server.tags[matchingKeys[j]] != tagObject[matchingKeys[j]]) {
- matching = false;
- break;
- }
- }
-
- // If we have a match add it to the list of matching servers
- if(matching) {
- candidateServers.push(server);
- }
- }
- }
-
- // If we have a candidate server return
- if(candidateServers.length > 0) {
- if(self.strategyInstance) return self.strategyInstance.checkoutConnection(tags, candidateServers);
- // Set instance to return
- return candidateServers[Math.floor(Math.random() * candidateServers.length)].checkoutReader();
- }
- }
-
- // No connection found
- return null;
-}
-
-/**
- * Pick a secondary using round robin
- *
- * @ignore
- */
-function _roundRobin (replset, tags) {
- var keys = Object.keys(replset._state.secondaries);
- // Update index
- replset._currentServerChoice = replset._currentServerChoice + 1;
- // Pick a server
- var key = keys[replset._currentServerChoice % keys.length];
-
- var conn = null != replset._state.secondaries[key]
- ? replset._state.secondaries[key].checkoutReader()
- : null;
-
- // If connection is null fallback to first available secondary
- if(null == conn) {
- conn = pickFirstConnectedSecondary(replset, tags);
- }
-
- return conn;
-}
-
-/**
- * @ignore
- */
-var pickFirstConnectedSecondary = function pickFirstConnectedSecondary(self, tags) {
- var keys = Object.keys(self._state.secondaries);
- var connection;
-
- // Find first available reader if any
- for(var i = 0; i < keys.length; i++) {
- connection = self._state.secondaries[keys[i]].checkoutReader();
- if(connection) return connection;
- }
-
- // If we still have a null, read from primary if it's not secondary only
- if(self._readPreference == ReadPreference.SECONDARY_PREFERRED) {
- connection = self._state.master.checkoutReader();
- if(connection) return connection;
- }
-
- var preferenceName = self._readPreference == ReadPreference.SECONDARY_PREFERRED
- ? 'secondary'
- : self._readPreference;
-
- return new Error("No replica set member available for query with ReadPreference "
- + preferenceName + " and tags " + JSON.stringify(tags));
-}
-
-/**
- * Get list of secondaries
- * @ignore
- */
-Object.defineProperty(ReplSet.prototype, "secondaries", {enumerable: true
- , get: function() {
- return utils.objectToArray(this._state.secondaries);
- }
-});
-
-/**
- * Get list of secondaries
- * @ignore
- */
-Object.defineProperty(ReplSet.prototype, "arbiters", {enumerable: true
- , get: function() {
- return utils.objectToArray(this._state.arbiters);
- }
-});
-
diff --git a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/repl_set/repl_set_state.js b/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/repl_set/repl_set_state.js
deleted file mode 100644
index 1fbd9c0..0000000
--- a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/repl_set/repl_set_state.js
+++ /dev/null
@@ -1,74 +0,0 @@
-/**
- * Interval state object constructor
- *
- * @ignore
- */
-var ReplSetState = function ReplSetState (replset) {
- this.errorMessages = [];
- this.secondaries = {};
- this.addresses = {};
- this.arbiters = {};
- this.passives = {};
- this.members = [];
- this.errors = {};
- this.setName = null;
- this.master = null;
- this.replset = replset;
-}
-
-ReplSetState.prototype.hasValidServers = function() {
- var validServers = [];
- if(this.master && this.master.isConnected()) return true;
-
- if(this.secondaries) {
- var keys = Object.keys(this.secondaries)
- for(var i = 0; i < keys.length; i++) {
- if(this.secondaries[keys[i]].isConnected())
- return true;
- }
- }
-
- return false;
-}
-
-ReplSetState.prototype.getAllReadServers = function() {
- var candidate_servers = [];
- for(var name in this.addresses) {
- candidate_servers.push(this.addresses[name]);
- }
-
- // Return all possible read candidates
- return candidate_servers;
-}
-
-ReplSetState.prototype.addServer = function(server, master) {
- server.name = master.me;
-
- if(master.ismaster) {
- this.master = server;
- this.addresses[server.name] = server;
- this.replset.emit('joined', "primary", master, server);
- } else if(master.secondary) {
- this.secondaries[server.name] = server;
- this.addresses[server.name] = server;
- this.replset.emit('joined', "secondary", master, server);
- } else if(master.arbiters) {
- this.arbiters[server.name] = server;
- this.addresses[server.name] = server;
- this.replset.emit('joined', "arbiter", master, server);
- }
-}
-
-ReplSetState.prototype.contains = function(host) {
- return this.addresses[host] != null;
-}
-
-ReplSetState.prototype.isPrimary = function(server) {
- return this.master && this.master.name == server.name;
-}
-
-ReplSetState.prototype.isSecondary = function(server) {
- return this.secondaries[server.name] != null;
-}
-
-exports.ReplSetState = ReplSetState;
diff --git a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/repl_set/strategies/ping_strategy.js b/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/repl_set/strategies/ping_strategy.js
deleted file mode 100644
index 7e2a6c9..0000000
--- a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/repl_set/strategies/ping_strategy.js
+++ /dev/null
@@ -1,366 +0,0 @@
-var Server = require("../../server").Server
- , format = require('util').format;
-
-// The ping strategy uses pings each server and records the
-// elapsed time for the server so it can pick a server based on lowest
-// return time for the db command {ping:true}
-var PingStrategy = exports.PingStrategy = function(replicaset, secondaryAcceptableLatencyMS) {
- this.replicaset = replicaset;
- this.secondaryAcceptableLatencyMS = secondaryAcceptableLatencyMS;
- this.state = 'disconnected';
- // Interval of ping attempts
- this.pingInterval = replicaset.options.socketOptions.pingInterval || 5000;
- // Timeout for ping response, default - no timeout
- this.pingTimeout = replicaset.options.socketOptions.pingTimeout || null;
- // Class instance
- this.Db = require("../../../db").Db;
- // Active db connections
- this.dbs = {};
- // Current server index
- this.index = 0;
- // Logger api
- this.Logger = null;
-}
-
-// Starts any needed code
-PingStrategy.prototype.start = function(callback) {
- // already running?
- if ('connected' == this.state) return;
-
- this.state = 'connected';
-
- // Start ping server
- this._pingServer(callback);
-}
-
-// Stops and kills any processes running
-PingStrategy.prototype.stop = function(callback) {
- // Stop the ping process
- this.state = 'disconnected';
-
- // Stop all the server instances
- for(var key in this.dbs) {
- this.dbs[key].close();
- }
-
- // optional callback
- callback && callback(null, null);
-}
-
-PingStrategy.prototype.checkoutConnection = function(tags, secondaryCandidates) {
- // Servers are picked based on the lowest ping time and then servers that lower than that + secondaryAcceptableLatencyMS
- // Create a list of candidat servers, containing the primary if available
- var candidateServers = [];
- var self = this;
-
- // If we have not provided a list of candidate servers use the default setup
- if(!Array.isArray(secondaryCandidates)) {
- candidateServers = this.replicaset._state.master != null ? [this.replicaset._state.master] : [];
- // Add all the secondaries
- var keys = Object.keys(this.replicaset._state.secondaries);
- for(var i = 0; i < keys.length; i++) {
- candidateServers.push(this.replicaset._state.secondaries[keys[i]])
- }
- } else {
- candidateServers = secondaryCandidates;
- }
-
- // Final list of eligable server
- var finalCandidates = [];
-
- // If we have tags filter by tags
- if(tags != null && typeof tags == 'object') {
- // If we have an array or single tag selection
- var tagObjects = Array.isArray(tags) ? tags : [tags];
- // Iterate over all tags until we find a candidate server
- for(var _i = 0; _i < tagObjects.length; _i++) {
- // Grab a tag object
- var tagObject = tagObjects[_i];
- // Matching keys
- var matchingKeys = Object.keys(tagObject);
- // Remove any that are not tagged correctly
- for(var i = 0; i < candidateServers.length; i++) {
- var server = candidateServers[i];
- // If we have tags match
- if(server.tags != null) {
- var matching = true;
-
- // Ensure we have all the values
- for(var j = 0; j < matchingKeys.length; j++) {
- if(server.tags[matchingKeys[j]] != tagObject[matchingKeys[j]]) {
- matching = false;
- break;
- }
- }
-
- // If we have a match add it to the list of matching servers
- if(matching) {
- finalCandidates.push(server);
- }
- }
- }
- }
- } else {
- // Final array candidates
- var finalCandidates = candidateServers;
- }
-
- // Filter out any non-connected servers
- finalCandidates = finalCandidates.filter(function(s) {
- return s.isConnected();
- })
-
- // Sort by ping time
- finalCandidates.sort(function(a, b) {
- return a.runtimeStats['pingMs'] > b.runtimeStats['pingMs'];
- });
-
- if(0 === finalCandidates.length)
- return new Error("No replica set members available for query");
-
- // find lowest server with a ping time
- var lowest = finalCandidates.filter(function (server) {
- return undefined != server.runtimeStats.pingMs;
- })[0];
-
- if(!lowest) {
- lowest = finalCandidates[0];
- }
-
- // convert to integer
- var lowestPing = lowest.runtimeStats.pingMs | 0;
-
- // determine acceptable latency
- var acceptable = lowestPing + this.secondaryAcceptableLatencyMS;
-
- // remove any server responding slower than acceptable
- var len = finalCandidates.length;
- while(len--) {
- if(finalCandidates[len].runtimeStats['pingMs'] > acceptable) {
- finalCandidates.splice(len, 1);
- }
- }
-
- if(self.logger && self.logger.debug) {
- self.logger.debug("Ping strategy selection order for tags", tags);
- finalCandidates.forEach(function(c) {
- self.logger.debug(format("%s:%s = %s ms", c.host, c.port, c.runtimeStats['pingMs']), null);
- })
- }
-
- // If no candidates available return an error
- if(finalCandidates.length == 0)
- return new Error("No replica set members available for query");
-
- // Ensure no we don't overflow
- this.index = this.index % finalCandidates.length
- // Pick a random acceptable server
- var connection = finalCandidates[this.index].checkoutReader();
- // Point to next candidate (round robin style)
- this.index = this.index + 1;
-
- if(self.logger && self.logger.debug) {
- if(connection)
- self.logger.debug(format("picked server %s:%s", connection.socketOptions.host, connection.socketOptions.port));
- }
-
- return connection;
-}
-
-PingStrategy.prototype._pingServer = function(callback) {
- var self = this;
-
- // Ping server function
- var pingFunction = function() {
- // Our state changed to disconnected or destroyed return
- if(self.state == 'disconnected' || self.state == 'destroyed') return;
- // If the replicaset is destroyed return
- if(self.replicaset.isDestroyed() || self.replicaset._serverState == 'disconnected') return
-
- // Create a list of all servers we can send the ismaster command to
- var allServers = self.replicaset._state.master != null ? [self.replicaset._state.master] : [];
-
- // Secondary keys
- var keys = Object.keys(self.replicaset._state.secondaries);
- // Add all secondaries
- for(var i = 0; i < keys.length; i++) {
- allServers.push(self.replicaset._state.secondaries[keys[i]]);
- }
-
- // Number of server entries
- var numberOfEntries = allServers.length;
-
- // We got keys
- for(var i = 0; i < allServers.length; i++) {
-
- // We got a server instance
- var server = allServers[i];
-
- // Create a new server object, avoid using internal connections as they might
- // be in an illegal state
- new function(serverInstance) {
- var _db = self.dbs[serverInstance.host + ":" + serverInstance.port];
- // If we have a db
- if(_db != null) {
- // Startup time of the command
- var startTime = Date.now();
-
- // Execute ping command in own scope
- var _ping = function(__db, __serverInstance) {
-
- // Server unavailable. Checks only if pingTimeout defined & greater than 0
- var _failTimer = self.pingTimeout ? setTimeout(function () {
- if(null != __serverInstance.runtimeStats && __serverInstance.isConnected()) {
- __serverInstance.close();
- }
- }, self.pingTimeout) : null;
-
- // Execute ping on this connection
- __db.executeDbCommand({ping:1}, {failFast:true}, function(err) {
-
- // Server available
- clearTimeout(_failTimer);
-
- // Emit the ping
- self.replicaset.emit("ping", err, serverInstance);
-
- if(err) {
- delete self.dbs[__db.serverConfig.host + ":" + __db.serverConfig.port];
- __db.close();
- return done();
- }
-
- if(null != __serverInstance.runtimeStats && __serverInstance.isConnected()) {
- __serverInstance.runtimeStats['pingMs'] = Date.now() - startTime;
- }
-
- __db.executeDbCommand({ismaster:1}, {failFast:true}, function(err, result) {
- // Emit the ping
- self.replicaset.emit("ping_ismaster", err, result, serverInstance);
-
- if(err) {
- delete self.dbs[__db.serverConfig.host + ":" + __db.serverConfig.port];
- __db.close();
- return done();
- }
-
- // Process the ismaster for the server
- if(result && result.documents && self.replicaset.processIsMaster) {
- self.replicaset.processIsMaster(__serverInstance, result.documents[0]);
- }
-
- // Done with the pinging
- done();
- });
- });
- };
- // Ping
- _ping(_db, serverInstance);
- } else {
- var connectTimeoutMS = self.replicaset.options.socketOptions
- ? self.replicaset.options.socketOptions.connectTimeoutMS : 0
-
- // Create a new master connection
- var _server = new Server(serverInstance.host, serverInstance.port, {
- auto_reconnect: false,
- returnIsMasterResults: true,
- slaveOk: true,
- poolSize: 1,
- socketOptions: { connectTimeoutMS: connectTimeoutMS },
- ssl: self.replicaset.options.ssl,
- sslValidate: self.replicaset.options.sslValidate,
- sslCA: self.replicaset.options.sslCA,
- sslCert: self.replicaset.options.sslCert,
- sslKey: self.replicaset.options.sslKey,
- sslPass: self.replicaset.options.sslPass
- });
-
- // Create Db instance
- var _db = new self.Db('local', _server, { safe: true });
- _db.on("close", function() {
- delete self.dbs[this.serverConfig.host + ":" + this.serverConfig.port];
- })
-
- var _ping = function(__db, __serverInstance) {
- if(self.state == 'disconnected') {
- self.stop();
- return;
- }
-
- __db.open(function(err, db) {
- // Emit ping connect
- self.replicaset.emit("ping_connect", err, __serverInstance);
-
- if(self.state == 'disconnected' && __db != null) {
- return __db.close();
- }
-
- if(err) {
- delete self.dbs[__db.serverConfig.host + ":" + __db.serverConfig.port];
- __db.close();
- return done();
- }
-
- // Save instance
- self.dbs[__db.serverConfig.host + ":" + __db.serverConfig.port] = __db;
-
- // Startup time of the command
- var startTime = Date.now();
-
- // Execute ping on this connection
- __db.executeDbCommand({ping:1}, {failFast:true}, function(err) {
- self.replicaset.emit("ping", err, __serverInstance);
-
- if(err) {
- delete self.dbs[__db.serverConfig.host + ":" + __db.serverConfig.port];
- __db.close();
- return done();
- }
-
- if(null != __serverInstance.runtimeStats && __serverInstance.isConnected()) {
- __serverInstance.runtimeStats['pingMs'] = Date.now() - startTime;
- }
-
- __db.executeDbCommand({ismaster:1}, {failFast:true}, function(err, result) {
- self.replicaset.emit("ping_ismaster", err, result, __serverInstance);
-
- if(err) {
- delete self.dbs[__db.serverConfig.host + ":" + __db.serverConfig.port];
- __db.close();
- return done();
- }
-
- // Process the ismaster for the server
- if(result && result.documents && self.replicaset.processIsMaster) {
- self.replicaset.processIsMaster(__serverInstance, result.documents[0]);
- }
-
- // Done with the pinging
- done();
- });
- });
- });
- };
-
- // Ping the server
- _ping(_db, serverInstance);
- }
-
- function done() {
- // Adjust the number of checks
- numberOfEntries--;
-
- // If we are done with all results coming back trigger ping again
- if(0 === numberOfEntries && 'connected' == self.state) {
- setTimeout(pingFunction, self.pingInterval);
- }
- }
- }(server);
- }
- }
-
- // Start pingFunction
- pingFunction();
-
- callback && callback(null);
-}
diff --git a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/repl_set/strategies/statistics_strategy.js b/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/repl_set/strategies/statistics_strategy.js
deleted file mode 100644
index 32d23c3..0000000
--- a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/repl_set/strategies/statistics_strategy.js
+++ /dev/null
@@ -1,93 +0,0 @@
-// The Statistics strategy uses the measure of each end-start time for each
-// query executed against the db to calculate the mean, variance and standard deviation
-// and pick the server which the lowest mean and deviation
-var StatisticsStrategy = exports.StatisticsStrategy = function(replicaset) {
- this.replicaset = replicaset;
- // Logger api
- this.Logger = null;
-}
-
-// Starts any needed code
-StatisticsStrategy.prototype.start = function(callback) {
- callback && callback(null, null);
-}
-
-StatisticsStrategy.prototype.stop = function(callback) {
- callback && callback(null, null);
-}
-
-StatisticsStrategy.prototype.checkoutConnection = function(tags, secondaryCandidates) {
- // Servers are picked based on the lowest ping time and then servers that lower than that + secondaryAcceptableLatencyMS
- // Create a list of candidat servers, containing the primary if available
- var candidateServers = [];
-
- // If we have not provided a list of candidate servers use the default setup
- if(!Array.isArray(secondaryCandidates)) {
- candidateServers = this.replicaset._state.master != null ? [this.replicaset._state.master] : [];
- // Add all the secondaries
- var keys = Object.keys(this.replicaset._state.secondaries);
- for(var i = 0; i < keys.length; i++) {
- candidateServers.push(this.replicaset._state.secondaries[keys[i]])
- }
- } else {
- candidateServers = secondaryCandidates;
- }
-
- // Final list of eligable server
- var finalCandidates = [];
-
- // If we have tags filter by tags
- if(tags != null && typeof tags == 'object') {
- // If we have an array or single tag selection
- var tagObjects = Array.isArray(tags) ? tags : [tags];
- // Iterate over all tags until we find a candidate server
- for(var _i = 0; _i < tagObjects.length; _i++) {
- // Grab a tag object
- var tagObject = tagObjects[_i];
- // Matching keys
- var matchingKeys = Object.keys(tagObject);
- // Remove any that are not tagged correctly
- for(var i = 0; i < candidateServers.length; i++) {
- var server = candidateServers[i];
- // If we have tags match
- if(server.tags != null) {
- var matching = true;
-
- // Ensure we have all the values
- for(var j = 0; j < matchingKeys.length; j++) {
- if(server.tags[matchingKeys[j]] != tagObject[matchingKeys[j]]) {
- matching = false;
- break;
- }
- }
-
- // If we have a match add it to the list of matching servers
- if(matching) {
- finalCandidates.push(server);
- }
- }
- }
- }
- } else {
- // Final array candidates
- var finalCandidates = candidateServers;
- }
-
- finalCandidates.sort(function(a, b) {
- return a.runtimeStats.queryStats.sScore > b.runtimeStats.queryStats.sScore;
- });
-
- // If no candidates available return an error
- if(finalCandidates.length == 0) return new Error("No replica set members available for query");
-
- var bestCandidates = [finalCandidates[0]];
- for (var i = 1; i < finalCandidates.length; ++i) {
- if (finalCandidates[i].runtimeStats.queryStats.sScore > finalCandidates[i - 1].runtimeStats.queryStats.sScore) {
- break;
- } else {
- bestCandidates.push(finalCandidates[i]);
- }
- }
-
- return bestCandidates[Math.floor(Math.random() * bestCandidates.length)].checkoutReader();
-}
diff --git a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/server.js b/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/server.js
deleted file mode 100644
index dfff183..0000000
--- a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/server.js
+++ /dev/null
@@ -1,945 +0,0 @@
-var Connection = require('./connection').Connection,
- ReadPreference = require('./read_preference').ReadPreference,
- DbCommand = require('../commands/db_command').DbCommand,
- MongoReply = require('../responses/mongo_reply').MongoReply,
- ConnectionPool = require('./connection_pool').ConnectionPool,
- EventEmitter = require('events').EventEmitter,
- ServerCapabilities = require('./server_capabilities').ServerCapabilities,
- Base = require('./base').Base,
- format = require('util').format,
- utils = require('../utils'),
- timers = require('timers'),
- inherits = require('util').inherits;
-
-// Set processor, setImmediate if 0.10 otherwise nextTick
-var processor = require('../utils').processor();
-
-/**
- * Class representing a single MongoDB Server connection
- *
- * Options
- * - **ssl** {Boolean, default:false}, use ssl connection (needs to have a mongod server with ssl support)
- * - **sslValidate** {Boolean, default:false}, validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher)
- * - **sslCA** {Array, default:null}, Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher)
- * - **sslCert** {Buffer/String, default:null}, String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher)
- * - **sslKey** {Buffer/String, default:null}, String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher)
- * - **sslPass** {Buffer/String, default:null}, String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher)
- * - **poolSize** {Number, default:5}, number of connections in the connection pool, set to 5 as default for legacy reasons.
- * - **socketOptions** {Object, default:null}, an object containing socket options to use (noDelay:(boolean), keepAlive:(number), connectTimeoutMS:(number), socketTimeoutMS:(number))
- * - **logger** {Object, default:null}, an object representing a logger that you want to use, needs to support functions debug, log, error **({error:function(message, object) {}, log:function(message, object) {}, debug:function(message, object) {}})**.
- * - **auto_reconnect** {Boolean, default:false}, reconnect on error.
- * - **disableDriverBSONSizeCheck** {Boolean, default:false}, force the server to error if the BSON message is to big
- *
- * @class Represents a Server connection.
- * @param {String} host the server host
- * @param {Number} port the server port
- * @param {Object} [options] optional options for insert command
- */
-function Server(host, port, options) {
- // Set up Server instance
- if(!(this instanceof Server)) return new Server(host, port, options);
-
- // Set up event emitter
- Base.call(this);
-
- // Ensure correct values
- if(port != null && typeof port == 'object') {
- options = port;
- port = Connection.DEFAULT_PORT;
- }
-
- var self = this;
- this.host = host;
- this.port = port;
- this.options = options == null ? {} : options;
- this.internalConnection;
- this.internalMaster = false;
- this.connected = false;
- this.poolSize = this.options.poolSize == null ? 5 : this.options.poolSize;
- this.disableDriverBSONSizeCheck = this.options.disableDriverBSONSizeCheck != null ? this.options.disableDriverBSONSizeCheck : false;
- this._used = false;
- this.replicasetInstance = null;
-
- // Emit open setup
- this.emitOpen = this.options.emitOpen || true;
- // Set ssl as connection method
- this.ssl = this.options.ssl == null ? false : this.options.ssl;
- // Set ssl validation
- this.sslValidate = this.options.sslValidate == null ? false : this.options.sslValidate;
- // Set the ssl certificate authority (array of Buffer/String keys)
- this.sslCA = Array.isArray(this.options.sslCA) ? this.options.sslCA : null;
- // Certificate to present to the server
- this.sslCert = this.options.sslCert;
- // Certificate private key if in separate file
- this.sslKey = this.options.sslKey;
- // Password to unlock private key
- this.sslPass = this.options.sslPass;
- // Server capabilities
- this.serverCapabilities = null;
- // Set server name
- this.name = format("%s:%s", host, port);
-
- // Ensure we are not trying to validate with no list of certificates
- if(this.sslValidate && (!Array.isArray(this.sslCA) || this.sslCA.length == 0)) {
- throw new Error("The driver expects an Array of CA certificates in the sslCA parameter when enabling sslValidate");
- }
-
- // Contains the isMaster information returned from the server
- this.isMasterDoc;
-
- // Set default connection pool options
- this.socketOptions = this.options.socketOptions != null ? this.options.socketOptions : {};
- if(this.disableDriverBSONSizeCheck) this.socketOptions.disableDriverBSONSizeCheck = this.disableDriverBSONSizeCheck;
-
- // Set ssl up if it's defined
- if(this.ssl) {
- this.socketOptions.ssl = true;
- // Set ssl validation
- this.socketOptions.sslValidate = this.sslValidate == null ? false : this.sslValidate;
- // Set the ssl certificate authority (array of Buffer/String keys)
- this.socketOptions.sslCA = Array.isArray(this.sslCA) ? this.sslCA : null;
- // Set certificate to present
- this.socketOptions.sslCert = this.sslCert;
- // Set certificate to present
- this.socketOptions.sslKey = this.sslKey;
- // Password to unlock private key
- this.socketOptions.sslPass = this.sslPass;
- }
-
- // Set up logger if any set
- this.logger = this.options.logger != null
- && (typeof this.options.logger.debug == 'function')
- && (typeof this.options.logger.error == 'function')
- && (typeof this.options.logger.log == 'function')
- ? this.options.logger : {error:function(message, object) {}, log:function(message, object) {}, debug:function(message, object) {}};
-
- // Just keeps list of events we allow
- this.eventHandlers = {error:[], parseError:[], poolReady:[], message:[], close:[], timeout:[]};
- // Internal state of server connection
- this._serverState = 'disconnected';
- // Contains state information about server connection
- this._state = {'runtimeStats': {'queryStats':new RunningStats()}};
- // Do we record server stats or not
- this.recordQueryStats = false;
-
- // Allow setting the socketTimeoutMS on all connections
- // to work around issues such as secondaries blocking due to compaction
- utils.setSocketTimeoutProperty(this, this.socketOptions);
-};
-
-/**
- * @ignore
- */
-inherits(Server, Base);
-
-//
-// Deprecated, USE ReadPreferences class
-//
-Server.READ_PRIMARY = ReadPreference.PRIMARY;
-Server.READ_SECONDARY = ReadPreference.SECONDARY_PREFERRED;
-Server.READ_SECONDARY_ONLY = ReadPreference.SECONDARY;
-
-/**
- * Always ourselves
- * @ignore
- */
-Server.prototype.setReadPreference = function(readPreference) {
- this._readPreference = readPreference;
-}
-
-/**
- * @ignore
- */
-Server.prototype.isMongos = function() {
- return this.isMasterDoc != null && this.isMasterDoc['msg'] == "isdbgrid" ? true : false;
-}
-
-/**
- * @ignore
- */
-Server.prototype._isUsed = function() {
- return this._used;
-}
-
-/**
- * @ignore
- */
-Server.prototype.close = function(callback) {
- // Set server status as disconnected
- this._serverState = 'destroyed';
- // Remove all local listeners
- this.removeAllListeners();
-
- if(this.connectionPool != null) {
- // Remove all the listeners on the pool so it does not fire messages all over the place
- this.connectionPool.removeAllEventListeners();
- // Close the connection if it's open
- this.connectionPool.stop(true);
- }
-
- // Emit close event
- if(this.db && !this.isSetMember()) {
- var self = this;
- processor(function() {
- self._emitAcrossAllDbInstances(self, null, "close", null, null, true)
- })
-
- // Flush out any remaining call handlers
- self._flushAllCallHandlers(utils.toError("Connection Closed By Application"));
- }
-
- // Peform callback if present
- if(typeof callback === 'function') callback(null);
-};
-
-Server.prototype.isDestroyed = function() {
- return this._serverState == 'destroyed';
-}
-
-/**
- * @ignore
- */
-Server.prototype.isConnected = function() {
- return this.connectionPool != null && this.connectionPool.isConnected();
-}
-
-/**
- * @ignore
- */
-Server.prototype.canWrite = Server.prototype.isConnected;
-Server.prototype.canRead = Server.prototype.isConnected;
-
-Server.prototype.isAutoReconnect = function() {
- if(this.isSetMember()) return false;
- return this.options.auto_reconnect != null ? this.options.auto_reconnect : true;
-}
-
-/**
- * @ignore
- */
-Server.prototype.allServerInstances = function() {
- return [this];
-}
-
-/**
- * @ignore
- */
-Server.prototype.isSetMember = function() {
- return this.replicasetInstance != null || this.mongosInstance != null;
-}
-
-/**
- * @ignore
- */
-Server.prototype.setSocketOptions = function(options) {
- var connections = this.allRawConnections();
- for(var i = 0; i < connections.length; i++) {
- connections[i].setSocketOptions(options);
- }
-}
-
-/**
- * Assigns a replica set to this `server`.
- *
- * @param {ReplSet} replset
- * @ignore
- */
-Server.prototype.assignReplicaSet = function (replset) {
- this.replicasetInstance = replset;
- this.inheritReplSetOptionsFrom(replset);
- this.enableRecordQueryStats(replset.recordQueryStats);
-}
-
-/**
- * Takes needed options from `replset` and overwrites
- * our own options.
- *
- * @param {ReplSet} replset
- * @ignore
- */
-Server.prototype.inheritReplSetOptionsFrom = function (replset) {
- this.socketOptions = {};
- this.socketOptions.connectTimeoutMS = replset.options.socketOptions.connectTimeoutMS || 30000;
-
- if(replset.options.ssl) {
- // Set ssl on
- this.socketOptions.ssl = true;
- // Set ssl validation
- this.socketOptions.sslValidate = replset.options.sslValidate == null ? false : replset.options.sslValidate;
- // Set the ssl certificate authority (array of Buffer/String keys)
- this.socketOptions.sslCA = Array.isArray(replset.options.sslCA) ? replset.options.sslCA : null;
- // Set certificate to present
- this.socketOptions.sslCert = replset.options.sslCert;
- // Set certificate to present
- this.socketOptions.sslKey = replset.options.sslKey;
- // Password to unlock private key
- this.socketOptions.sslPass = replset.options.sslPass;
- }
-
- // If a socket option object exists clone it
- if(utils.isObject(replset.options.socketOptions)) {
- var keys = Object.keys(replset.options.socketOptions);
- for(var i = 0; i < keys.length; i++)
- this.socketOptions[keys[i]] = replset.options.socketOptions[keys[i]];
- }
-}
-
-/**
- * Opens this server connection.
- *
- * @ignore
- */
-Server.prototype.connect = function(dbInstance, options, callback) {
- if('function' === typeof options) callback = options, options = {};
- if(options == null) options = {};
- if(!('function' === typeof callback)) callback = null;
- var self = this;
- // Save the options
- this.options = options;
-
- // Currently needed to work around problems with multiple connections in a pool with ssl
- // TODO fix if possible
- if(this.ssl == true) {
- // Set up socket options for ssl
- this.socketOptions.ssl = true;
- // Set ssl validation
- this.socketOptions.sslValidate = this.sslValidate == null ? false : this.sslValidate;
- // Set the ssl certificate authority (array of Buffer/String keys)
- this.socketOptions.sslCA = Array.isArray(this.sslCA) ? this.sslCA : null;
- // Set certificate to present
- this.socketOptions.sslCert = this.sslCert;
- // Set certificate to present
- this.socketOptions.sslKey = this.sslKey;
- // Password to unlock private key
- this.socketOptions.sslPass = this.sslPass;
- }
-
- // Let's connect
- var server = this;
- // Let's us override the main receiver of events
- var eventReceiver = options.eventReceiver != null ? options.eventReceiver : this;
- // Save reference to dbInstance
- this.db = dbInstance; // `db` property matches ReplSet and Mongos
- this.dbInstances = [dbInstance];
-
- // Force connection pool if there is one
- if(server.connectionPool) server.connectionPool.stop();
- // Set server state to connecting
- this._serverState = 'connecting';
-
- if(server.connectionPool != null) {
- // Remove all the listeners on the pool so it does not fire messages all over the place
- this.connectionPool.removeAllEventListeners();
- // Close the connection if it's open
- this.connectionPool.stop(true);
- }
-
- this.connectionPool = new ConnectionPool(this.host, this.port, this.poolSize, dbInstance.bson, this.socketOptions);
- var connectionPool = this.connectionPool;
- // If ssl is not enabled don't wait between the pool connections
- if(this.ssl == null || !this.ssl) connectionPool._timeToWait = null;
- // Set logger on pool
- connectionPool.logger = this.logger;
- connectionPool.bson = dbInstance.bson;
-
- // Set basic parameters passed in
- var returnIsMasterResults = options.returnIsMasterResults == null ? false : options.returnIsMasterResults;
-
- // Create a default connect handler, overriden when using replicasets
- var connectCallback = function(_server) {
- return function(err, reply) {
- // ensure no callbacks get called twice
- var internalCallback = callback;
- callback = null;
-
- // Assign the server
- _server = _server != null ? _server : server;
-
- // If something close down the connection and removed the callback before
- // proxy killed connection etc, ignore the erorr as close event was isssued
- if(err != null && internalCallback == null) return;
- // Internal callback
- if(err != null) return internalCallback(err, null, _server);
- _server.master = reply.documents[0].ismaster == 1 ? true : false;
- _server.connectionPool.setMaxBsonSize(reply.documents[0].maxBsonObjectSize);
- _server.connectionPool.setMaxMessageSizeBytes(reply.documents[0].maxMessageSizeBytes);
- _server.connectionPool.setMaxWriteBatchSize(reply.documents[0].maxWriteBatchSize);
- // Set server state to connEcted
- _server._serverState = 'connected';
- // Set server as connected
- _server.connected = true;
- // Save document returned so we can query it
- _server.isMasterDoc = reply.documents[0];
-
- if(self.emitOpen) {
- _server._emitAcrossAllDbInstances(_server, eventReceiver, "open", null, returnIsMasterResults ? reply : null, null);
- self.emitOpen = false;
- } else {
- _server._emitAcrossAllDbInstances(_server, eventReceiver, "reconnect", null, returnIsMasterResults ? reply : null, null);
- }
-
- // Set server capabilities
- server.serverCapabilities = new ServerCapabilities(_server.isMasterDoc);
-
- // If we have it set to returnIsMasterResults
- if(returnIsMasterResults) {
- internalCallback(null, reply, _server);
- } else {
- internalCallback(null, dbInstance, _server);
- }
- }
- };
-
- // Let's us override the main connect callback
- var connectHandler = options.connectHandler == null ? connectCallback(server) : options.connectHandler;
-
- // Set up on connect method
- connectionPool.on("poolReady", function() {
- // Create db command and Add the callback to the list of callbacks by the request id (mapping outgoing messages to correct callbacks)
- var db_command = DbCommand.NcreateIsMasterCommand(dbInstance, dbInstance.databaseName);
- // Check out a reader from the pool
- var connection = connectionPool.checkoutConnection();
- // Register handler for messages
- server._registerHandler(db_command, false, connection, connectHandler);
- // Write the command out
- connection.write(db_command);
- })
-
- // Set up item connection
- connectionPool.on("message", function(message) {
- // Attempt to parse the message
- try {
- // Create a new mongo reply
- var mongoReply = new MongoReply()
- // Parse the header
- mongoReply.parseHeader(message, connectionPool.bson)
-
- // If message size is not the same as the buffer size
- // something went terribly wrong somewhere
- if(mongoReply.messageLength != message.length) {
- // Emit the error
- if(eventReceiver.listeners("error") && eventReceiver.listeners("error").length > 0) eventReceiver.emit("error", new Error("bson length is different from message length"), server);
- // Remove all listeners
- server.removeAllListeners();
- } else {
- var startDate = new Date().getTime();
-
- // Callback instance
- var callbackInfo = server._findHandler(mongoReply.responseTo.toString());
- // Abort if not a valid callbackInfo, don't try to call it
- if(callbackInfo == null || callbackInfo.info == null) return;
-
- // The command executed another request, log the handler again under that request id
- if(mongoReply.requestId > 0 && mongoReply.cursorId.toString() != "0"
- && callbackInfo && callbackInfo.info && callbackInfo.info.exhaust) {
- server._reRegisterHandler(mongoReply.requestId, callbackInfo);
- }
-
- // Parse the body
- mongoReply.parseBody(message, connectionPool.bson, callbackInfo.info.raw, function(err) {
- if(err != null) {
- // If pool connection is already closed
- if(server._serverState === 'disconnected') return;
- // Set server state to disconnected
- server._serverState = 'disconnected';
- // Remove all listeners and close the connection pool
- server.removeAllListeners();
- connectionPool.stop(true);
-
- // If we have a callback return the error
- if(typeof callback === 'function') {
- // ensure no callbacks get called twice
- var internalCallback = callback;
- callback = null;
- // Perform callback
- internalCallback(err, null, server);
- } else if(server.isSetMember()) {
- if(server.listeners("parseError") && server.listeners("parseError").length > 0) server.emit("parseError", utils.toError(err), server);
- } else {
- if(eventReceiver.listeners("parseError") && eventReceiver.listeners("parseError").length > 0) eventReceiver.emit("parseError", utils.toError(err), server);
- }
-
- // If we are a single server connection fire errors correctly
- if(!server.isSetMember()) {
- // Fire all callback errors
- server.__executeAllCallbacksWithError(err);
- // Emit error
- server._emitAcrossAllDbInstances(server, eventReceiver, "parseError", server, null, true);
- }
- // Short cut
- return;
- }
-
- // Let's record the stats info if it's enabled
- if(server.recordQueryStats == true && server._state['runtimeStats'] != null
- && server._state.runtimeStats['queryStats'] instanceof RunningStats) {
- // Add data point to the running statistics object
- server._state.runtimeStats.queryStats.push(new Date().getTime() - callbackInfo.info.start);
- }
-
- // Dispatch the call
- server._callHandler(mongoReply.responseTo, mongoReply, null);
-
- // If we have an error about the server not being master or primary
- if((mongoReply.responseFlag & (1 << 1)) != 0
- && mongoReply.documents[0].code
- && mongoReply.documents[0].code == 13436) {
- server.close();
- }
- });
- }
- } catch (err) {
- // Throw error in next tick
- processor(function() {
- throw err;
- })
- }
- });
-
- // Handle timeout
- connectionPool.on("timeout", function(err) {
- // If pool connection is already closed
- if(server._serverState === 'disconnected'
- || server._serverState === 'destroyed') return;
- // Set server state to disconnected
- server._serverState = 'disconnected';
- // If we have a callback return the error
- if(typeof callback === 'function') {
- // ensure no callbacks get called twice
- var internalCallback = callback;
- callback = null;
- // Perform callback
- internalCallback(err, null, server);
- } else if(server.isSetMember()) {
- if(server.listeners("timeout") && server.listeners("timeout").length > 0) server.emit("timeout", err, server);
- } else {
- if(eventReceiver.listeners("timeout") && eventReceiver.listeners("timeout").length > 0) eventReceiver.emit("timeout", err, server);
- }
-
- // If we are a single server connection fire errors correctly
- if(!server.isSetMember()) {
- // Fire all callback errors
- server.__executeAllCallbacksWithError(err);
- // Emit error
- server._emitAcrossAllDbInstances(server, eventReceiver, "timeout", err, server, true);
- }
-
- // If we have autoConnect enabled let's fire up an attempt to reconnect
- if(server.isAutoReconnect()
- && !server.isSetMember()
- && (server._serverState != 'destroyed')
- && !server._reconnectInProgreess) {
- // Set the number of retries
- server._reconnect_retries = server.db.numberOfRetries;
- // Attempt reconnect
- server._reconnectInProgreess = true;
- setTimeout(__attemptReconnect(server), server.db.retryMiliSeconds);
- }
- });
-
- // Handle errors
- connectionPool.on("error", function(message, connection, error_options) {
- // If pool connection is already closed
- if(server._serverState === 'disconnected'
- || server._serverState === 'destroyed') return;
-
- // Set server state to disconnected
- server._serverState = 'disconnected';
- // Error message
- var error_message = new Error(message && message.err ? message.err : message);
- // Error message coming from ssl
- if(error_options && error_options.ssl) error_message.ssl = true;
-
- // If we have a callback return the error
- if(typeof callback === 'function') {
- // ensure no callbacks get called twice
- var internalCallback = callback;
- callback = null;
- // Perform callback
- internalCallback(error_message, null, server);
- } else if(server.isSetMember()) {
- if(server.listeners("error") && server.listeners("error").length > 0) server.emit("error", error_message, server);
- } else {
- if(eventReceiver.listeners("error") && eventReceiver.listeners("error").length > 0) eventReceiver.emit("error", error_message, server);
- }
-
- // If we are a single server connection fire errors correctly
- if(!server.isSetMember()) {
- // Fire all callback errors
- server.__executeAllCallbacksWithError(error_message);
- // Emit error
- server._emitAcrossAllDbInstances(server, eventReceiver, "error", error_message, server, true);
- }
-
- // If we have autoConnect enabled let's fire up an attempt to reconnect
- if(server.isAutoReconnect()
- && !server.isSetMember()
- && (server._serverState != 'destroyed')
- && !server._reconnectInProgreess) {
-
- // Set the number of retries
- server._reconnect_retries = server.db.numberOfRetries;
- // Attempt reconnect
- server._reconnectInProgreess = true;
- setTimeout(__attemptReconnect(server), server.db.retryMiliSeconds);
- }
- });
-
- // Handle close events
- connectionPool.on("close", function() {
- // If pool connection is already closed
- if(server._serverState === 'disconnected'
- || server._serverState === 'destroyed') return;
- // Set server state to disconnected
- server._serverState = 'disconnected';
- // If we have a callback return the error
- if(typeof callback == 'function') {
- // ensure no callbacks get called twice
- var internalCallback = callback;
- callback = null;
- // Perform callback
- internalCallback(new Error("connection closed"), null, server);
- } else if(server.isSetMember()) {
- if(server.listeners("close") && server.listeners("close").length > 0) server.emit("close", new Error("connection closed"), server);
- } else {
- if(eventReceiver.listeners("close") && eventReceiver.listeners("close").length > 0) eventReceiver.emit("close", new Error("connection closed"), server);
- }
-
- // If we are a single server connection fire errors correctly
- if(!server.isSetMember()) {
- // Fire all callback errors
- server.__executeAllCallbacksWithError(new Error("connection closed"));
- // Emit error
- server._emitAcrossAllDbInstances(server, eventReceiver, "close", server, null, true);
- }
-
- // If we have autoConnect enabled let's fire up an attempt to reconnect
- if(server.isAutoReconnect()
- && !server.isSetMember()
- && (server._serverState != 'destroyed')
- && !server._reconnectInProgreess) {
-
- // Set the number of retries
- server._reconnect_retries = server.db.numberOfRetries;
- // Attempt reconnect
- server._reconnectInProgreess = true;
- setTimeout(__attemptReconnect(server), server.db.retryMiliSeconds);
- }
- });
-
- /**
- * @ignore
- */
- var __attemptReconnect = function(server) {
- return function() {
- // Attempt reconnect
- server.connect(server.db, server.options, function(err, result) {
- server._reconnect_retries = server._reconnect_retries - 1;
-
- if(err) {
- // Retry
- if(server._reconnect_retries == 0 || server._serverState == 'destroyed') {
- server._serverState = 'connected';
- server._reconnectInProgreess = false
- // Fire all callback errors
- return server.__executeAllCallbacksWithError(new Error("failed to reconnect to server"));
- } else {
- return setTimeout(__attemptReconnect(server), server.db.retryMiliSeconds);
- }
- } else {
- // Set as authenticating (isConnected will be false)
- server._serverState = 'authenticating';
- // Apply any auths, we don't try to catch any errors here
- // as there are nowhere to simply propagate them to
- self._apply_auths(server.db, function(err, result) {
- server._serverState = 'connected';
- server._reconnectInProgreess = false;
-
- // Execute any buffered reads and writes
- server._commandsStore.execute_queries();
- server._commandsStore.execute_writes();
- // Emit reconnect event
- server.emit('reconnect');
- });
- }
- });
- }
- }
-
- // If we have a parser error we are in an unknown state, close everything and emit
- // error
- connectionPool.on("parseError", function(err) {
- // If pool connection is already closed
- if(server._serverState === 'disconnected'
- || server._serverState === 'destroyed') return;
- // Set server state to disconnected
- server._serverState = 'disconnected';
- // If we have a callback return the error
- if(typeof callback === 'function') {
- // ensure no callbacks get called twice
- var internalCallback = callback;
- callback = null;
- // Perform callback
- internalCallback(utils.toError(err), null, server);
- } else if(server.isSetMember()) {
- if(server.listeners("parseError") && server.listeners("parseError").length > 0) server.emit("parseError", utils.toError(err), server);
- } else {
- if(eventReceiver.listeners("parseError") && eventReceiver.listeners("parseError").length > 0) eventReceiver.emit("parseError", utils.toError(err), server);
- }
-
- // If we are a single server connection fire errors correctly
- if(!server.isSetMember()) {
- // Fire all callback errors
- server.__executeAllCallbacksWithError(utils.toError(err));
- // Emit error
- server._emitAcrossAllDbInstances(server, eventReceiver, "parseError", server, null, true);
- // Emit close event
- if(eventReceiver.listeners("close") && eventReceiver.listeners("close").length > 0) eventReceiver.emit("close", new Error("connection closed"), server); }
- });
-
- // Boot up connection poole, pass in a locator of callbacks
- connectionPool.start();
-}
-
-/**
- * @ignore
- */
-Server.prototype.allRawConnections = function() {
- return this.connectionPool != null ? this.connectionPool.getAllConnections() : [];
-}
-
-/**
- * Check if a writer can be provided
- * @ignore
- */
-var canCheckoutWriter = function(self, read) {
- // We cannot write to an arbiter or secondary server
- if(self.isMasterDoc && self.isMasterDoc['arbiterOnly'] == true) {
- return new Error("Cannot write to an arbiter");
- } if(self.isMasterDoc && self.isMasterDoc['secondary'] == true) {
- return new Error("Cannot write to a secondary");
- } else if(read == true && self._readPreference == ReadPreference.SECONDARY && self.isMasterDoc && self.isMasterDoc['ismaster'] == true) {
- return new Error("Cannot read from primary when secondary only specified");
- } else if(!self.isMasterDoc) {
- return new Error("Cannot determine state of server");
- }
-
- // Return no error
- return null;
-}
-
-/**
- * @ignore
- */
-Server.prototype.checkoutWriter = function(read) {
- if(this._serverState == 'disconnected' || this._serverState == 'destroyed')
- return null;
- if(read == true) return this.connectionPool.checkoutConnection();
- // Check if are allowed to do a checkout (if we try to use an arbiter f.ex)
- var result = canCheckoutWriter(this, read);
- // If the result is null check out a writer
- if(result == null && this.connectionPool != null) {
- var connection = this.connectionPool.checkoutConnection();
- // Add server capabilities to the connection
- if(connection)
- connection.serverCapabilities = this.serverCapabilities;
- return connection;
- } else if(result == null) {
- return null;
- } else {
- return result;
- }
-}
-
-/**
- * Check if a reader can be provided
- * @ignore
- */
-var canCheckoutReader = function(self) {
- // We cannot write to an arbiter or secondary server
- if(self.isMasterDoc && self.isMasterDoc['arbiterOnly'] == true && self.isSetMember()) {
- return new Error("Cannot write to an arbiter");
- } else if(self._readPreference != null) {
- // If the read preference is Primary and the instance is not a master return an error
- if((self._readPreference == ReadPreference.PRIMARY) && self.isMasterDoc && self.isMasterDoc['ismaster'] != true) {
- return new Error("Read preference is Server.PRIMARY and server is not master");
- } else if(self._readPreference == ReadPreference.SECONDARY && self.isMasterDoc && self.isMasterDoc['ismaster'] == true) {
- return new Error("Cannot read from primary when secondary only specified");
- }
- } else if(!self.isMasterDoc) {
- return new Error("Cannot determine state of server");
- }
-
- // Return no error
- return null;
-}
-
-/**
- * @ignore
- */
-Server.prototype.checkoutReader = function(read) {
- if(this._serverState == 'disconnected' || this._serverState == 'destroyed')
- return null;
- // Check if are allowed to do a checkout (if we try to use an arbiter f.ex)
- var result = canCheckoutReader(this);
- // If the result is null check out a writer
- if(result == null && this.connectionPool != null) {
- var connection = this.connectionPool.checkoutConnection();
- // Add server capabilities to the connection
- if(connection)
- connection.serverCapabilities = this.serverCapabilities;
- return connection;
- } else if(result == null) {
- return null;
- } else {
- return result;
- }
-}
-
-/**
- * @ignore
- */
-Server.prototype.enableRecordQueryStats = function(enable) {
- this.recordQueryStats = enable;
-}
-
-/**
- * Internal statistics object used for calculating average and standard devitation on
- * running queries
- * @ignore
- */
-var RunningStats = function() {
- var self = this;
- this.m_n = 0;
- this.m_oldM = 0.0;
- this.m_oldS = 0.0;
- this.m_newM = 0.0;
- this.m_newS = 0.0;
-
- // Define getters
- Object.defineProperty(this, "numDataValues", { enumerable: true
- , get: function () { return this.m_n; }
- });
-
- Object.defineProperty(this, "mean", { enumerable: true
- , get: function () { return (this.m_n > 0) ? this.m_newM : 0.0; }
- });
-
- Object.defineProperty(this, "variance", { enumerable: true
- , get: function () { return ((this.m_n > 1) ? this.m_newS/(this.m_n - 1) : 0.0); }
- });
-
- Object.defineProperty(this, "standardDeviation", { enumerable: true
- , get: function () { return Math.sqrt(this.variance); }
- });
-
- Object.defineProperty(this, "sScore", { enumerable: true
- , get: function () {
- var bottom = this.mean + this.standardDeviation;
- if(bottom == 0) return 0;
- return ((2 * this.mean * this.standardDeviation)/(bottom));
- }
- });
-}
-
-/**
- * @ignore
- */
-RunningStats.prototype.push = function(x) {
- // Update the number of samples
- this.m_n = this.m_n + 1;
-
- // See Knuth TAOCP vol 2, 3rd edition, page 232
- if(this.m_n == 1) {
- this.m_oldM = this.m_newM = x;
- this.m_oldS = 0.0;
- } else {
- this.m_newM = this.m_oldM + (x - this.m_oldM) / this.m_n;
- this.m_newS = this.m_oldS + (x - this.m_oldM) * (x - this.m_newM);
- // set up for next iteration
- this.m_oldM = this.m_newM;
- this.m_oldS = this.m_newS;
- }
-}
-
-/**
- * @ignore
- */
-Object.defineProperty(Server.prototype, "autoReconnect", { enumerable: true
- , get: function () {
- return this.options['auto_reconnect'] == null ? false : this.options['auto_reconnect'];
- }
-});
-
-/**
- * @ignore
- */
-Object.defineProperty(Server.prototype, "connection", { enumerable: true
- , get: function () {
- return this.internalConnection;
- }
- , set: function(connection) {
- this.internalConnection = connection;
- }
-});
-
-/**
- * @ignore
- */
-Object.defineProperty(Server.prototype, "master", { enumerable: true
- , get: function () {
- return this.internalMaster;
- }
- , set: function(value) {
- this.internalMaster = value;
- }
-});
-
-/**
- * @ignore
- */
-Object.defineProperty(Server.prototype, "primary", { enumerable: true
- , get: function () {
- return this;
- }
-});
-
-/**
- * Getter for query Stats
- * @ignore
- */
-Object.defineProperty(Server.prototype, "queryStats", { enumerable: true
- , get: function () {
- return this._state.runtimeStats.queryStats;
- }
-});
-
-/**
- * @ignore
- */
-Object.defineProperty(Server.prototype, "runtimeStats", { enumerable: true
- , get: function () {
- return this._state.runtimeStats;
- }
-});
-
-/**
- * Get Read Preference method
- * @ignore
- */
-Object.defineProperty(Server.prototype, "readPreference", { enumerable: true
- , get: function () {
- if(this._readPreference == null && this.readSecondary) {
- return Server.READ_SECONDARY;
- } else if(this._readPreference == null && !this.readSecondary) {
- return Server.READ_PRIMARY;
- } else {
- return this._readPreference;
- }
- }
-});
-
-/**
- * @ignore
- */
-exports.Server = Server;
diff --git a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/server_capabilities.js b/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/server_capabilities.js
deleted file mode 100644
index 68d42ea..0000000
--- a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/server_capabilities.js
+++ /dev/null
@@ -1,48 +0,0 @@
-var ServerCapabilities = function(isMasterResult) {
- // Capabilities
- var aggregationCursor = false;
- var writeCommands = false;
- var textSearch = false;
- var authCommands = false;
- var maxNumberOfDocsInBatch = isMasterResult.maxWriteBatchSize || 1000;
-
- if(isMasterResult.minWireVersion >= 0) {
- textSearch = true;
- }
-
- if(isMasterResult.maxWireVersion >= 1) {
- aggregationCursor = true;
- authCommands = true;
- }
-
- if(isMasterResult.maxWireVersion >= 2) {
- writeCommands = true;
- }
-
- // If no min or max wire version set to 0
- if(isMasterResult.minWireVersion == null) {
- isMasterResult.minWireVersion = 0;
- }
-
- if(isMasterResult.maxWireVersion == null) {
- isMasterResult.maxWireVersion = 0;
- }
-
- // Map up read only parameters
- setup_get_property(this, "hasAggregationCursor", aggregationCursor);
- setup_get_property(this, "hasWriteCommands", writeCommands);
- setup_get_property(this, "hasTextSearch", textSearch);
- setup_get_property(this, "hasAuthCommands", authCommands);
- setup_get_property(this, "minWireVersion", isMasterResult.minWireVersion);
- setup_get_property(this, "maxWireVersion", isMasterResult.maxWireVersion);
- setup_get_property(this, "maxNumberOfDocsInBatch", maxNumberOfDocsInBatch);
-}
-
-var setup_get_property = function(object, name, value) {
- Object.defineProperty(object, name, {
- enumerable: true
- , get: function () { return value; }
- });
-}
-
-exports.ServerCapabilities = ServerCapabilities;
\ No newline at end of file
diff --git a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/url_parser.js b/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/url_parser.js
deleted file mode 100644
index 4db9579..0000000
--- a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/url_parser.js
+++ /dev/null
@@ -1,265 +0,0 @@
-var fs = require('fs'),
- ReadPreference = require('./read_preference').ReadPreference;
-
-exports.parse = function(url, options) {
- // Ensure we have a default options object if none set
- options = options || {};
- // Variables
- var connection_part = '';
- var auth_part = '';
- var query_string_part = '';
- var dbName = 'admin';
-
- // Must start with mongodb
- if(url.indexOf("mongodb://") != 0)
- throw Error("URL must be in the format mongodb://user:pass@host:port/dbname");
- // If we have a ? mark cut the query elements off
- if(url.indexOf("?") != -1) {
- query_string_part = url.substr(url.indexOf("?") + 1);
- connection_part = url.substring("mongodb://".length, url.indexOf("?"))
- } else {
- connection_part = url.substring("mongodb://".length);
- }
-
- // Check if we have auth params
- if(connection_part.indexOf("@") != -1) {
- auth_part = connection_part.split("@")[0];
- connection_part = connection_part.split("@")[1];
- }
-
- // Check if the connection string has a db
- if(connection_part.indexOf(".sock") != -1) {
- if(connection_part.indexOf(".sock/") != -1) {
- dbName = connection_part.split(".sock/")[1];
- connection_part = connection_part.split("/", connection_part.indexOf(".sock") + ".sock".length);
- }
- } else if(connection_part.indexOf("/") != -1) {
- dbName = connection_part.split("/")[1];
- connection_part = connection_part.split("/")[0];
- }
-
- // Result object
- var object = {};
-
- // Pick apart the authentication part of the string
- var authPart = auth_part || '';
- var auth = authPart.split(':', 2);
- if(options['uri_decode_auth']){
- auth[0] = decodeURIComponent(auth[0]);
- if(auth[1]){
- auth[1] = decodeURIComponent(auth[1]);
- }
- }
-
- // Add auth to final object if we have 2 elements
- if(auth.length == 2) object.auth = {user: auth[0], password: auth[1]};
-
- // Variables used for temporary storage
- var hostPart;
- var urlOptions;
- var servers;
- var serverOptions = {socketOptions: {}};
- var dbOptions = {read_preference_tags: []};
- var replSetServersOptions = {socketOptions: {}};
- // Add server options to final object
- object.server_options = serverOptions;
- object.db_options = dbOptions;
- object.rs_options = replSetServersOptions;
- object.mongos_options = {};
-
- // Let's check if we are using a domain socket
- if(url.match(/\.sock/)) {
- // Split out the socket part
- var domainSocket = url.substring(
- url.indexOf("mongodb://") + "mongodb://".length
- , url.lastIndexOf(".sock") + ".sock".length);
- // Clean out any auth stuff if any
- if(domainSocket.indexOf("@") != -1) domainSocket = domainSocket.split("@")[1];
- servers = [{domain_socket: domainSocket}];
- } else {
- // Split up the db
- hostPart = connection_part;
- // Parse all server results
- servers = hostPart.split(',').map(function(h) {
- var _host, _port, ipv6match;
- //check if it matches [IPv6]:port, where the port number is optional
- if ((ipv6match = /\[([^\]]+)\](?:\:(.+))?/.exec(h))) {
- _host = ipv6match[1];
- _port = parseInt(ipv6match[2], 10) || 27017;
- } else {
- //otherwise assume it's IPv4, or plain hostname
- var hostPort = h.split(':', 2);
- _host = hostPort[0] || 'localhost';
- _port = hostPort[1] != null ? parseInt(hostPort[1], 10) : 27017;
- // Check for localhost?safe=true style case
- if(_host.indexOf("?") != -1) _host = _host.split(/\?/)[0];
- }
- // Return the mapped object
- return {host: _host, port: _port};
- });
- }
-
- // Get the db name
- object.dbName = dbName || 'admin';
- // Split up all the options
- urlOptions = (query_string_part || '').split(/[&;]/);
- // Ugh, we have to figure out which options go to which constructor manually.
- urlOptions.forEach(function(opt) {
- if(!opt) return;
- var splitOpt = opt.split('='), name = splitOpt[0], value = splitOpt[1];
- // Options implementations
- switch(name) {
- case 'slaveOk':
- case 'slave_ok':
- serverOptions.slave_ok = (value == 'true');
- dbOptions.slaveOk = (value == 'true');
- break;
- case 'maxPoolSize':
- case 'poolSize':
- serverOptions.poolSize = parseInt(value, 10);
- replSetServersOptions.poolSize = parseInt(value, 10);
- break;
- case 'autoReconnect':
- case 'auto_reconnect':
- serverOptions.auto_reconnect = (value == 'true');
- break;
- case 'minPoolSize':
- throw new Error("minPoolSize not supported");
- case 'maxIdleTimeMS':
- throw new Error("maxIdleTimeMS not supported");
- case 'waitQueueMultiple':
- throw new Error("waitQueueMultiple not supported");
- case 'waitQueueTimeoutMS':
- throw new Error("waitQueueTimeoutMS not supported");
- case 'uuidRepresentation':
- throw new Error("uuidRepresentation not supported");
- case 'ssl':
- if(value == 'prefer') {
- serverOptions.ssl = value;
- replSetServersOptions.ssl = value;
- break;
- }
- serverOptions.ssl = (value == 'true');
- replSetServersOptions.ssl = (value == 'true');
- break;
- case 'replicaSet':
- case 'rs_name':
- replSetServersOptions.rs_name = value;
- break;
- case 'reconnectWait':
- replSetServersOptions.reconnectWait = parseInt(value, 10);
- break;
- case 'retries':
- replSetServersOptions.retries = parseInt(value, 10);
- break;
- case 'readSecondary':
- case 'read_secondary':
- replSetServersOptions.read_secondary = (value == 'true');
- break;
- case 'fsync':
- dbOptions.fsync = (value == 'true');
- break;
- case 'journal':
- dbOptions.journal = (value == 'true');
- break;
- case 'safe':
- dbOptions.safe = (value == 'true');
- break;
- case 'nativeParser':
- case 'native_parser':
- dbOptions.native_parser = (value == 'true');
- break;
- case 'connectTimeoutMS':
- serverOptions.socketOptions.connectTimeoutMS = parseInt(value, 10);
- replSetServersOptions.socketOptions.connectTimeoutMS = parseInt(value, 10);
- break;
- case 'socketTimeoutMS':
- serverOptions.socketOptions.socketTimeoutMS = parseInt(value, 10);
- replSetServersOptions.socketOptions.socketTimeoutMS = parseInt(value, 10);
- break;
- case 'w':
- dbOptions.w = parseInt(value, 10);
- if(isNaN(dbOptions.w)) dbOptions.w = value;
- break;
- case 'authSource':
- dbOptions.authSource = value;
- break;
- case 'gssapiServiceName':
- dbOptions.gssapiServiceName = value;
- break;
- case 'authMechanism':
- if(value == 'GSSAPI') {
- // If no password provided decode only the principal
- if(object.auth == null) {
- var urlDecodeAuthPart = decodeURIComponent(authPart);
- if(urlDecodeAuthPart.indexOf("@") == -1) throw new Error("GSSAPI requires a provided principal");
- object.auth = {user: urlDecodeAuthPart, password: null};
- } else {
- object.auth.user = decodeURIComponent(object.auth.user);
- }
- } else if(value == 'MONGODB-X509') {
- object.auth = {user: decodeURIComponent(authPart)};
- }
-
- // Only support GSSAPI or MONGODB-CR for now
- if(value != 'GSSAPI'
- && value != 'MONGODB-X509'
- && value != 'SCRAM-SHA-1'
- && value != 'MONGODB-CR'
- && value != 'PLAIN')
- throw new Error("only GSSAPI, PLAIN, MONGODB-X509, SCRAM-SHA-1 or MONGODB-CR is supported by authMechanism");
-
- // Authentication mechanism
- dbOptions.authMechanism = value;
- break;
- case 'wtimeoutMS':
- dbOptions.wtimeout = parseInt(value, 10);
- break;
- case 'readPreference':
- if(!ReadPreference.isValid(value)) throw new Error("readPreference must be either primary/primaryPreferred/secondary/secondaryPreferred/nearest");
- dbOptions.read_preference = value;
- break;
- case 'readPreferenceTags':
- // Decode the value
- value = decodeURIComponent(value);
- // Contains the tag object
- var tagObject = {};
- if(value == null || value == '') {
- dbOptions.read_preference_tags.push(tagObject);
- break;
- }
-
- // Split up the tags
- var tags = value.split(/\,/);
- for(var i = 0; i < tags.length; i++) {
- var parts = tags[i].trim().split(/\:/);
- tagObject[parts[0]] = parts[1];
- }
-
- // Set the preferences tags
- dbOptions.read_preference_tags.push(tagObject);
- break;
- default:
- break;
- }
- });
-
- // No tags: should be null (not [])
- if(dbOptions.read_preference_tags.length === 0) {
- dbOptions.read_preference_tags = null;
- }
-
- // Validate if there are an invalid write concern combinations
- if((dbOptions.w == -1 || dbOptions.w == 0) && (
- dbOptions.journal == true
- || dbOptions.fsync == true
- || dbOptions.safe == true)) throw new Error("w set to -1 or 0 cannot be combined with safe/w/journal/fsync")
-
- // If no read preference set it to primary
- if(!dbOptions.read_preference) dbOptions.read_preference = 'primary';
-
- // Add servers to result
- object.servers = servers;
- // Returned parsed object
- return object;
-}
diff --git a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/cursor.js b/node_modules/mongojs/node_modules/mongodb/lib/mongodb/cursor.js
deleted file mode 100644
index 050cc9c..0000000
--- a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/cursor.js
+++ /dev/null
@@ -1,1038 +0,0 @@
-var QueryCommand = require('./commands/query_command').QueryCommand,
- GetMoreCommand = require('./commands/get_more_command').GetMoreCommand,
- KillCursorCommand = require('./commands/kill_cursor_command').KillCursorCommand,
- Long = require('bson').Long,
- ReadPreference = require('./connection/read_preference').ReadPreference,
- CursorStream = require('./cursorstream'),
- timers = require('timers'),
- utils = require('./utils');
-
-// Set processor, setImmediate if 0.10 otherwise nextTick
-var processor = require('./utils').processor();
-
-/**
- * Constructor for a cursor object that handles all the operations on query result
- * using find. This cursor object is unidirectional and cannot traverse backwards. Clients should not be creating a cursor directly,
- * but use find to acquire a cursor. (INTERNAL TYPE)
- *
- * Options
- * - **skip** {Number} skip number of documents to skip.
- * - **limit** {Number}, limit the number of results to return. -1 has a special meaning and is used by Db.eval. A value of 1 will also be treated as if it were -1.
- * - **sort** {Array | Object}, set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc.
- * - **hint** {Object}, hint force the query to use a specific index.
- * - **explain** {Boolean}, explain return the explaination of the query.
- * - **snapshot** {Boolean}, snapshot Snapshot mode assures no duplicates are returned.
- * - **timeout** {Boolean}, timeout allow the query to timeout.
- * - **tailable** {Boolean}, tailable allow the cursor to be tailable.
- * - **awaitdata** {Boolean}, awaitdata allow the cursor to wait for data, only applicable for tailable cursor.
- * - **oplogReplay** {Boolean}, sets an internal flag, only applicable for tailable cursor.
- * - **batchSize** {Number}, batchSize the number of the subset of results to request the database to return for every request. This should initially be greater than 1 otherwise the database will automatically close the cursor. The batch size can be set to 1 with cursorInstance.batchSize after performing the initial query to the database.
- * - **raw** {Boolean}, raw return all query documents as raw buffers (default false).
- * - **read** {Boolean}, read specify override of read from source (primary/secondary).
- * - **returnKey** {Boolean}, returnKey only return the index key.
- * - **maxScan** {Number}, maxScan limit the number of items to scan.
- * - **min** {Number}, min set index bounds.
- * - **max** {Number}, max set index bounds.
- * - **maxTimeMS** {Number}, number of miliseconds to wait before aborting the query.
- * - **showDiskLoc** {Boolean}, showDiskLoc show disk location of results.
- * - **comment** {String}, comment you can put a $comment field on a query to make looking in the profiler logs simpler.
- * - **numberOfRetries** {Number}, numberOfRetries if using awaidata specifies the number of times to retry on timeout.
- * - **dbName** {String}, dbName override the default dbName.
- * - **tailableRetryInterval** {Number}, tailableRetryInterval specify the miliseconds between getMores on tailable cursor.
- * - **exhaust** {Boolean}, exhaust have the server send all the documents at once as getMore packets.
- * - **partial** {Boolean}, partial have the sharded system return a partial result from mongos.
- *
- * @class Represents a Cursor.
- * @param {Db} db the database object to work with.
- * @param {Collection} collection the collection to query.
- * @param {Object} selector the query selector.
- * @param {Object} fields an object containing what fields to include or exclude from objects returned.
- * @param {Object} [options] additional options for the collection.
-*/
-function Cursor(db, collection, selector, fields, options) {
- this.db = db;
- this.collection = collection;
- this.selector = selector;
- this.fields = fields;
- options = !options ? {} : options;
-
- this.skipValue = options.skip == null ? 0 : options.skip;
- this.limitValue = options.limit == null ? 0 : options.limit;
- this.sortValue = options.sort;
- this.hint = options.hint;
- this.explainValue = options.explain;
- this.snapshot = options.snapshot;
- this.timeout = options.timeout == null ? true : options.timeout;
- this.tailable = options.tailable;
- this.awaitdata = options.awaitdata;
- this.oplogReplay = options.oplogReplay;
- this.numberOfRetries = options.numberOfRetries == null ? 5 : options.numberOfRetries;
- this.currentNumberOfRetries = this.numberOfRetries;
- this.batchSizeValue = options.batchSize == null ? 0 : options.batchSize;
- this.raw = options.raw == null ? false : options.raw;
- this.readPreference = options.readPreference == null ? ReadPreference.PRIMARY : options.readPreference;
- this.returnKey = options.returnKey;
- this.maxScan = options.maxScan;
- this.min = options.min;
- this.max = options.max;
- this.showDiskLoc = options.showDiskLoc;
- this.comment = options.comment;
- this.tailableRetryInterval = options.tailableRetryInterval || 100;
- this.exhaust = options.exhaust || false;
- this.partial = options.partial || false;
- this.slaveOk = options.slaveOk || false;
- this.maxTimeMSValue = options.maxTimeMS;
- this.connection = options.connection;
-
- this.totalNumberOfRecords = 0;
- this.items = [];
- this.cursorId = Long.fromInt(0);
-
- // This name
- this.dbName = options.dbName;
-
- // State variables for the cursor
- this.state = Cursor.INIT;
- // Keep track of the current query run
- this.queryRun = false;
- this.getMoreTimer = false;
-
- // If we are using a specific db execute against it
- if(this.dbName != null) {
- this.collectionName = this.dbName + "." + this.collection.collectionName;
- } else {
- this.collectionName = (this.db.databaseName ? this.db.databaseName + "." : '') + this.collection.collectionName;
- }
-}
-
-/**
- * Clones a given cursor but uses new options
- * @param {Cursor} cursor the cursor to clone.
- * @return {Object} [options] additional options for the collection when cloning.
- */
-Cursor.cloneWithOptions = function(cursor, options) {
- return new Cursor(cursor.db, cursor.collection, cursor.selector, cursor.fields, options);
-}
-
-/**
- * Resets this cursor to its initial state. All settings like the query string,
- * tailable, batchSizeValue, skipValue and limits are preserved.
- *
- * @return {Cursor} returns itself with rewind applied.
- * @api public
- */
-Cursor.prototype.rewind = function() {
- var self = this;
-
- if (self.state != Cursor.INIT) {
- if (self.state != Cursor.CLOSED) {
- self.close(function() {});
- }
-
- self.numberOfReturned = 0;
- self.totalNumberOfRecords = 0;
- self.items = [];
- self.cursorId = Long.fromInt(0);
- self.state = Cursor.INIT;
- self.queryRun = false;
- }
-
- return self;
-}
-
-
-/**
- * Returns an array of documents. The caller is responsible for making sure that there
- * is enough memory to store the results. Note that the array only contain partial
- * results when this cursor had been previouly accessed. In that case,
- * cursor.rewind() can be used to reset the cursor.
- *
- * @param {Function} callback This will be called after executing this method successfully. The first parameter will contain the Error object if an error occured, or null otherwise. The second parameter will contain an array of BSON deserialized objects as a result of the query.
- * @return {null}
- * @api public
- */
-Cursor.prototype.toArray = function(callback) {
- var self = this;
-
- if(!callback) {
- throw new Error('callback is mandatory');
- }
-
- if(this.tailable) {
- callback(new Error("Tailable cursor cannot be converted to array"), null);
- } else if(this.state != Cursor.CLOSED) {
- // return toArrayExhaust(self, callback);
- // If we are using exhaust we can't use the quick fire method
- if(self.exhaust) return toArrayExhaust(self, callback);
- // Quick fire using trampoline to avoid nextTick
- self.nextObject({noReturn: true}, function(err, result) {
- if(err) return callback(utils.toError(err), null);
- if(self.cursorId.toString() == "0") {
- self.state = Cursor.CLOSED;
- return callback(null, self.items);
- }
-
- // Let's issue getMores until we have no more records waiting
- getAllByGetMore(self, function(err, done) {
- self.state = Cursor.CLOSED;
- if(err) return callback(utils.toError(err), null);
- // Let's release the internal list
- var items = self.items;
- self.items = null;
- // Return all the items
- callback(null, items);
- });
- })
-
- } else {
- callback(new Error("Cursor is closed"), null);
- }
-}
-
-var toArrayExhaust = function(self, callback) {
- var items = [];
-
- self.each(function(err, item) {
- if(err != null) {
- return callback(utils.toError(err), null);
- }
-
- if(item != null && Array.isArray(items)) {
- items.push(item);
- } else {
- var resultItems = items;
- items = null;
- self.items = [];
- callback(null, resultItems);
- }
- });
-}
-
-var getAllByGetMore = function(self, callback) {
- getMore(self, {noReturn: true}, function(err, result) {
- if(err) return callback(utils.toError(err));
- if(result == null) return callback(null, null);
- if(self.cursorId.toString() == "0") return callback(null, null);
- getAllByGetMore(self, callback);
- })
-};
-
-/**
- * Iterates over all the documents for this cursor. As with **{cursor.toArray}**,
- * not all of the elements will be iterated if this cursor had been previouly accessed.
- * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike
- * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements
- * at any given time if batch size is specified. Otherwise, the caller is responsible
- * for making sure that the entire result can fit the memory.
- *
- * @param {Function} callback this will be called for while iterating every document of the query result. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the document.
- * @return {null}
- * @api public
- */
-Cursor.prototype.each = function(callback) {
- var self = this;
- var fn;
-
- if (!callback) {
- throw new Error('callback is mandatory');
- }
-
- if(this.state != Cursor.CLOSED) {
- // If we are using exhaust we can't use the quick fire method
- if(self.exhaust) return eachExhaust(self, callback);
- // Quick fire using trampoline to avoid nextTick
- if(this.items.length > 0) {
- // Trampoline all the entries
- while(fn = loop(self, callback)) fn(self, callback);
- // Call each again
- self.each(callback);
- } else {
- self.nextObject(function(err, item) {
-
- if(err) {
- self.state = Cursor.CLOSED;
- return callback(utils.toError(err), item);
- }
-
- if(item == null) return callback(null, null);
- callback(null, item);
- self.each(callback);
- })
- }
- } else {
- callback(new Error("Cursor is closed"), null);
- }
-};
-
-// Special for exhaust command as we don't initiate the actual result sets
-// the server just sends them as they arrive meaning we need to get the IO event
-// loop happen so we can receive more data from the socket or we return to early
-// after the first fetch and loose all the incoming getMore's automatically issued
-// from the server.
-var eachExhaust = function(self, callback) {
- //FIX: stack overflow (on deep callback) (cred: https://github.com/limp/node-mongodb-native/commit/27da7e4b2af02035847f262b29837a94bbbf6ce2)
- processor(function(){
- // Fetch the next object until there is no more objects
- self.nextObject(function(err, item) {
- if(err != null) return callback(err, null);
- if(item != null) {
- callback(null, item);
- eachExhaust(self, callback);
- } else {
- // Close the cursor if done
- self.state = Cursor.CLOSED;
- callback(err, null);
- }
- });
- });
-}
-
-// Trampoline emptying the number of retrieved items
-// without incurring a nextTick operation
-var loop = function(self, callback) {
- // No more items we are done
- if(self.items.length == 0) return;
- // Get the next document
- var doc = self.items.shift();
- // Callback
- callback(null, doc);
- // Loop
- return loop;
-}
-
-/**
- * Determines how many result the query for this cursor will return
- *
- * @param {Boolean} applySkipLimit if set to true will apply the skip and limits set on the cursor. Defaults to false.
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the number of results or null if an error occured.
- * @return {null}
- * @api public
- */
-Cursor.prototype.count = function(applySkipLimit, callback) {
- if(typeof applySkipLimit == 'function') {
- callback = applySkipLimit;
- applySkipLimit = false;
- }
-
- var options = {};
- if(applySkipLimit) {
- if(typeof this.skipValue == 'number') options.skip = this.skipValue;
- if(typeof this.limitValue == 'number') options.limit = this.limitValue;
- }
-
- // If maxTimeMS set
- if(typeof this.maxTimeMSValue == 'number') options.maxTimeMS = this.maxTimeMSValue;
- // Do we have a hint add it to the options
- if(this.hint) options.hint = this.hint;
-
- // Call count command
- this.collection.count(this.selector, options, callback);
-};
-
-/**
- * Sets the sort parameter of this cursor to the given value.
- *
- * This method has the following method signatures:
- * (keyOrList, callback)
- * (keyOrList, direction, callback)
- *
- * @param {String|Array|Object} keyOrList This can be a string or an array. If passed as a string, the string will be the field to sort. If passed an array, each element will represent a field to be sorted and should be an array that contains the format [string, direction].
- * @param {String|Number} direction this determines how the results are sorted. "asc", "ascending" or 1 for asceding order while "desc", "desceding or -1 for descending order. Note that the strings are case insensitive.
- * @param {Function} callback this will be called after executing this method. The first parameter will contain an error object when the cursor is already closed while the second parameter will contain a reference to this object upon successful execution.
- * @return {Cursor} an instance of this object.
- * @api public
- */
-Cursor.prototype.sort = function(keyOrList, direction, callback) {
- callback = callback || function(){};
- if(typeof direction === "function") { callback = direction; direction = null; }
-
- if(this.tailable) {
- callback(new Error("Tailable cursor doesn't support sorting"), null);
- } else if(this.queryRun == true || this.state == Cursor.CLOSED) {
- callback(new Error("Cursor is closed"), null);
- } else {
- var order = keyOrList;
-
- if(direction != null) {
- order = [[keyOrList, direction]];
- }
-
- this.sortValue = order;
- callback(null, this);
- }
- return this;
-};
-
-/**
- * Sets the limit parameter of this cursor to the given value.
- *
- * @param {Number} limit the new limit.
- * @param {Function} [callback] this optional callback will be called after executing this method. The first parameter will contain an error object when the limit given is not a valid number or when the cursor is already closed while the second parameter will contain a reference to this object upon successful execution.
- * @return {Cursor} an instance of this object.
- * @api public
- */
-Cursor.prototype.limit = function(limit, callback) {
- if(this.tailable) {
- if(callback) {
- callback(new Error("Tailable cursor doesn't support limit"), null);
- } else {
- throw new Error("Tailable cursor doesn't support limit");
- }
- } else if(this.queryRun == true || this.state == Cursor.CLOSED) {
- if(callback) {
- callback(new Error("Cursor is closed"), null);
- } else {
- throw new Error("Cursor is closed");
- }
- } else {
- if(limit != null && limit.constructor != Number) {
- if(callback) {
- callback(new Error("limit requires an integer"), null);
- } else {
- throw new Error("limit requires an integer");
- }
- } else {
- this.limitValue = limit;
- if(callback) return callback(null, this);
- }
- }
-
- return this;
-};
-
-/**
- * Specifies a time limit for a query operation. After the specified
- * time is exceeded, the operation will be aborted and an error will be
- * returned to the client. If maxTimeMS is null, no limit is applied.
- *
- * @param {Number} maxTimeMS the maxTimeMS for the query.
- * @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.maxTimeMS = function(maxTimeMS, callback) {
- if(typeof maxTimeMS != 'number') {
- throw new Error("maxTimeMS must be a number");
- }
-
- // Save the maxTimeMS option
- this.maxTimeMSValue = maxTimeMS;
- // Return the cursor for chaining
- return this;
-};
-
-/**
- * Sets the read preference for the cursor
- *
- * @param {String} the read preference for the cursor, one of Server.READ_PRIMARY, Server.READ_SECONDARY, Server.READ_SECONDARY_ONLY
- * @param {Function} [callback] this optional callback will be called after executing this method. The first parameter will contain an error object when the read preference given is not a valid number or when the cursor is already closed while the second parameter will contain a reference to this object upon successful execution.
- * @return {Cursor} an instance of this object.
- * @api public
- */
-Cursor.prototype.setReadPreference = function(readPreference, tags, callback) {
- if(typeof tags == 'function') callback = tags;
-
- var _mode = readPreference != null && typeof readPreference == 'object' ? readPreference.mode : readPreference;
-
- if(this.queryRun == true || this.state == Cursor.CLOSED) {
- if(callback == null) throw new Error("Cannot change read preference on executed query or closed cursor");
- callback(new Error("Cannot change read preference on executed query or closed cursor"));
- } else if(_mode != null && _mode != 'primary'
- && _mode != 'secondaryOnly' && _mode != 'secondary'
- && _mode != 'nearest' && _mode != 'primaryPreferred' && _mode != 'secondaryPreferred') {
- if(callback == null) throw new Error("only readPreference of primary, secondary, secondaryPreferred, primaryPreferred or nearest supported");
- callback(new Error("only readPreference of primary, secondary, secondaryPreferred, primaryPreferred or nearest supported"));
- } else {
- this.readPreference = readPreference;
- if(callback != null) callback(null, this);
- }
-
- return this;
-}
-
-/**
- * Sets the skip parameter of this cursor to the given value.
- *
- * @param {Number} skip the new skip value.
- * @param {Function} [callback] this optional callback will be called after executing this method. The first parameter will contain an error object when the skip value given is not a valid number or when the cursor is already closed while the second parameter will contain a reference to this object upon successful execution.
- * @return {Cursor} an instance of this object.
- * @api public
- */
-Cursor.prototype.skip = function(skip, callback) {
- callback = callback || function(){};
-
- if(this.tailable) {
- callback(new Error("Tailable cursor doesn't support skip"), null);
- } else if(this.queryRun == true || this.state == Cursor.CLOSED) {
- callback(new Error("Cursor is closed"), null);
- } else {
- if(skip != null && skip.constructor != Number) {
- callback(new Error("skip requires an integer"), null);
- } else {
- this.skipValue = skip;
- callback(null, this);
- }
- }
-
- return this;
-};
-
-/**
- * Sets the batch size parameter of this cursor to the given value.
- *
- * @param {Number} batchSize the new batch size.
- * @param {Function} [callback] this optional callback will be called after executing this method. The first parameter will contain an error object when the batchSize given is not a valid number or when the cursor is already closed while the second parameter will contain a reference to this object upon successful execution.
- * @return {Cursor} an instance of this object.
- * @api public
- */
-Cursor.prototype.batchSize = function(batchSize, callback) {
- if(this.state == Cursor.CLOSED) {
- if(callback != null) {
- return callback(new Error("Cursor is closed"), null);
- } else {
- throw new Error("Cursor is closed");
- }
- } else if(batchSize != null && batchSize.constructor != Number) {
- if(callback != null) {
- return callback(new Error("batchSize requires an integer"), null);
- } else {
- throw new Error("batchSize requires an integer");
- }
- } else {
- this.batchSizeValue = batchSize;
- if(callback != null) return callback(null, this);
- }
-
- return this;
-};
-
-/**
- * The limit used for the getMore command
- *
- * @return {Number} The number of records to request per batch.
- * @ignore
- * @api private
- */
-var limitRequest = function(self) {
- var requestedLimit = self.limitValue;
- var absLimitValue = Math.abs(self.limitValue);
- var absBatchValue = Math.abs(self.batchSizeValue);
-
- if(absLimitValue > 0) {
- if (absBatchValue > 0) {
- requestedLimit = Math.min(absLimitValue, absBatchValue);
- }
- } else {
- requestedLimit = self.batchSizeValue;
- }
-
- return requestedLimit;
-};
-
-
-/**
- * Generates a QueryCommand object using the parameters of this cursor.
- *
- * @return {QueryCommand} The command object
- * @ignore
- * @api private
- */
-var generateQueryCommand = function(self) {
- // Unpack the options
- var queryOptions = QueryCommand.OPTS_NONE;
- if(!self.timeout) {
- queryOptions |= QueryCommand.OPTS_NO_CURSOR_TIMEOUT;
- }
-
- if(self.tailable) {
- queryOptions |= QueryCommand.OPTS_TAILABLE_CURSOR;
- self.skipValue = self.limitValue = 0;
-
- // if awaitdata is set
- if(self.awaitdata) {
- queryOptions |= QueryCommand.OPTS_AWAIT_DATA;
- }
-
- // This sets an internal undocumented flag. Clients should not depend on its
- // behavior!
- if(self.oplogReplay) {
- queryOptions |= QueryCommand.OPTS_OPLOG_REPLAY;
- }
- }
-
- if(self.exhaust) {
- queryOptions |= QueryCommand.OPTS_EXHAUST;
- }
-
- // Unpack the read preference to set slave ok correctly
- var readPreference = self.readPreference instanceof ReadPreference ? self.readPreference.mode : self.readPreference;
-
- // if(self.read == 'secondary')
- if(readPreference == ReadPreference.PRIMARY_PREFERRED
- || readPreference == ReadPreference.SECONDARY
- || readPreference == ReadPreference.SECONDARY_PREFERRED
- || readPreference == ReadPreference.NEAREST) {
- queryOptions |= QueryCommand.OPTS_SLAVE;
- }
-
- // Override slaveOk from the user
- if(self.slaveOk) {
- queryOptions |= QueryCommand.OPTS_SLAVE;
- }
-
- if(self.partial) {
- queryOptions |= QueryCommand.OPTS_PARTIAL;
- }
-
- // limitValue of -1 is a special case used by Db#eval
- var numberToReturn = self.limitValue == -1 ? -1 : limitRequest(self);
-
- // Check if we need a special selector
- if(self.sortValue != null || self.explainValue != null || self.hint != null || self.snapshot != null
- || self.returnKey != null || self.maxScan != null || self.min != null || self.max != null
- || self.showDiskLoc != null || self.comment != null || typeof self.maxTimeMSValue == 'number') {
-
- // order by
- var orderBy = utils.formattedOrderClause(self.sortValue);
-
- // Build special selector
- var specialSelector = {'$query':self.selector};
- if(orderBy) specialSelector['orderby'] = orderBy;
- if(self.hint != null && self.hint.constructor == Object) specialSelector['$hint'] = self.hint;
- if(self.snapshot != null) specialSelector['$snapshot'] = self.snapshot;
- if(self.returnKey != null) specialSelector['$returnKey'] = self.returnKey;
- if(self.maxScan != null) specialSelector['$maxScan'] = self.maxScan;
- if(self.min != null) specialSelector['$min'] = self.min;
- if(self.max != null) specialSelector['$max'] = self.max;
- if(self.showDiskLoc != null) specialSelector['$showDiskLoc'] = self.showDiskLoc;
- if(self.comment != null) specialSelector['$comment'] = self.comment;
-
- // If we are querying the $cmd collection we need to add maxTimeMS as a field
- // otherwise for a normal query it's a "special selector" $maxTimeMS
- if(typeof self.maxTimeMSValue == 'number'
- && self.collectionName.indexOf('.$cmd') != -1) {
- specialSelector['maxTimeMS'] = self.maxTimeMSValue;
- } else if(typeof self.maxTimeMSValue == 'number'
- && self.collectionName.indexOf('.$cmd') == -1) {
- specialSelector['$maxTimeMS'] = self.maxTimeMSValue;
- }
-
- // If we have explain set only return a single document with automatic cursor close
- if(self.explainValue) {
- numberToReturn = (-1)*Math.abs(numberToReturn);
- specialSelector['$explain'] = true;
- }
-
- // Return the query
- return new QueryCommand(self.db, self.collectionName, queryOptions, self.skipValue, numberToReturn, specialSelector, self.fields);
- } else {
- return new QueryCommand(self.db, self.collectionName, queryOptions, self.skipValue, numberToReturn, self.selector, self.fields);
- }
-};
-
-/**
- * @return {Object} Returns an object containing the sort value of this cursor with
- * the proper formatting that can be used internally in this cursor.
- * @ignore
- * @api private
- */
-Cursor.prototype.formattedOrderClause = function() {
- return utils.formattedOrderClause(this.sortValue);
-};
-
-/**
- * Converts the value of the sort direction into its equivalent numerical value.
- *
- * @param sortDirection {String|number} Range of acceptable values:
- * 'ascending', 'descending', 'asc', 'desc', 1, -1
- *
- * @return {number} The equivalent numerical value
- * @throws Error if the given sortDirection is invalid
- * @ignore
- * @api private
- */
-Cursor.prototype.formatSortValue = function(sortDirection) {
- return utils.formatSortValue(sortDirection);
-};
-
-/**
- * Gets the next document from the cursor.
- *
- * @param {Function} callback this will be called after executing this method. The first parameter will contain an error object on error while the second parameter will contain a document from the returned result or null if there are no more results.
- * @api public
- */
-Cursor.prototype.nextObject = function(options, callback) {
- var self = this;
-
- if(typeof options == 'function') {
- callback = options;
- options = {};
- }
-
- if(self.state == Cursor.INIT) {
- var cmd;
- try {
- cmd = generateQueryCommand(self);
- } catch (err) {
- return callback(err, null);
- }
-
- // No need to check the keys
- var queryOptions = {exhaust: self.exhaust
- , raw:self.raw
- , readPreference:self.readPreference
- , connection:self.connection
- , checkKeys: false};
-
- // Execute command
- var commandHandler = function(err, result) {
- // If on reconnect, the command got given a different connection, switch
- // the whole cursor to it.
- self.connection = queryOptions.connection;
- self.state = Cursor.OPEN; // Adjust the state of the cursor
- if(err != null && result == null) return callback(utils.toError(err), null);
-
- if(err == null && (result == null || result.documents == null || !Array.isArray(result.documents))) {
- return self.close(function() {callback(new Error("command failed to return results"), null);});
- }
-
- if(err == null && result && result.documents[0] && result.documents[0]['$err']) {
- return self.close(function() {callback(utils.toError(result.documents[0]['$err']), null);});
- }
-
- if(err == null && result && result.documents[0] && result.documents[0]['errmsg']) {
- return self.close(function() {callback(utils.toError(result.documents[0]), null);});
- }
-
- self.queryRun = true;
- self.cursorId = result.cursorId;
- self.totalNumberOfRecords = result.numberReturned;
-
- // Add the new documents to the list of items, using forloop to avoid
- // new array allocations and copying
- for(var i = 0; i < result.documents.length; i++) {
- self.items.push(result.documents[i]);
- }
-
- // If we have noReturn set just return (not modifying the internal item list)
- // used for toArray
- if(options.noReturn) {
- return callback(null, true);
- }
-
- // Ignore callbacks until the cursor is dead for exhausted
- if(self.exhaust && result.cursorId.toString() == "0") {
- self.nextObject(callback);
- } else if(self.exhaust == false || self.exhaust == null) {
- self.nextObject(callback);
- }
- };
-
- // If we have no connection set on this cursor check one out
- if(self.connection == null) {
- try {
- self.connection = self.db.serverConfig.checkoutReader(this.readPreference);
-
- // Check if we have an error from the checkout Reader function
- if(self.connection instanceof Error) {
- return callback(utils.toError(self.connection), null);
- }
-
- // Add to the query options
- queryOptions.connection = self.connection;
- } catch(err) {
- return callback(utils.toError(err), null);
- }
- }
-
- // Execute the command
- self.db._executeQueryCommand(cmd, queryOptions, commandHandler);
- // Set the command handler to null
- commandHandler = null;
- } else if(self.items.length) {
- callback(null, self.items.shift());
- } else if(self.cursorId.greaterThan(Long.fromInt(0))) {
- getMore(self, callback);
- } else {
- // Force cursor to stay open
- return self.close(function() {callback(null, null);});
- }
-}
-
-/**
- * Gets more results from the database if any.
- *
- * @param {Function} callback this will be called after executing this method. The first parameter will contain an error object on error while the second parameter will contain a document from the returned result or null if there are no more results.
- * @ignore
- * @api private
- */
-var getMore = function(self, options, callback) {
- var limit = 0;
-
- if(typeof options == 'function') {
- callback = options;
- options = {};
- }
-
- if(self.state == Cursor.GET_MORE) return callback(null, null);
-
- // Set get more in progress
- self.state = Cursor.GET_MORE;
-
- // Set options
- if (!self.tailable && self.limitValue > 0) {
- limit = self.limitValue - self.totalNumberOfRecords;
- if (limit < 1) {
- self.close(function() {callback(null, null);});
- return;
- }
- }
-
- try {
- var getMoreCommand = new GetMoreCommand(
- self.db
- , self.collectionName
- , limitRequest(self)
- , self.cursorId
- );
-
- // Set up options
- var command_options = {
- readPreference: self.readPreference
- , raw: self.raw
- , connection:self.connection
- };
-
- // Execute the command
- self.db._executeQueryCommand(getMoreCommand, command_options, function(err, result) {
- var cbValue;
-
- // Get more done
- self.state = Cursor.OPEN;
-
- if(err != null) {
- self.state = Cursor.CLOSED;
- return callback(utils.toError(err), null);
- }
-
- // Ensure we get a valid result
- if(!result || !result.documents) {
- self.state = Cursor.CLOSED;
- return callback(utils.toError("command failed to return results"), null)
- }
-
- // If we have a timed out query
- if((result.responseFlag & (1 << 0)) != 0) {
- self.state = Cursor.CLOSED;
- return callback(utils.toError("cursor killed or timed out"), null);
- }
-
- // If the QueryFailure flag is set
- if((result.responseFlag & (1 << 1)) != 0) {
- self.state = Cursor.CLOSED;
- return callback(utils.toError("QueryFailure flag set on getmore command"), null);
- }
-
- try {
- var isDead = 1 === result.responseFlag && result.cursorId.isZero();
-
- self.cursorId = result.cursorId;
- self.totalNumberOfRecords += result.numberReturned;
-
- // Determine if there's more documents to fetch
- if(result.numberReturned > 0) {
- if (self.limitValue > 0) {
- var excessResult = self.totalNumberOfRecords - self.limitValue;
-
- if (excessResult > 0) {
- result.documents.splice(-1 * excessResult, excessResult);
- }
- }
-
- // Reset the tries for awaitdata if we are using it
- self.currentNumberOfRetries = self.numberOfRetries;
- // Get the documents
- for(var i = 0; i < result.documents.length; i++) {
- self.items.push(result.documents[i]);
- }
-
- // Don's shift a document out as we need it for toArray
- if(options.noReturn) {
- cbValue = true;
- } else {
- cbValue = self.items.shift();
- }
- } else if(self.tailable && !isDead && self.awaitdata) {
- // Excute the tailable cursor once more, will timeout after ~4 sec if awaitdata used
- self.currentNumberOfRetries = self.currentNumberOfRetries - 1;
- if(self.currentNumberOfRetries == 0) {
- self.close(function() {
- callback(new Error("tailable cursor timed out"), null);
- });
- } else {
- getMore(self, callback);
- }
- } else if(self.tailable && !isDead) {
- self.getMoreTimer = setTimeout(function() { getMore(self, callback); }, self.tailableRetryInterval);
- } else {
- self.close(function() {callback(null, null); });
- }
-
- result = null;
- } catch(err) {
- callback(utils.toError(err), null);
- }
- if (cbValue != null) callback(null, cbValue);
- });
-
- getMoreCommand = null;
- } catch(err) {
- // Get more done
- self.state = Cursor.OPEN;
-
- var handleClose = function() {
- callback(utils.toError(err), null);
- };
-
- self.close(handleClose);
- handleClose = null;
- }
-}
-
-/**
- * Gets a detailed information about how the query is performed on this cursor and how
- * long it took the database to process it.
- *
- * @param {Function} callback this will be called after executing this method. The first parameter will always be null while the second parameter will be an object containing the details.
- * @api public
- */
-Cursor.prototype.explain = function(callback) {
- var limit = (-1)*Math.abs(this.limitValue);
-
- // Create a new cursor and fetch the plan
- var cursor = new Cursor(this.db, this.collection, this.selector, this.fields, {
- skip: this.skipValue
- , limit:limit
- , sort: this.sortValue
- , hint: this.hint
- , explain: true
- , snapshot: this.snapshot
- , timeout: this.timeout
- , tailable: this.tailable
- , batchSize: this.batchSizeValue
- , slaveOk: this.slaveOk
- , raw: this.raw
- , readPreference: this.readPreference
- , returnKey: this.returnKey
- , maxScan: this.maxScan
- , min: this.min
- , max: this.max
- , showDiskLoc: this.showDiskLoc
- , comment: this.comment
- , awaitdata: this.awaitdata
- , oplogReplay: this.oplogReplay
- , numberOfRetries: this.numberOfRetries
- , dbName: this.dbName
- });
-
- // Fetch the explaination document
- cursor.nextObject(function(err, item) {
- if(err != null) return callback(utils.toError(err), null);
- // close the cursor
- cursor.close(function(err, result) {
- if(err != null) return callback(utils.toError(err), null);
- callback(null, item);
- });
- });
-};
-
-/**
- * Returns a Node Transform Stream interface for this cursor.
- *
- * Options
- * - **transform** {Function} function of type function(object) { return transformed }, allows for transformation of data before emitting.
- *
- * @return {CursorStream} returns a stream object.
- * @api public
- */
-Cursor.prototype.stream = function stream(options) {
- return new CursorStream(this, options);
-}
-
-/**
- * Close the cursor.
- *
- * @param {Function} callback this will be called after executing this method. The first parameter will always contain null while the second parameter will contain a reference to this cursor.
- * @return {null}
- * @api public
- */
-Cursor.prototype.close = function(callback) {
- var self = this
- this.getMoreTimer && clearTimeout(this.getMoreTimer);
- // Close the cursor if not needed
- if(this.cursorId instanceof Long && this.cursorId.greaterThan(Long.fromInt(0))) {
- try {
- var command = new KillCursorCommand(this.db, [this.cursorId]);
- // Added an empty callback to ensure we don't throw any null exceptions
- this.db._executeQueryCommand(command, {readPreference:self.readPreference, raw:self.raw, connection:self.connection});
- } catch(err) {}
- }
-
- // Null out the connection
- self.connection = null;
- // Reset cursor id
- this.cursorId = Long.fromInt(0);
- // Set to closed status
- this.state = Cursor.CLOSED;
-
- if(callback) {
- callback(null, self);
- self.items = [];
- }
-
- return this;
-};
-
-/**
- * Check if the cursor is closed or open.
- *
- * @return {Boolean} returns the state of the cursor.
- * @api public
- */
-Cursor.prototype.isClosed = function() {
- return this.state == Cursor.CLOSED ? true : false;
-};
-
-/**
- * Init state
- *
- * @classconstant INIT
- **/
-Cursor.INIT = 0;
-
-/**
- * Cursor open
- *
- * @classconstant OPEN
- **/
-Cursor.OPEN = 1;
-
-/**
- * Cursor closed
- *
- * @classconstant CLOSED
- **/
-Cursor.CLOSED = 2;
-
-/**
- * Cursor performing a get more
- *
- * @classconstant OPEN
- **/
-Cursor.GET_MORE = 3;
-
-/**
- * @ignore
- * @api private
- */
-exports.Cursor = Cursor;
diff --git a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/cursorstream.js b/node_modules/mongojs/node_modules/mongodb/lib/mongodb/cursorstream.js
deleted file mode 100644
index 123c266..0000000
--- a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/cursorstream.js
+++ /dev/null
@@ -1,167 +0,0 @@
-var timers = require('timers');
-
-// Set processor, setImmediate if 0.10 otherwise nextTick
-var processor = require('./utils').processor();
-
-/**
- * Module dependecies.
- */
-var Stream = require('stream').Stream;
-
-/**
- * CursorStream
- *
- * Returns a stream interface for the **cursor**.
- *
- * Options
- * - **transform** {Function} function of type function(object) { return transformed }, allows for transformation of data before emitting.
- *
- * Events
- * - **data** {function(item) {}} the data event triggers when a document is ready.
- * - **error** {function(err) {}} the error event triggers if an error happens.
- * - **close** {function() {}} the end event triggers when there is no more documents available.
- *
- * @class Represents a CursorStream.
- * @param {Cursor} cursor a cursor object that the stream wraps.
- * @return {Stream}
- */
-function CursorStream(cursor, options) {
- if(!(this instanceof CursorStream)) return new CursorStream(cursor);
- options = options ? options : {};
-
- Stream.call(this);
-
- this.readable = true;
- this.paused = false;
- this._cursor = cursor;
- this._destroyed = null;
- this.options = options;
-
- // give time to hook up events
- var self = this;
- process.nextTick(function() {
- self._init();
- });
-}
-
-/**
- * Inherit from Stream
- * @ignore
- * @api private
- */
-CursorStream.prototype.__proto__ = Stream.prototype;
-
-/**
- * Flag stating whether or not this stream is readable.
- */
-CursorStream.prototype.readable;
-
-/**
- * Flag stating whether or not this stream is paused.
- */
-CursorStream.prototype.paused;
-
-/**
- * Initialize the cursor.
- * @ignore
- * @api private
- */
-CursorStream.prototype._init = function () {
- if (this._destroyed) return;
- this._next();
-}
-
-/**
- * Pull the next document from the cursor.
- * @ignore
- * @api private
- */
-CursorStream.prototype._next = function () {
- if(this.paused || this._destroyed) return;
-
- var self = this;
- // Get the next object
- processor(function() {
- if(self.paused || self._destroyed) return;
-
- self._cursor.nextObject(function (err, doc) {
- self._onNextObject(err, doc);
- });
- });
-}
-
-/**
- * Handle each document as its returned from the cursor.
- * @ignore
- * @api private
- */
-CursorStream.prototype._onNextObject = function (err, doc) {
- if(err) {
- this.destroy(err);
- return this.emit('end');
- }
-
- // when doc is null we hit the end of the cursor
- if(!doc && (this._cursor.state == 1 || this._cursor.state == 2)) {
- this.emit('end')
- return this.destroy();
- } else if(doc) {
- var data = typeof this.options.transform == 'function' ? this.options.transform(doc) : doc;
- this.emit('data', data);
- this._next();
- }
-}
-
-/**
- * Pauses the stream.
- *
- * @api public
- */
-CursorStream.prototype.pause = function () {
- this.paused = true;
-}
-
-/**
- * Resumes the stream.
- *
- * @api public
- */
-CursorStream.prototype.resume = function () {
- var self = this;
-
- // Don't do anything if we are not paused
- if(!this.paused) return;
- if(!this._cursor.state == 3) return;
-
- process.nextTick(function() {
- self.paused = false;
- // Only trigger more fetching if the cursor is open
- self._next();
- })
-}
-
-/**
- * Destroys the stream, closing the underlying
- * cursor. No more events will be emitted.
- *
- * @api public
- */
-CursorStream.prototype.destroy = function (err) {
- if (this._destroyed) return;
- this._destroyed = true;
- this.readable = false;
-
- this._cursor.close();
-
- if(err && this.listeners('error').length > 0) {
- this.emit('error', err);
- }
-
- this.emit('close');
-}
-
-// TODO - maybe implement the raw option to pass binary?
-//CursorStream.prototype.setEncoding = function () {
-//}
-
-module.exports = exports = CursorStream;
diff --git a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/db.js b/node_modules/mongojs/node_modules/mongodb/lib/mongodb/db.js
deleted file mode 100644
index 3e8bd4e..0000000
--- a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/db.js
+++ /dev/null
@@ -1,2196 +0,0 @@
-/**
- * Module dependencies.
- * @ignore
- */
-var QueryCommand = require('./commands/query_command').QueryCommand
- , DbCommand = require('./commands/db_command').DbCommand
- , MongoReply = require('./responses/mongo_reply').MongoReply
- , Admin = require('./admin').Admin
- , Collection = require('./collection').Collection
- , Server = require('./connection/server').Server
- , ReplSet = require('./connection/repl_set/repl_set').ReplSet
- , ReadPreference = require('./connection/read_preference').ReadPreference
- , Mongos = require('./connection/mongos').Mongos
- , Cursor = require('./cursor').Cursor
- , EventEmitter = require('events').EventEmitter
- , InsertCommand = require('./commands/insert_command').InsertCommand
- , f = require('util').format
- , inherits = require('util').inherits
- , crypto = require('crypto')
- , timers = require('timers')
- , utils = require('./utils')
-
- // Authentication methods
- , mongodb_cr_authenticate = require('./auth/mongodb_cr.js').authenticate
- , mongodb_gssapi_authenticate = require('./auth/mongodb_gssapi.js').authenticate
- , mongodb_sspi_authenticate = require('./auth/mongodb_sspi.js').authenticate
- , mongodb_plain_authenticate = require('./auth/mongodb_plain.js').authenticate
- , mongodb_x509_authenticate = require('./auth/mongodb_x509.js').authenticate
- , mongodb_scram_authenticate = require('./auth/mongodb_scram.js').authenticate;
-
-var hasKerberos = false;
-// Check if we have a the kerberos library
-try {
- require('kerberos');
- hasKerberos = true;
-} catch(err) {}
-
-// Set processor, setImmediate if 0.10 otherwise nextTick
-var processor = require('./utils').processor();
-
-/**
- * Create a new Db instance.
- *
- * Options
- * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowledgement of write and w >= 1, w = 'majority' or tag acknowledges the write
- * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option)
- * - **fsync**, (Boolean, default:false) write waits for fsync before returning, from MongoDB 2.6 on, fsync cannot be combined with journal
- * - **j**, (Boolean, default:false) write waits for journal sync before returning
- * - **readPreference** {String}, the preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
- * - **native_parser** {Boolean, default:false}, use c++ bson parser.
- * - **forceServerObjectId** {Boolean, default:false}, force server to create _id fields instead of client.
- * - **pkFactory** {Object}, object overriding the basic ObjectID primary key generation.
- * - **serializeFunctions** {Boolean, default:false}, serialize functions.
- * - **raw** {Boolean, default:false}, perform operations using raw bson buffers.
- * - **recordQueryStats** {Boolean, default:false}, record query statistics during execution.
- * - **retryMiliSeconds** {Number, default:5000}, number of milliseconds between retries.
- * - **numberOfRetries** {Number, default:5}, number of retries off connection.
- * - **logger** {Object, default:null}, an object representing a logger that you want to use, needs to support functions debug, log, error **({error:function(message, object) {}, log:function(message, object) {}, debug:function(message, object) {}})**.
- * - **slaveOk** {Number, default:null}, force setting of SlaveOk flag on queries (only use when explicitly connecting to a secondary server).
- * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits
- * - **bufferMaxEntries** {Number, default: -1}, sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited
- *
- * @class Represents a Db
- * @param {String} databaseName name of the database.
- * @param {Object} serverConfig server config object.
- * @param {Object} [options] additional options for the collection.
- */
-function Db(databaseName, serverConfig, options) {
- if(!(this instanceof Db)) return new Db(databaseName, serverConfig, options);
- EventEmitter.call(this);
- var self = this;
- this.databaseName = databaseName;
- this.serverConfig = serverConfig;
- this.options = options == null ? {} : options;
- // State to check against if the user force closed db
- this._applicationClosed = false;
- // Fetch the override flag if any
- var overrideUsedFlag = this.options['override_used_flag'] == null ? false : this.options['override_used_flag'];
-
- // Verify that nobody is using this config
- if(!overrideUsedFlag && this.serverConfig != null && typeof this.serverConfig == 'object' && this.serverConfig._isUsed && this.serverConfig._isUsed()) {
- throw new Error('A Server or ReplSet instance cannot be shared across multiple Db instances');
- } else if(!overrideUsedFlag && typeof this.serverConfig == 'object'){
- // Set being used
- this.serverConfig._used = true;
- }
-
- // Allow slaveOk override
- this.slaveOk = this.options['slave_ok'] == null ? false : this.options['slave_ok'];
- this.slaveOk = this.options['slaveOk'] == null ? this.slaveOk : this.options['slaveOk'];
-
- // Number of operations to buffer before failure
- this.bufferMaxEntries = typeof this.options['bufferMaxEntries'] == 'number' ? this.options['bufferMaxEntries'] : -1;
-
- // Ensure we have a valid db name
- validateDatabaseName(databaseName);
-
- // Contains all the connections for the db
- try {
- this.native_parser = this.options.native_parser;
- // The bson lib
- var bsonLib = this.bsonLib = this.options.native_parser ? require('bson').BSONNative : require('bson').BSONPure;
- bsonLib = require('bson').BSONPure;
- // Fetch the serializer object
- var BSON = bsonLib.BSON;
-
- // Create a new instance
- this.bson = new BSON([bsonLib.Long, bsonLib.ObjectID, bsonLib.Binary, bsonLib.Code, bsonLib.DBRef, bsonLib.Symbol, bsonLib.Double, bsonLib.Timestamp, bsonLib.MaxKey, bsonLib.MinKey]);
- this.bson.promoteLongs = this.options.promoteLongs == null ? true : this.options.promoteLongs;
-
- // Backward compatibility to access types
- this.bson_deserializer = bsonLib;
- this.bson_serializer = bsonLib;
-
- // Add any overrides to the serializer and deserializer
- this.bson_deserializer.promoteLongs = this.options.promoteLongs == null ? true : this.options.promoteLongs;
- } catch (err) {
- // If we tried to instantiate the native driver
- var msg = 'Native bson parser not compiled, please compile '
- + 'or avoid using native_parser=true';
- throw Error(msg);
- }
-
- // Internal state of the server
- this._state = 'disconnected';
-
- this.pkFactory = this.options.pkFactory == null ? bsonLib.ObjectID : this.options.pkFactory;
- this.forceServerObjectId = this.options.forceServerObjectId != null ? this.options.forceServerObjectId : false;
-
- // Added safe
- this.safe = this.options.safe == null ? false : this.options.safe;
-
- // If we have not specified a "safe mode" we just print a warning to the console
- if(this.options.safe == null
- && this.options.w == null
- && this.options.j == null
- && this.options.journal == null
- && this.options.fsync == null) {
- console.log("========================================================================================");
- console.log("= Please ensure that you set the default write concern for the database by setting =");
- console.log("= one of the options =");
- console.log("= =");
- console.log("= w: (value of > -1 or the string 'majority'), where < 1 means =");
- console.log("= no write acknowledgement =");
- console.log("= journal: true/false, wait for flush to journal before acknowledgement =");
- console.log("= fsync: true/false, wait for flush to file system before acknowledgement =");
- console.log("= =");
- console.log("= For backward compatibility safe is still supported and =");
- console.log("= allows values of [true | false | {j:true} | {w:n, wtimeout:n} | {fsync:true}] =");
- console.log("= the default value is false which means the driver receives does not =");
- console.log("= return the information of the success/error of the insert/update/remove =");
- console.log("= =");
- console.log("= ex: new Db(new Server('localhost', 27017), {safe:false}) =");
- console.log("= =");
- console.log("= http://www.mongodb.org/display/DOCS/getLastError+Command =");
- console.log("= =");
- console.log("= The default of no acknowledgement will change in the very near future =");
- console.log("= =");
- console.log("= This message will disappear when the default safe is set on the driver Db =");
- console.log("========================================================================================");
- }
-
- // Internal states variables
- this.notReplied ={};
- this.isInitializing = true;
- this.openCalled = false;
-
- // Command queue, keeps a list of incoming commands that need to be executed once the connection is up
- this.commands = [];
-
- // Set up logger
- this.logger = this.options.logger != null
- && (typeof this.options.logger.debug == 'function')
- && (typeof this.options.logger.error == 'function')
- && (typeof this.options.logger.log == 'function')
- ? this.options.logger : {error:function(message, object) {}, log:function(message, object) {}, debug:function(message, object) {}};
-
- // Associate the logger with the server config
- this.serverConfig.logger = this.logger;
- if(this.serverConfig.strategyInstance) this.serverConfig.strategyInstance.logger = this.logger;
- this.tag = new Date().getTime();
- // Just keeps list of events we allow
- this.eventHandlers = {error:[], parseError:[], poolReady:[], message:[], close:[]};
-
- // Controls serialization options
- this.serializeFunctions = this.options.serializeFunctions != null ? this.options.serializeFunctions : false;
-
- // Raw mode
- this.raw = this.options.raw != null ? this.options.raw : false;
-
- // Record query stats
- this.recordQueryStats = this.options.recordQueryStats != null ? this.options.recordQueryStats : false;
-
- // If we have server stats let's make sure the driver objects have it enabled
- if(this.recordQueryStats == true) {
- this.serverConfig.enableRecordQueryStats(true);
- }
-
- // Retry information
- this.retryMiliSeconds = this.options.retryMiliSeconds != null ? this.options.retryMiliSeconds : 1000;
- this.numberOfRetries = this.options.numberOfRetries != null ? this.options.numberOfRetries : 60;
-
- // Set default read preference if any
- this.readPreference = this.options.readPreference;
-
- // Set slaveOk if we have specified a secondary or secondary preferred readPreference
- if(this.readPreference == ReadPreference.SECONDARY ||
- this.readPreference == ReadPreference.SECONDARY_PREFERRED) {
- this.slaveOk = true;
- }
-
- // Set read preference on serverConfig if none is set
- // but the db one was
- if(this.serverConfig.options.readPreference != null) {
- this.serverConfig.setReadPreference(this.serverConfig.options.readPreference);
- } else if(this.readPreference != null) {
- this.serverConfig.setReadPreference(this.readPreference);
- }
-
- // Ensure we keep a reference to this db
- this.serverConfig._dbStore.add(this);
-};
-
-/**
- * @ignore
- */
-function validateDatabaseName(databaseName) {
- if(typeof databaseName !== 'string') throw new Error("database name must be a string");
- if(databaseName.length === 0) throw new Error("database name cannot be the empty string");
- if(databaseName == '$external') return;
-
- var invalidChars = [" ", ".", "$", "/", "\\"];
- for(var i = 0; i < invalidChars.length; i++) {
- if(databaseName.indexOf(invalidChars[i]) != -1) throw new Error("database names cannot contain the character '" + invalidChars[i] + "'");
- }
-}
-
-/**
- * @ignore
- */
-inherits(Db, EventEmitter);
-
-/**
- * Initialize the database connection.
- *
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the index information or null if an error occurred.
- * @return {null}
- * @api public
- */
-Db.prototype.open = function(callback) {
- var self = this;
-
- // Check that the user has not called this twice
- if(this.openCalled) {
- // Close db
- this.close();
- // Throw error
- throw new Error("db object already connecting, open cannot be called multiple times");
- }
-
- // If we have a specified read preference
- if(this.readPreference != null) this.serverConfig.setReadPreference(this.readPreference);
-
- // Set that db has been opened
- this.openCalled = true;
-
- // Set the status of the server
- self._state = 'connecting';
-
- // Set up connections
- if(self.serverConfig instanceof Server || self.serverConfig instanceof ReplSet || self.serverConfig instanceof Mongos) {
- // Ensure we have the original options passed in for the server config
- var connect_options = {};
- for(var name in self.serverConfig.options) {
- connect_options[name] = self.serverConfig.options[name]
- }
- connect_options.firstCall = true;
-
- // Attempt to connect
- self.serverConfig.connect(self, connect_options, function(err, result) {
- if(err != null) {
- // Close db to reset connection
- return self.close(function () {
- // Return error from connection
- return callback(err, null);
- });
- }
- // Set the status of the server
- self._state = 'connected';
- // If we have queued up commands execute a command to trigger replays
- if(self.commands.length > 0) _execute_queued_command(self);
- // Callback
- process.nextTick(function() {
- try {
- callback(null, self);
- } catch(err) {
- self.close();
- throw err;
- }
- });
- });
- } else {
- try {
- callback(Error("Server parameter must be of type Server, ReplSet or Mongos"), null);
- } catch(err) {
- self.close();
- throw err;
- }
- }
-};
-
-/**
- * Create a new Db instance sharing the current socket connections.
- *
- * @param {String} dbName the name of the database we want to use.
- * @return {Db} a db instance using the new database.
- * @api public
- */
-Db.prototype.db = function(dbName) {
- // Copy the options and add out internal override of the not shared flag
- var options = {};
- for(var key in this.options) {
- options[key] = this.options[key];
- }
-
- // Add override flag
- options['override_used_flag'] = true;
- // Check if the db already exists and reuse if it's the case
- var db = this.serverConfig._dbStore.fetch(dbName);
-
- // Create a new instance
- if(!db) {
- db = new Db(dbName, this.serverConfig, options);
- }
-
- // Return the db object
- return db;
-};
-
-/**
- * Close the current db connection, including all the child db instances. Emits close event and calls optional callback.
- *
- * @param {Boolean} [forceClose] connection can never be reused.
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results or null if an error occurred.
- * @return {null}
- * @api public
- */
-Db.prototype.close = function(forceClose, callback) {
- var self = this;
- // Ensure we force close all connections
- this._applicationClosed = false;
-
- if(typeof forceClose == 'function') {
- callback = forceClose;
- } else if(typeof forceClose == 'boolean') {
- this._applicationClosed = forceClose;
- }
-
- this.serverConfig.close(function(err, result) {
- // You can reuse the db as everything is shut down
- self.openCalled = false;
- // If we have a callback call it
- if(callback) callback(err, result);
- });
-};
-
-/**
- * Access the Admin database
- *
- * @param {Function} [callback] returns the results.
- * @return {Admin} the admin db object.
- * @api public
- */
-Db.prototype.admin = function(callback) {
- if(callback == null) return new Admin(this);
- callback(null, new Admin(this));
-};
-
-/**
- * DEPRECATED: Returns a cursor to all the collection information. Does not work with 2.8 or higher when using
- * other storage engines
- *
- * @param {String} [collectionName] the collection name we wish to retrieve the information from.
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the options or null if an error occurred.
- * @return {null}
- * @api public
- * @deprecated
- */
-Db.prototype.collectionsInfo = function(collectionName, callback) {
- if(callback == null && typeof collectionName == 'function') { callback = collectionName; collectionName = null; }
- // Create selector
- var selector = {};
- // If we are limiting the access to a specific collection name
- if(collectionName != null) selector.name = this.databaseName + "." + collectionName;
-
- // Return Cursor
- // callback for backward compatibility
- if(callback) {
- callback(null, new Cursor(this, new Collection(this, DbCommand.SYSTEM_NAMESPACE_COLLECTION), selector));
- } else {
- return new Cursor(this, new Collection(this, DbCommand.SYSTEM_NAMESPACE_COLLECTION), selector);
- }
-};
-
-/**
- * Get the list of all collection names for the specified db
- *
- * Options
- * - **namesOnly** {String, default:false}, Return only the full collection namespace.
- * - **filter** {String|Object, default:null}, Filter collections by this filter (string or object)
- *
- * @param {String} [collectionName] the collection name we wish to filter by.
- * @param {Object} [options] additional options during update.
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the collection names or null if an error occurred.
- * @return {null}
- * @api public
- */
-Db.prototype.listCollections = function(name, options, callback) {
- var args = Array.prototype.slice.call(arguments, 0);
- callback = args.pop();
- name = args.length ? args.shift() : null;
- options = args.length ? args.shift() || {} : {};
- var self = this;
-
- // Only passed in options
- if(name != null && typeof name == 'object') options = name, name = null;
- // Do we have a filter
- var filter = options.filter || {};
-
- // Fallback to pre 2.8 list collections
- var fallbackListCollections = function() {
- // Ensure we have a filter
- filter = filter || {};
- // Set the name variable for the filter
- if(typeof name == 'string') filter.name = f("%s.%s", self.databaseName, name);
- // Get the system namespace collection as a cursor
- var cursor = self.collection(DbCommand.SYSTEM_NAMESPACE_COLLECTION).find(filter);
- // Get all documents
- cursor.toArray(function(err, documents) {
- if(err != null) return callback(err, null);
-
- // Filter out all the non valid names
- var filtered_documents = documents.filter(function(document) {
- if(document.name.indexOf('$') != -1) return false;
- return true;
- });
-
- // If we are returning only the names
- if(options.namesOnly) {
- filtered_documents = filtered_documents.map(function(document) { return document.name });
- }
-
- // Return filtered items
- callback(null, filtered_documents);
- });
- }
-
- // Set up the listCollectionsCommand
- var listCollectionsCommand = {listCollections:1};
- // Add the optional filter if available
- if(filter) listCollectionsCommand.filter = filter;
- // Set the name variable for the filter
- if(typeof name == 'string') filter.name = name;
-
- // Attempt to execute the collection list
- self.command(listCollectionsCommand, function(err, result) {
- if(err) return fallbackListCollections();
- // List of result documents that have been filtered
- var filtered_documents = result.collections.filter(function(document) {
- if(name && document.name != name) return false;
- if(document.name.indexOf('$') != -1) return false;
- return true;
- });
-
- // If we are returning only the names
- if(options.namesOnly) {
- filtered_documents = filtered_documents.map(function(document) { return document.name });
- }
-
- // Return filtered items
- callback(null, filtered_documents);
- });
-};
-
-/**
- * Get the list of all collection names for the specified db
- *
- * Options
- * - **namesOnly** {String, default:false}, Return only the full collection namespace.
- *
- * @param {String} [collectionName] the collection name we wish to filter by.
- * @param {Object} [options] additional options during update.
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the collection names or null if an error occurred.
- * @return {null}
- * @api public
- */
-Db.prototype.collectionNames = function(collectionName, options, callback) {
- var args = Array.prototype.slice.call(arguments, 0);
- this.listCollections.apply(this, args);
-};
-
-/**
- * Fetch a specific collection (containing the actual collection information). If the application does not use strict mode you can
- * can use it without a callback in the following way. var collection = db.collection('mycollection');
- *
- * Options
-* - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowledgement of write and w >= 1, w = 'majority' or tag acknowledges the write
- * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option)
- * - **fsync**, (Boolean, default:false) write waits for fsync before returning, from MongoDB 2.6 on, fsync cannot be combined with journal
- * - **j**, (Boolean, default:false) write waits for journal sync before returning
- * - **serializeFunctions** {Boolean, default:false}, serialize functions on the document.
- * - **raw** {Boolean, default:false}, perform all operations using raw bson objects.
- * - **pkFactory** {Object}, object overriding the basic ObjectID primary key generation.
- * - **readPreference** {String}, the preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
- * - **strict**, (Boolean, default:false) returns an error if the collection does not exist
- *
- * @param {String} collectionName the collection name we wish to access.
- * @param {Object} [options] returns option results.
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the collection or null if an error occurred.
- * @return {null}
- * @api public
- */
-Db.prototype.collection = function(collectionName, options, callback) {
- if(typeof options == 'function') callback = options, options = {};
- options = options || {};
- var self = this;
-
- if(options == null || !options.strict) {
- try {
- var collection = new Collection(self, collectionName, self.pkFactory, options);
- if(callback) callback(null, collection);
- return collection;
- } catch(err) {
- if(callback) return callback(err);
- throw err;
- }
- }
-
- // Strict mode
- if(typeof callback != 'function') {
- throw utils.toError(f("A callback is required in strict mode. While getting collection %s.", collectionName));
- }
-
- self.listCollections(collectionName, function(err, collections) {
- if(err != null) return callback(err, null);
- if(collections.length == 0) return callback(utils.toError(f("Collection %s does not exist. Currently in strict mode.", collectionName)), null);
-
- try {
- return callback(null, new Collection(self, collectionName, self.pkFactory, options));
- } catch(err) {
- return callback(err, null);
- }
- });
-};
-
-/**
- * Fetch all collections for the current db.
- *
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the collections or null if an error occurred.
- * @return {null}
- * @api public
- */
-Db.prototype.collections = function(callback) {
- var self = this;
- // Let's get the collection names
- self.collectionNames(function(err, documents) {
- if(err != null) return callback(err, null);
- var collections = [];
- documents.forEach(function(document) {
- collections.push(new Collection(self, document.name.replace(self.databaseName + ".", ''), self.pkFactory));
- });
- // Return the collection objects
- callback(null, collections);
- });
-};
-
-/**
- * Evaluate javascript on the server
- *
- * Options
- * - **nolock** {Boolean, default:false}, Tell MongoDB not to block on the evaulation of the javascript.
- *
- * @param {Code} code javascript to execute on server.
- * @param {Object|Array} [parameters] the parameters for the call.
- * @param {Object} [options] the options
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from eval or null if an error occurred.
- * @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 cmd = {'$eval':finalCode, 'args':finalParameters};
- // Check if the nolock parameter is passed in
- if(options['nolock']) {
- cmd['nolock'] = options['nolock'];
- }
-
- // Set primary read preference
- options.readPreference = ReadPreference.PRIMARY;
-
- // Execute the command
- this.command(cmd, options, function(err, result) {
- if(err) return callback(err, null);
- if(result && result.ok == 1) return callback(null, result.retval);
- if(result) return callback(new Error("eval failed: " + result.errmsg), null);
- callback(err, result);
- });
-};
-
-/**
- * Dereference a dbref, against a db
- *
- * @param {DBRef} dbRef db reference object we wish to resolve.
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from dereference or null if an error occurred.
- * @return {null}
- * @api public
- */
-Db.prototype.dereference = function(dbRef, callback) {
- var db = this;
- // If we have a db reference then let's get the db first
- if(dbRef.db != null) db = this.db(dbRef.db);
- // Fetch the collection and find the reference
- var collection = db.collection(dbRef.namespace);
- collection.findOne({'_id':dbRef.oid}, function(err, result) {
- callback(err, result);
- });
-}
-
-/**
- * Logout user from server, fire off on all connections and remove all auth info
- *
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from logout or null if an error occurred.
- * @return {null}
- * @api public
- */
-Db.prototype.logout = function(options, callback) {
- var self = this;
- // Unpack calls
- var args = Array.prototype.slice.call(arguments, 0);
- callback = args.pop();
- options = args.length ? args.shift() || {} : {};
-
- // Number of connections we need to logout from
- var numberOfConnections = this.serverConfig.allRawConnections().length;
- // logout command
- var cmd = {'logout':1};
- // Add onAll to login to ensure all connection are logged out
- options.onAll = true;
-
- // Execute the command
- this.command(cmd, options, function(err, result) {
- // Count down
- numberOfConnections = numberOfConnections - 1;
- // Work around the case where the number of connections are 0
- if(numberOfConnections <= 0 && typeof callback == 'function') {
- var internalCallback = callback;
- callback = null;
-
- // Remove the db from auths
- self.serverConfig.auth.remove(self.databaseName);
- // Callback with result
- internalCallback(null, result.ok == 1 ? true : false);
- }
- });
-}
-
-/**
- * Authenticate a user against the server.
- * authMechanism
- * Options
- * - **authMechanism** {String, default:MONGODB-CR}, The authentication mechanism to use, GSSAPI or MONGODB-CR
- *
- * @param {String} username username.
- * @param {String} password password.
- * @param {Object} [options] the options
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from authentication or null if an error occurred.
- * @return {null}
- * @api public
- */
-Db.prototype.authenticate = function(username, password, options, callback) {
- var self = this;
-
- if(typeof options == 'function') {
- callback = options;
- options = {};
- }
-
- // Set default mechanism
- if(!options.authMechanism) {
- options.authMechanism = 'DEFAULT';
- } else if(options.authMechanism != 'GSSAPI'
- && options.authMechanism != 'MONGODB-CR'
- && options.authMechanism != 'MONGODB-X509'
- && options.authMechanism != 'SCRAM-SHA-1'
- && options.authMechanism != 'PLAIN') {
- return callback(new Error("only GSSAPI, PLAIN, MONGODB-X509, SCRAM-SHA-1 or MONGODB-CR is supported by authMechanism"));
- }
-
- // the default db to authenticate against is 'this'
- // if authententicate is called from a retry context, it may be another one, like admin
- var authdb = options.authdb ? options.authdb : self.databaseName;
- authdb = options.authSource ? options.authSource : authdb;
-
- // Callback
- var _callback = function(err, result) {
- if(self.listeners("authenticated").length > 0) {
- self.emit("authenticated", err, result);
- }
-
- // Return to caller
- callback(err, result);
- }
-
- // If classic auth delegate to auth command
- if(options.authMechanism == 'MONGODB-CR') {
- mongodb_cr_authenticate(self, username, password, authdb, options, _callback);
- } else if(options.authMechanism == 'PLAIN') {
- mongodb_plain_authenticate(self, username, password, options, _callback);
- } else if(options.authMechanism == 'MONGODB-X509') {
- mongodb_x509_authenticate(self, username, password, options, _callback);
- } else if(options.authMechanism == 'SCRAM-SHA-1') {
- mongodb_scram_authenticate(self, username, password, authdb, options, _callback);
- } else if(options.authMechanism == 'DEFAULT') {
- // Get a server
- var servers = this.serverConfig.allServerInstances();
- // if the max wire protocol version >= 3 do scram otherwise mongodb_cr
- if(servers.length > 0 && servers[0].isMasterDoc && servers[0].isMasterDoc.maxWireVersion >= 3) {
- mongodb_scram_authenticate(self, username, password, authdb, options, _callback);
- } else {
- mongodb_cr_authenticate(self, username, password, authdb, options, _callback);
- }
- } else if(options.authMechanism == 'GSSAPI') {
- //
- // Kerberos library is not installed, throw and error
- if(hasKerberos == false) {
- console.log("========================================================================================");
- console.log("= Please make sure that you install the Kerberos library to use GSSAPI =");
- console.log("= =");
- console.log("= npm install -g kerberos =");
- console.log("= =");
- console.log("= The Kerberos package is not installed by default for simplicities sake =");
- console.log("= and needs to be global install =");
- console.log("========================================================================================");
- throw new Error("Kerberos library not installed");
- }
-
- if(process.platform == 'win32') {
- mongodb_sspi_authenticate(self, username, password, authdb, options, _callback);
- } else {
- // We have the kerberos library, execute auth process
- mongodb_gssapi_authenticate(self, username, password, authdb, options, _callback);
- }
- }
-};
-
-/**
- * Add a user to the database.
- *
- * Options
- * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowledgement of write and w >= 1, w = 'majority' or tag acknowledges the write
- * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option)
- * - **fsync**, (Boolean, default:false) write waits for fsync before returning, from MongoDB 2.6 on, fsync cannot be combined with journal
- * - **j**, (Boolean, default:false) write waits for journal sync before returning
- * - **customData**, (Object, default:{}) custom data associated with the user (only Mongodb 2.6 or higher)
- * - **roles**, (Array, default:[]) roles associated with the created user (only Mongodb 2.6 or higher)
- *
- * @param {String} username username.
- * @param {String} password password.
- * @param {Object} [options] additional options during update.
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from addUser or null if an error occurred.
- * @return {null}
- * @api public
- */
-Db.prototype.addUser = function(username, password, options, callback) {
- // Checkout a write connection to get the server capabilities
- var connection = this.serverConfig.checkoutWriter();
- if(connection != null
- && connection.serverCapabilities != null
- && connection.serverCapabilities.hasAuthCommands) {
- return _executeAuthCreateUserCommand(this, username, password, options, callback);
- }
-
- // Unpack the parameters
- var self = this;
- var args = Array.prototype.slice.call(arguments, 2);
- callback = args.pop();
- options = args.length ? args.shift() || {} : {};
-
- // Get the error options
- var errorOptions = _getWriteConcern(this, options);
- errorOptions.w = errorOptions.w == null ? 1 : errorOptions.w;
- // Use node md5 generator
- var md5 = crypto.createHash('md5');
- // Generate keys used for authentication
- md5.update(username + ":mongo:" + password);
- var userPassword = md5.digest('hex');
- // Fetch a user collection
- var collection = this.collection(DbCommand.SYSTEM_USER_COLLECTION);
- // Check if we are inserting the first user
- collection.count({}, function(err, count) {
- // We got an error (f.ex not authorized)
- if(err != null) return callback(err, null);
- // Check if the user exists and update i
- collection.find({user: username}, {dbName: options['dbName']}).toArray(function(err, documents) {
- // We got an error (f.ex not authorized)
- if(err != null) return callback(err, null);
- // Add command keys
- var commandOptions = errorOptions;
- commandOptions.dbName = options['dbName'];
- commandOptions.upsert = true;
-
- // We have a user, let's update the password or upsert if not
- collection.update({user: username},{$set: {user: username, pwd: userPassword}}, commandOptions, function(err, results, full) {
- if(count == 0 && err) {
- callback(null, [{user:username, pwd:userPassword}]);
- } else if(err) {
- callback(err, null)
- } else {
- callback(null, [{user:username, pwd:userPassword}]);
- }
- });
- });
- });
-};
-
-/**
- * @ignore
- */
-var _executeAuthCreateUserCommand = function(self, username, password, options, callback) {
- // Special case where there is no password ($external users)
- if(typeof username == 'string'
- && password != null && typeof password == 'object') {
- callback = options;
- options = password;
- password = null;
- }
-
- // Unpack all options
- if(typeof options == 'function') {
- callback = options;
- options = {};
- }
-
- // Error out if we digestPassword set
- if(options.digestPassword != null) {
- throw utils.toError("The digestPassword option is not supported via add_user. Please use db.command('createUser', ...) instead for this option.");
- }
-
- // Get additional values
- var customData = options.customData != null ? options.customData : {};
- var roles = Array.isArray(options.roles) ? options.roles : [];
- var maxTimeMS = typeof options.maxTimeMS == 'number' ? options.maxTimeMS : null;
-
- // If not roles defined print deprecated message
- if(roles.length == 0) {
- console.log("Creating a user without roles is deprecated in MongoDB >= 2.6");
- }
-
- // Get the error options
- var writeConcern = _getWriteConcern(self, options);
- var commandOptions = {writeCommand:true};
- if(options['dbName']) commandOptions.dbName = options['dbName'];
-
- // Add maxTimeMS to options if set
- if(maxTimeMS != null) commandOptions.maxTimeMS = maxTimeMS;
-
- // Check the db name and add roles if needed
- if((self.databaseName.toLowerCase() == 'admin' || options.dbName == 'admin') && !Array.isArray(options.roles)) {
- roles = ['root']
- } else if(!Array.isArray(options.roles)) {
- roles = ['dbOwner']
- }
-
- // Build the command to execute
- var command = {
- createUser: username
- , customData: customData
- , roles: roles
- , digestPassword:false
- , writeConcern: writeConcern
- }
-
- // Use node md5 generator
- var md5 = crypto.createHash('md5');
- // Generate keys used for authentication
- md5.update(username + ":mongo:" + password);
- var userPassword = md5.digest('hex');
-
- // No password
- if(typeof password == 'string') {
- command.pwd = userPassword;
- }
-
- // Execute the command
- self.command(command, commandOptions, function(err, result) {
- if(err) return callback(err, null);
- callback(!result.ok ? utils.toError("Failed to add user " + username) : null
- , result.ok ? [{user: username, pwd: ''}] : null);
- })
-}
-
-/**
- * Remove a user from a database
- *
- * Options
- * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowledgement of write and w >= 1, w = 'majority' or tag acknowledges the write
- * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option)
- * - **fsync**, (Boolean, default:false) write waits for fsync before returning, from MongoDB 2.6 on, fsync cannot be combined with journal
- * - **j**, (Boolean, default:false) write waits for journal sync before returning
- *
- * @param {String} username username.
- * @param {Object} [options] additional options during update.
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from removeUser or null if an error occurred.
- * @return {null}
- * @api public
- */
-Db.prototype.removeUser = function(username, options, callback) {
- // Checkout a write connection to get the server capabilities
- var connection = this.serverConfig.checkoutWriter();
- if(connection != null && connection.serverCapabilities != null && connection.serverCapabilities.hasAuthCommands) {
- return _executeAuthRemoveUserCommand(this, username, options, callback);
- }
-
- // Unpack the parameters
- var self = this;
- var args = Array.prototype.slice.call(arguments, 1);
- callback = args.pop();
- options = args.length ? args.shift() || {} : {};
-
- // Figure out the safe mode settings
- var safe = self.safe != null && self.safe == false ? {w: 1} : self.safe;
- // Override with options passed in if applicable
- safe = options != null && options['safe'] != null ? options['safe'] : safe;
- // Ensure it's at least set to safe
- safe = safe == null ? {w: 1} : safe;
-
- // Fetch a user collection
- var collection = this.collection(DbCommand.SYSTEM_USER_COLLECTION);
- collection.findOne({user: username}, {dbName: options['dbName']}, function(err, user) {
- if(user != null) {
- // Add command keys
- var commandOptions = safe;
- commandOptions.dbName = options['dbName'];
-
- collection.remove({user: username}, commandOptions, function(err, result) {
- callback(err, true);
- });
- } else {
- callback(err, false);
- }
- });
-};
-
-var _executeAuthRemoveUserCommand = function(self, username, options, callback) {
- // Unpack all options
- if(typeof options == 'function') {
- callback = options;
- options = {};
- }
-
- // Get the error options
- var writeConcern = _getWriteConcern(self, options);
- var commandOptions = {writeCommand:true};
- if(options['dbName']) commandOptions.dbName = options['dbName'];
-
- // Get additional values
- var maxTimeMS = typeof options.maxTimeMS == 'number' ? options.maxTimeMS : null;
-
- // Add maxTimeMS to options if set
- if(maxTimeMS != null) commandOptions.maxTimeMS = maxTimeMS;
-
- // Build the command to execute
- var command = {
- dropUser: username
- , writeConcern: writeConcern
- }
-
- // Execute the command
- self.command(command, commandOptions, function(err, result) {
- if(err) return callback(err, null);
- callback(null, result.ok ? true : false);
- })
-}
-
-/**
- * Creates a collection on a server pre-allocating space, need to create f.ex capped collections.
- *
- * Options
-* - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowledgement of write and w >= 1, w = 'majority' or tag acknowledges the write
- * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option)
- * - **fsync**, (Boolean, default:false) write waits for fsync before returning, from MongoDB 2.6 on, fsync cannot be combined with journal
- * - **j**, (Boolean, default:false) write waits for journal sync before returning
- * - **serializeFunctions** {Boolean, default:false}, serialize functions on the document.
- * - **raw** {Boolean, default:false}, perform all operations using raw bson objects.
- * - **pkFactory** {Object}, object overriding the basic ObjectID primary key generation.
- * - **capped** {Boolean, default:false}, create a capped collection.
- * - **size** {Number}, the size of the capped collection in bytes.
- * - **max** {Number}, the maximum number of documents in the capped collection.
- * - **autoIndexId** {Boolean, default:true}, create an index on the _id field of the document, True by default on MongoDB 2.2 or higher off for version < 2.2.
- * - **readPreference** {String}, the preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
- * - **strict**, (Boolean, default:false) throws an error if collection already exists
- *
- * @param {String} collectionName the collection name we wish to access.
- * @param {Object} [options] returns option results.
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from createCollection or null if an error occurred.
- * @return {null}
- * @api public
- */
-Db.prototype.createCollection = function(collectionName, options, callback) {
- var self = this;
- if(typeof options == 'function') {
- callback = options;
- options = {};
- }
-
- // Figure out the safe mode settings
- var safe = self.safe != null && self.safe == false ? {w: 1} : self.safe;
- // Override with options passed in if applicable
- safe = options != null && options['safe'] != null ? options['safe'] : safe;
- // Ensure it's at least set to safe
- safe = safe == null ? {w: 1} : safe;
- // Check if we have the name
- this.listCollections(collectionName, function(err, collections) {
- if(err != null) return callback(err, null);
- if(collections.length > 0 && options.strict) {
- return callback(utils.toError(f("Collection %s already exists. Currently in strict mode.", collectionName)), null);
- } else if (collections.length > 0) {
- try { return callback(null, new Collection(self, collectionName, self.pkFactory, options)); }
- catch(err) { return callback(err); }
- }
-
- // logout command
- var cmd = {'create':collectionName};
-
- for(var name in options) {
- if(options[name] != null && typeof options[name] != 'function') cmd[name] = options[name];
- }
-
- // Execute the command
- self.command(cmd, options, function(err, result) {
- if(err && err.code && err.code != 48 && options && options.strict) return callback(err, null);
- try {
- callback(null, new Collection(self, collectionName, self.pkFactory, options));
- } catch(err) {
- callback(utils.toError(err), null);
- }
- });
- });
-};
-
-var _getReadConcern = function(self, options) {
- if(options.readPreference) return options.readPreference;
- if(self.readPreference) return self.readPreference;
- return 'primary';
-}
-
-/**
- * Execute a command hash against MongoDB. This lets you acess any commands not available through the api on the server.
- *
- * Options
- * - **readPreference** {String}, the preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
- * - **maxTimeMS** {Number}, number of milliseconds to wait before aborting the query.
- * - **ignoreCommandFilter** {Boolean}, overrides the default redirection of certain commands to primary.
- * - **writeCommand** {Boolean, default: false}, signals this is a write command and to ignore read preferences
- * - **checkKeys** {Boolean, default: false}, overrides the default not to check the key names for the command
- *
- * @param {Object} selector the command hash to send to the server, ex: {ping:1}.
- * @param {Object} [options] additional options for the command.
- * @param {Function} callback this will be called after executing this method. The command always return the whole result of the command as the second parameter.
- * @return {null}
- * @api public
- */
-Db.prototype.command = function(selector, options, callback) {
- if(typeof options == 'function') {
- callback = options;
- options = {};
- }
-
- // Make a shallow copy so no modifications happen on the original
- options = utils.shallowObjectCopy(options);
-
- // Ignore command preference (I know what I'm doing)
- var ignoreCommandFilter = options.ignoreCommandFilter ? options.ignoreCommandFilter : false;
-
- // Get read preference if we set one
- var readPreference = _getReadConcern(this, options);
-
- // Ensure only commands who support read Prefrences are exeuted otherwise override and use Primary
- if(readPreference != false && ignoreCommandFilter == false) {
- if(selector['group'] || selector['aggregate'] || selector['collStats'] || selector['dbStats']
- || selector['count'] || selector['distinct'] || selector['geoNear'] || selector['geoSearch']
- || selector['geoWalk'] || selector['text'] || selector['cursorInfo']
- || selector['parallelCollectionScan']
- || (selector['mapreduce'] && (selector.out == 'inline' || selector.out.inline))) {
- // Set the read preference
- options.readPreference = readPreference;
- } else {
- options.readPreference = ReadPreference.PRIMARY;
- }
- } else if(readPreference != false) {
- options.readPreference = readPreference;
- }
-
- // Add the maxTimeMS option to the command if specified
- if(typeof options.maxTimeMS == 'number') {
- selector.maxTimeMS = options.maxTimeMS
- }
-
- // Command options
- var command_options = {};
-
- // Do we have an override for checkKeys
- if(typeof options['checkKeys'] == 'boolean') command_options['checkKeys'] = options['checkKeys'];
- command_options['checkKeys'] = typeof options['checkKeys'] == 'boolean' ? options['checkKeys'] : false;
- if(typeof options['serializeFunctions'] == 'boolean') command_options['serializeFunctions'] = options['serializeFunctions'];
- if(options['dbName']) command_options['dbName'] = options['dbName'];
-
- // If we have a write command, remove readPreference as an option
- if((options.writeCommand
- || selector['findAndModify']
- || selector['insert'] || selector['update'] || selector['delete']
- || selector['createUser'] || selector['updateUser'] || selector['removeUser'])
- && options.readPreference) {
- delete options['readPreference'];
- }
-
- // Add a write concern if we have passed in any
- if(options.w || options.wtimeout || options.j || options.fsync || options.safe) {
- selector.writeConcern = {};
- if(options.safe) selector.writeConcern.w = 1;
- if(options.w) selector.writeConcern.w = options.w;
- if(options.wtimeout) selector.writeConcern.wtimeout = options.wtimeout;
- if(options.j) selector.writeConcern.j = options.j;
- if(options.fsync) selector.writeConcern.fsync = options.fsync;
- }
-
- // If we have an actual writeConcern object override
- if(options.writeConcern) {
- selector.writeConcern = writeConcern;
- }
-
- // Check if we need to set slaveOk
- if(command_options.readPreference != 'primary')
- command_options.slaveOk = true;
-
- // Execution db
- var execDb = typeof options.auth == 'string' ? this.db(options.auth) : this;
- execDb = typeof options.authdb == 'string' ? this.db(options.authdb) : execDb;
-
- // Execute a query command
- this._executeQueryCommand(DbCommand.createDbSlaveOkCommand(execDb, selector, command_options), options, function(err, results, connection) {
- if(options.returnConnection) {
- if(err) return callback(err, null, connection);
- if(results == null || results.documents == null) return callback(new Error("command failed to return result"));
- if(results.documents[0].errmsg)
- return callback(utils.toError(results.documents[0]), null, connection);
- callback(null, results.documents[0], connection);
- } else {
- if(err) return callback(err, null);
- if(results == null || results.documents == null) return callback(new Error("command failed to return result"));
- if(results.documents[0].errmsg)
- return callback(utils.toError(results.documents[0]), null);
- callback(null, results.documents[0]);
- }
- });
-};
-
-/**
- * Drop a collection from the database, removing it permanently. New accesses will create a new collection.
- *
- * @param {String} collectionName the name of the collection we wish to drop.
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from dropCollection or null if an error occurred.
- * @return {null}
- * @api public
- */
-Db.prototype.dropCollection = function(collectionName, callback) {
- var self = this;
- callback || (callback = function(){});
-
- // Command to execute
- var cmd = {'drop':collectionName}
-
- // Execute the command
- this.command(cmd, {}, function(err, result) {
- if(err) return callback(err, null);
- if(result.ok) return callback(null, true);
- callback(null, false);
- });
-};
-
-/**
- * Rename a collection.
- *
- * Options
- * - **dropTarget** {Boolean, default:false}, drop the target name collection if it previously exists.
- *
- * @param {String} fromCollection the name of the current collection we wish to rename.
- * @param {String} toCollection the new name of the collection.
- * @param {Object} [options] returns option results.
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from renameCollection or null if an error occurred.
- * @return {null}
- * @api public
- */
-Db.prototype.renameCollection = function(fromCollection, toCollection, options, callback) {
- var self = this;
-
- if(typeof options == 'function') {
- callback = options;
- options = {}
- }
-
- // Add return new collection
- options.new_collection = true;
-
- // Execute using the collection method
- this.collection(fromCollection).rename(toCollection, options, callback);
-};
-
-/**
- * Runs a command on the database.
- * @ignore
- * @api private
- */
-Db.prototype.executeDbCommand = function(command_hash, options, callback) {
- if(callback == null) { callback = options; options = {}; }
- this._executeQueryCommand(DbCommand.createDbSlaveOkCommand(this, command_hash, options), options, function(err, result) {
- if(callback) callback(err, result);
- });
-};
-
-/**
- * Runs a command on the database as admin.
- * @ignore
- * @api private
- */
-Db.prototype.executeDbAdminCommand = function(command_hash, options, callback) {
- if(typeof options == 'function') {
- callback = options;
- options = {}
- }
-
- if(options.readPreference) {
- options.readPreference = options.readPreference;
- }
-
- this._executeQueryCommand(DbCommand.createAdminDbCommand(this, command_hash), options, function(err, result) {
- if(callback) callback(err, result);
- });
-};
-
-/**
- * Creates an index on the collection.
- *
- * Options
-* - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowledgement of write and w >= 1, w = 'majority' or tag acknowledges the write
- * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option)
- * - **fsync**, (Boolean, default:false) write waits for fsync before returning, from MongoDB 2.6 on, fsync cannot be combined with journal
- * - **j**, (Boolean, default:false) write waits for journal sync before returning
- * - **unique** {Boolean, default:false}, creates an unique index.
- * - **sparse** {Boolean, default:false}, creates a sparse index.
- * - **background** {Boolean, default:false}, creates the index in the background, yielding whenever possible.
- * - **min** {Number}, for geospatial indexes set the lower bound for the co-ordinates.
- * - **max** {Number}, for geospatial indexes set the high bound for the co-ordinates.
- * - **v** {Number}, specify the format version of the indexes.
- * - **expireAfterSeconds** {Number}, allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher)
- * - **name** {String}, override the autogenerated index name (useful if the resulting name is larger than 128 bytes)
- *
- * @param {String} collectionName name of the collection to create the index on.
- * @param {Object} fieldOrSpec fieldOrSpec that defines the index.
- * @param {Object} [options] additional options during update.
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from createIndex or null if an error occurred.
- * @return {null}
- * @api public
- */
-Db.prototype.createIndex = function(collectionName, fieldOrSpec, options, callback) {
- var self = this;
- var args = Array.prototype.slice.call(arguments, 2);
- callback = args.pop();
- options = args.length ? args.shift() || {} : {};
- options = typeof callback === 'function' ? options : callback;
- options = options == null ? {} : options;
-
- // Get the error options
- var writeConcern = _getWriteConcern(self, options);
- // Ensure we have a callback
- if(_hasWriteConcern(writeConcern) && typeof callback != 'function') {
- throw new Error("Cannot use a writeConcern without a provided callback");
- }
-
- // Attempt to run using createIndexes command
- createIndexUsingCreateIndexes(self, collectionName, fieldOrSpec, options, function(err, result) {
- if(err == null) {
- return callback(err, result);
- }
-
- // Create command
- var command = createCreateIndexCommand(self, collectionName, fieldOrSpec, options);
- // Default command options
- var commandOptions = {};
-
- // If we have error conditions set handle them
- if(_hasWriteConcern(writeConcern) && typeof callback == 'function') {
- // Set safe option
- commandOptions['safe'] = writeConcern;
- // If we have an error option
- if(typeof writeConcern == 'object') {
- var keys = Object.keys(writeConcern);
- for(var i = 0; i < keys.length; i++) {
- commandOptions[keys[i]] = writeConcern[keys[i]];
- }
- }
-
- // Execute insert command
- self._executeInsertCommand(command, commandOptions, function(err, result) {
- if(err != null) return callback(err, null);
- if(result == null || result.documents == null) return callback(new Error("command failed to return result"));
-
- result = result && result.documents;
- if (result[0].err) {
- callback(utils.toError(result[0]));
- } else {
- callback(null, command.documents[0].name);
- }
- });
- } else {
- // Execute insert command
- var result = self._executeInsertCommand(command, commandOptions, function() {});
- // 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);
- }
- });
-};
-
-var createCreateIndexCommand = function(db, collectionName, fieldOrSpec, options) {
- var indexParameters = utils.parseIndexOptions(fieldOrSpec);
- var fieldHash = indexParameters.fieldHash;
- var keys = indexParameters.keys;
-
- // Generate the index name
- var indexName = typeof options.name == 'string'
- ? options.name
- : indexParameters.name;
-
- 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 keysToOmit = Object.keys(selector);
- for(var optionName in options) {
- if(keysToOmit.indexOf(optionName) == -1) {
- selector[optionName] = options[optionName];
- }
- }
-
- if(selector['unique'] == null)
- selector['unique'] = finalUnique;
-
- var name = db.databaseName + "." + DbCommand.SYSTEM_INDEX_COLLECTION;
- var cmd = new InsertCommand(db, name, false);
- return cmd.add(selector);
-}
-
-var createIndexUsingCreateIndexes = function(self, collectionName, fieldOrSpec, options, callback) {
- // Build the index
- var indexParameters = utils.parseIndexOptions(fieldOrSpec);
- // Generate the index name
- var indexName = typeof options.name == 'string'
- ? options.name
- : indexParameters.name;
-
- // Set up the index
- var indexes = [{
- name: indexName
- , key: indexParameters.fieldHash
- }];
-
- // merge all the options
- var keysToOmit = Object.keys(indexes[0]);
- for(var optionName in options) {
- if(keysToOmit.indexOf(optionName) == -1) {
- indexes[0][optionName] = options[optionName];
- }
- }
-
- // Create command
- var command = {createIndexes: collectionName, indexes: indexes};
- // Build the command
- self.command(command, options, function(err, result) {
- if(err) return callback(err, null);
- if(result.ok == 0) {
- return callback(utils.toError(result), null);
- }
-
- // Return the indexName for backward compatibility
- callback(null, indexName);
- });
-}
-
-/**
- * Ensures that an index exists, if it does not it creates it
- *
- * Options
- * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowledgement of write and w >= 1, w = 'majority' or tag acknowledges the write
- * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option)
- * - **fsync**, (Boolean, default:false) write waits for fsync before returning, from MongoDB 2.6 on, fsync cannot be combined with journal
- * - **j**, (Boolean, default:false) write waits for journal sync before returning
- * - **unique** {Boolean, default:false}, creates an unique index.
- * - **sparse** {Boolean, default:false}, creates a sparse index.
- * - **background** {Boolean, default:false}, creates the index in the background, yielding whenever possible.
- * - **min** {Number}, for geospatial indexes set the lower bound for the co-ordinates.
- * - **max** {Number}, for geospatial indexes set the high bound for the co-ordinates.
- * - **v** {Number}, specify the format version of the indexes.
- * - **expireAfterSeconds** {Number}, allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher)
- * - **name** {String}, override the autogenerated index name (useful if the resulting name is larger than 128 bytes)
- *
- * @param {String} collectionName name of the collection to create the index on.
- * @param {Object} fieldOrSpec fieldOrSpec that defines the index.
- * @param {Object} [options] additional options during update.
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from ensureIndex or null if an error occurred.
- * @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 = {};
- }
-
- // Ensure non empty options
- options = options || {};
-
- // Get the error options
- var writeConcern = _getWriteConcern(this, options);
- // Make sure we don't try to do a write concern without a callback
- if(_hasWriteConcern(writeConcern) && callback == null)
- throw new Error("Cannot use a writeConcern without a provided callback");
-
- // Create command
- var command = createCreateIndexCommand(this, collectionName, fieldOrSpec, options);
- var index_name = command.documents[0].name;
-
- // Check if the index allready exists
- this.indexInformation(collectionName, writeConcern, function(err, indexInformation) {
- if(err != null) return callback(err, null);
- // If the index does not exist, create it
- if(!indexInformation[index_name]) {
- self.createIndex(collectionName, fieldOrSpec, options, callback);
- } else {
- if(typeof callback === 'function') return callback(null, index_name);
- }
- });
-};
-
-/**
- * Returns the information available on allocated cursors.
- *
- * Options
- * - **readPreference** {String}, the preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
- *
- * @param {Object} [options] additional options during update.
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from cursorInfo or null if an error occurred.
- * @return {null}
- * @api public
- */
-Db.prototype.cursorInfo = function(options, callback) {
- var args = Array.prototype.slice.call(arguments, 0);
- callback = args.pop();
- options = args.length ? args.shift() || {} : {};
-
- // cursorInfo command
- var cmd = {'cursorInfo':1};
-
- // Execute the command
- this.command(cmd, options, function(err, result) {
- if(err) return callback(err, null);
- callback(null, result);
- });
-};
-
-/**
- * Drop an index on a collection.
- *
- * @param {String} collectionName the name of the collection where the command will drop an index.
- * @param {String} indexName name of the index to drop.
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from dropIndex or null if an error occurred.
- * @return {null}
- * @api public
- */
-Db.prototype.dropIndex = function(collectionName, indexName, options, callback) {
- var args = Array.prototype.slice.call(arguments, 2);
- callback = args.pop();
- options = args.length ? args.shift() || {} : {};
-
- // Delete index command
- var cmd = {'deleteIndexes':collectionName, 'index':indexName};
-
- // Execute command
- this.command(cmd, options, function(err, result) {
- if(callback == null) return;
- if(err) return callback(err, null);
- callback(null, result);
- });
-};
-
-/**
- * Reindex all indexes on the collection
- * Warning: reIndex is a blocking operation (indexes are rebuilt in the foreground) and will be slow for large collections.
- *
- * @param {String} collectionName the name of the collection.
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from reIndex or null if an error occurred.
- * @api public
-**/
-Db.prototype.reIndex = function(collectionName, options, callback) {
- if(typeof options == 'function') {
- callback = options;
- options = {};
- }
-
- // Reindex
- var cmd = {'reIndex':collectionName};
-
- // Execute the command
- this.command(cmd, options, function(err, result) {
- if(callback == null) return;
- if(err) return callback(err, null);
- callback(null, result.ok ? true : false);
- });
-};
-
-/**
- * Retrieves this collections index info.
- *
- * Options
- * - **full** {Boolean, default:false}, returns the full raw index information.
- * - **readPreference** {String}, the preferred read preference ((Server.PRIMARY, Server.PRIMARY_PREFERRED, Server.SECONDARY, Server.SECONDARY_PREFERRED, Server.NEAREST).
- *
- * @param {String} collectionName the name of the collection.
- * @param {Object} [options] additional options during update.
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from indexInformation or null if an error occurred.
- * @return {null}
- * @api public
- */
-Db.prototype.indexInformation = function(name, options, callback) {
- if(typeof callback === 'undefined') {
- if(typeof options === 'undefined') {
- callback = name;
- name = null;
- } else {
- callback = options;
- }
- options = {};
- }
-
- // Throw is no name provided
- if(name == null) throw new Error("A collection name must be provided as first argument");
-
- // If we specified full information
- var full = options['full'] == null ? false : options['full'];
- var self = this;
-
- // Process all the results from the index command and collection
- var processResults = function(indexes) {
- // Contains all the information
- var info = {};
- // 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 info;
- }
-
- // Fallback to pre 2.8 getting the index information
- var fallbackListIndexes = function() {
- // Build selector for the indexes
- var selector = name != null ? {ns: (self.databaseName + "." + name)} : {};
-
- // Get read preference if we set one
- var readPreference = ReadPreference.PRIMARY;
-
- // Iterate through all the fields of the index
- var collection = self.collection(DbCommand.SYSTEM_INDEX_COLLECTION);
- // Perform the find for the collection
- collection.find(selector).setReadPreference(readPreference).toArray(function(err, indexes) {
- if(err != null) return callback(err, null);
- // if full defined just return all the indexes directly
- if(full) return callback(null, indexes);
- // Return all the indexes
- callback(null, processResults(indexes));
- });
- }
-
- // Attempt to execute the listIndexes command
- self.command({listIndexes: name}, function(err, result) {
- if(err) return fallbackListIndexes();
- // if full defined just return all the indexes directly
- if(full) return callback(null, result.indexes);
- // Return all the indexes
- callback(null, processResults(result.indexes));
- });
-};
-
-/**
- * Drop a database.
- *
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from dropDatabase or null if an error occurred.
- * @return {null}
- * @api public
- */
-Db.prototype.dropDatabase = function(options, callback) {
- if(typeof options == 'function') {
- callback = options;
- options = {};
- }
-
- // Reindex
- var cmd = {'dropDatabase':1};
-
- // Execute the command
- this.command(cmd, options, function(err, result) {
- if(callback == null) return;
- if(err) return callback(err, null);
- callback(null, result.ok ? true : false);
- });
-}
-
-/**
- * Get all the db statistics.
- *
- * Options
- * - **scale** {Number}, divide the returned sizes by scale value.
- * - **readPreference** {String}, the preferred read preference ((Server.PRIMARY, Server.PRIMARY_PREFERRED, Server.SECONDARY, Server.SECONDARY_PREFERRED, Server.NEAREST).
- *
- * @param {Objects} [options] options for the stats command
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from stats or null if an error occurred.
- * @return {null}
- * @api public
- */
-Db.prototype.stats = function stats(options, callback) {
- var args = Array.prototype.slice.call(arguments, 0);
- callback = args.pop();
- // Fetch all commands
- options = args.length ? args.shift() || {} : {};
-
- // Build command object
- var commandObject = {
- dbStats:true
- };
-
- // Check if we have the scale value
- if(options['scale'] != null) commandObject['scale'] = options['scale'];
-
- // Execute the command
- this.command(commandObject, options, callback);
-}
-
-/**
- * @ignore
- */
-var bindToCurrentDomain = function(callback) {
- var domain = process.domain;
- if(domain == null || callback == null) {
- return callback;
- } else {
- return domain.bind(callback);
- }
-}
-
-/**
- * @ignore
- */
-var __executeQueryCommand = function(self, db_command, options, callback) {
- // Options unpacking
- var readPreference = options.readPreference != null ? options.readPreference : 'primary';
- var onAll = options['onAll'] != null ? options['onAll'] : false;
- var specifiedConnection = options['connection'] != null ? options['connection'] : null;
- var raw = typeof options.raw == 'boolean' ? options.raw : false;
-
- // Correct readPreference preference to default primary if set to false, null or primary
- if(!(typeof readPreference == 'object') && readPreference._type == 'ReadPreference') {
- readPreference = (readPreference == null || readPreference == 'primary' || readPreference == false) ? ReadPreference.PRIMARY : readPreference;
- if(!ReadPreference.isValid(readPreference)) return callback(new Error("Illegal readPreference mode specified, " + JSON.stringify(readPreference)));
- } else if(typeof readPreference == 'object' && readPreference._type == 'ReadPreference') {
- if(!readPreference.isValid()) return callback(new Error("Illegal readPreference mode specified, " + JSON.stringify(readPreference)));
- }
-
- // If we have a read preference set and we are a mongos pass the read preference on to the mongos instance,
- if(self.serverConfig.isMongos() && readPreference != null && readPreference != 'primary') {
- db_command.setMongosReadPreference(readPreference);
- }
-
- // If we got a callback object
- if(typeof callback === 'function' && !onAll) {
- callback = bindToCurrentDomain(callback);
- // Override connection if we passed in a specific connection
- var connection = specifiedConnection != null ? specifiedConnection : null;
-
- if(connection instanceof Error) return callback(connection, null);
-
- // Fetch either a reader or writer dependent on the specified readPreference option if no connection
- // was passed in
- if(connection == null) {
- connection = self.serverConfig.checkoutReader(readPreference);
- }
-
- if(connection == null) {
- return callback(new Error("no open connections"));
- } else if(connection instanceof Error || connection['message'] != null) {
- return callback(connection);
- }
-
- // Exhaust Option
- var exhaust = options.exhaust || false;
-
- // Register the handler in the data structure
- self.serverConfig._registerHandler(db_command, raw, connection, exhaust, callback);
-
- // Write the message out and handle any errors if there are any
- connection.write(db_command, function(err) {
- if(err != null) {
- // Call the handler with an error
- if(Array.isArray(db_command))
- self.serverConfig._callHandler(db_command[0].getRequestId(), null, err);
- else
- self.serverConfig._callHandler(db_command.getRequestId(), null, err);
- }
- });
- } else if(typeof callback === 'function' && onAll) {
- callback = bindToCurrentDomain(callback);
- var connections = self.serverConfig.allRawConnections();
- var numberOfEntries = connections.length;
- // Go through all the connections
- for(var i = 0; i < connections.length; i++) {
- // Fetch a connection
- var connection = connections[i];
-
- // Ensure we have a valid connection
- if(connection == null) {
- return callback(new Error("no open connections"));
- } else if(connection instanceof Error) {
- return callback(connection);
- }
-
- // Register the handler in the data structure
- self.serverConfig._registerHandler(db_command, raw, connection, callback);
-
- // Write the message out
- connection.write(db_command, function(err) {
- // Adjust the number of entries we need to process
- numberOfEntries = numberOfEntries - 1;
- // Remove listener
- if(err != null) {
- // Clean up listener and return error
- self.serverConfig._removeHandler(db_command.getRequestId());
- }
-
- // No more entries to process callback with the error
- if(numberOfEntries <= 0) {
- callback(err);
- }
- });
-
- // Update the db_command request id
- db_command.updateRequestId();
- }
- } else {
- // Fetch either a reader or writer dependent on the specified read option
- var connection = self.serverConfig.checkoutReader(readPreference);
- // Override connection if needed
- connection = specifiedConnection != null ? specifiedConnection : connection;
- // Ensure we have a valid connection
- if(connection == null || connection instanceof Error || connection['message'] != null) return null;
- // Write the message out
- connection.write(db_command, function(err) {
- if(err != null) {
- // Emit the error
- self.emit("error", err);
- }
- });
- }
-};
-
-/**
- * Execute db query command (not safe)
- * @ignore
- * @api private
- */
-Db.prototype._executeQueryCommand = function(db_command, options, callback) {
- var self = this;
-
- // Unpack the parameters
- if(typeof options === 'function') {
- callback = options;
- options = {};
- }
- callback = bindToCurrentDomain(callback);
-
- // fast fail option used for HA, no retry
- var failFast = options['failFast'] != null
- ? options['failFast']
- : false;
-
- // Check if the user force closed the command
- if(this._applicationClosed) {
- var err = new Error("db closed by application");
- if('function' == typeof callback) {
- return callback(err, null);
- } else {
- throw err;
- }
- }
-
- if(this.serverConfig.isDestroyed())
- return callback(new Error("Connection was destroyed by application"));
-
- // Specific connection
- var connection = options.connection;
- // Check if the connection is actually live
- if(connection
- && (!connection.isConnected || !connection.isConnected())) connection = null;
-
- // Get the configuration
- var config = this.serverConfig;
- var readPreference = options.readPreference;
- // Allow for the usage of the readPreference model
- if(readPreference == null) {
- readPreference = options.readPreference;
- }
-
- if(!connection && !config.canRead(readPreference) && !config.canWrite() && config.isAutoReconnect()) {
-
- if(readPreference == ReadPreference.PRIMARY
- || readPreference == ReadPreference.PRIMARY_PREFERRED
- || (readPreference != null && typeof readPreference == 'object' && readPreference.mode)
- || readPreference == null) {
-
- // Save the command
- self.serverConfig._commandsStore.read_from_writer(
- { type: 'query'
- , db_command: db_command
- , options: options
- , callback: callback
- , db: self
- , executeQueryCommand: __executeQueryCommand
- , executeInsertCommand: __executeInsertCommand
- }
- );
- } else {
- self.serverConfig._commandsStore.read(
- { type: 'query'
- , db_command: db_command
- , options: options
- , callback: callback
- , db: self
- , executeQueryCommand: __executeQueryCommand
- , executeInsertCommand: __executeInsertCommand
- }
- );
- }
-
- // If we have blown through the number of items let's
- if(!self.serverConfig._commandsStore.validateBufferLimit(self.bufferMaxEntries)) {
- self.close();
- }
- } else if(!connection && !config.canRead(readPreference) && !config.canWrite() && !config.isAutoReconnect()) {
- return callback(new Error("no open connections"), null);
- } else {
- if(typeof callback == 'function') {
- __executeQueryCommand(self, db_command, options, function (err, result, conn) {
- callback(err, result, conn);
- });
- } else {
- __executeQueryCommand(self, db_command, options);
- }
- }
-};
-
-/**
- * @ignore
- */
-var __executeInsertCommand = function(self, db_command, options, callback) {
- // Always checkout a writer for this kind of operations
- var connection = self.serverConfig.checkoutWriter();
- // Get safe mode
- var safe = options['safe'] != null ? options['safe'] : false;
- var specifiedConnection = options['connection'] != null ? options['connection'] : null;
- // Override connection if needed
- connection = specifiedConnection != null ? specifiedConnection : connection;
-
- // Validate if we can use this server 2.6 wire protocol
- if(connection && !connection.isCompatible()) {
- return callback(utils.toError("driver is incompatible with this server version"), null);
- }
-
- // Ensure we have a valid connection
- if(typeof callback === 'function') {
- callback = bindToCurrentDomain(callback);
- // Ensure we have a valid connection
- if(connection == null) {
- return callback(new Error("no open connections"));
- } else if(connection instanceof Error) {
- return callback(connection);
- }
-
- var errorOptions = _getWriteConcern(self, options);
- if(errorOptions.w > 0 || errorOptions.w == 'majority' || errorOptions.j || errorOptions.journal || errorOptions.fsync) {
- // db command is now an array of commands (original command + lastError)
- db_command = [db_command, DbCommand.createGetLastErrorCommand(errorOptions, self)];
- // Register the handler in the data structure
- self.serverConfig._registerHandler(db_command[1], false, 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 the callback
- callback(err, null);
- } else if(typeof callback === 'function') {
- // Call the handler with an error
- self.serverConfig._callHandler(db_command[1].getRequestId(), null, err);
- } else if(typeof callback == 'function' && safe && safe.w == -1) {
- // Call the handler with no error
- self.serverConfig._callHandler(db_command[1].getRequestId(), null, null);
- } else if(!safe || safe.w == -1) {
- self.emit("error", err);
- }
- });
-};
-
-/**
- * Execute an insert Command
- * @ignore
- * @api private
- */
-Db.prototype._executeInsertCommand = function(db_command, options, callback) {
- var self = this;
-
- // Unpack the parameters
- if(callback == null && typeof options === 'function') {
- callback = options;
- options = {};
- }
- callback = bindToCurrentDomain(callback);
- // Ensure options are not null
- options = options == null ? {} : options;
-
- // Check if the user force closed the command
- if(this._applicationClosed) {
- if(typeof callback == 'function') {
- return callback(new Error("db closed by application"), null);
- } else {
- throw new Error("db closed by application");
- }
- }
-
- if(this.serverConfig.isDestroyed()) return callback(new Error("Connection was destroyed by application"));
-
- // Specific connection
- var connection = options.connection;
- // Check if the connection is actually live
- if(connection
- && (!connection.isConnected || !connection.isConnected())) connection = null;
-
- // Get config
- var config = self.serverConfig;
- // Check if we are connected
- if(!connection && !config.canWrite() && config.isAutoReconnect()) {
- self.serverConfig._commandsStore.write(
- { type:'insert'
- , 'db_command':db_command
- , 'options':options
- , 'callback':callback
- , db: self
- , executeQueryCommand: __executeQueryCommand
- , executeInsertCommand: __executeInsertCommand
- }
- );
-
- // If we have blown through the number of items let's
- if(!self.serverConfig._commandsStore.validateBufferLimit(self.bufferMaxEntries)) {
- self.close();
- }
- } else if(!connection && !config.canWrite() && !config.isAutoReconnect()) {
- return callback(new Error("no open connections"), null);
- } else {
- __executeInsertCommand(self, db_command, options, callback);
- }
-};
-
-/**
- * Update command is the same
- * @ignore
- * @api private
- */
-Db.prototype._executeUpdateCommand = Db.prototype._executeInsertCommand;
-/**
- * Remove command is the same
- * @ignore
- * @api private
- */
-Db.prototype._executeRemoveCommand = Db.prototype._executeInsertCommand;
-
-/**
- * Wrap a Mongo error document into an Error instance.
- * Deprecated. Use utils.toError instead.
- *
- * @ignore
- * @api private
- * @deprecated
- */
-Db.prototype.wrap = utils.toError;
-
-/**
- * Default URL
- *
- * @classconstant DEFAULT_URL
- **/
-Db.DEFAULT_URL = 'mongodb://localhost:27017/default';
-
-/**
- * Connect to MongoDB using a url as documented at
- *
- * docs.mongodb.org/manual/reference/connection-string/
- *
- * Options
- * - **uri_decode_auth** {Boolean, default:false} uri decode the user name and password for authentication
- * - **db** {Object, default: null} a hash off options to set on the db object, see **Db constructor**
- * - **server** {Object, default: null} a hash off options to set on the server objects, see **Server** constructor**
- * - **replSet** {Object, default: null} a hash off options to set on the replSet object, see **ReplSet** constructor**
- * - **mongos** {Object, default: null} a hash off options to set on the mongos object, see **Mongos** constructor**
- *
- * @param {String} url connection url for MongoDB.
- * @param {Object} [options] optional options for insert command
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the db instance or null if an error occurred.
- * @return {null}
- * @api public
- */
-Db.connect = function(url, options, callback) {
- // Ensure correct mapping of the callback
- if(typeof options == 'function') {
- callback = options;
- options = {};
- }
-
- // Ensure same behavior as previous version w:0
- if(url.indexOf("safe") == -1
- && url.indexOf("w") == -1
- && url.indexOf("journal") == -1 && url.indexOf("j") == -1
- && url.indexOf("fsync") == -1) options.w = 1;
-
- // Avoid circular require problem
- var MongoClient = require('./mongo_client.js').MongoClient;
- // Attempt to connect
- MongoClient.connect.call(MongoClient, url, options, callback);
-};
-
-/**
- * State of the db connection
- * @ignore
- */
-Object.defineProperty(Db.prototype, "state", { enumerable: true
- , get: function () {
- return this.serverConfig._serverState;
- }
-});
-
-/**
- * @ignore
- */
-var _hasWriteConcern = function(errorOptions) {
- return errorOptions == true
- || errorOptions.w > 0
- || errorOptions.w == 'majority'
- || errorOptions.j == true
- || errorOptions.journal == true
- || errorOptions.fsync == true
-};
-
-/**
- * @ignore
- */
-var _setWriteConcernHash = function(options) {
- var finalOptions = {};
- if(options.w != null) finalOptions.w = options.w;
- if(options.journal == true) finalOptions.j = options.journal;
- if(options.j == true) finalOptions.j = options.j;
- if(options.fsync == true) finalOptions.fsync = options.fsync;
- if(options.wtimeout != null) finalOptions.wtimeout = options.wtimeout;
- return finalOptions;
-};
-
-/**
- * @ignore
- */
-var _getWriteConcern = function(self, options) {
- // Final options
- var finalOptions = {w:1};
- // Local options verification
- if(options.w != null || typeof options.j == 'boolean' || typeof options.journal == 'boolean' || typeof options.fsync == 'boolean') {
- finalOptions = _setWriteConcernHash(options);
- } else if(options.safe != null && typeof options.safe == 'object') {
- finalOptions = _setWriteConcernHash(options.safe);
- } else if(typeof options.safe == "boolean") {
- finalOptions = {w: (options.safe ? 1 : 0)};
- } else if(self.options.w != null || typeof self.options.j == 'boolean' || typeof self.options.journal == 'boolean' || typeof self.options.fsync == 'boolean') {
- finalOptions = _setWriteConcernHash(self.options);
- } else if(self.safe.w != null || typeof self.safe.j == 'boolean' || typeof self.safe.journal == 'boolean' || typeof self.safe.fsync == 'boolean') {
- finalOptions = _setWriteConcernHash(self.safe);
- } else if(typeof self.safe == "boolean") {
- finalOptions = {w: (self.safe ? 1 : 0)};
- }
-
- // Ensure we don't have an invalid combination of write concerns
- if(finalOptions.w < 1
- && (finalOptions.journal == true || finalOptions.j == true || finalOptions.fsync == true)) throw new Error("No acknowledgement using w < 1 cannot be combined with journal:true or fsync:true");
-
- // Return the options
- return finalOptions;
-}
-
-/**
- * Legacy support
- *
- * @ignore
- * @api private
- */
-exports.connect = Db.connect;
-exports.Db = Db;
-
-/**
- * Remove all listeners to the db instance.
- * @ignore
- * @api private
- */
-Db.prototype.removeAllEventListeners = function() {
- this.removeAllListeners("close");
- this.removeAllListeners("error");
- this.removeAllListeners("timeout");
- this.removeAllListeners("parseError");
- this.removeAllListeners("poolReady");
- this.removeAllListeners("message");
-};
diff --git a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/gridfs/chunk.js b/node_modules/mongojs/node_modules/mongodb/lib/mongodb/gridfs/chunk.js
deleted file mode 100644
index 8cddafe..0000000
--- a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/gridfs/chunk.js
+++ /dev/null
@@ -1,232 +0,0 @@
-var Binary = require('bson').Binary,
- ObjectID = require('bson').ObjectID;
-
-/**
- * Class for representing a single chunk in GridFS.
- *
- * @class
- *
- * @param file {GridStore} The {@link GridStore} object holding this chunk.
- * @param mongoObject {object} The mongo object representation of this chunk.
- *
- * @throws Error when the type of data field for {@link mongoObject} is not
- * supported. Currently supported types for data field are instances of
- * {@link String}, {@link Array}, {@link Binary} and {@link Binary}
- * from the bson module
- *
- * @see Chunk#buildMongoObject
- */
-var Chunk = exports.Chunk = function(file, mongoObject, writeConcern) {
- if(!(this instanceof Chunk)) return new Chunk(file, mongoObject);
-
- this.file = file;
- var self = this;
- var mongoObjectFinal = mongoObject == null ? {} : mongoObject;
- this.writeConcern = writeConcern || {w:1};
- this.objectId = mongoObjectFinal._id == null ? new ObjectID() : mongoObjectFinal._id;
- this.chunkNumber = mongoObjectFinal.n == null ? 0 : mongoObjectFinal.n;
- this.data = new Binary();
-
- if(mongoObjectFinal.data == null) {
- } else if(typeof mongoObjectFinal.data == "string") {
- var buffer = new Buffer(mongoObjectFinal.data.length);
- buffer.write(mongoObjectFinal.data, 'binary', 0);
- this.data = new Binary(buffer);
- } else if(Array.isArray(mongoObjectFinal.data)) {
- var buffer = new Buffer(mongoObjectFinal.data.length);
- buffer.write(mongoObjectFinal.data.join(''), 'binary', 0);
- this.data = new Binary(buffer);
- } else if(mongoObjectFinal.data instanceof Binary || mongoObjectFinal.data._bsontype === 'Binary' || Object.prototype.toString.call(mongoObjectFinal.data) == "[object Binary]") {
- this.data = mongoObjectFinal.data;
- } else if(Buffer.isBuffer(mongoObjectFinal.data)) {
- } else {
- throw Error("Illegal chunk format");
- }
-
- // Update position
- this.internalPosition = 0;
-};
-
-/**
- * Writes a data to this object and advance the read/write head.
- *
- * @param data {string} the data to write
- * @param callback {function(*, GridStore)} This will be called after executing
- * this method. The first parameter will contain null and the second one
- * will contain a reference to this object.
- */
-Chunk.prototype.write = function(data, callback) {
- this.data.write(data, this.internalPosition);
- this.internalPosition = this.data.length();
- if(callback != null) return callback(null, this);
- return this;
-};
-
-/**
- * Reads data and advances the read/write head.
- *
- * @param length {number} The length of data to read.
- *
- * @return {string} The data read if the given length will not exceed the end of
- * the chunk. Returns an empty String otherwise.
- */
-Chunk.prototype.read = function(length) {
- // Default to full read if no index defined
- length = length == null || length == 0 ? this.length() : length;
-
- if(this.length() - this.internalPosition + 1 >= length) {
- var data = this.data.read(this.internalPosition, length);
- this.internalPosition = this.internalPosition + length;
- return data;
- } else {
- return '';
- }
-};
-
-Chunk.prototype.readSlice = function(length) {
- if ((this.length() - this.internalPosition) >= length) {
- var data = null;
- if (this.data.buffer != null) { //Pure BSON
- data = this.data.buffer.slice(this.internalPosition, this.internalPosition + length);
- } else { //Native BSON
- data = new Buffer(length);
- length = this.data.readInto(data, this.internalPosition);
- }
- this.internalPosition = this.internalPosition + length;
- return data;
- } else {
- return null;
- }
-};
-
-/**
- * Checks if the read/write head is at the end.
- *
- * @return {boolean} Whether the read/write head has reached the end of this
- * chunk.
- */
-Chunk.prototype.eof = function() {
- return this.internalPosition == this.length() ? true : false;
-};
-
-/**
- * Reads one character from the data of this chunk and advances the read/write
- * head.
- *
- * @return {string} a single character data read if the the read/write head is
- * not at the end of the chunk. Returns an empty String otherwise.
- */
-Chunk.prototype.getc = function() {
- return this.read(1);
-};
-
-/**
- * Clears the contents of the data in this chunk and resets the read/write head
- * to the initial position.
- */
-Chunk.prototype.rewind = function() {
- this.internalPosition = 0;
- this.data = new Binary();
-};
-
-/**
- * Saves this chunk to the database. Also overwrites existing entries having the
- * same id as this chunk.
- *
- * @param callback {function(*, GridStore)} This will be called after executing
- * this method. The first parameter will contain null and the second one
- * will contain a reference to this object.
- */
-Chunk.prototype.save = function(options, callback) {
- var self = this;
- if(typeof options == 'function') {
- callback = options;
- options = {};
- }
-
- self.file.chunkCollection(function(err, collection) {
- if(err) return callback(err);
-
- // Merge the options
- var writeOptions = {};
- for(var name in options) writeOptions[name] = options[name];
- for(var name in self.writeConcern) writeOptions[name] = self.writeConcern[name];
-
- // collection.remove({'_id':self.objectId}, self.writeConcern, function(err, result) {
- collection.remove({'_id':self.objectId}, writeOptions, function(err, result) {
- if(err) return callback(err);
-
- if(self.data.length() > 0) {
- self.buildMongoObject(function(mongoObject) {
- var options = {forceServerObjectId:true};
- for(var name in self.writeConcern) {
- options[name] = self.writeConcern[name];
- }
-
- collection.insert(mongoObject, writeOptions, function(err, collection) {
- callback(err, self);
- });
- });
- } else {
- callback(null, self);
- }
- });
- });
-};
-
-/**
- * Creates a mongoDB object representation of this chunk.
- *
- * @param callback {function(Object)} This will be called after executing this
- * method. The object will be passed to the first parameter and will have
- * the structure:
- *
- *
- * {
- * '_id' : , // {number} id for this chunk
- * 'files_id' : , // {number} foreign key to the file collection
- * 'n' : , // {number} chunk number
- * 'data' : , // {bson#Binary} the chunk data itself
- * }
- *
- *
- * @see MongoDB GridFS Chunk Object Structure
- */
-Chunk.prototype.buildMongoObject = function(callback) {
- var mongoObject = {
- 'files_id': this.file.fileId,
- 'n': this.chunkNumber,
- 'data': this.data};
- // If we are saving using a specific ObjectId
- if(this.objectId != null) mongoObject._id = this.objectId;
-
- callback(mongoObject);
-};
-
-/**
- * @return {number} the length of the data
- */
-Chunk.prototype.length = function() {
- return this.data.length();
-};
-
-/**
- * The position of the read/write head
- * @name position
- * @lends Chunk#
- * @field
- */
-Object.defineProperty(Chunk.prototype, "position", { enumerable: true
- , get: function () {
- return this.internalPosition;
- }
- , set: function(value) {
- this.internalPosition = value;
- }
-});
-
-/**
- * The default chunk size
- * @constant
- */
-Chunk.DEFAULT_CHUNK_SIZE = 1024 * 255;
diff --git a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/gridfs/grid.js b/node_modules/mongojs/node_modules/mongodb/lib/mongodb/gridfs/grid.js
deleted file mode 100644
index aa695b7..0000000
--- a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/gridfs/grid.js
+++ /dev/null
@@ -1,103 +0,0 @@
-var GridStore = require('./gridstore').GridStore,
- ObjectID = require('bson').ObjectID;
-
-/**
- * A class representation of a simple Grid interface.
- *
- * @class Represents the Grid.
- * @param {Db} db A database instance to interact with.
- * @param {String} [fsName] optional different root collection for GridFS.
- * @return {Grid}
- */
-function Grid(db, fsName) {
-
- if(!(this instanceof Grid)) return new Grid(db, fsName);
-
- this.db = db;
- this.fsName = fsName == null ? GridStore.DEFAULT_ROOT_COLLECTION : fsName;
-}
-
-/**
- * Puts binary data to the grid
- *
- * Options
- * - **_id** {Any}, unique id for this file
- * - **root** {String}, root collection to use. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**.
- * - **content_type** {String}, mime type of the file. Defaults to **{GridStore.DEFAULT_CONTENT_TYPE}**.
- * - **chunk_size** {Number}, size for the chunk. Defaults to **{Chunk.DEFAULT_CHUNK_SIZE}**.
- * - **metadata** {Object}, arbitrary data the user wants to store.
- *
- * @param {Buffer} data buffer with Binary Data.
- * @param {Object} [options] the options for the files.
- * @param {Function} callback this will be called after this method is executed. The first parameter will contain an Error object if an error occured or null otherwise. The second parameter will contain a reference to this object.
- * @return {null}
- * @api public
- */
-Grid.prototype.put = function(data, options, callback) {
- var self = this;
- var args = Array.prototype.slice.call(arguments, 1);
- callback = args.pop();
- options = args.length ? args.shift() : {};
- // If root is not defined add our default one
- options['root'] = options['root'] == null ? this.fsName : options['root'];
-
- // Return if we don't have a buffer object as data
- if(!(Buffer.isBuffer(data))) return callback(new Error("Data object must be a buffer object"), null);
- // Get filename if we are using it
- var filename = options['filename'] || null;
- // Get id if we are using it
- var id = options['_id'] || null;
- // Create gridstore
- var gridStore = new GridStore(this.db, id, filename, "w", options);
- gridStore.open(function(err, gridStore) {
- if(err) return callback(err, null);
-
- gridStore.write(data, function(err, result) {
- if(err) return callback(err, null);
-
- gridStore.close(function(err, result) {
- if(err) return callback(err, null);
- callback(null, result);
- })
- })
- })
-}
-
-/**
- * Get binary data to the grid
- *
- * @param {Any} id for file.
- * @param {Function} callback this will be called after this method is executed. The first parameter will contain an Error object if an error occured or null otherwise. The second parameter will contain a reference to this object.
- * @return {null}
- * @api public
- */
-Grid.prototype.get = function(id, callback) {
- // Create gridstore
- var gridStore = new GridStore(this.db, id, null, "r", {root:this.fsName});
- gridStore.open(function(err, gridStore) {
- if(err) return callback(err, null);
-
- // Return the data
- gridStore.read(function(err, data) {
- return callback(err, data)
- });
- })
-}
-
-/**
- * Delete file from grid
- *
- * @param {Any} id for file.
- * @param {Function} callback this will be called after this method is executed. The first parameter will contain an Error object if an error occured or null otherwise. The second parameter will contain a reference to this object.
- * @return {null}
- * @api public
- */
-Grid.prototype.delete = function(id, callback) {
- // Create gridstore
- GridStore.unlink(this.db, id, {root:this.fsName}, function(err, result) {
- if(err) return callback(err, false);
- return callback(null, true);
- });
-}
-
-exports.Grid = Grid;
diff --git a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/gridfs/gridstore.js b/node_modules/mongojs/node_modules/mongodb/lib/mongodb/gridfs/gridstore.js
deleted file mode 100644
index c6b9894..0000000
--- a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/gridfs/gridstore.js
+++ /dev/null
@@ -1,1570 +0,0 @@
-/**
- * @fileOverview GridFS is a tool for MongoDB to store files to the database.
- * Because of the restrictions of the object size the database can hold, a
- * facility to split a file into several chunks is needed. The {@link GridStore}
- * class offers a simplified api to interact with files while managing the
- * chunks of split files behind the scenes. More information about GridFS can be
- * found here.
- */
-var Chunk = require('./chunk').Chunk,
- DbCommand = require('../commands/db_command').DbCommand,
- ObjectID = require('bson').ObjectID,
- Buffer = require('buffer').Buffer,
- fs = require('fs'),
- timers = require('timers'),
- util = require('util'),
- inherits = util.inherits,
- ReadStream = require('./readstream').ReadStream,
- Stream = require('stream');
-
-// Set processor, setImmediate if 0.10 otherwise nextTick
-var processor = require('../utils').processor();
-
-var REFERENCE_BY_FILENAME = 0,
- REFERENCE_BY_ID = 1;
-
-/**
- * A class representation of a file stored in GridFS.
- *
- * Modes
- * - **"r"** - read only. This is the default mode.
- * - **"w"** - write in truncate mode. Existing data will be overwriten.
- * - **w+"** - write in edit mode (append is not guaranteed for concurrent operations)
- *
- * Options
- * - **root** {String}, root collection to use. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**.
- * - **content_type** {String}, mime type of the file. Defaults to **{GridStore.DEFAULT_CONTENT_TYPE}**.
- * - **chunk_size** {Number}, size for the chunk. Defaults to **{Chunk.DEFAULT_CHUNK_SIZE}**.
- * - **metadata** {Object}, arbitrary data the user wants to store.
- * - **readPreference** {String}, the prefered read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
- * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write
- * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option)
- * - **fsync**, (Boolean, default:false) write waits for fsync before returning, from MongoDB 2.6 on, fsync cannot be combined with journal
- * - **j**, (Boolean, default:false) write waits for journal sync before returning
- *
- * @class Represents the GridStore.
- * @param {Db} db A database instance to interact with.
- * @param {Any} [id] optional unique id for this file
- * @param {String} [filename] optional filename for this file, no unique constrain on the field
- * @param {String} mode set the mode for this file.
- * @param {Object} options optional properties to specify.
- * @return {GridStore}
- */
-var GridStore = function GridStore(db, id, filename, mode, options) {
- if(!(this instanceof GridStore)) return new GridStore(db, id, filename, mode, options);
-
- var self = this;
- this.db = db;
-
- // Call stream constructor
- if(typeof Stream == 'function') {
- Stream.call(this);
- }
-
- // Handle options
- if(typeof options === 'undefined') options = {};
- // Handle mode
- if(typeof mode === 'undefined') {
- mode = filename;
- filename = undefined;
- } else if(typeof mode == 'object') {
- options = mode;
- mode = filename;
- filename = undefined;
- }
-
- if(id instanceof ObjectID) {
- this.referenceBy = REFERENCE_BY_ID;
- this.fileId = id;
- this.filename = filename;
- } else if(typeof filename == 'undefined') {
- this.referenceBy = REFERENCE_BY_FILENAME;
- this.filename = id;
- if (mode.indexOf('w') != null) {
- this.fileId = new ObjectID();
- }
- } else {
- this.referenceBy = REFERENCE_BY_ID;
- this.fileId = id;
- this.filename = filename;
- }
-
- // Set up the rest
- this.mode = mode == null ? "r" : mode;
- this.options = options || {};
-
- // Set the root if overridden
- this.root = this.options['root'] == null ? exports.GridStore.DEFAULT_ROOT_COLLECTION : this.options['root'];
- this.position = 0;
- this.readPreference = this.options.readPreference || 'primary';
- this.writeConcern = _getWriteConcern(db, this.options);
-
- // Set default chunk size
- this.internalChunkSize = this.options['chunkSize'] == null ? Chunk.DEFAULT_CHUNK_SIZE : this.options['chunkSize'];
-}
-
-/**
- * Code for the streaming capabilities of the gridstore object
- * Most code from Aaron heckmanns project https://github.com/aheckmann/gridfs-stream
- * Modified to work on the gridstore object itself
- * @ignore
- */
-if(typeof Stream == 'function') {
- GridStore.prototype = { __proto__: Stream.prototype }
-} else {
- // Node 0.4.X compatibility code
- GridStore.prototype = { __proto__: Stream.Stream.prototype }
-}
-
-// Move pipe to _pipe
-GridStore.prototype._pipe = GridStore.prototype.pipe;
-
-/**
- * Opens the file from the database and initialize this object. Also creates a
- * new one if file does not exist.
- *
- * @param {Function} callback this will be called after executing this method. The first parameter will contain an **{Error}** object and the second parameter will be null if an error occured. Otherwise, the first parameter will be null and the second will contain the reference to this object.
- * @return {null}
- * @api public
- */
-GridStore.prototype.open = function(callback) {
- if( this.mode != "w" && this.mode != "w+" && this.mode != "r"){
- callback(new Error("Illegal mode " + this.mode), null);
- return;
- }
-
- var self = this;
-
- // Get the write concern
- var writeConcern = _getWriteConcern(this.db, this.options);
-
- // If we are writing we need to ensure we have the right indexes for md5's
- if((self.mode == "w" || self.mode == "w+")) {
- // Get files collection
- var collection = self.collection();
- // Put index on filename
- collection.ensureIndex([['filename', 1]], writeConcern, function(err, index) {
- // if(err) return callback(err);
-
- // Get chunk collection
- var chunkCollection = self.chunkCollection();
- // Ensure index on chunk collection
- chunkCollection.ensureIndex([['files_id', 1], ['n', 1]], writeConcern, function(err, index) {
- // if(err) return callback(err);
- _open(self, writeConcern, callback);
- });
- });
- } else {
- // Open the gridstore
- _open(self, writeConcern, callback);
- }
-};
-
-/**
- * Hidding the _open function
- * @ignore
- * @api private
- */
-var _open = function(self, options, callback) {
- var collection = self.collection();
- // Create the query
- var query = self.referenceBy == REFERENCE_BY_ID ? {_id:self.fileId} : {filename:self.filename};
- query = null == self.fileId && self.filename == null ? null : query;
- options.readPreference = self.readPreference;
-
- // Fetch the chunks
- if(query != null) {
- collection.findOne(query, options, function(err, doc) {
- if(err) return error(err);
-
- // Check if the collection for the files exists otherwise prepare the new one
- if(doc != null) {
- self.fileId = doc._id;
- // Prefer a new filename over the existing one if this is a write
- self.filename = ((self.mode == 'r') || (self.filename == undefined)) ? doc.filename : self.filename;
- self.contentType = doc.contentType;
- self.internalChunkSize = doc.chunkSize;
- self.uploadDate = doc.uploadDate;
- self.aliases = doc.aliases;
- self.length = doc.length;
- self.metadata = doc.metadata;
- self.internalMd5 = doc.md5;
- } else if (self.mode != 'r') {
- self.fileId = self.fileId == null ? new ObjectID() : self.fileId;
- self.contentType = exports.GridStore.DEFAULT_CONTENT_TYPE;
- self.internalChunkSize = self.internalChunkSize == null ? Chunk.DEFAULT_CHUNK_SIZE : self.internalChunkSize;
- self.length = 0;
- } else {
- self.length = 0;
- var txtId = self.fileId instanceof ObjectID ? self.fileId.toHexString() : self.fileId;
- return error(new Error((self.referenceBy == REFERENCE_BY_ID ? txtId : self.filename) + " does not exist", self));
- }
-
- // Process the mode of the object
- if(self.mode == "r") {
- nthChunk(self, 0, options, function(err, chunk) {
- if(err) return error(err);
- self.currentChunk = chunk;
- self.position = 0;
- callback(null, self);
- });
- } else if(self.mode == "w") {
- // Delete any existing chunks
- deleteChunks(self, options, function(err, result) {
- if(err) return error(err);
- self.currentChunk = new Chunk(self, {'n':0}, self.writeConcern);
- self.contentType = self.options['content_type'] == null ? self.contentType : self.options['content_type'];
- self.internalChunkSize = self.options['chunk_size'] == null ? self.internalChunkSize : self.options['chunk_size'];
- self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata'];
- self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases'];
- self.position = 0;
- callback(null, self);
- });
- } else if(self.mode == "w+") {
- nthChunk(self, lastChunkNumber(self), options, function(err, chunk) {
- if(err) return error(err);
- // Set the current chunk
- self.currentChunk = chunk == null ? new Chunk(self, {'n':0}, self.writeConcern) : chunk;
- self.currentChunk.position = self.currentChunk.data.length();
- self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata'];
- self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases'];
- 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;
-
- var collection2 = self.chunkCollection();
- // No file exists set up write mode
- if(self.mode == "w") {
- // Delete any existing chunks
- deleteChunks(self, options, function(err, result) {
- if(err) return error(err);
- self.currentChunk = new Chunk(self, {'n':0}, self.writeConcern);
- self.contentType = self.options['content_type'] == null ? self.contentType : self.options['content_type'];
- self.internalChunkSize = self.options['chunk_size'] == null ? self.internalChunkSize : self.options['chunk_size'];
- self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata'];
- self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases'];
- self.position = 0;
- callback(null, self);
- });
- } else if(self.mode == "w+") {
- nthChunk(self, lastChunkNumber(self), options, function(err, chunk) {
- if(err) return error(err);
- // Set the current chunk
- self.currentChunk = chunk == null ? new Chunk(self, {'n':0}, self.writeConcern) : chunk;
- self.currentChunk.position = self.currentChunk.data.length();
- self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata'];
- self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases'];
- self.position = self.length;
- callback(null, self);
- });
- }
- }
-
- // only pass error to callback once
- function error (err) {
- if(error.err) return;
- callback(error.err = err);
- }
-};
-
-/**
- * Stores a file from the file system to the GridFS database.
- *
- * @param {String|Buffer|FileHandle} file the file to store.
- * @param {Function} callback this will be called after this method is executed. The first parameter will be null and the the second will contain the reference to this object.
- * @return {null}
- * @api public
- */
-GridStore.prototype.writeFile = function (file, callback) {
- var self = this;
- if (typeof file === 'string') {
- fs.open(file, 'r', function (err, fd) {
- if(err) return callback(err);
- self.writeFile(fd, callback);
- });
- return;
- }
-
- self.open(function (err, self) {
- if(err) return callback(err, self);
-
- fs.fstat(file, function (err, stats) {
- if(err) return callback(err, self);
-
- var offset = 0;
- var index = 0;
- var numberOfChunksLeft = Math.min(stats.size / self.chunkSize);
-
- // Write a chunk
- var writeChunk = function() {
- fs.read(file, self.chunkSize, offset, 'binary', function(err, data, bytesRead) {
- if(err) return callback(err, self);
-
- offset = offset + bytesRead;
-
- // Create a new chunk for the data
- var chunk = new Chunk(self, {n:index++}, self.writeConcern);
- chunk.write(data, function(err, chunk) {
- if(err) return callback(err, self);
-
- chunk.save({}, function(err, result) {
- if(err) return callback(err, self);
-
- self.position = self.position + data.length;
-
- // Point to current chunk
- self.currentChunk = chunk;
-
- if(offset >= stats.size) {
- fs.close(file);
- self.close(function(err, result) {
- if(err) return callback(err, self);
- return callback(null, self);
- });
- } else {
- return processor(writeChunk);
- }
- });
- });
- });
- }
-
- // Process the first write
- processor(writeChunk);
- });
- });
-};
-
-/**
- * Writes some data. This method will work properly only if initialized with mode
- * "w" or "w+".
- *
- * @param string {string} The data to write.
- * @param close {boolean=false} opt_argument Closes this file after writing if
- * true.
- * @param callback {function(*, GridStore)} This will be called after executing
- * this method. The first parameter will contain null and the second one
- * will contain a reference to this object.
- *
- * @ignore
- * @api private
- */
-var writeBuffer = function(self, buffer, close, callback) {
- if(typeof close === "function") { callback = close; close = null; }
- var finalClose = typeof close == 'boolean' ? close : false;
-
- if(self.mode[0] != "w") {
- callback(new Error((self.referenceBy == REFERENCE_BY_ID ? self.toHexString() : self.filename) + " not opened for writing"), null);
- } else {
- if(self.currentChunk.position + buffer.length >= self.chunkSize) {
- // Write out the current Chunk and then keep writing until we have less data left than a chunkSize left
- // to a new chunk (recursively)
- var previousChunkNumber = self.currentChunk.chunkNumber;
- var leftOverDataSize = self.chunkSize - self.currentChunk.position;
- var firstChunkData = buffer.slice(0, leftOverDataSize);
- var leftOverData = buffer.slice(leftOverDataSize);
- // A list of chunks to write out
- var chunksToWrite = [self.currentChunk.write(firstChunkData)];
- // If we have more data left than the chunk size let's keep writing new chunks
- while(leftOverData.length >= self.chunkSize) {
- // Create a new chunk and write to it
- var newChunk = new Chunk(self, {'n': (previousChunkNumber + 1)}, self.writeConcern);
- var firstChunkData = leftOverData.slice(0, self.chunkSize);
- leftOverData = leftOverData.slice(self.chunkSize);
- // Update chunk number
- previousChunkNumber = previousChunkNumber + 1;
- // Write data
- newChunk.write(firstChunkData);
- // Push chunk to save list
- chunksToWrite.push(newChunk);
- }
-
- // Set current chunk with remaining data
- self.currentChunk = new Chunk(self, {'n': (previousChunkNumber + 1)}, self.writeConcern);
- // If we have left over data write it
- if(leftOverData.length > 0) self.currentChunk.write(leftOverData);
-
- // Update the position for the gridstore
- self.position = self.position + buffer.length;
- // Total number of chunks to write
- var numberOfChunksToWrite = chunksToWrite.length;
-
- for(var i = 0; i < chunksToWrite.length; i++) {
- chunksToWrite[i].save({}, function(err, result) {
- if(err) return callback(err);
-
- numberOfChunksToWrite = numberOfChunksToWrite - 1;
-
- if(numberOfChunksToWrite <= 0) {
- // We care closing the file before returning
- if(finalClose) {
- return self.close(function(err, result) {
- callback(err, self);
- });
- }
-
- // Return normally
- 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);
- // We care closing the file before returning
- if(finalClose) {
- return self.close(function(err, result) {
- callback(err, self);
- });
- }
- // Return normally
- return 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) {
- // Calcuate the length
- 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) {
- if(err) return callback(err);
-
- mongoObject.md5 = results.md5;
- callback(null, 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") {
- // Set up options
- var options = self.writeConcern;
-
- if(self.currentChunk != null && self.currentChunk.position > 0) {
- self.currentChunk.save({}, function(err, chunk) {
- if(err && typeof callback == 'function') return callback(err);
-
- self.collection(function(err, files) {
- if(err && typeof callback == 'function') return callback(err);
-
- // Build the mongo object
- if(self.uploadDate != null) {
- files.remove({'_id':self.fileId}, self.writeConcern, function(err, collection) {
- if(err && typeof callback == 'function') return callback(err);
-
- buildMongoObject(self, function(err, mongoObject) {
- if(err) {
- if(typeof callback == 'function') return callback(err); else throw err;
- }
-
- files.save(mongoObject, options, function(err) {
- if(typeof callback == 'function')
- callback(err, mongoObject);
- });
- });
- });
- } else {
- self.uploadDate = new Date();
- buildMongoObject(self, function(err, mongoObject) {
- if(err) {
- if(typeof callback == 'function') return callback(err); else throw err;
- }
-
- files.save(mongoObject, options, function(err) {
- if(typeof callback == 'function')
- callback(err, mongoObject);
- });
- });
- }
- });
- });
- } else {
- self.collection(function(err, files) {
- if(err && typeof callback == 'function') return callback(err);
-
- self.uploadDate = new Date();
- buildMongoObject(self, function(err, mongoObject) {
- if(err) {
- if(typeof callback == 'function') return callback(err); else throw err;
- }
-
- files.save(mongoObject, options, function(err) {
- if(typeof callback == 'function')
- callback(err, mongoObject);
- });
- });
- });
- }
- } else if(self.mode[0] == "r") {
- if(typeof callback == 'function')
- callback(null, null);
- } else {
- if(typeof callback == 'function')
- callback(new Error("Illegal mode " + self.mode), null);
- }
-};
-
-/**
- * Gets the nth chunk of this file.
- *
- * @param chunkNumber {number} The nth chunk to retrieve.
- * @param callback {function(*, Chunk|object)} This will be called after
- * executing this method. null will be passed to the first parameter while
- * a new {@link Chunk} instance will be passed to the second parameter if
- * the chunk was found or an empty object {} if not.
- *
- * @ignore
- * @api private
- */
-var nthChunk = function(self, chunkNumber, options, callback) {
- if(typeof options == 'function') {
- callback = options;
- options = {};
- }
-
- options = options || self.writeConcern;
- options.readPreference = self.readPreference;
- // Get the nth chunk
- self.chunkCollection().findOne({'files_id':self.fileId, 'n':chunkNumber}, options, function(err, chunk) {
- if(err) return callback(err);
-
- var finalChunk = chunk == null ? {} : chunk;
- callback(null, new Chunk(self, finalChunk, self.writeConcern));
- });
-};
-
-/**
- *
- * @ignore
- * @api private
- */
-GridStore.prototype._nthChunk = function(chunkNumber, callback) {
- nthChunk(this, chunkNumber, callback);
-}
-
-/**
- * @return {Number} The last chunk number of this file.
- *
- * @ignore
- * @api private
- */
-var lastChunkNumber = function(self) {
- return Math.floor((self.length ? self.length - 1 : 0)/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) {
- if(typeof callback == 'function')
- return this.db.collection((this.root + ".chunks"), callback);
- return this.db.collection((this.root + ".chunks"));
-};
-
-/**
- * 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, options, callback) {
- if(typeof options == 'function') {
- callback = options;
- options = {};
- }
-
- options = options || self.writeConcern;
-
- if(self.fileId != null) {
- self.chunkCollection().remove({'files_id':self.fileId}, options, function(err, result) {
- if(err) return callback(err, false);
- callback(null, true);
- });
- } else {
- callback(null, true);
- }
-};
-
-/**
- * Deletes all the chunks of this file in the database.
- *
- * @param {Function} callback this will be called after this method executes. Passes null to the first and true to the second argument.
- * @return {null}
- * @api public
- */
-GridStore.prototype.unlink = function(callback) {
- var self = this;
- deleteChunks(this, function(err) {
- if(err!==null) {
- err.message = "at deleteChunks: " + err.message;
- return callback(err);
- }
-
- self.collection(function(err, collection) {
- if(err!==null) {
- err.message = "at collection: " + err.message;
- return callback(err);
- }
-
- collection.remove({'_id':self.fileId}, self.writeConcern, function(err) {
- callback(err, self);
- });
- });
- });
-};
-
-/**
- * Retrieves the file collection associated with this object.
- *
- * @param {Function} callback this will be called after executing this method. An exception object will be passed to the first parameter when an error occured or null otherwise. A new **{Collection}** object will be passed to the second parameter if no error occured.
- * @return {null}
- * @api public
- */
-GridStore.prototype.collection = function(callback) {
- if(typeof callback == 'function')
- this.db.collection(this.root + ".files", callback);
- return this.db.collection(this.root + ".files");
-};
-
-/**
- * Reads the data of this file.
- *
- * @param {String} [separator] the character to be recognized as the newline separator.
- * @param {Function} callback This will be called after this method is executed. The first parameter will be null and the second parameter will contain an array of strings representing the entire data, each element representing a line including the separator character.
- * @return {null}
- * @api public
- */
-GridStore.prototype.readlines = function(separator, callback) {
- var args = Array.prototype.slice.call(arguments, 0);
- callback = args.pop();
- separator = args.length ? args.shift() : "\n";
-
- this.read(function(err, data) {
- if(err) return callback(err);
-
- var items = data.toString().split(separator);
- items = items.length > 0 ? items.splice(0, items.length - 1) : [];
- for(var i = 0; i < items.length; i++) {
- items[i] = items[i] + separator;
- }
-
- callback(null, items);
- });
-};
-
-/**
- * Deletes all the chunks of this file in the database if mode was set to "w" or
- * "w+" and resets the read/write head to the initial position.
- *
- * @param {Function} callback this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object.
- * @return {null}
- * @api public
- */
-GridStore.prototype.rewind = function(callback) {
- var self = this;
-
- if(this.currentChunk.chunkNumber != 0) {
- if(this.mode[0] == "w") {
- deleteChunks(self, function(err, gridStore) {
- if(err) return callback(err);
- self.currentChunk = new Chunk(self, {'n': 0}, self.writeConcern);
- self.position = 0;
- callback(null, self);
- });
- } else {
- self.currentChunk(0, function(err, chunk) {
- if(err) return callback(err);
- self.currentChunk = chunk;
- self.currentChunk.rewind();
- self.position = 0;
- callback(null, self);
- });
- }
- } else {
- self.currentChunk.rewind();
- self.position = 0;
- callback(null, self);
- }
-};
-
-/**
- * Retrieves the contents of this file and advances the read/write head. Works with Buffers only.
- *
- * There are 3 signatures for this method:
- *
- * (callback)
- * (length, callback)
- * (length, buffer, callback)
- *
- * @param {Number} [length] the number of characters to read. Reads all the characters from the read/write head to the EOF if not specified.
- * @param {String|Buffer} [buffer] a string to hold temporary data. This is used for storing the string data read so far when recursively calling this method.
- * @param {Function} callback this will be called after this method is executed. null will be passed to the first parameter and a string containing the contents of the buffer concatenated with the contents read from this file will be passed to the second.
- * @return {null}
- * @api public
- */
-GridStore.prototype.read = function(length, buffer, callback) {
- var self = this;
-
- var args = Array.prototype.slice.call(arguments, 0);
- callback = args.pop();
- length = args.length ? args.shift() : null;
- buffer = args.length ? args.shift() : null;
-
- // The data is a c-terminated string and thus the length - 1
- var finalLength = length == null ? self.length - self.position : length;
- var finalBuffer = buffer == null ? new Buffer(finalLength) : buffer;
- // Add a index to buffer to keep track of writing position or apply current index
- finalBuffer._index = buffer != null && buffer._index != null ? buffer._index : 0;
-
- if((self.currentChunk.length() - self.currentChunk.position + finalBuffer._index) >= finalLength) {
- var slice = self.currentChunk.readSlice(finalLength - finalBuffer._index);
- // Copy content to final buffer
- slice.copy(finalBuffer, finalBuffer._index);
- // Update internal position
- self.position = self.position + finalBuffer.length;
- // Check if we don't have a file at all
- if(finalLength == 0 && finalBuffer.length == 0) return callback(new Error("File does not exist"), null);
- // Else return data
- callback(null, finalBuffer);
- } else {
- var slice = self.currentChunk.readSlice(self.currentChunk.length() - self.currentChunk.position);
- // Copy content to final buffer
- slice.copy(finalBuffer, finalBuffer._index);
- // Update index position
- finalBuffer._index += slice.length;
-
- // Load next chunk and read more
- nthChunk(self, self.currentChunk.chunkNumber + 1, function(err, chunk) {
- if(err) return callback(err);
-
- if(chunk.length() > 0) {
- self.currentChunk = chunk;
- self.read(length, finalBuffer, callback);
- } else {
- if (finalBuffer._index > 0) {
- callback(null, finalBuffer)
- } else {
- callback(new Error("no chunks found for file, possibly corrupt"), null);
- }
- }
- });
- }
-}
-
-/**
- * Retrieves the position of the read/write head of this file.
- *
- * @param {Function} callback This gets called after this method terminates. null is passed to the first parameter and the position is passed to the second.
- * @return {null}
- * @api public
- */
-GridStore.prototype.tell = function(callback) {
- callback(null, this.position);
-};
-
-/**
- * Moves the read/write head to a new location.
- *
- * There are 3 signatures for this method
- *
- * Seek Location Modes
- * - **GridStore.IO_SEEK_SET**, **(default)** set the position from the start of the file.
- * - **GridStore.IO_SEEK_CUR**, set the position from the current position in the file.
- * - **GridStore.IO_SEEK_END**, set the position from the end of the file.
- *
- * @param {Number} [position] the position to seek to
- * @param {Number} [seekLocation] seek mode. Use one of the Seek Location modes.
- * @param {Function} callback this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object.
- * @return {null}
- * @api public
- */
-GridStore.prototype.seek = function(position, seekLocation, callback) {
- var self = this;
-
- var args = Array.prototype.slice.call(arguments, 1);
- callback = args.pop();
- seekLocation = args.length ? args.shift() : null;
-
- var seekLocationFinal = seekLocation == null ? exports.GridStore.IO_SEEK_SET : seekLocation;
- var finalPosition = position;
- var targetPosition = 0;
-
- // Calculate the position
- if(seekLocationFinal == exports.GridStore.IO_SEEK_CUR) {
- targetPosition = self.position + finalPosition;
- } else if(seekLocationFinal == exports.GridStore.IO_SEEK_END) {
- targetPosition = self.length + finalPosition;
- } else {
- targetPosition = finalPosition;
- }
-
- // Get the chunk
- var newChunkNumber = Math.floor(targetPosition/self.chunkSize);
- if(newChunkNumber != self.currentChunk.chunkNumber) {
- var seekChunk = function() {
- nthChunk(self, newChunkNumber, function(err, chunk) {
- self.currentChunk = chunk;
- self.position = targetPosition;
- self.currentChunk.position = (self.position % self.chunkSize);
- callback(err, self);
- });
- };
-
- if(self.mode[0] == 'w') {
- self.currentChunk.save({}, function(err) {
- if(err) return callback(err);
- seekChunk();
- });
- } else {
- seekChunk();
- }
- } else {
- self.position = targetPosition;
- self.currentChunk.position = (self.position % self.chunkSize);
- callback(null, self);
- }
-};
-
-/**
- * Verify if the file is at EOF.
- *
- * @return {Boolean} true if the read/write head is at the end of this file.
- * @api public
- */
-GridStore.prototype.eof = function() {
- return this.position == this.length ? true : false;
-};
-
-/**
- * Retrieves a single character from this file.
- *
- * @param {Function} callback this gets called after this method is executed. Passes null to the first parameter and the character read to the second or null to the second if the read/write head is at the end of the file.
- * @return {null}
- * @api public
- */
-GridStore.prototype.getc = function(callback) {
- var self = this;
-
- if(self.eof()) {
- callback(null, null);
- } else if(self.currentChunk.eof()) {
- nthChunk(self, self.currentChunk.chunkNumber + 1, function(err, chunk) {
- self.currentChunk = chunk;
- self.position = self.position + 1;
- callback(err, self.currentChunk.getc());
- });
- } else {
- self.position = self.position + 1;
- callback(null, self.currentChunk.getc());
- }
-};
-
-/**
- * Writes a string to the file with a newline character appended at the end if
- * the given string does not have one.
- *
- * @param {String} string the string to write.
- * @param {Function} callback this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object.
- * @return {null}
- * @api public
- */
-GridStore.prototype.puts = function(string, callback) {
- var finalString = string.match(/\n$/) == null ? string + "\n" : string;
- this.write(finalString, callback);
-};
-
-/**
- * Returns read stream based on this GridStore file
- *
- * Events
- * - **data** {function(item) {}} the data event triggers when a document is ready.
- * - **end** {function() {}} the end event triggers when there is no more documents available.
- * - **close** {function() {}} the close event triggers when the stream is closed.
- * - **error** {function(err) {}} the error event triggers if an error happens.
- *
- * @param {Boolean} autoclose if true current GridStore will be closed when EOF and 'close' event will be fired
- * @return {null}
- * @api public
- */
-GridStore.prototype.stream = function(autoclose) {
- return new ReadStream(autoclose, this);
-};
-
-/**
-* The collection to be used for holding the files and chunks collection.
-*
-* @classconstant DEFAULT_ROOT_COLLECTION
-**/
-GridStore.DEFAULT_ROOT_COLLECTION = 'fs';
-
-/**
-* Default file mime type
-*
-* @classconstant DEFAULT_CONTENT_TYPE
-**/
-GridStore.DEFAULT_CONTENT_TYPE = 'binary/octet-stream';
-
-/**
-* Seek mode where the given length is absolute.
-*
-* @classconstant IO_SEEK_SET
-**/
-GridStore.IO_SEEK_SET = 0;
-
-/**
-* Seek mode where the given length is an offset to the current read/write head.
-*
-* @classconstant IO_SEEK_CUR
-**/
-GridStore.IO_SEEK_CUR = 1;
-
-/**
-* Seek mode where the given length is an offset to the end of the file.
-*
-* @classconstant IO_SEEK_END
-**/
-GridStore.IO_SEEK_END = 2;
-
-/**
- * Checks if a file exists in the database.
- *
- * Options
- * - **readPreference** {String}, the prefered read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
- *
- * @param {Db} db the database to query.
- * @param {String} name the name of the file to look for.
- * @param {String} [rootCollection] the root collection that holds the files and chunks collection. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**.
- * @param {Function} callback this will be called after this method executes. Passes null to the first and passes true to the second if the file exists and false otherwise.
- * @return {null}
- * @api public
- */
-GridStore.exist = function(db, fileIdObject, rootCollection, options, callback) {
- var args = Array.prototype.slice.call(arguments, 2);
- callback = args.pop();
- rootCollection = args.length ? args.shift() : null;
- options = args.length ? args.shift() : {};
-
- // Establish read preference
- var readPreference = options.readPreference || 'primary';
- // Fetch collection
- var rootCollectionFinal = rootCollection != null ? rootCollection : GridStore.DEFAULT_ROOT_COLLECTION;
- db.collection(rootCollectionFinal + ".files", function(err, collection) {
- if(err) return callback(err);
-
- // Build query
- var query = (typeof fileIdObject == 'string' || Object.prototype.toString.call(fileIdObject) == '[object RegExp]' )
- ? {'filename':fileIdObject}
- : {'_id':fileIdObject}; // Attempt to locate file
-
- collection.findOne(query, {readPreference:readPreference}, function(err, item) {
- if(err) return callback(err);
-
- callback(null, item == null ? false : true);
- });
- });
-};
-
-/**
- * Gets the list of files stored in the GridFS.
- *
- * @param {Db} db the database to query.
- * @param {String} [rootCollection] the root collection that holds the files and chunks collection. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**.
- * @param {Function} callback this will be called after this method executes. Passes null to the first and passes an array of strings containing the names of the files.
- * @return {null}
- * @api public
- */
-GridStore.list = function(db, rootCollection, options, callback) {
- var args = Array.prototype.slice.call(arguments, 1);
- callback = args.pop();
- rootCollection = args.length ? args.shift() : null;
- options = args.length ? args.shift() : {};
-
- // Ensure we have correct values
- if(rootCollection != null && typeof rootCollection == 'object') {
- options = rootCollection;
- rootCollection = null;
- }
-
- // Establish read preference
- var readPreference = options.readPreference || 'primary';
- // Check if we are returning by id not filename
- var byId = options['id'] != null ? options['id'] : false;
- // Fetch item
- var rootCollectionFinal = rootCollection != null ? rootCollection : GridStore.DEFAULT_ROOT_COLLECTION;
- var items = [];
- db.collection((rootCollectionFinal + ".files"), function(err, collection) {
- if(err) return callback(err);
-
- collection.find({}, {readPreference:readPreference}, function(err, cursor) {
- if(err) return callback(err);
-
- cursor.each(function(err, item) {
- if(item != null) {
- items.push(byId ? item._id : item.filename);
- } else {
- callback(err, items);
- }
- });
- });
- });
-};
-
-/**
- * Reads the contents of a file.
- *
- * This method has the following signatures
- *
- * (db, name, callback)
- * (db, name, length, callback)
- * (db, name, length, offset, callback)
- * (db, name, length, offset, options, callback)
- *
- * @param {Db} db the database to query.
- * @param {String} name the name of the file.
- * @param {Number} [length] the size of data to read.
- * @param {Number} [offset] the offset from the head of the file of which to start reading from.
- * @param {Object} [options] the options for the file.
- * @param {Function} callback this will be called after this method executes. A string with an error message will be passed to the first parameter when the length and offset combination exceeds the length of the file while an Error object will be passed if other forms of error occured, otherwise, a string is passed. The second parameter will contain the data read if successful or null if an error occured.
- * @return {null}
- * @api public
- */
-GridStore.read = function(db, name, length, offset, options, callback) {
- var args = Array.prototype.slice.call(arguments, 2);
- callback = args.pop();
- length = args.length ? args.shift() : null;
- offset = args.length ? args.shift() : null;
- options = args.length ? args.shift() : null;
-
- new GridStore(db, name, "r", options).open(function(err, gridStore) {
- if(err) return callback(err);
- // Make sure we are not reading out of bounds
- if(offset && offset >= gridStore.length) return callback("offset larger than size of file", null);
- if(length && length > gridStore.length) return callback("length is larger than the size of the file", null);
- if(offset && length && (offset + length) > gridStore.length) return callback("offset and length is larger than the size of the file", null);
-
- if(offset != null) {
- gridStore.seek(offset, function(err, gridStore) {
- if(err) return callback(err);
- gridStore.read(length, callback);
- });
- } else {
- gridStore.read(length, callback);
- }
- });
-};
-
-/**
- * Reads the data of this file.
- *
- * @param {Db} db the database to query.
- * @param {String} name the name of the file.
- * @param {String} [separator] the character to be recognized as the newline separator.
- * @param {Object} [options] file options.
- * @param {Function} callback this will be called after this method is executed. The first parameter will be null and the second parameter will contain an array of strings representing the entire data, each element representing a line including the separator character.
- * @return {null}
- * @api public
- */
-GridStore.readlines = function(db, name, separator, options, callback) {
- var args = Array.prototype.slice.call(arguments, 2);
- callback = args.pop();
- separator = args.length ? args.shift() : null;
- options = args.length ? args.shift() : null;
-
- var finalSeperator = separator == null ? "\n" : separator;
- new GridStore(db, name, "r", options).open(function(err, gridStore) {
- if(err) return callback(err);
- gridStore.readlines(finalSeperator, callback);
- });
-};
-
-/**
- * Deletes the chunks and metadata information of a file from GridFS.
- *
- * @param {Db} db the database to interact with.
- * @param {String|Array} names the name/names of the files to delete.
- * @param {Object} [options] the options for the files.
- * @callback {Function} this will be called after this method is executed. The first parameter will contain an Error object if an error occured or null otherwise. The second parameter will contain a reference to this object.
- * @return {null}
- * @api public
- */
-GridStore.unlink = function(db, names, options, callback) {
- var self = this;
- var args = Array.prototype.slice.call(arguments, 2);
- callback = args.pop();
- options = args.length ? args.shift() : {};
-
- // Get the write concern
- var writeConcern = _getWriteConcern(db, options);
-
- // List of names
- if(names.constructor == Array) {
- var tc = 0;
- for(var i = 0; i < names.length; i++) {
- ++tc;
- GridStore.unlink(db, names[i], options, function(result) {
- if(--tc == 0) {
- callback(null, self);
- }
- });
- }
- } else {
- new GridStore(db, names, "w", options).open(function(err, gridStore) {
- if(err) return callback(err);
- deleteChunks(gridStore, function(err, result) {
- if(err) return callback(err);
- gridStore.collection(function(err, collection) {
- if(err) return callback(err);
- collection.remove({'_id':gridStore.fileId}, writeConcern, function(err, result) {
- callback(err, self);
- });
- });
- });
- });
- }
-};
-
-/**
- * Returns the current chunksize of the file.
- *
- * @field chunkSize
- * @type {Number}
- * @getter
- * @setter
- * @property return number of bytes in the current chunkSize.
- */
-Object.defineProperty(GridStore.prototype, "chunkSize", { enumerable: true
- , get: function () {
- return this.internalChunkSize;
- }
- , set: function(value) {
- if(!(this.mode[0] == "w" && this.position == 0 && this.uploadDate == null)) {
- this.internalChunkSize = this.internalChunkSize;
- } else {
- this.internalChunkSize = value;
- }
- }
-});
-
-/**
- * The md5 checksum for this file.
- *
- * @field md5
- * @type {Number}
- * @getter
- * @setter
- * @property return this files md5 checksum.
- */
-Object.defineProperty(GridStore.prototype, "md5", { enumerable: true
- , get: function () {
- return this.internalMd5;
- }
-});
-
-/**
- * GridStore Streaming methods
- * Handles the correct return of the writeable stream status
- * @ignore
- */
-Object.defineProperty(GridStore.prototype, "writable", { enumerable: true
- , get: function () {
- if(this._writeable == null) {
- this._writeable = this.mode != null && this.mode.indexOf("w") != -1;
- }
- // Return the _writeable
- return this._writeable;
- }
- , set: function(value) {
- this._writeable = value;
- }
-});
-
-/**
- * Handles the correct return of the readable stream status
- * @ignore
- */
-Object.defineProperty(GridStore.prototype, "readable", { enumerable: true
- , get: function () {
- if(this._readable == null) {
- this._readable = this.mode != null && this.mode.indexOf("r") != -1;
- }
- return this._readable;
- }
- , set: function(value) {
- this._readable = value;
- }
-});
-
-GridStore.prototype.paused;
-
-/**
- * Handles the correct setting of encoding for the stream
- * @ignore
- */
-GridStore.prototype.setEncoding = fs.ReadStream.prototype.setEncoding;
-
-/**
- * Handles the end events
- * @ignore
- */
-GridStore.prototype.end = function end(data) {
- var self = this;
- // allow queued data to write before closing
- if(!this.writable) return;
- this.writable = false;
-
- if(data) {
- this._q.push(data);
- }
-
- this.on('drain', function () {
- self.close(function (err) {
- if (err) return _error(self, err);
- self.emit('close');
- });
- });
-
- _flush(self);
-}
-
-/**
- * Handles the normal writes to gridstore
- * @ignore
- */
-var _writeNormal = function(self, data, close, callback) {
- // If we have a buffer write it using the writeBuffer method
- if(Buffer.isBuffer(data)) {
- return writeBuffer(self, data, close, callback);
- } else {
- return writeBuffer(self, new Buffer(data, 'binary'), close, callback);
- }
-}
-
-/**
- * Writes some data. This method will work properly only if initialized with mode "w" or "w+".
- *
- * @param {String|Buffer} data the data to write.
- * @param {Boolean} [close] closes this file after writing if set to true.
- * @param {Function} callback this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object.
- * @return {null}
- * @api public
- */
-GridStore.prototype.write = function write(data, close, callback) {
- // If it's a normal write delegate the call
- if(typeof close == 'function' || typeof callback == 'function') {
- return _writeNormal(this, data, close, callback);
- }
-
- // Otherwise it's a stream write
- var self = this;
- if (!this.writable) {
- throw new Error('GridWriteStream is not writable');
- }
-
- // queue data until we open.
- if(!this._opened) {
- // Set up a queue to save data until gridstore object is ready
- this._q = [];
- _openStream(self);
- this._q.push(data);
- return false;
- }
-
- // Push data to queue
- this._q.push(data);
- _flush(this);
- // Return write successful
- return true;
-}
-
-/**
- * Handles the destroy part of a stream
- * @ignore
- */
-GridStore.prototype.destroy = function destroy() {
- // close and do not emit any more events. queued data is not sent.
- if(!this.writable) return;
- this.readable = false;
- if(this.writable) {
- this.writable = false;
- this._q.length = 0;
- this.emit('close');
- }
-}
-
-/**
- * Handles the destroySoon part of a stream
- * @ignore
- */
-GridStore.prototype.destroySoon = function destroySoon() {
- // as soon as write queue is drained, destroy.
- // may call destroy immediately if no data is queued.
- if(!this._q.length) {
- return this.destroy();
- }
- this._destroying = true;
-}
-
-/**
- * Handles the pipe part of the stream
- * @ignore
- */
-GridStore.prototype.pipe = function(destination, options) {
- var self = this;
- // Open the gridstore
- this.open(function(err, result) {
- if(err) _errorRead(self, err);
- if(!self.readable) return;
- // Set up the pipe
- self._pipe(destination, options);
- // Emit the stream is open
- self.emit('open');
- // Read from the stream
- _read(self);
- });
- return destination;
-}
-
-/**
- * Internal module methods
- * @ignore
- */
-var _read = function _read(self) {
- if (!self.readable || self.paused || self.reading) {
- return;
- }
-
- self.reading = true;
- var stream = self._stream = self.stream();
- stream.paused = self.paused;
-
- stream.on('data', function (data) {
- if (self._decoder) {
- var str = self._decoder.write(data);
- if (str.length) self.emit('data', str);
- } else {
- self.emit('data', data);
- }
- });
-
- stream.on('end', function (data) {
- self.emit('end', data);
- });
-
- stream.on('error', function (data) {
- _errorRead(self, data);
- });
-
- stream.on('close', function (data) {
- self.emit('close', data);
- });
-
- self.pause = function () {
- // native doesn't always pause.
- // bypass its pause() method to hack it
- self.paused = stream.paused = true;
- }
-
- self.resume = function () {
- if(!self.paused) return;
-
- self.paused = false;
- stream.resume();
- self.readable = stream.readable;
- }
-
- self.destroy = function () {
- self.readable = false;
- stream.destroy();
- }
-}
-
-/**
- * pause
- * @ignore
- */
-GridStore.prototype.pause = function pause () {
- // Overridden when the GridStore opens.
- this.paused = true;
-}
-
-/**
- * resume
- * @ignore
- */
-GridStore.prototype.resume = function resume () {
- // Overridden when the GridStore opens.
- this.paused = false;
-}
-
-/**
- * Internal module methods
- * @ignore
- */
-var _flush = function _flush(self, _force) {
- if (!self._opened) return;
- if (!_force && self._flushing) return;
- self._flushing = true;
-
- // write the entire q to gridfs
- if (!self._q.length) {
- self._flushing = false;
- self.emit('drain');
-
- if(self._destroying) {
- self.destroy();
- }
- return;
- }
-
- self.write(self._q.shift(), function (err, store) {
- if (err) return _error(self, err);
- self.emit('progress', store.position);
- _flush(self, true);
- });
-}
-
-var _openStream = function _openStream (self) {
- if(self._opening == true) return;
- self._opening = true;
-
- // Open the store
- self.open(function (err, gridstore) {
- if (err) return _error(self, err);
- self._opened = true;
- self.emit('open');
- _flush(self);
- });
-}
-
-var _error = function _error(self, err) {
- self.destroy();
- self.emit('error', err);
-}
-
-var _errorRead = function _errorRead (self, err) {
- self.readable = false;
- self.emit('error', err);
-}
-
-/**
- * @ignore
- */
-var _hasWriteConcern = function(errorOptions) {
- return errorOptions == true
- || errorOptions.w > 0
- || errorOptions.w == 'majority'
- || errorOptions.j == true
- || errorOptions.journal == true
- || errorOptions.fsync == true
-}
-
-/**
- * @ignore
- */
-var _setWriteConcernHash = function(options) {
- var finalOptions = {};
- if(options.w != null) finalOptions.w = options.w;
- if(options.journal == true) finalOptions.j = options.journal;
- if(options.j == true) finalOptions.j = options.j;
- if(options.fsync == true) finalOptions.fsync = options.fsync;
- if(options.wtimeout != null) finalOptions.wtimeout = options.wtimeout;
- return finalOptions;
-}
-
-/**
- * @ignore
- */
-var _getWriteConcern = function(self, options) {
- // Final options
- var finalOptions = {w:1};
- options = options || {};
-
- // Local options verification
- if(options.w != null || typeof options.j == 'boolean' || typeof options.journal == 'boolean' || typeof options.fsync == 'boolean') {
- finalOptions = _setWriteConcernHash(options);
- } else if(options.safe != null && typeof options.safe == 'object') {
- finalOptions = _setWriteConcernHash(options.safe);
- } else if(typeof options.safe == "boolean") {
- finalOptions = {w: (options.safe ? 1 : 0)};
- } else if(self.options.w != null || typeof self.options.j == 'boolean' || typeof self.options.journal == 'boolean' || typeof self.options.fsync == 'boolean') {
- finalOptions = _setWriteConcernHash(self.options);
- } else if(self.safe.w != null || typeof self.safe.j == 'boolean' || typeof self.safe.journal == 'boolean' || typeof self.safe.fsync == 'boolean') {
- finalOptions = _setWriteConcernHash(self.safe);
- } else if(typeof self.safe == "boolean") {
- finalOptions = {w: (self.safe ? 1 : 0)};
- }
-
- // Ensure we don't have an invalid combination of write concerns
- if(finalOptions.w < 1
- && (finalOptions.journal == true || finalOptions.j == true || finalOptions.fsync == true)) throw new Error("No acknowledgement using w < 1 cannot be combined with journal:true or fsync:true");
-
- // Return the options
- return finalOptions;
-}
-
-/**
- * @ignore
- * @api private
- */
-exports.GridStore = GridStore;
diff --git a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/gridfs/readstream.js b/node_modules/mongojs/node_modules/mongodb/lib/mongodb/gridfs/readstream.js
deleted file mode 100644
index 4a4f7ee..0000000
--- a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/gridfs/readstream.js
+++ /dev/null
@@ -1,206 +0,0 @@
-var Stream = require('stream').Stream,
- timers = require('timers'),
- util = require('util');
-
-// Set processor, setImmediate if 0.10 otherwise nextTick
-var processor = require('../utils').processor();
-
-/**
- * ReadStream
- *
- * Returns a stream interface for the **file**.
- *
- * Events
- * - **data** {function(item) {}} the data event triggers when a document is ready.
- * - **end** {function() {}} the end event triggers when there is no more documents available.
- * - **close** {function() {}} the close event triggers when the stream is closed.
- * - **error** {function(err) {}} the error event triggers if an error happens.
- *
- * @class Represents a GridFS File Stream.
- * @param {Boolean} autoclose automatically close file when the stream reaches the end.
- * @param {GridStore} cursor a cursor object that the stream wraps.
- * @return {ReadStream}
- */
-function ReadStream(autoclose, gstore) {
- if (!(this instanceof ReadStream)) return new ReadStream(autoclose, gstore);
- Stream.call(this);
-
- this.autoclose = !!autoclose;
- this.gstore = gstore;
-
- this.finalLength = gstore.length - gstore.position;
- this.completedLength = 0;
- this.currentChunkNumber = gstore.currentChunk.chunkNumber;
-
- this.paused = false;
- this.readable = true;
- this.pendingChunk = null;
- this.executing = false;
- this.destroyed = false;
-
- // Calculate the number of chunks
- this.numberOfChunks = Math.ceil(gstore.length/gstore.chunkSize);
-
- // This seek start position inside the current chunk
- this.seekStartPosition = gstore.position - (this.currentChunkNumber * gstore.chunkSize);
-
- var self = this;
- processor(function() {
- self._execute();
- });
-};
-
-/**
- * Inherit from Stream
- * @ignore
- * @api private
- */
-ReadStream.prototype.__proto__ = Stream.prototype;
-
-/**
- * Flag stating whether or not this stream is readable.
- */
-ReadStream.prototype.readable;
-
-/**
- * Flag stating whether or not this stream is paused.
- */
-ReadStream.prototype.paused;
-
-/**
- * @ignore
- * @api private
- */
-ReadStream.prototype._execute = function() {
- if(this.paused === true || this.readable === false) {
- return;
- }
-
- var gstore = this.gstore;
- var self = this;
- // Set that we are executing
- this.executing = true;
-
- var last = false;
- var toRead = 0;
-
- if(gstore.currentChunk.chunkNumber >= (this.numberOfChunks - 1)) {
- self.executing = false;
- last = true;
- }
-
- // Data setup
- var data = null;
-
- // Read a slice (with seek set if none)
- if(this.seekStartPosition > 0 && (gstore.currentChunk.length() - this.seekStartPosition) > 0) {
- data = gstore.currentChunk.readSlice(gstore.currentChunk.length() - this.seekStartPosition);
- this.seekStartPosition = 0;
- } else {
- data = gstore.currentChunk.readSlice(gstore.currentChunk.length());
- }
-
- var processNext = function() {
- 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.destroyed = true;
- self.emit("close", doc);
- });
- } else {
- self.readable = false;
- self.destroyed = true;
- self.emit("close");
- }
- }
- } else {
- gstore._nthChunk(gstore.currentChunk.chunkNumber + 1, function(err, chunk) {
- if(err) {
- self.readable = false;
- if(self.listeners("error").length > 0)
- 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();
- });
- }
- }
-
- // Return the data
- if(data != null && gstore.currentChunk.chunkNumber == self.currentChunkNumber) {
- self.currentChunkNumber = self.currentChunkNumber + 1;
- self.completedLength += data.length;
- self.pendingChunk = null;
- // Send the data
- process.nextTick(function() {
- self.emit("data", data);
- processNext();
- })
- } else {
- processNext();
- }
-};
-
-/**
- * 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() {
- if(this.destroyed) return;
- this.destroyed = true;
- this.readable = false;
- // Emit close event
- this.emit("close");
-};
-
-/**
- * Resumes this stream.
- *
- * @ignore
- * @api public
- */
-ReadStream.prototype.resume = function() {
- if(this.paused === false || !this.readable) {
- return;
- }
-
- this.paused = false;
- var self = this;
- processor(function() {
- self._execute();
- });
-};
-
-exports.ReadStream = ReadStream;
diff --git a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/index.js b/node_modules/mongojs/node_modules/mongodb/lib/mongodb/index.js
deleted file mode 100644
index 05a4cde..0000000
--- a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/index.js
+++ /dev/null
@@ -1,62 +0,0 @@
-try {
- exports.BSONPure = require('bson').BSONPure;
- exports.BSONNative = require('bson').BSONNative;
-} catch(err) {
- // do nothing
-}
-
-// export the driver version
-exports.version = require('../../package').version;
-
-[ 'commands/base_command'
- , 'admin'
- , 'collection'
- , 'connection/read_preference'
- , 'connection/connection'
- , 'connection/server'
- , 'connection/mongos'
- , 'connection/repl_set/repl_set'
- , 'mongo_client'
- , 'cursor'
- , 'db'
- , 'mongo_client'
- , 'gridfs/grid'
- , 'gridfs/chunk'
- , 'gridfs/gridstore'].forEach(function (path) {
- var module = require('./' + path);
- for (var i in module) {
- exports[i] = module[i];
- }
-});
-
-// backwards compat
-exports.ReplSetServers = exports.ReplSet;
-// Add BSON Classes
-exports.Binary = require('bson').Binary;
-exports.Code = require('bson').Code;
-exports.DBRef = require('bson').DBRef;
-exports.Double = require('bson').Double;
-exports.Long = require('bson').Long;
-exports.MinKey = require('bson').MinKey;
-exports.MaxKey = require('bson').MaxKey;
-exports.ObjectID = require('bson').ObjectID;
-exports.Symbol = require('bson').Symbol;
-exports.Timestamp = require('bson').Timestamp;
-// Add BSON Parser
-exports.BSON = require('bson').BSONPure.BSON;
-
-// Set up the connect function
-var connect = exports.Db.connect;
-
-// Add the pure and native backward compatible functions
-exports.pure = exports.native = function() {
- return connect;
-}
-
-// Map all values to the exports value
-for(var name in exports) {
- connect[name] = exports[name];
-}
-
-// Set our exports to be the connect function
-module.exports = connect;
diff --git a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/mongo_client.js b/node_modules/mongojs/node_modules/mongodb/lib/mongodb/mongo_client.js
deleted file mode 100644
index 04a0fc2..0000000
--- a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/mongo_client.js
+++ /dev/null
@@ -1,482 +0,0 @@
-var Db = require('./db').Db
- , Server = require('./connection/server').Server
- , Mongos = require('./connection/mongos').Mongos
- , ReplSet = require('./connection/repl_set/repl_set').ReplSet
- , ReadPreference = require('./connection/read_preference').ReadPreference
- , inherits = require('util').inherits
- , EventEmitter = require('events').EventEmitter
- , parse = require('./connection/url_parser').parse;
-
-/**
- * Create a new MongoClient instance.
- *
- * Options
- * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write
- * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option)
- * - **fsync**, (Boolean, default:false) write waits for fsync before returning, from MongoDB 2.6 on, fsync cannot be combined with journal
- * - **j**, (Boolean, default:false) write waits for journal sync before returning
- * - **readPreference** {String}, the prefered read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
- * - **native_parser** {Boolean, default:false}, use c++ bson parser.
- * - **forceServerObjectId** {Boolean, default:false}, force server to create _id fields instead of client.
- * - **pkFactory** {Object}, object overriding the basic ObjectID primary key generation.
- * - **serializeFunctions** {Boolean, default:false}, serialize functions.
- * - **raw** {Boolean, default:false}, peform operations using raw bson buffers.
- * - **recordQueryStats** {Boolean, default:false}, record query statistics during execution.
- * - **retryMiliSeconds** {Number, default:5000}, number of miliseconds between retries.
- * - **numberOfRetries** {Number, default:5}, number of retries off connection.
- * - **bufferMaxEntries** {Boolean, default: -1}, sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited
- *
- * @class Represents a MongoClient
- * @param {Object} serverConfig server config object.
- * @param {Object} [options] additional options for the collection.
- */
-function MongoClient(serverConfig, options) {
- if(serverConfig != null) {
- options = options ? options : {};
- // If no write concern is set set the default to w:1
- if('w' in options === false) {
- options.w = 1;
- }
-
- // The internal db instance we are wrapping
- this._db = new Db('test', serverConfig, options);
- }
-}
-
-/**
- * @ignore
- */
-inherits(MongoClient, EventEmitter);
-
-/**
- * Connect to MongoDB using a url as documented at
- *
- * docs.mongodb.org/manual/reference/connection-string/
- *
- * Options
- * - **uri_decode_auth** {Boolean, default:false} uri decode the user name and password for authentication
- * - **db** {Object, default: null} a hash off options to set on the db object, see **Db constructor**
- * - **server** {Object, default: null} a hash off options to set on the server objects, see **Server** constructor**
- * - **replSet** {Object, default: null} a hash off options to set on the replSet object, see **ReplSet** constructor**
- * - **mongos** {Object, default: null} a hash off options to set on the mongos object, see **Mongos** constructor**
- *
- * @param {String} url connection url for MongoDB.
- * @param {Object} [options] optional options for insert command
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the initialized db object or null if an error occured.
- * @return {null}
- * @api public
- */
-MongoClient.prototype.connect = function(url, options, callback) {
- var self = this;
-
- if(typeof options == 'function') {
- callback = options;
- options = {};
- }
-
- MongoClient.connect(url, options, function(err, db) {
- if(err) return callback(err, db);
- // Store internal db instance reference
- self._db = db;
- // Emit open and perform callback
- self.emit("open", err, db);
- callback(err, db);
- });
-}
-
-/**
- * Initialize the database connection.
- *
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the connected mongoclient or null if an error occured.
- * @return {null}
- * @api public
- */
-MongoClient.prototype.open = function(callback) {
- // Self reference
- var self = this;
- // Open the db
- this._db.open(function(err, db) {
- if(err) return callback(err, null);
- // Emit open event
- self.emit("open", err, db);
- // Callback
- callback(null, self);
- })
-}
-
-/**
- * Close the current db connection, including all the child db instances. Emits close event and calls optional callback.
- *
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the close method or null if an error occured.
- * @return {null}
- * @api public
- */
-MongoClient.prototype.close = function(callback) {
- this._db.close(callback);
-}
-
-/**
- * Create a new Db instance sharing the current socket connections.
- *
- * @param {String} dbName the name of the database we want to use.
- * @return {Db} a db instance using the new database.
- * @api public
- */
-MongoClient.prototype.db = function(dbName) {
- return this._db.db(dbName);
-}
-
-/**
- * Connect to MongoDB using a url as documented at
- *
- * docs.mongodb.org/manual/reference/connection-string/
- *
- * Options
- * - **uri_decode_auth** {Boolean, default:false} uri decode the user name and password for authentication
- * - **db** {Object, default: null} a hash off options to set on the db object, see **Db constructor**
- * - **server** {Object, default: null} a hash off options to set on the server objects, see **Server** constructor**
- * - **replSet** {Object, default: null} a hash off options to set on the replSet object, see **ReplSet** constructor**
- * - **mongos** {Object, default: null} a hash off options to set on the mongos object, see **Mongos** constructor**
- *
- * @param {String} url connection url for MongoDB.
- * @param {Object} [options] optional options for insert command
- * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the initialized db object or null if an error occured.
- * @return {null}
- * @api public
- */
-MongoClient.connect = function(url, options, callback) {
- var args = Array.prototype.slice.call(arguments, 1);
- callback = typeof args[args.length - 1] == 'function' ? args.pop() : null;
- options = args.length ? args.shift() : null;
- options = options || {};
-
- // Set default empty server options
- var serverOptions = options.server || {};
- var mongosOptions = options.mongos || {};
- var replSetServersOptions = options.replSet || options.replSetServers || {};
- var dbOptions = options.db || {};
-
- // If callback is null throw an exception
- if(callback == null)
- throw new Error("no callback function provided");
-
- // Parse the string
- var object = parse(url, options);
-
- // Merge in any options for db in options object
- if(dbOptions) {
- for(var name in dbOptions) object.db_options[name] = dbOptions[name];
- }
-
- // Added the url to the options
- object.db_options.url = url;
-
- // Merge in any options for server in options object
- if(serverOptions) {
- for(var name in serverOptions) object.server_options[name] = serverOptions[name];
- }
-
- // Merge in any replicaset server options
- if(replSetServersOptions) {
- for(var name in replSetServersOptions) object.rs_options[name] = replSetServersOptions[name];
- }
-
- // Merge in any replicaset server options
- if(mongosOptions) {
- for(var name in mongosOptions) object.mongos_options[name] = mongosOptions[name];
- }
-
- // We need to ensure that the list of servers are only either direct members or mongos
- // they cannot be a mix of monogs and mongod's
- var totalNumberOfServers = object.servers.length;
- var totalNumberOfMongosServers = 0;
- var totalNumberOfMongodServers = 0;
- var serverConfig = null;
- var errorServers = {};
-
- // Failure modes
- if(object.servers.length == 0) throw new Error("connection string must contain at least one seed host");
-
- // If we have no db setting for the native parser try to set the c++ one first
- object.db_options.native_parser = _setNativeParser(object.db_options);
- // If no auto_reconnect is set, set it to true as default for single servers
- if(typeof object.server_options.auto_reconnect != 'boolean') {
- object.server_options.auto_reconnect = true;
- }
-
- // Establish the correct socketTimeout
- var connectTimeoutMS = 30000;
- var socketTimeoutMS = 0;
-
- // We have a server connection timeout setting
- if(object.server_options && object.server_options.socketOptions && object.server_options.socketOptions.connectTimeoutMS) {
- connectTimeoutMS = object.server_options.socketOptions.connectTimeoutMS;
- }
-
- // We have a rs options set for connection timeout, override any server ones
- if(object.rs_options && object.rs_options.socketOptions && object.rs_options.socketOptions.connectTimeoutMS) {
- connectTimeoutMS = object.rs_options.socketOptions.connectTimeoutMS;
- }
-
- // If we have no socket settings set the default values
- if(object.rs_options.socketOptions.connectTimeoutMS == null) {
- object.rs_options.socketOptions.connectTimeoutMS = connectTimeoutMS;
- }
-
- if(object.rs_options.socketOptions.socketTimeoutMS == null) {
- object.rs_options.socketOptions.socketTimeoutMS = socketTimeoutMS;
- }
-
- if(object.server_options.socketOptions.connectTimeoutMS == null) {
- object.server_options.socketOptions.connectTimeoutMS = connectTimeoutMS;
- }
-
- if(object.server_options.socketOptions.socketTimeoutMS == null) {
- object.server_options.socketOptions.socketTimeoutMS = socketTimeoutMS;
- }
-
- // If we have more than a server, it could be replicaset or mongos list
- // need to verify that it's one or the other and fail if it's a mix
- // Connect to all servers and run ismaster
- for(var i = 0; i < object.servers.length; i++) {
- // Set up socket options
- var _server_options = {
- poolSize:1
- , socketOptions: {
- connectTimeoutMS: connectTimeoutMS
- , socketTimeoutMS: socketTimeoutMS
- }
- , auto_reconnect:false};
-
- // Ensure we have ssl setup for the servers
- if(object.rs_options.ssl) {
- _server_options.ssl = object.rs_options.ssl;
- _server_options.sslValidate = object.rs_options.sslValidate;
- _server_options.sslCA = object.rs_options.sslCA;
- _server_options.sslCert = object.rs_options.sslCert;
- _server_options.sslKey = object.rs_options.sslKey;
- _server_options.sslPass = object.rs_options.sslPass;
- } else if(object.server_options.ssl) {
- _server_options.ssl = object.server_options.ssl;
- _server_options.sslValidate = object.server_options.sslValidate;
- _server_options.sslCA = object.server_options.sslCA;
- _server_options.sslCert = object.server_options.sslCert;
- _server_options.sslKey = object.server_options.sslKey;
- _server_options.sslPass = object.server_options.sslPass;
- }
-
- // Set up the Server object
- var _server = object.servers[i].domain_socket
- ? new Server(object.servers[i].domain_socket, _server_options)
- : new Server(object.servers[i].host, object.servers[i].port, _server_options);
-
- var connectFunction = function(__server) {
- // Attempt connect
- new Db(object.dbName, __server, {w:1, native_parser:false}).open(function(err, db) {
- // Update number of servers
- totalNumberOfServers = totalNumberOfServers - 1;
- // If no error do the correct checks
- if(!err) {
- // Close the connection
- db.close(true);
- var isMasterDoc = db.serverConfig.isMasterDoc;
- // Check what type of server we have
- if(isMasterDoc.setName) totalNumberOfMongodServers++;
- if(isMasterDoc.msg && isMasterDoc.msg == "isdbgrid") totalNumberOfMongosServers++;
- } else {
- errorServers[__server.host + ":" + __server.port] = __server;
- }
-
- if(totalNumberOfServers == 0) {
- // If we have a mix of mongod and mongos, throw an error
- if(totalNumberOfMongosServers > 0 && totalNumberOfMongodServers > 0) {
- return process.nextTick(function() {
- try {
- callback(new Error("cannot combine a list of replicaset seeds and mongos seeds"));
- } catch (err) {
- if(db) db.close();
- throw err
- }
- })
- }
-
- if(totalNumberOfMongodServers == 0 && object.servers.length == 1) {
- var obj = object.servers[0];
- serverConfig = obj.domain_socket ?
- new Server(obj.domain_socket, object.server_options)
- : new Server(obj.host, obj.port, object.server_options);
- } else if(totalNumberOfMongodServers > 0 || totalNumberOfMongosServers > 0) {
- var finalServers = object.servers
- .filter(function(serverObj) {
- return errorServers[serverObj.host + ":" + serverObj.port] == null;
- })
- .map(function(serverObj) {
- return new Server(serverObj.host, serverObj.port, object.server_options);
- });
- // Clean out any error servers
- errorServers = {};
- // Set up the final configuration
- if(totalNumberOfMongodServers > 0) {
- serverConfig = new ReplSet(finalServers, object.rs_options);
- } else {
- serverConfig = new Mongos(finalServers, object.mongos_options);
- }
- }
-
- if(serverConfig == null) {
- return process.nextTick(function() {
- try {
- callback(new Error("Could not locate any valid servers in initial seed list"));
- } catch (err) {
- if(db) db.close();
- throw err
- }
- });
- }
- // Ensure no firing off open event before we are ready
- serverConfig.emitOpen = false;
- // Set up all options etc and connect to the database
- _finishConnecting(serverConfig, object, options, callback)
- }
- });
- }
-
- // Wrap the context of the call
- connectFunction(_server);
- }
-}
-
-var _setNativeParser = function(db_options) {
- if(typeof db_options.native_parser == 'boolean') return db_options.native_parser;
-
- try {
- require('bson').BSONNative.BSON;
- return true;
- } catch(err) {
- return false;
- }
-}
-
-var _finishConnecting = function(serverConfig, object, options, callback) {
- // Safe settings
- var safe = {};
- // Build the safe parameter if needed
- if(object.db_options.journal) safe.j = object.db_options.journal;
- if(object.db_options.w) safe.w = object.db_options.w;
- if(object.db_options.fsync) safe.fsync = object.db_options.fsync;
- if(object.db_options.wtimeoutMS) safe.wtimeout = object.db_options.wtimeoutMS;
-
- // If we have a read Preference set
- if(object.db_options.read_preference) {
- var readPreference = new ReadPreference(object.db_options.read_preference);
- // If we have the tags set up
- if(object.db_options.read_preference_tags)
- readPreference = new ReadPreference(object.db_options.read_preference, object.db_options.read_preference_tags);
- // Add the read preference
- object.db_options.readPreference = readPreference;
- }
-
- // No safe mode if no keys
- if(Object.keys(safe).length == 0) safe = false;
-
- // Add the safe object
- object.db_options.safe = safe;
-
- // Get the socketTimeoutMS
- var socketTimeoutMS = object.server_options.socketOptions.socketTimeoutMS || 0;
- var connectTimeoutMS = object.server_options.socketOptions.connectTimeoutMS || 30000;
-
- // If we have a replset, override with replicaset socket timeout option if available
- if(serverConfig instanceof ReplSet) {
- socketTimeoutMS = object.rs_options.socketOptions.socketTimeoutMS || socketTimeoutMS;
- }
-
- //
- // Set socketTimeout to same as connectionTimeout to ensure we don't block on connect and auth
- // This is a workaround for pre 2.6 servers where auth can hang when indexes are build on secondaries
- serverConfig.setSocketOptions({socketTimeoutMS: connectTimeoutMS, connectTimeoutMS: connectTimeoutMS});
-
- // Set up the db options
- var db = new Db(object.dbName, serverConfig, object.db_options);
- // Open the db
- db.open(function(err, db){
- if(err) {
- return process.nextTick(function() {
- try {
- callback(err, null);
- } catch (err) {
- if(db) db.close();
- throw err
- }
- });
- }
-
- //
- // Set socketTimeout to same as connectionTimeout to ensure we don't block on connect and auth
- // This is a workaround for pre 2.6 servers where auth can hang when indexes are build on secondaries
- serverConfig.setSocketOptions({socketTimeoutMS: connectTimeoutMS, connectTimeoutMS: connectTimeoutMS});
-
- // Set the provided write concern or fall back to w:1 as default
- if(db.options !== null && !db.options.safe && !db.options.journal
- && !db.options.w && !db.options.fsync && typeof db.options.w != 'number'
- && (db.options.safe == false && object.db_options.url.indexOf("safe=") == -1)) {
- db.options.w = 1;
- }
-
- if(err == null && object.auth){
- // What db to authenticate against
- var authentication_db = db;
- if(object.db_options && object.db_options.authSource) {
- authentication_db = db.db(object.db_options.authSource);
- }
-
- // Build options object
- var options = {};
- if(object.db_options.authMechanism) options.authMechanism = object.db_options.authMechanism;
- if(object.db_options.gssapiServiceName) options.gssapiServiceName = object.db_options.gssapiServiceName;
-
- // Authenticate
- authentication_db.authenticate(object.auth.user, object.auth.password, options, function(err, success){
- // Reset the socket timeout
- serverConfig.setSocketOptions({socketTimeoutMS: socketTimeoutMS, connectTimeoutMS: connectTimeoutMS});
-
- // Handle the results
- if(success){
- process.nextTick(function() {
- try {
- callback(null, db);
- } catch (err) {
- if(db) db.close();
- throw err
- }
- });
- } else {
- if(db) db.close();
- process.nextTick(function() {
- try {
- callback(err ? err : new Error('Could not authenticate user ' + object.auth[0]), null);
- } catch (err) {
- if(db) db.close();
- throw err
- }
- });
- }
- });
- } else {
- // Reset the socket timeout
- serverConfig.setSocketOptions({socketTimeoutMS: socketTimeoutMS, connectTimeoutMS: connectTimeoutMS});
-
- // Return connection
- process.nextTick(function() {
- try {
- callback(err, db);
- } catch (err) {
- if(db) db.close();
- throw err
- }
- })
- }
- });
-}
-
-exports.MongoClient = MongoClient;
\ No newline at end of file
diff --git a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/responses/mongo_reply.js b/node_modules/mongojs/node_modules/mongodb/lib/mongodb/responses/mongo_reply.js
deleted file mode 100644
index 21e8cec..0000000
--- a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/responses/mongo_reply.js
+++ /dev/null
@@ -1,83 +0,0 @@
-var Long = require('bson').Long
- , timers = require('timers');
-
-// Set processor, setImmediate if 0.10 otherwise nextTick
-var processor = require('../utils').processor();
-
-/**
- Reply message from mongo db
-**/
-var MongoReply = exports.MongoReply = function() {
- this.documents = [];
- this.index = 0;
-};
-
-MongoReply.prototype.parseHeader = function(binary_reply, bson) {
- // Unpack the standard header first
- this.messageLength = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24;
- this.index = this.index + 4;
- // Fetch the request id for this reply
- this.requestId = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24;
- this.index = this.index + 4;
- // Fetch the id of the request that triggered the response
- this.responseTo = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24;
- // Skip op-code field
- this.index = this.index + 4 + 4;
- // Unpack the reply message
- this.responseFlag = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24;
- this.index = this.index + 4;
- // Unpack the cursor id (a 64 bit long integer)
- var low_bits = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24;
- this.index = this.index + 4;
- var high_bits = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24;
- this.index = this.index + 4;
- this.cursorId = new Long(low_bits, high_bits);
- // Unpack the starting from
- this.startingFrom = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24;
- this.index = this.index + 4;
- // Unpack the number of objects returned
- this.numberReturned = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24;
- this.index = this.index + 4;
-}
-
-MongoReply.prototype.parseBody = function(binary_reply, bson, raw, callback) {
- raw = raw == null ? false : raw;
-
- try {
- // Let's unpack all the bson documents, deserialize them and store them
- for(var object_index = 0; object_index < this.numberReturned; object_index++) {
- var _options = {promoteLongs: bson.promoteLongs};
-
- // Read the size of the bson object
- var bsonObjectSize = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24;
-
- // If we are storing the raw responses to pipe straight through
- if(raw) {
- // Deserialize the object and add to the documents array
- this.documents.push(binary_reply.slice(this.index, this.index + bsonObjectSize));
- } else {
- // Deserialize the object and add to the documents array
- this.documents.push(bson.deserialize(binary_reply.slice(this.index, this.index + bsonObjectSize), _options));
- }
-
- // Adjust binary index to point to next block of binary bson data
- this.index = this.index + bsonObjectSize;
- }
-
- // No error return
- callback(null);
- } catch(err) {
- return callback(err);
- }
-}
-
-MongoReply.prototype.is_error = function(){
- if(this.documents.length == 1) {
- return this.documents[0].ok == 1 ? false : true;
- }
- return false;
-};
-
-MongoReply.prototype.error_message = function() {
- return this.documents.length == 1 && this.documents[0].ok == 1 ? '' : this.documents[0].errmsg;
-};
\ No newline at end of file
diff --git a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/scope.js b/node_modules/mongojs/node_modules/mongodb/lib/mongodb/scope.js
deleted file mode 100644
index 19ca386..0000000
--- a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/scope.js
+++ /dev/null
@@ -1,86 +0,0 @@
-var Cursor = require('./cursor').Cursor
- , Readable = require('stream').Readable
- , utils = require('./utils')
- , inherits = require('util').inherits;
-
-var Scope = function(collection, _selector, _fields, _scope_options) {
- var self = this;
-
- // Ensure we have at least an empty cursor options object
- _scope_options = _scope_options || {};
- var _write_concern = _scope_options.write_concern || null;
-
- // Ensure default read preference
- // if(!_scope_options.readPreference) _scope_options.readPreference = 'primary';
-
- // Set up the cursor
- var _cursor = new Cursor(
- collection.db, collection, _selector
- , _fields, _scope_options
- );
-
- // Write branch options
- var writeOptions = {
- insert: function(documents, callback) {
- // Merge together options
- var options = _write_concern || {};
- // Execute insert
- collection.insert(documents, options, callback);
- },
-
- save: function(document, callback) {
- // Merge together options
- var save_options = _write_concern || {};
- // Execute save
- collection.save(document, save_options, function(err, result) {
- if(typeof result == 'number' && result == 1) {
- return callback(null, document);
- }
-
- return callback(null, document);
- });
- },
-
- find: function(selector) {
- _selector = selector;
- return writeOptions;
- },
-
- //
- // Update is implicit multiple document update
- update: function(operations, callback) {
- // Merge together options
- var update_options = _write_concern || {};
-
- // Set up options, multi is default operation
- update_options.multi = _scope_options.multi ? _scope_options.multi : true;
- if(_scope_options.upsert) update_options.upsert = _scope_options.upsert;
-
- // Execute options
- collection.update(_selector, operations, update_options, function(err, result, obj) {
- callback(err, obj);
- });
- },
- }
-
- // Set write concern
- this.withWriteConcern = function(write_concern) {
- // Save the current write concern to the Scope
- _scope_options.write_concern = write_concern;
- _write_concern = write_concern;
- // Only allow legal options
- return writeOptions;
- }
-
- // Start find
- this.find = function(selector, options) {
- // Save the current selector
- _selector = selector;
- // Set the cursor
- _cursor.selector = selector;
- // Return only legal read options
- return Cursor.cloneWithOptions(_cursor, _scope_options);
- }
-}
-
-exports.Scope = Scope;
diff --git a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/utils.js b/node_modules/mongojs/node_modules/mongodb/lib/mongodb/utils.js
deleted file mode 100644
index f7da514..0000000
--- a/node_modules/mongojs/node_modules/mongodb/lib/mongodb/utils.js
+++ /dev/null
@@ -1,286 +0,0 @@
-var timers = require('timers');
-
-/**
- * Sort functions, Normalize and prepare sort parameters
- */
-var formatSortValue = exports.formatSortValue = function(sortDirection) {
- var value = ("" + sortDirection).toLowerCase();
-
- switch (value) {
- case 'ascending':
- case 'asc':
- case '1':
- return 1;
- case 'descending':
- case 'desc':
- case '-1':
- return -1;
- default:
- throw new Error("Illegal sort clause, must be of the form "
- + "[['field1', '(ascending|descending)'], "
- + "['field2', '(ascending|descending)']]");
- }
-};
-
-var formattedOrderClause = exports.formattedOrderClause = function(sortValue) {
- var orderBy = {};
- if(sortValue == null) return null;
- if (Array.isArray(sortValue)) {
- if(sortValue.length === 0) {
- return null;
- }
-
- 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(sortValue != null && typeof sortValue == 'object') {
- orderBy = sortValue;
- } else if (typeof sortValue == 'string') {
- orderBy[sortValue] = 1;
- } else {
- throw new Error("Illegal sort clause, must be of the form " +
- "[['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]");
- }
-
- return orderBy;
-};
-
-exports.encodeInt = function(value) {
- var buffer = new Buffer(4);
- buffer[3] = (value >> 24) & 0xff;
- buffer[2] = (value >> 16) & 0xff;
- buffer[1] = (value >> 8) & 0xff;
- buffer[0] = value & 0xff;
- return buffer;
-}
-
-exports.encodeIntInPlace = function(value, buffer, index) {
- buffer[index + 3] = (value >> 24) & 0xff;
- buffer[index + 2] = (value >> 16) & 0xff;
- buffer[index + 1] = (value >> 8) & 0xff;
- buffer[index] = value & 0xff;
-}
-
-exports.encodeCString = function(string) {
- var buf = new Buffer(string, 'utf8');
- return [buf, new Buffer([0])];
-}
-
-exports.decodeUInt32 = function(array, index) {
- return array[index] | array[index + 1] << 8 | array[index + 2] << 16 | array[index + 3] << 24;
-}
-
-// Decode the int
-exports.decodeUInt8 = function(array, index) {
- return array[index];
-}
-
-/**
- * Context insensitive type checks
- */
-
-var toString = Object.prototype.toString;
-
-var isObject = exports.isObject = function (arg) {
- return '[object Object]' == toString.call(arg)
-}
-
-exports.isArray = function (arg) {
- return Array.isArray(arg) ||
- 'object' == typeof arg && '[object Array]' == toString.call(arg)
-}
-
-exports.isDate = function (arg) {
- return 'object' == typeof arg && '[object Date]' == toString.call(arg)
-}
-
-exports.isRegExp = function (arg) {
- return 'object' == typeof arg && '[object RegExp]' == toString.call(arg)
-}
-
-/**
- * Wrap a Mongo error document in an Error instance
- * @ignore
- * @api private
- */
-var toError = function(error) {
- if (error instanceof Error) return error;
-
- var msg = error.err || error.errmsg || error.errMessage || error;
- var e = new Error(msg);
- e.name = 'MongoError';
-
- // Get all object keys
- var keys = typeof error == 'object'
- ? Object.keys(error)
- : [];
-
- for(var i = 0; i < keys.length; i++) {
- e[keys[i]] = error[keys[i]];
- }
-
- return e;
-}
-exports.toError = toError;
-
-/**
- * Convert a single level object to an array
- * @ignore
- * @api private
- */
-exports.objectToArray = function(object) {
- var list = [];
-
- for(var name in object) {
- list.push(object[name])
- }
-
- return list;
-}
-
-/**
- * Handle single command document return
- * @ignore
- * @api private
- */
-exports.handleSingleCommandResultReturn = function(override_value_true, override_value_false, callback) {
- return function(err, result, connection) {
- if(callback == null) return;
- if(err && typeof callback == 'function') return callback(err, null);
- if(!result || !result.documents || result.documents.length == 0)
- if(typeof callback == 'function') return callback(toError("command failed to return results"), null)
- if(result && result.documents[0].ok == 1) {
- if(override_value_true) return callback(null, override_value_true)
- if(typeof callback == 'function') return callback(null, result.documents[0]);
- }
-
- // Return the error from the document
- if(typeof callback == 'function') return callback(toError(result.documents[0]), override_value_false);
- }
-}
-
-/**
- * Return correct processor
- * @ignore
- * @api private
- */
-exports.processor = function() {
- // Set processor, setImmediate if 0.10 otherwise nextTick
- process.maxTickDepth = Infinity;
- // Only use nextTick
- return process.nextTick;
-}
-
-/**
- * Allow setting the socketTimeoutMS on all connections
- * to work around issues such as secondaries blocking due to compaction
- *
- * @ignore
- * @api private
- */
-exports.setSocketTimeoutProperty = function(self, options) {
- Object.defineProperty(self, "socketTimeoutMS", {
- enumerable: true
- , get: function () { return options.socketTimeoutMS; }
- , set: function (value) {
- // Set the socket timeoutMS value
- options.socketTimeoutMS = value;
-
- // Get all the connections
- var connections = self.allRawConnections();
- for(var i = 0; i < connections.length; i++) {
- connections[i].socketTimeoutMS = value;
- }
- }
- });
-}
-
-/**
- * Determine if the server supports write commands
- *
- * @ignore
- * @api private
- */
-exports.hasWriteCommands = function(connection) {
- return connection != null && connection.serverCapabilities != null && connection.serverCapabilities.hasWriteCommands;
-}
-
-/**
- * Fetch server capabilities
- *
- * @ignore
- * @api private
- */
-exports.serverCapabilities = function(connection) {
- return connection != null && connection.serverCapabilities != null && connection.serverCapabilities.hasWriteCommands;
-}
-
-/**
- * Create index name based on field spec
- *
- * @ignore
- * @api private
- */
-exports.parseIndexOptions = function(fieldOrSpec) {
- var fieldHash = {};
- var indexes = [];
- var keys;
-
- // Get all the fields accordingly
- if('string' == typeof fieldOrSpec) {
- // 'type'
- indexes.push(fieldOrSpec + '_' + 1);
- fieldHash[fieldOrSpec] = 1;
- } else if(Array.isArray(fieldOrSpec)) {
- fieldOrSpec.forEach(function(f) {
- if('string' == typeof f) {
- // [{location:'2d'}, 'type']
- indexes.push(f + '_' + 1);
- fieldHash[f] = 1;
- } else if(Array.isArray(f)) {
- // [['location', '2d'],['type', 1]]
- indexes.push(f[0] + '_' + (f[1] || 1));
- fieldHash[f[0]] = f[1] || 1;
- } else if(isObject(f)) {
- // [{location:'2d'}, {type:1}]
- keys = Object.keys(f);
- keys.forEach(function(k) {
- indexes.push(k + '_' + f[k]);
- fieldHash[k] = f[k];
- });
- } else {
- // undefined (ignore)
- }
- });
- } else if(isObject(fieldOrSpec)) {
- // {location:'2d', type:1}
- keys = Object.keys(fieldOrSpec);
- keys.forEach(function(key) {
- indexes.push(key + '_' + fieldOrSpec[key]);
- fieldHash[key] = fieldOrSpec[key];
- });
- }
-
- return {
- name: indexes.join("_"), keys: keys, fieldHash: fieldHash
- }
-}
-
-exports.decorateCommand = function(command, options, exclude) {
- for(var name in options) {
- if(exclude[name] == null) command[name] = options[name];
- }
-
- return command;
-}
-
-exports.shallowObjectCopy = function(object) {
- var c = {};
- for(var n in object) c[n] = object[n];
- return c;
-}
-
diff --git a/node_modules/mongojs/node_modules/mongodb/node_modules/bson/.travis.yml b/node_modules/mongojs/node_modules/mongodb/node_modules/bson/.travis.yml
deleted file mode 100644
index 471ed72..0000000
--- a/node_modules/mongojs/node_modules/mongodb/node_modules/bson/.travis.yml
+++ /dev/null
@@ -1,4 +0,0 @@
-language: node_js
-node_js:
- - 0.10 # development version of 0.8, may be unstable
- - 0.11
\ No newline at end of file
diff --git a/node_modules/mongojs/node_modules/mongodb/node_modules/bson/HISTORY b/node_modules/mongojs/node_modules/mongodb/node_modules/bson/HISTORY
deleted file mode 100644
index e16d940..0000000
--- a/node_modules/mongojs/node_modules/mongodb/node_modules/bson/HISTORY
+++ /dev/null
@@ -1,22 +0,0 @@
-0.2.18 2014-01-20
------------------
-- Updated Nan to 1.5.1 to support io.js
-
-0.2.16 2014-12-17
------------------
-- Made pid cycle on 0xffff to avoid weird overflows on creation of ObjectID's
-
-0.2.12 2014-08-24
------------------
-- Fixes for fortify review of c++ extension
-- toBSON correctly allows returns of non objects
-
-0.2.3 2013-10-01
-----------------
-- Drying of ObjectId code for generation of id (Issue #54, https://github.com/moredip)
-- Fixed issue where corrupt CString's could cause endless loop
-- Support for Node 0.11.X > (Issue #49, https://github.com/kkoopa)
-
-0.1.4 2012-09-25
-----------------
-- Added precompiled c++ native extensions for win32 ia32 and x64
\ No newline at end of file
diff --git a/node_modules/mongojs/node_modules/mongodb/node_modules/bson/LICENSE b/node_modules/mongojs/node_modules/mongodb/node_modules/bson/LICENSE
deleted file mode 100644
index 261eeb9..0000000
--- a/node_modules/mongojs/node_modules/mongodb/node_modules/bson/LICENSE
+++ /dev/null
@@ -1,201 +0,0 @@
- Apache License
- Version 2.0, January 2004
- http://www.apache.org/licenses/
-
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
- 1. Definitions.
-
- "License" shall mean the terms and conditions for use, reproduction,
- and distribution as defined by Sections 1 through 9 of this document.
-
- "Licensor" shall mean the copyright owner or entity authorized by
- the copyright owner that is granting the License.
-
- "Legal Entity" shall mean the union of the acting entity and all
- other entities that control, are controlled by, or are under common
- control with that entity. For the purposes of this definition,
- "control" means (i) the power, direct or indirect, to cause the
- direction or management of such entity, whether by contract or
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
- outstanding shares, or (iii) beneficial ownership of such entity.
-
- "You" (or "Your") shall mean an individual or Legal Entity
- exercising permissions granted by this License.
-
- "Source" form shall mean the preferred form for making modifications,
- including but not limited to software source code, documentation
- source, and configuration files.
-
- "Object" form shall mean any form resulting from mechanical
- transformation or translation of a Source form, including but
- not limited to compiled object code, generated documentation,
- and conversions to other media types.
-
- "Work" shall mean the work of authorship, whether in Source or
- Object form, made available under the License, as indicated by a
- copyright notice that is included in or attached to the work
- (an example is provided in the Appendix below).
-
- "Derivative Works" shall mean any work, whether in Source or Object
- form, that is based on (or derived from) the Work and for which the
- editorial revisions, annotations, elaborations, or other modifications
- represent, as a whole, an original work of authorship. For the purposes
- of this License, Derivative Works shall not include works that remain
- separable from, or merely link (or bind by name) to the interfaces of,
- the Work and Derivative Works thereof.
-
- "Contribution" shall mean any work of authorship, including
- the original version of the Work and any modifications or additions
- to that Work or Derivative Works thereof, that is intentionally
- submitted to Licensor for inclusion in the Work by the copyright owner
- or by an individual or Legal Entity authorized to submit on behalf of
- the copyright owner. For the purposes of this definition, "submitted"
- means any form of electronic, verbal, or written communication sent
- to the Licensor or its representatives, including but not limited to
- communication on electronic mailing lists, source code control systems,
- and issue tracking systems that are managed by, or on behalf of, the
- Licensor for the purpose of discussing and improving the Work, but
- excluding communication that is conspicuously marked or otherwise
- designated in writing by the copyright owner as "Not a Contribution."
-
- "Contributor" shall mean Licensor and any individual or Legal Entity
- on behalf of whom a Contribution has been received by Licensor and
- subsequently incorporated within the Work.
-
- 2. Grant of Copyright License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- copyright license to reproduce, prepare Derivative Works of,
- publicly display, publicly perform, sublicense, and distribute the
- Work and such Derivative Works in Source or Object form.
-
- 3. Grant of Patent License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- (except as stated in this section) patent license to make, have made,
- use, offer to sell, sell, import, and otherwise transfer the Work,
- where such license applies only to those patent claims licensable
- by such Contributor that are necessarily infringed by their
- Contribution(s) alone or by combination of their Contribution(s)
- with the Work to which such Contribution(s) was submitted. If You
- institute patent litigation against any entity (including a
- cross-claim or counterclaim in a lawsuit) alleging that the Work
- or a Contribution incorporated within the Work constitutes direct
- or contributory patent infringement, then any patent licenses
- granted to You under this License for that Work shall terminate
- as of the date such litigation is filed.
-
- 4. Redistribution. You may reproduce and distribute copies of the
- Work or Derivative Works thereof in any medium, with or without
- modifications, and in Source or Object form, provided that You
- meet the following conditions:
-
- (a) You must give any other recipients of the Work or
- Derivative Works a copy of this License; and
-
- (b) You must cause any modified files to carry prominent notices
- stating that You changed the files; and
-
- (c) You must retain, in the Source form of any Derivative Works
- that You distribute, all copyright, patent, trademark, and
- attribution notices from the Source form of the Work,
- excluding those notices that do not pertain to any part of
- the Derivative Works; and
-
- (d) If the Work includes a "NOTICE" text file as part of its
- distribution, then any Derivative Works that You distribute must
- include a readable copy of the attribution notices contained
- within such NOTICE file, excluding those notices that do not
- pertain to any part of the Derivative Works, in at least one
- of the following places: within a NOTICE text file distributed
- as part of the Derivative Works; within the Source form or
- documentation, if provided along with the Derivative Works; or,
- within a display generated by the Derivative Works, if and
- wherever such third-party notices normally appear. The contents
- of the NOTICE file are for informational purposes only and
- do not modify the License. You may add Your own attribution
- notices within Derivative Works that You distribute, alongside
- or as an addendum to the NOTICE text from the Work, provided
- that such additional attribution notices cannot be construed
- as modifying the License.
-
- You may add Your own copyright statement to Your modifications and
- may provide additional or different license terms and conditions
- for use, reproduction, or distribution of Your modifications, or
- for any such Derivative Works as a whole, provided Your use,
- reproduction, and distribution of the Work otherwise complies with
- the conditions stated in this License.
-
- 5. Submission of Contributions. Unless You explicitly state otherwise,
- any Contribution intentionally submitted for inclusion in the Work
- by You to the Licensor shall be under the terms and conditions of
- this License, without any additional terms or conditions.
- Notwithstanding the above, nothing herein shall supersede or modify
- the terms of any separate license agreement you may have executed
- with Licensor regarding such Contributions.
-
- 6. Trademarks. This License does not grant permission to use the trade
- names, trademarks, service marks, or product names of the Licensor,
- except as required for reasonable and customary use in describing the
- origin of the Work and reproducing the content of the NOTICE file.
-
- 7. Disclaimer of Warranty. Unless required by applicable law or
- agreed to in writing, Licensor provides the Work (and each
- Contributor provides its Contributions) on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied, including, without limitation, any warranties or conditions
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
- PARTICULAR PURPOSE. You are solely responsible for determining the
- appropriateness of using or redistributing the Work and assume any
- risks associated with Your exercise of permissions under this License.
-
- 8. Limitation of Liability. In no event and under no legal theory,
- whether in tort (including negligence), contract, or otherwise,
- unless required by applicable law (such as deliberate and grossly
- negligent acts) or agreed to in writing, shall any Contributor be
- liable to You for damages, including any direct, indirect, special,
- incidental, or consequential damages of any character arising as a
- result of this License or out of the use or inability to use the
- Work (including but not limited to damages for loss of goodwill,
- work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses), even if such Contributor
- has been advised of the possibility of such damages.
-
- 9. Accepting Warranty or Additional Liability. While redistributing
- the Work or Derivative Works thereof, You may choose to offer,
- and charge a fee for, acceptance of support, warranty, indemnity,
- or other liability obligations and/or rights consistent with this
- License. However, in accepting such obligations, You may act only
- on Your own behalf and on Your sole responsibility, not on behalf
- of any other Contributor, and only if You agree to indemnify,
- defend, and hold each Contributor harmless for any liability
- incurred by, or claims asserted against, such Contributor by reason
- of your accepting any such warranty or additional liability.
-
- END OF TERMS AND CONDITIONS
-
- APPENDIX: How to apply the Apache License to your work.
-
- To apply the Apache License to your work, attach the following
- boilerplate notice, with the fields enclosed by brackets "[]"
- replaced with your own identifying information. (Don't include
- the brackets!) The text should be enclosed in the appropriate
- comment syntax for the file format. We also recommend that a
- file or class name and description of purpose be included on the
- same "printed page" as the copyright notice for easier
- identification within third-party archives.
-
- Copyright [yyyy] [name of copyright owner]
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
diff --git a/node_modules/mongojs/node_modules/mongodb/node_modules/bson/Makefile b/node_modules/mongojs/node_modules/mongodb/node_modules/bson/Makefile
deleted file mode 100644
index 77ce4e0..0000000
--- a/node_modules/mongojs/node_modules/mongodb/node_modules/bson/Makefile
+++ /dev/null
@@ -1,19 +0,0 @@
-NODE = node
-NPM = npm
-NODEUNIT = node_modules/nodeunit/bin/nodeunit
-
-all: clean node_gyp
-
-test: clean node_gyp
- npm test
-
-node_gyp: clean
- node-gyp configure build
-
-clean:
- node-gyp clean
-
-browserify:
- node_modules/.bin/onejs build browser_build/package.json browser_build/bson.js
-
-.PHONY: all
diff --git a/node_modules/mongojs/node_modules/mongodb/node_modules/bson/README.md b/node_modules/mongojs/node_modules/mongodb/node_modules/bson/README.md
deleted file mode 100644
index 5cac5b9..0000000
--- a/node_modules/mongojs/node_modules/mongodb/node_modules/bson/README.md
+++ /dev/null
@@ -1,69 +0,0 @@
-Javascript + C++ BSON parser
-============================
-
-This BSON parser is primarily meant to be used with the `mongodb` node.js driver.
-However, wonderful tools such as `onejs` can package up a BSON parser that will work in the browser.
-The current build is located in the `browser_build/bson.js` file.
-
-A simple example of how to use BSON in the browser:
-
-```html
-
-
-
-
-
-
-
-
-```
-
-A simple example of how to use BSON in `node.js`:
-
-```javascript
-var bson = require("bson");
-var BSON = bson.BSONPure.BSON;
-var Long = bson.BSONPure.Long;
-
-var doc = {long: Long.fromNumber(100)}
-
-// Serialize a document
-var data = BSON.serialize(doc, false, true, false);
-console.log("data:", data);
-
-// Deserialize the resulting Buffer
-var doc_2 = BSON.deserialize(data);
-console.log("doc_2:", doc_2);
-```
-
-The API consists of two simple methods to serialize/deserialize objects to/from BSON format:
-
- * BSON.serialize(object, checkKeys, asBuffer, serializeFunctions)
- * @param {Object} object the Javascript object to serialize.
- * @param {Boolean} checkKeys the serializer will check if keys are valid.
- * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**.
- * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**
- * @return {TypedArray/Array} returns a TypedArray or Array depending on what your browser supports
-
- * BSON.deserialize(buffer, options, isArray)
- * Options
- * **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized.
- * **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse.
- * **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function.
- * @param {TypedArray/Array} a TypedArray/Array containing the BSON data
- * @param {Object} [options] additional options used for the deserialization.
- * @param {Boolean} [isArray] ignore used for recursive parsing.
- * @return {Object} returns the deserialized Javascript Object.
diff --git a/node_modules/mongojs/node_modules/mongodb/node_modules/bson/binding.gyp b/node_modules/mongojs/node_modules/mongodb/node_modules/bson/binding.gyp
deleted file mode 100644
index c4455e7..0000000
--- a/node_modules/mongojs/node_modules/mongodb/node_modules/bson/binding.gyp
+++ /dev/null
@@ -1,18 +0,0 @@
-{
- 'targets': [
- {
- 'target_name': 'bson',
- 'sources': [ 'ext/bson.cc' ],
- 'cflags!': [ '-fno-exceptions' ],
- 'cflags_cc!': [ '-fno-exceptions' ],
- 'include_dirs': [ '0){
- id = pkg.modules[i].id;
-
- if(id==moduleId || id == moduleIndexId){
- module = pkg.modules[i];
- break;
- }
- }
-
- return module;
-}
-
-function newRequire(callingModule){
- function require(uri){
- var module, pkg;
-
- if(/^\./.test(uri)){
- module = findModule(callingModule, uri);
- } else if ( ties && ties.hasOwnProperty( uri ) ) {
- return ties[uri];
- } else if ( aliases && aliases.hasOwnProperty( uri ) ) {
- return require(aliases[uri]);
- } else {
- pkg = pkgmap[uri];
-
- if(!pkg && nativeRequire){
- try {
- pkg = nativeRequire(uri);
- } catch (nativeRequireError) {}
-
- if(pkg) return pkg;
- }
-
- if(!pkg){
- throw new Error('Cannot find module "'+uri+'" @[module: '+callingModule.id+' package: '+callingModule.pkg.name+']');
- }
-
- module = pkg.index;
- }
-
- if(!module){
- throw new Error('Cannot find module "'+uri+'" @[module: '+callingModule.id+' package: '+callingModule.pkg.name+']');
- }
-
- module.parent = callingModule;
- return module.call();
- };
-
-
- return require;
-}
-
-
-function module(parent, id, wrapper){
- var mod = { pkg: parent, id: id, wrapper: wrapper },
- cached = false;
-
- mod.exports = {};
- mod.require = newRequire(mod);
-
- mod.call = function(){
- if(cached) {
- return mod.exports;
- }
-
- cached = true;
-
- global.require = mod.require;
-
- mod.wrapper(mod, mod.exports, global, global.require);
- return mod.exports;
- };
-
- if(parent.mainModuleId == mod.id){
- parent.index = mod;
- parent.parents.length === 0 && ( main = mod.call );
- }
-
- parent.modules.push(mod);
-}
-
-function pkg(/* [ parentId ...], wrapper */){
- var wrapper = arguments[ arguments.length - 1 ],
- parents = Array.prototype.slice.call(arguments, 0, arguments.length - 1),
- ctx = wrapper(parents);
-
-
- pkgmap[ctx.name] = ctx;
-
- arguments.length == 1 && ( pkgmap.main = ctx );
-
- return function(modules){
- var id;
- for(id in modules){
- module(ctx, id, modules[id]);
- }
- };
-}
-
-
-}(this));
-
-bson.pkg(function(parents){
-
- return {
- 'name' : 'bson',
- 'mainModuleId' : 'bson',
- 'modules' : [],
- 'parents' : parents
- };
-
-})({ 'binary': function(module, exports, global, require, undefined){
- /**
- * Module dependencies.
- */
-if(typeof window === 'undefined') {
- var Buffer = require('buffer').Buffer; // TODO just use global Buffer
-}
-
-// Binary default subtype
-var BSON_BINARY_SUBTYPE_DEFAULT = 0;
-
-/**
- * @ignore
- * @api private
- */
-var writeStringToArray = function(data) {
- // Create a buffer
- var buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(data.length)) : new Array(data.length);
- // Write the content to the buffer
- for(var i = 0; i < data.length; i++) {
- buffer[i] = data.charCodeAt(i);
- }
- // Write the string to the buffer
- return buffer;
-}
-
-/**
- * Convert Array ot Uint8Array to Binary String
- *
- * @ignore
- * @api private
- */
-var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) {
- var result = "";
- for(var i = startIndex; i < endIndex; i++) {
- result = result + String.fromCharCode(byteArray[i]);
- }
- return result;
-};
-
-/**
- * A class representation of the BSON Binary type.
- *
- * Sub types
- * - **BSON.BSON_BINARY_SUBTYPE_DEFAULT**, default BSON type.
- * - **BSON.BSON_BINARY_SUBTYPE_FUNCTION**, BSON function type.
- * - **BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY**, BSON byte array type.
- * - **BSON.BSON_BINARY_SUBTYPE_UUID**, BSON uuid type.
- * - **BSON.BSON_BINARY_SUBTYPE_MD5**, BSON md5 type.
- * - **BSON.BSON_BINARY_SUBTYPE_USER_DEFINED**, BSON user defined type.
- *
- * @class Represents the Binary BSON type.
- * @param {Buffer} buffer a buffer object containing the binary data.
- * @param {Number} [subType] the option binary type.
- * @return {Grid}
- */
-function Binary(buffer, subType) {
- if(!(this instanceof Binary)) return new Binary(buffer, subType);
-
- this._bsontype = 'Binary';
-
- if(buffer instanceof Number) {
- this.sub_type = buffer;
- this.position = 0;
- } else {
- this.sub_type = subType == null ? BSON_BINARY_SUBTYPE_DEFAULT : subType;
- this.position = 0;
- }
-
- if(buffer != null && !(buffer instanceof Number)) {
- // Only accept Buffer, Uint8Array or Arrays
- if(typeof buffer == 'string') {
- // Different ways of writing the length of the string for the different types
- if(typeof Buffer != 'undefined') {
- this.buffer = new Buffer(buffer);
- } else if(typeof Uint8Array != 'undefined' || (Object.prototype.toString.call(buffer) == '[object Array]')) {
- this.buffer = writeStringToArray(buffer);
- } else {
- throw new Error("only String, Buffer, Uint8Array or Array accepted");
- }
- } else {
- this.buffer = buffer;
- }
- this.position = buffer.length;
- } else {
- if(typeof Buffer != 'undefined') {
- this.buffer = new Buffer(Binary.BUFFER_SIZE);
- } else if(typeof Uint8Array != 'undefined'){
- this.buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE));
- } else {
- this.buffer = new Array(Binary.BUFFER_SIZE);
- }
- // Set position to start of buffer
- this.position = 0;
- }
-};
-
-/**
- * Updates this binary with byte_value.
- *
- * @param {Character} byte_value a single byte we wish to write.
- * @api public
- */
-Binary.prototype.put = function put(byte_value) {
- // If it's a string and a has more than one character throw an error
- if(byte_value['length'] != null && typeof byte_value != 'number' && byte_value.length != 1) throw new Error("only accepts single character String, Uint8Array or Array");
- if(typeof byte_value != 'number' && byte_value < 0 || byte_value > 255) throw new Error("only accepts number in a valid unsigned byte range 0-255");
-
- // Decode the byte value once
- var decoded_byte = null;
- if(typeof byte_value == 'string') {
- decoded_byte = byte_value.charCodeAt(0);
- } else if(byte_value['length'] != null) {
- decoded_byte = byte_value[0];
- } else {
- decoded_byte = byte_value;
- }
-
- if(this.buffer.length > this.position) {
- this.buffer[this.position++] = decoded_byte;
- } else {
- if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) {
- // Create additional overflow buffer
- var buffer = new Buffer(Binary.BUFFER_SIZE + this.buffer.length);
- // Combine the two buffers together
- this.buffer.copy(buffer, 0, 0, this.buffer.length);
- this.buffer = buffer;
- this.buffer[this.position++] = decoded_byte;
- } else {
- var buffer = null;
- // Create a new buffer (typed or normal array)
- if(Object.prototype.toString.call(this.buffer) == '[object Uint8Array]') {
- buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE + this.buffer.length));
- } else {
- buffer = new Array(Binary.BUFFER_SIZE + this.buffer.length);
- }
-
- // We need to copy all the content to the new array
- for(var i = 0; i < this.buffer.length; i++) {
- buffer[i] = this.buffer[i];
- }
-
- // Reassign the buffer
- this.buffer = buffer;
- // Write the byte
- this.buffer[this.position++] = decoded_byte;
- }
- }
-};
-
-/**
- * Writes a buffer or string to the binary.
- *
- * @param {Buffer|String} string a string or buffer to be written to the Binary BSON object.
- * @param {Number} offset specify the binary of where to write the content.
- * @api public
- */
-Binary.prototype.write = function write(string, offset) {
- offset = typeof offset == 'number' ? offset : this.position;
-
- // If the buffer is to small let's extend the buffer
- if(this.buffer.length < offset + string.length) {
- var buffer = null;
- // If we are in node.js
- if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) {
- buffer = new Buffer(this.buffer.length + string.length);
- this.buffer.copy(buffer, 0, 0, this.buffer.length);
- } else if(Object.prototype.toString.call(this.buffer) == '[object Uint8Array]') {
- // Create a new buffer
- buffer = new Uint8Array(new ArrayBuffer(this.buffer.length + string.length))
- // Copy the content
- for(var i = 0; i < this.position; i++) {
- buffer[i] = this.buffer[i];
- }
- }
-
- // Assign the new buffer
- this.buffer = buffer;
- }
-
- if(typeof Buffer != 'undefined' && Buffer.isBuffer(string) && Buffer.isBuffer(this.buffer)) {
- string.copy(this.buffer, offset, 0, string.length);
- this.position = (offset + string.length) > this.position ? (offset + string.length) : this.position;
- // offset = string.length
- } else if(typeof Buffer != 'undefined' && typeof string == 'string' && Buffer.isBuffer(this.buffer)) {
- this.buffer.write(string, 'binary', offset);
- this.position = (offset + string.length) > this.position ? (offset + string.length) : this.position;
- // offset = string.length;
- } else if(Object.prototype.toString.call(string) == '[object Uint8Array]'
- || Object.prototype.toString.call(string) == '[object Array]' && typeof string != 'string') {
- for(var i = 0; i < string.length; i++) {
- this.buffer[offset++] = string[i];
- }
-
- this.position = offset > this.position ? offset : this.position;
- } else if(typeof string == 'string') {
- for(var i = 0; i < string.length; i++) {
- this.buffer[offset++] = string.charCodeAt(i);
- }
-
- this.position = offset > this.position ? offset : this.position;
- }
-};
-
-/**
- * Reads **length** bytes starting at **position**.
- *
- * @param {Number} position read from the given position in the Binary.
- * @param {Number} length the number of bytes to read.
- * @return {Buffer}
- * @api public
- */
-Binary.prototype.read = function read(position, length) {
- length = length && length > 0
- ? length
- : this.position;
-
- // Let's return the data based on the type we have
- if(this.buffer['slice']) {
- return this.buffer.slice(position, position + length);
- } else {
- // Create a buffer to keep the result
- var buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(length)) : new Array(length);
- for(var i = 0; i < length; i++) {
- buffer[i] = this.buffer[position++];
- }
- }
- // Return the buffer
- return buffer;
-};
-
-/**
- * Returns the value of this binary as a string.
- *
- * @return {String}
- * @api public
- */
-Binary.prototype.value = function value(asRaw) {
- asRaw = asRaw == null ? false : asRaw;
-
- // If it's a node.js buffer object
- if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) {
- return asRaw ? this.buffer.slice(0, this.position) : this.buffer.toString('binary', 0, this.position);
- } else {
- if(asRaw) {
- // we support the slice command use it
- if(this.buffer['slice'] != null) {
- return this.buffer.slice(0, this.position);
- } else {
- // Create a new buffer to copy content to
- var newBuffer = Object.prototype.toString.call(this.buffer) == '[object Uint8Array]' ? new Uint8Array(new ArrayBuffer(this.position)) : new Array(this.position);
- // Copy content
- for(var i = 0; i < this.position; i++) {
- newBuffer[i] = this.buffer[i];
- }
- // Return the buffer
- return newBuffer;
- }
- } else {
- return convertArraytoUtf8BinaryString(this.buffer, 0, this.position);
- }
- }
-};
-
-/**
- * Length.
- *
- * @return {Number} the length of the binary.
- * @api public
- */
-Binary.prototype.length = function length() {
- return this.position;
-};
-
-/**
- * @ignore
- * @api private
- */
-Binary.prototype.toJSON = function() {
- return this.buffer != null ? this.buffer.toString('base64') : '';
-}
-
-/**
- * @ignore
- * @api private
- */
-Binary.prototype.toString = function(format) {
- return this.buffer != null ? this.buffer.slice(0, this.position).toString(format) : '';
-}
-
-Binary.BUFFER_SIZE = 256;
-
-/**
- * Default BSON type
- *
- * @classconstant SUBTYPE_DEFAULT
- **/
-Binary.SUBTYPE_DEFAULT = 0;
-/**
- * Function BSON type
- *
- * @classconstant SUBTYPE_DEFAULT
- **/
-Binary.SUBTYPE_FUNCTION = 1;
-/**
- * Byte Array BSON type
- *
- * @classconstant SUBTYPE_DEFAULT
- **/
-Binary.SUBTYPE_BYTE_ARRAY = 2;
-/**
- * OLD UUID BSON type
- *
- * @classconstant SUBTYPE_DEFAULT
- **/
-Binary.SUBTYPE_UUID_OLD = 3;
-/**
- * UUID BSON type
- *
- * @classconstant SUBTYPE_DEFAULT
- **/
-Binary.SUBTYPE_UUID = 4;
-/**
- * MD5 BSON type
- *
- * @classconstant SUBTYPE_DEFAULT
- **/
-Binary.SUBTYPE_MD5 = 5;
-/**
- * User BSON type
- *
- * @classconstant SUBTYPE_DEFAULT
- **/
-Binary.SUBTYPE_USER_DEFINED = 128;
-
-/**
- * Expose.
- */
-exports.Binary = Binary;
-
-
-},
-
-
-
-'binary_parser': function(module, exports, global, require, undefined){
- /**
- * Binary Parser.
- * Jonas Raoni Soares Silva
- * http://jsfromhell.com/classes/binary-parser [v1.0]
- */
-var chr = String.fromCharCode;
-
-var maxBits = [];
-for (var i = 0; i < 64; i++) {
- maxBits[i] = Math.pow(2, i);
-}
-
-function BinaryParser (bigEndian, allowExceptions) {
- if(!(this instanceof BinaryParser)) return new BinaryParser(bigEndian, allowExceptions);
-
- this.bigEndian = bigEndian;
- this.allowExceptions = allowExceptions;
-};
-
-BinaryParser.warn = function warn (msg) {
- if (this.allowExceptions) {
- throw new Error(msg);
- }
-
- return 1;
-};
-
-BinaryParser.decodeFloat = function decodeFloat (data, precisionBits, exponentBits) {
- var b = new this.Buffer(this.bigEndian, data);
-
- b.checkBuffer(precisionBits + exponentBits + 1);
-
- var bias = maxBits[exponentBits - 1] - 1
- , signal = b.readBits(precisionBits + exponentBits, 1)
- , exponent = b.readBits(precisionBits, exponentBits)
- , significand = 0
- , divisor = 2
- , curByte = b.buffer.length + (-precisionBits >> 3) - 1;
-
- do {
- for (var byteValue = b.buffer[ ++curByte ], startBit = precisionBits % 8 || 8, mask = 1 << startBit; mask >>= 1; ( byteValue & mask ) && ( significand += 1 / divisor ), divisor *= 2 );
- } while (precisionBits -= startBit);
-
- return exponent == ( bias << 1 ) + 1 ? significand ? NaN : signal ? -Infinity : +Infinity : ( 1 + signal * -2 ) * ( exponent || significand ? !exponent ? Math.pow( 2, -bias + 1 ) * significand : Math.pow( 2, exponent - bias ) * ( 1 + significand ) : 0 );
-};
-
-BinaryParser.decodeInt = function decodeInt (data, bits, signed, forceBigEndian) {
- var b = new this.Buffer(this.bigEndian || forceBigEndian, data)
- , x = b.readBits(0, bits)
- , max = maxBits[bits]; //max = Math.pow( 2, bits );
-
- return signed && x >= max / 2
- ? x - max
- : x;
-};
-
-BinaryParser.encodeFloat = function encodeFloat (data, precisionBits, exponentBits) {
- var bias = maxBits[exponentBits - 1] - 1
- , minExp = -bias + 1
- , maxExp = bias
- , minUnnormExp = minExp - precisionBits
- , n = parseFloat(data)
- , status = isNaN(n) || n == -Infinity || n == +Infinity ? n : 0
- , exp = 0
- , len = 2 * bias + 1 + precisionBits + 3
- , bin = new Array(len)
- , signal = (n = status !== 0 ? 0 : n) < 0
- , intPart = Math.floor(n = Math.abs(n))
- , floatPart = n - intPart
- , lastBit
- , rounded
- , result
- , i
- , j;
-
- for (i = len; i; bin[--i] = 0);
-
- for (i = bias + 2; intPart && i; bin[--i] = intPart % 2, intPart = Math.floor(intPart / 2));
-
- for (i = bias + 1; floatPart > 0 && i; (bin[++i] = ((floatPart *= 2) >= 1) - 0 ) && --floatPart);
-
- for (i = -1; ++i < len && !bin[i];);
-
- if (bin[(lastBit = precisionBits - 1 + (i = (exp = bias + 1 - i) >= minExp && exp <= maxExp ? i + 1 : bias + 1 - (exp = minExp - 1))) + 1]) {
- if (!(rounded = bin[lastBit])) {
- for (j = lastBit + 2; !rounded && j < len; rounded = bin[j++]);
- }
-
- for (j = lastBit + 1; rounded && --j >= 0; (bin[j] = !bin[j] - 0) && (rounded = 0));
- }
-
- for (i = i - 2 < 0 ? -1 : i - 3; ++i < len && !bin[i];);
-
- if ((exp = bias + 1 - i) >= minExp && exp <= maxExp) {
- ++i;
- } else if (exp < minExp) {
- exp != bias + 1 - len && exp < minUnnormExp && this.warn("encodeFloat::float underflow");
- i = bias + 1 - (exp = minExp - 1);
- }
-
- if (intPart || status !== 0) {
- this.warn(intPart ? "encodeFloat::float overflow" : "encodeFloat::" + status);
- exp = maxExp + 1;
- i = bias + 2;
-
- if (status == -Infinity) {
- signal = 1;
- } else if (isNaN(status)) {
- bin[i] = 1;
- }
- }
-
- for (n = Math.abs(exp + bias), j = exponentBits + 1, result = ""; --j; result = (n % 2) + result, n = n >>= 1);
-
- for (n = 0, j = 0, i = (result = (signal ? "1" : "0") + result + bin.slice(i, i + precisionBits).join("")).length, r = []; i; j = (j + 1) % 8) {
- n += (1 << j) * result.charAt(--i);
- if (j == 7) {
- r[r.length] = String.fromCharCode(n);
- n = 0;
- }
- }
-
- r[r.length] = n
- ? String.fromCharCode(n)
- : "";
-
- return (this.bigEndian ? r.reverse() : r).join("");
-};
-
-BinaryParser.encodeInt = function encodeInt (data, bits, signed, forceBigEndian) {
- var max = maxBits[bits];
-
- if (data >= max || data < -(max / 2)) {
- this.warn("encodeInt::overflow");
- data = 0;
- }
-
- if (data < 0) {
- data += max;
- }
-
- for (var r = []; data; r[r.length] = String.fromCharCode(data % 256), data = Math.floor(data / 256));
-
- for (bits = -(-bits >> 3) - r.length; bits--; r[r.length] = "\0");
-
- return ((this.bigEndian || forceBigEndian) ? r.reverse() : r).join("");
-};
-
-BinaryParser.toSmall = function( data ){ return this.decodeInt( data, 8, true ); };
-BinaryParser.fromSmall = function( data ){ return this.encodeInt( data, 8, true ); };
-BinaryParser.toByte = function( data ){ return this.decodeInt( data, 8, false ); };
-BinaryParser.fromByte = function( data ){ return this.encodeInt( data, 8, false ); };
-BinaryParser.toShort = function( data ){ return this.decodeInt( data, 16, true ); };
-BinaryParser.fromShort = function( data ){ return this.encodeInt( data, 16, true ); };
-BinaryParser.toWord = function( data ){ return this.decodeInt( data, 16, false ); };
-BinaryParser.fromWord = function( data ){ return this.encodeInt( data, 16, false ); };
-BinaryParser.toInt = function( data ){ return this.decodeInt( data, 32, true ); };
-BinaryParser.fromInt = function( data ){ return this.encodeInt( data, 32, true ); };
-BinaryParser.toLong = function( data ){ return this.decodeInt( data, 64, true ); };
-BinaryParser.fromLong = function( data ){ return this.encodeInt( data, 64, true ); };
-BinaryParser.toDWord = function( data ){ return this.decodeInt( data, 32, false ); };
-BinaryParser.fromDWord = function( data ){ return this.encodeInt( data, 32, false ); };
-BinaryParser.toQWord = function( data ){ return this.decodeInt( data, 64, true ); };
-BinaryParser.fromQWord = function( data ){ return this.encodeInt( data, 64, true ); };
-BinaryParser.toFloat = function( data ){ return this.decodeFloat( data, 23, 8 ); };
-BinaryParser.fromFloat = function( data ){ return this.encodeFloat( data, 23, 8 ); };
-BinaryParser.toDouble = function( data ){ return this.decodeFloat( data, 52, 11 ); };
-BinaryParser.fromDouble = function( data ){ return this.encodeFloat( data, 52, 11 ); };
-
-// Factor out the encode so it can be shared by add_header and push_int32
-BinaryParser.encode_int32 = function encode_int32 (number, asArray) {
- var a, b, c, d, unsigned;
- unsigned = (number < 0) ? (number + 0x100000000) : number;
- a = Math.floor(unsigned / 0xffffff);
- unsigned &= 0xffffff;
- b = Math.floor(unsigned / 0xffff);
- unsigned &= 0xffff;
- c = Math.floor(unsigned / 0xff);
- unsigned &= 0xff;
- d = Math.floor(unsigned);
- return asArray ? [chr(a), chr(b), chr(c), chr(d)] : chr(a) + chr(b) + chr(c) + chr(d);
-};
-
-BinaryParser.encode_int64 = function encode_int64 (number) {
- var a, b, c, d, e, f, g, h, unsigned;
- unsigned = (number < 0) ? (number + 0x10000000000000000) : number;
- a = Math.floor(unsigned / 0xffffffffffffff);
- unsigned &= 0xffffffffffffff;
- b = Math.floor(unsigned / 0xffffffffffff);
- unsigned &= 0xffffffffffff;
- c = Math.floor(unsigned / 0xffffffffff);
- unsigned &= 0xffffffffff;
- d = Math.floor(unsigned / 0xffffffff);
- unsigned &= 0xffffffff;
- e = Math.floor(unsigned / 0xffffff);
- unsigned &= 0xffffff;
- f = Math.floor(unsigned / 0xffff);
- unsigned &= 0xffff;
- g = Math.floor(unsigned / 0xff);
- unsigned &= 0xff;
- h = Math.floor(unsigned);
- return chr(a) + chr(b) + chr(c) + chr(d) + chr(e) + chr(f) + chr(g) + chr(h);
-};
-
-/**
- * UTF8 methods
- */
-
-// Take a raw binary string and return a utf8 string
-BinaryParser.decode_utf8 = function decode_utf8 (binaryStr) {
- var len = binaryStr.length
- , decoded = ''
- , i = 0
- , c = 0
- , c1 = 0
- , c2 = 0
- , c3;
-
- while (i < len) {
- c = binaryStr.charCodeAt(i);
- if (c < 128) {
- decoded += String.fromCharCode(c);
- i++;
- } else if ((c > 191) && (c < 224)) {
- c2 = binaryStr.charCodeAt(i+1);
- decoded += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
- i += 2;
- } else {
- c2 = binaryStr.charCodeAt(i+1);
- c3 = binaryStr.charCodeAt(i+2);
- decoded += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
- i += 3;
- }
- }
-
- return decoded;
-};
-
-// Encode a cstring
-BinaryParser.encode_cstring = function encode_cstring (s) {
- return unescape(encodeURIComponent(s)) + BinaryParser.fromByte(0);
-};
-
-// Take a utf8 string and return a binary string
-BinaryParser.encode_utf8 = function encode_utf8 (s) {
- var a = ""
- , c;
-
- for (var n = 0, len = s.length; n < len; n++) {
- c = s.charCodeAt(n);
-
- if (c < 128) {
- a += String.fromCharCode(c);
- } else if ((c > 127) && (c < 2048)) {
- a += String.fromCharCode((c>>6) | 192) ;
- a += String.fromCharCode((c&63) | 128);
- } else {
- a += String.fromCharCode((c>>12) | 224);
- a += String.fromCharCode(((c>>6) & 63) | 128);
- a += String.fromCharCode((c&63) | 128);
- }
- }
-
- return a;
-};
-
-BinaryParser.hprint = function hprint (s) {
- var number;
-
- for (var i = 0, len = s.length; i < len; i++) {
- if (s.charCodeAt(i) < 32) {
- number = s.charCodeAt(i) <= 15
- ? "0" + s.charCodeAt(i).toString(16)
- : s.charCodeAt(i).toString(16);
- process.stdout.write(number + " ")
- } else {
- number = s.charCodeAt(i) <= 15
- ? "0" + s.charCodeAt(i).toString(16)
- : s.charCodeAt(i).toString(16);
- process.stdout.write(number + " ")
- }
- }
-
- process.stdout.write("\n\n");
-};
-
-BinaryParser.ilprint = function hprint (s) {
- var number;
-
- for (var i = 0, len = s.length; i < len; i++) {
- if (s.charCodeAt(i) < 32) {
- number = s.charCodeAt(i) <= 15
- ? "0" + s.charCodeAt(i).toString(10)
- : s.charCodeAt(i).toString(10);
-
- require('util').debug(number+' : ');
- } else {
- number = s.charCodeAt(i) <= 15
- ? "0" + s.charCodeAt(i).toString(10)
- : s.charCodeAt(i).toString(10);
- require('util').debug(number+' : '+ s.charAt(i));
- }
- }
-};
-
-BinaryParser.hlprint = function hprint (s) {
- var number;
-
- for (var i = 0, len = s.length; i < len; i++) {
- if (s.charCodeAt(i) < 32) {
- number = s.charCodeAt(i) <= 15
- ? "0" + s.charCodeAt(i).toString(16)
- : s.charCodeAt(i).toString(16);
- require('util').debug(number+' : ');
- } else {
- number = s.charCodeAt(i) <= 15
- ? "0" + s.charCodeAt(i).toString(16)
- : s.charCodeAt(i).toString(16);
- require('util').debug(number+' : '+ s.charAt(i));
- }
- }
-};
-
-/**
- * BinaryParser buffer constructor.
- */
-function BinaryParserBuffer (bigEndian, buffer) {
- this.bigEndian = bigEndian || 0;
- this.buffer = [];
- this.setBuffer(buffer);
-};
-
-BinaryParserBuffer.prototype.setBuffer = function setBuffer (data) {
- var l, i, b;
-
- if (data) {
- i = l = data.length;
- b = this.buffer = new Array(l);
- for (; i; b[l - i] = data.charCodeAt(--i));
- this.bigEndian && b.reverse();
- }
-};
-
-BinaryParserBuffer.prototype.hasNeededBits = function hasNeededBits (neededBits) {
- return this.buffer.length >= -(-neededBits >> 3);
-};
-
-BinaryParserBuffer.prototype.checkBuffer = function checkBuffer (neededBits) {
- if (!this.hasNeededBits(neededBits)) {
- throw new Error("checkBuffer::missing bytes");
- }
-};
-
-BinaryParserBuffer.prototype.readBits = function readBits (start, length) {
- //shl fix: Henri Torgemane ~1996 (compressed by Jonas Raoni)
-
- function shl (a, b) {
- for (; b--; a = ((a %= 0x7fffffff + 1) & 0x40000000) == 0x40000000 ? a * 2 : (a - 0x40000000) * 2 + 0x7fffffff + 1);
- return a;
- }
-
- if (start < 0 || length <= 0) {
- return 0;
- }
-
- this.checkBuffer(start + length);
-
- var offsetLeft
- , offsetRight = start % 8
- , curByte = this.buffer.length - ( start >> 3 ) - 1
- , lastByte = this.buffer.length + ( -( start + length ) >> 3 )
- , diff = curByte - lastByte
- , sum = ((this.buffer[ curByte ] >> offsetRight) & ((1 << (diff ? 8 - offsetRight : length)) - 1)) + (diff && (offsetLeft = (start + length) % 8) ? (this.buffer[lastByte++] & ((1 << offsetLeft) - 1)) << (diff-- << 3) - offsetRight : 0);
-
- for(; diff; sum += shl(this.buffer[lastByte++], (diff-- << 3) - offsetRight));
-
- return sum;
-};
-
-/**
- * Expose.
- */
-BinaryParser.Buffer = BinaryParserBuffer;
-
-exports.BinaryParser = BinaryParser;
-
-},
-
-
-
-'bson': function(module, exports, global, require, undefined){
- var Long = require('./long').Long
- , Double = require('./double').Double
- , Timestamp = require('./timestamp').Timestamp
- , ObjectID = require('./objectid').ObjectID
- , Symbol = require('./symbol').Symbol
- , Code = require('./code').Code
- , MinKey = require('./min_key').MinKey
- , MaxKey = require('./max_key').MaxKey
- , DBRef = require('./db_ref').DBRef
- , Binary = require('./binary').Binary
- , BinaryParser = require('./binary_parser').BinaryParser
- , writeIEEE754 = require('./float_parser').writeIEEE754
- , readIEEE754 = require('./float_parser').readIEEE754
-
-// To ensure that 0.4 of node works correctly
-var isDate = function isDate(d) {
- return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]';
-}
-
-/**
- * Create a new BSON instance
- *
- * @class Represents the BSON Parser
- * @return {BSON} instance of BSON Parser.
- */
-function BSON () {};
-
-/**
- * @ignore
- * @api private
- */
-// BSON MAX VALUES
-BSON.BSON_INT32_MAX = 0x7FFFFFFF;
-BSON.BSON_INT32_MIN = -0x80000000;
-
-BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1;
-BSON.BSON_INT64_MIN = -Math.pow(2, 63);
-
-// JS MAX PRECISE VALUES
-BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double.
-BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double.
-
-// Internal long versions
-var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double.
-var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double.
-
-/**
- * Number BSON Type
- *
- * @classconstant BSON_DATA_NUMBER
- **/
-BSON.BSON_DATA_NUMBER = 1;
-/**
- * String BSON Type
- *
- * @classconstant BSON_DATA_STRING
- **/
-BSON.BSON_DATA_STRING = 2;
-/**
- * Object BSON Type
- *
- * @classconstant BSON_DATA_OBJECT
- **/
-BSON.BSON_DATA_OBJECT = 3;
-/**
- * Array BSON Type
- *
- * @classconstant BSON_DATA_ARRAY
- **/
-BSON.BSON_DATA_ARRAY = 4;
-/**
- * Binary BSON Type
- *
- * @classconstant BSON_DATA_BINARY
- **/
-BSON.BSON_DATA_BINARY = 5;
-/**
- * ObjectID BSON Type
- *
- * @classconstant BSON_DATA_OID
- **/
-BSON.BSON_DATA_OID = 7;
-/**
- * Boolean BSON Type
- *
- * @classconstant BSON_DATA_BOOLEAN
- **/
-BSON.BSON_DATA_BOOLEAN = 8;
-/**
- * Date BSON Type
- *
- * @classconstant BSON_DATA_DATE
- **/
-BSON.BSON_DATA_DATE = 9;
-/**
- * null BSON Type
- *
- * @classconstant BSON_DATA_NULL
- **/
-BSON.BSON_DATA_NULL = 10;
-/**
- * RegExp BSON Type
- *
- * @classconstant BSON_DATA_REGEXP
- **/
-BSON.BSON_DATA_REGEXP = 11;
-/**
- * Code BSON Type
- *
- * @classconstant BSON_DATA_CODE
- **/
-BSON.BSON_DATA_CODE = 13;
-/**
- * Symbol BSON Type
- *
- * @classconstant BSON_DATA_SYMBOL
- **/
-BSON.BSON_DATA_SYMBOL = 14;
-/**
- * Code with Scope BSON Type
- *
- * @classconstant BSON_DATA_CODE_W_SCOPE
- **/
-BSON.BSON_DATA_CODE_W_SCOPE = 15;
-/**
- * 32 bit Integer BSON Type
- *
- * @classconstant BSON_DATA_INT
- **/
-BSON.BSON_DATA_INT = 16;
-/**
- * Timestamp BSON Type
- *
- * @classconstant BSON_DATA_TIMESTAMP
- **/
-BSON.BSON_DATA_TIMESTAMP = 17;
-/**
- * Long BSON Type
- *
- * @classconstant BSON_DATA_LONG
- **/
-BSON.BSON_DATA_LONG = 18;
-/**
- * MinKey BSON Type
- *
- * @classconstant BSON_DATA_MIN_KEY
- **/
-BSON.BSON_DATA_MIN_KEY = 0xff;
-/**
- * MaxKey BSON Type
- *
- * @classconstant BSON_DATA_MAX_KEY
- **/
-BSON.BSON_DATA_MAX_KEY = 0x7f;
-
-/**
- * Binary Default Type
- *
- * @classconstant BSON_BINARY_SUBTYPE_DEFAULT
- **/
-BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0;
-/**
- * Binary Function Type
- *
- * @classconstant BSON_BINARY_SUBTYPE_FUNCTION
- **/
-BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1;
-/**
- * Binary Byte Array Type
- *
- * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY
- **/
-BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2;
-/**
- * Binary UUID Type
- *
- * @classconstant BSON_BINARY_SUBTYPE_UUID
- **/
-BSON.BSON_BINARY_SUBTYPE_UUID = 3;
-/**
- * Binary MD5 Type
- *
- * @classconstant BSON_BINARY_SUBTYPE_MD5
- **/
-BSON.BSON_BINARY_SUBTYPE_MD5 = 4;
-/**
- * Binary User Defined Type
- *
- * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED
- **/
-BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128;
-
-/**
- * Calculate the bson size for a passed in Javascript object.
- *
- * @param {Object} object the Javascript object to calculate the BSON byte size for.
- * @param {Boolean} [serializeFunctions] serialize all functions in the object **(default:false)**.
- * @return {Number} returns the number of bytes the BSON object will take up.
- * @api public
- */
-BSON.calculateObjectSize = function calculateObjectSize(object, serializeFunctions) {
- var totalLength = (4 + 1);
-
- if(Array.isArray(object)) {
- for(var i = 0; i < object.length; i++) {
- totalLength += calculateElement(i.toString(), object[i], serializeFunctions)
- }
- } else {
- // If we have toBSON defined, override the current object
- if(object.toBSON) {
- object = object.toBSON();
- }
-
- // Calculate size
- for(var key in object) {
- totalLength += calculateElement(key, object[key], serializeFunctions)
- }
- }
-
- return totalLength;
-}
-
-/**
- * @ignore
- * @api private
- */
-function calculateElement(name, value, serializeFunctions) {
- var isBuffer = typeof Buffer !== 'undefined';
-
- switch(typeof value) {
- case 'string':
- return 1 + (!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1 + 4 + (!isBuffer ? numberOfBytes(value) : Buffer.byteLength(value, 'utf8')) + 1;
- case 'number':
- if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) {
- if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { // 32 bit
- return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (4 + 1);
- } else {
- return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1);
- }
- } else { // 64 bit
- return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1);
- }
- case 'undefined':
- return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1);
- case 'boolean':
- return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1 + 1);
- case 'object':
- if(value == null || value instanceof MinKey || value instanceof MaxKey || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') {
- return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1);
- } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') {
- return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (12 + 1);
- } else if(value instanceof Date || isDate(value)) {
- return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1);
- } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) {
- return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1 + 4 + 1) + value.length;
- } else if(value instanceof Long || value instanceof Double || value instanceof Timestamp
- || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Double' || value['_bsontype'] == 'Timestamp') {
- return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1);
- } else if(value instanceof Code || value['_bsontype'] == 'Code') {
- // Calculate size depending on the availability of a scope
- if(value.scope != null && Object.keys(value.scope).length > 0) {
- return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + 4 + (!isBuffer ? numberOfBytes(value.code.toString()) : Buffer.byteLength(value.code.toString(), 'utf8')) + 1 + BSON.calculateObjectSize(value.scope, serializeFunctions);
- } else {
- return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + (!isBuffer ? numberOfBytes(value.code.toString()) : Buffer.byteLength(value.code.toString(), 'utf8')) + 1;
- }
- } else if(value instanceof Binary || value['_bsontype'] == 'Binary') {
- // Check what kind of subtype we have
- if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) {
- return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (value.position + 1 + 4 + 1 + 4);
- } else {
- return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (value.position + 1 + 4 + 1);
- }
- } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') {
- return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + ((!isBuffer ? numberOfBytes(value.value) : Buffer.byteLength(value.value, 'utf8')) + 4 + 1 + 1);
- } else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') {
- // Set up correct object for serialization
- var ordered_values = {
- '$ref': value.namespace
- , '$id' : value.oid
- };
-
- // Add db reference if it exists
- if(null != value.db) {
- ordered_values['$db'] = value.db;
- }
-
- return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + BSON.calculateObjectSize(ordered_values, serializeFunctions);
- } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') {
- return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + (!isBuffer ? numberOfBytes(value.source) : Buffer.byteLength(value.source, 'utf8')) + 1
- + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1
- } else {
- return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + BSON.calculateObjectSize(value, serializeFunctions) + 1;
- }
- case 'function':
- // WTF for 0.4.X where typeof /someregexp/ === 'function'
- if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') {
- return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + (!isBuffer ? numberOfBytes(value.source) : Buffer.byteLength(value.source, 'utf8')) + 1
- + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1
- } else {
- if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) {
- return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + 4 + (!isBuffer ? numberOfBytes(value.toString()) : Buffer.byteLength(value.toString(), 'utf8')) + 1 + BSON.calculateObjectSize(value.scope, serializeFunctions);
- } else if(serializeFunctions) {
- return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + (!isBuffer ? numberOfBytes(value.toString()) : Buffer.byteLength(value.toString(), 'utf8')) + 1;
- }
- }
- }
-
- return 0;
-}
-
-/**
- * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization.
- *
- * @param {Object} object the Javascript object to serialize.
- * @param {Boolean} checkKeys the serializer will check if keys are valid.
- * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object.
- * @param {Number} index the index in the buffer where we wish to start serializing into.
- * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**.
- * @return {Number} returns the new write index in the Buffer.
- * @api public
- */
-BSON.serializeWithBufferAndIndex = function serializeWithBufferAndIndex(object, checkKeys, buffer, index, serializeFunctions) {
- // Default setting false
- serializeFunctions = serializeFunctions == null ? false : serializeFunctions;
- // Write end information (length of the object)
- var size = buffer.length;
- // Write the size of the object
- buffer[index++] = size & 0xff;
- buffer[index++] = (size >> 8) & 0xff;
- buffer[index++] = (size >> 16) & 0xff;
- buffer[index++] = (size >> 24) & 0xff;
- return serializeObject(object, checkKeys, buffer, index, serializeFunctions) - 1;
-}
-
-/**
- * @ignore
- * @api private
- */
-var serializeObject = function(object, checkKeys, buffer, index, serializeFunctions) {
- // Process the object
- if(Array.isArray(object)) {
- for(var i = 0; i < object.length; i++) {
- index = packElement(i.toString(), object[i], checkKeys, buffer, index, serializeFunctions);
- }
- } else {
- // If we have toBSON defined, override the current object
- if(object.toBSON) {
- object = object.toBSON();
- }
-
- // Serialize the object
- for(var key in object) {
- // Check the key and throw error if it's illegal
- if (key != '$db' && key != '$ref' && key != '$id') {
- // dollars and dots ok
- BSON.checkKey(key, !checkKeys);
- }
-
- // Pack the element
- index = packElement(key, object[key], checkKeys, buffer, index, serializeFunctions);
- }
- }
-
- // Write zero
- buffer[index++] = 0;
- return index;
-}
-
-var stringToBytes = function(str) {
- var ch, st, re = [];
- for (var i = 0; i < str.length; i++ ) {
- ch = str.charCodeAt(i); // get char
- st = []; // set up "stack"
- do {
- st.push( ch & 0xFF ); // push byte to stack
- ch = ch >> 8; // shift value down by 1 byte
- }
- while ( ch );
- // add stack contents to result
- // done because chars have "wrong" endianness
- re = re.concat( st.reverse() );
- }
- // return an array of bytes
- return re;
-}
-
-var numberOfBytes = function(str) {
- var ch, st, re = 0;
- for (var i = 0; i < str.length; i++ ) {
- ch = str.charCodeAt(i); // get char
- st = []; // set up "stack"
- do {
- st.push( ch & 0xFF ); // push byte to stack
- ch = ch >> 8; // shift value down by 1 byte
- }
- while ( ch );
- // add stack contents to result
- // done because chars have "wrong" endianness
- re = re + st.length;
- }
- // return an array of bytes
- return re;
-}
-
-/**
- * @ignore
- * @api private
- */
-var writeToTypedArray = function(buffer, string, index) {
- var bytes = stringToBytes(string);
- for(var i = 0; i < bytes.length; i++) {
- buffer[index + i] = bytes[i];
- }
- return bytes.length;
-}
-
-/**
- * @ignore
- * @api private
- */
-var supportsBuffer = typeof Buffer != 'undefined';
-
-/**
- * @ignore
- * @api private
- */
-var packElement = function(name, value, checkKeys, buffer, index, serializeFunctions) {
- var startIndex = index;
-
- switch(typeof value) {
- case 'string':
- // Encode String type
- buffer[index++] = BSON.BSON_DATA_STRING;
- // Number of written bytes
- var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index);
- // Encode the name
- index = index + numberOfWrittenBytes + 1;
- buffer[index - 1] = 0;
-
- // Calculate size
- var size = supportsBuffer ? Buffer.byteLength(value) + 1 : numberOfBytes(value) + 1;
- // Write the size of the string to buffer
- buffer[index + 3] = (size >> 24) & 0xff;
- buffer[index + 2] = (size >> 16) & 0xff;
- buffer[index + 1] = (size >> 8) & 0xff;
- buffer[index] = size & 0xff;
- // Ajust the index
- index = index + 4;
- // Write the string
- supportsBuffer ? buffer.write(value, index, 'utf8') : writeToTypedArray(buffer, value, index);
- // Update index
- index = index + size - 1;
- // Write zero
- buffer[index++] = 0;
- // Return index
- return index;
- case 'number':
- // We have an integer value
- if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) {
- // If the value fits in 32 bits encode as int, if it fits in a double
- // encode it as a double, otherwise long
- if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) {
- // Set int type 32 bits or less
- buffer[index++] = BSON.BSON_DATA_INT;
- // Number of written bytes
- var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index);
- // Encode the name
- index = index + numberOfWrittenBytes + 1;
- buffer[index - 1] = 0;
- // Write the int value
- buffer[index++] = value & 0xff;
- buffer[index++] = (value >> 8) & 0xff;
- buffer[index++] = (value >> 16) & 0xff;
- buffer[index++] = (value >> 24) & 0xff;
- } else if(value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) {
- // Encode as double
- buffer[index++] = BSON.BSON_DATA_NUMBER;
- // Number of written bytes
- var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index);
- // Encode the name
- index = index + numberOfWrittenBytes + 1;
- buffer[index - 1] = 0;
- // Write float
- writeIEEE754(buffer, value, index, 'little', 52, 8);
- // Ajust index
- index = index + 8;
- } else {
- // Set long type
- buffer[index++] = BSON.BSON_DATA_LONG;
- // Number of written bytes
- var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index);
- // Encode the name
- index = index + numberOfWrittenBytes + 1;
- buffer[index - 1] = 0;
- var longVal = Long.fromNumber(value);
- var lowBits = longVal.getLowBits();
- var highBits = longVal.getHighBits();
- // Encode low bits
- buffer[index++] = lowBits & 0xff;
- buffer[index++] = (lowBits >> 8) & 0xff;
- buffer[index++] = (lowBits >> 16) & 0xff;
- buffer[index++] = (lowBits >> 24) & 0xff;
- // Encode high bits
- buffer[index++] = highBits & 0xff;
- buffer[index++] = (highBits >> 8) & 0xff;
- buffer[index++] = (highBits >> 16) & 0xff;
- buffer[index++] = (highBits >> 24) & 0xff;
- }
- } else {
- // Encode as double
- buffer[index++] = BSON.BSON_DATA_NUMBER;
- // Number of written bytes
- var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index);
- // Encode the name
- index = index + numberOfWrittenBytes + 1;
- buffer[index - 1] = 0;
- // Write float
- writeIEEE754(buffer, value, index, 'little', 52, 8);
- // Ajust index
- index = index + 8;
- }
-
- return index;
- case 'undefined':
- // Set long type
- buffer[index++] = BSON.BSON_DATA_NULL;
- // Number of written bytes
- var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index);
- // Encode the name
- index = index + numberOfWrittenBytes + 1;
- buffer[index - 1] = 0;
- return index;
- case 'boolean':
- // Write the type
- buffer[index++] = BSON.BSON_DATA_BOOLEAN;
- // Number of written bytes
- var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index);
- // Encode the name
- index = index + numberOfWrittenBytes + 1;
- buffer[index - 1] = 0;
- // Encode the boolean value
- buffer[index++] = value ? 1 : 0;
- return index;
- case 'object':
- if(value === null || value instanceof MinKey || value instanceof MaxKey
- || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') {
- // Write the type of either min or max key
- if(value === null) {
- buffer[index++] = BSON.BSON_DATA_NULL;
- } else if(value instanceof MinKey) {
- buffer[index++] = BSON.BSON_DATA_MIN_KEY;
- } else {
- buffer[index++] = BSON.BSON_DATA_MAX_KEY;
- }
-
- // Number of written bytes
- var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index);
- // Encode the name
- index = index + numberOfWrittenBytes + 1;
- buffer[index - 1] = 0;
- return index;
- } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') {
- // Write the type
- buffer[index++] = BSON.BSON_DATA_OID;
- // Number of written bytes
- var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index);
- // Encode the name
- index = index + numberOfWrittenBytes + 1;
- buffer[index - 1] = 0;
-
- // Write objectid
- supportsBuffer ? buffer.write(value.id, index, 'binary') : writeToTypedArray(buffer, value.id, index);
- // Ajust index
- index = index + 12;
- return index;
- } else if(value instanceof Date || isDate(value)) {
- // Write the type
- buffer[index++] = BSON.BSON_DATA_DATE;
- // Number of written bytes
- var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index);
- // Encode the name
- index = index + numberOfWrittenBytes + 1;
- buffer[index - 1] = 0;
-
- // Write the date
- var dateInMilis = Long.fromNumber(value.getTime());
- var lowBits = dateInMilis.getLowBits();
- var highBits = dateInMilis.getHighBits();
- // Encode low bits
- buffer[index++] = lowBits & 0xff;
- buffer[index++] = (lowBits >> 8) & 0xff;
- buffer[index++] = (lowBits >> 16) & 0xff;
- buffer[index++] = (lowBits >> 24) & 0xff;
- // Encode high bits
- buffer[index++] = highBits & 0xff;
- buffer[index++] = (highBits >> 8) & 0xff;
- buffer[index++] = (highBits >> 16) & 0xff;
- buffer[index++] = (highBits >> 24) & 0xff;
- return index;
- } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) {
- // Write the type
- buffer[index++] = BSON.BSON_DATA_BINARY;
- // Number of written bytes
- var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index);
- // Encode the name
- index = index + numberOfWrittenBytes + 1;
- buffer[index - 1] = 0;
- // Get size of the buffer (current write point)
- var size = value.length;
- // Write the size of the string to buffer
- buffer[index++] = size & 0xff;
- buffer[index++] = (size >> 8) & 0xff;
- buffer[index++] = (size >> 16) & 0xff;
- buffer[index++] = (size >> 24) & 0xff;
- // Write the default subtype
- buffer[index++] = BSON.BSON_BINARY_SUBTYPE_DEFAULT;
- // Copy the content form the binary field to the buffer
- value.copy(buffer, index, 0, size);
- // Adjust the index
- index = index + size;
- return index;
- } else if(value instanceof Long || value instanceof Timestamp || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Timestamp') {
- // Write the type
- buffer[index++] = value instanceof Long ? BSON.BSON_DATA_LONG : BSON.BSON_DATA_TIMESTAMP;
- // Number of written bytes
- var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index);
- // Encode the name
- index = index + numberOfWrittenBytes + 1;
- buffer[index - 1] = 0;
- // Write the date
- var lowBits = value.getLowBits();
- var highBits = value.getHighBits();
- // Encode low bits
- buffer[index++] = lowBits & 0xff;
- buffer[index++] = (lowBits >> 8) & 0xff;
- buffer[index++] = (lowBits >> 16) & 0xff;
- buffer[index++] = (lowBits >> 24) & 0xff;
- // Encode high bits
- buffer[index++] = highBits & 0xff;
- buffer[index++] = (highBits >> 8) & 0xff;
- buffer[index++] = (highBits >> 16) & 0xff;
- buffer[index++] = (highBits >> 24) & 0xff;
- return index;
- } else if(value instanceof Double || value['_bsontype'] == 'Double') {
- // Encode as double
- buffer[index++] = BSON.BSON_DATA_NUMBER;
- // Number of written bytes
- var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index);
- // Encode the name
- index = index + numberOfWrittenBytes + 1;
- buffer[index - 1] = 0;
- // Write float
- writeIEEE754(buffer, value, index, 'little', 52, 8);
- // Ajust index
- index = index + 8;
- return index;
- } else if(value instanceof Code || value['_bsontype'] == 'Code') {
- if(value.scope != null && Object.keys(value.scope).length > 0) {
- // Write the type
- buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE;
- // Number of written bytes
- var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index);
- // Encode the name
- index = index + numberOfWrittenBytes + 1;
- buffer[index - 1] = 0;
- // Calculate the scope size
- var scopeSize = BSON.calculateObjectSize(value.scope, serializeFunctions);
- // Function string
- var functionString = value.code.toString();
- // Function Size
- var codeSize = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1;
-
- // Calculate full size of the object
- var totalSize = 4 + codeSize + scopeSize + 4;
-
- // Write the total size of the object
- buffer[index++] = totalSize & 0xff;
- buffer[index++] = (totalSize >> 8) & 0xff;
- buffer[index++] = (totalSize >> 16) & 0xff;
- buffer[index++] = (totalSize >> 24) & 0xff;
-
- // Write the size of the string to buffer
- buffer[index++] = codeSize & 0xff;
- buffer[index++] = (codeSize >> 8) & 0xff;
- buffer[index++] = (codeSize >> 16) & 0xff;
- buffer[index++] = (codeSize >> 24) & 0xff;
-
- // Write the string
- supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index);
- // Update index
- index = index + codeSize - 1;
- // Write zero
- buffer[index++] = 0;
- // Serialize the scope object
- var scopeObjectBuffer = supportsBuffer ? new Buffer(scopeSize) : new Uint8Array(new ArrayBuffer(scopeSize));
- // Execute the serialization into a seperate buffer
- serializeObject(value.scope, checkKeys, scopeObjectBuffer, 0, serializeFunctions);
-
- // Adjusted scope Size (removing the header)
- var scopeDocSize = scopeSize;
- // Write scope object size
- buffer[index++] = scopeDocSize & 0xff;
- buffer[index++] = (scopeDocSize >> 8) & 0xff;
- buffer[index++] = (scopeDocSize >> 16) & 0xff;
- buffer[index++] = (scopeDocSize >> 24) & 0xff;
-
- // Write the scopeObject into the buffer
- supportsBuffer ? scopeObjectBuffer.copy(buffer, index, 0, scopeSize) : buffer.set(scopeObjectBuffer, index);
- // Adjust index, removing the empty size of the doc (5 bytes 0000000005)
- index = index + scopeDocSize - 5;
- // Write trailing zero
- buffer[index++] = 0;
- return index
- } else {
- buffer[index++] = BSON.BSON_DATA_CODE;
- // Number of written bytes
- var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index);
- // Encode the name
- index = index + numberOfWrittenBytes + 1;
- buffer[index - 1] = 0;
- // Function string
- var functionString = value.code.toString();
- // Function Size
- var size = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1;
- // Write the size of the string to buffer
- buffer[index++] = size & 0xff;
- buffer[index++] = (size >> 8) & 0xff;
- buffer[index++] = (size >> 16) & 0xff;
- buffer[index++] = (size >> 24) & 0xff;
- // Write the string
- supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index);
- // Update index
- index = index + size - 1;
- // Write zero
- buffer[index++] = 0;
- return index;
- }
- } else if(value instanceof Binary || value['_bsontype'] == 'Binary') {
- // Write the type
- buffer[index++] = BSON.BSON_DATA_BINARY;
- // Number of written bytes
- var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index);
- // Encode the name
- index = index + numberOfWrittenBytes + 1;
- buffer[index - 1] = 0;
- // Extract the buffer
- var data = value.value(true);
- // Calculate size
- var size = value.position;
- // Write the size of the string to buffer
- buffer[index++] = size & 0xff;
- buffer[index++] = (size >> 8) & 0xff;
- buffer[index++] = (size >> 16) & 0xff;
- buffer[index++] = (size >> 24) & 0xff;
- // Write the subtype to the buffer
- buffer[index++] = value.sub_type;
-
- // If we have binary type 2 the 4 first bytes are the size
- if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) {
- buffer[index++] = size & 0xff;
- buffer[index++] = (size >> 8) & 0xff;
- buffer[index++] = (size >> 16) & 0xff;
- buffer[index++] = (size >> 24) & 0xff;
- }
-
- // Write the data to the object
- supportsBuffer ? data.copy(buffer, index, 0, value.position) : buffer.set(data, index);
- // Ajust index
- index = index + value.position;
- return index;
- } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') {
- // Write the type
- buffer[index++] = BSON.BSON_DATA_SYMBOL;
- // Number of written bytes
- var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index);
- // Encode the name
- index = index + numberOfWrittenBytes + 1;
- buffer[index - 1] = 0;
- // Calculate size
- var size = supportsBuffer ? Buffer.byteLength(value.value) + 1 : numberOfBytes(value.value) + 1;
- // Write the size of the string to buffer
- buffer[index++] = size & 0xff;
- buffer[index++] = (size >> 8) & 0xff;
- buffer[index++] = (size >> 16) & 0xff;
- buffer[index++] = (size >> 24) & 0xff;
- // Write the string
- buffer.write(value.value, index, 'utf8');
- // Update index
- index = index + size - 1;
- // Write zero
- buffer[index++] = 0x00;
- return index;
- } else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') {
- // Write the type
- buffer[index++] = BSON.BSON_DATA_OBJECT;
- // Number of written bytes
- var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index);
- // Encode the name
- index = index + numberOfWrittenBytes + 1;
- buffer[index - 1] = 0;
- // Set up correct object for serialization
- var ordered_values = {
- '$ref': value.namespace
- , '$id' : value.oid
- };
-
- // Add db reference if it exists
- if(null != value.db) {
- ordered_values['$db'] = value.db;
- }
-
- // Message size
- var size = BSON.calculateObjectSize(ordered_values, serializeFunctions);
- // Serialize the object
- var endIndex = BSON.serializeWithBufferAndIndex(ordered_values, checkKeys, buffer, index, serializeFunctions);
- // Write the size of the string to buffer
- buffer[index++] = size & 0xff;
- buffer[index++] = (size >> 8) & 0xff;
- buffer[index++] = (size >> 16) & 0xff;
- buffer[index++] = (size >> 24) & 0xff;
- // Write zero for object
- buffer[endIndex++] = 0x00;
- // Return the end index
- return endIndex;
- } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') {
- // Write the type
- buffer[index++] = BSON.BSON_DATA_REGEXP;
- // Number of written bytes
- var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index);
- // Encode the name
- index = index + numberOfWrittenBytes + 1;
- buffer[index - 1] = 0;
-
- // Write the regular expression string
- supportsBuffer ? buffer.write(value.source, index, 'utf8') : writeToTypedArray(buffer, value.source, index);
- // Adjust the index
- index = index + (supportsBuffer ? Buffer.byteLength(value.source) : numberOfBytes(value.source));
- // Write zero
- buffer[index++] = 0x00;
- // Write the parameters
- if(value.global) buffer[index++] = 0x73; // s
- if(value.ignoreCase) buffer[index++] = 0x69; // i
- if(value.multiline) buffer[index++] = 0x6d; // m
- // Add ending zero
- buffer[index++] = 0x00;
- return index;
- } else {
- // Write the type
- buffer[index++] = Array.isArray(value) ? BSON.BSON_DATA_ARRAY : BSON.BSON_DATA_OBJECT;
- // Number of written bytes
- var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index);
- // Adjust the index
- index = index + numberOfWrittenBytes + 1;
- buffer[index - 1] = 0;
- var endIndex = serializeObject(value, checkKeys, buffer, index + 4, serializeFunctions);
- // Write size
- var size = endIndex - index;
- // Write the size of the string to buffer
- buffer[index++] = size & 0xff;
- buffer[index++] = (size >> 8) & 0xff;
- buffer[index++] = (size >> 16) & 0xff;
- buffer[index++] = (size >> 24) & 0xff;
- return endIndex;
- }
- case 'function':
- // WTF for 0.4.X where typeof /someregexp/ === 'function'
- if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') {
- // Write the type
- buffer[index++] = BSON.BSON_DATA_REGEXP;
- // Number of written bytes
- var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index);
- // Encode the name
- index = index + numberOfWrittenBytes + 1;
- buffer[index - 1] = 0;
-
- // Write the regular expression string
- buffer.write(value.source, index, 'utf8');
- // Adjust the index
- index = index + (supportsBuffer ? Buffer.byteLength(value.source) : numberOfBytes(value.source));
- // Write zero
- buffer[index++] = 0x00;
- // Write the parameters
- if(value.global) buffer[index++] = 0x73; // s
- if(value.ignoreCase) buffer[index++] = 0x69; // i
- if(value.multiline) buffer[index++] = 0x6d; // m
- // Add ending zero
- buffer[index++] = 0x00;
- return index;
- } else {
- if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) {
- // Write the type
- buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE;
- // Number of written bytes
- var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index);
- // Encode the name
- index = index + numberOfWrittenBytes + 1;
- buffer[index - 1] = 0;
- // Calculate the scope size
- var scopeSize = BSON.calculateObjectSize(value.scope, serializeFunctions);
- // Function string
- var functionString = value.toString();
- // Function Size
- var codeSize = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1;
-
- // Calculate full size of the object
- var totalSize = 4 + codeSize + scopeSize;
-
- // Write the total size of the object
- buffer[index++] = totalSize & 0xff;
- buffer[index++] = (totalSize >> 8) & 0xff;
- buffer[index++] = (totalSize >> 16) & 0xff;
- buffer[index++] = (totalSize >> 24) & 0xff;
-
- // Write the size of the string to buffer
- buffer[index++] = codeSize & 0xff;
- buffer[index++] = (codeSize >> 8) & 0xff;
- buffer[index++] = (codeSize >> 16) & 0xff;
- buffer[index++] = (codeSize >> 24) & 0xff;
-
- // Write the string
- supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index);
- // Update index
- index = index + codeSize - 1;
- // Write zero
- buffer[index++] = 0;
- // Serialize the scope object
- var scopeObjectBuffer = new Buffer(scopeSize);
- // Execute the serialization into a seperate buffer
- serializeObject(value.scope, checkKeys, scopeObjectBuffer, 0, serializeFunctions);
-
- // Adjusted scope Size (removing the header)
- var scopeDocSize = scopeSize - 4;
- // Write scope object size
- buffer[index++] = scopeDocSize & 0xff;
- buffer[index++] = (scopeDocSize >> 8) & 0xff;
- buffer[index++] = (scopeDocSize >> 16) & 0xff;
- buffer[index++] = (scopeDocSize >> 24) & 0xff;
-
- // Write the scopeObject into the buffer
- scopeObjectBuffer.copy(buffer, index, 0, scopeSize);
-
- // Adjust index, removing the empty size of the doc (5 bytes 0000000005)
- index = index + scopeDocSize - 5;
- // Write trailing zero
- buffer[index++] = 0;
- return index
- } else if(serializeFunctions) {
- buffer[index++] = BSON.BSON_DATA_CODE;
- // Number of written bytes
- var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index);
- // Encode the name
- index = index + numberOfWrittenBytes + 1;
- buffer[index - 1] = 0;
- // Function string
- var functionString = value.toString();
- // Function Size
- var size = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1;
- // Write the size of the string to buffer
- buffer[index++] = size & 0xff;
- buffer[index++] = (size >> 8) & 0xff;
- buffer[index++] = (size >> 16) & 0xff;
- buffer[index++] = (size >> 24) & 0xff;
- // Write the string
- supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index);
- // Update index
- index = index + size - 1;
- // Write zero
- buffer[index++] = 0;
- return index;
- }
- }
- }
-
- // If no value to serialize
- return index;
-}
-
-/**
- * Serialize a Javascript object.
- *
- * @param {Object} object the Javascript object to serialize.
- * @param {Boolean} checkKeys the serializer will check if keys are valid.
- * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**.
- * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**.
- * @return {Buffer} returns the Buffer object containing the serialized object.
- * @api public
- */
-BSON.serialize = function(object, checkKeys, asBuffer, serializeFunctions) {
- // Throw error if we are trying serialize an illegal type
- if(object == null || typeof object != 'object' || Array.isArray(object))
- throw new Error("Only javascript objects supported");
-
- // Emoty target buffer
- var buffer = null;
- // Calculate the size of the object
- var size = BSON.calculateObjectSize(object, serializeFunctions);
- // Fetch the best available type for storing the binary data
- if(buffer = typeof Buffer != 'undefined') {
- buffer = new Buffer(size);
- asBuffer = true;
- } else if(typeof Uint8Array != 'undefined') {
- buffer = new Uint8Array(new ArrayBuffer(size));
- } else {
- buffer = new Array(size);
- }
-
- // If asBuffer is false use typed arrays
- BSON.serializeWithBufferAndIndex(object, checkKeys, buffer, 0, serializeFunctions);
- return buffer;
-}
-
-/**
- * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5
- *
- * @ignore
- * @api private
- */
-var functionCache = BSON.functionCache = {};
-
-/**
- * Crc state variables shared by function
- *
- * @ignore
- * @api private
- */
-var table = [0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D];
-
-/**
- * CRC32 hash method, Fast and enough versitility for our usage
- *
- * @ignore
- * @api private
- */
-var crc32 = function(string, start, end) {
- var crc = 0
- var x = 0;
- var y = 0;
- crc = crc ^ (-1);
-
- for(var i = start, iTop = end; i < iTop;i++) {
- y = (crc ^ string[i]) & 0xFF;
- x = table[y];
- crc = (crc >>> 8) ^ x;
- }
-
- return crc ^ (-1);
-}
-
-/**
- * Deserialize stream data as BSON documents.
- *
- * Options
- * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized.
- * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse.
- * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function.
- * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits
- *
- * @param {Buffer} data the buffer containing the serialized set of BSON documents.
- * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start.
- * @param {Number} numberOfDocuments number of documents to deserialize.
- * @param {Array} documents an array where to store the deserialized documents.
- * @param {Number} docStartIndex the index in the documents array from where to start inserting documents.
- * @param {Object} [options] additional options used for the deserialization.
- * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents.
- * @api public
- */
-BSON.deserializeStream = function(data, startIndex, numberOfDocuments, documents, docStartIndex, options) {
- // if(numberOfDocuments !== documents.length) throw new Error("Number of expected results back is less than the number of documents");
- options = options != null ? options : {};
- var index = startIndex;
- // Loop over all documents
- for(var i = 0; i < numberOfDocuments; i++) {
- // Find size of the document
- var size = data[index] | data[index + 1] << 8 | data[index + 2] << 16 | data[index + 3] << 24;
- // Update options with index
- options['index'] = index;
- // Parse the document at this point
- documents[docStartIndex + i] = BSON.deserialize(data, options);
- // Adjust index by the document size
- index = index + size;
- }
-
- // Return object containing end index of parsing and list of documents
- return index;
-}
-
-/**
- * Ensure eval is isolated.
- *
- * @ignore
- * @api private
- */
-var isolateEvalWithHash = function(functionCache, hash, functionString, object) {
- // Contains the value we are going to set
- var value = null;
-
- // Check for cache hit, eval if missing and return cached function
- if(functionCache[hash] == null) {
- eval("value = " + functionString);
- functionCache[hash] = value;
- }
- // Set the object
- return functionCache[hash].bind(object);
-}
-
-/**
- * Ensure eval is isolated.
- *
- * @ignore
- * @api private
- */
-var isolateEval = function(functionString) {
- // Contains the value we are going to set
- var value = null;
- // Eval the function
- eval("value = " + functionString);
- return value;
-}
-
-/**
- * Convert Uint8Array to String
- *
- * @ignore
- * @api private
- */
-var convertUint8ArrayToUtf8String = function(byteArray, startIndex, endIndex) {
- return BinaryParser.decode_utf8(convertArraytoUtf8BinaryString(byteArray, startIndex, endIndex));
-}
-
-var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) {
- var result = "";
- for(var i = startIndex; i < endIndex; i++) {
- result = result + String.fromCharCode(byteArray[i]);
- }
-
- return result;
-};
-
-/**
- * Deserialize data as BSON.
- *
- * Options
- * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized.
- * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse.
- * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function.
- * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits
- *
- * @param {Buffer} buffer the buffer containing the serialized set of BSON documents.
- * @param {Object} [options] additional options used for the deserialization.
- * @param {Boolean} [isArray] ignore used for recursive parsing.
- * @return {Object} returns the deserialized Javascript Object.
- * @api public
- */
-BSON.deserialize = function(buffer, options, isArray) {
- // Options
- options = options == null ? {} : options;
- var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions'];
- var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions'];
- var cacheFunctionsCrc32 = options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32'];
- var promoteLongs = options['promoteLongs'] || true;
-
- // Validate that we have at least 4 bytes of buffer
- if(buffer.length < 5) throw new Error("corrupt bson message < 5 bytes long");
-
- // Set up index
- var index = typeof options['index'] == 'number' ? options['index'] : 0;
- // Reads in a C style string
- var readCStyleString = function() {
- // Get the start search index
- var i = index;
- // Locate the end of the c string
- while(buffer[i] !== 0x00) { i++ }
- // Grab utf8 encoded string
- var string = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, i) : convertUint8ArrayToUtf8String(buffer, index, i);
- // Update index position
- index = i + 1;
- // Return string
- return string;
- }
-
- // Create holding object
- var object = isArray ? [] : {};
-
- // Read the document size
- var size = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24;
-
- // Ensure buffer is valid size
- if(size < 5 || size > buffer.length) throw new Error("corrupt bson message");
-
- // While we have more left data left keep parsing
- while(true) {
- // Read the type
- var elementType = buffer[index++];
- // If we get a zero it's the last byte, exit
- if(elementType == 0) break;
- // Read the name of the field
- var name = readCStyleString();
- // Switch on the type
- switch(elementType) {
- case BSON.BSON_DATA_OID:
- var string = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('binary', index, index + 12) : convertArraytoUtf8BinaryString(buffer, index, index + 12);
- // Decode the oid
- object[name] = new ObjectID(string);
- // Update index
- index = index + 12;
- break;
- case BSON.BSON_DATA_STRING:
- // Read the content of the field
- var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24;
- // Add string to object
- object[name] = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1);
- // Update parse index position
- index = index + stringSize;
- break;
- case BSON.BSON_DATA_INT:
- // Decode the 32bit value
- object[name] = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24;
- break;
- case BSON.BSON_DATA_NUMBER:
- // Decode the double value
- object[name] = readIEEE754(buffer, index, 'little', 52, 8);
- // Update the index
- index = index + 8;
- break;
- case BSON.BSON_DATA_DATE:
- // Unpack the low and high bits
- var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24;
- var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24;
- // Set date object
- object[name] = new Date(new Long(lowBits, highBits).toNumber());
- break;
- case BSON.BSON_DATA_BOOLEAN:
- // Parse the boolean value
- object[name] = buffer[index++] == 1;
- break;
- case BSON.BSON_DATA_NULL:
- // Parse the boolean value
- object[name] = null;
- break;
- case BSON.BSON_DATA_BINARY:
- // Decode the size of the binary blob
- var binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24;
- // Decode the subtype
- var subType = buffer[index++];
- // Decode as raw Buffer object if options specifies it
- if(buffer['slice'] != null) {
- // If we have subtype 2 skip the 4 bytes for the size
- if(subType == Binary.SUBTYPE_BYTE_ARRAY) {
- binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24;
- }
- // Slice the data
- object[name] = new Binary(buffer.slice(index, index + binarySize), subType);
- } else {
- var _buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(binarySize)) : new Array(binarySize);
- // If we have subtype 2 skip the 4 bytes for the size
- if(subType == Binary.SUBTYPE_BYTE_ARRAY) {
- binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24;
- }
- // Copy the data
- for(var i = 0; i < binarySize; i++) {
- _buffer[i] = buffer[index + i];
- }
- // Create the binary object
- object[name] = new Binary(_buffer, subType);
- }
- // Update the index
- index = index + binarySize;
- break;
- case BSON.BSON_DATA_ARRAY:
- options['index'] = index;
- // Decode the size of the array document
- var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24;
- // Set the array to the object
- object[name] = BSON.deserialize(buffer, options, true);
- // Adjust the index
- index = index + objectSize;
- break;
- case BSON.BSON_DATA_OBJECT:
- options['index'] = index;
- // Decode the size of the object document
- var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24;
- // Set the array to the object
- object[name] = BSON.deserialize(buffer, options, false);
- // Adjust the index
- index = index + objectSize;
- break;
- case BSON.BSON_DATA_REGEXP:
- // Create the regexp
- var source = readCStyleString();
- var regExpOptions = readCStyleString();
- // For each option add the corresponding one for javascript
- var optionsArray = new Array(regExpOptions.length);
-
- // Parse options
- for(var i = 0; i < regExpOptions.length; i++) {
- switch(regExpOptions[i]) {
- case 'm':
- optionsArray[i] = 'm';
- break;
- case 's':
- optionsArray[i] = 'g';
- break;
- case 'i':
- optionsArray[i] = 'i';
- break;
- }
- }
-
- object[name] = new RegExp(source, optionsArray.join(''));
- break;
- case BSON.BSON_DATA_LONG:
- // Unpack the low and high bits
- var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24;
- var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24;
- // Create long object
- var long = new Long(lowBits, highBits);
- // Promote the long if possible
- if(promoteLongs) {
- object[name] = long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) ? long.toNumber() : long;
- } else {
- object[name] = long;
- }
- break;
- case BSON.BSON_DATA_SYMBOL:
- // Read the content of the field
- var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24;
- // Add string to object
- object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1));
- // Update parse index position
- index = index + stringSize;
- break;
- case BSON.BSON_DATA_TIMESTAMP:
- // Unpack the low and high bits
- var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24;
- var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24;
- // Set the object
- object[name] = new Timestamp(lowBits, highBits);
- break;
- case BSON.BSON_DATA_MIN_KEY:
- // Parse the object
- object[name] = new MinKey();
- break;
- case BSON.BSON_DATA_MAX_KEY:
- // Parse the object
- object[name] = new MaxKey();
- break;
- case BSON.BSON_DATA_CODE:
- // Read the content of the field
- var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24;
- // Function string
- var functionString = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1);
-
- // If we are evaluating the functions
- if(evalFunctions) {
- // Contains the value we are going to set
- var value = null;
- // If we have cache enabled let's look for the md5 of the function in the cache
- if(cacheFunctions) {
- var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString;
- // Got to do this to avoid V8 deoptimizing the call due to finding eval
- object[name] = isolateEvalWithHash(functionCache, hash, functionString, object);
- } else {
- // Set directly
- object[name] = isolateEval(functionString);
- }
- } else {
- object[name] = new Code(functionString, {});
- }
-
- // Update parse index position
- index = index + stringSize;
- break;
- case BSON.BSON_DATA_CODE_W_SCOPE:
- // Read the content of the field
- var totalSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24;
- var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24;
- // Javascript function
- var functionString = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1);
- // Update parse index position
- index = index + stringSize;
- // Parse the element
- options['index'] = index;
- // Decode the size of the object document
- var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24;
- // Decode the scope object
- var scopeObject = BSON.deserialize(buffer, options, false);
- // Adjust the index
- index = index + objectSize;
-
- // If we are evaluating the functions
- if(evalFunctions) {
- // Contains the value we are going to set
- var value = null;
- // If we have cache enabled let's look for the md5 of the function in the cache
- if(cacheFunctions) {
- var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString;
- // Got to do this to avoid V8 deoptimizing the call due to finding eval
- object[name] = isolateEvalWithHash(functionCache, hash, functionString, object);
- } else {
- // Set directly
- object[name] = isolateEval(functionString);
- }
-
- // Set the scope on the object
- object[name].scope = scopeObject;
- } else {
- object[name] = new Code(functionString, scopeObject);
- }
-
- // Add string to object
- break;
- }
- }
-
- // Check if we have a db ref object
- if(object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']);
-
- // Return the final objects
- return object;
-}
-
-/**
- * Check if key name is valid.
- *
- * @ignore
- * @api private
- */
-BSON.checkKey = function checkKey (key, dollarsAndDotsOk) {
- if (!key.length) return;
- // Check if we have a legal key for the object
- if (!!~key.indexOf("\x00")) {
- // The BSON spec doesn't allow keys with null bytes because keys are
- // null-terminated.
- throw Error("key " + key + " must not contain null bytes");
- }
- if (!dollarsAndDotsOk) {
- if('$' == key[0]) {
- throw Error("key " + key + " must not start with '$'");
- } else if (!!~key.indexOf('.')) {
- throw Error("key " + key + " must not contain '.'");
- }
- }
-};
-
-/**
- * Deserialize data as BSON.
- *
- * Options
- * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized.
- * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse.
- * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function.
- *
- * @param {Buffer} buffer the buffer containing the serialized set of BSON documents.
- * @param {Object} [options] additional options used for the deserialization.
- * @param {Boolean} [isArray] ignore used for recursive parsing.
- * @return {Object} returns the deserialized Javascript Object.
- * @api public
- */
-BSON.prototype.deserialize = function(data, options) {
- return BSON.deserialize(data, options);
-}
-
-/**
- * Deserialize stream data as BSON documents.
- *
- * Options
- * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized.
- * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse.
- * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function.
- *
- * @param {Buffer} data the buffer containing the serialized set of BSON documents.
- * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start.
- * @param {Number} numberOfDocuments number of documents to deserialize.
- * @param {Array} documents an array where to store the deserialized documents.
- * @param {Number} docStartIndex the index in the documents array from where to start inserting documents.
- * @param {Object} [options] additional options used for the deserialization.
- * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents.
- * @api public
- */
-BSON.prototype.deserializeStream = function(data, startIndex, numberOfDocuments, documents, docStartIndex, options) {
- return BSON.deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options);
-}
-
-/**
- * Serialize a Javascript object.
- *
- * @param {Object} object the Javascript object to serialize.
- * @param {Boolean} checkKeys the serializer will check if keys are valid.
- * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**.
- * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**.
- * @return {Buffer} returns the Buffer object containing the serialized object.
- * @api public
- */
-BSON.prototype.serialize = function(object, checkKeys, asBuffer, serializeFunctions) {
- return BSON.serialize(object, checkKeys, asBuffer, serializeFunctions);
-}
-
-/**
- * Calculate the bson size for a passed in Javascript object.
- *
- * @param {Object} object the Javascript object to calculate the BSON byte size for.
- * @param {Boolean} [serializeFunctions] serialize all functions in the object **(default:false)**.
- * @return {Number} returns the number of bytes the BSON object will take up.
- * @api public
- */
-BSON.prototype.calculateObjectSize = function(object, serializeFunctions) {
- return BSON.calculateObjectSize(object, serializeFunctions);
-}
-
-/**
- * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization.
- *
- * @param {Object} object the Javascript object to serialize.
- * @param {Boolean} checkKeys the serializer will check if keys are valid.
- * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object.
- * @param {Number} index the index in the buffer where we wish to start serializing into.
- * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**.
- * @return {Number} returns the new write index in the Buffer.
- * @api public
- */
-BSON.prototype.serializeWithBufferAndIndex = function(object, checkKeys, buffer, startIndex, serializeFunctions) {
- return BSON.serializeWithBufferAndIndex(object, checkKeys, buffer, startIndex, serializeFunctions);
-}
-
-/**
- * @ignore
- * @api private
- */
-exports.Code = Code;
-exports.Symbol = Symbol;
-exports.BSON = BSON;
-exports.DBRef = DBRef;
-exports.Binary = Binary;
-exports.ObjectID = ObjectID;
-exports.Long = Long;
-exports.Timestamp = Timestamp;
-exports.Double = Double;
-exports.MinKey = MinKey;
-exports.MaxKey = MaxKey;
-
-},
-
-
-
-'code': function(module, exports, global, require, undefined){
- /**
- * A class representation of the BSON Code type.
- *
- * @class Represents the BSON Code type.
- * @param {String|Function} code a string or function.
- * @param {Object} [scope] an optional scope for the function.
- * @return {Code}
- */
-function Code(code, scope) {
- if(!(this instanceof Code)) return new Code(code, scope);
-
- this._bsontype = 'Code';
- this.code = code;
- this.scope = scope == null ? {} : scope;
-};
-
-/**
- * @ignore
- * @api private
- */
-Code.prototype.toJSON = function() {
- return {scope:this.scope, code:this.code};
-}
-
-exports.Code = Code;
-},
-
-
-
-'db_ref': function(module, exports, global, require, undefined){
- /**
- * A class representation of the BSON DBRef type.
- *
- * @class Represents the BSON DBRef type.
- * @param {String} namespace the collection name.
- * @param {ObjectID} oid the reference ObjectID.
- * @param {String} [db] optional db name, if omitted the reference is local to the current db.
- * @return {DBRef}
- */
-function DBRef(namespace, oid, db) {
- if(!(this instanceof DBRef)) return new DBRef(namespace, oid, db);
-
- this._bsontype = 'DBRef';
- this.namespace = namespace;
- this.oid = oid;
- this.db = db;
-};
-
-/**
- * @ignore
- * @api private
- */
-DBRef.prototype.toJSON = function() {
- return {
- '$ref':this.namespace,
- '$id':this.oid,
- '$db':this.db == null ? '' : this.db
- };
-}
-
-exports.DBRef = DBRef;
-},
-
-
-
-'double': function(module, exports, global, require, undefined){
- /**
- * A class representation of the BSON Double type.
- *
- * @class Represents the BSON Double type.
- * @param {Number} value the number we want to represent as a double.
- * @return {Double}
- */
-function Double(value) {
- if(!(this instanceof Double)) return new Double(value);
-
- this._bsontype = 'Double';
- this.value = value;
-}
-
-/**
- * Access the number value.
- *
- * @return {Number} returns the wrapped double number.
- * @api public
- */
-Double.prototype.valueOf = function() {
- return this.value;
-};
-
-/**
- * @ignore
- * @api private
- */
-Double.prototype.toJSON = function() {
- return this.value;
-}
-
-exports.Double = Double;
-},
-
-
-
-'float_parser': function(module, exports, global, require, undefined){
- // Copyright (c) 2008, Fair Oaks Labs, Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are met:
-//
-// * Redistributions of source code must retain the above copyright notice,
-// this list of conditions and the following disclaimer.
-//
-// * Redistributions in binary form must reproduce the above copyright notice,
-// this list of conditions and the following disclaimer in the documentation
-// and/or other materials provided with the distribution.
-//
-// * Neither the name of Fair Oaks Labs, Inc. nor the names of its contributors
-// may be used to endorse or promote products derived from this software
-// without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
-// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-// POSSIBILITY OF SUCH DAMAGE.
-//
-//
-// Modifications to writeIEEE754 to support negative zeroes made by Brian White
-
-var readIEEE754 = function(buffer, offset, endian, mLen, nBytes) {
- var e, m,
- bBE = (endian === 'big'),
- eLen = nBytes * 8 - mLen - 1,
- eMax = (1 << eLen) - 1,
- eBias = eMax >> 1,
- nBits = -7,
- i = bBE ? 0 : (nBytes - 1),
- d = bBE ? 1 : -1,
- s = buffer[offset + i];
-
- i += d;
-
- e = s & ((1 << (-nBits)) - 1);
- s >>= (-nBits);
- nBits += eLen;
- for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8);
-
- m = e & ((1 << (-nBits)) - 1);
- e >>= (-nBits);
- nBits += mLen;
- for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8);
-
- if (e === 0) {
- e = 1 - eBias;
- } else if (e === eMax) {
- return m ? NaN : ((s ? -1 : 1) * Infinity);
- } else {
- m = m + Math.pow(2, mLen);
- e = e - eBias;
- }
- return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
-};
-
-var writeIEEE754 = function(buffer, value, offset, endian, mLen, nBytes) {
- var e, m, c,
- bBE = (endian === 'big'),
- eLen = nBytes * 8 - mLen - 1,
- eMax = (1 << eLen) - 1,
- eBias = eMax >> 1,
- rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0),
- i = bBE ? (nBytes-1) : 0,
- d = bBE ? -1 : 1,
- s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
-
- value = Math.abs(value);
-
- if (isNaN(value) || value === Infinity) {
- m = isNaN(value) ? 1 : 0;
- e = eMax;
- } else {
- e = Math.floor(Math.log(value) / Math.LN2);
- if (value * (c = Math.pow(2, -e)) < 1) {
- e--;
- c *= 2;
- }
- if (e+eBias >= 1) {
- value += rt / c;
- } else {
- value += rt * Math.pow(2, 1 - eBias);
- }
- if (value * c >= 2) {
- e++;
- c /= 2;
- }
-
- if (e + eBias >= eMax) {
- m = 0;
- e = eMax;
- } else if (e + eBias >= 1) {
- m = (value * c - 1) * Math.pow(2, mLen);
- e = e + eBias;
- } else {
- m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
- e = 0;
- }
- }
-
- for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8);
-
- e = (e << mLen) | m;
- eLen += mLen;
- for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8);
-
- buffer[offset + i - d] |= s * 128;
-};
-
-exports.readIEEE754 = readIEEE754;
-exports.writeIEEE754 = writeIEEE754;
-},
-
-
-
-'index': function(module, exports, global, require, undefined){
- try {
- exports.BSONPure = require('./bson');
- exports.BSONNative = require('../../ext');
-} catch(err) {
- // do nothing
-}
-
-[ './binary_parser'
- , './binary'
- , './code'
- , './db_ref'
- , './double'
- , './max_key'
- , './min_key'
- , './objectid'
- , './symbol'
- , './timestamp'
- , './long'].forEach(function (path) {
- var module = require('./' + path);
- for (var i in module) {
- exports[i] = module[i];
- }
-});
-
-// Exports all the classes for the NATIVE JS BSON Parser
-exports.native = function() {
- var classes = {};
- // Map all the classes
- [ './binary_parser'
- , './binary'
- , './code'
- , './db_ref'
- , './double'
- , './max_key'
- , './min_key'
- , './objectid'
- , './symbol'
- , './timestamp'
- , './long'
- , '../../ext'
-].forEach(function (path) {
- var module = require('./' + path);
- for (var i in module) {
- classes[i] = module[i];
- }
- });
- // Return classes list
- return classes;
-}
-
-// Exports all the classes for the PURE JS BSON Parser
-exports.pure = function() {
- var classes = {};
- // Map all the classes
- [ './binary_parser'
- , './binary'
- , './code'
- , './db_ref'
- , './double'
- , './max_key'
- , './min_key'
- , './objectid'
- , './symbol'
- , './timestamp'
- , './long'
- , '././bson'].forEach(function (path) {
- var module = require('./' + path);
- for (var i in module) {
- classes[i] = module[i];
- }
- });
- // Return classes list
- return classes;
-}
-
-},
-
-
-
-'long': function(module, exports, global, require, undefined){
- // Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-// Copyright 2009 Google Inc. All Rights Reserved
-
-/**
- * Defines a Long class for representing a 64-bit two's-complement
- * integer value, which faithfully simulates the behavior of a Java "Long". This
- * implementation is derived from LongLib in GWT.
- *
- * Constructs a 64-bit two's-complement integer, given its low and high 32-bit
- * values as *signed* integers. See the from* functions below for more
- * convenient ways of constructing Longs.
- *
- * The internal representation of a Long is the two given signed, 32-bit values.
- * We use 32-bit pieces because these are the size of integers on which
- * Javascript performs bit-operations. For operations like addition and
- * multiplication, we split each number into 16-bit pieces, which can easily be
- * multiplied within Javascript's floating-point representation without overflow
- * or change in sign.
- *
- * In the algorithms below, we frequently reduce the negative case to the
- * positive case by negating the input(s) and then post-processing the result.
- * Note that we must ALWAYS check specially whether those values are MIN_VALUE
- * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as
- * a positive number, it overflows back into a negative). Not handling this
- * case would often result in infinite recursion.
- *
- * @class Represents the BSON Long type.
- * @param {Number} low the low (signed) 32 bits of the Long.
- * @param {Number} high the high (signed) 32 bits of the Long.
- */
-function Long(low, high) {
- if(!(this instanceof Long)) return new Long(low, high);
-
- this._bsontype = 'Long';
- /**
- * @type {number}
- * @api private
- */
- this.low_ = low | 0; // force into 32 signed bits.
-
- /**
- * @type {number}
- * @api private
- */
- this.high_ = high | 0; // force into 32 signed bits.
-};
-
-/**
- * Return the int value.
- *
- * @return {Number} the value, assuming it is a 32-bit integer.
- * @api public
- */
-Long.prototype.toInt = function() {
- return this.low_;
-};
-
-/**
- * Return the Number value.
- *
- * @return {Number} the closest floating-point representation to this value.
- * @api public
- */
-Long.prototype.toNumber = function() {
- return this.high_ * Long.TWO_PWR_32_DBL_ +
- this.getLowBitsUnsigned();
-};
-
-/**
- * Return the JSON value.
- *
- * @return {String} the JSON representation.
- * @api public
- */
-Long.prototype.toJSON = function() {
- return this.toString();
-}
-
-/**
- * Return the String value.
- *
- * @param {Number} [opt_radix] the radix in which the text should be written.
- * @return {String} the textual representation of this value.
- * @api public
- */
-Long.prototype.toString = function(opt_radix) {
- var radix = opt_radix || 10;
- if (radix < 2 || 36 < radix) {
- throw Error('radix out of range: ' + radix);
- }
-
- if (this.isZero()) {
- return '0';
- }
-
- if (this.isNegative()) {
- if (this.equals(Long.MIN_VALUE)) {
- // We need to change the Long value before it can be negated, so we remove
- // the bottom-most digit in this base and then recurse to do the rest.
- var radixLong = Long.fromNumber(radix);
- var div = this.div(radixLong);
- var rem = div.multiply(radixLong).subtract(this);
- return div.toString(radix) + rem.toInt().toString(radix);
- } else {
- return '-' + this.negate().toString(radix);
- }
- }
-
- // Do several (6) digits each time through the loop, so as to
- // minimize the calls to the very expensive emulated div.
- var radixToPower = Long.fromNumber(Math.pow(radix, 6));
-
- var rem = this;
- var result = '';
- while (true) {
- var remDiv = rem.div(radixToPower);
- var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt();
- var digits = intval.toString(radix);
-
- rem = remDiv;
- if (rem.isZero()) {
- return digits + result;
- } else {
- while (digits.length < 6) {
- digits = '0' + digits;
- }
- result = '' + digits + result;
- }
- }
-};
-
-/**
- * Return the high 32-bits value.
- *
- * @return {Number} the high 32-bits as a signed value.
- * @api public
- */
-Long.prototype.getHighBits = function() {
- return this.high_;
-};
-
-/**
- * Return the low 32-bits value.
- *
- * @return {Number} the low 32-bits as a signed value.
- * @api public
- */
-Long.prototype.getLowBits = function() {
- return this.low_;
-};
-
-/**
- * Return the low unsigned 32-bits value.
- *
- * @return {Number} the low 32-bits as an unsigned value.
- * @api public
- */
-Long.prototype.getLowBitsUnsigned = function() {
- return (this.low_ >= 0) ?
- this.low_ : Long.TWO_PWR_32_DBL_ + this.low_;
-};
-
-/**
- * Returns the number of bits needed to represent the absolute value of this Long.
- *
- * @return {Number} Returns the number of bits needed to represent the absolute value of this Long.
- * @api public
- */
-Long.prototype.getNumBitsAbs = function() {
- if (this.isNegative()) {
- if (this.equals(Long.MIN_VALUE)) {
- return 64;
- } else {
- return this.negate().getNumBitsAbs();
- }
- } else {
- var val = this.high_ != 0 ? this.high_ : this.low_;
- for (var bit = 31; bit > 0; bit--) {
- if ((val & (1 << bit)) != 0) {
- break;
- }
- }
- return this.high_ != 0 ? bit + 33 : bit + 1;
- }
-};
-
-/**
- * Return whether this value is zero.
- *
- * @return {Boolean} whether this value is zero.
- * @api public
- */
-Long.prototype.isZero = function() {
- return this.high_ == 0 && this.low_ == 0;
-};
-
-/**
- * Return whether this value is negative.
- *
- * @return {Boolean} whether this value is negative.
- * @api public
- */
-Long.prototype.isNegative = function() {
- return this.high_ < 0;
-};
-
-/**
- * Return whether this value is odd.
- *
- * @return {Boolean} whether this value is odd.
- * @api public
- */
-Long.prototype.isOdd = function() {
- return (this.low_ & 1) == 1;
-};
-
-/**
- * Return whether this Long equals the other
- *
- * @param {Long} other Long to compare against.
- * @return {Boolean} whether this Long equals the other
- * @api public
- */
-Long.prototype.equals = function(other) {
- return (this.high_ == other.high_) && (this.low_ == other.low_);
-};
-
-/**
- * Return whether this Long does not equal the other.
- *
- * @param {Long} other Long to compare against.
- * @return {Boolean} whether this Long does not equal the other.
- * @api public
- */
-Long.prototype.notEquals = function(other) {
- return (this.high_ != other.high_) || (this.low_ != other.low_);
-};
-
-/**
- * Return whether this Long is less than the other.
- *
- * @param {Long} other Long to compare against.
- * @return {Boolean} whether this Long is less than the other.
- * @api public
- */
-Long.prototype.lessThan = function(other) {
- return this.compare(other) < 0;
-};
-
-/**
- * Return whether this Long is less than or equal to the other.
- *
- * @param {Long} other Long to compare against.
- * @return {Boolean} whether this Long is less than or equal to the other.
- * @api public
- */
-Long.prototype.lessThanOrEqual = function(other) {
- return this.compare(other) <= 0;
-};
-
-/**
- * Return whether this Long is greater than the other.
- *
- * @param {Long} other Long to compare against.
- * @return {Boolean} whether this Long is greater than the other.
- * @api public
- */
-Long.prototype.greaterThan = function(other) {
- return this.compare(other) > 0;
-};
-
-/**
- * Return whether this Long is greater than or equal to the other.
- *
- * @param {Long} other Long to compare against.
- * @return {Boolean} whether this Long is greater than or equal to the other.
- * @api public
- */
-Long.prototype.greaterThanOrEqual = function(other) {
- return this.compare(other) >= 0;
-};
-
-/**
- * Compares this Long with the given one.
- *
- * @param {Long} other Long to compare against.
- * @return {Boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater.
- * @api public
- */
-Long.prototype.compare = function(other) {
- if (this.equals(other)) {
- return 0;
- }
-
- var thisNeg = this.isNegative();
- var otherNeg = other.isNegative();
- if (thisNeg && !otherNeg) {
- return -1;
- }
- if (!thisNeg && otherNeg) {
- return 1;
- }
-
- // at this point, the signs are the same, so subtraction will not overflow
- if (this.subtract(other).isNegative()) {
- return -1;
- } else {
- return 1;
- }
-};
-
-/**
- * The negation of this value.
- *
- * @return {Long} the negation of this value.
- * @api public
- */
-Long.prototype.negate = function() {
- if (this.equals(Long.MIN_VALUE)) {
- return Long.MIN_VALUE;
- } else {
- return this.not().add(Long.ONE);
- }
-};
-
-/**
- * Returns the sum of this and the given Long.
- *
- * @param {Long} other Long to add to this one.
- * @return {Long} the sum of this and the given Long.
- * @api public
- */
-Long.prototype.add = function(other) {
- // Divide each number into 4 chunks of 16 bits, and then sum the chunks.
-
- var a48 = this.high_ >>> 16;
- var a32 = this.high_ & 0xFFFF;
- var a16 = this.low_ >>> 16;
- var a00 = this.low_ & 0xFFFF;
-
- var b48 = other.high_ >>> 16;
- var b32 = other.high_ & 0xFFFF;
- var b16 = other.low_ >>> 16;
- var b00 = other.low_ & 0xFFFF;
-
- var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
- c00 += a00 + b00;
- c16 += c00 >>> 16;
- c00 &= 0xFFFF;
- c16 += a16 + b16;
- c32 += c16 >>> 16;
- c16 &= 0xFFFF;
- c32 += a32 + b32;
- c48 += c32 >>> 16;
- c32 &= 0xFFFF;
- c48 += a48 + b48;
- c48 &= 0xFFFF;
- return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32);
-};
-
-/**
- * Returns the difference of this and the given Long.
- *
- * @param {Long} other Long to subtract from this.
- * @return {Long} the difference of this and the given Long.
- * @api public
- */
-Long.prototype.subtract = function(other) {
- return this.add(other.negate());
-};
-
-/**
- * Returns the product of this and the given Long.
- *
- * @param {Long} other Long to multiply with this.
- * @return {Long} the product of this and the other.
- * @api public
- */
-Long.prototype.multiply = function(other) {
- if (this.isZero()) {
- return Long.ZERO;
- } else if (other.isZero()) {
- return Long.ZERO;
- }
-
- if (this.equals(Long.MIN_VALUE)) {
- return other.isOdd() ? Long.MIN_VALUE : Long.ZERO;
- } else if (other.equals(Long.MIN_VALUE)) {
- return this.isOdd() ? Long.MIN_VALUE : Long.ZERO;
- }
-
- if (this.isNegative()) {
- if (other.isNegative()) {
- return this.negate().multiply(other.negate());
- } else {
- return this.negate().multiply(other).negate();
- }
- } else if (other.isNegative()) {
- return this.multiply(other.negate()).negate();
- }
-
- // If both Longs are small, use float multiplication
- if (this.lessThan(Long.TWO_PWR_24_) &&
- other.lessThan(Long.TWO_PWR_24_)) {
- return Long.fromNumber(this.toNumber() * other.toNumber());
- }
-
- // Divide each Long into 4 chunks of 16 bits, and then add up 4x4 products.
- // We can skip products that would overflow.
-
- var a48 = this.high_ >>> 16;
- var a32 = this.high_ & 0xFFFF;
- var a16 = this.low_ >>> 16;
- var a00 = this.low_ & 0xFFFF;
-
- var b48 = other.high_ >>> 16;
- var b32 = other.high_ & 0xFFFF;
- var b16 = other.low_ >>> 16;
- var b00 = other.low_ & 0xFFFF;
-
- var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
- c00 += a00 * b00;
- c16 += c00 >>> 16;
- c00 &= 0xFFFF;
- c16 += a16 * b00;
- c32 += c16 >>> 16;
- c16 &= 0xFFFF;
- c16 += a00 * b16;
- c32 += c16 >>> 16;
- c16 &= 0xFFFF;
- c32 += a32 * b00;
- c48 += c32 >>> 16;
- c32 &= 0xFFFF;
- c32 += a16 * b16;
- c48 += c32 >>> 16;
- c32 &= 0xFFFF;
- c32 += a00 * b32;
- c48 += c32 >>> 16;
- c32 &= 0xFFFF;
- c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
- c48 &= 0xFFFF;
- return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32);
-};
-
-/**
- * Returns this Long divided by the given one.
- *
- * @param {Long} other Long by which to divide.
- * @return {Long} this Long divided by the given one.
- * @api public
- */
-Long.prototype.div = function(other) {
- if (other.isZero()) {
- throw Error('division by zero');
- } else if (this.isZero()) {
- return Long.ZERO;
- }
-
- if (this.equals(Long.MIN_VALUE)) {
- if (other.equals(Long.ONE) ||
- other.equals(Long.NEG_ONE)) {
- return Long.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE
- } else if (other.equals(Long.MIN_VALUE)) {
- return Long.ONE;
- } else {
- // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|.
- var halfThis = this.shiftRight(1);
- var approx = halfThis.div(other).shiftLeft(1);
- if (approx.equals(Long.ZERO)) {
- return other.isNegative() ? Long.ONE : Long.NEG_ONE;
- } else {
- var rem = this.subtract(other.multiply(approx));
- var result = approx.add(rem.div(other));
- return result;
- }
- }
- } else if (other.equals(Long.MIN_VALUE)) {
- return Long.ZERO;
- }
-
- if (this.isNegative()) {
- if (other.isNegative()) {
- return this.negate().div(other.negate());
- } else {
- return this.negate().div(other).negate();
- }
- } else if (other.isNegative()) {
- return this.div(other.negate()).negate();
- }
-
- // Repeat the following until the remainder is less than other: find a
- // floating-point that approximates remainder / other *from below*, add this
- // into the result, and subtract it from the remainder. It is critical that
- // the approximate value is less than or equal to the real value so that the
- // remainder never becomes negative.
- var res = Long.ZERO;
- var rem = this;
- while (rem.greaterThanOrEqual(other)) {
- // Approximate the result of division. This may be a little greater or
- // smaller than the actual value.
- var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber()));
-
- // We will tweak the approximate result by changing it in the 48-th digit or
- // the smallest non-fractional digit, whichever is larger.
- var log2 = Math.ceil(Math.log(approx) / Math.LN2);
- var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48);
-
- // Decrease the approximation until it is smaller than the remainder. Note
- // that if it is too large, the product overflows and is negative.
- var approxRes = Long.fromNumber(approx);
- var approxRem = approxRes.multiply(other);
- while (approxRem.isNegative() || approxRem.greaterThan(rem)) {
- approx -= delta;
- approxRes = Long.fromNumber(approx);
- approxRem = approxRes.multiply(other);
- }
-
- // We know the answer can't be zero... and actually, zero would cause
- // infinite recursion since we would make no progress.
- if (approxRes.isZero()) {
- approxRes = Long.ONE;
- }
-
- res = res.add(approxRes);
- rem = rem.subtract(approxRem);
- }
- return res;
-};
-
-/**
- * Returns this Long modulo the given one.
- *
- * @param {Long} other Long by which to mod.
- * @return {Long} this Long modulo the given one.
- * @api public
- */
-Long.prototype.modulo = function(other) {
- return this.subtract(this.div(other).multiply(other));
-};
-
-/**
- * The bitwise-NOT of this value.
- *
- * @return {Long} the bitwise-NOT of this value.
- * @api public
- */
-Long.prototype.not = function() {
- return Long.fromBits(~this.low_, ~this.high_);
-};
-
-/**
- * Returns the bitwise-AND of this Long and the given one.
- *
- * @param {Long} other the Long with which to AND.
- * @return {Long} the bitwise-AND of this and the other.
- * @api public
- */
-Long.prototype.and = function(other) {
- return Long.fromBits(this.low_ & other.low_, this.high_ & other.high_);
-};
-
-/**
- * Returns the bitwise-OR of this Long and the given one.
- *
- * @param {Long} other the Long with which to OR.
- * @return {Long} the bitwise-OR of this and the other.
- * @api public
- */
-Long.prototype.or = function(other) {
- return Long.fromBits(this.low_ | other.low_, this.high_ | other.high_);
-};
-
-/**
- * Returns the bitwise-XOR of this Long and the given one.
- *
- * @param {Long} other the Long with which to XOR.
- * @return {Long} the bitwise-XOR of this and the other.
- * @api public
- */
-Long.prototype.xor = function(other) {
- return Long.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_);
-};
-
-/**
- * Returns this Long with bits shifted to the left by the given amount.
- *
- * @param {Number} numBits the number of bits by which to shift.
- * @return {Long} this shifted to the left by the given amount.
- * @api public
- */
-Long.prototype.shiftLeft = function(numBits) {
- numBits &= 63;
- if (numBits == 0) {
- return this;
- } else {
- var low = this.low_;
- if (numBits < 32) {
- var high = this.high_;
- return Long.fromBits(
- low << numBits,
- (high << numBits) | (low >>> (32 - numBits)));
- } else {
- return Long.fromBits(0, low << (numBits - 32));
- }
- }
-};
-
-/**
- * Returns this Long with bits shifted to the right by the given amount.
- *
- * @param {Number} numBits the number of bits by which to shift.
- * @return {Long} this shifted to the right by the given amount.
- * @api public
- */
-Long.prototype.shiftRight = function(numBits) {
- numBits &= 63;
- if (numBits == 0) {
- return this;
- } else {
- var high = this.high_;
- if (numBits < 32) {
- var low = this.low_;
- return Long.fromBits(
- (low >>> numBits) | (high << (32 - numBits)),
- high >> numBits);
- } else {
- return Long.fromBits(
- high >> (numBits - 32),
- high >= 0 ? 0 : -1);
- }
- }
-};
-
-/**
- * Returns this Long with bits shifted to the right by the given amount, with the new top bits matching the current sign bit.
- *
- * @param {Number} numBits the number of bits by which to shift.
- * @return {Long} this shifted to the right by the given amount, with zeros placed into the new leading bits.
- * @api public
- */
-Long.prototype.shiftRightUnsigned = function(numBits) {
- numBits &= 63;
- if (numBits == 0) {
- return this;
- } else {
- var high = this.high_;
- if (numBits < 32) {
- var low = this.low_;
- return Long.fromBits(
- (low >>> numBits) | (high << (32 - numBits)),
- high >>> numBits);
- } else if (numBits == 32) {
- return Long.fromBits(high, 0);
- } else {
- return Long.fromBits(high >>> (numBits - 32), 0);
- }
- }
-};
-
-/**
- * Returns a Long representing the given (32-bit) integer value.
- *
- * @param {Number} value the 32-bit integer in question.
- * @return {Long} the corresponding Long value.
- * @api public
- */
-Long.fromInt = function(value) {
- if (-128 <= value && value < 128) {
- var cachedObj = Long.INT_CACHE_[value];
- if (cachedObj) {
- return cachedObj;
- }
- }
-
- var obj = new Long(value | 0, value < 0 ? -1 : 0);
- if (-128 <= value && value < 128) {
- Long.INT_CACHE_[value] = obj;
- }
- return obj;
-};
-
-/**
- * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned.
- *
- * @param {Number} value the number in question.
- * @return {Long} the corresponding Long value.
- * @api public
- */
-Long.fromNumber = function(value) {
- if (isNaN(value) || !isFinite(value)) {
- return Long.ZERO;
- } else if (value <= -Long.TWO_PWR_63_DBL_) {
- return Long.MIN_VALUE;
- } else if (value + 1 >= Long.TWO_PWR_63_DBL_) {
- return Long.MAX_VALUE;
- } else if (value < 0) {
- return Long.fromNumber(-value).negate();
- } else {
- return new Long(
- (value % Long.TWO_PWR_32_DBL_) | 0,
- (value / Long.TWO_PWR_32_DBL_) | 0);
- }
-};
-
-/**
- * Returns a Long representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits.
- *
- * @param {Number} lowBits the low 32-bits.
- * @param {Number} highBits the high 32-bits.
- * @return {Long} the corresponding Long value.
- * @api public
- */
-Long.fromBits = function(lowBits, highBits) {
- return new Long(lowBits, highBits);
-};
-
-/**
- * Returns a Long representation of the given string, written using the given radix.
- *
- * @param {String} str the textual representation of the Long.
- * @param {Number} opt_radix the radix in which the text is written.
- * @return {Long} the corresponding Long value.
- * @api public
- */
-Long.fromString = function(str, opt_radix) {
- if (str.length == 0) {
- throw Error('number format error: empty string');
- }
-
- var radix = opt_radix || 10;
- if (radix < 2 || 36 < radix) {
- throw Error('radix out of range: ' + radix);
- }
-
- if (str.charAt(0) == '-') {
- return Long.fromString(str.substring(1), radix).negate();
- } else if (str.indexOf('-') >= 0) {
- throw Error('number format error: interior "-" character: ' + str);
- }
-
- // Do several (8) digits each time through the loop, so as to
- // minimize the calls to the very expensive emulated div.
- var radixToPower = Long.fromNumber(Math.pow(radix, 8));
-
- var result = Long.ZERO;
- for (var i = 0; i < str.length; i += 8) {
- var size = Math.min(8, str.length - i);
- var value = parseInt(str.substring(i, i + size), radix);
- if (size < 8) {
- var power = Long.fromNumber(Math.pow(radix, size));
- result = result.multiply(power).add(Long.fromNumber(value));
- } else {
- result = result.multiply(radixToPower);
- result = result.add(Long.fromNumber(value));
- }
- }
- return result;
-};
-
-// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the
-// from* methods on which they depend.
-
-
-/**
- * A cache of the Long representations of small integer values.
- * @type {Object}
- * @api private
- */
-Long.INT_CACHE_ = {};
-
-// NOTE: the compiler should inline these constant values below and then remove
-// these variables, so there should be no runtime penalty for these.
-
-/**
- * Number used repeated below in calculations. This must appear before the
- * first call to any from* function below.
- * @type {number}
- * @api private
- */
-Long.TWO_PWR_16_DBL_ = 1 << 16;
-
-/**
- * @type {number}
- * @api private
- */
-Long.TWO_PWR_24_DBL_ = 1 << 24;
-
-/**
- * @type {number}
- * @api private
- */
-Long.TWO_PWR_32_DBL_ = Long.TWO_PWR_16_DBL_ * Long.TWO_PWR_16_DBL_;
-
-/**
- * @type {number}
- * @api private
- */
-Long.TWO_PWR_31_DBL_ = Long.TWO_PWR_32_DBL_ / 2;
-
-/**
- * @type {number}
- * @api private
- */
-Long.TWO_PWR_48_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_16_DBL_;
-
-/**
- * @type {number}
- * @api private
- */
-Long.TWO_PWR_64_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_32_DBL_;
-
-/**
- * @type {number}
- * @api private
- */
-Long.TWO_PWR_63_DBL_ = Long.TWO_PWR_64_DBL_ / 2;
-
-/** @type {Long} */
-Long.ZERO = Long.fromInt(0);
-
-/** @type {Long} */
-Long.ONE = Long.fromInt(1);
-
-/** @type {Long} */
-Long.NEG_ONE = Long.fromInt(-1);
-
-/** @type {Long} */
-Long.MAX_VALUE =
- Long.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0);
-
-/** @type {Long} */
-Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0);
-
-/**
- * @type {Long}
- * @api private
- */
-Long.TWO_PWR_24_ = Long.fromInt(1 << 24);
-
-/**
- * Expose.
- */
-exports.Long = Long;
-},
-
-
-
-'max_key': function(module, exports, global, require, undefined){
- /**
- * A class representation of the BSON MaxKey type.
- *
- * @class Represents the BSON MaxKey type.
- * @return {MaxKey}
- */
-function MaxKey() {
- if(!(this instanceof MaxKey)) return new MaxKey();
-
- this._bsontype = 'MaxKey';
-}
-
-exports.MaxKey = MaxKey;
-},
-
-
-
-'min_key': function(module, exports, global, require, undefined){
- /**
- * A class representation of the BSON MinKey type.
- *
- * @class Represents the BSON MinKey type.
- * @return {MinKey}
- */
-function MinKey() {
- if(!(this instanceof MinKey)) return new MinKey();
-
- this._bsontype = 'MinKey';
-}
-
-exports.MinKey = MinKey;
-},
-
-
-
-'objectid': function(module, exports, global, require, undefined){
- /**
- * Module dependencies.
- */
-var BinaryParser = require('./binary_parser').BinaryParser;
-
-/**
- * Machine id.
- *
- * Create a random 3-byte value (i.e. unique for this
- * process). Other drivers use a md5 of the machine id here, but
- * that would mean an asyc call to gethostname, so we don't bother.
- */
-var MACHINE_ID = parseInt(Math.random() * 0xFFFFFF, 10);
-
-// Regular expression that checks for hex value
-var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$");
-
-/**
-* Create a new ObjectID instance
-*
-* @class Represents the BSON ObjectID type
-* @param {String|Number} id Can be a 24 byte hex string, 12 byte binary string or a Number.
-* @return {Object} instance of ObjectID.
-*/
-var ObjectID = function ObjectID(id, _hex) {
- if(!(this instanceof ObjectID)) return new ObjectID(id, _hex);
-
- this._bsontype = 'ObjectID';
- var __id = null;
-
- // Throw an error if it's not a valid setup
- if(id != null && 'number' != typeof id && (id.length != 12 && id.length != 24))
- throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters");
-
- // Generate id based on the input
- if(id == null || typeof id == 'number') {
- // convert to 12 byte binary string
- this.id = this.generate(id);
- } else if(id != null && id.length === 12) {
- // assume 12 byte string
- this.id = id;
- } else if(checkForHexRegExp.test(id)) {
- return ObjectID.createFromHexString(id);
- } else {
- throw new Error("Value passed in is not a valid 24 character hex string");
- }
-
- if(ObjectID.cacheHexString) this.__id = this.toHexString();
-};
-
-// Allow usage of ObjectId as well as ObjectID
-var ObjectId = ObjectID;
-
-// Precomputed hex table enables speedy hex string conversion
-var hexTable = [];
-for (var i = 0; i < 256; i++) {
- hexTable[i] = (i <= 15 ? '0' : '') + i.toString(16);
-}
-
-/**
-* Return the ObjectID id as a 24 byte hex string representation
-*
-* @return {String} return the 24 byte hex string representation.
-* @api public
-*/
-ObjectID.prototype.toHexString = function() {
- if(ObjectID.cacheHexString && this.__id) return this.__id;
-
- var hexString = '';
-
- for (var i = 0; i < this.id.length; i++) {
- hexString += hexTable[this.id.charCodeAt(i)];
- }
-
- if(ObjectID.cacheHexString) this.__id = hexString;
- return hexString;
-};
-
-/**
-* Update the ObjectID index used in generating new ObjectID's on the driver
-*
-* @return {Number} returns next index value.
-* @api private
-*/
-ObjectID.prototype.get_inc = function() {
- return ObjectID.index = (ObjectID.index + 1) % 0xFFFFFF;
-};
-
-/**
-* Update the ObjectID index used in generating new ObjectID's on the driver
-*
-* @return {Number} returns next index value.
-* @api private
-*/
-ObjectID.prototype.getInc = function() {
- return this.get_inc();
-};
-
-/**
-* Generate a 12 byte id string used in ObjectID's
-*
-* @param {Number} [time] optional parameter allowing to pass in a second based timestamp.
-* @return {String} return the 12 byte id binary string.
-* @api private
-*/
-ObjectID.prototype.generate = function(time) {
- if ('number' == typeof time) {
- var time4Bytes = BinaryParser.encodeInt(time, 32, true, true);
- /* for time-based ObjectID the bytes following the time will be zeroed */
- var machine3Bytes = BinaryParser.encodeInt(MACHINE_ID, 24, false);
- var pid2Bytes = BinaryParser.fromShort(typeof process === 'undefined' ? Math.floor(Math.random() * 100000) : process.pid);
- var index3Bytes = BinaryParser.encodeInt(this.get_inc(), 24, false, true);
- } else {
- var unixTime = parseInt(Date.now()/1000,10);
- var time4Bytes = BinaryParser.encodeInt(unixTime, 32, true, true);
- var machine3Bytes = BinaryParser.encodeInt(MACHINE_ID, 24, false);
- var pid2Bytes = BinaryParser.fromShort(typeof process === 'undefined' ? Math.floor(Math.random() * 100000) : process.pid);
- var index3Bytes = BinaryParser.encodeInt(this.get_inc(), 24, false, true);
- }
-
- return time4Bytes + machine3Bytes + pid2Bytes + index3Bytes;
-};
-
-/**
-* Converts the id into a 24 byte hex string for printing
-*
-* @return {String} return the 24 byte hex string representation.
-* @api private
-*/
-ObjectID.prototype.toString = function() {
- return this.toHexString();
-};
-
-/**
-* Converts to a string representation of this Id.
-*
-* @return {String} return the 24 byte hex string representation.
-* @api private
-*/
-ObjectID.prototype.inspect = ObjectID.prototype.toString;
-
-/**
-* Converts to its JSON representation.
-*
-* @return {String} return the 24 byte hex string representation.
-* @api private
-*/
-ObjectID.prototype.toJSON = function() {
- return this.toHexString();
-};
-
-/**
-* Compares the equality of this ObjectID with `otherID`.
-*
-* @param {Object} otherID ObjectID instance to compare against.
-* @return {Bool} the result of comparing two ObjectID's
-* @api public
-*/
-ObjectID.prototype.equals = function equals (otherID) {
- var id = (otherID instanceof ObjectID || otherID.toHexString)
- ? otherID.id
- : ObjectID.createFromHexString(otherID).id;
-
- return this.id === id;
-}
-
-/**
-* Returns the generation date (accurate up to the second) that this ID was generated.
-*
-* @return {Date} the generation date
-* @api public
-*/
-ObjectID.prototype.getTimestamp = function() {
- var timestamp = new Date();
- timestamp.setTime(Math.floor(BinaryParser.decodeInt(this.id.substring(0,4), 32, true, true)) * 1000);
- return timestamp;
-}
-
-/**
-* @ignore
-* @api private
-*/
-ObjectID.index = parseInt(Math.random() * 0xFFFFFF, 10);
-
-ObjectID.createPk = function createPk () {
- return new ObjectID();
-};
-
-/**
-* Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID.
-*
-* @param {Number} time an integer number representing a number of seconds.
-* @return {ObjectID} return the created ObjectID
-* @api public
-*/
-ObjectID.createFromTime = function createFromTime (time) {
- var id = BinaryParser.encodeInt(time, 32, true, true) +
- BinaryParser.encodeInt(0, 64, true, true);
- return new ObjectID(id);
-};
-
-/**
-* Creates an ObjectID from a hex string representation of an ObjectID.
-*
-* @param {String} hexString create a ObjectID from a passed in 24 byte hexstring.
-* @return {ObjectID} return the created ObjectID
-* @api public
-*/
-ObjectID.createFromHexString = function createFromHexString (hexString) {
- // Throw an error if it's not a valid setup
- if(typeof hexString === 'undefined' || hexString != null && hexString.length != 24)
- throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters");
-
- var len = hexString.length;
-
- if(len > 12*2) {
- throw new Error('Id cannot be longer than 12 bytes');
- }
-
- var result = ''
- , string
- , number;
-
- for (var index = 0; index < len; index += 2) {
- string = hexString.substr(index, 2);
- number = parseInt(string, 16);
- result += BinaryParser.fromByte(number);
- }
-
- return new ObjectID(result, hexString);
-};
-
-/**
-* @ignore
-*/
-Object.defineProperty(ObjectID.prototype, "generationTime", {
- enumerable: true
- , get: function () {
- return Math.floor(BinaryParser.decodeInt(this.id.substring(0,4), 32, true, true));
- }
- , set: function (value) {
- var value = BinaryParser.encodeInt(value, 32, true, true);
- this.id = value + this.id.substr(4);
- // delete this.__id;
- this.toHexString();
- }
-});
-
-/**
- * Expose.
- */
-exports.ObjectID = ObjectID;
-exports.ObjectId = ObjectID;
-
-},
-
-
-
-'symbol': function(module, exports, global, require, undefined){
- /**
- * A class representation of the BSON Symbol type.
- *
- * @class Represents the BSON Symbol type.
- * @param {String} value the string representing the symbol.
- * @return {Symbol}
- */
-function Symbol(value) {
- if(!(this instanceof Symbol)) return new Symbol(value);
- this._bsontype = 'Symbol';
- this.value = value;
-}
-
-/**
- * Access the wrapped string value.
- *
- * @return {String} returns the wrapped string.
- * @api public
- */
-Symbol.prototype.valueOf = function() {
- return this.value;
-};
-
-/**
- * @ignore
- * @api private
- */
-Symbol.prototype.toString = function() {
- return this.value;
-}
-
-/**
- * @ignore
- * @api private
- */
-Symbol.prototype.inspect = function() {
- return this.value;
-}
-
-/**
- * @ignore
- * @api private
- */
-Symbol.prototype.toJSON = function() {
- return this.value;
-}
-
-exports.Symbol = Symbol;
-},
-
-
-
-'timestamp': function(module, exports, global, require, undefined){
- // Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-// Copyright 2009 Google Inc. All Rights Reserved
-
-/**
- * Defines a Timestamp class for representing a 64-bit two's-complement
- * integer value, which faithfully simulates the behavior of a Java "Timestamp". This
- * implementation is derived from TimestampLib in GWT.
- *
- * Constructs a 64-bit two's-complement integer, given its low and high 32-bit
- * values as *signed* integers. See the from* functions below for more
- * convenient ways of constructing Timestamps.
- *
- * The internal representation of a Timestamp is the two given signed, 32-bit values.
- * We use 32-bit pieces because these are the size of integers on which
- * Javascript performs bit-operations. For operations like addition and
- * multiplication, we split each number into 16-bit pieces, which can easily be
- * multiplied within Javascript's floating-point representation without overflow
- * or change in sign.
- *
- * In the algorithms below, we frequently reduce the negative case to the
- * positive case by negating the input(s) and then post-processing the result.
- * Note that we must ALWAYS check specially whether those values are MIN_VALUE
- * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as
- * a positive number, it overflows back into a negative). Not handling this
- * case would often result in infinite recursion.
- *
- * @class Represents the BSON Timestamp type.
- * @param {Number} low the low (signed) 32 bits of the Timestamp.
- * @param {Number} high the high (signed) 32 bits of the Timestamp.
- */
-function Timestamp(low, high) {
- if(!(this instanceof Timestamp)) return new Timestamp(low, high);
- this._bsontype = 'Timestamp';
- /**
- * @type {number}
- * @api private
- */
- this.low_ = low | 0; // force into 32 signed bits.
-
- /**
- * @type {number}
- * @api private
- */
- this.high_ = high | 0; // force into 32 signed bits.
-};
-
-/**
- * Return the int value.
- *
- * @return {Number} the value, assuming it is a 32-bit integer.
- * @api public
- */
-Timestamp.prototype.toInt = function() {
- return this.low_;
-};
-
-/**
- * Return the Number value.
- *
- * @return {Number} the closest floating-point representation to this value.
- * @api public
- */
-Timestamp.prototype.toNumber = function() {
- return this.high_ * Timestamp.TWO_PWR_32_DBL_ +
- this.getLowBitsUnsigned();
-};
-
-/**
- * Return the JSON value.
- *
- * @return {String} the JSON representation.
- * @api public
- */
-Timestamp.prototype.toJSON = function() {
- return this.toString();
-}
-
-/**
- * Return the String value.
- *
- * @param {Number} [opt_radix] the radix in which the text should be written.
- * @return {String} the textual representation of this value.
- * @api public
- */
-Timestamp.prototype.toString = function(opt_radix) {
- var radix = opt_radix || 10;
- if (radix < 2 || 36 < radix) {
- throw Error('radix out of range: ' + radix);
- }
-
- if (this.isZero()) {
- return '0';
- }
-
- if (this.isNegative()) {
- if (this.equals(Timestamp.MIN_VALUE)) {
- // We need to change the Timestamp value before it can be negated, so we remove
- // the bottom-most digit in this base and then recurse to do the rest.
- var radixTimestamp = Timestamp.fromNumber(radix);
- var div = this.div(radixTimestamp);
- var rem = div.multiply(radixTimestamp).subtract(this);
- return div.toString(radix) + rem.toInt().toString(radix);
- } else {
- return '-' + this.negate().toString(radix);
- }
- }
-
- // Do several (6) digits each time through the loop, so as to
- // minimize the calls to the very expensive emulated div.
- var radixToPower = Timestamp.fromNumber(Math.pow(radix, 6));
-
- var rem = this;
- var result = '';
- while (true) {
- var remDiv = rem.div(radixToPower);
- var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt();
- var digits = intval.toString(radix);
-
- rem = remDiv;
- if (rem.isZero()) {
- return digits + result;
- } else {
- while (digits.length < 6) {
- digits = '0' + digits;
- }
- result = '' + digits + result;
- }
- }
-};
-
-/**
- * Return the high 32-bits value.
- *
- * @return {Number} the high 32-bits as a signed value.
- * @api public
- */
-Timestamp.prototype.getHighBits = function() {
- return this.high_;
-};
-
-/**
- * Return the low 32-bits value.
- *
- * @return {Number} the low 32-bits as a signed value.
- * @api public
- */
-Timestamp.prototype.getLowBits = function() {
- return this.low_;
-};
-
-/**
- * Return the low unsigned 32-bits value.
- *
- * @return {Number} the low 32-bits as an unsigned value.
- * @api public
- */
-Timestamp.prototype.getLowBitsUnsigned = function() {
- return (this.low_ >= 0) ?
- this.low_ : Timestamp.TWO_PWR_32_DBL_ + this.low_;
-};
-
-/**
- * Returns the number of bits needed to represent the absolute value of this Timestamp.
- *
- * @return {Number} Returns the number of bits needed to represent the absolute value of this Timestamp.
- * @api public
- */
-Timestamp.prototype.getNumBitsAbs = function() {
- if (this.isNegative()) {
- if (this.equals(Timestamp.MIN_VALUE)) {
- return 64;
- } else {
- return this.negate().getNumBitsAbs();
- }
- } else {
- var val = this.high_ != 0 ? this.high_ : this.low_;
- for (var bit = 31; bit > 0; bit--) {
- if ((val & (1 << bit)) != 0) {
- break;
- }
- }
- return this.high_ != 0 ? bit + 33 : bit + 1;
- }
-};
-
-/**
- * Return whether this value is zero.
- *
- * @return {Boolean} whether this value is zero.
- * @api public
- */
-Timestamp.prototype.isZero = function() {
- return this.high_ == 0 && this.low_ == 0;
-};
-
-/**
- * Return whether this value is negative.
- *
- * @return {Boolean} whether this value is negative.
- * @api public
- */
-Timestamp.prototype.isNegative = function() {
- return this.high_ < 0;
-};
-
-/**
- * Return whether this value is odd.
- *
- * @return {Boolean} whether this value is odd.
- * @api public
- */
-Timestamp.prototype.isOdd = function() {
- return (this.low_ & 1) == 1;
-};
-
-/**
- * Return whether this Timestamp equals the other
- *
- * @param {Timestamp} other Timestamp to compare against.
- * @return {Boolean} whether this Timestamp equals the other
- * @api public
- */
-Timestamp.prototype.equals = function(other) {
- return (this.high_ == other.high_) && (this.low_ == other.low_);
-};
-
-/**
- * Return whether this Timestamp does not equal the other.
- *
- * @param {Timestamp} other Timestamp to compare against.
- * @return {Boolean} whether this Timestamp does not equal the other.
- * @api public
- */
-Timestamp.prototype.notEquals = function(other) {
- return (this.high_ != other.high_) || (this.low_ != other.low_);
-};
-
-/**
- * Return whether this Timestamp is less than the other.
- *
- * @param {Timestamp} other Timestamp to compare against.
- * @return {Boolean} whether this Timestamp is less than the other.
- * @api public
- */
-Timestamp.prototype.lessThan = function(other) {
- return this.compare(other) < 0;
-};
-
-/**
- * Return whether this Timestamp is less than or equal to the other.
- *
- * @param {Timestamp} other Timestamp to compare against.
- * @return {Boolean} whether this Timestamp is less than or equal to the other.
- * @api public
- */
-Timestamp.prototype.lessThanOrEqual = function(other) {
- return this.compare(other) <= 0;
-};
-
-/**
- * Return whether this Timestamp is greater than the other.
- *
- * @param {Timestamp} other Timestamp to compare against.
- * @return {Boolean} whether this Timestamp is greater than the other.
- * @api public
- */
-Timestamp.prototype.greaterThan = function(other) {
- return this.compare(other) > 0;
-};
-
-/**
- * Return whether this Timestamp is greater than or equal to the other.
- *
- * @param {Timestamp} other Timestamp to compare against.
- * @return {Boolean} whether this Timestamp is greater than or equal to the other.
- * @api public
- */
-Timestamp.prototype.greaterThanOrEqual = function(other) {
- return this.compare(other) >= 0;
-};
-
-/**
- * Compares this Timestamp with the given one.
- *
- * @param {Timestamp} other Timestamp to compare against.
- * @return {Boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater.
- * @api public
- */
-Timestamp.prototype.compare = function(other) {
- if (this.equals(other)) {
- return 0;
- }
-
- var thisNeg = this.isNegative();
- var otherNeg = other.isNegative();
- if (thisNeg && !otherNeg) {
- return -1;
- }
- if (!thisNeg && otherNeg) {
- return 1;
- }
-
- // at this point, the signs are the same, so subtraction will not overflow
- if (this.subtract(other).isNegative()) {
- return -1;
- } else {
- return 1;
- }
-};
-
-/**
- * The negation of this value.
- *
- * @return {Timestamp} the negation of this value.
- * @api public
- */
-Timestamp.prototype.negate = function() {
- if (this.equals(Timestamp.MIN_VALUE)) {
- return Timestamp.MIN_VALUE;
- } else {
- return this.not().add(Timestamp.ONE);
- }
-};
-
-/**
- * Returns the sum of this and the given Timestamp.
- *
- * @param {Timestamp} other Timestamp to add to this one.
- * @return {Timestamp} the sum of this and the given Timestamp.
- * @api public
- */
-Timestamp.prototype.add = function(other) {
- // Divide each number into 4 chunks of 16 bits, and then sum the chunks.
-
- var a48 = this.high_ >>> 16;
- var a32 = this.high_ & 0xFFFF;
- var a16 = this.low_ >>> 16;
- var a00 = this.low_ & 0xFFFF;
-
- var b48 = other.high_ >>> 16;
- var b32 = other.high_ & 0xFFFF;
- var b16 = other.low_ >>> 16;
- var b00 = other.low_ & 0xFFFF;
-
- var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
- c00 += a00 + b00;
- c16 += c00 >>> 16;
- c00 &= 0xFFFF;
- c16 += a16 + b16;
- c32 += c16 >>> 16;
- c16 &= 0xFFFF;
- c32 += a32 + b32;
- c48 += c32 >>> 16;
- c32 &= 0xFFFF;
- c48 += a48 + b48;
- c48 &= 0xFFFF;
- return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32);
-};
-
-/**
- * Returns the difference of this and the given Timestamp.
- *
- * @param {Timestamp} other Timestamp to subtract from this.
- * @return {Timestamp} the difference of this and the given Timestamp.
- * @api public
- */
-Timestamp.prototype.subtract = function(other) {
- return this.add(other.negate());
-};
-
-/**
- * Returns the product of this and the given Timestamp.
- *
- * @param {Timestamp} other Timestamp to multiply with this.
- * @return {Timestamp} the product of this and the other.
- * @api public
- */
-Timestamp.prototype.multiply = function(other) {
- if (this.isZero()) {
- return Timestamp.ZERO;
- } else if (other.isZero()) {
- return Timestamp.ZERO;
- }
-
- if (this.equals(Timestamp.MIN_VALUE)) {
- return other.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO;
- } else if (other.equals(Timestamp.MIN_VALUE)) {
- return this.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO;
- }
-
- if (this.isNegative()) {
- if (other.isNegative()) {
- return this.negate().multiply(other.negate());
- } else {
- return this.negate().multiply(other).negate();
- }
- } else if (other.isNegative()) {
- return this.multiply(other.negate()).negate();
- }
-
- // If both Timestamps are small, use float multiplication
- if (this.lessThan(Timestamp.TWO_PWR_24_) &&
- other.lessThan(Timestamp.TWO_PWR_24_)) {
- return Timestamp.fromNumber(this.toNumber() * other.toNumber());
- }
-
- // Divide each Timestamp into 4 chunks of 16 bits, and then add up 4x4 products.
- // We can skip products that would overflow.
-
- var a48 = this.high_ >>> 16;
- var a32 = this.high_ & 0xFFFF;
- var a16 = this.low_ >>> 16;
- var a00 = this.low_ & 0xFFFF;
-
- var b48 = other.high_ >>> 16;
- var b32 = other.high_ & 0xFFFF;
- var b16 = other.low_ >>> 16;
- var b00 = other.low_ & 0xFFFF;
-
- var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
- c00 += a00 * b00;
- c16 += c00 >>> 16;
- c00 &= 0xFFFF;
- c16 += a16 * b00;
- c32 += c16 >>> 16;
- c16 &= 0xFFFF;
- c16 += a00 * b16;
- c32 += c16 >>> 16;
- c16 &= 0xFFFF;
- c32 += a32 * b00;
- c48 += c32 >>> 16;
- c32 &= 0xFFFF;
- c32 += a16 * b16;
- c48 += c32 >>> 16;
- c32 &= 0xFFFF;
- c32 += a00 * b32;
- c48 += c32 >>> 16;
- c32 &= 0xFFFF;
- c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
- c48 &= 0xFFFF;
- return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32);
-};
-
-/**
- * Returns this Timestamp divided by the given one.
- *
- * @param {Timestamp} other Timestamp by which to divide.
- * @return {Timestamp} this Timestamp divided by the given one.
- * @api public
- */
-Timestamp.prototype.div = function(other) {
- if (other.isZero()) {
- throw Error('division by zero');
- } else if (this.isZero()) {
- return Timestamp.ZERO;
- }
-
- if (this.equals(Timestamp.MIN_VALUE)) {
- if (other.equals(Timestamp.ONE) ||
- other.equals(Timestamp.NEG_ONE)) {
- return Timestamp.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE
- } else if (other.equals(Timestamp.MIN_VALUE)) {
- return Timestamp.ONE;
- } else {
- // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|.
- var halfThis = this.shiftRight(1);
- var approx = halfThis.div(other).shiftLeft(1);
- if (approx.equals(Timestamp.ZERO)) {
- return other.isNegative() ? Timestamp.ONE : Timestamp.NEG_ONE;
- } else {
- var rem = this.subtract(other.multiply(approx));
- var result = approx.add(rem.div(other));
- return result;
- }
- }
- } else if (other.equals(Timestamp.MIN_VALUE)) {
- return Timestamp.ZERO;
- }
-
- if (this.isNegative()) {
- if (other.isNegative()) {
- return this.negate().div(other.negate());
- } else {
- return this.negate().div(other).negate();
- }
- } else if (other.isNegative()) {
- return this.div(other.negate()).negate();
- }
-
- // Repeat the following until the remainder is less than other: find a
- // floating-point that approximates remainder / other *from below*, add this
- // into the result, and subtract it from the remainder. It is critical that
- // the approximate value is less than or equal to the real value so that the
- // remainder never becomes negative.
- var res = Timestamp.ZERO;
- var rem = this;
- while (rem.greaterThanOrEqual(other)) {
- // Approximate the result of division. This may be a little greater or
- // smaller than the actual value.
- var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber()));
-
- // We will tweak the approximate result by changing it in the 48-th digit or
- // the smallest non-fractional digit, whichever is larger.
- var log2 = Math.ceil(Math.log(approx) / Math.LN2);
- var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48);
-
- // Decrease the approximation until it is smaller than the remainder. Note
- // that if it is too large, the product overflows and is negative.
- var approxRes = Timestamp.fromNumber(approx);
- var approxRem = approxRes.multiply(other);
- while (approxRem.isNegative() || approxRem.greaterThan(rem)) {
- approx -= delta;
- approxRes = Timestamp.fromNumber(approx);
- approxRem = approxRes.multiply(other);
- }
-
- // We know the answer can't be zero... and actually, zero would cause
- // infinite recursion since we would make no progress.
- if (approxRes.isZero()) {
- approxRes = Timestamp.ONE;
- }
-
- res = res.add(approxRes);
- rem = rem.subtract(approxRem);
- }
- return res;
-};
-
-/**
- * Returns this Timestamp modulo the given one.
- *
- * @param {Timestamp} other Timestamp by which to mod.
- * @return {Timestamp} this Timestamp modulo the given one.
- * @api public
- */
-Timestamp.prototype.modulo = function(other) {
- return this.subtract(this.div(other).multiply(other));
-};
-
-/**
- * The bitwise-NOT of this value.
- *
- * @return {Timestamp} the bitwise-NOT of this value.
- * @api public
- */
-Timestamp.prototype.not = function() {
- return Timestamp.fromBits(~this.low_, ~this.high_);
-};
-
-/**
- * Returns the bitwise-AND of this Timestamp and the given one.
- *
- * @param {Timestamp} other the Timestamp with which to AND.
- * @return {Timestamp} the bitwise-AND of this and the other.
- * @api public
- */
-Timestamp.prototype.and = function(other) {
- return Timestamp.fromBits(this.low_ & other.low_, this.high_ & other.high_);
-};
-
-/**
- * Returns the bitwise-OR of this Timestamp and the given one.
- *
- * @param {Timestamp} other the Timestamp with which to OR.
- * @return {Timestamp} the bitwise-OR of this and the other.
- * @api public
- */
-Timestamp.prototype.or = function(other) {
- return Timestamp.fromBits(this.low_ | other.low_, this.high_ | other.high_);
-};
-
-/**
- * Returns the bitwise-XOR of this Timestamp and the given one.
- *
- * @param {Timestamp} other the Timestamp with which to XOR.
- * @return {Timestamp} the bitwise-XOR of this and the other.
- * @api public
- */
-Timestamp.prototype.xor = function(other) {
- return Timestamp.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_);
-};
-
-/**
- * Returns this Timestamp with bits shifted to the left by the given amount.
- *
- * @param {Number} numBits the number of bits by which to shift.
- * @return {Timestamp} this shifted to the left by the given amount.
- * @api public
- */
-Timestamp.prototype.shiftLeft = function(numBits) {
- numBits &= 63;
- if (numBits == 0) {
- return this;
- } else {
- var low = this.low_;
- if (numBits < 32) {
- var high = this.high_;
- return Timestamp.fromBits(
- low << numBits,
- (high << numBits) | (low >>> (32 - numBits)));
- } else {
- return Timestamp.fromBits(0, low << (numBits - 32));
- }
- }
-};
-
-/**
- * Returns this Timestamp with bits shifted to the right by the given amount.
- *
- * @param {Number} numBits the number of bits by which to shift.
- * @return {Timestamp} this shifted to the right by the given amount.
- * @api public
- */
-Timestamp.prototype.shiftRight = function(numBits) {
- numBits &= 63;
- if (numBits == 0) {
- return this;
- } else {
- var high = this.high_;
- if (numBits < 32) {
- var low = this.low_;
- return Timestamp.fromBits(
- (low >>> numBits) | (high << (32 - numBits)),
- high >> numBits);
- } else {
- return Timestamp.fromBits(
- high >> (numBits - 32),
- high >= 0 ? 0 : -1);
- }
- }
-};
-
-/**
- * Returns this Timestamp with bits shifted to the right by the given amount, with the new top bits matching the current sign bit.
- *
- * @param {Number} numBits the number of bits by which to shift.
- * @return {Timestamp} this shifted to the right by the given amount, with zeros placed into the new leading bits.
- * @api public
- */
-Timestamp.prototype.shiftRightUnsigned = function(numBits) {
- numBits &= 63;
- if (numBits == 0) {
- return this;
- } else {
- var high = this.high_;
- if (numBits < 32) {
- var low = this.low_;
- return Timestamp.fromBits(
- (low >>> numBits) | (high << (32 - numBits)),
- high >>> numBits);
- } else if (numBits == 32) {
- return Timestamp.fromBits(high, 0);
- } else {
- return Timestamp.fromBits(high >>> (numBits - 32), 0);
- }
- }
-};
-
-/**
- * Returns a Timestamp representing the given (32-bit) integer value.
- *
- * @param {Number} value the 32-bit integer in question.
- * @return {Timestamp} the corresponding Timestamp value.
- * @api public
- */
-Timestamp.fromInt = function(value) {
- if (-128 <= value && value < 128) {
- var cachedObj = Timestamp.INT_CACHE_[value];
- if (cachedObj) {
- return cachedObj;
- }
- }
-
- var obj = new Timestamp(value | 0, value < 0 ? -1 : 0);
- if (-128 <= value && value < 128) {
- Timestamp.INT_CACHE_[value] = obj;
- }
- return obj;
-};
-
-/**
- * Returns a Timestamp representing the given value, provided that it is a finite number. Otherwise, zero is returned.
- *
- * @param {Number} value the number in question.
- * @return {Timestamp} the corresponding Timestamp value.
- * @api public
- */
-Timestamp.fromNumber = function(value) {
- if (isNaN(value) || !isFinite(value)) {
- return Timestamp.ZERO;
- } else if (value <= -Timestamp.TWO_PWR_63_DBL_) {
- return Timestamp.MIN_VALUE;
- } else if (value + 1 >= Timestamp.TWO_PWR_63_DBL_) {
- return Timestamp.MAX_VALUE;
- } else if (value < 0) {
- return Timestamp.fromNumber(-value).negate();
- } else {
- return new Timestamp(
- (value % Timestamp.TWO_PWR_32_DBL_) | 0,
- (value / Timestamp.TWO_PWR_32_DBL_) | 0);
- }
-};
-
-/**
- * Returns a Timestamp representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits.
- *
- * @param {Number} lowBits the low 32-bits.
- * @param {Number} highBits the high 32-bits.
- * @return {Timestamp} the corresponding Timestamp value.
- * @api public
- */
-Timestamp.fromBits = function(lowBits, highBits) {
- return new Timestamp(lowBits, highBits);
-};
-
-/**
- * Returns a Timestamp representation of the given string, written using the given radix.
- *
- * @param {String} str the textual representation of the Timestamp.
- * @param {Number} opt_radix the radix in which the text is written.
- * @return {Timestamp} the corresponding Timestamp value.
- * @api public
- */
-Timestamp.fromString = function(str, opt_radix) {
- if (str.length == 0) {
- throw Error('number format error: empty string');
- }
-
- var radix = opt_radix || 10;
- if (radix < 2 || 36 < radix) {
- throw Error('radix out of range: ' + radix);
- }
-
- if (str.charAt(0) == '-') {
- return Timestamp.fromString(str.substring(1), radix).negate();
- } else if (str.indexOf('-') >= 0) {
- throw Error('number format error: interior "-" character: ' + str);
- }
-
- // Do several (8) digits each time through the loop, so as to
- // minimize the calls to the very expensive emulated div.
- var radixToPower = Timestamp.fromNumber(Math.pow(radix, 8));
-
- var result = Timestamp.ZERO;
- for (var i = 0; i < str.length; i += 8) {
- var size = Math.min(8, str.length - i);
- var value = parseInt(str.substring(i, i + size), radix);
- if (size < 8) {
- var power = Timestamp.fromNumber(Math.pow(radix, size));
- result = result.multiply(power).add(Timestamp.fromNumber(value));
- } else {
- result = result.multiply(radixToPower);
- result = result.add(Timestamp.fromNumber(value));
- }
- }
- return result;
-};
-
-// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the
-// from* methods on which they depend.
-
-
-/**
- * A cache of the Timestamp representations of small integer values.
- * @type {Object}
- * @api private
- */
-Timestamp.INT_CACHE_ = {};
-
-// NOTE: the compiler should inline these constant values below and then remove
-// these variables, so there should be no runtime penalty for these.
-
-/**
- * Number used repeated below in calculations. This must appear before the
- * first call to any from* function below.
- * @type {number}
- * @api private
- */
-Timestamp.TWO_PWR_16_DBL_ = 1 << 16;
-
-/**
- * @type {number}
- * @api private
- */
-Timestamp.TWO_PWR_24_DBL_ = 1 << 24;
-
-/**
- * @type {number}
- * @api private
- */
-Timestamp.TWO_PWR_32_DBL_ = Timestamp.TWO_PWR_16_DBL_ * Timestamp.TWO_PWR_16_DBL_;
-
-/**
- * @type {number}
- * @api private
- */
-Timestamp.TWO_PWR_31_DBL_ = Timestamp.TWO_PWR_32_DBL_ / 2;
-
-/**
- * @type {number}
- * @api private
- */
-Timestamp.TWO_PWR_48_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_16_DBL_;
-
-/**
- * @type {number}
- * @api private
- */
-Timestamp.TWO_PWR_64_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_32_DBL_;
-
-/**
- * @type {number}
- * @api private
- */
-Timestamp.TWO_PWR_63_DBL_ = Timestamp.TWO_PWR_64_DBL_ / 2;
-
-/** @type {Timestamp} */
-Timestamp.ZERO = Timestamp.fromInt(0);
-
-/** @type {Timestamp} */
-Timestamp.ONE = Timestamp.fromInt(1);
-
-/** @type {Timestamp} */
-Timestamp.NEG_ONE = Timestamp.fromInt(-1);
-
-/** @type {Timestamp} */
-Timestamp.MAX_VALUE =
- Timestamp.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0);
-
-/** @type {Timestamp} */
-Timestamp.MIN_VALUE = Timestamp.fromBits(0, 0x80000000 | 0);
-
-/**
- * @type {Timestamp}
- * @api private
- */
-Timestamp.TWO_PWR_24_ = Timestamp.fromInt(1 << 24);
-
-/**
- * Expose.
- */
-exports.Timestamp = Timestamp;
-},
-
- });
-
-
-if(typeof module != 'undefined' && module.exports ){
- module.exports = bson;
-
- if( !module.parent ){
- bson();
- }
-}
-
-if(typeof window != 'undefined' && typeof require == 'undefined'){
- window.require = bson.require;
-}
diff --git a/node_modules/mongojs/node_modules/mongodb/node_modules/bson/browser_build/package.json b/node_modules/mongojs/node_modules/mongodb/node_modules/bson/browser_build/package.json
deleted file mode 100644
index 3ebb587..0000000
--- a/node_modules/mongojs/node_modules/mongodb/node_modules/bson/browser_build/package.json
+++ /dev/null
@@ -1,8 +0,0 @@
-{ "name" : "bson"
-, "description" : "A bson parser for node.js and the browser"
-, "main": "../lib/bson/bson"
-, "directories" : { "lib" : "../lib/bson" }
-, "engines" : { "node" : ">=0.6.0" }
-, "licenses" : [ { "type" : "Apache License, Version 2.0"
- , "url" : "http://www.apache.org/licenses/LICENSE-2.0" } ]
-}
diff --git a/node_modules/mongojs/node_modules/mongodb/node_modules/bson/build/Makefile b/node_modules/mongojs/node_modules/mongodb/node_modules/bson/build/Makefile
deleted file mode 100644
index f8e6836..0000000
--- a/node_modules/mongojs/node_modules/mongodb/node_modules/bson/build/Makefile
+++ /dev/null
@@ -1,350 +0,0 @@
-# We borrow heavily from the kernel build setup, though we are simpler since
-# we don't have Kconfig tweaking settings on us.
-
-# The implicit make rules have it looking for RCS files, among other things.
-# We instead explicitly write all the rules we care about.
-# It's even quicker (saves ~200ms) to pass -r on the command line.
-MAKEFLAGS=-r
-
-# The source directory tree.
-srcdir := ..
-abs_srcdir := $(abspath $(srcdir))
-
-# The name of the builddir.
-builddir_name ?= .
-
-# The V=1 flag on command line makes us verbosely print command lines.
-ifdef V
- quiet=
-else
- quiet=quiet_
-endif
-
-# Specify BUILDTYPE=Release on the command line for a release build.
-BUILDTYPE ?= Release
-
-# Directory all our build output goes into.
-# Note that this must be two directories beneath src/ for unit tests to pass,
-# as they reach into the src/ directory for data with relative paths.
-builddir ?= $(builddir_name)/$(BUILDTYPE)
-abs_builddir := $(abspath $(builddir))
-depsdir := $(builddir)/.deps
-
-# Object output directory.
-obj := $(builddir)/obj
-abs_obj := $(abspath $(obj))
-
-# We build up a list of every single one of the targets so we can slurp in the
-# generated dependency rule Makefiles in one pass.
-all_deps :=
-
-
-
-CC.target ?= $(CC)
-CFLAGS.target ?= $(CFLAGS)
-CXX.target ?= $(CXX)
-CXXFLAGS.target ?= $(CXXFLAGS)
-LINK.target ?= $(LINK)
-LDFLAGS.target ?= $(LDFLAGS)
-AR.target ?= $(AR)
-
-# C++ apps need to be linked with g++.
-#
-# Note: flock is used to seralize linking. Linking is a memory-intensive
-# process so running parallel links can often lead to thrashing. To disable
-# the serialization, override LINK via an envrionment variable as follows:
-#
-# export LINK=g++
-#
-# This will allow make to invoke N linker processes as specified in -jN.
-LINK ?= ./gyp-mac-tool flock $(builddir)/linker.lock $(CXX.target)
-
-# TODO(evan): move all cross-compilation logic to gyp-time so we don't need
-# to replicate this environment fallback in make as well.
-CC.host ?= gcc
-CFLAGS.host ?=
-CXX.host ?= g++
-CXXFLAGS.host ?=
-LINK.host ?= $(CXX.host)
-LDFLAGS.host ?=
-AR.host ?= ar
-
-# Define a dir function that can handle spaces.
-# http://www.gnu.org/software/make/manual/make.html#Syntax-of-Functions
-# "leading spaces cannot appear in the text of the first argument as written.
-# These characters can be put into the argument value by variable substitution."
-empty :=
-space := $(empty) $(empty)
-
-# http://stackoverflow.com/questions/1189781/using-make-dir-or-notdir-on-a-path-with-spaces
-replace_spaces = $(subst $(space),?,$1)
-unreplace_spaces = $(subst ?,$(space),$1)
-dirx = $(call unreplace_spaces,$(dir $(call replace_spaces,$1)))
-
-# Flags to make gcc output dependency info. Note that you need to be
-# careful here to use the flags that ccache and distcc can understand.
-# We write to a dep file on the side first and then rename at the end
-# so we can't end up with a broken dep file.
-depfile = $(depsdir)/$(call replace_spaces,$@).d
-DEPFLAGS = -MMD -MF $(depfile).raw
-
-# We have to fixup the deps output in a few ways.
-# (1) the file output should mention the proper .o file.
-# ccache or distcc lose the path to the target, so we convert a rule of
-# the form:
-# foobar.o: DEP1 DEP2
-# into
-# path/to/foobar.o: DEP1 DEP2
-# (2) we want missing files not to cause us to fail to build.
-# We want to rewrite
-# foobar.o: DEP1 DEP2 \
-# DEP3
-# to
-# DEP1:
-# DEP2:
-# DEP3:
-# so if the files are missing, they're just considered phony rules.
-# We have to do some pretty insane escaping to get those backslashes
-# and dollar signs past make, the shell, and sed at the same time.
-# Doesn't work with spaces, but that's fine: .d files have spaces in
-# their names replaced with other characters.
-define fixup_dep
-# The depfile may not exist if the input file didn't have any #includes.
-touch $(depfile).raw
-# Fixup path as in (1).
-sed -e "s|^$(notdir $@)|$@|" $(depfile).raw >> $(depfile)
-# Add extra rules as in (2).
-# We remove slashes and replace spaces with new lines;
-# remove blank lines;
-# delete the first line and append a colon to the remaining lines.
-sed -e 's|\\||' -e 'y| |\n|' $(depfile).raw |\
- grep -v '^$$' |\
- sed -e 1d -e 's|$$|:|' \
- >> $(depfile)
-rm $(depfile).raw
-endef
-
-# Command definitions:
-# - cmd_foo is the actual command to run;
-# - quiet_cmd_foo is the brief-output summary of the command.
-
-quiet_cmd_cc = CC($(TOOLSET)) $@
-cmd_cc = $(CC.$(TOOLSET)) $(GYP_CFLAGS) $(DEPFLAGS) $(CFLAGS.$(TOOLSET)) -c -o $@ $<
-
-quiet_cmd_cxx = CXX($(TOOLSET)) $@
-cmd_cxx = $(CXX.$(TOOLSET)) $(GYP_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $<
-
-quiet_cmd_objc = CXX($(TOOLSET)) $@
-cmd_objc = $(CC.$(TOOLSET)) $(GYP_OBJCFLAGS) $(DEPFLAGS) -c -o $@ $<
-
-quiet_cmd_objcxx = CXX($(TOOLSET)) $@
-cmd_objcxx = $(CXX.$(TOOLSET)) $(GYP_OBJCXXFLAGS) $(DEPFLAGS) -c -o $@ $<
-
-# Commands for precompiled header files.
-quiet_cmd_pch_c = CXX($(TOOLSET)) $@
-cmd_pch_c = $(CC.$(TOOLSET)) $(GYP_PCH_CFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $<
-quiet_cmd_pch_cc = CXX($(TOOLSET)) $@
-cmd_pch_cc = $(CC.$(TOOLSET)) $(GYP_PCH_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $<
-quiet_cmd_pch_m = CXX($(TOOLSET)) $@
-cmd_pch_m = $(CC.$(TOOLSET)) $(GYP_PCH_OBJCFLAGS) $(DEPFLAGS) -c -o $@ $<
-quiet_cmd_pch_mm = CXX($(TOOLSET)) $@
-cmd_pch_mm = $(CC.$(TOOLSET)) $(GYP_PCH_OBJCXXFLAGS) $(DEPFLAGS) -c -o $@ $<
-
-# gyp-mac-tool is written next to the root Makefile by gyp.
-# Use $(4) for the command, since $(2) and $(3) are used as flag by do_cmd
-# already.
-quiet_cmd_mac_tool = MACTOOL $(4) $<
-cmd_mac_tool = ./gyp-mac-tool $(4) $< "$@"
-
-quiet_cmd_mac_package_framework = PACKAGE FRAMEWORK $@
-cmd_mac_package_framework = ./gyp-mac-tool package-framework "$@" $(4)
-
-quiet_cmd_infoplist = INFOPLIST $@
-cmd_infoplist = $(CC.$(TOOLSET)) -E -P -Wno-trigraphs -x c $(INFOPLIST_DEFINES) "$<" -o "$@"
-
-quiet_cmd_touch = TOUCH $@
-cmd_touch = touch $@
-
-quiet_cmd_copy = COPY $@
-# send stderr to /dev/null to ignore messages when linking directories.
-cmd_copy = rm -rf "$@" && cp -af "$<" "$@"
-
-quiet_cmd_alink = LIBTOOL-STATIC $@
-cmd_alink = rm -f $@ && ./gyp-mac-tool filter-libtool libtool $(GYP_LIBTOOLFLAGS) -static -o $@ $(filter %.o,$^)
-
-quiet_cmd_link = LINK($(TOOLSET)) $@
-cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS)
-
-quiet_cmd_solink = SOLINK($(TOOLSET)) $@
-cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS)
-
-quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@
-cmd_solink_module = $(LINK.$(TOOLSET)) -bundle $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(filter-out FORCE_DO_CMD, $^) $(LIBS)
-
-
-# Define an escape_quotes function to escape single quotes.
-# This allows us to handle quotes properly as long as we always use
-# use single quotes and escape_quotes.
-escape_quotes = $(subst ','\'',$(1))
-# This comment is here just to include a ' to unconfuse syntax highlighting.
-# Define an escape_vars function to escape '$' variable syntax.
-# This allows us to read/write command lines with shell variables (e.g.
-# $LD_LIBRARY_PATH), without triggering make substitution.
-escape_vars = $(subst $$,$$$$,$(1))
-# Helper that expands to a shell command to echo a string exactly as it is in
-# make. This uses printf instead of echo because printf's behaviour with respect
-# to escape sequences is more portable than echo's across different shells
-# (e.g., dash, bash).
-exact_echo = printf '%s\n' '$(call escape_quotes,$(1))'
-
-# Helper to compare the command we're about to run against the command
-# we logged the last time we ran the command. Produces an empty
-# string (false) when the commands match.
-# Tricky point: Make has no string-equality test function.
-# The kernel uses the following, but it seems like it would have false
-# positives, where one string reordered its arguments.
-# arg_check = $(strip $(filter-out $(cmd_$(1)), $(cmd_$@)) \
-# $(filter-out $(cmd_$@), $(cmd_$(1))))
-# We instead substitute each for the empty string into the other, and
-# say they're equal if both substitutions produce the empty string.
-# .d files contain ? instead of spaces, take that into account.
-command_changed = $(or $(subst $(cmd_$(1)),,$(cmd_$(call replace_spaces,$@))),\
- $(subst $(cmd_$(call replace_spaces,$@)),,$(cmd_$(1))))
-
-# Helper that is non-empty when a prerequisite changes.
-# Normally make does this implicitly, but we force rules to always run
-# so we can check their command lines.
-# $? -- new prerequisites
-# $| -- order-only dependencies
-prereq_changed = $(filter-out FORCE_DO_CMD,$(filter-out $|,$?))
-
-# Helper that executes all postbuilds until one fails.
-define do_postbuilds
- @E=0;\
- for p in $(POSTBUILDS); do\
- eval $$p;\
- E=$$?;\
- if [ $$E -ne 0 ]; then\
- break;\
- fi;\
- done;\
- if [ $$E -ne 0 ]; then\
- rm -rf "$@";\
- exit $$E;\
- fi
-endef
-
-# do_cmd: run a command via the above cmd_foo names, if necessary.
-# Should always run for a given target to handle command-line changes.
-# Second argument, if non-zero, makes it do asm/C/C++ dependency munging.
-# Third argument, if non-zero, makes it do POSTBUILDS processing.
-# Note: We intentionally do NOT call dirx for depfile, since it contains ? for
-# spaces already and dirx strips the ? characters.
-define do_cmd
-$(if $(or $(command_changed),$(prereq_changed)),
- @$(call exact_echo, $($(quiet)cmd_$(1)))
- @mkdir -p "$(call dirx,$@)" "$(dir $(depfile))"
- $(if $(findstring flock,$(word 2,$(cmd_$1))),
- @$(cmd_$(1))
- @echo " $(quiet_cmd_$(1)): Finished",
- @$(cmd_$(1))
- )
- @$(call exact_echo,$(call escape_vars,cmd_$(call replace_spaces,$@) := $(cmd_$(1)))) > $(depfile)
- @$(if $(2),$(fixup_dep))
- $(if $(and $(3), $(POSTBUILDS)),
- $(call do_postbuilds)
- )
-)
-endef
-
-# Declare the "all" target first so it is the default,
-# even though we don't have the deps yet.
-.PHONY: all
-all:
-
-# make looks for ways to re-generate included makefiles, but in our case, we
-# don't have a direct way. Explicitly telling make that it has nothing to do
-# for them makes it go faster.
-%.d: ;
-
-# Use FORCE_DO_CMD to force a target to run. Should be coupled with
-# do_cmd.
-.PHONY: FORCE_DO_CMD
-FORCE_DO_CMD:
-
-TOOLSET := target
-# Suffix rules, putting all outputs into $(obj).
-$(obj).$(TOOLSET)/%.o: $(srcdir)/%.c FORCE_DO_CMD
- @$(call do_cmd,cc,1)
-$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD
- @$(call do_cmd,cxx,1)
-$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cpp FORCE_DO_CMD
- @$(call do_cmd,cxx,1)
-$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cxx FORCE_DO_CMD
- @$(call do_cmd,cxx,1)
-$(obj).$(TOOLSET)/%.o: $(srcdir)/%.m FORCE_DO_CMD
- @$(call do_cmd,objc,1)
-$(obj).$(TOOLSET)/%.o: $(srcdir)/%.mm FORCE_DO_CMD
- @$(call do_cmd,objcxx,1)
-$(obj).$(TOOLSET)/%.o: $(srcdir)/%.S FORCE_DO_CMD
- @$(call do_cmd,cc,1)
-$(obj).$(TOOLSET)/%.o: $(srcdir)/%.s FORCE_DO_CMD
- @$(call do_cmd,cc,1)
-
-# Try building from generated source, too.
-$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.c FORCE_DO_CMD
- @$(call do_cmd,cc,1)
-$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD
- @$(call do_cmd,cxx,1)
-$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cpp FORCE_DO_CMD
- @$(call do_cmd,cxx,1)
-$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cxx FORCE_DO_CMD
- @$(call do_cmd,cxx,1)
-$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.m FORCE_DO_CMD
- @$(call do_cmd,objc,1)
-$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.mm FORCE_DO_CMD
- @$(call do_cmd,objcxx,1)
-$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.S FORCE_DO_CMD
- @$(call do_cmd,cc,1)
-$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.s FORCE_DO_CMD
- @$(call do_cmd,cc,1)
-
-$(obj).$(TOOLSET)/%.o: $(obj)/%.c FORCE_DO_CMD
- @$(call do_cmd,cc,1)
-$(obj).$(TOOLSET)/%.o: $(obj)/%.cc FORCE_DO_CMD
- @$(call do_cmd,cxx,1)
-$(obj).$(TOOLSET)/%.o: $(obj)/%.cpp FORCE_DO_CMD
- @$(call do_cmd,cxx,1)
-$(obj).$(TOOLSET)/%.o: $(obj)/%.cxx FORCE_DO_CMD
- @$(call do_cmd,cxx,1)
-$(obj).$(TOOLSET)/%.o: $(obj)/%.m FORCE_DO_CMD
- @$(call do_cmd,objc,1)
-$(obj).$(TOOLSET)/%.o: $(obj)/%.mm FORCE_DO_CMD
- @$(call do_cmd,objcxx,1)
-$(obj).$(TOOLSET)/%.o: $(obj)/%.S FORCE_DO_CMD
- @$(call do_cmd,cc,1)
-$(obj).$(TOOLSET)/%.o: $(obj)/%.s FORCE_DO_CMD
- @$(call do_cmd,cc,1)
-
-
-ifeq ($(strip $(foreach prefix,$(NO_LOAD),\
- $(findstring $(join ^,$(prefix)),\
- $(join ^,bson.target.mk)))),)
- include bson.target.mk
-endif
-
-quiet_cmd_regen_makefile = ACTION Regenerating $@
-cmd_regen_makefile = cd $(srcdir); /usr/local/lib/node_modules/pangyp/gyp/gyp_main.py -fmake --ignore-environment "--toplevel-dir=." -I/Users/ck/coding/projects/js-bson/build/config.gypi -I/usr/local/lib/node_modules/pangyp/addon.gypi -I/Users/ck/.node-gyp/1.0.2/common.gypi "--depth=." "-Goutput_dir=." "--generator-output=build" "-Dlibrary=shared_library" "-Dvisibility=default" "-Dnode_root_dir=/Users/ck/.node-gyp/1.0.2" "-Dmodule_root_dir=/Users/ck/coding/projects/js-bson" binding.gyp
-Makefile: $(srcdir)/../../../.node-gyp/1.0.2/common.gypi $(srcdir)/build/config.gypi $(srcdir)/binding.gyp $(srcdir)/../../../../../usr/local/lib/node_modules/pangyp/addon.gypi
- $(call do_cmd,regen_makefile)
-
-# "all" is a concatenation of the "all" targets from all the included
-# sub-makefiles. This is just here to clarify.
-all:
-
-# Add in dependency-tracking rules. $(all_deps) is the list of every single
-# target in our tree. Only consider the ones with .d (dependency) info:
-d_files := $(wildcard $(foreach f,$(all_deps),$(depsdir)/$(f).d))
-ifneq ($(d_files),)
- include $(d_files)
-endif
diff --git a/node_modules/mongojs/node_modules/mongodb/node_modules/bson/build/Release/.deps/Release/bson.node.d b/node_modules/mongojs/node_modules/mongodb/node_modules/bson/build/Release/.deps/Release/bson.node.d
deleted file mode 100644
index b3465a6..0000000
--- a/node_modules/mongojs/node_modules/mongodb/node_modules/bson/build/Release/.deps/Release/bson.node.d
+++ /dev/null
@@ -1 +0,0 @@
-cmd_Release/bson.node := ./gyp-mac-tool flock ./Release/linker.lock c++ -bundle -Wl,-search_paths_first -mmacosx-version-min=10.5 -arch x86_64 -L./Release -o Release/bson.node Release/obj.target/bson/ext/bson.o -undefined dynamic_lookup
diff --git a/node_modules/mongojs/node_modules/mongodb/node_modules/bson/build/Release/.deps/Release/obj.target/bson/ext/bson.o.d b/node_modules/mongojs/node_modules/mongodb/node_modules/bson/build/Release/.deps/Release/obj.target/bson/ext/bson.o.d
deleted file mode 100644
index a7d83fa..0000000
--- a/node_modules/mongojs/node_modules/mongodb/node_modules/bson/build/Release/.deps/Release/obj.target/bson/ext/bson.o.d
+++ /dev/null
@@ -1,36 +0,0 @@
-cmd_Release/obj.target/bson/ext/bson.o := c++ '-D_DARWIN_USE_64_BIT_INODE=1' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-DBUILDING_NODE_EXTENSION' -I/Users/ck/.node-gyp/1.0.2/src -I/Users/ck/.node-gyp/1.0.2/deps/uv/include -I/Users/ck/.node-gyp/1.0.2/deps/v8/include -I../node_modules/nan -Os -gdwarf-2 -mmacosx-version-min=10.5 -arch x86_64 -Wall -Wendif-labels -W -Wno-unused-parameter -std=gnu++0x -fno-rtti -fno-threadsafe-statics -fno-strict-aliasing -MMD -MF ./Release/.deps/Release/obj.target/bson/ext/bson.o.d.raw -c -o Release/obj.target/bson/ext/bson.o ../ext/bson.cc
-Release/obj.target/bson/ext/bson.o: ../ext/bson.cc \
- /Users/ck/.node-gyp/1.0.2/deps/v8/include/v8.h \
- /Users/ck/.node-gyp/1.0.2/deps/v8/include/v8config.h \
- /Users/ck/.node-gyp/1.0.2/src/node.h \
- /Users/ck/.node-gyp/1.0.2/src/node_version.h \
- /Users/ck/.node-gyp/1.0.2/src/node_buffer.h \
- /Users/ck/.node-gyp/1.0.2/src/smalloc.h ../ext/bson.h \
- /Users/ck/.node-gyp/1.0.2/src/node_object_wrap.h \
- ../node_modules/nan/nan.h \
- /Users/ck/.node-gyp/1.0.2/deps/uv/include/uv.h \
- /Users/ck/.node-gyp/1.0.2/deps/uv/include/uv-errno.h \
- /Users/ck/.node-gyp/1.0.2/deps/uv/include/uv-version.h \
- /Users/ck/.node-gyp/1.0.2/deps/uv/include/uv-unix.h \
- /Users/ck/.node-gyp/1.0.2/deps/uv/include/uv-threadpool.h \
- /Users/ck/.node-gyp/1.0.2/deps/uv/include/uv-darwin.h \
- ../node_modules/nan/nan_new.h \
- ../node_modules/nan/nan_implementation_12_inl.h
-../ext/bson.cc:
-/Users/ck/.node-gyp/1.0.2/deps/v8/include/v8.h:
-/Users/ck/.node-gyp/1.0.2/deps/v8/include/v8config.h:
-/Users/ck/.node-gyp/1.0.2/src/node.h:
-/Users/ck/.node-gyp/1.0.2/src/node_version.h:
-/Users/ck/.node-gyp/1.0.2/src/node_buffer.h:
-/Users/ck/.node-gyp/1.0.2/src/smalloc.h:
-../ext/bson.h:
-/Users/ck/.node-gyp/1.0.2/src/node_object_wrap.h:
-../node_modules/nan/nan.h:
-/Users/ck/.node-gyp/1.0.2/deps/uv/include/uv.h:
-/Users/ck/.node-gyp/1.0.2/deps/uv/include/uv-errno.h:
-/Users/ck/.node-gyp/1.0.2/deps/uv/include/uv-version.h:
-/Users/ck/.node-gyp/1.0.2/deps/uv/include/uv-unix.h:
-/Users/ck/.node-gyp/1.0.2/deps/uv/include/uv-threadpool.h:
-/Users/ck/.node-gyp/1.0.2/deps/uv/include/uv-darwin.h:
-../node_modules/nan/nan_new.h:
-../node_modules/nan/nan_implementation_12_inl.h:
diff --git a/node_modules/mongojs/node_modules/mongodb/node_modules/bson/build/Release/bson.node b/node_modules/mongojs/node_modules/mongodb/node_modules/bson/build/Release/bson.node
deleted file mode 100644
index f24383d..0000000
Binary files a/node_modules/mongojs/node_modules/mongodb/node_modules/bson/build/Release/bson.node and /dev/null differ
diff --git a/node_modules/mongojs/node_modules/mongodb/node_modules/bson/build/Release/linker.lock b/node_modules/mongojs/node_modules/mongodb/node_modules/bson/build/Release/linker.lock
deleted file mode 100644
index e69de29..0000000
diff --git a/node_modules/mongojs/node_modules/mongodb/node_modules/bson/build/Release/obj.target/bson/ext/bson.o b/node_modules/mongojs/node_modules/mongodb/node_modules/bson/build/Release/obj.target/bson/ext/bson.o
deleted file mode 100644
index edb171d..0000000
Binary files a/node_modules/mongojs/node_modules/mongodb/node_modules/bson/build/Release/obj.target/bson/ext/bson.o and /dev/null differ
diff --git a/node_modules/mongojs/node_modules/mongodb/node_modules/bson/build/binding.Makefile b/node_modules/mongojs/node_modules/mongodb/node_modules/bson/build/binding.Makefile
deleted file mode 100644
index d7430e6..0000000
--- a/node_modules/mongojs/node_modules/mongodb/node_modules/bson/build/binding.Makefile
+++ /dev/null
@@ -1,6 +0,0 @@
-# This file is generated by gyp; do not edit.
-
-export builddir_name ?= ./build/.
-.PHONY: all
-all:
- $(MAKE) bson
diff --git a/node_modules/mongojs/node_modules/mongodb/node_modules/bson/build/bson.target.mk b/node_modules/mongojs/node_modules/mongodb/node_modules/bson/build/bson.target.mk
deleted file mode 100644
index c96f695..0000000
--- a/node_modules/mongojs/node_modules/mongodb/node_modules/bson/build/bson.target.mk
+++ /dev/null
@@ -1,156 +0,0 @@
-# This file is generated by gyp; do not edit.
-
-TOOLSET := target
-TARGET := bson
-DEFS_Debug := \
- '-D_DARWIN_USE_64_BIT_INODE=1' \
- '-D_LARGEFILE_SOURCE' \
- '-D_FILE_OFFSET_BITS=64' \
- '-DBUILDING_NODE_EXTENSION' \
- '-DDEBUG' \
- '-D_DEBUG'
-
-# Flags passed to all source files.
-CFLAGS_Debug := \
- -O0 \
- -gdwarf-2 \
- -mmacosx-version-min=10.5 \
- -arch x86_64 \
- -Wall \
- -Wendif-labels \
- -W \
- -Wno-unused-parameter
-
-# Flags passed to only C files.
-CFLAGS_C_Debug := \
- -fno-strict-aliasing
-
-# Flags passed to only C++ files.
-CFLAGS_CC_Debug := \
- -std=gnu++0x \
- -fno-rtti \
- -fno-threadsafe-statics \
- -fno-strict-aliasing
-
-# Flags passed to only ObjC files.
-CFLAGS_OBJC_Debug :=
-
-# Flags passed to only ObjC++ files.
-CFLAGS_OBJCC_Debug :=
-
-INCS_Debug := \
- -I/Users/ck/.node-gyp/1.0.2/src \
- -I/Users/ck/.node-gyp/1.0.2/deps/uv/include \
- -I/Users/ck/.node-gyp/1.0.2/deps/v8/include \
- -I$(srcdir)/node_modules/nan
-
-DEFS_Release := \
- '-D_DARWIN_USE_64_BIT_INODE=1' \
- '-D_LARGEFILE_SOURCE' \
- '-D_FILE_OFFSET_BITS=64' \
- '-DBUILDING_NODE_EXTENSION'
-
-# Flags passed to all source files.
-CFLAGS_Release := \
- -Os \
- -gdwarf-2 \
- -mmacosx-version-min=10.5 \
- -arch x86_64 \
- -Wall \
- -Wendif-labels \
- -W \
- -Wno-unused-parameter
-
-# Flags passed to only C files.
-CFLAGS_C_Release := \
- -fno-strict-aliasing
-
-# Flags passed to only C++ files.
-CFLAGS_CC_Release := \
- -std=gnu++0x \
- -fno-rtti \
- -fno-threadsafe-statics \
- -fno-strict-aliasing
-
-# Flags passed to only ObjC files.
-CFLAGS_OBJC_Release :=
-
-# Flags passed to only ObjC++ files.
-CFLAGS_OBJCC_Release :=
-
-INCS_Release := \
- -I/Users/ck/.node-gyp/1.0.2/src \
- -I/Users/ck/.node-gyp/1.0.2/deps/uv/include \
- -I/Users/ck/.node-gyp/1.0.2/deps/v8/include \
- -I$(srcdir)/node_modules/nan
-
-OBJS := \
- $(obj).target/$(TARGET)/ext/bson.o
-
-# Add to the list of files we specially track dependencies for.
-all_deps += $(OBJS)
-
-# CFLAGS et al overrides must be target-local.
-# See "Target-specific Variable Values" in the GNU Make manual.
-$(OBJS): TOOLSET := $(TOOLSET)
-$(OBJS): GYP_CFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_C_$(BUILDTYPE))
-$(OBJS): GYP_CXXFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_CC_$(BUILDTYPE))
-$(OBJS): GYP_OBJCFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_C_$(BUILDTYPE)) $(CFLAGS_OBJC_$(BUILDTYPE))
-$(OBJS): GYP_OBJCXXFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_CC_$(BUILDTYPE)) $(CFLAGS_OBJCC_$(BUILDTYPE))
-
-# Suffix rules, putting all outputs into $(obj).
-
-$(obj).$(TOOLSET)/$(TARGET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD
- @$(call do_cmd,cxx,1)
-
-# Try building from generated source, too.
-
-$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD
- @$(call do_cmd,cxx,1)
-
-$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj)/%.cc FORCE_DO_CMD
- @$(call do_cmd,cxx,1)
-
-# End of this set of suffix rules
-### Rules for final target.
-LDFLAGS_Debug := \
- -Wl,-search_paths_first \
- -mmacosx-version-min=10.5 \
- -arch x86_64 \
- -L$(builddir)
-
-LIBTOOLFLAGS_Debug := \
- -Wl,-search_paths_first
-
-LDFLAGS_Release := \
- -Wl,-search_paths_first \
- -mmacosx-version-min=10.5 \
- -arch x86_64 \
- -L$(builddir)
-
-LIBTOOLFLAGS_Release := \
- -Wl,-search_paths_first
-
-LIBS := \
- -undefined dynamic_lookup
-
-$(builddir)/bson.node: GYP_LDFLAGS := $(LDFLAGS_$(BUILDTYPE))
-$(builddir)/bson.node: LIBS := $(LIBS)
-$(builddir)/bson.node: GYP_LIBTOOLFLAGS := $(LIBTOOLFLAGS_$(BUILDTYPE))
-$(builddir)/bson.node: TOOLSET := $(TOOLSET)
-$(builddir)/bson.node: $(OBJS) FORCE_DO_CMD
- $(call do_cmd,solink_module)
-
-all_deps += $(builddir)/bson.node
-# Add target alias
-.PHONY: bson
-bson: $(builddir)/bson.node
-
-# Short alias for building this executable.
-.PHONY: bson.node
-bson.node: $(builddir)/bson.node
-
-# Add executable to "all" target.
-.PHONY: all
-all: $(builddir)/bson.node
-
diff --git a/node_modules/mongojs/node_modules/mongodb/node_modules/bson/build/config.gypi b/node_modules/mongojs/node_modules/mongodb/node_modules/bson/build/config.gypi
deleted file mode 100644
index 4d55994..0000000
--- a/node_modules/mongojs/node_modules/mongodb/node_modules/bson/build/config.gypi
+++ /dev/null
@@ -1,43 +0,0 @@
-# Do not edit. File was generated by pangyp's "configure" step
-{
- "target_defaults": {
- "cflags": [],
- "default_configuration": "Release",
- "defines": [],
- "include_dirs": [],
- "libraries": []
- },
- "variables": {
- "host_arch": "x64",
- "icu_small": "false",
- "node_install_npm": "true",
- "node_prefix": "",
- "node_shared_http_parser": "false",
- "node_shared_libuv": "false",
- "node_shared_openssl": "false",
- "node_shared_v8": "false",
- "node_shared_zlib": "false",
- "node_tag": "",
- "node_use_dtrace": "true",
- "node_use_etw": "false",
- "node_use_mdb": "false",
- "node_use_openssl": "true",
- "node_use_perfctr": "false",
- "openssl_no_asm": 0,
- "python": "/usr/bin/python",
- "target_arch": "x64",
- "uv_library": "static_library",
- "uv_parent_path": "/deps/uv/",
- "uv_use_dtrace": "true",
- "v8_enable_gdbjit": 0,
- "v8_enable_i18n_support": 0,
- "v8_no_strict_aliasing": 1,
- "v8_optimized_debug": 0,
- "v8_random_seed": 0,
- "v8_use_snapshot": "true",
- "want_separate_host_toolset": 0,
- "nodedir": "/Users/ck/.node-gyp/1.0.2",
- "copy_dev_lib": "true",
- "standalone_static_library": 1
- }
-}
diff --git a/node_modules/mongojs/node_modules/mongodb/node_modules/bson/build/gyp-mac-tool b/node_modules/mongojs/node_modules/mongodb/node_modules/bson/build/gyp-mac-tool
deleted file mode 100644
index 7abfed5..0000000
--- a/node_modules/mongojs/node_modules/mongodb/node_modules/bson/build/gyp-mac-tool
+++ /dev/null
@@ -1,512 +0,0 @@
-#!/usr/bin/env python
-# Generated by gyp. Do not edit.
-# Copyright (c) 2012 Google Inc. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""Utility functions to perform Xcode-style build steps.
-
-These functions are executed via gyp-mac-tool when using the Makefile generator.
-"""
-
-import fcntl
-import fnmatch
-import glob
-import json
-import os
-import plistlib
-import re
-import shutil
-import string
-import subprocess
-import sys
-import tempfile
-
-
-def main(args):
- executor = MacTool()
- exit_code = executor.Dispatch(args)
- if exit_code is not None:
- sys.exit(exit_code)
-
-
-class MacTool(object):
- """This class performs all the Mac tooling steps. The methods can either be
- executed directly, or dispatched from an argument list."""
-
- def Dispatch(self, args):
- """Dispatches a string command to a method."""
- if len(args) < 1:
- raise Exception("Not enough arguments")
-
- method = "Exec%s" % self._CommandifyName(args[0])
- return getattr(self, method)(*args[1:])
-
- def _CommandifyName(self, name_string):
- """Transforms a tool name like copy-info-plist to CopyInfoPlist"""
- return name_string.title().replace('-', '')
-
- def ExecCopyBundleResource(self, source, dest):
- """Copies a resource file to the bundle/Resources directory, performing any
- necessary compilation on each resource."""
- extension = os.path.splitext(source)[1].lower()
- if os.path.isdir(source):
- # Copy tree.
- # TODO(thakis): This copies file attributes like mtime, while the
- # single-file branch below doesn't. This should probably be changed to
- # be consistent with the single-file branch.
- if os.path.exists(dest):
- shutil.rmtree(dest)
- shutil.copytree(source, dest)
- elif extension == '.xib':
- return self._CopyXIBFile(source, dest)
- elif extension == '.storyboard':
- return self._CopyXIBFile(source, dest)
- elif extension == '.strings':
- self._CopyStringsFile(source, dest)
- else:
- shutil.copy(source, dest)
-
- def _CopyXIBFile(self, source, dest):
- """Compiles a XIB file with ibtool into a binary plist in the bundle."""
-
- # ibtool sometimes crashes with relative paths. See crbug.com/314728.
- base = os.path.dirname(os.path.realpath(__file__))
- if os.path.relpath(source):
- source = os.path.join(base, source)
- if os.path.relpath(dest):
- dest = os.path.join(base, dest)
-
- args = ['xcrun', 'ibtool', '--errors', '--warnings', '--notices',
- '--output-format', 'human-readable-text', '--compile', dest, source]
- ibtool_section_re = re.compile(r'/\*.*\*/')
- ibtool_re = re.compile(r'.*note:.*is clipping its content')
- ibtoolout = subprocess.Popen(args, stdout=subprocess.PIPE)
- current_section_header = None
- for line in ibtoolout.stdout:
- if ibtool_section_re.match(line):
- current_section_header = line
- elif not ibtool_re.match(line):
- if current_section_header:
- sys.stdout.write(current_section_header)
- current_section_header = None
- sys.stdout.write(line)
- return ibtoolout.returncode
-
- def _CopyStringsFile(self, source, dest):
- """Copies a .strings file using iconv to reconvert the input into UTF-16."""
- input_code = self._DetectInputEncoding(source) or "UTF-8"
-
- # Xcode's CpyCopyStringsFile / builtin-copyStrings seems to call
- # CFPropertyListCreateFromXMLData() behind the scenes; at least it prints
- # CFPropertyListCreateFromXMLData(): Old-style plist parser: missing
- # semicolon in dictionary.
- # on invalid files. Do the same kind of validation.
- import CoreFoundation
- s = open(source, 'rb').read()
- d = CoreFoundation.CFDataCreate(None, s, len(s))
- _, error = CoreFoundation.CFPropertyListCreateFromXMLData(None, d, 0, None)
- if error:
- return
-
- fp = open(dest, 'wb')
- fp.write(s.decode(input_code).encode('UTF-16'))
- fp.close()
-
- def _DetectInputEncoding(self, file_name):
- """Reads the first few bytes from file_name and tries to guess the text
- encoding. Returns None as a guess if it can't detect it."""
- fp = open(file_name, 'rb')
- try:
- header = fp.read(3)
- except e:
- fp.close()
- return None
- fp.close()
- if header.startswith("\xFE\xFF"):
- return "UTF-16"
- elif header.startswith("\xFF\xFE"):
- return "UTF-16"
- elif header.startswith("\xEF\xBB\xBF"):
- return "UTF-8"
- else:
- return None
-
- def ExecCopyInfoPlist(self, source, dest, *keys):
- """Copies the |source| Info.plist to the destination directory |dest|."""
- # Read the source Info.plist into memory.
- fd = open(source, 'r')
- lines = fd.read()
- fd.close()
-
- # Insert synthesized key/value pairs (e.g. BuildMachineOSBuild).
- plist = plistlib.readPlistFromString(lines)
- if keys:
- plist = dict(plist.items() + json.loads(keys[0]).items())
- lines = plistlib.writePlistToString(plist)
-
- # Go through all the environment variables and replace them as variables in
- # the file.
- IDENT_RE = re.compile('[/\s]')
- for key in os.environ:
- if key.startswith('_'):
- continue
- evar = '${%s}' % key
- evalue = os.environ[key]
- lines = string.replace(lines, evar, evalue)
-
- # Xcode supports various suffices on environment variables, which are
- # all undocumented. :rfc1034identifier is used in the standard project
- # template these days, and :identifier was used earlier. They are used to
- # convert non-url characters into things that look like valid urls --
- # except that the replacement character for :identifier, '_' isn't valid
- # in a URL either -- oops, hence :rfc1034identifier was born.
- evar = '${%s:identifier}' % key
- evalue = IDENT_RE.sub('_', os.environ[key])
- lines = string.replace(lines, evar, evalue)
-
- evar = '${%s:rfc1034identifier}' % key
- evalue = IDENT_RE.sub('-', os.environ[key])
- lines = string.replace(lines, evar, evalue)
-
- # Remove any keys with values that haven't been replaced.
- lines = lines.split('\n')
- for i in range(len(lines)):
- if lines[i].strip().startswith("