UNPKG

349 kBJavaScriptView Raw
1// PouchDB 7.2.1
2//
3// (c) 2012-2020 Dale Harvey and the PouchDB team
4// PouchDB may be freely distributed under the Apache license, version 2.0.
5// For all details and documentation:
6// http://pouchdb.com
7(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.PouchDB = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(_dereq_,module,exports){
8'use strict';
9
10module.exports = argsArray;
11
12function argsArray(fun) {
13 return function () {
14 var len = arguments.length;
15 if (len) {
16 var args = [];
17 var i = -1;
18 while (++i < len) {
19 args[i] = arguments[i];
20 }
21 return fun.call(this, args);
22 } else {
23 return fun.call(this, []);
24 }
25 };
26}
27},{}],2:[function(_dereq_,module,exports){
28// Copyright Joyent, Inc. and other Node contributors.
29//
30// Permission is hereby granted, free of charge, to any person obtaining a
31// copy of this software and associated documentation files (the
32// "Software"), to deal in the Software without restriction, including
33// without limitation the rights to use, copy, modify, merge, publish,
34// distribute, sublicense, and/or sell copies of the Software, and to permit
35// persons to whom the Software is furnished to do so, subject to the
36// following conditions:
37//
38// The above copyright notice and this permission notice shall be included
39// in all copies or substantial portions of the Software.
40//
41// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
42// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
43// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
44// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
45// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
46// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
47// USE OR OTHER DEALINGS IN THE SOFTWARE.
48
49var objectCreate = Object.create || objectCreatePolyfill
50var objectKeys = Object.keys || objectKeysPolyfill
51var bind = Function.prototype.bind || functionBindPolyfill
52
53function EventEmitter() {
54 if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) {
55 this._events = objectCreate(null);
56 this._eventsCount = 0;
57 }
58
59 this._maxListeners = this._maxListeners || undefined;
60}
61module.exports = EventEmitter;
62
63// Backwards-compat with node 0.10.x
64EventEmitter.EventEmitter = EventEmitter;
65
66EventEmitter.prototype._events = undefined;
67EventEmitter.prototype._maxListeners = undefined;
68
69// By default EventEmitters will print a warning if more than 10 listeners are
70// added to it. This is a useful default which helps finding memory leaks.
71var defaultMaxListeners = 10;
72
73var hasDefineProperty;
74try {
75 var o = {};
76 if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 });
77 hasDefineProperty = o.x === 0;
78} catch (err) { hasDefineProperty = false }
79if (hasDefineProperty) {
80 Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
81 enumerable: true,
82 get: function() {
83 return defaultMaxListeners;
84 },
85 set: function(arg) {
86 // check whether the input is a positive number (whose value is zero or
87 // greater and not a NaN).
88 if (typeof arg !== 'number' || arg < 0 || arg !== arg)
89 throw new TypeError('"defaultMaxListeners" must be a positive number');
90 defaultMaxListeners = arg;
91 }
92 });
93} else {
94 EventEmitter.defaultMaxListeners = defaultMaxListeners;
95}
96
97// Obviously not all Emitters should be limited to 10. This function allows
98// that to be increased. Set to zero for unlimited.
99EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
100 if (typeof n !== 'number' || n < 0 || isNaN(n))
101 throw new TypeError('"n" argument must be a positive number');
102 this._maxListeners = n;
103 return this;
104};
105
106function $getMaxListeners(that) {
107 if (that._maxListeners === undefined)
108 return EventEmitter.defaultMaxListeners;
109 return that._maxListeners;
110}
111
112EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
113 return $getMaxListeners(this);
114};
115
116// These standalone emit* functions are used to optimize calling of event
117// handlers for fast cases because emit() itself often has a variable number of
118// arguments and can be deoptimized because of that. These functions always have
119// the same number of arguments and thus do not get deoptimized, so the code
120// inside them can execute faster.
121function emitNone(handler, isFn, self) {
122 if (isFn)
123 handler.call(self);
124 else {
125 var len = handler.length;
126 var listeners = arrayClone(handler, len);
127 for (var i = 0; i < len; ++i)
128 listeners[i].call(self);
129 }
130}
131function emitOne(handler, isFn, self, arg1) {
132 if (isFn)
133 handler.call(self, arg1);
134 else {
135 var len = handler.length;
136 var listeners = arrayClone(handler, len);
137 for (var i = 0; i < len; ++i)
138 listeners[i].call(self, arg1);
139 }
140}
141function emitTwo(handler, isFn, self, arg1, arg2) {
142 if (isFn)
143 handler.call(self, arg1, arg2);
144 else {
145 var len = handler.length;
146 var listeners = arrayClone(handler, len);
147 for (var i = 0; i < len; ++i)
148 listeners[i].call(self, arg1, arg2);
149 }
150}
151function emitThree(handler, isFn, self, arg1, arg2, arg3) {
152 if (isFn)
153 handler.call(self, arg1, arg2, arg3);
154 else {
155 var len = handler.length;
156 var listeners = arrayClone(handler, len);
157 for (var i = 0; i < len; ++i)
158 listeners[i].call(self, arg1, arg2, arg3);
159 }
160}
161
162function emitMany(handler, isFn, self, args) {
163 if (isFn)
164 handler.apply(self, args);
165 else {
166 var len = handler.length;
167 var listeners = arrayClone(handler, len);
168 for (var i = 0; i < len; ++i)
169 listeners[i].apply(self, args);
170 }
171}
172
173EventEmitter.prototype.emit = function emit(type) {
174 var er, handler, len, args, i, events;
175 var doError = (type === 'error');
176
177 events = this._events;
178 if (events)
179 doError = (doError && events.error == null);
180 else if (!doError)
181 return false;
182
183 // If there is no 'error' event listener then throw.
184 if (doError) {
185 if (arguments.length > 1)
186 er = arguments[1];
187 if (er instanceof Error) {
188 throw er; // Unhandled 'error' event
189 } else {
190 // At least give some kind of context to the user
191 var err = new Error('Unhandled "error" event. (' + er + ')');
192 err.context = er;
193 throw err;
194 }
195 return false;
196 }
197
198 handler = events[type];
199
200 if (!handler)
201 return false;
202
203 var isFn = typeof handler === 'function';
204 len = arguments.length;
205 switch (len) {
206 // fast cases
207 case 1:
208 emitNone(handler, isFn, this);
209 break;
210 case 2:
211 emitOne(handler, isFn, this, arguments[1]);
212 break;
213 case 3:
214 emitTwo(handler, isFn, this, arguments[1], arguments[2]);
215 break;
216 case 4:
217 emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
218 break;
219 // slower
220 default:
221 args = new Array(len - 1);
222 for (i = 1; i < len; i++)
223 args[i - 1] = arguments[i];
224 emitMany(handler, isFn, this, args);
225 }
226
227 return true;
228};
229
230function _addListener(target, type, listener, prepend) {
231 var m;
232 var events;
233 var existing;
234
235 if (typeof listener !== 'function')
236 throw new TypeError('"listener" argument must be a function');
237
238 events = target._events;
239 if (!events) {
240 events = target._events = objectCreate(null);
241 target._eventsCount = 0;
242 } else {
243 // To avoid recursion in the case that type === "newListener"! Before
244 // adding it to the listeners, first emit "newListener".
245 if (events.newListener) {
246 target.emit('newListener', type,
247 listener.listener ? listener.listener : listener);
248
249 // Re-assign `events` because a newListener handler could have caused the
250 // this._events to be assigned to a new object
251 events = target._events;
252 }
253 existing = events[type];
254 }
255
256 if (!existing) {
257 // Optimize the case of one listener. Don't need the extra array object.
258 existing = events[type] = listener;
259 ++target._eventsCount;
260 } else {
261 if (typeof existing === 'function') {
262 // Adding the second element, need to change to array.
263 existing = events[type] =
264 prepend ? [listener, existing] : [existing, listener];
265 } else {
266 // If we've already got an array, just append.
267 if (prepend) {
268 existing.unshift(listener);
269 } else {
270 existing.push(listener);
271 }
272 }
273
274 // Check for listener leak
275 if (!existing.warned) {
276 m = $getMaxListeners(target);
277 if (m && m > 0 && existing.length > m) {
278 existing.warned = true;
279 var w = new Error('Possible EventEmitter memory leak detected. ' +
280 existing.length + ' "' + String(type) + '" listeners ' +
281 'added. Use emitter.setMaxListeners() to ' +
282 'increase limit.');
283 w.name = 'MaxListenersExceededWarning';
284 w.emitter = target;
285 w.type = type;
286 w.count = existing.length;
287 if (typeof console === 'object' && console.warn) {
288 console.warn('%s: %s', w.name, w.message);
289 }
290 }
291 }
292 }
293
294 return target;
295}
296
297EventEmitter.prototype.addListener = function addListener(type, listener) {
298 return _addListener(this, type, listener, false);
299};
300
301EventEmitter.prototype.on = EventEmitter.prototype.addListener;
302
303EventEmitter.prototype.prependListener =
304 function prependListener(type, listener) {
305 return _addListener(this, type, listener, true);
306 };
307
308function onceWrapper() {
309 if (!this.fired) {
310 this.target.removeListener(this.type, this.wrapFn);
311 this.fired = true;
312 switch (arguments.length) {
313 case 0:
314 return this.listener.call(this.target);
315 case 1:
316 return this.listener.call(this.target, arguments[0]);
317 case 2:
318 return this.listener.call(this.target, arguments[0], arguments[1]);
319 case 3:
320 return this.listener.call(this.target, arguments[0], arguments[1],
321 arguments[2]);
322 default:
323 var args = new Array(arguments.length);
324 for (var i = 0; i < args.length; ++i)
325 args[i] = arguments[i];
326 this.listener.apply(this.target, args);
327 }
328 }
329}
330
331function _onceWrap(target, type, listener) {
332 var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
333 var wrapped = bind.call(onceWrapper, state);
334 wrapped.listener = listener;
335 state.wrapFn = wrapped;
336 return wrapped;
337}
338
339EventEmitter.prototype.once = function once(type, listener) {
340 if (typeof listener !== 'function')
341 throw new TypeError('"listener" argument must be a function');
342 this.on(type, _onceWrap(this, type, listener));
343 return this;
344};
345
346EventEmitter.prototype.prependOnceListener =
347 function prependOnceListener(type, listener) {
348 if (typeof listener !== 'function')
349 throw new TypeError('"listener" argument must be a function');
350 this.prependListener(type, _onceWrap(this, type, listener));
351 return this;
352 };
353
354// Emits a 'removeListener' event if and only if the listener was removed.
355EventEmitter.prototype.removeListener =
356 function removeListener(type, listener) {
357 var list, events, position, i, originalListener;
358
359 if (typeof listener !== 'function')
360 throw new TypeError('"listener" argument must be a function');
361
362 events = this._events;
363 if (!events)
364 return this;
365
366 list = events[type];
367 if (!list)
368 return this;
369
370 if (list === listener || list.listener === listener) {
371 if (--this._eventsCount === 0)
372 this._events = objectCreate(null);
373 else {
374 delete events[type];
375 if (events.removeListener)
376 this.emit('removeListener', type, list.listener || listener);
377 }
378 } else if (typeof list !== 'function') {
379 position = -1;
380
381 for (i = list.length - 1; i >= 0; i--) {
382 if (list[i] === listener || list[i].listener === listener) {
383 originalListener = list[i].listener;
384 position = i;
385 break;
386 }
387 }
388
389 if (position < 0)
390 return this;
391
392 if (position === 0)
393 list.shift();
394 else
395 spliceOne(list, position);
396
397 if (list.length === 1)
398 events[type] = list[0];
399
400 if (events.removeListener)
401 this.emit('removeListener', type, originalListener || listener);
402 }
403
404 return this;
405 };
406
407EventEmitter.prototype.removeAllListeners =
408 function removeAllListeners(type) {
409 var listeners, events, i;
410
411 events = this._events;
412 if (!events)
413 return this;
414
415 // not listening for removeListener, no need to emit
416 if (!events.removeListener) {
417 if (arguments.length === 0) {
418 this._events = objectCreate(null);
419 this._eventsCount = 0;
420 } else if (events[type]) {
421 if (--this._eventsCount === 0)
422 this._events = objectCreate(null);
423 else
424 delete events[type];
425 }
426 return this;
427 }
428
429 // emit removeListener for all listeners on all events
430 if (arguments.length === 0) {
431 var keys = objectKeys(events);
432 var key;
433 for (i = 0; i < keys.length; ++i) {
434 key = keys[i];
435 if (key === 'removeListener') continue;
436 this.removeAllListeners(key);
437 }
438 this.removeAllListeners('removeListener');
439 this._events = objectCreate(null);
440 this._eventsCount = 0;
441 return this;
442 }
443
444 listeners = events[type];
445
446 if (typeof listeners === 'function') {
447 this.removeListener(type, listeners);
448 } else if (listeners) {
449 // LIFO order
450 for (i = listeners.length - 1; i >= 0; i--) {
451 this.removeListener(type, listeners[i]);
452 }
453 }
454
455 return this;
456 };
457
458function _listeners(target, type, unwrap) {
459 var events = target._events;
460
461 if (!events)
462 return [];
463
464 var evlistener = events[type];
465 if (!evlistener)
466 return [];
467
468 if (typeof evlistener === 'function')
469 return unwrap ? [evlistener.listener || evlistener] : [evlistener];
470
471 return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
472}
473
474EventEmitter.prototype.listeners = function listeners(type) {
475 return _listeners(this, type, true);
476};
477
478EventEmitter.prototype.rawListeners = function rawListeners(type) {
479 return _listeners(this, type, false);
480};
481
482EventEmitter.listenerCount = function(emitter, type) {
483 if (typeof emitter.listenerCount === 'function') {
484 return emitter.listenerCount(type);
485 } else {
486 return listenerCount.call(emitter, type);
487 }
488};
489
490EventEmitter.prototype.listenerCount = listenerCount;
491function listenerCount(type) {
492 var events = this._events;
493
494 if (events) {
495 var evlistener = events[type];
496
497 if (typeof evlistener === 'function') {
498 return 1;
499 } else if (evlistener) {
500 return evlistener.length;
501 }
502 }
503
504 return 0;
505}
506
507EventEmitter.prototype.eventNames = function eventNames() {
508 return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
509};
510
511// About 1.5x faster than the two-arg version of Array#splice().
512function spliceOne(list, index) {
513 for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
514 list[i] = list[k];
515 list.pop();
516}
517
518function arrayClone(arr, n) {
519 var copy = new Array(n);
520 for (var i = 0; i < n; ++i)
521 copy[i] = arr[i];
522 return copy;
523}
524
525function unwrapListeners(arr) {
526 var ret = new Array(arr.length);
527 for (var i = 0; i < ret.length; ++i) {
528 ret[i] = arr[i].listener || arr[i];
529 }
530 return ret;
531}
532
533function objectCreatePolyfill(proto) {
534 var F = function() {};
535 F.prototype = proto;
536 return new F;
537}
538function objectKeysPolyfill(obj) {
539 var keys = [];
540 for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) {
541 keys.push(k);
542 }
543 return k;
544}
545function functionBindPolyfill(context) {
546 var fn = this;
547 return function () {
548 return fn.apply(context, arguments);
549 };
550}
551
552},{}],3:[function(_dereq_,module,exports){
553(function (global){
554'use strict';
555var Mutation = global.MutationObserver || global.WebKitMutationObserver;
556
557var scheduleDrain;
558
559{
560 if (Mutation) {
561 var called = 0;
562 var observer = new Mutation(nextTick);
563 var element = global.document.createTextNode('');
564 observer.observe(element, {
565 characterData: true
566 });
567 scheduleDrain = function () {
568 element.data = (called = ++called % 2);
569 };
570 } else if (!global.setImmediate && typeof global.MessageChannel !== 'undefined') {
571 var channel = new global.MessageChannel();
572 channel.port1.onmessage = nextTick;
573 scheduleDrain = function () {
574 channel.port2.postMessage(0);
575 };
576 } else if ('document' in global && 'onreadystatechange' in global.document.createElement('script')) {
577 scheduleDrain = function () {
578
579 // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
580 // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
581 var scriptEl = global.document.createElement('script');
582 scriptEl.onreadystatechange = function () {
583 nextTick();
584
585 scriptEl.onreadystatechange = null;
586 scriptEl.parentNode.removeChild(scriptEl);
587 scriptEl = null;
588 };
589 global.document.documentElement.appendChild(scriptEl);
590 };
591 } else {
592 scheduleDrain = function () {
593 setTimeout(nextTick, 0);
594 };
595 }
596}
597
598var draining;
599var queue = [];
600//named nextTick for less confusing stack traces
601function nextTick() {
602 draining = true;
603 var i, oldQueue;
604 var len = queue.length;
605 while (len) {
606 oldQueue = queue;
607 queue = [];
608 i = -1;
609 while (++i < len) {
610 oldQueue[i]();
611 }
612 len = queue.length;
613 }
614 draining = false;
615}
616
617module.exports = immediate;
618function immediate(task) {
619 if (queue.push(task) === 1 && !draining) {
620 scheduleDrain();
621 }
622}
623
624}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
625},{}],4:[function(_dereq_,module,exports){
626if (typeof Object.create === 'function') {
627 // implementation from standard node.js 'util' module
628 module.exports = function inherits(ctor, superCtor) {
629 if (superCtor) {
630 ctor.super_ = superCtor
631 ctor.prototype = Object.create(superCtor.prototype, {
632 constructor: {
633 value: ctor,
634 enumerable: false,
635 writable: true,
636 configurable: true
637 }
638 })
639 }
640 };
641} else {
642 // old school shim for old browsers
643 module.exports = function inherits(ctor, superCtor) {
644 if (superCtor) {
645 ctor.super_ = superCtor
646 var TempCtor = function () {}
647 TempCtor.prototype = superCtor.prototype
648 ctor.prototype = new TempCtor()
649 ctor.prototype.constructor = ctor
650 }
651 }
652}
653
654},{}],5:[function(_dereq_,module,exports){
655// shim for using process in browser
656var process = module.exports = {};
657
658// cached from whatever global is present so that test runners that stub it
659// don't break things. But we need to wrap it in a try catch in case it is
660// wrapped in strict mode code which doesn't define any globals. It's inside a
661// function because try/catches deoptimize in certain engines.
662
663var cachedSetTimeout;
664var cachedClearTimeout;
665
666function defaultSetTimout() {
667 throw new Error('setTimeout has not been defined');
668}
669function defaultClearTimeout () {
670 throw new Error('clearTimeout has not been defined');
671}
672(function () {
673 try {
674 if (typeof setTimeout === 'function') {
675 cachedSetTimeout = setTimeout;
676 } else {
677 cachedSetTimeout = defaultSetTimout;
678 }
679 } catch (e) {
680 cachedSetTimeout = defaultSetTimout;
681 }
682 try {
683 if (typeof clearTimeout === 'function') {
684 cachedClearTimeout = clearTimeout;
685 } else {
686 cachedClearTimeout = defaultClearTimeout;
687 }
688 } catch (e) {
689 cachedClearTimeout = defaultClearTimeout;
690 }
691} ())
692function runTimeout(fun) {
693 if (cachedSetTimeout === setTimeout) {
694 //normal enviroments in sane situations
695 return setTimeout(fun, 0);
696 }
697 // if setTimeout wasn't available but was latter defined
698 if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
699 cachedSetTimeout = setTimeout;
700 return setTimeout(fun, 0);
701 }
702 try {
703 // when when somebody has screwed with setTimeout but no I.E. maddness
704 return cachedSetTimeout(fun, 0);
705 } catch(e){
706 try {
707 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
708 return cachedSetTimeout.call(null, fun, 0);
709 } catch(e){
710 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
711 return cachedSetTimeout.call(this, fun, 0);
712 }
713 }
714
715
716}
717function runClearTimeout(marker) {
718 if (cachedClearTimeout === clearTimeout) {
719 //normal enviroments in sane situations
720 return clearTimeout(marker);
721 }
722 // if clearTimeout wasn't available but was latter defined
723 if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
724 cachedClearTimeout = clearTimeout;
725 return clearTimeout(marker);
726 }
727 try {
728 // when when somebody has screwed with setTimeout but no I.E. maddness
729 return cachedClearTimeout(marker);
730 } catch (e){
731 try {
732 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
733 return cachedClearTimeout.call(null, marker);
734 } catch (e){
735 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
736 // Some versions of I.E. have different rules for clearTimeout vs setTimeout
737 return cachedClearTimeout.call(this, marker);
738 }
739 }
740
741
742
743}
744var queue = [];
745var draining = false;
746var currentQueue;
747var queueIndex = -1;
748
749function cleanUpNextTick() {
750 if (!draining || !currentQueue) {
751 return;
752 }
753 draining = false;
754 if (currentQueue.length) {
755 queue = currentQueue.concat(queue);
756 } else {
757 queueIndex = -1;
758 }
759 if (queue.length) {
760 drainQueue();
761 }
762}
763
764function drainQueue() {
765 if (draining) {
766 return;
767 }
768 var timeout = runTimeout(cleanUpNextTick);
769 draining = true;
770
771 var len = queue.length;
772 while(len) {
773 currentQueue = queue;
774 queue = [];
775 while (++queueIndex < len) {
776 if (currentQueue) {
777 currentQueue[queueIndex].run();
778 }
779 }
780 queueIndex = -1;
781 len = queue.length;
782 }
783 currentQueue = null;
784 draining = false;
785 runClearTimeout(timeout);
786}
787
788process.nextTick = function (fun) {
789 var args = new Array(arguments.length - 1);
790 if (arguments.length > 1) {
791 for (var i = 1; i < arguments.length; i++) {
792 args[i - 1] = arguments[i];
793 }
794 }
795 queue.push(new Item(fun, args));
796 if (queue.length === 1 && !draining) {
797 runTimeout(drainQueue);
798 }
799};
800
801// v8 likes predictible objects
802function Item(fun, array) {
803 this.fun = fun;
804 this.array = array;
805}
806Item.prototype.run = function () {
807 this.fun.apply(null, this.array);
808};
809process.title = 'browser';
810process.browser = true;
811process.env = {};
812process.argv = [];
813process.version = ''; // empty string to avoid regexp issues
814process.versions = {};
815
816function noop() {}
817
818process.on = noop;
819process.addListener = noop;
820process.once = noop;
821process.off = noop;
822process.removeListener = noop;
823process.removeAllListeners = noop;
824process.emit = noop;
825process.prependListener = noop;
826process.prependOnceListener = noop;
827
828process.listeners = function (name) { return [] }
829
830process.binding = function (name) {
831 throw new Error('process.binding is not supported');
832};
833
834process.cwd = function () { return '/' };
835process.chdir = function (dir) {
836 throw new Error('process.chdir is not supported');
837};
838process.umask = function() { return 0; };
839
840},{}],6:[function(_dereq_,module,exports){
841(function (factory) {
842 if (typeof exports === 'object') {
843 // Node/CommonJS
844 module.exports = factory();
845 } else if (typeof define === 'function' && define.amd) {
846 // AMD
847 define(factory);
848 } else {
849 // Browser globals (with support for web workers)
850 var glob;
851
852 try {
853 glob = window;
854 } catch (e) {
855 glob = self;
856 }
857
858 glob.SparkMD5 = factory();
859 }
860}(function (undefined) {
861
862 'use strict';
863
864 /*
865 * Fastest md5 implementation around (JKM md5).
866 * Credits: Joseph Myers
867 *
868 * @see http://www.myersdaily.org/joseph/javascript/md5-text.html
869 * @see http://jsperf.com/md5-shootout/7
870 */
871
872 /* this function is much faster,
873 so if possible we use it. Some IEs
874 are the only ones I know of that
875 need the idiotic second function,
876 generated by an if clause. */
877 var add32 = function (a, b) {
878 return (a + b) & 0xFFFFFFFF;
879 },
880 hex_chr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
881
882
883 function cmn(q, a, b, x, s, t) {
884 a = add32(add32(a, q), add32(x, t));
885 return add32((a << s) | (a >>> (32 - s)), b);
886 }
887
888 function md5cycle(x, k) {
889 var a = x[0],
890 b = x[1],
891 c = x[2],
892 d = x[3];
893
894 a += (b & c | ~b & d) + k[0] - 680876936 | 0;
895 a = (a << 7 | a >>> 25) + b | 0;
896 d += (a & b | ~a & c) + k[1] - 389564586 | 0;
897 d = (d << 12 | d >>> 20) + a | 0;
898 c += (d & a | ~d & b) + k[2] + 606105819 | 0;
899 c = (c << 17 | c >>> 15) + d | 0;
900 b += (c & d | ~c & a) + k[3] - 1044525330 | 0;
901 b = (b << 22 | b >>> 10) + c | 0;
902 a += (b & c | ~b & d) + k[4] - 176418897 | 0;
903 a = (a << 7 | a >>> 25) + b | 0;
904 d += (a & b | ~a & c) + k[5] + 1200080426 | 0;
905 d = (d << 12 | d >>> 20) + a | 0;
906 c += (d & a | ~d & b) + k[6] - 1473231341 | 0;
907 c = (c << 17 | c >>> 15) + d | 0;
908 b += (c & d | ~c & a) + k[7] - 45705983 | 0;
909 b = (b << 22 | b >>> 10) + c | 0;
910 a += (b & c | ~b & d) + k[8] + 1770035416 | 0;
911 a = (a << 7 | a >>> 25) + b | 0;
912 d += (a & b | ~a & c) + k[9] - 1958414417 | 0;
913 d = (d << 12 | d >>> 20) + a | 0;
914 c += (d & a | ~d & b) + k[10] - 42063 | 0;
915 c = (c << 17 | c >>> 15) + d | 0;
916 b += (c & d | ~c & a) + k[11] - 1990404162 | 0;
917 b = (b << 22 | b >>> 10) + c | 0;
918 a += (b & c | ~b & d) + k[12] + 1804603682 | 0;
919 a = (a << 7 | a >>> 25) + b | 0;
920 d += (a & b | ~a & c) + k[13] - 40341101 | 0;
921 d = (d << 12 | d >>> 20) + a | 0;
922 c += (d & a | ~d & b) + k[14] - 1502002290 | 0;
923 c = (c << 17 | c >>> 15) + d | 0;
924 b += (c & d | ~c & a) + k[15] + 1236535329 | 0;
925 b = (b << 22 | b >>> 10) + c | 0;
926
927 a += (b & d | c & ~d) + k[1] - 165796510 | 0;
928 a = (a << 5 | a >>> 27) + b | 0;
929 d += (a & c | b & ~c) + k[6] - 1069501632 | 0;
930 d = (d << 9 | d >>> 23) + a | 0;
931 c += (d & b | a & ~b) + k[11] + 643717713 | 0;
932 c = (c << 14 | c >>> 18) + d | 0;
933 b += (c & a | d & ~a) + k[0] - 373897302 | 0;
934 b = (b << 20 | b >>> 12) + c | 0;
935 a += (b & d | c & ~d) + k[5] - 701558691 | 0;
936 a = (a << 5 | a >>> 27) + b | 0;
937 d += (a & c | b & ~c) + k[10] + 38016083 | 0;
938 d = (d << 9 | d >>> 23) + a | 0;
939 c += (d & b | a & ~b) + k[15] - 660478335 | 0;
940 c = (c << 14 | c >>> 18) + d | 0;
941 b += (c & a | d & ~a) + k[4] - 405537848 | 0;
942 b = (b << 20 | b >>> 12) + c | 0;
943 a += (b & d | c & ~d) + k[9] + 568446438 | 0;
944 a = (a << 5 | a >>> 27) + b | 0;
945 d += (a & c | b & ~c) + k[14] - 1019803690 | 0;
946 d = (d << 9 | d >>> 23) + a | 0;
947 c += (d & b | a & ~b) + k[3] - 187363961 | 0;
948 c = (c << 14 | c >>> 18) + d | 0;
949 b += (c & a | d & ~a) + k[8] + 1163531501 | 0;
950 b = (b << 20 | b >>> 12) + c | 0;
951 a += (b & d | c & ~d) + k[13] - 1444681467 | 0;
952 a = (a << 5 | a >>> 27) + b | 0;
953 d += (a & c | b & ~c) + k[2] - 51403784 | 0;
954 d = (d << 9 | d >>> 23) + a | 0;
955 c += (d & b | a & ~b) + k[7] + 1735328473 | 0;
956 c = (c << 14 | c >>> 18) + d | 0;
957 b += (c & a | d & ~a) + k[12] - 1926607734 | 0;
958 b = (b << 20 | b >>> 12) + c | 0;
959
960 a += (b ^ c ^ d) + k[5] - 378558 | 0;
961 a = (a << 4 | a >>> 28) + b | 0;
962 d += (a ^ b ^ c) + k[8] - 2022574463 | 0;
963 d = (d << 11 | d >>> 21) + a | 0;
964 c += (d ^ a ^ b) + k[11] + 1839030562 | 0;
965 c = (c << 16 | c >>> 16) + d | 0;
966 b += (c ^ d ^ a) + k[14] - 35309556 | 0;
967 b = (b << 23 | b >>> 9) + c | 0;
968 a += (b ^ c ^ d) + k[1] - 1530992060 | 0;
969 a = (a << 4 | a >>> 28) + b | 0;
970 d += (a ^ b ^ c) + k[4] + 1272893353 | 0;
971 d = (d << 11 | d >>> 21) + a | 0;
972 c += (d ^ a ^ b) + k[7] - 155497632 | 0;
973 c = (c << 16 | c >>> 16) + d | 0;
974 b += (c ^ d ^ a) + k[10] - 1094730640 | 0;
975 b = (b << 23 | b >>> 9) + c | 0;
976 a += (b ^ c ^ d) + k[13] + 681279174 | 0;
977 a = (a << 4 | a >>> 28) + b | 0;
978 d += (a ^ b ^ c) + k[0] - 358537222 | 0;
979 d = (d << 11 | d >>> 21) + a | 0;
980 c += (d ^ a ^ b) + k[3] - 722521979 | 0;
981 c = (c << 16 | c >>> 16) + d | 0;
982 b += (c ^ d ^ a) + k[6] + 76029189 | 0;
983 b = (b << 23 | b >>> 9) + c | 0;
984 a += (b ^ c ^ d) + k[9] - 640364487 | 0;
985 a = (a << 4 | a >>> 28) + b | 0;
986 d += (a ^ b ^ c) + k[12] - 421815835 | 0;
987 d = (d << 11 | d >>> 21) + a | 0;
988 c += (d ^ a ^ b) + k[15] + 530742520 | 0;
989 c = (c << 16 | c >>> 16) + d | 0;
990 b += (c ^ d ^ a) + k[2] - 995338651 | 0;
991 b = (b << 23 | b >>> 9) + c | 0;
992
993 a += (c ^ (b | ~d)) + k[0] - 198630844 | 0;
994 a = (a << 6 | a >>> 26) + b | 0;
995 d += (b ^ (a | ~c)) + k[7] + 1126891415 | 0;
996 d = (d << 10 | d >>> 22) + a | 0;
997 c += (a ^ (d | ~b)) + k[14] - 1416354905 | 0;
998 c = (c << 15 | c >>> 17) + d | 0;
999 b += (d ^ (c | ~a)) + k[5] - 57434055 | 0;
1000 b = (b << 21 |b >>> 11) + c | 0;
1001 a += (c ^ (b | ~d)) + k[12] + 1700485571 | 0;
1002 a = (a << 6 | a >>> 26) + b | 0;
1003 d += (b ^ (a | ~c)) + k[3] - 1894986606 | 0;
1004 d = (d << 10 | d >>> 22) + a | 0;
1005 c += (a ^ (d | ~b)) + k[10] - 1051523 | 0;
1006 c = (c << 15 | c >>> 17) + d | 0;
1007 b += (d ^ (c | ~a)) + k[1] - 2054922799 | 0;
1008 b = (b << 21 |b >>> 11) + c | 0;
1009 a += (c ^ (b | ~d)) + k[8] + 1873313359 | 0;
1010 a = (a << 6 | a >>> 26) + b | 0;
1011 d += (b ^ (a | ~c)) + k[15] - 30611744 | 0;
1012 d = (d << 10 | d >>> 22) + a | 0;
1013 c += (a ^ (d | ~b)) + k[6] - 1560198380 | 0;
1014 c = (c << 15 | c >>> 17) + d | 0;
1015 b += (d ^ (c | ~a)) + k[13] + 1309151649 | 0;
1016 b = (b << 21 |b >>> 11) + c | 0;
1017 a += (c ^ (b | ~d)) + k[4] - 145523070 | 0;
1018 a = (a << 6 | a >>> 26) + b | 0;
1019 d += (b ^ (a | ~c)) + k[11] - 1120210379 | 0;
1020 d = (d << 10 | d >>> 22) + a | 0;
1021 c += (a ^ (d | ~b)) + k[2] + 718787259 | 0;
1022 c = (c << 15 | c >>> 17) + d | 0;
1023 b += (d ^ (c | ~a)) + k[9] - 343485551 | 0;
1024 b = (b << 21 | b >>> 11) + c | 0;
1025
1026 x[0] = a + x[0] | 0;
1027 x[1] = b + x[1] | 0;
1028 x[2] = c + x[2] | 0;
1029 x[3] = d + x[3] | 0;
1030 }
1031
1032 function md5blk(s) {
1033 var md5blks = [],
1034 i; /* Andy King said do it this way. */
1035
1036 for (i = 0; i < 64; i += 4) {
1037 md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) << 24);
1038 }
1039 return md5blks;
1040 }
1041
1042 function md5blk_array(a) {
1043 var md5blks = [],
1044 i; /* Andy King said do it this way. */
1045
1046 for (i = 0; i < 64; i += 4) {
1047 md5blks[i >> 2] = a[i] + (a[i + 1] << 8) + (a[i + 2] << 16) + (a[i + 3] << 24);
1048 }
1049 return md5blks;
1050 }
1051
1052 function md51(s) {
1053 var n = s.length,
1054 state = [1732584193, -271733879, -1732584194, 271733878],
1055 i,
1056 length,
1057 tail,
1058 tmp,
1059 lo,
1060 hi;
1061
1062 for (i = 64; i <= n; i += 64) {
1063 md5cycle(state, md5blk(s.substring(i - 64, i)));
1064 }
1065 s = s.substring(i - 64);
1066 length = s.length;
1067 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
1068 for (i = 0; i < length; i += 1) {
1069 tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3);
1070 }
1071 tail[i >> 2] |= 0x80 << ((i % 4) << 3);
1072 if (i > 55) {
1073 md5cycle(state, tail);
1074 for (i = 0; i < 16; i += 1) {
1075 tail[i] = 0;
1076 }
1077 }
1078
1079 // Beware that the final length might not fit in 32 bits so we take care of that
1080 tmp = n * 8;
1081 tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
1082 lo = parseInt(tmp[2], 16);
1083 hi = parseInt(tmp[1], 16) || 0;
1084
1085 tail[14] = lo;
1086 tail[15] = hi;
1087
1088 md5cycle(state, tail);
1089 return state;
1090 }
1091
1092 function md51_array(a) {
1093 var n = a.length,
1094 state = [1732584193, -271733879, -1732584194, 271733878],
1095 i,
1096 length,
1097 tail,
1098 tmp,
1099 lo,
1100 hi;
1101
1102 for (i = 64; i <= n; i += 64) {
1103 md5cycle(state, md5blk_array(a.subarray(i - 64, i)));
1104 }
1105
1106 // Not sure if it is a bug, however IE10 will always produce a sub array of length 1
1107 // containing the last element of the parent array if the sub array specified starts
1108 // beyond the length of the parent array - weird.
1109 // https://connect.microsoft.com/IE/feedback/details/771452/typed-array-subarray-issue
1110 a = (i - 64) < n ? a.subarray(i - 64) : new Uint8Array(0);
1111
1112 length = a.length;
1113 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
1114 for (i = 0; i < length; i += 1) {
1115 tail[i >> 2] |= a[i] << ((i % 4) << 3);
1116 }
1117
1118 tail[i >> 2] |= 0x80 << ((i % 4) << 3);
1119 if (i > 55) {
1120 md5cycle(state, tail);
1121 for (i = 0; i < 16; i += 1) {
1122 tail[i] = 0;
1123 }
1124 }
1125
1126 // Beware that the final length might not fit in 32 bits so we take care of that
1127 tmp = n * 8;
1128 tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
1129 lo = parseInt(tmp[2], 16);
1130 hi = parseInt(tmp[1], 16) || 0;
1131
1132 tail[14] = lo;
1133 tail[15] = hi;
1134
1135 md5cycle(state, tail);
1136
1137 return state;
1138 }
1139
1140 function rhex(n) {
1141 var s = '',
1142 j;
1143 for (j = 0; j < 4; j += 1) {
1144 s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F];
1145 }
1146 return s;
1147 }
1148
1149 function hex(x) {
1150 var i;
1151 for (i = 0; i < x.length; i += 1) {
1152 x[i] = rhex(x[i]);
1153 }
1154 return x.join('');
1155 }
1156
1157 // In some cases the fast add32 function cannot be used..
1158 if (hex(md51('hello')) !== '5d41402abc4b2a76b9719d911017c592') {
1159 add32 = function (x, y) {
1160 var lsw = (x & 0xFFFF) + (y & 0xFFFF),
1161 msw = (x >> 16) + (y >> 16) + (lsw >> 16);
1162 return (msw << 16) | (lsw & 0xFFFF);
1163 };
1164 }
1165
1166 // ---------------------------------------------------
1167
1168 /**
1169 * ArrayBuffer slice polyfill.
1170 *
1171 * @see https://github.com/ttaubert/node-arraybuffer-slice
1172 */
1173
1174 if (typeof ArrayBuffer !== 'undefined' && !ArrayBuffer.prototype.slice) {
1175 (function () {
1176 function clamp(val, length) {
1177 val = (val | 0) || 0;
1178
1179 if (val < 0) {
1180 return Math.max(val + length, 0);
1181 }
1182
1183 return Math.min(val, length);
1184 }
1185
1186 ArrayBuffer.prototype.slice = function (from, to) {
1187 var length = this.byteLength,
1188 begin = clamp(from, length),
1189 end = length,
1190 num,
1191 target,
1192 targetArray,
1193 sourceArray;
1194
1195 if (to !== undefined) {
1196 end = clamp(to, length);
1197 }
1198
1199 if (begin > end) {
1200 return new ArrayBuffer(0);
1201 }
1202
1203 num = end - begin;
1204 target = new ArrayBuffer(num);
1205 targetArray = new Uint8Array(target);
1206
1207 sourceArray = new Uint8Array(this, begin, num);
1208 targetArray.set(sourceArray);
1209
1210 return target;
1211 };
1212 })();
1213 }
1214
1215 // ---------------------------------------------------
1216
1217 /**
1218 * Helpers.
1219 */
1220
1221 function toUtf8(str) {
1222 if (/[\u0080-\uFFFF]/.test(str)) {
1223 str = unescape(encodeURIComponent(str));
1224 }
1225
1226 return str;
1227 }
1228
1229 function utf8Str2ArrayBuffer(str, returnUInt8Array) {
1230 var length = str.length,
1231 buff = new ArrayBuffer(length),
1232 arr = new Uint8Array(buff),
1233 i;
1234
1235 for (i = 0; i < length; i += 1) {
1236 arr[i] = str.charCodeAt(i);
1237 }
1238
1239 return returnUInt8Array ? arr : buff;
1240 }
1241
1242 function arrayBuffer2Utf8Str(buff) {
1243 return String.fromCharCode.apply(null, new Uint8Array(buff));
1244 }
1245
1246 function concatenateArrayBuffers(first, second, returnUInt8Array) {
1247 var result = new Uint8Array(first.byteLength + second.byteLength);
1248
1249 result.set(new Uint8Array(first));
1250 result.set(new Uint8Array(second), first.byteLength);
1251
1252 return returnUInt8Array ? result : result.buffer;
1253 }
1254
1255 function hexToBinaryString(hex) {
1256 var bytes = [],
1257 length = hex.length,
1258 x;
1259
1260 for (x = 0; x < length - 1; x += 2) {
1261 bytes.push(parseInt(hex.substr(x, 2), 16));
1262 }
1263
1264 return String.fromCharCode.apply(String, bytes);
1265 }
1266
1267 // ---------------------------------------------------
1268
1269 /**
1270 * SparkMD5 OOP implementation.
1271 *
1272 * Use this class to perform an incremental md5, otherwise use the
1273 * static methods instead.
1274 */
1275
1276 function SparkMD5() {
1277 // call reset to init the instance
1278 this.reset();
1279 }
1280
1281 /**
1282 * Appends a string.
1283 * A conversion will be applied if an utf8 string is detected.
1284 *
1285 * @param {String} str The string to be appended
1286 *
1287 * @return {SparkMD5} The instance itself
1288 */
1289 SparkMD5.prototype.append = function (str) {
1290 // Converts the string to utf8 bytes if necessary
1291 // Then append as binary
1292 this.appendBinary(toUtf8(str));
1293
1294 return this;
1295 };
1296
1297 /**
1298 * Appends a binary string.
1299 *
1300 * @param {String} contents The binary string to be appended
1301 *
1302 * @return {SparkMD5} The instance itself
1303 */
1304 SparkMD5.prototype.appendBinary = function (contents) {
1305 this._buff += contents;
1306 this._length += contents.length;
1307
1308 var length = this._buff.length,
1309 i;
1310
1311 for (i = 64; i <= length; i += 64) {
1312 md5cycle(this._hash, md5blk(this._buff.substring(i - 64, i)));
1313 }
1314
1315 this._buff = this._buff.substring(i - 64);
1316
1317 return this;
1318 };
1319
1320 /**
1321 * Finishes the incremental computation, reseting the internal state and
1322 * returning the result.
1323 *
1324 * @param {Boolean} raw True to get the raw string, false to get the hex string
1325 *
1326 * @return {String} The result
1327 */
1328 SparkMD5.prototype.end = function (raw) {
1329 var buff = this._buff,
1330 length = buff.length,
1331 i,
1332 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
1333 ret;
1334
1335 for (i = 0; i < length; i += 1) {
1336 tail[i >> 2] |= buff.charCodeAt(i) << ((i % 4) << 3);
1337 }
1338
1339 this._finish(tail, length);
1340 ret = hex(this._hash);
1341
1342 if (raw) {
1343 ret = hexToBinaryString(ret);
1344 }
1345
1346 this.reset();
1347
1348 return ret;
1349 };
1350
1351 /**
1352 * Resets the internal state of the computation.
1353 *
1354 * @return {SparkMD5} The instance itself
1355 */
1356 SparkMD5.prototype.reset = function () {
1357 this._buff = '';
1358 this._length = 0;
1359 this._hash = [1732584193, -271733879, -1732584194, 271733878];
1360
1361 return this;
1362 };
1363
1364 /**
1365 * Gets the internal state of the computation.
1366 *
1367 * @return {Object} The state
1368 */
1369 SparkMD5.prototype.getState = function () {
1370 return {
1371 buff: this._buff,
1372 length: this._length,
1373 hash: this._hash
1374 };
1375 };
1376
1377 /**
1378 * Gets the internal state of the computation.
1379 *
1380 * @param {Object} state The state
1381 *
1382 * @return {SparkMD5} The instance itself
1383 */
1384 SparkMD5.prototype.setState = function (state) {
1385 this._buff = state.buff;
1386 this._length = state.length;
1387 this._hash = state.hash;
1388
1389 return this;
1390 };
1391
1392 /**
1393 * Releases memory used by the incremental buffer and other additional
1394 * resources. If you plan to use the instance again, use reset instead.
1395 */
1396 SparkMD5.prototype.destroy = function () {
1397 delete this._hash;
1398 delete this._buff;
1399 delete this._length;
1400 };
1401
1402 /**
1403 * Finish the final calculation based on the tail.
1404 *
1405 * @param {Array} tail The tail (will be modified)
1406 * @param {Number} length The length of the remaining buffer
1407 */
1408 SparkMD5.prototype._finish = function (tail, length) {
1409 var i = length,
1410 tmp,
1411 lo,
1412 hi;
1413
1414 tail[i >> 2] |= 0x80 << ((i % 4) << 3);
1415 if (i > 55) {
1416 md5cycle(this._hash, tail);
1417 for (i = 0; i < 16; i += 1) {
1418 tail[i] = 0;
1419 }
1420 }
1421
1422 // Do the final computation based on the tail and length
1423 // Beware that the final length may not fit in 32 bits so we take care of that
1424 tmp = this._length * 8;
1425 tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
1426 lo = parseInt(tmp[2], 16);
1427 hi = parseInt(tmp[1], 16) || 0;
1428
1429 tail[14] = lo;
1430 tail[15] = hi;
1431 md5cycle(this._hash, tail);
1432 };
1433
1434 /**
1435 * Performs the md5 hash on a string.
1436 * A conversion will be applied if utf8 string is detected.
1437 *
1438 * @param {String} str The string
1439 * @param {Boolean} raw True to get the raw string, false to get the hex string
1440 *
1441 * @return {String} The result
1442 */
1443 SparkMD5.hash = function (str, raw) {
1444 // Converts the string to utf8 bytes if necessary
1445 // Then compute it using the binary function
1446 return SparkMD5.hashBinary(toUtf8(str), raw);
1447 };
1448
1449 /**
1450 * Performs the md5 hash on a binary string.
1451 *
1452 * @param {String} content The binary string
1453 * @param {Boolean} raw True to get the raw string, false to get the hex string
1454 *
1455 * @return {String} The result
1456 */
1457 SparkMD5.hashBinary = function (content, raw) {
1458 var hash = md51(content),
1459 ret = hex(hash);
1460
1461 return raw ? hexToBinaryString(ret) : ret;
1462 };
1463
1464 // ---------------------------------------------------
1465
1466 /**
1467 * SparkMD5 OOP implementation for array buffers.
1468 *
1469 * Use this class to perform an incremental md5 ONLY for array buffers.
1470 */
1471 SparkMD5.ArrayBuffer = function () {
1472 // call reset to init the instance
1473 this.reset();
1474 };
1475
1476 /**
1477 * Appends an array buffer.
1478 *
1479 * @param {ArrayBuffer} arr The array to be appended
1480 *
1481 * @return {SparkMD5.ArrayBuffer} The instance itself
1482 */
1483 SparkMD5.ArrayBuffer.prototype.append = function (arr) {
1484 var buff = concatenateArrayBuffers(this._buff.buffer, arr, true),
1485 length = buff.length,
1486 i;
1487
1488 this._length += arr.byteLength;
1489
1490 for (i = 64; i <= length; i += 64) {
1491 md5cycle(this._hash, md5blk_array(buff.subarray(i - 64, i)));
1492 }
1493
1494 this._buff = (i - 64) < length ? new Uint8Array(buff.buffer.slice(i - 64)) : new Uint8Array(0);
1495
1496 return this;
1497 };
1498
1499 /**
1500 * Finishes the incremental computation, reseting the internal state and
1501 * returning the result.
1502 *
1503 * @param {Boolean} raw True to get the raw string, false to get the hex string
1504 *
1505 * @return {String} The result
1506 */
1507 SparkMD5.ArrayBuffer.prototype.end = function (raw) {
1508 var buff = this._buff,
1509 length = buff.length,
1510 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
1511 i,
1512 ret;
1513
1514 for (i = 0; i < length; i += 1) {
1515 tail[i >> 2] |= buff[i] << ((i % 4) << 3);
1516 }
1517
1518 this._finish(tail, length);
1519 ret = hex(this._hash);
1520
1521 if (raw) {
1522 ret = hexToBinaryString(ret);
1523 }
1524
1525 this.reset();
1526
1527 return ret;
1528 };
1529
1530 /**
1531 * Resets the internal state of the computation.
1532 *
1533 * @return {SparkMD5.ArrayBuffer} The instance itself
1534 */
1535 SparkMD5.ArrayBuffer.prototype.reset = function () {
1536 this._buff = new Uint8Array(0);
1537 this._length = 0;
1538 this._hash = [1732584193, -271733879, -1732584194, 271733878];
1539
1540 return this;
1541 };
1542
1543 /**
1544 * Gets the internal state of the computation.
1545 *
1546 * @return {Object} The state
1547 */
1548 SparkMD5.ArrayBuffer.prototype.getState = function () {
1549 var state = SparkMD5.prototype.getState.call(this);
1550
1551 // Convert buffer to a string
1552 state.buff = arrayBuffer2Utf8Str(state.buff);
1553
1554 return state;
1555 };
1556
1557 /**
1558 * Gets the internal state of the computation.
1559 *
1560 * @param {Object} state The state
1561 *
1562 * @return {SparkMD5.ArrayBuffer} The instance itself
1563 */
1564 SparkMD5.ArrayBuffer.prototype.setState = function (state) {
1565 // Convert string to buffer
1566 state.buff = utf8Str2ArrayBuffer(state.buff, true);
1567
1568 return SparkMD5.prototype.setState.call(this, state);
1569 };
1570
1571 SparkMD5.ArrayBuffer.prototype.destroy = SparkMD5.prototype.destroy;
1572
1573 SparkMD5.ArrayBuffer.prototype._finish = SparkMD5.prototype._finish;
1574
1575 /**
1576 * Performs the md5 hash on an array buffer.
1577 *
1578 * @param {ArrayBuffer} arr The array buffer
1579 * @param {Boolean} raw True to get the raw string, false to get the hex one
1580 *
1581 * @return {String} The result
1582 */
1583 SparkMD5.ArrayBuffer.hash = function (arr, raw) {
1584 var hash = md51_array(new Uint8Array(arr)),
1585 ret = hex(hash);
1586
1587 return raw ? hexToBinaryString(ret) : ret;
1588 };
1589
1590 return SparkMD5;
1591}));
1592
1593},{}],7:[function(_dereq_,module,exports){
1594var v1 = _dereq_(10);
1595var v4 = _dereq_(11);
1596
1597var uuid = v4;
1598uuid.v1 = v1;
1599uuid.v4 = v4;
1600
1601module.exports = uuid;
1602
1603},{"10":10,"11":11}],8:[function(_dereq_,module,exports){
1604/**
1605 * Convert array of 16 byte values to UUID string format of the form:
1606 * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
1607 */
1608var byteToHex = [];
1609for (var i = 0; i < 256; ++i) {
1610 byteToHex[i] = (i + 0x100).toString(16).substr(1);
1611}
1612
1613function bytesToUuid(buf, offset) {
1614 var i = offset || 0;
1615 var bth = byteToHex;
1616 // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4
1617 return ([bth[buf[i++]], bth[buf[i++]],
1618 bth[buf[i++]], bth[buf[i++]], '-',
1619 bth[buf[i++]], bth[buf[i++]], '-',
1620 bth[buf[i++]], bth[buf[i++]], '-',
1621 bth[buf[i++]], bth[buf[i++]], '-',
1622 bth[buf[i++]], bth[buf[i++]],
1623 bth[buf[i++]], bth[buf[i++]],
1624 bth[buf[i++]], bth[buf[i++]]]).join('');
1625}
1626
1627module.exports = bytesToUuid;
1628
1629},{}],9:[function(_dereq_,module,exports){
1630// Unique ID creation requires a high quality random # generator. In the
1631// browser this is a little complicated due to unknown quality of Math.random()
1632// and inconsistent support for the `crypto` API. We do the best we can via
1633// feature-detection
1634
1635// getRandomValues needs to be invoked in a context where "this" is a Crypto
1636// implementation. Also, find the complete implementation of crypto on IE11.
1637var getRandomValues = (typeof(crypto) != 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto)) ||
1638 (typeof(msCrypto) != 'undefined' && typeof window.msCrypto.getRandomValues == 'function' && msCrypto.getRandomValues.bind(msCrypto));
1639
1640if (getRandomValues) {
1641 // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto
1642 var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef
1643
1644 module.exports = function whatwgRNG() {
1645 getRandomValues(rnds8);
1646 return rnds8;
1647 };
1648} else {
1649 // Math.random()-based (RNG)
1650 //
1651 // If all else fails, use Math.random(). It's fast, but is of unspecified
1652 // quality.
1653 var rnds = new Array(16);
1654
1655 module.exports = function mathRNG() {
1656 for (var i = 0, r; i < 16; i++) {
1657 if ((i & 0x03) === 0) r = Math.random() * 0x100000000;
1658 rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
1659 }
1660
1661 return rnds;
1662 };
1663}
1664
1665},{}],10:[function(_dereq_,module,exports){
1666var rng = _dereq_(9);
1667var bytesToUuid = _dereq_(8);
1668
1669// **`v1()` - Generate time-based UUID**
1670//
1671// Inspired by https://github.com/LiosK/UUID.js
1672// and http://docs.python.org/library/uuid.html
1673
1674var _nodeId;
1675var _clockseq;
1676
1677// Previous uuid creation time
1678var _lastMSecs = 0;
1679var _lastNSecs = 0;
1680
1681// See https://github.com/broofa/node-uuid for API details
1682function v1(options, buf, offset) {
1683 var i = buf && offset || 0;
1684 var b = buf || [];
1685
1686 options = options || {};
1687 var node = options.node || _nodeId;
1688 var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq;
1689
1690 // node and clockseq need to be initialized to random values if they're not
1691 // specified. We do this lazily to minimize issues related to insufficient
1692 // system entropy. See #189
1693 if (node == null || clockseq == null) {
1694 var seedBytes = rng();
1695 if (node == null) {
1696 // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
1697 node = _nodeId = [
1698 seedBytes[0] | 0x01,
1699 seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]
1700 ];
1701 }
1702 if (clockseq == null) {
1703 // Per 4.2.2, randomize (14 bit) clockseq
1704 clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;
1705 }
1706 }
1707
1708 // UUID timestamps are 100 nano-second units since the Gregorian epoch,
1709 // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
1710 // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
1711 // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
1712 var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime();
1713
1714 // Per 4.2.1.2, use count of uuid's generated during the current clock
1715 // cycle to simulate higher resolution clock
1716 var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1;
1717
1718 // Time since last uuid creation (in msecs)
1719 var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;
1720
1721 // Per 4.2.1.2, Bump clockseq on clock regression
1722 if (dt < 0 && options.clockseq === undefined) {
1723 clockseq = clockseq + 1 & 0x3fff;
1724 }
1725
1726 // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
1727 // time interval
1728 if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {
1729 nsecs = 0;
1730 }
1731
1732 // Per 4.2.1.2 Throw error if too many uuids are requested
1733 if (nsecs >= 10000) {
1734 throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec');
1735 }
1736
1737 _lastMSecs = msecs;
1738 _lastNSecs = nsecs;
1739 _clockseq = clockseq;
1740
1741 // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
1742 msecs += 12219292800000;
1743
1744 // `time_low`
1745 var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
1746 b[i++] = tl >>> 24 & 0xff;
1747 b[i++] = tl >>> 16 & 0xff;
1748 b[i++] = tl >>> 8 & 0xff;
1749 b[i++] = tl & 0xff;
1750
1751 // `time_mid`
1752 var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;
1753 b[i++] = tmh >>> 8 & 0xff;
1754 b[i++] = tmh & 0xff;
1755
1756 // `time_high_and_version`
1757 b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
1758 b[i++] = tmh >>> 16 & 0xff;
1759
1760 // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
1761 b[i++] = clockseq >>> 8 | 0x80;
1762
1763 // `clock_seq_low`
1764 b[i++] = clockseq & 0xff;
1765
1766 // `node`
1767 for (var n = 0; n < 6; ++n) {
1768 b[i + n] = node[n];
1769 }
1770
1771 return buf ? buf : bytesToUuid(b);
1772}
1773
1774module.exports = v1;
1775
1776},{"8":8,"9":9}],11:[function(_dereq_,module,exports){
1777var rng = _dereq_(9);
1778var bytesToUuid = _dereq_(8);
1779
1780function v4(options, buf, offset) {
1781 var i = buf && offset || 0;
1782
1783 if (typeof(options) == 'string') {
1784 buf = options === 'binary' ? new Array(16) : null;
1785 options = null;
1786 }
1787 options = options || {};
1788
1789 var rnds = options.random || (options.rng || rng)();
1790
1791 // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
1792 rnds[6] = (rnds[6] & 0x0f) | 0x40;
1793 rnds[8] = (rnds[8] & 0x3f) | 0x80;
1794
1795 // Copy bytes to buffer, if provided
1796 if (buf) {
1797 for (var ii = 0; ii < 16; ++ii) {
1798 buf[i + ii] = rnds[ii];
1799 }
1800 }
1801
1802 return buf || bytesToUuid(rnds);
1803}
1804
1805module.exports = v4;
1806
1807},{"8":8,"9":9}],12:[function(_dereq_,module,exports){
1808'use strict';
1809
1810/**
1811 * Stringify/parse functions that don't operate
1812 * recursively, so they avoid call stack exceeded
1813 * errors.
1814 */
1815exports.stringify = function stringify(input) {
1816 var queue = [];
1817 queue.push({obj: input});
1818
1819 var res = '';
1820 var next, obj, prefix, val, i, arrayPrefix, keys, k, key, value, objPrefix;
1821 while ((next = queue.pop())) {
1822 obj = next.obj;
1823 prefix = next.prefix || '';
1824 val = next.val || '';
1825 res += prefix;
1826 if (val) {
1827 res += val;
1828 } else if (typeof obj !== 'object') {
1829 res += typeof obj === 'undefined' ? null : JSON.stringify(obj);
1830 } else if (obj === null) {
1831 res += 'null';
1832 } else if (Array.isArray(obj)) {
1833 queue.push({val: ']'});
1834 for (i = obj.length - 1; i >= 0; i--) {
1835 arrayPrefix = i === 0 ? '' : ',';
1836 queue.push({obj: obj[i], prefix: arrayPrefix});
1837 }
1838 queue.push({val: '['});
1839 } else { // object
1840 keys = [];
1841 for (k in obj) {
1842 if (obj.hasOwnProperty(k)) {
1843 keys.push(k);
1844 }
1845 }
1846 queue.push({val: '}'});
1847 for (i = keys.length - 1; i >= 0; i--) {
1848 key = keys[i];
1849 value = obj[key];
1850 objPrefix = (i > 0 ? ',' : '');
1851 objPrefix += JSON.stringify(key) + ':';
1852 queue.push({obj: value, prefix: objPrefix});
1853 }
1854 queue.push({val: '{'});
1855 }
1856 }
1857 return res;
1858};
1859
1860// Convenience function for the parse function.
1861// This pop function is basically copied from
1862// pouchCollate.parseIndexableString
1863function pop(obj, stack, metaStack) {
1864 var lastMetaElement = metaStack[metaStack.length - 1];
1865 if (obj === lastMetaElement.element) {
1866 // popping a meta-element, e.g. an object whose value is another object
1867 metaStack.pop();
1868 lastMetaElement = metaStack[metaStack.length - 1];
1869 }
1870 var element = lastMetaElement.element;
1871 var lastElementIndex = lastMetaElement.index;
1872 if (Array.isArray(element)) {
1873 element.push(obj);
1874 } else if (lastElementIndex === stack.length - 2) { // obj with key+value
1875 var key = stack.pop();
1876 element[key] = obj;
1877 } else {
1878 stack.push(obj); // obj with key only
1879 }
1880}
1881
1882exports.parse = function (str) {
1883 var stack = [];
1884 var metaStack = []; // stack for arrays and objects
1885 var i = 0;
1886 var collationIndex,parsedNum,numChar;
1887 var parsedString,lastCh,numConsecutiveSlashes,ch;
1888 var arrayElement, objElement;
1889 while (true) {
1890 collationIndex = str[i++];
1891 if (collationIndex === '}' ||
1892 collationIndex === ']' ||
1893 typeof collationIndex === 'undefined') {
1894 if (stack.length === 1) {
1895 return stack.pop();
1896 } else {
1897 pop(stack.pop(), stack, metaStack);
1898 continue;
1899 }
1900 }
1901 switch (collationIndex) {
1902 case ' ':
1903 case '\t':
1904 case '\n':
1905 case ':':
1906 case ',':
1907 break;
1908 case 'n':
1909 i += 3; // 'ull'
1910 pop(null, stack, metaStack);
1911 break;
1912 case 't':
1913 i += 3; // 'rue'
1914 pop(true, stack, metaStack);
1915 break;
1916 case 'f':
1917 i += 4; // 'alse'
1918 pop(false, stack, metaStack);
1919 break;
1920 case '0':
1921 case '1':
1922 case '2':
1923 case '3':
1924 case '4':
1925 case '5':
1926 case '6':
1927 case '7':
1928 case '8':
1929 case '9':
1930 case '-':
1931 parsedNum = '';
1932 i--;
1933 while (true) {
1934 numChar = str[i++];
1935 if (/[\d\.\-e\+]/.test(numChar)) {
1936 parsedNum += numChar;
1937 } else {
1938 i--;
1939 break;
1940 }
1941 }
1942 pop(parseFloat(parsedNum), stack, metaStack);
1943 break;
1944 case '"':
1945 parsedString = '';
1946 lastCh = void 0;
1947 numConsecutiveSlashes = 0;
1948 while (true) {
1949 ch = str[i++];
1950 if (ch !== '"' || (lastCh === '\\' &&
1951 numConsecutiveSlashes % 2 === 1)) {
1952 parsedString += ch;
1953 lastCh = ch;
1954 if (lastCh === '\\') {
1955 numConsecutiveSlashes++;
1956 } else {
1957 numConsecutiveSlashes = 0;
1958 }
1959 } else {
1960 break;
1961 }
1962 }
1963 pop(JSON.parse('"' + parsedString + '"'), stack, metaStack);
1964 break;
1965 case '[':
1966 arrayElement = { element: [], index: stack.length };
1967 stack.push(arrayElement.element);
1968 metaStack.push(arrayElement);
1969 break;
1970 case '{':
1971 objElement = { element: {}, index: stack.length };
1972 stack.push(objElement.element);
1973 metaStack.push(objElement);
1974 break;
1975 default:
1976 throw new Error(
1977 'unexpectedly reached end of input: ' + collationIndex);
1978 }
1979 }
1980};
1981
1982},{}],13:[function(_dereq_,module,exports){
1983(function (process,global){
1984'use strict';
1985
1986function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
1987
1988var immediate = _interopDefault(_dereq_(3));
1989var uuidV4 = _interopDefault(_dereq_(7));
1990var Md5 = _interopDefault(_dereq_(6));
1991var vuvuzela = _interopDefault(_dereq_(12));
1992var getArguments = _interopDefault(_dereq_(1));
1993var inherits = _interopDefault(_dereq_(4));
1994var events = _dereq_(2);
1995
1996function mangle(key) {
1997 return '$' + key;
1998}
1999function unmangle(key) {
2000 return key.substring(1);
2001}
2002function Map$1() {
2003 this._store = {};
2004}
2005Map$1.prototype.get = function (key) {
2006 var mangled = mangle(key);
2007 return this._store[mangled];
2008};
2009Map$1.prototype.set = function (key, value) {
2010 var mangled = mangle(key);
2011 this._store[mangled] = value;
2012 return true;
2013};
2014Map$1.prototype.has = function (key) {
2015 var mangled = mangle(key);
2016 return mangled in this._store;
2017};
2018Map$1.prototype["delete"] = function (key) {
2019 var mangled = mangle(key);
2020 var res = mangled in this._store;
2021 delete this._store[mangled];
2022 return res;
2023};
2024Map$1.prototype.forEach = function (cb) {
2025 var keys = Object.keys(this._store);
2026 for (var i = 0, len = keys.length; i < len; i++) {
2027 var key = keys[i];
2028 var value = this._store[key];
2029 key = unmangle(key);
2030 cb(value, key);
2031 }
2032};
2033Object.defineProperty(Map$1.prototype, 'size', {
2034 get: function () {
2035 return Object.keys(this._store).length;
2036 }
2037});
2038
2039function Set$1(array) {
2040 this._store = new Map$1();
2041
2042 // init with an array
2043 if (array && Array.isArray(array)) {
2044 for (var i = 0, len = array.length; i < len; i++) {
2045 this.add(array[i]);
2046 }
2047 }
2048}
2049Set$1.prototype.add = function (key) {
2050 return this._store.set(key, true);
2051};
2052Set$1.prototype.has = function (key) {
2053 return this._store.has(key);
2054};
2055Set$1.prototype.forEach = function (cb) {
2056 this._store.forEach(function (value, key) {
2057 cb(key);
2058 });
2059};
2060Object.defineProperty(Set$1.prototype, 'size', {
2061 get: function () {
2062 return this._store.size;
2063 }
2064});
2065
2066/* global Map,Set,Symbol */
2067// Based on https://kangax.github.io/compat-table/es6/ we can sniff out
2068// incomplete Map/Set implementations which would otherwise cause our tests to fail.
2069// Notably they fail in IE11 and iOS 8.4, which this prevents.
2070function supportsMapAndSet() {
2071 if (typeof Symbol === 'undefined' || typeof Map === 'undefined' || typeof Set === 'undefined') {
2072 return false;
2073 }
2074 var prop = Object.getOwnPropertyDescriptor(Map, Symbol.species);
2075 return prop && 'get' in prop && Map[Symbol.species] === Map;
2076}
2077
2078// based on https://github.com/montagejs/collections
2079
2080var ExportedSet;
2081var ExportedMap;
2082
2083{
2084 if (supportsMapAndSet()) { // prefer built-in Map/Set
2085 ExportedSet = Set;
2086 ExportedMap = Map;
2087 } else { // fall back to our polyfill
2088 ExportedSet = Set$1;
2089 ExportedMap = Map$1;
2090 }
2091}
2092
2093function isBinaryObject(object) {
2094 return (typeof ArrayBuffer !== 'undefined' && object instanceof ArrayBuffer) ||
2095 (typeof Blob !== 'undefined' && object instanceof Blob);
2096}
2097
2098function cloneArrayBuffer(buff) {
2099 if (typeof buff.slice === 'function') {
2100 return buff.slice(0);
2101 }
2102 // IE10-11 slice() polyfill
2103 var target = new ArrayBuffer(buff.byteLength);
2104 var targetArray = new Uint8Array(target);
2105 var sourceArray = new Uint8Array(buff);
2106 targetArray.set(sourceArray);
2107 return target;
2108}
2109
2110function cloneBinaryObject(object) {
2111 if (object instanceof ArrayBuffer) {
2112 return cloneArrayBuffer(object);
2113 }
2114 var size = object.size;
2115 var type = object.type;
2116 // Blob
2117 if (typeof object.slice === 'function') {
2118 return object.slice(0, size, type);
2119 }
2120 // PhantomJS slice() replacement
2121 return object.webkitSlice(0, size, type);
2122}
2123
2124// most of this is borrowed from lodash.isPlainObject:
2125// https://github.com/fis-components/lodash.isplainobject/
2126// blob/29c358140a74f252aeb08c9eb28bef86f2217d4a/index.js
2127
2128var funcToString = Function.prototype.toString;
2129var objectCtorString = funcToString.call(Object);
2130
2131function isPlainObject(value) {
2132 var proto = Object.getPrototypeOf(value);
2133 /* istanbul ignore if */
2134 if (proto === null) { // not sure when this happens, but I guess it can
2135 return true;
2136 }
2137 var Ctor = proto.constructor;
2138 return (typeof Ctor == 'function' &&
2139 Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString);
2140}
2141
2142function clone(object) {
2143 var newObject;
2144 var i;
2145 var len;
2146
2147 if (!object || typeof object !== 'object') {
2148 return object;
2149 }
2150
2151 if (Array.isArray(object)) {
2152 newObject = [];
2153 for (i = 0, len = object.length; i < len; i++) {
2154 newObject[i] = clone(object[i]);
2155 }
2156 return newObject;
2157 }
2158
2159 // special case: to avoid inconsistencies between IndexedDB
2160 // and other backends, we automatically stringify Dates
2161 if (object instanceof Date) {
2162 return object.toISOString();
2163 }
2164
2165 if (isBinaryObject(object)) {
2166 return cloneBinaryObject(object);
2167 }
2168
2169 if (!isPlainObject(object)) {
2170 return object; // don't clone objects like Workers
2171 }
2172
2173 newObject = {};
2174 for (i in object) {
2175 /* istanbul ignore else */
2176 if (Object.prototype.hasOwnProperty.call(object, i)) {
2177 var value = clone(object[i]);
2178 if (typeof value !== 'undefined') {
2179 newObject[i] = value;
2180 }
2181 }
2182 }
2183 return newObject;
2184}
2185
2186function once(fun) {
2187 var called = false;
2188 return getArguments(function (args) {
2189 /* istanbul ignore if */
2190 if (called) {
2191 // this is a smoke test and should never actually happen
2192 throw new Error('once called more than once');
2193 } else {
2194 called = true;
2195 fun.apply(this, args);
2196 }
2197 });
2198}
2199
2200function toPromise(func) {
2201 //create the function we will be returning
2202 return getArguments(function (args) {
2203 // Clone arguments
2204 args = clone(args);
2205 var self = this;
2206 // if the last argument is a function, assume its a callback
2207 var usedCB = (typeof args[args.length - 1] === 'function') ? args.pop() : false;
2208 var promise = new Promise(function (fulfill, reject) {
2209 var resp;
2210 try {
2211 var callback = once(function (err, mesg) {
2212 if (err) {
2213 reject(err);
2214 } else {
2215 fulfill(mesg);
2216 }
2217 });
2218 // create a callback for this invocation
2219 // apply the function in the orig context
2220 args.push(callback);
2221 resp = func.apply(self, args);
2222 if (resp && typeof resp.then === 'function') {
2223 fulfill(resp);
2224 }
2225 } catch (e) {
2226 reject(e);
2227 }
2228 });
2229 // if there is a callback, call it back
2230 if (usedCB) {
2231 promise.then(function (result) {
2232 usedCB(null, result);
2233 }, usedCB);
2234 }
2235 return promise;
2236 });
2237}
2238
2239function logApiCall(self, name, args) {
2240 /* istanbul ignore if */
2241 if (self.constructor.listeners('debug').length) {
2242 var logArgs = ['api', self.name, name];
2243 for (var i = 0; i < args.length - 1; i++) {
2244 logArgs.push(args[i]);
2245 }
2246 self.constructor.emit('debug', logArgs);
2247
2248 // override the callback itself to log the response
2249 var origCallback = args[args.length - 1];
2250 args[args.length - 1] = function (err, res) {
2251 var responseArgs = ['api', self.name, name];
2252 responseArgs = responseArgs.concat(
2253 err ? ['error', err] : ['success', res]
2254 );
2255 self.constructor.emit('debug', responseArgs);
2256 origCallback(err, res);
2257 };
2258 }
2259}
2260
2261function adapterFun(name, callback) {
2262 return toPromise(getArguments(function (args) {
2263 if (this._closed) {
2264 return Promise.reject(new Error('database is closed'));
2265 }
2266 if (this._destroyed) {
2267 return Promise.reject(new Error('database is destroyed'));
2268 }
2269 var self = this;
2270 logApiCall(self, name, args);
2271 if (!this.taskqueue.isReady) {
2272 return new Promise(function (fulfill, reject) {
2273 self.taskqueue.addTask(function (failed) {
2274 if (failed) {
2275 reject(failed);
2276 } else {
2277 fulfill(self[name].apply(self, args));
2278 }
2279 });
2280 });
2281 }
2282 return callback.apply(this, args);
2283 }));
2284}
2285
2286// like underscore/lodash _.pick()
2287function pick(obj, arr) {
2288 var res = {};
2289 for (var i = 0, len = arr.length; i < len; i++) {
2290 var prop = arr[i];
2291 if (prop in obj) {
2292 res[prop] = obj[prop];
2293 }
2294 }
2295 return res;
2296}
2297
2298// Most browsers throttle concurrent requests at 6, so it's silly
2299// to shim _bulk_get by trying to launch potentially hundreds of requests
2300// and then letting the majority time out. We can handle this ourselves.
2301var MAX_NUM_CONCURRENT_REQUESTS = 6;
2302
2303function identityFunction(x) {
2304 return x;
2305}
2306
2307function formatResultForOpenRevsGet(result) {
2308 return [{
2309 ok: result
2310 }];
2311}
2312
2313// shim for P/CouchDB adapters that don't directly implement _bulk_get
2314function bulkGet(db, opts, callback) {
2315 var requests = opts.docs;
2316
2317 // consolidate into one request per doc if possible
2318 var requestsById = new ExportedMap();
2319 requests.forEach(function (request) {
2320 if (requestsById.has(request.id)) {
2321 requestsById.get(request.id).push(request);
2322 } else {
2323 requestsById.set(request.id, [request]);
2324 }
2325 });
2326
2327 var numDocs = requestsById.size;
2328 var numDone = 0;
2329 var perDocResults = new Array(numDocs);
2330
2331 function collapseResultsAndFinish() {
2332 var results = [];
2333 perDocResults.forEach(function (res) {
2334 res.docs.forEach(function (info) {
2335 results.push({
2336 id: res.id,
2337 docs: [info]
2338 });
2339 });
2340 });
2341 callback(null, {results: results});
2342 }
2343
2344 function checkDone() {
2345 if (++numDone === numDocs) {
2346 collapseResultsAndFinish();
2347 }
2348 }
2349
2350 function gotResult(docIndex, id, docs) {
2351 perDocResults[docIndex] = {id: id, docs: docs};
2352 checkDone();
2353 }
2354
2355 var allRequests = [];
2356 requestsById.forEach(function (value, key) {
2357 allRequests.push(key);
2358 });
2359
2360 var i = 0;
2361
2362 function nextBatch() {
2363
2364 if (i >= allRequests.length) {
2365 return;
2366 }
2367
2368 var upTo = Math.min(i + MAX_NUM_CONCURRENT_REQUESTS, allRequests.length);
2369 var batch = allRequests.slice(i, upTo);
2370 processBatch(batch, i);
2371 i += batch.length;
2372 }
2373
2374 function processBatch(batch, offset) {
2375 batch.forEach(function (docId, j) {
2376 var docIdx = offset + j;
2377 var docRequests = requestsById.get(docId);
2378
2379 // just use the first request as the "template"
2380 // TODO: The _bulk_get API allows for more subtle use cases than this,
2381 // but for now it is unlikely that there will be a mix of different
2382 // "atts_since" or "attachments" in the same request, since it's just
2383 // replicate.js that is using this for the moment.
2384 // Also, atts_since is aspirational, since we don't support it yet.
2385 var docOpts = pick(docRequests[0], ['atts_since', 'attachments']);
2386 docOpts.open_revs = docRequests.map(function (request) {
2387 // rev is optional, open_revs disallowed
2388 return request.rev;
2389 });
2390
2391 // remove falsey / undefined revisions
2392 docOpts.open_revs = docOpts.open_revs.filter(identityFunction);
2393
2394 var formatResult = identityFunction;
2395
2396 if (docOpts.open_revs.length === 0) {
2397 delete docOpts.open_revs;
2398
2399 // when fetching only the "winning" leaf,
2400 // transform the result so it looks like an open_revs
2401 // request
2402 formatResult = formatResultForOpenRevsGet;
2403 }
2404
2405 // globally-supplied options
2406 ['revs', 'attachments', 'binary', 'ajax', 'latest'].forEach(function (param) {
2407 if (param in opts) {
2408 docOpts[param] = opts[param];
2409 }
2410 });
2411 db.get(docId, docOpts, function (err, res) {
2412 var result;
2413 /* istanbul ignore if */
2414 if (err) {
2415 result = [{error: err}];
2416 } else {
2417 result = formatResult(res);
2418 }
2419 gotResult(docIdx, docId, result);
2420 nextBatch();
2421 });
2422 });
2423 }
2424
2425 nextBatch();
2426
2427}
2428
2429var hasLocal;
2430
2431try {
2432 localStorage.setItem('_pouch_check_localstorage', 1);
2433 hasLocal = !!localStorage.getItem('_pouch_check_localstorage');
2434} catch (e) {
2435 hasLocal = false;
2436}
2437
2438function hasLocalStorage() {
2439 return hasLocal;
2440}
2441
2442// Custom nextTick() shim for browsers. In node, this will just be process.nextTick(). We
2443
2444inherits(Changes, events.EventEmitter);
2445
2446/* istanbul ignore next */
2447function attachBrowserEvents(self) {
2448 if (hasLocalStorage()) {
2449 addEventListener("storage", function (e) {
2450 self.emit(e.key);
2451 });
2452 }
2453}
2454
2455function Changes() {
2456 events.EventEmitter.call(this);
2457 this._listeners = {};
2458
2459 attachBrowserEvents(this);
2460}
2461Changes.prototype.addListener = function (dbName, id, db, opts) {
2462 /* istanbul ignore if */
2463 if (this._listeners[id]) {
2464 return;
2465 }
2466 var self = this;
2467 var inprogress = false;
2468 function eventFunction() {
2469 /* istanbul ignore if */
2470 if (!self._listeners[id]) {
2471 return;
2472 }
2473 if (inprogress) {
2474 inprogress = 'waiting';
2475 return;
2476 }
2477 inprogress = true;
2478 var changesOpts = pick(opts, [
2479 'style', 'include_docs', 'attachments', 'conflicts', 'filter',
2480 'doc_ids', 'view', 'since', 'query_params', 'binary', 'return_docs'
2481 ]);
2482
2483 /* istanbul ignore next */
2484 function onError() {
2485 inprogress = false;
2486 }
2487
2488 db.changes(changesOpts).on('change', function (c) {
2489 if (c.seq > opts.since && !opts.cancelled) {
2490 opts.since = c.seq;
2491 opts.onChange(c);
2492 }
2493 }).on('complete', function () {
2494 if (inprogress === 'waiting') {
2495 immediate(eventFunction);
2496 }
2497 inprogress = false;
2498 }).on('error', onError);
2499 }
2500 this._listeners[id] = eventFunction;
2501 this.on(dbName, eventFunction);
2502};
2503
2504Changes.prototype.removeListener = function (dbName, id) {
2505 /* istanbul ignore if */
2506 if (!(id in this._listeners)) {
2507 return;
2508 }
2509 events.EventEmitter.prototype.removeListener.call(this, dbName,
2510 this._listeners[id]);
2511 delete this._listeners[id];
2512};
2513
2514
2515/* istanbul ignore next */
2516Changes.prototype.notifyLocalWindows = function (dbName) {
2517 //do a useless change on a storage thing
2518 //in order to get other windows's listeners to activate
2519 if (hasLocalStorage()) {
2520 localStorage[dbName] = (localStorage[dbName] === "a") ? "b" : "a";
2521 }
2522};
2523
2524Changes.prototype.notify = function (dbName) {
2525 this.emit(dbName);
2526 this.notifyLocalWindows(dbName);
2527};
2528
2529function guardedConsole(method) {
2530 /* istanbul ignore else */
2531 if (typeof console !== 'undefined' && typeof console[method] === 'function') {
2532 var args = Array.prototype.slice.call(arguments, 1);
2533 console[method].apply(console, args);
2534 }
2535}
2536
2537function randomNumber(min, max) {
2538 var maxTimeout = 600000; // Hard-coded default of 10 minutes
2539 min = parseInt(min, 10) || 0;
2540 max = parseInt(max, 10);
2541 if (max !== max || max <= min) {
2542 max = (min || 1) << 1; //doubling
2543 } else {
2544 max = max + 1;
2545 }
2546 // In order to not exceed maxTimeout, pick a random value between half of maxTimeout and maxTimeout
2547 if (max > maxTimeout) {
2548 min = maxTimeout >> 1; // divide by two
2549 max = maxTimeout;
2550 }
2551 var ratio = Math.random();
2552 var range = max - min;
2553
2554 return ~~(range * ratio + min); // ~~ coerces to an int, but fast.
2555}
2556
2557function defaultBackOff(min) {
2558 var max = 0;
2559 if (!min) {
2560 max = 2000;
2561 }
2562 return randomNumber(min, max);
2563}
2564
2565// designed to give info to browser users, who are disturbed
2566// when they see http errors in the console
2567function explainError(status, str) {
2568 guardedConsole('info', 'The above ' + status + ' is totally normal. ' + str);
2569}
2570
2571var assign;
2572{
2573 if (typeof Object.assign === 'function') {
2574 assign = Object.assign;
2575 } else {
2576 // lite Object.assign polyfill based on
2577 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
2578 assign = function (target) {
2579 var to = Object(target);
2580
2581 for (var index = 1; index < arguments.length; index++) {
2582 var nextSource = arguments[index];
2583
2584 if (nextSource != null) { // Skip over if undefined or null
2585 for (var nextKey in nextSource) {
2586 // Avoid bugs when hasOwnProperty is shadowed
2587 if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
2588 to[nextKey] = nextSource[nextKey];
2589 }
2590 }
2591 }
2592 }
2593 return to;
2594 };
2595 }
2596}
2597
2598var $inject_Object_assign = assign;
2599
2600inherits(PouchError, Error);
2601
2602function PouchError(status, error, reason) {
2603 Error.call(this, reason);
2604 this.status = status;
2605 this.name = error;
2606 this.message = reason;
2607 this.error = true;
2608}
2609
2610PouchError.prototype.toString = function () {
2611 return JSON.stringify({
2612 status: this.status,
2613 name: this.name,
2614 message: this.message,
2615 reason: this.reason
2616 });
2617};
2618
2619var UNAUTHORIZED = new PouchError(401, 'unauthorized', "Name or password is incorrect.");
2620var MISSING_BULK_DOCS = new PouchError(400, 'bad_request', "Missing JSON list of 'docs'");
2621var MISSING_DOC = new PouchError(404, 'not_found', 'missing');
2622var REV_CONFLICT = new PouchError(409, 'conflict', 'Document update conflict');
2623var INVALID_ID = new PouchError(400, 'bad_request', '_id field must contain a string');
2624var MISSING_ID = new PouchError(412, 'missing_id', '_id is required for puts');
2625var RESERVED_ID = new PouchError(400, 'bad_request', 'Only reserved document ids may start with underscore.');
2626var NOT_OPEN = new PouchError(412, 'precondition_failed', 'Database not open');
2627var UNKNOWN_ERROR = new PouchError(500, 'unknown_error', 'Database encountered an unknown error');
2628var BAD_ARG = new PouchError(500, 'badarg', 'Some query argument is invalid');
2629var INVALID_REQUEST = new PouchError(400, 'invalid_request', 'Request was invalid');
2630var QUERY_PARSE_ERROR = new PouchError(400, 'query_parse_error', 'Some query parameter is invalid');
2631var DOC_VALIDATION = new PouchError(500, 'doc_validation', 'Bad special document member');
2632var BAD_REQUEST = new PouchError(400, 'bad_request', 'Something wrong with the request');
2633var NOT_AN_OBJECT = new PouchError(400, 'bad_request', 'Document must be a JSON object');
2634var DB_MISSING = new PouchError(404, 'not_found', 'Database not found');
2635var IDB_ERROR = new PouchError(500, 'indexed_db_went_bad', 'unknown');
2636var WSQ_ERROR = new PouchError(500, 'web_sql_went_bad', 'unknown');
2637var LDB_ERROR = new PouchError(500, 'levelDB_went_went_bad', 'unknown');
2638var FORBIDDEN = new PouchError(403, 'forbidden', 'Forbidden by design doc validate_doc_update function');
2639var INVALID_REV = new PouchError(400, 'bad_request', 'Invalid rev format');
2640var FILE_EXISTS = new PouchError(412, 'file_exists', 'The database could not be created, the file already exists.');
2641var MISSING_STUB = new PouchError(412, 'missing_stub', 'A pre-existing attachment stub wasn\'t found');
2642var INVALID_URL = new PouchError(413, 'invalid_url', 'Provided URL is invalid');
2643
2644function createError(error, reason) {
2645 function CustomPouchError(reason) {
2646 // inherit error properties from our parent error manually
2647 // so as to allow proper JSON parsing.
2648 /* jshint ignore:start */
2649 for (var p in error) {
2650 if (typeof error[p] !== 'function') {
2651 this[p] = error[p];
2652 }
2653 }
2654 /* jshint ignore:end */
2655 if (reason !== undefined) {
2656 this.reason = reason;
2657 }
2658 }
2659 CustomPouchError.prototype = PouchError.prototype;
2660 return new CustomPouchError(reason);
2661}
2662
2663function generateErrorFromResponse(err) {
2664
2665 if (typeof err !== 'object') {
2666 var data = err;
2667 err = UNKNOWN_ERROR;
2668 err.data = data;
2669 }
2670
2671 if ('error' in err && err.error === 'conflict') {
2672 err.name = 'conflict';
2673 err.status = 409;
2674 }
2675
2676 if (!('name' in err)) {
2677 err.name = err.error || 'unknown';
2678 }
2679
2680 if (!('status' in err)) {
2681 err.status = 500;
2682 }
2683
2684 if (!('message' in err)) {
2685 err.message = err.message || err.reason;
2686 }
2687
2688 return err;
2689}
2690
2691function tryFilter(filter, doc, req) {
2692 try {
2693 return !filter(doc, req);
2694 } catch (err) {
2695 var msg = 'Filter function threw: ' + err.toString();
2696 return createError(BAD_REQUEST, msg);
2697 }
2698}
2699
2700function filterChange(opts) {
2701 var req = {};
2702 var hasFilter = opts.filter && typeof opts.filter === 'function';
2703 req.query = opts.query_params;
2704
2705 return function filter(change) {
2706 if (!change.doc) {
2707 // CSG sends events on the changes feed that don't have documents,
2708 // this hack makes a whole lot of existing code robust.
2709 change.doc = {};
2710 }
2711
2712 var filterReturn = hasFilter && tryFilter(opts.filter, change.doc, req);
2713
2714 if (typeof filterReturn === 'object') {
2715 return filterReturn;
2716 }
2717
2718 if (filterReturn) {
2719 return false;
2720 }
2721
2722 if (!opts.include_docs) {
2723 delete change.doc;
2724 } else if (!opts.attachments) {
2725 for (var att in change.doc._attachments) {
2726 /* istanbul ignore else */
2727 if (change.doc._attachments.hasOwnProperty(att)) {
2728 change.doc._attachments[att].stub = true;
2729 }
2730 }
2731 }
2732 return true;
2733 };
2734}
2735
2736function flatten(arrs) {
2737 var res = [];
2738 for (var i = 0, len = arrs.length; i < len; i++) {
2739 res = res.concat(arrs[i]);
2740 }
2741 return res;
2742}
2743
2744// shim for Function.prototype.name,
2745
2746// Determine id an ID is valid
2747// - invalid IDs begin with an underescore that does not begin '_design' or
2748// '_local'
2749// - any other string value is a valid id
2750// Returns the specific error object for each case
2751function invalidIdError(id) {
2752 var err;
2753 if (!id) {
2754 err = createError(MISSING_ID);
2755 } else if (typeof id !== 'string') {
2756 err = createError(INVALID_ID);
2757 } else if (/^_/.test(id) && !(/^_(design|local)/).test(id)) {
2758 err = createError(RESERVED_ID);
2759 }
2760 if (err) {
2761 throw err;
2762 }
2763}
2764
2765// Checks if a PouchDB object is "remote" or not. This is
2766
2767function isRemote(db) {
2768 if (typeof db._remote === 'boolean') {
2769 return db._remote;
2770 }
2771 /* istanbul ignore next */
2772 if (typeof db.type === 'function') {
2773 guardedConsole('warn',
2774 'db.type() is deprecated and will be removed in ' +
2775 'a future version of PouchDB');
2776 return db.type() === 'http';
2777 }
2778 /* istanbul ignore next */
2779 return false;
2780}
2781
2782function listenerCount(ee, type) {
2783 return 'listenerCount' in ee ? ee.listenerCount(type) :
2784 events.EventEmitter.listenerCount(ee, type);
2785}
2786
2787function parseDesignDocFunctionName(s) {
2788 if (!s) {
2789 return null;
2790 }
2791 var parts = s.split('/');
2792 if (parts.length === 2) {
2793 return parts;
2794 }
2795 if (parts.length === 1) {
2796 return [s, s];
2797 }
2798 return null;
2799}
2800
2801function normalizeDesignDocFunctionName(s) {
2802 var normalized = parseDesignDocFunctionName(s);
2803 return normalized ? normalized.join('/') : null;
2804}
2805
2806// originally parseUri 1.2.2, now patched by us
2807// (c) Steven Levithan <stevenlevithan.com>
2808// MIT License
2809var keys = ["source", "protocol", "authority", "userInfo", "user", "password",
2810 "host", "port", "relative", "path", "directory", "file", "query", "anchor"];
2811var qName ="queryKey";
2812var qParser = /(?:^|&)([^&=]*)=?([^&]*)/g;
2813
2814// use the "loose" parser
2815/* eslint maxlen: 0, no-useless-escape: 0 */
2816var parser = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
2817
2818function parseUri(str) {
2819 var m = parser.exec(str);
2820 var uri = {};
2821 var i = 14;
2822
2823 while (i--) {
2824 var key = keys[i];
2825 var value = m[i] || "";
2826 var encoded = ['user', 'password'].indexOf(key) !== -1;
2827 uri[key] = encoded ? decodeURIComponent(value) : value;
2828 }
2829
2830 uri[qName] = {};
2831 uri[keys[12]].replace(qParser, function ($0, $1, $2) {
2832 if ($1) {
2833 uri[qName][$1] = $2;
2834 }
2835 });
2836
2837 return uri;
2838}
2839
2840// Based on https://github.com/alexdavid/scope-eval v0.0.3
2841// (source: https://unpkg.com/scope-eval@0.0.3/scope_eval.js)
2842// This is basically just a wrapper around new Function()
2843
2844function scopeEval(source, scope) {
2845 var keys = [];
2846 var values = [];
2847 for (var key in scope) {
2848 if (scope.hasOwnProperty(key)) {
2849 keys.push(key);
2850 values.push(scope[key]);
2851 }
2852 }
2853 keys.push(source);
2854 return Function.apply(null, keys).apply(null, values);
2855}
2856
2857// this is essentially the "update sugar" function from daleharvey/pouchdb#1388
2858// the diffFun tells us what delta to apply to the doc. it either returns
2859// the doc, or false if it doesn't need to do an update after all
2860function upsert(db, docId, diffFun) {
2861 return new Promise(function (fulfill, reject) {
2862 db.get(docId, function (err, doc) {
2863 if (err) {
2864 /* istanbul ignore next */
2865 if (err.status !== 404) {
2866 return reject(err);
2867 }
2868 doc = {};
2869 }
2870
2871 // the user might change the _rev, so save it for posterity
2872 var docRev = doc._rev;
2873 var newDoc = diffFun(doc);
2874
2875 if (!newDoc) {
2876 // if the diffFun returns falsy, we short-circuit as
2877 // an optimization
2878 return fulfill({updated: false, rev: docRev});
2879 }
2880
2881 // users aren't allowed to modify these values,
2882 // so reset them here
2883 newDoc._id = docId;
2884 newDoc._rev = docRev;
2885 fulfill(tryAndPut(db, newDoc, diffFun));
2886 });
2887 });
2888}
2889
2890function tryAndPut(db, doc, diffFun) {
2891 return db.put(doc).then(function (res) {
2892 return {
2893 updated: true,
2894 rev: res.rev
2895 };
2896 }, function (err) {
2897 /* istanbul ignore next */
2898 if (err.status !== 409) {
2899 throw err;
2900 }
2901 return upsert(db, doc._id, diffFun);
2902 });
2903}
2904
2905var thisAtob = function (str) {
2906 return atob(str);
2907};
2908
2909var thisBtoa = function (str) {
2910 return btoa(str);
2911};
2912
2913// Abstracts constructing a Blob object, so it also works in older
2914// browsers that don't support the native Blob constructor (e.g.
2915// old QtWebKit versions, Android < 4.4).
2916function createBlob(parts, properties) {
2917 /* global BlobBuilder,MSBlobBuilder,MozBlobBuilder,WebKitBlobBuilder */
2918 parts = parts || [];
2919 properties = properties || {};
2920 try {
2921 return new Blob(parts, properties);
2922 } catch (e) {
2923 if (e.name !== "TypeError") {
2924 throw e;
2925 }
2926 var Builder = typeof BlobBuilder !== 'undefined' ? BlobBuilder :
2927 typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder :
2928 typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder :
2929 WebKitBlobBuilder;
2930 var builder = new Builder();
2931 for (var i = 0; i < parts.length; i += 1) {
2932 builder.append(parts[i]);
2933 }
2934 return builder.getBlob(properties.type);
2935 }
2936}
2937
2938// From http://stackoverflow.com/questions/14967647/ (continues on next line)
2939// encode-decode-image-with-base64-breaks-image (2013-04-21)
2940function binaryStringToArrayBuffer(bin) {
2941 var length = bin.length;
2942 var buf = new ArrayBuffer(length);
2943 var arr = new Uint8Array(buf);
2944 for (var i = 0; i < length; i++) {
2945 arr[i] = bin.charCodeAt(i);
2946 }
2947 return buf;
2948}
2949
2950function binStringToBluffer(binString, type) {
2951 return createBlob([binaryStringToArrayBuffer(binString)], {type: type});
2952}
2953
2954function b64ToBluffer(b64, type) {
2955 return binStringToBluffer(thisAtob(b64), type);
2956}
2957
2958//Can't find original post, but this is close
2959//http://stackoverflow.com/questions/6965107/ (continues on next line)
2960//converting-between-strings-and-arraybuffers
2961function arrayBufferToBinaryString(buffer) {
2962 var binary = '';
2963 var bytes = new Uint8Array(buffer);
2964 var length = bytes.byteLength;
2965 for (var i = 0; i < length; i++) {
2966 binary += String.fromCharCode(bytes[i]);
2967 }
2968 return binary;
2969}
2970
2971// shim for browsers that don't support it
2972function readAsBinaryString(blob, callback) {
2973 var reader = new FileReader();
2974 var hasBinaryString = typeof reader.readAsBinaryString === 'function';
2975 reader.onloadend = function (e) {
2976 var result = e.target.result || '';
2977 if (hasBinaryString) {
2978 return callback(result);
2979 }
2980 callback(arrayBufferToBinaryString(result));
2981 };
2982 if (hasBinaryString) {
2983 reader.readAsBinaryString(blob);
2984 } else {
2985 reader.readAsArrayBuffer(blob);
2986 }
2987}
2988
2989function blobToBinaryString(blobOrBuffer, callback) {
2990 readAsBinaryString(blobOrBuffer, function (bin) {
2991 callback(bin);
2992 });
2993}
2994
2995function blobToBase64(blobOrBuffer, callback) {
2996 blobToBinaryString(blobOrBuffer, function (base64) {
2997 callback(thisBtoa(base64));
2998 });
2999}
3000
3001// simplified API. universal browser support is assumed
3002function readAsArrayBuffer(blob, callback) {
3003 var reader = new FileReader();
3004 reader.onloadend = function (e) {
3005 var result = e.target.result || new ArrayBuffer(0);
3006 callback(result);
3007 };
3008 reader.readAsArrayBuffer(blob);
3009}
3010
3011// this is not used in the browser
3012
3013var setImmediateShim = global.setImmediate || global.setTimeout;
3014var MD5_CHUNK_SIZE = 32768;
3015
3016function rawToBase64(raw) {
3017 return thisBtoa(raw);
3018}
3019
3020function sliceBlob(blob, start, end) {
3021 if (blob.webkitSlice) {
3022 return blob.webkitSlice(start, end);
3023 }
3024 return blob.slice(start, end);
3025}
3026
3027function appendBlob(buffer, blob, start, end, callback) {
3028 if (start > 0 || end < blob.size) {
3029 // only slice blob if we really need to
3030 blob = sliceBlob(blob, start, end);
3031 }
3032 readAsArrayBuffer(blob, function (arrayBuffer) {
3033 buffer.append(arrayBuffer);
3034 callback();
3035 });
3036}
3037
3038function appendString(buffer, string, start, end, callback) {
3039 if (start > 0 || end < string.length) {
3040 // only create a substring if we really need to
3041 string = string.substring(start, end);
3042 }
3043 buffer.appendBinary(string);
3044 callback();
3045}
3046
3047function binaryMd5(data, callback) {
3048 var inputIsString = typeof data === 'string';
3049 var len = inputIsString ? data.length : data.size;
3050 var chunkSize = Math.min(MD5_CHUNK_SIZE, len);
3051 var chunks = Math.ceil(len / chunkSize);
3052 var currentChunk = 0;
3053 var buffer = inputIsString ? new Md5() : new Md5.ArrayBuffer();
3054
3055 var append = inputIsString ? appendString : appendBlob;
3056
3057 function next() {
3058 setImmediateShim(loadNextChunk);
3059 }
3060
3061 function done() {
3062 var raw = buffer.end(true);
3063 var base64 = rawToBase64(raw);
3064 callback(base64);
3065 buffer.destroy();
3066 }
3067
3068 function loadNextChunk() {
3069 var start = currentChunk * chunkSize;
3070 var end = start + chunkSize;
3071 currentChunk++;
3072 if (currentChunk < chunks) {
3073 append(buffer, data, start, end, next);
3074 } else {
3075 append(buffer, data, start, end, done);
3076 }
3077 }
3078 loadNextChunk();
3079}
3080
3081function stringMd5(string) {
3082 return Md5.hash(string);
3083}
3084
3085function rev(doc, deterministic_revs) {
3086 var clonedDoc = clone(doc);
3087 if (!deterministic_revs) {
3088 return uuidV4.v4().replace(/-/g, '').toLowerCase();
3089 }
3090
3091 delete clonedDoc._rev_tree;
3092 return stringMd5(JSON.stringify(clonedDoc));
3093}
3094
3095var uuid = uuidV4.v4;
3096
3097// We fetch all leafs of the revision tree, and sort them based on tree length
3098// and whether they were deleted, undeleted documents with the longest revision
3099// tree (most edits) win
3100// The final sort algorithm is slightly documented in a sidebar here:
3101// http://guide.couchdb.org/draft/conflicts.html
3102function winningRev(metadata) {
3103 var winningId;
3104 var winningPos;
3105 var winningDeleted;
3106 var toVisit = metadata.rev_tree.slice();
3107 var node;
3108 while ((node = toVisit.pop())) {
3109 var tree = node.ids;
3110 var branches = tree[2];
3111 var pos = node.pos;
3112 if (branches.length) { // non-leaf
3113 for (var i = 0, len = branches.length; i < len; i++) {
3114 toVisit.push({pos: pos + 1, ids: branches[i]});
3115 }
3116 continue;
3117 }
3118 var deleted = !!tree[1].deleted;
3119 var id = tree[0];
3120 // sort by deleted, then pos, then id
3121 if (!winningId || (winningDeleted !== deleted ? winningDeleted :
3122 winningPos !== pos ? winningPos < pos : winningId < id)) {
3123 winningId = id;
3124 winningPos = pos;
3125 winningDeleted = deleted;
3126 }
3127 }
3128
3129 return winningPos + '-' + winningId;
3130}
3131
3132// Pretty much all below can be combined into a higher order function to
3133// traverse revisions
3134// The return value from the callback will be passed as context to all
3135// children of that node
3136function traverseRevTree(revs, callback) {
3137 var toVisit = revs.slice();
3138
3139 var node;
3140 while ((node = toVisit.pop())) {
3141 var pos = node.pos;
3142 var tree = node.ids;
3143 var branches = tree[2];
3144 var newCtx =
3145 callback(branches.length === 0, pos, tree[0], node.ctx, tree[1]);
3146 for (var i = 0, len = branches.length; i < len; i++) {
3147 toVisit.push({pos: pos + 1, ids: branches[i], ctx: newCtx});
3148 }
3149 }
3150}
3151
3152function sortByPos(a, b) {
3153 return a.pos - b.pos;
3154}
3155
3156function collectLeaves(revs) {
3157 var leaves = [];
3158 traverseRevTree(revs, function (isLeaf, pos, id, acc, opts) {
3159 if (isLeaf) {
3160 leaves.push({rev: pos + "-" + id, pos: pos, opts: opts});
3161 }
3162 });
3163 leaves.sort(sortByPos).reverse();
3164 for (var i = 0, len = leaves.length; i < len; i++) {
3165 delete leaves[i].pos;
3166 }
3167 return leaves;
3168}
3169
3170// returns revs of all conflicts that is leaves such that
3171// 1. are not deleted and
3172// 2. are different than winning revision
3173function collectConflicts(metadata) {
3174 var win = winningRev(metadata);
3175 var leaves = collectLeaves(metadata.rev_tree);
3176 var conflicts = [];
3177 for (var i = 0, len = leaves.length; i < len; i++) {
3178 var leaf = leaves[i];
3179 if (leaf.rev !== win && !leaf.opts.deleted) {
3180 conflicts.push(leaf.rev);
3181 }
3182 }
3183 return conflicts;
3184}
3185
3186// compact a tree by marking its non-leafs as missing,
3187// and return a list of revs to delete
3188function compactTree(metadata) {
3189 var revs = [];
3190 traverseRevTree(metadata.rev_tree, function (isLeaf, pos,
3191 revHash, ctx, opts) {
3192 if (opts.status === 'available' && !isLeaf) {
3193 revs.push(pos + '-' + revHash);
3194 opts.status = 'missing';
3195 }
3196 });
3197 return revs;
3198}
3199
3200// build up a list of all the paths to the leafs in this revision tree
3201function rootToLeaf(revs) {
3202 var paths = [];
3203 var toVisit = revs.slice();
3204 var node;
3205 while ((node = toVisit.pop())) {
3206 var pos = node.pos;
3207 var tree = node.ids;
3208 var id = tree[0];
3209 var opts = tree[1];
3210 var branches = tree[2];
3211 var isLeaf = branches.length === 0;
3212
3213 var history = node.history ? node.history.slice() : [];
3214 history.push({id: id, opts: opts});
3215 if (isLeaf) {
3216 paths.push({pos: (pos + 1 - history.length), ids: history});
3217 }
3218 for (var i = 0, len = branches.length; i < len; i++) {
3219 toVisit.push({pos: pos + 1, ids: branches[i], history: history});
3220 }
3221 }
3222 return paths.reverse();
3223}
3224
3225// for a better overview of what this is doing, read:
3226
3227function sortByPos$1(a, b) {
3228 return a.pos - b.pos;
3229}
3230
3231// classic binary search
3232function binarySearch(arr, item, comparator) {
3233 var low = 0;
3234 var high = arr.length;
3235 var mid;
3236 while (low < high) {
3237 mid = (low + high) >>> 1;
3238 if (comparator(arr[mid], item) < 0) {
3239 low = mid + 1;
3240 } else {
3241 high = mid;
3242 }
3243 }
3244 return low;
3245}
3246
3247// assuming the arr is sorted, insert the item in the proper place
3248function insertSorted(arr, item, comparator) {
3249 var idx = binarySearch(arr, item, comparator);
3250 arr.splice(idx, 0, item);
3251}
3252
3253// Turn a path as a flat array into a tree with a single branch.
3254// If any should be stemmed from the beginning of the array, that's passed
3255// in as the second argument
3256function pathToTree(path, numStemmed) {
3257 var root;
3258 var leaf;
3259 for (var i = numStemmed, len = path.length; i < len; i++) {
3260 var node = path[i];
3261 var currentLeaf = [node.id, node.opts, []];
3262 if (leaf) {
3263 leaf[2].push(currentLeaf);
3264 leaf = currentLeaf;
3265 } else {
3266 root = leaf = currentLeaf;
3267 }
3268 }
3269 return root;
3270}
3271
3272// compare the IDs of two trees
3273function compareTree(a, b) {
3274 return a[0] < b[0] ? -1 : 1;
3275}
3276
3277// Merge two trees together
3278// The roots of tree1 and tree2 must be the same revision
3279function mergeTree(in_tree1, in_tree2) {
3280 var queue = [{tree1: in_tree1, tree2: in_tree2}];
3281 var conflicts = false;
3282 while (queue.length > 0) {
3283 var item = queue.pop();
3284 var tree1 = item.tree1;
3285 var tree2 = item.tree2;
3286
3287 if (tree1[1].status || tree2[1].status) {
3288 tree1[1].status =
3289 (tree1[1].status === 'available' ||
3290 tree2[1].status === 'available') ? 'available' : 'missing';
3291 }
3292
3293 for (var i = 0; i < tree2[2].length; i++) {
3294 if (!tree1[2][0]) {
3295 conflicts = 'new_leaf';
3296 tree1[2][0] = tree2[2][i];
3297 continue;
3298 }
3299
3300 var merged = false;
3301 for (var j = 0; j < tree1[2].length; j++) {
3302 if (tree1[2][j][0] === tree2[2][i][0]) {
3303 queue.push({tree1: tree1[2][j], tree2: tree2[2][i]});
3304 merged = true;
3305 }
3306 }
3307 if (!merged) {
3308 conflicts = 'new_branch';
3309 insertSorted(tree1[2], tree2[2][i], compareTree);
3310 }
3311 }
3312 }
3313 return {conflicts: conflicts, tree: in_tree1};
3314}
3315
3316function doMerge(tree, path, dontExpand) {
3317 var restree = [];
3318 var conflicts = false;
3319 var merged = false;
3320 var res;
3321
3322 if (!tree.length) {
3323 return {tree: [path], conflicts: 'new_leaf'};
3324 }
3325
3326 for (var i = 0, len = tree.length; i < len; i++) {
3327 var branch = tree[i];
3328 if (branch.pos === path.pos && branch.ids[0] === path.ids[0]) {
3329 // Paths start at the same position and have the same root, so they need
3330 // merged
3331 res = mergeTree(branch.ids, path.ids);
3332 restree.push({pos: branch.pos, ids: res.tree});
3333 conflicts = conflicts || res.conflicts;
3334 merged = true;
3335 } else if (dontExpand !== true) {
3336 // The paths start at a different position, take the earliest path and
3337 // traverse up until it as at the same point from root as the path we
3338 // want to merge. If the keys match we return the longer path with the
3339 // other merged After stemming we dont want to expand the trees
3340
3341 var t1 = branch.pos < path.pos ? branch : path;
3342 var t2 = branch.pos < path.pos ? path : branch;
3343 var diff = t2.pos - t1.pos;
3344
3345 var candidateParents = [];
3346
3347 var trees = [];
3348 trees.push({ids: t1.ids, diff: diff, parent: null, parentIdx: null});
3349 while (trees.length > 0) {
3350 var item = trees.pop();
3351 if (item.diff === 0) {
3352 if (item.ids[0] === t2.ids[0]) {
3353 candidateParents.push(item);
3354 }
3355 continue;
3356 }
3357 var elements = item.ids[2];
3358 for (var j = 0, elementsLen = elements.length; j < elementsLen; j++) {
3359 trees.push({
3360 ids: elements[j],
3361 diff: item.diff - 1,
3362 parent: item.ids,
3363 parentIdx: j
3364 });
3365 }
3366 }
3367
3368 var el = candidateParents[0];
3369
3370 if (!el) {
3371 restree.push(branch);
3372 } else {
3373 res = mergeTree(el.ids, t2.ids);
3374 el.parent[2][el.parentIdx] = res.tree;
3375 restree.push({pos: t1.pos, ids: t1.ids});
3376 conflicts = conflicts || res.conflicts;
3377 merged = true;
3378 }
3379 } else {
3380 restree.push(branch);
3381 }
3382 }
3383
3384 // We didnt find
3385 if (!merged) {
3386 restree.push(path);
3387 }
3388
3389 restree.sort(sortByPos$1);
3390
3391 return {
3392 tree: restree,
3393 conflicts: conflicts || 'internal_node'
3394 };
3395}
3396
3397// To ensure we dont grow the revision tree infinitely, we stem old revisions
3398function stem(tree, depth) {
3399 // First we break out the tree into a complete list of root to leaf paths
3400 var paths = rootToLeaf(tree);
3401 var stemmedRevs;
3402
3403 var result;
3404 for (var i = 0, len = paths.length; i < len; i++) {
3405 // Then for each path, we cut off the start of the path based on the
3406 // `depth` to stem to, and generate a new set of flat trees
3407 var path = paths[i];
3408 var stemmed = path.ids;
3409 var node;
3410 if (stemmed.length > depth) {
3411 // only do the stemming work if we actually need to stem
3412 if (!stemmedRevs) {
3413 stemmedRevs = {}; // avoid allocating this object unnecessarily
3414 }
3415 var numStemmed = stemmed.length - depth;
3416 node = {
3417 pos: path.pos + numStemmed,
3418 ids: pathToTree(stemmed, numStemmed)
3419 };
3420
3421 for (var s = 0; s < numStemmed; s++) {
3422 var rev = (path.pos + s) + '-' + stemmed[s].id;
3423 stemmedRevs[rev] = true;
3424 }
3425 } else { // no need to actually stem
3426 node = {
3427 pos: path.pos,
3428 ids: pathToTree(stemmed, 0)
3429 };
3430 }
3431
3432 // Then we remerge all those flat trees together, ensuring that we dont
3433 // connect trees that would go beyond the depth limit
3434 if (result) {
3435 result = doMerge(result, node, true).tree;
3436 } else {
3437 result = [node];
3438 }
3439 }
3440
3441 // this is memory-heavy per Chrome profiler, avoid unless we actually stemmed
3442 if (stemmedRevs) {
3443 traverseRevTree(result, function (isLeaf, pos, revHash) {
3444 // some revisions may have been removed in a branch but not in another
3445 delete stemmedRevs[pos + '-' + revHash];
3446 });
3447 }
3448
3449 return {
3450 tree: result,
3451 revs: stemmedRevs ? Object.keys(stemmedRevs) : []
3452 };
3453}
3454
3455function merge(tree, path, depth) {
3456 var newTree = doMerge(tree, path);
3457 var stemmed = stem(newTree.tree, depth);
3458 return {
3459 tree: stemmed.tree,
3460 stemmedRevs: stemmed.revs,
3461 conflicts: newTree.conflicts
3462 };
3463}
3464
3465// return true if a rev exists in the rev tree, false otherwise
3466function revExists(revs, rev) {
3467 var toVisit = revs.slice();
3468 var splitRev = rev.split('-');
3469 var targetPos = parseInt(splitRev[0], 10);
3470 var targetId = splitRev[1];
3471
3472 var node;
3473 while ((node = toVisit.pop())) {
3474 if (node.pos === targetPos && node.ids[0] === targetId) {
3475 return true;
3476 }
3477 var branches = node.ids[2];
3478 for (var i = 0, len = branches.length; i < len; i++) {
3479 toVisit.push({pos: node.pos + 1, ids: branches[i]});
3480 }
3481 }
3482 return false;
3483}
3484
3485function getTrees(node) {
3486 return node.ids;
3487}
3488
3489// check if a specific revision of a doc has been deleted
3490// - metadata: the metadata object from the doc store
3491// - rev: (optional) the revision to check. defaults to winning revision
3492function isDeleted(metadata, rev) {
3493 if (!rev) {
3494 rev = winningRev(metadata);
3495 }
3496 var id = rev.substring(rev.indexOf('-') + 1);
3497 var toVisit = metadata.rev_tree.map(getTrees);
3498
3499 var tree;
3500 while ((tree = toVisit.pop())) {
3501 if (tree[0] === id) {
3502 return !!tree[1].deleted;
3503 }
3504 toVisit = toVisit.concat(tree[2]);
3505 }
3506}
3507
3508function isLocalId(id) {
3509 return (/^_local/).test(id);
3510}
3511
3512// returns the current leaf node for a given revision
3513function latest(rev, metadata) {
3514 var toVisit = metadata.rev_tree.slice();
3515 var node;
3516 while ((node = toVisit.pop())) {
3517 var pos = node.pos;
3518 var tree = node.ids;
3519 var id = tree[0];
3520 var opts = tree[1];
3521 var branches = tree[2];
3522 var isLeaf = branches.length === 0;
3523
3524 var history = node.history ? node.history.slice() : [];
3525 history.push({id: id, pos: pos, opts: opts});
3526
3527 if (isLeaf) {
3528 for (var i = 0, len = history.length; i < len; i++) {
3529 var historyNode = history[i];
3530 var historyRev = historyNode.pos + '-' + historyNode.id;
3531
3532 if (historyRev === rev) {
3533 // return the rev of this leaf
3534 return pos + '-' + id;
3535 }
3536 }
3537 }
3538
3539 for (var j = 0, l = branches.length; j < l; j++) {
3540 toVisit.push({pos: pos + 1, ids: branches[j], history: history});
3541 }
3542 }
3543
3544 /* istanbul ignore next */
3545 throw new Error('Unable to resolve latest revision for id ' + metadata.id + ', rev ' + rev);
3546}
3547
3548inherits(Changes$1, events.EventEmitter);
3549
3550function tryCatchInChangeListener(self, change, pending, lastSeq) {
3551 // isolate try/catches to avoid V8 deoptimizations
3552 try {
3553 self.emit('change', change, pending, lastSeq);
3554 } catch (e) {
3555 guardedConsole('error', 'Error in .on("change", function):', e);
3556 }
3557}
3558
3559function Changes$1(db, opts, callback) {
3560 events.EventEmitter.call(this);
3561 var self = this;
3562 this.db = db;
3563 opts = opts ? clone(opts) : {};
3564 var complete = opts.complete = once(function (err, resp) {
3565 if (err) {
3566 if (listenerCount(self, 'error') > 0) {
3567 self.emit('error', err);
3568 }
3569 } else {
3570 self.emit('complete', resp);
3571 }
3572 self.removeAllListeners();
3573 db.removeListener('destroyed', onDestroy);
3574 });
3575 if (callback) {
3576 self.on('complete', function (resp) {
3577 callback(null, resp);
3578 });
3579 self.on('error', callback);
3580 }
3581 function onDestroy() {
3582 self.cancel();
3583 }
3584 db.once('destroyed', onDestroy);
3585
3586 opts.onChange = function (change, pending, lastSeq) {
3587 /* istanbul ignore if */
3588 if (self.isCancelled) {
3589 return;
3590 }
3591 tryCatchInChangeListener(self, change, pending, lastSeq);
3592 };
3593
3594 var promise = new Promise(function (fulfill, reject) {
3595 opts.complete = function (err, res) {
3596 if (err) {
3597 reject(err);
3598 } else {
3599 fulfill(res);
3600 }
3601 };
3602 });
3603 self.once('cancel', function () {
3604 db.removeListener('destroyed', onDestroy);
3605 opts.complete(null, {status: 'cancelled'});
3606 });
3607 this.then = promise.then.bind(promise);
3608 this['catch'] = promise['catch'].bind(promise);
3609 this.then(function (result) {
3610 complete(null, result);
3611 }, complete);
3612
3613
3614
3615 if (!db.taskqueue.isReady) {
3616 db.taskqueue.addTask(function (failed) {
3617 if (failed) {
3618 opts.complete(failed);
3619 } else if (self.isCancelled) {
3620 self.emit('cancel');
3621 } else {
3622 self.validateChanges(opts);
3623 }
3624 });
3625 } else {
3626 self.validateChanges(opts);
3627 }
3628}
3629Changes$1.prototype.cancel = function () {
3630 this.isCancelled = true;
3631 if (this.db.taskqueue.isReady) {
3632 this.emit('cancel');
3633 }
3634};
3635function processChange(doc, metadata, opts) {
3636 var changeList = [{rev: doc._rev}];
3637 if (opts.style === 'all_docs') {
3638 changeList = collectLeaves(metadata.rev_tree)
3639 .map(function (x) { return {rev: x.rev}; });
3640 }
3641 var change = {
3642 id: metadata.id,
3643 changes: changeList,
3644 doc: doc
3645 };
3646
3647 if (isDeleted(metadata, doc._rev)) {
3648 change.deleted = true;
3649 }
3650 if (opts.conflicts) {
3651 change.doc._conflicts = collectConflicts(metadata);
3652 if (!change.doc._conflicts.length) {
3653 delete change.doc._conflicts;
3654 }
3655 }
3656 return change;
3657}
3658
3659Changes$1.prototype.validateChanges = function (opts) {
3660 var callback = opts.complete;
3661 var self = this;
3662
3663 /* istanbul ignore else */
3664 if (PouchDB._changesFilterPlugin) {
3665 PouchDB._changesFilterPlugin.validate(opts, function (err) {
3666 if (err) {
3667 return callback(err);
3668 }
3669 self.doChanges(opts);
3670 });
3671 } else {
3672 self.doChanges(opts);
3673 }
3674};
3675
3676Changes$1.prototype.doChanges = function (opts) {
3677 var self = this;
3678 var callback = opts.complete;
3679
3680 opts = clone(opts);
3681 if ('live' in opts && !('continuous' in opts)) {
3682 opts.continuous = opts.live;
3683 }
3684 opts.processChange = processChange;
3685
3686 if (opts.since === 'latest') {
3687 opts.since = 'now';
3688 }
3689 if (!opts.since) {
3690 opts.since = 0;
3691 }
3692 if (opts.since === 'now') {
3693 this.db.info().then(function (info) {
3694 /* istanbul ignore if */
3695 if (self.isCancelled) {
3696 callback(null, {status: 'cancelled'});
3697 return;
3698 }
3699 opts.since = info.update_seq;
3700 self.doChanges(opts);
3701 }, callback);
3702 return;
3703 }
3704
3705 /* istanbul ignore else */
3706 if (PouchDB._changesFilterPlugin) {
3707 PouchDB._changesFilterPlugin.normalize(opts);
3708 if (PouchDB._changesFilterPlugin.shouldFilter(this, opts)) {
3709 return PouchDB._changesFilterPlugin.filter(this, opts);
3710 }
3711 } else {
3712 ['doc_ids', 'filter', 'selector', 'view'].forEach(function (key) {
3713 if (key in opts) {
3714 guardedConsole('warn',
3715 'The "' + key + '" option was passed in to changes/replicate, ' +
3716 'but pouchdb-changes-filter plugin is not installed, so it ' +
3717 'was ignored. Please install the plugin to enable filtering.'
3718 );
3719 }
3720 });
3721 }
3722
3723 if (!('descending' in opts)) {
3724 opts.descending = false;
3725 }
3726
3727 // 0 and 1 should return 1 document
3728 opts.limit = opts.limit === 0 ? 1 : opts.limit;
3729 opts.complete = callback;
3730 var newPromise = this.db._changes(opts);
3731 /* istanbul ignore else */
3732 if (newPromise && typeof newPromise.cancel === 'function') {
3733 var cancel = self.cancel;
3734 self.cancel = getArguments(function (args) {
3735 newPromise.cancel();
3736 cancel.apply(this, args);
3737 });
3738 }
3739};
3740
3741/*
3742 * A generic pouch adapter
3743 */
3744
3745function compare(left, right) {
3746 return left < right ? -1 : left > right ? 1 : 0;
3747}
3748
3749// Wrapper for functions that call the bulkdocs api with a single doc,
3750// if the first result is an error, return an error
3751function yankError(callback, docId) {
3752 return function (err, results) {
3753 if (err || (results[0] && results[0].error)) {
3754 err = err || results[0];
3755 err.docId = docId;
3756 callback(err);
3757 } else {
3758 callback(null, results.length ? results[0] : results);
3759 }
3760 };
3761}
3762
3763// clean docs given to us by the user
3764function cleanDocs(docs) {
3765 for (var i = 0; i < docs.length; i++) {
3766 var doc = docs[i];
3767 if (doc._deleted) {
3768 delete doc._attachments; // ignore atts for deleted docs
3769 } else if (doc._attachments) {
3770 // filter out extraneous keys from _attachments
3771 var atts = Object.keys(doc._attachments);
3772 for (var j = 0; j < atts.length; j++) {
3773 var att = atts[j];
3774 doc._attachments[att] = pick(doc._attachments[att],
3775 ['data', 'digest', 'content_type', 'length', 'revpos', 'stub']);
3776 }
3777 }
3778 }
3779}
3780
3781// compare two docs, first by _id then by _rev
3782function compareByIdThenRev(a, b) {
3783 var idCompare = compare(a._id, b._id);
3784 if (idCompare !== 0) {
3785 return idCompare;
3786 }
3787 var aStart = a._revisions ? a._revisions.start : 0;
3788 var bStart = b._revisions ? b._revisions.start : 0;
3789 return compare(aStart, bStart);
3790}
3791
3792// for every node in a revision tree computes its distance from the closest
3793// leaf
3794function computeHeight(revs) {
3795 var height = {};
3796 var edges = [];
3797 traverseRevTree(revs, function (isLeaf, pos, id, prnt) {
3798 var rev$$1 = pos + "-" + id;
3799 if (isLeaf) {
3800 height[rev$$1] = 0;
3801 }
3802 if (prnt !== undefined) {
3803 edges.push({from: prnt, to: rev$$1});
3804 }
3805 return rev$$1;
3806 });
3807
3808 edges.reverse();
3809 edges.forEach(function (edge) {
3810 if (height[edge.from] === undefined) {
3811 height[edge.from] = 1 + height[edge.to];
3812 } else {
3813 height[edge.from] = Math.min(height[edge.from], 1 + height[edge.to]);
3814 }
3815 });
3816 return height;
3817}
3818
3819function allDocsKeysParse(opts) {
3820 var keys = ('limit' in opts) ?
3821 opts.keys.slice(opts.skip, opts.limit + opts.skip) :
3822 (opts.skip > 0) ? opts.keys.slice(opts.skip) : opts.keys;
3823 opts.keys = keys;
3824 opts.skip = 0;
3825 delete opts.limit;
3826 if (opts.descending) {
3827 keys.reverse();
3828 opts.descending = false;
3829 }
3830}
3831
3832// all compaction is done in a queue, to avoid attaching
3833// too many listeners at once
3834function doNextCompaction(self) {
3835 var task = self._compactionQueue[0];
3836 var opts = task.opts;
3837 var callback = task.callback;
3838 self.get('_local/compaction')["catch"](function () {
3839 return false;
3840 }).then(function (doc) {
3841 if (doc && doc.last_seq) {
3842 opts.last_seq = doc.last_seq;
3843 }
3844 self._compact(opts, function (err, res) {
3845 /* istanbul ignore if */
3846 if (err) {
3847 callback(err);
3848 } else {
3849 callback(null, res);
3850 }
3851 immediate(function () {
3852 self._compactionQueue.shift();
3853 if (self._compactionQueue.length) {
3854 doNextCompaction(self);
3855 }
3856 });
3857 });
3858 });
3859}
3860
3861function attachmentNameError(name) {
3862 if (name.charAt(0) === '_') {
3863 return name + ' is not a valid attachment name, attachment ' +
3864 'names cannot start with \'_\'';
3865 }
3866 return false;
3867}
3868
3869inherits(AbstractPouchDB, events.EventEmitter);
3870
3871function AbstractPouchDB() {
3872 events.EventEmitter.call(this);
3873
3874 // re-bind prototyped methods
3875 for (var p in AbstractPouchDB.prototype) {
3876 if (typeof this[p] === 'function') {
3877 this[p] = this[p].bind(this);
3878 }
3879 }
3880}
3881
3882AbstractPouchDB.prototype.post =
3883 adapterFun('post', function (doc, opts, callback) {
3884 if (typeof opts === 'function') {
3885 callback = opts;
3886 opts = {};
3887 }
3888 if (typeof doc !== 'object' || Array.isArray(doc)) {
3889 return callback(createError(NOT_AN_OBJECT));
3890 }
3891 this.bulkDocs({docs: [doc]}, opts, yankError(callback, doc._id));
3892});
3893
3894AbstractPouchDB.prototype.put = adapterFun('put', function (doc, opts, cb) {
3895 if (typeof opts === 'function') {
3896 cb = opts;
3897 opts = {};
3898 }
3899 if (typeof doc !== 'object' || Array.isArray(doc)) {
3900 return cb(createError(NOT_AN_OBJECT));
3901 }
3902 invalidIdError(doc._id);
3903 if (isLocalId(doc._id) && typeof this._putLocal === 'function') {
3904 if (doc._deleted) {
3905 return this._removeLocal(doc, cb);
3906 } else {
3907 return this._putLocal(doc, cb);
3908 }
3909 }
3910 var self = this;
3911 if (opts.force && doc._rev) {
3912 transformForceOptionToNewEditsOption();
3913 putDoc(function (err) {
3914 var result = err ? null : {ok: true, id: doc._id, rev: doc._rev};
3915 cb(err, result);
3916 });
3917 } else {
3918 putDoc(cb);
3919 }
3920
3921 function transformForceOptionToNewEditsOption() {
3922 var parts = doc._rev.split('-');
3923 var oldRevId = parts[1];
3924 var oldRevNum = parseInt(parts[0], 10);
3925
3926 var newRevNum = oldRevNum + 1;
3927 var newRevId = rev();
3928
3929 doc._revisions = {
3930 start: newRevNum,
3931 ids: [newRevId, oldRevId]
3932 };
3933 doc._rev = newRevNum + '-' + newRevId;
3934 opts.new_edits = false;
3935 }
3936 function putDoc(next) {
3937 if (typeof self._put === 'function' && opts.new_edits !== false) {
3938 self._put(doc, opts, next);
3939 } else {
3940 self.bulkDocs({docs: [doc]}, opts, yankError(next, doc._id));
3941 }
3942 }
3943});
3944
3945AbstractPouchDB.prototype.putAttachment =
3946 adapterFun('putAttachment', function (docId, attachmentId, rev$$1,
3947 blob, type) {
3948 var api = this;
3949 if (typeof type === 'function') {
3950 type = blob;
3951 blob = rev$$1;
3952 rev$$1 = null;
3953 }
3954 // Lets fix in https://github.com/pouchdb/pouchdb/issues/3267
3955 /* istanbul ignore if */
3956 if (typeof type === 'undefined') {
3957 type = blob;
3958 blob = rev$$1;
3959 rev$$1 = null;
3960 }
3961 if (!type) {
3962 guardedConsole('warn', 'Attachment', attachmentId, 'on document', docId, 'is missing content_type');
3963 }
3964
3965 function createAttachment(doc) {
3966 var prevrevpos = '_rev' in doc ? parseInt(doc._rev, 10) : 0;
3967 doc._attachments = doc._attachments || {};
3968 doc._attachments[attachmentId] = {
3969 content_type: type,
3970 data: blob,
3971 revpos: ++prevrevpos
3972 };
3973 return api.put(doc);
3974 }
3975
3976 return api.get(docId).then(function (doc) {
3977 if (doc._rev !== rev$$1) {
3978 throw createError(REV_CONFLICT);
3979 }
3980
3981 return createAttachment(doc);
3982 }, function (err) {
3983 // create new doc
3984 /* istanbul ignore else */
3985 if (err.reason === MISSING_DOC.message) {
3986 return createAttachment({_id: docId});
3987 } else {
3988 throw err;
3989 }
3990 });
3991});
3992
3993AbstractPouchDB.prototype.removeAttachment =
3994 adapterFun('removeAttachment', function (docId, attachmentId, rev$$1,
3995 callback) {
3996 var self = this;
3997 self.get(docId, function (err, obj) {
3998 /* istanbul ignore if */
3999 if (err) {
4000 callback(err);
4001 return;
4002 }
4003 if (obj._rev !== rev$$1) {
4004 callback(createError(REV_CONFLICT));
4005 return;
4006 }
4007 /* istanbul ignore if */
4008 if (!obj._attachments) {
4009 return callback();
4010 }
4011 delete obj._attachments[attachmentId];
4012 if (Object.keys(obj._attachments).length === 0) {
4013 delete obj._attachments;
4014 }
4015 self.put(obj, callback);
4016 });
4017});
4018
4019AbstractPouchDB.prototype.remove =
4020 adapterFun('remove', function (docOrId, optsOrRev, opts, callback) {
4021 var doc;
4022 if (typeof optsOrRev === 'string') {
4023 // id, rev, opts, callback style
4024 doc = {
4025 _id: docOrId,
4026 _rev: optsOrRev
4027 };
4028 if (typeof opts === 'function') {
4029 callback = opts;
4030 opts = {};
4031 }
4032 } else {
4033 // doc, opts, callback style
4034 doc = docOrId;
4035 if (typeof optsOrRev === 'function') {
4036 callback = optsOrRev;
4037 opts = {};
4038 } else {
4039 callback = opts;
4040 opts = optsOrRev;
4041 }
4042 }
4043 opts = opts || {};
4044 opts.was_delete = true;
4045 var newDoc = {_id: doc._id, _rev: (doc._rev || opts.rev)};
4046 newDoc._deleted = true;
4047 if (isLocalId(newDoc._id) && typeof this._removeLocal === 'function') {
4048 return this._removeLocal(doc, callback);
4049 }
4050 this.bulkDocs({docs: [newDoc]}, opts, yankError(callback, newDoc._id));
4051});
4052
4053AbstractPouchDB.prototype.revsDiff =
4054 adapterFun('revsDiff', function (req, opts, callback) {
4055 if (typeof opts === 'function') {
4056 callback = opts;
4057 opts = {};
4058 }
4059 var ids = Object.keys(req);
4060
4061 if (!ids.length) {
4062 return callback(null, {});
4063 }
4064
4065 var count = 0;
4066 var missing = new ExportedMap();
4067
4068 function addToMissing(id, revId) {
4069 if (!missing.has(id)) {
4070 missing.set(id, {missing: []});
4071 }
4072 missing.get(id).missing.push(revId);
4073 }
4074
4075 function processDoc(id, rev_tree) {
4076 // Is this fast enough? Maybe we should switch to a set simulated by a map
4077 var missingForId = req[id].slice(0);
4078 traverseRevTree(rev_tree, function (isLeaf, pos, revHash, ctx,
4079 opts) {
4080 var rev$$1 = pos + '-' + revHash;
4081 var idx = missingForId.indexOf(rev$$1);
4082 if (idx === -1) {
4083 return;
4084 }
4085
4086 missingForId.splice(idx, 1);
4087 /* istanbul ignore if */
4088 if (opts.status !== 'available') {
4089 addToMissing(id, rev$$1);
4090 }
4091 });
4092
4093 // Traversing the tree is synchronous, so now `missingForId` contains
4094 // revisions that were not found in the tree
4095 missingForId.forEach(function (rev$$1) {
4096 addToMissing(id, rev$$1);
4097 });
4098 }
4099
4100 ids.map(function (id) {
4101 this._getRevisionTree(id, function (err, rev_tree) {
4102 if (err && err.status === 404 && err.message === 'missing') {
4103 missing.set(id, {missing: req[id]});
4104 } else if (err) {
4105 /* istanbul ignore next */
4106 return callback(err);
4107 } else {
4108 processDoc(id, rev_tree);
4109 }
4110
4111 if (++count === ids.length) {
4112 // convert LazyMap to object
4113 var missingObj = {};
4114 missing.forEach(function (value, key) {
4115 missingObj[key] = value;
4116 });
4117 return callback(null, missingObj);
4118 }
4119 });
4120 }, this);
4121});
4122
4123// _bulk_get API for faster replication, as described in
4124// https://github.com/apache/couchdb-chttpd/pull/33
4125// At the "abstract" level, it will just run multiple get()s in
4126// parallel, because this isn't much of a performance cost
4127// for local databases (except the cost of multiple transactions, which is
4128// small). The http adapter overrides this in order
4129// to do a more efficient single HTTP request.
4130AbstractPouchDB.prototype.bulkGet =
4131 adapterFun('bulkGet', function (opts, callback) {
4132 bulkGet(this, opts, callback);
4133});
4134
4135// compact one document and fire callback
4136// by compacting we mean removing all revisions which
4137// are further from the leaf in revision tree than max_height
4138AbstractPouchDB.prototype.compactDocument =
4139 adapterFun('compactDocument', function (docId, maxHeight, callback) {
4140 var self = this;
4141 this._getRevisionTree(docId, function (err, revTree) {
4142 /* istanbul ignore if */
4143 if (err) {
4144 return callback(err);
4145 }
4146 var height = computeHeight(revTree);
4147 var candidates = [];
4148 var revs = [];
4149 Object.keys(height).forEach(function (rev$$1) {
4150 if (height[rev$$1] > maxHeight) {
4151 candidates.push(rev$$1);
4152 }
4153 });
4154
4155 traverseRevTree(revTree, function (isLeaf, pos, revHash, ctx, opts) {
4156 var rev$$1 = pos + '-' + revHash;
4157 if (opts.status === 'available' && candidates.indexOf(rev$$1) !== -1) {
4158 revs.push(rev$$1);
4159 }
4160 });
4161 self._doCompaction(docId, revs, callback);
4162 });
4163});
4164
4165// compact the whole database using single document
4166// compaction
4167AbstractPouchDB.prototype.compact =
4168 adapterFun('compact', function (opts, callback) {
4169 if (typeof opts === 'function') {
4170 callback = opts;
4171 opts = {};
4172 }
4173
4174 var self = this;
4175 opts = opts || {};
4176
4177 self._compactionQueue = self._compactionQueue || [];
4178 self._compactionQueue.push({opts: opts, callback: callback});
4179 if (self._compactionQueue.length === 1) {
4180 doNextCompaction(self);
4181 }
4182});
4183AbstractPouchDB.prototype._compact = function (opts, callback) {
4184 var self = this;
4185 var changesOpts = {
4186 return_docs: false,
4187 last_seq: opts.last_seq || 0
4188 };
4189 var promises = [];
4190
4191 function onChange(row) {
4192 promises.push(self.compactDocument(row.id, 0));
4193 }
4194 function onComplete(resp) {
4195 var lastSeq = resp.last_seq;
4196 Promise.all(promises).then(function () {
4197 return upsert(self, '_local/compaction', function deltaFunc(doc) {
4198 if (!doc.last_seq || doc.last_seq < lastSeq) {
4199 doc.last_seq = lastSeq;
4200 return doc;
4201 }
4202 return false; // somebody else got here first, don't update
4203 });
4204 }).then(function () {
4205 callback(null, {ok: true});
4206 })["catch"](callback);
4207 }
4208 self.changes(changesOpts)
4209 .on('change', onChange)
4210 .on('complete', onComplete)
4211 .on('error', callback);
4212};
4213
4214/* Begin api wrappers. Specific functionality to storage belongs in the
4215 _[method] */
4216AbstractPouchDB.prototype.get = adapterFun('get', function (id, opts, cb) {
4217 if (typeof opts === 'function') {
4218 cb = opts;
4219 opts = {};
4220 }
4221 if (typeof id !== 'string') {
4222 return cb(createError(INVALID_ID));
4223 }
4224 if (isLocalId(id) && typeof this._getLocal === 'function') {
4225 return this._getLocal(id, cb);
4226 }
4227 var leaves = [], self = this;
4228
4229 function finishOpenRevs() {
4230 var result = [];
4231 var count = leaves.length;
4232 /* istanbul ignore if */
4233 if (!count) {
4234 return cb(null, result);
4235 }
4236
4237 // order with open_revs is unspecified
4238 leaves.forEach(function (leaf) {
4239 self.get(id, {
4240 rev: leaf,
4241 revs: opts.revs,
4242 latest: opts.latest,
4243 attachments: opts.attachments,
4244 binary: opts.binary
4245 }, function (err, doc) {
4246 if (!err) {
4247 // using latest=true can produce duplicates
4248 var existing;
4249 for (var i = 0, l = result.length; i < l; i++) {
4250 if (result[i].ok && result[i].ok._rev === doc._rev) {
4251 existing = true;
4252 break;
4253 }
4254 }
4255 if (!existing) {
4256 result.push({ok: doc});
4257 }
4258 } else {
4259 result.push({missing: leaf});
4260 }
4261 count--;
4262 if (!count) {
4263 cb(null, result);
4264 }
4265 });
4266 });
4267 }
4268
4269 if (opts.open_revs) {
4270 if (opts.open_revs === "all") {
4271 this._getRevisionTree(id, function (err, rev_tree) {
4272 /* istanbul ignore if */
4273 if (err) {
4274 return cb(err);
4275 }
4276 leaves = collectLeaves(rev_tree).map(function (leaf) {
4277 return leaf.rev;
4278 });
4279 finishOpenRevs();
4280 });
4281 } else {
4282 if (Array.isArray(opts.open_revs)) {
4283 leaves = opts.open_revs;
4284 for (var i = 0; i < leaves.length; i++) {
4285 var l = leaves[i];
4286 // looks like it's the only thing couchdb checks
4287 if (!(typeof (l) === "string" && /^\d+-/.test(l))) {
4288 return cb(createError(INVALID_REV));
4289 }
4290 }
4291 finishOpenRevs();
4292 } else {
4293 return cb(createError(UNKNOWN_ERROR, 'function_clause'));
4294 }
4295 }
4296 return; // open_revs does not like other options
4297 }
4298
4299 return this._get(id, opts, function (err, result) {
4300 if (err) {
4301 err.docId = id;
4302 return cb(err);
4303 }
4304
4305 var doc = result.doc;
4306 var metadata = result.metadata;
4307 var ctx = result.ctx;
4308
4309 if (opts.conflicts) {
4310 var conflicts = collectConflicts(metadata);
4311 if (conflicts.length) {
4312 doc._conflicts = conflicts;
4313 }
4314 }
4315
4316 if (isDeleted(metadata, doc._rev)) {
4317 doc._deleted = true;
4318 }
4319
4320 if (opts.revs || opts.revs_info) {
4321 var splittedRev = doc._rev.split('-');
4322 var revNo = parseInt(splittedRev[0], 10);
4323 var revHash = splittedRev[1];
4324
4325 var paths = rootToLeaf(metadata.rev_tree);
4326 var path = null;
4327
4328 for (var i = 0; i < paths.length; i++) {
4329 var currentPath = paths[i];
4330 var hashIndex = currentPath.ids.map(function (x) { return x.id; })
4331 .indexOf(revHash);
4332 var hashFoundAtRevPos = hashIndex === (revNo - 1);
4333
4334 if (hashFoundAtRevPos || (!path && hashIndex !== -1)) {
4335 path = currentPath;
4336 }
4337 }
4338
4339 /* istanbul ignore if */
4340 if (!path) {
4341 err = new Error('invalid rev tree');
4342 err.docId = id;
4343 return cb(err);
4344 }
4345
4346 var indexOfRev = path.ids.map(function (x) { return x.id; })
4347 .indexOf(doc._rev.split('-')[1]) + 1;
4348 var howMany = path.ids.length - indexOfRev;
4349 path.ids.splice(indexOfRev, howMany);
4350 path.ids.reverse();
4351
4352 if (opts.revs) {
4353 doc._revisions = {
4354 start: (path.pos + path.ids.length) - 1,
4355 ids: path.ids.map(function (rev$$1) {
4356 return rev$$1.id;
4357 })
4358 };
4359 }
4360 if (opts.revs_info) {
4361 var pos = path.pos + path.ids.length;
4362 doc._revs_info = path.ids.map(function (rev$$1) {
4363 pos--;
4364 return {
4365 rev: pos + '-' + rev$$1.id,
4366 status: rev$$1.opts.status
4367 };
4368 });
4369 }
4370 }
4371
4372 if (opts.attachments && doc._attachments) {
4373 var attachments = doc._attachments;
4374 var count = Object.keys(attachments).length;
4375 if (count === 0) {
4376 return cb(null, doc);
4377 }
4378 Object.keys(attachments).forEach(function (key) {
4379 this._getAttachment(doc._id, key, attachments[key], {
4380 // Previously the revision handling was done in adapter.js
4381 // getAttachment, however since idb-next doesnt we need to
4382 // pass the rev through
4383 rev: doc._rev,
4384 binary: opts.binary,
4385 ctx: ctx
4386 }, function (err, data) {
4387 var att = doc._attachments[key];
4388 att.data = data;
4389 delete att.stub;
4390 delete att.length;
4391 if (!--count) {
4392 cb(null, doc);
4393 }
4394 });
4395 }, self);
4396 } else {
4397 if (doc._attachments) {
4398 for (var key in doc._attachments) {
4399 /* istanbul ignore else */
4400 if (doc._attachments.hasOwnProperty(key)) {
4401 doc._attachments[key].stub = true;
4402 }
4403 }
4404 }
4405 cb(null, doc);
4406 }
4407 });
4408});
4409
4410// TODO: I dont like this, it forces an extra read for every
4411// attachment read and enforces a confusing api between
4412// adapter.js and the adapter implementation
4413AbstractPouchDB.prototype.getAttachment =
4414 adapterFun('getAttachment', function (docId, attachmentId, opts, callback) {
4415 var self = this;
4416 if (opts instanceof Function) {
4417 callback = opts;
4418 opts = {};
4419 }
4420 this._get(docId, opts, function (err, res) {
4421 if (err) {
4422 return callback(err);
4423 }
4424 if (res.doc._attachments && res.doc._attachments[attachmentId]) {
4425 opts.ctx = res.ctx;
4426 opts.binary = true;
4427 self._getAttachment(docId, attachmentId,
4428 res.doc._attachments[attachmentId], opts, callback);
4429 } else {
4430 return callback(createError(MISSING_DOC));
4431 }
4432 });
4433});
4434
4435AbstractPouchDB.prototype.allDocs =
4436 adapterFun('allDocs', function (opts, callback) {
4437 if (typeof opts === 'function') {
4438 callback = opts;
4439 opts = {};
4440 }
4441 opts.skip = typeof opts.skip !== 'undefined' ? opts.skip : 0;
4442 if (opts.start_key) {
4443 opts.startkey = opts.start_key;
4444 }
4445 if (opts.end_key) {
4446 opts.endkey = opts.end_key;
4447 }
4448 if ('keys' in opts) {
4449 if (!Array.isArray(opts.keys)) {
4450 return callback(new TypeError('options.keys must be an array'));
4451 }
4452 var incompatibleOpt =
4453 ['startkey', 'endkey', 'key'].filter(function (incompatibleOpt) {
4454 return incompatibleOpt in opts;
4455 })[0];
4456 if (incompatibleOpt) {
4457 callback(createError(QUERY_PARSE_ERROR,
4458 'Query parameter `' + incompatibleOpt +
4459 '` is not compatible with multi-get'
4460 ));
4461 return;
4462 }
4463 if (!isRemote(this)) {
4464 allDocsKeysParse(opts);
4465 if (opts.keys.length === 0) {
4466 return this._allDocs({limit: 0}, callback);
4467 }
4468 }
4469 }
4470
4471 return this._allDocs(opts, callback);
4472});
4473
4474AbstractPouchDB.prototype.changes = function (opts, callback) {
4475 if (typeof opts === 'function') {
4476 callback = opts;
4477 opts = {};
4478 }
4479
4480 opts = opts || {};
4481
4482 // By default set return_docs to false if the caller has opts.live = true,
4483 // this will prevent us from collecting the set of changes indefinitely
4484 // resulting in growing memory
4485 opts.return_docs = ('return_docs' in opts) ? opts.return_docs : !opts.live;
4486
4487 return new Changes$1(this, opts, callback);
4488};
4489
4490AbstractPouchDB.prototype.close = adapterFun('close', function (callback) {
4491 this._closed = true;
4492 this.emit('closed');
4493 return this._close(callback);
4494});
4495
4496AbstractPouchDB.prototype.info = adapterFun('info', function (callback) {
4497 var self = this;
4498 this._info(function (err, info) {
4499 if (err) {
4500 return callback(err);
4501 }
4502 // assume we know better than the adapter, unless it informs us
4503 info.db_name = info.db_name || self.name;
4504 info.auto_compaction = !!(self.auto_compaction && !isRemote(self));
4505 info.adapter = self.adapter;
4506 callback(null, info);
4507 });
4508});
4509
4510AbstractPouchDB.prototype.id = adapterFun('id', function (callback) {
4511 return this._id(callback);
4512});
4513
4514/* istanbul ignore next */
4515AbstractPouchDB.prototype.type = function () {
4516 return (typeof this._type === 'function') ? this._type() : this.adapter;
4517};
4518
4519AbstractPouchDB.prototype.bulkDocs =
4520 adapterFun('bulkDocs', function (req, opts, callback) {
4521 if (typeof opts === 'function') {
4522 callback = opts;
4523 opts = {};
4524 }
4525
4526 opts = opts || {};
4527
4528 if (Array.isArray(req)) {
4529 req = {
4530 docs: req
4531 };
4532 }
4533
4534 if (!req || !req.docs || !Array.isArray(req.docs)) {
4535 return callback(createError(MISSING_BULK_DOCS));
4536 }
4537
4538 for (var i = 0; i < req.docs.length; ++i) {
4539 if (typeof req.docs[i] !== 'object' || Array.isArray(req.docs[i])) {
4540 return callback(createError(NOT_AN_OBJECT));
4541 }
4542 }
4543
4544 var attachmentError;
4545 req.docs.forEach(function (doc) {
4546 if (doc._attachments) {
4547 Object.keys(doc._attachments).forEach(function (name) {
4548 attachmentError = attachmentError || attachmentNameError(name);
4549 if (!doc._attachments[name].content_type) {
4550 guardedConsole('warn', 'Attachment', name, 'on document', doc._id, 'is missing content_type');
4551 }
4552 });
4553 }
4554 });
4555
4556 if (attachmentError) {
4557 return callback(createError(BAD_REQUEST, attachmentError));
4558 }
4559
4560 if (!('new_edits' in opts)) {
4561 if ('new_edits' in req) {
4562 opts.new_edits = req.new_edits;
4563 } else {
4564 opts.new_edits = true;
4565 }
4566 }
4567
4568 var adapter = this;
4569 if (!opts.new_edits && !isRemote(adapter)) {
4570 // ensure revisions of the same doc are sorted, so that
4571 // the local adapter processes them correctly (#2935)
4572 req.docs.sort(compareByIdThenRev);
4573 }
4574
4575 cleanDocs(req.docs);
4576
4577 // in the case of conflicts, we want to return the _ids to the user
4578 // however, the underlying adapter may destroy the docs array, so
4579 // create a copy here
4580 var ids = req.docs.map(function (doc) {
4581 return doc._id;
4582 });
4583
4584 return this._bulkDocs(req, opts, function (err, res) {
4585 if (err) {
4586 return callback(err);
4587 }
4588 if (!opts.new_edits) {
4589 // this is what couch does when new_edits is false
4590 res = res.filter(function (x) {
4591 return x.error;
4592 });
4593 }
4594 // add ids for error/conflict responses (not required for CouchDB)
4595 if (!isRemote(adapter)) {
4596 for (var i = 0, l = res.length; i < l; i++) {
4597 res[i].id = res[i].id || ids[i];
4598 }
4599 }
4600
4601 callback(null, res);
4602 });
4603});
4604
4605AbstractPouchDB.prototype.registerDependentDatabase =
4606 adapterFun('registerDependentDatabase', function (dependentDb,
4607 callback) {
4608 var depDB = new this.constructor(dependentDb, this.__opts);
4609
4610 function diffFun(doc) {
4611 doc.dependentDbs = doc.dependentDbs || {};
4612 if (doc.dependentDbs[dependentDb]) {
4613 return false; // no update required
4614 }
4615 doc.dependentDbs[dependentDb] = true;
4616 return doc;
4617 }
4618 upsert(this, '_local/_pouch_dependentDbs', diffFun)
4619 .then(function () {
4620 callback(null, {db: depDB});
4621 })["catch"](callback);
4622});
4623
4624AbstractPouchDB.prototype.destroy =
4625 adapterFun('destroy', function (opts, callback) {
4626
4627 if (typeof opts === 'function') {
4628 callback = opts;
4629 opts = {};
4630 }
4631
4632 var self = this;
4633 var usePrefix = 'use_prefix' in self ? self.use_prefix : true;
4634
4635 function destroyDb() {
4636 // call destroy method of the particular adaptor
4637 self._destroy(opts, function (err, resp) {
4638 if (err) {
4639 return callback(err);
4640 }
4641 self._destroyed = true;
4642 self.emit('destroyed');
4643 callback(null, resp || { 'ok': true });
4644 });
4645 }
4646
4647 if (isRemote(self)) {
4648 // no need to check for dependent DBs if it's a remote DB
4649 return destroyDb();
4650 }
4651
4652 self.get('_local/_pouch_dependentDbs', function (err, localDoc) {
4653 if (err) {
4654 /* istanbul ignore if */
4655 if (err.status !== 404) {
4656 return callback(err);
4657 } else { // no dependencies
4658 return destroyDb();
4659 }
4660 }
4661 var dependentDbs = localDoc.dependentDbs;
4662 var PouchDB = self.constructor;
4663 var deletedMap = Object.keys(dependentDbs).map(function (name) {
4664 // use_prefix is only false in the browser
4665 /* istanbul ignore next */
4666 var trueName = usePrefix ?
4667 name.replace(new RegExp('^' + PouchDB.prefix), '') : name;
4668 return new PouchDB(trueName, self.__opts).destroy();
4669 });
4670 Promise.all(deletedMap).then(destroyDb, callback);
4671 });
4672});
4673
4674function TaskQueue() {
4675 this.isReady = false;
4676 this.failed = false;
4677 this.queue = [];
4678}
4679
4680TaskQueue.prototype.execute = function () {
4681 var fun;
4682 if (this.failed) {
4683 while ((fun = this.queue.shift())) {
4684 fun(this.failed);
4685 }
4686 } else {
4687 while ((fun = this.queue.shift())) {
4688 fun();
4689 }
4690 }
4691};
4692
4693TaskQueue.prototype.fail = function (err) {
4694 this.failed = err;
4695 this.execute();
4696};
4697
4698TaskQueue.prototype.ready = function (db) {
4699 this.isReady = true;
4700 this.db = db;
4701 this.execute();
4702};
4703
4704TaskQueue.prototype.addTask = function (fun) {
4705 this.queue.push(fun);
4706 if (this.failed) {
4707 this.execute();
4708 }
4709};
4710
4711function parseAdapter(name, opts) {
4712 var match = name.match(/([a-z-]*):\/\/(.*)/);
4713 if (match) {
4714 // the http adapter expects the fully qualified name
4715 return {
4716 name: /https?/.test(match[1]) ? match[1] + '://' + match[2] : match[2],
4717 adapter: match[1]
4718 };
4719 }
4720
4721 var adapters = PouchDB.adapters;
4722 var preferredAdapters = PouchDB.preferredAdapters;
4723 var prefix = PouchDB.prefix;
4724 var adapterName = opts.adapter;
4725
4726 if (!adapterName) { // automatically determine adapter
4727 for (var i = 0; i < preferredAdapters.length; ++i) {
4728 adapterName = preferredAdapters[i];
4729 // check for browsers that have been upgraded from websql-only to websql+idb
4730 /* istanbul ignore if */
4731 if (adapterName === 'idb' && 'websql' in adapters &&
4732 hasLocalStorage() && localStorage['_pouch__websqldb_' + prefix + name]) {
4733 // log it, because this can be confusing during development
4734 guardedConsole('log', 'PouchDB is downgrading "' + name + '" to WebSQL to' +
4735 ' avoid data loss, because it was already opened with WebSQL.');
4736 continue; // keep using websql to avoid user data loss
4737 }
4738 break;
4739 }
4740 }
4741
4742 var adapter = adapters[adapterName];
4743
4744 // if adapter is invalid, then an error will be thrown later
4745 var usePrefix = (adapter && 'use_prefix' in adapter) ?
4746 adapter.use_prefix : true;
4747
4748 return {
4749 name: usePrefix ? (prefix + name) : name,
4750 adapter: adapterName
4751 };
4752}
4753
4754// OK, so here's the deal. Consider this code:
4755// var db1 = new PouchDB('foo');
4756// var db2 = new PouchDB('foo');
4757// db1.destroy();
4758// ^ these two both need to emit 'destroyed' events,
4759// as well as the PouchDB constructor itself.
4760// So we have one db object (whichever one got destroy() called on it)
4761// responsible for emitting the initial event, which then gets emitted
4762// by the constructor, which then broadcasts it to any other dbs
4763// that may have been created with the same name.
4764function prepareForDestruction(self) {
4765
4766 function onDestroyed(from_constructor) {
4767 self.removeListener('closed', onClosed);
4768 if (!from_constructor) {
4769 self.constructor.emit('destroyed', self.name);
4770 }
4771 }
4772
4773 function onClosed() {
4774 self.removeListener('destroyed', onDestroyed);
4775 self.constructor.emit('unref', self);
4776 }
4777
4778 self.once('destroyed', onDestroyed);
4779 self.once('closed', onClosed);
4780 self.constructor.emit('ref', self);
4781}
4782
4783inherits(PouchDB, AbstractPouchDB);
4784function PouchDB(name, opts) {
4785 // In Node our test suite only tests this for PouchAlt unfortunately
4786 /* istanbul ignore if */
4787 if (!(this instanceof PouchDB)) {
4788 return new PouchDB(name, opts);
4789 }
4790
4791 var self = this;
4792 opts = opts || {};
4793
4794 if (name && typeof name === 'object') {
4795 opts = name;
4796 name = opts.name;
4797 delete opts.name;
4798 }
4799
4800 if (opts.deterministic_revs === undefined) {
4801 opts.deterministic_revs = true;
4802 }
4803
4804 this.__opts = opts = clone(opts);
4805
4806 self.auto_compaction = opts.auto_compaction;
4807 self.prefix = PouchDB.prefix;
4808
4809 if (typeof name !== 'string') {
4810 throw new Error('Missing/invalid DB name');
4811 }
4812
4813 var prefixedName = (opts.prefix || '') + name;
4814 var backend = parseAdapter(prefixedName, opts);
4815
4816 opts.name = backend.name;
4817 opts.adapter = opts.adapter || backend.adapter;
4818
4819 self.name = name;
4820 self._adapter = opts.adapter;
4821 PouchDB.emit('debug', ['adapter', 'Picked adapter: ', opts.adapter]);
4822
4823 if (!PouchDB.adapters[opts.adapter] ||
4824 !PouchDB.adapters[opts.adapter].valid()) {
4825 throw new Error('Invalid Adapter: ' + opts.adapter);
4826 }
4827
4828 AbstractPouchDB.call(self);
4829 self.taskqueue = new TaskQueue();
4830
4831 self.adapter = opts.adapter;
4832
4833 PouchDB.adapters[opts.adapter].call(self, opts, function (err) {
4834 if (err) {
4835 return self.taskqueue.fail(err);
4836 }
4837 prepareForDestruction(self);
4838
4839 self.emit('created', self);
4840 PouchDB.emit('created', self.name);
4841 self.taskqueue.ready(self);
4842 });
4843
4844}
4845
4846// AbortController was introduced quite a while after fetch and
4847// isnt required for PouchDB to function so polyfill if needed
4848var a = (typeof AbortController !== 'undefined')
4849 ? AbortController
4850 : function () { return {abort: function () {}}; };
4851
4852var f$1 = fetch;
4853var h = Headers;
4854
4855PouchDB.adapters = {};
4856PouchDB.preferredAdapters = [];
4857
4858PouchDB.prefix = '_pouch_';
4859
4860var eventEmitter = new events.EventEmitter();
4861
4862function setUpEventEmitter(Pouch) {
4863 Object.keys(events.EventEmitter.prototype).forEach(function (key) {
4864 if (typeof events.EventEmitter.prototype[key] === 'function') {
4865 Pouch[key] = eventEmitter[key].bind(eventEmitter);
4866 }
4867 });
4868
4869 // these are created in constructor.js, and allow us to notify each DB with
4870 // the same name that it was destroyed, via the constructor object
4871 var destructListeners = Pouch._destructionListeners = new ExportedMap();
4872
4873 Pouch.on('ref', function onConstructorRef(db) {
4874 if (!destructListeners.has(db.name)) {
4875 destructListeners.set(db.name, []);
4876 }
4877 destructListeners.get(db.name).push(db);
4878 });
4879
4880 Pouch.on('unref', function onConstructorUnref(db) {
4881 if (!destructListeners.has(db.name)) {
4882 return;
4883 }
4884 var dbList = destructListeners.get(db.name);
4885 var pos = dbList.indexOf(db);
4886 if (pos < 0) {
4887 /* istanbul ignore next */
4888 return;
4889 }
4890 dbList.splice(pos, 1);
4891 if (dbList.length > 1) {
4892 /* istanbul ignore next */
4893 destructListeners.set(db.name, dbList);
4894 } else {
4895 destructListeners["delete"](db.name);
4896 }
4897 });
4898
4899 Pouch.on('destroyed', function onConstructorDestroyed(name) {
4900 if (!destructListeners.has(name)) {
4901 return;
4902 }
4903 var dbList = destructListeners.get(name);
4904 destructListeners["delete"](name);
4905 dbList.forEach(function (db) {
4906 db.emit('destroyed',true);
4907 });
4908 });
4909}
4910
4911setUpEventEmitter(PouchDB);
4912
4913PouchDB.adapter = function (id, obj, addToPreferredAdapters) {
4914 /* istanbul ignore else */
4915 if (obj.valid()) {
4916 PouchDB.adapters[id] = obj;
4917 if (addToPreferredAdapters) {
4918 PouchDB.preferredAdapters.push(id);
4919 }
4920 }
4921};
4922
4923PouchDB.plugin = function (obj) {
4924 if (typeof obj === 'function') { // function style for plugins
4925 obj(PouchDB);
4926 } else if (typeof obj !== 'object' || Object.keys(obj).length === 0) {
4927 throw new Error('Invalid plugin: got "' + obj + '", expected an object or a function');
4928 } else {
4929 Object.keys(obj).forEach(function (id) { // object style for plugins
4930 PouchDB.prototype[id] = obj[id];
4931 });
4932 }
4933 if (this.__defaults) {
4934 PouchDB.__defaults = $inject_Object_assign({}, this.__defaults);
4935 }
4936 return PouchDB;
4937};
4938
4939PouchDB.defaults = function (defaultOpts) {
4940 function PouchAlt(name, opts) {
4941 if (!(this instanceof PouchAlt)) {
4942 return new PouchAlt(name, opts);
4943 }
4944
4945 opts = opts || {};
4946
4947 if (name && typeof name === 'object') {
4948 opts = name;
4949 name = opts.name;
4950 delete opts.name;
4951 }
4952
4953 opts = $inject_Object_assign({}, PouchAlt.__defaults, opts);
4954 PouchDB.call(this, name, opts);
4955 }
4956
4957 inherits(PouchAlt, PouchDB);
4958
4959 PouchAlt.preferredAdapters = PouchDB.preferredAdapters.slice();
4960 Object.keys(PouchDB).forEach(function (key) {
4961 if (!(key in PouchAlt)) {
4962 PouchAlt[key] = PouchDB[key];
4963 }
4964 });
4965
4966 // make default options transitive
4967 // https://github.com/pouchdb/pouchdb/issues/5922
4968 PouchAlt.__defaults = $inject_Object_assign({}, this.__defaults, defaultOpts);
4969
4970 return PouchAlt;
4971};
4972
4973PouchDB.fetch = function (url, opts) {
4974 return f$1(url, opts);
4975};
4976
4977// managed automatically by set-version.js
4978var version = "7.2.1";
4979
4980// this would just be "return doc[field]", but fields
4981// can be "deep" due to dot notation
4982function getFieldFromDoc(doc, parsedField) {
4983 var value = doc;
4984 for (var i = 0, len = parsedField.length; i < len; i++) {
4985 var key = parsedField[i];
4986 value = value[key];
4987 if (!value) {
4988 break;
4989 }
4990 }
4991 return value;
4992}
4993
4994function compare$1(left, right) {
4995 return left < right ? -1 : left > right ? 1 : 0;
4996}
4997
4998// Converts a string in dot notation to an array of its components, with backslash escaping
4999function parseField(fieldName) {
5000 // fields may be deep (e.g. "foo.bar.baz"), so parse
5001 var fields = [];
5002 var current = '';
5003 for (var i = 0, len = fieldName.length; i < len; i++) {
5004 var ch = fieldName[i];
5005 if (ch === '.') {
5006 if (i > 0 && fieldName[i - 1] === '\\') { // escaped delimiter
5007 current = current.substring(0, current.length - 1) + '.';
5008 } else { // not escaped, so delimiter
5009 fields.push(current);
5010 current = '';
5011 }
5012 } else { // normal character
5013 current += ch;
5014 }
5015 }
5016 fields.push(current);
5017 return fields;
5018}
5019
5020var combinationFields = ['$or', '$nor', '$not'];
5021function isCombinationalField(field) {
5022 return combinationFields.indexOf(field) > -1;
5023}
5024
5025function getKey(obj) {
5026 return Object.keys(obj)[0];
5027}
5028
5029function getValue(obj) {
5030 return obj[getKey(obj)];
5031}
5032
5033
5034// flatten an array of selectors joined by an $and operator
5035function mergeAndedSelectors(selectors) {
5036
5037 // sort to ensure that e.g. if the user specified
5038 // $and: [{$gt: 'a'}, {$gt: 'b'}], then it's collapsed into
5039 // just {$gt: 'b'}
5040 var res = {};
5041
5042 selectors.forEach(function (selector) {
5043 Object.keys(selector).forEach(function (field) {
5044 var matcher = selector[field];
5045 if (typeof matcher !== 'object') {
5046 matcher = {$eq: matcher};
5047 }
5048
5049 if (isCombinationalField(field)) {
5050 if (matcher instanceof Array) {
5051 res[field] = matcher.map(function (m) {
5052 return mergeAndedSelectors([m]);
5053 });
5054 } else {
5055 res[field] = mergeAndedSelectors([matcher]);
5056 }
5057 } else {
5058 var fieldMatchers = res[field] = res[field] || {};
5059 Object.keys(matcher).forEach(function (operator) {
5060 var value = matcher[operator];
5061
5062 if (operator === '$gt' || operator === '$gte') {
5063 return mergeGtGte(operator, value, fieldMatchers);
5064 } else if (operator === '$lt' || operator === '$lte') {
5065 return mergeLtLte(operator, value, fieldMatchers);
5066 } else if (operator === '$ne') {
5067 return mergeNe(value, fieldMatchers);
5068 } else if (operator === '$eq') {
5069 return mergeEq(value, fieldMatchers);
5070 }
5071 fieldMatchers[operator] = value;
5072 });
5073 }
5074 });
5075 });
5076
5077 return res;
5078}
5079
5080
5081
5082// collapse logically equivalent gt/gte values
5083function mergeGtGte(operator, value, fieldMatchers) {
5084 if (typeof fieldMatchers.$eq !== 'undefined') {
5085 return; // do nothing
5086 }
5087 if (typeof fieldMatchers.$gte !== 'undefined') {
5088 if (operator === '$gte') {
5089 if (value > fieldMatchers.$gte) { // more specificity
5090 fieldMatchers.$gte = value;
5091 }
5092 } else { // operator === '$gt'
5093 if (value >= fieldMatchers.$gte) { // more specificity
5094 delete fieldMatchers.$gte;
5095 fieldMatchers.$gt = value;
5096 }
5097 }
5098 } else if (typeof fieldMatchers.$gt !== 'undefined') {
5099 if (operator === '$gte') {
5100 if (value > fieldMatchers.$gt) { // more specificity
5101 delete fieldMatchers.$gt;
5102 fieldMatchers.$gte = value;
5103 }
5104 } else { // operator === '$gt'
5105 if (value > fieldMatchers.$gt) { // more specificity
5106 fieldMatchers.$gt = value;
5107 }
5108 }
5109 } else {
5110 fieldMatchers[operator] = value;
5111 }
5112}
5113
5114// collapse logically equivalent lt/lte values
5115function mergeLtLte(operator, value, fieldMatchers) {
5116 if (typeof fieldMatchers.$eq !== 'undefined') {
5117 return; // do nothing
5118 }
5119 if (typeof fieldMatchers.$lte !== 'undefined') {
5120 if (operator === '$lte') {
5121 if (value < fieldMatchers.$lte) { // more specificity
5122 fieldMatchers.$lte = value;
5123 }
5124 } else { // operator === '$gt'
5125 if (value <= fieldMatchers.$lte) { // more specificity
5126 delete fieldMatchers.$lte;
5127 fieldMatchers.$lt = value;
5128 }
5129 }
5130 } else if (typeof fieldMatchers.$lt !== 'undefined') {
5131 if (operator === '$lte') {
5132 if (value < fieldMatchers.$lt) { // more specificity
5133 delete fieldMatchers.$lt;
5134 fieldMatchers.$lte = value;
5135 }
5136 } else { // operator === '$gt'
5137 if (value < fieldMatchers.$lt) { // more specificity
5138 fieldMatchers.$lt = value;
5139 }
5140 }
5141 } else {
5142 fieldMatchers[operator] = value;
5143 }
5144}
5145
5146// combine $ne values into one array
5147function mergeNe(value, fieldMatchers) {
5148 if ('$ne' in fieldMatchers) {
5149 // there are many things this could "not" be
5150 fieldMatchers.$ne.push(value);
5151 } else { // doesn't exist yet
5152 fieldMatchers.$ne = [value];
5153 }
5154}
5155
5156// add $eq into the mix
5157function mergeEq(value, fieldMatchers) {
5158 // these all have less specificity than the $eq
5159 // TODO: check for user errors here
5160 delete fieldMatchers.$gt;
5161 delete fieldMatchers.$gte;
5162 delete fieldMatchers.$lt;
5163 delete fieldMatchers.$lte;
5164 delete fieldMatchers.$ne;
5165 fieldMatchers.$eq = value;
5166}
5167
5168//#7458: execute function mergeAndedSelectors on nested $and
5169function mergeAndedSelectorsNested(obj) {
5170 for (var prop in obj) {
5171 if (Array.isArray(obj)) {
5172 for (var i in obj) {
5173 if (obj[i]['$and']) {
5174 obj[i] = mergeAndedSelectors(obj[i]['$and']);
5175 }
5176 }
5177 }
5178 var value = obj[prop];
5179 if (typeof value === 'object') {
5180 mergeAndedSelectorsNested(value); // <- recursive call
5181 }
5182 }
5183 return obj;
5184}
5185
5186//#7458: determine id $and is present in selector (at any level)
5187function isAndInSelector(obj, isAnd) {
5188 for (var prop in obj) {
5189 if (prop === '$and') {
5190 isAnd = true;
5191 }
5192 var value = obj[prop];
5193 if (typeof value === 'object') {
5194 isAnd = isAndInSelector(value, isAnd); // <- recursive call
5195 }
5196 }
5197 return isAnd;
5198}
5199
5200//
5201// normalize the selector
5202//
5203function massageSelector(input) {
5204 var result = clone(input);
5205 var wasAnded = false;
5206 //#7458: if $and is present in selector (at any level) merge nested $and
5207 if (isAndInSelector(result, false)) {
5208 result = mergeAndedSelectorsNested(result);
5209 if ('$and' in result) {
5210 result = mergeAndedSelectors(result['$and']);
5211 }
5212 wasAnded = true;
5213 }
5214
5215 ['$or', '$nor'].forEach(function (orOrNor) {
5216 if (orOrNor in result) {
5217 // message each individual selector
5218 // e.g. {foo: 'bar'} becomes {foo: {$eq: 'bar'}}
5219 result[orOrNor].forEach(function (subSelector) {
5220 var fields = Object.keys(subSelector);
5221 for (var i = 0; i < fields.length; i++) {
5222 var field = fields[i];
5223 var matcher = subSelector[field];
5224 if (typeof matcher !== 'object' || matcher === null) {
5225 subSelector[field] = {$eq: matcher};
5226 }
5227 }
5228 });
5229 }
5230 });
5231
5232 if ('$not' in result) {
5233 //This feels a little like forcing, but it will work for now,
5234 //I would like to come back to this and make the merging of selectors a little more generic
5235 result['$not'] = mergeAndedSelectors([result['$not']]);
5236 }
5237
5238 var fields = Object.keys(result);
5239
5240 for (var i = 0; i < fields.length; i++) {
5241 var field = fields[i];
5242 var matcher = result[field];
5243
5244 if (typeof matcher !== 'object' || matcher === null) {
5245 matcher = {$eq: matcher};
5246 } else if ('$ne' in matcher && !wasAnded) {
5247 // I put these in an array, since there may be more than one
5248 // but in the "mergeAnded" operation, I already take care of that
5249 matcher.$ne = [matcher.$ne];
5250 }
5251 result[field] = matcher;
5252 }
5253
5254 return result;
5255}
5256
5257function pad(str, padWith, upToLength) {
5258 var padding = '';
5259 var targetLength = upToLength - str.length;
5260 /* istanbul ignore next */
5261 while (padding.length < targetLength) {
5262 padding += padWith;
5263 }
5264 return padding;
5265}
5266
5267function padLeft(str, padWith, upToLength) {
5268 var padding = pad(str, padWith, upToLength);
5269 return padding + str;
5270}
5271
5272var MIN_MAGNITUDE = -324; // verified by -Number.MIN_VALUE
5273var MAGNITUDE_DIGITS = 3; // ditto
5274var SEP = ''; // set to '_' for easier debugging
5275
5276function collate(a, b) {
5277
5278 if (a === b) {
5279 return 0;
5280 }
5281
5282 a = normalizeKey(a);
5283 b = normalizeKey(b);
5284
5285 var ai = collationIndex(a);
5286 var bi = collationIndex(b);
5287 if ((ai - bi) !== 0) {
5288 return ai - bi;
5289 }
5290 switch (typeof a) {
5291 case 'number':
5292 return a - b;
5293 case 'boolean':
5294 return a < b ? -1 : 1;
5295 case 'string':
5296 return stringCollate(a, b);
5297 }
5298 return Array.isArray(a) ? arrayCollate(a, b) : objectCollate(a, b);
5299}
5300
5301// couch considers null/NaN/Infinity/-Infinity === undefined,
5302// for the purposes of mapreduce indexes. also, dates get stringified.
5303function normalizeKey(key) {
5304 switch (typeof key) {
5305 case 'undefined':
5306 return null;
5307 case 'number':
5308 if (key === Infinity || key === -Infinity || isNaN(key)) {
5309 return null;
5310 }
5311 return key;
5312 case 'object':
5313 var origKey = key;
5314 if (Array.isArray(key)) {
5315 var len = key.length;
5316 key = new Array(len);
5317 for (var i = 0; i < len; i++) {
5318 key[i] = normalizeKey(origKey[i]);
5319 }
5320 /* istanbul ignore next */
5321 } else if (key instanceof Date) {
5322 return key.toJSON();
5323 } else if (key !== null) { // generic object
5324 key = {};
5325 for (var k in origKey) {
5326 if (origKey.hasOwnProperty(k)) {
5327 var val = origKey[k];
5328 if (typeof val !== 'undefined') {
5329 key[k] = normalizeKey(val);
5330 }
5331 }
5332 }
5333 }
5334 }
5335 return key;
5336}
5337
5338function indexify(key) {
5339 if (key !== null) {
5340 switch (typeof key) {
5341 case 'boolean':
5342 return key ? 1 : 0;
5343 case 'number':
5344 return numToIndexableString(key);
5345 case 'string':
5346 // We've to be sure that key does not contain \u0000
5347 // Do order-preserving replacements:
5348 // 0 -> 1, 1
5349 // 1 -> 1, 2
5350 // 2 -> 2, 2
5351 /* eslint-disable no-control-regex */
5352 return key
5353 .replace(/\u0002/g, '\u0002\u0002')
5354 .replace(/\u0001/g, '\u0001\u0002')
5355 .replace(/\u0000/g, '\u0001\u0001');
5356 /* eslint-enable no-control-regex */
5357 case 'object':
5358 var isArray = Array.isArray(key);
5359 var arr = isArray ? key : Object.keys(key);
5360 var i = -1;
5361 var len = arr.length;
5362 var result = '';
5363 if (isArray) {
5364 while (++i < len) {
5365 result += toIndexableString(arr[i]);
5366 }
5367 } else {
5368 while (++i < len) {
5369 var objKey = arr[i];
5370 result += toIndexableString(objKey) +
5371 toIndexableString(key[objKey]);
5372 }
5373 }
5374 return result;
5375 }
5376 }
5377 return '';
5378}
5379
5380// convert the given key to a string that would be appropriate
5381// for lexical sorting, e.g. within a database, where the
5382// sorting is the same given by the collate() function.
5383function toIndexableString(key) {
5384 var zero = '\u0000';
5385 key = normalizeKey(key);
5386 return collationIndex(key) + SEP + indexify(key) + zero;
5387}
5388
5389function parseNumber(str, i) {
5390 var originalIdx = i;
5391 var num;
5392 var zero = str[i] === '1';
5393 if (zero) {
5394 num = 0;
5395 i++;
5396 } else {
5397 var neg = str[i] === '0';
5398 i++;
5399 var numAsString = '';
5400 var magAsString = str.substring(i, i + MAGNITUDE_DIGITS);
5401 var magnitude = parseInt(magAsString, 10) + MIN_MAGNITUDE;
5402 /* istanbul ignore next */
5403 if (neg) {
5404 magnitude = -magnitude;
5405 }
5406 i += MAGNITUDE_DIGITS;
5407 while (true) {
5408 var ch = str[i];
5409 if (ch === '\u0000') {
5410 break;
5411 } else {
5412 numAsString += ch;
5413 }
5414 i++;
5415 }
5416 numAsString = numAsString.split('.');
5417 if (numAsString.length === 1) {
5418 num = parseInt(numAsString, 10);
5419 } else {
5420 /* istanbul ignore next */
5421 num = parseFloat(numAsString[0] + '.' + numAsString[1]);
5422 }
5423 /* istanbul ignore next */
5424 if (neg) {
5425 num = num - 10;
5426 }
5427 /* istanbul ignore next */
5428 if (magnitude !== 0) {
5429 // parseFloat is more reliable than pow due to rounding errors
5430 // e.g. Number.MAX_VALUE would return Infinity if we did
5431 // num * Math.pow(10, magnitude);
5432 num = parseFloat(num + 'e' + magnitude);
5433 }
5434 }
5435 return {num: num, length : i - originalIdx};
5436}
5437
5438// move up the stack while parsing
5439// this function moved outside of parseIndexableString for performance
5440function pop(stack, metaStack) {
5441 var obj = stack.pop();
5442
5443 if (metaStack.length) {
5444 var lastMetaElement = metaStack[metaStack.length - 1];
5445 if (obj === lastMetaElement.element) {
5446 // popping a meta-element, e.g. an object whose value is another object
5447 metaStack.pop();
5448 lastMetaElement = metaStack[metaStack.length - 1];
5449 }
5450 var element = lastMetaElement.element;
5451 var lastElementIndex = lastMetaElement.index;
5452 if (Array.isArray(element)) {
5453 element.push(obj);
5454 } else if (lastElementIndex === stack.length - 2) { // obj with key+value
5455 var key = stack.pop();
5456 element[key] = obj;
5457 } else {
5458 stack.push(obj); // obj with key only
5459 }
5460 }
5461}
5462
5463function parseIndexableString(str) {
5464 var stack = [];
5465 var metaStack = []; // stack for arrays and objects
5466 var i = 0;
5467
5468 /*eslint no-constant-condition: ["error", { "checkLoops": false }]*/
5469 while (true) {
5470 var collationIndex = str[i++];
5471 if (collationIndex === '\u0000') {
5472 if (stack.length === 1) {
5473 return stack.pop();
5474 } else {
5475 pop(stack, metaStack);
5476 continue;
5477 }
5478 }
5479 switch (collationIndex) {
5480 case '1':
5481 stack.push(null);
5482 break;
5483 case '2':
5484 stack.push(str[i] === '1');
5485 i++;
5486 break;
5487 case '3':
5488 var parsedNum = parseNumber(str, i);
5489 stack.push(parsedNum.num);
5490 i += parsedNum.length;
5491 break;
5492 case '4':
5493 var parsedStr = '';
5494 /*eslint no-constant-condition: ["error", { "checkLoops": false }]*/
5495 while (true) {
5496 var ch = str[i];
5497 if (ch === '\u0000') {
5498 break;
5499 }
5500 parsedStr += ch;
5501 i++;
5502 }
5503 // perform the reverse of the order-preserving replacement
5504 // algorithm (see above)
5505 /* eslint-disable no-control-regex */
5506 parsedStr = parsedStr.replace(/\u0001\u0001/g, '\u0000')
5507 .replace(/\u0001\u0002/g, '\u0001')
5508 .replace(/\u0002\u0002/g, '\u0002');
5509 /* eslint-enable no-control-regex */
5510 stack.push(parsedStr);
5511 break;
5512 case '5':
5513 var arrayElement = { element: [], index: stack.length };
5514 stack.push(arrayElement.element);
5515 metaStack.push(arrayElement);
5516 break;
5517 case '6':
5518 var objElement = { element: {}, index: stack.length };
5519 stack.push(objElement.element);
5520 metaStack.push(objElement);
5521 break;
5522 /* istanbul ignore next */
5523 default:
5524 throw new Error(
5525 'bad collationIndex or unexpectedly reached end of input: ' +
5526 collationIndex);
5527 }
5528 }
5529}
5530
5531function arrayCollate(a, b) {
5532 var len = Math.min(a.length, b.length);
5533 for (var i = 0; i < len; i++) {
5534 var sort = collate(a[i], b[i]);
5535 if (sort !== 0) {
5536 return sort;
5537 }
5538 }
5539 return (a.length === b.length) ? 0 :
5540 (a.length > b.length) ? 1 : -1;
5541}
5542function stringCollate(a, b) {
5543 // See: https://github.com/daleharvey/pouchdb/issues/40
5544 // This is incompatible with the CouchDB implementation, but its the
5545 // best we can do for now
5546 return (a === b) ? 0 : ((a > b) ? 1 : -1);
5547}
5548function objectCollate(a, b) {
5549 var ak = Object.keys(a), bk = Object.keys(b);
5550 var len = Math.min(ak.length, bk.length);
5551 for (var i = 0; i < len; i++) {
5552 // First sort the keys
5553 var sort = collate(ak[i], bk[i]);
5554 if (sort !== 0) {
5555 return sort;
5556 }
5557 // if the keys are equal sort the values
5558 sort = collate(a[ak[i]], b[bk[i]]);
5559 if (sort !== 0) {
5560 return sort;
5561 }
5562
5563 }
5564 return (ak.length === bk.length) ? 0 :
5565 (ak.length > bk.length) ? 1 : -1;
5566}
5567// The collation is defined by erlangs ordered terms
5568// the atoms null, true, false come first, then numbers, strings,
5569// arrays, then objects
5570// null/undefined/NaN/Infinity/-Infinity are all considered null
5571function collationIndex(x) {
5572 var id = ['boolean', 'number', 'string', 'object'];
5573 var idx = id.indexOf(typeof x);
5574 //false if -1 otherwise true, but fast!!!!1
5575 if (~idx) {
5576 if (x === null) {
5577 return 1;
5578 }
5579 if (Array.isArray(x)) {
5580 return 5;
5581 }
5582 return idx < 3 ? (idx + 2) : (idx + 3);
5583 }
5584 /* istanbul ignore next */
5585 if (Array.isArray(x)) {
5586 return 5;
5587 }
5588}
5589
5590// conversion:
5591// x yyy zz...zz
5592// x = 0 for negative, 1 for 0, 2 for positive
5593// y = exponent (for negative numbers negated) moved so that it's >= 0
5594// z = mantisse
5595function numToIndexableString(num) {
5596
5597 if (num === 0) {
5598 return '1';
5599 }
5600
5601 // convert number to exponential format for easier and
5602 // more succinct string sorting
5603 var expFormat = num.toExponential().split(/e\+?/);
5604 var magnitude = parseInt(expFormat[1], 10);
5605
5606 var neg = num < 0;
5607
5608 var result = neg ? '0' : '2';
5609
5610 // first sort by magnitude
5611 // it's easier if all magnitudes are positive
5612 var magForComparison = ((neg ? -magnitude : magnitude) - MIN_MAGNITUDE);
5613 var magString = padLeft((magForComparison).toString(), '0', MAGNITUDE_DIGITS);
5614
5615 result += SEP + magString;
5616
5617 // then sort by the factor
5618 var factor = Math.abs(parseFloat(expFormat[0])); // [1..10)
5619 /* istanbul ignore next */
5620 if (neg) { // for negative reverse ordering
5621 factor = 10 - factor;
5622 }
5623
5624 var factorStr = factor.toFixed(20);
5625
5626 // strip zeros from the end
5627 factorStr = factorStr.replace(/\.?0+$/, '');
5628
5629 result += SEP + factorStr;
5630
5631 return result;
5632}
5633
5634// create a comparator based on the sort object
5635function createFieldSorter(sort) {
5636
5637 function getFieldValuesAsArray(doc) {
5638 return sort.map(function (sorting) {
5639 var fieldName = getKey(sorting);
5640 var parsedField = parseField(fieldName);
5641 var docFieldValue = getFieldFromDoc(doc, parsedField);
5642 return docFieldValue;
5643 });
5644 }
5645
5646 return function (aRow, bRow) {
5647 var aFieldValues = getFieldValuesAsArray(aRow.doc);
5648 var bFieldValues = getFieldValuesAsArray(bRow.doc);
5649 var collation = collate(aFieldValues, bFieldValues);
5650 if (collation !== 0) {
5651 return collation;
5652 }
5653 // this is what mango seems to do
5654 return compare$1(aRow.doc._id, bRow.doc._id);
5655 };
5656}
5657
5658function filterInMemoryFields(rows, requestDef, inMemoryFields) {
5659 rows = rows.filter(function (row) {
5660 return rowFilter(row.doc, requestDef.selector, inMemoryFields);
5661 });
5662
5663 if (requestDef.sort) {
5664 // in-memory sort
5665 var fieldSorter = createFieldSorter(requestDef.sort);
5666 rows = rows.sort(fieldSorter);
5667 if (typeof requestDef.sort[0] !== 'string' &&
5668 getValue(requestDef.sort[0]) === 'desc') {
5669 rows = rows.reverse();
5670 }
5671 }
5672
5673 if ('limit' in requestDef || 'skip' in requestDef) {
5674 // have to do the limit in-memory
5675 var skip = requestDef.skip || 0;
5676 var limit = ('limit' in requestDef ? requestDef.limit : rows.length) + skip;
5677 rows = rows.slice(skip, limit);
5678 }
5679 return rows;
5680}
5681
5682function rowFilter(doc, selector, inMemoryFields) {
5683 return inMemoryFields.every(function (field) {
5684 var matcher = selector[field];
5685 var parsedField = parseField(field);
5686 var docFieldValue = getFieldFromDoc(doc, parsedField);
5687 if (isCombinationalField(field)) {
5688 return matchCominationalSelector(field, matcher, doc);
5689 }
5690
5691 return matchSelector(matcher, doc, parsedField, docFieldValue);
5692 });
5693}
5694
5695function matchSelector(matcher, doc, parsedField, docFieldValue) {
5696 if (!matcher) {
5697 // no filtering necessary; this field is just needed for sorting
5698 return true;
5699 }
5700
5701 // is matcher an object, if so continue recursion
5702 if (typeof matcher === 'object') {
5703 return Object.keys(matcher).every(function (userOperator) {
5704 var userValue = matcher[userOperator];
5705 return match(userOperator, doc, userValue, parsedField, docFieldValue);
5706 });
5707 }
5708
5709 // no more depth, No need to recurse further
5710 return matcher === docFieldValue;
5711}
5712
5713function matchCominationalSelector(field, matcher, doc) {
5714
5715 if (field === '$or') {
5716 return matcher.some(function (orMatchers) {
5717 return rowFilter(doc, orMatchers, Object.keys(orMatchers));
5718 });
5719 }
5720
5721 if (field === '$not') {
5722 return !rowFilter(doc, matcher, Object.keys(matcher));
5723 }
5724
5725 //`$nor`
5726 return !matcher.find(function (orMatchers) {
5727 return rowFilter(doc, orMatchers, Object.keys(orMatchers));
5728 });
5729
5730}
5731
5732function match(userOperator, doc, userValue, parsedField, docFieldValue) {
5733 if (!matchers[userOperator]) {
5734 throw new Error('unknown operator "' + userOperator +
5735 '" - should be one of $eq, $lte, $lt, $gt, $gte, $exists, $ne, $in, ' +
5736 '$nin, $size, $mod, $regex, $elemMatch, $type, $allMatch or $all');
5737 }
5738 return matchers[userOperator](doc, userValue, parsedField, docFieldValue);
5739}
5740
5741function fieldExists(docFieldValue) {
5742 return typeof docFieldValue !== 'undefined' && docFieldValue !== null;
5743}
5744
5745function fieldIsNotUndefined(docFieldValue) {
5746 return typeof docFieldValue !== 'undefined';
5747}
5748
5749function modField(docFieldValue, userValue) {
5750 var divisor = userValue[0];
5751 var mod = userValue[1];
5752 if (divisor === 0) {
5753 throw new Error('Bad divisor, cannot divide by zero');
5754 }
5755
5756 if (parseInt(divisor, 10) !== divisor ) {
5757 throw new Error('Divisor is not an integer');
5758 }
5759
5760 if (parseInt(mod, 10) !== mod ) {
5761 throw new Error('Modulus is not an integer');
5762 }
5763
5764 if (parseInt(docFieldValue, 10) !== docFieldValue) {
5765 return false;
5766 }
5767
5768 return docFieldValue % divisor === mod;
5769}
5770
5771function arrayContainsValue(docFieldValue, userValue) {
5772 return userValue.some(function (val) {
5773 if (docFieldValue instanceof Array) {
5774 return docFieldValue.indexOf(val) > -1;
5775 }
5776
5777 return docFieldValue === val;
5778 });
5779}
5780
5781function arrayContainsAllValues(docFieldValue, userValue) {
5782 return userValue.every(function (val) {
5783 return docFieldValue.indexOf(val) > -1;
5784 });
5785}
5786
5787function arraySize(docFieldValue, userValue) {
5788 return docFieldValue.length === userValue;
5789}
5790
5791function regexMatch(docFieldValue, userValue) {
5792 var re = new RegExp(userValue);
5793
5794 return re.test(docFieldValue);
5795}
5796
5797function typeMatch(docFieldValue, userValue) {
5798
5799 switch (userValue) {
5800 case 'null':
5801 return docFieldValue === null;
5802 case 'boolean':
5803 return typeof (docFieldValue) === 'boolean';
5804 case 'number':
5805 return typeof (docFieldValue) === 'number';
5806 case 'string':
5807 return typeof (docFieldValue) === 'string';
5808 case 'array':
5809 return docFieldValue instanceof Array;
5810 case 'object':
5811 return ({}).toString.call(docFieldValue) === '[object Object]';
5812 }
5813
5814 throw new Error(userValue + ' not supported as a type.' +
5815 'Please use one of object, string, array, number, boolean or null.');
5816
5817}
5818
5819var matchers = {
5820
5821 '$elemMatch': function (doc, userValue, parsedField, docFieldValue) {
5822 if (!Array.isArray(docFieldValue)) {
5823 return false;
5824 }
5825
5826 if (docFieldValue.length === 0) {
5827 return false;
5828 }
5829
5830 if (typeof docFieldValue[0] === 'object') {
5831 return docFieldValue.some(function (val) {
5832 return rowFilter(val, userValue, Object.keys(userValue));
5833 });
5834 }
5835
5836 return docFieldValue.some(function (val) {
5837 return matchSelector(userValue, doc, parsedField, val);
5838 });
5839 },
5840
5841 '$allMatch': function (doc, userValue, parsedField, docFieldValue) {
5842 if (!Array.isArray(docFieldValue)) {
5843 return false;
5844 }
5845
5846 /* istanbul ignore next */
5847 if (docFieldValue.length === 0) {
5848 return false;
5849 }
5850
5851 if (typeof docFieldValue[0] === 'object') {
5852 return docFieldValue.every(function (val) {
5853 return rowFilter(val, userValue, Object.keys(userValue));
5854 });
5855 }
5856
5857 return docFieldValue.every(function (val) {
5858 return matchSelector(userValue, doc, parsedField, val);
5859 });
5860 },
5861
5862 '$eq': function (doc, userValue, parsedField, docFieldValue) {
5863 return fieldIsNotUndefined(docFieldValue) && collate(docFieldValue, userValue) === 0;
5864 },
5865
5866 '$gte': function (doc, userValue, parsedField, docFieldValue) {
5867 return fieldIsNotUndefined(docFieldValue) && collate(docFieldValue, userValue) >= 0;
5868 },
5869
5870 '$gt': function (doc, userValue, parsedField, docFieldValue) {
5871 return fieldIsNotUndefined(docFieldValue) && collate(docFieldValue, userValue) > 0;
5872 },
5873
5874 '$lte': function (doc, userValue, parsedField, docFieldValue) {
5875 return fieldIsNotUndefined(docFieldValue) && collate(docFieldValue, userValue) <= 0;
5876 },
5877
5878 '$lt': function (doc, userValue, parsedField, docFieldValue) {
5879 return fieldIsNotUndefined(docFieldValue) && collate(docFieldValue, userValue) < 0;
5880 },
5881
5882 '$exists': function (doc, userValue, parsedField, docFieldValue) {
5883 //a field that is null is still considered to exist
5884 if (userValue) {
5885 return fieldIsNotUndefined(docFieldValue);
5886 }
5887
5888 return !fieldIsNotUndefined(docFieldValue);
5889 },
5890
5891 '$mod': function (doc, userValue, parsedField, docFieldValue) {
5892 return fieldExists(docFieldValue) && modField(docFieldValue, userValue);
5893 },
5894
5895 '$ne': function (doc, userValue, parsedField, docFieldValue) {
5896 return userValue.every(function (neValue) {
5897 return collate(docFieldValue, neValue) !== 0;
5898 });
5899 },
5900 '$in': function (doc, userValue, parsedField, docFieldValue) {
5901 return fieldExists(docFieldValue) && arrayContainsValue(docFieldValue, userValue);
5902 },
5903
5904 '$nin': function (doc, userValue, parsedField, docFieldValue) {
5905 return fieldExists(docFieldValue) && !arrayContainsValue(docFieldValue, userValue);
5906 },
5907
5908 '$size': function (doc, userValue, parsedField, docFieldValue) {
5909 return fieldExists(docFieldValue) && arraySize(docFieldValue, userValue);
5910 },
5911
5912 '$all': function (doc, userValue, parsedField, docFieldValue) {
5913 return Array.isArray(docFieldValue) && arrayContainsAllValues(docFieldValue, userValue);
5914 },
5915
5916 '$regex': function (doc, userValue, parsedField, docFieldValue) {
5917 return fieldExists(docFieldValue) && regexMatch(docFieldValue, userValue);
5918 },
5919
5920 '$type': function (doc, userValue, parsedField, docFieldValue) {
5921 return typeMatch(docFieldValue, userValue);
5922 }
5923};
5924
5925// return true if the given doc matches the supplied selector
5926function matchesSelector(doc, selector) {
5927 /* istanbul ignore if */
5928 if (typeof selector !== 'object') {
5929 // match the CouchDB error message
5930 throw new Error('Selector error: expected a JSON object');
5931 }
5932
5933 selector = massageSelector(selector);
5934 var row = {
5935 'doc': doc
5936 };
5937
5938 var rowsMatched = filterInMemoryFields([row], { 'selector': selector }, Object.keys(selector));
5939 return rowsMatched && rowsMatched.length === 1;
5940}
5941
5942function evalFilter(input) {
5943 return scopeEval('"use strict";\nreturn ' + input + ';', {});
5944}
5945
5946function evalView(input) {
5947 var code = [
5948 'return function(doc) {',
5949 ' "use strict";',
5950 ' var emitted = false;',
5951 ' var emit = function (a, b) {',
5952 ' emitted = true;',
5953 ' };',
5954 ' var view = ' + input + ';',
5955 ' view(doc);',
5956 ' if (emitted) {',
5957 ' return true;',
5958 ' }',
5959 '};'
5960 ].join('\n');
5961
5962 return scopeEval(code, {});
5963}
5964
5965function validate(opts, callback) {
5966 if (opts.selector) {
5967 if (opts.filter && opts.filter !== '_selector') {
5968 var filterName = typeof opts.filter === 'string' ?
5969 opts.filter : 'function';
5970 return callback(new Error('selector invalid for filter "' + filterName + '"'));
5971 }
5972 }
5973 callback();
5974}
5975
5976function normalize(opts) {
5977 if (opts.view && !opts.filter) {
5978 opts.filter = '_view';
5979 }
5980
5981 if (opts.selector && !opts.filter) {
5982 opts.filter = '_selector';
5983 }
5984
5985 if (opts.filter && typeof opts.filter === 'string') {
5986 if (opts.filter === '_view') {
5987 opts.view = normalizeDesignDocFunctionName(opts.view);
5988 } else {
5989 opts.filter = normalizeDesignDocFunctionName(opts.filter);
5990 }
5991 }
5992}
5993
5994function shouldFilter(changesHandler, opts) {
5995 return opts.filter && typeof opts.filter === 'string' &&
5996 !opts.doc_ids && !isRemote(changesHandler.db);
5997}
5998
5999function filter(changesHandler, opts) {
6000 var callback = opts.complete;
6001 if (opts.filter === '_view') {
6002 if (!opts.view || typeof opts.view !== 'string') {
6003 var err = createError(BAD_REQUEST,
6004 '`view` filter parameter not found or invalid.');
6005 return callback(err);
6006 }
6007 // fetch a view from a design doc, make it behave like a filter
6008 var viewName = parseDesignDocFunctionName(opts.view);
6009 changesHandler.db.get('_design/' + viewName[0], function (err, ddoc) {
6010 /* istanbul ignore if */
6011 if (changesHandler.isCancelled) {
6012 return callback(null, {status: 'cancelled'});
6013 }
6014 /* istanbul ignore next */
6015 if (err) {
6016 return callback(generateErrorFromResponse(err));
6017 }
6018 var mapFun = ddoc && ddoc.views && ddoc.views[viewName[1]] &&
6019 ddoc.views[viewName[1]].map;
6020 if (!mapFun) {
6021 return callback(createError(MISSING_DOC,
6022 (ddoc.views ? 'missing json key: ' + viewName[1] :
6023 'missing json key: views')));
6024 }
6025 opts.filter = evalView(mapFun);
6026 changesHandler.doChanges(opts);
6027 });
6028 } else if (opts.selector) {
6029 opts.filter = function (doc) {
6030 return matchesSelector(doc, opts.selector);
6031 };
6032 changesHandler.doChanges(opts);
6033 } else {
6034 // fetch a filter from a design doc
6035 var filterName = parseDesignDocFunctionName(opts.filter);
6036 changesHandler.db.get('_design/' + filterName[0], function (err, ddoc) {
6037 /* istanbul ignore if */
6038 if (changesHandler.isCancelled) {
6039 return callback(null, {status: 'cancelled'});
6040 }
6041 /* istanbul ignore next */
6042 if (err) {
6043 return callback(generateErrorFromResponse(err));
6044 }
6045 var filterFun = ddoc && ddoc.filters && ddoc.filters[filterName[1]];
6046 if (!filterFun) {
6047 return callback(createError(MISSING_DOC,
6048 ((ddoc && ddoc.filters) ? 'missing json key: ' + filterName[1]
6049 : 'missing json key: filters')));
6050 }
6051 opts.filter = evalFilter(filterFun);
6052 changesHandler.doChanges(opts);
6053 });
6054 }
6055}
6056
6057function applyChangesFilterPlugin(PouchDB) {
6058 PouchDB._changesFilterPlugin = {
6059 validate: validate,
6060 normalize: normalize,
6061 shouldFilter: shouldFilter,
6062 filter: filter
6063 };
6064}
6065
6066// TODO: remove from pouchdb-core (breaking)
6067PouchDB.plugin(applyChangesFilterPlugin);
6068
6069PouchDB.version = version;
6070
6071function toObject(array) {
6072 return array.reduce(function (obj, item) {
6073 obj[item] = true;
6074 return obj;
6075 }, {});
6076}
6077// List of top level reserved words for doc
6078var reservedWords = toObject([
6079 '_id',
6080 '_rev',
6081 '_attachments',
6082 '_deleted',
6083 '_revisions',
6084 '_revs_info',
6085 '_conflicts',
6086 '_deleted_conflicts',
6087 '_local_seq',
6088 '_rev_tree',
6089 //replication documents
6090 '_replication_id',
6091 '_replication_state',
6092 '_replication_state_time',
6093 '_replication_state_reason',
6094 '_replication_stats',
6095 // Specific to Couchbase Sync Gateway
6096 '_removed'
6097]);
6098
6099// List of reserved words that should end up the document
6100var dataWords = toObject([
6101 '_attachments',
6102 //replication documents
6103 '_replication_id',
6104 '_replication_state',
6105 '_replication_state_time',
6106 '_replication_state_reason',
6107 '_replication_stats'
6108]);
6109
6110function parseRevisionInfo(rev$$1) {
6111 if (!/^\d+-/.test(rev$$1)) {
6112 return createError(INVALID_REV);
6113 }
6114 var idx = rev$$1.indexOf('-');
6115 var left = rev$$1.substring(0, idx);
6116 var right = rev$$1.substring(idx + 1);
6117 return {
6118 prefix: parseInt(left, 10),
6119 id: right
6120 };
6121}
6122
6123function makeRevTreeFromRevisions(revisions, opts) {
6124 var pos = revisions.start - revisions.ids.length + 1;
6125
6126 var revisionIds = revisions.ids;
6127 var ids = [revisionIds[0], opts, []];
6128
6129 for (var i = 1, len = revisionIds.length; i < len; i++) {
6130 ids = [revisionIds[i], {status: 'missing'}, [ids]];
6131 }
6132
6133 return [{
6134 pos: pos,
6135 ids: ids
6136 }];
6137}
6138
6139// Preprocess documents, parse their revisions, assign an id and a
6140// revision for new writes that are missing them, etc
6141function parseDoc(doc, newEdits, dbOpts) {
6142 if (!dbOpts) {
6143 dbOpts = {
6144 deterministic_revs: true
6145 };
6146 }
6147
6148 var nRevNum;
6149 var newRevId;
6150 var revInfo;
6151 var opts = {status: 'available'};
6152 if (doc._deleted) {
6153 opts.deleted = true;
6154 }
6155
6156 if (newEdits) {
6157 if (!doc._id) {
6158 doc._id = uuid();
6159 }
6160 newRevId = rev(doc, dbOpts.deterministic_revs);
6161 if (doc._rev) {
6162 revInfo = parseRevisionInfo(doc._rev);
6163 if (revInfo.error) {
6164 return revInfo;
6165 }
6166 doc._rev_tree = [{
6167 pos: revInfo.prefix,
6168 ids: [revInfo.id, {status: 'missing'}, [[newRevId, opts, []]]]
6169 }];
6170 nRevNum = revInfo.prefix + 1;
6171 } else {
6172 doc._rev_tree = [{
6173 pos: 1,
6174 ids : [newRevId, opts, []]
6175 }];
6176 nRevNum = 1;
6177 }
6178 } else {
6179 if (doc._revisions) {
6180 doc._rev_tree = makeRevTreeFromRevisions(doc._revisions, opts);
6181 nRevNum = doc._revisions.start;
6182 newRevId = doc._revisions.ids[0];
6183 }
6184 if (!doc._rev_tree) {
6185 revInfo = parseRevisionInfo(doc._rev);
6186 if (revInfo.error) {
6187 return revInfo;
6188 }
6189 nRevNum = revInfo.prefix;
6190 newRevId = revInfo.id;
6191 doc._rev_tree = [{
6192 pos: nRevNum,
6193 ids: [newRevId, opts, []]
6194 }];
6195 }
6196 }
6197
6198 invalidIdError(doc._id);
6199
6200 doc._rev = nRevNum + '-' + newRevId;
6201
6202 var result = {metadata : {}, data : {}};
6203 for (var key in doc) {
6204 /* istanbul ignore else */
6205 if (Object.prototype.hasOwnProperty.call(doc, key)) {
6206 var specialKey = key[0] === '_';
6207 if (specialKey && !reservedWords[key]) {
6208 var error = createError(DOC_VALIDATION, key);
6209 error.message = DOC_VALIDATION.message + ': ' + key;
6210 throw error;
6211 } else if (specialKey && !dataWords[key]) {
6212 result.metadata[key.slice(1)] = doc[key];
6213 } else {
6214 result.data[key] = doc[key];
6215 }
6216 }
6217 }
6218 return result;
6219}
6220
6221function parseBase64(data) {
6222 try {
6223 return thisAtob(data);
6224 } catch (e) {
6225 var err = createError(BAD_ARG,
6226 'Attachment is not a valid base64 string');
6227 return {error: err};
6228 }
6229}
6230
6231function preprocessString(att, blobType, callback) {
6232 var asBinary = parseBase64(att.data);
6233 if (asBinary.error) {
6234 return callback(asBinary.error);
6235 }
6236
6237 att.length = asBinary.length;
6238 if (blobType === 'blob') {
6239 att.data = binStringToBluffer(asBinary, att.content_type);
6240 } else if (blobType === 'base64') {
6241 att.data = thisBtoa(asBinary);
6242 } else { // binary
6243 att.data = asBinary;
6244 }
6245 binaryMd5(asBinary, function (result) {
6246 att.digest = 'md5-' + result;
6247 callback();
6248 });
6249}
6250
6251function preprocessBlob(att, blobType, callback) {
6252 binaryMd5(att.data, function (md5) {
6253 att.digest = 'md5-' + md5;
6254 // size is for blobs (browser), length is for buffers (node)
6255 att.length = att.data.size || att.data.length || 0;
6256 if (blobType === 'binary') {
6257 blobToBinaryString(att.data, function (binString) {
6258 att.data = binString;
6259 callback();
6260 });
6261 } else if (blobType === 'base64') {
6262 blobToBase64(att.data, function (b64) {
6263 att.data = b64;
6264 callback();
6265 });
6266 } else {
6267 callback();
6268 }
6269 });
6270}
6271
6272function preprocessAttachment(att, blobType, callback) {
6273 if (att.stub) {
6274 return callback();
6275 }
6276 if (typeof att.data === 'string') { // input is a base64 string
6277 preprocessString(att, blobType, callback);
6278 } else { // input is a blob
6279 preprocessBlob(att, blobType, callback);
6280 }
6281}
6282
6283function preprocessAttachments(docInfos, blobType, callback) {
6284
6285 if (!docInfos.length) {
6286 return callback();
6287 }
6288
6289 var docv = 0;
6290 var overallErr;
6291
6292 docInfos.forEach(function (docInfo) {
6293 var attachments = docInfo.data && docInfo.data._attachments ?
6294 Object.keys(docInfo.data._attachments) : [];
6295 var recv = 0;
6296
6297 if (!attachments.length) {
6298 return done();
6299 }
6300
6301 function processedAttachment(err) {
6302 overallErr = err;
6303 recv++;
6304 if (recv === attachments.length) {
6305 done();
6306 }
6307 }
6308
6309 for (var key in docInfo.data._attachments) {
6310 if (docInfo.data._attachments.hasOwnProperty(key)) {
6311 preprocessAttachment(docInfo.data._attachments[key],
6312 blobType, processedAttachment);
6313 }
6314 }
6315 });
6316
6317 function done() {
6318 docv++;
6319 if (docInfos.length === docv) {
6320 if (overallErr) {
6321 callback(overallErr);
6322 } else {
6323 callback();
6324 }
6325 }
6326 }
6327}
6328
6329function updateDoc(revLimit, prev, docInfo, results,
6330 i, cb, writeDoc, newEdits) {
6331
6332 if (revExists(prev.rev_tree, docInfo.metadata.rev) && !newEdits) {
6333 results[i] = docInfo;
6334 return cb();
6335 }
6336
6337 // sometimes this is pre-calculated. historically not always
6338 var previousWinningRev = prev.winningRev || winningRev(prev);
6339 var previouslyDeleted = 'deleted' in prev ? prev.deleted :
6340 isDeleted(prev, previousWinningRev);
6341 var deleted = 'deleted' in docInfo.metadata ? docInfo.metadata.deleted :
6342 isDeleted(docInfo.metadata);
6343 var isRoot = /^1-/.test(docInfo.metadata.rev);
6344
6345 if (previouslyDeleted && !deleted && newEdits && isRoot) {
6346 var newDoc = docInfo.data;
6347 newDoc._rev = previousWinningRev;
6348 newDoc._id = docInfo.metadata.id;
6349 docInfo = parseDoc(newDoc, newEdits);
6350 }
6351
6352 var merged = merge(prev.rev_tree, docInfo.metadata.rev_tree[0], revLimit);
6353
6354 var inConflict = newEdits && ((
6355 (previouslyDeleted && deleted && merged.conflicts !== 'new_leaf') ||
6356 (!previouslyDeleted && merged.conflicts !== 'new_leaf') ||
6357 (previouslyDeleted && !deleted && merged.conflicts === 'new_branch')));
6358
6359 if (inConflict) {
6360 var err = createError(REV_CONFLICT);
6361 results[i] = err;
6362 return cb();
6363 }
6364
6365 var newRev = docInfo.metadata.rev;
6366 docInfo.metadata.rev_tree = merged.tree;
6367 docInfo.stemmedRevs = merged.stemmedRevs || [];
6368 /* istanbul ignore else */
6369 if (prev.rev_map) {
6370 docInfo.metadata.rev_map = prev.rev_map; // used only by leveldb
6371 }
6372
6373 // recalculate
6374 var winningRev$$1 = winningRev(docInfo.metadata);
6375 var winningRevIsDeleted = isDeleted(docInfo.metadata, winningRev$$1);
6376
6377 // calculate the total number of documents that were added/removed,
6378 // from the perspective of total_rows/doc_count
6379 var delta = (previouslyDeleted === winningRevIsDeleted) ? 0 :
6380 previouslyDeleted < winningRevIsDeleted ? -1 : 1;
6381
6382 var newRevIsDeleted;
6383 if (newRev === winningRev$$1) {
6384 // if the new rev is the same as the winning rev, we can reuse that value
6385 newRevIsDeleted = winningRevIsDeleted;
6386 } else {
6387 // if they're not the same, then we need to recalculate
6388 newRevIsDeleted = isDeleted(docInfo.metadata, newRev);
6389 }
6390
6391 writeDoc(docInfo, winningRev$$1, winningRevIsDeleted, newRevIsDeleted,
6392 true, delta, i, cb);
6393}
6394
6395function rootIsMissing(docInfo) {
6396 return docInfo.metadata.rev_tree[0].ids[1].status === 'missing';
6397}
6398
6399function processDocs(revLimit, docInfos, api, fetchedDocs, tx, results,
6400 writeDoc, opts, overallCallback) {
6401
6402 // Default to 1000 locally
6403 revLimit = revLimit || 1000;
6404
6405 function insertDoc(docInfo, resultsIdx, callback) {
6406 // Cant insert new deleted documents
6407 var winningRev$$1 = winningRev(docInfo.metadata);
6408 var deleted = isDeleted(docInfo.metadata, winningRev$$1);
6409 if ('was_delete' in opts && deleted) {
6410 results[resultsIdx] = createError(MISSING_DOC, 'deleted');
6411 return callback();
6412 }
6413
6414 // 4712 - detect whether a new document was inserted with a _rev
6415 var inConflict = newEdits && rootIsMissing(docInfo);
6416
6417 if (inConflict) {
6418 var err = createError(REV_CONFLICT);
6419 results[resultsIdx] = err;
6420 return callback();
6421 }
6422
6423 var delta = deleted ? 0 : 1;
6424
6425 writeDoc(docInfo, winningRev$$1, deleted, deleted, false,
6426 delta, resultsIdx, callback);
6427 }
6428
6429 var newEdits = opts.new_edits;
6430 var idsToDocs = new ExportedMap();
6431
6432 var docsDone = 0;
6433 var docsToDo = docInfos.length;
6434
6435 function checkAllDocsDone() {
6436 if (++docsDone === docsToDo && overallCallback) {
6437 overallCallback();
6438 }
6439 }
6440
6441 docInfos.forEach(function (currentDoc, resultsIdx) {
6442
6443 if (currentDoc._id && isLocalId(currentDoc._id)) {
6444 var fun = currentDoc._deleted ? '_removeLocal' : '_putLocal';
6445 api[fun](currentDoc, {ctx: tx}, function (err, res) {
6446 results[resultsIdx] = err || res;
6447 checkAllDocsDone();
6448 });
6449 return;
6450 }
6451
6452 var id = currentDoc.metadata.id;
6453 if (idsToDocs.has(id)) {
6454 docsToDo--; // duplicate
6455 idsToDocs.get(id).push([currentDoc, resultsIdx]);
6456 } else {
6457 idsToDocs.set(id, [[currentDoc, resultsIdx]]);
6458 }
6459 });
6460
6461 // in the case of new_edits, the user can provide multiple docs
6462 // with the same id. these need to be processed sequentially
6463 idsToDocs.forEach(function (docs, id) {
6464 var numDone = 0;
6465
6466 function docWritten() {
6467 if (++numDone < docs.length) {
6468 nextDoc();
6469 } else {
6470 checkAllDocsDone();
6471 }
6472 }
6473 function nextDoc() {
6474 var value = docs[numDone];
6475 var currentDoc = value[0];
6476 var resultsIdx = value[1];
6477
6478 if (fetchedDocs.has(id)) {
6479 updateDoc(revLimit, fetchedDocs.get(id), currentDoc, results,
6480 resultsIdx, docWritten, writeDoc, newEdits);
6481 } else {
6482 // Ensure stemming applies to new writes as well
6483 var merged = merge([], currentDoc.metadata.rev_tree[0], revLimit);
6484 currentDoc.metadata.rev_tree = merged.tree;
6485 currentDoc.stemmedRevs = merged.stemmedRevs || [];
6486 insertDoc(currentDoc, resultsIdx, docWritten);
6487 }
6488 }
6489 nextDoc();
6490 });
6491}
6492
6493// IndexedDB requires a versioned database structure, so we use the
6494// version here to manage migrations.
6495var ADAPTER_VERSION = 5;
6496
6497// The object stores created for each database
6498// DOC_STORE stores the document meta data, its revision history and state
6499// Keyed by document id
6500var DOC_STORE = 'document-store';
6501// BY_SEQ_STORE stores a particular version of a document, keyed by its
6502// sequence id
6503var BY_SEQ_STORE = 'by-sequence';
6504// Where we store attachments
6505var ATTACH_STORE = 'attach-store';
6506// Where we store many-to-many relations
6507// between attachment digests and seqs
6508var ATTACH_AND_SEQ_STORE = 'attach-seq-store';
6509
6510// Where we store database-wide meta data in a single record
6511// keyed by id: META_STORE
6512var META_STORE = 'meta-store';
6513// Where we store local documents
6514var LOCAL_STORE = 'local-store';
6515// Where we detect blob support
6516var DETECT_BLOB_SUPPORT_STORE = 'detect-blob-support';
6517
6518function safeJsonParse(str) {
6519 // This try/catch guards against stack overflow errors.
6520 // JSON.parse() is faster than vuvuzela.parse() but vuvuzela
6521 // cannot overflow.
6522 try {
6523 return JSON.parse(str);
6524 } catch (e) {
6525 /* istanbul ignore next */
6526 return vuvuzela.parse(str);
6527 }
6528}
6529
6530function safeJsonStringify(json) {
6531 try {
6532 return JSON.stringify(json);
6533 } catch (e) {
6534 /* istanbul ignore next */
6535 return vuvuzela.stringify(json);
6536 }
6537}
6538
6539function idbError(callback) {
6540 return function (evt) {
6541 var message = 'unknown_error';
6542 if (evt.target && evt.target.error) {
6543 message = evt.target.error.name || evt.target.error.message;
6544 }
6545 callback(createError(IDB_ERROR, message, evt.type));
6546 };
6547}
6548
6549// Unfortunately, the metadata has to be stringified
6550// when it is put into the database, because otherwise
6551// IndexedDB can throw errors for deeply-nested objects.
6552// Originally we just used JSON.parse/JSON.stringify; now
6553// we use this custom vuvuzela library that avoids recursion.
6554// If we could do it all over again, we'd probably use a
6555// format for the revision trees other than JSON.
6556function encodeMetadata(metadata, winningRev, deleted) {
6557 return {
6558 data: safeJsonStringify(metadata),
6559 winningRev: winningRev,
6560 deletedOrLocal: deleted ? '1' : '0',
6561 seq: metadata.seq, // highest seq for this doc
6562 id: metadata.id
6563 };
6564}
6565
6566function decodeMetadata(storedObject) {
6567 if (!storedObject) {
6568 return null;
6569 }
6570 var metadata = safeJsonParse(storedObject.data);
6571 metadata.winningRev = storedObject.winningRev;
6572 metadata.deleted = storedObject.deletedOrLocal === '1';
6573 metadata.seq = storedObject.seq;
6574 return metadata;
6575}
6576
6577// read the doc back out from the database. we don't store the
6578// _id or _rev because we already have _doc_id_rev.
6579function decodeDoc(doc) {
6580 if (!doc) {
6581 return doc;
6582 }
6583 var idx = doc._doc_id_rev.lastIndexOf(':');
6584 doc._id = doc._doc_id_rev.substring(0, idx - 1);
6585 doc._rev = doc._doc_id_rev.substring(idx + 1);
6586 delete doc._doc_id_rev;
6587 return doc;
6588}
6589
6590// Read a blob from the database, encoding as necessary
6591// and translating from base64 if the IDB doesn't support
6592// native Blobs
6593function readBlobData(body, type, asBlob, callback) {
6594 if (asBlob) {
6595 if (!body) {
6596 callback(createBlob([''], {type: type}));
6597 } else if (typeof body !== 'string') { // we have blob support
6598 callback(body);
6599 } else { // no blob support
6600 callback(b64ToBluffer(body, type));
6601 }
6602 } else { // as base64 string
6603 if (!body) {
6604 callback('');
6605 } else if (typeof body !== 'string') { // we have blob support
6606 readAsBinaryString(body, function (binary) {
6607 callback(thisBtoa(binary));
6608 });
6609 } else { // no blob support
6610 callback(body);
6611 }
6612 }
6613}
6614
6615function fetchAttachmentsIfNecessary(doc, opts, txn, cb) {
6616 var attachments = Object.keys(doc._attachments || {});
6617 if (!attachments.length) {
6618 return cb && cb();
6619 }
6620 var numDone = 0;
6621
6622 function checkDone() {
6623 if (++numDone === attachments.length && cb) {
6624 cb();
6625 }
6626 }
6627
6628 function fetchAttachment(doc, att) {
6629 var attObj = doc._attachments[att];
6630 var digest = attObj.digest;
6631 var req = txn.objectStore(ATTACH_STORE).get(digest);
6632 req.onsuccess = function (e) {
6633 attObj.body = e.target.result.body;
6634 checkDone();
6635 };
6636 }
6637
6638 attachments.forEach(function (att) {
6639 if (opts.attachments && opts.include_docs) {
6640 fetchAttachment(doc, att);
6641 } else {
6642 doc._attachments[att].stub = true;
6643 checkDone();
6644 }
6645 });
6646}
6647
6648// IDB-specific postprocessing necessary because
6649// we don't know whether we stored a true Blob or
6650// a base64-encoded string, and if it's a Blob it
6651// needs to be read outside of the transaction context
6652function postProcessAttachments(results, asBlob) {
6653 return Promise.all(results.map(function (row) {
6654 if (row.doc && row.doc._attachments) {
6655 var attNames = Object.keys(row.doc._attachments);
6656 return Promise.all(attNames.map(function (att) {
6657 var attObj = row.doc._attachments[att];
6658 if (!('body' in attObj)) { // already processed
6659 return;
6660 }
6661 var body = attObj.body;
6662 var type = attObj.content_type;
6663 return new Promise(function (resolve) {
6664 readBlobData(body, type, asBlob, function (data) {
6665 row.doc._attachments[att] = $inject_Object_assign(
6666 pick(attObj, ['digest', 'content_type']),
6667 {data: data}
6668 );
6669 resolve();
6670 });
6671 });
6672 }));
6673 }
6674 }));
6675}
6676
6677function compactRevs(revs, docId, txn) {
6678
6679 var possiblyOrphanedDigests = [];
6680 var seqStore = txn.objectStore(BY_SEQ_STORE);
6681 var attStore = txn.objectStore(ATTACH_STORE);
6682 var attAndSeqStore = txn.objectStore(ATTACH_AND_SEQ_STORE);
6683 var count = revs.length;
6684
6685 function checkDone() {
6686 count--;
6687 if (!count) { // done processing all revs
6688 deleteOrphanedAttachments();
6689 }
6690 }
6691
6692 function deleteOrphanedAttachments() {
6693 if (!possiblyOrphanedDigests.length) {
6694 return;
6695 }
6696 possiblyOrphanedDigests.forEach(function (digest) {
6697 var countReq = attAndSeqStore.index('digestSeq').count(
6698 IDBKeyRange.bound(
6699 digest + '::', digest + '::\uffff', false, false));
6700 countReq.onsuccess = function (e) {
6701 var count = e.target.result;
6702 if (!count) {
6703 // orphaned
6704 attStore["delete"](digest);
6705 }
6706 };
6707 });
6708 }
6709
6710 revs.forEach(function (rev$$1) {
6711 var index = seqStore.index('_doc_id_rev');
6712 var key = docId + "::" + rev$$1;
6713 index.getKey(key).onsuccess = function (e) {
6714 var seq = e.target.result;
6715 if (typeof seq !== 'number') {
6716 return checkDone();
6717 }
6718 seqStore["delete"](seq);
6719
6720 var cursor = attAndSeqStore.index('seq')
6721 .openCursor(IDBKeyRange.only(seq));
6722
6723 cursor.onsuccess = function (event) {
6724 var cursor = event.target.result;
6725 if (cursor) {
6726 var digest = cursor.value.digestSeq.split('::')[0];
6727 possiblyOrphanedDigests.push(digest);
6728 attAndSeqStore["delete"](cursor.primaryKey);
6729 cursor["continue"]();
6730 } else { // done
6731 checkDone();
6732 }
6733 };
6734 };
6735 });
6736}
6737
6738function openTransactionSafely(idb, stores, mode) {
6739 try {
6740 return {
6741 txn: idb.transaction(stores, mode)
6742 };
6743 } catch (err) {
6744 return {
6745 error: err
6746 };
6747 }
6748}
6749
6750var changesHandler = new Changes();
6751
6752function idbBulkDocs(dbOpts, req, opts, api, idb, callback) {
6753 var docInfos = req.docs;
6754 var txn;
6755 var docStore;
6756 var bySeqStore;
6757 var attachStore;
6758 var attachAndSeqStore;
6759 var metaStore;
6760 var docInfoError;
6761 var metaDoc;
6762
6763 for (var i = 0, len = docInfos.length; i < len; i++) {
6764 var doc = docInfos[i];
6765 if (doc._id && isLocalId(doc._id)) {
6766 continue;
6767 }
6768 doc = docInfos[i] = parseDoc(doc, opts.new_edits, dbOpts);
6769 if (doc.error && !docInfoError) {
6770 docInfoError = doc;
6771 }
6772 }
6773
6774 if (docInfoError) {
6775 return callback(docInfoError);
6776 }
6777
6778 var allDocsProcessed = false;
6779 var docCountDelta = 0;
6780 var results = new Array(docInfos.length);
6781 var fetchedDocs = new ExportedMap();
6782 var preconditionErrored = false;
6783 var blobType = api._meta.blobSupport ? 'blob' : 'base64';
6784
6785 preprocessAttachments(docInfos, blobType, function (err) {
6786 if (err) {
6787 return callback(err);
6788 }
6789 startTransaction();
6790 });
6791
6792 function startTransaction() {
6793
6794 var stores = [
6795 DOC_STORE, BY_SEQ_STORE,
6796 ATTACH_STORE,
6797 LOCAL_STORE, ATTACH_AND_SEQ_STORE,
6798 META_STORE
6799 ];
6800 var txnResult = openTransactionSafely(idb, stores, 'readwrite');
6801 if (txnResult.error) {
6802 return callback(txnResult.error);
6803 }
6804 txn = txnResult.txn;
6805 txn.onabort = idbError(callback);
6806 txn.ontimeout = idbError(callback);
6807 txn.oncomplete = complete;
6808 docStore = txn.objectStore(DOC_STORE);
6809 bySeqStore = txn.objectStore(BY_SEQ_STORE);
6810 attachStore = txn.objectStore(ATTACH_STORE);
6811 attachAndSeqStore = txn.objectStore(ATTACH_AND_SEQ_STORE);
6812 metaStore = txn.objectStore(META_STORE);
6813
6814 metaStore.get(META_STORE).onsuccess = function (e) {
6815 metaDoc = e.target.result;
6816 updateDocCountIfReady();
6817 };
6818
6819 verifyAttachments(function (err) {
6820 if (err) {
6821 preconditionErrored = true;
6822 return callback(err);
6823 }
6824 fetchExistingDocs();
6825 });
6826 }
6827
6828 function onAllDocsProcessed() {
6829 allDocsProcessed = true;
6830 updateDocCountIfReady();
6831 }
6832
6833 function idbProcessDocs() {
6834 processDocs(dbOpts.revs_limit, docInfos, api, fetchedDocs,
6835 txn, results, writeDoc, opts, onAllDocsProcessed);
6836 }
6837
6838 function updateDocCountIfReady() {
6839 if (!metaDoc || !allDocsProcessed) {
6840 return;
6841 }
6842 // caching the docCount saves a lot of time in allDocs() and
6843 // info(), which is why we go to all the trouble of doing this
6844 metaDoc.docCount += docCountDelta;
6845 metaStore.put(metaDoc);
6846 }
6847
6848 function fetchExistingDocs() {
6849
6850 if (!docInfos.length) {
6851 return;
6852 }
6853
6854 var numFetched = 0;
6855
6856 function checkDone() {
6857 if (++numFetched === docInfos.length) {
6858 idbProcessDocs();
6859 }
6860 }
6861
6862 function readMetadata(event) {
6863 var metadata = decodeMetadata(event.target.result);
6864
6865 if (metadata) {
6866 fetchedDocs.set(metadata.id, metadata);
6867 }
6868 checkDone();
6869 }
6870
6871 for (var i = 0, len = docInfos.length; i < len; i++) {
6872 var docInfo = docInfos[i];
6873 if (docInfo._id && isLocalId(docInfo._id)) {
6874 checkDone(); // skip local docs
6875 continue;
6876 }
6877 var req = docStore.get(docInfo.metadata.id);
6878 req.onsuccess = readMetadata;
6879 }
6880 }
6881
6882 function complete() {
6883 if (preconditionErrored) {
6884 return;
6885 }
6886
6887 changesHandler.notify(api._meta.name);
6888 callback(null, results);
6889 }
6890
6891 function verifyAttachment(digest, callback) {
6892
6893 var req = attachStore.get(digest);
6894 req.onsuccess = function (e) {
6895 if (!e.target.result) {
6896 var err = createError(MISSING_STUB,
6897 'unknown stub attachment with digest ' +
6898 digest);
6899 err.status = 412;
6900 callback(err);
6901 } else {
6902 callback();
6903 }
6904 };
6905 }
6906
6907 function verifyAttachments(finish) {
6908
6909
6910 var digests = [];
6911 docInfos.forEach(function (docInfo) {
6912 if (docInfo.data && docInfo.data._attachments) {
6913 Object.keys(docInfo.data._attachments).forEach(function (filename) {
6914 var att = docInfo.data._attachments[filename];
6915 if (att.stub) {
6916 digests.push(att.digest);
6917 }
6918 });
6919 }
6920 });
6921 if (!digests.length) {
6922 return finish();
6923 }
6924 var numDone = 0;
6925 var err;
6926
6927 function checkDone() {
6928 if (++numDone === digests.length) {
6929 finish(err);
6930 }
6931 }
6932 digests.forEach(function (digest) {
6933 verifyAttachment(digest, function (attErr) {
6934 if (attErr && !err) {
6935 err = attErr;
6936 }
6937 checkDone();
6938 });
6939 });
6940 }
6941
6942 function writeDoc(docInfo, winningRev$$1, winningRevIsDeleted, newRevIsDeleted,
6943 isUpdate, delta, resultsIdx, callback) {
6944
6945 docInfo.metadata.winningRev = winningRev$$1;
6946 docInfo.metadata.deleted = winningRevIsDeleted;
6947
6948 var doc = docInfo.data;
6949 doc._id = docInfo.metadata.id;
6950 doc._rev = docInfo.metadata.rev;
6951
6952 if (newRevIsDeleted) {
6953 doc._deleted = true;
6954 }
6955
6956 var hasAttachments = doc._attachments &&
6957 Object.keys(doc._attachments).length;
6958 if (hasAttachments) {
6959 return writeAttachments(docInfo, winningRev$$1, winningRevIsDeleted,
6960 isUpdate, resultsIdx, callback);
6961 }
6962
6963 docCountDelta += delta;
6964 updateDocCountIfReady();
6965
6966 finishDoc(docInfo, winningRev$$1, winningRevIsDeleted,
6967 isUpdate, resultsIdx, callback);
6968 }
6969
6970 function finishDoc(docInfo, winningRev$$1, winningRevIsDeleted,
6971 isUpdate, resultsIdx, callback) {
6972
6973 var doc = docInfo.data;
6974 var metadata = docInfo.metadata;
6975
6976 doc._doc_id_rev = metadata.id + '::' + metadata.rev;
6977 delete doc._id;
6978 delete doc._rev;
6979
6980 function afterPutDoc(e) {
6981 var revsToDelete = docInfo.stemmedRevs || [];
6982
6983 if (isUpdate && api.auto_compaction) {
6984 revsToDelete = revsToDelete.concat(compactTree(docInfo.metadata));
6985 }
6986
6987 if (revsToDelete && revsToDelete.length) {
6988 compactRevs(revsToDelete, docInfo.metadata.id, txn);
6989 }
6990
6991 metadata.seq = e.target.result;
6992 // Current _rev is calculated from _rev_tree on read
6993 // delete metadata.rev;
6994 var metadataToStore = encodeMetadata(metadata, winningRev$$1,
6995 winningRevIsDeleted);
6996 var metaDataReq = docStore.put(metadataToStore);
6997 metaDataReq.onsuccess = afterPutMetadata;
6998 }
6999
7000 function afterPutDocError(e) {
7001 // ConstraintError, need to update, not put (see #1638 for details)
7002 e.preventDefault(); // avoid transaction abort
7003 e.stopPropagation(); // avoid transaction onerror
7004 var index = bySeqStore.index('_doc_id_rev');
7005 var getKeyReq = index.getKey(doc._doc_id_rev);
7006 getKeyReq.onsuccess = function (e) {
7007 var putReq = bySeqStore.put(doc, e.target.result);
7008 putReq.onsuccess = afterPutDoc;
7009 };
7010 }
7011
7012 function afterPutMetadata() {
7013 results[resultsIdx] = {
7014 ok: true,
7015 id: metadata.id,
7016 rev: metadata.rev
7017 };
7018 fetchedDocs.set(docInfo.metadata.id, docInfo.metadata);
7019 insertAttachmentMappings(docInfo, metadata.seq, callback);
7020 }
7021
7022 var putReq = bySeqStore.put(doc);
7023
7024 putReq.onsuccess = afterPutDoc;
7025 putReq.onerror = afterPutDocError;
7026 }
7027
7028 function writeAttachments(docInfo, winningRev$$1, winningRevIsDeleted,
7029 isUpdate, resultsIdx, callback) {
7030
7031
7032 var doc = docInfo.data;
7033
7034 var numDone = 0;
7035 var attachments = Object.keys(doc._attachments);
7036
7037 function collectResults() {
7038 if (numDone === attachments.length) {
7039 finishDoc(docInfo, winningRev$$1, winningRevIsDeleted,
7040 isUpdate, resultsIdx, callback);
7041 }
7042 }
7043
7044 function attachmentSaved() {
7045 numDone++;
7046 collectResults();
7047 }
7048
7049 attachments.forEach(function (key) {
7050 var att = docInfo.data._attachments[key];
7051 if (!att.stub) {
7052 var data = att.data;
7053 delete att.data;
7054 att.revpos = parseInt(winningRev$$1, 10);
7055 var digest = att.digest;
7056 saveAttachment(digest, data, attachmentSaved);
7057 } else {
7058 numDone++;
7059 collectResults();
7060 }
7061 });
7062 }
7063
7064 // map seqs to attachment digests, which
7065 // we will need later during compaction
7066 function insertAttachmentMappings(docInfo, seq, callback) {
7067
7068 var attsAdded = 0;
7069 var attsToAdd = Object.keys(docInfo.data._attachments || {});
7070
7071 if (!attsToAdd.length) {
7072 return callback();
7073 }
7074
7075 function checkDone() {
7076 if (++attsAdded === attsToAdd.length) {
7077 callback();
7078 }
7079 }
7080
7081 function add(att) {
7082 var digest = docInfo.data._attachments[att].digest;
7083 var req = attachAndSeqStore.put({
7084 seq: seq,
7085 digestSeq: digest + '::' + seq
7086 });
7087
7088 req.onsuccess = checkDone;
7089 req.onerror = function (e) {
7090 // this callback is for a constaint error, which we ignore
7091 // because this docid/rev has already been associated with
7092 // the digest (e.g. when new_edits == false)
7093 e.preventDefault(); // avoid transaction abort
7094 e.stopPropagation(); // avoid transaction onerror
7095 checkDone();
7096 };
7097 }
7098 for (var i = 0; i < attsToAdd.length; i++) {
7099 add(attsToAdd[i]); // do in parallel
7100 }
7101 }
7102
7103 function saveAttachment(digest, data, callback) {
7104
7105
7106 var getKeyReq = attachStore.count(digest);
7107 getKeyReq.onsuccess = function (e) {
7108 var count = e.target.result;
7109 if (count) {
7110 return callback(); // already exists
7111 }
7112 var newAtt = {
7113 digest: digest,
7114 body: data
7115 };
7116 var putReq = attachStore.put(newAtt);
7117 putReq.onsuccess = callback;
7118 };
7119 }
7120}
7121
7122// Abstraction over IDBCursor and getAll()/getAllKeys() that allows us to batch our operations
7123// while falling back to a normal IDBCursor operation on browsers that don't support getAll() or
7124// getAllKeys(). This allows for a much faster implementation than just straight-up cursors, because
7125// we're not processing each document one-at-a-time.
7126function runBatchedCursor(objectStore, keyRange, descending, batchSize, onBatch) {
7127
7128 if (batchSize === -1) {
7129 batchSize = 1000;
7130 }
7131
7132 // Bail out of getAll()/getAllKeys() in the following cases:
7133 // 1) either method is unsupported - we need both
7134 // 2) batchSize is 1 (might as well use IDBCursor)
7135 // 3) descending – no real way to do this via getAll()/getAllKeys()
7136
7137 var useGetAll = typeof objectStore.getAll === 'function' &&
7138 typeof objectStore.getAllKeys === 'function' &&
7139 batchSize > 1 && !descending;
7140
7141 var keysBatch;
7142 var valuesBatch;
7143 var pseudoCursor;
7144
7145 function onGetAll(e) {
7146 valuesBatch = e.target.result;
7147 if (keysBatch) {
7148 onBatch(keysBatch, valuesBatch, pseudoCursor);
7149 }
7150 }
7151
7152 function onGetAllKeys(e) {
7153 keysBatch = e.target.result;
7154 if (valuesBatch) {
7155 onBatch(keysBatch, valuesBatch, pseudoCursor);
7156 }
7157 }
7158
7159 function continuePseudoCursor() {
7160 if (!keysBatch.length) { // no more results
7161 return onBatch();
7162 }
7163 // fetch next batch, exclusive start
7164 var lastKey = keysBatch[keysBatch.length - 1];
7165 var newKeyRange;
7166 if (keyRange && keyRange.upper) {
7167 try {
7168 newKeyRange = IDBKeyRange.bound(lastKey, keyRange.upper,
7169 true, keyRange.upperOpen);
7170 } catch (e) {
7171 if (e.name === "DataError" && e.code === 0) {
7172 return onBatch(); // we're done, startkey and endkey are equal
7173 }
7174 }
7175 } else {
7176 newKeyRange = IDBKeyRange.lowerBound(lastKey, true);
7177 }
7178 keyRange = newKeyRange;
7179 keysBatch = null;
7180 valuesBatch = null;
7181 objectStore.getAll(keyRange, batchSize).onsuccess = onGetAll;
7182 objectStore.getAllKeys(keyRange, batchSize).onsuccess = onGetAllKeys;
7183 }
7184
7185 function onCursor(e) {
7186 var cursor = e.target.result;
7187 if (!cursor) { // done
7188 return onBatch();
7189 }
7190 // regular IDBCursor acts like a batch where batch size is always 1
7191 onBatch([cursor.key], [cursor.value], cursor);
7192 }
7193
7194 if (useGetAll) {
7195 pseudoCursor = {"continue": continuePseudoCursor};
7196 objectStore.getAll(keyRange, batchSize).onsuccess = onGetAll;
7197 objectStore.getAllKeys(keyRange, batchSize).onsuccess = onGetAllKeys;
7198 } else if (descending) {
7199 objectStore.openCursor(keyRange, 'prev').onsuccess = onCursor;
7200 } else {
7201 objectStore.openCursor(keyRange).onsuccess = onCursor;
7202 }
7203}
7204
7205// simple shim for objectStore.getAll(), falling back to IDBCursor
7206function getAll(objectStore, keyRange, onSuccess) {
7207 if (typeof objectStore.getAll === 'function') {
7208 // use native getAll
7209 objectStore.getAll(keyRange).onsuccess = onSuccess;
7210 return;
7211 }
7212 // fall back to cursors
7213 var values = [];
7214
7215 function onCursor(e) {
7216 var cursor = e.target.result;
7217 if (cursor) {
7218 values.push(cursor.value);
7219 cursor["continue"]();
7220 } else {
7221 onSuccess({
7222 target: {
7223 result: values
7224 }
7225 });
7226 }
7227 }
7228
7229 objectStore.openCursor(keyRange).onsuccess = onCursor;
7230}
7231
7232function allDocsKeys(keys, docStore, onBatch) {
7233 // It's not guaranted to be returned in right order
7234 var valuesBatch = new Array(keys.length);
7235 var count = 0;
7236 keys.forEach(function (key, index) {
7237 docStore.get(key).onsuccess = function (event) {
7238 if (event.target.result) {
7239 valuesBatch[index] = event.target.result;
7240 } else {
7241 valuesBatch[index] = {key: key, error: 'not_found'};
7242 }
7243 count++;
7244 if (count === keys.length) {
7245 onBatch(keys, valuesBatch, {});
7246 }
7247 };
7248 });
7249}
7250
7251function createKeyRange(start, end, inclusiveEnd, key, descending) {
7252 try {
7253 if (start && end) {
7254 if (descending) {
7255 return IDBKeyRange.bound(end, start, !inclusiveEnd, false);
7256 } else {
7257 return IDBKeyRange.bound(start, end, false, !inclusiveEnd);
7258 }
7259 } else if (start) {
7260 if (descending) {
7261 return IDBKeyRange.upperBound(start);
7262 } else {
7263 return IDBKeyRange.lowerBound(start);
7264 }
7265 } else if (end) {
7266 if (descending) {
7267 return IDBKeyRange.lowerBound(end, !inclusiveEnd);
7268 } else {
7269 return IDBKeyRange.upperBound(end, !inclusiveEnd);
7270 }
7271 } else if (key) {
7272 return IDBKeyRange.only(key);
7273 }
7274 } catch (e) {
7275 return {error: e};
7276 }
7277 return null;
7278}
7279
7280function idbAllDocs(opts, idb, callback) {
7281 var start = 'startkey' in opts ? opts.startkey : false;
7282 var end = 'endkey' in opts ? opts.endkey : false;
7283 var key = 'key' in opts ? opts.key : false;
7284 var keys = 'keys' in opts ? opts.keys : false;
7285 var skip = opts.skip || 0;
7286 var limit = typeof opts.limit === 'number' ? opts.limit : -1;
7287 var inclusiveEnd = opts.inclusive_end !== false;
7288
7289 var keyRange ;
7290 var keyRangeError;
7291 if (!keys) {
7292 keyRange = createKeyRange(start, end, inclusiveEnd, key, opts.descending);
7293 keyRangeError = keyRange && keyRange.error;
7294 if (keyRangeError &&
7295 !(keyRangeError.name === "DataError" && keyRangeError.code === 0)) {
7296 // DataError with error code 0 indicates start is less than end, so
7297 // can just do an empty query. Else need to throw
7298 return callback(createError(IDB_ERROR,
7299 keyRangeError.name, keyRangeError.message));
7300 }
7301 }
7302
7303 var stores = [DOC_STORE, BY_SEQ_STORE, META_STORE];
7304
7305 if (opts.attachments) {
7306 stores.push(ATTACH_STORE);
7307 }
7308 var txnResult = openTransactionSafely(idb, stores, 'readonly');
7309 if (txnResult.error) {
7310 return callback(txnResult.error);
7311 }
7312 var txn = txnResult.txn;
7313 txn.oncomplete = onTxnComplete;
7314 txn.onabort = idbError(callback);
7315 var docStore = txn.objectStore(DOC_STORE);
7316 var seqStore = txn.objectStore(BY_SEQ_STORE);
7317 var metaStore = txn.objectStore(META_STORE);
7318 var docIdRevIndex = seqStore.index('_doc_id_rev');
7319 var results = [];
7320 var docCount;
7321 var updateSeq;
7322
7323 metaStore.get(META_STORE).onsuccess = function (e) {
7324 docCount = e.target.result.docCount;
7325 };
7326
7327 /* istanbul ignore if */
7328 if (opts.update_seq) {
7329 getMaxUpdateSeq(seqStore, function (e) {
7330 if (e.target.result && e.target.result.length > 0) {
7331 updateSeq = e.target.result[0];
7332 }
7333 });
7334 }
7335
7336 function getMaxUpdateSeq(objectStore, onSuccess) {
7337 function onCursor(e) {
7338 var cursor = e.target.result;
7339 var maxKey = undefined;
7340 if (cursor && cursor.key) {
7341 maxKey = cursor.key;
7342 }
7343 return onSuccess({
7344 target: {
7345 result: [maxKey]
7346 }
7347 });
7348 }
7349 objectStore.openCursor(null, 'prev').onsuccess = onCursor;
7350 }
7351
7352 // if the user specifies include_docs=true, then we don't
7353 // want to block the main cursor while we're fetching the doc
7354 function fetchDocAsynchronously(metadata, row, winningRev$$1) {
7355 var key = metadata.id + "::" + winningRev$$1;
7356 docIdRevIndex.get(key).onsuccess = function onGetDoc(e) {
7357 row.doc = decodeDoc(e.target.result) || {};
7358 if (opts.conflicts) {
7359 var conflicts = collectConflicts(metadata);
7360 if (conflicts.length) {
7361 row.doc._conflicts = conflicts;
7362 }
7363 }
7364 fetchAttachmentsIfNecessary(row.doc, opts, txn);
7365 };
7366 }
7367
7368 function allDocsInner(winningRev$$1, metadata) {
7369 var row = {
7370 id: metadata.id,
7371 key: metadata.id,
7372 value: {
7373 rev: winningRev$$1
7374 }
7375 };
7376 var deleted = metadata.deleted;
7377 if (deleted) {
7378 if (keys) {
7379 results.push(row);
7380 // deleted docs are okay with "keys" requests
7381 row.value.deleted = true;
7382 row.doc = null;
7383 }
7384 } else if (skip-- <= 0) {
7385 results.push(row);
7386 if (opts.include_docs) {
7387 fetchDocAsynchronously(metadata, row, winningRev$$1);
7388 }
7389 }
7390 }
7391
7392 function processBatch(batchValues) {
7393 for (var i = 0, len = batchValues.length; i < len; i++) {
7394 if (results.length === limit) {
7395 break;
7396 }
7397 var batchValue = batchValues[i];
7398 if (batchValue.error && keys) {
7399 // key was not found with "keys" requests
7400 results.push(batchValue);
7401 continue;
7402 }
7403 var metadata = decodeMetadata(batchValue);
7404 var winningRev$$1 = metadata.winningRev;
7405 allDocsInner(winningRev$$1, metadata);
7406 }
7407 }
7408
7409 function onBatch(batchKeys, batchValues, cursor) {
7410 if (!cursor) {
7411 return;
7412 }
7413 processBatch(batchValues);
7414 if (results.length < limit) {
7415 cursor["continue"]();
7416 }
7417 }
7418
7419 function onGetAll(e) {
7420 var values = e.target.result;
7421 if (opts.descending) {
7422 values = values.reverse();
7423 }
7424 processBatch(values);
7425 }
7426
7427 function onResultsReady() {
7428 var returnVal = {
7429 total_rows: docCount,
7430 offset: opts.skip,
7431 rows: results
7432 };
7433
7434 /* istanbul ignore if */
7435 if (opts.update_seq && updateSeq !== undefined) {
7436 returnVal.update_seq = updateSeq;
7437 }
7438 callback(null, returnVal);
7439 }
7440
7441 function onTxnComplete() {
7442 if (opts.attachments) {
7443 postProcessAttachments(results, opts.binary).then(onResultsReady);
7444 } else {
7445 onResultsReady();
7446 }
7447 }
7448
7449 // don't bother doing any requests if start > end or limit === 0
7450 if (keyRangeError || limit === 0) {
7451 return;
7452 }
7453 if (keys) {
7454 return allDocsKeys(opts.keys, docStore, onBatch);
7455 }
7456 if (limit === -1) { // just fetch everything
7457 return getAll(docStore, keyRange, onGetAll);
7458 }
7459 // else do a cursor
7460 // choose a batch size based on the skip, since we'll need to skip that many
7461 runBatchedCursor(docStore, keyRange, opts.descending, limit + skip, onBatch);
7462}
7463
7464//
7465// Blobs are not supported in all versions of IndexedDB, notably
7466// Chrome <37 and Android <5. In those versions, storing a blob will throw.
7467//
7468// Various other blob bugs exist in Chrome v37-42 (inclusive).
7469// Detecting them is expensive and confusing to users, and Chrome 37-42
7470// is at very low usage worldwide, so we do a hacky userAgent check instead.
7471//
7472// content-type bug: https://code.google.com/p/chromium/issues/detail?id=408120
7473// 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916
7474// FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836
7475//
7476function checkBlobSupport(txn) {
7477 return new Promise(function (resolve) {
7478 var blob$$1 = createBlob(['']);
7479 var req = txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob$$1, 'key');
7480
7481 req.onsuccess = function () {
7482 var matchedChrome = navigator.userAgent.match(/Chrome\/(\d+)/);
7483 var matchedEdge = navigator.userAgent.match(/Edge\//);
7484 // MS Edge pretends to be Chrome 42:
7485 // https://msdn.microsoft.com/en-us/library/hh869301%28v=vs.85%29.aspx
7486 resolve(matchedEdge || !matchedChrome ||
7487 parseInt(matchedChrome[1], 10) >= 43);
7488 };
7489
7490 req.onerror = txn.onabort = function (e) {
7491 // If the transaction aborts now its due to not being able to
7492 // write to the database, likely due to the disk being full
7493 e.preventDefault();
7494 e.stopPropagation();
7495 resolve(false);
7496 };
7497 })["catch"](function () {
7498 return false; // error, so assume unsupported
7499 });
7500}
7501
7502function countDocs(txn, cb) {
7503 var index = txn.objectStore(DOC_STORE).index('deletedOrLocal');
7504 index.count(IDBKeyRange.only('0')).onsuccess = function (e) {
7505 cb(e.target.result);
7506 };
7507}
7508
7509// This task queue ensures that IDB open calls are done in their own tick
7510
7511var running = false;
7512var queue = [];
7513
7514function tryCode(fun, err, res, PouchDB) {
7515 try {
7516 fun(err, res);
7517 } catch (err) {
7518 // Shouldn't happen, but in some odd cases
7519 // IndexedDB implementations might throw a sync
7520 // error, in which case this will at least log it.
7521 PouchDB.emit('error', err);
7522 }
7523}
7524
7525function applyNext() {
7526 if (running || !queue.length) {
7527 return;
7528 }
7529 running = true;
7530 queue.shift()();
7531}
7532
7533function enqueueTask(action, callback, PouchDB) {
7534 queue.push(function runAction() {
7535 action(function runCallback(err, res) {
7536 tryCode(callback, err, res, PouchDB);
7537 running = false;
7538 immediate(function runNext() {
7539 applyNext(PouchDB);
7540 });
7541 });
7542 });
7543 applyNext();
7544}
7545
7546function changes(opts, api, dbName, idb) {
7547 opts = clone(opts);
7548
7549 if (opts.continuous) {
7550 var id = dbName + ':' + uuid();
7551 changesHandler.addListener(dbName, id, api, opts);
7552 changesHandler.notify(dbName);
7553 return {
7554 cancel: function () {
7555 changesHandler.removeListener(dbName, id);
7556 }
7557 };
7558 }
7559
7560 var docIds = opts.doc_ids && new ExportedSet(opts.doc_ids);
7561
7562 opts.since = opts.since || 0;
7563 var lastSeq = opts.since;
7564
7565 var limit = 'limit' in opts ? opts.limit : -1;
7566 if (limit === 0) {
7567 limit = 1; // per CouchDB _changes spec
7568 }
7569
7570 var results = [];
7571 var numResults = 0;
7572 var filter = filterChange(opts);
7573 var docIdsToMetadata = new ExportedMap();
7574
7575 var txn;
7576 var bySeqStore;
7577 var docStore;
7578 var docIdRevIndex;
7579
7580 function onBatch(batchKeys, batchValues, cursor) {
7581 if (!cursor || !batchKeys.length) { // done
7582 return;
7583 }
7584
7585 var winningDocs = new Array(batchKeys.length);
7586 var metadatas = new Array(batchKeys.length);
7587
7588 function processMetadataAndWinningDoc(metadata, winningDoc) {
7589 var change = opts.processChange(winningDoc, metadata, opts);
7590 lastSeq = change.seq = metadata.seq;
7591
7592 var filtered = filter(change);
7593 if (typeof filtered === 'object') { // anything but true/false indicates error
7594 return Promise.reject(filtered);
7595 }
7596
7597 if (!filtered) {
7598 return Promise.resolve();
7599 }
7600 numResults++;
7601 if (opts.return_docs) {
7602 results.push(change);
7603 }
7604 // process the attachment immediately
7605 // for the benefit of live listeners
7606 if (opts.attachments && opts.include_docs) {
7607 return new Promise(function (resolve) {
7608 fetchAttachmentsIfNecessary(winningDoc, opts, txn, function () {
7609 postProcessAttachments([change], opts.binary).then(function () {
7610 resolve(change);
7611 });
7612 });
7613 });
7614 } else {
7615 return Promise.resolve(change);
7616 }
7617 }
7618
7619 function onBatchDone() {
7620 var promises = [];
7621 for (var i = 0, len = winningDocs.length; i < len; i++) {
7622 if (numResults === limit) {
7623 break;
7624 }
7625 var winningDoc = winningDocs[i];
7626 if (!winningDoc) {
7627 continue;
7628 }
7629 var metadata = metadatas[i];
7630 promises.push(processMetadataAndWinningDoc(metadata, winningDoc));
7631 }
7632
7633 Promise.all(promises).then(function (changes) {
7634 for (var i = 0, len = changes.length; i < len; i++) {
7635 if (changes[i]) {
7636 opts.onChange(changes[i]);
7637 }
7638 }
7639 })["catch"](opts.complete);
7640
7641 if (numResults !== limit) {
7642 cursor["continue"]();
7643 }
7644 }
7645
7646 // Fetch all metadatas/winningdocs from this batch in parallel, then process
7647 // them all only once all data has been collected. This is done in parallel
7648 // because it's faster than doing it one-at-a-time.
7649 var numDone = 0;
7650 batchValues.forEach(function (value, i) {
7651 var doc = decodeDoc(value);
7652 var seq = batchKeys[i];
7653 fetchWinningDocAndMetadata(doc, seq, function (metadata, winningDoc) {
7654 metadatas[i] = metadata;
7655 winningDocs[i] = winningDoc;
7656 if (++numDone === batchKeys.length) {
7657 onBatchDone();
7658 }
7659 });
7660 });
7661 }
7662
7663 function onGetMetadata(doc, seq, metadata, cb) {
7664 if (metadata.seq !== seq) {
7665 // some other seq is later
7666 return cb();
7667 }
7668
7669 if (metadata.winningRev === doc._rev) {
7670 // this is the winning doc
7671 return cb(metadata, doc);
7672 }
7673
7674 // fetch winning doc in separate request
7675 var docIdRev = doc._id + '::' + metadata.winningRev;
7676 var req = docIdRevIndex.get(docIdRev);
7677 req.onsuccess = function (e) {
7678 cb(metadata, decodeDoc(e.target.result));
7679 };
7680 }
7681
7682 function fetchWinningDocAndMetadata(doc, seq, cb) {
7683 if (docIds && !docIds.has(doc._id)) {
7684 return cb();
7685 }
7686
7687 var metadata = docIdsToMetadata.get(doc._id);
7688 if (metadata) { // cached
7689 return onGetMetadata(doc, seq, metadata, cb);
7690 }
7691 // metadata not cached, have to go fetch it
7692 docStore.get(doc._id).onsuccess = function (e) {
7693 metadata = decodeMetadata(e.target.result);
7694 docIdsToMetadata.set(doc._id, metadata);
7695 onGetMetadata(doc, seq, metadata, cb);
7696 };
7697 }
7698
7699 function finish() {
7700 opts.complete(null, {
7701 results: results,
7702 last_seq: lastSeq
7703 });
7704 }
7705
7706 function onTxnComplete() {
7707 if (!opts.continuous && opts.attachments) {
7708 // cannot guarantee that postProcessing was already done,
7709 // so do it again
7710 postProcessAttachments(results).then(finish);
7711 } else {
7712 finish();
7713 }
7714 }
7715
7716 var objectStores = [DOC_STORE, BY_SEQ_STORE];
7717 if (opts.attachments) {
7718 objectStores.push(ATTACH_STORE);
7719 }
7720 var txnResult = openTransactionSafely(idb, objectStores, 'readonly');
7721 if (txnResult.error) {
7722 return opts.complete(txnResult.error);
7723 }
7724 txn = txnResult.txn;
7725 txn.onabort = idbError(opts.complete);
7726 txn.oncomplete = onTxnComplete;
7727
7728 bySeqStore = txn.objectStore(BY_SEQ_STORE);
7729 docStore = txn.objectStore(DOC_STORE);
7730 docIdRevIndex = bySeqStore.index('_doc_id_rev');
7731
7732 var keyRange = (opts.since && !opts.descending) ?
7733 IDBKeyRange.lowerBound(opts.since, true) : null;
7734
7735 runBatchedCursor(bySeqStore, keyRange, opts.descending, limit, onBatch);
7736}
7737
7738var cachedDBs = new ExportedMap();
7739var blobSupportPromise;
7740var openReqList = new ExportedMap();
7741
7742function IdbPouch(opts, callback) {
7743 var api = this;
7744
7745 enqueueTask(function (thisCallback) {
7746 init(api, opts, thisCallback);
7747 }, callback, api.constructor);
7748}
7749
7750function init(api, opts, callback) {
7751
7752 var dbName = opts.name;
7753
7754 var idb = null;
7755 api._meta = null;
7756
7757 // called when creating a fresh new database
7758 function createSchema(db) {
7759 var docStore = db.createObjectStore(DOC_STORE, {keyPath : 'id'});
7760 db.createObjectStore(BY_SEQ_STORE, {autoIncrement: true})
7761 .createIndex('_doc_id_rev', '_doc_id_rev', {unique: true});
7762 db.createObjectStore(ATTACH_STORE, {keyPath: 'digest'});
7763 db.createObjectStore(META_STORE, {keyPath: 'id', autoIncrement: false});
7764 db.createObjectStore(DETECT_BLOB_SUPPORT_STORE);
7765
7766 // added in v2
7767 docStore.createIndex('deletedOrLocal', 'deletedOrLocal', {unique : false});
7768
7769 // added in v3
7770 db.createObjectStore(LOCAL_STORE, {keyPath: '_id'});
7771
7772 // added in v4
7773 var attAndSeqStore = db.createObjectStore(ATTACH_AND_SEQ_STORE,
7774 {autoIncrement: true});
7775 attAndSeqStore.createIndex('seq', 'seq');
7776 attAndSeqStore.createIndex('digestSeq', 'digestSeq', {unique: true});
7777 }
7778
7779 // migration to version 2
7780 // unfortunately "deletedOrLocal" is a misnomer now that we no longer
7781 // store local docs in the main doc-store, but whaddyagonnado
7782 function addDeletedOrLocalIndex(txn, callback) {
7783 var docStore = txn.objectStore(DOC_STORE);
7784 docStore.createIndex('deletedOrLocal', 'deletedOrLocal', {unique : false});
7785
7786 docStore.openCursor().onsuccess = function (event) {
7787 var cursor = event.target.result;
7788 if (cursor) {
7789 var metadata = cursor.value;
7790 var deleted = isDeleted(metadata);
7791 metadata.deletedOrLocal = deleted ? "1" : "0";
7792 docStore.put(metadata);
7793 cursor["continue"]();
7794 } else {
7795 callback();
7796 }
7797 };
7798 }
7799
7800 // migration to version 3 (part 1)
7801 function createLocalStoreSchema(db) {
7802 db.createObjectStore(LOCAL_STORE, {keyPath: '_id'})
7803 .createIndex('_doc_id_rev', '_doc_id_rev', {unique: true});
7804 }
7805
7806 // migration to version 3 (part 2)
7807 function migrateLocalStore(txn, cb) {
7808 var localStore = txn.objectStore(LOCAL_STORE);
7809 var docStore = txn.objectStore(DOC_STORE);
7810 var seqStore = txn.objectStore(BY_SEQ_STORE);
7811
7812 var cursor = docStore.openCursor();
7813 cursor.onsuccess = function (event) {
7814 var cursor = event.target.result;
7815 if (cursor) {
7816 var metadata = cursor.value;
7817 var docId = metadata.id;
7818 var local = isLocalId(docId);
7819 var rev$$1 = winningRev(metadata);
7820 if (local) {
7821 var docIdRev = docId + "::" + rev$$1;
7822 // remove all seq entries
7823 // associated with this docId
7824 var start = docId + "::";
7825 var end = docId + "::~";
7826 var index = seqStore.index('_doc_id_rev');
7827 var range = IDBKeyRange.bound(start, end, false, false);
7828 var seqCursor = index.openCursor(range);
7829 seqCursor.onsuccess = function (e) {
7830 seqCursor = e.target.result;
7831 if (!seqCursor) {
7832 // done
7833 docStore["delete"](cursor.primaryKey);
7834 cursor["continue"]();
7835 } else {
7836 var data = seqCursor.value;
7837 if (data._doc_id_rev === docIdRev) {
7838 localStore.put(data);
7839 }
7840 seqStore["delete"](seqCursor.primaryKey);
7841 seqCursor["continue"]();
7842 }
7843 };
7844 } else {
7845 cursor["continue"]();
7846 }
7847 } else if (cb) {
7848 cb();
7849 }
7850 };
7851 }
7852
7853 // migration to version 4 (part 1)
7854 function addAttachAndSeqStore(db) {
7855 var attAndSeqStore = db.createObjectStore(ATTACH_AND_SEQ_STORE,
7856 {autoIncrement: true});
7857 attAndSeqStore.createIndex('seq', 'seq');
7858 attAndSeqStore.createIndex('digestSeq', 'digestSeq', {unique: true});
7859 }
7860
7861 // migration to version 4 (part 2)
7862 function migrateAttsAndSeqs(txn, callback) {
7863 var seqStore = txn.objectStore(BY_SEQ_STORE);
7864 var attStore = txn.objectStore(ATTACH_STORE);
7865 var attAndSeqStore = txn.objectStore(ATTACH_AND_SEQ_STORE);
7866
7867 // need to actually populate the table. this is the expensive part,
7868 // so as an optimization, check first that this database even
7869 // contains attachments
7870 var req = attStore.count();
7871 req.onsuccess = function (e) {
7872 var count = e.target.result;
7873 if (!count) {
7874 return callback(); // done
7875 }
7876
7877 seqStore.openCursor().onsuccess = function (e) {
7878 var cursor = e.target.result;
7879 if (!cursor) {
7880 return callback(); // done
7881 }
7882 var doc = cursor.value;
7883 var seq = cursor.primaryKey;
7884 var atts = Object.keys(doc._attachments || {});
7885 var digestMap = {};
7886 for (var j = 0; j < atts.length; j++) {
7887 var att = doc._attachments[atts[j]];
7888 digestMap[att.digest] = true; // uniq digests, just in case
7889 }
7890 var digests = Object.keys(digestMap);
7891 for (j = 0; j < digests.length; j++) {
7892 var digest = digests[j];
7893 attAndSeqStore.put({
7894 seq: seq,
7895 digestSeq: digest + '::' + seq
7896 });
7897 }
7898 cursor["continue"]();
7899 };
7900 };
7901 }
7902
7903 // migration to version 5
7904 // Instead of relying on on-the-fly migration of metadata,
7905 // this brings the doc-store to its modern form:
7906 // - metadata.winningrev
7907 // - metadata.seq
7908 // - stringify the metadata when storing it
7909 function migrateMetadata(txn) {
7910
7911 function decodeMetadataCompat(storedObject) {
7912 if (!storedObject.data) {
7913 // old format, when we didn't store it stringified
7914 storedObject.deleted = storedObject.deletedOrLocal === '1';
7915 return storedObject;
7916 }
7917 return decodeMetadata(storedObject);
7918 }
7919
7920 // ensure that every metadata has a winningRev and seq,
7921 // which was previously created on-the-fly but better to migrate
7922 var bySeqStore = txn.objectStore(BY_SEQ_STORE);
7923 var docStore = txn.objectStore(DOC_STORE);
7924 var cursor = docStore.openCursor();
7925 cursor.onsuccess = function (e) {
7926 var cursor = e.target.result;
7927 if (!cursor) {
7928 return; // done
7929 }
7930 var metadata = decodeMetadataCompat(cursor.value);
7931
7932 metadata.winningRev = metadata.winningRev ||
7933 winningRev(metadata);
7934
7935 function fetchMetadataSeq() {
7936 // metadata.seq was added post-3.2.0, so if it's missing,
7937 // we need to fetch it manually
7938 var start = metadata.id + '::';
7939 var end = metadata.id + '::\uffff';
7940 var req = bySeqStore.index('_doc_id_rev').openCursor(
7941 IDBKeyRange.bound(start, end));
7942
7943 var metadataSeq = 0;
7944 req.onsuccess = function (e) {
7945 var cursor = e.target.result;
7946 if (!cursor) {
7947 metadata.seq = metadataSeq;
7948 return onGetMetadataSeq();
7949 }
7950 var seq = cursor.primaryKey;
7951 if (seq > metadataSeq) {
7952 metadataSeq = seq;
7953 }
7954 cursor["continue"]();
7955 };
7956 }
7957
7958 function onGetMetadataSeq() {
7959 var metadataToStore = encodeMetadata(metadata,
7960 metadata.winningRev, metadata.deleted);
7961
7962 var req = docStore.put(metadataToStore);
7963 req.onsuccess = function () {
7964 cursor["continue"]();
7965 };
7966 }
7967
7968 if (metadata.seq) {
7969 return onGetMetadataSeq();
7970 }
7971
7972 fetchMetadataSeq();
7973 };
7974
7975 }
7976
7977 api._remote = false;
7978 api.type = function () {
7979 return 'idb';
7980 };
7981
7982 api._id = toPromise(function (callback) {
7983 callback(null, api._meta.instanceId);
7984 });
7985
7986 api._bulkDocs = function idb_bulkDocs(req, reqOpts, callback) {
7987 idbBulkDocs(opts, req, reqOpts, api, idb, callback);
7988 };
7989
7990 // First we look up the metadata in the ids database, then we fetch the
7991 // current revision(s) from the by sequence store
7992 api._get = function idb_get(id, opts, callback) {
7993 var doc;
7994 var metadata;
7995 var err;
7996 var txn = opts.ctx;
7997 if (!txn) {
7998 var txnResult = openTransactionSafely(idb,
7999 [DOC_STORE, BY_SEQ_STORE, ATTACH_STORE], 'readonly');
8000 if (txnResult.error) {
8001 return callback(txnResult.error);
8002 }
8003 txn = txnResult.txn;
8004 }
8005
8006 function finish() {
8007 callback(err, {doc: doc, metadata: metadata, ctx: txn});
8008 }
8009
8010 txn.objectStore(DOC_STORE).get(id).onsuccess = function (e) {
8011 metadata = decodeMetadata(e.target.result);
8012 // we can determine the result here if:
8013 // 1. there is no such document
8014 // 2. the document is deleted and we don't ask about specific rev
8015 // When we ask with opts.rev we expect the answer to be either
8016 // doc (possibly with _deleted=true) or missing error
8017 if (!metadata) {
8018 err = createError(MISSING_DOC, 'missing');
8019 return finish();
8020 }
8021
8022 var rev$$1;
8023 if (!opts.rev) {
8024 rev$$1 = metadata.winningRev;
8025 var deleted = isDeleted(metadata);
8026 if (deleted) {
8027 err = createError(MISSING_DOC, "deleted");
8028 return finish();
8029 }
8030 } else {
8031 rev$$1 = opts.latest ? latest(opts.rev, metadata) : opts.rev;
8032 }
8033
8034 var objectStore = txn.objectStore(BY_SEQ_STORE);
8035 var key = metadata.id + '::' + rev$$1;
8036
8037 objectStore.index('_doc_id_rev').get(key).onsuccess = function (e) {
8038 doc = e.target.result;
8039 if (doc) {
8040 doc = decodeDoc(doc);
8041 }
8042 if (!doc) {
8043 err = createError(MISSING_DOC, 'missing');
8044 return finish();
8045 }
8046 finish();
8047 };
8048 };
8049 };
8050
8051 api._getAttachment = function (docId, attachId, attachment, opts, callback) {
8052 var txn;
8053 if (opts.ctx) {
8054 txn = opts.ctx;
8055 } else {
8056 var txnResult = openTransactionSafely(idb,
8057 [DOC_STORE, BY_SEQ_STORE, ATTACH_STORE], 'readonly');
8058 if (txnResult.error) {
8059 return callback(txnResult.error);
8060 }
8061 txn = txnResult.txn;
8062 }
8063 var digest = attachment.digest;
8064 var type = attachment.content_type;
8065
8066 txn.objectStore(ATTACH_STORE).get(digest).onsuccess = function (e) {
8067 var body = e.target.result.body;
8068 readBlobData(body, type, opts.binary, function (blobData) {
8069 callback(null, blobData);
8070 });
8071 };
8072 };
8073
8074 api._info = function idb_info(callback) {
8075 var updateSeq;
8076 var docCount;
8077
8078 var txnResult = openTransactionSafely(idb, [META_STORE, BY_SEQ_STORE], 'readonly');
8079 if (txnResult.error) {
8080 return callback(txnResult.error);
8081 }
8082 var txn = txnResult.txn;
8083 txn.objectStore(META_STORE).get(META_STORE).onsuccess = function (e) {
8084 docCount = e.target.result.docCount;
8085 };
8086 txn.objectStore(BY_SEQ_STORE).openCursor(null, 'prev').onsuccess = function (e) {
8087 var cursor = e.target.result;
8088 updateSeq = cursor ? cursor.key : 0;
8089 };
8090
8091 txn.oncomplete = function () {
8092 callback(null, {
8093 doc_count: docCount,
8094 update_seq: updateSeq,
8095 // for debugging
8096 idb_attachment_format: (api._meta.blobSupport ? 'binary' : 'base64')
8097 });
8098 };
8099 };
8100
8101 api._allDocs = function idb_allDocs(opts, callback) {
8102 idbAllDocs(opts, idb, callback);
8103 };
8104
8105 api._changes = function idbChanges(opts) {
8106 return changes(opts, api, dbName, idb);
8107 };
8108
8109 api._close = function (callback) {
8110 // https://developer.mozilla.org/en-US/docs/IndexedDB/IDBDatabase#close
8111 // "Returns immediately and closes the connection in a separate thread..."
8112 idb.close();
8113 cachedDBs["delete"](dbName);
8114 callback();
8115 };
8116
8117 api._getRevisionTree = function (docId, callback) {
8118 var txnResult = openTransactionSafely(idb, [DOC_STORE], 'readonly');
8119 if (txnResult.error) {
8120 return callback(txnResult.error);
8121 }
8122 var txn = txnResult.txn;
8123 var req = txn.objectStore(DOC_STORE).get(docId);
8124 req.onsuccess = function (event) {
8125 var doc = decodeMetadata(event.target.result);
8126 if (!doc) {
8127 callback(createError(MISSING_DOC));
8128 } else {
8129 callback(null, doc.rev_tree);
8130 }
8131 };
8132 };
8133
8134 // This function removes revisions of document docId
8135 // which are listed in revs and sets this document
8136 // revision to to rev_tree
8137 api._doCompaction = function (docId, revs, callback) {
8138 var stores = [
8139 DOC_STORE,
8140 BY_SEQ_STORE,
8141 ATTACH_STORE,
8142 ATTACH_AND_SEQ_STORE
8143 ];
8144 var txnResult = openTransactionSafely(idb, stores, 'readwrite');
8145 if (txnResult.error) {
8146 return callback(txnResult.error);
8147 }
8148 var txn = txnResult.txn;
8149
8150 var docStore = txn.objectStore(DOC_STORE);
8151
8152 docStore.get(docId).onsuccess = function (event) {
8153 var metadata = decodeMetadata(event.target.result);
8154 traverseRevTree(metadata.rev_tree, function (isLeaf, pos,
8155 revHash, ctx, opts) {
8156 var rev$$1 = pos + '-' + revHash;
8157 if (revs.indexOf(rev$$1) !== -1) {
8158 opts.status = 'missing';
8159 }
8160 });
8161 compactRevs(revs, docId, txn);
8162 var winningRev$$1 = metadata.winningRev;
8163 var deleted = metadata.deleted;
8164 txn.objectStore(DOC_STORE).put(
8165 encodeMetadata(metadata, winningRev$$1, deleted));
8166 };
8167 txn.onabort = idbError(callback);
8168 txn.oncomplete = function () {
8169 callback();
8170 };
8171 };
8172
8173
8174 api._getLocal = function (id, callback) {
8175 var txnResult = openTransactionSafely(idb, [LOCAL_STORE], 'readonly');
8176 if (txnResult.error) {
8177 return callback(txnResult.error);
8178 }
8179 var tx = txnResult.txn;
8180 var req = tx.objectStore(LOCAL_STORE).get(id);
8181
8182 req.onerror = idbError(callback);
8183 req.onsuccess = function (e) {
8184 var doc = e.target.result;
8185 if (!doc) {
8186 callback(createError(MISSING_DOC));
8187 } else {
8188 delete doc['_doc_id_rev']; // for backwards compat
8189 callback(null, doc);
8190 }
8191 };
8192 };
8193
8194 api._putLocal = function (doc, opts, callback) {
8195 if (typeof opts === 'function') {
8196 callback = opts;
8197 opts = {};
8198 }
8199 delete doc._revisions; // ignore this, trust the rev
8200 var oldRev = doc._rev;
8201 var id = doc._id;
8202 if (!oldRev) {
8203 doc._rev = '0-1';
8204 } else {
8205 doc._rev = '0-' + (parseInt(oldRev.split('-')[1], 10) + 1);
8206 }
8207
8208 var tx = opts.ctx;
8209 var ret;
8210 if (!tx) {
8211 var txnResult = openTransactionSafely(idb, [LOCAL_STORE], 'readwrite');
8212 if (txnResult.error) {
8213 return callback(txnResult.error);
8214 }
8215 tx = txnResult.txn;
8216 tx.onerror = idbError(callback);
8217 tx.oncomplete = function () {
8218 if (ret) {
8219 callback(null, ret);
8220 }
8221 };
8222 }
8223
8224 var oStore = tx.objectStore(LOCAL_STORE);
8225 var req;
8226 if (oldRev) {
8227 req = oStore.get(id);
8228 req.onsuccess = function (e) {
8229 var oldDoc = e.target.result;
8230 if (!oldDoc || oldDoc._rev !== oldRev) {
8231 callback(createError(REV_CONFLICT));
8232 } else { // update
8233 var req = oStore.put(doc);
8234 req.onsuccess = function () {
8235 ret = {ok: true, id: doc._id, rev: doc._rev};
8236 if (opts.ctx) { // return immediately
8237 callback(null, ret);
8238 }
8239 };
8240 }
8241 };
8242 } else { // new doc
8243 req = oStore.add(doc);
8244 req.onerror = function (e) {
8245 // constraint error, already exists
8246 callback(createError(REV_CONFLICT));
8247 e.preventDefault(); // avoid transaction abort
8248 e.stopPropagation(); // avoid transaction onerror
8249 };
8250 req.onsuccess = function () {
8251 ret = {ok: true, id: doc._id, rev: doc._rev};
8252 if (opts.ctx) { // return immediately
8253 callback(null, ret);
8254 }
8255 };
8256 }
8257 };
8258
8259 api._removeLocal = function (doc, opts, callback) {
8260 if (typeof opts === 'function') {
8261 callback = opts;
8262 opts = {};
8263 }
8264 var tx = opts.ctx;
8265 if (!tx) {
8266 var txnResult = openTransactionSafely(idb, [LOCAL_STORE], 'readwrite');
8267 if (txnResult.error) {
8268 return callback(txnResult.error);
8269 }
8270 tx = txnResult.txn;
8271 tx.oncomplete = function () {
8272 if (ret) {
8273 callback(null, ret);
8274 }
8275 };
8276 }
8277 var ret;
8278 var id = doc._id;
8279 var oStore = tx.objectStore(LOCAL_STORE);
8280 var req = oStore.get(id);
8281
8282 req.onerror = idbError(callback);
8283 req.onsuccess = function (e) {
8284 var oldDoc = e.target.result;
8285 if (!oldDoc || oldDoc._rev !== doc._rev) {
8286 callback(createError(MISSING_DOC));
8287 } else {
8288 oStore["delete"](id);
8289 ret = {ok: true, id: id, rev: '0-0'};
8290 if (opts.ctx) { // return immediately
8291 callback(null, ret);
8292 }
8293 }
8294 };
8295 };
8296
8297 api._destroy = function (opts, callback) {
8298 changesHandler.removeAllListeners(dbName);
8299
8300 //Close open request for "dbName" database to fix ie delay.
8301 var openReq = openReqList.get(dbName);
8302 if (openReq && openReq.result) {
8303 openReq.result.close();
8304 cachedDBs["delete"](dbName);
8305 }
8306 var req = indexedDB.deleteDatabase(dbName);
8307
8308 req.onsuccess = function () {
8309 //Remove open request from the list.
8310 openReqList["delete"](dbName);
8311 if (hasLocalStorage() && (dbName in localStorage)) {
8312 delete localStorage[dbName];
8313 }
8314 callback(null, { 'ok': true });
8315 };
8316
8317 req.onerror = idbError(callback);
8318 };
8319
8320 var cached = cachedDBs.get(dbName);
8321
8322 if (cached) {
8323 idb = cached.idb;
8324 api._meta = cached.global;
8325 return immediate(function () {
8326 callback(null, api);
8327 });
8328 }
8329
8330 var req = indexedDB.open(dbName, ADAPTER_VERSION);
8331 openReqList.set(dbName, req);
8332
8333 req.onupgradeneeded = function (e) {
8334 var db = e.target.result;
8335 if (e.oldVersion < 1) {
8336 return createSchema(db); // new db, initial schema
8337 }
8338 // do migrations
8339
8340 var txn = e.currentTarget.transaction;
8341 // these migrations have to be done in this function, before
8342 // control is returned to the event loop, because IndexedDB
8343
8344 if (e.oldVersion < 3) {
8345 createLocalStoreSchema(db); // v2 -> v3
8346 }
8347 if (e.oldVersion < 4) {
8348 addAttachAndSeqStore(db); // v3 -> v4
8349 }
8350
8351 var migrations = [
8352 addDeletedOrLocalIndex, // v1 -> v2
8353 migrateLocalStore, // v2 -> v3
8354 migrateAttsAndSeqs, // v3 -> v4
8355 migrateMetadata // v4 -> v5
8356 ];
8357
8358 var i = e.oldVersion;
8359
8360 function next() {
8361 var migration = migrations[i - 1];
8362 i++;
8363 if (migration) {
8364 migration(txn, next);
8365 }
8366 }
8367
8368 next();
8369 };
8370
8371 req.onsuccess = function (e) {
8372
8373 idb = e.target.result;
8374
8375 idb.onversionchange = function () {
8376 idb.close();
8377 cachedDBs["delete"](dbName);
8378 };
8379
8380 idb.onabort = function (e) {
8381 guardedConsole('error', 'Database has a global failure', e.target.error);
8382 idb.close();
8383 cachedDBs["delete"](dbName);
8384 };
8385
8386 // Do a few setup operations (in parallel as much as possible):
8387 // 1. Fetch meta doc
8388 // 2. Check blob support
8389 // 3. Calculate docCount
8390 // 4. Generate an instanceId if necessary
8391 // 5. Store docCount and instanceId on meta doc
8392
8393 var txn = idb.transaction([
8394 META_STORE,
8395 DETECT_BLOB_SUPPORT_STORE,
8396 DOC_STORE
8397 ], 'readwrite');
8398
8399 var storedMetaDoc = false;
8400 var metaDoc;
8401 var docCount;
8402 var blobSupport;
8403 var instanceId;
8404
8405 function completeSetup() {
8406 if (typeof blobSupport === 'undefined' || !storedMetaDoc) {
8407 return;
8408 }
8409 api._meta = {
8410 name: dbName,
8411 instanceId: instanceId,
8412 blobSupport: blobSupport
8413 };
8414
8415 cachedDBs.set(dbName, {
8416 idb: idb,
8417 global: api._meta
8418 });
8419 callback(null, api);
8420 }
8421
8422 function storeMetaDocIfReady() {
8423 if (typeof docCount === 'undefined' || typeof metaDoc === 'undefined') {
8424 return;
8425 }
8426 var instanceKey = dbName + '_id';
8427 if (instanceKey in metaDoc) {
8428 instanceId = metaDoc[instanceKey];
8429 } else {
8430 metaDoc[instanceKey] = instanceId = uuid();
8431 }
8432 metaDoc.docCount = docCount;
8433 txn.objectStore(META_STORE).put(metaDoc);
8434 }
8435
8436 //
8437 // fetch or generate the instanceId
8438 //
8439 txn.objectStore(META_STORE).get(META_STORE).onsuccess = function (e) {
8440 metaDoc = e.target.result || { id: META_STORE };
8441 storeMetaDocIfReady();
8442 };
8443
8444 //
8445 // countDocs
8446 //
8447 countDocs(txn, function (count) {
8448 docCount = count;
8449 storeMetaDocIfReady();
8450 });
8451
8452 //
8453 // check blob support
8454 //
8455 if (!blobSupportPromise) {
8456 // make sure blob support is only checked once
8457 blobSupportPromise = checkBlobSupport(txn);
8458 }
8459
8460 blobSupportPromise.then(function (val) {
8461 blobSupport = val;
8462 completeSetup();
8463 });
8464
8465 // only when the metadata put transaction has completed,
8466 // consider the setup done
8467 txn.oncomplete = function () {
8468 storedMetaDoc = true;
8469 completeSetup();
8470 };
8471 txn.onabort = idbError(callback);
8472 };
8473
8474 req.onerror = function (e) {
8475 var msg = e.target.error && e.target.error.message;
8476
8477 if (!msg) {
8478 msg = 'Failed to open indexedDB, are you in private browsing mode?';
8479 } else if (msg.indexOf("stored database is a higher version") !== -1) {
8480 msg = new Error('This DB was created with the newer "indexeddb" adapter, but you are trying to open it with the older "idb" adapter');
8481 }
8482
8483 guardedConsole('error', msg);
8484 callback(createError(IDB_ERROR, msg));
8485 };
8486}
8487
8488IdbPouch.valid = function () {
8489 // Following #7085 buggy idb versions (typically Safari < 10.1) are
8490 // considered valid.
8491
8492 // On Firefox SecurityError is thrown while referencing indexedDB if cookies
8493 // are not allowed. `typeof indexedDB` also triggers the error.
8494 try {
8495 // some outdated implementations of IDB that appear on Samsung
8496 // and HTC Android devices <4.4 are missing IDBKeyRange
8497 return typeof indexedDB !== 'undefined' && typeof IDBKeyRange !== 'undefined';
8498 } catch (e) {
8499 return false;
8500 }
8501};
8502
8503function IDBPouch (PouchDB) {
8504 PouchDB.adapter('idb', IdbPouch, true);
8505}
8506
8507// dead simple promise pool, inspired by https://github.com/timdp/es6-promise-pool
8508// but much smaller in code size. limits the number of concurrent promises that are executed
8509
8510
8511function pool(promiseFactories, limit) {
8512 return new Promise(function (resolve, reject) {
8513 var running = 0;
8514 var current = 0;
8515 var done = 0;
8516 var len = promiseFactories.length;
8517 var err;
8518
8519 function runNext() {
8520 running++;
8521 promiseFactories[current++]().then(onSuccess, onError);
8522 }
8523
8524 function doNext() {
8525 if (++done === len) {
8526 /* istanbul ignore if */
8527 if (err) {
8528 reject(err);
8529 } else {
8530 resolve();
8531 }
8532 } else {
8533 runNextBatch();
8534 }
8535 }
8536
8537 function onSuccess() {
8538 running--;
8539 doNext();
8540 }
8541
8542 /* istanbul ignore next */
8543 function onError(thisErr) {
8544 running--;
8545 err = err || thisErr;
8546 doNext();
8547 }
8548
8549 function runNextBatch() {
8550 while (running < limit && current < len) {
8551 runNext();
8552 }
8553 }
8554
8555 runNextBatch();
8556 });
8557}
8558
8559var CHANGES_BATCH_SIZE = 25;
8560var MAX_SIMULTANEOUS_REVS = 50;
8561var CHANGES_TIMEOUT_BUFFER = 5000;
8562var DEFAULT_HEARTBEAT = 10000;
8563
8564var supportsBulkGetMap = {};
8565
8566function readAttachmentsAsBlobOrBuffer(row) {
8567 var doc = row.doc || row.ok;
8568 var atts = doc && doc._attachments;
8569 if (!atts) {
8570 return;
8571 }
8572 Object.keys(atts).forEach(function (filename) {
8573 var att = atts[filename];
8574 att.data = b64ToBluffer(att.data, att.content_type);
8575 });
8576}
8577
8578function encodeDocId(id) {
8579 if (/^_design/.test(id)) {
8580 return '_design/' + encodeURIComponent(id.slice(8));
8581 }
8582 if (/^_local/.test(id)) {
8583 return '_local/' + encodeURIComponent(id.slice(7));
8584 }
8585 return encodeURIComponent(id);
8586}
8587
8588function preprocessAttachments$1(doc) {
8589 if (!doc._attachments || !Object.keys(doc._attachments)) {
8590 return Promise.resolve();
8591 }
8592
8593 return Promise.all(Object.keys(doc._attachments).map(function (key) {
8594 var attachment = doc._attachments[key];
8595 if (attachment.data && typeof attachment.data !== 'string') {
8596 return new Promise(function (resolve) {
8597 blobToBase64(attachment.data, resolve);
8598 }).then(function (b64) {
8599 attachment.data = b64;
8600 });
8601 }
8602 }));
8603}
8604
8605function hasUrlPrefix(opts) {
8606 if (!opts.prefix) {
8607 return false;
8608 }
8609 var protocol = parseUri(opts.prefix).protocol;
8610 return protocol === 'http' || protocol === 'https';
8611}
8612
8613// Get all the information you possibly can about the URI given by name and
8614// return it as a suitable object.
8615function getHost(name, opts) {
8616 // encode db name if opts.prefix is a url (#5574)
8617 if (hasUrlPrefix(opts)) {
8618 var dbName = opts.name.substr(opts.prefix.length);
8619 // Ensure prefix has a trailing slash
8620 var prefix = opts.prefix.replace(/\/?$/, '/');
8621 name = prefix + encodeURIComponent(dbName);
8622 }
8623
8624 var uri = parseUri(name);
8625 if (uri.user || uri.password) {
8626 uri.auth = {username: uri.user, password: uri.password};
8627 }
8628
8629 // Split the path part of the URI into parts using '/' as the delimiter
8630 // after removing any leading '/' and any trailing '/'
8631 var parts = uri.path.replace(/(^\/|\/$)/g, '').split('/');
8632
8633 uri.db = parts.pop();
8634 // Prevent double encoding of URI component
8635 if (uri.db.indexOf('%') === -1) {
8636 uri.db = encodeURIComponent(uri.db);
8637 }
8638
8639 uri.path = parts.join('/');
8640
8641 return uri;
8642}
8643
8644// Generate a URL with the host data given by opts and the given path
8645function genDBUrl(opts, path) {
8646 return genUrl(opts, opts.db + '/' + path);
8647}
8648
8649// Generate a URL with the host data given by opts and the given path
8650function genUrl(opts, path) {
8651 // If the host already has a path, then we need to have a path delimiter
8652 // Otherwise, the path delimiter is the empty string
8653 var pathDel = !opts.path ? '' : '/';
8654
8655 // If the host already has a path, then we need to have a path delimiter
8656 // Otherwise, the path delimiter is the empty string
8657 return opts.protocol + '://' + opts.host +
8658 (opts.port ? (':' + opts.port) : '') +
8659 '/' + opts.path + pathDel + path;
8660}
8661
8662function paramsToStr(params) {
8663 return '?' + Object.keys(params).map(function (k) {
8664 return k + '=' + encodeURIComponent(params[k]);
8665 }).join('&');
8666}
8667
8668function shouldCacheBust(opts) {
8669 var ua = (typeof navigator !== 'undefined' && navigator.userAgent) ?
8670 navigator.userAgent.toLowerCase() : '';
8671 var isIE = ua.indexOf('msie') !== -1;
8672 var isTrident = ua.indexOf('trident') !== -1;
8673 var isEdge = ua.indexOf('edge') !== -1;
8674 var isGET = !('method' in opts) || opts.method === 'GET';
8675 return (isIE || isTrident || isEdge) && isGET;
8676}
8677
8678// Implements the PouchDB API for dealing with CouchDB instances over HTTP
8679function HttpPouch(opts, callback) {
8680
8681 // The functions that will be publicly available for HttpPouch
8682 var api = this;
8683
8684 var host = getHost(opts.name, opts);
8685 var dbUrl = genDBUrl(host, '');
8686
8687 opts = clone(opts);
8688
8689 var ourFetch = function (url, options) {
8690
8691 options = options || {};
8692 options.headers = options.headers || new h();
8693
8694 options.credentials = 'include';
8695
8696 if (opts.auth || host.auth) {
8697 var nAuth = opts.auth || host.auth;
8698 var str = nAuth.username + ':' + nAuth.password;
8699 var token = thisBtoa(unescape(encodeURIComponent(str)));
8700 options.headers.set('Authorization', 'Basic ' + token);
8701 }
8702
8703 var headers = opts.headers || {};
8704 Object.keys(headers).forEach(function (key) {
8705 options.headers.append(key, headers[key]);
8706 });
8707
8708 /* istanbul ignore if */
8709 if (shouldCacheBust(options)) {
8710 url += (url.indexOf('?') === -1 ? '?' : '&') + '_nonce=' + Date.now();
8711 }
8712
8713 var fetchFun = opts.fetch || f$1;
8714 return fetchFun(url, options);
8715 };
8716
8717 function adapterFun$$1(name, fun) {
8718 return adapterFun(name, getArguments(function (args) {
8719 setup().then(function () {
8720 return fun.apply(this, args);
8721 })["catch"](function (e) {
8722 var callback = args.pop();
8723 callback(e);
8724 });
8725 })).bind(api);
8726 }
8727
8728 function fetchJSON(url, options, callback) {
8729
8730 var result = {};
8731
8732 options = options || {};
8733 options.headers = options.headers || new h();
8734
8735 if (!options.headers.get('Content-Type')) {
8736 options.headers.set('Content-Type', 'application/json');
8737 }
8738 if (!options.headers.get('Accept')) {
8739 options.headers.set('Accept', 'application/json');
8740 }
8741
8742 return ourFetch(url, options).then(function (response) {
8743 result.ok = response.ok;
8744 result.status = response.status;
8745 return response.json();
8746 }).then(function (json) {
8747 result.data = json;
8748 if (!result.ok) {
8749 result.data.status = result.status;
8750 var err = generateErrorFromResponse(result.data);
8751 if (callback) {
8752 return callback(err);
8753 } else {
8754 throw err;
8755 }
8756 }
8757
8758 if (Array.isArray(result.data)) {
8759 result.data = result.data.map(function (v) {
8760 if (v.error || v.missing) {
8761 return generateErrorFromResponse(v);
8762 } else {
8763 return v;
8764 }
8765 });
8766 }
8767
8768 if (callback) {
8769 callback(null, result.data);
8770 } else {
8771 return result;
8772 }
8773 });
8774 }
8775
8776 var setupPromise;
8777
8778 function setup() {
8779 if (opts.skip_setup) {
8780 return Promise.resolve();
8781 }
8782
8783 // If there is a setup in process or previous successful setup
8784 // done then we will use that
8785 // If previous setups have been rejected we will try again
8786 if (setupPromise) {
8787 return setupPromise;
8788 }
8789
8790 setupPromise = fetchJSON(dbUrl)["catch"](function (err) {
8791 if (err && err.status && err.status === 404) {
8792 // Doesnt exist, create it
8793 explainError(404, 'PouchDB is just detecting if the remote exists.');
8794 return fetchJSON(dbUrl, {method: 'PUT'});
8795 } else {
8796 return Promise.reject(err);
8797 }
8798 })["catch"](function (err) {
8799 // If we try to create a database that already exists, skipped in
8800 // istanbul since its catching a race condition.
8801 /* istanbul ignore if */
8802 if (err && err.status && err.status === 412) {
8803 return true;
8804 }
8805 return Promise.reject(err);
8806 });
8807
8808 setupPromise["catch"](function () {
8809 setupPromise = null;
8810 });
8811
8812 return setupPromise;
8813 }
8814
8815 immediate(function () {
8816 callback(null, api);
8817 });
8818
8819 api._remote = true;
8820
8821 /* istanbul ignore next */
8822 api.type = function () {
8823 return 'http';
8824 };
8825
8826 api.id = adapterFun$$1('id', function (callback) {
8827 ourFetch(genUrl(host, '')).then(function (response) {
8828 return response.json();
8829 })["catch"](function () {
8830 return {};
8831 }).then(function (result) {
8832 // Bad response or missing `uuid` should not prevent ID generation.
8833 var uuid$$1 = (result && result.uuid) ?
8834 (result.uuid + host.db) : genDBUrl(host, '');
8835 callback(null, uuid$$1);
8836 });
8837 });
8838
8839 // Sends a POST request to the host calling the couchdb _compact function
8840 // version: The version of CouchDB it is running
8841 api.compact = adapterFun$$1('compact', function (opts, callback) {
8842 if (typeof opts === 'function') {
8843 callback = opts;
8844 opts = {};
8845 }
8846 opts = clone(opts);
8847
8848 fetchJSON(genDBUrl(host, '_compact'), {method: 'POST'}).then(function () {
8849 function ping() {
8850 api.info(function (err, res) {
8851 // CouchDB may send a "compact_running:true" if it's
8852 // already compacting. PouchDB Server doesn't.
8853 /* istanbul ignore else */
8854 if (res && !res.compact_running) {
8855 callback(null, {ok: true});
8856 } else {
8857 setTimeout(ping, opts.interval || 200);
8858 }
8859 });
8860 }
8861 // Ping the http if it's finished compaction
8862 ping();
8863 });
8864 });
8865
8866 api.bulkGet = adapterFun('bulkGet', function (opts, callback) {
8867 var self = this;
8868
8869 function doBulkGet(cb) {
8870 var params = {};
8871 if (opts.revs) {
8872 params.revs = true;
8873 }
8874 if (opts.attachments) {
8875 /* istanbul ignore next */
8876 params.attachments = true;
8877 }
8878 if (opts.latest) {
8879 params.latest = true;
8880 }
8881 fetchJSON(genDBUrl(host, '_bulk_get' + paramsToStr(params)), {
8882 method: 'POST',
8883 body: JSON.stringify({ docs: opts.docs})
8884 }).then(function (result) {
8885 if (opts.attachments && opts.binary) {
8886 result.data.results.forEach(function (res) {
8887 res.docs.forEach(readAttachmentsAsBlobOrBuffer);
8888 });
8889 }
8890 cb(null, result.data);
8891 })["catch"](cb);
8892 }
8893
8894 /* istanbul ignore next */
8895 function doBulkGetShim() {
8896 // avoid "url too long error" by splitting up into multiple requests
8897 var batchSize = MAX_SIMULTANEOUS_REVS;
8898 var numBatches = Math.ceil(opts.docs.length / batchSize);
8899 var numDone = 0;
8900 var results = new Array(numBatches);
8901
8902 function onResult(batchNum) {
8903 return function (err, res) {
8904 // err is impossible because shim returns a list of errs in that case
8905 results[batchNum] = res.results;
8906 if (++numDone === numBatches) {
8907 callback(null, {results: flatten(results)});
8908 }
8909 };
8910 }
8911
8912 for (var i = 0; i < numBatches; i++) {
8913 var subOpts = pick(opts, ['revs', 'attachments', 'binary', 'latest']);
8914 subOpts.docs = opts.docs.slice(i * batchSize,
8915 Math.min(opts.docs.length, (i + 1) * batchSize));
8916 bulkGet(self, subOpts, onResult(i));
8917 }
8918 }
8919
8920 // mark the whole database as either supporting or not supporting _bulk_get
8921 var dbUrl = genUrl(host, '');
8922 var supportsBulkGet = supportsBulkGetMap[dbUrl];
8923
8924 /* istanbul ignore next */
8925 if (typeof supportsBulkGet !== 'boolean') {
8926 // check if this database supports _bulk_get
8927 doBulkGet(function (err, res) {
8928 if (err) {
8929 supportsBulkGetMap[dbUrl] = false;
8930 explainError(
8931 err.status,
8932 'PouchDB is just detecting if the remote ' +
8933 'supports the _bulk_get API.'
8934 );
8935 doBulkGetShim();
8936 } else {
8937 supportsBulkGetMap[dbUrl] = true;
8938 callback(null, res);
8939 }
8940 });
8941 } else if (supportsBulkGet) {
8942 doBulkGet(callback);
8943 } else {
8944 doBulkGetShim();
8945 }
8946 });
8947
8948 // Calls GET on the host, which gets back a JSON string containing
8949 // couchdb: A welcome string
8950 // version: The version of CouchDB it is running
8951 api._info = function (callback) {
8952 setup().then(function () {
8953 return ourFetch(genDBUrl(host, ''));
8954 }).then(function (response) {
8955 return response.json();
8956 }).then(function (info) {
8957 info.host = genDBUrl(host, '');
8958 callback(null, info);
8959 })["catch"](callback);
8960 };
8961
8962 api.fetch = function (path, options) {
8963 return setup().then(function () {
8964 var url = path.substring(0, 1) === '/' ?
8965 genUrl(host, path.substring(1)) :
8966 genDBUrl(host, path);
8967 return ourFetch(url, options);
8968 });
8969 };
8970
8971 // Get the document with the given id from the database given by host.
8972 // The id could be solely the _id in the database, or it may be a
8973 // _design/ID or _local/ID path
8974 api.get = adapterFun$$1('get', function (id, opts, callback) {
8975 // If no options were given, set the callback to the second parameter
8976 if (typeof opts === 'function') {
8977 callback = opts;
8978 opts = {};
8979 }
8980 opts = clone(opts);
8981
8982 // List of parameters to add to the GET request
8983 var params = {};
8984
8985 if (opts.revs) {
8986 params.revs = true;
8987 }
8988
8989 if (opts.revs_info) {
8990 params.revs_info = true;
8991 }
8992
8993 if (opts.latest) {
8994 params.latest = true;
8995 }
8996
8997 if (opts.open_revs) {
8998 if (opts.open_revs !== "all") {
8999 opts.open_revs = JSON.stringify(opts.open_revs);
9000 }
9001 params.open_revs = opts.open_revs;
9002 }
9003
9004 if (opts.rev) {
9005 params.rev = opts.rev;
9006 }
9007
9008 if (opts.conflicts) {
9009 params.conflicts = opts.conflicts;
9010 }
9011
9012 /* istanbul ignore if */
9013 if (opts.update_seq) {
9014 params.update_seq = opts.update_seq;
9015 }
9016
9017 id = encodeDocId(id);
9018
9019 function fetchAttachments(doc) {
9020 var atts = doc._attachments;
9021 var filenames = atts && Object.keys(atts);
9022 if (!atts || !filenames.length) {
9023 return;
9024 }
9025 // we fetch these manually in separate XHRs, because
9026 // Sync Gateway would normally send it back as multipart/mixed,
9027 // which we cannot parse. Also, this is more efficient than
9028 // receiving attachments as base64-encoded strings.
9029 function fetchData(filename) {
9030 var att = atts[filename];
9031 var path = encodeDocId(doc._id) + '/' + encodeAttachmentId(filename) +
9032 '?rev=' + doc._rev;
9033 return ourFetch(genDBUrl(host, path)).then(function (response) {
9034 if ('buffer' in response) {
9035 return response.buffer();
9036 } else {
9037 /* istanbul ignore next */
9038 return response.blob();
9039 }
9040 }).then(function (blob) {
9041 if (opts.binary) {
9042 var typeFieldDescriptor = Object.getOwnPropertyDescriptor(blob.__proto__, 'type');
9043 if (!typeFieldDescriptor || typeFieldDescriptor.set) {
9044 blob.type = att.content_type;
9045 }
9046 return blob;
9047 }
9048 return new Promise(function (resolve) {
9049 blobToBase64(blob, resolve);
9050 });
9051 }).then(function (data) {
9052 delete att.stub;
9053 delete att.length;
9054 att.data = data;
9055 });
9056 }
9057
9058 var promiseFactories = filenames.map(function (filename) {
9059 return function () {
9060 return fetchData(filename);
9061 };
9062 });
9063
9064 // This limits the number of parallel xhr requests to 5 any time
9065 // to avoid issues with maximum browser request limits
9066 return pool(promiseFactories, 5);
9067 }
9068
9069 function fetchAllAttachments(docOrDocs) {
9070 if (Array.isArray(docOrDocs)) {
9071 return Promise.all(docOrDocs.map(function (doc) {
9072 if (doc.ok) {
9073 return fetchAttachments(doc.ok);
9074 }
9075 }));
9076 }
9077 return fetchAttachments(docOrDocs);
9078 }
9079
9080 var url = genDBUrl(host, id + paramsToStr(params));
9081 fetchJSON(url).then(function (res) {
9082 return Promise.resolve().then(function () {
9083 if (opts.attachments) {
9084 return fetchAllAttachments(res.data);
9085 }
9086 }).then(function () {
9087 callback(null, res.data);
9088 });
9089 })["catch"](function (e) {
9090 e.docId = id;
9091 callback(e);
9092 });
9093 });
9094
9095
9096 // Delete the document given by doc from the database given by host.
9097 api.remove = adapterFun$$1('remove', function (docOrId, optsOrRev, opts, cb) {
9098 var doc;
9099 if (typeof optsOrRev === 'string') {
9100 // id, rev, opts, callback style
9101 doc = {
9102 _id: docOrId,
9103 _rev: optsOrRev
9104 };
9105 if (typeof opts === 'function') {
9106 cb = opts;
9107 opts = {};
9108 }
9109 } else {
9110 // doc, opts, callback style
9111 doc = docOrId;
9112 if (typeof optsOrRev === 'function') {
9113 cb = optsOrRev;
9114 opts = {};
9115 } else {
9116 cb = opts;
9117 opts = optsOrRev;
9118 }
9119 }
9120
9121 var rev$$1 = (doc._rev || opts.rev);
9122 var url = genDBUrl(host, encodeDocId(doc._id)) + '?rev=' + rev$$1;
9123
9124 fetchJSON(url, {method: 'DELETE'}, cb)["catch"](cb);
9125 });
9126
9127 function encodeAttachmentId(attachmentId) {
9128 return attachmentId.split("/").map(encodeURIComponent).join("/");
9129 }
9130
9131 // Get the attachment
9132 api.getAttachment = adapterFun$$1('getAttachment', function (docId, attachmentId,
9133 opts, callback) {
9134 if (typeof opts === 'function') {
9135 callback = opts;
9136 opts = {};
9137 }
9138 var params = opts.rev ? ('?rev=' + opts.rev) : '';
9139 var url = genDBUrl(host, encodeDocId(docId)) + '/' +
9140 encodeAttachmentId(attachmentId) + params;
9141 var contentType;
9142 ourFetch(url, {method: 'GET'}).then(function (response) {
9143 contentType = response.headers.get('content-type');
9144 if (!response.ok) {
9145 throw response;
9146 } else {
9147 if (typeof process !== 'undefined' && !process.browser && typeof response.buffer === 'function') {
9148 return response.buffer();
9149 } else {
9150 /* istanbul ignore next */
9151 return response.blob();
9152 }
9153 }
9154 }).then(function (blob) {
9155 // TODO: also remove
9156 if (typeof process !== 'undefined' && !process.browser) {
9157 blob.type = contentType;
9158 }
9159 callback(null, blob);
9160 })["catch"](function (err) {
9161 callback(err);
9162 });
9163 });
9164
9165 // Remove the attachment given by the id and rev
9166 api.removeAttachment = adapterFun$$1('removeAttachment', function (docId,
9167 attachmentId,
9168 rev$$1,
9169 callback) {
9170 var url = genDBUrl(host, encodeDocId(docId) + '/' +
9171 encodeAttachmentId(attachmentId)) + '?rev=' + rev$$1;
9172 fetchJSON(url, {method: 'DELETE'}, callback)["catch"](callback);
9173 });
9174
9175 // Add the attachment given by blob and its contentType property
9176 // to the document with the given id, the revision given by rev, and
9177 // add it to the database given by host.
9178 api.putAttachment = adapterFun$$1('putAttachment', function (docId, attachmentId,
9179 rev$$1, blob,
9180 type, callback) {
9181 if (typeof type === 'function') {
9182 callback = type;
9183 type = blob;
9184 blob = rev$$1;
9185 rev$$1 = null;
9186 }
9187 var id = encodeDocId(docId) + '/' + encodeAttachmentId(attachmentId);
9188 var url = genDBUrl(host, id);
9189 if (rev$$1) {
9190 url += '?rev=' + rev$$1;
9191 }
9192
9193 if (typeof blob === 'string') {
9194 // input is assumed to be a base64 string
9195 var binary;
9196 try {
9197 binary = thisAtob(blob);
9198 } catch (err) {
9199 return callback(createError(BAD_ARG,
9200 'Attachment is not a valid base64 string'));
9201 }
9202 blob = binary ? binStringToBluffer(binary, type) : '';
9203 }
9204
9205 // Add the attachment
9206 fetchJSON(url, {
9207 headers: new h({'Content-Type': type}),
9208 method: 'PUT',
9209 body: blob
9210 }, callback)["catch"](callback);
9211 });
9212
9213 // Update/create multiple documents given by req in the database
9214 // given by host.
9215 api._bulkDocs = function (req, opts, callback) {
9216 // If new_edits=false then it prevents the database from creating
9217 // new revision numbers for the documents. Instead it just uses
9218 // the old ones. This is used in database replication.
9219 req.new_edits = opts.new_edits;
9220
9221 setup().then(function () {
9222 return Promise.all(req.docs.map(preprocessAttachments$1));
9223 }).then(function () {
9224 // Update/create the documents
9225 return fetchJSON(genDBUrl(host, '_bulk_docs'), {
9226 method: 'POST',
9227 body: JSON.stringify(req)
9228 }, callback);
9229 })["catch"](callback);
9230 };
9231
9232
9233 // Update/create document
9234 api._put = function (doc, opts, callback) {
9235 setup().then(function () {
9236 return preprocessAttachments$1(doc);
9237 }).then(function () {
9238 return fetchJSON(genDBUrl(host, encodeDocId(doc._id)), {
9239 method: 'PUT',
9240 body: JSON.stringify(doc)
9241 });
9242 }).then(function (result) {
9243 callback(null, result.data);
9244 })["catch"](function (err) {
9245 err.docId = doc && doc._id;
9246 callback(err);
9247 });
9248 };
9249
9250
9251 // Get a listing of the documents in the database given
9252 // by host and ordered by increasing id.
9253 api.allDocs = adapterFun$$1('allDocs', function (opts, callback) {
9254 if (typeof opts === 'function') {
9255 callback = opts;
9256 opts = {};
9257 }
9258 opts = clone(opts);
9259
9260 // List of parameters to add to the GET request
9261 var params = {};
9262 var body;
9263 var method = 'GET';
9264
9265 if (opts.conflicts) {
9266 params.conflicts = true;
9267 }
9268
9269 /* istanbul ignore if */
9270 if (opts.update_seq) {
9271 params.update_seq = true;
9272 }
9273
9274 if (opts.descending) {
9275 params.descending = true;
9276 }
9277
9278 if (opts.include_docs) {
9279 params.include_docs = true;
9280 }
9281
9282 // added in CouchDB 1.6.0
9283 if (opts.attachments) {
9284 params.attachments = true;
9285 }
9286
9287 if (opts.key) {
9288 params.key = JSON.stringify(opts.key);
9289 }
9290
9291 if (opts.start_key) {
9292 opts.startkey = opts.start_key;
9293 }
9294
9295 if (opts.startkey) {
9296 params.startkey = JSON.stringify(opts.startkey);
9297 }
9298
9299 if (opts.end_key) {
9300 opts.endkey = opts.end_key;
9301 }
9302
9303 if (opts.endkey) {
9304 params.endkey = JSON.stringify(opts.endkey);
9305 }
9306
9307 if (typeof opts.inclusive_end !== 'undefined') {
9308 params.inclusive_end = !!opts.inclusive_end;
9309 }
9310
9311 if (typeof opts.limit !== 'undefined') {
9312 params.limit = opts.limit;
9313 }
9314
9315 if (typeof opts.skip !== 'undefined') {
9316 params.skip = opts.skip;
9317 }
9318
9319 var paramStr = paramsToStr(params);
9320
9321 if (typeof opts.keys !== 'undefined') {
9322 method = 'POST';
9323 body = {keys: opts.keys};
9324 }
9325
9326 fetchJSON(genDBUrl(host, '_all_docs' + paramStr), {
9327 method: method,
9328 body: JSON.stringify(body)
9329 }).then(function (result) {
9330 if (opts.include_docs && opts.attachments && opts.binary) {
9331 result.data.rows.forEach(readAttachmentsAsBlobOrBuffer);
9332 }
9333 callback(null, result.data);
9334 })["catch"](callback);
9335 });
9336
9337 // Get a list of changes made to documents in the database given by host.
9338 // TODO According to the README, there should be two other methods here,
9339 // api.changes.addListener and api.changes.removeListener.
9340 api._changes = function (opts) {
9341
9342 // We internally page the results of a changes request, this means
9343 // if there is a large set of changes to be returned we can start
9344 // processing them quicker instead of waiting on the entire
9345 // set of changes to return and attempting to process them at once
9346 var batchSize = 'batch_size' in opts ? opts.batch_size : CHANGES_BATCH_SIZE;
9347
9348 opts = clone(opts);
9349
9350 if (opts.continuous && !('heartbeat' in opts)) {
9351 opts.heartbeat = DEFAULT_HEARTBEAT;
9352 }
9353
9354 var requestTimeout = ('timeout' in opts) ? opts.timeout : 30 * 1000;
9355
9356 // ensure CHANGES_TIMEOUT_BUFFER applies
9357 if ('timeout' in opts && opts.timeout &&
9358 (requestTimeout - opts.timeout) < CHANGES_TIMEOUT_BUFFER) {
9359 requestTimeout = opts.timeout + CHANGES_TIMEOUT_BUFFER;
9360 }
9361
9362 /* istanbul ignore if */
9363 if ('heartbeat' in opts && opts.heartbeat &&
9364 (requestTimeout - opts.heartbeat) < CHANGES_TIMEOUT_BUFFER) {
9365 requestTimeout = opts.heartbeat + CHANGES_TIMEOUT_BUFFER;
9366 }
9367
9368 var params = {};
9369 if ('timeout' in opts && opts.timeout) {
9370 params.timeout = opts.timeout;
9371 }
9372
9373 var limit = (typeof opts.limit !== 'undefined') ? opts.limit : false;
9374 var leftToFetch = limit;
9375
9376 if (opts.style) {
9377 params.style = opts.style;
9378 }
9379
9380 if (opts.include_docs || opts.filter && typeof opts.filter === 'function') {
9381 params.include_docs = true;
9382 }
9383
9384 if (opts.attachments) {
9385 params.attachments = true;
9386 }
9387
9388 if (opts.continuous) {
9389 params.feed = 'longpoll';
9390 }
9391
9392 if (opts.seq_interval) {
9393 params.seq_interval = opts.seq_interval;
9394 }
9395
9396 if (opts.conflicts) {
9397 params.conflicts = true;
9398 }
9399
9400 if (opts.descending) {
9401 params.descending = true;
9402 }
9403
9404 /* istanbul ignore if */
9405 if (opts.update_seq) {
9406 params.update_seq = true;
9407 }
9408
9409 if ('heartbeat' in opts) {
9410 // If the heartbeat value is false, it disables the default heartbeat
9411 if (opts.heartbeat) {
9412 params.heartbeat = opts.heartbeat;
9413 }
9414 }
9415
9416 if (opts.filter && typeof opts.filter === 'string') {
9417 params.filter = opts.filter;
9418 }
9419
9420 if (opts.view && typeof opts.view === 'string') {
9421 params.filter = '_view';
9422 params.view = opts.view;
9423 }
9424
9425 // If opts.query_params exists, pass it through to the changes request.
9426 // These parameters may be used by the filter on the source database.
9427 if (opts.query_params && typeof opts.query_params === 'object') {
9428 for (var param_name in opts.query_params) {
9429 /* istanbul ignore else */
9430 if (opts.query_params.hasOwnProperty(param_name)) {
9431 params[param_name] = opts.query_params[param_name];
9432 }
9433 }
9434 }
9435
9436 var method = 'GET';
9437 var body;
9438
9439 if (opts.doc_ids) {
9440 // set this automagically for the user; it's annoying that couchdb
9441 // requires both a "filter" and a "doc_ids" param.
9442 params.filter = '_doc_ids';
9443 method = 'POST';
9444 body = {doc_ids: opts.doc_ids };
9445 }
9446 /* istanbul ignore next */
9447 else if (opts.selector) {
9448 // set this automagically for the user, similar to above
9449 params.filter = '_selector';
9450 method = 'POST';
9451 body = {selector: opts.selector };
9452 }
9453
9454 var controller = new a();
9455 var lastFetchedSeq;
9456
9457 // Get all the changes starting wtih the one immediately after the
9458 // sequence number given by since.
9459 var fetchData = function (since, callback) {
9460 if (opts.aborted) {
9461 return;
9462 }
9463 params.since = since;
9464 // "since" can be any kind of json object in Cloudant/CouchDB 2.x
9465 /* istanbul ignore next */
9466 if (typeof params.since === "object") {
9467 params.since = JSON.stringify(params.since);
9468 }
9469
9470 if (opts.descending) {
9471 if (limit) {
9472 params.limit = leftToFetch;
9473 }
9474 } else {
9475 params.limit = (!limit || leftToFetch > batchSize) ?
9476 batchSize : leftToFetch;
9477 }
9478
9479 // Set the options for the ajax call
9480 var url = genDBUrl(host, '_changes' + paramsToStr(params));
9481 var fetchOpts = {
9482 signal: controller.signal,
9483 method: method,
9484 body: JSON.stringify(body)
9485 };
9486 lastFetchedSeq = since;
9487
9488 /* istanbul ignore if */
9489 if (opts.aborted) {
9490 return;
9491 }
9492
9493 // Get the changes
9494 setup().then(function () {
9495 return fetchJSON(url, fetchOpts, callback);
9496 })["catch"](callback);
9497 };
9498
9499 // If opts.since exists, get all the changes from the sequence
9500 // number given by opts.since. Otherwise, get all the changes
9501 // from the sequence number 0.
9502 var results = {results: []};
9503
9504 var fetched = function (err, res) {
9505 if (opts.aborted) {
9506 return;
9507 }
9508 var raw_results_length = 0;
9509 // If the result of the ajax call (res) contains changes (res.results)
9510 if (res && res.results) {
9511 raw_results_length = res.results.length;
9512 results.last_seq = res.last_seq;
9513 var pending = null;
9514 var lastSeq = null;
9515 // Attach 'pending' property if server supports it (CouchDB 2.0+)
9516 /* istanbul ignore if */
9517 if (typeof res.pending === 'number') {
9518 pending = res.pending;
9519 }
9520 if (typeof results.last_seq === 'string' || typeof results.last_seq === 'number') {
9521 lastSeq = results.last_seq;
9522 }
9523 // For each change
9524 var req = {};
9525 req.query = opts.query_params;
9526 res.results = res.results.filter(function (c) {
9527 leftToFetch--;
9528 var ret = filterChange(opts)(c);
9529 if (ret) {
9530 if (opts.include_docs && opts.attachments && opts.binary) {
9531 readAttachmentsAsBlobOrBuffer(c);
9532 }
9533 if (opts.return_docs) {
9534 results.results.push(c);
9535 }
9536 opts.onChange(c, pending, lastSeq);
9537 }
9538 return ret;
9539 });
9540 } else if (err) {
9541 // In case of an error, stop listening for changes and call
9542 // opts.complete
9543 opts.aborted = true;
9544 opts.complete(err);
9545 return;
9546 }
9547
9548 // The changes feed may have timed out with no results
9549 // if so reuse last update sequence
9550 if (res && res.last_seq) {
9551 lastFetchedSeq = res.last_seq;
9552 }
9553
9554 var finished = (limit && leftToFetch <= 0) ||
9555 (res && raw_results_length < batchSize) ||
9556 (opts.descending);
9557
9558 if ((opts.continuous && !(limit && leftToFetch <= 0)) || !finished) {
9559 // Queue a call to fetch again with the newest sequence number
9560 immediate(function () { fetchData(lastFetchedSeq, fetched); });
9561 } else {
9562 // We're done, call the callback
9563 opts.complete(null, results);
9564 }
9565 };
9566
9567 fetchData(opts.since || 0, fetched);
9568
9569 // Return a method to cancel this method from processing any more
9570 return {
9571 cancel: function () {
9572 opts.aborted = true;
9573 controller.abort();
9574 }
9575 };
9576 };
9577
9578 // Given a set of document/revision IDs (given by req), tets the subset of
9579 // those that do NOT correspond to revisions stored in the database.
9580 // See http://wiki.apache.org/couchdb/HttpPostRevsDiff
9581 api.revsDiff = adapterFun$$1('revsDiff', function (req, opts, callback) {
9582 // If no options were given, set the callback to be the second parameter
9583 if (typeof opts === 'function') {
9584 callback = opts;
9585 opts = {};
9586 }
9587
9588 // Get the missing document/revision IDs
9589 fetchJSON(genDBUrl(host, '_revs_diff'), {
9590 method: 'POST',
9591 body: JSON.stringify(req)
9592 }, callback)["catch"](callback);
9593 });
9594
9595 api._close = function (callback) {
9596 callback();
9597 };
9598
9599 api._destroy = function (options, callback) {
9600 fetchJSON(genDBUrl(host, ''), {method: 'DELETE'}).then(function (json) {
9601 callback(null, json);
9602 })["catch"](function (err) {
9603 /* istanbul ignore if */
9604 if (err.status === 404) {
9605 callback(null, {ok: true});
9606 } else {
9607 callback(err);
9608 }
9609 });
9610 };
9611}
9612
9613// HttpPouch is a valid adapter.
9614HttpPouch.valid = function () {
9615 return true;
9616};
9617
9618function HttpPouch$1 (PouchDB) {
9619 PouchDB.adapter('http', HttpPouch, false);
9620 PouchDB.adapter('https', HttpPouch, false);
9621}
9622
9623function QueryParseError(message) {
9624 this.status = 400;
9625 this.name = 'query_parse_error';
9626 this.message = message;
9627 this.error = true;
9628 try {
9629 Error.captureStackTrace(this, QueryParseError);
9630 } catch (e) {}
9631}
9632
9633inherits(QueryParseError, Error);
9634
9635function NotFoundError(message) {
9636 this.status = 404;
9637 this.name = 'not_found';
9638 this.message = message;
9639 this.error = true;
9640 try {
9641 Error.captureStackTrace(this, NotFoundError);
9642 } catch (e) {}
9643}
9644
9645inherits(NotFoundError, Error);
9646
9647function BuiltInError(message) {
9648 this.status = 500;
9649 this.name = 'invalid_value';
9650 this.message = message;
9651 this.error = true;
9652 try {
9653 Error.captureStackTrace(this, BuiltInError);
9654 } catch (e) {}
9655}
9656
9657inherits(BuiltInError, Error);
9658
9659function promisedCallback(promise, callback) {
9660 if (callback) {
9661 promise.then(function (res) {
9662 immediate(function () {
9663 callback(null, res);
9664 });
9665 }, function (reason) {
9666 immediate(function () {
9667 callback(reason);
9668 });
9669 });
9670 }
9671 return promise;
9672}
9673
9674function callbackify(fun) {
9675 return getArguments(function (args) {
9676 var cb = args.pop();
9677 var promise = fun.apply(this, args);
9678 if (typeof cb === 'function') {
9679 promisedCallback(promise, cb);
9680 }
9681 return promise;
9682 });
9683}
9684
9685// Promise finally util similar to Q.finally
9686function fin(promise, finalPromiseFactory) {
9687 return promise.then(function (res) {
9688 return finalPromiseFactory().then(function () {
9689 return res;
9690 });
9691 }, function (reason) {
9692 return finalPromiseFactory().then(function () {
9693 throw reason;
9694 });
9695 });
9696}
9697
9698function sequentialize(queue, promiseFactory) {
9699 return function () {
9700 var args = arguments;
9701 var that = this;
9702 return queue.add(function () {
9703 return promiseFactory.apply(that, args);
9704 });
9705 };
9706}
9707
9708// uniq an array of strings, order not guaranteed
9709// similar to underscore/lodash _.uniq
9710function uniq(arr) {
9711 var theSet = new ExportedSet(arr);
9712 var result = new Array(theSet.size);
9713 var index = -1;
9714 theSet.forEach(function (value) {
9715 result[++index] = value;
9716 });
9717 return result;
9718}
9719
9720function mapToKeysArray(map) {
9721 var result = new Array(map.size);
9722 var index = -1;
9723 map.forEach(function (value, key) {
9724 result[++index] = key;
9725 });
9726 return result;
9727}
9728
9729function createBuiltInError(name) {
9730 var message = 'builtin ' + name +
9731 ' function requires map values to be numbers' +
9732 ' or number arrays';
9733 return new BuiltInError(message);
9734}
9735
9736function sum(values) {
9737 var result = 0;
9738 for (var i = 0, len = values.length; i < len; i++) {
9739 var num = values[i];
9740 if (typeof num !== 'number') {
9741 if (Array.isArray(num)) {
9742 // lists of numbers are also allowed, sum them separately
9743 result = typeof result === 'number' ? [result] : result;
9744 for (var j = 0, jLen = num.length; j < jLen; j++) {
9745 var jNum = num[j];
9746 if (typeof jNum !== 'number') {
9747 throw createBuiltInError('_sum');
9748 } else if (typeof result[j] === 'undefined') {
9749 result.push(jNum);
9750 } else {
9751 result[j] += jNum;
9752 }
9753 }
9754 } else { // not array/number
9755 throw createBuiltInError('_sum');
9756 }
9757 } else if (typeof result === 'number') {
9758 result += num;
9759 } else { // add number to array
9760 result[0] += num;
9761 }
9762 }
9763 return result;
9764}
9765
9766var log = guardedConsole.bind(null, 'log');
9767var isArray = Array.isArray;
9768var toJSON = JSON.parse;
9769
9770function evalFunctionWithEval(func, emit) {
9771 return scopeEval(
9772 "return (" + func.replace(/;\s*$/, "") + ");",
9773 {
9774 emit: emit,
9775 sum: sum,
9776 log: log,
9777 isArray: isArray,
9778 toJSON: toJSON
9779 }
9780 );
9781}
9782
9783/*
9784 * Simple task queue to sequentialize actions. Assumes
9785 * callbacks will eventually fire (once).
9786 */
9787
9788
9789function TaskQueue$1() {
9790 this.promise = new Promise(function (fulfill) {fulfill(); });
9791}
9792TaskQueue$1.prototype.add = function (promiseFactory) {
9793 this.promise = this.promise["catch"](function () {
9794 // just recover
9795 }).then(function () {
9796 return promiseFactory();
9797 });
9798 return this.promise;
9799};
9800TaskQueue$1.prototype.finish = function () {
9801 return this.promise;
9802};
9803
9804function stringify(input) {
9805 if (!input) {
9806 return 'undefined'; // backwards compat for empty reduce
9807 }
9808 // for backwards compat with mapreduce, functions/strings are stringified
9809 // as-is. everything else is JSON-stringified.
9810 switch (typeof input) {
9811 case 'function':
9812 // e.g. a mapreduce map
9813 return input.toString();
9814 case 'string':
9815 // e.g. a mapreduce built-in _reduce function
9816 return input.toString();
9817 default:
9818 // e.g. a JSON object in the case of mango queries
9819 return JSON.stringify(input);
9820 }
9821}
9822
9823/* create a string signature for a view so we can cache it and uniq it */
9824function createViewSignature(mapFun, reduceFun) {
9825 // the "undefined" part is for backwards compatibility
9826 return stringify(mapFun) + stringify(reduceFun) + 'undefined';
9827}
9828
9829function createView(sourceDB, viewName, mapFun, reduceFun, temporary, localDocName) {
9830 var viewSignature = createViewSignature(mapFun, reduceFun);
9831
9832 var cachedViews;
9833 if (!temporary) {
9834 // cache this to ensure we don't try to update the same view twice
9835 cachedViews = sourceDB._cachedViews = sourceDB._cachedViews || {};
9836 if (cachedViews[viewSignature]) {
9837 return cachedViews[viewSignature];
9838 }
9839 }
9840
9841 var promiseForView = sourceDB.info().then(function (info) {
9842
9843 var depDbName = info.db_name + '-mrview-' +
9844 (temporary ? 'temp' : stringMd5(viewSignature));
9845
9846 // save the view name in the source db so it can be cleaned up if necessary
9847 // (e.g. when the _design doc is deleted, remove all associated view data)
9848 function diffFunction(doc) {
9849 doc.views = doc.views || {};
9850 var fullViewName = viewName;
9851 if (fullViewName.indexOf('/') === -1) {
9852 fullViewName = viewName + '/' + viewName;
9853 }
9854 var depDbs = doc.views[fullViewName] = doc.views[fullViewName] || {};
9855 /* istanbul ignore if */
9856 if (depDbs[depDbName]) {
9857 return; // no update necessary
9858 }
9859 depDbs[depDbName] = true;
9860 return doc;
9861 }
9862 return upsert(sourceDB, '_local/' + localDocName, diffFunction).then(function () {
9863 return sourceDB.registerDependentDatabase(depDbName).then(function (res) {
9864 var db = res.db;
9865 db.auto_compaction = true;
9866 var view = {
9867 name: depDbName,
9868 db: db,
9869 sourceDB: sourceDB,
9870 adapter: sourceDB.adapter,
9871 mapFun: mapFun,
9872 reduceFun: reduceFun
9873 };
9874 return view.db.get('_local/lastSeq')["catch"](function (err) {
9875 /* istanbul ignore if */
9876 if (err.status !== 404) {
9877 throw err;
9878 }
9879 }).then(function (lastSeqDoc) {
9880 view.seq = lastSeqDoc ? lastSeqDoc.seq : 0;
9881 if (cachedViews) {
9882 view.db.once('destroyed', function () {
9883 delete cachedViews[viewSignature];
9884 });
9885 }
9886 return view;
9887 });
9888 });
9889 });
9890 });
9891
9892 if (cachedViews) {
9893 cachedViews[viewSignature] = promiseForView;
9894 }
9895 return promiseForView;
9896}
9897
9898var persistentQueues = {};
9899var tempViewQueue = new TaskQueue$1();
9900var CHANGES_BATCH_SIZE$1 = 50;
9901
9902function parseViewName(name) {
9903 // can be either 'ddocname/viewname' or just 'viewname'
9904 // (where the ddoc name is the same)
9905 return name.indexOf('/') === -1 ? [name, name] : name.split('/');
9906}
9907
9908function isGenOne(changes) {
9909 // only return true if the current change is 1-
9910 // and there are no other leafs
9911 return changes.length === 1 && /^1-/.test(changes[0].rev);
9912}
9913
9914function emitError(db, e) {
9915 try {
9916 db.emit('error', e);
9917 } catch (err) {
9918 guardedConsole('error',
9919 'The user\'s map/reduce function threw an uncaught error.\n' +
9920 'You can debug this error by doing:\n' +
9921 'myDatabase.on(\'error\', function (err) { debugger; });\n' +
9922 'Please double-check your map/reduce function.');
9923 guardedConsole('error', e);
9924 }
9925}
9926
9927/**
9928 * Returns an "abstract" mapreduce object of the form:
9929 *
9930 * {
9931 * query: queryFun,
9932 * viewCleanup: viewCleanupFun
9933 * }
9934 *
9935 * Arguments are:
9936 *
9937 * localDoc: string
9938 * This is for the local doc that gets saved in order to track the
9939 * "dependent" DBs and clean them up for viewCleanup. It should be
9940 * unique, so that indexer plugins don't collide with each other.
9941 * mapper: function (mapFunDef, emit)
9942 * Returns a map function based on the mapFunDef, which in the case of
9943 * normal map/reduce is just the de-stringified function, but may be
9944 * something else, such as an object in the case of pouchdb-find.
9945 * reducer: function (reduceFunDef)
9946 * Ditto, but for reducing. Modules don't have to support reducing
9947 * (e.g. pouchdb-find).
9948 * ddocValidator: function (ddoc, viewName)
9949 * Throws an error if the ddoc or viewName is not valid.
9950 * This could be a way to communicate to the user that the configuration for the
9951 * indexer is invalid.
9952 */
9953function createAbstractMapReduce(localDocName, mapper, reducer, ddocValidator) {
9954
9955 function tryMap(db, fun, doc) {
9956 // emit an event if there was an error thrown by a map function.
9957 // putting try/catches in a single function also avoids deoptimizations.
9958 try {
9959 fun(doc);
9960 } catch (e) {
9961 emitError(db, e);
9962 }
9963 }
9964
9965 function tryReduce(db, fun, keys, values, rereduce) {
9966 // same as above, but returning the result or an error. there are two separate
9967 // functions to avoid extra memory allocations since the tryCode() case is used
9968 // for custom map functions (common) vs this function, which is only used for
9969 // custom reduce functions (rare)
9970 try {
9971 return {output : fun(keys, values, rereduce)};
9972 } catch (e) {
9973 emitError(db, e);
9974 return {error: e};
9975 }
9976 }
9977
9978 function sortByKeyThenValue(x, y) {
9979 var keyCompare = collate(x.key, y.key);
9980 return keyCompare !== 0 ? keyCompare : collate(x.value, y.value);
9981 }
9982
9983 function sliceResults(results, limit, skip) {
9984 skip = skip || 0;
9985 if (typeof limit === 'number') {
9986 return results.slice(skip, limit + skip);
9987 } else if (skip > 0) {
9988 return results.slice(skip);
9989 }
9990 return results;
9991 }
9992
9993 function rowToDocId(row) {
9994 var val = row.value;
9995 // Users can explicitly specify a joined doc _id, or it
9996 // defaults to the doc _id that emitted the key/value.
9997 var docId = (val && typeof val === 'object' && val._id) || row.id;
9998 return docId;
9999 }
10000
10001 function readAttachmentsAsBlobOrBuffer(res) {
10002 res.rows.forEach(function (row) {
10003 var atts = row.doc && row.doc._attachments;
10004 if (!atts) {
10005 return;
10006 }
10007 Object.keys(atts).forEach(function (filename) {
10008 var att = atts[filename];
10009 atts[filename].data = b64ToBluffer(att.data, att.content_type);
10010 });
10011 });
10012 }
10013
10014 function postprocessAttachments(opts) {
10015 return function (res) {
10016 if (opts.include_docs && opts.attachments && opts.binary) {
10017 readAttachmentsAsBlobOrBuffer(res);
10018 }
10019 return res;
10020 };
10021 }
10022
10023 function addHttpParam(paramName, opts, params, asJson) {
10024 // add an http param from opts to params, optionally json-encoded
10025 var val = opts[paramName];
10026 if (typeof val !== 'undefined') {
10027 if (asJson) {
10028 val = encodeURIComponent(JSON.stringify(val));
10029 }
10030 params.push(paramName + '=' + val);
10031 }
10032 }
10033
10034 function coerceInteger(integerCandidate) {
10035 if (typeof integerCandidate !== 'undefined') {
10036 var asNumber = Number(integerCandidate);
10037 // prevents e.g. '1foo' or '1.1' being coerced to 1
10038 if (!isNaN(asNumber) && asNumber === parseInt(integerCandidate, 10)) {
10039 return asNumber;
10040 } else {
10041 return integerCandidate;
10042 }
10043 }
10044 }
10045
10046 function coerceOptions(opts) {
10047 opts.group_level = coerceInteger(opts.group_level);
10048 opts.limit = coerceInteger(opts.limit);
10049 opts.skip = coerceInteger(opts.skip);
10050 return opts;
10051 }
10052
10053 function checkPositiveInteger(number) {
10054 if (number) {
10055 if (typeof number !== 'number') {
10056 return new QueryParseError('Invalid value for integer: "' +
10057 number + '"');
10058 }
10059 if (number < 0) {
10060 return new QueryParseError('Invalid value for positive integer: ' +
10061 '"' + number + '"');
10062 }
10063 }
10064 }
10065
10066 function checkQueryParseError(options, fun) {
10067 var startkeyName = options.descending ? 'endkey' : 'startkey';
10068 var endkeyName = options.descending ? 'startkey' : 'endkey';
10069
10070 if (typeof options[startkeyName] !== 'undefined' &&
10071 typeof options[endkeyName] !== 'undefined' &&
10072 collate(options[startkeyName], options[endkeyName]) > 0) {
10073 throw new QueryParseError('No rows can match your key range, ' +
10074 'reverse your start_key and end_key or set {descending : true}');
10075 } else if (fun.reduce && options.reduce !== false) {
10076 if (options.include_docs) {
10077 throw new QueryParseError('{include_docs:true} is invalid for reduce');
10078 } else if (options.keys && options.keys.length > 1 &&
10079 !options.group && !options.group_level) {
10080 throw new QueryParseError('Multi-key fetches for reduce views must use ' +
10081 '{group: true}');
10082 }
10083 }
10084 ['group_level', 'limit', 'skip'].forEach(function (optionName) {
10085 var error = checkPositiveInteger(options[optionName]);
10086 if (error) {
10087 throw error;
10088 }
10089 });
10090 }
10091
10092 function httpQuery(db, fun, opts) {
10093 // List of parameters to add to the PUT request
10094 var params = [];
10095 var body;
10096 var method = 'GET';
10097 var ok, status;
10098
10099 // If opts.reduce exists and is defined, then add it to the list
10100 // of parameters.
10101 // If reduce=false then the results are that of only the map function
10102 // not the final result of map and reduce.
10103 addHttpParam('reduce', opts, params);
10104 addHttpParam('include_docs', opts, params);
10105 addHttpParam('attachments', opts, params);
10106 addHttpParam('limit', opts, params);
10107 addHttpParam('descending', opts, params);
10108 addHttpParam('group', opts, params);
10109 addHttpParam('group_level', opts, params);
10110 addHttpParam('skip', opts, params);
10111 addHttpParam('stale', opts, params);
10112 addHttpParam('conflicts', opts, params);
10113 addHttpParam('startkey', opts, params, true);
10114 addHttpParam('start_key', opts, params, true);
10115 addHttpParam('endkey', opts, params, true);
10116 addHttpParam('end_key', opts, params, true);
10117 addHttpParam('inclusive_end', opts, params);
10118 addHttpParam('key', opts, params, true);
10119 addHttpParam('update_seq', opts, params);
10120
10121 // Format the list of parameters into a valid URI query string
10122 params = params.join('&');
10123 params = params === '' ? '' : '?' + params;
10124
10125 // If keys are supplied, issue a POST to circumvent GET query string limits
10126 // see http://wiki.apache.org/couchdb/HTTP_view_API#Querying_Options
10127 if (typeof opts.keys !== 'undefined') {
10128 var MAX_URL_LENGTH = 2000;
10129 // according to http://stackoverflow.com/a/417184/680742,
10130 // the de facto URL length limit is 2000 characters
10131
10132 var keysAsString =
10133 'keys=' + encodeURIComponent(JSON.stringify(opts.keys));
10134 if (keysAsString.length + params.length + 1 <= MAX_URL_LENGTH) {
10135 // If the keys are short enough, do a GET. we do this to work around
10136 // Safari not understanding 304s on POSTs (see pouchdb/pouchdb#1239)
10137 params += (params[0] === '?' ? '&' : '?') + keysAsString;
10138 } else {
10139 method = 'POST';
10140 if (typeof fun === 'string') {
10141 body = {keys: opts.keys};
10142 } else { // fun is {map : mapfun}, so append to this
10143 fun.keys = opts.keys;
10144 }
10145 }
10146 }
10147
10148 // We are referencing a query defined in the design doc
10149 if (typeof fun === 'string') {
10150 var parts = parseViewName(fun);
10151 return db.fetch('_design/' + parts[0] + '/_view/' + parts[1] + params, {
10152 headers: new h({'Content-Type': 'application/json'}),
10153 method: method,
10154 body: JSON.stringify(body)
10155 }).then(function (response) {
10156 ok = response.ok;
10157 status = response.status;
10158 return response.json();
10159 }).then(function (result) {
10160 if (!ok) {
10161 result.status = status;
10162 throw generateErrorFromResponse(result);
10163 }
10164 // fail the entire request if the result contains an error
10165 result.rows.forEach(function (row) {
10166 /* istanbul ignore if */
10167 if (row.value && row.value.error && row.value.error === "builtin_reduce_error") {
10168 throw new Error(row.reason);
10169 }
10170 });
10171 return result;
10172 }).then(postprocessAttachments(opts));
10173 }
10174
10175 // We are using a temporary view, terrible for performance, good for testing
10176 body = body || {};
10177 Object.keys(fun).forEach(function (key) {
10178 if (Array.isArray(fun[key])) {
10179 body[key] = fun[key];
10180 } else {
10181 body[key] = fun[key].toString();
10182 }
10183 });
10184
10185 return db.fetch('_temp_view' + params, {
10186 headers: new h({'Content-Type': 'application/json'}),
10187 method: 'POST',
10188 body: JSON.stringify(body)
10189 }).then(function (response) {
10190 ok = response.ok;
10191 status = response.status;
10192 return response.json();
10193 }).then(function (result) {
10194 if (!ok) {
10195 result.status = status;
10196 throw generateErrorFromResponse(result);
10197 }
10198 return result;
10199 }).then(postprocessAttachments(opts));
10200 }
10201
10202 // custom adapters can define their own api._query
10203 // and override the default behavior
10204 /* istanbul ignore next */
10205 function customQuery(db, fun, opts) {
10206 return new Promise(function (resolve, reject) {
10207 db._query(fun, opts, function (err, res) {
10208 if (err) {
10209 return reject(err);
10210 }
10211 resolve(res);
10212 });
10213 });
10214 }
10215
10216 // custom adapters can define their own api._viewCleanup
10217 // and override the default behavior
10218 /* istanbul ignore next */
10219 function customViewCleanup(db) {
10220 return new Promise(function (resolve, reject) {
10221 db._viewCleanup(function (err, res) {
10222 if (err) {
10223 return reject(err);
10224 }
10225 resolve(res);
10226 });
10227 });
10228 }
10229
10230 function defaultsTo(value) {
10231 return function (reason) {
10232 /* istanbul ignore else */
10233 if (reason.status === 404) {
10234 return value;
10235 } else {
10236 throw reason;
10237 }
10238 };
10239 }
10240
10241 // returns a promise for a list of docs to update, based on the input docId.
10242 // the order doesn't matter, because post-3.2.0, bulkDocs
10243 // is an atomic operation in all three adapters.
10244 function getDocsToPersist(docId, view, docIdsToChangesAndEmits) {
10245 var metaDocId = '_local/doc_' + docId;
10246 var defaultMetaDoc = {_id: metaDocId, keys: []};
10247 var docData = docIdsToChangesAndEmits.get(docId);
10248 var indexableKeysToKeyValues = docData[0];
10249 var changes = docData[1];
10250
10251 function getMetaDoc() {
10252 if (isGenOne(changes)) {
10253 // generation 1, so we can safely assume initial state
10254 // for performance reasons (avoids unnecessary GETs)
10255 return Promise.resolve(defaultMetaDoc);
10256 }
10257 return view.db.get(metaDocId)["catch"](defaultsTo(defaultMetaDoc));
10258 }
10259
10260 function getKeyValueDocs(metaDoc) {
10261 if (!metaDoc.keys.length) {
10262 // no keys, no need for a lookup
10263 return Promise.resolve({rows: []});
10264 }
10265 return view.db.allDocs({
10266 keys: metaDoc.keys,
10267 include_docs: true
10268 });
10269 }
10270
10271 function processKeyValueDocs(metaDoc, kvDocsRes) {
10272 var kvDocs = [];
10273 var oldKeys = new ExportedSet();
10274
10275 for (var i = 0, len = kvDocsRes.rows.length; i < len; i++) {
10276 var row = kvDocsRes.rows[i];
10277 var doc = row.doc;
10278 if (!doc) { // deleted
10279 continue;
10280 }
10281 kvDocs.push(doc);
10282 oldKeys.add(doc._id);
10283 doc._deleted = !indexableKeysToKeyValues.has(doc._id);
10284 if (!doc._deleted) {
10285 var keyValue = indexableKeysToKeyValues.get(doc._id);
10286 if ('value' in keyValue) {
10287 doc.value = keyValue.value;
10288 }
10289 }
10290 }
10291 var newKeys = mapToKeysArray(indexableKeysToKeyValues);
10292 newKeys.forEach(function (key) {
10293 if (!oldKeys.has(key)) {
10294 // new doc
10295 var kvDoc = {
10296 _id: key
10297 };
10298 var keyValue = indexableKeysToKeyValues.get(key);
10299 if ('value' in keyValue) {
10300 kvDoc.value = keyValue.value;
10301 }
10302 kvDocs.push(kvDoc);
10303 }
10304 });
10305 metaDoc.keys = uniq(newKeys.concat(metaDoc.keys));
10306 kvDocs.push(metaDoc);
10307
10308 return kvDocs;
10309 }
10310
10311 return getMetaDoc().then(function (metaDoc) {
10312 return getKeyValueDocs(metaDoc).then(function (kvDocsRes) {
10313 return processKeyValueDocs(metaDoc, kvDocsRes);
10314 });
10315 });
10316 }
10317
10318 // updates all emitted key/value docs and metaDocs in the mrview database
10319 // for the given batch of documents from the source database
10320 function saveKeyValues(view, docIdsToChangesAndEmits, seq) {
10321 var seqDocId = '_local/lastSeq';
10322 return view.db.get(seqDocId)[
10323 "catch"](defaultsTo({_id: seqDocId, seq: 0}))
10324 .then(function (lastSeqDoc) {
10325 var docIds = mapToKeysArray(docIdsToChangesAndEmits);
10326 return Promise.all(docIds.map(function (docId) {
10327 return getDocsToPersist(docId, view, docIdsToChangesAndEmits);
10328 })).then(function (listOfDocsToPersist) {
10329 var docsToPersist = flatten(listOfDocsToPersist);
10330 lastSeqDoc.seq = seq;
10331 docsToPersist.push(lastSeqDoc);
10332 // write all docs in a single operation, update the seq once
10333 return view.db.bulkDocs({docs : docsToPersist});
10334 });
10335 });
10336 }
10337
10338 function getQueue(view) {
10339 var viewName = typeof view === 'string' ? view : view.name;
10340 var queue = persistentQueues[viewName];
10341 if (!queue) {
10342 queue = persistentQueues[viewName] = new TaskQueue$1();
10343 }
10344 return queue;
10345 }
10346
10347 function updateView(view) {
10348 return sequentialize(getQueue(view), function () {
10349 return updateViewInQueue(view);
10350 })();
10351 }
10352
10353 function updateViewInQueue(view) {
10354 // bind the emit function once
10355 var mapResults;
10356 var doc;
10357
10358 function emit(key, value) {
10359 var output = {id: doc._id, key: normalizeKey(key)};
10360 // Don't explicitly store the value unless it's defined and non-null.
10361 // This saves on storage space, because often people don't use it.
10362 if (typeof value !== 'undefined' && value !== null) {
10363 output.value = normalizeKey(value);
10364 }
10365 mapResults.push(output);
10366 }
10367
10368 var mapFun = mapper(view.mapFun, emit);
10369
10370 var currentSeq = view.seq || 0;
10371
10372 function processChange(docIdsToChangesAndEmits, seq) {
10373 return function () {
10374 return saveKeyValues(view, docIdsToChangesAndEmits, seq);
10375 };
10376 }
10377
10378 var queue = new TaskQueue$1();
10379
10380 function processNextBatch() {
10381 return view.sourceDB.changes({
10382 return_docs: true,
10383 conflicts: true,
10384 include_docs: true,
10385 style: 'all_docs',
10386 since: currentSeq,
10387 limit: CHANGES_BATCH_SIZE$1
10388 }).then(processBatch);
10389 }
10390
10391 function processBatch(response) {
10392 var results = response.results;
10393 if (!results.length) {
10394 return;
10395 }
10396 var docIdsToChangesAndEmits = createDocIdsToChangesAndEmits(results);
10397 queue.add(processChange(docIdsToChangesAndEmits, currentSeq));
10398 if (results.length < CHANGES_BATCH_SIZE$1) {
10399 return;
10400 }
10401 return processNextBatch();
10402 }
10403
10404 function createDocIdsToChangesAndEmits(results) {
10405 var docIdsToChangesAndEmits = new ExportedMap();
10406 for (var i = 0, len = results.length; i < len; i++) {
10407 var change = results[i];
10408 if (change.doc._id[0] !== '_') {
10409 mapResults = [];
10410 doc = change.doc;
10411
10412 if (!doc._deleted) {
10413 tryMap(view.sourceDB, mapFun, doc);
10414 }
10415 mapResults.sort(sortByKeyThenValue);
10416
10417 var indexableKeysToKeyValues = createIndexableKeysToKeyValues(mapResults);
10418 docIdsToChangesAndEmits.set(change.doc._id, [
10419 indexableKeysToKeyValues,
10420 change.changes
10421 ]);
10422 }
10423 currentSeq = change.seq;
10424 }
10425 return docIdsToChangesAndEmits;
10426 }
10427
10428 function createIndexableKeysToKeyValues(mapResults) {
10429 var indexableKeysToKeyValues = new ExportedMap();
10430 var lastKey;
10431 for (var i = 0, len = mapResults.length; i < len; i++) {
10432 var emittedKeyValue = mapResults[i];
10433 var complexKey = [emittedKeyValue.key, emittedKeyValue.id];
10434 if (i > 0 && collate(emittedKeyValue.key, lastKey) === 0) {
10435 complexKey.push(i); // dup key+id, so make it unique
10436 }
10437 indexableKeysToKeyValues.set(toIndexableString(complexKey), emittedKeyValue);
10438 lastKey = emittedKeyValue.key;
10439 }
10440 return indexableKeysToKeyValues;
10441 }
10442
10443 return processNextBatch().then(function () {
10444 return queue.finish();
10445 }).then(function () {
10446 view.seq = currentSeq;
10447 });
10448 }
10449
10450 function reduceView(view, results, options) {
10451 if (options.group_level === 0) {
10452 delete options.group_level;
10453 }
10454
10455 var shouldGroup = options.group || options.group_level;
10456
10457 var reduceFun = reducer(view.reduceFun);
10458
10459 var groups = [];
10460 var lvl = isNaN(options.group_level) ? Number.POSITIVE_INFINITY :
10461 options.group_level;
10462 results.forEach(function (e) {
10463 var last = groups[groups.length - 1];
10464 var groupKey = shouldGroup ? e.key : null;
10465
10466 // only set group_level for array keys
10467 if (shouldGroup && Array.isArray(groupKey)) {
10468 groupKey = groupKey.slice(0, lvl);
10469 }
10470
10471 if (last && collate(last.groupKey, groupKey) === 0) {
10472 last.keys.push([e.key, e.id]);
10473 last.values.push(e.value);
10474 return;
10475 }
10476 groups.push({
10477 keys: [[e.key, e.id]],
10478 values: [e.value],
10479 groupKey: groupKey
10480 });
10481 });
10482 results = [];
10483 for (var i = 0, len = groups.length; i < len; i++) {
10484 var e = groups[i];
10485 var reduceTry = tryReduce(view.sourceDB, reduceFun, e.keys, e.values, false);
10486 if (reduceTry.error && reduceTry.error instanceof BuiltInError) {
10487 // CouchDB returns an error if a built-in errors out
10488 throw reduceTry.error;
10489 }
10490 results.push({
10491 // CouchDB just sets the value to null if a non-built-in errors out
10492 value: reduceTry.error ? null : reduceTry.output,
10493 key: e.groupKey
10494 });
10495 }
10496 // no total_rows/offset when reducing
10497 return {rows: sliceResults(results, options.limit, options.skip)};
10498 }
10499
10500 function queryView(view, opts) {
10501 return sequentialize(getQueue(view), function () {
10502 return queryViewInQueue(view, opts);
10503 })();
10504 }
10505
10506 function queryViewInQueue(view, opts) {
10507 var totalRows;
10508 var shouldReduce = view.reduceFun && opts.reduce !== false;
10509 var skip = opts.skip || 0;
10510 if (typeof opts.keys !== 'undefined' && !opts.keys.length) {
10511 // equivalent query
10512 opts.limit = 0;
10513 delete opts.keys;
10514 }
10515
10516 function fetchFromView(viewOpts) {
10517 viewOpts.include_docs = true;
10518 return view.db.allDocs(viewOpts).then(function (res) {
10519 totalRows = res.total_rows;
10520 return res.rows.map(function (result) {
10521
10522 // implicit migration - in older versions of PouchDB,
10523 // we explicitly stored the doc as {id: ..., key: ..., value: ...}
10524 // this is tested in a migration test
10525 /* istanbul ignore next */
10526 if ('value' in result.doc && typeof result.doc.value === 'object' &&
10527 result.doc.value !== null) {
10528 var keys = Object.keys(result.doc.value).sort();
10529 // this detection method is not perfect, but it's unlikely the user
10530 // emitted a value which was an object with these 3 exact keys
10531 var expectedKeys = ['id', 'key', 'value'];
10532 if (!(keys < expectedKeys || keys > expectedKeys)) {
10533 return result.doc.value;
10534 }
10535 }
10536
10537 var parsedKeyAndDocId = parseIndexableString(result.doc._id);
10538 return {
10539 key: parsedKeyAndDocId[0],
10540 id: parsedKeyAndDocId[1],
10541 value: ('value' in result.doc ? result.doc.value : null)
10542 };
10543 });
10544 });
10545 }
10546
10547 function onMapResultsReady(rows) {
10548 var finalResults;
10549 if (shouldReduce) {
10550 finalResults = reduceView(view, rows, opts);
10551 } else {
10552 finalResults = {
10553 total_rows: totalRows,
10554 offset: skip,
10555 rows: rows
10556 };
10557 }
10558 /* istanbul ignore if */
10559 if (opts.update_seq) {
10560 finalResults.update_seq = view.seq;
10561 }
10562 if (opts.include_docs) {
10563 var docIds = uniq(rows.map(rowToDocId));
10564
10565 return view.sourceDB.allDocs({
10566 keys: docIds,
10567 include_docs: true,
10568 conflicts: opts.conflicts,
10569 attachments: opts.attachments,
10570 binary: opts.binary
10571 }).then(function (allDocsRes) {
10572 var docIdsToDocs = new ExportedMap();
10573 allDocsRes.rows.forEach(function (row) {
10574 docIdsToDocs.set(row.id, row.doc);
10575 });
10576 rows.forEach(function (row) {
10577 var docId = rowToDocId(row);
10578 var doc = docIdsToDocs.get(docId);
10579 if (doc) {
10580 row.doc = doc;
10581 }
10582 });
10583 return finalResults;
10584 });
10585 } else {
10586 return finalResults;
10587 }
10588 }
10589
10590 if (typeof opts.keys !== 'undefined') {
10591 var keys = opts.keys;
10592 var fetchPromises = keys.map(function (key) {
10593 var viewOpts = {
10594 startkey : toIndexableString([key]),
10595 endkey : toIndexableString([key, {}])
10596 };
10597 /* istanbul ignore if */
10598 if (opts.update_seq) {
10599 viewOpts.update_seq = true;
10600 }
10601 return fetchFromView(viewOpts);
10602 });
10603 return Promise.all(fetchPromises).then(flatten).then(onMapResultsReady);
10604 } else { // normal query, no 'keys'
10605 var viewOpts = {
10606 descending : opts.descending
10607 };
10608 /* istanbul ignore if */
10609 if (opts.update_seq) {
10610 viewOpts.update_seq = true;
10611 }
10612 var startkey;
10613 var endkey;
10614 if ('start_key' in opts) {
10615 startkey = opts.start_key;
10616 }
10617 if ('startkey' in opts) {
10618 startkey = opts.startkey;
10619 }
10620 if ('end_key' in opts) {
10621 endkey = opts.end_key;
10622 }
10623 if ('endkey' in opts) {
10624 endkey = opts.endkey;
10625 }
10626 if (typeof startkey !== 'undefined') {
10627 viewOpts.startkey = opts.descending ?
10628 toIndexableString([startkey, {}]) :
10629 toIndexableString([startkey]);
10630 }
10631 if (typeof endkey !== 'undefined') {
10632 var inclusiveEnd = opts.inclusive_end !== false;
10633 if (opts.descending) {
10634 inclusiveEnd = !inclusiveEnd;
10635 }
10636
10637 viewOpts.endkey = toIndexableString(
10638 inclusiveEnd ? [endkey, {}] : [endkey]);
10639 }
10640 if (typeof opts.key !== 'undefined') {
10641 var keyStart = toIndexableString([opts.key]);
10642 var keyEnd = toIndexableString([opts.key, {}]);
10643 if (viewOpts.descending) {
10644 viewOpts.endkey = keyStart;
10645 viewOpts.startkey = keyEnd;
10646 } else {
10647 viewOpts.startkey = keyStart;
10648 viewOpts.endkey = keyEnd;
10649 }
10650 }
10651 if (!shouldReduce) {
10652 if (typeof opts.limit === 'number') {
10653 viewOpts.limit = opts.limit;
10654 }
10655 viewOpts.skip = skip;
10656 }
10657 return fetchFromView(viewOpts).then(onMapResultsReady);
10658 }
10659 }
10660
10661 function httpViewCleanup(db) {
10662 return db.fetch('_view_cleanup', {
10663 headers: new h({'Content-Type': 'application/json'}),
10664 method: 'POST'
10665 }).then(function (response) {
10666 return response.json();
10667 });
10668 }
10669
10670 function localViewCleanup(db) {
10671 return db.get('_local/' + localDocName).then(function (metaDoc) {
10672 var docsToViews = new ExportedMap();
10673 Object.keys(metaDoc.views).forEach(function (fullViewName) {
10674 var parts = parseViewName(fullViewName);
10675 var designDocName = '_design/' + parts[0];
10676 var viewName = parts[1];
10677 var views = docsToViews.get(designDocName);
10678 if (!views) {
10679 views = new ExportedSet();
10680 docsToViews.set(designDocName, views);
10681 }
10682 views.add(viewName);
10683 });
10684 var opts = {
10685 keys : mapToKeysArray(docsToViews),
10686 include_docs : true
10687 };
10688 return db.allDocs(opts).then(function (res) {
10689 var viewsToStatus = {};
10690 res.rows.forEach(function (row) {
10691 var ddocName = row.key.substring(8); // cuts off '_design/'
10692 docsToViews.get(row.key).forEach(function (viewName) {
10693 var fullViewName = ddocName + '/' + viewName;
10694 /* istanbul ignore if */
10695 if (!metaDoc.views[fullViewName]) {
10696 // new format, without slashes, to support PouchDB 2.2.0
10697 // migration test in pouchdb's browser.migration.js verifies this
10698 fullViewName = viewName;
10699 }
10700 var viewDBNames = Object.keys(metaDoc.views[fullViewName]);
10701 // design doc deleted, or view function nonexistent
10702 var statusIsGood = row.doc && row.doc.views &&
10703 row.doc.views[viewName];
10704 viewDBNames.forEach(function (viewDBName) {
10705 viewsToStatus[viewDBName] =
10706 viewsToStatus[viewDBName] || statusIsGood;
10707 });
10708 });
10709 });
10710 var dbsToDelete = Object.keys(viewsToStatus).filter(
10711 function (viewDBName) { return !viewsToStatus[viewDBName]; });
10712 var destroyPromises = dbsToDelete.map(function (viewDBName) {
10713 return sequentialize(getQueue(viewDBName), function () {
10714 return new db.constructor(viewDBName, db.__opts).destroy();
10715 })();
10716 });
10717 return Promise.all(destroyPromises).then(function () {
10718 return {ok: true};
10719 });
10720 });
10721 }, defaultsTo({ok: true}));
10722 }
10723
10724 function queryPromised(db, fun, opts) {
10725 /* istanbul ignore next */
10726 if (typeof db._query === 'function') {
10727 return customQuery(db, fun, opts);
10728 }
10729 if (isRemote(db)) {
10730 return httpQuery(db, fun, opts);
10731 }
10732
10733 if (typeof fun !== 'string') {
10734 // temp_view
10735 checkQueryParseError(opts, fun);
10736
10737 tempViewQueue.add(function () {
10738 var createViewPromise = createView(
10739 /* sourceDB */ db,
10740 /* viewName */ 'temp_view/temp_view',
10741 /* mapFun */ fun.map,
10742 /* reduceFun */ fun.reduce,
10743 /* temporary */ true,
10744 /* localDocName */ localDocName);
10745 return createViewPromise.then(function (view) {
10746 return fin(updateView(view).then(function () {
10747 return queryView(view, opts);
10748 }), function () {
10749 return view.db.destroy();
10750 });
10751 });
10752 });
10753 return tempViewQueue.finish();
10754 } else {
10755 // persistent view
10756 var fullViewName = fun;
10757 var parts = parseViewName(fullViewName);
10758 var designDocName = parts[0];
10759 var viewName = parts[1];
10760 return db.get('_design/' + designDocName).then(function (doc) {
10761 var fun = doc.views && doc.views[viewName];
10762
10763 if (!fun) {
10764 // basic validator; it's assumed that every subclass would want this
10765 throw new NotFoundError('ddoc ' + doc._id + ' has no view named ' +
10766 viewName);
10767 }
10768
10769 ddocValidator(doc, viewName);
10770 checkQueryParseError(opts, fun);
10771
10772 var createViewPromise = createView(
10773 /* sourceDB */ db,
10774 /* viewName */ fullViewName,
10775 /* mapFun */ fun.map,
10776 /* reduceFun */ fun.reduce,
10777 /* temporary */ false,
10778 /* localDocName */ localDocName);
10779 return createViewPromise.then(function (view) {
10780 if (opts.stale === 'ok' || opts.stale === 'update_after') {
10781 if (opts.stale === 'update_after') {
10782 immediate(function () {
10783 updateView(view);
10784 });
10785 }
10786 return queryView(view, opts);
10787 } else { // stale not ok
10788 return updateView(view).then(function () {
10789 return queryView(view, opts);
10790 });
10791 }
10792 });
10793 });
10794 }
10795 }
10796
10797 function abstractQuery(fun, opts, callback) {
10798 var db = this;
10799 if (typeof opts === 'function') {
10800 callback = opts;
10801 opts = {};
10802 }
10803 opts = opts ? coerceOptions(opts) : {};
10804
10805 if (typeof fun === 'function') {
10806 fun = {map : fun};
10807 }
10808
10809 var promise = Promise.resolve().then(function () {
10810 return queryPromised(db, fun, opts);
10811 });
10812 promisedCallback(promise, callback);
10813 return promise;
10814 }
10815
10816 var abstractViewCleanup = callbackify(function () {
10817 var db = this;
10818 /* istanbul ignore next */
10819 if (typeof db._viewCleanup === 'function') {
10820 return customViewCleanup(db);
10821 }
10822 if (isRemote(db)) {
10823 return httpViewCleanup(db);
10824 }
10825 return localViewCleanup(db);
10826 });
10827
10828 return {
10829 query: abstractQuery,
10830 viewCleanup: abstractViewCleanup
10831 };
10832}
10833
10834var builtInReduce = {
10835 _sum: function (keys, values) {
10836 return sum(values);
10837 },
10838
10839 _count: function (keys, values) {
10840 return values.length;
10841 },
10842
10843 _stats: function (keys, values) {
10844 // no need to implement rereduce=true, because Pouch
10845 // will never call it
10846 function sumsqr(values) {
10847 var _sumsqr = 0;
10848 for (var i = 0, len = values.length; i < len; i++) {
10849 var num = values[i];
10850 _sumsqr += (num * num);
10851 }
10852 return _sumsqr;
10853 }
10854 return {
10855 sum : sum(values),
10856 min : Math.min.apply(null, values),
10857 max : Math.max.apply(null, values),
10858 count : values.length,
10859 sumsqr : sumsqr(values)
10860 };
10861 }
10862};
10863
10864function getBuiltIn(reduceFunString) {
10865 if (/^_sum/.test(reduceFunString)) {
10866 return builtInReduce._sum;
10867 } else if (/^_count/.test(reduceFunString)) {
10868 return builtInReduce._count;
10869 } else if (/^_stats/.test(reduceFunString)) {
10870 return builtInReduce._stats;
10871 } else if (/^_/.test(reduceFunString)) {
10872 throw new Error(reduceFunString + ' is not a supported reduce function.');
10873 }
10874}
10875
10876function mapper(mapFun, emit) {
10877 // for temp_views one can use emit(doc, emit), see #38
10878 if (typeof mapFun === "function" && mapFun.length === 2) {
10879 var origMap = mapFun;
10880 return function (doc) {
10881 return origMap(doc, emit);
10882 };
10883 } else {
10884 return evalFunctionWithEval(mapFun.toString(), emit);
10885 }
10886}
10887
10888function reducer(reduceFun) {
10889 var reduceFunString = reduceFun.toString();
10890 var builtIn = getBuiltIn(reduceFunString);
10891 if (builtIn) {
10892 return builtIn;
10893 } else {
10894 return evalFunctionWithEval(reduceFunString);
10895 }
10896}
10897
10898function ddocValidator(ddoc, viewName) {
10899 var fun = ddoc.views && ddoc.views[viewName];
10900 if (typeof fun.map !== 'string') {
10901 throw new NotFoundError('ddoc ' + ddoc._id + ' has no string view named ' +
10902 viewName + ', instead found object of type: ' + typeof fun.map);
10903 }
10904}
10905
10906var localDocName = 'mrviews';
10907var abstract = createAbstractMapReduce(localDocName, mapper, reducer, ddocValidator);
10908
10909function query(fun, opts, callback) {
10910 return abstract.query.call(this, fun, opts, callback);
10911}
10912
10913function viewCleanup(callback) {
10914 return abstract.viewCleanup.call(this, callback);
10915}
10916
10917var mapreduce = {
10918 query: query,
10919 viewCleanup: viewCleanup
10920};
10921
10922function isGenOne$1(rev$$1) {
10923 return /^1-/.test(rev$$1);
10924}
10925
10926function fileHasChanged(localDoc, remoteDoc, filename) {
10927 return !localDoc._attachments ||
10928 !localDoc._attachments[filename] ||
10929 localDoc._attachments[filename].digest !== remoteDoc._attachments[filename].digest;
10930}
10931
10932function getDocAttachments(db, doc) {
10933 var filenames = Object.keys(doc._attachments);
10934 return Promise.all(filenames.map(function (filename) {
10935 return db.getAttachment(doc._id, filename, {rev: doc._rev});
10936 }));
10937}
10938
10939function getDocAttachmentsFromTargetOrSource(target, src, doc) {
10940 var doCheckForLocalAttachments = isRemote(src) && !isRemote(target);
10941 var filenames = Object.keys(doc._attachments);
10942
10943 if (!doCheckForLocalAttachments) {
10944 return getDocAttachments(src, doc);
10945 }
10946
10947 return target.get(doc._id).then(function (localDoc) {
10948 return Promise.all(filenames.map(function (filename) {
10949 if (fileHasChanged(localDoc, doc, filename)) {
10950 return src.getAttachment(doc._id, filename);
10951 }
10952
10953 return target.getAttachment(localDoc._id, filename);
10954 }));
10955 })["catch"](function (error) {
10956 /* istanbul ignore if */
10957 if (error.status !== 404) {
10958 throw error;
10959 }
10960
10961 return getDocAttachments(src, doc);
10962 });
10963}
10964
10965function createBulkGetOpts(diffs) {
10966 var requests = [];
10967 Object.keys(diffs).forEach(function (id) {
10968 var missingRevs = diffs[id].missing;
10969 missingRevs.forEach(function (missingRev) {
10970 requests.push({
10971 id: id,
10972 rev: missingRev
10973 });
10974 });
10975 });
10976
10977 return {
10978 docs: requests,
10979 revs: true,
10980 latest: true
10981 };
10982}
10983
10984//
10985// Fetch all the documents from the src as described in the "diffs",
10986// which is a mapping of docs IDs to revisions. If the state ever
10987// changes to "cancelled", then the returned promise will be rejected.
10988// Else it will be resolved with a list of fetched documents.
10989//
10990function getDocs(src, target, diffs, state) {
10991 diffs = clone(diffs); // we do not need to modify this
10992
10993 var resultDocs = [],
10994 ok = true;
10995
10996 function getAllDocs() {
10997
10998 var bulkGetOpts = createBulkGetOpts(diffs);
10999
11000 if (!bulkGetOpts.docs.length) { // optimization: skip empty requests
11001 return;
11002 }
11003
11004 return src.bulkGet(bulkGetOpts).then(function (bulkGetResponse) {
11005 /* istanbul ignore if */
11006 if (state.cancelled) {
11007 throw new Error('cancelled');
11008 }
11009 return Promise.all(bulkGetResponse.results.map(function (bulkGetInfo) {
11010 return Promise.all(bulkGetInfo.docs.map(function (doc) {
11011 var remoteDoc = doc.ok;
11012
11013 if (doc.error) {
11014 // when AUTO_COMPACTION is set, docs can be returned which look
11015 // like this: {"missing":"1-7c3ac256b693c462af8442f992b83696"}
11016 ok = false;
11017 }
11018
11019 if (!remoteDoc || !remoteDoc._attachments) {
11020 return remoteDoc;
11021 }
11022
11023 return getDocAttachmentsFromTargetOrSource(target, src, remoteDoc)
11024 .then(function (attachments) {
11025 var filenames = Object.keys(remoteDoc._attachments);
11026 attachments
11027 .forEach(function (attachment, i) {
11028 var att = remoteDoc._attachments[filenames[i]];
11029 delete att.stub;
11030 delete att.length;
11031 att.data = attachment;
11032 });
11033
11034 return remoteDoc;
11035 });
11036 }));
11037 }))
11038
11039 .then(function (results) {
11040 resultDocs = resultDocs.concat(flatten(results).filter(Boolean));
11041 });
11042 });
11043 }
11044
11045 function hasAttachments(doc) {
11046 return doc._attachments && Object.keys(doc._attachments).length > 0;
11047 }
11048
11049 function hasConflicts(doc) {
11050 return doc._conflicts && doc._conflicts.length > 0;
11051 }
11052
11053 function fetchRevisionOneDocs(ids) {
11054 // Optimization: fetch gen-1 docs and attachments in
11055 // a single request using _all_docs
11056 return src.allDocs({
11057 keys: ids,
11058 include_docs: true,
11059 conflicts: true
11060 }).then(function (res) {
11061 if (state.cancelled) {
11062 throw new Error('cancelled');
11063 }
11064 res.rows.forEach(function (row) {
11065 if (row.deleted || !row.doc || !isGenOne$1(row.value.rev) ||
11066 hasAttachments(row.doc) || hasConflicts(row.doc)) {
11067 // if any of these conditions apply, we need to fetch using get()
11068 return;
11069 }
11070
11071 // strip _conflicts array to appease CSG (#5793)
11072 /* istanbul ignore if */
11073 if (row.doc._conflicts) {
11074 delete row.doc._conflicts;
11075 }
11076
11077 // the doc we got back from allDocs() is sufficient
11078 resultDocs.push(row.doc);
11079 delete diffs[row.id];
11080 });
11081 });
11082 }
11083
11084 function getRevisionOneDocs() {
11085 // filter out the generation 1 docs and get them
11086 // leaving the non-generation one docs to be got otherwise
11087 var ids = Object.keys(diffs).filter(function (id) {
11088 var missing = diffs[id].missing;
11089 return missing.length === 1 && isGenOne$1(missing[0]);
11090 });
11091 if (ids.length > 0) {
11092 return fetchRevisionOneDocs(ids);
11093 }
11094 }
11095
11096 function returnResult() {
11097 return { ok:ok, docs:resultDocs };
11098 }
11099
11100 return Promise.resolve()
11101 .then(getRevisionOneDocs)
11102 .then(getAllDocs)
11103 .then(returnResult);
11104}
11105
11106var CHECKPOINT_VERSION = 1;
11107var REPLICATOR = "pouchdb";
11108// This is an arbitrary number to limit the
11109// amount of replication history we save in the checkpoint.
11110// If we save too much, the checkpoing docs will become very big,
11111// if we save fewer, we'll run a greater risk of having to
11112// read all the changes from 0 when checkpoint PUTs fail
11113// CouchDB 2.0 has a more involved history pruning,
11114// but let's go for the simple version for now.
11115var CHECKPOINT_HISTORY_SIZE = 5;
11116var LOWEST_SEQ = 0;
11117
11118function updateCheckpoint(db, id, checkpoint, session, returnValue) {
11119 return db.get(id)["catch"](function (err) {
11120 if (err.status === 404) {
11121 if (db.adapter === 'http' || db.adapter === 'https') {
11122 explainError(
11123 404, 'PouchDB is just checking if a remote checkpoint exists.'
11124 );
11125 }
11126 return {
11127 session_id: session,
11128 _id: id,
11129 history: [],
11130 replicator: REPLICATOR,
11131 version: CHECKPOINT_VERSION
11132 };
11133 }
11134 throw err;
11135 }).then(function (doc) {
11136 if (returnValue.cancelled) {
11137 return;
11138 }
11139
11140 // if the checkpoint has not changed, do not update
11141 if (doc.last_seq === checkpoint) {
11142 return;
11143 }
11144
11145 // Filter out current entry for this replication
11146 doc.history = (doc.history || []).filter(function (item) {
11147 return item.session_id !== session;
11148 });
11149
11150 // Add the latest checkpoint to history
11151 doc.history.unshift({
11152 last_seq: checkpoint,
11153 session_id: session
11154 });
11155
11156 // Just take the last pieces in history, to
11157 // avoid really big checkpoint docs.
11158 // see comment on history size above
11159 doc.history = doc.history.slice(0, CHECKPOINT_HISTORY_SIZE);
11160
11161 doc.version = CHECKPOINT_VERSION;
11162 doc.replicator = REPLICATOR;
11163
11164 doc.session_id = session;
11165 doc.last_seq = checkpoint;
11166
11167 return db.put(doc)["catch"](function (err) {
11168 if (err.status === 409) {
11169 // retry; someone is trying to write a checkpoint simultaneously
11170 return updateCheckpoint(db, id, checkpoint, session, returnValue);
11171 }
11172 throw err;
11173 });
11174 });
11175}
11176
11177function Checkpointer(src, target, id, returnValue, opts) {
11178 this.src = src;
11179 this.target = target;
11180 this.id = id;
11181 this.returnValue = returnValue;
11182 this.opts = opts || {};
11183}
11184
11185Checkpointer.prototype.writeCheckpoint = function (checkpoint, session) {
11186 var self = this;
11187 return this.updateTarget(checkpoint, session).then(function () {
11188 return self.updateSource(checkpoint, session);
11189 });
11190};
11191
11192Checkpointer.prototype.updateTarget = function (checkpoint, session) {
11193 if (this.opts.writeTargetCheckpoint) {
11194 return updateCheckpoint(this.target, this.id, checkpoint,
11195 session, this.returnValue);
11196 } else {
11197 return Promise.resolve(true);
11198 }
11199};
11200
11201Checkpointer.prototype.updateSource = function (checkpoint, session) {
11202 if (this.opts.writeSourceCheckpoint) {
11203 var self = this;
11204 return updateCheckpoint(this.src, this.id, checkpoint,
11205 session, this.returnValue)[
11206 "catch"](function (err) {
11207 if (isForbiddenError(err)) {
11208 self.opts.writeSourceCheckpoint = false;
11209 return true;
11210 }
11211 throw err;
11212 });
11213 } else {
11214 return Promise.resolve(true);
11215 }
11216};
11217
11218var comparisons = {
11219 "undefined": function (targetDoc, sourceDoc) {
11220 // This is the previous comparison function
11221 if (collate(targetDoc.last_seq, sourceDoc.last_seq) === 0) {
11222 return sourceDoc.last_seq;
11223 }
11224 /* istanbul ignore next */
11225 return 0;
11226 },
11227 "1": function (targetDoc, sourceDoc) {
11228 // This is the comparison function ported from CouchDB
11229 return compareReplicationLogs(sourceDoc, targetDoc).last_seq;
11230 }
11231};
11232
11233Checkpointer.prototype.getCheckpoint = function () {
11234 var self = this;
11235
11236 if (self.opts && self.opts.writeSourceCheckpoint && !self.opts.writeTargetCheckpoint) {
11237 return self.src.get(self.id).then(function (sourceDoc) {
11238 return sourceDoc.last_seq || LOWEST_SEQ;
11239 })["catch"](function (err) {
11240 /* istanbul ignore if */
11241 if (err.status !== 404) {
11242 throw err;
11243 }
11244 return LOWEST_SEQ;
11245 });
11246 }
11247
11248 return self.target.get(self.id).then(function (targetDoc) {
11249 if (self.opts && self.opts.writeTargetCheckpoint && !self.opts.writeSourceCheckpoint) {
11250 return targetDoc.last_seq || LOWEST_SEQ;
11251 }
11252
11253 return self.src.get(self.id).then(function (sourceDoc) {
11254 // Since we can't migrate an old version doc to a new one
11255 // (no session id), we just go with the lowest seq in this case
11256 /* istanbul ignore if */
11257 if (targetDoc.version !== sourceDoc.version) {
11258 return LOWEST_SEQ;
11259 }
11260
11261 var version;
11262 if (targetDoc.version) {
11263 version = targetDoc.version.toString();
11264 } else {
11265 version = "undefined";
11266 }
11267
11268 if (version in comparisons) {
11269 return comparisons[version](targetDoc, sourceDoc);
11270 }
11271 /* istanbul ignore next */
11272 return LOWEST_SEQ;
11273 }, function (err) {
11274 if (err.status === 404 && targetDoc.last_seq) {
11275 return self.src.put({
11276 _id: self.id,
11277 last_seq: LOWEST_SEQ
11278 }).then(function () {
11279 return LOWEST_SEQ;
11280 }, function (err) {
11281 if (isForbiddenError(err)) {
11282 self.opts.writeSourceCheckpoint = false;
11283 return targetDoc.last_seq;
11284 }
11285 /* istanbul ignore next */
11286 return LOWEST_SEQ;
11287 });
11288 }
11289 throw err;
11290 });
11291 })["catch"](function (err) {
11292 if (err.status !== 404) {
11293 throw err;
11294 }
11295 return LOWEST_SEQ;
11296 });
11297};
11298// This checkpoint comparison is ported from CouchDBs source
11299// they come from here:
11300// https://github.com/apache/couchdb-couch-replicator/blob/master/src/couch_replicator.erl#L863-L906
11301
11302function compareReplicationLogs(srcDoc, tgtDoc) {
11303 if (srcDoc.session_id === tgtDoc.session_id) {
11304 return {
11305 last_seq: srcDoc.last_seq,
11306 history: srcDoc.history
11307 };
11308 }
11309
11310 return compareReplicationHistory(srcDoc.history, tgtDoc.history);
11311}
11312
11313function compareReplicationHistory(sourceHistory, targetHistory) {
11314 // the erlang loop via function arguments is not so easy to repeat in JS
11315 // therefore, doing this as recursion
11316 var S = sourceHistory[0];
11317 var sourceRest = sourceHistory.slice(1);
11318 var T = targetHistory[0];
11319 var targetRest = targetHistory.slice(1);
11320
11321 if (!S || targetHistory.length === 0) {
11322 return {
11323 last_seq: LOWEST_SEQ,
11324 history: []
11325 };
11326 }
11327
11328 var sourceId = S.session_id;
11329 /* istanbul ignore if */
11330 if (hasSessionId(sourceId, targetHistory)) {
11331 return {
11332 last_seq: S.last_seq,
11333 history: sourceHistory
11334 };
11335 }
11336
11337 var targetId = T.session_id;
11338 if (hasSessionId(targetId, sourceRest)) {
11339 return {
11340 last_seq: T.last_seq,
11341 history: targetRest
11342 };
11343 }
11344
11345 return compareReplicationHistory(sourceRest, targetRest);
11346}
11347
11348function hasSessionId(sessionId, history) {
11349 var props = history[0];
11350 var rest = history.slice(1);
11351
11352 if (!sessionId || history.length === 0) {
11353 return false;
11354 }
11355
11356 if (sessionId === props.session_id) {
11357 return true;
11358 }
11359
11360 return hasSessionId(sessionId, rest);
11361}
11362
11363function isForbiddenError(err) {
11364 return typeof err.status === 'number' && Math.floor(err.status / 100) === 4;
11365}
11366
11367var STARTING_BACK_OFF = 0;
11368
11369function backOff(opts, returnValue, error, callback) {
11370 if (opts.retry === false) {
11371 returnValue.emit('error', error);
11372 returnValue.removeAllListeners();
11373 return;
11374 }
11375 /* istanbul ignore if */
11376 if (typeof opts.back_off_function !== 'function') {
11377 opts.back_off_function = defaultBackOff;
11378 }
11379 returnValue.emit('requestError', error);
11380 if (returnValue.state === 'active' || returnValue.state === 'pending') {
11381 returnValue.emit('paused', error);
11382 returnValue.state = 'stopped';
11383 var backOffSet = function backoffTimeSet() {
11384 opts.current_back_off = STARTING_BACK_OFF;
11385 };
11386 var removeBackOffSetter = function removeBackOffTimeSet() {
11387 returnValue.removeListener('active', backOffSet);
11388 };
11389 returnValue.once('paused', removeBackOffSetter);
11390 returnValue.once('active', backOffSet);
11391 }
11392
11393 opts.current_back_off = opts.current_back_off || STARTING_BACK_OFF;
11394 opts.current_back_off = opts.back_off_function(opts.current_back_off);
11395 setTimeout(callback, opts.current_back_off);
11396}
11397
11398function sortObjectPropertiesByKey(queryParams) {
11399 return Object.keys(queryParams).sort(collate).reduce(function (result, key) {
11400 result[key] = queryParams[key];
11401 return result;
11402 }, {});
11403}
11404
11405// Generate a unique id particular to this replication.
11406// Not guaranteed to align perfectly with CouchDB's rep ids.
11407function generateReplicationId(src, target, opts) {
11408 var docIds = opts.doc_ids ? opts.doc_ids.sort(collate) : '';
11409 var filterFun = opts.filter ? opts.filter.toString() : '';
11410 var queryParams = '';
11411 var filterViewName = '';
11412 var selector = '';
11413
11414 // possibility for checkpoints to be lost here as behaviour of
11415 // JSON.stringify is not stable (see #6226)
11416 /* istanbul ignore if */
11417 if (opts.selector) {
11418 selector = JSON.stringify(opts.selector);
11419 }
11420
11421 if (opts.filter && opts.query_params) {
11422 queryParams = JSON.stringify(sortObjectPropertiesByKey(opts.query_params));
11423 }
11424
11425 if (opts.filter && opts.filter === '_view') {
11426 filterViewName = opts.view.toString();
11427 }
11428
11429 return Promise.all([src.id(), target.id()]).then(function (res) {
11430 var queryData = res[0] + res[1] + filterFun + filterViewName +
11431 queryParams + docIds + selector;
11432 return new Promise(function (resolve) {
11433 binaryMd5(queryData, resolve);
11434 });
11435 }).then(function (md5sum) {
11436 // can't use straight-up md5 alphabet, because
11437 // the char '/' is interpreted as being for attachments,
11438 // and + is also not url-safe
11439 md5sum = md5sum.replace(/\//g, '.').replace(/\+/g, '_');
11440 return '_local/' + md5sum;
11441 });
11442}
11443
11444function replicate(src, target, opts, returnValue, result) {
11445 var batches = []; // list of batches to be processed
11446 var currentBatch; // the batch currently being processed
11447 var pendingBatch = {
11448 seq: 0,
11449 changes: [],
11450 docs: []
11451 }; // next batch, not yet ready to be processed
11452 var writingCheckpoint = false; // true while checkpoint is being written
11453 var changesCompleted = false; // true when all changes received
11454 var replicationCompleted = false; // true when replication has completed
11455 var last_seq = 0;
11456 var continuous = opts.continuous || opts.live || false;
11457 var batch_size = opts.batch_size || 100;
11458 var batches_limit = opts.batches_limit || 10;
11459 var changesPending = false; // true while src.changes is running
11460 var doc_ids = opts.doc_ids;
11461 var selector = opts.selector;
11462 var repId;
11463 var checkpointer;
11464 var changedDocs = [];
11465 // Like couchdb, every replication gets a unique session id
11466 var session = uuid();
11467
11468 result = result || {
11469 ok: true,
11470 start_time: new Date().toISOString(),
11471 docs_read: 0,
11472 docs_written: 0,
11473 doc_write_failures: 0,
11474 errors: []
11475 };
11476
11477 var changesOpts = {};
11478 returnValue.ready(src, target);
11479
11480 function initCheckpointer() {
11481 if (checkpointer) {
11482 return Promise.resolve();
11483 }
11484 return generateReplicationId(src, target, opts).then(function (res) {
11485 repId = res;
11486
11487 var checkpointOpts = {};
11488 if (opts.checkpoint === false) {
11489 checkpointOpts = { writeSourceCheckpoint: false, writeTargetCheckpoint: false };
11490 } else if (opts.checkpoint === 'source') {
11491 checkpointOpts = { writeSourceCheckpoint: true, writeTargetCheckpoint: false };
11492 } else if (opts.checkpoint === 'target') {
11493 checkpointOpts = { writeSourceCheckpoint: false, writeTargetCheckpoint: true };
11494 } else {
11495 checkpointOpts = { writeSourceCheckpoint: true, writeTargetCheckpoint: true };
11496 }
11497
11498 checkpointer = new Checkpointer(src, target, repId, returnValue, checkpointOpts);
11499 });
11500 }
11501
11502 function writeDocs() {
11503 changedDocs = [];
11504
11505 if (currentBatch.docs.length === 0) {
11506 return;
11507 }
11508 var docs = currentBatch.docs;
11509 var bulkOpts = {timeout: opts.timeout};
11510 return target.bulkDocs({docs: docs, new_edits: false}, bulkOpts).then(function (res) {
11511 /* istanbul ignore if */
11512 if (returnValue.cancelled) {
11513 completeReplication();
11514 throw new Error('cancelled');
11515 }
11516
11517 // `res` doesn't include full documents (which live in `docs`), so we create a map of
11518 // (id -> error), and check for errors while iterating over `docs`
11519 var errorsById = Object.create(null);
11520 res.forEach(function (res) {
11521 if (res.error) {
11522 errorsById[res.id] = res;
11523 }
11524 });
11525
11526 var errorsNo = Object.keys(errorsById).length;
11527 result.doc_write_failures += errorsNo;
11528 result.docs_written += docs.length - errorsNo;
11529
11530 docs.forEach(function (doc) {
11531 var error = errorsById[doc._id];
11532 if (error) {
11533 result.errors.push(error);
11534 // Normalize error name. i.e. 'Unauthorized' -> 'unauthorized' (eg Sync Gateway)
11535 var errorName = (error.name || '').toLowerCase();
11536 if (errorName === 'unauthorized' || errorName === 'forbidden') {
11537 returnValue.emit('denied', clone(error));
11538 } else {
11539 throw error;
11540 }
11541 } else {
11542 changedDocs.push(doc);
11543 }
11544 });
11545
11546 }, function (err) {
11547 result.doc_write_failures += docs.length;
11548 throw err;
11549 });
11550 }
11551
11552 function finishBatch() {
11553 if (currentBatch.error) {
11554 throw new Error('There was a problem getting docs.');
11555 }
11556 result.last_seq = last_seq = currentBatch.seq;
11557 var outResult = clone(result);
11558 if (changedDocs.length) {
11559 outResult.docs = changedDocs;
11560 // Attach 'pending' property if server supports it (CouchDB 2.0+)
11561 /* istanbul ignore if */
11562 if (typeof currentBatch.pending === 'number') {
11563 outResult.pending = currentBatch.pending;
11564 delete currentBatch.pending;
11565 }
11566 returnValue.emit('change', outResult);
11567 }
11568 writingCheckpoint = true;
11569 return checkpointer.writeCheckpoint(currentBatch.seq,
11570 session).then(function () {
11571 writingCheckpoint = false;
11572 /* istanbul ignore if */
11573 if (returnValue.cancelled) {
11574 completeReplication();
11575 throw new Error('cancelled');
11576 }
11577 currentBatch = undefined;
11578 getChanges();
11579 })["catch"](function (err) {
11580 onCheckpointError(err);
11581 throw err;
11582 });
11583 }
11584
11585 function getDiffs() {
11586 var diff = {};
11587 currentBatch.changes.forEach(function (change) {
11588 // Couchbase Sync Gateway emits these, but we can ignore them
11589 /* istanbul ignore if */
11590 if (change.id === "_user/") {
11591 return;
11592 }
11593 diff[change.id] = change.changes.map(function (x) {
11594 return x.rev;
11595 });
11596 });
11597 return target.revsDiff(diff).then(function (diffs) {
11598 /* istanbul ignore if */
11599 if (returnValue.cancelled) {
11600 completeReplication();
11601 throw new Error('cancelled');
11602 }
11603 // currentBatch.diffs elements are deleted as the documents are written
11604 currentBatch.diffs = diffs;
11605 });
11606 }
11607
11608 function getBatchDocs() {
11609 return getDocs(src, target, currentBatch.diffs, returnValue).then(function (got) {
11610 currentBatch.error = !got.ok;
11611 got.docs.forEach(function (doc) {
11612 delete currentBatch.diffs[doc._id];
11613 result.docs_read++;
11614 currentBatch.docs.push(doc);
11615 });
11616 });
11617 }
11618
11619 function startNextBatch() {
11620 if (returnValue.cancelled || currentBatch) {
11621 return;
11622 }
11623 if (batches.length === 0) {
11624 processPendingBatch(true);
11625 return;
11626 }
11627 currentBatch = batches.shift();
11628 getDiffs()
11629 .then(getBatchDocs)
11630 .then(writeDocs)
11631 .then(finishBatch)
11632 .then(startNextBatch)[
11633 "catch"](function (err) {
11634 abortReplication('batch processing terminated with error', err);
11635 });
11636 }
11637
11638
11639 function processPendingBatch(immediate$$1) {
11640 if (pendingBatch.changes.length === 0) {
11641 if (batches.length === 0 && !currentBatch) {
11642 if ((continuous && changesOpts.live) || changesCompleted) {
11643 returnValue.state = 'pending';
11644 returnValue.emit('paused');
11645 }
11646 if (changesCompleted) {
11647 completeReplication();
11648 }
11649 }
11650 return;
11651 }
11652 if (
11653 immediate$$1 ||
11654 changesCompleted ||
11655 pendingBatch.changes.length >= batch_size
11656 ) {
11657 batches.push(pendingBatch);
11658 pendingBatch = {
11659 seq: 0,
11660 changes: [],
11661 docs: []
11662 };
11663 if (returnValue.state === 'pending' || returnValue.state === 'stopped') {
11664 returnValue.state = 'active';
11665 returnValue.emit('active');
11666 }
11667 startNextBatch();
11668 }
11669 }
11670
11671
11672 function abortReplication(reason, err) {
11673 if (replicationCompleted) {
11674 return;
11675 }
11676 if (!err.message) {
11677 err.message = reason;
11678 }
11679 result.ok = false;
11680 result.status = 'aborting';
11681 batches = [];
11682 pendingBatch = {
11683 seq: 0,
11684 changes: [],
11685 docs: []
11686 };
11687 completeReplication(err);
11688 }
11689
11690
11691 function completeReplication(fatalError) {
11692 if (replicationCompleted) {
11693 return;
11694 }
11695 /* istanbul ignore if */
11696 if (returnValue.cancelled) {
11697 result.status = 'cancelled';
11698 if (writingCheckpoint) {
11699 return;
11700 }
11701 }
11702 result.status = result.status || 'complete';
11703 result.end_time = new Date().toISOString();
11704 result.last_seq = last_seq;
11705 replicationCompleted = true;
11706
11707 if (fatalError) {
11708 // need to extend the error because Firefox considers ".result" read-only
11709 fatalError = createError(fatalError);
11710 fatalError.result = result;
11711
11712 // Normalize error name. i.e. 'Unauthorized' -> 'unauthorized' (eg Sync Gateway)
11713 var errorName = (fatalError.name || '').toLowerCase();
11714 if (errorName === 'unauthorized' || errorName === 'forbidden') {
11715 returnValue.emit('error', fatalError);
11716 returnValue.removeAllListeners();
11717 } else {
11718 backOff(opts, returnValue, fatalError, function () {
11719 replicate(src, target, opts, returnValue);
11720 });
11721 }
11722 } else {
11723 returnValue.emit('complete', result);
11724 returnValue.removeAllListeners();
11725 }
11726 }
11727
11728
11729 function onChange(change, pending, lastSeq) {
11730 /* istanbul ignore if */
11731 if (returnValue.cancelled) {
11732 return completeReplication();
11733 }
11734 // Attach 'pending' property if server supports it (CouchDB 2.0+)
11735 /* istanbul ignore if */
11736 if (typeof pending === 'number') {
11737 pendingBatch.pending = pending;
11738 }
11739
11740 var filter = filterChange(opts)(change);
11741 if (!filter) {
11742 return;
11743 }
11744 pendingBatch.seq = change.seq || lastSeq;
11745 pendingBatch.changes.push(change);
11746 immediate(function () {
11747 processPendingBatch(batches.length === 0 && changesOpts.live);
11748 });
11749 }
11750
11751
11752 function onChangesComplete(changes) {
11753 changesPending = false;
11754 /* istanbul ignore if */
11755 if (returnValue.cancelled) {
11756 return completeReplication();
11757 }
11758
11759 // if no results were returned then we're done,
11760 // else fetch more
11761 if (changes.results.length > 0) {
11762 changesOpts.since = changes.results[changes.results.length - 1].seq;
11763 getChanges();
11764 processPendingBatch(true);
11765 } else {
11766
11767 var complete = function () {
11768 if (continuous) {
11769 changesOpts.live = true;
11770 getChanges();
11771 } else {
11772 changesCompleted = true;
11773 }
11774 processPendingBatch(true);
11775 };
11776
11777 // update the checkpoint so we start from the right seq next time
11778 if (!currentBatch && changes.results.length === 0) {
11779 writingCheckpoint = true;
11780 checkpointer.writeCheckpoint(changes.last_seq,
11781 session).then(function () {
11782 writingCheckpoint = false;
11783 result.last_seq = last_seq = changes.last_seq;
11784 complete();
11785 })[
11786 "catch"](onCheckpointError);
11787 } else {
11788 complete();
11789 }
11790 }
11791 }
11792
11793
11794 function onChangesError(err) {
11795 changesPending = false;
11796 /* istanbul ignore if */
11797 if (returnValue.cancelled) {
11798 return completeReplication();
11799 }
11800 abortReplication('changes rejected', err);
11801 }
11802
11803
11804 function getChanges() {
11805 if (!(
11806 !changesPending &&
11807 !changesCompleted &&
11808 batches.length < batches_limit
11809 )) {
11810 return;
11811 }
11812 changesPending = true;
11813 function abortChanges() {
11814 changes.cancel();
11815 }
11816 function removeListener() {
11817 returnValue.removeListener('cancel', abortChanges);
11818 }
11819
11820 if (returnValue._changes) { // remove old changes() and listeners
11821 returnValue.removeListener('cancel', returnValue._abortChanges);
11822 returnValue._changes.cancel();
11823 }
11824 returnValue.once('cancel', abortChanges);
11825
11826 var changes = src.changes(changesOpts)
11827 .on('change', onChange);
11828 changes.then(removeListener, removeListener);
11829 changes.then(onChangesComplete)[
11830 "catch"](onChangesError);
11831
11832 if (opts.retry) {
11833 // save for later so we can cancel if necessary
11834 returnValue._changes = changes;
11835 returnValue._abortChanges = abortChanges;
11836 }
11837 }
11838
11839
11840 function startChanges() {
11841 initCheckpointer().then(function () {
11842 /* istanbul ignore if */
11843 if (returnValue.cancelled) {
11844 completeReplication();
11845 return;
11846 }
11847 return checkpointer.getCheckpoint().then(function (checkpoint) {
11848 last_seq = checkpoint;
11849 changesOpts = {
11850 since: last_seq,
11851 limit: batch_size,
11852 batch_size: batch_size,
11853 style: 'all_docs',
11854 doc_ids: doc_ids,
11855 selector: selector,
11856 return_docs: true // required so we know when we're done
11857 };
11858 if (opts.filter) {
11859 if (typeof opts.filter !== 'string') {
11860 // required for the client-side filter in onChange
11861 changesOpts.include_docs = true;
11862 } else { // ddoc filter
11863 changesOpts.filter = opts.filter;
11864 }
11865 }
11866 if ('heartbeat' in opts) {
11867 changesOpts.heartbeat = opts.heartbeat;
11868 }
11869 if ('timeout' in opts) {
11870 changesOpts.timeout = opts.timeout;
11871 }
11872 if (opts.query_params) {
11873 changesOpts.query_params = opts.query_params;
11874 }
11875 if (opts.view) {
11876 changesOpts.view = opts.view;
11877 }
11878 getChanges();
11879 });
11880 })["catch"](function (err) {
11881 abortReplication('getCheckpoint rejected with ', err);
11882 });
11883 }
11884
11885 /* istanbul ignore next */
11886 function onCheckpointError(err) {
11887 writingCheckpoint = false;
11888 abortReplication('writeCheckpoint completed with error', err);
11889 }
11890
11891 /* istanbul ignore if */
11892 if (returnValue.cancelled) { // cancelled immediately
11893 completeReplication();
11894 return;
11895 }
11896
11897 if (!returnValue._addedListeners) {
11898 returnValue.once('cancel', completeReplication);
11899
11900 if (typeof opts.complete === 'function') {
11901 returnValue.once('error', opts.complete);
11902 returnValue.once('complete', function (result) {
11903 opts.complete(null, result);
11904 });
11905 }
11906 returnValue._addedListeners = true;
11907 }
11908
11909 if (typeof opts.since === 'undefined') {
11910 startChanges();
11911 } else {
11912 initCheckpointer().then(function () {
11913 writingCheckpoint = true;
11914 return checkpointer.writeCheckpoint(opts.since, session);
11915 }).then(function () {
11916 writingCheckpoint = false;
11917 /* istanbul ignore if */
11918 if (returnValue.cancelled) {
11919 completeReplication();
11920 return;
11921 }
11922 last_seq = opts.since;
11923 startChanges();
11924 })["catch"](onCheckpointError);
11925 }
11926}
11927
11928// We create a basic promise so the caller can cancel the replication possibly
11929// before we have actually started listening to changes etc
11930inherits(Replication, events.EventEmitter);
11931function Replication() {
11932 events.EventEmitter.call(this);
11933 this.cancelled = false;
11934 this.state = 'pending';
11935 var self = this;
11936 var promise = new Promise(function (fulfill, reject) {
11937 self.once('complete', fulfill);
11938 self.once('error', reject);
11939 });
11940 self.then = function (resolve, reject) {
11941 return promise.then(resolve, reject);
11942 };
11943 self["catch"] = function (reject) {
11944 return promise["catch"](reject);
11945 };
11946 // As we allow error handling via "error" event as well,
11947 // put a stub in here so that rejecting never throws UnhandledError.
11948 self["catch"](function () {});
11949}
11950
11951Replication.prototype.cancel = function () {
11952 this.cancelled = true;
11953 this.state = 'cancelled';
11954 this.emit('cancel');
11955};
11956
11957Replication.prototype.ready = function (src, target) {
11958 var self = this;
11959 if (self._readyCalled) {
11960 return;
11961 }
11962 self._readyCalled = true;
11963
11964 function onDestroy() {
11965 self.cancel();
11966 }
11967 src.once('destroyed', onDestroy);
11968 target.once('destroyed', onDestroy);
11969 function cleanup() {
11970 src.removeListener('destroyed', onDestroy);
11971 target.removeListener('destroyed', onDestroy);
11972 }
11973 self.once('complete', cleanup);
11974};
11975
11976function toPouch(db, opts) {
11977 var PouchConstructor = opts.PouchConstructor;
11978 if (typeof db === 'string') {
11979 return new PouchConstructor(db, opts);
11980 } else {
11981 return db;
11982 }
11983}
11984
11985function replicateWrapper(src, target, opts, callback) {
11986
11987 if (typeof opts === 'function') {
11988 callback = opts;
11989 opts = {};
11990 }
11991 if (typeof opts === 'undefined') {
11992 opts = {};
11993 }
11994
11995 if (opts.doc_ids && !Array.isArray(opts.doc_ids)) {
11996 throw createError(BAD_REQUEST,
11997 "`doc_ids` filter parameter is not a list.");
11998 }
11999
12000 opts.complete = callback;
12001 opts = clone(opts);
12002 opts.continuous = opts.continuous || opts.live;
12003 opts.retry = ('retry' in opts) ? opts.retry : false;
12004 /*jshint validthis:true */
12005 opts.PouchConstructor = opts.PouchConstructor || this;
12006 var replicateRet = new Replication(opts);
12007 var srcPouch = toPouch(src, opts);
12008 var targetPouch = toPouch(target, opts);
12009 replicate(srcPouch, targetPouch, opts, replicateRet);
12010 return replicateRet;
12011}
12012
12013inherits(Sync, events.EventEmitter);
12014function sync(src, target, opts, callback) {
12015 if (typeof opts === 'function') {
12016 callback = opts;
12017 opts = {};
12018 }
12019 if (typeof opts === 'undefined') {
12020 opts = {};
12021 }
12022 opts = clone(opts);
12023 /*jshint validthis:true */
12024 opts.PouchConstructor = opts.PouchConstructor || this;
12025 src = toPouch(src, opts);
12026 target = toPouch(target, opts);
12027 return new Sync(src, target, opts, callback);
12028}
12029
12030function Sync(src, target, opts, callback) {
12031 var self = this;
12032 this.canceled = false;
12033
12034 var optsPush = opts.push ? $inject_Object_assign({}, opts, opts.push) : opts;
12035 var optsPull = opts.pull ? $inject_Object_assign({}, opts, opts.pull) : opts;
12036
12037 this.push = replicateWrapper(src, target, optsPush);
12038 this.pull = replicateWrapper(target, src, optsPull);
12039
12040 this.pushPaused = true;
12041 this.pullPaused = true;
12042
12043 function pullChange(change) {
12044 self.emit('change', {
12045 direction: 'pull',
12046 change: change
12047 });
12048 }
12049 function pushChange(change) {
12050 self.emit('change', {
12051 direction: 'push',
12052 change: change
12053 });
12054 }
12055 function pushDenied(doc) {
12056 self.emit('denied', {
12057 direction: 'push',
12058 doc: doc
12059 });
12060 }
12061 function pullDenied(doc) {
12062 self.emit('denied', {
12063 direction: 'pull',
12064 doc: doc
12065 });
12066 }
12067 function pushPaused() {
12068 self.pushPaused = true;
12069 /* istanbul ignore if */
12070 if (self.pullPaused) {
12071 self.emit('paused');
12072 }
12073 }
12074 function pullPaused() {
12075 self.pullPaused = true;
12076 /* istanbul ignore if */
12077 if (self.pushPaused) {
12078 self.emit('paused');
12079 }
12080 }
12081 function pushActive() {
12082 self.pushPaused = false;
12083 /* istanbul ignore if */
12084 if (self.pullPaused) {
12085 self.emit('active', {
12086 direction: 'push'
12087 });
12088 }
12089 }
12090 function pullActive() {
12091 self.pullPaused = false;
12092 /* istanbul ignore if */
12093 if (self.pushPaused) {
12094 self.emit('active', {
12095 direction: 'pull'
12096 });
12097 }
12098 }
12099
12100 var removed = {};
12101
12102 function removeAll(type) { // type is 'push' or 'pull'
12103 return function (event, func) {
12104 var isChange = event === 'change' &&
12105 (func === pullChange || func === pushChange);
12106 var isDenied = event === 'denied' &&
12107 (func === pullDenied || func === pushDenied);
12108 var isPaused = event === 'paused' &&
12109 (func === pullPaused || func === pushPaused);
12110 var isActive = event === 'active' &&
12111 (func === pullActive || func === pushActive);
12112
12113 if (isChange || isDenied || isPaused || isActive) {
12114 if (!(event in removed)) {
12115 removed[event] = {};
12116 }
12117 removed[event][type] = true;
12118 if (Object.keys(removed[event]).length === 2) {
12119 // both push and pull have asked to be removed
12120 self.removeAllListeners(event);
12121 }
12122 }
12123 };
12124 }
12125
12126 if (opts.live) {
12127 this.push.on('complete', self.pull.cancel.bind(self.pull));
12128 this.pull.on('complete', self.push.cancel.bind(self.push));
12129 }
12130
12131 function addOneListener(ee, event, listener) {
12132 if (ee.listeners(event).indexOf(listener) == -1) {
12133 ee.on(event, listener);
12134 }
12135 }
12136
12137 this.on('newListener', function (event) {
12138 if (event === 'change') {
12139 addOneListener(self.pull, 'change', pullChange);
12140 addOneListener(self.push, 'change', pushChange);
12141 } else if (event === 'denied') {
12142 addOneListener(self.pull, 'denied', pullDenied);
12143 addOneListener(self.push, 'denied', pushDenied);
12144 } else if (event === 'active') {
12145 addOneListener(self.pull, 'active', pullActive);
12146 addOneListener(self.push, 'active', pushActive);
12147 } else if (event === 'paused') {
12148 addOneListener(self.pull, 'paused', pullPaused);
12149 addOneListener(self.push, 'paused', pushPaused);
12150 }
12151 });
12152
12153 this.on('removeListener', function (event) {
12154 if (event === 'change') {
12155 self.pull.removeListener('change', pullChange);
12156 self.push.removeListener('change', pushChange);
12157 } else if (event === 'denied') {
12158 self.pull.removeListener('denied', pullDenied);
12159 self.push.removeListener('denied', pushDenied);
12160 } else if (event === 'active') {
12161 self.pull.removeListener('active', pullActive);
12162 self.push.removeListener('active', pushActive);
12163 } else if (event === 'paused') {
12164 self.pull.removeListener('paused', pullPaused);
12165 self.push.removeListener('paused', pushPaused);
12166 }
12167 });
12168
12169 this.pull.on('removeListener', removeAll('pull'));
12170 this.push.on('removeListener', removeAll('push'));
12171
12172 var promise = Promise.all([
12173 this.push,
12174 this.pull
12175 ]).then(function (resp) {
12176 var out = {
12177 push: resp[0],
12178 pull: resp[1]
12179 };
12180 self.emit('complete', out);
12181 if (callback) {
12182 callback(null, out);
12183 }
12184 self.removeAllListeners();
12185 return out;
12186 }, function (err) {
12187 self.cancel();
12188 if (callback) {
12189 // if there's a callback, then the callback can receive
12190 // the error event
12191 callback(err);
12192 } else {
12193 // if there's no callback, then we're safe to emit an error
12194 // event, which would otherwise throw an unhandled error
12195 // due to 'error' being a special event in EventEmitters
12196 self.emit('error', err);
12197 }
12198 self.removeAllListeners();
12199 if (callback) {
12200 // no sense throwing if we're already emitting an 'error' event
12201 throw err;
12202 }
12203 });
12204
12205 this.then = function (success, err) {
12206 return promise.then(success, err);
12207 };
12208
12209 this["catch"] = function (err) {
12210 return promise["catch"](err);
12211 };
12212}
12213
12214Sync.prototype.cancel = function () {
12215 if (!this.canceled) {
12216 this.canceled = true;
12217 this.push.cancel();
12218 this.pull.cancel();
12219 }
12220};
12221
12222function replication(PouchDB) {
12223 PouchDB.replicate = replicateWrapper;
12224 PouchDB.sync = sync;
12225
12226 Object.defineProperty(PouchDB.prototype, 'replicate', {
12227 get: function () {
12228 var self = this;
12229 if (typeof this.replicateMethods === 'undefined') {
12230 this.replicateMethods = {
12231 from: function (other, opts, callback) {
12232 return self.constructor.replicate(other, self, opts, callback);
12233 },
12234 to: function (other, opts, callback) {
12235 return self.constructor.replicate(self, other, opts, callback);
12236 }
12237 };
12238 }
12239 return this.replicateMethods;
12240 }
12241 });
12242
12243 PouchDB.prototype.sync = function (dbName, opts, callback) {
12244 return this.constructor.sync(this, dbName, opts, callback);
12245 };
12246}
12247
12248PouchDB.plugin(IDBPouch)
12249 .plugin(HttpPouch$1)
12250 .plugin(mapreduce)
12251 .plugin(replication);
12252
12253// Pull from src because pouchdb-node/pouchdb-browser themselves
12254
12255module.exports = PouchDB;
12256
12257}).call(this,_dereq_(5),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
12258},{"1":1,"12":12,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7}]},{},[13])(13)
12259});