UNPKG

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