diff --git a/.gitignore b/.gitignore index 9bd15e5..e7cc9b2 100755 --- a/.gitignore +++ b/.gitignore @@ -11,6 +11,8 @@ pids logs results +.DS_Store + npm-debug.log workspace node_modules @@ -20,4 +22,7 @@ browser-version/node_modules *.swp *~ -*.swo \ No newline at end of file +*.swo + +browser-version/out +test-results diff --git a/benchmarks/commonUtilities.js b/benchmarks/commonUtilities.js index 18424e1..ec708ed 100755 --- a/benchmarks/commonUtilities.js +++ b/benchmarks/commonUtilities.js @@ -29,7 +29,7 @@ module.exports.getConfiguration = function (benchDb) { console.log('----------------------------') console.log('Test with ' + n + ' documents') - console.log(program.withIndex ? 'Use an index' : "Don't use an index") + console.log(program.withIndex ? 'Use an index' : 'Don\'t use an index') console.log(program.inMemory ? 'Use an in-memory datastore' : 'Use a persistent datastore') console.log('----------------------------') @@ -75,7 +75,7 @@ function getRandomArray (n) { } return res -}; +} module.exports.getRandomArray = getRandomArray /** @@ -102,6 +102,7 @@ module.exports.insertDocs = function (d, n, profiler, cb) { }) }) } + runFrom(0) } @@ -128,6 +129,7 @@ module.exports.findDocs = function (d, n, profiler, cb) { }) }) } + runFrom(0) } @@ -164,6 +166,7 @@ module.exports.findDocsWithIn = function (d, n, profiler, cb) { }) }) } + runFrom(0) } @@ -190,6 +193,7 @@ module.exports.findOneDocs = function (d, n, profiler, cb) { }) }) } + runFrom(0) } @@ -218,6 +222,7 @@ module.exports.updateDocs = function (options, d, n, profiler, cb) { }) }) } + runFrom(0) } @@ -253,6 +258,7 @@ module.exports.removeDocs = function (options, d, n, profiler, cb) { }) }) } + runFrom(0) } @@ -276,5 +282,6 @@ module.exports.loadDatabase = function (d, n, profiler, cb) { }) }) } + runFrom(0) } diff --git a/benchmarks/ensureIndex.js b/benchmarks/ensureIndex.js index 5cd14a5..43b06b7 100755 --- a/benchmarks/ensureIndex.js +++ b/benchmarks/ensureIndex.js @@ -1,11 +1,12 @@ -const Datastore = require('../lib/datastore') -const benchDb = 'workspace/insert.bench.db' const async = require('async') +const program = require('commander') +const Datastore = require('../lib/datastore') const commonUtilities = require('./commonUtilities') -const ExecTime = require('exec-time') -const profiler = new ExecTime('INSERT BENCH') +const Profiler = require('./profiler') + +const profiler = new Profiler('INSERT BENCH') +const benchDb = 'workspace/insert.bench.db' const d = new Datastore(benchDb) -const program = require('commander') program .option('-n --number [number]', 'Size of the collection to test on', parseInt) diff --git a/benchmarks/find.js b/benchmarks/find.js index 5b32098..b81b03d 100755 --- a/benchmarks/find.js +++ b/benchmarks/find.js @@ -1,8 +1,9 @@ -const benchDb = 'workspace/find.bench.db' const async = require('async') -const ExecTime = require('exec-time') -const profiler = new ExecTime('FIND BENCH') const commonUtilities = require('./commonUtilities') +const Profiler = require('./profiler') + +const profiler = new Profiler('FIND BENCH') +const benchDb = 'workspace/find.bench.db' const config = commonUtilities.getConfiguration(benchDb) const d = config.d const n = config.n diff --git a/benchmarks/findOne.js b/benchmarks/findOne.js index 97b8951..93911bd 100755 --- a/benchmarks/findOne.js +++ b/benchmarks/findOne.js @@ -1,8 +1,9 @@ -const benchDb = 'workspace/findOne.bench.db' const async = require('async') -const ExecTime = require('exec-time') -const profiler = new ExecTime('FINDONE BENCH') const commonUtilities = require('./commonUtilities') +const Profiler = require('./profiler') + +const benchDb = 'workspace/findOne.bench.db' +const profiler = new Profiler('FINDONE BENCH') const config = commonUtilities.getConfiguration(benchDb) const d = config.d const n = config.n diff --git a/benchmarks/findWithIn.js b/benchmarks/findWithIn.js index ab0b7de..e167a6f 100755 --- a/benchmarks/findWithIn.js +++ b/benchmarks/findWithIn.js @@ -1,8 +1,9 @@ -const benchDb = 'workspace/find.bench.db' const async = require('async') -const ExecTime = require('exec-time') -const profiler = new ExecTime('FIND BENCH') const commonUtilities = require('./commonUtilities') +const Profiler = require('./profiler') + +const benchDb = 'workspace/find.bench.db' +const profiler = new Profiler('FIND BENCH') const config = commonUtilities.getConfiguration(benchDb) const d = config.d const n = config.n diff --git a/benchmarks/insert.js b/benchmarks/insert.js index 784844a..f78d8b5 100755 --- a/benchmarks/insert.js +++ b/benchmarks/insert.js @@ -1,8 +1,9 @@ -const benchDb = 'workspace/insert.bench.db' const async = require('async') -const ExecTime = require('exec-time') -const profiler = new ExecTime('INSERT BENCH') const commonUtilities = require('./commonUtilities') +const Profiler = require('./profiler') + +const benchDb = 'workspace/insert.bench.db' +const profiler = new Profiler('INSERT BENCH') const config = commonUtilities.getConfiguration(benchDb) const d = config.d let n = config.n diff --git a/benchmarks/loadDatabase.js b/benchmarks/loadDatabase.js index fc8a157..a9910d3 100755 --- a/benchmarks/loadDatabase.js +++ b/benchmarks/loadDatabase.js @@ -1,11 +1,12 @@ -const Datastore = require('../lib/datastore') -const benchDb = 'workspace/loaddb.bench.db' const async = require('async') +const program = require('commander') +const Datastore = require('../lib/datastore') const commonUtilities = require('./commonUtilities') -const ExecTime = require('exec-time') -const profiler = new ExecTime('LOADDB BENCH') +const Profiler = require('./profiler') + +const benchDb = 'workspace/loaddb.bench.db' +const profiler = new Profiler('LOADDB BENCH') const d = new Datastore(benchDb) -const program = require('commander') program .option('-n --number [number]', 'Size of the collection to test on', parseInt) diff --git a/benchmarks/profiler.js b/benchmarks/profiler.js new file mode 100644 index 0000000..a5d73af --- /dev/null +++ b/benchmarks/profiler.js @@ -0,0 +1,92 @@ +const util = require('util') + +function formatTime (time, precision) { + // If we're dealing with ms, round up to seconds when time is at least 1 second + if (time > 1000 && precision === 'ms') { + return (Math.floor(time / 100) / 10) + ' s' + } else { + return time.toFixed(3) + ' ' + precision + } +} + +// get time in ns +function getTime () { + const t = process.hrtime() + return (t[0] * 1e9 + t[1]) +} + +/** + * Create a profiler with name testName to monitor the execution time of a route + * The profiler has two arguments: a step msg and an optional reset for the internal timer + * It will display the execution time per step and total from latest rest + * + * Optional logToConsole flag, which defaults to true, causes steps to be printed to console. + * otherwise, they can be accessed from Profiler.steps array. + */ +function Profiler (name, logToConsole, precision) { + this.name = name + this.steps = [] + this.sinceBeginning = null + this.lastStep = null + this.logToConsole = typeof (logToConsole) === 'undefined' ? true : logToConsole + this.precision = typeof (precision) === 'undefined' ? 'ms' : precision + this.divisor = 1 + + if (this.precision === 'ms') this.divisor = 1e6 +} + +Profiler.prototype.beginProfiling = function () { + if (this.logToConsole) { console.log(this.name + ' - Begin profiling') } + this.resetTimers() +} + +Profiler.prototype.resetTimers = function () { + this.sinceBeginning = getTime() + this.lastStep = getTime() + this.steps.push(['BEGIN_TIMER', this.lastStep]) +} + +Profiler.prototype.elapsedSinceBeginning = function () { + return (getTime() - this.sinceBeginning) / this.divisor +} + +Profiler.prototype.elapsedSinceLastStep = function () { + return (getTime() - this.lastStep) / this.divisor +} + +// Return the deltas between steps, in nanoseconds + +Profiler.prototype.getSteps = function () { + const divisor = this.divisor + + return this.steps.map(function (curr, index, arr) { + if (index === 0) return undefined + const delta = (curr[1] - arr[index - 1][1]) + return [curr[0], (delta / divisor)] + }).slice(1) +} + +Profiler.prototype.step = function (msg) { + if (!this.sinceBeginning || !this.lastStep) { + console.log(util.format( + '%s - %s - You must call beginProfiling before registering steps', + this.name, + msg + )) + return + } + + if (this.logToConsole) { + console.log(util.format('%s - %s - %s (total: %s)', + this.name, + msg, + formatTime(this.elapsedSinceLastStep(), this.precision), + formatTime(this.elapsedSinceBeginning(), this.precision) + )) + } + + this.lastStep = getTime() + this.steps.push([msg, this.lastStep]) +} + +module.exports = Profiler diff --git a/benchmarks/remove.js b/benchmarks/remove.js index 5bd580d..a262d52 100755 --- a/benchmarks/remove.js +++ b/benchmarks/remove.js @@ -1,8 +1,9 @@ -const benchDb = 'workspace/remove.bench.db' const async = require('async') -const ExecTime = require('exec-time') -const profiler = new ExecTime('REMOVE BENCH') const commonUtilities = require('./commonUtilities') +const Profiler = require('./profiler') + +const benchDb = 'workspace/remove.bench.db' +const profiler = new Profiler('REMOVE BENCH') const config = commonUtilities.getConfiguration(benchDb) const d = config.d const n = config.n diff --git a/benchmarks/update.js b/benchmarks/update.js index 91d27c7..1304f2f 100755 --- a/benchmarks/update.js +++ b/benchmarks/update.js @@ -1,8 +1,9 @@ -const benchDb = 'workspace/update.bench.db' const async = require('async') -const ExecTime = require('exec-time') -const profiler = new ExecTime('UPDATE BENCH') const commonUtilities = require('./commonUtilities') +const Profiler = require('./profiler') + +const benchDb = 'workspace/update.bench.db' +const profiler = new Profiler('UPDATE BENCH') const config = commonUtilities.getConfiguration(benchDb) const d = config.d const n = config.n diff --git a/bower.json b/bower.json deleted file mode 100755 index 5a8e356..0000000 --- a/bower.json +++ /dev/null @@ -1,6 +0,0 @@ -{ -"name": "nedb", -"description": "The Javascript Database for Node, nwjs, Electron and the browser", -"ignore": ["benchmarks", "lib", "test", "test_lac"], -"main": ["browser-version/nedb.js", "browser-version/nedb.min.js"] -} diff --git a/browser-version/browser-specific/lib/storage.js b/browser-version/browser-specific/lib/storage.js deleted file mode 100755 index 86b4640..0000000 --- a/browser-version/browser-specific/lib/storage.js +++ /dev/null @@ -1,95 +0,0 @@ -/** - * Way data is stored for this database - * For a Node.js/Node Webkit database it's the file system - * For a browser-side database it's localforage, which uses the best backend available (IndexedDB then WebSQL then localStorage) - * - * This version is the browser version - */ - -var localforage = require('localforage') - -// Configure localforage to display NeDB name for now. Would be a good idea to let user use his own app name -localforage.config({ - name: 'NeDB' -, storeName: 'nedbdata' -}); - - -function exists (filename, callback) { - localforage.getItem(filename, function (err, value) { - if (value !== null) { // Even if value is undefined, localforage returns null - return callback(true); - } else { - return callback(false); - } - }); -} - - -function rename (filename, newFilename, callback) { - localforage.getItem(filename, function (err, value) { - if (value === null) { - localforage.removeItem(newFilename, function () { return callback(); }); - } else { - localforage.setItem(newFilename, value, function () { - localforage.removeItem(filename, function () { return callback(); }); - }); - } - }); -} - - -function writeFile (filename, contents, options, callback) { - // Options do not matter in browser setup - if (typeof options === 'function') { callback = options; } - localforage.setItem(filename, contents, function () { return callback(); }); -} - - -function appendFile (filename, toAppend, options, callback) { - // Options do not matter in browser setup - if (typeof options === 'function') { callback = options; } - - localforage.getItem(filename, function (err, contents) { - contents = contents || ''; - contents += toAppend; - localforage.setItem(filename, contents, function () { return callback(); }); - }); -} - - -function readFile (filename, options, callback) { - // Options do not matter in browser setup - if (typeof options === 'function') { callback = options; } - localforage.getItem(filename, function (err, contents) { return callback(null, contents || ''); }); -} - - -function unlink (filename, callback) { - localforage.removeItem(filename, function () { return callback(); }); -} - - -// Nothing to do, no directories will be used on the browser -function mkdirp (dir, callback) { - return callback(); -} - - -// Nothing to do, no data corruption possible in the brower -function ensureDatafileIntegrity (filename, callback) { - return callback(null); -} - - -// Interface -module.exports.exists = exists; -module.exports.rename = rename; -module.exports.writeFile = writeFile; -module.exports.crashSafeWriteFile = writeFile; // No need for a crash safe function in the browser -module.exports.appendFile = appendFile; -module.exports.readFile = readFile; -module.exports.unlink = unlink; -module.exports.mkdirp = mkdirp; -module.exports.ensureDatafileIntegrity = ensureDatafileIntegrity; - diff --git a/browser-version/build.js b/browser-version/build.js deleted file mode 100755 index a058c86..0000000 --- a/browser-version/build.js +++ /dev/null @@ -1,101 +0,0 @@ -/** - * Build the browser version of nedb - */ - -var fs = require('fs') - , path = require('path') - , child_process = require('child_process') - , toCopy = ['lib', 'node_modules'] - , async, browserify, uglify - ; - -// Ensuring both node_modules (the source one and build one), src and out directories exist -function ensureDirExists (name) { - try { - fs.mkdirSync(path.join(__dirname, name)); - } catch (e) { - if (e.code !== 'EEXIST') { - console.log("Error ensuring that node_modules exists"); - process.exit(1); - } - } -} -ensureDirExists('../node_modules'); -ensureDirExists('node_modules'); -ensureDirExists('out'); -ensureDirExists('src'); - - -// Installing build dependencies and require them -console.log("Installing build dependencies"); -child_process.exec('npm install', { cwd: __dirname }, function (err, stdout, stderr) { - if (err) { console.log("Error reinstalling dependencies"); process.exit(1); } - - fs = require('fs-extra'); - async = require('async'); - browserify = require('browserify'); - uglify = require('uglify-js'); - - async.waterfall([ - function (cb) { - console.log("Installing source dependencies if needed"); - - child_process.exec('npm install', { cwd: path.join(__dirname, '..') }, function (err) { return cb(err); }); - } - , function (cb) { - console.log("Removing contents of the src directory"); - - async.eachSeries(fs.readdirSync(path.join(__dirname, 'src')), function (item, _cb) { - fs.remove(path.join(__dirname, 'src', item), _cb); - }, cb); - } - , function (cb) { - console.log("Copying source files"); - - async.eachSeries(toCopy, function (item, _cb) { - fs.copy(path.join(__dirname, '..', item), path.join(__dirname, 'src', item), _cb); - }, cb); - } - , function (cb) { - console.log("Copying browser specific files to replace their server-specific counterparts"); - - async.eachSeries(fs.readdirSync(path.join(__dirname, 'browser-specific')), function (item, _cb) { - fs.copy(path.join(__dirname, 'browser-specific', item), path.join(__dirname, 'src', item), _cb); - }, cb); - } - , function (cb) { - console.log("Browserifying the code"); - - var b = browserify() - , srcPath = path.join(__dirname, 'src/lib/datastore.js'); - - b.add(srcPath); - b.bundle({ standalone: 'Nedb' }, function (err, out) { - if (err) { return cb(err); } - fs.writeFile(path.join(__dirname, 'out/nedb.js'), out, 'utf8', function (err) { - if (err) { - return cb(err); - } else { - return cb(null, out); - } - }); - }); - } - , function (out, cb) { - console.log("Creating the minified version"); - - var compressedCode = uglify.minify(out, { fromString: true }); - fs.writeFile(path.join(__dirname, 'out/nedb.min.js'), compressedCode.code, 'utf8', cb); - } - ], function (err) { - if (err) { - console.log("Error during build"); - console.log(err); - } else { - console.log("Build finished with success"); - } - }); -}); - - - diff --git a/browser-version/browser-specific/lib/customUtils.js b/browser-version/lib/customUtils.js similarity index 63% rename from browser-version/browser-specific/lib/customUtils.js rename to browser-version/lib/customUtils.js index e1dfeeb..f956aab 100755 --- a/browser-version/browser-specific/lib/customUtils.js +++ b/browser-version/lib/customUtils.js @@ -8,59 +8,58 @@ * NOTE: Math.random() does not guarantee "cryptographic quality" but we actually don't need it */ function randomBytes (size) { - var bytes = new Array(size); - var r; + const bytes = new Array(size) - for (var i = 0, r; i < size; i++) { - if ((i & 0x03) == 0) r = Math.random() * 0x100000000; - bytes[i] = r >>> ((i & 0x03) << 3) & 0xff; + for (let i = 0, r; i < size; i++) { + if ((i & 0x03) === 0) r = Math.random() * 0x100000000 + bytes[i] = r >>> ((i & 0x03) << 3) & 0xff } - return bytes; + return bytes } - /** * Taken from the base64-js module * https://github.com/beatgammit/base64-js/ */ function byteArrayToBase64 (uint8) { - var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' - , extraBytes = uint8.length % 3 // if we have 1 byte left, pad 2 bytes - , output = "" - , temp, length, i; + const lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' + const extraBytes = uint8.length % 3 // if we have 1 byte left, pad 2 bytes + let output = '' + let temp + let length + let i function tripletToBase64 (num) { - return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]; - }; + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] + } // go through the array every three bytes, we'll deal with trailing stuff later for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) { - temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); - output += tripletToBase64(temp); + temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) + output += tripletToBase64(temp) } // pad the end with zeros, but make sure to not forget the extra bytes switch (extraBytes) { case 1: - temp = uint8[uint8.length - 1]; - output += lookup[temp >> 2]; - output += lookup[(temp << 4) & 0x3F]; - output += '=='; - break; + temp = uint8[uint8.length - 1] + output += lookup[temp >> 2] + output += lookup[(temp << 4) & 0x3F] + output += '==' + break case 2: - temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1]); - output += lookup[temp >> 10]; - output += lookup[(temp >> 4) & 0x3F]; - output += lookup[(temp << 2) & 0x3F]; - output += '='; - break; + temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1]) + output += lookup[temp >> 10] + output += lookup[(temp >> 4) & 0x3F] + output += lookup[(temp << 2) & 0x3F] + output += '=' + break } - return output; + return output } - /** * Return a random alphanumerical string of length len * There is a very small probability (less than 1/1,000,000) for the length to be less than len @@ -70,9 +69,7 @@ function byteArrayToBase64 (uint8) { * See http://en.wikipedia.org/wiki/Birthday_problem */ function uid (len) { - return byteArrayToBase64(randomBytes(Math.ceil(Math.max(8, len * 2)))).replace(/[+\/]/g, '').slice(0, len); + return byteArrayToBase64(randomBytes(Math.ceil(Math.max(8, len * 2)))).replace(/[+/]/g, '').slice(0, len) } - - -module.exports.uid = uid; +module.exports.uid = uid diff --git a/browser-version/lib/storage.js b/browser-version/lib/storage.js new file mode 100755 index 0000000..ce8d081 --- /dev/null +++ b/browser-version/lib/storage.js @@ -0,0 +1,84 @@ +/** + * Way data is stored for this database + * For a Node.js/Node Webkit database it's the file system + * For a browser-side database it's localforage, which uses the best backend available (IndexedDB then WebSQL then localStorage) + * + * This version is the browser version + */ +const localforage = require('localforage') + +// Configure localforage to display NeDB name for now. Would be a good idea to let user use his own app name +const store = localforage.createInstance({ + name: 'NeDB', + storeName: 'nedbdata' +}) + +function exists (filename, cback) { + // eslint-disable-next-line node/handle-callback-err + store.getItem(filename, (err, value) => { + if (value !== null) return cback(true) // Even if value is undefined, localforage returns null + else return cback(false) + }) +} + +function rename (filename, newFilename, callback) { + // eslint-disable-next-line node/handle-callback-err + store.getItem(filename, (err, value) => { + if (value === null) store.removeItem(newFilename, () => callback()) + else { + store.setItem(newFilename, value, () => { + store.removeItem(filename, () => callback()) + }) + } + }) +} + +function writeFile (filename, contents, options, callback) { + // Options do not matter in browser setup + if (typeof options === 'function') { callback = options } + store.setItem(filename, contents, () => callback()) +} + +function appendFile (filename, toAppend, options, callback) { + // Options do not matter in browser setup + if (typeof options === 'function') { callback = options } + + // eslint-disable-next-line node/handle-callback-err + store.getItem(filename, (err, contents) => { + contents = contents || '' + contents += toAppend + store.setItem(filename, contents, () => callback()) + }) +} + +function readFile (filename, options, callback) { + // Options do not matter in browser setup + if (typeof options === 'function') { callback = options } + // eslint-disable-next-line node/handle-callback-err + store.getItem(filename, (err, contents) => callback(null, contents || '')) +} + +function unlink (filename, callback) { + store.removeItem(filename, () => callback()) +} + +// Nothing to do, no directories will be used on the browser +function mkdir (dir, options, callback) { + return callback() +} + +// Nothing to do, no data corruption possible in the brower +function ensureDatafileIntegrity (filename, callback) { + return callback(null) +} + +// Interface +module.exports.exists = exists +module.exports.rename = rename +module.exports.writeFile = writeFile +module.exports.crashSafeWriteFile = writeFile // No need for a crash safe function in the browser +module.exports.appendFile = appendFile +module.exports.readFile = readFile +module.exports.unlink = unlink +module.exports.mkdir = mkdir +module.exports.ensureDatafileIntegrity = ensureDatafileIntegrity diff --git a/browser-version/out/nedb.js b/browser-version/out/nedb.js deleted file mode 100755 index e9655bf..0000000 --- a/browser-version/out/nedb.js +++ /dev/null @@ -1,9419 +0,0 @@ -(function(e){if("function"==typeof bootstrap)bootstrap("nedb",e);else if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&define.amd)define(e);else if("undefined"!=typeof ses){if(!ses.ok())return;ses.makeNedb=e}else"undefined"!=typeof window?window.Nedb=e():global.Nedb=e()})(function(){var define,ses,bootstrap,module,exports; -return (function(e,t,n){function i(n,s){if(!t[n]){if(!e[n]){var o=typeof require=="function"&&require;if(!s&&o)return o(n,!0);if(r)return r(n,!0);throw new Error("Cannot find module '"+n+"'")}var u=t[n]={exports:{}};e[n][0].call(u.exports,function(t){var r=e[n][1][t];return i(r?r:t)},u,u.exports)}return t[n].exports}var r=typeof require=="function"&&require;for(var s=0;s 0 && this._events[type].length > m) { - this._events[type].warned = true; - console.error('(node) warning: possible EventEmitter memory ' + - 'leak detected. %d listeners added. ' + - 'Use emitter.setMaxListeners() to increase limit.', - this._events[type].length); - console.trace(); - } - } - - // If we've already got an array, just append. - this._events[type].push(listener); - } else { - // Adding the second element, need to change to array. - this._events[type] = [this._events[type], listener]; - } - - return this; -}; - -EventEmitter.prototype.on = EventEmitter.prototype.addListener; - -EventEmitter.prototype.once = function(type, listener) { - var self = this; - self.on(type, function g() { - self.removeListener(type, g); - listener.apply(this, arguments); - }); - - return this; -}; - -EventEmitter.prototype.removeListener = function(type, listener) { - if ('function' !== typeof listener) { - throw new Error('removeListener only takes instances of Function'); - } - - // does not use listeners(), so no side effect of creating _events[type] - if (!this._events || !this._events[type]) return this; - - var list = this._events[type]; - - if (isArray(list)) { - var i = indexOf(list, listener); - if (i < 0) return this; - list.splice(i, 1); - if (list.length == 0) - delete this._events[type]; - } else if (this._events[type] === listener) { - delete this._events[type]; - } - - return this; -}; - -EventEmitter.prototype.removeAllListeners = function(type) { - if (arguments.length === 0) { - this._events = {}; - return this; - } - - // does not use listeners(), so no side effect of creating _events[type] - if (type && this._events && this._events[type]) this._events[type] = null; - return this; -}; - -EventEmitter.prototype.listeners = function(type) { - if (!this._events) this._events = {}; - if (!this._events[type]) this._events[type] = []; - if (!isArray(this._events[type])) { - this._events[type] = [this._events[type]]; - } - return this._events[type]; -}; - -EventEmitter.listenerCount = function(emitter, type) { - var ret; - if (!emitter._events || !emitter._events[type]) - ret = 0; - else if (typeof emitter._events[type] === 'function') - ret = 1; - else - ret = emitter._events[type].length; - return ret; -}; - -},{"__browserify_process":4}],2:[function(require,module,exports){ -var process=require("__browserify_process");function filter (xs, fn) { - var res = []; - for (var i = 0; i < xs.length; i++) { - if (fn(xs[i], i, xs)) res.push(xs[i]); - } - return res; -} - -// resolves . and .. elements in a path array with directory names there -// must be no slashes, empty elements, or device names (c:\) in the array -// (so also no leading and trailing slashes - it does not distinguish -// relative and absolute paths) -function normalizeArray(parts, allowAboveRoot) { - // if the path tries to go above the root, `up` ends up > 0 - var up = 0; - for (var i = parts.length; i >= 0; i--) { - var last = parts[i]; - if (last == '.') { - parts.splice(i, 1); - } else if (last === '..') { - parts.splice(i, 1); - up++; - } else if (up) { - parts.splice(i, 1); - up--; - } - } - - // if the path is allowed to go above the root, restore leading ..s - if (allowAboveRoot) { - for (; up--; up) { - parts.unshift('..'); - } - } - - return parts; -} - -// Regex to split a filename into [*, dir, basename, ext] -// posix version -var splitPathRe = /^(.+\/(?!$)|\/)?((?:.+?)?(\.[^.]*)?)$/; - -// path.resolve([from ...], to) -// posix version -exports.resolve = function() { -var resolvedPath = '', - resolvedAbsolute = false; - -for (var i = arguments.length; i >= -1 && !resolvedAbsolute; i--) { - var path = (i >= 0) - ? arguments[i] - : process.cwd(); - - // Skip empty and invalid entries - if (typeof path !== 'string' || !path) { - continue; - } - - resolvedPath = path + '/' + resolvedPath; - resolvedAbsolute = path.charAt(0) === '/'; -} - -// At this point the path should be resolved to a full absolute path, but -// handle relative paths to be safe (might happen when process.cwd() fails) - -// Normalize the path -resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { - return !!p; - }), !resolvedAbsolute).join('/'); - - return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; -}; - -// path.normalize(path) -// posix version -exports.normalize = function(path) { -var isAbsolute = path.charAt(0) === '/', - trailingSlash = path.slice(-1) === '/'; - -// Normalize the path -path = normalizeArray(filter(path.split('/'), function(p) { - return !!p; - }), !isAbsolute).join('/'); - - if (!path && !isAbsolute) { - path = '.'; - } - if (path && trailingSlash) { - path += '/'; - } - - return (isAbsolute ? '/' : '') + path; -}; - - -// posix version -exports.join = function() { - var paths = Array.prototype.slice.call(arguments, 0); - return exports.normalize(filter(paths, function(p, index) { - return p && typeof p === 'string'; - }).join('/')); -}; - - -exports.dirname = function(path) { - var dir = splitPathRe.exec(path)[1] || ''; - var isWindows = false; - if (!dir) { - // No dirname - return '.'; - } else if (dir.length === 1 || - (isWindows && dir.length <= 3 && dir.charAt(1) === ':')) { - // It is just a slash or a drive letter with a slash - return dir; - } else { - // It is a full dirname, strip trailing slash - return dir.substring(0, dir.length - 1); - } -}; - - -exports.basename = function(path, ext) { - var f = splitPathRe.exec(path)[2] || ''; - // TODO: make this comparison case-insensitive on windows? - if (ext && f.substr(-1 * ext.length) === ext) { - f = f.substr(0, f.length - ext.length); - } - return f; -}; - - -exports.extname = function(path) { - return splitPathRe.exec(path)[3] || ''; -}; - -exports.relative = function(from, to) { - from = exports.resolve(from).substr(1); - to = exports.resolve(to).substr(1); - - function trim(arr) { - var start = 0; - for (; start < arr.length; start++) { - if (arr[start] !== '') break; - } - - var end = arr.length - 1; - for (; end >= 0; end--) { - if (arr[end] !== '') break; - } - - if (start > end) return []; - return arr.slice(start, end - start + 1); - } - - var fromParts = trim(from.split('/')); - var toParts = trim(to.split('/')); - - var length = Math.min(fromParts.length, toParts.length); - var samePartsLength = length; - for (var i = 0; i < length; i++) { - if (fromParts[i] !== toParts[i]) { - samePartsLength = i; - break; - } - } - - var outputParts = []; - for (var i = samePartsLength; i < fromParts.length; i++) { - outputParts.push('..'); - } - - outputParts = outputParts.concat(toParts.slice(samePartsLength)); - - return outputParts.join('/'); -}; - -exports.sep = '/'; - -},{"__browserify_process":4}],3:[function(require,module,exports){ -var events = require('events'); - -exports.isArray = isArray; -exports.isDate = function(obj){return Object.prototype.toString.call(obj) === '[object Date]'}; -exports.isRegExp = function(obj){return Object.prototype.toString.call(obj) === '[object RegExp]'}; - - -exports.print = function () {}; -exports.puts = function () {}; -exports.debug = function() {}; - -exports.inspect = function(obj, showHidden, depth, colors) { - var seen = []; - - var stylize = function(str, styleType) { - // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics - var styles = - { 'bold' : [1, 22], - 'italic' : [3, 23], - 'underline' : [4, 24], - 'inverse' : [7, 27], - 'white' : [37, 39], - 'grey' : [90, 39], - 'black' : [30, 39], - 'blue' : [34, 39], - 'cyan' : [36, 39], - 'green' : [32, 39], - 'magenta' : [35, 39], - 'red' : [31, 39], - 'yellow' : [33, 39] }; - - var style = - { 'special': 'cyan', - 'number': 'blue', - 'boolean': 'yellow', - 'undefined': 'grey', - 'null': 'bold', - 'string': 'green', - 'date': 'magenta', - // "name": intentionally not styling - 'regexp': 'red' }[styleType]; - - if (style) { - return '\u001b[' + styles[style][0] + 'm' + str + - '\u001b[' + styles[style][1] + 'm'; - } else { - return str; - } - }; - if (! colors) { - stylize = function(str, styleType) { return str; }; - } - - function format(value, recurseTimes) { - // Provide a hook for user-specified inspect functions. - // Check that value is an object with an inspect function on it - if (value && typeof value.inspect === 'function' && - // Filter out the util module, it's inspect function is special - value !== exports && - // Also filter out any prototype objects using the circular check. - !(value.constructor && value.constructor.prototype === value)) { - return value.inspect(recurseTimes); - } - - // Primitive types cannot have properties - switch (typeof value) { - case 'undefined': - return stylize('undefined', 'undefined'); - - case 'string': - var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') + '\''; - return stylize(simple, 'string'); - - case 'number': - return stylize('' + value, 'number'); - - case 'boolean': - return stylize('' + value, 'boolean'); - } - // For some reason typeof null is "object", so special case here. - if (value === null) { - return stylize('null', 'null'); - } - - // Look up the keys of the object. - var visible_keys = Object_keys(value); - var keys = showHidden ? Object_getOwnPropertyNames(value) : visible_keys; - - // Functions without properties can be shortcutted. - if (typeof value === 'function' && keys.length === 0) { - if (isRegExp(value)) { - return stylize('' + value, 'regexp'); - } else { - var name = value.name ? ': ' + value.name : ''; - return stylize('[Function' + name + ']', 'special'); - } - } - - // Dates without properties can be shortcutted - if (isDate(value) && keys.length === 0) { - return stylize(value.toUTCString(), 'date'); - } - - var base, type, braces; - // Determine the object type - if (isArray(value)) { - type = 'Array'; - braces = ['[', ']']; - } else { - type = 'Object'; - braces = ['{', '}']; - } - - // Make functions say that they are functions - if (typeof value === 'function') { - var n = value.name ? ': ' + value.name : ''; - base = (isRegExp(value)) ? ' ' + value : ' [Function' + n + ']'; - } else { - base = ''; - } - - // Make dates with properties first say the date - if (isDate(value)) { - base = ' ' + value.toUTCString(); - } - - if (keys.length === 0) { - return braces[0] + base + braces[1]; - } - - if (recurseTimes < 0) { - if (isRegExp(value)) { - return stylize('' + value, 'regexp'); - } else { - return stylize('[Object]', 'special'); - } - } - - seen.push(value); - - var output = keys.map(function(key) { - var name, str; - if (value.__lookupGetter__) { - if (value.__lookupGetter__(key)) { - if (value.__lookupSetter__(key)) { - str = stylize('[Getter/Setter]', 'special'); - } else { - str = stylize('[Getter]', 'special'); - } - } else { - if (value.__lookupSetter__(key)) { - str = stylize('[Setter]', 'special'); - } - } - } - if (visible_keys.indexOf(key) < 0) { - name = '[' + key + ']'; - } - if (!str) { - if (seen.indexOf(value[key]) < 0) { - if (recurseTimes === null) { - str = format(value[key]); - } else { - str = format(value[key], recurseTimes - 1); - } - if (str.indexOf('\n') > -1) { - if (isArray(value)) { - str = str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n').substr(2); - } else { - str = '\n' + str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n'); - } - } - } else { - str = stylize('[Circular]', 'special'); - } - } - if (typeof name === 'undefined') { - if (type === 'Array' && key.match(/^\d+$/)) { - return str; - } - name = JSON.stringify('' + key); - if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { - name = name.substr(1, name.length - 2); - name = stylize(name, 'name'); - } else { - name = name.replace(/'/g, "\\'") - .replace(/\\"/g, '"') - .replace(/(^"|"$)/g, "'"); - name = stylize(name, 'string'); - } - } - - return name + ': ' + str; - }); - - seen.pop(); - - var numLinesEst = 0; - var length = output.reduce(function(prev, cur) { - numLinesEst++; - if (cur.indexOf('\n') >= 0) numLinesEst++; - return prev + cur.length + 1; - }, 0); - - if (length > 50) { - output = braces[0] + - (base === '' ? '' : base + '\n ') + - ' ' + - output.join(',\n ') + - ' ' + - braces[1]; - - } else { - output = braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; - } - - return output; - } - return format(obj, (typeof depth === 'undefined' ? 2 : depth)); -}; - - -function isArray(ar) { - return Array.isArray(ar) || - (typeof ar === 'object' && Object.prototype.toString.call(ar) === '[object Array]'); -} - - -function isRegExp(re) { - typeof re === 'object' && Object.prototype.toString.call(re) === '[object RegExp]'; -} - - -function isDate(d) { - return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; -} - -function pad(n) { - return n < 10 ? '0' + n.toString(10) : n.toString(10); -} - -var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', - 'Oct', 'Nov', 'Dec']; - -// 26 Feb 16:19:34 -function timestamp() { - var d = new Date(); - var time = [pad(d.getHours()), - pad(d.getMinutes()), - pad(d.getSeconds())].join(':'); - return [d.getDate(), months[d.getMonth()], time].join(' '); -} - -exports.log = function (msg) {}; - -exports.pump = null; - -var Object_keys = Object.keys || function (obj) { - var res = []; - for (var key in obj) res.push(key); - return res; -}; - -var Object_getOwnPropertyNames = Object.getOwnPropertyNames || function (obj) { - var res = []; - for (var key in obj) { - if (Object.hasOwnProperty.call(obj, key)) res.push(key); - } - return res; -}; - -var Object_create = Object.create || function (prototype, properties) { - // from es5-shim - var object; - if (prototype === null) { - object = { '__proto__' : null }; - } - else { - if (typeof prototype !== 'object') { - throw new TypeError( - 'typeof prototype[' + (typeof prototype) + '] != \'object\'' - ); - } - var Type = function () {}; - Type.prototype = prototype; - object = new Type(); - object.__proto__ = prototype; - } - if (typeof properties !== 'undefined' && Object.defineProperties) { - Object.defineProperties(object, properties); - } - return object; -}; - -exports.inherits = function(ctor, superCtor) { - ctor.super_ = superCtor; - ctor.prototype = Object_create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); -}; - -var formatRegExp = /%[sdj%]/g; -exports.format = function(f) { - if (typeof f !== 'string') { - var objects = []; - for (var i = 0; i < arguments.length; i++) { - objects.push(exports.inspect(arguments[i])); - } - return objects.join(' '); - } - - var i = 1; - var args = arguments; - var len = args.length; - var str = String(f).replace(formatRegExp, function(x) { - if (x === '%%') return '%'; - if (i >= len) return x; - switch (x) { - case '%s': return String(args[i++]); - case '%d': return Number(args[i++]); - case '%j': return JSON.stringify(args[i++]); - default: - return x; - } - }); - for(var x = args[i]; i < len; x = args[++i]){ - if (x === null || typeof x !== 'object') { - str += ' ' + x; - } else { - str += ' ' + exports.inspect(x); - } - } - return str; -}; - -},{"events":1}],4:[function(require,module,exports){ -// shim for using process in browser - -var process = module.exports = {}; - -process.nextTick = (function () { - var canSetImmediate = typeof window !== 'undefined' - && window.setImmediate; - var canPost = typeof window !== 'undefined' - && window.postMessage && window.addEventListener - ; - - if (canSetImmediate) { - return function (f) { return window.setImmediate(f) }; - } - - if (canPost) { - var queue = []; - window.addEventListener('message', function (ev) { - var source = ev.source; - if ((source === window || source === null) && ev.data === 'process-tick') { - ev.stopPropagation(); - if (queue.length > 0) { - var fn = queue.shift(); - fn(); - } - } - }, true); - - return function nextTick(fn) { - queue.push(fn); - window.postMessage('process-tick', '*'); - }; - } - - return function nextTick(fn) { - setTimeout(fn, 0); - }; -})(); - -process.title = 'browser'; -process.browser = true; -process.env = {}; -process.argv = []; - -process.binding = function (name) { - throw new Error('process.binding is not supported'); -} - -// TODO(shtylman) -process.cwd = function () { return '/' }; -process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); -}; - -},{}],5:[function(require,module,exports){ -/** - * Manage access to data, be it to find, update or remove it - */ -var model = require('./model') - , _ = require('underscore') - ; - - - -/** - * Create a new cursor for this collection - * @param {Datastore} db - The datastore this cursor is bound to - * @param {Query} query - The query this cursor will operate on - * @param {Function} execFn - Handler to be executed after cursor has found the results and before the callback passed to find/findOne/update/remove - */ -function Cursor (db, query, execFn) { - this.db = db; - this.query = query || {}; - if (execFn) { this.execFn = execFn; } -} - - -/** - * Set a limit to the number of results - */ -Cursor.prototype.limit = function(limit) { - this._limit = limit; - return this; -}; - - -/** - * Skip a the number of results - */ -Cursor.prototype.skip = function(skip) { - this._skip = skip; - return this; -}; - - -/** - * Sort results of the query - * @param {SortQuery} sortQuery - SortQuery is { field: order }, field can use the dot-notation, order is 1 for ascending and -1 for descending - */ -Cursor.prototype.sort = function(sortQuery) { - this._sort = sortQuery; - return this; -}; - - -/** - * Add the use of a projection - * @param {Object} projection - MongoDB-style projection. {} means take all fields. Then it's { key1: 1, key2: 1 } to take only key1 and key2 - * { key1: 0, key2: 0 } to omit only key1 and key2. Except _id, you can't mix takes and omits - */ -Cursor.prototype.projection = function(projection) { - this._projection = projection; - return this; -}; - - -/** - * Apply the projection - */ -Cursor.prototype.project = function (candidates) { - var res = [], self = this - , keepId, action, keys - ; - - if (this._projection === undefined || Object.keys(this._projection).length === 0) { - return candidates; - } - - keepId = this._projection._id === 0 ? false : true; - this._projection = _.omit(this._projection, '_id'); - - // Check for consistency - keys = Object.keys(this._projection); - keys.forEach(function (k) { - if (action !== undefined && self._projection[k] !== action) { throw new Error("Can't both keep and omit fields except for _id"); } - action = self._projection[k]; - }); - - // Do the actual projection - candidates.forEach(function (candidate) { - var toPush; - if (action === 1) { // pick-type projection - toPush = { $set: {} }; - keys.forEach(function (k) { - toPush.$set[k] = model.getDotValue(candidate, k); - if (toPush.$set[k] === undefined) { delete toPush.$set[k]; } - }); - toPush = model.modify({}, toPush); - } else { // omit-type projection - toPush = { $unset: {} }; - keys.forEach(function (k) { toPush.$unset[k] = true }); - toPush = model.modify(candidate, toPush); - } - if (keepId) { - toPush._id = candidate._id; - } else { - delete toPush._id; - } - res.push(toPush); - }); - - return res; -}; - - -/** - * Get all matching elements - * Will return pointers to matched elements (shallow copies), returning full copies is the role of find or findOne - * This is an internal function, use exec which uses the executor - * - * @param {Function} callback - Signature: err, results - */ -Cursor.prototype._exec = function(_callback) { - var res = [], added = 0, skipped = 0, self = this - , error = null - , i, keys, key - ; - - function callback (error, res) { - if (self.execFn) { - return self.execFn(error, res, _callback); - } else { - return _callback(error, res); - } - } - - this.db.getCandidates(this.query, function (err, candidates) { - if (err) { return callback(err); } - - try { - for (i = 0; i < candidates.length; i += 1) { - if (model.match(candidates[i], self.query)) { - // If a sort is defined, wait for the results to be sorted before applying limit and skip - if (!self._sort) { - if (self._skip && self._skip > skipped) { - skipped += 1; - } else { - res.push(candidates[i]); - added += 1; - if (self._limit && self._limit <= added) { break; } - } - } else { - res.push(candidates[i]); - } - } - } - } catch (err) { - return callback(err); - } - - // Apply all sorts - if (self._sort) { - keys = Object.keys(self._sort); - - // Sorting - var criteria = []; - for (i = 0; i < keys.length; i++) { - key = keys[i]; - criteria.push({ key: key, direction: self._sort[key] }); - } - res.sort(function(a, b) { - var criterion, compare, i; - for (i = 0; i < criteria.length; i++) { - criterion = criteria[i]; - compare = criterion.direction * model.compareThings(model.getDotValue(a, criterion.key), model.getDotValue(b, criterion.key), self.db.compareStrings); - if (compare !== 0) { - return compare; - } - } - return 0; - }); - - // Applying limit and skip - var limit = self._limit || res.length - , skip = self._skip || 0; - - res = res.slice(skip, skip + limit); - } - - // Apply projection - try { - res = self.project(res); - } catch (e) { - error = e; - res = undefined; - } - - return callback(error, res); - }); -}; - -Cursor.prototype.exec = function () { - this.db.executor.push({ this: this, fn: this._exec, arguments: arguments }); -}; - - - -// Interface -module.exports = Cursor; - -},{"./model":10,"underscore":19}],6:[function(require,module,exports){ -/** - * Specific customUtils for the browser, where we don't have access to the Crypto and Buffer modules - */ - -/** - * Taken from the crypto-browserify module - * https://github.com/dominictarr/crypto-browserify - * NOTE: Math.random() does not guarantee "cryptographic quality" but we actually don't need it - */ -function randomBytes (size) { - var bytes = new Array(size); - var r; - - for (var i = 0, r; i < size; i++) { - if ((i & 0x03) == 0) r = Math.random() * 0x100000000; - bytes[i] = r >>> ((i & 0x03) << 3) & 0xff; - } - - return bytes; -} - - -/** - * Taken from the base64-js module - * https://github.com/beatgammit/base64-js/ - */ -function byteArrayToBase64 (uint8) { - var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' - , extraBytes = uint8.length % 3 // if we have 1 byte left, pad 2 bytes - , output = "" - , temp, length, i; - - function tripletToBase64 (num) { - return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]; - }; - - // go through the array every three bytes, we'll deal with trailing stuff later - for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) { - temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); - output += tripletToBase64(temp); - } - - // pad the end with zeros, but make sure to not forget the extra bytes - switch (extraBytes) { - case 1: - temp = uint8[uint8.length - 1]; - output += lookup[temp >> 2]; - output += lookup[(temp << 4) & 0x3F]; - output += '=='; - break; - case 2: - temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1]); - output += lookup[temp >> 10]; - output += lookup[(temp >> 4) & 0x3F]; - output += lookup[(temp << 2) & 0x3F]; - output += '='; - break; - } - - return output; -} - - -/** - * Return a random alphanumerical string of length len - * There is a very small probability (less than 1/1,000,000) for the length to be less than len - * (il the base64 conversion yields too many pluses and slashes) but - * that's not an issue here - * The probability of a collision is extremely small (need 3*10^12 documents to have one chance in a million of a collision) - * See http://en.wikipedia.org/wiki/Birthday_problem - */ -function uid (len) { - return byteArrayToBase64(randomBytes(Math.ceil(Math.max(8, len * 2)))).replace(/[+\/]/g, '').slice(0, len); -} - - - -module.exports.uid = uid; - -},{}],7:[function(require,module,exports){ -var customUtils = require('./customUtils') - , model = require('./model') - , async = require('async') - , Executor = require('./executor') - , Index = require('./indexes') - , util = require('util') - , _ = require('underscore') - , Persistence = require('./persistence') - , Cursor = require('./cursor') - ; - - -/** - * Create a new collection - * @param {String} options.filename Optional, datastore will be in-memory only if not provided - * @param {Boolean} options.timestampData Optional, defaults to false. If set to true, createdAt and updatedAt will be created and populated automatically (if not specified by user) - * @param {Boolean} options.inMemoryOnly Optional, defaults to false - * @param {String} options.nodeWebkitAppName Optional, specify the name of your NW app if you want options.filename to be relative to the directory where - * Node Webkit stores application data such as cookies and local storage (the best place to store data in my opinion) - * @param {Boolean} options.autoload Optional, defaults to false - * @param {Function} options.onload Optional, if autoload is used this will be called after the load database with the error object as parameter. If you don't pass it the error will be thrown - * @param {Function} options.afterSerialization/options.beforeDeserialization Optional, serialization hooks - * @param {Number} options.corruptAlertThreshold Optional, threshold after which an alert is thrown if too much data is corrupt - * @param {Function} options.compareStrings Optional, string comparison function that overrides default for sorting - * - * Event Emitter - Events - * * compaction.done - Fired whenever a compaction operation was finished - */ -function Datastore (options) { - var filename; - - // Retrocompatibility with v0.6 and before - if (typeof options === 'string') { - filename = options; - this.inMemoryOnly = false; // Default - } else { - options = options || {}; - filename = options.filename; - this.inMemoryOnly = options.inMemoryOnly || false; - this.autoload = options.autoload || false; - this.timestampData = options.timestampData || false; - } - - // Determine whether in memory or persistent - if (!filename || typeof filename !== 'string' || filename.length === 0) { - this.filename = null; - this.inMemoryOnly = true; - } else { - this.filename = filename; - } - - // String comparison function - this.compareStrings = options.compareStrings; - - // Persistence handling - this.persistence = new Persistence({ db: this, nodeWebkitAppName: options.nodeWebkitAppName - , afterSerialization: options.afterSerialization - , beforeDeserialization: options.beforeDeserialization - , corruptAlertThreshold: options.corruptAlertThreshold - }); - - // This new executor is ready if we don't use persistence - // If we do, it will only be ready once loadDatabase is called - this.executor = new Executor(); - if (this.inMemoryOnly) { this.executor.ready = true; } - - // Indexed by field name, dot notation can be used - // _id is always indexed and since _ids are generated randomly the underlying - // binary is always well-balanced - this.indexes = {}; - this.indexes._id = new Index({ fieldName: '_id', unique: true }); - this.ttlIndexes = {}; - - // Queue a load of the database right away and call the onload handler - // By default (no onload handler), if there is an error there, no operation will be possible so warn the user by throwing an exception - if (this.autoload) { this.loadDatabase(options.onload || function (err) { - if (err) { throw err; } - }); } -} - -util.inherits(Datastore, require('events').EventEmitter); - - -/** - * Load the database from the datafile, and trigger the execution of buffered commands if any - */ -Datastore.prototype.loadDatabase = function () { - this.executor.push({ this: this.persistence, fn: this.persistence.loadDatabase, arguments: arguments }, true); -}; - - -/** - * Get an array of all the data in the database - */ -Datastore.prototype.getAllData = function () { - return this.indexes._id.getAll(); -}; - - -/** - * Reset all currently defined indexes - */ -Datastore.prototype.resetIndexes = function (newData) { - var self = this; - - Object.keys(this.indexes).forEach(function (i) { - self.indexes[i].reset(newData); - }); -}; - - -/** - * Ensure an index is kept for this field. Same parameters as lib/indexes - * For now this function is synchronous, we need to test how much time it takes - * We use an async API for consistency with the rest of the code - * @param {String} options.fieldName - * @param {Boolean} options.unique - * @param {Boolean} options.sparse - * @param {Number} options.expireAfterSeconds - Optional, if set this index becomes a TTL index (only works on Date fields, not arrays of Date) - * @param {Function} cb Optional callback, signature: err - */ -Datastore.prototype.ensureIndex = function (options, cb) { - var err - , callback = cb || function () {}; - - options = options || {}; - - if (!options.fieldName) { - err = new Error("Cannot create an index without a fieldName"); - err.missingFieldName = true; - return callback(err); - } - if (this.indexes[options.fieldName]) { return callback(null); } - - this.indexes[options.fieldName] = new Index(options); - if (options.expireAfterSeconds !== undefined) { this.ttlIndexes[options.fieldName] = options.expireAfterSeconds; } // With this implementation index creation is not necessary to ensure TTL but we stick with MongoDB's API here - - try { - this.indexes[options.fieldName].insert(this.getAllData()); - } catch (e) { - delete this.indexes[options.fieldName]; - return callback(e); - } - - // We may want to force all options to be persisted including defaults, not just the ones passed the index creation function - this.persistence.persistNewState([{ $$indexCreated: options }], function (err) { - if (err) { return callback(err); } - return callback(null); - }); -}; - - -/** - * Remove an index - * @param {String} fieldName - * @param {Function} cb Optional callback, signature: err - */ -Datastore.prototype.removeIndex = function (fieldName, cb) { - var callback = cb || function () {}; - - delete this.indexes[fieldName]; - - this.persistence.persistNewState([{ $$indexRemoved: fieldName }], function (err) { - if (err) { return callback(err); } - return callback(null); - }); -}; - - -/** - * Add one or several document(s) to all indexes - */ -Datastore.prototype.addToIndexes = function (doc) { - var i, failingIndex, error - , keys = Object.keys(this.indexes) - ; - - for (i = 0; i < keys.length; i += 1) { - try { - this.indexes[keys[i]].insert(doc); - } catch (e) { - failingIndex = i; - error = e; - break; - } - } - - // If an error happened, we need to rollback the insert on all other indexes - if (error) { - for (i = 0; i < failingIndex; i += 1) { - this.indexes[keys[i]].remove(doc); - } - - throw error; - } -}; - - -/** - * Remove one or several document(s) from all indexes - */ -Datastore.prototype.removeFromIndexes = function (doc) { - var self = this; - - Object.keys(this.indexes).forEach(function (i) { - self.indexes[i].remove(doc); - }); -}; - - -/** - * Update one or several documents in all indexes - * To update multiple documents, oldDoc must be an array of { oldDoc, newDoc } pairs - * If one update violates a constraint, all changes are rolled back - */ -Datastore.prototype.updateIndexes = function (oldDoc, newDoc) { - var i, failingIndex, error - , keys = Object.keys(this.indexes) - ; - - for (i = 0; i < keys.length; i += 1) { - try { - this.indexes[keys[i]].update(oldDoc, newDoc); - } catch (e) { - failingIndex = i; - error = e; - break; - } - } - - // If an error happened, we need to rollback the update on all other indexes - if (error) { - for (i = 0; i < failingIndex; i += 1) { - this.indexes[keys[i]].revertUpdate(oldDoc, newDoc); - } - - throw error; - } -}; - - -/** - * Return the list of candidates for a given query - * Crude implementation for now, we return the candidates given by the first usable index if any - * We try the following query types, in this order: basic match, $in match, comparison match - * One way to make it better would be to enable the use of multiple indexes if the first usable index - * returns too much data. I may do it in the future. - * - * Returned candidates will be scanned to find and remove all expired documents - * - * @param {Query} query - * @param {Boolean} dontExpireStaleDocs Optional, defaults to false, if true don't remove stale docs. Useful for the remove function which shouldn't be impacted by expirations - * @param {Function} callback Signature err, candidates - */ -Datastore.prototype.getCandidates = function (query, dontExpireStaleDocs, callback) { - var indexNames = Object.keys(this.indexes) - , self = this - , usableQueryKeys; - - if (typeof dontExpireStaleDocs === 'function') { - callback = dontExpireStaleDocs; - dontExpireStaleDocs = false; - } - - - async.waterfall([ - // STEP 1: get candidates list by checking indexes from most to least frequent usecase - function (cb) { - // For a basic match - usableQueryKeys = []; - Object.keys(query).forEach(function (k) { - if (typeof query[k] === 'string' || typeof query[k] === 'number' || typeof query[k] === 'boolean' || util.isDate(query[k]) || query[k] === null) { - usableQueryKeys.push(k); - } - }); - usableQueryKeys = _.intersection(usableQueryKeys, indexNames); - if (usableQueryKeys.length > 0) { - return cb(null, self.indexes[usableQueryKeys[0]].getMatching(query[usableQueryKeys[0]])); - } - - // For a $in match - usableQueryKeys = []; - Object.keys(query).forEach(function (k) { - if (query[k] && query[k].hasOwnProperty('$in')) { - usableQueryKeys.push(k); - } - }); - usableQueryKeys = _.intersection(usableQueryKeys, indexNames); - if (usableQueryKeys.length > 0) { - return cb(null, self.indexes[usableQueryKeys[0]].getMatching(query[usableQueryKeys[0]].$in)); - } - - // For a comparison match - usableQueryKeys = []; - Object.keys(query).forEach(function (k) { - if (query[k] && (query[k].hasOwnProperty('$lt') || query[k].hasOwnProperty('$lte') || query[k].hasOwnProperty('$gt') || query[k].hasOwnProperty('$gte'))) { - usableQueryKeys.push(k); - } - }); - usableQueryKeys = _.intersection(usableQueryKeys, indexNames); - if (usableQueryKeys.length > 0) { - return cb(null, self.indexes[usableQueryKeys[0]].getBetweenBounds(query[usableQueryKeys[0]])); - } - - // By default, return all the DB data - return cb(null, self.getAllData()); - } - // STEP 2: remove all expired documents - , function (docs) { - if (dontExpireStaleDocs) { return callback(null, docs); } - - var expiredDocsIds = [], validDocs = [], ttlIndexesFieldNames = Object.keys(self.ttlIndexes); - - docs.forEach(function (doc) { - var valid = true; - ttlIndexesFieldNames.forEach(function (i) { - if (doc[i] !== undefined && util.isDate(doc[i]) && Date.now() > doc[i].getTime() + self.ttlIndexes[i] * 1000) { - valid = false; - } - }); - if (valid) { validDocs.push(doc); } else { expiredDocsIds.push(doc._id); } - }); - - async.eachSeries(expiredDocsIds, function (_id, cb) { - self._remove({ _id: _id }, {}, function (err) { - if (err) { return callback(err); } - return cb(); - }); - }, function (err) { - return callback(null, validDocs); - }); - }]); -}; - - -/** - * Insert a new document - * @param {Function} cb Optional callback, signature: err, insertedDoc - * - * @api private Use Datastore.insert which has the same signature - */ -Datastore.prototype._insert = function (newDoc, cb) { - var callback = cb || function () {} - , preparedDoc - ; - - try { - preparedDoc = this.prepareDocumentForInsertion(newDoc) - this._insertInCache(preparedDoc); - } catch (e) { - return callback(e); - } - - this.persistence.persistNewState(util.isArray(preparedDoc) ? preparedDoc : [preparedDoc], function (err) { - if (err) { return callback(err); } - return callback(null, model.deepCopy(preparedDoc)); - }); -}; - -/** - * Create a new _id that's not already in use - */ -Datastore.prototype.createNewId = function () { - var tentativeId = customUtils.uid(16); - // Try as many times as needed to get an unused _id. As explained in customUtils, the probability of this ever happening is extremely small, so this is O(1) - if (this.indexes._id.getMatching(tentativeId).length > 0) { - tentativeId = this.createNewId(); - } - return tentativeId; -}; - -/** - * Prepare a document (or array of documents) to be inserted in a database - * Meaning adds _id and timestamps if necessary on a copy of newDoc to avoid any side effect on user input - * @api private - */ -Datastore.prototype.prepareDocumentForInsertion = function (newDoc) { - var preparedDoc, self = this; - - if (util.isArray(newDoc)) { - preparedDoc = []; - newDoc.forEach(function (doc) { preparedDoc.push(self.prepareDocumentForInsertion(doc)); }); - } else { - preparedDoc = model.deepCopy(newDoc); - if (preparedDoc._id === undefined) { preparedDoc._id = this.createNewId(); } - var now = new Date(); - if (this.timestampData && preparedDoc.createdAt === undefined) { preparedDoc.createdAt = now; } - if (this.timestampData && preparedDoc.updatedAt === undefined) { preparedDoc.updatedAt = now; } - model.checkObject(preparedDoc); - } - - return preparedDoc; -}; - -/** - * If newDoc is an array of documents, this will insert all documents in the cache - * @api private - */ -Datastore.prototype._insertInCache = function (preparedDoc) { - if (util.isArray(preparedDoc)) { - this._insertMultipleDocsInCache(preparedDoc); - } else { - this.addToIndexes(preparedDoc); - } -}; - -/** - * If one insertion fails (e.g. because of a unique constraint), roll back all previous - * inserts and throws the error - * @api private - */ -Datastore.prototype._insertMultipleDocsInCache = function (preparedDocs) { - var i, failingI, error; - - for (i = 0; i < preparedDocs.length; i += 1) { - try { - this.addToIndexes(preparedDocs[i]); - } catch (e) { - error = e; - failingI = i; - break; - } - } - - if (error) { - for (i = 0; i < failingI; i += 1) { - this.removeFromIndexes(preparedDocs[i]); - } - - throw error; - } -}; - -Datastore.prototype.insert = function () { - this.executor.push({ this: this, fn: this._insert, arguments: arguments }); -}; - - -/** - * Count all documents matching the query - * @param {Object} query MongoDB-style query - */ -Datastore.prototype.count = function(query, callback) { - var cursor = new Cursor(this, query, function(err, docs, callback) { - if (err) { return callback(err); } - return callback(null, docs.length); - }); - - if (typeof callback === 'function') { - cursor.exec(callback); - } else { - return cursor; - } -}; - - -/** - * Find all documents matching the query - * If no callback is passed, we return the cursor so that user can limit, skip and finally exec - * @param {Object} query MongoDB-style query - * @param {Object} projection MongoDB-style projection - */ -Datastore.prototype.find = function (query, projection, callback) { - switch (arguments.length) { - case 1: - projection = {}; - // callback is undefined, will return a cursor - break; - case 2: - if (typeof projection === 'function') { - callback = projection; - projection = {}; - } // If not assume projection is an object and callback undefined - break; - } - - var cursor = new Cursor(this, query, function(err, docs, callback) { - var res = [], i; - - if (err) { return callback(err); } - - for (i = 0; i < docs.length; i += 1) { - res.push(model.deepCopy(docs[i])); - } - return callback(null, res); - }); - - cursor.projection(projection); - if (typeof callback === 'function') { - cursor.exec(callback); - } else { - return cursor; - } -}; - - -/** - * Find one document matching the query - * @param {Object} query MongoDB-style query - * @param {Object} projection MongoDB-style projection - */ -Datastore.prototype.findOne = function (query, projection, callback) { - switch (arguments.length) { - case 1: - projection = {}; - // callback is undefined, will return a cursor - break; - case 2: - if (typeof projection === 'function') { - callback = projection; - projection = {}; - } // If not assume projection is an object and callback undefined - break; - } - - var cursor = new Cursor(this, query, function(err, docs, callback) { - if (err) { return callback(err); } - if (docs.length === 1) { - return callback(null, model.deepCopy(docs[0])); - } else { - return callback(null, null); - } - }); - - cursor.projection(projection).limit(1); - if (typeof callback === 'function') { - cursor.exec(callback); - } else { - return cursor; - } -}; - - -/** - * Update all docs matching query - * @param {Object} query - * @param {Object} updateQuery - * @param {Object} options Optional options - * options.multi If true, can update multiple documents (defaults to false) - * options.upsert If true, document is inserted if the query doesn't match anything - * options.returnUpdatedDocs Defaults to false, if true return as third argument the array of updated matched documents (even if no change actually took place) - * @param {Function} cb Optional callback, signature: (err, numAffected, affectedDocuments, upsert) - * If update was an upsert, upsert flag is set to true - * affectedDocuments can be one of the following: - * * For an upsert, the upserted document - * * For an update with returnUpdatedDocs option false, null - * * For an update with returnUpdatedDocs true and multi false, the updated document - * * For an update with returnUpdatedDocs true and multi true, the array of updated documents - * - * WARNING: The API was changed between v1.7.4 and v1.8, for consistency and readability reasons. Prior and including to v1.7.4, - * the callback signature was (err, numAffected, updated) where updated was the updated document in case of an upsert - * or the array of updated documents for an update if the returnUpdatedDocs option was true. That meant that the type of - * affectedDocuments in a non multi update depended on whether there was an upsert or not, leaving only two ways for the - * user to check whether an upsert had occured: checking the type of affectedDocuments or running another find query on - * the whole dataset to check its size. Both options being ugly, the breaking change was necessary. - * - * @api private Use Datastore.update which has the same signature - */ -Datastore.prototype._update = function (query, updateQuery, options, cb) { - var callback - , self = this - , numReplaced = 0 - , multi, upsert - , i - ; - - if (typeof options === 'function') { cb = options; options = {}; } - callback = cb || function () {}; - multi = options.multi !== undefined ? options.multi : false; - upsert = options.upsert !== undefined ? options.upsert : false; - - async.waterfall([ - function (cb) { // If upsert option is set, check whether we need to insert the doc - if (!upsert) { return cb(); } - - // Need to use an internal function not tied to the executor to avoid deadlock - var cursor = new Cursor(self, query); - cursor.limit(1)._exec(function (err, docs) { - if (err) { return callback(err); } - if (docs.length === 1) { - return cb(); - } else { - var toBeInserted; - - try { - model.checkObject(updateQuery); - // updateQuery is a simple object with no modifier, use it as the document to insert - toBeInserted = updateQuery; - } catch (e) { - // updateQuery contains modifiers, use the find query as the base, - // strip it from all operators and update it according to updateQuery - try { - toBeInserted = model.modify(model.deepCopy(query, true), updateQuery); - } catch (err) { - return callback(err); - } - } - - return self._insert(toBeInserted, function (err, newDoc) { - if (err) { return callback(err); } - return callback(null, 1, newDoc, true); - }); - } - }); - } - , function () { // Perform the update - var modifiedDoc , modifications = [], createdAt; - - self.getCandidates(query, function (err, candidates) { - if (err) { return callback(err); } - - // Preparing update (if an error is thrown here neither the datafile nor - // the in-memory indexes are affected) - try { - for (i = 0; i < candidates.length; i += 1) { - if (model.match(candidates[i], query) && (multi || numReplaced === 0)) { - numReplaced += 1; - if (self.timestampData) { createdAt = candidates[i].createdAt; } - modifiedDoc = model.modify(candidates[i], updateQuery); - if (self.timestampData) { - modifiedDoc.createdAt = createdAt; - modifiedDoc.updatedAt = new Date(); - } - modifications.push({ oldDoc: candidates[i], newDoc: modifiedDoc }); - } - } - } catch (err) { - return callback(err); - } - - // Change the docs in memory - try { - self.updateIndexes(modifications); - } catch (err) { - return callback(err); - } - - // Update the datafile - var updatedDocs = _.pluck(modifications, 'newDoc'); - self.persistence.persistNewState(updatedDocs, function (err) { - if (err) { return callback(err); } - if (!options.returnUpdatedDocs) { - return callback(null, numReplaced); - } else { - var updatedDocsDC = []; - updatedDocs.forEach(function (doc) { updatedDocsDC.push(model.deepCopy(doc)); }); - if (! multi) { updatedDocsDC = updatedDocsDC[0]; } - return callback(null, numReplaced, updatedDocsDC); - } - }); - }); - }]); -}; - -Datastore.prototype.update = function () { - this.executor.push({ this: this, fn: this._update, arguments: arguments }); -}; - - -/** - * Remove all docs matching the query - * For now very naive implementation (similar to update) - * @param {Object} query - * @param {Object} options Optional options - * options.multi If true, can update multiple documents (defaults to false) - * @param {Function} cb Optional callback, signature: err, numRemoved - * - * @api private Use Datastore.remove which has the same signature - */ -Datastore.prototype._remove = function (query, options, cb) { - var callback - , self = this, numRemoved = 0, removedDocs = [], multi - ; - - if (typeof options === 'function') { cb = options; options = {}; } - callback = cb || function () {}; - multi = options.multi !== undefined ? options.multi : false; - - this.getCandidates(query, true, function (err, candidates) { - if (err) { return callback(err); } - - try { - candidates.forEach(function (d) { - if (model.match(d, query) && (multi || numRemoved === 0)) { - numRemoved += 1; - removedDocs.push({ $$deleted: true, _id: d._id }); - self.removeFromIndexes(d); - } - }); - } catch (err) { return callback(err); } - - self.persistence.persistNewState(removedDocs, function (err) { - if (err) { return callback(err); } - return callback(null, numRemoved); - }); - }); -}; - -Datastore.prototype.remove = function () { - this.executor.push({ this: this, fn: this._remove, arguments: arguments }); -}; - - - -module.exports = Datastore; - -},{"./cursor":5,"./customUtils":6,"./executor":8,"./indexes":9,"./model":10,"./persistence":11,"async":13,"events":1,"underscore":19,"util":3}],8:[function(require,module,exports){ -var process=require("__browserify_process");/** - * Responsible for sequentially executing actions on the database - */ - -var async = require('async') - ; - -function Executor () { - this.buffer = []; - this.ready = false; - - // This queue will execute all commands, one-by-one in order - this.queue = async.queue(function (task, cb) { - var newArguments = []; - - // task.arguments is an array-like object on which adding a new field doesn't work, so we transform it into a real array - for (var i = 0; i < task.arguments.length; i += 1) { newArguments.push(task.arguments[i]); } - var lastArg = task.arguments[task.arguments.length - 1]; - - // Always tell the queue task is complete. Execute callback if any was given. - if (typeof lastArg === 'function') { - // Callback was supplied - newArguments[newArguments.length - 1] = function () { - if (typeof setImmediate === 'function') { - setImmediate(cb); - } else { - process.nextTick(cb); - } - lastArg.apply(null, arguments); - }; - } else if (!lastArg && task.arguments.length !== 0) { - // false/undefined/null supplied as callbback - newArguments[newArguments.length - 1] = function () { cb(); }; - } else { - // Nothing supplied as callback - newArguments.push(function () { cb(); }); - } - - - task.fn.apply(task.this, newArguments); - }, 1); -} - - -/** - * If executor is ready, queue task (and process it immediately if executor was idle) - * If not, buffer task for later processing - * @param {Object} task - * task.this - Object to use as this - * task.fn - Function to execute - * task.arguments - Array of arguments, IMPORTANT: only the last argument may be a function (the callback) - * and the last argument cannot be false/undefined/null - * @param {Boolean} forceQueuing Optional (defaults to false) force executor to queue task even if it is not ready - */ -Executor.prototype.push = function (task, forceQueuing) { - if (this.ready || forceQueuing) { - this.queue.push(task); - } else { - this.buffer.push(task); - } -}; - - -/** - * Queue all tasks in buffer (in the same order they came in) - * Automatically sets executor as ready - */ -Executor.prototype.processBuffer = function () { - var i; - this.ready = true; - for (i = 0; i < this.buffer.length; i += 1) { this.queue.push(this.buffer[i]); } - this.buffer = []; -}; - - - -// Interface -module.exports = Executor; - -},{"__browserify_process":4,"async":13}],9:[function(require,module,exports){ -var BinarySearchTree = require('binary-search-tree').AVLTree - , model = require('./model') - , _ = require('underscore') - , util = require('util') - ; - -/** - * Two indexed pointers are equal iif they point to the same place - */ -function checkValueEquality (a, b) { - return a === b; -} - -/** - * Type-aware projection - */ -function projectForUnique (elt) { - if (elt === null) { return '$null'; } - if (typeof elt === 'string') { return '$string' + elt; } - if (typeof elt === 'boolean') { return '$boolean' + elt; } - if (typeof elt === 'number') { return '$number' + elt; } - if (util.isArray(elt)) { return '$date' + elt.getTime(); } - - return elt; // Arrays and objects, will check for pointer equality -} - - -/** - * Create a new index - * All methods on an index guarantee that either the whole operation was successful and the index changed - * or the operation was unsuccessful and an error is thrown while the index is unchanged - * @param {String} options.fieldName On which field should the index apply (can use dot notation to index on sub fields) - * @param {Boolean} options.unique Optional, enforce a unique constraint (default: false) - * @param {Boolean} options.sparse Optional, allow a sparse index (we can have documents for which fieldName is undefined) (default: false) - */ -function Index (options) { - this.fieldName = options.fieldName; - this.unique = options.unique || false; - this.sparse = options.sparse || false; - - this.treeOptions = { unique: this.unique, compareKeys: model.compareThings, checkValueEquality: checkValueEquality }; - - this.reset(); // No data in the beginning -} - - -/** - * Reset an index - * @param {Document or Array of documents} newData Optional, data to initialize the index with - * If an error is thrown during insertion, the index is not modified - */ -Index.prototype.reset = function (newData) { - this.tree = new BinarySearchTree(this.treeOptions); - - if (newData) { this.insert(newData); } -}; - - -/** - * Insert a new document in the index - * If an array is passed, we insert all its elements (if one insertion fails the index is not modified) - * O(log(n)) - */ -Index.prototype.insert = function (doc) { - var key, self = this - , keys, i, failingI, error - ; - - if (util.isArray(doc)) { this.insertMultipleDocs(doc); return; } - - key = model.getDotValue(doc, this.fieldName); - - // We don't index documents that don't contain the field if the index is sparse - if (key === undefined && this.sparse) { return; } - - if (!util.isArray(key)) { - this.tree.insert(key, doc); - } else { - // If an insert fails due to a unique constraint, roll back all inserts before it - keys = _.uniq(key, projectForUnique); - - for (i = 0; i < keys.length; i += 1) { - try { - this.tree.insert(keys[i], doc); - } catch (e) { - error = e; - failingI = i; - break; - } - } - - if (error) { - for (i = 0; i < failingI; i += 1) { - this.tree.delete(keys[i], doc); - } - - throw error; - } - } -}; - - -/** - * Insert an array of documents in the index - * If a constraint is violated, the changes should be rolled back and an error thrown - * - * @API private - */ -Index.prototype.insertMultipleDocs = function (docs) { - var i, error, failingI; - - for (i = 0; i < docs.length; i += 1) { - try { - this.insert(docs[i]); - } catch (e) { - error = e; - failingI = i; - break; - } - } - - if (error) { - for (i = 0; i < failingI; i += 1) { - this.remove(docs[i]); - } - - throw error; - } -}; - - -/** - * Remove a document from the index - * If an array is passed, we remove all its elements - * The remove operation is safe with regards to the 'unique' constraint - * O(log(n)) - */ -Index.prototype.remove = function (doc) { - var key, self = this; - - if (util.isArray(doc)) { doc.forEach(function (d) { self.remove(d); }); return; } - - key = model.getDotValue(doc, this.fieldName); - - if (key === undefined && this.sparse) { return; } - - if (!util.isArray(key)) { - this.tree.delete(key, doc); - } else { - _.uniq(key, projectForUnique).forEach(function (_key) { - self.tree.delete(_key, doc); - }); - } -}; - - -/** - * Update a document in the index - * If a constraint is violated, changes are rolled back and an error thrown - * Naive implementation, still in O(log(n)) - */ -Index.prototype.update = function (oldDoc, newDoc) { - if (util.isArray(oldDoc)) { this.updateMultipleDocs(oldDoc); return; } - - this.remove(oldDoc); - - try { - this.insert(newDoc); - } catch (e) { - this.insert(oldDoc); - throw e; - } -}; - - -/** - * Update multiple documents in the index - * If a constraint is violated, the changes need to be rolled back - * and an error thrown - * @param {Array of oldDoc, newDoc pairs} pairs - * - * @API private - */ -Index.prototype.updateMultipleDocs = function (pairs) { - var i, failingI, error; - - for (i = 0; i < pairs.length; i += 1) { - this.remove(pairs[i].oldDoc); - } - - for (i = 0; i < pairs.length; i += 1) { - try { - this.insert(pairs[i].newDoc); - } catch (e) { - error = e; - failingI = i; - break; - } - } - - // If an error was raised, roll back changes in the inverse order - if (error) { - for (i = 0; i < failingI; i += 1) { - this.remove(pairs[i].newDoc); - } - - for (i = 0; i < pairs.length; i += 1) { - this.insert(pairs[i].oldDoc); - } - - throw error; - } -}; - - -/** - * Revert an update - */ -Index.prototype.revertUpdate = function (oldDoc, newDoc) { - var revert = []; - - if (!util.isArray(oldDoc)) { - this.update(newDoc, oldDoc); - } else { - oldDoc.forEach(function (pair) { - revert.push({ oldDoc: pair.newDoc, newDoc: pair.oldDoc }); - }); - this.update(revert); - } -}; - - -/** - * Get all documents in index whose key match value (if it is a Thing) or one of the elements of value (if it is an array of Things) - * @param {Thing} value Value to match the key against - * @return {Array of documents} - */ -Index.prototype.getMatching = function (value) { - var self = this; - - if (!util.isArray(value)) { - return self.tree.search(value); - } else { - var _res = {}, res = []; - - value.forEach(function (v) { - self.getMatching(v).forEach(function (doc) { - _res[doc._id] = doc; - }); - }); - - Object.keys(_res).forEach(function (_id) { - res.push(_res[_id]); - }); - - return res; - } -}; - - -/** - * Get all documents in index whose key is between bounds are they are defined by query - * Documents are sorted by key - * @param {Query} query - * @return {Array of documents} - */ -Index.prototype.getBetweenBounds = function (query) { - return this.tree.betweenBounds(query); -}; - - -/** - * Get all elements in the index - * @return {Array of documents} - */ -Index.prototype.getAll = function () { - var res = []; - - this.tree.executeOnEveryNode(function (node) { - var i; - - for (i = 0; i < node.data.length; i += 1) { - res.push(node.data[i]); - } - }); - - return res; -}; - - - - -// Interface -module.exports = Index; - -},{"./model":10,"binary-search-tree":14,"underscore":19,"util":3}],10:[function(require,module,exports){ -/** - * Handle models (i.e. docs) - * Serialization/deserialization - * Copying - * Querying, update - */ - -var util = require('util') - , _ = require('underscore') - , modifierFunctions = {} - , lastStepModifierFunctions = {} - , comparisonFunctions = {} - , logicalOperators = {} - , arrayComparisonFunctions = {} - ; - - -/** - * Check a key, throw an error if the key is non valid - * @param {String} k key - * @param {Model} v value, needed to treat the Date edge case - * Non-treatable edge cases here: if part of the object if of the form { $$date: number } or { $$deleted: true } - * Its serialized-then-deserialized version it will transformed into a Date object - * But you really need to want it to trigger such behaviour, even when warned not to use '$' at the beginning of the field names... - */ -function checkKey (k, v) { - if (typeof k === 'number') { - k = k.toString(); - } - - if (k[0] === '$' && !(k === '$$date' && typeof v === 'number') && !(k === '$$deleted' && v === true) && !(k === '$$indexCreated') && !(k === '$$indexRemoved')) { - throw new Error('Field names cannot begin with the $ character'); - } - - if (k.indexOf('.') !== -1) { - throw new Error('Field names cannot contain a .'); - } -} - - -/** - * Check a DB object and throw an error if it's not valid - * Works by applying the above checkKey function to all fields recursively - */ -function checkObject (obj) { - if (util.isArray(obj)) { - obj.forEach(function (o) { - checkObject(o); - }); - } - - if (typeof obj === 'object' && obj !== null) { - Object.keys(obj).forEach(function (k) { - checkKey(k, obj[k]); - checkObject(obj[k]); - }); - } -} - - -/** - * Serialize an object to be persisted to a one-line string - * For serialization/deserialization, we use the native JSON parser and not eval or Function - * That gives us less freedom but data entered in the database may come from users - * so eval and the like are not safe - * Accepted primitive types: Number, String, Boolean, Date, null - * Accepted secondary types: Objects, Arrays - */ -function serialize (obj) { - var res; - - res = JSON.stringify(obj, function (k, v) { - checkKey(k, v); - - if (v === undefined) { return undefined; } - if (v === null) { return null; } - - // Hackish way of checking if object is Date (this way it works between execution contexts in node-webkit). - // We can't use value directly because for dates it is already string in this function (date.toJSON was already called), so we use this - if (typeof this[k].getTime === 'function') { return { $$date: this[k].getTime() }; } - - return v; - }); - - return res; -} - - -/** - * From a one-line representation of an object generate by the serialize function - * Return the object itself - */ -function deserialize (rawData) { - return JSON.parse(rawData, function (k, v) { - if (k === '$$date') { return new Date(v); } - if (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean' || v === null) { return v; } - if (v && v.$$date) { return v.$$date; } - - return v; - }); -} - - -/** - * Deep copy a DB object - * The optional strictKeys flag (defaulting to false) indicates whether to copy everything or only fields - * where the keys are valid, i.e. don't begin with $ and don't contain a . - */ -function deepCopy (obj, strictKeys) { - var res; - - if ( typeof obj === 'boolean' || - typeof obj === 'number' || - typeof obj === 'string' || - obj === null || - (util.isDate(obj)) ) { - return obj; - } - - if (util.isArray(obj)) { - res = []; - obj.forEach(function (o) { res.push(deepCopy(o, strictKeys)); }); - return res; - } - - if (typeof obj === 'object') { - res = {}; - Object.keys(obj).forEach(function (k) { - if (!strictKeys || (k[0] !== '$' && k.indexOf('.') === -1)) { - res[k] = deepCopy(obj[k], strictKeys); - } - }); - return res; - } - - return undefined; // For now everything else is undefined. We should probably throw an error instead -} - - -/** - * Tells if an object is a primitive type or a "real" object - * Arrays are considered primitive - */ -function isPrimitiveType (obj) { - return ( typeof obj === 'boolean' || - typeof obj === 'number' || - typeof obj === 'string' || - obj === null || - util.isDate(obj) || - util.isArray(obj)); -} - - -/** - * Utility functions for comparing things - * Assumes type checking was already done (a and b already have the same type) - * compareNSB works for numbers, strings and booleans - */ -function compareNSB (a, b) { - if (a < b) { return -1; } - if (a > b) { return 1; } - return 0; -} - -function compareArrays (a, b) { - var i, comp; - - for (i = 0; i < Math.min(a.length, b.length); i += 1) { - comp = compareThings(a[i], b[i]); - - if (comp !== 0) { return comp; } - } - - // Common section was identical, longest one wins - return compareNSB(a.length, b.length); -} - - -/** - * Compare { things U undefined } - * Things are defined as any native types (string, number, boolean, null, date) and objects - * We need to compare with undefined as it will be used in indexes - * In the case of objects and arrays, we deep-compare - * If two objects dont have the same type, the (arbitrary) type hierarchy is: undefined, null, number, strings, boolean, dates, arrays, objects - * Return -1 if a < b, 1 if a > b and 0 if a = b (note that equality here is NOT the same as defined in areThingsEqual!) - * - * @param {Function} _compareStrings String comparing function, returning -1, 0 or 1, overriding default string comparison (useful for languages with accented letters) - */ -function compareThings (a, b, _compareStrings) { - var aKeys, bKeys, comp, i - , compareStrings = _compareStrings || compareNSB; - - // undefined - if (a === undefined) { return b === undefined ? 0 : -1; } - if (b === undefined) { return a === undefined ? 0 : 1; } - - // null - if (a === null) { return b === null ? 0 : -1; } - if (b === null) { return a === null ? 0 : 1; } - - // Numbers - if (typeof a === 'number') { return typeof b === 'number' ? compareNSB(a, b) : -1; } - if (typeof b === 'number') { return typeof a === 'number' ? compareNSB(a, b) : 1; } - - // Strings - if (typeof a === 'string') { return typeof b === 'string' ? compareStrings(a, b) : -1; } - if (typeof b === 'string') { return typeof a === 'string' ? compareStrings(a, b) : 1; } - - // Booleans - if (typeof a === 'boolean') { return typeof b === 'boolean' ? compareNSB(a, b) : -1; } - if (typeof b === 'boolean') { return typeof a === 'boolean' ? compareNSB(a, b) : 1; } - - // Dates - if (util.isDate(a)) { return util.isDate(b) ? compareNSB(a.getTime(), b.getTime()) : -1; } - if (util.isDate(b)) { return util.isDate(a) ? compareNSB(a.getTime(), b.getTime()) : 1; } - - // Arrays (first element is most significant and so on) - if (util.isArray(a)) { return util.isArray(b) ? compareArrays(a, b) : -1; } - if (util.isArray(b)) { return util.isArray(a) ? compareArrays(a, b) : 1; } - - // Objects - aKeys = Object.keys(a).sort(); - bKeys = Object.keys(b).sort(); - - for (i = 0; i < Math.min(aKeys.length, bKeys.length); i += 1) { - comp = compareThings(a[aKeys[i]], b[bKeys[i]]); - - if (comp !== 0) { return comp; } - } - - return compareNSB(aKeys.length, bKeys.length); -} - - - -// ============================================================== -// Updating documents -// ============================================================== - -/** - * The signature of modifier functions is as follows - * Their structure is always the same: recursively follow the dot notation while creating - * the nested documents if needed, then apply the "last step modifier" - * @param {Object} obj The model to modify - * @param {String} field Can contain dots, in that case that means we will set a subfield recursively - * @param {Model} value - */ - -/** - * Set a field to a new value - */ -lastStepModifierFunctions.$set = function (obj, field, value) { - obj[field] = value; -}; - - -/** - * Unset a field - */ -lastStepModifierFunctions.$unset = function (obj, field, value) { - delete obj[field]; -}; - - -/** - * Push an element to the end of an array field - * Optional modifier $each instead of value to push several values - * Optional modifier $slice to slice the resulting array, see https://docs.mongodb.org/manual/reference/operator/update/slice/ - * Différeence with MongoDB: if $slice is specified and not $each, we act as if value is an empty array - */ -lastStepModifierFunctions.$push = function (obj, field, value) { - // Create the array if it doesn't exist - if (!obj.hasOwnProperty(field)) { obj[field] = []; } - - if (!util.isArray(obj[field])) { throw new Error("Can't $push an element on non-array values"); } - - if (value !== null && typeof value === 'object' && value.$slice && value.$each === undefined) { - value.$each = []; - } - - if (value !== null && typeof value === 'object' && value.$each) { - if (Object.keys(value).length >= 3 || (Object.keys(value).length === 2 && value.$slice === undefined)) { throw new Error("Can only use $slice in cunjunction with $each when $push to array"); } - if (!util.isArray(value.$each)) { throw new Error("$each requires an array value"); } - - value.$each.forEach(function (v) { - obj[field].push(v); - }); - - if (value.$slice === undefined || typeof value.$slice !== 'number') { return; } - - if (value.$slice === 0) { - obj[field] = []; - } else { - var start, end, n = obj[field].length; - if (value.$slice < 0) { - start = Math.max(0, n + value.$slice); - end = n; - } else if (value.$slice > 0) { - start = 0; - end = Math.min(n, value.$slice); - } - obj[field] = obj[field].slice(start, end); - } - } else { - obj[field].push(value); - } -}; - - -/** - * Add an element to an array field only if it is not already in it - * No modification if the element is already in the array - * Note that it doesn't check whether the original array contains duplicates - */ -lastStepModifierFunctions.$addToSet = function (obj, field, value) { - var addToSet = true; - - // Create the array if it doesn't exist - if (!obj.hasOwnProperty(field)) { obj[field] = []; } - - if (!util.isArray(obj[field])) { throw new Error("Can't $addToSet an element on non-array values"); } - - if (value !== null && typeof value === 'object' && value.$each) { - if (Object.keys(value).length > 1) { throw new Error("Can't use another field in conjunction with $each"); } - if (!util.isArray(value.$each)) { throw new Error("$each requires an array value"); } - - value.$each.forEach(function (v) { - lastStepModifierFunctions.$addToSet(obj, field, v); - }); - } else { - obj[field].forEach(function (v) { - if (compareThings(v, value) === 0) { addToSet = false; } - }); - if (addToSet) { obj[field].push(value); } - } -}; - - -/** - * Remove the first or last element of an array - */ -lastStepModifierFunctions.$pop = function (obj, field, value) { - if (!util.isArray(obj[field])) { throw new Error("Can't $pop an element from non-array values"); } - if (typeof value !== 'number') { throw new Error(value + " isn't an integer, can't use it with $pop"); } - if (value === 0) { return; } - - if (value > 0) { - obj[field] = obj[field].slice(0, obj[field].length - 1); - } else { - obj[field] = obj[field].slice(1); - } -}; - - -/** - * Removes all instances of a value from an existing array - */ -lastStepModifierFunctions.$pull = function (obj, field, value) { - var arr, i; - - if (!util.isArray(obj[field])) { throw new Error("Can't $pull an element from non-array values"); } - - arr = obj[field]; - for (i = arr.length - 1; i >= 0; i -= 1) { - if (match(arr[i], value)) { - arr.splice(i, 1); - } - } -}; - - -/** - * Increment a numeric field's value - */ -lastStepModifierFunctions.$inc = function (obj, field, value) { - if (typeof value !== 'number') { throw new Error(value + " must be a number"); } - - if (typeof obj[field] !== 'number') { - if (!_.has(obj, field)) { - obj[field] = value; - } else { - throw new Error("Don't use the $inc modifier on non-number fields"); - } - } else { - obj[field] += value; - } -}; - -/** - * Updates the value of the field, only if specified field is greater than the current value of the field - */ -lastStepModifierFunctions.$max = function (obj, field, value) { - if (typeof obj[field] === 'undefined') { - obj[field] = value; - } else if (value > obj[field]) { - obj[field] = value; - } -}; - -/** - * Updates the value of the field, only if specified field is smaller than the current value of the field - */ -lastStepModifierFunctions.$min = function (obj, field, value) { - if (typeof obj[field] === 'undefined') {  - obj[field] = value; - } else if (value < obj[field]) { - obj[field] = value; - } -}; - -// Given its name, create the complete modifier function -function createModifierFunction (modifier) { - return function (obj, field, value) { - var fieldParts = typeof field === 'string' ? field.split('.') : field; - - if (fieldParts.length === 1) { - lastStepModifierFunctions[modifier](obj, field, value); - } else { - if (obj[fieldParts[0]] === undefined) { - if (modifier === '$unset') { return; } // Bad looking specific fix, needs to be generalized modifiers that behave like $unset are implemented - obj[fieldParts[0]] = {}; - } - modifierFunctions[modifier](obj[fieldParts[0]], fieldParts.slice(1), value); - } - }; -} - -// Actually create all modifier functions -Object.keys(lastStepModifierFunctions).forEach(function (modifier) { - modifierFunctions[modifier] = createModifierFunction(modifier); -}); - - -/** - * Modify a DB object according to an update query - */ -function modify (obj, updateQuery) { - var keys = Object.keys(updateQuery) - , firstChars = _.map(keys, function (item) { return item[0]; }) - , dollarFirstChars = _.filter(firstChars, function (c) { return c === '$'; }) - , newDoc, modifiers - ; - - if (keys.indexOf('_id') !== -1 && updateQuery._id !== obj._id) { throw new Error("You cannot change a document's _id"); } - - if (dollarFirstChars.length !== 0 && dollarFirstChars.length !== firstChars.length) { - throw new Error("You cannot mix modifiers and normal fields"); - } - - if (dollarFirstChars.length === 0) { - // Simply replace the object with the update query contents - newDoc = deepCopy(updateQuery); - newDoc._id = obj._id; - } else { - // Apply modifiers - modifiers = _.uniq(keys); - newDoc = deepCopy(obj); - modifiers.forEach(function (m) { - var keys; - - if (!modifierFunctions[m]) { throw new Error("Unknown modifier " + m); } - - // Can't rely on Object.keys throwing on non objects since ES6 - // Not 100% satisfying as non objects can be interpreted as objects but no false negatives so we can live with it - if (typeof updateQuery[m] !== 'object') { - throw new Error("Modifier " + m + "'s argument must be an object"); - } - - keys = Object.keys(updateQuery[m]); - keys.forEach(function (k) { - modifierFunctions[m](newDoc, k, updateQuery[m][k]); - }); - }); - } - - // Check result is valid and return it - checkObject(newDoc); - - if (obj._id !== newDoc._id) { throw new Error("You can't change a document's _id"); } - return newDoc; -}; - - -// ============================================================== -// Finding documents -// ============================================================== - -/** - * Get a value from object with dot notation - * @param {Object} obj - * @param {String} field - */ -function getDotValue (obj, field) { - var fieldParts = typeof field === 'string' ? field.split('.') : field - , i, objs; - - if (!obj) { return undefined; } // field cannot be empty so that means we should return undefined so that nothing can match - - if (fieldParts.length === 0) { return obj; } - - if (fieldParts.length === 1) { return obj[fieldParts[0]]; } - - if (util.isArray(obj[fieldParts[0]])) { - // If the next field is an integer, return only this item of the array - i = parseInt(fieldParts[1], 10); - if (typeof i === 'number' && !isNaN(i)) { - return getDotValue(obj[fieldParts[0]][i], fieldParts.slice(2)) - } - - // Return the array of values - objs = new Array(); - for (i = 0; i < obj[fieldParts[0]].length; i += 1) { - objs.push(getDotValue(obj[fieldParts[0]][i], fieldParts.slice(1))); - } - return objs; - } else { - return getDotValue(obj[fieldParts[0]], fieldParts.slice(1)); - } -} - - -/** - * Check whether 'things' are equal - * Things are defined as any native types (string, number, boolean, null, date) and objects - * In the case of object, we check deep equality - * Returns true if they are, false otherwise - */ -function areThingsEqual (a, b) { - var aKeys , bKeys , i; - - // Strings, booleans, numbers, null - if (a === null || typeof a === 'string' || typeof a === 'boolean' || typeof a === 'number' || - b === null || typeof b === 'string' || typeof b === 'boolean' || typeof b === 'number') { return a === b; } - - // Dates - if (util.isDate(a) || util.isDate(b)) { return util.isDate(a) && util.isDate(b) && a.getTime() === b.getTime(); } - - // Arrays (no match since arrays are used as a $in) - // undefined (no match since they mean field doesn't exist and can't be serialized) - if ((!(util.isArray(a) && util.isArray(b)) && (util.isArray(a) || util.isArray(b))) || a === undefined || b === undefined) { return false; } - - // General objects (check for deep equality) - // a and b should be objects at this point - try { - aKeys = Object.keys(a); - bKeys = Object.keys(b); - } catch (e) { - return false; - } - - if (aKeys.length !== bKeys.length) { return false; } - for (i = 0; i < aKeys.length; i += 1) { - if (bKeys.indexOf(aKeys[i]) === -1) { return false; } - if (!areThingsEqual(a[aKeys[i]], b[aKeys[i]])) { return false; } - } - return true; -} - - -/** - * Check that two values are comparable - */ -function areComparable (a, b) { - if (typeof a !== 'string' && typeof a !== 'number' && !util.isDate(a) && - typeof b !== 'string' && typeof b !== 'number' && !util.isDate(b)) { - return false; - } - - if (typeof a !== typeof b) { return false; } - - return true; -} - - -/** - * Arithmetic and comparison operators - * @param {Native value} a Value in the object - * @param {Native value} b Value in the query - */ -comparisonFunctions.$lt = function (a, b) { - return areComparable(a, b) && a < b; -}; - -comparisonFunctions.$lte = function (a, b) { - return areComparable(a, b) && a <= b; -}; - -comparisonFunctions.$gt = function (a, b) { - return areComparable(a, b) && a > b; -}; - -comparisonFunctions.$gte = function (a, b) { - return areComparable(a, b) && a >= b; -}; - -comparisonFunctions.$ne = function (a, b) { - if (a === undefined) { return true; } - return !areThingsEqual(a, b); -}; - -comparisonFunctions.$in = function (a, b) { - var i; - - if (!util.isArray(b)) { throw new Error("$in operator called with a non-array"); } - - for (i = 0; i < b.length; i += 1) { - if (areThingsEqual(a, b[i])) { return true; } - } - - return false; -}; - -comparisonFunctions.$nin = function (a, b) { - if (!util.isArray(b)) { throw new Error("$nin operator called with a non-array"); } - - return !comparisonFunctions.$in(a, b); -}; - -comparisonFunctions.$regex = function (a, b) { - if (!util.isRegExp(b)) { throw new Error("$regex operator called with non regular expression"); } - - if (typeof a !== 'string') { - return false - } else { - return b.test(a); - } -}; - -comparisonFunctions.$exists = function (value, exists) { - if (exists || exists === '') { // This will be true for all values of exists except false, null, undefined and 0 - exists = true; // That's strange behaviour (we should only use true/false) but that's the way Mongo does it... - } else { - exists = false; - } - - if (value === undefined) { - return !exists - } else { - return exists; - } -}; - -// Specific to arrays -comparisonFunctions.$size = function (obj, value) { - if (!util.isArray(obj)) { return false; } - if (value % 1 !== 0) { throw new Error("$size operator called without an integer"); } - - return (obj.length == value); -}; -comparisonFunctions.$elemMatch = function (obj, value) { - if (!util.isArray(obj)) { return false; } - var i = obj.length; - var result = false; // Initialize result - while (i--) { - if (match(obj[i], value)) { // If match for array element, return true - result = true; - break; - } - } - return result; -}; -arrayComparisonFunctions.$size = true; -arrayComparisonFunctions.$elemMatch = true; - - -/** - * Match any of the subqueries - * @param {Model} obj - * @param {Array of Queries} query - */ -logicalOperators.$or = function (obj, query) { - var i; - - if (!util.isArray(query)) { throw new Error("$or operator used without an array"); } - - for (i = 0; i < query.length; i += 1) { - if (match(obj, query[i])) { return true; } - } - - return false; -}; - - -/** - * Match all of the subqueries - * @param {Model} obj - * @param {Array of Queries} query - */ -logicalOperators.$and = function (obj, query) { - var i; - - if (!util.isArray(query)) { throw new Error("$and operator used without an array"); } - - for (i = 0; i < query.length; i += 1) { - if (!match(obj, query[i])) { return false; } - } - - return true; -}; - - -/** - * Inverted match of the query - * @param {Model} obj - * @param {Query} query - */ -logicalOperators.$not = function (obj, query) { - return !match(obj, query); -}; - - -/** - * Use a function to match - * @param {Model} obj - * @param {Query} query - */ -logicalOperators.$where = function (obj, fn) { - var result; - - if (!_.isFunction(fn)) { throw new Error("$where operator used without a function"); } - - result = fn.call(obj); - if (!_.isBoolean(result)) { throw new Error("$where function must return boolean"); } - - return result; -}; - - -/** - * Tell if a given document matches a query - * @param {Object} obj Document to check - * @param {Object} query - */ -function match (obj, query) { - var queryKeys, queryKey, queryValue, i; - - // Primitive query against a primitive type - // This is a bit of a hack since we construct an object with an arbitrary key only to dereference it later - // But I don't have time for a cleaner implementation now - if (isPrimitiveType(obj) || isPrimitiveType(query)) { - return matchQueryPart({ needAKey: obj }, 'needAKey', query); - } - - // Normal query - queryKeys = Object.keys(query); - for (i = 0; i < queryKeys.length; i += 1) { - queryKey = queryKeys[i]; - queryValue = query[queryKey]; - - if (queryKey[0] === '$') { - if (!logicalOperators[queryKey]) { throw new Error("Unknown logical operator " + queryKey); } - if (!logicalOperators[queryKey](obj, queryValue)) { return false; } - } else { - if (!matchQueryPart(obj, queryKey, queryValue)) { return false; } - } - } - - return true; -}; - - -/** - * Match an object against a specific { key: value } part of a query - * if the treatObjAsValue flag is set, don't try to match every part separately, but the array as a whole - */ -function matchQueryPart (obj, queryKey, queryValue, treatObjAsValue) { - var objValue = getDotValue(obj, queryKey) - , i, keys, firstChars, dollarFirstChars; - - // Check if the value is an array if we don't force a treatment as value - if (util.isArray(objValue) && !treatObjAsValue) { - // If the queryValue is an array, try to perform an exact match - if (util.isArray(queryValue)) { - return matchQueryPart(obj, queryKey, queryValue, true); - } - - // Check if we are using an array-specific comparison function - if (queryValue !== null && typeof queryValue === 'object' && !util.isRegExp(queryValue)) { - keys = Object.keys(queryValue); - for (i = 0; i < keys.length; i += 1) { - if (arrayComparisonFunctions[keys[i]]) { return matchQueryPart(obj, queryKey, queryValue, true); } - } - } - - // If not, treat it as an array of { obj, query } where there needs to be at least one match - for (i = 0; i < objValue.length; i += 1) { - if (matchQueryPart({ k: objValue[i] }, 'k', queryValue)) { return true; } // k here could be any string - } - return false; - } - - // queryValue is an actual object. Determine whether it contains comparison operators - // or only normal fields. Mixed objects are not allowed - if (queryValue !== null && typeof queryValue === 'object' && !util.isRegExp(queryValue) && !util.isArray(queryValue)) { - keys = Object.keys(queryValue); - firstChars = _.map(keys, function (item) { return item[0]; }); - dollarFirstChars = _.filter(firstChars, function (c) { return c === '$'; }); - - if (dollarFirstChars.length !== 0 && dollarFirstChars.length !== firstChars.length) { - throw new Error("You cannot mix operators and normal fields"); - } - - // queryValue is an object of this form: { $comparisonOperator1: value1, ... } - if (dollarFirstChars.length > 0) { - for (i = 0; i < keys.length; i += 1) { - if (!comparisonFunctions[keys[i]]) { throw new Error("Unknown comparison function " + keys[i]); } - - if (!comparisonFunctions[keys[i]](objValue, queryValue[keys[i]])) { return false; } - } - return true; - } - } - - // Using regular expressions with basic querying - if (util.isRegExp(queryValue)) { return comparisonFunctions.$regex(objValue, queryValue); } - - // queryValue is either a native value or a normal object - // Basic matching is possible - if (!areThingsEqual(objValue, queryValue)) { return false; } - - return true; -} - - -// Interface -module.exports.serialize = serialize; -module.exports.deserialize = deserialize; -module.exports.deepCopy = deepCopy; -module.exports.checkObject = checkObject; -module.exports.isPrimitiveType = isPrimitiveType; -module.exports.modify = modify; -module.exports.getDotValue = getDotValue; -module.exports.match = match; -module.exports.areThingsEqual = areThingsEqual; -module.exports.compareThings = compareThings; - -},{"underscore":19,"util":3}],11:[function(require,module,exports){ -var process=require("__browserify_process");/** - * Handle every persistence-related task - * The interface Datastore expects to be implemented is - * * Persistence.loadDatabase(callback) and callback has signature err - * * Persistence.persistNewState(newDocs, callback) where newDocs is an array of documents and callback has signature err - */ - -var storage = require('./storage') - , path = require('path') - , model = require('./model') - , async = require('async') - , customUtils = require('./customUtils') - , Index = require('./indexes') - ; - - -/** - * Create a new Persistence object for database options.db - * @param {Datastore} options.db - * @param {Boolean} options.nodeWebkitAppName Optional, specify the name of your NW app if you want options.filename to be relative to the directory where - * Node Webkit stores application data such as cookies and local storage (the best place to store data in my opinion) - */ -function Persistence (options) { - var i, j, randomString; - - this.db = options.db; - this.inMemoryOnly = this.db.inMemoryOnly; - this.filename = this.db.filename; - this.corruptAlertThreshold = options.corruptAlertThreshold !== undefined ? options.corruptAlertThreshold : 0.1; - - if (!this.inMemoryOnly && this.filename && this.filename.charAt(this.filename.length - 1) === '~') { - throw new Error("The datafile name can't end with a ~, which is reserved for crash safe backup files"); - } - - // After serialization and before deserialization hooks with some basic sanity checks - if (options.afterSerialization && !options.beforeDeserialization) { - throw new Error("Serialization hook defined but deserialization hook undefined, cautiously refusing to start NeDB to prevent dataloss"); - } - if (!options.afterSerialization && options.beforeDeserialization) { - throw new Error("Serialization hook undefined but deserialization hook defined, cautiously refusing to start NeDB to prevent dataloss"); - } - this.afterSerialization = options.afterSerialization || function (s) { return s; }; - this.beforeDeserialization = options.beforeDeserialization || function (s) { return s; }; - for (i = 1; i < 30; i += 1) { - for (j = 0; j < 10; j += 1) { - randomString = customUtils.uid(i); - if (this.beforeDeserialization(this.afterSerialization(randomString)) !== randomString) { - throw new Error("beforeDeserialization is not the reverse of afterSerialization, cautiously refusing to start NeDB to prevent dataloss"); - } - } - } - - // For NW apps, store data in the same directory where NW stores application data - if (this.filename && options.nodeWebkitAppName) { - console.log("=================================================================="); - console.log("WARNING: The nodeWebkitAppName option is deprecated"); - console.log("To get the path to the directory where Node Webkit stores the data"); - console.log("for your app, use the internal nw.gui module like this"); - console.log("require('nw.gui').App.dataPath"); - console.log("See https://github.com/rogerwang/node-webkit/issues/500"); - console.log("=================================================================="); - this.filename = Persistence.getNWAppFilename(options.nodeWebkitAppName, this.filename); - } -}; - - -/** - * Check if a directory exists and create it on the fly if it is not the case - * cb is optional, signature: err - */ -Persistence.ensureDirectoryExists = function (dir, cb) { - var callback = cb || function () {} - ; - - storage.mkdirp(dir, function (err) { return callback(err); }); -}; - - - - -/** - * Return the path the datafile if the given filename is relative to the directory where Node Webkit stores - * data for this application. Probably the best place to store data - */ -Persistence.getNWAppFilename = function (appName, relativeFilename) { - var home; - - switch (process.platform) { - case 'win32': - case 'win64': - home = process.env.LOCALAPPDATA || process.env.APPDATA; - if (!home) { throw new Error("Couldn't find the base application data folder"); } - home = path.join(home, appName); - break; - case 'darwin': - home = process.env.HOME; - if (!home) { throw new Error("Couldn't find the base application data directory"); } - home = path.join(home, 'Library', 'Application Support', appName); - break; - case 'linux': - home = process.env.HOME; - if (!home) { throw new Error("Couldn't find the base application data directory"); } - home = path.join(home, '.config', appName); - break; - default: - throw new Error("Can't use the Node Webkit relative path for platform " + process.platform); - break; - } - - return path.join(home, 'nedb-data', relativeFilename); -} - - -/** - * Persist cached database - * This serves as a compaction function since the cache always contains only the number of documents in the collection - * while the data file is append-only so it may grow larger - * @param {Function} cb Optional callback, signature: err - */ -Persistence.prototype.persistCachedDatabase = function (cb) { - var callback = cb || function () {} - , toPersist = '' - , self = this - ; - - if (this.inMemoryOnly) { return callback(null); } - - this.db.getAllData().forEach(function (doc) { - toPersist += self.afterSerialization(model.serialize(doc)) + '\n'; - }); - Object.keys(this.db.indexes).forEach(function (fieldName) { - if (fieldName != "_id") { // The special _id index is managed by datastore.js, the others need to be persisted - toPersist += self.afterSerialization(model.serialize({ $$indexCreated: { fieldName: fieldName, unique: self.db.indexes[fieldName].unique, sparse: self.db.indexes[fieldName].sparse }})) + '\n'; - } - }); - - storage.crashSafeWriteFile(this.filename, toPersist, function (err) { - if (err) { return callback(err); } - self.db.emit('compaction.done'); - return callback(null); - }); -}; - - -/** - * Queue a rewrite of the datafile - */ -Persistence.prototype.compactDatafile = function () { - this.db.executor.push({ this: this, fn: this.persistCachedDatabase, arguments: [] }); -}; - - -/** - * Set automatic compaction every interval ms - * @param {Number} interval in milliseconds, with an enforced minimum of 5 seconds - */ -Persistence.prototype.setAutocompactionInterval = function (interval) { - var self = this - , minInterval = 5000 - , realInterval = Math.max(interval || 0, minInterval) - ; - - this.stopAutocompaction(); - - this.autocompactionIntervalId = setInterval(function () { - self.compactDatafile(); - }, realInterval); -}; - - -/** - * Stop autocompaction (do nothing if autocompaction was not running) - */ -Persistence.prototype.stopAutocompaction = function () { - if (this.autocompactionIntervalId) { clearInterval(this.autocompactionIntervalId); } -}; - - -/** - * Persist new state for the given newDocs (can be insertion, update or removal) - * Use an append-only format - * @param {Array} newDocs Can be empty if no doc was updated/removed - * @param {Function} cb Optional, signature: err - */ -Persistence.prototype.persistNewState = function (newDocs, cb) { - var self = this - , toPersist = '' - , callback = cb || function () {} - ; - - // In-memory only datastore - if (self.inMemoryOnly) { return callback(null); } - - newDocs.forEach(function (doc) { - toPersist += self.afterSerialization(model.serialize(doc)) + '\n'; - }); - - if (toPersist.length === 0) { return callback(null); } - - storage.appendFile(self.filename, toPersist, 'utf8', function (err) { - return callback(err); - }); -}; - - -/** - * From a database's raw data, return the corresponding - * machine understandable collection - */ -Persistence.prototype.treatRawData = function (rawData) { - var data = rawData.split('\n') - , dataById = {} - , tdata = [] - , i - , indexes = {} - , corruptItems = -1 // Last line of every data file is usually blank so not really corrupt - ; - - for (i = 0; i < data.length; i += 1) { - var doc; - - try { - doc = model.deserialize(this.beforeDeserialization(data[i])); - if (doc._id) { - if (doc.$$deleted === true) { - delete dataById[doc._id]; - } else { - dataById[doc._id] = doc; - } - } else if (doc.$$indexCreated && doc.$$indexCreated.fieldName != undefined) { - indexes[doc.$$indexCreated.fieldName] = doc.$$indexCreated; - } else if (typeof doc.$$indexRemoved === "string") { - delete indexes[doc.$$indexRemoved]; - } - } catch (e) { - corruptItems += 1; - } - } - - // A bit lenient on corruption - if (data.length > 0 && corruptItems / data.length > this.corruptAlertThreshold) { - throw new Error("More than " + Math.floor(100 * this.corruptAlertThreshold) + "% of the data file is corrupt, the wrong beforeDeserialization hook may be used. Cautiously refusing to start NeDB to prevent dataloss"); - } - - Object.keys(dataById).forEach(function (k) { - tdata.push(dataById[k]); - }); - - return { data: tdata, indexes: indexes }; -}; - - -/** - * Load the database - * 1) Create all indexes - * 2) Insert all data - * 3) Compact the database - * This means pulling data out of the data file or creating it if it doesn't exist - * Also, all data is persisted right away, which has the effect of compacting the database file - * This operation is very quick at startup for a big collection (60ms for ~10k docs) - * @param {Function} cb Optional callback, signature: err - */ -Persistence.prototype.loadDatabase = function (cb) { - var callback = cb || function () {} - , self = this - ; - - self.db.resetIndexes(); - - // In-memory only datastore - if (self.inMemoryOnly) { return callback(null); } - - async.waterfall([ - function (cb) { - Persistence.ensureDirectoryExists(path.dirname(self.filename), function (err) { - storage.ensureDatafileIntegrity(self.filename, function (err) { - storage.readFile(self.filename, 'utf8', function (err, rawData) { - if (err) { return cb(err); } - - try { - var treatedData = self.treatRawData(rawData); - } catch (e) { - return cb(e); - } - - // Recreate all indexes in the datafile - Object.keys(treatedData.indexes).forEach(function (key) { - self.db.indexes[key] = new Index(treatedData.indexes[key]); - }); - - // Fill cached database (i.e. all indexes) with data - try { - self.db.resetIndexes(treatedData.data); - } catch (e) { - self.db.resetIndexes(); // Rollback any index which didn't fail - return cb(e); - } - - self.db.persistence.persistCachedDatabase(cb); - }); - }); - }); - } - ], function (err) { - if (err) { return callback(err); } - - self.db.executor.processBuffer(); - return callback(null); - }); -}; - - -// Interface -module.exports = Persistence; - -},{"./customUtils":6,"./indexes":9,"./model":10,"./storage":12,"__browserify_process":4,"async":13,"path":2}],12:[function(require,module,exports){ -/** - * Way data is stored for this database - * For a Node.js/Node Webkit database it's the file system - * For a browser-side database it's localforage, which uses the best backend available (IndexedDB then WebSQL then localStorage) - * - * This version is the browser version - */ - -var localforage = require('localforage') - -// Configure localforage to display NeDB name for now. Would be a good idea to let user use his own app name -localforage.config({ - name: 'NeDB' -, storeName: 'nedbdata' -}); - - -function exists (filename, callback) { - localforage.getItem(filename, function (err, value) { - if (value !== null) { // Even if value is undefined, localforage returns null - return callback(true); - } else { - return callback(false); - } - }); -} - - -function rename (filename, newFilename, callback) { - localforage.getItem(filename, function (err, value) { - if (value === null) { - localforage.removeItem(newFilename, function () { return callback(); }); - } else { - localforage.setItem(newFilename, value, function () { - localforage.removeItem(filename, function () { return callback(); }); - }); - } - }); -} - - -function writeFile (filename, contents, options, callback) { - // Options do not matter in browser setup - if (typeof options === 'function') { callback = options; } - localforage.setItem(filename, contents, function () { return callback(); }); -} - - -function appendFile (filename, toAppend, options, callback) { - // Options do not matter in browser setup - if (typeof options === 'function') { callback = options; } - - localforage.getItem(filename, function (err, contents) { - contents = contents || ''; - contents += toAppend; - localforage.setItem(filename, contents, function () { return callback(); }); - }); -} - - -function readFile (filename, options, callback) { - // Options do not matter in browser setup - if (typeof options === 'function') { callback = options; } - localforage.getItem(filename, function (err, contents) { return callback(null, contents || ''); }); -} - - -function unlink (filename, callback) { - localforage.removeItem(filename, function () { return callback(); }); -} - - -// Nothing to do, no directories will be used on the browser -function mkdirp (dir, callback) { - return callback(); -} - - -// Nothing to do, no data corruption possible in the brower -function ensureDatafileIntegrity (filename, callback) { - return callback(null); -} - - -// Interface -module.exports.exists = exists; -module.exports.rename = rename; -module.exports.writeFile = writeFile; -module.exports.crashSafeWriteFile = writeFile; // No need for a crash safe function in the browser -module.exports.appendFile = appendFile; -module.exports.readFile = readFile; -module.exports.unlink = unlink; -module.exports.mkdirp = mkdirp; -module.exports.ensureDatafileIntegrity = ensureDatafileIntegrity; - - -},{"localforage":18}],13:[function(require,module,exports){ -var process=require("__browserify_process");/*global setImmediate: false, setTimeout: false, console: false */ -(function () { - - var async = {}; - - // global on the server, window in the browser - var root, previous_async; - - root = this; - if (root != null) { - previous_async = root.async; - } - - async.noConflict = function () { - root.async = previous_async; - return async; - }; - - function only_once(fn) { - var called = false; - return function() { - if (called) throw new Error("Callback was already called."); - called = true; - fn.apply(root, arguments); - } - } - - //// cross-browser compatiblity functions //// - - var _each = function (arr, iterator) { - if (arr.forEach) { - return arr.forEach(iterator); - } - for (var i = 0; i < arr.length; i += 1) { - iterator(arr[i], i, arr); - } - }; - - var _map = function (arr, iterator) { - if (arr.map) { - return arr.map(iterator); - } - var results = []; - _each(arr, function (x, i, a) { - results.push(iterator(x, i, a)); - }); - return results; - }; - - var _reduce = function (arr, iterator, memo) { - if (arr.reduce) { - return arr.reduce(iterator, memo); - } - _each(arr, function (x, i, a) { - memo = iterator(memo, x, i, a); - }); - return memo; - }; - - var _keys = function (obj) { - if (Object.keys) { - return Object.keys(obj); - } - var keys = []; - for (var k in obj) { - if (obj.hasOwnProperty(k)) { - keys.push(k); - } - } - return keys; - }; - - //// exported async module functions //// - - //// nextTick implementation with browser-compatible fallback //// - if (typeof process === 'undefined' || !(process.nextTick)) { - if (typeof setImmediate === 'function') { - async.nextTick = function (fn) { - // not a direct alias for IE10 compatibility - setImmediate(fn); - }; - async.setImmediate = async.nextTick; - } - else { - async.nextTick = function (fn) { - setTimeout(fn, 0); - }; - async.setImmediate = async.nextTick; - } - } - else { - async.nextTick = process.nextTick; - if (typeof setImmediate !== 'undefined') { - async.setImmediate = function (fn) { - // not a direct alias for IE10 compatibility - setImmediate(fn); - }; - } - else { - async.setImmediate = async.nextTick; - } - } - - async.each = function (arr, iterator, callback) { - callback = callback || function () {}; - if (!arr.length) { - return callback(); - } - var completed = 0; - _each(arr, function (x) { - iterator(x, only_once(function (err) { - if (err) { - callback(err); - callback = function () {}; - } - else { - completed += 1; - if (completed >= arr.length) { - callback(null); - } - } - })); - }); - }; - async.forEach = async.each; - - async.eachSeries = function (arr, iterator, callback) { - callback = callback || function () {}; - if (!arr.length) { - return callback(); - } - var completed = 0; - var iterate = function () { - iterator(arr[completed], function (err) { - if (err) { - callback(err); - callback = function () {}; - } - else { - completed += 1; - if (completed >= arr.length) { - callback(null); - } - else { - iterate(); - } - } - }); - }; - iterate(); - }; - async.forEachSeries = async.eachSeries; - - async.eachLimit = function (arr, limit, iterator, callback) { - var fn = _eachLimit(limit); - fn.apply(null, [arr, iterator, callback]); - }; - async.forEachLimit = async.eachLimit; - - var _eachLimit = function (limit) { - - return function (arr, iterator, callback) { - callback = callback || function () {}; - if (!arr.length || limit <= 0) { - return callback(); - } - var completed = 0; - var started = 0; - var running = 0; - - (function replenish () { - if (completed >= arr.length) { - return callback(); - } - - while (running < limit && started < arr.length) { - started += 1; - running += 1; - iterator(arr[started - 1], function (err) { - if (err) { - callback(err); - callback = function () {}; - } - else { - completed += 1; - running -= 1; - if (completed >= arr.length) { - callback(); - } - else { - replenish(); - } - } - }); - } - })(); - }; - }; - - - var doParallel = function (fn) { - return function () { - var args = Array.prototype.slice.call(arguments); - return fn.apply(null, [async.each].concat(args)); - }; - }; - var doParallelLimit = function(limit, fn) { - return function () { - var args = Array.prototype.slice.call(arguments); - return fn.apply(null, [_eachLimit(limit)].concat(args)); - }; - }; - var doSeries = function (fn) { - return function () { - var args = Array.prototype.slice.call(arguments); - return fn.apply(null, [async.eachSeries].concat(args)); - }; - }; - - - var _asyncMap = function (eachfn, arr, iterator, callback) { - var results = []; - arr = _map(arr, function (x, i) { - return {index: i, value: x}; - }); - eachfn(arr, function (x, callback) { - iterator(x.value, function (err, v) { - results[x.index] = v; - callback(err); - }); - }, function (err) { - callback(err, results); - }); - }; - async.map = doParallel(_asyncMap); - async.mapSeries = doSeries(_asyncMap); - async.mapLimit = function (arr, limit, iterator, callback) { - return _mapLimit(limit)(arr, iterator, callback); - }; - - var _mapLimit = function(limit) { - return doParallelLimit(limit, _asyncMap); - }; - - // reduce only has a series version, as doing reduce in parallel won't - // work in many situations. - async.reduce = function (arr, memo, iterator, callback) { - async.eachSeries(arr, function (x, callback) { - iterator(memo, x, function (err, v) { - memo = v; - callback(err); - }); - }, function (err) { - callback(err, memo); - }); - }; - // inject alias - async.inject = async.reduce; - // foldl alias - async.foldl = async.reduce; - - async.reduceRight = function (arr, memo, iterator, callback) { - var reversed = _map(arr, function (x) { - return x; - }).reverse(); - async.reduce(reversed, memo, iterator, callback); - }; - // foldr alias - async.foldr = async.reduceRight; - - var _filter = function (eachfn, arr, iterator, callback) { - var results = []; - arr = _map(arr, function (x, i) { - return {index: i, value: x}; - }); - eachfn(arr, function (x, callback) { - iterator(x.value, function (v) { - if (v) { - results.push(x); - } - callback(); - }); - }, function (err) { - callback(_map(results.sort(function (a, b) { - return a.index - b.index; - }), function (x) { - return x.value; - })); - }); - }; - async.filter = doParallel(_filter); - async.filterSeries = doSeries(_filter); - // select alias - async.select = async.filter; - async.selectSeries = async.filterSeries; - - var _reject = function (eachfn, arr, iterator, callback) { - var results = []; - arr = _map(arr, function (x, i) { - return {index: i, value: x}; - }); - eachfn(arr, function (x, callback) { - iterator(x.value, function (v) { - if (!v) { - results.push(x); - } - callback(); - }); - }, function (err) { - callback(_map(results.sort(function (a, b) { - return a.index - b.index; - }), function (x) { - return x.value; - })); - }); - }; - async.reject = doParallel(_reject); - async.rejectSeries = doSeries(_reject); - - var _detect = function (eachfn, arr, iterator, main_callback) { - eachfn(arr, function (x, callback) { - iterator(x, function (result) { - if (result) { - main_callback(x); - main_callback = function () {}; - } - else { - callback(); - } - }); - }, function (err) { - main_callback(); - }); - }; - async.detect = doParallel(_detect); - async.detectSeries = doSeries(_detect); - - async.some = function (arr, iterator, main_callback) { - async.each(arr, function (x, callback) { - iterator(x, function (v) { - if (v) { - main_callback(true); - main_callback = function () {}; - } - callback(); - }); - }, function (err) { - main_callback(false); - }); - }; - // any alias - async.any = async.some; - - async.every = function (arr, iterator, main_callback) { - async.each(arr, function (x, callback) { - iterator(x, function (v) { - if (!v) { - main_callback(false); - main_callback = function () {}; - } - callback(); - }); - }, function (err) { - main_callback(true); - }); - }; - // all alias - async.all = async.every; - - async.sortBy = function (arr, iterator, callback) { - async.map(arr, function (x, callback) { - iterator(x, function (err, criteria) { - if (err) { - callback(err); - } - else { - callback(null, {value: x, criteria: criteria}); - } - }); - }, function (err, results) { - if (err) { - return callback(err); - } - else { - var fn = function (left, right) { - var a = left.criteria, b = right.criteria; - return a < b ? -1 : a > b ? 1 : 0; - }; - callback(null, _map(results.sort(fn), function (x) { - return x.value; - })); - } - }); - }; - - async.auto = function (tasks, callback) { - callback = callback || function () {}; - var keys = _keys(tasks); - if (!keys.length) { - return callback(null); - } - - var results = {}; - - var listeners = []; - var addListener = function (fn) { - listeners.unshift(fn); - }; - var removeListener = function (fn) { - for (var i = 0; i < listeners.length; i += 1) { - if (listeners[i] === fn) { - listeners.splice(i, 1); - return; - } - } - }; - var taskComplete = function () { - _each(listeners.slice(0), function (fn) { - fn(); - }); - }; - - addListener(function () { - if (_keys(results).length === keys.length) { - callback(null, results); - callback = function () {}; - } - }); - - _each(keys, function (k) { - var task = (tasks[k] instanceof Function) ? [tasks[k]]: tasks[k]; - var taskCallback = function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (args.length <= 1) { - args = args[0]; - } - if (err) { - var safeResults = {}; - _each(_keys(results), function(rkey) { - safeResults[rkey] = results[rkey]; - }); - safeResults[k] = args; - callback(err, safeResults); - // stop subsequent errors hitting callback multiple times - callback = function () {}; - } - else { - results[k] = args; - async.setImmediate(taskComplete); - } - }; - var requires = task.slice(0, Math.abs(task.length - 1)) || []; - var ready = function () { - return _reduce(requires, function (a, x) { - return (a && results.hasOwnProperty(x)); - }, true) && !results.hasOwnProperty(k); - }; - if (ready()) { - task[task.length - 1](taskCallback, results); - } - else { - var listener = function () { - if (ready()) { - removeListener(listener); - task[task.length - 1](taskCallback, results); - } - }; - addListener(listener); - } - }); - }; - - async.waterfall = function (tasks, callback) { - callback = callback || function () {}; - if (tasks.constructor !== Array) { - var err = new Error('First argument to waterfall must be an array of functions'); - return callback(err); - } - if (!tasks.length) { - return callback(); - } - var wrapIterator = function (iterator) { - return function (err) { - if (err) { - callback.apply(null, arguments); - callback = function () {}; - } - else { - var args = Array.prototype.slice.call(arguments, 1); - var next = iterator.next(); - if (next) { - args.push(wrapIterator(next)); - } - else { - args.push(callback); - } - async.setImmediate(function () { - iterator.apply(null, args); - }); - } - }; - }; - wrapIterator(async.iterator(tasks))(); - }; - - var _parallel = function(eachfn, tasks, callback) { - callback = callback || function () {}; - if (tasks.constructor === Array) { - eachfn.map(tasks, function (fn, callback) { - if (fn) { - fn(function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (args.length <= 1) { - args = args[0]; - } - callback.call(null, err, args); - }); - } - }, callback); - } - else { - var results = {}; - eachfn.each(_keys(tasks), function (k, callback) { - tasks[k](function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (args.length <= 1) { - args = args[0]; - } - results[k] = args; - callback(err); - }); - }, function (err) { - callback(err, results); - }); - } - }; - - async.parallel = function (tasks, callback) { - _parallel({ map: async.map, each: async.each }, tasks, callback); - }; - - async.parallelLimit = function(tasks, limit, callback) { - _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback); - }; - - async.series = function (tasks, callback) { - callback = callback || function () {}; - if (tasks.constructor === Array) { - async.mapSeries(tasks, function (fn, callback) { - if (fn) { - fn(function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (args.length <= 1) { - args = args[0]; - } - callback.call(null, err, args); - }); - } - }, callback); - } - else { - var results = {}; - async.eachSeries(_keys(tasks), function (k, callback) { - tasks[k](function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (args.length <= 1) { - args = args[0]; - } - results[k] = args; - callback(err); - }); - }, function (err) { - callback(err, results); - }); - } - }; - - async.iterator = function (tasks) { - var makeCallback = function (index) { - var fn = function () { - if (tasks.length) { - tasks[index].apply(null, arguments); - } - return fn.next(); - }; - fn.next = function () { - return (index < tasks.length - 1) ? makeCallback(index + 1): null; - }; - return fn; - }; - return makeCallback(0); - }; - - async.apply = function (fn) { - var args = Array.prototype.slice.call(arguments, 1); - return function () { - return fn.apply( - null, args.concat(Array.prototype.slice.call(arguments)) - ); - }; - }; - - var _concat = function (eachfn, arr, fn, callback) { - var r = []; - eachfn(arr, function (x, cb) { - fn(x, function (err, y) { - r = r.concat(y || []); - cb(err); - }); - }, function (err) { - callback(err, r); - }); - }; - async.concat = doParallel(_concat); - async.concatSeries = doSeries(_concat); - - async.whilst = function (test, iterator, callback) { - if (test()) { - iterator(function (err) { - if (err) { - return callback(err); - } - async.whilst(test, iterator, callback); - }); - } - else { - callback(); - } - }; - - async.doWhilst = function (iterator, test, callback) { - iterator(function (err) { - if (err) { - return callback(err); - } - if (test()) { - async.doWhilst(iterator, test, callback); - } - else { - callback(); - } - }); - }; - - async.until = function (test, iterator, callback) { - if (!test()) { - iterator(function (err) { - if (err) { - return callback(err); - } - async.until(test, iterator, callback); - }); - } - else { - callback(); - } - }; - - async.doUntil = function (iterator, test, callback) { - iterator(function (err) { - if (err) { - return callback(err); - } - if (!test()) { - async.doUntil(iterator, test, callback); - } - else { - callback(); - } - }); - }; - - async.queue = function (worker, concurrency) { - if (concurrency === undefined) { - concurrency = 1; - } - function _insert(q, data, pos, callback) { - if(data.constructor !== Array) { - data = [data]; - } - _each(data, function(task) { - var item = { - data: task, - callback: typeof callback === 'function' ? callback : null - }; - - if (pos) { - q.tasks.unshift(item); - } else { - q.tasks.push(item); - } - - if (q.saturated && q.tasks.length === concurrency) { - q.saturated(); - } - async.setImmediate(q.process); - }); - } - - var workers = 0; - var q = { - tasks: [], - concurrency: concurrency, - saturated: null, - empty: null, - drain: null, - push: function (data, callback) { - _insert(q, data, false, callback); - }, - unshift: function (data, callback) { - _insert(q, data, true, callback); - }, - process: function () { - if (workers < q.concurrency && q.tasks.length) { - var task = q.tasks.shift(); - if (q.empty && q.tasks.length === 0) { - q.empty(); - } - workers += 1; - var next = function () { - workers -= 1; - if (task.callback) { - task.callback.apply(task, arguments); - } - if (q.drain && q.tasks.length + workers === 0) { - q.drain(); - } - q.process(); - }; - var cb = only_once(next); - worker(task.data, cb); - } - }, - length: function () { - return q.tasks.length; - }, - running: function () { - return workers; - } - }; - return q; - }; - - async.cargo = function (worker, payload) { - var working = false, - tasks = []; - - var cargo = { - tasks: tasks, - payload: payload, - saturated: null, - empty: null, - drain: null, - push: function (data, callback) { - if(data.constructor !== Array) { - data = [data]; - } - _each(data, function(task) { - tasks.push({ - data: task, - callback: typeof callback === 'function' ? callback : null - }); - if (cargo.saturated && tasks.length === payload) { - cargo.saturated(); - } - }); - async.setImmediate(cargo.process); - }, - process: function process() { - if (working) return; - if (tasks.length === 0) { - if(cargo.drain) cargo.drain(); - return; - } - - var ts = typeof payload === 'number' - ? tasks.splice(0, payload) - : tasks.splice(0); - - var ds = _map(ts, function (task) { - return task.data; - }); - - if(cargo.empty) cargo.empty(); - working = true; - worker(ds, function () { - working = false; - - var args = arguments; - _each(ts, function (data) { - if (data.callback) { - data.callback.apply(null, args); - } - }); - - process(); - }); - }, - length: function () { - return tasks.length; - }, - running: function () { - return working; - } - }; - return cargo; - }; - - var _console_fn = function (name) { - return function (fn) { - var args = Array.prototype.slice.call(arguments, 1); - fn.apply(null, args.concat([function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (typeof console !== 'undefined') { - if (err) { - if (console.error) { - console.error(err); - } - } - else if (console[name]) { - _each(args, function (x) { - console[name](x); - }); - } - } - }])); - }; - }; - async.log = _console_fn('log'); - async.dir = _console_fn('dir'); - /*async.info = _console_fn('info'); - async.warn = _console_fn('warn'); - async.error = _console_fn('error');*/ - - async.memoize = function (fn, hasher) { - var memo = {}; - var queues = {}; - hasher = hasher || function (x) { - return x; - }; - var memoized = function () { - var args = Array.prototype.slice.call(arguments); - var callback = args.pop(); - var key = hasher.apply(null, args); - if (key in memo) { - callback.apply(null, memo[key]); - } - else if (key in queues) { - queues[key].push(callback); - } - else { - queues[key] = [callback]; - fn.apply(null, args.concat([function () { - memo[key] = arguments; - var q = queues[key]; - delete queues[key]; - for (var i = 0, l = q.length; i < l; i++) { - q[i].apply(null, arguments); - } - }])); - } - }; - memoized.memo = memo; - memoized.unmemoized = fn; - return memoized; - }; - - async.unmemoize = function (fn) { - return function () { - return (fn.unmemoized || fn).apply(null, arguments); - }; - }; - - async.times = function (count, iterator, callback) { - var counter = []; - for (var i = 0; i < count; i++) { - counter.push(i); - } - return async.map(counter, iterator, callback); - }; - - async.timesSeries = function (count, iterator, callback) { - var counter = []; - for (var i = 0; i < count; i++) { - counter.push(i); - } - return async.mapSeries(counter, iterator, callback); - }; - - async.compose = function (/* functions... */) { - var fns = Array.prototype.reverse.call(arguments); - return function () { - var that = this; - var args = Array.prototype.slice.call(arguments); - var callback = args.pop(); - async.reduce(fns, args, function (newargs, fn, cb) { - fn.apply(that, newargs.concat([function () { - var err = arguments[0]; - var nextargs = Array.prototype.slice.call(arguments, 1); - cb(err, nextargs); - }])) - }, - function (err, results) { - callback.apply(that, [err].concat(results)); - }); - }; - }; - - var _applyEach = function (eachfn, fns /*args...*/) { - var go = function () { - var that = this; - var args = Array.prototype.slice.call(arguments); - var callback = args.pop(); - return eachfn(fns, function (fn, cb) { - fn.apply(that, args.concat([cb])); - }, - callback); - }; - if (arguments.length > 2) { - var args = Array.prototype.slice.call(arguments, 2); - return go.apply(this, args); - } - else { - return go; - } - }; - async.applyEach = doParallel(_applyEach); - async.applyEachSeries = doSeries(_applyEach); - - async.forever = function (fn, callback) { - function next(err) { - if (err) { - if (callback) { - return callback(err); - } - throw err; - } - fn(next); - } - next(); - }; - - // AMD / RequireJS - if (typeof define !== 'undefined' && define.amd) { - define([], function () { - return async; - }); - } - // Node.js - else if (typeof module !== 'undefined' && module.exports) { - module.exports = async; - } - // included directly via - - - - - - - - - - diff --git a/browser-version/test/jquery.min.js b/browser-version/test/jquery.min.js deleted file mode 100755 index ab28a24..0000000 --- a/browser-version/test/jquery.min.js +++ /dev/null @@ -1,4 +0,0 @@ -/*! jQuery v1.11.1 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */ -!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k={},l="1.11.1",m=function(a,b){return new m.fn.init(a,b)},n=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,o=/^-ms-/,p=/-([\da-z])/gi,q=function(a,b){return b.toUpperCase()};m.fn=m.prototype={jquery:l,constructor:m,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=m.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return m.each(this,a,b)},map:function(a){return this.pushStack(m.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},m.extend=m.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||m.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(m.isPlainObject(c)||(b=m.isArray(c)))?(b?(b=!1,f=a&&m.isArray(a)?a:[]):f=a&&m.isPlainObject(a)?a:{},g[d]=m.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},m.extend({expando:"jQuery"+(l+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===m.type(a)},isArray:Array.isArray||function(a){return"array"===m.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return!m.isArray(a)&&a-parseFloat(a)>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==m.type(a)||a.nodeType||m.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(k.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&m.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(o,"ms-").replace(p,q)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=r(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(n,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(r(Object(a))?m.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(g)return g.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=r(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),m.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||m.guid++,e):void 0},now:function(){return+new Date},support:k}),m.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function r(a){var b=a.length,c=m.type(a);return"function"===c||m.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var s=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+-new Date,v=a.document,w=0,x=0,y=gb(),z=gb(),A=gb(),B=function(a,b){return a===b&&(l=!0),0},C="undefined",D=1<<31,E={}.hasOwnProperty,F=[],G=F.pop,H=F.push,I=F.push,J=F.slice,K=F.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},L="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",M="[\\x20\\t\\r\\n\\f]",N="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",O=N.replace("w","w#"),P="\\["+M+"*("+N+")(?:"+M+"*([*^$|!~]?=)"+M+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+O+"))|)"+M+"*\\]",Q=":("+N+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+P+")*)|.*)\\)|)",R=new RegExp("^"+M+"+|((?:^|[^\\\\])(?:\\\\.)*)"+M+"+$","g"),S=new RegExp("^"+M+"*,"+M+"*"),T=new RegExp("^"+M+"*([>+~]|"+M+")"+M+"*"),U=new RegExp("="+M+"*([^\\]'\"]*?)"+M+"*\\]","g"),V=new RegExp(Q),W=new RegExp("^"+O+"$"),X={ID:new RegExp("^#("+N+")"),CLASS:new RegExp("^\\.("+N+")"),TAG:new RegExp("^("+N.replace("w","w*")+")"),ATTR:new RegExp("^"+P),PSEUDO:new RegExp("^"+Q),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+L+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,$=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ab=/[+~]/,bb=/'|\\/g,cb=new RegExp("\\\\([\\da-f]{1,6}"+M+"?|("+M+")|.)","ig"),db=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)};try{I.apply(F=J.call(v.childNodes),v.childNodes),F[v.childNodes.length].nodeType}catch(eb){I={apply:F.length?function(a,b){H.apply(a,J.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function fb(a,b,d,e){var f,h,j,k,l,o,r,s,w,x;if((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,d=d||[],!a||"string"!=typeof a)return d;if(1!==(k=b.nodeType)&&9!==k)return[];if(p&&!e){if(f=_.exec(a))if(j=f[1]){if(9===k){if(h=b.getElementById(j),!h||!h.parentNode)return d;if(h.id===j)return d.push(h),d}else if(b.ownerDocument&&(h=b.ownerDocument.getElementById(j))&&t(b,h)&&h.id===j)return d.push(h),d}else{if(f[2])return I.apply(d,b.getElementsByTagName(a)),d;if((j=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return I.apply(d,b.getElementsByClassName(j)),d}if(c.qsa&&(!q||!q.test(a))){if(s=r=u,w=b,x=9===k&&a,1===k&&"object"!==b.nodeName.toLowerCase()){o=g(a),(r=b.getAttribute("id"))?s=r.replace(bb,"\\$&"):b.setAttribute("id",s),s="[id='"+s+"'] ",l=o.length;while(l--)o[l]=s+qb(o[l]);w=ab.test(a)&&ob(b.parentNode)||b,x=o.join(",")}if(x)try{return I.apply(d,w.querySelectorAll(x)),d}catch(y){}finally{r||b.removeAttribute("id")}}}return i(a.replace(R,"$1"),b,d,e)}function gb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function hb(a){return a[u]=!0,a}function ib(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function jb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function kb(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||D)-(~a.sourceIndex||D);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function lb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function mb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function nb(a){return hb(function(b){return b=+b,hb(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function ob(a){return a&&typeof a.getElementsByTagName!==C&&a}c=fb.support={},f=fb.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=fb.setDocument=function(a){var b,e=a?a.ownerDocument||a:v,g=e.defaultView;return e!==n&&9===e.nodeType&&e.documentElement?(n=e,o=e.documentElement,p=!f(e),g&&g!==g.top&&(g.addEventListener?g.addEventListener("unload",function(){m()},!1):g.attachEvent&&g.attachEvent("onunload",function(){m()})),c.attributes=ib(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ib(function(a){return a.appendChild(e.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=$.test(e.getElementsByClassName)&&ib(function(a){return a.innerHTML="
",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),c.getById=ib(function(a){return o.appendChild(a).id=u,!e.getElementsByName||!e.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if(typeof b.getElementById!==C&&p){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){var c=typeof a.getAttributeNode!==C&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==C?b.getElementsByTagName(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return typeof b.getElementsByClassName!==C&&p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=$.test(e.querySelectorAll))&&(ib(function(a){a.innerHTML="",a.querySelectorAll("[msallowclip^='']").length&&q.push("[*^$]="+M+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+M+"*(?:value|"+L+")"),a.querySelectorAll(":checked").length||q.push(":checked")}),ib(function(a){var b=e.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+M+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=$.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ib(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",Q)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=$.test(o.compareDocumentPosition),t=b||$.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===e||a.ownerDocument===v&&t(v,a)?-1:b===e||b.ownerDocument===v&&t(v,b)?1:k?K.call(k,a)-K.call(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,f=a.parentNode,g=b.parentNode,h=[a],i=[b];if(!f||!g)return a===e?-1:b===e?1:f?-1:g?1:k?K.call(k,a)-K.call(k,b):0;if(f===g)return kb(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)i.unshift(c);while(h[d]===i[d])d++;return d?kb(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},e):n},fb.matches=function(a,b){return fb(a,null,null,b)},fb.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(U,"='$1']"),!(!c.matchesSelector||!p||r&&r.test(b)||q&&q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return fb(b,n,null,[a]).length>0},fb.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},fb.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&E.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},fb.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},fb.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=fb.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=fb.selectors={cacheLength:50,createPseudo:hb,match:X,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(cb,db),a[3]=(a[3]||a[4]||a[5]||"").replace(cb,db),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||fb.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&fb.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return X.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&V.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(cb,db).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+M+")"+a+"("+M+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==C&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=fb.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){k=q[u]||(q[u]={}),j=k[a]||[],n=j[0]===w&&j[1],m=j[0]===w&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[w,n,m];break}}else if(s&&(j=(b[u]||(b[u]={}))[a])&&j[0]===w)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(s&&((l[u]||(l[u]={}))[a]=[w,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||fb.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?hb(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=K.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:hb(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?hb(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:hb(function(a){return function(b){return fb(a,b).length>0}}),contains:hb(function(a){return function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:hb(function(a){return W.test(a||"")||fb.error("unsupported lang: "+a),a=a.replace(cb,db).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Z.test(a.nodeName)},input:function(a){return Y.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:nb(function(){return[0]}),last:nb(function(a,b){return[b-1]}),eq:nb(function(a,b,c){return[0>c?c+b:c]}),even:nb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:nb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:nb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:nb(function(a,b,c){for(var d=0>c?c+b:c;++db;b++)d+=a[b].value;return d}function rb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[u]||(b[u]={}),(h=i[d])&&h[0]===w&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function sb(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function tb(a,b,c){for(var d=0,e=b.length;e>d;d++)fb(a,b[d],c);return c}function ub(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function vb(a,b,c,d,e,f){return d&&!d[u]&&(d=vb(d)),e&&!e[u]&&(e=vb(e,f)),hb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||tb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:ub(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=ub(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?K.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=ub(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):I.apply(g,r)})}function wb(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=rb(function(a){return a===b},h,!0),l=rb(function(a){return K.call(b,a)>-1},h,!0),m=[function(a,c,d){return!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>i;i++)if(c=d.relative[a[i].type])m=[rb(sb(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return vb(i>1&&sb(m),i>1&&qb(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&wb(a.slice(i,e)),f>e&&wb(a=a.slice(e)),f>e&&qb(a))}m.push(c)}return sb(m)}function xb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,m,o,p=0,q="0",r=f&&[],s=[],t=j,u=f||e&&d.find.TAG("*",k),v=w+=null==t?1:Math.random()||.1,x=u.length;for(k&&(j=g!==n&&g);q!==x&&null!=(l=u[q]);q++){if(e&&l){m=0;while(o=a[m++])if(o(l,g,h)){i.push(l);break}k&&(w=v)}c&&((l=!o&&l)&&p--,f&&r.push(l))}if(p+=q,c&&q!==p){m=0;while(o=b[m++])o(r,s,g,h);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=G.call(i));s=ub(s)}I.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&fb.uniqueSort(i)}return k&&(w=v,j=t),r};return c?hb(f):f}return h=fb.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=wb(b[c]),f[u]?d.push(f):e.push(f);f=A(a,xb(e,d)),f.selector=a}return f},i=fb.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(cb,db),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=X.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(cb,db),ab.test(j[0].type)&&ob(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&qb(j),!a)return I.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,ab.test(a)&&ob(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ib(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ib(function(a){return a.innerHTML="","#"===a.firstChild.getAttribute("href")})||jb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ib(function(a){return a.innerHTML="",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||jb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ib(function(a){return null==a.getAttribute("disabled")})||jb(L,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),fb}(a);m.find=s,m.expr=s.selectors,m.expr[":"]=m.expr.pseudos,m.unique=s.uniqueSort,m.text=s.getText,m.isXMLDoc=s.isXML,m.contains=s.contains;var t=m.expr.match.needsContext,u=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,v=/^.[^:#\[\.,]*$/;function w(a,b,c){if(m.isFunction(b))return m.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return m.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(v.test(b))return m.filter(b,a,c);b=m.filter(b,a)}return m.grep(a,function(a){return m.inArray(a,b)>=0!==c})}m.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?m.find.matchesSelector(d,a)?[d]:[]:m.find.matches(a,m.grep(b,function(a){return 1===a.nodeType}))},m.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(m(a).filter(function(){for(b=0;e>b;b++)if(m.contains(d[b],this))return!0}));for(b=0;e>b;b++)m.find(a,d[b],c);return c=this.pushStack(e>1?m.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(w(this,a||[],!1))},not:function(a){return this.pushStack(w(this,a||[],!0))},is:function(a){return!!w(this,"string"==typeof a&&t.test(a)?m(a):a||[],!1).length}});var x,y=a.document,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=m.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||x).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof m?b[0]:b,m.merge(this,m.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:y,!0)),u.test(c[1])&&m.isPlainObject(b))for(c in b)m.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=y.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return x.find(a);this.length=1,this[0]=d}return this.context=y,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):m.isFunction(a)?"undefined"!=typeof x.ready?x.ready(a):a(m):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),m.makeArray(a,this))};A.prototype=m.fn,x=m(y);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};m.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!m(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),m.fn.extend({has:function(a){var b,c=m(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(m.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=t.test(a)||"string"!=typeof a?m(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&m.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?m.unique(f):f)},index:function(a){return a?"string"==typeof a?m.inArray(this[0],m(a)):m.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(m.unique(m.merge(this.get(),m(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}m.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return m.dir(a,"parentNode")},parentsUntil:function(a,b,c){return m.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return m.dir(a,"nextSibling")},prevAll:function(a){return m.dir(a,"previousSibling")},nextUntil:function(a,b,c){return m.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return m.dir(a,"previousSibling",c)},siblings:function(a){return m.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return m.sibling(a.firstChild)},contents:function(a){return m.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:m.merge([],a.childNodes)}},function(a,b){m.fn[a]=function(c,d){var e=m.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=m.filter(d,e)),this.length>1&&(C[a]||(e=m.unique(e)),B.test(a)&&(e=e.reverse())),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return m.each(a.match(E)||[],function(a,c){b[c]=!0}),b}m.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):m.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){m.each(b,function(b,c){var d=m.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&m.each(arguments,function(a,c){var d;while((d=m.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?m.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},m.extend({Deferred:function(a){var b=[["resolve","done",m.Callbacks("once memory"),"resolved"],["reject","fail",m.Callbacks("once memory"),"rejected"],["notify","progress",m.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return m.Deferred(function(c){m.each(b,function(b,f){var g=m.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&m.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?m.extend(a,d):d}},e={};return d.pipe=d.then,m.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&m.isFunction(a.promise)?e:0,g=1===f?a:m.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&m.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;m.fn.ready=function(a){return m.ready.promise().done(a),this},m.extend({isReady:!1,readyWait:1,holdReady:function(a){a?m.readyWait++:m.ready(!0)},ready:function(a){if(a===!0?!--m.readyWait:!m.isReady){if(!y.body)return setTimeout(m.ready);m.isReady=!0,a!==!0&&--m.readyWait>0||(H.resolveWith(y,[m]),m.fn.triggerHandler&&(m(y).triggerHandler("ready"),m(y).off("ready")))}}});function I(){y.addEventListener?(y.removeEventListener("DOMContentLoaded",J,!1),a.removeEventListener("load",J,!1)):(y.detachEvent("onreadystatechange",J),a.detachEvent("onload",J))}function J(){(y.addEventListener||"load"===event.type||"complete"===y.readyState)&&(I(),m.ready())}m.ready.promise=function(b){if(!H)if(H=m.Deferred(),"complete"===y.readyState)setTimeout(m.ready);else if(y.addEventListener)y.addEventListener("DOMContentLoaded",J,!1),a.addEventListener("load",J,!1);else{y.attachEvent("onreadystatechange",J),a.attachEvent("onload",J);var c=!1;try{c=null==a.frameElement&&y.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!m.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}I(),m.ready()}}()}return H.promise(b)};var K="undefined",L;for(L in m(k))break;k.ownLast="0"!==L,k.inlineBlockNeedsLayout=!1,m(function(){var a,b,c,d;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",k.inlineBlockNeedsLayout=a=3===b.offsetWidth,a&&(c.style.zoom=1)),c.removeChild(d))}),function(){var a=y.createElement("div");if(null==k.deleteExpando){k.deleteExpando=!0;try{delete a.test}catch(b){k.deleteExpando=!1}}a=null}(),m.acceptData=function(a){var b=m.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var M=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,N=/([A-Z])/g;function O(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(N,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:M.test(c)?m.parseJSON(c):c}catch(e){}m.data(a,b,c)}else c=void 0}return c}function P(a){var b;for(b in a)if(("data"!==b||!m.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;return!0}function Q(a,b,d,e){if(m.acceptData(a)){var f,g,h=m.expando,i=a.nodeType,j=i?m.cache:a,k=i?a[h]:a[h]&&h; -if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||m.guid++:h),j[k]||(j[k]=i?{}:{toJSON:m.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=m.extend(j[k],b):j[k].data=m.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[m.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[m.camelCase(b)])):f=g,f}}function R(a,b,c){if(m.acceptData(a)){var d,e,f=a.nodeType,g=f?m.cache:a,h=f?a[m.expando]:m.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){m.isArray(b)?b=b.concat(m.map(b,m.camelCase)):b in d?b=[b]:(b=m.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!P(d):!m.isEmptyObject(d))return}(c||(delete g[h].data,P(g[h])))&&(f?m.cleanData([a],!0):k.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}m.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?m.cache[a[m.expando]]:a[m.expando],!!a&&!P(a)},data:function(a,b,c){return Q(a,b,c)},removeData:function(a,b){return R(a,b)},_data:function(a,b,c){return Q(a,b,c,!0)},_removeData:function(a,b){return R(a,b,!0)}}),m.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=m.data(f),1===f.nodeType&&!m._data(f,"parsedAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=m.camelCase(d.slice(5)),O(f,d,e[d])));m._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){m.data(this,a)}):arguments.length>1?this.each(function(){m.data(this,a,b)}):f?O(f,a,m.data(f,a)):void 0},removeData:function(a){return this.each(function(){m.removeData(this,a)})}}),m.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=m._data(a,b),c&&(!d||m.isArray(c)?d=m._data(a,b,m.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=m.queue(a,b),d=c.length,e=c.shift(),f=m._queueHooks(a,b),g=function(){m.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return m._data(a,c)||m._data(a,c,{empty:m.Callbacks("once memory").add(function(){m._removeData(a,b+"queue"),m._removeData(a,c)})})}}),m.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.lengthh;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},W=/^(?:checkbox|radio)$/i;!function(){var a=y.createElement("input"),b=y.createElement("div"),c=y.createDocumentFragment();if(b.innerHTML="
a",k.leadingWhitespace=3===b.firstChild.nodeType,k.tbody=!b.getElementsByTagName("tbody").length,k.htmlSerialize=!!b.getElementsByTagName("link").length,k.html5Clone="<:nav>"!==y.createElement("nav").cloneNode(!0).outerHTML,a.type="checkbox",a.checked=!0,c.appendChild(a),k.appendChecked=a.checked,b.innerHTML="",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,c.appendChild(b),b.innerHTML="",k.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,k.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){k.noCloneEvent=!1}),b.cloneNode(!0).click()),null==k.deleteExpando){k.deleteExpando=!0;try{delete b.test}catch(d){k.deleteExpando=!1}}}(),function(){var b,c,d=y.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(k[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),k[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var X=/^(?:input|select|textarea)$/i,Y=/^key/,Z=/^(?:mouse|pointer|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=/^([^.]*)(?:\.(.+)|)$/;function ab(){return!0}function bb(){return!1}function cb(){try{return y.activeElement}catch(a){}}m.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=m.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof m===K||a&&m.event.triggered===a.type?void 0:m.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(E)||[""],h=b.length;while(h--)f=_.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=m.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=m.event.special[o]||{},l=m.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&m.expr.match.needsContext.test(e),namespace:p.join(".")},i),(n=g[o])||(n=g[o]=[],n.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?n.splice(n.delegateCount++,0,l):n.push(l),m.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m.hasData(a)&&m._data(a);if(r&&(k=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=_.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=m.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,n=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=n.length;while(f--)g=n[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(n.splice(f,1),g.selector&&n.delegateCount--,l.remove&&l.remove.call(a,g));i&&!n.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||m.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)m.event.remove(a,o+b[j],c,d,!0);m.isEmptyObject(k)&&(delete r.handle,m._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,n,o=[d||y],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||y,3!==d.nodeType&&8!==d.nodeType&&!$.test(p+m.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[m.expando]?b:new m.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:m.makeArray(c,[b]),k=m.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!m.isWindow(d)){for(i=k.delegateType||p,$.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||y)&&o.push(l.defaultView||l.parentWindow||a)}n=0;while((h=o[n++])&&!b.isPropagationStopped())b.type=n>1?i:k.bindType||p,f=(m._data(h,"events")||{})[b.type]&&m._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&m.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&m.acceptData(d)&&g&&d[p]&&!m.isWindow(d)){l=d[g],l&&(d[g]=null),m.event.triggered=p;try{d[p]()}catch(r){}m.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=m.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(m._data(this,"events")||{})[a.type]||[],k=m.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=m.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((m.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?m(c,this).index(i)>=0:m.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h]","i"),hb=/^\s+/,ib=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,jb=/<([\w:]+)/,kb=/\s*$/g,rb={option:[1,""],legend:[1,"
","
"],area:[1,"",""],param:[1,"",""],thead:[1,"","
"],tr:[2,"","
"],col:[2,"","
"],td:[3,"","
"],_default:k.htmlSerialize?[0,"",""]:[1,"X
","
"]},sb=db(y),tb=sb.appendChild(y.createElement("div"));rb.optgroup=rb.option,rb.tbody=rb.tfoot=rb.colgroup=rb.caption=rb.thead,rb.th=rb.td;function ub(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==K?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==K?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||m.nodeName(d,b)?f.push(d):m.merge(f,ub(d,b));return void 0===b||b&&m.nodeName(a,b)?m.merge([a],f):f}function vb(a){W.test(a.type)&&(a.defaultChecked=a.checked)}function wb(a,b){return m.nodeName(a,"table")&&m.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function xb(a){return a.type=(null!==m.find.attr(a,"type"))+"/"+a.type,a}function yb(a){var b=pb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function zb(a,b){for(var c,d=0;null!=(c=a[d]);d++)m._data(c,"globalEval",!b||m._data(b[d],"globalEval"))}function Ab(a,b){if(1===b.nodeType&&m.hasData(a)){var c,d,e,f=m._data(a),g=m._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)m.event.add(b,c,h[c][d])}g.data&&(g.data=m.extend({},g.data))}}function Bb(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!k.noCloneEvent&&b[m.expando]){e=m._data(b);for(d in e.events)m.removeEvent(b,d,e.handle);b.removeAttribute(m.expando)}"script"===c&&b.text!==a.text?(xb(b).text=a.text,yb(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),k.html5Clone&&a.innerHTML&&!m.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&W.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}m.extend({clone:function(a,b,c){var d,e,f,g,h,i=m.contains(a.ownerDocument,a);if(k.html5Clone||m.isXMLDoc(a)||!gb.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(tb.innerHTML=a.outerHTML,tb.removeChild(f=tb.firstChild)),!(k.noCloneEvent&&k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||m.isXMLDoc(a)))for(d=ub(f),h=ub(a),g=0;null!=(e=h[g]);++g)d[g]&&Bb(e,d[g]);if(b)if(c)for(h=h||ub(a),d=d||ub(f),g=0;null!=(e=h[g]);g++)Ab(e,d[g]);else Ab(a,f);return d=ub(f,"script"),d.length>0&&zb(d,!i&&ub(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,l,n=a.length,o=db(b),p=[],q=0;n>q;q++)if(f=a[q],f||0===f)if("object"===m.type(f))m.merge(p,f.nodeType?[f]:f);else if(lb.test(f)){h=h||o.appendChild(b.createElement("div")),i=(jb.exec(f)||["",""])[1].toLowerCase(),l=rb[i]||rb._default,h.innerHTML=l[1]+f.replace(ib,"<$1>")+l[2],e=l[0];while(e--)h=h.lastChild;if(!k.leadingWhitespace&&hb.test(f)&&p.push(b.createTextNode(hb.exec(f)[0])),!k.tbody){f="table"!==i||kb.test(f)?""!==l[1]||kb.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)m.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}m.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),k.appendChecked||m.grep(ub(p,"input"),vb),q=0;while(f=p[q++])if((!d||-1===m.inArray(f,d))&&(g=m.contains(f.ownerDocument,f),h=ub(o.appendChild(f),"script"),g&&zb(h),c)){e=0;while(f=h[e++])ob.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=m.expando,j=m.cache,l=k.deleteExpando,n=m.event.special;null!=(d=a[h]);h++)if((b||m.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)n[e]?m.event.remove(d,e):m.removeEvent(d,e,g.handle);j[f]&&(delete j[f],l?delete d[i]:typeof d.removeAttribute!==K?d.removeAttribute(i):d[i]=null,c.push(f))}}}),m.fn.extend({text:function(a){return V(this,function(a){return void 0===a?m.text(this):this.empty().append((this[0]&&this[0].ownerDocument||y).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wb(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wb(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?m.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||m.cleanData(ub(c)),c.parentNode&&(b&&m.contains(c.ownerDocument,c)&&zb(ub(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&m.cleanData(ub(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&m.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return m.clone(this,a,b)})},html:function(a){return V(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(fb,""):void 0;if(!("string"!=typeof a||mb.test(a)||!k.htmlSerialize&&gb.test(a)||!k.leadingWhitespace&&hb.test(a)||rb[(jb.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(ib,"<$1>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(m.cleanData(ub(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,m.cleanData(ub(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,l=this.length,n=this,o=l-1,p=a[0],q=m.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&nb.test(p))return this.each(function(c){var d=n.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(i=m.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=m.map(ub(i,"script"),xb),f=g.length;l>j;j++)d=i,j!==o&&(d=m.clone(d,!0,!0),f&&m.merge(g,ub(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,m.map(g,yb),j=0;f>j;j++)d=g[j],ob.test(d.type||"")&&!m._data(d,"globalEval")&&m.contains(h,d)&&(d.src?m._evalUrl&&m._evalUrl(d.src):m.globalEval((d.text||d.textContent||d.innerHTML||"").replace(qb,"")));i=c=null}return this}}),m.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){m.fn[a]=function(a){for(var c,d=0,e=[],g=m(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),m(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Cb,Db={};function Eb(b,c){var d,e=m(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:m.css(e[0],"display");return e.detach(),f}function Fb(a){var b=y,c=Db[a];return c||(c=Eb(a,b),"none"!==c&&c||(Cb=(Cb||m("