UNPKG

386 kBJavaScriptView Raw
1// PouchDB 8.0.1
2//
3// (c) 2012-2023 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
9},{}],2:[function(_dereq_,module,exports){
10// Copyright Joyent, Inc. and other Node contributors.
11//
12// Permission is hereby granted, free of charge, to any person obtaining a
13// copy of this software and associated documentation files (the
14// "Software"), to deal in the Software without restriction, including
15// without limitation the rights to use, copy, modify, merge, publish,
16// distribute, sublicense, and/or sell copies of the Software, and to permit
17// persons to whom the Software is furnished to do so, subject to the
18// following conditions:
19//
20// The above copyright notice and this permission notice shall be included
21// in all copies or substantial portions of the Software.
22//
23// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
24// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
26// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
27// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
28// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
29// USE OR OTHER DEALINGS IN THE SOFTWARE.
30
31var objectCreate = Object.create || objectCreatePolyfill
32var objectKeys = Object.keys || objectKeysPolyfill
33var bind = Function.prototype.bind || functionBindPolyfill
34
35function EventEmitter() {
36 if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) {
37 this._events = objectCreate(null);
38 this._eventsCount = 0;
39 }
40
41 this._maxListeners = this._maxListeners || undefined;
42}
43module.exports = EventEmitter;
44
45// Backwards-compat with node 0.10.x
46EventEmitter.EventEmitter = EventEmitter;
47
48EventEmitter.prototype._events = undefined;
49EventEmitter.prototype._maxListeners = undefined;
50
51// By default EventEmitters will print a warning if more than 10 listeners are
52// added to it. This is a useful default which helps finding memory leaks.
53var defaultMaxListeners = 10;
54
55var hasDefineProperty;
56try {
57 var o = {};
58 if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 });
59 hasDefineProperty = o.x === 0;
60} catch (err) { hasDefineProperty = false }
61if (hasDefineProperty) {
62 Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
63 enumerable: true,
64 get: function() {
65 return defaultMaxListeners;
66 },
67 set: function(arg) {
68 // check whether the input is a positive number (whose value is zero or
69 // greater and not a NaN).
70 if (typeof arg !== 'number' || arg < 0 || arg !== arg)
71 throw new TypeError('"defaultMaxListeners" must be a positive number');
72 defaultMaxListeners = arg;
73 }
74 });
75} else {
76 EventEmitter.defaultMaxListeners = defaultMaxListeners;
77}
78
79// Obviously not all Emitters should be limited to 10. This function allows
80// that to be increased. Set to zero for unlimited.
81EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
82 if (typeof n !== 'number' || n < 0 || isNaN(n))
83 throw new TypeError('"n" argument must be a positive number');
84 this._maxListeners = n;
85 return this;
86};
87
88function $getMaxListeners(that) {
89 if (that._maxListeners === undefined)
90 return EventEmitter.defaultMaxListeners;
91 return that._maxListeners;
92}
93
94EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
95 return $getMaxListeners(this);
96};
97
98// These standalone emit* functions are used to optimize calling of event
99// handlers for fast cases because emit() itself often has a variable number of
100// arguments and can be deoptimized because of that. These functions always have
101// the same number of arguments and thus do not get deoptimized, so the code
102// inside them can execute faster.
103function emitNone(handler, isFn, self) {
104 if (isFn)
105 handler.call(self);
106 else {
107 var len = handler.length;
108 var listeners = arrayClone(handler, len);
109 for (var i = 0; i < len; ++i)
110 listeners[i].call(self);
111 }
112}
113function emitOne(handler, isFn, self, arg1) {
114 if (isFn)
115 handler.call(self, arg1);
116 else {
117 var len = handler.length;
118 var listeners = arrayClone(handler, len);
119 for (var i = 0; i < len; ++i)
120 listeners[i].call(self, arg1);
121 }
122}
123function emitTwo(handler, isFn, self, arg1, arg2) {
124 if (isFn)
125 handler.call(self, arg1, arg2);
126 else {
127 var len = handler.length;
128 var listeners = arrayClone(handler, len);
129 for (var i = 0; i < len; ++i)
130 listeners[i].call(self, arg1, arg2);
131 }
132}
133function emitThree(handler, isFn, self, arg1, arg2, arg3) {
134 if (isFn)
135 handler.call(self, arg1, arg2, arg3);
136 else {
137 var len = handler.length;
138 var listeners = arrayClone(handler, len);
139 for (var i = 0; i < len; ++i)
140 listeners[i].call(self, arg1, arg2, arg3);
141 }
142}
143
144function emitMany(handler, isFn, self, args) {
145 if (isFn)
146 handler.apply(self, args);
147 else {
148 var len = handler.length;
149 var listeners = arrayClone(handler, len);
150 for (var i = 0; i < len; ++i)
151 listeners[i].apply(self, args);
152 }
153}
154
155EventEmitter.prototype.emit = function emit(type) {
156 var er, handler, len, args, i, events;
157 var doError = (type === 'error');
158
159 events = this._events;
160 if (events)
161 doError = (doError && events.error == null);
162 else if (!doError)
163 return false;
164
165 // If there is no 'error' event listener then throw.
166 if (doError) {
167 if (arguments.length > 1)
168 er = arguments[1];
169 if (er instanceof Error) {
170 throw er; // Unhandled 'error' event
171 } else {
172 // At least give some kind of context to the user
173 var err = new Error('Unhandled "error" event. (' + er + ')');
174 err.context = er;
175 throw err;
176 }
177 return false;
178 }
179
180 handler = events[type];
181
182 if (!handler)
183 return false;
184
185 var isFn = typeof handler === 'function';
186 len = arguments.length;
187 switch (len) {
188 // fast cases
189 case 1:
190 emitNone(handler, isFn, this);
191 break;
192 case 2:
193 emitOne(handler, isFn, this, arguments[1]);
194 break;
195 case 3:
196 emitTwo(handler, isFn, this, arguments[1], arguments[2]);
197 break;
198 case 4:
199 emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
200 break;
201 // slower
202 default:
203 args = new Array(len - 1);
204 for (i = 1; i < len; i++)
205 args[i - 1] = arguments[i];
206 emitMany(handler, isFn, this, args);
207 }
208
209 return true;
210};
211
212function _addListener(target, type, listener, prepend) {
213 var m;
214 var events;
215 var existing;
216
217 if (typeof listener !== 'function')
218 throw new TypeError('"listener" argument must be a function');
219
220 events = target._events;
221 if (!events) {
222 events = target._events = objectCreate(null);
223 target._eventsCount = 0;
224 } else {
225 // To avoid recursion in the case that type === "newListener"! Before
226 // adding it to the listeners, first emit "newListener".
227 if (events.newListener) {
228 target.emit('newListener', type,
229 listener.listener ? listener.listener : listener);
230
231 // Re-assign `events` because a newListener handler could have caused the
232 // this._events to be assigned to a new object
233 events = target._events;
234 }
235 existing = events[type];
236 }
237
238 if (!existing) {
239 // Optimize the case of one listener. Don't need the extra array object.
240 existing = events[type] = listener;
241 ++target._eventsCount;
242 } else {
243 if (typeof existing === 'function') {
244 // Adding the second element, need to change to array.
245 existing = events[type] =
246 prepend ? [listener, existing] : [existing, listener];
247 } else {
248 // If we've already got an array, just append.
249 if (prepend) {
250 existing.unshift(listener);
251 } else {
252 existing.push(listener);
253 }
254 }
255
256 // Check for listener leak
257 if (!existing.warned) {
258 m = $getMaxListeners(target);
259 if (m && m > 0 && existing.length > m) {
260 existing.warned = true;
261 var w = new Error('Possible EventEmitter memory leak detected. ' +
262 existing.length + ' "' + String(type) + '" listeners ' +
263 'added. Use emitter.setMaxListeners() to ' +
264 'increase limit.');
265 w.name = 'MaxListenersExceededWarning';
266 w.emitter = target;
267 w.type = type;
268 w.count = existing.length;
269 if (typeof console === 'object' && console.warn) {
270 console.warn('%s: %s', w.name, w.message);
271 }
272 }
273 }
274 }
275
276 return target;
277}
278
279EventEmitter.prototype.addListener = function addListener(type, listener) {
280 return _addListener(this, type, listener, false);
281};
282
283EventEmitter.prototype.on = EventEmitter.prototype.addListener;
284
285EventEmitter.prototype.prependListener =
286 function prependListener(type, listener) {
287 return _addListener(this, type, listener, true);
288 };
289
290function onceWrapper() {
291 if (!this.fired) {
292 this.target.removeListener(this.type, this.wrapFn);
293 this.fired = true;
294 switch (arguments.length) {
295 case 0:
296 return this.listener.call(this.target);
297 case 1:
298 return this.listener.call(this.target, arguments[0]);
299 case 2:
300 return this.listener.call(this.target, arguments[0], arguments[1]);
301 case 3:
302 return this.listener.call(this.target, arguments[0], arguments[1],
303 arguments[2]);
304 default:
305 var args = new Array(arguments.length);
306 for (var i = 0; i < args.length; ++i)
307 args[i] = arguments[i];
308 this.listener.apply(this.target, args);
309 }
310 }
311}
312
313function _onceWrap(target, type, listener) {
314 var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
315 var wrapped = bind.call(onceWrapper, state);
316 wrapped.listener = listener;
317 state.wrapFn = wrapped;
318 return wrapped;
319}
320
321EventEmitter.prototype.once = function once(type, listener) {
322 if (typeof listener !== 'function')
323 throw new TypeError('"listener" argument must be a function');
324 this.on(type, _onceWrap(this, type, listener));
325 return this;
326};
327
328EventEmitter.prototype.prependOnceListener =
329 function prependOnceListener(type, listener) {
330 if (typeof listener !== 'function')
331 throw new TypeError('"listener" argument must be a function');
332 this.prependListener(type, _onceWrap(this, type, listener));
333 return this;
334 };
335
336// Emits a 'removeListener' event if and only if the listener was removed.
337EventEmitter.prototype.removeListener =
338 function removeListener(type, listener) {
339 var list, events, position, i, originalListener;
340
341 if (typeof listener !== 'function')
342 throw new TypeError('"listener" argument must be a function');
343
344 events = this._events;
345 if (!events)
346 return this;
347
348 list = events[type];
349 if (!list)
350 return this;
351
352 if (list === listener || list.listener === listener) {
353 if (--this._eventsCount === 0)
354 this._events = objectCreate(null);
355 else {
356 delete events[type];
357 if (events.removeListener)
358 this.emit('removeListener', type, list.listener || listener);
359 }
360 } else if (typeof list !== 'function') {
361 position = -1;
362
363 for (i = list.length - 1; i >= 0; i--) {
364 if (list[i] === listener || list[i].listener === listener) {
365 originalListener = list[i].listener;
366 position = i;
367 break;
368 }
369 }
370
371 if (position < 0)
372 return this;
373
374 if (position === 0)
375 list.shift();
376 else
377 spliceOne(list, position);
378
379 if (list.length === 1)
380 events[type] = list[0];
381
382 if (events.removeListener)
383 this.emit('removeListener', type, originalListener || listener);
384 }
385
386 return this;
387 };
388
389EventEmitter.prototype.removeAllListeners =
390 function removeAllListeners(type) {
391 var listeners, events, i;
392
393 events = this._events;
394 if (!events)
395 return this;
396
397 // not listening for removeListener, no need to emit
398 if (!events.removeListener) {
399 if (arguments.length === 0) {
400 this._events = objectCreate(null);
401 this._eventsCount = 0;
402 } else if (events[type]) {
403 if (--this._eventsCount === 0)
404 this._events = objectCreate(null);
405 else
406 delete events[type];
407 }
408 return this;
409 }
410
411 // emit removeListener for all listeners on all events
412 if (arguments.length === 0) {
413 var keys = objectKeys(events);
414 var key;
415 for (i = 0; i < keys.length; ++i) {
416 key = keys[i];
417 if (key === 'removeListener') continue;
418 this.removeAllListeners(key);
419 }
420 this.removeAllListeners('removeListener');
421 this._events = objectCreate(null);
422 this._eventsCount = 0;
423 return this;
424 }
425
426 listeners = events[type];
427
428 if (typeof listeners === 'function') {
429 this.removeListener(type, listeners);
430 } else if (listeners) {
431 // LIFO order
432 for (i = listeners.length - 1; i >= 0; i--) {
433 this.removeListener(type, listeners[i]);
434 }
435 }
436
437 return this;
438 };
439
440function _listeners(target, type, unwrap) {
441 var events = target._events;
442
443 if (!events)
444 return [];
445
446 var evlistener = events[type];
447 if (!evlistener)
448 return [];
449
450 if (typeof evlistener === 'function')
451 return unwrap ? [evlistener.listener || evlistener] : [evlistener];
452
453 return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
454}
455
456EventEmitter.prototype.listeners = function listeners(type) {
457 return _listeners(this, type, true);
458};
459
460EventEmitter.prototype.rawListeners = function rawListeners(type) {
461 return _listeners(this, type, false);
462};
463
464EventEmitter.listenerCount = function(emitter, type) {
465 if (typeof emitter.listenerCount === 'function') {
466 return emitter.listenerCount(type);
467 } else {
468 return listenerCount.call(emitter, type);
469 }
470};
471
472EventEmitter.prototype.listenerCount = listenerCount;
473function listenerCount(type) {
474 var events = this._events;
475
476 if (events) {
477 var evlistener = events[type];
478
479 if (typeof evlistener === 'function') {
480 return 1;
481 } else if (evlistener) {
482 return evlistener.length;
483 }
484 }
485
486 return 0;
487}
488
489EventEmitter.prototype.eventNames = function eventNames() {
490 return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
491};
492
493// About 1.5x faster than the two-arg version of Array#splice().
494function spliceOne(list, index) {
495 for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
496 list[i] = list[k];
497 list.pop();
498}
499
500function arrayClone(arr, n) {
501 var copy = new Array(n);
502 for (var i = 0; i < n; ++i)
503 copy[i] = arr[i];
504 return copy;
505}
506
507function unwrapListeners(arr) {
508 var ret = new Array(arr.length);
509 for (var i = 0; i < ret.length; ++i) {
510 ret[i] = arr[i].listener || arr[i];
511 }
512 return ret;
513}
514
515function objectCreatePolyfill(proto) {
516 var F = function() {};
517 F.prototype = proto;
518 return new F;
519}
520function objectKeysPolyfill(obj) {
521 var keys = [];
522 for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) {
523 keys.push(k);
524 }
525 return k;
526}
527function functionBindPolyfill(context) {
528 var fn = this;
529 return function () {
530 return fn.apply(context, arguments);
531 };
532}
533
534},{}],3:[function(_dereq_,module,exports){
535'use strict';
536var types = [
537 _dereq_(1),
538 _dereq_(6),
539 _dereq_(5),
540 _dereq_(4),
541 _dereq_(7),
542 _dereq_(8)
543];
544var draining;
545var currentQueue;
546var queueIndex = -1;
547var queue = [];
548var scheduled = false;
549function cleanUpNextTick() {
550 if (!draining || !currentQueue) {
551 return;
552 }
553 draining = false;
554 if (currentQueue.length) {
555 queue = currentQueue.concat(queue);
556 } else {
557 queueIndex = -1;
558 }
559 if (queue.length) {
560 nextTick();
561 }
562}
563
564//named nextTick for less confusing stack traces
565function nextTick() {
566 if (draining) {
567 return;
568 }
569 scheduled = false;
570 draining = true;
571 var len = queue.length;
572 var timeout = setTimeout(cleanUpNextTick);
573 while (len) {
574 currentQueue = queue;
575 queue = [];
576 while (currentQueue && ++queueIndex < len) {
577 currentQueue[queueIndex].run();
578 }
579 queueIndex = -1;
580 len = queue.length;
581 }
582 currentQueue = null;
583 queueIndex = -1;
584 draining = false;
585 clearTimeout(timeout);
586}
587var scheduleDrain;
588var i = -1;
589var len = types.length;
590while (++i < len) {
591 if (types[i] && types[i].test && types[i].test()) {
592 scheduleDrain = types[i].install(nextTick);
593 break;
594 }
595}
596// v8 likes predictible objects
597function Item(fun, array) {
598 this.fun = fun;
599 this.array = array;
600}
601Item.prototype.run = function () {
602 var fun = this.fun;
603 var array = this.array;
604 switch (array.length) {
605 case 0:
606 return fun();
607 case 1:
608 return fun(array[0]);
609 case 2:
610 return fun(array[0], array[1]);
611 case 3:
612 return fun(array[0], array[1], array[2]);
613 default:
614 return fun.apply(null, array);
615 }
616
617};
618module.exports = immediate;
619function immediate(task) {
620 var args = new Array(arguments.length - 1);
621 if (arguments.length > 1) {
622 for (var i = 1; i < arguments.length; i++) {
623 args[i - 1] = arguments[i];
624 }
625 }
626 queue.push(new Item(task, args));
627 if (!scheduled && !draining) {
628 scheduled = true;
629 scheduleDrain();
630 }
631}
632
633},{"1":1,"4":4,"5":5,"6":6,"7":7,"8":8}],4:[function(_dereq_,module,exports){
634(function (global){(function (){
635'use strict';
636
637exports.test = function () {
638 if (global.setImmediate) {
639 // we can only get here in IE10
640 // which doesn't handel postMessage well
641 return false;
642 }
643 return typeof global.MessageChannel !== 'undefined';
644};
645
646exports.install = function (func) {
647 var channel = new global.MessageChannel();
648 channel.port1.onmessage = func;
649 return function () {
650 channel.port2.postMessage(0);
651 };
652};
653}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
654},{}],5:[function(_dereq_,module,exports){
655(function (global){(function (){
656'use strict';
657//based off rsvp https://github.com/tildeio/rsvp.js
658//license https://github.com/tildeio/rsvp.js/blob/master/LICENSE
659//https://github.com/tildeio/rsvp.js/blob/master/lib/rsvp/asap.js
660
661var Mutation = global.MutationObserver || global.WebKitMutationObserver;
662
663exports.test = function () {
664 return Mutation;
665};
666
667exports.install = function (handle) {
668 var called = 0;
669 var observer = new Mutation(handle);
670 var element = global.document.createTextNode('');
671 observer.observe(element, {
672 characterData: true
673 });
674 return function () {
675 element.data = (called = ++called % 2);
676 };
677};
678}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
679},{}],6:[function(_dereq_,module,exports){
680(function (global){(function (){
681'use strict';
682exports.test = function () {
683 return typeof global.queueMicrotask === 'function';
684};
685
686exports.install = function (func) {
687 return function () {
688 global.queueMicrotask(func);
689 };
690};
691
692}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
693},{}],7:[function(_dereq_,module,exports){
694(function (global){(function (){
695'use strict';
696
697exports.test = function () {
698 return 'document' in global && 'onreadystatechange' in global.document.createElement('script');
699};
700
701exports.install = function (handle) {
702 return function () {
703
704 // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
705 // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
706 var scriptEl = global.document.createElement('script');
707 scriptEl.onreadystatechange = function () {
708 handle();
709
710 scriptEl.onreadystatechange = null;
711 scriptEl.parentNode.removeChild(scriptEl);
712 scriptEl = null;
713 };
714 global.document.documentElement.appendChild(scriptEl);
715
716 return handle;
717 };
718};
719}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
720},{}],8:[function(_dereq_,module,exports){
721'use strict';
722exports.test = function () {
723 return true;
724};
725
726exports.install = function (t) {
727 return function () {
728 setTimeout(t, 0);
729 };
730};
731},{}],9:[function(_dereq_,module,exports){
732// shim for using process in browser
733var process = module.exports = {};
734
735// cached from whatever global is present so that test runners that stub it
736// don't break things. But we need to wrap it in a try catch in case it is
737// wrapped in strict mode code which doesn't define any globals. It's inside a
738// function because try/catches deoptimize in certain engines.
739
740var cachedSetTimeout;
741var cachedClearTimeout;
742
743function defaultSetTimout() {
744 throw new Error('setTimeout has not been defined');
745}
746function defaultClearTimeout () {
747 throw new Error('clearTimeout has not been defined');
748}
749(function () {
750 try {
751 if (typeof setTimeout === 'function') {
752 cachedSetTimeout = setTimeout;
753 } else {
754 cachedSetTimeout = defaultSetTimout;
755 }
756 } catch (e) {
757 cachedSetTimeout = defaultSetTimout;
758 }
759 try {
760 if (typeof clearTimeout === 'function') {
761 cachedClearTimeout = clearTimeout;
762 } else {
763 cachedClearTimeout = defaultClearTimeout;
764 }
765 } catch (e) {
766 cachedClearTimeout = defaultClearTimeout;
767 }
768} ())
769function runTimeout(fun) {
770 if (cachedSetTimeout === setTimeout) {
771 //normal enviroments in sane situations
772 return setTimeout(fun, 0);
773 }
774 // if setTimeout wasn't available but was latter defined
775 if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
776 cachedSetTimeout = setTimeout;
777 return setTimeout(fun, 0);
778 }
779 try {
780 // when when somebody has screwed with setTimeout but no I.E. maddness
781 return cachedSetTimeout(fun, 0);
782 } catch(e){
783 try {
784 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
785 return cachedSetTimeout.call(null, fun, 0);
786 } catch(e){
787 // 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
788 return cachedSetTimeout.call(this, fun, 0);
789 }
790 }
791
792
793}
794function runClearTimeout(marker) {
795 if (cachedClearTimeout === clearTimeout) {
796 //normal enviroments in sane situations
797 return clearTimeout(marker);
798 }
799 // if clearTimeout wasn't available but was latter defined
800 if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
801 cachedClearTimeout = clearTimeout;
802 return clearTimeout(marker);
803 }
804 try {
805 // when when somebody has screwed with setTimeout but no I.E. maddness
806 return cachedClearTimeout(marker);
807 } catch (e){
808 try {
809 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
810 return cachedClearTimeout.call(null, marker);
811 } catch (e){
812 // 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.
813 // Some versions of I.E. have different rules for clearTimeout vs setTimeout
814 return cachedClearTimeout.call(this, marker);
815 }
816 }
817
818
819
820}
821var queue = [];
822var draining = false;
823var currentQueue;
824var queueIndex = -1;
825
826function cleanUpNextTick() {
827 if (!draining || !currentQueue) {
828 return;
829 }
830 draining = false;
831 if (currentQueue.length) {
832 queue = currentQueue.concat(queue);
833 } else {
834 queueIndex = -1;
835 }
836 if (queue.length) {
837 drainQueue();
838 }
839}
840
841function drainQueue() {
842 if (draining) {
843 return;
844 }
845 var timeout = runTimeout(cleanUpNextTick);
846 draining = true;
847
848 var len = queue.length;
849 while(len) {
850 currentQueue = queue;
851 queue = [];
852 while (++queueIndex < len) {
853 if (currentQueue) {
854 currentQueue[queueIndex].run();
855 }
856 }
857 queueIndex = -1;
858 len = queue.length;
859 }
860 currentQueue = null;
861 draining = false;
862 runClearTimeout(timeout);
863}
864
865process.nextTick = function (fun) {
866 var args = new Array(arguments.length - 1);
867 if (arguments.length > 1) {
868 for (var i = 1; i < arguments.length; i++) {
869 args[i - 1] = arguments[i];
870 }
871 }
872 queue.push(new Item(fun, args));
873 if (queue.length === 1 && !draining) {
874 runTimeout(drainQueue);
875 }
876};
877
878// v8 likes predictible objects
879function Item(fun, array) {
880 this.fun = fun;
881 this.array = array;
882}
883Item.prototype.run = function () {
884 this.fun.apply(null, this.array);
885};
886process.title = 'browser';
887process.browser = true;
888process.env = {};
889process.argv = [];
890process.version = ''; // empty string to avoid regexp issues
891process.versions = {};
892
893function noop() {}
894
895process.on = noop;
896process.addListener = noop;
897process.once = noop;
898process.off = noop;
899process.removeListener = noop;
900process.removeAllListeners = noop;
901process.emit = noop;
902process.prependListener = noop;
903process.prependOnceListener = noop;
904
905process.listeners = function (name) { return [] }
906
907process.binding = function (name) {
908 throw new Error('process.binding is not supported');
909};
910
911process.cwd = function () { return '/' };
912process.chdir = function (dir) {
913 throw new Error('process.chdir is not supported');
914};
915process.umask = function() { return 0; };
916
917},{}],10:[function(_dereq_,module,exports){
918(function (factory) {
919 if (typeof exports === 'object') {
920 // Node/CommonJS
921 module.exports = factory();
922 } else if (typeof define === 'function' && define.amd) {
923 // AMD
924 define(factory);
925 } else {
926 // Browser globals (with support for web workers)
927 var glob;
928
929 try {
930 glob = window;
931 } catch (e) {
932 glob = self;
933 }
934
935 glob.SparkMD5 = factory();
936 }
937}(function (undefined) {
938
939 'use strict';
940
941 /*
942 * Fastest md5 implementation around (JKM md5).
943 * Credits: Joseph Myers
944 *
945 * @see http://www.myersdaily.org/joseph/javascript/md5-text.html
946 * @see http://jsperf.com/md5-shootout/7
947 */
948
949 /* this function is much faster,
950 so if possible we use it. Some IEs
951 are the only ones I know of that
952 need the idiotic second function,
953 generated by an if clause. */
954 var add32 = function (a, b) {
955 return (a + b) & 0xFFFFFFFF;
956 },
957 hex_chr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
958
959
960 function cmn(q, a, b, x, s, t) {
961 a = add32(add32(a, q), add32(x, t));
962 return add32((a << s) | (a >>> (32 - s)), b);
963 }
964
965 function md5cycle(x, k) {
966 var a = x[0],
967 b = x[1],
968 c = x[2],
969 d = x[3];
970
971 a += (b & c | ~b & d) + k[0] - 680876936 | 0;
972 a = (a << 7 | a >>> 25) + b | 0;
973 d += (a & b | ~a & c) + k[1] - 389564586 | 0;
974 d = (d << 12 | d >>> 20) + a | 0;
975 c += (d & a | ~d & b) + k[2] + 606105819 | 0;
976 c = (c << 17 | c >>> 15) + d | 0;
977 b += (c & d | ~c & a) + k[3] - 1044525330 | 0;
978 b = (b << 22 | b >>> 10) + c | 0;
979 a += (b & c | ~b & d) + k[4] - 176418897 | 0;
980 a = (a << 7 | a >>> 25) + b | 0;
981 d += (a & b | ~a & c) + k[5] + 1200080426 | 0;
982 d = (d << 12 | d >>> 20) + a | 0;
983 c += (d & a | ~d & b) + k[6] - 1473231341 | 0;
984 c = (c << 17 | c >>> 15) + d | 0;
985 b += (c & d | ~c & a) + k[7] - 45705983 | 0;
986 b = (b << 22 | b >>> 10) + c | 0;
987 a += (b & c | ~b & d) + k[8] + 1770035416 | 0;
988 a = (a << 7 | a >>> 25) + b | 0;
989 d += (a & b | ~a & c) + k[9] - 1958414417 | 0;
990 d = (d << 12 | d >>> 20) + a | 0;
991 c += (d & a | ~d & b) + k[10] - 42063 | 0;
992 c = (c << 17 | c >>> 15) + d | 0;
993 b += (c & d | ~c & a) + k[11] - 1990404162 | 0;
994 b = (b << 22 | b >>> 10) + c | 0;
995 a += (b & c | ~b & d) + k[12] + 1804603682 | 0;
996 a = (a << 7 | a >>> 25) + b | 0;
997 d += (a & b | ~a & c) + k[13] - 40341101 | 0;
998 d = (d << 12 | d >>> 20) + a | 0;
999 c += (d & a | ~d & b) + k[14] - 1502002290 | 0;
1000 c = (c << 17 | c >>> 15) + d | 0;
1001 b += (c & d | ~c & a) + k[15] + 1236535329 | 0;
1002 b = (b << 22 | b >>> 10) + c | 0;
1003
1004 a += (b & d | c & ~d) + k[1] - 165796510 | 0;
1005 a = (a << 5 | a >>> 27) + b | 0;
1006 d += (a & c | b & ~c) + k[6] - 1069501632 | 0;
1007 d = (d << 9 | d >>> 23) + a | 0;
1008 c += (d & b | a & ~b) + k[11] + 643717713 | 0;
1009 c = (c << 14 | c >>> 18) + d | 0;
1010 b += (c & a | d & ~a) + k[0] - 373897302 | 0;
1011 b = (b << 20 | b >>> 12) + c | 0;
1012 a += (b & d | c & ~d) + k[5] - 701558691 | 0;
1013 a = (a << 5 | a >>> 27) + b | 0;
1014 d += (a & c | b & ~c) + k[10] + 38016083 | 0;
1015 d = (d << 9 | d >>> 23) + a | 0;
1016 c += (d & b | a & ~b) + k[15] - 660478335 | 0;
1017 c = (c << 14 | c >>> 18) + d | 0;
1018 b += (c & a | d & ~a) + k[4] - 405537848 | 0;
1019 b = (b << 20 | b >>> 12) + c | 0;
1020 a += (b & d | c & ~d) + k[9] + 568446438 | 0;
1021 a = (a << 5 | a >>> 27) + b | 0;
1022 d += (a & c | b & ~c) + k[14] - 1019803690 | 0;
1023 d = (d << 9 | d >>> 23) + a | 0;
1024 c += (d & b | a & ~b) + k[3] - 187363961 | 0;
1025 c = (c << 14 | c >>> 18) + d | 0;
1026 b += (c & a | d & ~a) + k[8] + 1163531501 | 0;
1027 b = (b << 20 | b >>> 12) + c | 0;
1028 a += (b & d | c & ~d) + k[13] - 1444681467 | 0;
1029 a = (a << 5 | a >>> 27) + b | 0;
1030 d += (a & c | b & ~c) + k[2] - 51403784 | 0;
1031 d = (d << 9 | d >>> 23) + a | 0;
1032 c += (d & b | a & ~b) + k[7] + 1735328473 | 0;
1033 c = (c << 14 | c >>> 18) + d | 0;
1034 b += (c & a | d & ~a) + k[12] - 1926607734 | 0;
1035 b = (b << 20 | b >>> 12) + c | 0;
1036
1037 a += (b ^ c ^ d) + k[5] - 378558 | 0;
1038 a = (a << 4 | a >>> 28) + b | 0;
1039 d += (a ^ b ^ c) + k[8] - 2022574463 | 0;
1040 d = (d << 11 | d >>> 21) + a | 0;
1041 c += (d ^ a ^ b) + k[11] + 1839030562 | 0;
1042 c = (c << 16 | c >>> 16) + d | 0;
1043 b += (c ^ d ^ a) + k[14] - 35309556 | 0;
1044 b = (b << 23 | b >>> 9) + c | 0;
1045 a += (b ^ c ^ d) + k[1] - 1530992060 | 0;
1046 a = (a << 4 | a >>> 28) + b | 0;
1047 d += (a ^ b ^ c) + k[4] + 1272893353 | 0;
1048 d = (d << 11 | d >>> 21) + a | 0;
1049 c += (d ^ a ^ b) + k[7] - 155497632 | 0;
1050 c = (c << 16 | c >>> 16) + d | 0;
1051 b += (c ^ d ^ a) + k[10] - 1094730640 | 0;
1052 b = (b << 23 | b >>> 9) + c | 0;
1053 a += (b ^ c ^ d) + k[13] + 681279174 | 0;
1054 a = (a << 4 | a >>> 28) + b | 0;
1055 d += (a ^ b ^ c) + k[0] - 358537222 | 0;
1056 d = (d << 11 | d >>> 21) + a | 0;
1057 c += (d ^ a ^ b) + k[3] - 722521979 | 0;
1058 c = (c << 16 | c >>> 16) + d | 0;
1059 b += (c ^ d ^ a) + k[6] + 76029189 | 0;
1060 b = (b << 23 | b >>> 9) + c | 0;
1061 a += (b ^ c ^ d) + k[9] - 640364487 | 0;
1062 a = (a << 4 | a >>> 28) + b | 0;
1063 d += (a ^ b ^ c) + k[12] - 421815835 | 0;
1064 d = (d << 11 | d >>> 21) + a | 0;
1065 c += (d ^ a ^ b) + k[15] + 530742520 | 0;
1066 c = (c << 16 | c >>> 16) + d | 0;
1067 b += (c ^ d ^ a) + k[2] - 995338651 | 0;
1068 b = (b << 23 | b >>> 9) + c | 0;
1069
1070 a += (c ^ (b | ~d)) + k[0] - 198630844 | 0;
1071 a = (a << 6 | a >>> 26) + b | 0;
1072 d += (b ^ (a | ~c)) + k[7] + 1126891415 | 0;
1073 d = (d << 10 | d >>> 22) + a | 0;
1074 c += (a ^ (d | ~b)) + k[14] - 1416354905 | 0;
1075 c = (c << 15 | c >>> 17) + d | 0;
1076 b += (d ^ (c | ~a)) + k[5] - 57434055 | 0;
1077 b = (b << 21 |b >>> 11) + c | 0;
1078 a += (c ^ (b | ~d)) + k[12] + 1700485571 | 0;
1079 a = (a << 6 | a >>> 26) + b | 0;
1080 d += (b ^ (a | ~c)) + k[3] - 1894986606 | 0;
1081 d = (d << 10 | d >>> 22) + a | 0;
1082 c += (a ^ (d | ~b)) + k[10] - 1051523 | 0;
1083 c = (c << 15 | c >>> 17) + d | 0;
1084 b += (d ^ (c | ~a)) + k[1] - 2054922799 | 0;
1085 b = (b << 21 |b >>> 11) + c | 0;
1086 a += (c ^ (b | ~d)) + k[8] + 1873313359 | 0;
1087 a = (a << 6 | a >>> 26) + b | 0;
1088 d += (b ^ (a | ~c)) + k[15] - 30611744 | 0;
1089 d = (d << 10 | d >>> 22) + a | 0;
1090 c += (a ^ (d | ~b)) + k[6] - 1560198380 | 0;
1091 c = (c << 15 | c >>> 17) + d | 0;
1092 b += (d ^ (c | ~a)) + k[13] + 1309151649 | 0;
1093 b = (b << 21 |b >>> 11) + c | 0;
1094 a += (c ^ (b | ~d)) + k[4] - 145523070 | 0;
1095 a = (a << 6 | a >>> 26) + b | 0;
1096 d += (b ^ (a | ~c)) + k[11] - 1120210379 | 0;
1097 d = (d << 10 | d >>> 22) + a | 0;
1098 c += (a ^ (d | ~b)) + k[2] + 718787259 | 0;
1099 c = (c << 15 | c >>> 17) + d | 0;
1100 b += (d ^ (c | ~a)) + k[9] - 343485551 | 0;
1101 b = (b << 21 | b >>> 11) + c | 0;
1102
1103 x[0] = a + x[0] | 0;
1104 x[1] = b + x[1] | 0;
1105 x[2] = c + x[2] | 0;
1106 x[3] = d + x[3] | 0;
1107 }
1108
1109 function md5blk(s) {
1110 var md5blks = [],
1111 i; /* Andy King said do it this way. */
1112
1113 for (i = 0; i < 64; i += 4) {
1114 md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) << 24);
1115 }
1116 return md5blks;
1117 }
1118
1119 function md5blk_array(a) {
1120 var md5blks = [],
1121 i; /* Andy King said do it this way. */
1122
1123 for (i = 0; i < 64; i += 4) {
1124 md5blks[i >> 2] = a[i] + (a[i + 1] << 8) + (a[i + 2] << 16) + (a[i + 3] << 24);
1125 }
1126 return md5blks;
1127 }
1128
1129 function md51(s) {
1130 var n = s.length,
1131 state = [1732584193, -271733879, -1732584194, 271733878],
1132 i,
1133 length,
1134 tail,
1135 tmp,
1136 lo,
1137 hi;
1138
1139 for (i = 64; i <= n; i += 64) {
1140 md5cycle(state, md5blk(s.substring(i - 64, i)));
1141 }
1142 s = s.substring(i - 64);
1143 length = s.length;
1144 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
1145 for (i = 0; i < length; i += 1) {
1146 tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3);
1147 }
1148 tail[i >> 2] |= 0x80 << ((i % 4) << 3);
1149 if (i > 55) {
1150 md5cycle(state, tail);
1151 for (i = 0; i < 16; i += 1) {
1152 tail[i] = 0;
1153 }
1154 }
1155
1156 // Beware that the final length might not fit in 32 bits so we take care of that
1157 tmp = n * 8;
1158 tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
1159 lo = parseInt(tmp[2], 16);
1160 hi = parseInt(tmp[1], 16) || 0;
1161
1162 tail[14] = lo;
1163 tail[15] = hi;
1164
1165 md5cycle(state, tail);
1166 return state;
1167 }
1168
1169 function md51_array(a) {
1170 var n = a.length,
1171 state = [1732584193, -271733879, -1732584194, 271733878],
1172 i,
1173 length,
1174 tail,
1175 tmp,
1176 lo,
1177 hi;
1178
1179 for (i = 64; i <= n; i += 64) {
1180 md5cycle(state, md5blk_array(a.subarray(i - 64, i)));
1181 }
1182
1183 // Not sure if it is a bug, however IE10 will always produce a sub array of length 1
1184 // containing the last element of the parent array if the sub array specified starts
1185 // beyond the length of the parent array - weird.
1186 // https://connect.microsoft.com/IE/feedback/details/771452/typed-array-subarray-issue
1187 a = (i - 64) < n ? a.subarray(i - 64) : new Uint8Array(0);
1188
1189 length = a.length;
1190 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
1191 for (i = 0; i < length; i += 1) {
1192 tail[i >> 2] |= a[i] << ((i % 4) << 3);
1193 }
1194
1195 tail[i >> 2] |= 0x80 << ((i % 4) << 3);
1196 if (i > 55) {
1197 md5cycle(state, tail);
1198 for (i = 0; i < 16; i += 1) {
1199 tail[i] = 0;
1200 }
1201 }
1202
1203 // Beware that the final length might not fit in 32 bits so we take care of that
1204 tmp = n * 8;
1205 tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
1206 lo = parseInt(tmp[2], 16);
1207 hi = parseInt(tmp[1], 16) || 0;
1208
1209 tail[14] = lo;
1210 tail[15] = hi;
1211
1212 md5cycle(state, tail);
1213
1214 return state;
1215 }
1216
1217 function rhex(n) {
1218 var s = '',
1219 j;
1220 for (j = 0; j < 4; j += 1) {
1221 s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F];
1222 }
1223 return s;
1224 }
1225
1226 function hex(x) {
1227 var i;
1228 for (i = 0; i < x.length; i += 1) {
1229 x[i] = rhex(x[i]);
1230 }
1231 return x.join('');
1232 }
1233
1234 // In some cases the fast add32 function cannot be used..
1235 if (hex(md51('hello')) !== '5d41402abc4b2a76b9719d911017c592') {
1236 add32 = function (x, y) {
1237 var lsw = (x & 0xFFFF) + (y & 0xFFFF),
1238 msw = (x >> 16) + (y >> 16) + (lsw >> 16);
1239 return (msw << 16) | (lsw & 0xFFFF);
1240 };
1241 }
1242
1243 // ---------------------------------------------------
1244
1245 /**
1246 * ArrayBuffer slice polyfill.
1247 *
1248 * @see https://github.com/ttaubert/node-arraybuffer-slice
1249 */
1250
1251 if (typeof ArrayBuffer !== 'undefined' && !ArrayBuffer.prototype.slice) {
1252 (function () {
1253 function clamp(val, length) {
1254 val = (val | 0) || 0;
1255
1256 if (val < 0) {
1257 return Math.max(val + length, 0);
1258 }
1259
1260 return Math.min(val, length);
1261 }
1262
1263 ArrayBuffer.prototype.slice = function (from, to) {
1264 var length = this.byteLength,
1265 begin = clamp(from, length),
1266 end = length,
1267 num,
1268 target,
1269 targetArray,
1270 sourceArray;
1271
1272 if (to !== undefined) {
1273 end = clamp(to, length);
1274 }
1275
1276 if (begin > end) {
1277 return new ArrayBuffer(0);
1278 }
1279
1280 num = end - begin;
1281 target = new ArrayBuffer(num);
1282 targetArray = new Uint8Array(target);
1283
1284 sourceArray = new Uint8Array(this, begin, num);
1285 targetArray.set(sourceArray);
1286
1287 return target;
1288 };
1289 })();
1290 }
1291
1292 // ---------------------------------------------------
1293
1294 /**
1295 * Helpers.
1296 */
1297
1298 function toUtf8(str) {
1299 if (/[\u0080-\uFFFF]/.test(str)) {
1300 str = unescape(encodeURIComponent(str));
1301 }
1302
1303 return str;
1304 }
1305
1306 function utf8Str2ArrayBuffer(str, returnUInt8Array) {
1307 var length = str.length,
1308 buff = new ArrayBuffer(length),
1309 arr = new Uint8Array(buff),
1310 i;
1311
1312 for (i = 0; i < length; i += 1) {
1313 arr[i] = str.charCodeAt(i);
1314 }
1315
1316 return returnUInt8Array ? arr : buff;
1317 }
1318
1319 function arrayBuffer2Utf8Str(buff) {
1320 return String.fromCharCode.apply(null, new Uint8Array(buff));
1321 }
1322
1323 function concatenateArrayBuffers(first, second, returnUInt8Array) {
1324 var result = new Uint8Array(first.byteLength + second.byteLength);
1325
1326 result.set(new Uint8Array(first));
1327 result.set(new Uint8Array(second), first.byteLength);
1328
1329 return returnUInt8Array ? result : result.buffer;
1330 }
1331
1332 function hexToBinaryString(hex) {
1333 var bytes = [],
1334 length = hex.length,
1335 x;
1336
1337 for (x = 0; x < length - 1; x += 2) {
1338 bytes.push(parseInt(hex.substr(x, 2), 16));
1339 }
1340
1341 return String.fromCharCode.apply(String, bytes);
1342 }
1343
1344 // ---------------------------------------------------
1345
1346 /**
1347 * SparkMD5 OOP implementation.
1348 *
1349 * Use this class to perform an incremental md5, otherwise use the
1350 * static methods instead.
1351 */
1352
1353 function SparkMD5() {
1354 // call reset to init the instance
1355 this.reset();
1356 }
1357
1358 /**
1359 * Appends a string.
1360 * A conversion will be applied if an utf8 string is detected.
1361 *
1362 * @param {String} str The string to be appended
1363 *
1364 * @return {SparkMD5} The instance itself
1365 */
1366 SparkMD5.prototype.append = function (str) {
1367 // Converts the string to utf8 bytes if necessary
1368 // Then append as binary
1369 this.appendBinary(toUtf8(str));
1370
1371 return this;
1372 };
1373
1374 /**
1375 * Appends a binary string.
1376 *
1377 * @param {String} contents The binary string to be appended
1378 *
1379 * @return {SparkMD5} The instance itself
1380 */
1381 SparkMD5.prototype.appendBinary = function (contents) {
1382 this._buff += contents;
1383 this._length += contents.length;
1384
1385 var length = this._buff.length,
1386 i;
1387
1388 for (i = 64; i <= length; i += 64) {
1389 md5cycle(this._hash, md5blk(this._buff.substring(i - 64, i)));
1390 }
1391
1392 this._buff = this._buff.substring(i - 64);
1393
1394 return this;
1395 };
1396
1397 /**
1398 * Finishes the incremental computation, reseting the internal state and
1399 * returning the result.
1400 *
1401 * @param {Boolean} raw True to get the raw string, false to get the hex string
1402 *
1403 * @return {String} The result
1404 */
1405 SparkMD5.prototype.end = function (raw) {
1406 var buff = this._buff,
1407 length = buff.length,
1408 i,
1409 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
1410 ret;
1411
1412 for (i = 0; i < length; i += 1) {
1413 tail[i >> 2] |= buff.charCodeAt(i) << ((i % 4) << 3);
1414 }
1415
1416 this._finish(tail, length);
1417 ret = hex(this._hash);
1418
1419 if (raw) {
1420 ret = hexToBinaryString(ret);
1421 }
1422
1423 this.reset();
1424
1425 return ret;
1426 };
1427
1428 /**
1429 * Resets the internal state of the computation.
1430 *
1431 * @return {SparkMD5} The instance itself
1432 */
1433 SparkMD5.prototype.reset = function () {
1434 this._buff = '';
1435 this._length = 0;
1436 this._hash = [1732584193, -271733879, -1732584194, 271733878];
1437
1438 return this;
1439 };
1440
1441 /**
1442 * Gets the internal state of the computation.
1443 *
1444 * @return {Object} The state
1445 */
1446 SparkMD5.prototype.getState = function () {
1447 return {
1448 buff: this._buff,
1449 length: this._length,
1450 hash: this._hash.slice()
1451 };
1452 };
1453
1454 /**
1455 * Gets the internal state of the computation.
1456 *
1457 * @param {Object} state The state
1458 *
1459 * @return {SparkMD5} The instance itself
1460 */
1461 SparkMD5.prototype.setState = function (state) {
1462 this._buff = state.buff;
1463 this._length = state.length;
1464 this._hash = state.hash;
1465
1466 return this;
1467 };
1468
1469 /**
1470 * Releases memory used by the incremental buffer and other additional
1471 * resources. If you plan to use the instance again, use reset instead.
1472 */
1473 SparkMD5.prototype.destroy = function () {
1474 delete this._hash;
1475 delete this._buff;
1476 delete this._length;
1477 };
1478
1479 /**
1480 * Finish the final calculation based on the tail.
1481 *
1482 * @param {Array} tail The tail (will be modified)
1483 * @param {Number} length The length of the remaining buffer
1484 */
1485 SparkMD5.prototype._finish = function (tail, length) {
1486 var i = length,
1487 tmp,
1488 lo,
1489 hi;
1490
1491 tail[i >> 2] |= 0x80 << ((i % 4) << 3);
1492 if (i > 55) {
1493 md5cycle(this._hash, tail);
1494 for (i = 0; i < 16; i += 1) {
1495 tail[i] = 0;
1496 }
1497 }
1498
1499 // Do the final computation based on the tail and length
1500 // Beware that the final length may not fit in 32 bits so we take care of that
1501 tmp = this._length * 8;
1502 tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
1503 lo = parseInt(tmp[2], 16);
1504 hi = parseInt(tmp[1], 16) || 0;
1505
1506 tail[14] = lo;
1507 tail[15] = hi;
1508 md5cycle(this._hash, tail);
1509 };
1510
1511 /**
1512 * Performs the md5 hash on a string.
1513 * A conversion will be applied if utf8 string is detected.
1514 *
1515 * @param {String} str The string
1516 * @param {Boolean} [raw] True to get the raw string, false to get the hex string
1517 *
1518 * @return {String} The result
1519 */
1520 SparkMD5.hash = function (str, raw) {
1521 // Converts the string to utf8 bytes if necessary
1522 // Then compute it using the binary function
1523 return SparkMD5.hashBinary(toUtf8(str), raw);
1524 };
1525
1526 /**
1527 * Performs the md5 hash on a binary string.
1528 *
1529 * @param {String} content The binary string
1530 * @param {Boolean} [raw] True to get the raw string, false to get the hex string
1531 *
1532 * @return {String} The result
1533 */
1534 SparkMD5.hashBinary = function (content, raw) {
1535 var hash = md51(content),
1536 ret = hex(hash);
1537
1538 return raw ? hexToBinaryString(ret) : ret;
1539 };
1540
1541 // ---------------------------------------------------
1542
1543 /**
1544 * SparkMD5 OOP implementation for array buffers.
1545 *
1546 * Use this class to perform an incremental md5 ONLY for array buffers.
1547 */
1548 SparkMD5.ArrayBuffer = function () {
1549 // call reset to init the instance
1550 this.reset();
1551 };
1552
1553 /**
1554 * Appends an array buffer.
1555 *
1556 * @param {ArrayBuffer} arr The array to be appended
1557 *
1558 * @return {SparkMD5.ArrayBuffer} The instance itself
1559 */
1560 SparkMD5.ArrayBuffer.prototype.append = function (arr) {
1561 var buff = concatenateArrayBuffers(this._buff.buffer, arr, true),
1562 length = buff.length,
1563 i;
1564
1565 this._length += arr.byteLength;
1566
1567 for (i = 64; i <= length; i += 64) {
1568 md5cycle(this._hash, md5blk_array(buff.subarray(i - 64, i)));
1569 }
1570
1571 this._buff = (i - 64) < length ? new Uint8Array(buff.buffer.slice(i - 64)) : new Uint8Array(0);
1572
1573 return this;
1574 };
1575
1576 /**
1577 * Finishes the incremental computation, reseting the internal state and
1578 * returning the result.
1579 *
1580 * @param {Boolean} raw True to get the raw string, false to get the hex string
1581 *
1582 * @return {String} The result
1583 */
1584 SparkMD5.ArrayBuffer.prototype.end = function (raw) {
1585 var buff = this._buff,
1586 length = buff.length,
1587 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
1588 i,
1589 ret;
1590
1591 for (i = 0; i < length; i += 1) {
1592 tail[i >> 2] |= buff[i] << ((i % 4) << 3);
1593 }
1594
1595 this._finish(tail, length);
1596 ret = hex(this._hash);
1597
1598 if (raw) {
1599 ret = hexToBinaryString(ret);
1600 }
1601
1602 this.reset();
1603
1604 return ret;
1605 };
1606
1607 /**
1608 * Resets the internal state of the computation.
1609 *
1610 * @return {SparkMD5.ArrayBuffer} The instance itself
1611 */
1612 SparkMD5.ArrayBuffer.prototype.reset = function () {
1613 this._buff = new Uint8Array(0);
1614 this._length = 0;
1615 this._hash = [1732584193, -271733879, -1732584194, 271733878];
1616
1617 return this;
1618 };
1619
1620 /**
1621 * Gets the internal state of the computation.
1622 *
1623 * @return {Object} The state
1624 */
1625 SparkMD5.ArrayBuffer.prototype.getState = function () {
1626 var state = SparkMD5.prototype.getState.call(this);
1627
1628 // Convert buffer to a string
1629 state.buff = arrayBuffer2Utf8Str(state.buff);
1630
1631 return state;
1632 };
1633
1634 /**
1635 * Gets the internal state of the computation.
1636 *
1637 * @param {Object} state The state
1638 *
1639 * @return {SparkMD5.ArrayBuffer} The instance itself
1640 */
1641 SparkMD5.ArrayBuffer.prototype.setState = function (state) {
1642 // Convert string to buffer
1643 state.buff = utf8Str2ArrayBuffer(state.buff, true);
1644
1645 return SparkMD5.prototype.setState.call(this, state);
1646 };
1647
1648 SparkMD5.ArrayBuffer.prototype.destroy = SparkMD5.prototype.destroy;
1649
1650 SparkMD5.ArrayBuffer.prototype._finish = SparkMD5.prototype._finish;
1651
1652 /**
1653 * Performs the md5 hash on an array buffer.
1654 *
1655 * @param {ArrayBuffer} arr The array buffer
1656 * @param {Boolean} [raw] True to get the raw string, false to get the hex one
1657 *
1658 * @return {String} The result
1659 */
1660 SparkMD5.ArrayBuffer.hash = function (arr, raw) {
1661 var hash = md51_array(new Uint8Array(arr)),
1662 ret = hex(hash);
1663
1664 return raw ? hexToBinaryString(ret) : ret;
1665 };
1666
1667 return SparkMD5;
1668}));
1669
1670},{}],11:[function(_dereq_,module,exports){
1671"use strict";
1672
1673Object.defineProperty(exports, "__esModule", {
1674 value: true
1675});
1676Object.defineProperty(exports, "v1", {
1677 enumerable: true,
1678 get: function () {
1679 return _v.default;
1680 }
1681});
1682Object.defineProperty(exports, "v3", {
1683 enumerable: true,
1684 get: function () {
1685 return _v2.default;
1686 }
1687});
1688Object.defineProperty(exports, "v4", {
1689 enumerable: true,
1690 get: function () {
1691 return _v3.default;
1692 }
1693});
1694Object.defineProperty(exports, "v5", {
1695 enumerable: true,
1696 get: function () {
1697 return _v4.default;
1698 }
1699});
1700Object.defineProperty(exports, "NIL", {
1701 enumerable: true,
1702 get: function () {
1703 return _nil.default;
1704 }
1705});
1706Object.defineProperty(exports, "version", {
1707 enumerable: true,
1708 get: function () {
1709 return _version.default;
1710 }
1711});
1712Object.defineProperty(exports, "validate", {
1713 enumerable: true,
1714 get: function () {
1715 return _validate.default;
1716 }
1717});
1718Object.defineProperty(exports, "stringify", {
1719 enumerable: true,
1720 get: function () {
1721 return _stringify.default;
1722 }
1723});
1724Object.defineProperty(exports, "parse", {
1725 enumerable: true,
1726 get: function () {
1727 return _parse.default;
1728 }
1729});
1730
1731var _v = _interopRequireDefault(_dereq_(19));
1732
1733var _v2 = _interopRequireDefault(_dereq_(20));
1734
1735var _v3 = _interopRequireDefault(_dereq_(22));
1736
1737var _v4 = _interopRequireDefault(_dereq_(23));
1738
1739var _nil = _interopRequireDefault(_dereq_(13));
1740
1741var _version = _interopRequireDefault(_dereq_(25));
1742
1743var _validate = _interopRequireDefault(_dereq_(24));
1744
1745var _stringify = _interopRequireDefault(_dereq_(18));
1746
1747var _parse = _interopRequireDefault(_dereq_(14));
1748
1749function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
1750},{"13":13,"14":14,"18":18,"19":19,"20":20,"22":22,"23":23,"24":24,"25":25}],12:[function(_dereq_,module,exports){
1751"use strict";
1752
1753Object.defineProperty(exports, "__esModule", {
1754 value: true
1755});
1756exports.default = void 0;
1757
1758/*
1759 * Browser-compatible JavaScript MD5
1760 *
1761 * Modification of JavaScript MD5
1762 * https://github.com/blueimp/JavaScript-MD5
1763 *
1764 * Copyright 2011, Sebastian Tschan
1765 * https://blueimp.net
1766 *
1767 * Licensed under the MIT license:
1768 * https://opensource.org/licenses/MIT
1769 *
1770 * Based on
1771 * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
1772 * Digest Algorithm, as defined in RFC 1321.
1773 * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009
1774 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
1775 * Distributed under the BSD License
1776 * See http://pajhome.org.uk/crypt/md5 for more info.
1777 */
1778function md5(bytes) {
1779 if (typeof bytes === 'string') {
1780 const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape
1781
1782 bytes = new Uint8Array(msg.length);
1783
1784 for (let i = 0; i < msg.length; ++i) {
1785 bytes[i] = msg.charCodeAt(i);
1786 }
1787 }
1788
1789 return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes), bytes.length * 8));
1790}
1791/*
1792 * Convert an array of little-endian words to an array of bytes
1793 */
1794
1795
1796function md5ToHexEncodedArray(input) {
1797 const output = [];
1798 const length32 = input.length * 32;
1799 const hexTab = '0123456789abcdef';
1800
1801 for (let i = 0; i < length32; i += 8) {
1802 const x = input[i >> 5] >>> i % 32 & 0xff;
1803 const hex = parseInt(hexTab.charAt(x >>> 4 & 0x0f) + hexTab.charAt(x & 0x0f), 16);
1804 output.push(hex);
1805 }
1806
1807 return output;
1808}
1809/**
1810 * Calculate output length with padding and bit length
1811 */
1812
1813
1814function getOutputLength(inputLength8) {
1815 return (inputLength8 + 64 >>> 9 << 4) + 14 + 1;
1816}
1817/*
1818 * Calculate the MD5 of an array of little-endian words, and a bit length.
1819 */
1820
1821
1822function wordsToMd5(x, len) {
1823 /* append padding */
1824 x[len >> 5] |= 0x80 << len % 32;
1825 x[getOutputLength(len) - 1] = len;
1826 let a = 1732584193;
1827 let b = -271733879;
1828 let c = -1732584194;
1829 let d = 271733878;
1830
1831 for (let i = 0; i < x.length; i += 16) {
1832 const olda = a;
1833 const oldb = b;
1834 const oldc = c;
1835 const oldd = d;
1836 a = md5ff(a, b, c, d, x[i], 7, -680876936);
1837 d = md5ff(d, a, b, c, x[i + 1], 12, -389564586);
1838 c = md5ff(c, d, a, b, x[i + 2], 17, 606105819);
1839 b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330);
1840 a = md5ff(a, b, c, d, x[i + 4], 7, -176418897);
1841 d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426);
1842 c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341);
1843 b = md5ff(b, c, d, a, x[i + 7], 22, -45705983);
1844 a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416);
1845 d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417);
1846 c = md5ff(c, d, a, b, x[i + 10], 17, -42063);
1847 b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162);
1848 a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682);
1849 d = md5ff(d, a, b, c, x[i + 13], 12, -40341101);
1850 c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290);
1851 b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329);
1852 a = md5gg(a, b, c, d, x[i + 1], 5, -165796510);
1853 d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632);
1854 c = md5gg(c, d, a, b, x[i + 11], 14, 643717713);
1855 b = md5gg(b, c, d, a, x[i], 20, -373897302);
1856 a = md5gg(a, b, c, d, x[i + 5], 5, -701558691);
1857 d = md5gg(d, a, b, c, x[i + 10], 9, 38016083);
1858 c = md5gg(c, d, a, b, x[i + 15], 14, -660478335);
1859 b = md5gg(b, c, d, a, x[i + 4], 20, -405537848);
1860 a = md5gg(a, b, c, d, x[i + 9], 5, 568446438);
1861 d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690);
1862 c = md5gg(c, d, a, b, x[i + 3], 14, -187363961);
1863 b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501);
1864 a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467);
1865 d = md5gg(d, a, b, c, x[i + 2], 9, -51403784);
1866 c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473);
1867 b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734);
1868 a = md5hh(a, b, c, d, x[i + 5], 4, -378558);
1869 d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463);
1870 c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562);
1871 b = md5hh(b, c, d, a, x[i + 14], 23, -35309556);
1872 a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060);
1873 d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353);
1874 c = md5hh(c, d, a, b, x[i + 7], 16, -155497632);
1875 b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640);
1876 a = md5hh(a, b, c, d, x[i + 13], 4, 681279174);
1877 d = md5hh(d, a, b, c, x[i], 11, -358537222);
1878 c = md5hh(c, d, a, b, x[i + 3], 16, -722521979);
1879 b = md5hh(b, c, d, a, x[i + 6], 23, 76029189);
1880 a = md5hh(a, b, c, d, x[i + 9], 4, -640364487);
1881 d = md5hh(d, a, b, c, x[i + 12], 11, -421815835);
1882 c = md5hh(c, d, a, b, x[i + 15], 16, 530742520);
1883 b = md5hh(b, c, d, a, x[i + 2], 23, -995338651);
1884 a = md5ii(a, b, c, d, x[i], 6, -198630844);
1885 d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415);
1886 c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905);
1887 b = md5ii(b, c, d, a, x[i + 5], 21, -57434055);
1888 a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571);
1889 d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606);
1890 c = md5ii(c, d, a, b, x[i + 10], 15, -1051523);
1891 b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799);
1892 a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359);
1893 d = md5ii(d, a, b, c, x[i + 15], 10, -30611744);
1894 c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380);
1895 b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649);
1896 a = md5ii(a, b, c, d, x[i + 4], 6, -145523070);
1897 d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379);
1898 c = md5ii(c, d, a, b, x[i + 2], 15, 718787259);
1899 b = md5ii(b, c, d, a, x[i + 9], 21, -343485551);
1900 a = safeAdd(a, olda);
1901 b = safeAdd(b, oldb);
1902 c = safeAdd(c, oldc);
1903 d = safeAdd(d, oldd);
1904 }
1905
1906 return [a, b, c, d];
1907}
1908/*
1909 * Convert an array bytes to an array of little-endian words
1910 * Characters >255 have their high-byte silently ignored.
1911 */
1912
1913
1914function bytesToWords(input) {
1915 if (input.length === 0) {
1916 return [];
1917 }
1918
1919 const length8 = input.length * 8;
1920 const output = new Uint32Array(getOutputLength(length8));
1921
1922 for (let i = 0; i < length8; i += 8) {
1923 output[i >> 5] |= (input[i / 8] & 0xff) << i % 32;
1924 }
1925
1926 return output;
1927}
1928/*
1929 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
1930 * to work around bugs in some JS interpreters.
1931 */
1932
1933
1934function safeAdd(x, y) {
1935 const lsw = (x & 0xffff) + (y & 0xffff);
1936 const msw = (x >> 16) + (y >> 16) + (lsw >> 16);
1937 return msw << 16 | lsw & 0xffff;
1938}
1939/*
1940 * Bitwise rotate a 32-bit number to the left.
1941 */
1942
1943
1944function bitRotateLeft(num, cnt) {
1945 return num << cnt | num >>> 32 - cnt;
1946}
1947/*
1948 * These functions implement the four basic operations the algorithm uses.
1949 */
1950
1951
1952function md5cmn(q, a, b, x, s, t) {
1953 return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b);
1954}
1955
1956function md5ff(a, b, c, d, x, s, t) {
1957 return md5cmn(b & c | ~b & d, a, b, x, s, t);
1958}
1959
1960function md5gg(a, b, c, d, x, s, t) {
1961 return md5cmn(b & d | c & ~d, a, b, x, s, t);
1962}
1963
1964function md5hh(a, b, c, d, x, s, t) {
1965 return md5cmn(b ^ c ^ d, a, b, x, s, t);
1966}
1967
1968function md5ii(a, b, c, d, x, s, t) {
1969 return md5cmn(c ^ (b | ~d), a, b, x, s, t);
1970}
1971
1972var _default = md5;
1973exports.default = _default;
1974},{}],13:[function(_dereq_,module,exports){
1975"use strict";
1976
1977Object.defineProperty(exports, "__esModule", {
1978 value: true
1979});
1980exports.default = void 0;
1981var _default = '00000000-0000-0000-0000-000000000000';
1982exports.default = _default;
1983},{}],14:[function(_dereq_,module,exports){
1984"use strict";
1985
1986Object.defineProperty(exports, "__esModule", {
1987 value: true
1988});
1989exports.default = void 0;
1990
1991var _validate = _interopRequireDefault(_dereq_(24));
1992
1993function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
1994
1995function parse(uuid) {
1996 if (!(0, _validate.default)(uuid)) {
1997 throw TypeError('Invalid UUID');
1998 }
1999
2000 let v;
2001 const arr = new Uint8Array(16); // Parse ########-....-....-....-............
2002
2003 arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;
2004 arr[1] = v >>> 16 & 0xff;
2005 arr[2] = v >>> 8 & 0xff;
2006 arr[3] = v & 0xff; // Parse ........-####-....-....-............
2007
2008 arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;
2009 arr[5] = v & 0xff; // Parse ........-....-####-....-............
2010
2011 arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;
2012 arr[7] = v & 0xff; // Parse ........-....-....-####-............
2013
2014 arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;
2015 arr[9] = v & 0xff; // Parse ........-....-....-....-############
2016 // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes)
2017
2018 arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff;
2019 arr[11] = v / 0x100000000 & 0xff;
2020 arr[12] = v >>> 24 & 0xff;
2021 arr[13] = v >>> 16 & 0xff;
2022 arr[14] = v >>> 8 & 0xff;
2023 arr[15] = v & 0xff;
2024 return arr;
2025}
2026
2027var _default = parse;
2028exports.default = _default;
2029},{"24":24}],15:[function(_dereq_,module,exports){
2030"use strict";
2031
2032Object.defineProperty(exports, "__esModule", {
2033 value: true
2034});
2035exports.default = void 0;
2036var _default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;
2037exports.default = _default;
2038},{}],16:[function(_dereq_,module,exports){
2039"use strict";
2040
2041Object.defineProperty(exports, "__esModule", {
2042 value: true
2043});
2044exports.default = rng;
2045// Unique ID creation requires a high quality random # generator. In the browser we therefore
2046// require the crypto API and do not support built-in fallback to lower quality random number
2047// generators (like Math.random()).
2048let getRandomValues;
2049const rnds8 = new Uint8Array(16);
2050
2051function rng() {
2052 // lazy load so that environments that need to polyfill have a chance to do so
2053 if (!getRandomValues) {
2054 // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. Also,
2055 // find the complete implementation of crypto (msCrypto) on IE11.
2056 getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== 'undefined' && typeof msCrypto.getRandomValues === 'function' && msCrypto.getRandomValues.bind(msCrypto);
2057
2058 if (!getRandomValues) {
2059 throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
2060 }
2061 }
2062
2063 return getRandomValues(rnds8);
2064}
2065},{}],17:[function(_dereq_,module,exports){
2066"use strict";
2067
2068Object.defineProperty(exports, "__esModule", {
2069 value: true
2070});
2071exports.default = void 0;
2072
2073// Adapted from Chris Veness' SHA1 code at
2074// http://www.movable-type.co.uk/scripts/sha1.html
2075function f(s, x, y, z) {
2076 switch (s) {
2077 case 0:
2078 return x & y ^ ~x & z;
2079
2080 case 1:
2081 return x ^ y ^ z;
2082
2083 case 2:
2084 return x & y ^ x & z ^ y & z;
2085
2086 case 3:
2087 return x ^ y ^ z;
2088 }
2089}
2090
2091function ROTL(x, n) {
2092 return x << n | x >>> 32 - n;
2093}
2094
2095function sha1(bytes) {
2096 const K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6];
2097 const H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0];
2098
2099 if (typeof bytes === 'string') {
2100 const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape
2101
2102 bytes = [];
2103
2104 for (let i = 0; i < msg.length; ++i) {
2105 bytes.push(msg.charCodeAt(i));
2106 }
2107 } else if (!Array.isArray(bytes)) {
2108 // Convert Array-like to Array
2109 bytes = Array.prototype.slice.call(bytes);
2110 }
2111
2112 bytes.push(0x80);
2113 const l = bytes.length / 4 + 2;
2114 const N = Math.ceil(l / 16);
2115 const M = new Array(N);
2116
2117 for (let i = 0; i < N; ++i) {
2118 const arr = new Uint32Array(16);
2119
2120 for (let j = 0; j < 16; ++j) {
2121 arr[j] = bytes[i * 64 + j * 4] << 24 | bytes[i * 64 + j * 4 + 1] << 16 | bytes[i * 64 + j * 4 + 2] << 8 | bytes[i * 64 + j * 4 + 3];
2122 }
2123
2124 M[i] = arr;
2125 }
2126
2127 M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32);
2128 M[N - 1][14] = Math.floor(M[N - 1][14]);
2129 M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff;
2130
2131 for (let i = 0; i < N; ++i) {
2132 const W = new Uint32Array(80);
2133
2134 for (let t = 0; t < 16; ++t) {
2135 W[t] = M[i][t];
2136 }
2137
2138 for (let t = 16; t < 80; ++t) {
2139 W[t] = ROTL(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1);
2140 }
2141
2142 let a = H[0];
2143 let b = H[1];
2144 let c = H[2];
2145 let d = H[3];
2146 let e = H[4];
2147
2148 for (let t = 0; t < 80; ++t) {
2149 const s = Math.floor(t / 20);
2150 const T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[t] >>> 0;
2151 e = d;
2152 d = c;
2153 c = ROTL(b, 30) >>> 0;
2154 b = a;
2155 a = T;
2156 }
2157
2158 H[0] = H[0] + a >>> 0;
2159 H[1] = H[1] + b >>> 0;
2160 H[2] = H[2] + c >>> 0;
2161 H[3] = H[3] + d >>> 0;
2162 H[4] = H[4] + e >>> 0;
2163 }
2164
2165 return [H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff];
2166}
2167
2168var _default = sha1;
2169exports.default = _default;
2170},{}],18:[function(_dereq_,module,exports){
2171"use strict";
2172
2173Object.defineProperty(exports, "__esModule", {
2174 value: true
2175});
2176exports.default = void 0;
2177
2178var _validate = _interopRequireDefault(_dereq_(24));
2179
2180function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
2181
2182/**
2183 * Convert array of 16 byte values to UUID string format of the form:
2184 * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
2185 */
2186const byteToHex = [];
2187
2188for (let i = 0; i < 256; ++i) {
2189 byteToHex.push((i + 0x100).toString(16).substr(1));
2190}
2191
2192function stringify(arr, offset = 0) {
2193 // Note: Be careful editing this code! It's been tuned for performance
2194 // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
2195 const uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one
2196 // of the following:
2197 // - One or more input array values don't map to a hex octet (leading to
2198 // "undefined" in the uuid)
2199 // - Invalid input values for the RFC `version` or `variant` fields
2200
2201 if (!(0, _validate.default)(uuid)) {
2202 throw TypeError('Stringified UUID is invalid');
2203 }
2204
2205 return uuid;
2206}
2207
2208var _default = stringify;
2209exports.default = _default;
2210},{"24":24}],19:[function(_dereq_,module,exports){
2211"use strict";
2212
2213Object.defineProperty(exports, "__esModule", {
2214 value: true
2215});
2216exports.default = void 0;
2217
2218var _rng = _interopRequireDefault(_dereq_(16));
2219
2220var _stringify = _interopRequireDefault(_dereq_(18));
2221
2222function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
2223
2224// **`v1()` - Generate time-based UUID**
2225//
2226// Inspired by https://github.com/LiosK/UUID.js
2227// and http://docs.python.org/library/uuid.html
2228let _nodeId;
2229
2230let _clockseq; // Previous uuid creation time
2231
2232
2233let _lastMSecs = 0;
2234let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details
2235
2236function v1(options, buf, offset) {
2237 let i = buf && offset || 0;
2238 const b = buf || new Array(16);
2239 options = options || {};
2240 let node = options.node || _nodeId;
2241 let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not
2242 // specified. We do this lazily to minimize issues related to insufficient
2243 // system entropy. See #189
2244
2245 if (node == null || clockseq == null) {
2246 const seedBytes = options.random || (options.rng || _rng.default)();
2247
2248 if (node == null) {
2249 // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
2250 node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]];
2251 }
2252
2253 if (clockseq == null) {
2254 // Per 4.2.2, randomize (14 bit) clockseq
2255 clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;
2256 }
2257 } // UUID timestamps are 100 nano-second units since the Gregorian epoch,
2258 // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
2259 // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
2260 // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
2261
2262
2263 let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock
2264 // cycle to simulate higher resolution clock
2265
2266 let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs)
2267
2268 const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression
2269
2270 if (dt < 0 && options.clockseq === undefined) {
2271 clockseq = clockseq + 1 & 0x3fff;
2272 } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
2273 // time interval
2274
2275
2276 if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {
2277 nsecs = 0;
2278 } // Per 4.2.1.2 Throw error if too many uuids are requested
2279
2280
2281 if (nsecs >= 10000) {
2282 throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");
2283 }
2284
2285 _lastMSecs = msecs;
2286 _lastNSecs = nsecs;
2287 _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
2288
2289 msecs += 12219292800000; // `time_low`
2290
2291 const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
2292 b[i++] = tl >>> 24 & 0xff;
2293 b[i++] = tl >>> 16 & 0xff;
2294 b[i++] = tl >>> 8 & 0xff;
2295 b[i++] = tl & 0xff; // `time_mid`
2296
2297 const tmh = msecs / 0x100000000 * 10000 & 0xfffffff;
2298 b[i++] = tmh >>> 8 & 0xff;
2299 b[i++] = tmh & 0xff; // `time_high_and_version`
2300
2301 b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
2302
2303 b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
2304
2305 b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low`
2306
2307 b[i++] = clockseq & 0xff; // `node`
2308
2309 for (let n = 0; n < 6; ++n) {
2310 b[i + n] = node[n];
2311 }
2312
2313 return buf || (0, _stringify.default)(b);
2314}
2315
2316var _default = v1;
2317exports.default = _default;
2318},{"16":16,"18":18}],20:[function(_dereq_,module,exports){
2319"use strict";
2320
2321Object.defineProperty(exports, "__esModule", {
2322 value: true
2323});
2324exports.default = void 0;
2325
2326var _v = _interopRequireDefault(_dereq_(21));
2327
2328var _md = _interopRequireDefault(_dereq_(12));
2329
2330function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
2331
2332const v3 = (0, _v.default)('v3', 0x30, _md.default);
2333var _default = v3;
2334exports.default = _default;
2335},{"12":12,"21":21}],21:[function(_dereq_,module,exports){
2336"use strict";
2337
2338Object.defineProperty(exports, "__esModule", {
2339 value: true
2340});
2341exports.default = _default;
2342exports.URL = exports.DNS = void 0;
2343
2344var _stringify = _interopRequireDefault(_dereq_(18));
2345
2346var _parse = _interopRequireDefault(_dereq_(14));
2347
2348function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
2349
2350function stringToBytes(str) {
2351 str = unescape(encodeURIComponent(str)); // UTF8 escape
2352
2353 const bytes = [];
2354
2355 for (let i = 0; i < str.length; ++i) {
2356 bytes.push(str.charCodeAt(i));
2357 }
2358
2359 return bytes;
2360}
2361
2362const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
2363exports.DNS = DNS;
2364const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';
2365exports.URL = URL;
2366
2367function _default(name, version, hashfunc) {
2368 function generateUUID(value, namespace, buf, offset) {
2369 if (typeof value === 'string') {
2370 value = stringToBytes(value);
2371 }
2372
2373 if (typeof namespace === 'string') {
2374 namespace = (0, _parse.default)(namespace);
2375 }
2376
2377 if (namespace.length !== 16) {
2378 throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)');
2379 } // Compute hash of namespace and value, Per 4.3
2380 // Future: Use spread syntax when supported on all platforms, e.g. `bytes =
2381 // hashfunc([...namespace, ... value])`
2382
2383
2384 let bytes = new Uint8Array(16 + value.length);
2385 bytes.set(namespace);
2386 bytes.set(value, namespace.length);
2387 bytes = hashfunc(bytes);
2388 bytes[6] = bytes[6] & 0x0f | version;
2389 bytes[8] = bytes[8] & 0x3f | 0x80;
2390
2391 if (buf) {
2392 offset = offset || 0;
2393
2394 for (let i = 0; i < 16; ++i) {
2395 buf[offset + i] = bytes[i];
2396 }
2397
2398 return buf;
2399 }
2400
2401 return (0, _stringify.default)(bytes);
2402 } // Function#name is not settable on some platforms (#270)
2403
2404
2405 try {
2406 generateUUID.name = name; // eslint-disable-next-line no-empty
2407 } catch (err) {} // For CommonJS default export support
2408
2409
2410 generateUUID.DNS = DNS;
2411 generateUUID.URL = URL;
2412 return generateUUID;
2413}
2414},{"14":14,"18":18}],22:[function(_dereq_,module,exports){
2415"use strict";
2416
2417Object.defineProperty(exports, "__esModule", {
2418 value: true
2419});
2420exports.default = void 0;
2421
2422var _rng = _interopRequireDefault(_dereq_(16));
2423
2424var _stringify = _interopRequireDefault(_dereq_(18));
2425
2426function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
2427
2428function v4(options, buf, offset) {
2429 options = options || {};
2430
2431 const rnds = options.random || (options.rng || _rng.default)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
2432
2433
2434 rnds[6] = rnds[6] & 0x0f | 0x40;
2435 rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided
2436
2437 if (buf) {
2438 offset = offset || 0;
2439
2440 for (let i = 0; i < 16; ++i) {
2441 buf[offset + i] = rnds[i];
2442 }
2443
2444 return buf;
2445 }
2446
2447 return (0, _stringify.default)(rnds);
2448}
2449
2450var _default = v4;
2451exports.default = _default;
2452},{"16":16,"18":18}],23:[function(_dereq_,module,exports){
2453"use strict";
2454
2455Object.defineProperty(exports, "__esModule", {
2456 value: true
2457});
2458exports.default = void 0;
2459
2460var _v = _interopRequireDefault(_dereq_(21));
2461
2462var _sha = _interopRequireDefault(_dereq_(17));
2463
2464function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
2465
2466const v5 = (0, _v.default)('v5', 0x50, _sha.default);
2467var _default = v5;
2468exports.default = _default;
2469},{"17":17,"21":21}],24:[function(_dereq_,module,exports){
2470"use strict";
2471
2472Object.defineProperty(exports, "__esModule", {
2473 value: true
2474});
2475exports.default = void 0;
2476
2477var _regex = _interopRequireDefault(_dereq_(15));
2478
2479function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
2480
2481function validate(uuid) {
2482 return typeof uuid === 'string' && _regex.default.test(uuid);
2483}
2484
2485var _default = validate;
2486exports.default = _default;
2487},{"15":15}],25:[function(_dereq_,module,exports){
2488"use strict";
2489
2490Object.defineProperty(exports, "__esModule", {
2491 value: true
2492});
2493exports.default = void 0;
2494
2495var _validate = _interopRequireDefault(_dereq_(24));
2496
2497function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
2498
2499function version(uuid) {
2500 if (!(0, _validate.default)(uuid)) {
2501 throw TypeError('Invalid UUID');
2502 }
2503
2504 return parseInt(uuid.substr(14, 1), 16);
2505}
2506
2507var _default = version;
2508exports.default = _default;
2509},{"24":24}],26:[function(_dereq_,module,exports){
2510'use strict';
2511
2512/**
2513 * Stringify/parse functions that don't operate
2514 * recursively, so they avoid call stack exceeded
2515 * errors.
2516 */
2517exports.stringify = function stringify(input) {
2518 var queue = [];
2519 queue.push({obj: input});
2520
2521 var res = '';
2522 var next, obj, prefix, val, i, arrayPrefix, keys, k, key, value, objPrefix;
2523 while ((next = queue.pop())) {
2524 obj = next.obj;
2525 prefix = next.prefix || '';
2526 val = next.val || '';
2527 res += prefix;
2528 if (val) {
2529 res += val;
2530 } else if (typeof obj !== 'object') {
2531 res += typeof obj === 'undefined' ? null : JSON.stringify(obj);
2532 } else if (obj === null) {
2533 res += 'null';
2534 } else if (Array.isArray(obj)) {
2535 queue.push({val: ']'});
2536 for (i = obj.length - 1; i >= 0; i--) {
2537 arrayPrefix = i === 0 ? '' : ',';
2538 queue.push({obj: obj[i], prefix: arrayPrefix});
2539 }
2540 queue.push({val: '['});
2541 } else { // object
2542 keys = [];
2543 for (k in obj) {
2544 if (obj.hasOwnProperty(k)) {
2545 keys.push(k);
2546 }
2547 }
2548 queue.push({val: '}'});
2549 for (i = keys.length - 1; i >= 0; i--) {
2550 key = keys[i];
2551 value = obj[key];
2552 objPrefix = (i > 0 ? ',' : '');
2553 objPrefix += JSON.stringify(key) + ':';
2554 queue.push({obj: value, prefix: objPrefix});
2555 }
2556 queue.push({val: '{'});
2557 }
2558 }
2559 return res;
2560};
2561
2562// Convenience function for the parse function.
2563// This pop function is basically copied from
2564// pouchCollate.parseIndexableString
2565function pop(obj, stack, metaStack) {
2566 var lastMetaElement = metaStack[metaStack.length - 1];
2567 if (obj === lastMetaElement.element) {
2568 // popping a meta-element, e.g. an object whose value is another object
2569 metaStack.pop();
2570 lastMetaElement = metaStack[metaStack.length - 1];
2571 }
2572 var element = lastMetaElement.element;
2573 var lastElementIndex = lastMetaElement.index;
2574 if (Array.isArray(element)) {
2575 element.push(obj);
2576 } else if (lastElementIndex === stack.length - 2) { // obj with key+value
2577 var key = stack.pop();
2578 element[key] = obj;
2579 } else {
2580 stack.push(obj); // obj with key only
2581 }
2582}
2583
2584exports.parse = function (str) {
2585 var stack = [];
2586 var metaStack = []; // stack for arrays and objects
2587 var i = 0;
2588 var collationIndex,parsedNum,numChar;
2589 var parsedString,lastCh,numConsecutiveSlashes,ch;
2590 var arrayElement, objElement;
2591 while (true) {
2592 collationIndex = str[i++];
2593 if (collationIndex === '}' ||
2594 collationIndex === ']' ||
2595 typeof collationIndex === 'undefined') {
2596 if (stack.length === 1) {
2597 return stack.pop();
2598 } else {
2599 pop(stack.pop(), stack, metaStack);
2600 continue;
2601 }
2602 }
2603 switch (collationIndex) {
2604 case ' ':
2605 case '\t':
2606 case '\n':
2607 case ':':
2608 case ',':
2609 break;
2610 case 'n':
2611 i += 3; // 'ull'
2612 pop(null, stack, metaStack);
2613 break;
2614 case 't':
2615 i += 3; // 'rue'
2616 pop(true, stack, metaStack);
2617 break;
2618 case 'f':
2619 i += 4; // 'alse'
2620 pop(false, stack, metaStack);
2621 break;
2622 case '0':
2623 case '1':
2624 case '2':
2625 case '3':
2626 case '4':
2627 case '5':
2628 case '6':
2629 case '7':
2630 case '8':
2631 case '9':
2632 case '-':
2633 parsedNum = '';
2634 i--;
2635 while (true) {
2636 numChar = str[i++];
2637 if (/[\d\.\-e\+]/.test(numChar)) {
2638 parsedNum += numChar;
2639 } else {
2640 i--;
2641 break;
2642 }
2643 }
2644 pop(parseFloat(parsedNum), stack, metaStack);
2645 break;
2646 case '"':
2647 parsedString = '';
2648 lastCh = void 0;
2649 numConsecutiveSlashes = 0;
2650 while (true) {
2651 ch = str[i++];
2652 if (ch !== '"' || (lastCh === '\\' &&
2653 numConsecutiveSlashes % 2 === 1)) {
2654 parsedString += ch;
2655 lastCh = ch;
2656 if (lastCh === '\\') {
2657 numConsecutiveSlashes++;
2658 } else {
2659 numConsecutiveSlashes = 0;
2660 }
2661 } else {
2662 break;
2663 }
2664 }
2665 pop(JSON.parse('"' + parsedString + '"'), stack, metaStack);
2666 break;
2667 case '[':
2668 arrayElement = { element: [], index: stack.length };
2669 stack.push(arrayElement.element);
2670 metaStack.push(arrayElement);
2671 break;
2672 case '{':
2673 objElement = { element: {}, index: stack.length };
2674 stack.push(objElement.element);
2675 metaStack.push(objElement);
2676 break;
2677 default:
2678 throw new Error(
2679 'unexpectedly reached end of input: ' + collationIndex);
2680 }
2681 }
2682};
2683
2684},{}],27:[function(_dereq_,module,exports){
2685(function (process){(function (){
2686'use strict';
2687
2688function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
2689
2690var immediate = _interopDefault(_dereq_(3));
2691var Md5 = _interopDefault(_dereq_(10));
2692var uuid = _dereq_(11);
2693var vuvuzela = _interopDefault(_dereq_(26));
2694var EE = _interopDefault(_dereq_(2));
2695
2696function mangle(key) {
2697 return '$' + key;
2698}
2699function unmangle(key) {
2700 return key.substring(1);
2701}
2702function Map$1() {
2703 this._store = {};
2704}
2705Map$1.prototype.get = function (key) {
2706 var mangled = mangle(key);
2707 return this._store[mangled];
2708};
2709Map$1.prototype.set = function (key, value) {
2710 var mangled = mangle(key);
2711 this._store[mangled] = value;
2712 return true;
2713};
2714Map$1.prototype.has = function (key) {
2715 var mangled = mangle(key);
2716 return mangled in this._store;
2717};
2718Map$1.prototype.keys = function () {
2719 return Object.keys(this._store).map(k => unmangle(k));
2720};
2721Map$1.prototype["delete"] = function (key) {
2722 var mangled = mangle(key);
2723 var res = mangled in this._store;
2724 delete this._store[mangled];
2725 return res;
2726};
2727Map$1.prototype.forEach = function (cb) {
2728 var keys = Object.keys(this._store);
2729 for (var i = 0, len = keys.length; i < len; i++) {
2730 var key = keys[i];
2731 var value = this._store[key];
2732 key = unmangle(key);
2733 cb(value, key);
2734 }
2735};
2736Object.defineProperty(Map$1.prototype, 'size', {
2737 get: function () {
2738 return Object.keys(this._store).length;
2739 }
2740});
2741
2742function Set$1(array) {
2743 this._store = new Map$1();
2744
2745 // init with an array
2746 if (array && Array.isArray(array)) {
2747 for (var i = 0, len = array.length; i < len; i++) {
2748 this.add(array[i]);
2749 }
2750 }
2751}
2752Set$1.prototype.add = function (key) {
2753 return this._store.set(key, true);
2754};
2755Set$1.prototype.has = function (key) {
2756 return this._store.has(key);
2757};
2758Set$1.prototype.forEach = function (cb) {
2759 this._store.forEach(function (value, key) {
2760 cb(key);
2761 });
2762};
2763Object.defineProperty(Set$1.prototype, 'size', {
2764 get: function () {
2765 return this._store.size;
2766 }
2767});
2768
2769// Based on https://kangax.github.io/compat-table/es6/ we can sniff out
2770// incomplete Map/Set implementations which would otherwise cause our tests to fail.
2771// Notably they fail in IE11 and iOS 8.4, which this prevents.
2772function supportsMapAndSet() {
2773 if (typeof Symbol === 'undefined' || typeof Map === 'undefined' || typeof Set === 'undefined') {
2774 return false;
2775 }
2776 var prop = Object.getOwnPropertyDescriptor(Map, Symbol.species);
2777 return prop && 'get' in prop && Map[Symbol.species] === Map;
2778}
2779
2780// based on https://github.com/montagejs/collections
2781
2782var ExportedSet;
2783var ExportedMap;
2784
2785{
2786 if (supportsMapAndSet()) { // prefer built-in Map/Set
2787 ExportedSet = Set;
2788 ExportedMap = Map;
2789 } else { // fall back to our polyfill
2790 ExportedSet = Set$1;
2791 ExportedMap = Map$1;
2792 }
2793}
2794
2795function isBinaryObject(object) {
2796 return (typeof ArrayBuffer !== 'undefined' && object instanceof ArrayBuffer) ||
2797 (typeof Blob !== 'undefined' && object instanceof Blob);
2798}
2799
2800function cloneArrayBuffer(buff) {
2801 if (typeof buff.slice === 'function') {
2802 return buff.slice(0);
2803 }
2804 // IE10-11 slice() polyfill
2805 var target = new ArrayBuffer(buff.byteLength);
2806 var targetArray = new Uint8Array(target);
2807 var sourceArray = new Uint8Array(buff);
2808 targetArray.set(sourceArray);
2809 return target;
2810}
2811
2812function cloneBinaryObject(object) {
2813 if (object instanceof ArrayBuffer) {
2814 return cloneArrayBuffer(object);
2815 }
2816 var size = object.size;
2817 var type = object.type;
2818 // Blob
2819 if (typeof object.slice === 'function') {
2820 return object.slice(0, size, type);
2821 }
2822 // PhantomJS slice() replacement
2823 return object.webkitSlice(0, size, type);
2824}
2825
2826// most of this is borrowed from lodash.isPlainObject:
2827// https://github.com/fis-components/lodash.isplainobject/
2828// blob/29c358140a74f252aeb08c9eb28bef86f2217d4a/index.js
2829
2830var funcToString = Function.prototype.toString;
2831var objectCtorString = funcToString.call(Object);
2832
2833function isPlainObject(value) {
2834 var proto = Object.getPrototypeOf(value);
2835 /* istanbul ignore if */
2836 if (proto === null) { // not sure when this happens, but I guess it can
2837 return true;
2838 }
2839 var Ctor = proto.constructor;
2840 return (typeof Ctor == 'function' &&
2841 Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString);
2842}
2843
2844function clone(object) {
2845 var newObject;
2846 var i;
2847 var len;
2848
2849 if (!object || typeof object !== 'object') {
2850 return object;
2851 }
2852
2853 if (Array.isArray(object)) {
2854 newObject = [];
2855 for (i = 0, len = object.length; i < len; i++) {
2856 newObject[i] = clone(object[i]);
2857 }
2858 return newObject;
2859 }
2860
2861 // special case: to avoid inconsistencies between IndexedDB
2862 // and other backends, we automatically stringify Dates
2863 if (object instanceof Date && isFinite(object)) {
2864 return object.toISOString();
2865 }
2866
2867 if (isBinaryObject(object)) {
2868 return cloneBinaryObject(object);
2869 }
2870
2871 if (!isPlainObject(object)) {
2872 return object; // don't clone objects like Workers
2873 }
2874
2875 newObject = {};
2876 for (i in object) {
2877 /* istanbul ignore else */
2878 if (Object.prototype.hasOwnProperty.call(object, i)) {
2879 var value = clone(object[i]);
2880 if (typeof value !== 'undefined') {
2881 newObject[i] = value;
2882 }
2883 }
2884 }
2885 return newObject;
2886}
2887
2888function once(fun) {
2889 var called = false;
2890 return function (...args) {
2891 /* istanbul ignore if */
2892 if (called) {
2893 // this is a smoke test and should never actually happen
2894 throw new Error('once called more than once');
2895 } else {
2896 called = true;
2897 fun.apply(this, args);
2898 }
2899 };
2900}
2901
2902function toPromise(func) {
2903 //create the function we will be returning
2904 return function (...args) {
2905 // Clone arguments
2906 args = clone(args);
2907 var self = this;
2908 // if the last argument is a function, assume its a callback
2909 var usedCB = (typeof args[args.length - 1] === 'function') ? args.pop() : false;
2910 var promise = new Promise(function (fulfill, reject) {
2911 var resp;
2912 try {
2913 var callback = once(function (err, mesg) {
2914 if (err) {
2915 reject(err);
2916 } else {
2917 fulfill(mesg);
2918 }
2919 });
2920 // create a callback for this invocation
2921 // apply the function in the orig context
2922 args.push(callback);
2923 resp = func.apply(self, args);
2924 if (resp && typeof resp.then === 'function') {
2925 fulfill(resp);
2926 }
2927 } catch (e) {
2928 reject(e);
2929 }
2930 });
2931 // if there is a callback, call it back
2932 if (usedCB) {
2933 promise.then(function (result) {
2934 usedCB(null, result);
2935 }, usedCB);
2936 }
2937 return promise;
2938 };
2939}
2940
2941function logApiCall(self, name, args) {
2942 /* istanbul ignore if */
2943 if (self.constructor.listeners('debug').length) {
2944 var logArgs = ['api', self.name, name];
2945 for (var i = 0; i < args.length - 1; i++) {
2946 logArgs.push(args[i]);
2947 }
2948 self.constructor.emit('debug', logArgs);
2949
2950 // override the callback itself to log the response
2951 var origCallback = args[args.length - 1];
2952 args[args.length - 1] = function (err, res) {
2953 var responseArgs = ['api', self.name, name];
2954 responseArgs = responseArgs.concat(
2955 err ? ['error', err] : ['success', res]
2956 );
2957 self.constructor.emit('debug', responseArgs);
2958 origCallback(err, res);
2959 };
2960 }
2961}
2962
2963function adapterFun(name, callback) {
2964 return toPromise(function (...args) {
2965 if (this._closed) {
2966 return Promise.reject(new Error('database is closed'));
2967 }
2968 if (this._destroyed) {
2969 return Promise.reject(new Error('database is destroyed'));
2970 }
2971 var self = this;
2972 logApiCall(self, name, args);
2973 if (!this.taskqueue.isReady) {
2974 return new Promise(function (fulfill, reject) {
2975 self.taskqueue.addTask(function (failed) {
2976 if (failed) {
2977 reject(failed);
2978 } else {
2979 fulfill(self[name].apply(self, args));
2980 }
2981 });
2982 });
2983 }
2984 return callback.apply(this, args);
2985 });
2986}
2987
2988// like underscore/lodash _.pick()
2989function pick(obj, arr) {
2990 var res = {};
2991 for (var i = 0, len = arr.length; i < len; i++) {
2992 var prop = arr[i];
2993 if (prop in obj) {
2994 res[prop] = obj[prop];
2995 }
2996 }
2997 return res;
2998}
2999
3000// Most browsers throttle concurrent requests at 6, so it's silly
3001// to shim _bulk_get by trying to launch potentially hundreds of requests
3002// and then letting the majority time out. We can handle this ourselves.
3003var MAX_NUM_CONCURRENT_REQUESTS = 6;
3004
3005function identityFunction(x) {
3006 return x;
3007}
3008
3009function formatResultForOpenRevsGet(result) {
3010 return [{
3011 ok: result
3012 }];
3013}
3014
3015// shim for P/CouchDB adapters that don't directly implement _bulk_get
3016function bulkGet(db, opts, callback) {
3017 var requests = opts.docs;
3018
3019 // consolidate into one request per doc if possible
3020 var requestsById = new ExportedMap();
3021 requests.forEach(function (request) {
3022 if (requestsById.has(request.id)) {
3023 requestsById.get(request.id).push(request);
3024 } else {
3025 requestsById.set(request.id, [request]);
3026 }
3027 });
3028
3029 var numDocs = requestsById.size;
3030 var numDone = 0;
3031 var perDocResults = new Array(numDocs);
3032
3033 function collapseResultsAndFinish() {
3034 var results = [];
3035 perDocResults.forEach(function (res) {
3036 res.docs.forEach(function (info) {
3037 results.push({
3038 id: res.id,
3039 docs: [info]
3040 });
3041 });
3042 });
3043 callback(null, {results: results});
3044 }
3045
3046 function checkDone() {
3047 if (++numDone === numDocs) {
3048 collapseResultsAndFinish();
3049 }
3050 }
3051
3052 function gotResult(docIndex, id, docs) {
3053 perDocResults[docIndex] = {id: id, docs: docs};
3054 checkDone();
3055 }
3056
3057 var allRequests = [];
3058 requestsById.forEach(function (value, key) {
3059 allRequests.push(key);
3060 });
3061
3062 var i = 0;
3063
3064 function nextBatch() {
3065
3066 if (i >= allRequests.length) {
3067 return;
3068 }
3069
3070 var upTo = Math.min(i + MAX_NUM_CONCURRENT_REQUESTS, allRequests.length);
3071 var batch = allRequests.slice(i, upTo);
3072 processBatch(batch, i);
3073 i += batch.length;
3074 }
3075
3076 function processBatch(batch, offset) {
3077 batch.forEach(function (docId, j) {
3078 var docIdx = offset + j;
3079 var docRequests = requestsById.get(docId);
3080
3081 // just use the first request as the "template"
3082 // TODO: The _bulk_get API allows for more subtle use cases than this,
3083 // but for now it is unlikely that there will be a mix of different
3084 // "atts_since" or "attachments" in the same request, since it's just
3085 // replicate.js that is using this for the moment.
3086 // Also, atts_since is aspirational, since we don't support it yet.
3087 var docOpts = pick(docRequests[0], ['atts_since', 'attachments']);
3088 docOpts.open_revs = docRequests.map(function (request) {
3089 // rev is optional, open_revs disallowed
3090 return request.rev;
3091 });
3092
3093 // remove falsey / undefined revisions
3094 docOpts.open_revs = docOpts.open_revs.filter(identityFunction);
3095
3096 var formatResult = identityFunction;
3097
3098 if (docOpts.open_revs.length === 0) {
3099 delete docOpts.open_revs;
3100
3101 // when fetching only the "winning" leaf,
3102 // transform the result so it looks like an open_revs
3103 // request
3104 formatResult = formatResultForOpenRevsGet;
3105 }
3106
3107 // globally-supplied options
3108 ['revs', 'attachments', 'binary', 'ajax', 'latest'].forEach(function (param) {
3109 if (param in opts) {
3110 docOpts[param] = opts[param];
3111 }
3112 });
3113 db.get(docId, docOpts, function (err, res) {
3114 var result;
3115 /* istanbul ignore if */
3116 if (err) {
3117 result = [{error: err}];
3118 } else {
3119 result = formatResult(res);
3120 }
3121 gotResult(docIdx, docId, result);
3122 nextBatch();
3123 });
3124 });
3125 }
3126
3127 nextBatch();
3128
3129}
3130
3131var hasLocal;
3132
3133try {
3134 localStorage.setItem('_pouch_check_localstorage', 1);
3135 hasLocal = !!localStorage.getItem('_pouch_check_localstorage');
3136} catch (e) {
3137 hasLocal = false;
3138}
3139
3140function hasLocalStorage() {
3141 return hasLocal;
3142}
3143
3144// Custom nextTick() shim for browsers. In node, this will just be process.nextTick(). We
3145
3146class Changes extends EE {
3147 constructor() {
3148 super();
3149
3150 this._listeners = {};
3151
3152 if (hasLocalStorage()) {
3153 addEventListener("storage", (e) => {
3154 this.emit(e.key);
3155 });
3156 }
3157 }
3158
3159 addListener(dbName, id, db, opts) {
3160 if (this._listeners[id]) {
3161 return;
3162 }
3163 var inprogress = false;
3164 var self = this;
3165 function eventFunction() {
3166 if (!self._listeners[id]) {
3167 return;
3168 }
3169 if (inprogress) {
3170 inprogress = 'waiting';
3171 return;
3172 }
3173 inprogress = true;
3174 var changesOpts = pick(opts, [
3175 'style', 'include_docs', 'attachments', 'conflicts', 'filter',
3176 'doc_ids', 'view', 'since', 'query_params', 'binary', 'return_docs'
3177 ]);
3178
3179 function onError() {
3180 inprogress = false;
3181 }
3182
3183 db.changes(changesOpts).on('change', function (c) {
3184 if (c.seq > opts.since && !opts.cancelled) {
3185 opts.since = c.seq;
3186 opts.onChange(c);
3187 }
3188 }).on('complete', function () {
3189 if (inprogress === 'waiting') {
3190 immediate(eventFunction);
3191 }
3192 inprogress = false;
3193 }).on('error', onError);
3194 }
3195 this._listeners[id] = eventFunction;
3196 this.on(dbName, eventFunction);
3197 }
3198
3199 removeListener(dbName, id) {
3200 if (!(id in this._listeners)) {
3201 return;
3202 }
3203 super.removeListener(dbName, this._listeners[id]);
3204 delete this._listeners[id];
3205 }
3206
3207 notifyLocalWindows(dbName) {
3208 //do a useless change on a storage thing
3209 //in order to get other windows's listeners to activate
3210 if (hasLocalStorage()) {
3211 localStorage[dbName] = (localStorage[dbName] === "a") ? "b" : "a";
3212 }
3213 }
3214
3215 notify(dbName) {
3216 this.emit(dbName);
3217 this.notifyLocalWindows(dbName);
3218 }
3219}
3220
3221function guardedConsole(method) {
3222 /* istanbul ignore else */
3223 if (typeof console !== 'undefined' && typeof console[method] === 'function') {
3224 var args = Array.prototype.slice.call(arguments, 1);
3225 console[method].apply(console, args);
3226 }
3227}
3228
3229function randomNumber(min, max) {
3230 var maxTimeout = 600000; // Hard-coded default of 10 minutes
3231 min = parseInt(min, 10) || 0;
3232 max = parseInt(max, 10);
3233 if (max !== max || max <= min) {
3234 max = (min || 1) << 1; //doubling
3235 } else {
3236 max = max + 1;
3237 }
3238 // In order to not exceed maxTimeout, pick a random value between half of maxTimeout and maxTimeout
3239 if (max > maxTimeout) {
3240 min = maxTimeout >> 1; // divide by two
3241 max = maxTimeout;
3242 }
3243 var ratio = Math.random();
3244 var range = max - min;
3245
3246 return ~~(range * ratio + min); // ~~ coerces to an int, but fast.
3247}
3248
3249function defaultBackOff(min) {
3250 var max = 0;
3251 if (!min) {
3252 max = 2000;
3253 }
3254 return randomNumber(min, max);
3255}
3256
3257// designed to give info to browser users, who are disturbed
3258// when they see http errors in the console
3259function explainError(status, str) {
3260 guardedConsole('info', 'The above ' + status + ' is totally normal. ' + str);
3261}
3262
3263var assign;
3264{
3265 if (typeof Object.assign === 'function') {
3266 assign = Object.assign;
3267 } else {
3268 // lite Object.assign polyfill based on
3269 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
3270 assign = function (target) {
3271 var to = Object(target);
3272
3273 for (var index = 1; index < arguments.length; index++) {
3274 var nextSource = arguments[index];
3275
3276 if (nextSource != null) { // Skip over if undefined or null
3277 for (var nextKey in nextSource) {
3278 // Avoid bugs when hasOwnProperty is shadowed
3279 if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
3280 to[nextKey] = nextSource[nextKey];
3281 }
3282 }
3283 }
3284 }
3285 return to;
3286 };
3287 }
3288}
3289
3290var $inject_Object_assign = assign;
3291
3292class PouchError extends Error {
3293 constructor(status, error, reason) {
3294 super();
3295 this.status = status;
3296 this.name = error;
3297 this.message = reason;
3298 this.error = true;
3299 }
3300
3301 toString() {
3302 return JSON.stringify({
3303 status: this.status,
3304 name: this.name,
3305 message: this.message,
3306 reason: this.reason
3307 });
3308 }
3309}
3310
3311var UNAUTHORIZED = new PouchError(401, 'unauthorized', "Name or password is incorrect.");
3312var MISSING_BULK_DOCS = new PouchError(400, 'bad_request', "Missing JSON list of 'docs'");
3313var MISSING_DOC = new PouchError(404, 'not_found', 'missing');
3314var REV_CONFLICT = new PouchError(409, 'conflict', 'Document update conflict');
3315var INVALID_ID = new PouchError(400, 'bad_request', '_id field must contain a string');
3316var MISSING_ID = new PouchError(412, 'missing_id', '_id is required for puts');
3317var RESERVED_ID = new PouchError(400, 'bad_request', 'Only reserved document ids may start with underscore.');
3318var NOT_OPEN = new PouchError(412, 'precondition_failed', 'Database not open');
3319var UNKNOWN_ERROR = new PouchError(500, 'unknown_error', 'Database encountered an unknown error');
3320var BAD_ARG = new PouchError(500, 'badarg', 'Some query argument is invalid');
3321var INVALID_REQUEST = new PouchError(400, 'invalid_request', 'Request was invalid');
3322var QUERY_PARSE_ERROR = new PouchError(400, 'query_parse_error', 'Some query parameter is invalid');
3323var DOC_VALIDATION = new PouchError(500, 'doc_validation', 'Bad special document member');
3324var BAD_REQUEST = new PouchError(400, 'bad_request', 'Something wrong with the request');
3325var NOT_AN_OBJECT = new PouchError(400, 'bad_request', 'Document must be a JSON object');
3326var DB_MISSING = new PouchError(404, 'not_found', 'Database not found');
3327var IDB_ERROR = new PouchError(500, 'indexed_db_went_bad', 'unknown');
3328var WSQ_ERROR = new PouchError(500, 'web_sql_went_bad', 'unknown');
3329var LDB_ERROR = new PouchError(500, 'levelDB_went_went_bad', 'unknown');
3330var FORBIDDEN = new PouchError(403, 'forbidden', 'Forbidden by design doc validate_doc_update function');
3331var INVALID_REV = new PouchError(400, 'bad_request', 'Invalid rev format');
3332var FILE_EXISTS = new PouchError(412, 'file_exists', 'The database could not be created, the file already exists.');
3333var MISSING_STUB = new PouchError(412, 'missing_stub', 'A pre-existing attachment stub wasn\'t found');
3334var INVALID_URL = new PouchError(413, 'invalid_url', 'Provided URL is invalid');
3335
3336function createError(error, reason) {
3337 function CustomPouchError(reason) {
3338 // inherit error properties from our parent error manually
3339 // so as to allow proper JSON parsing.
3340 /* jshint ignore:start */
3341 var names = Object.getOwnPropertyNames(error);
3342 for (var i = 0, len = names.length; i < len; i++) {
3343 if (typeof error[names[i]] !== 'function') {
3344 this[names[i]] = error[names[i]];
3345 }
3346 }
3347
3348 if (this.stack === undefined) {
3349 this.stack = (new Error()).stack;
3350 }
3351
3352 /* jshint ignore:end */
3353 if (reason !== undefined) {
3354 this.reason = reason;
3355 }
3356 }
3357 CustomPouchError.prototype = PouchError.prototype;
3358 return new CustomPouchError(reason);
3359}
3360
3361function generateErrorFromResponse(err) {
3362
3363 if (typeof err !== 'object') {
3364 var data = err;
3365 err = UNKNOWN_ERROR;
3366 err.data = data;
3367 }
3368
3369 if ('error' in err && err.error === 'conflict') {
3370 err.name = 'conflict';
3371 err.status = 409;
3372 }
3373
3374 if (!('name' in err)) {
3375 err.name = err.error || 'unknown';
3376 }
3377
3378 if (!('status' in err)) {
3379 err.status = 500;
3380 }
3381
3382 if (!('message' in err)) {
3383 err.message = err.message || err.reason;
3384 }
3385
3386 if (!('stack' in err)) {
3387 err.stack = (new Error()).stack;
3388 }
3389
3390 return err;
3391}
3392
3393function tryFilter(filter, doc, req) {
3394 try {
3395 return !filter(doc, req);
3396 } catch (err) {
3397 var msg = 'Filter function threw: ' + err.toString();
3398 return createError(BAD_REQUEST, msg);
3399 }
3400}
3401
3402function filterChange(opts) {
3403 var req = {};
3404 var hasFilter = opts.filter && typeof opts.filter === 'function';
3405 req.query = opts.query_params;
3406
3407 return function filter(change) {
3408 if (!change.doc) {
3409 // CSG sends events on the changes feed that don't have documents,
3410 // this hack makes a whole lot of existing code robust.
3411 change.doc = {};
3412 }
3413
3414 var filterReturn = hasFilter && tryFilter(opts.filter, change.doc, req);
3415
3416 if (typeof filterReturn === 'object') {
3417 return filterReturn;
3418 }
3419
3420 if (filterReturn) {
3421 return false;
3422 }
3423
3424 if (!opts.include_docs) {
3425 delete change.doc;
3426 } else if (!opts.attachments) {
3427 for (var att in change.doc._attachments) {
3428 /* istanbul ignore else */
3429 if (Object.prototype.hasOwnProperty.call(change.doc._attachments, att)) {
3430 change.doc._attachments[att].stub = true;
3431 }
3432 }
3433 }
3434 return true;
3435 };
3436}
3437
3438function flatten(arrs) {
3439 var res = [];
3440 for (var i = 0, len = arrs.length; i < len; i++) {
3441 res = res.concat(arrs[i]);
3442 }
3443 return res;
3444}
3445
3446// shim for Function.prototype.name,
3447
3448// Determine id an ID is valid
3449// - invalid IDs begin with an underescore that does not begin '_design' or
3450// '_local'
3451// - any other string value is a valid id
3452// Returns the specific error object for each case
3453function invalidIdError(id) {
3454 var err;
3455 if (!id) {
3456 err = createError(MISSING_ID);
3457 } else if (typeof id !== 'string') {
3458 err = createError(INVALID_ID);
3459 } else if (/^_/.test(id) && !(/^_(design|local)/).test(id)) {
3460 err = createError(RESERVED_ID);
3461 }
3462 if (err) {
3463 throw err;
3464 }
3465}
3466
3467// Checks if a PouchDB object is "remote" or not. This is
3468
3469function isRemote(db) {
3470 if (typeof db._remote === 'boolean') {
3471 return db._remote;
3472 }
3473 /* istanbul ignore next */
3474 if (typeof db.type === 'function') {
3475 guardedConsole('warn',
3476 'db.type() is deprecated and will be removed in ' +
3477 'a future version of PouchDB');
3478 return db.type() === 'http';
3479 }
3480 /* istanbul ignore next */
3481 return false;
3482}
3483
3484function listenerCount(ee, type) {
3485 return 'listenerCount' in ee ? ee.listenerCount(type) :
3486 EE.listenerCount(ee, type);
3487}
3488
3489function parseDesignDocFunctionName(s) {
3490 if (!s) {
3491 return null;
3492 }
3493 var parts = s.split('/');
3494 if (parts.length === 2) {
3495 return parts;
3496 }
3497 if (parts.length === 1) {
3498 return [s, s];
3499 }
3500 return null;
3501}
3502
3503function normalizeDesignDocFunctionName(s) {
3504 var normalized = parseDesignDocFunctionName(s);
3505 return normalized ? normalized.join('/') : null;
3506}
3507
3508// originally parseUri 1.2.2, now patched by us
3509// (c) Steven Levithan <stevenlevithan.com>
3510// MIT License
3511var keys = ["source", "protocol", "authority", "userInfo", "user", "password",
3512 "host", "port", "relative", "path", "directory", "file", "query", "anchor"];
3513var qName ="queryKey";
3514var qParser = /(?:^|&)([^&=]*)=?([^&]*)/g;
3515
3516// use the "loose" parser
3517/* eslint no-useless-escape: 0 */
3518var parser = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
3519
3520function parseUri(str) {
3521 var m = parser.exec(str);
3522 var uri = {};
3523 var i = 14;
3524
3525 while (i--) {
3526 var key = keys[i];
3527 var value = m[i] || "";
3528 var encoded = ['user', 'password'].indexOf(key) !== -1;
3529 uri[key] = encoded ? decodeURIComponent(value) : value;
3530 }
3531
3532 uri[qName] = {};
3533 uri[keys[12]].replace(qParser, function ($0, $1, $2) {
3534 if ($1) {
3535 uri[qName][$1] = $2;
3536 }
3537 });
3538
3539 return uri;
3540}
3541
3542// Based on https://github.com/alexdavid/scope-eval v0.0.3
3543// (source: https://unpkg.com/scope-eval@0.0.3/scope_eval.js)
3544// This is basically just a wrapper around new Function()
3545
3546function scopeEval(source, scope) {
3547 var keys = [];
3548 var values = [];
3549 for (var key in scope) {
3550 if (Object.prototype.hasOwnProperty.call(scope, key)) {
3551 keys.push(key);
3552 values.push(scope[key]);
3553 }
3554 }
3555 keys.push(source);
3556 return Function.apply(null, keys).apply(null, values);
3557}
3558
3559// this is essentially the "update sugar" function from daleharvey/pouchdb#1388
3560// the diffFun tells us what delta to apply to the doc. it either returns
3561// the doc, or false if it doesn't need to do an update after all
3562function upsert(db, docId, diffFun) {
3563 return db.get(docId)[
3564 "catch"](function (err) {
3565 /* istanbul ignore next */
3566 if (err.status !== 404) {
3567 throw err;
3568 }
3569 return {};
3570 })
3571 .then(function (doc) {
3572 // the user might change the _rev, so save it for posterity
3573 var docRev = doc._rev;
3574 var newDoc = diffFun(doc);
3575
3576 if (!newDoc) {
3577 // if the diffFun returns falsy, we short-circuit as
3578 // an optimization
3579 return {updated: false, rev: docRev};
3580 }
3581
3582 // users aren't allowed to modify these values,
3583 // so reset them here
3584 newDoc._id = docId;
3585 newDoc._rev = docRev;
3586 return tryAndPut(db, newDoc, diffFun);
3587 });
3588}
3589
3590function tryAndPut(db, doc, diffFun) {
3591 return db.put(doc).then(function (res) {
3592 return {
3593 updated: true,
3594 rev: res.rev
3595 };
3596 }, function (err) {
3597 /* istanbul ignore next */
3598 if (err.status !== 409) {
3599 throw err;
3600 }
3601 return upsert(db, doc._id, diffFun);
3602 });
3603}
3604
3605var thisAtob = function (str) {
3606 return atob(str);
3607};
3608
3609var thisBtoa = function (str) {
3610 return btoa(str);
3611};
3612
3613// Abstracts constructing a Blob object, so it also works in older
3614// browsers that don't support the native Blob constructor (e.g.
3615// old QtWebKit versions, Android < 4.4).
3616function createBlob(parts, properties) {
3617 /* global BlobBuilder,MSBlobBuilder,MozBlobBuilder,WebKitBlobBuilder */
3618 parts = parts || [];
3619 properties = properties || {};
3620 try {
3621 return new Blob(parts, properties);
3622 } catch (e) {
3623 if (e.name !== "TypeError") {
3624 throw e;
3625 }
3626 var Builder = typeof BlobBuilder !== 'undefined' ? BlobBuilder :
3627 typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder :
3628 typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder :
3629 WebKitBlobBuilder;
3630 var builder = new Builder();
3631 for (var i = 0; i < parts.length; i += 1) {
3632 builder.append(parts[i]);
3633 }
3634 return builder.getBlob(properties.type);
3635 }
3636}
3637
3638// From http://stackoverflow.com/questions/14967647/ (continues on next line)
3639// encode-decode-image-with-base64-breaks-image (2013-04-21)
3640function binaryStringToArrayBuffer(bin) {
3641 var length = bin.length;
3642 var buf = new ArrayBuffer(length);
3643 var arr = new Uint8Array(buf);
3644 for (var i = 0; i < length; i++) {
3645 arr[i] = bin.charCodeAt(i);
3646 }
3647 return buf;
3648}
3649
3650function binStringToBluffer(binString, type) {
3651 return createBlob([binaryStringToArrayBuffer(binString)], {type: type});
3652}
3653
3654function b64ToBluffer(b64, type) {
3655 return binStringToBluffer(thisAtob(b64), type);
3656}
3657
3658//Can't find original post, but this is close
3659//http://stackoverflow.com/questions/6965107/ (continues on next line)
3660//converting-between-strings-and-arraybuffers
3661function arrayBufferToBinaryString(buffer) {
3662 var binary = '';
3663 var bytes = new Uint8Array(buffer);
3664 var length = bytes.byteLength;
3665 for (var i = 0; i < length; i++) {
3666 binary += String.fromCharCode(bytes[i]);
3667 }
3668 return binary;
3669}
3670
3671// shim for browsers that don't support it
3672function readAsBinaryString(blob, callback) {
3673 var reader = new FileReader();
3674 var hasBinaryString = typeof reader.readAsBinaryString === 'function';
3675 reader.onloadend = function (e) {
3676 var result = e.target.result || '';
3677 if (hasBinaryString) {
3678 return callback(result);
3679 }
3680 callback(arrayBufferToBinaryString(result));
3681 };
3682 if (hasBinaryString) {
3683 reader.readAsBinaryString(blob);
3684 } else {
3685 reader.readAsArrayBuffer(blob);
3686 }
3687}
3688
3689function blobToBinaryString(blobOrBuffer, callback) {
3690 readAsBinaryString(blobOrBuffer, function (bin) {
3691 callback(bin);
3692 });
3693}
3694
3695function blobToBase64(blobOrBuffer, callback) {
3696 blobToBinaryString(blobOrBuffer, function (base64) {
3697 callback(thisBtoa(base64));
3698 });
3699}
3700
3701// simplified API. universal browser support is assumed
3702function readAsArrayBuffer(blob, callback) {
3703 var reader = new FileReader();
3704 reader.onloadend = function (e) {
3705 var result = e.target.result || new ArrayBuffer(0);
3706 callback(result);
3707 };
3708 reader.readAsArrayBuffer(blob);
3709}
3710
3711// this is not used in the browser
3712
3713var setImmediateShim = self.setImmediate || self.setTimeout;
3714var MD5_CHUNK_SIZE = 32768;
3715
3716function rawToBase64(raw) {
3717 return thisBtoa(raw);
3718}
3719
3720function sliceBlob(blob, start, end) {
3721 if (blob.webkitSlice) {
3722 return blob.webkitSlice(start, end);
3723 }
3724 return blob.slice(start, end);
3725}
3726
3727function appendBlob(buffer, blob, start, end, callback) {
3728 if (start > 0 || end < blob.size) {
3729 // only slice blob if we really need to
3730 blob = sliceBlob(blob, start, end);
3731 }
3732 readAsArrayBuffer(blob, function (arrayBuffer) {
3733 buffer.append(arrayBuffer);
3734 callback();
3735 });
3736}
3737
3738function appendString(buffer, string, start, end, callback) {
3739 if (start > 0 || end < string.length) {
3740 // only create a substring if we really need to
3741 string = string.substring(start, end);
3742 }
3743 buffer.appendBinary(string);
3744 callback();
3745}
3746
3747function binaryMd5(data, callback) {
3748 var inputIsString = typeof data === 'string';
3749 var len = inputIsString ? data.length : data.size;
3750 var chunkSize = Math.min(MD5_CHUNK_SIZE, len);
3751 var chunks = Math.ceil(len / chunkSize);
3752 var currentChunk = 0;
3753 var buffer = inputIsString ? new Md5() : new Md5.ArrayBuffer();
3754
3755 var append = inputIsString ? appendString : appendBlob;
3756
3757 function next() {
3758 setImmediateShim(loadNextChunk);
3759 }
3760
3761 function done() {
3762 var raw = buffer.end(true);
3763 var base64 = rawToBase64(raw);
3764 callback(base64);
3765 buffer.destroy();
3766 }
3767
3768 function loadNextChunk() {
3769 var start = currentChunk * chunkSize;
3770 var end = start + chunkSize;
3771 currentChunk++;
3772 if (currentChunk < chunks) {
3773 append(buffer, data, start, end, next);
3774 } else {
3775 append(buffer, data, start, end, done);
3776 }
3777 }
3778 loadNextChunk();
3779}
3780
3781function stringMd5(string) {
3782 return Md5.hash(string);
3783}
3784
3785/**
3786 * Creates a new revision string that does NOT include the revision height
3787 * For example '56649f1b0506c6ca9fda0746eb0cacdf'
3788 */
3789function rev$$1(doc, deterministic_revs) {
3790 if (!deterministic_revs) {
3791 return uuid.v4().replace(/-/g, '').toLowerCase();
3792 }
3793
3794 var mutateableDoc = $inject_Object_assign({}, doc);
3795 delete mutateableDoc._rev_tree;
3796 return stringMd5(JSON.stringify(mutateableDoc));
3797}
3798
3799var uuid$1 = uuid.v4; // mimic old import, only v4 is ever used elsewhere
3800
3801// We fetch all leafs of the revision tree, and sort them based on tree length
3802// and whether they were deleted, undeleted documents with the longest revision
3803// tree (most edits) win
3804// The final sort algorithm is slightly documented in a sidebar here:
3805// http://guide.couchdb.org/draft/conflicts.html
3806function winningRev(metadata) {
3807 var winningId;
3808 var winningPos;
3809 var winningDeleted;
3810 var toVisit = metadata.rev_tree.slice();
3811 var node;
3812 while ((node = toVisit.pop())) {
3813 var tree = node.ids;
3814 var branches = tree[2];
3815 var pos = node.pos;
3816 if (branches.length) { // non-leaf
3817 for (var i = 0, len = branches.length; i < len; i++) {
3818 toVisit.push({pos: pos + 1, ids: branches[i]});
3819 }
3820 continue;
3821 }
3822 var deleted = !!tree[1].deleted;
3823 var id = tree[0];
3824 // sort by deleted, then pos, then id
3825 if (!winningId || (winningDeleted !== deleted ? winningDeleted :
3826 winningPos !== pos ? winningPos < pos : winningId < id)) {
3827 winningId = id;
3828 winningPos = pos;
3829 winningDeleted = deleted;
3830 }
3831 }
3832
3833 return winningPos + '-' + winningId;
3834}
3835
3836// Pretty much all below can be combined into a higher order function to
3837// traverse revisions
3838// The return value from the callback will be passed as context to all
3839// children of that node
3840function traverseRevTree(revs, callback) {
3841 var toVisit = revs.slice();
3842
3843 var node;
3844 while ((node = toVisit.pop())) {
3845 var pos = node.pos;
3846 var tree = node.ids;
3847 var branches = tree[2];
3848 var newCtx =
3849 callback(branches.length === 0, pos, tree[0], node.ctx, tree[1]);
3850 for (var i = 0, len = branches.length; i < len; i++) {
3851 toVisit.push({pos: pos + 1, ids: branches[i], ctx: newCtx});
3852 }
3853 }
3854}
3855
3856function sortByPos(a, b) {
3857 return a.pos - b.pos;
3858}
3859
3860function collectLeaves(revs) {
3861 var leaves = [];
3862 traverseRevTree(revs, function (isLeaf, pos, id, acc, opts) {
3863 if (isLeaf) {
3864 leaves.push({rev: pos + "-" + id, pos: pos, opts: opts});
3865 }
3866 });
3867 leaves.sort(sortByPos).reverse();
3868 for (var i = 0, len = leaves.length; i < len; i++) {
3869 delete leaves[i].pos;
3870 }
3871 return leaves;
3872}
3873
3874// returns revs of all conflicts that is leaves such that
3875// 1. are not deleted and
3876// 2. are different than winning revision
3877function collectConflicts(metadata) {
3878 var win = winningRev(metadata);
3879 var leaves = collectLeaves(metadata.rev_tree);
3880 var conflicts = [];
3881 for (var i = 0, len = leaves.length; i < len; i++) {
3882 var leaf = leaves[i];
3883 if (leaf.rev !== win && !leaf.opts.deleted) {
3884 conflicts.push(leaf.rev);
3885 }
3886 }
3887 return conflicts;
3888}
3889
3890// compact a tree by marking its non-leafs as missing,
3891// and return a list of revs to delete
3892function compactTree(metadata) {
3893 var revs = [];
3894 traverseRevTree(metadata.rev_tree, function (isLeaf, pos,
3895 revHash, ctx, opts) {
3896 if (opts.status === 'available' && !isLeaf) {
3897 revs.push(pos + '-' + revHash);
3898 opts.status = 'missing';
3899 }
3900 });
3901 return revs;
3902}
3903
3904// `findPathToLeaf()` returns an array of revs that goes from the specified
3905// leaf rev to the root of that leaf’s branch.
3906//
3907// eg. for this rev tree:
3908// 1-9692 ▶ 2-37aa ▶ 3-df22 ▶ 4-6e94 ▶ 5-df4a ▶ 6-6a3a ▶ 7-57e5
3909// ┃ ┗━━━━━━▶ 5-8d8c ▶ 6-65e0
3910// ┗━━━━━━▶ 3-43f6 ▶ 4-a3b4
3911//
3912// For a `targetRev` of '7-57e5', `findPathToLeaf()` would return ['7-57e5', '6-6a3a', '5-df4a']
3913// The `revs` arument has the same structure as what `revs_tree` has on e.g.
3914// the IndexedDB representation of the rev tree datastructure. Please refer to
3915// tests/unit/test.purge.js for examples of what these look like.
3916//
3917// This function will throw an error if:
3918// - The requested revision does not exist
3919// - The requested revision is not a leaf
3920function findPathToLeaf(revs, targetRev) {
3921 let path = [];
3922 const toVisit = revs.slice();
3923
3924 let node;
3925 while ((node = toVisit.pop())) {
3926 const { pos, ids: tree } = node;
3927 const rev = `${pos}-${tree[0]}`;
3928 const branches = tree[2];
3929
3930 // just assuming we're already working on the path up towards our desired leaf.
3931 path.push(rev);
3932
3933 // we've reached the leaf of our dreams, so return the computed path.
3934 if (rev === targetRev) {
3935 //…unleeeeess
3936 if (branches.length !== 0) {
3937 throw new Error('The requested revision is not a leaf');
3938 }
3939 return path.reverse();
3940 }
3941
3942 // this is based on the assumption that after we have a leaf (`branches.length == 0`), we handle the next
3943 // branch. this is true for all branches other than the path leading to the winning rev (which is 7-57e5 in
3944 // the example above. i've added a reset condition for branching nodes (`branches.length > 1`) as well.
3945 if (branches.length === 0 || branches.length > 1) {
3946 path = [];
3947 }
3948
3949 // as a next step, we push the branches of this node to `toVisit` for visiting it during the next iteration
3950 for (let i = 0, len = branches.length; i < len; i++) {
3951 toVisit.push({ pos: pos + 1, ids: branches[i] });
3952 }
3953 }
3954 if (path.length === 0) {
3955 throw new Error('The requested revision does not exist');
3956 }
3957 return path.reverse();
3958}
3959
3960// build up a list of all the paths to the leafs in this revision tree
3961function rootToLeaf(revs) {
3962 var paths = [];
3963 var toVisit = revs.slice();
3964 var node;
3965 while ((node = toVisit.pop())) {
3966 var pos = node.pos;
3967 var tree = node.ids;
3968 var id = tree[0];
3969 var opts = tree[1];
3970 var branches = tree[2];
3971 var isLeaf = branches.length === 0;
3972
3973 var history = node.history ? node.history.slice() : [];
3974 history.push({id: id, opts: opts});
3975 if (isLeaf) {
3976 paths.push({pos: (pos + 1 - history.length), ids: history});
3977 }
3978 for (var i = 0, len = branches.length; i < len; i++) {
3979 toVisit.push({pos: pos + 1, ids: branches[i], history: history});
3980 }
3981 }
3982 return paths.reverse();
3983}
3984
3985// for a better overview of what this is doing, read:
3986
3987function sortByPos$1(a, b) {
3988 return a.pos - b.pos;
3989}
3990
3991// classic binary search
3992function binarySearch(arr, item, comparator) {
3993 var low = 0;
3994 var high = arr.length;
3995 var mid;
3996 while (low < high) {
3997 mid = (low + high) >>> 1;
3998 if (comparator(arr[mid], item) < 0) {
3999 low = mid + 1;
4000 } else {
4001 high = mid;
4002 }
4003 }
4004 return low;
4005}
4006
4007// assuming the arr is sorted, insert the item in the proper place
4008function insertSorted(arr, item, comparator) {
4009 var idx = binarySearch(arr, item, comparator);
4010 arr.splice(idx, 0, item);
4011}
4012
4013// Turn a path as a flat array into a tree with a single branch.
4014// If any should be stemmed from the beginning of the array, that's passed
4015// in as the second argument
4016function pathToTree(path, numStemmed) {
4017 var root;
4018 var leaf;
4019 for (var i = numStemmed, len = path.length; i < len; i++) {
4020 var node = path[i];
4021 var currentLeaf = [node.id, node.opts, []];
4022 if (leaf) {
4023 leaf[2].push(currentLeaf);
4024 leaf = currentLeaf;
4025 } else {
4026 root = leaf = currentLeaf;
4027 }
4028 }
4029 return root;
4030}
4031
4032// compare the IDs of two trees
4033function compareTree(a, b) {
4034 return a[0] < b[0] ? -1 : 1;
4035}
4036
4037// Merge two trees together
4038// The roots of tree1 and tree2 must be the same revision
4039function mergeTree(in_tree1, in_tree2) {
4040 var queue = [{tree1: in_tree1, tree2: in_tree2}];
4041 var conflicts = false;
4042 while (queue.length > 0) {
4043 var item = queue.pop();
4044 var tree1 = item.tree1;
4045 var tree2 = item.tree2;
4046
4047 if (tree1[1].status || tree2[1].status) {
4048 tree1[1].status =
4049 (tree1[1].status === 'available' ||
4050 tree2[1].status === 'available') ? 'available' : 'missing';
4051 }
4052
4053 for (var i = 0; i < tree2[2].length; i++) {
4054 if (!tree1[2][0]) {
4055 conflicts = 'new_leaf';
4056 tree1[2][0] = tree2[2][i];
4057 continue;
4058 }
4059
4060 var merged = false;
4061 for (var j = 0; j < tree1[2].length; j++) {
4062 if (tree1[2][j][0] === tree2[2][i][0]) {
4063 queue.push({tree1: tree1[2][j], tree2: tree2[2][i]});
4064 merged = true;
4065 }
4066 }
4067 if (!merged) {
4068 conflicts = 'new_branch';
4069 insertSorted(tree1[2], tree2[2][i], compareTree);
4070 }
4071 }
4072 }
4073 return {conflicts: conflicts, tree: in_tree1};
4074}
4075
4076function doMerge(tree, path, dontExpand) {
4077 var restree = [];
4078 var conflicts = false;
4079 var merged = false;
4080 var res;
4081
4082 if (!tree.length) {
4083 return {tree: [path], conflicts: 'new_leaf'};
4084 }
4085
4086 for (var i = 0, len = tree.length; i < len; i++) {
4087 var branch = tree[i];
4088 if (branch.pos === path.pos && branch.ids[0] === path.ids[0]) {
4089 // Paths start at the same position and have the same root, so they need
4090 // merged
4091 res = mergeTree(branch.ids, path.ids);
4092 restree.push({pos: branch.pos, ids: res.tree});
4093 conflicts = conflicts || res.conflicts;
4094 merged = true;
4095 } else if (dontExpand !== true) {
4096 // The paths start at a different position, take the earliest path and
4097 // traverse up until it as at the same point from root as the path we
4098 // want to merge. If the keys match we return the longer path with the
4099 // other merged After stemming we dont want to expand the trees
4100
4101 var t1 = branch.pos < path.pos ? branch : path;
4102 var t2 = branch.pos < path.pos ? path : branch;
4103 var diff = t2.pos - t1.pos;
4104
4105 var candidateParents = [];
4106
4107 var trees = [];
4108 trees.push({ids: t1.ids, diff: diff, parent: null, parentIdx: null});
4109 while (trees.length > 0) {
4110 var item = trees.pop();
4111 if (item.diff === 0) {
4112 if (item.ids[0] === t2.ids[0]) {
4113 candidateParents.push(item);
4114 }
4115 continue;
4116 }
4117 var elements = item.ids[2];
4118 for (var j = 0, elementsLen = elements.length; j < elementsLen; j++) {
4119 trees.push({
4120 ids: elements[j],
4121 diff: item.diff - 1,
4122 parent: item.ids,
4123 parentIdx: j
4124 });
4125 }
4126 }
4127
4128 var el = candidateParents[0];
4129
4130 if (!el) {
4131 restree.push(branch);
4132 } else {
4133 res = mergeTree(el.ids, t2.ids);
4134 el.parent[2][el.parentIdx] = res.tree;
4135 restree.push({pos: t1.pos, ids: t1.ids});
4136 conflicts = conflicts || res.conflicts;
4137 merged = true;
4138 }
4139 } else {
4140 restree.push(branch);
4141 }
4142 }
4143
4144 // We didnt find
4145 if (!merged) {
4146 restree.push(path);
4147 }
4148
4149 restree.sort(sortByPos$1);
4150
4151 return {
4152 tree: restree,
4153 conflicts: conflicts || 'internal_node'
4154 };
4155}
4156
4157// To ensure we dont grow the revision tree infinitely, we stem old revisions
4158function stem(tree, depth) {
4159 // First we break out the tree into a complete list of root to leaf paths
4160 var paths = rootToLeaf(tree);
4161 var stemmedRevs;
4162
4163 var result;
4164 for (var i = 0, len = paths.length; i < len; i++) {
4165 // Then for each path, we cut off the start of the path based on the
4166 // `depth` to stem to, and generate a new set of flat trees
4167 var path = paths[i];
4168 var stemmed = path.ids;
4169 var node;
4170 if (stemmed.length > depth) {
4171 // only do the stemming work if we actually need to stem
4172 if (!stemmedRevs) {
4173 stemmedRevs = {}; // avoid allocating this object unnecessarily
4174 }
4175 var numStemmed = stemmed.length - depth;
4176 node = {
4177 pos: path.pos + numStemmed,
4178 ids: pathToTree(stemmed, numStemmed)
4179 };
4180
4181 for (var s = 0; s < numStemmed; s++) {
4182 var rev = (path.pos + s) + '-' + stemmed[s].id;
4183 stemmedRevs[rev] = true;
4184 }
4185 } else { // no need to actually stem
4186 node = {
4187 pos: path.pos,
4188 ids: pathToTree(stemmed, 0)
4189 };
4190 }
4191
4192 // Then we remerge all those flat trees together, ensuring that we dont
4193 // connect trees that would go beyond the depth limit
4194 if (result) {
4195 result = doMerge(result, node, true).tree;
4196 } else {
4197 result = [node];
4198 }
4199 }
4200
4201 // this is memory-heavy per Chrome profiler, avoid unless we actually stemmed
4202 if (stemmedRevs) {
4203 traverseRevTree(result, function (isLeaf, pos, revHash) {
4204 // some revisions may have been removed in a branch but not in another
4205 delete stemmedRevs[pos + '-' + revHash];
4206 });
4207 }
4208
4209 return {
4210 tree: result,
4211 revs: stemmedRevs ? Object.keys(stemmedRevs) : []
4212 };
4213}
4214
4215function merge(tree, path, depth) {
4216 var newTree = doMerge(tree, path);
4217 var stemmed = stem(newTree.tree, depth);
4218 return {
4219 tree: stemmed.tree,
4220 stemmedRevs: stemmed.revs,
4221 conflicts: newTree.conflicts
4222 };
4223}
4224
4225// return true if a rev exists in the rev tree, false otherwise
4226function revExists(revs, rev) {
4227 var toVisit = revs.slice();
4228 var splitRev = rev.split('-');
4229 var targetPos = parseInt(splitRev[0], 10);
4230 var targetId = splitRev[1];
4231
4232 var node;
4233 while ((node = toVisit.pop())) {
4234 if (node.pos === targetPos && node.ids[0] === targetId) {
4235 return true;
4236 }
4237 var branches = node.ids[2];
4238 for (var i = 0, len = branches.length; i < len; i++) {
4239 toVisit.push({pos: node.pos + 1, ids: branches[i]});
4240 }
4241 }
4242 return false;
4243}
4244
4245function getTrees(node) {
4246 return node.ids;
4247}
4248
4249// check if a specific revision of a doc has been deleted
4250// - metadata: the metadata object from the doc store
4251// - rev: (optional) the revision to check. defaults to winning revision
4252function isDeleted(metadata, rev) {
4253 if (!rev) {
4254 rev = winningRev(metadata);
4255 }
4256 var id = rev.substring(rev.indexOf('-') + 1);
4257 var toVisit = metadata.rev_tree.map(getTrees);
4258
4259 var tree;
4260 while ((tree = toVisit.pop())) {
4261 if (tree[0] === id) {
4262 return !!tree[1].deleted;
4263 }
4264 toVisit = toVisit.concat(tree[2]);
4265 }
4266}
4267
4268function isLocalId(id) {
4269 return (/^_local/).test(id);
4270}
4271
4272// returns the current leaf node for a given revision
4273function latest(rev, metadata) {
4274 var toVisit = metadata.rev_tree.slice();
4275 var node;
4276 while ((node = toVisit.pop())) {
4277 var pos = node.pos;
4278 var tree = node.ids;
4279 var id = tree[0];
4280 var opts = tree[1];
4281 var branches = tree[2];
4282 var isLeaf = branches.length === 0;
4283
4284 var history = node.history ? node.history.slice() : [];
4285 history.push({id: id, pos: pos, opts: opts});
4286
4287 if (isLeaf) {
4288 for (var i = 0, len = history.length; i < len; i++) {
4289 var historyNode = history[i];
4290 var historyRev = historyNode.pos + '-' + historyNode.id;
4291
4292 if (historyRev === rev) {
4293 // return the rev of this leaf
4294 return pos + '-' + id;
4295 }
4296 }
4297 }
4298
4299 for (var j = 0, l = branches.length; j < l; j++) {
4300 toVisit.push({pos: pos + 1, ids: branches[j], history: history});
4301 }
4302 }
4303
4304 /* istanbul ignore next */
4305 throw new Error('Unable to resolve latest revision for id ' + metadata.id + ', rev ' + rev);
4306}
4307
4308function tryCatchInChangeListener(self, change, pending, lastSeq) {
4309 // isolate try/catches to avoid V8 deoptimizations
4310 try {
4311 self.emit('change', change, pending, lastSeq);
4312 } catch (e) {
4313 guardedConsole('error', 'Error in .on("change", function):', e);
4314 }
4315}
4316
4317function processChange(doc, metadata, opts) {
4318 var changeList = [{rev: doc._rev}];
4319 if (opts.style === 'all_docs') {
4320 changeList = collectLeaves(metadata.rev_tree)
4321 .map(function (x) { return {rev: x.rev}; });
4322 }
4323 var change = {
4324 id: metadata.id,
4325 changes: changeList,
4326 doc: doc
4327 };
4328
4329 if (isDeleted(metadata, doc._rev)) {
4330 change.deleted = true;
4331 }
4332 if (opts.conflicts) {
4333 change.doc._conflicts = collectConflicts(metadata);
4334 if (!change.doc._conflicts.length) {
4335 delete change.doc._conflicts;
4336 }
4337 }
4338 return change;
4339}
4340
4341class Changes$1 extends EE {
4342 constructor(db, opts, callback) {
4343 super();
4344 this.db = db;
4345 opts = opts ? clone(opts) : {};
4346 var complete = opts.complete = once((err, resp) => {
4347 if (err) {
4348 if (listenerCount(this, 'error') > 0) {
4349 this.emit('error', err);
4350 }
4351 } else {
4352 this.emit('complete', resp);
4353 }
4354 this.removeAllListeners();
4355 db.removeListener('destroyed', onDestroy);
4356 });
4357 if (callback) {
4358 this.on('complete', function (resp) {
4359 callback(null, resp);
4360 });
4361 this.on('error', callback);
4362 }
4363 const onDestroy = () => {
4364 this.cancel();
4365 };
4366 db.once('destroyed', onDestroy);
4367
4368 opts.onChange = (change, pending, lastSeq) => {
4369 /* istanbul ignore if */
4370 if (this.isCancelled) {
4371 return;
4372 }
4373 tryCatchInChangeListener(this, change, pending, lastSeq);
4374 };
4375
4376 var promise = new Promise(function (fulfill, reject) {
4377 opts.complete = function (err, res) {
4378 if (err) {
4379 reject(err);
4380 } else {
4381 fulfill(res);
4382 }
4383 };
4384 });
4385 this.once('cancel', function () {
4386 db.removeListener('destroyed', onDestroy);
4387 opts.complete(null, {status: 'cancelled'});
4388 });
4389 this.then = promise.then.bind(promise);
4390 this['catch'] = promise['catch'].bind(promise);
4391 this.then(function (result) {
4392 complete(null, result);
4393 }, complete);
4394
4395
4396
4397 if (!db.taskqueue.isReady) {
4398 db.taskqueue.addTask((failed) => {
4399 if (failed) {
4400 opts.complete(failed);
4401 } else if (this.isCancelled) {
4402 this.emit('cancel');
4403 } else {
4404 this.validateChanges(opts);
4405 }
4406 });
4407 } else {
4408 this.validateChanges(opts);
4409 }
4410 }
4411
4412 cancel() {
4413 this.isCancelled = true;
4414 if (this.db.taskqueue.isReady) {
4415 this.emit('cancel');
4416 }
4417 }
4418
4419 validateChanges(opts) {
4420 var callback = opts.complete;
4421
4422 /* istanbul ignore else */
4423 if (PouchDB._changesFilterPlugin) {
4424 PouchDB._changesFilterPlugin.validate(opts, (err) => {
4425 if (err) {
4426 return callback(err);
4427 }
4428 this.doChanges(opts);
4429 });
4430 } else {
4431 this.doChanges(opts);
4432 }
4433 }
4434
4435 doChanges(opts) {
4436 var callback = opts.complete;
4437
4438 opts = clone(opts);
4439 if ('live' in opts && !('continuous' in opts)) {
4440 opts.continuous = opts.live;
4441 }
4442 opts.processChange = processChange;
4443
4444 if (opts.since === 'latest') {
4445 opts.since = 'now';
4446 }
4447 if (!opts.since) {
4448 opts.since = 0;
4449 }
4450 if (opts.since === 'now') {
4451 this.db.info().then((info) => {
4452 /* istanbul ignore if */
4453 if (this.isCancelled) {
4454 callback(null, {status: 'cancelled'});
4455 return;
4456 }
4457 opts.since = info.update_seq;
4458 this.doChanges(opts);
4459 }, callback);
4460 return;
4461 }
4462
4463 /* istanbul ignore else */
4464 if (PouchDB._changesFilterPlugin) {
4465 PouchDB._changesFilterPlugin.normalize(opts);
4466 if (PouchDB._changesFilterPlugin.shouldFilter(this, opts)) {
4467 return PouchDB._changesFilterPlugin.filter(this, opts);
4468 }
4469 } else {
4470 ['doc_ids', 'filter', 'selector', 'view'].forEach(function (key) {
4471 if (key in opts) {
4472 guardedConsole('warn',
4473 'The "' + key + '" option was passed in to changes/replicate, ' +
4474 'but pouchdb-changes-filter plugin is not installed, so it ' +
4475 'was ignored. Please install the plugin to enable filtering.'
4476 );
4477 }
4478 });
4479 }
4480
4481 if (!('descending' in opts)) {
4482 opts.descending = false;
4483 }
4484
4485 // 0 and 1 should return 1 document
4486 opts.limit = opts.limit === 0 ? 1 : opts.limit;
4487 opts.complete = callback;
4488 var newPromise = this.db._changes(opts);
4489 /* istanbul ignore else */
4490 if (newPromise && typeof newPromise.cancel === 'function') {
4491 const cancel = this.cancel;
4492 this.cancel = (...args) => {
4493 newPromise.cancel();
4494 cancel.apply(this, args);
4495 };
4496 }
4497 }
4498}
4499
4500/*
4501 * A generic pouch adapter
4502 */
4503
4504function compare(left, right) {
4505 return left < right ? -1 : left > right ? 1 : 0;
4506}
4507
4508// Wrapper for functions that call the bulkdocs api with a single doc,
4509// if the first result is an error, return an error
4510function yankError(callback, docId) {
4511 return function (err, results) {
4512 if (err || (results[0] && results[0].error)) {
4513 err = err || results[0];
4514 err.docId = docId;
4515 callback(err);
4516 } else {
4517 callback(null, results.length ? results[0] : results);
4518 }
4519 };
4520}
4521
4522// clean docs given to us by the user
4523function cleanDocs(docs) {
4524 for (var i = 0; i < docs.length; i++) {
4525 var doc = docs[i];
4526 if (doc._deleted) {
4527 delete doc._attachments; // ignore atts for deleted docs
4528 } else if (doc._attachments) {
4529 // filter out extraneous keys from _attachments
4530 var atts = Object.keys(doc._attachments);
4531 for (var j = 0; j < atts.length; j++) {
4532 var att = atts[j];
4533 doc._attachments[att] = pick(doc._attachments[att],
4534 ['data', 'digest', 'content_type', 'length', 'revpos', 'stub']);
4535 }
4536 }
4537 }
4538}
4539
4540// compare two docs, first by _id then by _rev
4541function compareByIdThenRev(a, b) {
4542 var idCompare = compare(a._id, b._id);
4543 if (idCompare !== 0) {
4544 return idCompare;
4545 }
4546 var aStart = a._revisions ? a._revisions.start : 0;
4547 var bStart = b._revisions ? b._revisions.start : 0;
4548 return compare(aStart, bStart);
4549}
4550
4551// for every node in a revision tree computes its distance from the closest
4552// leaf
4553function computeHeight(revs) {
4554 var height = {};
4555 var edges = [];
4556 traverseRevTree(revs, function (isLeaf, pos, id, prnt) {
4557 var rev = pos + "-" + id;
4558 if (isLeaf) {
4559 height[rev] = 0;
4560 }
4561 if (prnt !== undefined) {
4562 edges.push({from: prnt, to: rev});
4563 }
4564 return rev;
4565 });
4566
4567 edges.reverse();
4568 edges.forEach(function (edge) {
4569 if (height[edge.from] === undefined) {
4570 height[edge.from] = 1 + height[edge.to];
4571 } else {
4572 height[edge.from] = Math.min(height[edge.from], 1 + height[edge.to]);
4573 }
4574 });
4575 return height;
4576}
4577
4578function allDocsKeysParse(opts) {
4579 var keys = ('limit' in opts) ?
4580 opts.keys.slice(opts.skip, opts.limit + opts.skip) :
4581 (opts.skip > 0) ? opts.keys.slice(opts.skip) : opts.keys;
4582 opts.keys = keys;
4583 opts.skip = 0;
4584 delete opts.limit;
4585 if (opts.descending) {
4586 keys.reverse();
4587 opts.descending = false;
4588 }
4589}
4590
4591// all compaction is done in a queue, to avoid attaching
4592// too many listeners at once
4593function doNextCompaction(self) {
4594 var task = self._compactionQueue[0];
4595 var opts = task.opts;
4596 var callback = task.callback;
4597 self.get('_local/compaction')["catch"](function () {
4598 return false;
4599 }).then(function (doc) {
4600 if (doc && doc.last_seq) {
4601 opts.last_seq = doc.last_seq;
4602 }
4603 self._compact(opts, function (err, res) {
4604 /* istanbul ignore if */
4605 if (err) {
4606 callback(err);
4607 } else {
4608 callback(null, res);
4609 }
4610 immediate(function () {
4611 self._compactionQueue.shift();
4612 if (self._compactionQueue.length) {
4613 doNextCompaction(self);
4614 }
4615 });
4616 });
4617 });
4618}
4619
4620function appendPurgeSeq(db, docId, rev) {
4621 return db.get('_local/purges').then(function (doc) {
4622 const purgeSeq = doc.purgeSeq + 1;
4623 doc.purges.push({
4624 docId,
4625 rev,
4626 purgeSeq
4627 });
4628 if (doc.purges.length > self.purged_infos_limit) {
4629 doc.purges.splice(0, doc.purges.length - self.purged_infos_limit);
4630 }
4631 doc.purgeSeq = purgeSeq;
4632 return doc;
4633 })["catch"](function (err) {
4634 if (err.status !== 404) {
4635 throw err;
4636 }
4637 return {
4638 _id: '_local/purges',
4639 purges: [{
4640 docId,
4641 rev,
4642 purgeSeq: 0
4643 }],
4644 purgeSeq: 0
4645 };
4646 }).then(function (doc) {
4647 return db.put(doc);
4648 });
4649}
4650
4651function attachmentNameError(name) {
4652 if (name.charAt(0) === '_') {
4653 return name + ' is not a valid attachment name, attachment ' +
4654 'names cannot start with \'_\'';
4655 }
4656 return false;
4657}
4658
4659class AbstractPouchDB extends EE {
4660 _setup() {
4661 this.post = adapterFun('post', function (doc, opts, callback) {
4662 if (typeof opts === 'function') {
4663 callback = opts;
4664 opts = {};
4665 }
4666 if (typeof doc !== 'object' || Array.isArray(doc)) {
4667 return callback(createError(NOT_AN_OBJECT));
4668 }
4669 this.bulkDocs({docs: [doc]}, opts, yankError(callback, doc._id));
4670 }).bind(this);
4671
4672 this.put = adapterFun('put', function (doc, opts, cb) {
4673 if (typeof opts === 'function') {
4674 cb = opts;
4675 opts = {};
4676 }
4677 if (typeof doc !== 'object' || Array.isArray(doc)) {
4678 return cb(createError(NOT_AN_OBJECT));
4679 }
4680 invalidIdError(doc._id);
4681 if (isLocalId(doc._id) && typeof this._putLocal === 'function') {
4682 if (doc._deleted) {
4683 return this._removeLocal(doc, cb);
4684 } else {
4685 return this._putLocal(doc, cb);
4686 }
4687 }
4688
4689 const putDoc = (next) => {
4690 if (typeof this._put === 'function' && opts.new_edits !== false) {
4691 this._put(doc, opts, next);
4692 } else {
4693 this.bulkDocs({docs: [doc]}, opts, yankError(next, doc._id));
4694 }
4695 };
4696
4697 if (opts.force && doc._rev) {
4698 transformForceOptionToNewEditsOption();
4699 putDoc(function (err) {
4700 var result = err ? null : {ok: true, id: doc._id, rev: doc._rev};
4701 cb(err, result);
4702 });
4703 } else {
4704 putDoc(cb);
4705 }
4706
4707 function transformForceOptionToNewEditsOption() {
4708 var parts = doc._rev.split('-');
4709 var oldRevId = parts[1];
4710 var oldRevNum = parseInt(parts[0], 10);
4711
4712 var newRevNum = oldRevNum + 1;
4713 var newRevId = rev$$1();
4714
4715 doc._revisions = {
4716 start: newRevNum,
4717 ids: [newRevId, oldRevId]
4718 };
4719 doc._rev = newRevNum + '-' + newRevId;
4720 opts.new_edits = false;
4721 }
4722 }).bind(this);
4723
4724 this.putAttachment = adapterFun('putAttachment', function (docId, attachmentId, rev, blob, type) {
4725 var api = this;
4726 if (typeof type === 'function') {
4727 type = blob;
4728 blob = rev;
4729 rev = null;
4730 }
4731 // Lets fix in https://github.com/pouchdb/pouchdb/issues/3267
4732 /* istanbul ignore if */
4733 if (typeof type === 'undefined') {
4734 type = blob;
4735 blob = rev;
4736 rev = null;
4737 }
4738 if (!type) {
4739 guardedConsole('warn', 'Attachment', attachmentId, 'on document', docId, 'is missing content_type');
4740 }
4741
4742 function createAttachment(doc) {
4743 var prevrevpos = '_rev' in doc ? parseInt(doc._rev, 10) : 0;
4744 doc._attachments = doc._attachments || {};
4745 doc._attachments[attachmentId] = {
4746 content_type: type,
4747 data: blob,
4748 revpos: ++prevrevpos
4749 };
4750 return api.put(doc);
4751 }
4752
4753 return api.get(docId).then(function (doc) {
4754 if (doc._rev !== rev) {
4755 throw createError(REV_CONFLICT);
4756 }
4757
4758 return createAttachment(doc);
4759 }, function (err) {
4760 // create new doc
4761 /* istanbul ignore else */
4762 if (err.reason === MISSING_DOC.message) {
4763 return createAttachment({_id: docId});
4764 } else {
4765 throw err;
4766 }
4767 });
4768 }).bind(this);
4769
4770 this.removeAttachment = adapterFun('removeAttachment', function (docId, attachmentId, rev, callback) {
4771 this.get(docId, (err, obj) => {
4772 /* istanbul ignore if */
4773 if (err) {
4774 callback(err);
4775 return;
4776 }
4777 if (obj._rev !== rev) {
4778 callback(createError(REV_CONFLICT));
4779 return;
4780 }
4781 /* istanbul ignore if */
4782 if (!obj._attachments) {
4783 return callback();
4784 }
4785 delete obj._attachments[attachmentId];
4786 if (Object.keys(obj._attachments).length === 0) {
4787 delete obj._attachments;
4788 }
4789 this.put(obj, callback);
4790 });
4791 }).bind(this);
4792
4793 this.remove = adapterFun('remove', function (docOrId, optsOrRev, opts, callback) {
4794 var doc;
4795 if (typeof optsOrRev === 'string') {
4796 // id, rev, opts, callback style
4797 doc = {
4798 _id: docOrId,
4799 _rev: optsOrRev
4800 };
4801 if (typeof opts === 'function') {
4802 callback = opts;
4803 opts = {};
4804 }
4805 } else {
4806 // doc, opts, callback style
4807 doc = docOrId;
4808 if (typeof optsOrRev === 'function') {
4809 callback = optsOrRev;
4810 opts = {};
4811 } else {
4812 callback = opts;
4813 opts = optsOrRev;
4814 }
4815 }
4816 opts = opts || {};
4817 opts.was_delete = true;
4818 var newDoc = {_id: doc._id, _rev: (doc._rev || opts.rev)};
4819 newDoc._deleted = true;
4820 if (isLocalId(newDoc._id) && typeof this._removeLocal === 'function') {
4821 return this._removeLocal(doc, callback);
4822 }
4823 this.bulkDocs({docs: [newDoc]}, opts, yankError(callback, newDoc._id));
4824 }).bind(this);
4825
4826 this.revsDiff = adapterFun('revsDiff', function (req, opts, callback) {
4827 if (typeof opts === 'function') {
4828 callback = opts;
4829 opts = {};
4830 }
4831 var ids = Object.keys(req);
4832
4833 if (!ids.length) {
4834 return callback(null, {});
4835 }
4836
4837 var count = 0;
4838 var missing = new ExportedMap();
4839
4840 function addToMissing(id, revId) {
4841 if (!missing.has(id)) {
4842 missing.set(id, {missing: []});
4843 }
4844 missing.get(id).missing.push(revId);
4845 }
4846
4847 function processDoc(id, rev_tree) {
4848 // Is this fast enough? Maybe we should switch to a set simulated by a map
4849 var missingForId = req[id].slice(0);
4850 traverseRevTree(rev_tree, function (isLeaf, pos, revHash, ctx,
4851 opts) {
4852 var rev = pos + '-' + revHash;
4853 var idx = missingForId.indexOf(rev);
4854 if (idx === -1) {
4855 return;
4856 }
4857
4858 missingForId.splice(idx, 1);
4859 /* istanbul ignore if */
4860 if (opts.status !== 'available') {
4861 addToMissing(id, rev);
4862 }
4863 });
4864
4865 // Traversing the tree is synchronous, so now `missingForId` contains
4866 // revisions that were not found in the tree
4867 missingForId.forEach(function (rev) {
4868 addToMissing(id, rev);
4869 });
4870 }
4871
4872 ids.map(function (id) {
4873 this._getRevisionTree(id, function (err, rev_tree) {
4874 if (err && err.status === 404 && err.message === 'missing') {
4875 missing.set(id, {missing: req[id]});
4876 } else if (err) {
4877 /* istanbul ignore next */
4878 return callback(err);
4879 } else {
4880 processDoc(id, rev_tree);
4881 }
4882
4883 if (++count === ids.length) {
4884 // convert LazyMap to object
4885 var missingObj = {};
4886 missing.forEach(function (value, key) {
4887 missingObj[key] = value;
4888 });
4889 return callback(null, missingObj);
4890 }
4891 });
4892 }, this);
4893 }).bind(this);
4894
4895 // _bulk_get API for faster replication, as described in
4896 // https://github.com/apache/couchdb-chttpd/pull/33
4897 // At the "abstract" level, it will just run multiple get()s in
4898 // parallel, because this isn't much of a performance cost
4899 // for local databases (except the cost of multiple transactions, which is
4900 // small). The http adapter overrides this in order
4901 // to do a more efficient single HTTP request.
4902 this.bulkGet = adapterFun('bulkGet', function (opts, callback) {
4903 bulkGet(this, opts, callback);
4904 }).bind(this);
4905
4906 // compact one document and fire callback
4907 // by compacting we mean removing all revisions which
4908 // are further from the leaf in revision tree than max_height
4909 this.compactDocument = adapterFun('compactDocument', function (docId, maxHeight, callback) {
4910 this._getRevisionTree(docId, (err, revTree) => {
4911 /* istanbul ignore if */
4912 if (err) {
4913 return callback(err);
4914 }
4915 var height = computeHeight(revTree);
4916 var candidates = [];
4917 var revs = [];
4918 Object.keys(height).forEach(function (rev) {
4919 if (height[rev] > maxHeight) {
4920 candidates.push(rev);
4921 }
4922 });
4923
4924 traverseRevTree(revTree, function (isLeaf, pos, revHash, ctx, opts) {
4925 var rev = pos + '-' + revHash;
4926 if (opts.status === 'available' && candidates.indexOf(rev) !== -1) {
4927 revs.push(rev);
4928 }
4929 });
4930 this._doCompaction(docId, revs, callback);
4931 });
4932 }).bind(this);
4933
4934 // compact the whole database using single document
4935 // compaction
4936 this.compact = adapterFun('compact', function (opts, callback) {
4937 if (typeof opts === 'function') {
4938 callback = opts;
4939 opts = {};
4940 }
4941
4942 opts = opts || {};
4943
4944 this._compactionQueue = this._compactionQueue || [];
4945 this._compactionQueue.push({opts: opts, callback: callback});
4946 if (this._compactionQueue.length === 1) {
4947 doNextCompaction(this);
4948 }
4949 }).bind(this);
4950
4951 /* Begin api wrappers. Specific functionality to storage belongs in the _[method] */
4952 this.get = adapterFun('get', function (id, opts, cb) {
4953 if (typeof opts === 'function') {
4954 cb = opts;
4955 opts = {};
4956 }
4957 if (typeof id !== 'string') {
4958 return cb(createError(INVALID_ID));
4959 }
4960 if (isLocalId(id) && typeof this._getLocal === 'function') {
4961 return this._getLocal(id, cb);
4962 }
4963 var leaves = [];
4964
4965 const finishOpenRevs = () => {
4966 var result = [];
4967 var count = leaves.length;
4968 /* istanbul ignore if */
4969 if (!count) {
4970 return cb(null, result);
4971 }
4972
4973 // order with open_revs is unspecified
4974 leaves.forEach((leaf) => {
4975 this.get(id, {
4976 rev: leaf,
4977 revs: opts.revs,
4978 latest: opts.latest,
4979 attachments: opts.attachments,
4980 binary: opts.binary
4981 }, function (err, doc) {
4982 if (!err) {
4983 // using latest=true can produce duplicates
4984 var existing;
4985 for (var i = 0, l = result.length; i < l; i++) {
4986 if (result[i].ok && result[i].ok._rev === doc._rev) {
4987 existing = true;
4988 break;
4989 }
4990 }
4991 if (!existing) {
4992 result.push({ok: doc});
4993 }
4994 } else {
4995 result.push({missing: leaf});
4996 }
4997 count--;
4998 if (!count) {
4999 cb(null, result);
5000 }
5001 });
5002 });
5003 };
5004
5005 if (opts.open_revs) {
5006 if (opts.open_revs === "all") {
5007 this._getRevisionTree(id, function (err, rev_tree) {
5008 /* istanbul ignore if */
5009 if (err) {
5010 return cb(err);
5011 }
5012 leaves = collectLeaves(rev_tree).map(function (leaf) {
5013 return leaf.rev;
5014 });
5015 finishOpenRevs();
5016 });
5017 } else {
5018 if (Array.isArray(opts.open_revs)) {
5019 leaves = opts.open_revs;
5020 for (var i = 0; i < leaves.length; i++) {
5021 var l = leaves[i];
5022 // looks like it's the only thing couchdb checks
5023 if (!(typeof (l) === "string" && /^\d+-/.test(l))) {
5024 return cb(createError(INVALID_REV));
5025 }
5026 }
5027 finishOpenRevs();
5028 } else {
5029 return cb(createError(UNKNOWN_ERROR, 'function_clause'));
5030 }
5031 }
5032 return; // open_revs does not like other options
5033 }
5034
5035 return this._get(id, opts, (err, result) => {
5036 if (err) {
5037 err.docId = id;
5038 return cb(err);
5039 }
5040
5041 var doc = result.doc;
5042 var metadata = result.metadata;
5043 var ctx = result.ctx;
5044
5045 if (opts.conflicts) {
5046 var conflicts = collectConflicts(metadata);
5047 if (conflicts.length) {
5048 doc._conflicts = conflicts;
5049 }
5050 }
5051
5052 if (isDeleted(metadata, doc._rev)) {
5053 doc._deleted = true;
5054 }
5055
5056 if (opts.revs || opts.revs_info) {
5057 var splittedRev = doc._rev.split('-');
5058 var revNo = parseInt(splittedRev[0], 10);
5059 var revHash = splittedRev[1];
5060
5061 var paths = rootToLeaf(metadata.rev_tree);
5062 var path = null;
5063
5064 for (var i = 0; i < paths.length; i++) {
5065 var currentPath = paths[i];
5066 var hashIndex = currentPath.ids.map(function (x) { return x.id; })
5067 .indexOf(revHash);
5068 var hashFoundAtRevPos = hashIndex === (revNo - 1);
5069
5070 if (hashFoundAtRevPos || (!path && hashIndex !== -1)) {
5071 path = currentPath;
5072 }
5073 }
5074
5075 /* istanbul ignore if */
5076 if (!path) {
5077 err = new Error('invalid rev tree');
5078 err.docId = id;
5079 return cb(err);
5080 }
5081
5082 var indexOfRev = path.ids.map(function (x) { return x.id; })
5083 .indexOf(doc._rev.split('-')[1]) + 1;
5084 var howMany = path.ids.length - indexOfRev;
5085 path.ids.splice(indexOfRev, howMany);
5086 path.ids.reverse();
5087
5088 if (opts.revs) {
5089 doc._revisions = {
5090 start: (path.pos + path.ids.length) - 1,
5091 ids: path.ids.map(function (rev) {
5092 return rev.id;
5093 })
5094 };
5095 }
5096 if (opts.revs_info) {
5097 var pos = path.pos + path.ids.length;
5098 doc._revs_info = path.ids.map(function (rev) {
5099 pos--;
5100 return {
5101 rev: pos + '-' + rev.id,
5102 status: rev.opts.status
5103 };
5104 });
5105 }
5106 }
5107
5108 if (opts.attachments && doc._attachments) {
5109 var attachments = doc._attachments;
5110 var count = Object.keys(attachments).length;
5111 if (count === 0) {
5112 return cb(null, doc);
5113 }
5114 Object.keys(attachments).forEach((key) => {
5115 this._getAttachment(doc._id, key, attachments[key], {
5116 // Previously the revision handling was done in adapter.js
5117 // getAttachment, however since idb-next doesnt we need to
5118 // pass the rev through
5119 rev: doc._rev,
5120 binary: opts.binary,
5121 ctx: ctx
5122 }, function (err, data) {
5123 var att = doc._attachments[key];
5124 att.data = data;
5125 delete att.stub;
5126 delete att.length;
5127 if (!--count) {
5128 cb(null, doc);
5129 }
5130 });
5131 });
5132 } else {
5133 if (doc._attachments) {
5134 for (var key in doc._attachments) {
5135 /* istanbul ignore else */
5136 if (Object.prototype.hasOwnProperty.call(doc._attachments, key)) {
5137 doc._attachments[key].stub = true;
5138 }
5139 }
5140 }
5141 cb(null, doc);
5142 }
5143 });
5144 }).bind(this);
5145
5146 // TODO: I dont like this, it forces an extra read for every
5147 // attachment read and enforces a confusing api between
5148 // adapter.js and the adapter implementation
5149 this.getAttachment = adapterFun('getAttachment', function (docId, attachmentId, opts, callback) {
5150 if (opts instanceof Function) {
5151 callback = opts;
5152 opts = {};
5153 }
5154 this._get(docId, opts, (err, res) => {
5155 if (err) {
5156 return callback(err);
5157 }
5158 if (res.doc._attachments && res.doc._attachments[attachmentId]) {
5159 opts.ctx = res.ctx;
5160 opts.binary = true;
5161 this._getAttachment(docId, attachmentId,
5162 res.doc._attachments[attachmentId], opts, callback);
5163 } else {
5164 return callback(createError(MISSING_DOC));
5165 }
5166 });
5167 }).bind(this);
5168
5169 this.allDocs = adapterFun('allDocs', function (opts, callback) {
5170 if (typeof opts === 'function') {
5171 callback = opts;
5172 opts = {};
5173 }
5174 opts.skip = typeof opts.skip !== 'undefined' ? opts.skip : 0;
5175 if (opts.start_key) {
5176 opts.startkey = opts.start_key;
5177 }
5178 if (opts.end_key) {
5179 opts.endkey = opts.end_key;
5180 }
5181 if ('keys' in opts) {
5182 if (!Array.isArray(opts.keys)) {
5183 return callback(new TypeError('options.keys must be an array'));
5184 }
5185 var incompatibleOpt =
5186 ['startkey', 'endkey', 'key'].filter(function (incompatibleOpt) {
5187 return incompatibleOpt in opts;
5188 })[0];
5189 if (incompatibleOpt) {
5190 callback(createError(QUERY_PARSE_ERROR,
5191 'Query parameter `' + incompatibleOpt +
5192 '` is not compatible with multi-get'
5193 ));
5194 return;
5195 }
5196 if (!isRemote(this)) {
5197 allDocsKeysParse(opts);
5198 if (opts.keys.length === 0) {
5199 return this._allDocs({limit: 0}, callback);
5200 }
5201 }
5202 }
5203
5204 return this._allDocs(opts, callback);
5205 }).bind(this);
5206
5207 this.close = adapterFun('close', function (callback) {
5208 this._closed = true;
5209 this.emit('closed');
5210 return this._close(callback);
5211 }).bind(this);
5212
5213 this.info = adapterFun('info', function (callback) {
5214 this._info((err, info) => {
5215 if (err) {
5216 return callback(err);
5217 }
5218 // assume we know better than the adapter, unless it informs us
5219 info.db_name = info.db_name || this.name;
5220 info.auto_compaction = !!(this.auto_compaction && !isRemote(this));
5221 info.adapter = this.adapter;
5222 callback(null, info);
5223 });
5224 }).bind(this);
5225
5226 this.id = adapterFun('id', function (callback) {
5227 return this._id(callback);
5228 }).bind(this);
5229
5230 this.bulkDocs = adapterFun('bulkDocs', function (req, opts, callback) {
5231 if (typeof opts === 'function') {
5232 callback = opts;
5233 opts = {};
5234 }
5235
5236 opts = opts || {};
5237
5238 if (Array.isArray(req)) {
5239 req = {
5240 docs: req
5241 };
5242 }
5243
5244 if (!req || !req.docs || !Array.isArray(req.docs)) {
5245 return callback(createError(MISSING_BULK_DOCS));
5246 }
5247
5248 for (var i = 0; i < req.docs.length; ++i) {
5249 if (typeof req.docs[i] !== 'object' || Array.isArray(req.docs[i])) {
5250 return callback(createError(NOT_AN_OBJECT));
5251 }
5252 }
5253
5254 var attachmentError;
5255 req.docs.forEach(function (doc) {
5256 if (doc._attachments) {
5257 Object.keys(doc._attachments).forEach(function (name) {
5258 attachmentError = attachmentError || attachmentNameError(name);
5259 if (!doc._attachments[name].content_type) {
5260 guardedConsole('warn', 'Attachment', name, 'on document', doc._id, 'is missing content_type');
5261 }
5262 });
5263 }
5264 });
5265
5266 if (attachmentError) {
5267 return callback(createError(BAD_REQUEST, attachmentError));
5268 }
5269
5270 if (!('new_edits' in opts)) {
5271 if ('new_edits' in req) {
5272 opts.new_edits = req.new_edits;
5273 } else {
5274 opts.new_edits = true;
5275 }
5276 }
5277
5278 var adapter = this;
5279 if (!opts.new_edits && !isRemote(adapter)) {
5280 // ensure revisions of the same doc are sorted, so that
5281 // the local adapter processes them correctly (#2935)
5282 req.docs.sort(compareByIdThenRev);
5283 }
5284
5285 cleanDocs(req.docs);
5286
5287 // in the case of conflicts, we want to return the _ids to the user
5288 // however, the underlying adapter may destroy the docs array, so
5289 // create a copy here
5290 var ids = req.docs.map(function (doc) {
5291 return doc._id;
5292 });
5293
5294 this._bulkDocs(req, opts, function (err, res) {
5295 if (err) {
5296 return callback(err);
5297 }
5298 if (!opts.new_edits) {
5299 // this is what couch does when new_edits is false
5300 res = res.filter(function (x) {
5301 return x.error;
5302 });
5303 }
5304 // add ids for error/conflict responses (not required for CouchDB)
5305 if (!isRemote(adapter)) {
5306 for (var i = 0, l = res.length; i < l; i++) {
5307 res[i].id = res[i].id || ids[i];
5308 }
5309 }
5310
5311 callback(null, res);
5312 });
5313 }).bind(this);
5314
5315 this.registerDependentDatabase = adapterFun('registerDependentDatabase', function (dependentDb, callback) {
5316 var dbOptions = clone(this.__opts);
5317 if (this.__opts.view_adapter) {
5318 dbOptions.adapter = this.__opts.view_adapter;
5319 }
5320
5321 var depDB = new this.constructor(dependentDb, dbOptions);
5322
5323 function diffFun(doc) {
5324 doc.dependentDbs = doc.dependentDbs || {};
5325 if (doc.dependentDbs[dependentDb]) {
5326 return false; // no update required
5327 }
5328 doc.dependentDbs[dependentDb] = true;
5329 return doc;
5330 }
5331 upsert(this, '_local/_pouch_dependentDbs', diffFun).then(function () {
5332 callback(null, {db: depDB});
5333 })["catch"](callback);
5334 }).bind(this);
5335
5336 this.destroy = adapterFun('destroy', function (opts, callback) {
5337
5338 if (typeof opts === 'function') {
5339 callback = opts;
5340 opts = {};
5341 }
5342
5343 var usePrefix = 'use_prefix' in this ? this.use_prefix : true;
5344
5345 const destroyDb = () => {
5346 // call destroy method of the particular adaptor
5347 this._destroy(opts, (err, resp) => {
5348 if (err) {
5349 return callback(err);
5350 }
5351 this._destroyed = true;
5352 this.emit('destroyed');
5353 callback(null, resp || { 'ok': true });
5354 });
5355 };
5356
5357 if (isRemote(this)) {
5358 // no need to check for dependent DBs if it's a remote DB
5359 return destroyDb();
5360 }
5361
5362 this.get('_local/_pouch_dependentDbs', (err, localDoc) => {
5363 if (err) {
5364 /* istanbul ignore if */
5365 if (err.status !== 404) {
5366 return callback(err);
5367 } else { // no dependencies
5368 return destroyDb();
5369 }
5370 }
5371 var dependentDbs = localDoc.dependentDbs;
5372 var PouchDB = this.constructor;
5373 var deletedMap = Object.keys(dependentDbs).map((name) => {
5374 // use_prefix is only false in the browser
5375 /* istanbul ignore next */
5376 var trueName = usePrefix ?
5377 name.replace(new RegExp('^' + PouchDB.prefix), '') : name;
5378 return new PouchDB(trueName, this.__opts).destroy();
5379 });
5380 Promise.all(deletedMap).then(destroyDb, callback);
5381 });
5382 }).bind(this);
5383 }
5384
5385 _compact(opts, callback) {
5386 var changesOpts = {
5387 return_docs: false,
5388 last_seq: opts.last_seq || 0
5389 };
5390 var promises = [];
5391
5392 var taskId;
5393 var compactedDocs = 0;
5394
5395 const onChange = (row) => {
5396 this.activeTasks.update(taskId, {
5397 completed_items: ++compactedDocs
5398 });
5399 promises.push(this.compactDocument(row.id, 0));
5400 };
5401 const onError = (err) => {
5402 this.activeTasks.remove(taskId, err);
5403 callback(err);
5404 };
5405 const onComplete = (resp) => {
5406 var lastSeq = resp.last_seq;
5407 Promise.all(promises).then(() => {
5408 return upsert(this, '_local/compaction', (doc) => {
5409 if (!doc.last_seq || doc.last_seq < lastSeq) {
5410 doc.last_seq = lastSeq;
5411 return doc;
5412 }
5413 return false; // somebody else got here first, don't update
5414 });
5415 }).then(() => {
5416 this.activeTasks.remove(taskId);
5417 callback(null, {ok: true});
5418 })["catch"](onError);
5419 };
5420
5421 this.info().then((info) => {
5422 taskId = this.activeTasks.add({
5423 name: 'database_compaction',
5424 total_items: info.update_seq - changesOpts.last_seq
5425 });
5426
5427 this.changes(changesOpts)
5428 .on('change', onChange)
5429 .on('complete', onComplete)
5430 .on('error', onError);
5431 });
5432 }
5433
5434 changes(opts, callback) {
5435 if (typeof opts === 'function') {
5436 callback = opts;
5437 opts = {};
5438 }
5439
5440 opts = opts || {};
5441
5442 // By default set return_docs to false if the caller has opts.live = true,
5443 // this will prevent us from collecting the set of changes indefinitely
5444 // resulting in growing memory
5445 opts.return_docs = ('return_docs' in opts) ? opts.return_docs : !opts.live;
5446
5447 return new Changes$1(this, opts, callback);
5448 }
5449
5450 type() {
5451 return (typeof this._type === 'function') ? this._type() : this.adapter;
5452 }
5453}
5454
5455// The abstract purge implementation expects a doc id and the rev of a leaf node in that doc.
5456// It will return errors if the rev doesn’t exist or isn’t a leaf.
5457AbstractPouchDB.prototype.purge = adapterFun('_purge', function (docId, rev, callback) {
5458 if (typeof this._purge === 'undefined') {
5459 return callback(createError(UNKNOWN_ERROR, 'Purge is not implemented in the ' + this.adapter + ' adapter.'));
5460 }
5461 var self = this;
5462
5463 self._getRevisionTree(docId, (error, revs) => {
5464 if (error) {
5465 return callback(error);
5466 }
5467 if (!revs) {
5468 return callback(createError(MISSING_DOC));
5469 }
5470 let path;
5471 try {
5472 path = findPathToLeaf(revs, rev);
5473 } catch (error) {
5474 return callback(error.message || error);
5475 }
5476 self._purge(docId, path, (error, result) => {
5477 if (error) {
5478 return callback(error);
5479 } else {
5480 appendPurgeSeq(self, docId, rev).then(function () {
5481 return callback(null, result);
5482 });
5483 }
5484 });
5485 });
5486});
5487
5488class TaskQueue {
5489 constructor() {
5490 this.isReady = false;
5491 this.failed = false;
5492 this.queue = [];
5493 }
5494
5495 execute() {
5496 var fun;
5497 if (this.failed) {
5498 while ((fun = this.queue.shift())) {
5499 fun(this.failed);
5500 }
5501 } else {
5502 while ((fun = this.queue.shift())) {
5503 fun();
5504 }
5505 }
5506 }
5507
5508 fail(err) {
5509 this.failed = err;
5510 this.execute();
5511 }
5512
5513 ready(db) {
5514 this.isReady = true;
5515 this.db = db;
5516 this.execute();
5517 }
5518
5519 addTask(fun) {
5520 this.queue.push(fun);
5521 if (this.failed) {
5522 this.execute();
5523 }
5524 }
5525}
5526
5527function parseAdapter(name, opts) {
5528 var match = name.match(/([a-z-]*):\/\/(.*)/);
5529 if (match) {
5530 // the http adapter expects the fully qualified name
5531 return {
5532 name: /https?/.test(match[1]) ? match[1] + '://' + match[2] : match[2],
5533 adapter: match[1]
5534 };
5535 }
5536
5537 var adapters = PouchDB.adapters;
5538 var preferredAdapters = PouchDB.preferredAdapters;
5539 var prefix = PouchDB.prefix;
5540 var adapterName = opts.adapter;
5541
5542 if (!adapterName) { // automatically determine adapter
5543 for (var i = 0; i < preferredAdapters.length; ++i) {
5544 adapterName = preferredAdapters[i];
5545 // check for browsers that have been upgraded from websql-only to websql+idb
5546 /* istanbul ignore if */
5547 if (adapterName === 'idb' && 'websql' in adapters &&
5548 hasLocalStorage() && localStorage['_pouch__websqldb_' + prefix + name]) {
5549 // log it, because this can be confusing during development
5550 guardedConsole('log', 'PouchDB is downgrading "' + name + '" to WebSQL to' +
5551 ' avoid data loss, because it was already opened with WebSQL.');
5552 continue; // keep using websql to avoid user data loss
5553 }
5554 break;
5555 }
5556 }
5557
5558 var adapter = adapters[adapterName];
5559
5560 // if adapter is invalid, then an error will be thrown later
5561 var usePrefix = (adapter && 'use_prefix' in adapter) ?
5562 adapter.use_prefix : true;
5563
5564 return {
5565 name: usePrefix ? (prefix + name) : name,
5566 adapter: adapterName
5567 };
5568}
5569
5570function inherits(A, B) {
5571 A.prototype = Object.create(B.prototype, {
5572 constructor: { value: A }
5573 });
5574}
5575
5576function createClass(parent, init) {
5577 let klass = function (...args) {
5578 if (!(this instanceof klass)) {
5579 return new klass(...args);
5580 }
5581 init.apply(this, args);
5582 };
5583 inherits(klass, parent);
5584 return klass;
5585}
5586
5587// OK, so here's the deal. Consider this code:
5588// var db1 = new PouchDB('foo');
5589// var db2 = new PouchDB('foo');
5590// db1.destroy();
5591// ^ these two both need to emit 'destroyed' events,
5592// as well as the PouchDB constructor itself.
5593// So we have one db object (whichever one got destroy() called on it)
5594// responsible for emitting the initial event, which then gets emitted
5595// by the constructor, which then broadcasts it to any other dbs
5596// that may have been created with the same name.
5597function prepareForDestruction(self) {
5598
5599 function onDestroyed(from_constructor) {
5600 self.removeListener('closed', onClosed);
5601 if (!from_constructor) {
5602 self.constructor.emit('destroyed', self.name);
5603 }
5604 }
5605
5606 function onClosed() {
5607 self.removeListener('destroyed', onDestroyed);
5608 self.constructor.emit('unref', self);
5609 }
5610
5611 self.once('destroyed', onDestroyed);
5612 self.once('closed', onClosed);
5613 self.constructor.emit('ref', self);
5614}
5615
5616class PouchInternal extends AbstractPouchDB {
5617 constructor(name, opts) {
5618 super();
5619 this._setup(name, opts);
5620 }
5621
5622 _setup(name, opts) {
5623 super._setup();
5624 opts = opts || {};
5625
5626 if (name && typeof name === 'object') {
5627 opts = name;
5628 name = opts.name;
5629 delete opts.name;
5630 }
5631
5632 if (opts.deterministic_revs === undefined) {
5633 opts.deterministic_revs = true;
5634 }
5635
5636 this.__opts = opts = clone(opts);
5637
5638 this.auto_compaction = opts.auto_compaction;
5639 this.purged_infos_limit = opts.purged_infos_limit || 1000;
5640 this.prefix = PouchDB.prefix;
5641
5642 if (typeof name !== 'string') {
5643 throw new Error('Missing/invalid DB name');
5644 }
5645
5646 var prefixedName = (opts.prefix || '') + name;
5647 var backend = parseAdapter(prefixedName, opts);
5648
5649 opts.name = backend.name;
5650 opts.adapter = opts.adapter || backend.adapter;
5651
5652 this.name = name;
5653 this._adapter = opts.adapter;
5654 PouchDB.emit('debug', ['adapter', 'Picked adapter: ', opts.adapter]);
5655
5656 if (!PouchDB.adapters[opts.adapter] ||
5657 !PouchDB.adapters[opts.adapter].valid()) {
5658 throw new Error('Invalid Adapter: ' + opts.adapter);
5659 }
5660
5661 if (opts.view_adapter) {
5662 if (!PouchDB.adapters[opts.view_adapter] ||
5663 !PouchDB.adapters[opts.view_adapter].valid()) {
5664 throw new Error('Invalid View Adapter: ' + opts.view_adapter);
5665 }
5666 }
5667
5668 this.taskqueue = new TaskQueue();
5669
5670 this.adapter = opts.adapter;
5671
5672 PouchDB.adapters[opts.adapter].call(this, opts, (err) => {
5673 if (err) {
5674 return this.taskqueue.fail(err);
5675 }
5676 prepareForDestruction(this);
5677
5678 this.emit('created', this);
5679 PouchDB.emit('created', this.name);
5680 this.taskqueue.ready(this);
5681 });
5682 }
5683}
5684
5685const PouchDB = createClass(PouchInternal, function (name, opts) {
5686 PouchInternal.prototype._setup.call(this, name, opts);
5687});
5688
5689// AbortController was introduced quite a while after fetch and
5690// isnt required for PouchDB to function so polyfill if needed
5691var a = (typeof AbortController !== 'undefined')
5692 ? AbortController
5693 : function () { return {abort: function () {}}; };
5694
5695var f$1 = fetch;
5696var h = Headers;
5697
5698class ActiveTasks {
5699 constructor() {
5700 this.tasks = {};
5701 }
5702
5703 list() {
5704 return Object.values(this.tasks);
5705 }
5706
5707 add(task) {
5708 const id = uuid.v4();
5709 this.tasks[id] = {
5710 id,
5711 name: task.name,
5712 total_items: task.total_items,
5713 created_at: new Date().toJSON()
5714 };
5715 return id;
5716 }
5717
5718 get(id) {
5719 return this.tasks[id];
5720 }
5721
5722 /* eslint-disable no-unused-vars */
5723 remove(id, reason) {
5724 delete this.tasks[id];
5725 return this.tasks;
5726 }
5727
5728 update(id, updatedTask) {
5729 const task = this.tasks[id];
5730 if (typeof task !== 'undefined') {
5731 const mergedTask = {
5732 id: task.id,
5733 name: task.name,
5734 created_at: task.created_at,
5735 total_items: updatedTask.total_items || task.total_items,
5736 completed_items: updatedTask.completed_items || task.completed_items,
5737 updated_at: new Date().toJSON()
5738 };
5739 this.tasks[id] = mergedTask;
5740 }
5741 return this.tasks;
5742 }
5743}
5744
5745PouchDB.adapters = {};
5746PouchDB.preferredAdapters = [];
5747
5748PouchDB.prefix = '_pouch_';
5749
5750var eventEmitter = new EE();
5751
5752function setUpEventEmitter(Pouch) {
5753 Object.keys(EE.prototype).forEach(function (key) {
5754 if (typeof EE.prototype[key] === 'function') {
5755 Pouch[key] = eventEmitter[key].bind(eventEmitter);
5756 }
5757 });
5758
5759 // these are created in constructor.js, and allow us to notify each DB with
5760 // the same name that it was destroyed, via the constructor object
5761 var destructListeners = Pouch._destructionListeners = new ExportedMap();
5762
5763 Pouch.on('ref', function onConstructorRef(db) {
5764 if (!destructListeners.has(db.name)) {
5765 destructListeners.set(db.name, []);
5766 }
5767 destructListeners.get(db.name).push(db);
5768 });
5769
5770 Pouch.on('unref', function onConstructorUnref(db) {
5771 if (!destructListeners.has(db.name)) {
5772 return;
5773 }
5774 var dbList = destructListeners.get(db.name);
5775 var pos = dbList.indexOf(db);
5776 if (pos < 0) {
5777 /* istanbul ignore next */
5778 return;
5779 }
5780 dbList.splice(pos, 1);
5781 if (dbList.length > 1) {
5782 /* istanbul ignore next */
5783 destructListeners.set(db.name, dbList);
5784 } else {
5785 destructListeners["delete"](db.name);
5786 }
5787 });
5788
5789 Pouch.on('destroyed', function onConstructorDestroyed(name) {
5790 if (!destructListeners.has(name)) {
5791 return;
5792 }
5793 var dbList = destructListeners.get(name);
5794 destructListeners["delete"](name);
5795 dbList.forEach(function (db) {
5796 db.emit('destroyed',true);
5797 });
5798 });
5799}
5800
5801setUpEventEmitter(PouchDB);
5802
5803PouchDB.adapter = function (id, obj, addToPreferredAdapters) {
5804 /* istanbul ignore else */
5805 if (obj.valid()) {
5806 PouchDB.adapters[id] = obj;
5807 if (addToPreferredAdapters) {
5808 PouchDB.preferredAdapters.push(id);
5809 }
5810 }
5811};
5812
5813PouchDB.plugin = function (obj) {
5814 if (typeof obj === 'function') { // function style for plugins
5815 obj(PouchDB);
5816 } else if (typeof obj !== 'object' || Object.keys(obj).length === 0) {
5817 throw new Error('Invalid plugin: got "' + obj + '", expected an object or a function');
5818 } else {
5819 Object.keys(obj).forEach(function (id) { // object style for plugins
5820 PouchDB.prototype[id] = obj[id];
5821 });
5822 }
5823 if (this.__defaults) {
5824 PouchDB.__defaults = $inject_Object_assign({}, this.__defaults);
5825 }
5826 return PouchDB;
5827};
5828
5829PouchDB.defaults = function (defaultOpts) {
5830 let PouchWithDefaults = createClass(PouchDB, function (name, opts) {
5831 opts = opts || {};
5832
5833 if (name && typeof name === 'object') {
5834 opts = name;
5835 name = opts.name;
5836 delete opts.name;
5837 }
5838
5839 opts = $inject_Object_assign({}, PouchWithDefaults.__defaults, opts);
5840 PouchDB.call(this, name, opts);
5841 });
5842
5843 PouchWithDefaults.preferredAdapters = PouchDB.preferredAdapters.slice();
5844 Object.keys(PouchDB).forEach(function (key) {
5845 if (!(key in PouchWithDefaults)) {
5846 PouchWithDefaults[key] = PouchDB[key];
5847 }
5848 });
5849
5850 // make default options transitive
5851 // https://github.com/pouchdb/pouchdb/issues/5922
5852 PouchWithDefaults.__defaults = $inject_Object_assign({}, this.__defaults, defaultOpts);
5853
5854 return PouchWithDefaults;
5855};
5856
5857PouchDB.fetch = function (url, opts) {
5858 return f$1(url, opts);
5859};
5860
5861PouchDB.prototype.activeTasks = PouchDB.activeTasks = new ActiveTasks();
5862
5863// managed automatically by set-version.js
5864var version = "8.0.1";
5865
5866// this would just be "return doc[field]", but fields
5867// can be "deep" due to dot notation
5868function getFieldFromDoc(doc, parsedField) {
5869 var value = doc;
5870 for (var i = 0, len = parsedField.length; i < len; i++) {
5871 var key = parsedField[i];
5872 value = value[key];
5873 if (!value) {
5874 break;
5875 }
5876 }
5877 return value;
5878}
5879
5880function compare$1(left, right) {
5881 return left < right ? -1 : left > right ? 1 : 0;
5882}
5883
5884// Converts a string in dot notation to an array of its components, with backslash escaping
5885function parseField(fieldName) {
5886 // fields may be deep (e.g. "foo.bar.baz"), so parse
5887 var fields = [];
5888 var current = '';
5889 for (var i = 0, len = fieldName.length; i < len; i++) {
5890 var ch = fieldName[i];
5891 if (i > 0 && fieldName[i - 1] === '\\' && (ch === '$' || ch === '.')) {
5892 // escaped delimiter
5893 current = current.substring(0, current.length - 1) + ch;
5894 } else if (ch === '.') {
5895 // When `.` is not escaped (above), it is a field delimiter
5896 fields.push(current);
5897 current = '';
5898 } else { // normal character
5899 current += ch;
5900 }
5901 }
5902 fields.push(current);
5903 return fields;
5904}
5905
5906var combinationFields = ['$or', '$nor', '$not'];
5907function isCombinationalField(field) {
5908 return combinationFields.indexOf(field) > -1;
5909}
5910
5911function getKey(obj) {
5912 return Object.keys(obj)[0];
5913}
5914
5915function getValue(obj) {
5916 return obj[getKey(obj)];
5917}
5918
5919
5920// flatten an array of selectors joined by an $and operator
5921function mergeAndedSelectors(selectors) {
5922
5923 // sort to ensure that e.g. if the user specified
5924 // $and: [{$gt: 'a'}, {$gt: 'b'}], then it's collapsed into
5925 // just {$gt: 'b'}
5926 var res = {};
5927 var first = {$or: true, $nor: true};
5928
5929 selectors.forEach(function (selector) {
5930 Object.keys(selector).forEach(function (field) {
5931 var matcher = selector[field];
5932 if (typeof matcher !== 'object') {
5933 matcher = {$eq: matcher};
5934 }
5935
5936 if (isCombinationalField(field)) {
5937 // or, nor
5938 if (matcher instanceof Array) {
5939 if (first[field]) {
5940 first[field] = false;
5941 res[field] = matcher;
5942 return;
5943 }
5944
5945 var entries = [];
5946 res[field].forEach(function (existing) {
5947 Object.keys(matcher).forEach(function (key) {
5948 var m = matcher[key];
5949 var longest = Math.max(Object.keys(existing).length, Object.keys(m).length);
5950 var merged = mergeAndedSelectors([existing, m]);
5951 if (Object.keys(merged).length <= longest) {
5952 // we have a situation like: (a :{$eq :1} || ...) && (a {$eq: 2} || ...)
5953 // merging would produce a $eq 2 when actually we shouldn't ever match against these merged conditions
5954 // merged should always contain more values to be valid
5955 return;
5956 }
5957 entries.push(merged);
5958 });
5959 });
5960 res[field] = entries;
5961 } else {
5962 // not
5963 res[field] = mergeAndedSelectors([matcher]);
5964 }
5965 } else {
5966 var fieldMatchers = res[field] = res[field] || {};
5967 Object.keys(matcher).forEach(function (operator) {
5968 var value = matcher[operator];
5969
5970 if (operator === '$gt' || operator === '$gte') {
5971 return mergeGtGte(operator, value, fieldMatchers);
5972 } else if (operator === '$lt' || operator === '$lte') {
5973 return mergeLtLte(operator, value, fieldMatchers);
5974 } else if (operator === '$ne') {
5975 return mergeNe(value, fieldMatchers);
5976 } else if (operator === '$eq') {
5977 return mergeEq(value, fieldMatchers);
5978 } else if (operator === "$regex") {
5979 return mergeRegex(value, fieldMatchers);
5980 }
5981 fieldMatchers[operator] = value;
5982 });
5983 }
5984 });
5985 });
5986
5987 return res;
5988}
5989
5990
5991
5992// collapse logically equivalent gt/gte values
5993function mergeGtGte(operator, value, fieldMatchers) {
5994 if (typeof fieldMatchers.$eq !== 'undefined') {
5995 return; // do nothing
5996 }
5997 if (typeof fieldMatchers.$gte !== 'undefined') {
5998 if (operator === '$gte') {
5999 if (value > fieldMatchers.$gte) { // more specificity
6000 fieldMatchers.$gte = value;
6001 }
6002 } else { // operator === '$gt'
6003 if (value >= fieldMatchers.$gte) { // more specificity
6004 delete fieldMatchers.$gte;
6005 fieldMatchers.$gt = value;
6006 }
6007 }
6008 } else if (typeof fieldMatchers.$gt !== 'undefined') {
6009 if (operator === '$gte') {
6010 if (value > fieldMatchers.$gt) { // more specificity
6011 delete fieldMatchers.$gt;
6012 fieldMatchers.$gte = value;
6013 }
6014 } else { // operator === '$gt'
6015 if (value > fieldMatchers.$gt) { // more specificity
6016 fieldMatchers.$gt = value;
6017 }
6018 }
6019 } else {
6020 fieldMatchers[operator] = value;
6021 }
6022}
6023
6024// collapse logically equivalent lt/lte values
6025function mergeLtLte(operator, value, fieldMatchers) {
6026 if (typeof fieldMatchers.$eq !== 'undefined') {
6027 return; // do nothing
6028 }
6029 if (typeof fieldMatchers.$lte !== 'undefined') {
6030 if (operator === '$lte') {
6031 if (value < fieldMatchers.$lte) { // more specificity
6032 fieldMatchers.$lte = value;
6033 }
6034 } else { // operator === '$gt'
6035 if (value <= fieldMatchers.$lte) { // more specificity
6036 delete fieldMatchers.$lte;
6037 fieldMatchers.$lt = value;
6038 }
6039 }
6040 } else if (typeof fieldMatchers.$lt !== 'undefined') {
6041 if (operator === '$lte') {
6042 if (value < fieldMatchers.$lt) { // more specificity
6043 delete fieldMatchers.$lt;
6044 fieldMatchers.$lte = value;
6045 }
6046 } else { // operator === '$gt'
6047 if (value < fieldMatchers.$lt) { // more specificity
6048 fieldMatchers.$lt = value;
6049 }
6050 }
6051 } else {
6052 fieldMatchers[operator] = value;
6053 }
6054}
6055
6056// combine $ne values into one array
6057function mergeNe(value, fieldMatchers) {
6058 if ('$ne' in fieldMatchers) {
6059 // there are many things this could "not" be
6060 fieldMatchers.$ne.push(value);
6061 } else { // doesn't exist yet
6062 fieldMatchers.$ne = [value];
6063 }
6064}
6065
6066// add $eq into the mix
6067function mergeEq(value, fieldMatchers) {
6068 // these all have less specificity than the $eq
6069 // TODO: check for user errors here
6070 delete fieldMatchers.$gt;
6071 delete fieldMatchers.$gte;
6072 delete fieldMatchers.$lt;
6073 delete fieldMatchers.$lte;
6074 delete fieldMatchers.$ne;
6075 fieldMatchers.$eq = value;
6076}
6077
6078// combine $regex values into one array
6079function mergeRegex(value, fieldMatchers) {
6080 if ('$regex' in fieldMatchers) {
6081 // a value could match multiple regexes
6082 fieldMatchers.$regex.push(value);
6083 } else { // doesn't exist yet
6084 fieldMatchers.$regex = [value];
6085 }
6086}
6087
6088//#7458: execute function mergeAndedSelectors on nested $and
6089function mergeAndedSelectorsNested(obj) {
6090 for (var prop in obj) {
6091 if (Array.isArray(obj)) {
6092 for (var i in obj) {
6093 if (obj[i]['$and']) {
6094 obj[i] = mergeAndedSelectors(obj[i]['$and']);
6095 }
6096 }
6097 }
6098 var value = obj[prop];
6099 if (typeof value === 'object') {
6100 mergeAndedSelectorsNested(value); // <- recursive call
6101 }
6102 }
6103 return obj;
6104}
6105
6106//#7458: determine id $and is present in selector (at any level)
6107function isAndInSelector(obj, isAnd) {
6108 for (var prop in obj) {
6109 if (prop === '$and') {
6110 isAnd = true;
6111 }
6112 var value = obj[prop];
6113 if (typeof value === 'object') {
6114 isAnd = isAndInSelector(value, isAnd); // <- recursive call
6115 }
6116 }
6117 return isAnd;
6118}
6119
6120//
6121// normalize the selector
6122//
6123function massageSelector(input) {
6124 var result = clone(input);
6125
6126 //#7458: if $and is present in selector (at any level) merge nested $and
6127 if (isAndInSelector(result, false)) {
6128 result = mergeAndedSelectorsNested(result);
6129 if ('$and' in result) {
6130 result = mergeAndedSelectors(result['$and']);
6131 }
6132 }
6133
6134 ['$or', '$nor'].forEach(function (orOrNor) {
6135 if (orOrNor in result) {
6136 // message each individual selector
6137 // e.g. {foo: 'bar'} becomes {foo: {$eq: 'bar'}}
6138 result[orOrNor].forEach(function (subSelector) {
6139 var fields = Object.keys(subSelector);
6140 for (var i = 0; i < fields.length; i++) {
6141 var field = fields[i];
6142 var matcher = subSelector[field];
6143 if (typeof matcher !== 'object' || matcher === null) {
6144 subSelector[field] = {$eq: matcher};
6145 }
6146 }
6147 });
6148 }
6149 });
6150
6151 if ('$not' in result) {
6152 //This feels a little like forcing, but it will work for now,
6153 //I would like to come back to this and make the merging of selectors a little more generic
6154 result['$not'] = mergeAndedSelectors([result['$not']]);
6155 }
6156
6157 var fields = Object.keys(result);
6158
6159 for (var i = 0; i < fields.length; i++) {
6160 var field = fields[i];
6161 var matcher = result[field];
6162
6163 if (typeof matcher !== 'object' || matcher === null) {
6164 matcher = {$eq: matcher};
6165 }
6166 result[field] = matcher;
6167 }
6168
6169 normalizeArrayOperators(result);
6170
6171 return result;
6172}
6173
6174//
6175// The $ne and $regex values must be placed in an array because these operators can be used multiple times on the same field.
6176// When $and is used, mergeAndedSelectors takes care of putting some of them into arrays, otherwise it's done here.
6177//
6178function normalizeArrayOperators(selector) {
6179 Object.keys(selector).forEach(function (field) {
6180 var matcher = selector[field];
6181
6182 if (Array.isArray(matcher)) {
6183 matcher.forEach(function (matcherItem) {
6184 if (matcherItem && typeof matcherItem === 'object') {
6185 normalizeArrayOperators(matcherItem);
6186 }
6187 });
6188 } else if (field === '$ne') {
6189 selector.$ne = [matcher];
6190 } else if (field === '$regex') {
6191 selector.$regex = [matcher];
6192 } else if (matcher && typeof matcher === 'object') {
6193 normalizeArrayOperators(matcher);
6194 }
6195 });
6196}
6197
6198function pad(str, padWith, upToLength) {
6199 var padding = '';
6200 var targetLength = upToLength - str.length;
6201 /* istanbul ignore next */
6202 while (padding.length < targetLength) {
6203 padding += padWith;
6204 }
6205 return padding;
6206}
6207
6208function padLeft(str, padWith, upToLength) {
6209 var padding = pad(str, padWith, upToLength);
6210 return padding + str;
6211}
6212
6213var MIN_MAGNITUDE = -324; // verified by -Number.MIN_VALUE
6214var MAGNITUDE_DIGITS = 3; // ditto
6215var SEP = ''; // set to '_' for easier debugging
6216
6217function collate(a, b) {
6218
6219 if (a === b) {
6220 return 0;
6221 }
6222
6223 a = normalizeKey(a);
6224 b = normalizeKey(b);
6225
6226 var ai = collationIndex(a);
6227 var bi = collationIndex(b);
6228 if ((ai - bi) !== 0) {
6229 return ai - bi;
6230 }
6231 switch (typeof a) {
6232 case 'number':
6233 return a - b;
6234 case 'boolean':
6235 return a < b ? -1 : 1;
6236 case 'string':
6237 return stringCollate(a, b);
6238 }
6239 return Array.isArray(a) ? arrayCollate(a, b) : objectCollate(a, b);
6240}
6241
6242// couch considers null/NaN/Infinity/-Infinity === undefined,
6243// for the purposes of mapreduce indexes. also, dates get stringified.
6244function normalizeKey(key) {
6245 switch (typeof key) {
6246 case 'undefined':
6247 return null;
6248 case 'number':
6249 if (key === Infinity || key === -Infinity || isNaN(key)) {
6250 return null;
6251 }
6252 return key;
6253 case 'object':
6254 var origKey = key;
6255 if (Array.isArray(key)) {
6256 var len = key.length;
6257 key = new Array(len);
6258 for (var i = 0; i < len; i++) {
6259 key[i] = normalizeKey(origKey[i]);
6260 }
6261 /* istanbul ignore next */
6262 } else if (key instanceof Date) {
6263 return key.toJSON();
6264 } else if (key !== null) { // generic object
6265 key = {};
6266 for (var k in origKey) {
6267 if (Object.prototype.hasOwnProperty.call(origKey, k)) {
6268 var val = origKey[k];
6269 if (typeof val !== 'undefined') {
6270 key[k] = normalizeKey(val);
6271 }
6272 }
6273 }
6274 }
6275 }
6276 return key;
6277}
6278
6279function indexify(key) {
6280 if (key !== null) {
6281 switch (typeof key) {
6282 case 'boolean':
6283 return key ? 1 : 0;
6284 case 'number':
6285 return numToIndexableString(key);
6286 case 'string':
6287 // We've to be sure that key does not contain \u0000
6288 // Do order-preserving replacements:
6289 // 0 -> 1, 1
6290 // 1 -> 1, 2
6291 // 2 -> 2, 2
6292 /* eslint-disable no-control-regex */
6293 return key
6294 .replace(/\u0002/g, '\u0002\u0002')
6295 .replace(/\u0001/g, '\u0001\u0002')
6296 .replace(/\u0000/g, '\u0001\u0001');
6297 /* eslint-enable no-control-regex */
6298 case 'object':
6299 var isArray = Array.isArray(key);
6300 var arr = isArray ? key : Object.keys(key);
6301 var i = -1;
6302 var len = arr.length;
6303 var result = '';
6304 if (isArray) {
6305 while (++i < len) {
6306 result += toIndexableString(arr[i]);
6307 }
6308 } else {
6309 while (++i < len) {
6310 var objKey = arr[i];
6311 result += toIndexableString(objKey) +
6312 toIndexableString(key[objKey]);
6313 }
6314 }
6315 return result;
6316 }
6317 }
6318 return '';
6319}
6320
6321// convert the given key to a string that would be appropriate
6322// for lexical sorting, e.g. within a database, where the
6323// sorting is the same given by the collate() function.
6324function toIndexableString(key) {
6325 var zero = '\u0000';
6326 key = normalizeKey(key);
6327 return collationIndex(key) + SEP + indexify(key) + zero;
6328}
6329
6330function parseNumber(str, i) {
6331 var originalIdx = i;
6332 var num;
6333 var zero = str[i] === '1';
6334 if (zero) {
6335 num = 0;
6336 i++;
6337 } else {
6338 var neg = str[i] === '0';
6339 i++;
6340 var numAsString = '';
6341 var magAsString = str.substring(i, i + MAGNITUDE_DIGITS);
6342 var magnitude = parseInt(magAsString, 10) + MIN_MAGNITUDE;
6343 /* istanbul ignore next */
6344 if (neg) {
6345 magnitude = -magnitude;
6346 }
6347 i += MAGNITUDE_DIGITS;
6348 while (true) {
6349 var ch = str[i];
6350 if (ch === '\u0000') {
6351 break;
6352 } else {
6353 numAsString += ch;
6354 }
6355 i++;
6356 }
6357 numAsString = numAsString.split('.');
6358 if (numAsString.length === 1) {
6359 num = parseInt(numAsString, 10);
6360 } else {
6361 /* istanbul ignore next */
6362 num = parseFloat(numAsString[0] + '.' + numAsString[1]);
6363 }
6364 /* istanbul ignore next */
6365 if (neg) {
6366 num = num - 10;
6367 }
6368 /* istanbul ignore next */
6369 if (magnitude !== 0) {
6370 // parseFloat is more reliable than pow due to rounding errors
6371 // e.g. Number.MAX_VALUE would return Infinity if we did
6372 // num * Math.pow(10, magnitude);
6373 num = parseFloat(num + 'e' + magnitude);
6374 }
6375 }
6376 return {num: num, length : i - originalIdx};
6377}
6378
6379// move up the stack while parsing
6380// this function moved outside of parseIndexableString for performance
6381function pop(stack, metaStack) {
6382 var obj = stack.pop();
6383
6384 if (metaStack.length) {
6385 var lastMetaElement = metaStack[metaStack.length - 1];
6386 if (obj === lastMetaElement.element) {
6387 // popping a meta-element, e.g. an object whose value is another object
6388 metaStack.pop();
6389 lastMetaElement = metaStack[metaStack.length - 1];
6390 }
6391 var element = lastMetaElement.element;
6392 var lastElementIndex = lastMetaElement.index;
6393 if (Array.isArray(element)) {
6394 element.push(obj);
6395 } else if (lastElementIndex === stack.length - 2) { // obj with key+value
6396 var key = stack.pop();
6397 element[key] = obj;
6398 } else {
6399 stack.push(obj); // obj with key only
6400 }
6401 }
6402}
6403
6404function parseIndexableString(str) {
6405 var stack = [];
6406 var metaStack = []; // stack for arrays and objects
6407 var i = 0;
6408
6409 /*eslint no-constant-condition: ["error", { "checkLoops": false }]*/
6410 while (true) {
6411 var collationIndex = str[i++];
6412 if (collationIndex === '\u0000') {
6413 if (stack.length === 1) {
6414 return stack.pop();
6415 } else {
6416 pop(stack, metaStack);
6417 continue;
6418 }
6419 }
6420 switch (collationIndex) {
6421 case '1':
6422 stack.push(null);
6423 break;
6424 case '2':
6425 stack.push(str[i] === '1');
6426 i++;
6427 break;
6428 case '3':
6429 var parsedNum = parseNumber(str, i);
6430 stack.push(parsedNum.num);
6431 i += parsedNum.length;
6432 break;
6433 case '4':
6434 var parsedStr = '';
6435 /*eslint no-constant-condition: ["error", { "checkLoops": false }]*/
6436 while (true) {
6437 var ch = str[i];
6438 if (ch === '\u0000') {
6439 break;
6440 }
6441 parsedStr += ch;
6442 i++;
6443 }
6444 // perform the reverse of the order-preserving replacement
6445 // algorithm (see above)
6446 /* eslint-disable no-control-regex */
6447 parsedStr = parsedStr.replace(/\u0001\u0001/g, '\u0000')
6448 .replace(/\u0001\u0002/g, '\u0001')
6449 .replace(/\u0002\u0002/g, '\u0002');
6450 /* eslint-enable no-control-regex */
6451 stack.push(parsedStr);
6452 break;
6453 case '5':
6454 var arrayElement = { element: [], index: stack.length };
6455 stack.push(arrayElement.element);
6456 metaStack.push(arrayElement);
6457 break;
6458 case '6':
6459 var objElement = { element: {}, index: stack.length };
6460 stack.push(objElement.element);
6461 metaStack.push(objElement);
6462 break;
6463 /* istanbul ignore next */
6464 default:
6465 throw new Error(
6466 'bad collationIndex or unexpectedly reached end of input: ' +
6467 collationIndex);
6468 }
6469 }
6470}
6471
6472function arrayCollate(a, b) {
6473 var len = Math.min(a.length, b.length);
6474 for (var i = 0; i < len; i++) {
6475 var sort = collate(a[i], b[i]);
6476 if (sort !== 0) {
6477 return sort;
6478 }
6479 }
6480 return (a.length === b.length) ? 0 :
6481 (a.length > b.length) ? 1 : -1;
6482}
6483function stringCollate(a, b) {
6484 // See: https://github.com/daleharvey/pouchdb/issues/40
6485 // This is incompatible with the CouchDB implementation, but its the
6486 // best we can do for now
6487 return (a === b) ? 0 : ((a > b) ? 1 : -1);
6488}
6489function objectCollate(a, b) {
6490 var ak = Object.keys(a), bk = Object.keys(b);
6491 var len = Math.min(ak.length, bk.length);
6492 for (var i = 0; i < len; i++) {
6493 // First sort the keys
6494 var sort = collate(ak[i], bk[i]);
6495 if (sort !== 0) {
6496 return sort;
6497 }
6498 // if the keys are equal sort the values
6499 sort = collate(a[ak[i]], b[bk[i]]);
6500 if (sort !== 0) {
6501 return sort;
6502 }
6503
6504 }
6505 return (ak.length === bk.length) ? 0 :
6506 (ak.length > bk.length) ? 1 : -1;
6507}
6508// The collation is defined by erlangs ordered terms
6509// the atoms null, true, false come first, then numbers, strings,
6510// arrays, then objects
6511// null/undefined/NaN/Infinity/-Infinity are all considered null
6512function collationIndex(x) {
6513 var id = ['boolean', 'number', 'string', 'object'];
6514 var idx = id.indexOf(typeof x);
6515 //false if -1 otherwise true, but fast!!!!1
6516 if (~idx) {
6517 if (x === null) {
6518 return 1;
6519 }
6520 if (Array.isArray(x)) {
6521 return 5;
6522 }
6523 return idx < 3 ? (idx + 2) : (idx + 3);
6524 }
6525 /* istanbul ignore next */
6526 if (Array.isArray(x)) {
6527 return 5;
6528 }
6529}
6530
6531// conversion:
6532// x yyy zz...zz
6533// x = 0 for negative, 1 for 0, 2 for positive
6534// y = exponent (for negative numbers negated) moved so that it's >= 0
6535// z = mantisse
6536function numToIndexableString(num) {
6537
6538 if (num === 0) {
6539 return '1';
6540 }
6541
6542 // convert number to exponential format for easier and
6543 // more succinct string sorting
6544 var expFormat = num.toExponential().split(/e\+?/);
6545 var magnitude = parseInt(expFormat[1], 10);
6546
6547 var neg = num < 0;
6548
6549 var result = neg ? '0' : '2';
6550
6551 // first sort by magnitude
6552 // it's easier if all magnitudes are positive
6553 var magForComparison = ((neg ? -magnitude : magnitude) - MIN_MAGNITUDE);
6554 var magString = padLeft((magForComparison).toString(), '0', MAGNITUDE_DIGITS);
6555
6556 result += SEP + magString;
6557
6558 // then sort by the factor
6559 var factor = Math.abs(parseFloat(expFormat[0])); // [1..10)
6560 /* istanbul ignore next */
6561 if (neg) { // for negative reverse ordering
6562 factor = 10 - factor;
6563 }
6564
6565 var factorStr = factor.toFixed(20);
6566
6567 // strip zeros from the end
6568 factorStr = factorStr.replace(/\.?0+$/, '');
6569
6570 result += SEP + factorStr;
6571
6572 return result;
6573}
6574
6575// create a comparator based on the sort object
6576function createFieldSorter(sort) {
6577
6578 function getFieldValuesAsArray(doc) {
6579 return sort.map(function (sorting) {
6580 var fieldName = getKey(sorting);
6581 var parsedField = parseField(fieldName);
6582 var docFieldValue = getFieldFromDoc(doc, parsedField);
6583 return docFieldValue;
6584 });
6585 }
6586
6587 return function (aRow, bRow) {
6588 var aFieldValues = getFieldValuesAsArray(aRow.doc);
6589 var bFieldValues = getFieldValuesAsArray(bRow.doc);
6590 var collation = collate(aFieldValues, bFieldValues);
6591 if (collation !== 0) {
6592 return collation;
6593 }
6594 // this is what mango seems to do
6595 return compare$1(aRow.doc._id, bRow.doc._id);
6596 };
6597}
6598
6599function filterInMemoryFields(rows, requestDef, inMemoryFields) {
6600 rows = rows.filter(function (row) {
6601 return rowFilter(row.doc, requestDef.selector, inMemoryFields);
6602 });
6603
6604 if (requestDef.sort) {
6605 // in-memory sort
6606 var fieldSorter = createFieldSorter(requestDef.sort);
6607 rows = rows.sort(fieldSorter);
6608 if (typeof requestDef.sort[0] !== 'string' &&
6609 getValue(requestDef.sort[0]) === 'desc') {
6610 rows = rows.reverse();
6611 }
6612 }
6613
6614 if ('limit' in requestDef || 'skip' in requestDef) {
6615 // have to do the limit in-memory
6616 var skip = requestDef.skip || 0;
6617 var limit = ('limit' in requestDef ? requestDef.limit : rows.length) + skip;
6618 rows = rows.slice(skip, limit);
6619 }
6620 return rows;
6621}
6622
6623function rowFilter(doc, selector, inMemoryFields) {
6624 return inMemoryFields.every(function (field) {
6625 var matcher = selector[field];
6626 var parsedField = parseField(field);
6627 var docFieldValue = getFieldFromDoc(doc, parsedField);
6628 if (isCombinationalField(field)) {
6629 return matchCominationalSelector(field, matcher, doc);
6630 }
6631
6632 return matchSelector(matcher, doc, parsedField, docFieldValue);
6633 });
6634}
6635
6636function matchSelector(matcher, doc, parsedField, docFieldValue) {
6637 if (!matcher) {
6638 // no filtering necessary; this field is just needed for sorting
6639 return true;
6640 }
6641
6642 // is matcher an object, if so continue recursion
6643 if (typeof matcher === 'object') {
6644 return Object.keys(matcher).every(function (maybeUserOperator) {
6645 var userValue = matcher[ maybeUserOperator ];
6646 // explicit operator
6647 if (maybeUserOperator.indexOf("$") === 0) {
6648 return match(maybeUserOperator, doc, userValue, parsedField, docFieldValue);
6649 } else {
6650 var subParsedField = parseField(maybeUserOperator);
6651
6652 if (
6653 docFieldValue === undefined &&
6654 typeof userValue !== "object" &&
6655 subParsedField.length > 0
6656 ) {
6657 // the field does not exist, return or getFieldFromDoc will throw
6658 return false;
6659 }
6660
6661 var subDocFieldValue = getFieldFromDoc(docFieldValue, subParsedField);
6662
6663 if (typeof userValue === "object") {
6664 // field value is an object that might contain more operators
6665 return matchSelector(userValue, doc, parsedField, subDocFieldValue);
6666 }
6667
6668 // implicit operator
6669 return match("$eq", doc, userValue, subParsedField, subDocFieldValue);
6670 }
6671 });
6672 }
6673
6674 // no more depth, No need to recurse further
6675 return matcher === docFieldValue;
6676}
6677
6678function matchCominationalSelector(field, matcher, doc) {
6679
6680 if (field === '$or') {
6681 return matcher.some(function (orMatchers) {
6682 return rowFilter(doc, orMatchers, Object.keys(orMatchers));
6683 });
6684 }
6685
6686 if (field === '$not') {
6687 return !rowFilter(doc, matcher, Object.keys(matcher));
6688 }
6689
6690 //`$nor`
6691 return !matcher.find(function (orMatchers) {
6692 return rowFilter(doc, orMatchers, Object.keys(orMatchers));
6693 });
6694
6695}
6696
6697function match(userOperator, doc, userValue, parsedField, docFieldValue) {
6698 if (!matchers[userOperator]) {
6699 /* istanbul ignore next */
6700 throw new Error('unknown operator "' + userOperator +
6701 '" - should be one of $eq, $lte, $lt, $gt, $gte, $exists, $ne, $in, ' +
6702 '$nin, $size, $mod, $regex, $elemMatch, $type, $allMatch or $all');
6703 }
6704 return matchers[userOperator](doc, userValue, parsedField, docFieldValue);
6705}
6706
6707function fieldExists(docFieldValue) {
6708 return typeof docFieldValue !== 'undefined' && docFieldValue !== null;
6709}
6710
6711function fieldIsNotUndefined(docFieldValue) {
6712 return typeof docFieldValue !== 'undefined';
6713}
6714
6715function modField(docFieldValue, userValue) {
6716 if (typeof docFieldValue !== "number" ||
6717 parseInt(docFieldValue, 10) !== docFieldValue) {
6718 return false;
6719 }
6720
6721 var divisor = userValue[0];
6722 var mod = userValue[1];
6723
6724 return docFieldValue % divisor === mod;
6725}
6726
6727function arrayContainsValue(docFieldValue, userValue) {
6728 return userValue.some(function (val) {
6729 if (docFieldValue instanceof Array) {
6730 return docFieldValue.some(function (docFieldValueItem) {
6731 return collate(val, docFieldValueItem) === 0;
6732 });
6733 }
6734
6735 return collate(val, docFieldValue) === 0;
6736 });
6737}
6738
6739function arrayContainsAllValues(docFieldValue, userValue) {
6740 return userValue.every(function (val) {
6741 return docFieldValue.some(function (docFieldValueItem) {
6742 return collate(val, docFieldValueItem) === 0;
6743 });
6744 });
6745}
6746
6747function arraySize(docFieldValue, userValue) {
6748 return docFieldValue.length === userValue;
6749}
6750
6751function regexMatch(docFieldValue, userValue) {
6752 var re = new RegExp(userValue);
6753
6754 return re.test(docFieldValue);
6755}
6756
6757function typeMatch(docFieldValue, userValue) {
6758
6759 switch (userValue) {
6760 case 'null':
6761 return docFieldValue === null;
6762 case 'boolean':
6763 return typeof (docFieldValue) === 'boolean';
6764 case 'number':
6765 return typeof (docFieldValue) === 'number';
6766 case 'string':
6767 return typeof (docFieldValue) === 'string';
6768 case 'array':
6769 return docFieldValue instanceof Array;
6770 case 'object':
6771 return ({}).toString.call(docFieldValue) === '[object Object]';
6772 }
6773}
6774
6775var matchers = {
6776
6777 '$elemMatch': function (doc, userValue, parsedField, docFieldValue) {
6778 if (!Array.isArray(docFieldValue)) {
6779 return false;
6780 }
6781
6782 if (docFieldValue.length === 0) {
6783 return false;
6784 }
6785
6786 if (typeof docFieldValue[0] === 'object' && docFieldValue[0] !== null) {
6787 return docFieldValue.some(function (val) {
6788 return rowFilter(val, userValue, Object.keys(userValue));
6789 });
6790 }
6791
6792 return docFieldValue.some(function (val) {
6793 return matchSelector(userValue, doc, parsedField, val);
6794 });
6795 },
6796
6797 '$allMatch': function (doc, userValue, parsedField, docFieldValue) {
6798 if (!Array.isArray(docFieldValue)) {
6799 return false;
6800 }
6801
6802 /* istanbul ignore next */
6803 if (docFieldValue.length === 0) {
6804 return false;
6805 }
6806
6807 if (typeof docFieldValue[0] === 'object' && docFieldValue[0] !== null) {
6808 return docFieldValue.every(function (val) {
6809 return rowFilter(val, userValue, Object.keys(userValue));
6810 });
6811 }
6812
6813 return docFieldValue.every(function (val) {
6814 return matchSelector(userValue, doc, parsedField, val);
6815 });
6816 },
6817
6818 '$eq': function (doc, userValue, parsedField, docFieldValue) {
6819 return fieldIsNotUndefined(docFieldValue) && collate(docFieldValue, userValue) === 0;
6820 },
6821
6822 '$gte': function (doc, userValue, parsedField, docFieldValue) {
6823 return fieldIsNotUndefined(docFieldValue) && collate(docFieldValue, userValue) >= 0;
6824 },
6825
6826 '$gt': function (doc, userValue, parsedField, docFieldValue) {
6827 return fieldIsNotUndefined(docFieldValue) && collate(docFieldValue, userValue) > 0;
6828 },
6829
6830 '$lte': function (doc, userValue, parsedField, docFieldValue) {
6831 return fieldIsNotUndefined(docFieldValue) && collate(docFieldValue, userValue) <= 0;
6832 },
6833
6834 '$lt': function (doc, userValue, parsedField, docFieldValue) {
6835 return fieldIsNotUndefined(docFieldValue) && collate(docFieldValue, userValue) < 0;
6836 },
6837
6838 '$exists': function (doc, userValue, parsedField, docFieldValue) {
6839 //a field that is null is still considered to exist
6840 if (userValue) {
6841 return fieldIsNotUndefined(docFieldValue);
6842 }
6843
6844 return !fieldIsNotUndefined(docFieldValue);
6845 },
6846
6847 '$mod': function (doc, userValue, parsedField, docFieldValue) {
6848 return fieldExists(docFieldValue) && modField(docFieldValue, userValue);
6849 },
6850
6851 '$ne': function (doc, userValue, parsedField, docFieldValue) {
6852 return userValue.every(function (neValue) {
6853 return collate(docFieldValue, neValue) !== 0;
6854 });
6855 },
6856 '$in': function (doc, userValue, parsedField, docFieldValue) {
6857 return fieldExists(docFieldValue) && arrayContainsValue(docFieldValue, userValue);
6858 },
6859
6860 '$nin': function (doc, userValue, parsedField, docFieldValue) {
6861 return fieldExists(docFieldValue) && !arrayContainsValue(docFieldValue, userValue);
6862 },
6863
6864 '$size': function (doc, userValue, parsedField, docFieldValue) {
6865 return fieldExists(docFieldValue) &&
6866 Array.isArray(docFieldValue) &&
6867 arraySize(docFieldValue, userValue);
6868 },
6869
6870 '$all': function (doc, userValue, parsedField, docFieldValue) {
6871 return Array.isArray(docFieldValue) && arrayContainsAllValues(docFieldValue, userValue);
6872 },
6873
6874 '$regex': function (doc, userValue, parsedField, docFieldValue) {
6875 return fieldExists(docFieldValue) &&
6876 typeof docFieldValue == "string" &&
6877 userValue.every(function (regexValue) {
6878 return regexMatch(docFieldValue, regexValue);
6879 });
6880 },
6881
6882 '$type': function (doc, userValue, parsedField, docFieldValue) {
6883 return typeMatch(docFieldValue, userValue);
6884 }
6885};
6886
6887// return true if the given doc matches the supplied selector
6888function matchesSelector(doc, selector) {
6889 /* istanbul ignore if */
6890 if (typeof selector !== 'object') {
6891 // match the CouchDB error message
6892 throw new Error('Selector error: expected a JSON object');
6893 }
6894
6895 selector = massageSelector(selector);
6896 var row = {
6897 'doc': doc
6898 };
6899
6900 var rowsMatched = filterInMemoryFields([row], { 'selector': selector }, Object.keys(selector));
6901 return rowsMatched && rowsMatched.length === 1;
6902}
6903
6904function evalFilter(input) {
6905 return scopeEval('"use strict";\nreturn ' + input + ';', {});
6906}
6907
6908function evalView(input) {
6909 var code = [
6910 'return function(doc) {',
6911 ' "use strict";',
6912 ' var emitted = false;',
6913 ' var emit = function (a, b) {',
6914 ' emitted = true;',
6915 ' };',
6916 ' var view = ' + input + ';',
6917 ' view(doc);',
6918 ' if (emitted) {',
6919 ' return true;',
6920 ' }',
6921 '};'
6922 ].join('\n');
6923
6924 return scopeEval(code, {});
6925}
6926
6927function validate(opts, callback) {
6928 if (opts.selector) {
6929 if (opts.filter && opts.filter !== '_selector') {
6930 var filterName = typeof opts.filter === 'string' ?
6931 opts.filter : 'function';
6932 return callback(new Error('selector invalid for filter "' + filterName + '"'));
6933 }
6934 }
6935 callback();
6936}
6937
6938function normalize(opts) {
6939 if (opts.view && !opts.filter) {
6940 opts.filter = '_view';
6941 }
6942
6943 if (opts.selector && !opts.filter) {
6944 opts.filter = '_selector';
6945 }
6946
6947 if (opts.filter && typeof opts.filter === 'string') {
6948 if (opts.filter === '_view') {
6949 opts.view = normalizeDesignDocFunctionName(opts.view);
6950 } else {
6951 opts.filter = normalizeDesignDocFunctionName(opts.filter);
6952 }
6953 }
6954}
6955
6956function shouldFilter(changesHandler, opts) {
6957 return opts.filter && typeof opts.filter === 'string' &&
6958 !opts.doc_ids && !isRemote(changesHandler.db);
6959}
6960
6961function filter(changesHandler, opts) {
6962 var callback = opts.complete;
6963 if (opts.filter === '_view') {
6964 if (!opts.view || typeof opts.view !== 'string') {
6965 var err = createError(BAD_REQUEST,
6966 '`view` filter parameter not found or invalid.');
6967 return callback(err);
6968 }
6969 // fetch a view from a design doc, make it behave like a filter
6970 var viewName = parseDesignDocFunctionName(opts.view);
6971 changesHandler.db.get('_design/' + viewName[0], function (err, ddoc) {
6972 /* istanbul ignore if */
6973 if (changesHandler.isCancelled) {
6974 return callback(null, {status: 'cancelled'});
6975 }
6976 /* istanbul ignore next */
6977 if (err) {
6978 return callback(generateErrorFromResponse(err));
6979 }
6980 var mapFun = ddoc && ddoc.views && ddoc.views[viewName[1]] &&
6981 ddoc.views[viewName[1]].map;
6982 if (!mapFun) {
6983 return callback(createError(MISSING_DOC,
6984 (ddoc.views ? 'missing json key: ' + viewName[1] :
6985 'missing json key: views')));
6986 }
6987 opts.filter = evalView(mapFun);
6988 changesHandler.doChanges(opts);
6989 });
6990 } else if (opts.selector) {
6991 opts.filter = function (doc) {
6992 return matchesSelector(doc, opts.selector);
6993 };
6994 changesHandler.doChanges(opts);
6995 } else {
6996 // fetch a filter from a design doc
6997 var filterName = parseDesignDocFunctionName(opts.filter);
6998 changesHandler.db.get('_design/' + filterName[0], function (err, ddoc) {
6999 /* istanbul ignore if */
7000 if (changesHandler.isCancelled) {
7001 return callback(null, {status: 'cancelled'});
7002 }
7003 /* istanbul ignore next */
7004 if (err) {
7005 return callback(generateErrorFromResponse(err));
7006 }
7007 var filterFun = ddoc && ddoc.filters && ddoc.filters[filterName[1]];
7008 if (!filterFun) {
7009 return callback(createError(MISSING_DOC,
7010 ((ddoc && ddoc.filters) ? 'missing json key: ' + filterName[1]
7011 : 'missing json key: filters')));
7012 }
7013 opts.filter = evalFilter(filterFun);
7014 changesHandler.doChanges(opts);
7015 });
7016 }
7017}
7018
7019function applyChangesFilterPlugin(PouchDB) {
7020 PouchDB._changesFilterPlugin = {
7021 validate: validate,
7022 normalize: normalize,
7023 shouldFilter: shouldFilter,
7024 filter: filter
7025 };
7026}
7027
7028// TODO: remove from pouchdb-core (breaking)
7029PouchDB.plugin(applyChangesFilterPlugin);
7030
7031PouchDB.version = version;
7032
7033function toObject(array) {
7034 return array.reduce(function (obj, item) {
7035 obj[item] = true;
7036 return obj;
7037 }, {});
7038}
7039// List of top level reserved words for doc
7040var reservedWords = toObject([
7041 '_id',
7042 '_rev',
7043 '_access',
7044 '_attachments',
7045 '_deleted',
7046 '_revisions',
7047 '_revs_info',
7048 '_conflicts',
7049 '_deleted_conflicts',
7050 '_local_seq',
7051 '_rev_tree',
7052 // replication documents
7053 '_replication_id',
7054 '_replication_state',
7055 '_replication_state_time',
7056 '_replication_state_reason',
7057 '_replication_stats',
7058 // Specific to Couchbase Sync Gateway
7059 '_removed'
7060]);
7061
7062// List of reserved words that should end up in the document
7063var dataWords = toObject([
7064 '_access',
7065 '_attachments',
7066 // replication documents
7067 '_replication_id',
7068 '_replication_state',
7069 '_replication_state_time',
7070 '_replication_state_reason',
7071 '_replication_stats'
7072]);
7073
7074function parseRevisionInfo(rev) {
7075 if (!/^\d+-/.test(rev)) {
7076 return createError(INVALID_REV);
7077 }
7078 var idx = rev.indexOf('-');
7079 var left = rev.substring(0, idx);
7080 var right = rev.substring(idx + 1);
7081 return {
7082 prefix: parseInt(left, 10),
7083 id: right
7084 };
7085}
7086
7087function makeRevTreeFromRevisions(revisions, opts) {
7088 var pos = revisions.start - revisions.ids.length + 1;
7089
7090 var revisionIds = revisions.ids;
7091 var ids = [revisionIds[0], opts, []];
7092
7093 for (var i = 1, len = revisionIds.length; i < len; i++) {
7094 ids = [revisionIds[i], {status: 'missing'}, [ids]];
7095 }
7096
7097 return [{
7098 pos: pos,
7099 ids: ids
7100 }];
7101}
7102
7103// Preprocess documents, parse their revisions, assign an id and a
7104// revision for new writes that are missing them, etc
7105function parseDoc(doc, newEdits, dbOpts) {
7106 if (!dbOpts) {
7107 dbOpts = {
7108 deterministic_revs: true
7109 };
7110 }
7111
7112 var nRevNum;
7113 var newRevId;
7114 var revInfo;
7115 var opts = {status: 'available'};
7116 if (doc._deleted) {
7117 opts.deleted = true;
7118 }
7119
7120 if (newEdits) {
7121 if (!doc._id) {
7122 doc._id = uuid$1();
7123 }
7124 newRevId = rev$$1(doc, dbOpts.deterministic_revs);
7125 if (doc._rev) {
7126 revInfo = parseRevisionInfo(doc._rev);
7127 if (revInfo.error) {
7128 return revInfo;
7129 }
7130 doc._rev_tree = [{
7131 pos: revInfo.prefix,
7132 ids: [revInfo.id, {status: 'missing'}, [[newRevId, opts, []]]]
7133 }];
7134 nRevNum = revInfo.prefix + 1;
7135 } else {
7136 doc._rev_tree = [{
7137 pos: 1,
7138 ids : [newRevId, opts, []]
7139 }];
7140 nRevNum = 1;
7141 }
7142 } else {
7143 if (doc._revisions) {
7144 doc._rev_tree = makeRevTreeFromRevisions(doc._revisions, opts);
7145 nRevNum = doc._revisions.start;
7146 newRevId = doc._revisions.ids[0];
7147 }
7148 if (!doc._rev_tree) {
7149 revInfo = parseRevisionInfo(doc._rev);
7150 if (revInfo.error) {
7151 return revInfo;
7152 }
7153 nRevNum = revInfo.prefix;
7154 newRevId = revInfo.id;
7155 doc._rev_tree = [{
7156 pos: nRevNum,
7157 ids: [newRevId, opts, []]
7158 }];
7159 }
7160 }
7161
7162 invalidIdError(doc._id);
7163
7164 doc._rev = nRevNum + '-' + newRevId;
7165
7166 var result = {metadata : {}, data : {}};
7167 for (var key in doc) {
7168 /* istanbul ignore else */
7169 if (Object.prototype.hasOwnProperty.call(doc, key)) {
7170 var specialKey = key[0] === '_';
7171 if (specialKey && !reservedWords[key]) {
7172 var error = createError(DOC_VALIDATION, key);
7173 error.message = DOC_VALIDATION.message + ': ' + key;
7174 throw error;
7175 } else if (specialKey && !dataWords[key]) {
7176 result.metadata[key.slice(1)] = doc[key];
7177 } else {
7178 result.data[key] = doc[key];
7179 }
7180 }
7181 }
7182 return result;
7183}
7184
7185function parseBase64(data) {
7186 try {
7187 return thisAtob(data);
7188 } catch (e) {
7189 var err = createError(BAD_ARG,
7190 'Attachment is not a valid base64 string');
7191 return {error: err};
7192 }
7193}
7194
7195function preprocessString(att, blobType, callback) {
7196 var asBinary = parseBase64(att.data);
7197 if (asBinary.error) {
7198 return callback(asBinary.error);
7199 }
7200
7201 att.length = asBinary.length;
7202 if (blobType === 'blob') {
7203 att.data = binStringToBluffer(asBinary, att.content_type);
7204 } else if (blobType === 'base64') {
7205 att.data = thisBtoa(asBinary);
7206 } else { // binary
7207 att.data = asBinary;
7208 }
7209 binaryMd5(asBinary, function (result) {
7210 att.digest = 'md5-' + result;
7211 callback();
7212 });
7213}
7214
7215function preprocessBlob(att, blobType, callback) {
7216 binaryMd5(att.data, function (md5) {
7217 att.digest = 'md5-' + md5;
7218 // size is for blobs (browser), length is for buffers (node)
7219 att.length = att.data.size || att.data.length || 0;
7220 if (blobType === 'binary') {
7221 blobToBinaryString(att.data, function (binString) {
7222 att.data = binString;
7223 callback();
7224 });
7225 } else if (blobType === 'base64') {
7226 blobToBase64(att.data, function (b64) {
7227 att.data = b64;
7228 callback();
7229 });
7230 } else {
7231 callback();
7232 }
7233 });
7234}
7235
7236function preprocessAttachment(att, blobType, callback) {
7237 if (att.stub) {
7238 return callback();
7239 }
7240 if (typeof att.data === 'string') { // input is a base64 string
7241 preprocessString(att, blobType, callback);
7242 } else { // input is a blob
7243 preprocessBlob(att, blobType, callback);
7244 }
7245}
7246
7247function preprocessAttachments(docInfos, blobType, callback) {
7248
7249 if (!docInfos.length) {
7250 return callback();
7251 }
7252
7253 var docv = 0;
7254 var overallErr;
7255
7256 docInfos.forEach(function (docInfo) {
7257 var attachments = docInfo.data && docInfo.data._attachments ?
7258 Object.keys(docInfo.data._attachments) : [];
7259 var recv = 0;
7260
7261 if (!attachments.length) {
7262 return done();
7263 }
7264
7265 function processedAttachment(err) {
7266 overallErr = err;
7267 recv++;
7268 if (recv === attachments.length) {
7269 done();
7270 }
7271 }
7272
7273 for (var key in docInfo.data._attachments) {
7274 if (Object.prototype.hasOwnProperty.call(docInfo.data._attachments, key)) {
7275 preprocessAttachment(docInfo.data._attachments[key],
7276 blobType, processedAttachment);
7277 }
7278 }
7279 });
7280
7281 function done() {
7282 docv++;
7283 if (docInfos.length === docv) {
7284 if (overallErr) {
7285 callback(overallErr);
7286 } else {
7287 callback();
7288 }
7289 }
7290 }
7291}
7292
7293function updateDoc(revLimit, prev, docInfo, results,
7294 i, cb, writeDoc, newEdits) {
7295
7296 if (revExists(prev.rev_tree, docInfo.metadata.rev) && !newEdits) {
7297 results[i] = docInfo;
7298 return cb();
7299 }
7300
7301 // sometimes this is pre-calculated. historically not always
7302 var previousWinningRev = prev.winningRev || winningRev(prev);
7303 var previouslyDeleted = 'deleted' in prev ? prev.deleted :
7304 isDeleted(prev, previousWinningRev);
7305 var deleted = 'deleted' in docInfo.metadata ? docInfo.metadata.deleted :
7306 isDeleted(docInfo.metadata);
7307 var isRoot = /^1-/.test(docInfo.metadata.rev);
7308
7309 if (previouslyDeleted && !deleted && newEdits && isRoot) {
7310 var newDoc = docInfo.data;
7311 newDoc._rev = previousWinningRev;
7312 newDoc._id = docInfo.metadata.id;
7313 docInfo = parseDoc(newDoc, newEdits);
7314 }
7315
7316 var merged = merge(prev.rev_tree, docInfo.metadata.rev_tree[0], revLimit);
7317
7318 var inConflict = newEdits && ((
7319 (previouslyDeleted && deleted && merged.conflicts !== 'new_leaf') ||
7320 (!previouslyDeleted && merged.conflicts !== 'new_leaf') ||
7321 (previouslyDeleted && !deleted && merged.conflicts === 'new_branch')));
7322
7323 if (inConflict) {
7324 var err = createError(REV_CONFLICT);
7325 results[i] = err;
7326 return cb();
7327 }
7328
7329 var newRev = docInfo.metadata.rev;
7330 docInfo.metadata.rev_tree = merged.tree;
7331 docInfo.stemmedRevs = merged.stemmedRevs || [];
7332 /* istanbul ignore else */
7333 if (prev.rev_map) {
7334 docInfo.metadata.rev_map = prev.rev_map; // used only by leveldb
7335 }
7336
7337 // recalculate
7338 var winningRev$$1 = winningRev(docInfo.metadata);
7339 var winningRevIsDeleted = isDeleted(docInfo.metadata, winningRev$$1);
7340
7341 // calculate the total number of documents that were added/removed,
7342 // from the perspective of total_rows/doc_count
7343 var delta = (previouslyDeleted === winningRevIsDeleted) ? 0 :
7344 previouslyDeleted < winningRevIsDeleted ? -1 : 1;
7345
7346 var newRevIsDeleted;
7347 if (newRev === winningRev$$1) {
7348 // if the new rev is the same as the winning rev, we can reuse that value
7349 newRevIsDeleted = winningRevIsDeleted;
7350 } else {
7351 // if they're not the same, then we need to recalculate
7352 newRevIsDeleted = isDeleted(docInfo.metadata, newRev);
7353 }
7354
7355 writeDoc(docInfo, winningRev$$1, winningRevIsDeleted, newRevIsDeleted,
7356 true, delta, i, cb);
7357}
7358
7359function rootIsMissing(docInfo) {
7360 return docInfo.metadata.rev_tree[0].ids[1].status === 'missing';
7361}
7362
7363function processDocs(revLimit, docInfos, api, fetchedDocs, tx, results,
7364 writeDoc, opts, overallCallback) {
7365
7366 // Default to 1000 locally
7367 revLimit = revLimit || 1000;
7368
7369 function insertDoc(docInfo, resultsIdx, callback) {
7370 // Cant insert new deleted documents
7371 var winningRev$$1 = winningRev(docInfo.metadata);
7372 var deleted = isDeleted(docInfo.metadata, winningRev$$1);
7373 if ('was_delete' in opts && deleted) {
7374 results[resultsIdx] = createError(MISSING_DOC, 'deleted');
7375 return callback();
7376 }
7377
7378 // 4712 - detect whether a new document was inserted with a _rev
7379 var inConflict = newEdits && rootIsMissing(docInfo);
7380
7381 if (inConflict) {
7382 var err = createError(REV_CONFLICT);
7383 results[resultsIdx] = err;
7384 return callback();
7385 }
7386
7387 var delta = deleted ? 0 : 1;
7388
7389 writeDoc(docInfo, winningRev$$1, deleted, deleted, false,
7390 delta, resultsIdx, callback);
7391 }
7392
7393 var newEdits = opts.new_edits;
7394 var idsToDocs = new ExportedMap();
7395
7396 var docsDone = 0;
7397 var docsToDo = docInfos.length;
7398
7399 function checkAllDocsDone() {
7400 if (++docsDone === docsToDo && overallCallback) {
7401 overallCallback();
7402 }
7403 }
7404
7405 docInfos.forEach(function (currentDoc, resultsIdx) {
7406
7407 if (currentDoc._id && isLocalId(currentDoc._id)) {
7408 var fun = currentDoc._deleted ? '_removeLocal' : '_putLocal';
7409 api[fun](currentDoc, {ctx: tx}, function (err, res) {
7410 results[resultsIdx] = err || res;
7411 checkAllDocsDone();
7412 });
7413 return;
7414 }
7415
7416 var id = currentDoc.metadata.id;
7417 if (idsToDocs.has(id)) {
7418 docsToDo--; // duplicate
7419 idsToDocs.get(id).push([currentDoc, resultsIdx]);
7420 } else {
7421 idsToDocs.set(id, [[currentDoc, resultsIdx]]);
7422 }
7423 });
7424
7425 // in the case of new_edits, the user can provide multiple docs
7426 // with the same id. these need to be processed sequentially
7427 idsToDocs.forEach(function (docs, id) {
7428 var numDone = 0;
7429
7430 function docWritten() {
7431 if (++numDone < docs.length) {
7432 nextDoc();
7433 } else {
7434 checkAllDocsDone();
7435 }
7436 }
7437 function nextDoc() {
7438 var value = docs[numDone];
7439 var currentDoc = value[0];
7440 var resultsIdx = value[1];
7441
7442 if (fetchedDocs.has(id)) {
7443 updateDoc(revLimit, fetchedDocs.get(id), currentDoc, results,
7444 resultsIdx, docWritten, writeDoc, newEdits);
7445 } else {
7446 // Ensure stemming applies to new writes as well
7447 var merged = merge([], currentDoc.metadata.rev_tree[0], revLimit);
7448 currentDoc.metadata.rev_tree = merged.tree;
7449 currentDoc.stemmedRevs = merged.stemmedRevs || [];
7450 insertDoc(currentDoc, resultsIdx, docWritten);
7451 }
7452 }
7453 nextDoc();
7454 });
7455}
7456
7457// IndexedDB requires a versioned database structure, so we use the
7458// version here to manage migrations.
7459var ADAPTER_VERSION = 5;
7460
7461// The object stores created for each database
7462// DOC_STORE stores the document meta data, its revision history and state
7463// Keyed by document id
7464var DOC_STORE = 'document-store';
7465// BY_SEQ_STORE stores a particular version of a document, keyed by its
7466// sequence id
7467var BY_SEQ_STORE = 'by-sequence';
7468// Where we store attachments
7469var ATTACH_STORE = 'attach-store';
7470// Where we store many-to-many relations
7471// between attachment digests and seqs
7472var ATTACH_AND_SEQ_STORE = 'attach-seq-store';
7473
7474// Where we store database-wide meta data in a single record
7475// keyed by id: META_STORE
7476var META_STORE = 'meta-store';
7477// Where we store local documents
7478var LOCAL_STORE = 'local-store';
7479// Where we detect blob support
7480var DETECT_BLOB_SUPPORT_STORE = 'detect-blob-support';
7481
7482function safeJsonParse(str) {
7483 // This try/catch guards against stack overflow errors.
7484 // JSON.parse() is faster than vuvuzela.parse() but vuvuzela
7485 // cannot overflow.
7486 try {
7487 return JSON.parse(str);
7488 } catch (e) {
7489 /* istanbul ignore next */
7490 return vuvuzela.parse(str);
7491 }
7492}
7493
7494function safeJsonStringify(json) {
7495 try {
7496 return JSON.stringify(json);
7497 } catch (e) {
7498 /* istanbul ignore next */
7499 return vuvuzela.stringify(json);
7500 }
7501}
7502
7503function idbError(callback) {
7504 return function (evt) {
7505 var message = 'unknown_error';
7506 if (evt.target && evt.target.error) {
7507 message = evt.target.error.name || evt.target.error.message;
7508 }
7509 callback(createError(IDB_ERROR, message, evt.type));
7510 };
7511}
7512
7513// Unfortunately, the metadata has to be stringified
7514// when it is put into the database, because otherwise
7515// IndexedDB can throw errors for deeply-nested objects.
7516// Originally we just used JSON.parse/JSON.stringify; now
7517// we use this custom vuvuzela library that avoids recursion.
7518// If we could do it all over again, we'd probably use a
7519// format for the revision trees other than JSON.
7520function encodeMetadata(metadata, winningRev, deleted) {
7521 return {
7522 data: safeJsonStringify(metadata),
7523 winningRev: winningRev,
7524 deletedOrLocal: deleted ? '1' : '0',
7525 seq: metadata.seq, // highest seq for this doc
7526 id: metadata.id
7527 };
7528}
7529
7530function decodeMetadata(storedObject) {
7531 if (!storedObject) {
7532 return null;
7533 }
7534 var metadata = safeJsonParse(storedObject.data);
7535 metadata.winningRev = storedObject.winningRev;
7536 metadata.deleted = storedObject.deletedOrLocal === '1';
7537 metadata.seq = storedObject.seq;
7538 return metadata;
7539}
7540
7541// read the doc back out from the database. we don't store the
7542// _id or _rev because we already have _doc_id_rev.
7543function decodeDoc(doc) {
7544 if (!doc) {
7545 return doc;
7546 }
7547 var idx = doc._doc_id_rev.lastIndexOf(':');
7548 doc._id = doc._doc_id_rev.substring(0, idx - 1);
7549 doc._rev = doc._doc_id_rev.substring(idx + 1);
7550 delete doc._doc_id_rev;
7551 return doc;
7552}
7553
7554// Read a blob from the database, encoding as necessary
7555// and translating from base64 if the IDB doesn't support
7556// native Blobs
7557function readBlobData(body, type, asBlob, callback) {
7558 if (asBlob) {
7559 if (!body) {
7560 callback(createBlob([''], {type: type}));
7561 } else if (typeof body !== 'string') { // we have blob support
7562 callback(body);
7563 } else { // no blob support
7564 callback(b64ToBluffer(body, type));
7565 }
7566 } else { // as base64 string
7567 if (!body) {
7568 callback('');
7569 } else if (typeof body !== 'string') { // we have blob support
7570 readAsBinaryString(body, function (binary) {
7571 callback(thisBtoa(binary));
7572 });
7573 } else { // no blob support
7574 callback(body);
7575 }
7576 }
7577}
7578
7579function fetchAttachmentsIfNecessary(doc, opts, txn, cb) {
7580 var attachments = Object.keys(doc._attachments || {});
7581 if (!attachments.length) {
7582 return cb && cb();
7583 }
7584 var numDone = 0;
7585
7586 function checkDone() {
7587 if (++numDone === attachments.length && cb) {
7588 cb();
7589 }
7590 }
7591
7592 function fetchAttachment(doc, att) {
7593 var attObj = doc._attachments[att];
7594 var digest = attObj.digest;
7595 var req = txn.objectStore(ATTACH_STORE).get(digest);
7596 req.onsuccess = function (e) {
7597 attObj.body = e.target.result.body;
7598 checkDone();
7599 };
7600 }
7601
7602 attachments.forEach(function (att) {
7603 if (opts.attachments && opts.include_docs) {
7604 fetchAttachment(doc, att);
7605 } else {
7606 doc._attachments[att].stub = true;
7607 checkDone();
7608 }
7609 });
7610}
7611
7612// IDB-specific postprocessing necessary because
7613// we don't know whether we stored a true Blob or
7614// a base64-encoded string, and if it's a Blob it
7615// needs to be read outside of the transaction context
7616function postProcessAttachments(results, asBlob) {
7617 return Promise.all(results.map(function (row) {
7618 if (row.doc && row.doc._attachments) {
7619 var attNames = Object.keys(row.doc._attachments);
7620 return Promise.all(attNames.map(function (att) {
7621 var attObj = row.doc._attachments[att];
7622 if (!('body' in attObj)) { // already processed
7623 return;
7624 }
7625 var body = attObj.body;
7626 var type = attObj.content_type;
7627 return new Promise(function (resolve) {
7628 readBlobData(body, type, asBlob, function (data) {
7629 row.doc._attachments[att] = $inject_Object_assign(
7630 pick(attObj, ['digest', 'content_type']),
7631 {data: data}
7632 );
7633 resolve();
7634 });
7635 });
7636 }));
7637 }
7638 }));
7639}
7640
7641function compactRevs(revs, docId, txn) {
7642
7643 var possiblyOrphanedDigests = [];
7644 var seqStore = txn.objectStore(BY_SEQ_STORE);
7645 var attStore = txn.objectStore(ATTACH_STORE);
7646 var attAndSeqStore = txn.objectStore(ATTACH_AND_SEQ_STORE);
7647 var count = revs.length;
7648
7649 function checkDone() {
7650 count--;
7651 if (!count) { // done processing all revs
7652 deleteOrphanedAttachments();
7653 }
7654 }
7655
7656 function deleteOrphanedAttachments() {
7657 if (!possiblyOrphanedDigests.length) {
7658 return;
7659 }
7660 possiblyOrphanedDigests.forEach(function (digest) {
7661 var countReq = attAndSeqStore.index('digestSeq').count(
7662 IDBKeyRange.bound(
7663 digest + '::', digest + '::\uffff', false, false));
7664 countReq.onsuccess = function (e) {
7665 var count = e.target.result;
7666 if (!count) {
7667 // orphaned
7668 attStore["delete"](digest);
7669 }
7670 };
7671 });
7672 }
7673
7674 revs.forEach(function (rev) {
7675 var index = seqStore.index('_doc_id_rev');
7676 var key = docId + "::" + rev;
7677 index.getKey(key).onsuccess = function (e) {
7678 var seq = e.target.result;
7679 if (typeof seq !== 'number') {
7680 return checkDone();
7681 }
7682 seqStore["delete"](seq);
7683
7684 var cursor = attAndSeqStore.index('seq')
7685 .openCursor(IDBKeyRange.only(seq));
7686
7687 cursor.onsuccess = function (event) {
7688 var cursor = event.target.result;
7689 if (cursor) {
7690 var digest = cursor.value.digestSeq.split('::')[0];
7691 possiblyOrphanedDigests.push(digest);
7692 attAndSeqStore["delete"](cursor.primaryKey);
7693 cursor["continue"]();
7694 } else { // done
7695 checkDone();
7696 }
7697 };
7698 };
7699 });
7700}
7701
7702function openTransactionSafely(idb, stores, mode) {
7703 try {
7704 return {
7705 txn: idb.transaction(stores, mode)
7706 };
7707 } catch (err) {
7708 return {
7709 error: err
7710 };
7711 }
7712}
7713
7714var changesHandler = new Changes();
7715
7716function idbBulkDocs(dbOpts, req, opts, api, idb, callback) {
7717 var docInfos = req.docs;
7718 var txn;
7719 var docStore;
7720 var bySeqStore;
7721 var attachStore;
7722 var attachAndSeqStore;
7723 var metaStore;
7724 var docInfoError;
7725 var metaDoc;
7726
7727 for (var i = 0, len = docInfos.length; i < len; i++) {
7728 var doc = docInfos[i];
7729 if (doc._id && isLocalId(doc._id)) {
7730 continue;
7731 }
7732 doc = docInfos[i] = parseDoc(doc, opts.new_edits, dbOpts);
7733 if (doc.error && !docInfoError) {
7734 docInfoError = doc;
7735 }
7736 }
7737
7738 if (docInfoError) {
7739 return callback(docInfoError);
7740 }
7741
7742 var allDocsProcessed = false;
7743 var docCountDelta = 0;
7744 var results = new Array(docInfos.length);
7745 var fetchedDocs = new ExportedMap();
7746 var preconditionErrored = false;
7747 var blobType = api._meta.blobSupport ? 'blob' : 'base64';
7748
7749 preprocessAttachments(docInfos, blobType, function (err) {
7750 if (err) {
7751 return callback(err);
7752 }
7753 startTransaction();
7754 });
7755
7756 function startTransaction() {
7757
7758 var stores = [
7759 DOC_STORE, BY_SEQ_STORE,
7760 ATTACH_STORE,
7761 LOCAL_STORE, ATTACH_AND_SEQ_STORE,
7762 META_STORE
7763 ];
7764 var txnResult = openTransactionSafely(idb, stores, 'readwrite');
7765 if (txnResult.error) {
7766 return callback(txnResult.error);
7767 }
7768 txn = txnResult.txn;
7769 txn.onabort = idbError(callback);
7770 txn.ontimeout = idbError(callback);
7771 txn.oncomplete = complete;
7772 docStore = txn.objectStore(DOC_STORE);
7773 bySeqStore = txn.objectStore(BY_SEQ_STORE);
7774 attachStore = txn.objectStore(ATTACH_STORE);
7775 attachAndSeqStore = txn.objectStore(ATTACH_AND_SEQ_STORE);
7776 metaStore = txn.objectStore(META_STORE);
7777
7778 metaStore.get(META_STORE).onsuccess = function (e) {
7779 metaDoc = e.target.result;
7780 updateDocCountIfReady();
7781 };
7782
7783 verifyAttachments(function (err) {
7784 if (err) {
7785 preconditionErrored = true;
7786 return callback(err);
7787 }
7788 fetchExistingDocs();
7789 });
7790 }
7791
7792 function onAllDocsProcessed() {
7793 allDocsProcessed = true;
7794 updateDocCountIfReady();
7795 }
7796
7797 function idbProcessDocs() {
7798 processDocs(dbOpts.revs_limit, docInfos, api, fetchedDocs,
7799 txn, results, writeDoc, opts, onAllDocsProcessed);
7800 }
7801
7802 function updateDocCountIfReady() {
7803 if (!metaDoc || !allDocsProcessed) {
7804 return;
7805 }
7806 // caching the docCount saves a lot of time in allDocs() and
7807 // info(), which is why we go to all the trouble of doing this
7808 metaDoc.docCount += docCountDelta;
7809 metaStore.put(metaDoc);
7810 }
7811
7812 function fetchExistingDocs() {
7813
7814 if (!docInfos.length) {
7815 return;
7816 }
7817
7818 var numFetched = 0;
7819
7820 function checkDone() {
7821 if (++numFetched === docInfos.length) {
7822 idbProcessDocs();
7823 }
7824 }
7825
7826 function readMetadata(event) {
7827 var metadata = decodeMetadata(event.target.result);
7828
7829 if (metadata) {
7830 fetchedDocs.set(metadata.id, metadata);
7831 }
7832 checkDone();
7833 }
7834
7835 for (var i = 0, len = docInfos.length; i < len; i++) {
7836 var docInfo = docInfos[i];
7837 if (docInfo._id && isLocalId(docInfo._id)) {
7838 checkDone(); // skip local docs
7839 continue;
7840 }
7841 var req = docStore.get(docInfo.metadata.id);
7842 req.onsuccess = readMetadata;
7843 }
7844 }
7845
7846 function complete() {
7847 if (preconditionErrored) {
7848 return;
7849 }
7850
7851 changesHandler.notify(api._meta.name);
7852 callback(null, results);
7853 }
7854
7855 function verifyAttachment(digest, callback) {
7856
7857 var req = attachStore.get(digest);
7858 req.onsuccess = function (e) {
7859 if (!e.target.result) {
7860 var err = createError(MISSING_STUB,
7861 'unknown stub attachment with digest ' +
7862 digest);
7863 err.status = 412;
7864 callback(err);
7865 } else {
7866 callback();
7867 }
7868 };
7869 }
7870
7871 function verifyAttachments(finish) {
7872
7873
7874 var digests = [];
7875 docInfos.forEach(function (docInfo) {
7876 if (docInfo.data && docInfo.data._attachments) {
7877 Object.keys(docInfo.data._attachments).forEach(function (filename) {
7878 var att = docInfo.data._attachments[filename];
7879 if (att.stub) {
7880 digests.push(att.digest);
7881 }
7882 });
7883 }
7884 });
7885 if (!digests.length) {
7886 return finish();
7887 }
7888 var numDone = 0;
7889 var err;
7890
7891 function checkDone() {
7892 if (++numDone === digests.length) {
7893 finish(err);
7894 }
7895 }
7896 digests.forEach(function (digest) {
7897 verifyAttachment(digest, function (attErr) {
7898 if (attErr && !err) {
7899 err = attErr;
7900 }
7901 checkDone();
7902 });
7903 });
7904 }
7905
7906 function writeDoc(docInfo, winningRev$$1, winningRevIsDeleted, newRevIsDeleted,
7907 isUpdate, delta, resultsIdx, callback) {
7908
7909 docInfo.metadata.winningRev = winningRev$$1;
7910 docInfo.metadata.deleted = winningRevIsDeleted;
7911
7912 var doc = docInfo.data;
7913 doc._id = docInfo.metadata.id;
7914 doc._rev = docInfo.metadata.rev;
7915
7916 if (newRevIsDeleted) {
7917 doc._deleted = true;
7918 }
7919
7920 var hasAttachments = doc._attachments &&
7921 Object.keys(doc._attachments).length;
7922 if (hasAttachments) {
7923 return writeAttachments(docInfo, winningRev$$1, winningRevIsDeleted,
7924 isUpdate, resultsIdx, callback);
7925 }
7926
7927 docCountDelta += delta;
7928 updateDocCountIfReady();
7929
7930 finishDoc(docInfo, winningRev$$1, winningRevIsDeleted,
7931 isUpdate, resultsIdx, callback);
7932 }
7933
7934 function finishDoc(docInfo, winningRev$$1, winningRevIsDeleted,
7935 isUpdate, resultsIdx, callback) {
7936
7937 var doc = docInfo.data;
7938 var metadata = docInfo.metadata;
7939
7940 doc._doc_id_rev = metadata.id + '::' + metadata.rev;
7941 delete doc._id;
7942 delete doc._rev;
7943
7944 function afterPutDoc(e) {
7945 var revsToDelete = docInfo.stemmedRevs || [];
7946
7947 if (isUpdate && api.auto_compaction) {
7948 revsToDelete = revsToDelete.concat(compactTree(docInfo.metadata));
7949 }
7950
7951 if (revsToDelete && revsToDelete.length) {
7952 compactRevs(revsToDelete, docInfo.metadata.id, txn);
7953 }
7954
7955 metadata.seq = e.target.result;
7956 // Current _rev is calculated from _rev_tree on read
7957 // delete metadata.rev;
7958 var metadataToStore = encodeMetadata(metadata, winningRev$$1,
7959 winningRevIsDeleted);
7960 var metaDataReq = docStore.put(metadataToStore);
7961 metaDataReq.onsuccess = afterPutMetadata;
7962 }
7963
7964 function afterPutDocError(e) {
7965 // ConstraintError, need to update, not put (see #1638 for details)
7966 e.preventDefault(); // avoid transaction abort
7967 e.stopPropagation(); // avoid transaction onerror
7968 var index = bySeqStore.index('_doc_id_rev');
7969 var getKeyReq = index.getKey(doc._doc_id_rev);
7970 getKeyReq.onsuccess = function (e) {
7971 var putReq = bySeqStore.put(doc, e.target.result);
7972 putReq.onsuccess = afterPutDoc;
7973 };
7974 }
7975
7976 function afterPutMetadata() {
7977 results[resultsIdx] = {
7978 ok: true,
7979 id: metadata.id,
7980 rev: metadata.rev
7981 };
7982 fetchedDocs.set(docInfo.metadata.id, docInfo.metadata);
7983 insertAttachmentMappings(docInfo, metadata.seq, callback);
7984 }
7985
7986 var putReq = bySeqStore.put(doc);
7987
7988 putReq.onsuccess = afterPutDoc;
7989 putReq.onerror = afterPutDocError;
7990 }
7991
7992 function writeAttachments(docInfo, winningRev$$1, winningRevIsDeleted,
7993 isUpdate, resultsIdx, callback) {
7994
7995
7996 var doc = docInfo.data;
7997
7998 var numDone = 0;
7999 var attachments = Object.keys(doc._attachments);
8000
8001 function collectResults() {
8002 if (numDone === attachments.length) {
8003 finishDoc(docInfo, winningRev$$1, winningRevIsDeleted,
8004 isUpdate, resultsIdx, callback);
8005 }
8006 }
8007
8008 function attachmentSaved() {
8009 numDone++;
8010 collectResults();
8011 }
8012
8013 attachments.forEach(function (key) {
8014 var att = docInfo.data._attachments[key];
8015 if (!att.stub) {
8016 var data = att.data;
8017 delete att.data;
8018 att.revpos = parseInt(winningRev$$1, 10);
8019 var digest = att.digest;
8020 saveAttachment(digest, data, attachmentSaved);
8021 } else {
8022 numDone++;
8023 collectResults();
8024 }
8025 });
8026 }
8027
8028 // map seqs to attachment digests, which
8029 // we will need later during compaction
8030 function insertAttachmentMappings(docInfo, seq, callback) {
8031
8032 var attsAdded = 0;
8033 var attsToAdd = Object.keys(docInfo.data._attachments || {});
8034
8035 if (!attsToAdd.length) {
8036 return callback();
8037 }
8038
8039 function checkDone() {
8040 if (++attsAdded === attsToAdd.length) {
8041 callback();
8042 }
8043 }
8044
8045 function add(att) {
8046 var digest = docInfo.data._attachments[att].digest;
8047 var req = attachAndSeqStore.put({
8048 seq: seq,
8049 digestSeq: digest + '::' + seq
8050 });
8051
8052 req.onsuccess = checkDone;
8053 req.onerror = function (e) {
8054 // this callback is for a constaint error, which we ignore
8055 // because this docid/rev has already been associated with
8056 // the digest (e.g. when new_edits == false)
8057 e.preventDefault(); // avoid transaction abort
8058 e.stopPropagation(); // avoid transaction onerror
8059 checkDone();
8060 };
8061 }
8062 for (var i = 0; i < attsToAdd.length; i++) {
8063 add(attsToAdd[i]); // do in parallel
8064 }
8065 }
8066
8067 function saveAttachment(digest, data, callback) {
8068
8069
8070 var getKeyReq = attachStore.count(digest);
8071 getKeyReq.onsuccess = function (e) {
8072 var count = e.target.result;
8073 if (count) {
8074 return callback(); // already exists
8075 }
8076 var newAtt = {
8077 digest: digest,
8078 body: data
8079 };
8080 var putReq = attachStore.put(newAtt);
8081 putReq.onsuccess = callback;
8082 };
8083 }
8084}
8085
8086// Abstraction over IDBCursor and getAll()/getAllKeys() that allows us to batch our operations
8087// while falling back to a normal IDBCursor operation on browsers that don't support getAll() or
8088// getAllKeys(). This allows for a much faster implementation than just straight-up cursors, because
8089// we're not processing each document one-at-a-time.
8090function runBatchedCursor(objectStore, keyRange, descending, batchSize, onBatch) {
8091
8092 if (batchSize === -1) {
8093 batchSize = 1000;
8094 }
8095
8096 // Bail out of getAll()/getAllKeys() in the following cases:
8097 // 1) either method is unsupported - we need both
8098 // 2) batchSize is 1 (might as well use IDBCursor)
8099 // 3) descending – no real way to do this via getAll()/getAllKeys()
8100
8101 var useGetAll = typeof objectStore.getAll === 'function' &&
8102 typeof objectStore.getAllKeys === 'function' &&
8103 batchSize > 1 && !descending;
8104
8105 var keysBatch;
8106 var valuesBatch;
8107 var pseudoCursor;
8108
8109 function onGetAll(e) {
8110 valuesBatch = e.target.result;
8111 if (keysBatch) {
8112 onBatch(keysBatch, valuesBatch, pseudoCursor);
8113 }
8114 }
8115
8116 function onGetAllKeys(e) {
8117 keysBatch = e.target.result;
8118 if (valuesBatch) {
8119 onBatch(keysBatch, valuesBatch, pseudoCursor);
8120 }
8121 }
8122
8123 function continuePseudoCursor() {
8124 if (!keysBatch.length) { // no more results
8125 return onBatch();
8126 }
8127 // fetch next batch, exclusive start
8128 var lastKey = keysBatch[keysBatch.length - 1];
8129 var newKeyRange;
8130 if (keyRange && keyRange.upper) {
8131 try {
8132 newKeyRange = IDBKeyRange.bound(lastKey, keyRange.upper,
8133 true, keyRange.upperOpen);
8134 } catch (e) {
8135 if (e.name === "DataError" && e.code === 0) {
8136 return onBatch(); // we're done, startkey and endkey are equal
8137 }
8138 }
8139 } else {
8140 newKeyRange = IDBKeyRange.lowerBound(lastKey, true);
8141 }
8142 keyRange = newKeyRange;
8143 keysBatch = null;
8144 valuesBatch = null;
8145 objectStore.getAll(keyRange, batchSize).onsuccess = onGetAll;
8146 objectStore.getAllKeys(keyRange, batchSize).onsuccess = onGetAllKeys;
8147 }
8148
8149 function onCursor(e) {
8150 var cursor = e.target.result;
8151 if (!cursor) { // done
8152 return onBatch();
8153 }
8154 // regular IDBCursor acts like a batch where batch size is always 1
8155 onBatch([cursor.key], [cursor.value], cursor);
8156 }
8157
8158 if (useGetAll) {
8159 pseudoCursor = {"continue": continuePseudoCursor};
8160 objectStore.getAll(keyRange, batchSize).onsuccess = onGetAll;
8161 objectStore.getAllKeys(keyRange, batchSize).onsuccess = onGetAllKeys;
8162 } else if (descending) {
8163 objectStore.openCursor(keyRange, 'prev').onsuccess = onCursor;
8164 } else {
8165 objectStore.openCursor(keyRange).onsuccess = onCursor;
8166 }
8167}
8168
8169// simple shim for objectStore.getAll(), falling back to IDBCursor
8170function getAll(objectStore, keyRange, onSuccess) {
8171 if (typeof objectStore.getAll === 'function') {
8172 // use native getAll
8173 objectStore.getAll(keyRange).onsuccess = onSuccess;
8174 return;
8175 }
8176 // fall back to cursors
8177 var values = [];
8178
8179 function onCursor(e) {
8180 var cursor = e.target.result;
8181 if (cursor) {
8182 values.push(cursor.value);
8183 cursor["continue"]();
8184 } else {
8185 onSuccess({
8186 target: {
8187 result: values
8188 }
8189 });
8190 }
8191 }
8192
8193 objectStore.openCursor(keyRange).onsuccess = onCursor;
8194}
8195
8196function allDocsKeys(keys, docStore, onBatch) {
8197 // It's not guaranted to be returned in right order
8198 var valuesBatch = new Array(keys.length);
8199 var count = 0;
8200 keys.forEach(function (key, index) {
8201 docStore.get(key).onsuccess = function (event) {
8202 if (event.target.result) {
8203 valuesBatch[index] = event.target.result;
8204 } else {
8205 valuesBatch[index] = {key: key, error: 'not_found'};
8206 }
8207 count++;
8208 if (count === keys.length) {
8209 onBatch(keys, valuesBatch, {});
8210 }
8211 };
8212 });
8213}
8214
8215function createKeyRange(start, end, inclusiveEnd, key, descending) {
8216 try {
8217 if (start && end) {
8218 if (descending) {
8219 return IDBKeyRange.bound(end, start, !inclusiveEnd, false);
8220 } else {
8221 return IDBKeyRange.bound(start, end, false, !inclusiveEnd);
8222 }
8223 } else if (start) {
8224 if (descending) {
8225 return IDBKeyRange.upperBound(start);
8226 } else {
8227 return IDBKeyRange.lowerBound(start);
8228 }
8229 } else if (end) {
8230 if (descending) {
8231 return IDBKeyRange.lowerBound(end, !inclusiveEnd);
8232 } else {
8233 return IDBKeyRange.upperBound(end, !inclusiveEnd);
8234 }
8235 } else if (key) {
8236 return IDBKeyRange.only(key);
8237 }
8238 } catch (e) {
8239 return {error: e};
8240 }
8241 return null;
8242}
8243
8244function idbAllDocs(opts, idb, callback) {
8245 var start = 'startkey' in opts ? opts.startkey : false;
8246 var end = 'endkey' in opts ? opts.endkey : false;
8247 var key = 'key' in opts ? opts.key : false;
8248 var keys = 'keys' in opts ? opts.keys : false;
8249 var skip = opts.skip || 0;
8250 var limit = typeof opts.limit === 'number' ? opts.limit : -1;
8251 var inclusiveEnd = opts.inclusive_end !== false;
8252
8253 var keyRange ;
8254 var keyRangeError;
8255 if (!keys) {
8256 keyRange = createKeyRange(start, end, inclusiveEnd, key, opts.descending);
8257 keyRangeError = keyRange && keyRange.error;
8258 if (keyRangeError &&
8259 !(keyRangeError.name === "DataError" && keyRangeError.code === 0)) {
8260 // DataError with error code 0 indicates start is less than end, so
8261 // can just do an empty query. Else need to throw
8262 return callback(createError(IDB_ERROR,
8263 keyRangeError.name, keyRangeError.message));
8264 }
8265 }
8266
8267 var stores = [DOC_STORE, BY_SEQ_STORE, META_STORE];
8268
8269 if (opts.attachments) {
8270 stores.push(ATTACH_STORE);
8271 }
8272 var txnResult = openTransactionSafely(idb, stores, 'readonly');
8273 if (txnResult.error) {
8274 return callback(txnResult.error);
8275 }
8276 var txn = txnResult.txn;
8277 txn.oncomplete = onTxnComplete;
8278 txn.onabort = idbError(callback);
8279 var docStore = txn.objectStore(DOC_STORE);
8280 var seqStore = txn.objectStore(BY_SEQ_STORE);
8281 var metaStore = txn.objectStore(META_STORE);
8282 var docIdRevIndex = seqStore.index('_doc_id_rev');
8283 var results = [];
8284 var docCount;
8285 var updateSeq;
8286
8287 metaStore.get(META_STORE).onsuccess = function (e) {
8288 docCount = e.target.result.docCount;
8289 };
8290
8291 /* istanbul ignore if */
8292 if (opts.update_seq) {
8293 getMaxUpdateSeq(seqStore, function (e) {
8294 if (e.target.result && e.target.result.length > 0) {
8295 updateSeq = e.target.result[0];
8296 }
8297 });
8298 }
8299
8300 function getMaxUpdateSeq(objectStore, onSuccess) {
8301 function onCursor(e) {
8302 var cursor = e.target.result;
8303 var maxKey = undefined;
8304 if (cursor && cursor.key) {
8305 maxKey = cursor.key;
8306 }
8307 return onSuccess({
8308 target: {
8309 result: [maxKey]
8310 }
8311 });
8312 }
8313 objectStore.openCursor(null, 'prev').onsuccess = onCursor;
8314 }
8315
8316 // if the user specifies include_docs=true, then we don't
8317 // want to block the main cursor while we're fetching the doc
8318 function fetchDocAsynchronously(metadata, row, winningRev$$1) {
8319 var key = metadata.id + "::" + winningRev$$1;
8320 docIdRevIndex.get(key).onsuccess = function onGetDoc(e) {
8321 row.doc = decodeDoc(e.target.result) || {};
8322 if (opts.conflicts) {
8323 var conflicts = collectConflicts(metadata);
8324 if (conflicts.length) {
8325 row.doc._conflicts = conflicts;
8326 }
8327 }
8328 fetchAttachmentsIfNecessary(row.doc, opts, txn);
8329 };
8330 }
8331
8332 function allDocsInner(winningRev$$1, metadata) {
8333 var row = {
8334 id: metadata.id,
8335 key: metadata.id,
8336 value: {
8337 rev: winningRev$$1
8338 }
8339 };
8340 var deleted = metadata.deleted;
8341 if (deleted) {
8342 if (keys) {
8343 results.push(row);
8344 // deleted docs are okay with "keys" requests
8345 row.value.deleted = true;
8346 row.doc = null;
8347 }
8348 } else if (skip-- <= 0) {
8349 results.push(row);
8350 if (opts.include_docs) {
8351 fetchDocAsynchronously(metadata, row, winningRev$$1);
8352 }
8353 }
8354 }
8355
8356 function processBatch(batchValues) {
8357 for (var i = 0, len = batchValues.length; i < len; i++) {
8358 if (results.length === limit) {
8359 break;
8360 }
8361 var batchValue = batchValues[i];
8362 if (batchValue.error && keys) {
8363 // key was not found with "keys" requests
8364 results.push(batchValue);
8365 continue;
8366 }
8367 var metadata = decodeMetadata(batchValue);
8368 var winningRev$$1 = metadata.winningRev;
8369 allDocsInner(winningRev$$1, metadata);
8370 }
8371 }
8372
8373 function onBatch(batchKeys, batchValues, cursor) {
8374 if (!cursor) {
8375 return;
8376 }
8377 processBatch(batchValues);
8378 if (results.length < limit) {
8379 cursor["continue"]();
8380 }
8381 }
8382
8383 function onGetAll(e) {
8384 var values = e.target.result;
8385 if (opts.descending) {
8386 values = values.reverse();
8387 }
8388 processBatch(values);
8389 }
8390
8391 function onResultsReady() {
8392 var returnVal = {
8393 total_rows: docCount,
8394 offset: opts.skip,
8395 rows: results
8396 };
8397
8398 /* istanbul ignore if */
8399 if (opts.update_seq && updateSeq !== undefined) {
8400 returnVal.update_seq = updateSeq;
8401 }
8402 callback(null, returnVal);
8403 }
8404
8405 function onTxnComplete() {
8406 if (opts.attachments) {
8407 postProcessAttachments(results, opts.binary).then(onResultsReady);
8408 } else {
8409 onResultsReady();
8410 }
8411 }
8412
8413 // don't bother doing any requests if start > end or limit === 0
8414 if (keyRangeError || limit === 0) {
8415 return;
8416 }
8417 if (keys) {
8418 return allDocsKeys(opts.keys, docStore, onBatch);
8419 }
8420 if (limit === -1) { // just fetch everything
8421 return getAll(docStore, keyRange, onGetAll);
8422 }
8423 // else do a cursor
8424 // choose a batch size based on the skip, since we'll need to skip that many
8425 runBatchedCursor(docStore, keyRange, opts.descending, limit + skip, onBatch);
8426}
8427
8428//
8429// Blobs are not supported in all versions of IndexedDB, notably
8430// Chrome <37 and Android <5. In those versions, storing a blob will throw.
8431//
8432// Various other blob bugs exist in Chrome v37-42 (inclusive).
8433// Detecting them is expensive and confusing to users, and Chrome 37-42
8434// is at very low usage worldwide, so we do a hacky userAgent check instead.
8435//
8436// content-type bug: https://code.google.com/p/chromium/issues/detail?id=408120
8437// 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916
8438// FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836
8439//
8440function checkBlobSupport(txn) {
8441 return new Promise(function (resolve) {
8442 var blob$$1 = createBlob(['']);
8443 var req = txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob$$1, 'key');
8444
8445 req.onsuccess = function () {
8446 var matchedChrome = navigator.userAgent.match(/Chrome\/(\d+)/);
8447 var matchedEdge = navigator.userAgent.match(/Edge\//);
8448 // MS Edge pretends to be Chrome 42:
8449 // https://msdn.microsoft.com/en-us/library/hh869301%28v=vs.85%29.aspx
8450 resolve(matchedEdge || !matchedChrome ||
8451 parseInt(matchedChrome[1], 10) >= 43);
8452 };
8453
8454 req.onerror = txn.onabort = function (e) {
8455 // If the transaction aborts now its due to not being able to
8456 // write to the database, likely due to the disk being full
8457 e.preventDefault();
8458 e.stopPropagation();
8459 resolve(false);
8460 };
8461 })["catch"](function () {
8462 return false; // error, so assume unsupported
8463 });
8464}
8465
8466function countDocs(txn, cb) {
8467 var index = txn.objectStore(DOC_STORE).index('deletedOrLocal');
8468 index.count(IDBKeyRange.only('0')).onsuccess = function (e) {
8469 cb(e.target.result);
8470 };
8471}
8472
8473// This task queue ensures that IDB open calls are done in their own tick
8474
8475var running = false;
8476var queue = [];
8477
8478function tryCode(fun, err, res, PouchDB) {
8479 try {
8480 fun(err, res);
8481 } catch (err) {
8482 // Shouldn't happen, but in some odd cases
8483 // IndexedDB implementations might throw a sync
8484 // error, in which case this will at least log it.
8485 PouchDB.emit('error', err);
8486 }
8487}
8488
8489function applyNext() {
8490 if (running || !queue.length) {
8491 return;
8492 }
8493 running = true;
8494 queue.shift()();
8495}
8496
8497function enqueueTask(action, callback, PouchDB) {
8498 queue.push(function runAction() {
8499 action(function runCallback(err, res) {
8500 tryCode(callback, err, res, PouchDB);
8501 running = false;
8502 immediate(function runNext() {
8503 applyNext(PouchDB);
8504 });
8505 });
8506 });
8507 applyNext();
8508}
8509
8510function changes(opts, api, dbName, idb) {
8511 opts = clone(opts);
8512
8513 if (opts.continuous) {
8514 var id = dbName + ':' + uuid$1();
8515 changesHandler.addListener(dbName, id, api, opts);
8516 changesHandler.notify(dbName);
8517 return {
8518 cancel: function () {
8519 changesHandler.removeListener(dbName, id);
8520 }
8521 };
8522 }
8523
8524 var docIds = opts.doc_ids && new ExportedSet(opts.doc_ids);
8525
8526 opts.since = opts.since || 0;
8527 var lastSeq = opts.since;
8528
8529 var limit = 'limit' in opts ? opts.limit : -1;
8530 if (limit === 0) {
8531 limit = 1; // per CouchDB _changes spec
8532 }
8533
8534 var results = [];
8535 var numResults = 0;
8536 var filter = filterChange(opts);
8537 var docIdsToMetadata = new ExportedMap();
8538
8539 var txn;
8540 var bySeqStore;
8541 var docStore;
8542 var docIdRevIndex;
8543
8544 function onBatch(batchKeys, batchValues, cursor) {
8545 if (!cursor || !batchKeys.length) { // done
8546 return;
8547 }
8548
8549 var winningDocs = new Array(batchKeys.length);
8550 var metadatas = new Array(batchKeys.length);
8551
8552 function processMetadataAndWinningDoc(metadata, winningDoc) {
8553 var change = opts.processChange(winningDoc, metadata, opts);
8554 lastSeq = change.seq = metadata.seq;
8555
8556 var filtered = filter(change);
8557 if (typeof filtered === 'object') { // anything but true/false indicates error
8558 return Promise.reject(filtered);
8559 }
8560
8561 if (!filtered) {
8562 return Promise.resolve();
8563 }
8564 numResults++;
8565 if (opts.return_docs) {
8566 results.push(change);
8567 }
8568 // process the attachment immediately
8569 // for the benefit of live listeners
8570 if (opts.attachments && opts.include_docs) {
8571 return new Promise(function (resolve) {
8572 fetchAttachmentsIfNecessary(winningDoc, opts, txn, function () {
8573 postProcessAttachments([change], opts.binary).then(function () {
8574 resolve(change);
8575 });
8576 });
8577 });
8578 } else {
8579 return Promise.resolve(change);
8580 }
8581 }
8582
8583 function onBatchDone() {
8584 var promises = [];
8585 for (var i = 0, len = winningDocs.length; i < len; i++) {
8586 if (numResults === limit) {
8587 break;
8588 }
8589 var winningDoc = winningDocs[i];
8590 if (!winningDoc) {
8591 continue;
8592 }
8593 var metadata = metadatas[i];
8594 promises.push(processMetadataAndWinningDoc(metadata, winningDoc));
8595 }
8596
8597 Promise.all(promises).then(function (changes) {
8598 for (var i = 0, len = changes.length; i < len; i++) {
8599 if (changes[i]) {
8600 opts.onChange(changes[i]);
8601 }
8602 }
8603 })["catch"](opts.complete);
8604
8605 if (numResults !== limit) {
8606 cursor["continue"]();
8607 }
8608 }
8609
8610 // Fetch all metadatas/winningdocs from this batch in parallel, then process
8611 // them all only once all data has been collected. This is done in parallel
8612 // because it's faster than doing it one-at-a-time.
8613 var numDone = 0;
8614 batchValues.forEach(function (value, i) {
8615 var doc = decodeDoc(value);
8616 var seq = batchKeys[i];
8617 fetchWinningDocAndMetadata(doc, seq, function (metadata, winningDoc) {
8618 metadatas[i] = metadata;
8619 winningDocs[i] = winningDoc;
8620 if (++numDone === batchKeys.length) {
8621 onBatchDone();
8622 }
8623 });
8624 });
8625 }
8626
8627 function onGetMetadata(doc, seq, metadata, cb) {
8628 if (metadata.seq !== seq) {
8629 // some other seq is later
8630 return cb();
8631 }
8632
8633 if (metadata.winningRev === doc._rev) {
8634 // this is the winning doc
8635 return cb(metadata, doc);
8636 }
8637
8638 // fetch winning doc in separate request
8639 var docIdRev = doc._id + '::' + metadata.winningRev;
8640 var req = docIdRevIndex.get(docIdRev);
8641 req.onsuccess = function (e) {
8642 cb(metadata, decodeDoc(e.target.result));
8643 };
8644 }
8645
8646 function fetchWinningDocAndMetadata(doc, seq, cb) {
8647 if (docIds && !docIds.has(doc._id)) {
8648 return cb();
8649 }
8650
8651 var metadata = docIdsToMetadata.get(doc._id);
8652 if (metadata) { // cached
8653 return onGetMetadata(doc, seq, metadata, cb);
8654 }
8655 // metadata not cached, have to go fetch it
8656 docStore.get(doc._id).onsuccess = function (e) {
8657 metadata = decodeMetadata(e.target.result);
8658 docIdsToMetadata.set(doc._id, metadata);
8659 onGetMetadata(doc, seq, metadata, cb);
8660 };
8661 }
8662
8663 function finish() {
8664 opts.complete(null, {
8665 results: results,
8666 last_seq: lastSeq
8667 });
8668 }
8669
8670 function onTxnComplete() {
8671 if (!opts.continuous && opts.attachments) {
8672 // cannot guarantee that postProcessing was already done,
8673 // so do it again
8674 postProcessAttachments(results).then(finish);
8675 } else {
8676 finish();
8677 }
8678 }
8679
8680 var objectStores = [DOC_STORE, BY_SEQ_STORE];
8681 if (opts.attachments) {
8682 objectStores.push(ATTACH_STORE);
8683 }
8684 var txnResult = openTransactionSafely(idb, objectStores, 'readonly');
8685 if (txnResult.error) {
8686 return opts.complete(txnResult.error);
8687 }
8688 txn = txnResult.txn;
8689 txn.onabort = idbError(opts.complete);
8690 txn.oncomplete = onTxnComplete;
8691
8692 bySeqStore = txn.objectStore(BY_SEQ_STORE);
8693 docStore = txn.objectStore(DOC_STORE);
8694 docIdRevIndex = bySeqStore.index('_doc_id_rev');
8695
8696 var keyRange = (opts.since && !opts.descending) ?
8697 IDBKeyRange.lowerBound(opts.since, true) : null;
8698
8699 runBatchedCursor(bySeqStore, keyRange, opts.descending, limit, onBatch);
8700}
8701
8702var cachedDBs = new ExportedMap();
8703var blobSupportPromise;
8704var openReqList = new ExportedMap();
8705
8706function IdbPouch(opts, callback) {
8707 var api = this;
8708
8709 enqueueTask(function (thisCallback) {
8710 init(api, opts, thisCallback);
8711 }, callback, api.constructor);
8712}
8713
8714function init(api, opts, callback) {
8715
8716 var dbName = opts.name;
8717
8718 var idb = null;
8719 var idbGlobalFailureError = null;
8720 api._meta = null;
8721
8722 function enrichCallbackError(callback) {
8723 return function (error, result) {
8724 if (error && error instanceof Error && !error.reason) {
8725 if (idbGlobalFailureError) {
8726 error.reason = idbGlobalFailureError;
8727 }
8728 }
8729
8730 callback(error, result);
8731 };
8732 }
8733
8734 // called when creating a fresh new database
8735 function createSchema(db) {
8736 var docStore = db.createObjectStore(DOC_STORE, {keyPath : 'id'});
8737 db.createObjectStore(BY_SEQ_STORE, {autoIncrement: true})
8738 .createIndex('_doc_id_rev', '_doc_id_rev', {unique: true});
8739 db.createObjectStore(ATTACH_STORE, {keyPath: 'digest'});
8740 db.createObjectStore(META_STORE, {keyPath: 'id', autoIncrement: false});
8741 db.createObjectStore(DETECT_BLOB_SUPPORT_STORE);
8742
8743 // added in v2
8744 docStore.createIndex('deletedOrLocal', 'deletedOrLocal', {unique : false});
8745
8746 // added in v3
8747 db.createObjectStore(LOCAL_STORE, {keyPath: '_id'});
8748
8749 // added in v4
8750 var attAndSeqStore = db.createObjectStore(ATTACH_AND_SEQ_STORE,
8751 {autoIncrement: true});
8752 attAndSeqStore.createIndex('seq', 'seq');
8753 attAndSeqStore.createIndex('digestSeq', 'digestSeq', {unique: true});
8754 }
8755
8756 // migration to version 2
8757 // unfortunately "deletedOrLocal" is a misnomer now that we no longer
8758 // store local docs in the main doc-store, but whaddyagonnado
8759 function addDeletedOrLocalIndex(txn, callback) {
8760 var docStore = txn.objectStore(DOC_STORE);
8761 docStore.createIndex('deletedOrLocal', 'deletedOrLocal', {unique : false});
8762
8763 docStore.openCursor().onsuccess = function (event) {
8764 var cursor = event.target.result;
8765 if (cursor) {
8766 var metadata = cursor.value;
8767 var deleted = isDeleted(metadata);
8768 metadata.deletedOrLocal = deleted ? "1" : "0";
8769 docStore.put(metadata);
8770 cursor["continue"]();
8771 } else {
8772 callback();
8773 }
8774 };
8775 }
8776
8777 // migration to version 3 (part 1)
8778 function createLocalStoreSchema(db) {
8779 db.createObjectStore(LOCAL_STORE, {keyPath: '_id'})
8780 .createIndex('_doc_id_rev', '_doc_id_rev', {unique: true});
8781 }
8782
8783 // migration to version 3 (part 2)
8784 function migrateLocalStore(txn, cb) {
8785 var localStore = txn.objectStore(LOCAL_STORE);
8786 var docStore = txn.objectStore(DOC_STORE);
8787 var seqStore = txn.objectStore(BY_SEQ_STORE);
8788
8789 var cursor = docStore.openCursor();
8790 cursor.onsuccess = function (event) {
8791 var cursor = event.target.result;
8792 if (cursor) {
8793 var metadata = cursor.value;
8794 var docId = metadata.id;
8795 var local = isLocalId(docId);
8796 var rev = winningRev(metadata);
8797 if (local) {
8798 var docIdRev = docId + "::" + rev;
8799 // remove all seq entries
8800 // associated with this docId
8801 var start = docId + "::";
8802 var end = docId + "::~";
8803 var index = seqStore.index('_doc_id_rev');
8804 var range = IDBKeyRange.bound(start, end, false, false);
8805 var seqCursor = index.openCursor(range);
8806 seqCursor.onsuccess = function (e) {
8807 seqCursor = e.target.result;
8808 if (!seqCursor) {
8809 // done
8810 docStore["delete"](cursor.primaryKey);
8811 cursor["continue"]();
8812 } else {
8813 var data = seqCursor.value;
8814 if (data._doc_id_rev === docIdRev) {
8815 localStore.put(data);
8816 }
8817 seqStore["delete"](seqCursor.primaryKey);
8818 seqCursor["continue"]();
8819 }
8820 };
8821 } else {
8822 cursor["continue"]();
8823 }
8824 } else if (cb) {
8825 cb();
8826 }
8827 };
8828 }
8829
8830 // migration to version 4 (part 1)
8831 function addAttachAndSeqStore(db) {
8832 var attAndSeqStore = db.createObjectStore(ATTACH_AND_SEQ_STORE,
8833 {autoIncrement: true});
8834 attAndSeqStore.createIndex('seq', 'seq');
8835 attAndSeqStore.createIndex('digestSeq', 'digestSeq', {unique: true});
8836 }
8837
8838 // migration to version 4 (part 2)
8839 function migrateAttsAndSeqs(txn, callback) {
8840 var seqStore = txn.objectStore(BY_SEQ_STORE);
8841 var attStore = txn.objectStore(ATTACH_STORE);
8842 var attAndSeqStore = txn.objectStore(ATTACH_AND_SEQ_STORE);
8843
8844 // need to actually populate the table. this is the expensive part,
8845 // so as an optimization, check first that this database even
8846 // contains attachments
8847 var req = attStore.count();
8848 req.onsuccess = function (e) {
8849 var count = e.target.result;
8850 if (!count) {
8851 return callback(); // done
8852 }
8853
8854 seqStore.openCursor().onsuccess = function (e) {
8855 var cursor = e.target.result;
8856 if (!cursor) {
8857 return callback(); // done
8858 }
8859 var doc = cursor.value;
8860 var seq = cursor.primaryKey;
8861 var atts = Object.keys(doc._attachments || {});
8862 var digestMap = {};
8863 for (var j = 0; j < atts.length; j++) {
8864 var att = doc._attachments[atts[j]];
8865 digestMap[att.digest] = true; // uniq digests, just in case
8866 }
8867 var digests = Object.keys(digestMap);
8868 for (j = 0; j < digests.length; j++) {
8869 var digest = digests[j];
8870 attAndSeqStore.put({
8871 seq: seq,
8872 digestSeq: digest + '::' + seq
8873 });
8874 }
8875 cursor["continue"]();
8876 };
8877 };
8878 }
8879
8880 // migration to version 5
8881 // Instead of relying on on-the-fly migration of metadata,
8882 // this brings the doc-store to its modern form:
8883 // - metadata.winningrev
8884 // - metadata.seq
8885 // - stringify the metadata when storing it
8886 function migrateMetadata(txn) {
8887
8888 function decodeMetadataCompat(storedObject) {
8889 if (!storedObject.data) {
8890 // old format, when we didn't store it stringified
8891 storedObject.deleted = storedObject.deletedOrLocal === '1';
8892 return storedObject;
8893 }
8894 return decodeMetadata(storedObject);
8895 }
8896
8897 // ensure that every metadata has a winningRev and seq,
8898 // which was previously created on-the-fly but better to migrate
8899 var bySeqStore = txn.objectStore(BY_SEQ_STORE);
8900 var docStore = txn.objectStore(DOC_STORE);
8901 var cursor = docStore.openCursor();
8902 cursor.onsuccess = function (e) {
8903 var cursor = e.target.result;
8904 if (!cursor) {
8905 return; // done
8906 }
8907 var metadata = decodeMetadataCompat(cursor.value);
8908
8909 metadata.winningRev = metadata.winningRev ||
8910 winningRev(metadata);
8911
8912 function fetchMetadataSeq() {
8913 // metadata.seq was added post-3.2.0, so if it's missing,
8914 // we need to fetch it manually
8915 var start = metadata.id + '::';
8916 var end = metadata.id + '::\uffff';
8917 var req = bySeqStore.index('_doc_id_rev').openCursor(
8918 IDBKeyRange.bound(start, end));
8919
8920 var metadataSeq = 0;
8921 req.onsuccess = function (e) {
8922 var cursor = e.target.result;
8923 if (!cursor) {
8924 metadata.seq = metadataSeq;
8925 return onGetMetadataSeq();
8926 }
8927 var seq = cursor.primaryKey;
8928 if (seq > metadataSeq) {
8929 metadataSeq = seq;
8930 }
8931 cursor["continue"]();
8932 };
8933 }
8934
8935 function onGetMetadataSeq() {
8936 var metadataToStore = encodeMetadata(metadata,
8937 metadata.winningRev, metadata.deleted);
8938
8939 var req = docStore.put(metadataToStore);
8940 req.onsuccess = function () {
8941 cursor["continue"]();
8942 };
8943 }
8944
8945 if (metadata.seq) {
8946 return onGetMetadataSeq();
8947 }
8948
8949 fetchMetadataSeq();
8950 };
8951
8952 }
8953
8954 api._remote = false;
8955 api.type = function () {
8956 return 'idb';
8957 };
8958
8959 api._id = toPromise(function (callback) {
8960 callback(null, api._meta.instanceId);
8961 });
8962
8963 api._bulkDocs = function idb_bulkDocs(req, reqOpts, callback) {
8964 idbBulkDocs(opts, req, reqOpts, api, idb, enrichCallbackError(callback));
8965 };
8966
8967 // First we look up the metadata in the ids database, then we fetch the
8968 // current revision(s) from the by sequence store
8969 api._get = function idb_get(id, opts, callback) {
8970 var doc;
8971 var metadata;
8972 var err;
8973 var txn = opts.ctx;
8974 if (!txn) {
8975 var txnResult = openTransactionSafely(idb,
8976 [DOC_STORE, BY_SEQ_STORE, ATTACH_STORE], 'readonly');
8977 if (txnResult.error) {
8978 return callback(txnResult.error);
8979 }
8980 txn = txnResult.txn;
8981 }
8982
8983 function finish() {
8984 callback(err, {doc: doc, metadata: metadata, ctx: txn});
8985 }
8986
8987 txn.objectStore(DOC_STORE).get(id).onsuccess = function (e) {
8988 metadata = decodeMetadata(e.target.result);
8989 // we can determine the result here if:
8990 // 1. there is no such document
8991 // 2. the document is deleted and we don't ask about specific rev
8992 // When we ask with opts.rev we expect the answer to be either
8993 // doc (possibly with _deleted=true) or missing error
8994 if (!metadata) {
8995 err = createError(MISSING_DOC, 'missing');
8996 return finish();
8997 }
8998
8999 var rev;
9000 if (!opts.rev) {
9001 rev = metadata.winningRev;
9002 var deleted = isDeleted(metadata);
9003 if (deleted) {
9004 err = createError(MISSING_DOC, "deleted");
9005 return finish();
9006 }
9007 } else {
9008 rev = opts.latest ? latest(opts.rev, metadata) : opts.rev;
9009 }
9010
9011 var objectStore = txn.objectStore(BY_SEQ_STORE);
9012 var key = metadata.id + '::' + rev;
9013
9014 objectStore.index('_doc_id_rev').get(key).onsuccess = function (e) {
9015 doc = e.target.result;
9016 if (doc) {
9017 doc = decodeDoc(doc);
9018 }
9019 if (!doc) {
9020 err = createError(MISSING_DOC, 'missing');
9021 return finish();
9022 }
9023 finish();
9024 };
9025 };
9026 };
9027
9028 api._getAttachment = function (docId, attachId, attachment, opts, callback) {
9029 var txn;
9030 if (opts.ctx) {
9031 txn = opts.ctx;
9032 } else {
9033 var txnResult = openTransactionSafely(idb,
9034 [DOC_STORE, BY_SEQ_STORE, ATTACH_STORE], 'readonly');
9035 if (txnResult.error) {
9036 return callback(txnResult.error);
9037 }
9038 txn = txnResult.txn;
9039 }
9040 var digest = attachment.digest;
9041 var type = attachment.content_type;
9042
9043 txn.objectStore(ATTACH_STORE).get(digest).onsuccess = function (e) {
9044 var body = e.target.result.body;
9045 readBlobData(body, type, opts.binary, function (blobData) {
9046 callback(null, blobData);
9047 });
9048 };
9049 };
9050
9051 api._info = function idb_info(callback) {
9052 var updateSeq;
9053 var docCount;
9054
9055 var txnResult = openTransactionSafely(idb, [META_STORE, BY_SEQ_STORE], 'readonly');
9056 if (txnResult.error) {
9057 return callback(txnResult.error);
9058 }
9059 var txn = txnResult.txn;
9060 txn.objectStore(META_STORE).get(META_STORE).onsuccess = function (e) {
9061 docCount = e.target.result.docCount;
9062 };
9063 txn.objectStore(BY_SEQ_STORE).openCursor(null, 'prev').onsuccess = function (e) {
9064 var cursor = e.target.result;
9065 updateSeq = cursor ? cursor.key : 0;
9066 };
9067
9068 txn.oncomplete = function () {
9069 callback(null, {
9070 doc_count: docCount,
9071 update_seq: updateSeq,
9072 // for debugging
9073 idb_attachment_format: (api._meta.blobSupport ? 'binary' : 'base64')
9074 });
9075 };
9076 };
9077
9078 api._allDocs = function idb_allDocs(opts, callback) {
9079 idbAllDocs(opts, idb, enrichCallbackError(callback));
9080 };
9081
9082 api._changes = function idbChanges(opts) {
9083 return changes(opts, api, dbName, idb);
9084 };
9085
9086 api._close = function (callback) {
9087 // https://developer.mozilla.org/en-US/docs/IndexedDB/IDBDatabase#close
9088 // "Returns immediately and closes the connection in a separate thread..."
9089 idb.close();
9090 cachedDBs["delete"](dbName);
9091 callback();
9092 };
9093
9094 api._getRevisionTree = function (docId, callback) {
9095 var txnResult = openTransactionSafely(idb, [DOC_STORE], 'readonly');
9096 if (txnResult.error) {
9097 return callback(txnResult.error);
9098 }
9099 var txn = txnResult.txn;
9100 var req = txn.objectStore(DOC_STORE).get(docId);
9101 req.onsuccess = function (event) {
9102 var doc = decodeMetadata(event.target.result);
9103 if (!doc) {
9104 callback(createError(MISSING_DOC));
9105 } else {
9106 callback(null, doc.rev_tree);
9107 }
9108 };
9109 };
9110
9111 // This function removes revisions of document docId
9112 // which are listed in revs and sets this document
9113 // revision to to rev_tree
9114 api._doCompaction = function (docId, revs, callback) {
9115 var stores = [
9116 DOC_STORE,
9117 BY_SEQ_STORE,
9118 ATTACH_STORE,
9119 ATTACH_AND_SEQ_STORE
9120 ];
9121 var txnResult = openTransactionSafely(idb, stores, 'readwrite');
9122 if (txnResult.error) {
9123 return callback(txnResult.error);
9124 }
9125 var txn = txnResult.txn;
9126
9127 var docStore = txn.objectStore(DOC_STORE);
9128
9129 docStore.get(docId).onsuccess = function (event) {
9130 var metadata = decodeMetadata(event.target.result);
9131 traverseRevTree(metadata.rev_tree, function (isLeaf, pos,
9132 revHash, ctx, opts) {
9133 var rev = pos + '-' + revHash;
9134 if (revs.indexOf(rev) !== -1) {
9135 opts.status = 'missing';
9136 }
9137 });
9138 compactRevs(revs, docId, txn);
9139 var winningRev$$1 = metadata.winningRev;
9140 var deleted = metadata.deleted;
9141 txn.objectStore(DOC_STORE).put(
9142 encodeMetadata(metadata, winningRev$$1, deleted));
9143 };
9144 txn.onabort = idbError(callback);
9145 txn.oncomplete = function () {
9146 callback();
9147 };
9148 };
9149
9150
9151 api._getLocal = function (id, callback) {
9152 var txnResult = openTransactionSafely(idb, [LOCAL_STORE], 'readonly');
9153 if (txnResult.error) {
9154 return callback(txnResult.error);
9155 }
9156 var tx = txnResult.txn;
9157 var req = tx.objectStore(LOCAL_STORE).get(id);
9158
9159 req.onerror = idbError(callback);
9160 req.onsuccess = function (e) {
9161 var doc = e.target.result;
9162 if (!doc) {
9163 callback(createError(MISSING_DOC));
9164 } else {
9165 delete doc['_doc_id_rev']; // for backwards compat
9166 callback(null, doc);
9167 }
9168 };
9169 };
9170
9171 api._putLocal = function (doc, opts, callback) {
9172 if (typeof opts === 'function') {
9173 callback = opts;
9174 opts = {};
9175 }
9176 delete doc._revisions; // ignore this, trust the rev
9177 var oldRev = doc._rev;
9178 var id = doc._id;
9179 if (!oldRev) {
9180 doc._rev = '0-1';
9181 } else {
9182 doc._rev = '0-' + (parseInt(oldRev.split('-')[1], 10) + 1);
9183 }
9184
9185 var tx = opts.ctx;
9186 var ret;
9187 if (!tx) {
9188 var txnResult = openTransactionSafely(idb, [LOCAL_STORE], 'readwrite');
9189 if (txnResult.error) {
9190 return callback(txnResult.error);
9191 }
9192 tx = txnResult.txn;
9193 tx.onerror = idbError(callback);
9194 tx.oncomplete = function () {
9195 if (ret) {
9196 callback(null, ret);
9197 }
9198 };
9199 }
9200
9201 var oStore = tx.objectStore(LOCAL_STORE);
9202 var req;
9203 if (oldRev) {
9204 req = oStore.get(id);
9205 req.onsuccess = function (e) {
9206 var oldDoc = e.target.result;
9207 if (!oldDoc || oldDoc._rev !== oldRev) {
9208 callback(createError(REV_CONFLICT));
9209 } else { // update
9210 var req = oStore.put(doc);
9211 req.onsuccess = function () {
9212 ret = {ok: true, id: doc._id, rev: doc._rev};
9213 if (opts.ctx) { // return immediately
9214 callback(null, ret);
9215 }
9216 };
9217 }
9218 };
9219 } else { // new doc
9220 req = oStore.add(doc);
9221 req.onerror = function (e) {
9222 // constraint error, already exists
9223 callback(createError(REV_CONFLICT));
9224 e.preventDefault(); // avoid transaction abort
9225 e.stopPropagation(); // avoid transaction onerror
9226 };
9227 req.onsuccess = function () {
9228 ret = {ok: true, id: doc._id, rev: doc._rev};
9229 if (opts.ctx) { // return immediately
9230 callback(null, ret);
9231 }
9232 };
9233 }
9234 };
9235
9236 api._removeLocal = function (doc, opts, callback) {
9237 if (typeof opts === 'function') {
9238 callback = opts;
9239 opts = {};
9240 }
9241 var tx = opts.ctx;
9242 if (!tx) {
9243 var txnResult = openTransactionSafely(idb, [LOCAL_STORE], 'readwrite');
9244 if (txnResult.error) {
9245 return callback(txnResult.error);
9246 }
9247 tx = txnResult.txn;
9248 tx.oncomplete = function () {
9249 if (ret) {
9250 callback(null, ret);
9251 }
9252 };
9253 }
9254 var ret;
9255 var id = doc._id;
9256 var oStore = tx.objectStore(LOCAL_STORE);
9257 var req = oStore.get(id);
9258
9259 req.onerror = idbError(callback);
9260 req.onsuccess = function (e) {
9261 var oldDoc = e.target.result;
9262 if (!oldDoc || oldDoc._rev !== doc._rev) {
9263 callback(createError(MISSING_DOC));
9264 } else {
9265 oStore["delete"](id);
9266 ret = {ok: true, id: id, rev: '0-0'};
9267 if (opts.ctx) { // return immediately
9268 callback(null, ret);
9269 }
9270 }
9271 };
9272 };
9273
9274 api._destroy = function (opts, callback) {
9275 changesHandler.removeAllListeners(dbName);
9276
9277 //Close open request for "dbName" database to fix ie delay.
9278 var openReq = openReqList.get(dbName);
9279 if (openReq && openReq.result) {
9280 openReq.result.close();
9281 cachedDBs["delete"](dbName);
9282 }
9283 var req = indexedDB.deleteDatabase(dbName);
9284
9285 req.onsuccess = function () {
9286 //Remove open request from the list.
9287 openReqList["delete"](dbName);
9288 if (hasLocalStorage() && (dbName in localStorage)) {
9289 delete localStorage[dbName];
9290 }
9291 callback(null, { 'ok': true });
9292 };
9293
9294 req.onerror = idbError(callback);
9295 };
9296
9297 var cached = cachedDBs.get(dbName);
9298
9299 if (cached) {
9300 idb = cached.idb;
9301 api._meta = cached.global;
9302 return immediate(function () {
9303 callback(null, api);
9304 });
9305 }
9306
9307 var req = indexedDB.open(dbName, ADAPTER_VERSION);
9308 openReqList.set(dbName, req);
9309
9310 req.onupgradeneeded = function (e) {
9311 var db = e.target.result;
9312 if (e.oldVersion < 1) {
9313 return createSchema(db); // new db, initial schema
9314 }
9315 // do migrations
9316
9317 var txn = e.currentTarget.transaction;
9318 // these migrations have to be done in this function, before
9319 // control is returned to the event loop, because IndexedDB
9320
9321 if (e.oldVersion < 3) {
9322 createLocalStoreSchema(db); // v2 -> v3
9323 }
9324 if (e.oldVersion < 4) {
9325 addAttachAndSeqStore(db); // v3 -> v4
9326 }
9327
9328 var migrations = [
9329 addDeletedOrLocalIndex, // v1 -> v2
9330 migrateLocalStore, // v2 -> v3
9331 migrateAttsAndSeqs, // v3 -> v4
9332 migrateMetadata // v4 -> v5
9333 ];
9334
9335 var i = e.oldVersion;
9336
9337 function next() {
9338 var migration = migrations[i - 1];
9339 i++;
9340 if (migration) {
9341 migration(txn, next);
9342 }
9343 }
9344
9345 next();
9346 };
9347
9348 req.onsuccess = function (e) {
9349
9350 idb = e.target.result;
9351
9352 idb.onversionchange = function () {
9353 idb.close();
9354 cachedDBs["delete"](dbName);
9355 };
9356
9357 idb.onabort = function (e) {
9358 guardedConsole('error', 'Database has a global failure', e.target.error);
9359 idbGlobalFailureError = e.target.error;
9360 idb.close();
9361 cachedDBs["delete"](dbName);
9362 };
9363
9364 // Do a few setup operations (in parallel as much as possible):
9365 // 1. Fetch meta doc
9366 // 2. Check blob support
9367 // 3. Calculate docCount
9368 // 4. Generate an instanceId if necessary
9369 // 5. Store docCount and instanceId on meta doc
9370
9371 var txn = idb.transaction([
9372 META_STORE,
9373 DETECT_BLOB_SUPPORT_STORE,
9374 DOC_STORE
9375 ], 'readwrite');
9376
9377 var storedMetaDoc = false;
9378 var metaDoc;
9379 var docCount;
9380 var blobSupport;
9381 var instanceId;
9382
9383 function completeSetup() {
9384 if (typeof blobSupport === 'undefined' || !storedMetaDoc) {
9385 return;
9386 }
9387 api._meta = {
9388 name: dbName,
9389 instanceId: instanceId,
9390 blobSupport: blobSupport
9391 };
9392
9393 cachedDBs.set(dbName, {
9394 idb: idb,
9395 global: api._meta
9396 });
9397 callback(null, api);
9398 }
9399
9400 function storeMetaDocIfReady() {
9401 if (typeof docCount === 'undefined' || typeof metaDoc === 'undefined') {
9402 return;
9403 }
9404 var instanceKey = dbName + '_id';
9405 if (instanceKey in metaDoc) {
9406 instanceId = metaDoc[instanceKey];
9407 } else {
9408 metaDoc[instanceKey] = instanceId = uuid$1();
9409 }
9410 metaDoc.docCount = docCount;
9411 txn.objectStore(META_STORE).put(metaDoc);
9412 }
9413
9414 //
9415 // fetch or generate the instanceId
9416 //
9417 txn.objectStore(META_STORE).get(META_STORE).onsuccess = function (e) {
9418 metaDoc = e.target.result || { id: META_STORE };
9419 storeMetaDocIfReady();
9420 };
9421
9422 //
9423 // countDocs
9424 //
9425 countDocs(txn, function (count) {
9426 docCount = count;
9427 storeMetaDocIfReady();
9428 });
9429
9430 //
9431 // check blob support
9432 //
9433 if (!blobSupportPromise) {
9434 // make sure blob support is only checked once
9435 blobSupportPromise = checkBlobSupport(txn);
9436 }
9437
9438 blobSupportPromise.then(function (val) {
9439 blobSupport = val;
9440 completeSetup();
9441 });
9442
9443 // only when the metadata put transaction has completed,
9444 // consider the setup done
9445 txn.oncomplete = function () {
9446 storedMetaDoc = true;
9447 completeSetup();
9448 };
9449 txn.onabort = idbError(callback);
9450 };
9451
9452 req.onerror = function (e) {
9453 var msg = e.target.error && e.target.error.message;
9454
9455 if (!msg) {
9456 msg = 'Failed to open indexedDB, are you in private browsing mode?';
9457 } else if (msg.indexOf("stored database is a higher version") !== -1) {
9458 msg = new Error('This DB was created with the newer "indexeddb" adapter, but you are trying to open it with the older "idb" adapter');
9459 }
9460
9461 guardedConsole('error', msg);
9462 callback(createError(IDB_ERROR, msg));
9463 };
9464}
9465
9466IdbPouch.valid = function () {
9467 // Following #7085 buggy idb versions (typically Safari < 10.1) are
9468 // considered valid.
9469
9470 // On Firefox SecurityError is thrown while referencing indexedDB if cookies
9471 // are not allowed. `typeof indexedDB` also triggers the error.
9472 try {
9473 // some outdated implementations of IDB that appear on Samsung
9474 // and HTC Android devices <4.4 are missing IDBKeyRange
9475 return typeof indexedDB !== 'undefined' && typeof IDBKeyRange !== 'undefined';
9476 } catch (e) {
9477 return false;
9478 }
9479};
9480
9481function IDBPouch (PouchDB) {
9482 PouchDB.adapter('idb', IdbPouch, true);
9483}
9484
9485// dead simple promise pool, inspired by https://github.com/timdp/es6-promise-pool
9486// but much smaller in code size. limits the number of concurrent promises that are executed
9487
9488
9489function pool(promiseFactories, limit) {
9490 return new Promise(function (resolve, reject) {
9491 var running = 0;
9492 var current = 0;
9493 var done = 0;
9494 var len = promiseFactories.length;
9495 var err;
9496
9497 function runNext() {
9498 running++;
9499 promiseFactories[current++]().then(onSuccess, onError);
9500 }
9501
9502 function doNext() {
9503 if (++done === len) {
9504 /* istanbul ignore if */
9505 if (err) {
9506 reject(err);
9507 } else {
9508 resolve();
9509 }
9510 } else {
9511 runNextBatch();
9512 }
9513 }
9514
9515 function onSuccess() {
9516 running--;
9517 doNext();
9518 }
9519
9520 /* istanbul ignore next */
9521 function onError(thisErr) {
9522 running--;
9523 err = err || thisErr;
9524 doNext();
9525 }
9526
9527 function runNextBatch() {
9528 while (running < limit && current < len) {
9529 runNext();
9530 }
9531 }
9532
9533 runNextBatch();
9534 });
9535}
9536
9537const CHANGES_BATCH_SIZE = 25;
9538const MAX_SIMULTANEOUS_REVS = 50;
9539const CHANGES_TIMEOUT_BUFFER = 5000;
9540const DEFAULT_HEARTBEAT = 10000;
9541
9542let supportsBulkGetMap = {};
9543
9544function readAttachmentsAsBlobOrBuffer(row) {
9545 let doc = row.doc || row.ok;
9546 let atts = doc && doc._attachments;
9547 if (!atts) {
9548 return;
9549 }
9550 Object.keys(atts).forEach(function (filename) {
9551 let att = atts[filename];
9552 att.data = b64ToBluffer(att.data, att.content_type);
9553 });
9554}
9555
9556function encodeDocId(id) {
9557 if (/^_design/.test(id)) {
9558 return '_design/' + encodeURIComponent(id.slice(8));
9559 }
9560 if (/^_local/.test(id)) {
9561 return '_local/' + encodeURIComponent(id.slice(7));
9562 }
9563 return encodeURIComponent(id);
9564}
9565
9566function preprocessAttachments$1(doc) {
9567 if (!doc._attachments || !Object.keys(doc._attachments)) {
9568 return Promise.resolve();
9569 }
9570
9571 return Promise.all(Object.keys(doc._attachments).map(function (key) {
9572 let attachment = doc._attachments[key];
9573 if (attachment.data && typeof attachment.data !== 'string') {
9574 return new Promise(function (resolve) {
9575 blobToBase64(attachment.data, resolve);
9576 }).then(function (b64) {
9577 attachment.data = b64;
9578 });
9579 }
9580 }));
9581}
9582
9583function hasUrlPrefix(opts) {
9584 if (!opts.prefix) {
9585 return false;
9586 }
9587 let protocol = parseUri(opts.prefix).protocol;
9588 return protocol === 'http' || protocol === 'https';
9589}
9590
9591// Get all the information you possibly can about the URI given by name and
9592// return it as a suitable object.
9593function getHost(name, opts) {
9594 // encode db name if opts.prefix is a url (#5574)
9595 if (hasUrlPrefix(opts)) {
9596 let dbName = opts.name.substr(opts.prefix.length);
9597 // Ensure prefix has a trailing slash
9598 let prefix = opts.prefix.replace(/\/?$/, '/');
9599 name = prefix + encodeURIComponent(dbName);
9600 }
9601
9602 let uri = parseUri(name);
9603 if (uri.user || uri.password) {
9604 uri.auth = {username: uri.user, password: uri.password};
9605 }
9606
9607 // Split the path part of the URI into parts using '/' as the delimiter
9608 // after removing any leading '/' and any trailing '/'
9609 let parts = uri.path.replace(/(^\/|\/$)/g, '').split('/');
9610
9611 uri.db = parts.pop();
9612 // Prevent double encoding of URI component
9613 if (uri.db.indexOf('%') === -1) {
9614 uri.db = encodeURIComponent(uri.db);
9615 }
9616
9617 uri.path = parts.join('/');
9618
9619 return uri;
9620}
9621
9622// Generate a URL with the host data given by opts and the given path
9623function genDBUrl(opts, path) {
9624 return genUrl(opts, opts.db + '/' + path);
9625}
9626
9627// Generate a URL with the host data given by opts and the given path
9628function genUrl(opts, path) {
9629 // If the host already has a path, then we need to have a path delimiter
9630 // Otherwise, the path delimiter is the empty string
9631 let pathDel = !opts.path ? '' : '/';
9632
9633 // If the host already has a path, then we need to have a path delimiter
9634 // Otherwise, the path delimiter is the empty string
9635 return opts.protocol + '://' + opts.host +
9636 (opts.port ? (':' + opts.port) : '') +
9637 '/' + opts.path + pathDel + path;
9638}
9639
9640function paramsToStr(params) {
9641 return '?' + Object.keys(params).map(function (k) {
9642 return k + '=' + encodeURIComponent(params[k]);
9643 }).join('&');
9644}
9645
9646function shouldCacheBust(opts) {
9647 let ua = (typeof navigator !== 'undefined' && navigator.userAgent) ?
9648 navigator.userAgent.toLowerCase() : '';
9649 let isIE = ua.indexOf('msie') !== -1;
9650 let isTrident = ua.indexOf('trident') !== -1;
9651 let isEdge = ua.indexOf('edge') !== -1;
9652 let isGET = !('method' in opts) || opts.method === 'GET';
9653 return (isIE || isTrident || isEdge) && isGET;
9654}
9655
9656// Implements the PouchDB API for dealing with CouchDB instances over HTTP
9657function HttpPouch(opts, callback) {
9658
9659 // The functions that will be publicly available for HttpPouch
9660 let api = this;
9661
9662 let host = getHost(opts.name, opts);
9663 let dbUrl = genDBUrl(host, '');
9664
9665 opts = clone(opts);
9666
9667 const ourFetch = async function (url, options) {
9668
9669 options = options || {};
9670 options.headers = options.headers || new h();
9671
9672 options.credentials = 'include';
9673
9674 if (opts.auth || host.auth) {
9675 let nAuth = opts.auth || host.auth;
9676 let str = nAuth.username + ':' + nAuth.password;
9677 let token = thisBtoa(unescape(encodeURIComponent(str)));
9678 options.headers.set('Authorization', 'Basic ' + token);
9679 }
9680
9681 let headers = opts.headers || {};
9682 Object.keys(headers).forEach(function (key) {
9683 options.headers.append(key, headers[key]);
9684 });
9685
9686 /* istanbul ignore if */
9687 if (shouldCacheBust(options)) {
9688 url += (url.indexOf('?') === -1 ? '?' : '&') + '_nonce=' + Date.now();
9689 }
9690
9691 let fetchFun = opts.fetch || f$1;
9692 return await fetchFun(url, options);
9693 };
9694
9695 function adapterFun$$1(name, fun) {
9696 return adapterFun(name, function (...args) {
9697 setup().then(function () {
9698 return fun.apply(this, args);
9699 })["catch"](function (e) {
9700 let callback = args.pop();
9701 callback(e);
9702 });
9703 }).bind(api);
9704 }
9705
9706 async function fetchJSON(url, options) {
9707
9708 let result = {};
9709
9710 options = options || {};
9711 options.headers = options.headers || new h();
9712
9713 if (!options.headers.get('Content-Type')) {
9714 options.headers.set('Content-Type', 'application/json');
9715 }
9716 if (!options.headers.get('Accept')) {
9717 options.headers.set('Accept', 'application/json');
9718 }
9719
9720 const response = await ourFetch(url, options);
9721 result.ok = response.ok;
9722 result.status = response.status;
9723 const json = await response.json();
9724
9725 result.data = json;
9726 if (!result.ok) {
9727 result.data.status = result.status;
9728 let err = generateErrorFromResponse(result.data);
9729 throw err;
9730 }
9731
9732 if (Array.isArray(result.data)) {
9733 result.data = result.data.map(function (v) {
9734 if (v.error || v.missing) {
9735 return generateErrorFromResponse(v);
9736 } else {
9737 return v;
9738 }
9739 });
9740 }
9741
9742 return result;
9743 }
9744
9745 let setupPromise;
9746
9747 async function setup() {
9748 if (opts.skip_setup) {
9749 return Promise.resolve();
9750 }
9751
9752 // If there is a setup in process or previous successful setup
9753 // done then we will use that
9754 // If previous setups have been rejected we will try again
9755 if (setupPromise) {
9756 return setupPromise;
9757 }
9758
9759 setupPromise = fetchJSON(dbUrl)["catch"](function (err) {
9760 if (err && err.status && err.status === 404) {
9761 // Doesnt exist, create it
9762 explainError(404, 'PouchDB is just detecting if the remote exists.');
9763 return fetchJSON(dbUrl, {method: 'PUT'});
9764 } else {
9765 return Promise.reject(err);
9766 }
9767 })["catch"](function (err) {
9768 // If we try to create a database that already exists, skipped in
9769 // istanbul since its catching a race condition.
9770 /* istanbul ignore if */
9771 if (err && err.status && err.status === 412) {
9772 return true;
9773 }
9774 return Promise.reject(err);
9775 });
9776
9777 setupPromise["catch"](function () {
9778 setupPromise = null;
9779 });
9780
9781 return setupPromise;
9782 }
9783
9784 immediate(function () {
9785 callback(null, api);
9786 });
9787
9788 api._remote = true;
9789
9790 /* istanbul ignore next */
9791 api.type = function () {
9792 return 'http';
9793 };
9794
9795 api.id = adapterFun$$1('id', async function (callback) {
9796 let result;
9797 try {
9798 const response = await ourFetch(genUrl(host, ''));
9799 result = await response.json();
9800 } catch (err) {
9801 result = {};
9802 }
9803
9804 // Bad response or missing `uuid` should not prevent ID generation.
9805 let uuid$$1 = (result && result.uuid) ? (result.uuid + host.db) : genDBUrl(host, '');
9806 callback(null, uuid$$1);
9807 });
9808
9809 // Sends a POST request to the host calling the couchdb _compact function
9810 // version: The version of CouchDB it is running
9811 api.compact = adapterFun$$1('compact', async function (opts, callback) {
9812 if (typeof opts === 'function') {
9813 callback = opts;
9814 opts = {};
9815 }
9816 opts = clone(opts);
9817
9818 await fetchJSON(genDBUrl(host, '_compact'), {method: 'POST'});
9819
9820 function ping() {
9821 api.info(function (err, res) {
9822 // CouchDB may send a "compact_running:true" if it's
9823 // already compacting. PouchDB Server doesn't.
9824 /* istanbul ignore else */
9825 if (res && !res.compact_running) {
9826 callback(null, {ok: true});
9827 } else {
9828 setTimeout(ping, opts.interval || 200);
9829 }
9830 });
9831 }
9832 // Ping the http if it's finished compaction
9833 ping();
9834 });
9835
9836 api.bulkGet = adapterFun('bulkGet', function (opts, callback) {
9837 let self = this;
9838
9839 async function doBulkGet(cb) {
9840 let params = {};
9841 if (opts.revs) {
9842 params.revs = true;
9843 }
9844 if (opts.attachments) {
9845 /* istanbul ignore next */
9846 params.attachments = true;
9847 }
9848 if (opts.latest) {
9849 params.latest = true;
9850 }
9851 try {
9852 const result = await fetchJSON(genDBUrl(host, '_bulk_get' + paramsToStr(params)), {
9853 method: 'POST',
9854 body: JSON.stringify({ docs: opts.docs})
9855 });
9856
9857 if (opts.attachments && opts.binary) {
9858 result.data.results.forEach(function (res) {
9859 res.docs.forEach(readAttachmentsAsBlobOrBuffer);
9860 });
9861 }
9862 cb(null, result.data);
9863 } catch (error) {
9864 cb(error);
9865 }
9866 }
9867
9868 /* istanbul ignore next */
9869 function doBulkGetShim() {
9870 // avoid "url too long error" by splitting up into multiple requests
9871 let batchSize = MAX_SIMULTANEOUS_REVS;
9872 let numBatches = Math.ceil(opts.docs.length / batchSize);
9873 let numDone = 0;
9874 let results = new Array(numBatches);
9875
9876 function onResult(batchNum) {
9877 return function (err, res) {
9878 // err is impossible because shim returns a list of errs in that case
9879 results[batchNum] = res.results;
9880 if (++numDone === numBatches) {
9881 callback(null, {results: flatten(results)});
9882 }
9883 };
9884 }
9885
9886 for (let i = 0; i < numBatches; i++) {
9887 let subOpts = pick(opts, ['revs', 'attachments', 'binary', 'latest']);
9888 subOpts.docs = opts.docs.slice(i * batchSize,
9889 Math.min(opts.docs.length, (i + 1) * batchSize));
9890 bulkGet(self, subOpts, onResult(i));
9891 }
9892 }
9893
9894 // mark the whole database as either supporting or not supporting _bulk_get
9895 let dbUrl = genUrl(host, '');
9896 let supportsBulkGet = supportsBulkGetMap[dbUrl];
9897
9898 /* istanbul ignore next */
9899 if (typeof supportsBulkGet !== 'boolean') {
9900 // check if this database supports _bulk_get
9901 doBulkGet(function (err, res) {
9902 if (err) {
9903 supportsBulkGetMap[dbUrl] = false;
9904 explainError(
9905 err.status,
9906 'PouchDB is just detecting if the remote ' +
9907 'supports the _bulk_get API.'
9908 );
9909 doBulkGetShim();
9910 } else {
9911 supportsBulkGetMap[dbUrl] = true;
9912 callback(null, res);
9913 }
9914 });
9915 } else if (supportsBulkGet) {
9916 doBulkGet(callback);
9917 } else {
9918 doBulkGetShim();
9919 }
9920 });
9921
9922 // Calls GET on the host, which gets back a JSON string containing
9923 // couchdb: A welcome string
9924 // version: The version of CouchDB it is running
9925 api._info = async function (callback) {
9926 try {
9927 await setup();
9928 const response = await ourFetch(genDBUrl(host, ''));
9929 const info = await response.json();
9930 info.host = genDBUrl(host, '');
9931 callback(null, info);
9932 } catch (err) {
9933 callback(err);
9934 }
9935 };
9936
9937 api.fetch = async function (path, options) {
9938 await setup();
9939 const url = path.substring(0, 1) === '/' ?
9940 genUrl(host, path.substring(1)) :
9941 genDBUrl(host, path);
9942 return ourFetch(url, options);
9943 };
9944
9945 // Get the document with the given id from the database given by host.
9946 // The id could be solely the _id in the database, or it may be a
9947 // _design/ID or _local/ID path
9948 api.get = adapterFun$$1('get', async function (id, opts, callback) {
9949 // If no options were given, set the callback to the second parameter
9950 if (typeof opts === 'function') {
9951 callback = opts;
9952 opts = {};
9953 }
9954 opts = clone(opts);
9955
9956 // List of parameters to add to the GET request
9957 let params = {};
9958
9959 if (opts.revs) {
9960 params.revs = true;
9961 }
9962
9963 if (opts.revs_info) {
9964 params.revs_info = true;
9965 }
9966
9967 if (opts.latest) {
9968 params.latest = true;
9969 }
9970
9971 if (opts.open_revs) {
9972 if (opts.open_revs !== "all") {
9973 opts.open_revs = JSON.stringify(opts.open_revs);
9974 }
9975 params.open_revs = opts.open_revs;
9976 }
9977
9978 if (opts.rev) {
9979 params.rev = opts.rev;
9980 }
9981
9982 if (opts.conflicts) {
9983 params.conflicts = opts.conflicts;
9984 }
9985
9986 /* istanbul ignore if */
9987 if (opts.update_seq) {
9988 params.update_seq = opts.update_seq;
9989 }
9990
9991 id = encodeDocId(id);
9992
9993 function fetchAttachments(doc) {
9994 let atts = doc._attachments;
9995 let filenames = atts && Object.keys(atts);
9996 if (!atts || !filenames.length) {
9997 return;
9998 }
9999 // we fetch these manually in separate XHRs, because
10000 // Sync Gateway would normally send it back as multipart/mixed,
10001 // which we cannot parse. Also, this is more efficient than
10002 // receiving attachments as base64-encoded strings.
10003 async function fetchData(filename) {
10004 const att = atts[filename];
10005 const path = encodeDocId(doc._id) + '/' + encodeAttachmentId(filename) +
10006 '?rev=' + doc._rev;
10007
10008 const response = await ourFetch(genDBUrl(host, path));
10009
10010 let blob;
10011 if ('buffer' in response) {
10012 blob = await response.buffer();
10013 } else {
10014 /* istanbul ignore next */
10015 blob = await response.blob();
10016 }
10017
10018 let data;
10019 if (opts.binary) {
10020 let typeFieldDescriptor = Object.getOwnPropertyDescriptor(blob.__proto__, 'type');
10021 if (!typeFieldDescriptor || typeFieldDescriptor.set) {
10022 blob.type = att.content_type;
10023 }
10024 data = blob;
10025 } else {
10026 data = await new Promise(function (resolve) {
10027 blobToBase64(blob, resolve);
10028 });
10029 }
10030
10031 delete att.stub;
10032 delete att.length;
10033 att.data = data;
10034 }
10035
10036 let promiseFactories = filenames.map(function (filename) {
10037 return function () {
10038 return fetchData(filename);
10039 };
10040 });
10041
10042 // This limits the number of parallel xhr requests to 5 any time
10043 // to avoid issues with maximum browser request limits
10044 return pool(promiseFactories, 5);
10045 }
10046
10047 function fetchAllAttachments(docOrDocs) {
10048 if (Array.isArray(docOrDocs)) {
10049 return Promise.all(docOrDocs.map(function (doc) {
10050 if (doc.ok) {
10051 return fetchAttachments(doc.ok);
10052 }
10053 }));
10054 }
10055 return fetchAttachments(docOrDocs);
10056 }
10057
10058 const url = genDBUrl(host, id + paramsToStr(params));
10059 try {
10060 const res = await fetchJSON(url);
10061 if (opts.attachments) {
10062 await fetchAllAttachments(res.data);
10063 }
10064 callback(null, res.data);
10065 } catch (error) {
10066 error.docId = id;
10067 callback(error);
10068 }
10069 });
10070
10071
10072 // Delete the document given by doc from the database given by host.
10073 api.remove = adapterFun$$1('remove', async function (docOrId, optsOrRev, opts, cb) {
10074 let doc;
10075 if (typeof optsOrRev === 'string') {
10076 // id, rev, opts, callback style
10077 doc = {
10078 _id: docOrId,
10079 _rev: optsOrRev
10080 };
10081 if (typeof opts === 'function') {
10082 cb = opts;
10083 opts = {};
10084 }
10085 } else {
10086 // doc, opts, callback style
10087 doc = docOrId;
10088 if (typeof optsOrRev === 'function') {
10089 cb = optsOrRev;
10090 opts = {};
10091 } else {
10092 cb = opts;
10093 opts = optsOrRev;
10094 }
10095 }
10096
10097 const rev = (doc._rev || opts.rev);
10098 const url = genDBUrl(host, encodeDocId(doc._id)) + '?rev=' + rev;
10099
10100 try {
10101 const result = await fetchJSON(url, {method: 'DELETE'});
10102 cb(null, result.data);
10103 } catch (error) {
10104 cb(error);
10105 }
10106 });
10107
10108 function encodeAttachmentId(attachmentId) {
10109 return attachmentId.split("/").map(encodeURIComponent).join("/");
10110 }
10111
10112 // Get the attachment
10113 api.getAttachment = adapterFun$$1('getAttachment', async function (docId, attachmentId,
10114 opts, callback) {
10115 if (typeof opts === 'function') {
10116 callback = opts;
10117 opts = {};
10118 }
10119 const params = opts.rev ? ('?rev=' + opts.rev) : '';
10120 const url = genDBUrl(host, encodeDocId(docId)) + '/' +
10121 encodeAttachmentId(attachmentId) + params;
10122 let contentType;
10123 try {
10124 const response = await ourFetch(url, {method: 'GET'});
10125
10126 if (!response.ok) {
10127 throw response;
10128 }
10129
10130 contentType = response.headers.get('content-type');
10131 let blob;
10132 if (typeof process !== 'undefined' && !process.browser && typeof response.buffer === 'function') {
10133 blob = await response.buffer();
10134 } else {
10135 /* istanbul ignore next */
10136 blob = await response.blob();
10137 }
10138
10139 // TODO: also remove
10140 if (typeof process !== 'undefined' && !process.browser) {
10141 var typeFieldDescriptor = Object.getOwnPropertyDescriptor(blob.__proto__, 'type');
10142 if (!typeFieldDescriptor || typeFieldDescriptor.set) {
10143 blob.type = contentType;
10144 }
10145 }
10146 callback(null, blob);
10147 } catch (err) {
10148 callback(err);
10149 }
10150 });
10151
10152 // Remove the attachment given by the id and rev
10153 api.removeAttachment = adapterFun$$1('removeAttachment', async function (
10154 docId,
10155 attachmentId,
10156 rev,
10157 callback,
10158 ) {
10159 const url = genDBUrl(host, encodeDocId(docId) + '/' + encodeAttachmentId(attachmentId)) + '?rev=' + rev;
10160
10161 try {
10162 const result = await fetchJSON(url, {method: 'DELETE'});
10163 callback(null, result.data);
10164 } catch (error) {
10165 callback(error);
10166 }
10167 });
10168
10169 // Add the attachment given by blob and its contentType property
10170 // to the document with the given id, the revision given by rev, and
10171 // add it to the database given by host.
10172 api.putAttachment = adapterFun$$1('putAttachment', async function (
10173 docId,
10174 attachmentId,
10175 rev,
10176 blob,
10177 type,
10178 callback,
10179 ) {
10180 if (typeof type === 'function') {
10181 callback = type;
10182 type = blob;
10183 blob = rev;
10184 rev = null;
10185 }
10186 const id = encodeDocId(docId) + '/' + encodeAttachmentId(attachmentId);
10187 let url = genDBUrl(host, id);
10188 if (rev) {
10189 url += '?rev=' + rev;
10190 }
10191
10192 if (typeof blob === 'string') {
10193 // input is assumed to be a base64 string
10194 let binary;
10195 try {
10196 binary = thisAtob(blob);
10197 } catch (err) {
10198 return callback(createError(BAD_ARG,
10199 'Attachment is not a valid base64 string'));
10200 }
10201 blob = binary ? binStringToBluffer(binary, type) : '';
10202 }
10203
10204 try {
10205 // Add the attachment
10206 const result = await fetchJSON(url, {
10207 headers: new h({'Content-Type': type}),
10208 method: 'PUT',
10209 body: blob
10210 });
10211 callback(null, result.data);
10212 } catch (error) {
10213 callback(error);
10214 }
10215 });
10216
10217 // Update/create multiple documents given by req in the database
10218 // given by host.
10219 api._bulkDocs = async function (req, opts, callback) {
10220 // If new_edits=false then it prevents the database from creating
10221 // new revision numbers for the documents. Instead it just uses
10222 // the old ones. This is used in database replication.
10223 req.new_edits = opts.new_edits;
10224
10225 try {
10226 await setup();
10227 await Promise.all(req.docs.map(preprocessAttachments$1));
10228
10229 // Update/create the documents
10230 const result = await fetchJSON(genDBUrl(host, '_bulk_docs'), {
10231 method: 'POST',
10232 body: JSON.stringify(req)
10233 });
10234 callback(null, result.data);
10235 } catch (error) {
10236 callback(error);
10237 }
10238 };
10239
10240 // Update/create document
10241 api._put = async function (doc, opts, callback) {
10242 try {
10243 await setup();
10244 await preprocessAttachments$1(doc);
10245
10246 const result = await fetchJSON(genDBUrl(host, encodeDocId(doc._id)), {
10247 method: 'PUT',
10248 body: JSON.stringify(doc)
10249 });
10250 callback(null, result.data);
10251 } catch (error) {
10252 error.docId = doc && doc._id;
10253 callback(error);
10254 }
10255 };
10256
10257
10258 // Get a listing of the documents in the database given
10259 // by host and ordered by increasing id.
10260 api.allDocs = adapterFun$$1('allDocs', async function (opts, callback) {
10261 if (typeof opts === 'function') {
10262 callback = opts;
10263 opts = {};
10264 }
10265 opts = clone(opts);
10266
10267 // List of parameters to add to the GET request
10268 let params = {};
10269 let body;
10270 let method = 'GET';
10271
10272 if (opts.conflicts) {
10273 params.conflicts = true;
10274 }
10275
10276 /* istanbul ignore if */
10277 if (opts.update_seq) {
10278 params.update_seq = true;
10279 }
10280
10281 if (opts.descending) {
10282 params.descending = true;
10283 }
10284
10285 if (opts.include_docs) {
10286 params.include_docs = true;
10287 }
10288
10289 // added in CouchDB 1.6.0
10290 if (opts.attachments) {
10291 params.attachments = true;
10292 }
10293
10294 if (opts.key) {
10295 params.key = JSON.stringify(opts.key);
10296 }
10297
10298 if (opts.start_key) {
10299 opts.startkey = opts.start_key;
10300 }
10301
10302 if (opts.startkey) {
10303 params.startkey = JSON.stringify(opts.startkey);
10304 }
10305
10306 if (opts.end_key) {
10307 opts.endkey = opts.end_key;
10308 }
10309
10310 if (opts.endkey) {
10311 params.endkey = JSON.stringify(opts.endkey);
10312 }
10313
10314 if (typeof opts.inclusive_end !== 'undefined') {
10315 params.inclusive_end = !!opts.inclusive_end;
10316 }
10317
10318 if (typeof opts.limit !== 'undefined') {
10319 params.limit = opts.limit;
10320 }
10321
10322 if (typeof opts.skip !== 'undefined') {
10323 params.skip = opts.skip;
10324 }
10325
10326 let paramStr = paramsToStr(params);
10327
10328 if (typeof opts.keys !== 'undefined') {
10329 method = 'POST';
10330 body = {keys: opts.keys};
10331 }
10332
10333 try {
10334 const result = await fetchJSON(genDBUrl(host, '_all_docs' + paramStr), {
10335 method: method,
10336 body: JSON.stringify(body)
10337 });
10338 if (opts.include_docs && opts.attachments && opts.binary) {
10339 result.data.rows.forEach(readAttachmentsAsBlobOrBuffer);
10340 }
10341 callback(null, result.data);
10342 } catch (error) {
10343 callback(error);
10344 }
10345 });
10346
10347 // Get a list of changes made to documents in the database given by host.
10348 // TODO According to the README, there should be two other methods here,
10349 // api.changes.addListener and api.changes.removeListener.
10350 api._changes = function (opts) {
10351
10352 // We internally page the results of a changes request, this means
10353 // if there is a large set of changes to be returned we can start
10354 // processing them quicker instead of waiting on the entire
10355 // set of changes to return and attempting to process them at once
10356 let batchSize = 'batch_size' in opts ? opts.batch_size : CHANGES_BATCH_SIZE;
10357
10358 opts = clone(opts);
10359
10360 if (opts.continuous && !('heartbeat' in opts)) {
10361 opts.heartbeat = DEFAULT_HEARTBEAT;
10362 }
10363
10364 let requestTimeout = ('timeout' in opts) ? opts.timeout : 30 * 1000;
10365
10366 // ensure CHANGES_TIMEOUT_BUFFER applies
10367 if ('timeout' in opts && opts.timeout &&
10368 (requestTimeout - opts.timeout) < CHANGES_TIMEOUT_BUFFER) {
10369 requestTimeout = opts.timeout + CHANGES_TIMEOUT_BUFFER;
10370 }
10371
10372 /* istanbul ignore if */
10373 if ('heartbeat' in opts && opts.heartbeat &&
10374 (requestTimeout - opts.heartbeat) < CHANGES_TIMEOUT_BUFFER) {
10375 requestTimeout = opts.heartbeat + CHANGES_TIMEOUT_BUFFER;
10376 }
10377
10378 let params = {};
10379 if ('timeout' in opts && opts.timeout) {
10380 params.timeout = opts.timeout;
10381 }
10382
10383 let limit = (typeof opts.limit !== 'undefined') ? opts.limit : false;
10384 let leftToFetch = limit;
10385
10386 if (opts.style) {
10387 params.style = opts.style;
10388 }
10389
10390 if (opts.include_docs || opts.filter && typeof opts.filter === 'function') {
10391 params.include_docs = true;
10392 }
10393
10394 if (opts.attachments) {
10395 params.attachments = true;
10396 }
10397
10398 if (opts.continuous) {
10399 params.feed = 'longpoll';
10400 }
10401
10402 if (opts.seq_interval) {
10403 params.seq_interval = opts.seq_interval;
10404 }
10405
10406 if (opts.conflicts) {
10407 params.conflicts = true;
10408 }
10409
10410 if (opts.descending) {
10411 params.descending = true;
10412 }
10413
10414 /* istanbul ignore if */
10415 if (opts.update_seq) {
10416 params.update_seq = true;
10417 }
10418
10419 if ('heartbeat' in opts) {
10420 // If the heartbeat value is false, it disables the default heartbeat
10421 if (opts.heartbeat) {
10422 params.heartbeat = opts.heartbeat;
10423 }
10424 }
10425
10426 if (opts.filter && typeof opts.filter === 'string') {
10427 params.filter = opts.filter;
10428 }
10429
10430 if (opts.view && typeof opts.view === 'string') {
10431 params.filter = '_view';
10432 params.view = opts.view;
10433 }
10434
10435 // If opts.query_params exists, pass it through to the changes request.
10436 // These parameters may be used by the filter on the source database.
10437 if (opts.query_params && typeof opts.query_params === 'object') {
10438 for (let param_name in opts.query_params) {
10439 /* istanbul ignore else */
10440 if (Object.prototype.hasOwnProperty.call(opts.query_params, param_name)) {
10441 params[param_name] = opts.query_params[param_name];
10442 }
10443 }
10444 }
10445
10446 let method = 'GET';
10447 let body;
10448
10449 if (opts.doc_ids) {
10450 // set this automagically for the user; it's annoying that couchdb
10451 // requires both a "filter" and a "doc_ids" param.
10452 params.filter = '_doc_ids';
10453 method = 'POST';
10454 body = {doc_ids: opts.doc_ids };
10455 }
10456 /* istanbul ignore next */
10457 else if (opts.selector) {
10458 // set this automagically for the user, similar to above
10459 params.filter = '_selector';
10460 method = 'POST';
10461 body = {selector: opts.selector };
10462 }
10463
10464 let controller = new a();
10465 let lastFetchedSeq;
10466
10467 // Get all the changes starting wtih the one immediately after the
10468 // sequence number given by since.
10469 const fetchData = async function (since, callback) {
10470 if (opts.aborted) {
10471 return;
10472 }
10473 params.since = since;
10474 // "since" can be any kind of json object in Cloudant/CouchDB 2.x
10475 /* istanbul ignore next */
10476 if (typeof params.since === "object") {
10477 params.since = JSON.stringify(params.since);
10478 }
10479
10480 if (opts.descending) {
10481 if (limit) {
10482 params.limit = leftToFetch;
10483 }
10484 } else {
10485 params.limit = (!limit || leftToFetch > batchSize) ?
10486 batchSize : leftToFetch;
10487 }
10488
10489 // Set the options for the ajax call
10490 let url = genDBUrl(host, '_changes' + paramsToStr(params));
10491 let fetchOpts = {
10492 signal: controller.signal,
10493 method: method,
10494 body: JSON.stringify(body)
10495 };
10496 lastFetchedSeq = since;
10497
10498 /* istanbul ignore if */
10499 if (opts.aborted) {
10500 return;
10501 }
10502
10503 // Get the changes
10504 try {
10505 await setup();
10506 const result = await fetchJSON(url, fetchOpts);
10507 callback(null, result.data);
10508 } catch (error) {
10509 callback(error);
10510 }
10511 };
10512
10513 // If opts.since exists, get all the changes from the sequence
10514 // number given by opts.since. Otherwise, get all the changes
10515 // from the sequence number 0.
10516 let results = {results: []};
10517
10518 const fetched = function (err, res) {
10519 if (opts.aborted) {
10520 return;
10521 }
10522 let raw_results_length = 0;
10523 // If the result of the ajax call (res) contains changes (res.results)
10524 if (res && res.results) {
10525 raw_results_length = res.results.length;
10526 results.last_seq = res.last_seq;
10527 let pending = null;
10528 let lastSeq = null;
10529 // Attach 'pending' property if server supports it (CouchDB 2.0+)
10530 /* istanbul ignore if */
10531 if (typeof res.pending === 'number') {
10532 pending = res.pending;
10533 }
10534 if (typeof results.last_seq === 'string' || typeof results.last_seq === 'number') {
10535 lastSeq = results.last_seq;
10536 }
10537 // For each change
10538 let req = {};
10539 req.query = opts.query_params;
10540 res.results = res.results.filter(function (c) {
10541 leftToFetch--;
10542 let ret = filterChange(opts)(c);
10543 if (ret) {
10544 if (opts.include_docs && opts.attachments && opts.binary) {
10545 readAttachmentsAsBlobOrBuffer(c);
10546 }
10547 if (opts.return_docs) {
10548 results.results.push(c);
10549 }
10550 opts.onChange(c, pending, lastSeq);
10551 }
10552 return ret;
10553 });
10554 } else if (err) {
10555 // In case of an error, stop listening for changes and call
10556 // opts.complete
10557 opts.aborted = true;
10558 opts.complete(err);
10559 return;
10560 }
10561
10562 // The changes feed may have timed out with no results
10563 // if so reuse last update sequence
10564 if (res && res.last_seq) {
10565 lastFetchedSeq = res.last_seq;
10566 }
10567
10568 let finished = (limit && leftToFetch <= 0) ||
10569 (res && raw_results_length < batchSize) ||
10570 (opts.descending);
10571
10572 if ((opts.continuous && !(limit && leftToFetch <= 0)) || !finished) {
10573 // Queue a call to fetch again with the newest sequence number
10574 immediate(function () { fetchData(lastFetchedSeq, fetched); });
10575 } else {
10576 // We're done, call the callback
10577 opts.complete(null, results);
10578 }
10579 };
10580
10581 fetchData(opts.since || 0, fetched);
10582
10583 // Return a method to cancel this method from processing any more
10584 return {
10585 cancel: function () {
10586 opts.aborted = true;
10587 controller.abort();
10588 }
10589 };
10590 };
10591
10592 // Given a set of document/revision IDs (given by req), tets the subset of
10593 // those that do NOT correspond to revisions stored in the database.
10594 // See http://wiki.apache.org/couchdb/HttpPostRevsDiff
10595 api.revsDiff = adapterFun$$1('revsDiff', async function (req, opts, callback) {
10596 // If no options were given, set the callback to be the second parameter
10597 if (typeof opts === 'function') {
10598 callback = opts;
10599 opts = {};
10600 }
10601
10602 try {
10603 // Get the missing document/revision IDs
10604 const result = await fetchJSON(genDBUrl(host, '_revs_diff'), {
10605 method: 'POST',
10606 body: JSON.stringify(req)
10607 });
10608 callback(null, result.data);
10609 } catch (error) {
10610 callback(error);
10611 }
10612 });
10613
10614 api._close = function (callback) {
10615 callback();
10616 };
10617
10618 api._destroy = async function (options, callback) {
10619 try {
10620 const json = await fetchJSON(genDBUrl(host, ''), {method: 'DELETE'});
10621 callback(null, json);
10622 } catch (error) {
10623 if (error.status === 404) {
10624 callback(null, {ok: true});
10625 } else {
10626 callback(error);
10627 }
10628 }
10629 };
10630}
10631
10632// HttpPouch is a valid adapter.
10633HttpPouch.valid = function () {
10634 return true;
10635};
10636
10637function HttpPouch$1 (PouchDB) {
10638 PouchDB.adapter('http', HttpPouch, false);
10639 PouchDB.adapter('https', HttpPouch, false);
10640}
10641
10642class QueryParseError extends Error {
10643 constructor(message) {
10644 super();
10645 this.status = 400;
10646 this.name = 'query_parse_error';
10647 this.message = message;
10648 this.error = true;
10649 try {
10650 Error.captureStackTrace(this, QueryParseError);
10651 } catch (e) {}
10652 }
10653}
10654
10655class NotFoundError extends Error {
10656 constructor(message) {
10657 super();
10658 this.status = 404;
10659 this.name = 'not_found';
10660 this.message = message;
10661 this.error = true;
10662 try {
10663 Error.captureStackTrace(this, NotFoundError);
10664 } catch (e) {}
10665 }
10666}
10667
10668class BuiltInError extends Error {
10669 constructor(message) {
10670 super();
10671 this.status = 500;
10672 this.name = 'invalid_value';
10673 this.message = message;
10674 this.error = true;
10675 try {
10676 Error.captureStackTrace(this, BuiltInError);
10677 } catch (e) {}
10678 }
10679}
10680
10681function promisedCallback(promise, callback) {
10682 if (callback) {
10683 promise.then(function (res) {
10684 immediate(function () {
10685 callback(null, res);
10686 });
10687 }, function (reason) {
10688 immediate(function () {
10689 callback(reason);
10690 });
10691 });
10692 }
10693 return promise;
10694}
10695
10696function callbackify(fun) {
10697 return function (...args) {
10698 var cb = args.pop();
10699 var promise = fun.apply(this, args);
10700 if (typeof cb === 'function') {
10701 promisedCallback(promise, cb);
10702 }
10703 return promise;
10704 };
10705}
10706
10707// Promise finally util similar to Q.finally
10708function fin(promise, finalPromiseFactory) {
10709 return promise.then(function (res) {
10710 return finalPromiseFactory().then(function () {
10711 return res;
10712 });
10713 }, function (reason) {
10714 return finalPromiseFactory().then(function () {
10715 throw reason;
10716 });
10717 });
10718}
10719
10720function sequentialize(queue, promiseFactory) {
10721 return function () {
10722 var args = arguments;
10723 var that = this;
10724 return queue.add(function () {
10725 return promiseFactory.apply(that, args);
10726 });
10727 };
10728}
10729
10730// uniq an array of strings, order not guaranteed
10731// similar to underscore/lodash _.uniq
10732function uniq(arr) {
10733 var theSet = new ExportedSet(arr);
10734 var result = new Array(theSet.size);
10735 var index = -1;
10736 theSet.forEach(function (value) {
10737 result[++index] = value;
10738 });
10739 return result;
10740}
10741
10742function mapToKeysArray(map) {
10743 var result = new Array(map.size);
10744 var index = -1;
10745 map.forEach(function (value, key) {
10746 result[++index] = key;
10747 });
10748 return result;
10749}
10750
10751function createBuiltInError(name) {
10752 var message = 'builtin ' + name +
10753 ' function requires map values to be numbers' +
10754 ' or number arrays';
10755 return new BuiltInError(message);
10756}
10757
10758function sum(values) {
10759 var result = 0;
10760 for (var i = 0, len = values.length; i < len; i++) {
10761 var num = values[i];
10762 if (typeof num !== 'number') {
10763 if (Array.isArray(num)) {
10764 // lists of numbers are also allowed, sum them separately
10765 result = typeof result === 'number' ? [result] : result;
10766 for (var j = 0, jLen = num.length; j < jLen; j++) {
10767 var jNum = num[j];
10768 if (typeof jNum !== 'number') {
10769 throw createBuiltInError('_sum');
10770 } else if (typeof result[j] === 'undefined') {
10771 result.push(jNum);
10772 } else {
10773 result[j] += jNum;
10774 }
10775 }
10776 } else { // not array/number
10777 throw createBuiltInError('_sum');
10778 }
10779 } else if (typeof result === 'number') {
10780 result += num;
10781 } else { // add number to array
10782 result[0] += num;
10783 }
10784 }
10785 return result;
10786}
10787
10788var log = guardedConsole.bind(null, 'log');
10789var isArray = Array.isArray;
10790var toJSON = JSON.parse;
10791
10792function evalFunctionWithEval(func, emit) {
10793 return scopeEval(
10794 "return (" + func.replace(/;\s*$/, "") + ");",
10795 {
10796 emit: emit,
10797 sum: sum,
10798 log: log,
10799 isArray: isArray,
10800 toJSON: toJSON
10801 }
10802 );
10803}
10804
10805/*
10806 * Simple task queue to sequentialize actions. Assumes
10807 * callbacks will eventually fire (once).
10808 */
10809
10810
10811class TaskQueue$1 {
10812 constructor() {
10813 this.promise = new Promise(function (fulfill) {fulfill(); });
10814 }
10815
10816 add(promiseFactory) {
10817 this.promise = this.promise["catch"](function () {
10818 // just recover
10819 }).then(function () {
10820 return promiseFactory();
10821 });
10822 return this.promise;
10823 }
10824
10825 finish() {
10826 return this.promise;
10827 }
10828}
10829
10830function stringify(input) {
10831 if (!input) {
10832 return 'undefined'; // backwards compat for empty reduce
10833 }
10834 // for backwards compat with mapreduce, functions/strings are stringified
10835 // as-is. everything else is JSON-stringified.
10836 switch (typeof input) {
10837 case 'function':
10838 // e.g. a mapreduce map
10839 return input.toString();
10840 case 'string':
10841 // e.g. a mapreduce built-in _reduce function
10842 return input.toString();
10843 default:
10844 // e.g. a JSON object in the case of mango queries
10845 return JSON.stringify(input);
10846 }
10847}
10848
10849/* create a string signature for a view so we can cache it and uniq it */
10850function createViewSignature(mapFun, reduceFun) {
10851 // the "undefined" part is for backwards compatibility
10852 return stringify(mapFun) + stringify(reduceFun) + 'undefined';
10853}
10854
10855async function createView(sourceDB, viewName, mapFun, reduceFun, temporary, localDocName) {
10856 const viewSignature = createViewSignature(mapFun, reduceFun);
10857
10858 let cachedViews;
10859 if (!temporary) {
10860 // cache this to ensure we don't try to update the same view twice
10861 cachedViews = sourceDB._cachedViews = sourceDB._cachedViews || {};
10862 if (cachedViews[viewSignature]) {
10863 return cachedViews[viewSignature];
10864 }
10865 }
10866
10867 const promiseForView = sourceDB.info().then(async function (info) {
10868 const depDbName = info.db_name + '-mrview-' +
10869 (temporary ? 'temp' : stringMd5(viewSignature));
10870
10871 // save the view name in the source db so it can be cleaned up if necessary
10872 // (e.g. when the _design doc is deleted, remove all associated view data)
10873 function diffFunction(doc) {
10874 doc.views = doc.views || {};
10875 let fullViewName = viewName;
10876 if (fullViewName.indexOf('/') === -1) {
10877 fullViewName = viewName + '/' + viewName;
10878 }
10879 const depDbs = doc.views[fullViewName] = doc.views[fullViewName] || {};
10880 /* istanbul ignore if */
10881 if (depDbs[depDbName]) {
10882 return; // no update necessary
10883 }
10884 depDbs[depDbName] = true;
10885 return doc;
10886 }
10887 await upsert(sourceDB, '_local/' + localDocName, diffFunction);
10888 const res = await sourceDB.registerDependentDatabase(depDbName);
10889 const db = res.db;
10890 db.auto_compaction = true;
10891 const view = {
10892 name: depDbName,
10893 db: db,
10894 sourceDB: sourceDB,
10895 adapter: sourceDB.adapter,
10896 mapFun: mapFun,
10897 reduceFun: reduceFun
10898 };
10899
10900 let lastSeqDoc;
10901 try {
10902 lastSeqDoc = await view.db.get('_local/lastSeq');
10903 } catch (err) {
10904 /* istanbul ignore if */
10905 if (err.status !== 404) {
10906 throw err;
10907 }
10908 }
10909
10910 view.seq = lastSeqDoc ? lastSeqDoc.seq : 0;
10911 if (cachedViews) {
10912 view.db.once('destroyed', function () {
10913 delete cachedViews[viewSignature];
10914 });
10915 }
10916 return view;
10917 });
10918
10919 if (cachedViews) {
10920 cachedViews[viewSignature] = promiseForView;
10921 }
10922 return promiseForView;
10923}
10924
10925var persistentQueues = {};
10926var tempViewQueue = new TaskQueue$1();
10927var CHANGES_BATCH_SIZE$1 = 50;
10928
10929function parseViewName(name) {
10930 // can be either 'ddocname/viewname' or just 'viewname'
10931 // (where the ddoc name is the same)
10932 return name.indexOf('/') === -1 ? [name, name] : name.split('/');
10933}
10934
10935function isGenOne(changes) {
10936 // only return true if the current change is 1-
10937 // and there are no other leafs
10938 return changes.length === 1 && /^1-/.test(changes[0].rev);
10939}
10940
10941function emitError(db, e, data) {
10942 try {
10943 db.emit('error', e);
10944 } catch (err) {
10945 guardedConsole('error',
10946 'The user\'s map/reduce function threw an uncaught error.\n' +
10947 'You can debug this error by doing:\n' +
10948 'myDatabase.on(\'error\', function (err) { debugger; });\n' +
10949 'Please double-check your map/reduce function.');
10950 guardedConsole('error', e, data);
10951 }
10952}
10953
10954/**
10955 * Returns an "abstract" mapreduce object of the form:
10956 *
10957 * {
10958 * query: queryFun,
10959 * viewCleanup: viewCleanupFun
10960 * }
10961 *
10962 * Arguments are:
10963 *
10964 * localDoc: string
10965 * This is for the local doc that gets saved in order to track the
10966 * "dependent" DBs and clean them up for viewCleanup. It should be
10967 * unique, so that indexer plugins don't collide with each other.
10968 * mapper: function (mapFunDef, emit)
10969 * Returns a map function based on the mapFunDef, which in the case of
10970 * normal map/reduce is just the de-stringified function, but may be
10971 * something else, such as an object in the case of pouchdb-find.
10972 * reducer: function (reduceFunDef)
10973 * Ditto, but for reducing. Modules don't have to support reducing
10974 * (e.g. pouchdb-find).
10975 * ddocValidator: function (ddoc, viewName)
10976 * Throws an error if the ddoc or viewName is not valid.
10977 * This could be a way to communicate to the user that the configuration for the
10978 * indexer is invalid.
10979 */
10980function createAbstractMapReduce(localDocName, mapper, reducer, ddocValidator) {
10981
10982 function tryMap(db, fun, doc) {
10983 // emit an event if there was an error thrown by a map function.
10984 // putting try/catches in a single function also avoids deoptimizations.
10985 try {
10986 fun(doc);
10987 } catch (e) {
10988 emitError(db, e, {fun: fun, doc: doc});
10989 }
10990 }
10991
10992 function tryReduce(db, fun, keys, values, rereduce) {
10993 // same as above, but returning the result or an error. there are two separate
10994 // functions to avoid extra memory allocations since the tryCode() case is used
10995 // for custom map functions (common) vs this function, which is only used for
10996 // custom reduce functions (rare)
10997 try {
10998 return {output : fun(keys, values, rereduce)};
10999 } catch (e) {
11000 emitError(db, e, {fun: fun, keys: keys, values: values, rereduce: rereduce});
11001 return {error: e};
11002 }
11003 }
11004
11005 function sortByKeyThenValue(x, y) {
11006 const keyCompare = collate(x.key, y.key);
11007 return keyCompare !== 0 ? keyCompare : collate(x.value, y.value);
11008 }
11009
11010 function sliceResults(results, limit, skip) {
11011 skip = skip || 0;
11012 if (typeof limit === 'number') {
11013 return results.slice(skip, limit + skip);
11014 } else if (skip > 0) {
11015 return results.slice(skip);
11016 }
11017 return results;
11018 }
11019
11020 function rowToDocId(row) {
11021 const val = row.value;
11022 // Users can explicitly specify a joined doc _id, or it
11023 // defaults to the doc _id that emitted the key/value.
11024 const docId = (val && typeof val === 'object' && val._id) || row.id;
11025 return docId;
11026 }
11027
11028 function readAttachmentsAsBlobOrBuffer(res) {
11029 res.rows.forEach(function (row) {
11030 const atts = row.doc && row.doc._attachments;
11031 if (!atts) {
11032 return;
11033 }
11034 Object.keys(atts).forEach(function (filename) {
11035 const att = atts[filename];
11036 atts[filename].data = b64ToBluffer(att.data, att.content_type);
11037 });
11038 });
11039 }
11040
11041 function postprocessAttachments(opts) {
11042 return function (res) {
11043 if (opts.include_docs && opts.attachments && opts.binary) {
11044 readAttachmentsAsBlobOrBuffer(res);
11045 }
11046 return res;
11047 };
11048 }
11049
11050 function addHttpParam(paramName, opts, params, asJson) {
11051 // add an http param from opts to params, optionally json-encoded
11052 let val = opts[paramName];
11053 if (typeof val !== 'undefined') {
11054 if (asJson) {
11055 val = encodeURIComponent(JSON.stringify(val));
11056 }
11057 params.push(paramName + '=' + val);
11058 }
11059 }
11060
11061 function coerceInteger(integerCandidate) {
11062 if (typeof integerCandidate !== 'undefined') {
11063 const asNumber = Number(integerCandidate);
11064 // prevents e.g. '1foo' or '1.1' being coerced to 1
11065 if (!isNaN(asNumber) && asNumber === parseInt(integerCandidate, 10)) {
11066 return asNumber;
11067 } else {
11068 return integerCandidate;
11069 }
11070 }
11071 }
11072
11073 function coerceOptions(opts) {
11074 opts.group_level = coerceInteger(opts.group_level);
11075 opts.limit = coerceInteger(opts.limit);
11076 opts.skip = coerceInteger(opts.skip);
11077 return opts;
11078 }
11079
11080 function checkPositiveInteger(number) {
11081 if (number) {
11082 if (typeof number !== 'number') {
11083 return new QueryParseError(`Invalid value for integer: "${number}"`);
11084 }
11085 if (number < 0) {
11086 return new QueryParseError(`Invalid value for positive integer: "${number}"`);
11087 }
11088 }
11089 }
11090
11091 function checkQueryParseError(options, fun) {
11092 const startkeyName = options.descending ? 'endkey' : 'startkey';
11093 const endkeyName = options.descending ? 'startkey' : 'endkey';
11094
11095 if (typeof options[startkeyName] !== 'undefined' &&
11096 typeof options[endkeyName] !== 'undefined' &&
11097 collate(options[startkeyName], options[endkeyName]) > 0) {
11098 throw new QueryParseError('No rows can match your key range, ' +
11099 'reverse your start_key and end_key or set {descending : true}');
11100 } else if (fun.reduce && options.reduce !== false) {
11101 if (options.include_docs) {
11102 throw new QueryParseError('{include_docs:true} is invalid for reduce');
11103 } else if (options.keys && options.keys.length > 1 &&
11104 !options.group && !options.group_level) {
11105 throw new QueryParseError('Multi-key fetches for reduce views must use ' +
11106 '{group: true}');
11107 }
11108 }
11109 ['group_level', 'limit', 'skip'].forEach(function (optionName) {
11110 const error = checkPositiveInteger(options[optionName]);
11111 if (error) {
11112 throw error;
11113 }
11114 });
11115 }
11116
11117 async function httpQuery(db, fun, opts) {
11118 // List of parameters to add to the PUT request
11119 let params = [];
11120 let body;
11121 let method = 'GET';
11122 let ok;
11123
11124 // If opts.reduce exists and is defined, then add it to the list
11125 // of parameters.
11126 // If reduce=false then the results are that of only the map function
11127 // not the final result of map and reduce.
11128 addHttpParam('reduce', opts, params);
11129 addHttpParam('include_docs', opts, params);
11130 addHttpParam('attachments', opts, params);
11131 addHttpParam('limit', opts, params);
11132 addHttpParam('descending', opts, params);
11133 addHttpParam('group', opts, params);
11134 addHttpParam('group_level', opts, params);
11135 addHttpParam('skip', opts, params);
11136 addHttpParam('stale', opts, params);
11137 addHttpParam('conflicts', opts, params);
11138 addHttpParam('startkey', opts, params, true);
11139 addHttpParam('start_key', opts, params, true);
11140 addHttpParam('endkey', opts, params, true);
11141 addHttpParam('end_key', opts, params, true);
11142 addHttpParam('inclusive_end', opts, params);
11143 addHttpParam('key', opts, params, true);
11144 addHttpParam('update_seq', opts, params);
11145
11146 // Format the list of parameters into a valid URI query string
11147 params = params.join('&');
11148 params = params === '' ? '' : '?' + params;
11149
11150 // If keys are supplied, issue a POST to circumvent GET query string limits
11151 // see http://wiki.apache.org/couchdb/HTTP_view_API#Querying_Options
11152 if (typeof opts.keys !== 'undefined') {
11153 const MAX_URL_LENGTH = 2000;
11154 // according to http://stackoverflow.com/a/417184/680742,
11155 // the de facto URL length limit is 2000 characters
11156
11157 const keysAsString = `keys=${encodeURIComponent(JSON.stringify(opts.keys))}`;
11158 if (keysAsString.length + params.length + 1 <= MAX_URL_LENGTH) {
11159 // If the keys are short enough, do a GET. we do this to work around
11160 // Safari not understanding 304s on POSTs (see pouchdb/pouchdb#1239)
11161 params += (params[0] === '?' ? '&' : '?') + keysAsString;
11162 } else {
11163 method = 'POST';
11164 if (typeof fun === 'string') {
11165 body = {keys: opts.keys};
11166 } else { // fun is {map : mapfun}, so append to this
11167 fun.keys = opts.keys;
11168 }
11169 }
11170 }
11171
11172 // We are referencing a query defined in the design doc
11173 if (typeof fun === 'string') {
11174 const parts = parseViewName(fun);
11175
11176 const response = await db.fetch('_design/' + parts[0] + '/_view/' + parts[1] + params, {
11177 headers: new h({'Content-Type': 'application/json'}),
11178 method: method,
11179 body: JSON.stringify(body)
11180 });
11181 ok = response.ok;
11182 // status = response.status;
11183 const result = await response.json();
11184
11185 if (!ok) {
11186 result.status = response.status;
11187 throw generateErrorFromResponse(result);
11188 }
11189
11190 // fail the entire request if the result contains an error
11191 result.rows.forEach(function (row) {
11192 /* istanbul ignore if */
11193 if (row.value && row.value.error && row.value.error === "builtin_reduce_error") {
11194 throw new Error(row.reason);
11195 }
11196 });
11197
11198 return new Promise(function (resolve) {
11199 resolve(result);
11200 }).then(postprocessAttachments(opts));
11201 }
11202
11203 // We are using a temporary view, terrible for performance, good for testing
11204 body = body || {};
11205 Object.keys(fun).forEach(function (key) {
11206 if (Array.isArray(fun[key])) {
11207 body[key] = fun[key];
11208 } else {
11209 body[key] = fun[key].toString();
11210 }
11211 });
11212
11213 const response = await db.fetch('_temp_view' + params, {
11214 headers: new h({'Content-Type': 'application/json'}),
11215 method: 'POST',
11216 body: JSON.stringify(body)
11217 });
11218
11219 ok = response.ok;
11220 // status = response.status;
11221 const result = await response.json();
11222 if (!ok) {
11223 result.status = response.status;
11224 throw generateErrorFromResponse(result);
11225 }
11226
11227 return new Promise(function (resolve) {
11228 resolve(result);
11229 }).then(postprocessAttachments(opts));
11230 }
11231
11232 // custom adapters can define their own api._query
11233 // and override the default behavior
11234 /* istanbul ignore next */
11235 function customQuery(db, fun, opts) {
11236 return new Promise(function (resolve, reject) {
11237 db._query(fun, opts, function (err, res) {
11238 if (err) {
11239 return reject(err);
11240 }
11241 resolve(res);
11242 });
11243 });
11244 }
11245
11246 // custom adapters can define their own api._viewCleanup
11247 // and override the default behavior
11248 /* istanbul ignore next */
11249 function customViewCleanup(db) {
11250 return new Promise(function (resolve, reject) {
11251 db._viewCleanup(function (err, res) {
11252 if (err) {
11253 return reject(err);
11254 }
11255 resolve(res);
11256 });
11257 });
11258 }
11259
11260 function defaultsTo(value) {
11261 return function (reason) {
11262 /* istanbul ignore else */
11263 if (reason.status === 404) {
11264 return value;
11265 } else {
11266 throw reason;
11267 }
11268 };
11269 }
11270
11271 // returns a promise for a list of docs to update, based on the input docId.
11272 // the order doesn't matter, because post-3.2.0, bulkDocs
11273 // is an atomic operation in all three adapters.
11274 async function getDocsToPersist(docId, view, docIdsToChangesAndEmits) {
11275 const metaDocId = '_local/doc_' + docId;
11276 const defaultMetaDoc = {_id: metaDocId, keys: []};
11277 const docData = docIdsToChangesAndEmits.get(docId);
11278 const indexableKeysToKeyValues = docData[0];
11279 const changes = docData[1];
11280
11281 function getMetaDoc() {
11282 if (isGenOne(changes)) {
11283 // generation 1, so we can safely assume initial state
11284 // for performance reasons (avoids unnecessary GETs)
11285 return Promise.resolve(defaultMetaDoc);
11286 }
11287 return view.db.get(metaDocId)["catch"](defaultsTo(defaultMetaDoc));
11288 }
11289
11290 function getKeyValueDocs(metaDoc) {
11291 if (!metaDoc.keys.length) {
11292 // no keys, no need for a lookup
11293 return Promise.resolve({rows: []});
11294 }
11295 return view.db.allDocs({
11296 keys: metaDoc.keys,
11297 include_docs: true
11298 });
11299 }
11300
11301 function processKeyValueDocs(metaDoc, kvDocsRes) {
11302 const kvDocs = [];
11303 const oldKeys = new ExportedSet();
11304
11305 for (let i = 0, len = kvDocsRes.rows.length; i < len; i++) {
11306 const row = kvDocsRes.rows[i];
11307 const doc = row.doc;
11308 if (!doc) { // deleted
11309 continue;
11310 }
11311 kvDocs.push(doc);
11312 oldKeys.add(doc._id);
11313 doc._deleted = !indexableKeysToKeyValues.has(doc._id);
11314 if (!doc._deleted) {
11315 const keyValue = indexableKeysToKeyValues.get(doc._id);
11316 if ('value' in keyValue) {
11317 doc.value = keyValue.value;
11318 }
11319 }
11320 }
11321 const newKeys = mapToKeysArray(indexableKeysToKeyValues);
11322 newKeys.forEach(function (key) {
11323 if (!oldKeys.has(key)) {
11324 // new doc
11325 const kvDoc = {
11326 _id: key
11327 };
11328 const keyValue = indexableKeysToKeyValues.get(key);
11329 if ('value' in keyValue) {
11330 kvDoc.value = keyValue.value;
11331 }
11332 kvDocs.push(kvDoc);
11333 }
11334 });
11335 metaDoc.keys = uniq(newKeys.concat(metaDoc.keys));
11336 kvDocs.push(metaDoc);
11337
11338 return kvDocs;
11339 }
11340
11341 const metaDoc = await getMetaDoc();
11342 const keyValueDocs = await getKeyValueDocs(metaDoc);
11343 return processKeyValueDocs(metaDoc, keyValueDocs);
11344 }
11345
11346 function updatePurgeSeq(view) {
11347 // with this approach, we just assume to have processed all missing purges and write the latest
11348 // purgeSeq into the _local/purgeSeq doc.
11349 return view.sourceDB.get('_local/purges').then(function (res) {
11350 const purgeSeq = res.purgeSeq;
11351 return view.db.get('_local/purgeSeq').then(function (res) {
11352 return res._rev;
11353 })["catch"](function (err) {
11354 if (err.status !== 404) {
11355 throw err;
11356 }
11357 return undefined;
11358 }).then(function (rev) {
11359 return view.db.put({
11360 _id: '_local/purgeSeq',
11361 _rev: rev,
11362 purgeSeq
11363 });
11364 });
11365 })["catch"](function (err) {
11366 if (err.status !== 404) {
11367 throw err;
11368 }
11369 });
11370 }
11371
11372 // updates all emitted key/value docs and metaDocs in the mrview database
11373 // for the given batch of documents from the source database
11374 function saveKeyValues(view, docIdsToChangesAndEmits, seq) {
11375 var seqDocId = '_local/lastSeq';
11376 return view.db.get(seqDocId)[
11377 "catch"](defaultsTo({_id: seqDocId, seq: 0}))
11378 .then(function (lastSeqDoc) {
11379 var docIds = mapToKeysArray(docIdsToChangesAndEmits);
11380 return Promise.all(docIds.map(function (docId) {
11381 return getDocsToPersist(docId, view, docIdsToChangesAndEmits);
11382 })).then(function (listOfDocsToPersist) {
11383 var docsToPersist = flatten(listOfDocsToPersist);
11384 lastSeqDoc.seq = seq;
11385 docsToPersist.push(lastSeqDoc);
11386 // write all docs in a single operation, update the seq once
11387 return view.db.bulkDocs({docs : docsToPersist});
11388 })
11389 // TODO: this should be placed somewhere else, probably? we're querying both docs twice
11390 // (first time when getting the actual purges).
11391 .then(() => updatePurgeSeq(view));
11392 });
11393 }
11394
11395 function getQueue(view) {
11396 const viewName = typeof view === 'string' ? view : view.name;
11397 let queue = persistentQueues[viewName];
11398 if (!queue) {
11399 queue = persistentQueues[viewName] = new TaskQueue$1();
11400 }
11401 return queue;
11402 }
11403
11404 async function updateView(view, opts) {
11405 return sequentialize(getQueue(view), function () {
11406 return updateViewInQueue(view, opts);
11407 })();
11408 }
11409
11410 async function updateViewInQueue(view, opts) {
11411 // bind the emit function once
11412 let mapResults;
11413 let doc;
11414 let taskId;
11415
11416 function emit(key, value) {
11417 const output = {id: doc._id, key: normalizeKey(key)};
11418 // Don't explicitly store the value unless it's defined and non-null.
11419 // This saves on storage space, because often people don't use it.
11420 if (typeof value !== 'undefined' && value !== null) {
11421 output.value = normalizeKey(value);
11422 }
11423 mapResults.push(output);
11424 }
11425
11426 const mapFun = mapper(view.mapFun, emit);
11427
11428 let currentSeq = view.seq || 0;
11429
11430 function createTask() {
11431 return view.sourceDB.info().then(function (info) {
11432 taskId = view.sourceDB.activeTasks.add({
11433 name: 'view_indexing',
11434 total_items: info.update_seq - currentSeq
11435 });
11436 });
11437 }
11438
11439 function processChange(docIdsToChangesAndEmits, seq) {
11440 return function () {
11441 return saveKeyValues(view, docIdsToChangesAndEmits, seq);
11442 };
11443 }
11444
11445 let indexed_docs = 0;
11446 const progress = {
11447 view: view.name,
11448 indexed_docs: indexed_docs
11449 };
11450 view.sourceDB.emit('indexing', progress);
11451
11452 const queue = new TaskQueue$1();
11453
11454 async function processNextBatch() {
11455 const response = await view.sourceDB.changes({
11456 return_docs: true,
11457 conflicts: true,
11458 include_docs: true,
11459 style: 'all_docs',
11460 since: currentSeq,
11461 limit: opts.changes_batch_size
11462 });
11463 const purges = await getRecentPurges();
11464 return processBatch(response, purges);
11465 }
11466
11467 function getRecentPurges() {
11468 return view.db.get('_local/purgeSeq').then(function (res) {
11469 return res.purgeSeq;
11470 })["catch"](function (err) {
11471 if (err && err.status !== 404) {
11472 throw err;
11473 }
11474 return -1;
11475 }).then(function (purgeSeq) {
11476 return view.sourceDB.get('_local/purges').then(function (res) {
11477 const recentPurges = res.purges.filter(function (purge, index) {
11478 return index > purgeSeq;
11479 }).map((purge) => purge.docId);
11480
11481 const uniquePurges = recentPurges.filter(function (docId, index) {
11482 return recentPurges.indexOf(docId) === index;
11483 });
11484
11485 return Promise.all(uniquePurges.map(function (docId) {
11486 return view.sourceDB.get(docId).then(function (doc) {
11487 return { docId, doc };
11488 })["catch"](function (err) {
11489 if (err.status !== 404) {
11490 throw err;
11491 }
11492 return { docId };
11493 });
11494 }));
11495 })["catch"](function (err) {
11496 if (err && err.status !== 404) {
11497 throw err;
11498 }
11499 return [];
11500 });
11501 });
11502 }
11503
11504 function processBatch(response, purges) {
11505 var results = response.results;
11506 if (!results.length && !purges.length) {
11507 return;
11508 }
11509
11510 for (let purge of purges) {
11511 const index = results.findIndex(function (change) {
11512 return change.id === purge.docId;
11513 });
11514 if (index < 0) {
11515 // mimic a db.remove() on the changes feed
11516 const entry = {
11517 _id: purge.docId,
11518 doc: {
11519 _id: purge.docId,
11520 _deleted: 1
11521 },
11522 changes: []
11523 };
11524
11525 if (purge.doc) {
11526 // update with new winning rev after purge
11527 entry.doc = purge.doc;
11528 entry.changes.push({ rev: purge.doc._rev });
11529 }
11530
11531 results.push(entry);
11532 }
11533 }
11534
11535 var docIdsToChangesAndEmits = createDocIdsToChangesAndEmits(results);
11536
11537 queue.add(processChange(docIdsToChangesAndEmits, currentSeq));
11538
11539 indexed_docs = indexed_docs + results.length;
11540 const progress = {
11541 view: view.name,
11542 last_seq: response.last_seq,
11543 results_count: results.length,
11544 indexed_docs: indexed_docs
11545 };
11546 view.sourceDB.emit('indexing', progress);
11547 view.sourceDB.activeTasks.update(taskId, {completed_items: indexed_docs});
11548
11549 if (results.length < opts.changes_batch_size) {
11550 return;
11551 }
11552 return processNextBatch();
11553 }
11554
11555 function createDocIdsToChangesAndEmits(results) {
11556 const docIdsToChangesAndEmits = new ExportedMap();
11557 for (let i = 0, len = results.length; i < len; i++) {
11558 const change = results[i];
11559 if (change.doc._id[0] !== '_') {
11560 mapResults = [];
11561 doc = change.doc;
11562
11563 if (!doc._deleted) {
11564 tryMap(view.sourceDB, mapFun, doc);
11565 }
11566 mapResults.sort(sortByKeyThenValue);
11567
11568 const indexableKeysToKeyValues = createIndexableKeysToKeyValues(mapResults);
11569 docIdsToChangesAndEmits.set(change.doc._id, [
11570 indexableKeysToKeyValues,
11571 change.changes
11572 ]);
11573 }
11574 currentSeq = change.seq;
11575 }
11576 return docIdsToChangesAndEmits;
11577 }
11578
11579 function createIndexableKeysToKeyValues(mapResults) {
11580 const indexableKeysToKeyValues = new ExportedMap();
11581 let lastKey;
11582 for (let i = 0, len = mapResults.length; i < len; i++) {
11583 const emittedKeyValue = mapResults[i];
11584 const complexKey = [emittedKeyValue.key, emittedKeyValue.id];
11585 if (i > 0 && collate(emittedKeyValue.key, lastKey) === 0) {
11586 complexKey.push(i); // dup key+id, so make it unique
11587 }
11588 indexableKeysToKeyValues.set(toIndexableString(complexKey), emittedKeyValue);
11589 lastKey = emittedKeyValue.key;
11590 }
11591 return indexableKeysToKeyValues;
11592 }
11593
11594 try {
11595 await createTask();
11596 await processNextBatch();
11597 await queue.finish();
11598 view.seq = currentSeq;
11599 view.sourceDB.activeTasks.remove(taskId);
11600 } catch (error) {
11601 view.sourceDB.activeTasks.remove(taskId, error);
11602 }
11603 }
11604
11605 function reduceView(view, results, options) {
11606 if (options.group_level === 0) {
11607 delete options.group_level;
11608 }
11609
11610 const shouldGroup = options.group || options.group_level;
11611
11612 const reduceFun = reducer(view.reduceFun);
11613
11614 const groups = [];
11615 const lvl = isNaN(options.group_level) ? Number.POSITIVE_INFINITY :
11616 options.group_level;
11617 results.forEach(function (e) {
11618 const last = groups[groups.length - 1];
11619 let groupKey = shouldGroup ? e.key : null;
11620
11621 // only set group_level for array keys
11622 if (shouldGroup && Array.isArray(groupKey)) {
11623 groupKey = groupKey.slice(0, lvl);
11624 }
11625
11626 if (last && collate(last.groupKey, groupKey) === 0) {
11627 last.keys.push([e.key, e.id]);
11628 last.values.push(e.value);
11629 return;
11630 }
11631 groups.push({
11632 keys: [[e.key, e.id]],
11633 values: [e.value],
11634 groupKey: groupKey
11635 });
11636 });
11637 results = [];
11638 for (let i = 0, len = groups.length; i < len; i++) {
11639 const e = groups[i];
11640 const reduceTry = tryReduce(view.sourceDB, reduceFun, e.keys, e.values, false);
11641 if (reduceTry.error && reduceTry.error instanceof BuiltInError) {
11642 // CouchDB returns an error if a built-in errors out
11643 throw reduceTry.error;
11644 }
11645 results.push({
11646 // CouchDB just sets the value to null if a non-built-in errors out
11647 value: reduceTry.error ? null : reduceTry.output,
11648 key: e.groupKey
11649 });
11650 }
11651 // no total_rows/offset when reducing
11652 return {rows: sliceResults(results, options.limit, options.skip)};
11653 }
11654
11655 function queryView(view, opts) {
11656 return sequentialize(getQueue(view), function () {
11657 return queryViewInQueue(view, opts);
11658 })();
11659 }
11660
11661 async function queryViewInQueue(view, opts) {
11662 let totalRows;
11663 const shouldReduce = view.reduceFun && opts.reduce !== false;
11664 const skip = opts.skip || 0;
11665 if (typeof opts.keys !== 'undefined' && !opts.keys.length) {
11666 // equivalent query
11667 opts.limit = 0;
11668 delete opts.keys;
11669 }
11670
11671 async function fetchFromView(viewOpts) {
11672 viewOpts.include_docs = true;
11673 const res = await view.db.allDocs(viewOpts);
11674 totalRows = res.total_rows;
11675
11676 return res.rows.map(function (result) {
11677 // implicit migration - in older versions of PouchDB,
11678 // we explicitly stored the doc as {id: ..., key: ..., value: ...}
11679 // this is tested in a migration test
11680 /* istanbul ignore next */
11681 if ('value' in result.doc && typeof result.doc.value === 'object' &&
11682 result.doc.value !== null) {
11683 const keys = Object.keys(result.doc.value).sort();
11684 // this detection method is not perfect, but it's unlikely the user
11685 // emitted a value which was an object with these 3 exact keys
11686 const expectedKeys = ['id', 'key', 'value'];
11687 if (!(keys < expectedKeys || keys > expectedKeys)) {
11688 return result.doc.value;
11689 }
11690 }
11691
11692 const parsedKeyAndDocId = parseIndexableString(result.doc._id);
11693 return {
11694 key: parsedKeyAndDocId[0],
11695 id: parsedKeyAndDocId[1],
11696 value: ('value' in result.doc ? result.doc.value : null)
11697 };
11698 });
11699 }
11700
11701 async function onMapResultsReady(rows) {
11702 let finalResults;
11703 if (shouldReduce) {
11704 finalResults = reduceView(view, rows, opts);
11705 } else if (typeof opts.keys === 'undefined') {
11706 finalResults = {
11707 total_rows: totalRows,
11708 offset: skip,
11709 rows: rows
11710 };
11711 } else {
11712 // support limit, skip for keys query
11713 finalResults = {
11714 total_rows: totalRows,
11715 offset: skip,
11716 rows: sliceResults(rows,opts.limit,opts.skip)
11717 };
11718 }
11719 /* istanbul ignore if */
11720 if (opts.update_seq) {
11721 finalResults.update_seq = view.seq;
11722 }
11723 if (opts.include_docs) {
11724 const docIds = uniq(rows.map(rowToDocId));
11725
11726 const allDocsRes = await view.sourceDB.allDocs({
11727 keys: docIds,
11728 include_docs: true,
11729 conflicts: opts.conflicts,
11730 attachments: opts.attachments,
11731 binary: opts.binary
11732 });
11733 var docIdsToDocs = new ExportedMap();
11734 allDocsRes.rows.forEach(function (row) {
11735 docIdsToDocs.set(row.id, row.doc);
11736 });
11737 rows.forEach(function (row) {
11738 var docId = rowToDocId(row);
11739 var doc = docIdsToDocs.get(docId);
11740 if (doc) {
11741 row.doc = doc;
11742 }
11743 });
11744 return finalResults;
11745 } else {
11746 return finalResults;
11747 }
11748 }
11749
11750 if (typeof opts.keys !== 'undefined') {
11751 const keys = opts.keys;
11752 const fetchPromises = keys.map(function (key) {
11753 const viewOpts = {
11754 startkey : toIndexableString([key]),
11755 endkey : toIndexableString([key, {}])
11756 };
11757 /* istanbul ignore if */
11758 if (opts.update_seq) {
11759 viewOpts.update_seq = true;
11760 }
11761 return fetchFromView(viewOpts);
11762 });
11763 const result = await Promise.all(fetchPromises);
11764 const flattenedResult = flatten(result);
11765 return onMapResultsReady(flattenedResult);
11766 } else { // normal query, no 'keys'
11767 const viewOpts = {
11768 descending : opts.descending
11769 };
11770 /* istanbul ignore if */
11771 if (opts.update_seq) {
11772 viewOpts.update_seq = true;
11773 }
11774 let startkey;
11775 let endkey;
11776 if ('start_key' in opts) {
11777 startkey = opts.start_key;
11778 }
11779 if ('startkey' in opts) {
11780 startkey = opts.startkey;
11781 }
11782 if ('end_key' in opts) {
11783 endkey = opts.end_key;
11784 }
11785 if ('endkey' in opts) {
11786 endkey = opts.endkey;
11787 }
11788 if (typeof startkey !== 'undefined') {
11789 viewOpts.startkey = opts.descending ?
11790 toIndexableString([startkey, {}]) :
11791 toIndexableString([startkey]);
11792 }
11793 if (typeof endkey !== 'undefined') {
11794 let inclusiveEnd = opts.inclusive_end !== false;
11795 if (opts.descending) {
11796 inclusiveEnd = !inclusiveEnd;
11797 }
11798
11799 viewOpts.endkey = toIndexableString(
11800 inclusiveEnd ? [endkey, {}] : [endkey]);
11801 }
11802 if (typeof opts.key !== 'undefined') {
11803 const keyStart = toIndexableString([opts.key]);
11804 const keyEnd = toIndexableString([opts.key, {}]);
11805 if (viewOpts.descending) {
11806 viewOpts.endkey = keyStart;
11807 viewOpts.startkey = keyEnd;
11808 } else {
11809 viewOpts.startkey = keyStart;
11810 viewOpts.endkey = keyEnd;
11811 }
11812 }
11813 if (!shouldReduce) {
11814 if (typeof opts.limit === 'number') {
11815 viewOpts.limit = opts.limit;
11816 }
11817 viewOpts.skip = skip;
11818 }
11819
11820 const result = await fetchFromView(viewOpts);
11821 return onMapResultsReady(result);
11822 }
11823 }
11824
11825 async function httpViewCleanup(db) {
11826 const response = await db.fetch('_view_cleanup', {
11827 headers: new h({'Content-Type': 'application/json'}),
11828 method: 'POST'
11829 });
11830 return response.json();
11831 }
11832
11833 async function localViewCleanup(db) {
11834 try {
11835 const metaDoc = await db.get('_local/' + localDocName);
11836 const docsToViews = new ExportedMap();
11837
11838 Object.keys(metaDoc.views).forEach(function (fullViewName) {
11839 const parts = parseViewName(fullViewName);
11840 const designDocName = '_design/' + parts[0];
11841 const viewName = parts[1];
11842 let views = docsToViews.get(designDocName);
11843 if (!views) {
11844 views = new ExportedSet();
11845 docsToViews.set(designDocName, views);
11846 }
11847 views.add(viewName);
11848 });
11849 const opts = {
11850 keys : mapToKeysArray(docsToViews),
11851 include_docs : true
11852 };
11853
11854 const res = await db.allDocs(opts);
11855 const viewsToStatus = {};
11856 res.rows.forEach(function (row) {
11857 const ddocName = row.key.substring(8); // cuts off '_design/'
11858 docsToViews.get(row.key).forEach(function (viewName) {
11859 let fullViewName = ddocName + '/' + viewName;
11860 /* istanbul ignore if */
11861 if (!metaDoc.views[fullViewName]) {
11862 // new format, without slashes, to support PouchDB 2.2.0
11863 // migration test in pouchdb's browser.migration.js verifies this
11864 fullViewName = viewName;
11865 }
11866 const viewDBNames = Object.keys(metaDoc.views[fullViewName]);
11867 // design doc deleted, or view function nonexistent
11868 const statusIsGood = row.doc && row.doc.views &&
11869 row.doc.views[viewName];
11870 viewDBNames.forEach(function (viewDBName) {
11871 viewsToStatus[viewDBName] =
11872 viewsToStatus[viewDBName] || statusIsGood;
11873 });
11874 });
11875 });
11876
11877 const dbsToDelete = Object.keys(viewsToStatus)
11878 .filter(function (viewDBName) { return !viewsToStatus[viewDBName]; });
11879
11880 const destroyPromises = dbsToDelete.map(function (viewDBName) {
11881 return sequentialize(getQueue(viewDBName), function () {
11882 return new db.constructor(viewDBName, db.__opts).destroy();
11883 })();
11884 });
11885
11886 return Promise.all(destroyPromises).then(function () {
11887 return {ok: true};
11888 });
11889 } catch (err) {
11890 if (err.status === 404) {
11891 return {ok: true};
11892 } else {
11893 throw err;
11894 }
11895 }
11896 }
11897
11898 async function queryPromised(db, fun, opts) {
11899 /* istanbul ignore next */
11900 if (typeof db._query === 'function') {
11901 return customQuery(db, fun, opts);
11902 }
11903 if (isRemote(db)) {
11904 return httpQuery(db, fun, opts);
11905 }
11906
11907 const updateViewOpts = {
11908 changes_batch_size: db.__opts.view_update_changes_batch_size || CHANGES_BATCH_SIZE$1
11909 };
11910
11911 if (typeof fun !== 'string') {
11912 // temp_view
11913 checkQueryParseError(opts, fun);
11914
11915 tempViewQueue.add(async function () {
11916 const view = await createView(
11917 /* sourceDB */ db,
11918 /* viewName */ 'temp_view/temp_view',
11919 /* mapFun */ fun.map,
11920 /* reduceFun */ fun.reduce,
11921 /* temporary */ true,
11922 /* localDocName */ localDocName);
11923
11924 return fin(updateView(view, updateViewOpts).then(
11925 function () { return queryView(view, opts); }),
11926 function () { return view.db.destroy(); }
11927 );
11928 });
11929 return tempViewQueue.finish();
11930 } else {
11931 // persistent view
11932 const fullViewName = fun;
11933 const parts = parseViewName(fullViewName);
11934 const designDocName = parts[0];
11935 const viewName = parts[1];
11936
11937 const doc = await db.get('_design/' + designDocName);
11938 fun = doc.views && doc.views[viewName];
11939
11940 if (!fun) {
11941 // basic validator; it's assumed that every subclass would want this
11942 throw new NotFoundError(`ddoc ${doc._id} has no view named ${viewName}`);
11943 }
11944
11945 ddocValidator(doc, viewName);
11946 checkQueryParseError(opts, fun);
11947
11948 const view = await createView(
11949 /* sourceDB */ db,
11950 /* viewName */ fullViewName,
11951 /* mapFun */ fun.map,
11952 /* reduceFun */ fun.reduce,
11953 /* temporary */ false,
11954 /* localDocName */ localDocName);
11955
11956 if (opts.stale === 'ok' || opts.stale === 'update_after') {
11957 if (opts.stale === 'update_after') {
11958 immediate(function () {
11959 updateView(view, updateViewOpts);
11960 });
11961 }
11962 return queryView(view, opts);
11963 } else { // stale not ok
11964 await updateView(view, updateViewOpts);
11965 return queryView(view, opts);
11966 }
11967 }
11968 }
11969
11970 function abstractQuery(fun, opts, callback) {
11971 const db = this;
11972 if (typeof opts === 'function') {
11973 callback = opts;
11974 opts = {};
11975 }
11976 opts = opts ? coerceOptions(opts) : {};
11977
11978 if (typeof fun === 'function') {
11979 fun = {map : fun};
11980 }
11981
11982 const promise = Promise.resolve().then(function () {
11983 return queryPromised(db, fun, opts);
11984 });
11985 promisedCallback(promise, callback);
11986 return promise;
11987 }
11988
11989 const abstractViewCleanup = callbackify(function () {
11990 const db = this;
11991 /* istanbul ignore next */
11992 if (typeof db._viewCleanup === 'function') {
11993 return customViewCleanup(db);
11994 }
11995 if (isRemote(db)) {
11996 return httpViewCleanup(db);
11997 }
11998 return localViewCleanup(db);
11999 });
12000
12001 return {
12002 query: abstractQuery,
12003 viewCleanup: abstractViewCleanup
12004 };
12005}
12006
12007var builtInReduce = {
12008 _sum: function (keys, values) {
12009 return sum(values);
12010 },
12011
12012 _count: function (keys, values) {
12013 return values.length;
12014 },
12015
12016 _stats: function (keys, values) {
12017 // no need to implement rereduce=true, because Pouch
12018 // will never call it
12019 function sumsqr(values) {
12020 var _sumsqr = 0;
12021 for (var i = 0, len = values.length; i < len; i++) {
12022 var num = values[i];
12023 _sumsqr += (num * num);
12024 }
12025 return _sumsqr;
12026 }
12027 return {
12028 sum : sum(values),
12029 min : Math.min.apply(null, values),
12030 max : Math.max.apply(null, values),
12031 count : values.length,
12032 sumsqr : sumsqr(values)
12033 };
12034 }
12035};
12036
12037function getBuiltIn(reduceFunString) {
12038 if (/^_sum/.test(reduceFunString)) {
12039 return builtInReduce._sum;
12040 } else if (/^_count/.test(reduceFunString)) {
12041 return builtInReduce._count;
12042 } else if (/^_stats/.test(reduceFunString)) {
12043 return builtInReduce._stats;
12044 } else if (/^_/.test(reduceFunString)) {
12045 throw new Error(reduceFunString + ' is not a supported reduce function.');
12046 }
12047}
12048
12049function mapper(mapFun, emit) {
12050 // for temp_views one can use emit(doc, emit), see #38
12051 if (typeof mapFun === "function" && mapFun.length === 2) {
12052 var origMap = mapFun;
12053 return function (doc) {
12054 return origMap(doc, emit);
12055 };
12056 } else {
12057 return evalFunctionWithEval(mapFun.toString(), emit);
12058 }
12059}
12060
12061function reducer(reduceFun) {
12062 var reduceFunString = reduceFun.toString();
12063 var builtIn = getBuiltIn(reduceFunString);
12064 if (builtIn) {
12065 return builtIn;
12066 } else {
12067 return evalFunctionWithEval(reduceFunString);
12068 }
12069}
12070
12071function ddocValidator(ddoc, viewName) {
12072 var fun = ddoc.views && ddoc.views[viewName];
12073 if (typeof fun.map !== 'string') {
12074 throw new NotFoundError('ddoc ' + ddoc._id + ' has no string view named ' +
12075 viewName + ', instead found object of type: ' + typeof fun.map);
12076 }
12077}
12078
12079var localDocName = 'mrviews';
12080var abstract = createAbstractMapReduce(localDocName, mapper, reducer, ddocValidator);
12081
12082function query(fun, opts, callback) {
12083 return abstract.query.call(this, fun, opts, callback);
12084}
12085
12086function viewCleanup(callback) {
12087 return abstract.viewCleanup.call(this, callback);
12088}
12089
12090var mapreduce = {
12091 query: query,
12092 viewCleanup: viewCleanup
12093};
12094
12095function fileHasChanged(localDoc, remoteDoc, filename) {
12096 return !localDoc._attachments ||
12097 !localDoc._attachments[filename] ||
12098 localDoc._attachments[filename].digest !== remoteDoc._attachments[filename].digest;
12099}
12100
12101function getDocAttachments(db, doc) {
12102 var filenames = Object.keys(doc._attachments);
12103 return Promise.all(filenames.map(function (filename) {
12104 return db.getAttachment(doc._id, filename, {rev: doc._rev});
12105 }));
12106}
12107
12108function getDocAttachmentsFromTargetOrSource(target, src, doc) {
12109 var doCheckForLocalAttachments = isRemote(src) && !isRemote(target);
12110 var filenames = Object.keys(doc._attachments);
12111
12112 if (!doCheckForLocalAttachments) {
12113 return getDocAttachments(src, doc);
12114 }
12115
12116 return target.get(doc._id).then(function (localDoc) {
12117 return Promise.all(filenames.map(function (filename) {
12118 if (fileHasChanged(localDoc, doc, filename)) {
12119 return src.getAttachment(doc._id, filename);
12120 }
12121
12122 return target.getAttachment(localDoc._id, filename);
12123 }));
12124 })["catch"](function (error) {
12125 /* istanbul ignore if */
12126 if (error.status !== 404) {
12127 throw error;
12128 }
12129
12130 return getDocAttachments(src, doc);
12131 });
12132}
12133
12134function createBulkGetOpts(diffs) {
12135 var requests = [];
12136 Object.keys(diffs).forEach(function (id) {
12137 var missingRevs = diffs[id].missing;
12138 missingRevs.forEach(function (missingRev) {
12139 requests.push({
12140 id: id,
12141 rev: missingRev
12142 });
12143 });
12144 });
12145
12146 return {
12147 docs: requests,
12148 revs: true,
12149 latest: true
12150 };
12151}
12152
12153//
12154// Fetch all the documents from the src as described in the "diffs",
12155// which is a mapping of docs IDs to revisions. If the state ever
12156// changes to "cancelled", then the returned promise will be rejected.
12157// Else it will be resolved with a list of fetched documents.
12158//
12159function getDocs(src, target, diffs, state) {
12160 diffs = clone(diffs); // we do not need to modify this
12161
12162 var resultDocs = [],
12163 ok = true;
12164
12165 function getAllDocs() {
12166
12167 var bulkGetOpts = createBulkGetOpts(diffs);
12168
12169 if (!bulkGetOpts.docs.length) { // optimization: skip empty requests
12170 return;
12171 }
12172
12173 return src.bulkGet(bulkGetOpts).then(function (bulkGetResponse) {
12174 /* istanbul ignore if */
12175 if (state.cancelled) {
12176 throw new Error('cancelled');
12177 }
12178 return Promise.all(bulkGetResponse.results.map(function (bulkGetInfo) {
12179 return Promise.all(bulkGetInfo.docs.map(function (doc) {
12180 var remoteDoc = doc.ok;
12181
12182 if (doc.error) {
12183 // when AUTO_COMPACTION is set, docs can be returned which look
12184 // like this: {"missing":"1-7c3ac256b693c462af8442f992b83696"}
12185 ok = false;
12186 }
12187
12188 if (!remoteDoc || !remoteDoc._attachments) {
12189 return remoteDoc;
12190 }
12191
12192 return getDocAttachmentsFromTargetOrSource(target, src, remoteDoc)
12193 .then(function (attachments) {
12194 var filenames = Object.keys(remoteDoc._attachments);
12195 attachments
12196 .forEach(function (attachment, i) {
12197 var att = remoteDoc._attachments[filenames[i]];
12198 delete att.stub;
12199 delete att.length;
12200 att.data = attachment;
12201 });
12202
12203 return remoteDoc;
12204 });
12205 }));
12206 }))
12207
12208 .then(function (results) {
12209 resultDocs = resultDocs.concat(flatten(results).filter(Boolean));
12210 });
12211 });
12212 }
12213
12214 function returnResult() {
12215 return { ok:ok, docs:resultDocs };
12216 }
12217
12218 return Promise.resolve()
12219 .then(getAllDocs)
12220 .then(returnResult);
12221}
12222
12223var CHECKPOINT_VERSION = 1;
12224var REPLICATOR = "pouchdb";
12225// This is an arbitrary number to limit the
12226// amount of replication history we save in the checkpoint.
12227// If we save too much, the checkpoing docs will become very big,
12228// if we save fewer, we'll run a greater risk of having to
12229// read all the changes from 0 when checkpoint PUTs fail
12230// CouchDB 2.0 has a more involved history pruning,
12231// but let's go for the simple version for now.
12232var CHECKPOINT_HISTORY_SIZE = 5;
12233var LOWEST_SEQ = 0;
12234
12235function updateCheckpoint(db, id, checkpoint, session, returnValue) {
12236 return db.get(id)["catch"](function (err) {
12237 if (err.status === 404) {
12238 if (db.adapter === 'http' || db.adapter === 'https') {
12239 explainError(
12240 404, 'PouchDB is just checking if a remote checkpoint exists.'
12241 );
12242 }
12243 return {
12244 session_id: session,
12245 _id: id,
12246 history: [],
12247 replicator: REPLICATOR,
12248 version: CHECKPOINT_VERSION
12249 };
12250 }
12251 throw err;
12252 }).then(function (doc) {
12253 if (returnValue.cancelled) {
12254 return;
12255 }
12256
12257 // if the checkpoint has not changed, do not update
12258 if (doc.last_seq === checkpoint) {
12259 return;
12260 }
12261
12262 // Filter out current entry for this replication
12263 doc.history = (doc.history || []).filter(function (item) {
12264 return item.session_id !== session;
12265 });
12266
12267 // Add the latest checkpoint to history
12268 doc.history.unshift({
12269 last_seq: checkpoint,
12270 session_id: session
12271 });
12272
12273 // Just take the last pieces in history, to
12274 // avoid really big checkpoint docs.
12275 // see comment on history size above
12276 doc.history = doc.history.slice(0, CHECKPOINT_HISTORY_SIZE);
12277
12278 doc.version = CHECKPOINT_VERSION;
12279 doc.replicator = REPLICATOR;
12280
12281 doc.session_id = session;
12282 doc.last_seq = checkpoint;
12283
12284 return db.put(doc)["catch"](function (err) {
12285 if (err.status === 409) {
12286 // retry; someone is trying to write a checkpoint simultaneously
12287 return updateCheckpoint(db, id, checkpoint, session, returnValue);
12288 }
12289 throw err;
12290 });
12291 });
12292}
12293
12294class CheckpointerInternal {
12295 constructor(src, target, id, returnValue, opts) {
12296 this.src = src;
12297 this.target = target;
12298 this.id = id;
12299 this.returnValue = returnValue;
12300 this.opts = opts || {};
12301 }
12302
12303 writeCheckpoint(checkpoint, session) {
12304 var self = this;
12305 return this.updateTarget(checkpoint, session).then(function () {
12306 return self.updateSource(checkpoint, session);
12307 });
12308 }
12309
12310 updateTarget(checkpoint, session) {
12311 if (this.opts.writeTargetCheckpoint) {
12312 return updateCheckpoint(this.target, this.id, checkpoint,
12313 session, this.returnValue);
12314 } else {
12315 return Promise.resolve(true);
12316 }
12317 }
12318
12319 updateSource(checkpoint, session) {
12320 if (this.opts.writeSourceCheckpoint) {
12321 var self = this;
12322 return updateCheckpoint(this.src, this.id, checkpoint,
12323 session, this.returnValue)[
12324 "catch"](function (err) {
12325 if (isForbiddenError(err)) {
12326 self.opts.writeSourceCheckpoint = false;
12327 return true;
12328 }
12329 throw err;
12330 });
12331 } else {
12332 return Promise.resolve(true);
12333 }
12334 }
12335
12336 getCheckpoint() {
12337 var self = this;
12338
12339 if (self.opts && self.opts.writeSourceCheckpoint && !self.opts.writeTargetCheckpoint) {
12340 return self.src.get(self.id).then(function (sourceDoc) {
12341 return sourceDoc.last_seq || LOWEST_SEQ;
12342 })["catch"](function (err) {
12343 /* istanbul ignore if */
12344 if (err.status !== 404) {
12345 throw err;
12346 }
12347 return LOWEST_SEQ;
12348 });
12349 }
12350
12351 return self.target.get(self.id).then(function (targetDoc) {
12352 if (self.opts && self.opts.writeTargetCheckpoint && !self.opts.writeSourceCheckpoint) {
12353 return targetDoc.last_seq || LOWEST_SEQ;
12354 }
12355
12356 return self.src.get(self.id).then(function (sourceDoc) {
12357 // Since we can't migrate an old version doc to a new one
12358 // (no session id), we just go with the lowest seq in this case
12359 /* istanbul ignore if */
12360 if (targetDoc.version !== sourceDoc.version) {
12361 return LOWEST_SEQ;
12362 }
12363
12364 var version;
12365 if (targetDoc.version) {
12366 version = targetDoc.version.toString();
12367 } else {
12368 version = "undefined";
12369 }
12370
12371 if (version in comparisons) {
12372 return comparisons[version](targetDoc, sourceDoc);
12373 }
12374 /* istanbul ignore next */
12375 return LOWEST_SEQ;
12376 }, function (err) {
12377 if (err.status === 404 && targetDoc.last_seq) {
12378 return self.src.put({
12379 _id: self.id,
12380 last_seq: LOWEST_SEQ
12381 }).then(function () {
12382 return LOWEST_SEQ;
12383 }, function (err) {
12384 if (isForbiddenError(err)) {
12385 self.opts.writeSourceCheckpoint = false;
12386 return targetDoc.last_seq;
12387 }
12388 /* istanbul ignore next */
12389 return LOWEST_SEQ;
12390 });
12391 }
12392 throw err;
12393 });
12394 })["catch"](function (err) {
12395 if (err.status !== 404) {
12396 throw err;
12397 }
12398 return LOWEST_SEQ;
12399 });
12400 }
12401}
12402
12403var comparisons = {
12404 "undefined": function (targetDoc, sourceDoc) {
12405 // This is the previous comparison function
12406 if (collate(targetDoc.last_seq, sourceDoc.last_seq) === 0) {
12407 return sourceDoc.last_seq;
12408 }
12409 /* istanbul ignore next */
12410 return 0;
12411 },
12412 "1": function (targetDoc, sourceDoc) {
12413 // This is the comparison function ported from CouchDB
12414 return compareReplicationLogs(sourceDoc, targetDoc).last_seq;
12415 }
12416};
12417
12418// This checkpoint comparison is ported from CouchDBs source
12419// they come from here:
12420// https://github.com/apache/couchdb-couch-replicator/blob/master/src/couch_replicator.erl#L863-L906
12421
12422function compareReplicationLogs(srcDoc, tgtDoc) {
12423 if (srcDoc.session_id === tgtDoc.session_id) {
12424 return {
12425 last_seq: srcDoc.last_seq,
12426 history: srcDoc.history
12427 };
12428 }
12429
12430 return compareReplicationHistory(srcDoc.history, tgtDoc.history);
12431}
12432
12433function compareReplicationHistory(sourceHistory, targetHistory) {
12434 // the erlang loop via function arguments is not so easy to repeat in JS
12435 // therefore, doing this as recursion
12436 var S = sourceHistory[0];
12437 var sourceRest = sourceHistory.slice(1);
12438 var T = targetHistory[0];
12439 var targetRest = targetHistory.slice(1);
12440
12441 if (!S || targetHistory.length === 0) {
12442 return {
12443 last_seq: LOWEST_SEQ,
12444 history: []
12445 };
12446 }
12447
12448 var sourceId = S.session_id;
12449 /* istanbul ignore if */
12450 if (hasSessionId(sourceId, targetHistory)) {
12451 return {
12452 last_seq: S.last_seq,
12453 history: sourceHistory
12454 };
12455 }
12456
12457 var targetId = T.session_id;
12458 if (hasSessionId(targetId, sourceRest)) {
12459 return {
12460 last_seq: T.last_seq,
12461 history: targetRest
12462 };
12463 }
12464
12465 return compareReplicationHistory(sourceRest, targetRest);
12466}
12467
12468function hasSessionId(sessionId, history) {
12469 var props = history[0];
12470 var rest = history.slice(1);
12471
12472 if (!sessionId || history.length === 0) {
12473 return false;
12474 }
12475
12476 if (sessionId === props.session_id) {
12477 return true;
12478 }
12479
12480 return hasSessionId(sessionId, rest);
12481}
12482
12483function isForbiddenError(err) {
12484 return typeof err.status === 'number' && Math.floor(err.status / 100) === 4;
12485}
12486
12487function Checkpointer(src, target, id, returnValue, opts) {
12488 if (!(this instanceof CheckpointerInternal)) {
12489 return new CheckpointerInternal(src, target, id, returnValue, opts);
12490 }
12491 return Checkpointer;
12492}
12493
12494var STARTING_BACK_OFF = 0;
12495
12496function backOff(opts, returnValue, error, callback) {
12497 if (opts.retry === false) {
12498 returnValue.emit('error', error);
12499 returnValue.removeAllListeners();
12500 return;
12501 }
12502 /* istanbul ignore if */
12503 if (typeof opts.back_off_function !== 'function') {
12504 opts.back_off_function = defaultBackOff;
12505 }
12506 returnValue.emit('requestError', error);
12507 if (returnValue.state === 'active' || returnValue.state === 'pending') {
12508 returnValue.emit('paused', error);
12509 returnValue.state = 'stopped';
12510 var backOffSet = function backoffTimeSet() {
12511 opts.current_back_off = STARTING_BACK_OFF;
12512 };
12513 var removeBackOffSetter = function removeBackOffTimeSet() {
12514 returnValue.removeListener('active', backOffSet);
12515 };
12516 returnValue.once('paused', removeBackOffSetter);
12517 returnValue.once('active', backOffSet);
12518 }
12519
12520 opts.current_back_off = opts.current_back_off || STARTING_BACK_OFF;
12521 opts.current_back_off = opts.back_off_function(opts.current_back_off);
12522 setTimeout(callback, opts.current_back_off);
12523}
12524
12525function sortObjectPropertiesByKey(queryParams) {
12526 return Object.keys(queryParams).sort(collate).reduce(function (result, key) {
12527 result[key] = queryParams[key];
12528 return result;
12529 }, {});
12530}
12531
12532// Generate a unique id particular to this replication.
12533// Not guaranteed to align perfectly with CouchDB's rep ids.
12534function generateReplicationId(src, target, opts) {
12535 var docIds = opts.doc_ids ? opts.doc_ids.sort(collate) : '';
12536 var filterFun = opts.filter ? opts.filter.toString() : '';
12537 var queryParams = '';
12538 var filterViewName = '';
12539 var selector = '';
12540
12541 // possibility for checkpoints to be lost here as behaviour of
12542 // JSON.stringify is not stable (see #6226)
12543 /* istanbul ignore if */
12544 if (opts.selector) {
12545 selector = JSON.stringify(opts.selector);
12546 }
12547
12548 if (opts.filter && opts.query_params) {
12549 queryParams = JSON.stringify(sortObjectPropertiesByKey(opts.query_params));
12550 }
12551
12552 if (opts.filter && opts.filter === '_view') {
12553 filterViewName = opts.view.toString();
12554 }
12555
12556 return Promise.all([src.id(), target.id()]).then(function (res) {
12557 var queryData = res[0] + res[1] + filterFun + filterViewName +
12558 queryParams + docIds + selector;
12559 return new Promise(function (resolve) {
12560 binaryMd5(queryData, resolve);
12561 });
12562 }).then(function (md5sum) {
12563 // can't use straight-up md5 alphabet, because
12564 // the char '/' is interpreted as being for attachments,
12565 // and + is also not url-safe
12566 md5sum = md5sum.replace(/\//g, '.').replace(/\+/g, '_');
12567 return '_local/' + md5sum;
12568 });
12569}
12570
12571function replicate(src, target, opts, returnValue, result) {
12572 var batches = []; // list of batches to be processed
12573 var currentBatch; // the batch currently being processed
12574 var pendingBatch = {
12575 seq: 0,
12576 changes: [],
12577 docs: []
12578 }; // next batch, not yet ready to be processed
12579 var writingCheckpoint = false; // true while checkpoint is being written
12580 var changesCompleted = false; // true when all changes received
12581 var replicationCompleted = false; // true when replication has completed
12582 // initial_last_seq is the state of the source db before
12583 // replication started, and it is _not_ updated during
12584 // replication or used anywhere else, as opposed to last_seq
12585 var initial_last_seq = 0;
12586 var last_seq = 0;
12587 var continuous = opts.continuous || opts.live || false;
12588 var batch_size = opts.batch_size || 100;
12589 var batches_limit = opts.batches_limit || 10;
12590 var style = opts.style || 'all_docs';
12591 var changesPending = false; // true while src.changes is running
12592 var doc_ids = opts.doc_ids;
12593 var selector = opts.selector;
12594 var repId;
12595 var checkpointer;
12596 var changedDocs = [];
12597 // Like couchdb, every replication gets a unique session id
12598 var session = uuid$1();
12599 var taskId;
12600
12601 result = result || {
12602 ok: true,
12603 start_time: new Date().toISOString(),
12604 docs_read: 0,
12605 docs_written: 0,
12606 doc_write_failures: 0,
12607 errors: []
12608 };
12609
12610 var changesOpts = {};
12611 returnValue.ready(src, target);
12612
12613 function initCheckpointer() {
12614 if (checkpointer) {
12615 return Promise.resolve();
12616 }
12617 return generateReplicationId(src, target, opts).then(function (res) {
12618 repId = res;
12619
12620 var checkpointOpts = {};
12621 if (opts.checkpoint === false) {
12622 checkpointOpts = { writeSourceCheckpoint: false, writeTargetCheckpoint: false };
12623 } else if (opts.checkpoint === 'source') {
12624 checkpointOpts = { writeSourceCheckpoint: true, writeTargetCheckpoint: false };
12625 } else if (opts.checkpoint === 'target') {
12626 checkpointOpts = { writeSourceCheckpoint: false, writeTargetCheckpoint: true };
12627 } else {
12628 checkpointOpts = { writeSourceCheckpoint: true, writeTargetCheckpoint: true };
12629 }
12630
12631 checkpointer = new Checkpointer(src, target, repId, returnValue, checkpointOpts);
12632 });
12633 }
12634
12635 function writeDocs() {
12636 changedDocs = [];
12637
12638 if (currentBatch.docs.length === 0) {
12639 return;
12640 }
12641 var docs = currentBatch.docs;
12642 var bulkOpts = {timeout: opts.timeout};
12643 return target.bulkDocs({docs: docs, new_edits: false}, bulkOpts).then(function (res) {
12644 /* istanbul ignore if */
12645 if (returnValue.cancelled) {
12646 completeReplication();
12647 throw new Error('cancelled');
12648 }
12649
12650 // `res` doesn't include full documents (which live in `docs`), so we create a map of
12651 // (id -> error), and check for errors while iterating over `docs`
12652 var errorsById = Object.create(null);
12653 res.forEach(function (res) {
12654 if (res.error) {
12655 errorsById[res.id] = res;
12656 }
12657 });
12658
12659 var errorsNo = Object.keys(errorsById).length;
12660 result.doc_write_failures += errorsNo;
12661 result.docs_written += docs.length - errorsNo;
12662
12663 docs.forEach(function (doc) {
12664 var error = errorsById[doc._id];
12665 if (error) {
12666 result.errors.push(error);
12667 // Normalize error name. i.e. 'Unauthorized' -> 'unauthorized' (eg Sync Gateway)
12668 var errorName = (error.name || '').toLowerCase();
12669 if (errorName === 'unauthorized' || errorName === 'forbidden') {
12670 returnValue.emit('denied', clone(error));
12671 } else {
12672 throw error;
12673 }
12674 } else {
12675 changedDocs.push(doc);
12676 }
12677 });
12678
12679 }, function (err) {
12680 result.doc_write_failures += docs.length;
12681 throw err;
12682 });
12683 }
12684
12685 function finishBatch() {
12686 if (currentBatch.error) {
12687 throw new Error('There was a problem getting docs.');
12688 }
12689 result.last_seq = last_seq = currentBatch.seq;
12690 var outResult = clone(result);
12691 if (changedDocs.length) {
12692 outResult.docs = changedDocs;
12693 // Attach 'pending' property if server supports it (CouchDB 2.0+)
12694 /* istanbul ignore if */
12695 if (typeof currentBatch.pending === 'number') {
12696 outResult.pending = currentBatch.pending;
12697 delete currentBatch.pending;
12698 }
12699 returnValue.emit('change', outResult);
12700 }
12701 writingCheckpoint = true;
12702
12703 src.info().then(function (info) {
12704 var task = src.activeTasks.get(taskId);
12705 if (!currentBatch || !task) {
12706 return;
12707 }
12708
12709 var completed = task.completed_items || 0;
12710 var total_items = parseInt(info.update_seq, 10) - parseInt(initial_last_seq, 10);
12711 src.activeTasks.update(taskId, {
12712 completed_items: completed + currentBatch.changes.length,
12713 total_items
12714 });
12715 });
12716
12717 return checkpointer.writeCheckpoint(currentBatch.seq,
12718 session).then(function () {
12719 returnValue.emit('checkpoint', { 'checkpoint': currentBatch.seq });
12720 writingCheckpoint = false;
12721 /* istanbul ignore if */
12722 if (returnValue.cancelled) {
12723 completeReplication();
12724 throw new Error('cancelled');
12725 }
12726 currentBatch = undefined;
12727 getChanges();
12728 })["catch"](function (err) {
12729 onCheckpointError(err);
12730 throw err;
12731 });
12732 }
12733
12734 function getDiffs() {
12735 var diff = {};
12736 currentBatch.changes.forEach(function (change) {
12737 returnValue.emit('checkpoint', { 'revs_diff': change });
12738 // Couchbase Sync Gateway emits these, but we can ignore them
12739 /* istanbul ignore if */
12740 if (change.id === "_user/") {
12741 return;
12742 }
12743 diff[change.id] = change.changes.map(function (x) {
12744 return x.rev;
12745 });
12746 });
12747 return target.revsDiff(diff).then(function (diffs) {
12748 /* istanbul ignore if */
12749 if (returnValue.cancelled) {
12750 completeReplication();
12751 throw new Error('cancelled');
12752 }
12753 // currentBatch.diffs elements are deleted as the documents are written
12754 currentBatch.diffs = diffs;
12755 });
12756 }
12757
12758 function getBatchDocs() {
12759 return getDocs(src, target, currentBatch.diffs, returnValue).then(function (got) {
12760 currentBatch.error = !got.ok;
12761 got.docs.forEach(function (doc) {
12762 delete currentBatch.diffs[doc._id];
12763 result.docs_read++;
12764 currentBatch.docs.push(doc);
12765 });
12766 });
12767 }
12768
12769 function startNextBatch() {
12770 if (returnValue.cancelled || currentBatch) {
12771 return;
12772 }
12773 if (batches.length === 0) {
12774 processPendingBatch(true);
12775 return;
12776 }
12777 currentBatch = batches.shift();
12778 returnValue.emit('checkpoint', { 'start_next_batch': currentBatch.seq });
12779 getDiffs()
12780 .then(getBatchDocs)
12781 .then(writeDocs)
12782 .then(finishBatch)
12783 .then(startNextBatch)[
12784 "catch"](function (err) {
12785 abortReplication('batch processing terminated with error', err);
12786 });
12787 }
12788
12789
12790 function processPendingBatch(immediate$$1) {
12791 if (pendingBatch.changes.length === 0) {
12792 if (batches.length === 0 && !currentBatch) {
12793 if ((continuous && changesOpts.live) || changesCompleted) {
12794 returnValue.state = 'pending';
12795 returnValue.emit('paused');
12796 }
12797 if (changesCompleted) {
12798 completeReplication();
12799 }
12800 }
12801 return;
12802 }
12803 if (
12804 immediate$$1 ||
12805 changesCompleted ||
12806 pendingBatch.changes.length >= batch_size
12807 ) {
12808 batches.push(pendingBatch);
12809 pendingBatch = {
12810 seq: 0,
12811 changes: [],
12812 docs: []
12813 };
12814 if (returnValue.state === 'pending' || returnValue.state === 'stopped') {
12815 returnValue.state = 'active';
12816 returnValue.emit('active');
12817 }
12818 startNextBatch();
12819 }
12820 }
12821
12822
12823 function abortReplication(reason, err) {
12824 if (replicationCompleted) {
12825 return;
12826 }
12827 if (!err.message) {
12828 err.message = reason;
12829 }
12830 result.ok = false;
12831 result.status = 'aborting';
12832 batches = [];
12833 pendingBatch = {
12834 seq: 0,
12835 changes: [],
12836 docs: []
12837 };
12838 completeReplication(err);
12839 }
12840
12841
12842 function completeReplication(fatalError) {
12843 if (replicationCompleted) {
12844 return;
12845 }
12846 /* istanbul ignore if */
12847 if (returnValue.cancelled) {
12848 result.status = 'cancelled';
12849 if (writingCheckpoint) {
12850 return;
12851 }
12852 }
12853 result.status = result.status || 'complete';
12854 result.end_time = new Date().toISOString();
12855 result.last_seq = last_seq;
12856 replicationCompleted = true;
12857
12858 src.activeTasks.remove(taskId, fatalError);
12859
12860 if (fatalError) {
12861 // need to extend the error because Firefox considers ".result" read-only
12862 fatalError = createError(fatalError);
12863 fatalError.result = result;
12864
12865 // Normalize error name. i.e. 'Unauthorized' -> 'unauthorized' (eg Sync Gateway)
12866 var errorName = (fatalError.name || '').toLowerCase();
12867 if (errorName === 'unauthorized' || errorName === 'forbidden') {
12868 returnValue.emit('error', fatalError);
12869 returnValue.removeAllListeners();
12870 } else {
12871 backOff(opts, returnValue, fatalError, function () {
12872 replicate(src, target, opts, returnValue);
12873 });
12874 }
12875 } else {
12876 returnValue.emit('complete', result);
12877 returnValue.removeAllListeners();
12878 }
12879 }
12880
12881 function onChange(change, pending, lastSeq) {
12882 /* istanbul ignore if */
12883 if (returnValue.cancelled) {
12884 return completeReplication();
12885 }
12886 // Attach 'pending' property if server supports it (CouchDB 2.0+)
12887 /* istanbul ignore if */
12888 if (typeof pending === 'number') {
12889 pendingBatch.pending = pending;
12890 }
12891
12892 var filter = filterChange(opts)(change);
12893 if (!filter) {
12894 // update processed items count by 1
12895 var task = src.activeTasks.get(taskId);
12896 if (task) {
12897 // we can assume that task exists here? shouldn't be deleted by here.
12898 var completed = task.completed_items || 0;
12899 src.activeTasks.update(taskId, {completed_items: ++completed});
12900 }
12901 return;
12902 }
12903 pendingBatch.seq = change.seq || lastSeq;
12904 pendingBatch.changes.push(change);
12905 returnValue.emit('checkpoint', { 'pending_batch': pendingBatch.seq });
12906 immediate(function () {
12907 processPendingBatch(batches.length === 0 && changesOpts.live);
12908 });
12909 }
12910
12911
12912 function onChangesComplete(changes) {
12913 changesPending = false;
12914 /* istanbul ignore if */
12915 if (returnValue.cancelled) {
12916 return completeReplication();
12917 }
12918
12919 // if no results were returned then we're done,
12920 // else fetch more
12921 if (changes.results.length > 0) {
12922 changesOpts.since = changes.results[changes.results.length - 1].seq;
12923 getChanges();
12924 processPendingBatch(true);
12925 } else {
12926
12927 var complete = function () {
12928 if (continuous) {
12929 changesOpts.live = true;
12930 getChanges();
12931 } else {
12932 changesCompleted = true;
12933 }
12934 processPendingBatch(true);
12935 };
12936
12937 // update the checkpoint so we start from the right seq next time
12938 if (!currentBatch && changes.results.length === 0) {
12939 writingCheckpoint = true;
12940 checkpointer.writeCheckpoint(changes.last_seq,
12941 session).then(function () {
12942 writingCheckpoint = false;
12943 result.last_seq = last_seq = changes.last_seq;
12944 if (returnValue.cancelled) {
12945 completeReplication();
12946 throw new Error('cancelled');
12947 } else {
12948 complete();
12949 }
12950 })[
12951 "catch"](onCheckpointError);
12952 } else {
12953 complete();
12954 }
12955 }
12956 }
12957
12958
12959 function onChangesError(err) {
12960 changesPending = false;
12961 /* istanbul ignore if */
12962 if (returnValue.cancelled) {
12963 return completeReplication();
12964 }
12965 abortReplication('changes rejected', err);
12966 }
12967
12968
12969 function getChanges() {
12970 if (!(
12971 !changesPending &&
12972 !changesCompleted &&
12973 batches.length < batches_limit
12974 )) {
12975 return;
12976 }
12977 changesPending = true;
12978 function abortChanges() {
12979 changes.cancel();
12980 }
12981 function removeListener() {
12982 returnValue.removeListener('cancel', abortChanges);
12983 }
12984
12985 if (returnValue._changes) { // remove old changes() and listeners
12986 returnValue.removeListener('cancel', returnValue._abortChanges);
12987 returnValue._changes.cancel();
12988 }
12989 returnValue.once('cancel', abortChanges);
12990
12991 var changes = src.changes(changesOpts)
12992 .on('change', onChange);
12993 changes.then(removeListener, removeListener);
12994 changes.then(onChangesComplete)[
12995 "catch"](onChangesError);
12996
12997 if (opts.retry) {
12998 // save for later so we can cancel if necessary
12999 returnValue._changes = changes;
13000 returnValue._abortChanges = abortChanges;
13001 }
13002 }
13003
13004 function createTask(checkpoint) {
13005 return src.info().then(function (info) {
13006 var total_items = typeof opts.since === 'undefined' ?
13007 parseInt(info.update_seq, 10) - parseInt(checkpoint, 10) :
13008 parseInt(info.update_seq, 10);
13009
13010 taskId = src.activeTasks.add({
13011 name: `${continuous ? 'continuous ' : ''}replication from ${info.db_name}` ,
13012 total_items
13013 });
13014
13015 return checkpoint;
13016 });
13017 }
13018
13019 function startChanges() {
13020 initCheckpointer().then(function () {
13021 /* istanbul ignore if */
13022 if (returnValue.cancelled) {
13023 completeReplication();
13024 return;
13025 }
13026 return checkpointer.getCheckpoint().then(createTask).then(function (checkpoint) {
13027 last_seq = checkpoint;
13028 initial_last_seq = checkpoint;
13029 changesOpts = {
13030 since: last_seq,
13031 limit: batch_size,
13032 batch_size: batch_size,
13033 style: style,
13034 doc_ids: doc_ids,
13035 selector: selector,
13036 return_docs: true // required so we know when we're done
13037 };
13038 if (opts.filter) {
13039 if (typeof opts.filter !== 'string') {
13040 // required for the client-side filter in onChange
13041 changesOpts.include_docs = true;
13042 } else { // ddoc filter
13043 changesOpts.filter = opts.filter;
13044 }
13045 }
13046 if ('heartbeat' in opts) {
13047 changesOpts.heartbeat = opts.heartbeat;
13048 }
13049 if ('timeout' in opts) {
13050 changesOpts.timeout = opts.timeout;
13051 }
13052 if (opts.query_params) {
13053 changesOpts.query_params = opts.query_params;
13054 }
13055 if (opts.view) {
13056 changesOpts.view = opts.view;
13057 }
13058 getChanges();
13059 });
13060 })["catch"](function (err) {
13061 abortReplication('getCheckpoint rejected with ', err);
13062 });
13063 }
13064
13065 /* istanbul ignore next */
13066 function onCheckpointError(err) {
13067 writingCheckpoint = false;
13068 abortReplication('writeCheckpoint completed with error', err);
13069 }
13070
13071 /* istanbul ignore if */
13072 if (returnValue.cancelled) { // cancelled immediately
13073 completeReplication();
13074 return;
13075 }
13076
13077 if (!returnValue._addedListeners) {
13078 returnValue.once('cancel', completeReplication);
13079
13080 if (typeof opts.complete === 'function') {
13081 returnValue.once('error', opts.complete);
13082 returnValue.once('complete', function (result) {
13083 opts.complete(null, result);
13084 });
13085 }
13086 returnValue._addedListeners = true;
13087 }
13088
13089 if (typeof opts.since === 'undefined') {
13090 startChanges();
13091 } else {
13092 initCheckpointer().then(function () {
13093 writingCheckpoint = true;
13094 return checkpointer.writeCheckpoint(opts.since, session);
13095 }).then(function () {
13096 writingCheckpoint = false;
13097 /* istanbul ignore if */
13098 if (returnValue.cancelled) {
13099 completeReplication();
13100 return;
13101 }
13102 last_seq = opts.since;
13103 startChanges();
13104 })["catch"](onCheckpointError);
13105 }
13106}
13107
13108// We create a basic promise so the caller can cancel the replication possibly
13109// before we have actually started listening to changes etc
13110class Replication extends EE {
13111 constructor() {
13112 super();
13113 this.cancelled = false;
13114 this.state = 'pending';
13115 const promise = new Promise((fulfill, reject) => {
13116 this.once('complete', fulfill);
13117 this.once('error', reject);
13118 });
13119 this.then = function (resolve, reject) {
13120 return promise.then(resolve, reject);
13121 };
13122 this["catch"] = function (reject) {
13123 return promise["catch"](reject);
13124 };
13125 // As we allow error handling via "error" event as well,
13126 // put a stub in here so that rejecting never throws UnhandledError.
13127 this["catch"](function () {});
13128 }
13129
13130 cancel() {
13131 this.cancelled = true;
13132 this.state = 'cancelled';
13133 this.emit('cancel');
13134 }
13135
13136 ready(src, target) {
13137 if (this._readyCalled) {
13138 return;
13139 }
13140 this._readyCalled = true;
13141
13142 const onDestroy = () => {
13143 this.cancel();
13144 };
13145 src.once('destroyed', onDestroy);
13146 target.once('destroyed', onDestroy);
13147 function cleanup() {
13148 src.removeListener('destroyed', onDestroy);
13149 target.removeListener('destroyed', onDestroy);
13150 }
13151 this.once('complete', cleanup);
13152 this.once('error', cleanup);
13153 }
13154}
13155
13156function toPouch(db, opts) {
13157 var PouchConstructor = opts.PouchConstructor;
13158 if (typeof db === 'string') {
13159 return new PouchConstructor(db, opts);
13160 } else {
13161 return db;
13162 }
13163}
13164
13165function replicateWrapper(src, target, opts, callback) {
13166
13167 if (typeof opts === 'function') {
13168 callback = opts;
13169 opts = {};
13170 }
13171 if (typeof opts === 'undefined') {
13172 opts = {};
13173 }
13174
13175 if (opts.doc_ids && !Array.isArray(opts.doc_ids)) {
13176 throw createError(BAD_REQUEST,
13177 "`doc_ids` filter parameter is not a list.");
13178 }
13179
13180 opts.complete = callback;
13181 opts = clone(opts);
13182 opts.continuous = opts.continuous || opts.live;
13183 opts.retry = ('retry' in opts) ? opts.retry : false;
13184 /*jshint validthis:true */
13185 opts.PouchConstructor = opts.PouchConstructor || this;
13186 var replicateRet = new Replication(opts);
13187 var srcPouch = toPouch(src, opts);
13188 var targetPouch = toPouch(target, opts);
13189 replicate(srcPouch, targetPouch, opts, replicateRet);
13190 return replicateRet;
13191}
13192
13193function sync(src, target, opts, callback) {
13194 if (typeof opts === 'function') {
13195 callback = opts;
13196 opts = {};
13197 }
13198 if (typeof opts === 'undefined') {
13199 opts = {};
13200 }
13201 opts = clone(opts);
13202 /*jshint validthis:true */
13203 opts.PouchConstructor = opts.PouchConstructor || this;
13204 src = toPouch(src, opts);
13205 target = toPouch(target, opts);
13206 return new Sync(src, target, opts, callback);
13207}
13208
13209class Sync extends EE {
13210 constructor(src, target, opts, callback) {
13211 super();
13212 this.canceled = false;
13213
13214 const optsPush = opts.push ? $inject_Object_assign({}, opts, opts.push) : opts;
13215 const optsPull = opts.pull ? $inject_Object_assign({}, opts, opts.pull) : opts;
13216
13217 this.push = replicateWrapper(src, target, optsPush);
13218 this.pull = replicateWrapper(target, src, optsPull);
13219
13220 this.pushPaused = true;
13221 this.pullPaused = true;
13222
13223 const pullChange = (change) => {
13224 this.emit('change', {
13225 direction: 'pull',
13226 change: change
13227 });
13228 };
13229 const pushChange = (change) => {
13230 this.emit('change', {
13231 direction: 'push',
13232 change: change
13233 });
13234 };
13235 const pushDenied = (doc) => {
13236 this.emit('denied', {
13237 direction: 'push',
13238 doc: doc
13239 });
13240 };
13241 const pullDenied = (doc) => {
13242 this.emit('denied', {
13243 direction: 'pull',
13244 doc: doc
13245 });
13246 };
13247 const pushPaused = () => {
13248 this.pushPaused = true;
13249 /* istanbul ignore if */
13250 if (this.pullPaused) {
13251 this.emit('paused');
13252 }
13253 };
13254 const pullPaused = () => {
13255 this.pullPaused = true;
13256 /* istanbul ignore if */
13257 if (this.pushPaused) {
13258 this.emit('paused');
13259 }
13260 };
13261 const pushActive = () => {
13262 this.pushPaused = false;
13263 /* istanbul ignore if */
13264 if (this.pullPaused) {
13265 this.emit('active', {
13266 direction: 'push'
13267 });
13268 }
13269 };
13270 const pullActive = () => {
13271 this.pullPaused = false;
13272 /* istanbul ignore if */
13273 if (this.pushPaused) {
13274 this.emit('active', {
13275 direction: 'pull'
13276 });
13277 }
13278 };
13279
13280 let removed = {};
13281
13282 const removeAll = (type) => { // type is 'push' or 'pull'
13283 return (event, func) => {
13284 const isChange = event === 'change' &&
13285 (func === pullChange || func === pushChange);
13286 const isDenied = event === 'denied' &&
13287 (func === pullDenied || func === pushDenied);
13288 const isPaused = event === 'paused' &&
13289 (func === pullPaused || func === pushPaused);
13290 const isActive = event === 'active' &&
13291 (func === pullActive || func === pushActive);
13292
13293 if (isChange || isDenied || isPaused || isActive) {
13294 if (!(event in removed)) {
13295 removed[event] = {};
13296 }
13297 removed[event][type] = true;
13298 if (Object.keys(removed[event]).length === 2) {
13299 // both push and pull have asked to be removed
13300 this.removeAllListeners(event);
13301 }
13302 }
13303 };
13304 };
13305
13306 if (opts.live) {
13307 this.push.on('complete', this.pull.cancel.bind(this.pull));
13308 this.pull.on('complete', this.push.cancel.bind(this.push));
13309 }
13310
13311 function addOneListener(ee, event, listener) {
13312 if (ee.listeners(event).indexOf(listener) == -1) {
13313 ee.on(event, listener);
13314 }
13315 }
13316
13317 this.on('newListener', function (event) {
13318 if (event === 'change') {
13319 addOneListener(this.pull, 'change', pullChange);
13320 addOneListener(this.push, 'change', pushChange);
13321 } else if (event === 'denied') {
13322 addOneListener(this.pull, 'denied', pullDenied);
13323 addOneListener(this.push, 'denied', pushDenied);
13324 } else if (event === 'active') {
13325 addOneListener(this.pull, 'active', pullActive);
13326 addOneListener(this.push, 'active', pushActive);
13327 } else if (event === 'paused') {
13328 addOneListener(this.pull, 'paused', pullPaused);
13329 addOneListener(this.push, 'paused', pushPaused);
13330 }
13331 });
13332
13333 this.on('removeListener', function (event) {
13334 if (event === 'change') {
13335 this.pull.removeListener('change', pullChange);
13336 this.push.removeListener('change', pushChange);
13337 } else if (event === 'denied') {
13338 this.pull.removeListener('denied', pullDenied);
13339 this.push.removeListener('denied', pushDenied);
13340 } else if (event === 'active') {
13341 this.pull.removeListener('active', pullActive);
13342 this.push.removeListener('active', pushActive);
13343 } else if (event === 'paused') {
13344 this.pull.removeListener('paused', pullPaused);
13345 this.push.removeListener('paused', pushPaused);
13346 }
13347 });
13348
13349 this.pull.on('removeListener', removeAll('pull'));
13350 this.push.on('removeListener', removeAll('push'));
13351
13352 const promise = Promise.all([
13353 this.push,
13354 this.pull
13355 ]).then((resp) => {
13356 const out = {
13357 push: resp[0],
13358 pull: resp[1]
13359 };
13360 this.emit('complete', out);
13361 if (callback) {
13362 callback(null, out);
13363 }
13364 this.removeAllListeners();
13365 return out;
13366 }, (err) => {
13367 this.cancel();
13368 if (callback) {
13369 // if there's a callback, then the callback can receive
13370 // the error event
13371 callback(err);
13372 } else {
13373 // if there's no callback, then we're safe to emit an error
13374 // event, which would otherwise throw an unhandled error
13375 // due to 'error' being a special event in EventEmitters
13376 this.emit('error', err);
13377 }
13378 this.removeAllListeners();
13379 if (callback) {
13380 // no sense throwing if we're already emitting an 'error' event
13381 throw err;
13382 }
13383 });
13384
13385 this.then = function (success, err) {
13386 return promise.then(success, err);
13387 };
13388
13389 this["catch"] = function (err) {
13390 return promise["catch"](err);
13391 };
13392 }
13393
13394 cancel() {
13395 if (!this.canceled) {
13396 this.canceled = true;
13397 this.push.cancel();
13398 this.pull.cancel();
13399 }
13400 }
13401}
13402
13403function replication(PouchDB) {
13404 PouchDB.replicate = replicateWrapper;
13405 PouchDB.sync = sync;
13406
13407 Object.defineProperty(PouchDB.prototype, 'replicate', {
13408 get: function () {
13409 var self = this;
13410 if (typeof this.replicateMethods === 'undefined') {
13411 this.replicateMethods = {
13412 from: function (other, opts, callback) {
13413 return self.constructor.replicate(other, self, opts, callback);
13414 },
13415 to: function (other, opts, callback) {
13416 return self.constructor.replicate(self, other, opts, callback);
13417 }
13418 };
13419 }
13420 return this.replicateMethods;
13421 }
13422 });
13423
13424 PouchDB.prototype.sync = function (dbName, opts, callback) {
13425 return this.constructor.sync(this, dbName, opts, callback);
13426 };
13427}
13428
13429PouchDB.plugin(IDBPouch)
13430 .plugin(HttpPouch$1)
13431 .plugin(mapreduce)
13432 .plugin(replication);
13433
13434// Pull from src because pouchdb-node/pouchdb-browser themselves
13435
13436module.exports = PouchDB;
13437
13438}).call(this)}).call(this,_dereq_(9))
13439},{"10":10,"11":11,"2":2,"26":26,"3":3,"9":9}]},{},[27])(27)
13440});