pouchdb-all-dbs
Version:
PouchDB allDbs plugin
830 lines (736 loc) • 21 kB
JavaScript
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
(function (process){
;
var Promise = require('pouchdb-promise');
/* istanbul ignore next */
exports.once = function (fun) {
var called = false;
return exports.getArguments(function (args) {
if (called) {
console.trace();
throw new Error('once called more than once');
} else {
called = true;
fun.apply(this, args);
}
});
};
/* istanbul ignore next */
exports.getArguments = function (fun) {
return function () {
var len = arguments.length;
var args = new Array(len);
var i = -1;
while (++i < len) {
args[i] = arguments[i];
}
return fun.call(this, args);
};
};
/* istanbul ignore next */
exports.toPromise = function (func) {
//create the function we will be returning
return exports.getArguments(function (args) {
var self = this;
var tempCB = (typeof args[args.length - 1] === 'function') ? args.pop() : false;
// if the last argument is a function, assume its a callback
var usedCB;
if (tempCB) {
// if it was a callback, create a new callback which calls it,
// but do so async so we don't trap any errors
usedCB = function (err, resp) {
process.nextTick(function () {
tempCB(err, resp);
});
};
}
var promise = new Promise(function (fulfill, reject) {
try {
var callback = exports.once(function (err, mesg) {
if (err) {
reject(err);
} else {
fulfill(mesg);
}
});
// create a callback for this invocation
// apply the function in the orig context
args.push(callback);
func.apply(self, args);
} catch (e) {
reject(e);
}
});
// if there is a callback, call it back
if (usedCB) {
promise.then(function (result) {
usedCB(null, result);
}, usedCB);
}
promise.cancel = function () {
return this;
};
return promise;
});
};
exports.inherits = require('inherits');
}).call(this,require('_process'))
},{"_process":8,"inherits":5,"pouchdb-promise":7}],2:[function(require,module,exports){
(function (process,global){
;
var argsarray = require('argsarray');
var Queue = require('tiny-queue');
// see http://stackoverflow.com/a/15349865/680742
/* istanbul ignore next */
var nextTick = global.setImmediate || process.nextTick;
function TaskQueue() {
this.queue = new Queue();
this.running = false;
}
TaskQueue.prototype.add = function (fun, callback) {
callback = callback || function () {};
this.queue.push({fun: fun, callback: callback});
this.processNext();
};
TaskQueue.prototype.processNext = function () {
var self = this;
if (self.running || !self.queue.length) {
return;
}
self.running = true;
var task = self.queue.shift();
nextTick(function () {
task.fun(argsarray(function (args) {
task.callback.apply(null, args);
self.running = false;
self.processNext();
}));
});
};
module.exports = TaskQueue;
}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"_process":8,"argsarray":3,"tiny-queue":9}],3:[function(require,module,exports){
;
module.exports = argsArray;
function argsArray(fun) {
return function () {
var len = arguments.length;
if (len) {
var args = [];
var i = -1;
while (++i < len) {
args[i] = arguments[i];
}
return fun.call(this, args);
} else {
return fun.call(this, []);
}
};
}
},{}],4:[function(require,module,exports){
(function (global){
;
var Mutation = global.MutationObserver || global.WebKitMutationObserver;
var scheduleDrain;
{
if (Mutation) {
var called = 0;
var observer = new Mutation(nextTick);
var element = global.document.createTextNode('');
observer.observe(element, {
characterData: true
});
scheduleDrain = function () {
element.data = (called = ++called % 2);
};
} else if (!global.setImmediate && typeof global.MessageChannel !== 'undefined') {
var channel = new global.MessageChannel();
channel.port1.onmessage = nextTick;
scheduleDrain = function () {
channel.port2.postMessage(0);
};
} else if ('document' in global && 'onreadystatechange' in global.document.createElement('script')) {
scheduleDrain = function () {
// Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
// into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
var scriptEl = global.document.createElement('script');
scriptEl.onreadystatechange = function () {
nextTick();
scriptEl.onreadystatechange = null;
scriptEl.parentNode.removeChild(scriptEl);
scriptEl = null;
};
global.document.documentElement.appendChild(scriptEl);
};
} else {
scheduleDrain = function () {
setTimeout(nextTick, 0);
};
}
}
var draining;
var queue = [];
//named nextTick for less confusing stack traces
function nextTick() {
draining = true;
var i, oldQueue;
var len = queue.length;
while (len) {
oldQueue = queue;
queue = [];
i = -1;
while (++i < len) {
oldQueue[i]();
}
len = queue.length;
}
draining = false;
}
module.exports = immediate;
function immediate(task) {
if (queue.push(task) === 1 && !draining) {
scheduleDrain();
}
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],5:[function(require,module,exports){
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
},{}],6:[function(require,module,exports){
;
var immediate = require('immediate');
/* istanbul ignore next */
function INTERNAL() {}
var handlers = {};
var REJECTED = ['REJECTED'];
var FULFILLED = ['FULFILLED'];
var PENDING = ['PENDING'];
module.exports = Promise;
function Promise(resolver) {
if (typeof resolver !== 'function') {
throw new TypeError('resolver must be a function');
}
this.state = PENDING;
this.queue = [];
this.outcome = void 0;
if (resolver !== INTERNAL) {
safelyResolveThenable(this, resolver);
}
}
Promise.prototype["catch"] = function (onRejected) {
return this.then(null, onRejected);
};
Promise.prototype.then = function (onFulfilled, onRejected) {
if (typeof onFulfilled !== 'function' && this.state === FULFILLED ||
typeof onRejected !== 'function' && this.state === REJECTED) {
return this;
}
var promise = new this.constructor(INTERNAL);
if (this.state !== PENDING) {
var resolver = this.state === FULFILLED ? onFulfilled : onRejected;
unwrap(promise, resolver, this.outcome);
} else {
this.queue.push(new QueueItem(promise, onFulfilled, onRejected));
}
return promise;
};
function QueueItem(promise, onFulfilled, onRejected) {
this.promise = promise;
if (typeof onFulfilled === 'function') {
this.onFulfilled = onFulfilled;
this.callFulfilled = this.otherCallFulfilled;
}
if (typeof onRejected === 'function') {
this.onRejected = onRejected;
this.callRejected = this.otherCallRejected;
}
}
QueueItem.prototype.callFulfilled = function (value) {
handlers.resolve(this.promise, value);
};
QueueItem.prototype.otherCallFulfilled = function (value) {
unwrap(this.promise, this.onFulfilled, value);
};
QueueItem.prototype.callRejected = function (value) {
handlers.reject(this.promise, value);
};
QueueItem.prototype.otherCallRejected = function (value) {
unwrap(this.promise, this.onRejected, value);
};
function unwrap(promise, func, value) {
immediate(function () {
var returnValue;
try {
returnValue = func(value);
} catch (e) {
return handlers.reject(promise, e);
}
if (returnValue === promise) {
handlers.reject(promise, new TypeError('Cannot resolve promise with itself'));
} else {
handlers.resolve(promise, returnValue);
}
});
}
handlers.resolve = function (self, value) {
var result = tryCatch(getThen, value);
if (result.status === 'error') {
return handlers.reject(self, result.value);
}
var thenable = result.value;
if (thenable) {
safelyResolveThenable(self, thenable);
} else {
self.state = FULFILLED;
self.outcome = value;
var i = -1;
var len = self.queue.length;
while (++i < len) {
self.queue[i].callFulfilled(value);
}
}
return self;
};
handlers.reject = function (self, error) {
self.state = REJECTED;
self.outcome = error;
var i = -1;
var len = self.queue.length;
while (++i < len) {
self.queue[i].callRejected(error);
}
return self;
};
function getThen(obj) {
// Make sure we only access the accessor once as required by the spec
var then = obj && obj.then;
if (obj && typeof obj === 'object' && typeof then === 'function') {
return function appyThen() {
then.apply(obj, arguments);
};
}
}
function safelyResolveThenable(self, thenable) {
// Either fulfill, reject or reject with error
var called = false;
function onError(value) {
if (called) {
return;
}
called = true;
handlers.reject(self, value);
}
function onSuccess(value) {
if (called) {
return;
}
called = true;
handlers.resolve(self, value);
}
function tryToUnwrap() {
thenable(onSuccess, onError);
}
var result = tryCatch(tryToUnwrap);
if (result.status === 'error') {
onError(result.value);
}
}
function tryCatch(func, value) {
var out = {};
try {
out.value = func(value);
out.status = 'success';
} catch (e) {
out.status = 'error';
out.value = e;
}
return out;
}
Promise.resolve = resolve;
function resolve(value) {
if (value instanceof this) {
return value;
}
return handlers.resolve(new this(INTERNAL), value);
}
Promise.reject = reject;
function reject(reason) {
var promise = new this(INTERNAL);
return handlers.reject(promise, reason);
}
Promise.all = all;
function all(iterable) {
var self = this;
if (Object.prototype.toString.call(iterable) !== '[object Array]') {
return this.reject(new TypeError('must be an array'));
}
var len = iterable.length;
var called = false;
if (!len) {
return this.resolve([]);
}
var values = new Array(len);
var resolved = 0;
var i = -1;
var promise = new this(INTERNAL);
while (++i < len) {
allResolver(iterable[i], i);
}
return promise;
function allResolver(value, i) {
self.resolve(value).then(resolveFromAll, function (error) {
if (!called) {
called = true;
handlers.reject(promise, error);
}
});
function resolveFromAll(outValue) {
values[i] = outValue;
if (++resolved === len && !called) {
called = true;
handlers.resolve(promise, values);
}
}
}
}
Promise.race = race;
function race(iterable) {
var self = this;
if (Object.prototype.toString.call(iterable) !== '[object Array]') {
return this.reject(new TypeError('must be an array'));
}
var len = iterable.length;
var called = false;
if (!len) {
return this.resolve([]);
}
var i = -1;
var promise = new this(INTERNAL);
while (++i < len) {
resolver(iterable[i]);
}
return promise;
function resolver(value) {
self.resolve(value).then(function (response) {
if (!called) {
called = true;
handlers.resolve(promise, response);
}
}, function (error) {
if (!called) {
called = true;
handlers.reject(promise, error);
}
});
}
}
},{"immediate":4}],7:[function(require,module,exports){
;
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var lie = _interopDefault(require('lie'));
/* istanbul ignore next */
var PouchPromise = typeof Promise === 'function' ? Promise : lie;
module.exports = PouchPromise;
},{"lie":6}],8:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
(function () {
try {
cachedSetTimeout = setTimeout;
} catch (e) {
cachedSetTimeout = function () {
throw new Error('setTimeout is not defined');
}
}
try {
cachedClearTimeout = clearTimeout;
} catch (e) {
cachedClearTimeout = function () {
throw new Error('clearTimeout is not defined');
}
}
} ())
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = cachedSetTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
cachedClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
cachedSetTimeout(drainQueue, 0);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}],9:[function(require,module,exports){
;
// Simple FIFO queue implementation to avoid having to do shift()
// on an array, which is slow.
function Queue() {
this.length = 0;
}
Queue.prototype.push = function (item) {
var node = {item: item};
if (this.last) {
this.last = this.last.next = node;
} else {
this.last = this.first = node;
}
this.length++;
};
Queue.prototype.shift = function () {
var node = this.first;
if (node) {
this.first = node.next;
if (!(--this.length)) {
this.last = undefined;
}
return node.item;
}
};
Queue.prototype.slice = function (start, end) {
start = typeof start === 'undefined' ? 0 : start;
end = typeof end === 'undefined' ? Infinity : end;
var output = [];
var i = 0;
for (var node = this.first; node; node = node.next) {
if (--end < 0) {
break;
} else if (++i > start) {
output.push(node.item);
}
}
return output;
}
module.exports = Queue;
},{}],10:[function(require,module,exports){
;
var utils = require('./pouch-utils');
var TaskQueue = require('./taskqueue');
var PREFIX = "db_";
function prefixed(dbName) {
//A database name starting with an underscore is valid, but a document
//id starting with an underscore is not in most cases. Because of
//that, they're prefixed in the all dbs database. See issue #7 for
//more info.
return PREFIX + dbName;
}
function unprefixed(dbName) {
return dbName.slice(PREFIX.length);
}
module.exports = function (Pouch) {
var ALL_DBS_NAME = 'pouch__all_dbs__';
var pouch;
var cache;
var queue = new TaskQueue();
function log(err) {
/* istanbul ignore if */
if (err) {
console.error(err); // shouldn't happen
}
}
function init() {
queue.add(function (callback) {
if (pouch) {
return callback();
}
pouch = new Pouch(ALL_DBS_NAME);
callback();
});
}
function normalize(name) {
return name.replace(/^_pouch_/, ''); // TODO: remove when fixed in Pouch
}
function canIgnore(dbName) {
return (dbName === ALL_DBS_NAME) ||
// TODO: get rid of this when we have a real 'onDependentDbRegistered'
// event (pouchdb/pouchdb#2438)
(dbName.indexOf('-mrview-') !== -1) ||
// TODO: might be a better way to detect remote DBs
(/^https?:\/\//.test(dbName));
}
Pouch.on('created', function (dbName) {
dbName = normalize(dbName);
if (canIgnore(dbName)) {
return;
}
dbName = prefixed(dbName);
init();
queue.add(function (callback) {
pouch.get(dbName).then(function () {
// db exists, nothing to do
})["catch"](function (err) {
/* istanbul ignore if */
if (err.name !== 'not_found') {
throw err;
}
return pouch.put({_id: dbName});
}).then(function () {
if (cache) {
cache[dbName] = true;
}
callback();
}, callback);
}, log);
});
Pouch.on('destroyed', function (dbName) {
dbName = normalize(dbName);
if (canIgnore(dbName)) {
return;
}
dbName = prefixed(dbName);
init();
queue.add(function (callback) {
pouch.get(dbName).then(function (doc) {
return pouch.remove(doc);
})["catch"](/* istanbul ignore next */ function (err) {
// normally a not_found error; nothing to do
if (err.name !== 'not_found') {
throw err;
}
}).then(function () {
/* istanbul ignore else */
if (cache) {
delete cache[dbName];
}
callback();
}, callback);
}, log);
});
Pouch.allDbs = utils.toPromise(function (callback) {
init();
queue.add(function (callback) {
if (cache) {
return callback(null, Object.keys(cache).map(unprefixed));
}
// older versions of this module didn't have prefixes, so check here
var opts = {startkey: PREFIX, endkey: (PREFIX + '\uffff')};
pouch.allDocs(opts).then(function (res) {
cache = {};
var dbs = [];
res.rows.forEach(function (row) {
dbs.push(unprefixed(row.key));
cache[row.key] = true;
});
callback(null, dbs);
})["catch"](/* istanbul ignore next */ function (err) {
console.error(err);
callback(err);
});
}, callback);
});
Pouch.resetAllDbs = utils.toPromise(function (callback) {
queue.add(function (callback) {
pouch.destroy().then(function () {
pouch = null;
cache = null;
callback();
})["catch"](/* istanbul ignore next */ function (err) {
console.error(err);
callback(err);
});
}, callback);
});
};
/* istanbul ignore next */
if (typeof window !== 'undefined' && window.PouchDB) {
module.exports(window.PouchDB);
}
},{"./pouch-utils":1,"./taskqueue":2}]},{},[10]);