UNPKG

375 kBJavaScriptView Raw
1// PouchDB 7.3.0
2//
3// (c) 2012-2022 Dale Harvey and the PouchDB team
4// PouchDB may be freely distributed under the Apache license, version 2.0.
5// For all details and documentation:
6// http://pouchdb.com
7(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.PouchDB = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(_dereq_,module,exports){
8'use strict';
9
10module.exports = argsArray;
11
12function argsArray(fun) {
13 return function () {
14 var len = arguments.length;
15 if (len) {
16 var args = [];
17 var i = -1;
18 while (++i < len) {
19 args[i] = arguments[i];
20 }
21 return fun.call(this, args);
22 } else {
23 return fun.call(this, []);
24 }
25 };
26}
27},{}],2:[function(_dereq_,module,exports){
28
29},{}],3:[function(_dereq_,module,exports){
30// Copyright Joyent, Inc. and other Node contributors.
31//
32// Permission is hereby granted, free of charge, to any person obtaining a
33// copy of this software and associated documentation files (the
34// "Software"), to deal in the Software without restriction, including
35// without limitation the rights to use, copy, modify, merge, publish,
36// distribute, sublicense, and/or sell copies of the Software, and to permit
37// persons to whom the Software is furnished to do so, subject to the
38// following conditions:
39//
40// The above copyright notice and this permission notice shall be included
41// in all copies or substantial portions of the Software.
42//
43// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
44// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
45// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
46// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
47// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
48// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
49// USE OR OTHER DEALINGS IN THE SOFTWARE.
50
51var objectCreate = Object.create || objectCreatePolyfill
52var objectKeys = Object.keys || objectKeysPolyfill
53var bind = Function.prototype.bind || functionBindPolyfill
54
55function EventEmitter() {
56 if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) {
57 this._events = objectCreate(null);
58 this._eventsCount = 0;
59 }
60
61 this._maxListeners = this._maxListeners || undefined;
62}
63module.exports = EventEmitter;
64
65// Backwards-compat with node 0.10.x
66EventEmitter.EventEmitter = EventEmitter;
67
68EventEmitter.prototype._events = undefined;
69EventEmitter.prototype._maxListeners = undefined;
70
71// By default EventEmitters will print a warning if more than 10 listeners are
72// added to it. This is a useful default which helps finding memory leaks.
73var defaultMaxListeners = 10;
74
75var hasDefineProperty;
76try {
77 var o = {};
78 if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 });
79 hasDefineProperty = o.x === 0;
80} catch (err) { hasDefineProperty = false }
81if (hasDefineProperty) {
82 Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
83 enumerable: true,
84 get: function() {
85 return defaultMaxListeners;
86 },
87 set: function(arg) {
88 // check whether the input is a positive number (whose value is zero or
89 // greater and not a NaN).
90 if (typeof arg !== 'number' || arg < 0 || arg !== arg)
91 throw new TypeError('"defaultMaxListeners" must be a positive number');
92 defaultMaxListeners = arg;
93 }
94 });
95} else {
96 EventEmitter.defaultMaxListeners = defaultMaxListeners;
97}
98
99// Obviously not all Emitters should be limited to 10. This function allows
100// that to be increased. Set to zero for unlimited.
101EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
102 if (typeof n !== 'number' || n < 0 || isNaN(n))
103 throw new TypeError('"n" argument must be a positive number');
104 this._maxListeners = n;
105 return this;
106};
107
108function $getMaxListeners(that) {
109 if (that._maxListeners === undefined)
110 return EventEmitter.defaultMaxListeners;
111 return that._maxListeners;
112}
113
114EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
115 return $getMaxListeners(this);
116};
117
118// These standalone emit* functions are used to optimize calling of event
119// handlers for fast cases because emit() itself often has a variable number of
120// arguments and can be deoptimized because of that. These functions always have
121// the same number of arguments and thus do not get deoptimized, so the code
122// inside them can execute faster.
123function emitNone(handler, isFn, self) {
124 if (isFn)
125 handler.call(self);
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);
131 }
132}
133function emitOne(handler, isFn, self, arg1) {
134 if (isFn)
135 handler.call(self, arg1);
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);
141 }
142}
143function emitTwo(handler, isFn, self, arg1, arg2) {
144 if (isFn)
145 handler.call(self, arg1, arg2);
146 else {
147 var len = handler.length;
148 var listeners = arrayClone(handler, len);
149 for (var i = 0; i < len; ++i)
150 listeners[i].call(self, arg1, arg2);
151 }
152}
153function emitThree(handler, isFn, self, arg1, arg2, arg3) {
154 if (isFn)
155 handler.call(self, arg1, arg2, arg3);
156 else {
157 var len = handler.length;
158 var listeners = arrayClone(handler, len);
159 for (var i = 0; i < len; ++i)
160 listeners[i].call(self, arg1, arg2, arg3);
161 }
162}
163
164function emitMany(handler, isFn, self, args) {
165 if (isFn)
166 handler.apply(self, args);
167 else {
168 var len = handler.length;
169 var listeners = arrayClone(handler, len);
170 for (var i = 0; i < len; ++i)
171 listeners[i].apply(self, args);
172 }
173}
174
175EventEmitter.prototype.emit = function emit(type) {
176 var er, handler, len, args, i, events;
177 var doError = (type === 'error');
178
179 events = this._events;
180 if (events)
181 doError = (doError && events.error == null);
182 else if (!doError)
183 return false;
184
185 // If there is no 'error' event listener then throw.
186 if (doError) {
187 if (arguments.length > 1)
188 er = arguments[1];
189 if (er instanceof Error) {
190 throw er; // Unhandled 'error' event
191 } else {
192 // At least give some kind of context to the user
193 var err = new Error('Unhandled "error" event. (' + er + ')');
194 err.context = er;
195 throw err;
196 }
197 return false;
198 }
199
200 handler = events[type];
201
202 if (!handler)
203 return false;
204
205 var isFn = typeof handler === 'function';
206 len = arguments.length;
207 switch (len) {
208 // fast cases
209 case 1:
210 emitNone(handler, isFn, this);
211 break;
212 case 2:
213 emitOne(handler, isFn, this, arguments[1]);
214 break;
215 case 3:
216 emitTwo(handler, isFn, this, arguments[1], arguments[2]);
217 break;
218 case 4:
219 emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
220 break;
221 // slower
222 default:
223 args = new Array(len - 1);
224 for (i = 1; i < len; i++)
225 args[i - 1] = arguments[i];
226 emitMany(handler, isFn, this, args);
227 }
228
229 return true;
230};
231
232function _addListener(target, type, listener, prepend) {
233 var m;
234 var events;
235 var existing;
236
237 if (typeof listener !== 'function')
238 throw new TypeError('"listener" argument must be a function');
239
240 events = target._events;
241 if (!events) {
242 events = target._events = objectCreate(null);
243 target._eventsCount = 0;
244 } else {
245 // To avoid recursion in the case that type === "newListener"! Before
246 // adding it to the listeners, first emit "newListener".
247 if (events.newListener) {
248 target.emit('newListener', type,
249 listener.listener ? listener.listener : listener);
250
251 // Re-assign `events` because a newListener handler could have caused the
252 // this._events to be assigned to a new object
253 events = target._events;
254 }
255 existing = events[type];
256 }
257
258 if (!existing) {
259 // Optimize the case of one listener. Don't need the extra array object.
260 existing = events[type] = listener;
261 ++target._eventsCount;
262 } else {
263 if (typeof existing === 'function') {
264 // Adding the second element, need to change to array.
265 existing = events[type] =
266 prepend ? [listener, existing] : [existing, listener];
267 } else {
268 // If we've already got an array, just append.
269 if (prepend) {
270 existing.unshift(listener);
271 } else {
272 existing.push(listener);
273 }
274 }
275
276 // Check for listener leak
277 if (!existing.warned) {
278 m = $getMaxListeners(target);
279 if (m && m > 0 && existing.length > m) {
280 existing.warned = true;
281 var w = new Error('Possible EventEmitter memory leak detected. ' +
282 existing.length + ' "' + String(type) + '" listeners ' +
283 'added. Use emitter.setMaxListeners() to ' +
284 'increase limit.');
285 w.name = 'MaxListenersExceededWarning';
286 w.emitter = target;
287 w.type = type;
288 w.count = existing.length;
289 if (typeof console === 'object' && console.warn) {
290 console.warn('%s: %s', w.name, w.message);
291 }
292 }
293 }
294 }
295
296 return target;
297}
298
299EventEmitter.prototype.addListener = function addListener(type, listener) {
300 return _addListener(this, type, listener, false);
301};
302
303EventEmitter.prototype.on = EventEmitter.prototype.addListener;
304
305EventEmitter.prototype.prependListener =
306 function prependListener(type, listener) {
307 return _addListener(this, type, listener, true);
308 };
309
310function onceWrapper() {
311 if (!this.fired) {
312 this.target.removeListener(this.type, this.wrapFn);
313 this.fired = true;
314 switch (arguments.length) {
315 case 0:
316 return this.listener.call(this.target);
317 case 1:
318 return this.listener.call(this.target, arguments[0]);
319 case 2:
320 return this.listener.call(this.target, arguments[0], arguments[1]);
321 case 3:
322 return this.listener.call(this.target, arguments[0], arguments[1],
323 arguments[2]);
324 default:
325 var args = new Array(arguments.length);
326 for (var i = 0; i < args.length; ++i)
327 args[i] = arguments[i];
328 this.listener.apply(this.target, args);
329 }
330 }
331}
332
333function _onceWrap(target, type, listener) {
334 var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
335 var wrapped = bind.call(onceWrapper, state);
336 wrapped.listener = listener;
337 state.wrapFn = wrapped;
338 return wrapped;
339}
340
341EventEmitter.prototype.once = function once(type, listener) {
342 if (typeof listener !== 'function')
343 throw new TypeError('"listener" argument must be a function');
344 this.on(type, _onceWrap(this, type, listener));
345 return this;
346};
347
348EventEmitter.prototype.prependOnceListener =
349 function prependOnceListener(type, listener) {
350 if (typeof listener !== 'function')
351 throw new TypeError('"listener" argument must be a function');
352 this.prependListener(type, _onceWrap(this, type, listener));
353 return this;
354 };
355
356// Emits a 'removeListener' event if and only if the listener was removed.
357EventEmitter.prototype.removeListener =
358 function removeListener(type, listener) {
359 var list, events, position, i, originalListener;
360
361 if (typeof listener !== 'function')
362 throw new TypeError('"listener" argument must be a function');
363
364 events = this._events;
365 if (!events)
366 return this;
367
368 list = events[type];
369 if (!list)
370 return this;
371
372 if (list === listener || list.listener === listener) {
373 if (--this._eventsCount === 0)
374 this._events = objectCreate(null);
375 else {
376 delete events[type];
377 if (events.removeListener)
378 this.emit('removeListener', type, list.listener || listener);
379 }
380 } else if (typeof list !== 'function') {
381 position = -1;
382
383 for (i = list.length - 1; i >= 0; i--) {
384 if (list[i] === listener || list[i].listener === listener) {
385 originalListener = list[i].listener;
386 position = i;
387 break;
388 }
389 }
390
391 if (position < 0)
392 return this;
393
394 if (position === 0)
395 list.shift();
396 else
397 spliceOne(list, position);
398
399 if (list.length === 1)
400 events[type] = list[0];
401
402 if (events.removeListener)
403 this.emit('removeListener', type, originalListener || listener);
404 }
405
406 return this;
407 };
408
409EventEmitter.prototype.removeAllListeners =
410 function removeAllListeners(type) {
411 var listeners, events, i;
412
413 events = this._events;
414 if (!events)
415 return this;
416
417 // not listening for removeListener, no need to emit
418 if (!events.removeListener) {
419 if (arguments.length === 0) {
420 this._events = objectCreate(null);
421 this._eventsCount = 0;
422 } else if (events[type]) {
423 if (--this._eventsCount === 0)
424 this._events = objectCreate(null);
425 else
426 delete events[type];
427 }
428 return this;
429 }
430
431 // emit removeListener for all listeners on all events
432 if (arguments.length === 0) {
433 var keys = objectKeys(events);
434 var key;
435 for (i = 0; i < keys.length; ++i) {
436 key = keys[i];
437 if (key === 'removeListener') continue;
438 this.removeAllListeners(key);
439 }
440 this.removeAllListeners('removeListener');
441 this._events = objectCreate(null);
442 this._eventsCount = 0;
443 return this;
444 }
445
446 listeners = events[type];
447
448 if (typeof listeners === 'function') {
449 this.removeListener(type, listeners);
450 } else if (listeners) {
451 // LIFO order
452 for (i = listeners.length - 1; i >= 0; i--) {
453 this.removeListener(type, listeners[i]);
454 }
455 }
456
457 return this;
458 };
459
460function _listeners(target, type, unwrap) {
461 var events = target._events;
462
463 if (!events)
464 return [];
465
466 var evlistener = events[type];
467 if (!evlistener)
468 return [];
469
470 if (typeof evlistener === 'function')
471 return unwrap ? [evlistener.listener || evlistener] : [evlistener];
472
473 return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
474}
475
476EventEmitter.prototype.listeners = function listeners(type) {
477 return _listeners(this, type, true);
478};
479
480EventEmitter.prototype.rawListeners = function rawListeners(type) {
481 return _listeners(this, type, false);
482};
483
484EventEmitter.listenerCount = function(emitter, type) {
485 if (typeof emitter.listenerCount === 'function') {
486 return emitter.listenerCount(type);
487 } else {
488 return listenerCount.call(emitter, type);
489 }
490};
491
492EventEmitter.prototype.listenerCount = listenerCount;
493function listenerCount(type) {
494 var events = this._events;
495
496 if (events) {
497 var evlistener = events[type];
498
499 if (typeof evlistener === 'function') {
500 return 1;
501 } else if (evlistener) {
502 return evlistener.length;
503 }
504 }
505
506 return 0;
507}
508
509EventEmitter.prototype.eventNames = function eventNames() {
510 return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
511};
512
513// About 1.5x faster than the two-arg version of Array#splice().
514function spliceOne(list, index) {
515 for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
516 list[i] = list[k];
517 list.pop();
518}
519
520function arrayClone(arr, n) {
521 var copy = new Array(n);
522 for (var i = 0; i < n; ++i)
523 copy[i] = arr[i];
524 return copy;
525}
526
527function unwrapListeners(arr) {
528 var ret = new Array(arr.length);
529 for (var i = 0; i < ret.length; ++i) {
530 ret[i] = arr[i].listener || arr[i];
531 }
532 return ret;
533}
534
535function objectCreatePolyfill(proto) {
536 var F = function() {};
537 F.prototype = proto;
538 return new F;
539}
540function objectKeysPolyfill(obj) {
541 var keys = [];
542 for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) {
543 keys.push(k);
544 }
545 return k;
546}
547function functionBindPolyfill(context) {
548 var fn = this;
549 return function () {
550 return fn.apply(context, arguments);
551 };
552}
553
554},{}],4:[function(_dereq_,module,exports){
555'use strict';
556var types = [
557 _dereq_(2),
558 _dereq_(7),
559 _dereq_(6),
560 _dereq_(5),
561 _dereq_(8),
562 _dereq_(9)
563];
564var draining;
565var currentQueue;
566var queueIndex = -1;
567var queue = [];
568var scheduled = false;
569function cleanUpNextTick() {
570 if (!draining || !currentQueue) {
571 return;
572 }
573 draining = false;
574 if (currentQueue.length) {
575 queue = currentQueue.concat(queue);
576 } else {
577 queueIndex = -1;
578 }
579 if (queue.length) {
580 nextTick();
581 }
582}
583
584//named nextTick for less confusing stack traces
585function nextTick() {
586 if (draining) {
587 return;
588 }
589 scheduled = false;
590 draining = true;
591 var len = queue.length;
592 var timeout = setTimeout(cleanUpNextTick);
593 while (len) {
594 currentQueue = queue;
595 queue = [];
596 while (currentQueue && ++queueIndex < len) {
597 currentQueue[queueIndex].run();
598 }
599 queueIndex = -1;
600 len = queue.length;
601 }
602 currentQueue = null;
603 queueIndex = -1;
604 draining = false;
605 clearTimeout(timeout);
606}
607var scheduleDrain;
608var i = -1;
609var len = types.length;
610while (++i < len) {
611 if (types[i] && types[i].test && types[i].test()) {
612 scheduleDrain = types[i].install(nextTick);
613 break;
614 }
615}
616// v8 likes predictible objects
617function Item(fun, array) {
618 this.fun = fun;
619 this.array = array;
620}
621Item.prototype.run = function () {
622 var fun = this.fun;
623 var array = this.array;
624 switch (array.length) {
625 case 0:
626 return fun();
627 case 1:
628 return fun(array[0]);
629 case 2:
630 return fun(array[0], array[1]);
631 case 3:
632 return fun(array[0], array[1], array[2]);
633 default:
634 return fun.apply(null, array);
635 }
636
637};
638module.exports = immediate;
639function immediate(task) {
640 var args = new Array(arguments.length - 1);
641 if (arguments.length > 1) {
642 for (var i = 1; i < arguments.length; i++) {
643 args[i - 1] = arguments[i];
644 }
645 }
646 queue.push(new Item(task, args));
647 if (!scheduled && !draining) {
648 scheduled = true;
649 scheduleDrain();
650 }
651}
652
653},{"2":2,"5":5,"6":6,"7":7,"8":8,"9":9}],5:[function(_dereq_,module,exports){
654(function (global){(function (){
655'use strict';
656
657exports.test = function () {
658 if (global.setImmediate) {
659 // we can only get here in IE10
660 // which doesn't handel postMessage well
661 return false;
662 }
663 return typeof global.MessageChannel !== 'undefined';
664};
665
666exports.install = function (func) {
667 var channel = new global.MessageChannel();
668 channel.port1.onmessage = func;
669 return function () {
670 channel.port2.postMessage(0);
671 };
672};
673}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
674},{}],6:[function(_dereq_,module,exports){
675(function (global){(function (){
676'use strict';
677//based off rsvp https://github.com/tildeio/rsvp.js
678//license https://github.com/tildeio/rsvp.js/blob/master/LICENSE
679//https://github.com/tildeio/rsvp.js/blob/master/lib/rsvp/asap.js
680
681var Mutation = global.MutationObserver || global.WebKitMutationObserver;
682
683exports.test = function () {
684 return Mutation;
685};
686
687exports.install = function (handle) {
688 var called = 0;
689 var observer = new Mutation(handle);
690 var element = global.document.createTextNode('');
691 observer.observe(element, {
692 characterData: true
693 });
694 return function () {
695 element.data = (called = ++called % 2);
696 };
697};
698}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
699},{}],7:[function(_dereq_,module,exports){
700(function (global){(function (){
701'use strict';
702exports.test = function () {
703 return typeof global.queueMicrotask === 'function';
704};
705
706exports.install = function (func) {
707 return function () {
708 global.queueMicrotask(func);
709 };
710};
711
712}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
713},{}],8:[function(_dereq_,module,exports){
714(function (global){(function (){
715'use strict';
716
717exports.test = function () {
718 return 'document' in global && 'onreadystatechange' in global.document.createElement('script');
719};
720
721exports.install = function (handle) {
722 return function () {
723
724 // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
725 // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
726 var scriptEl = global.document.createElement('script');
727 scriptEl.onreadystatechange = function () {
728 handle();
729
730 scriptEl.onreadystatechange = null;
731 scriptEl.parentNode.removeChild(scriptEl);
732 scriptEl = null;
733 };
734 global.document.documentElement.appendChild(scriptEl);
735
736 return handle;
737 };
738};
739}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
740},{}],9:[function(_dereq_,module,exports){
741'use strict';
742exports.test = function () {
743 return true;
744};
745
746exports.install = function (t) {
747 return function () {
748 setTimeout(t, 0);
749 };
750};
751},{}],10:[function(_dereq_,module,exports){
752if (typeof Object.create === 'function') {
753 // implementation from standard node.js 'util' module
754 module.exports = function inherits(ctor, superCtor) {
755 if (superCtor) {
756 ctor.super_ = superCtor
757 ctor.prototype = Object.create(superCtor.prototype, {
758 constructor: {
759 value: ctor,
760 enumerable: false,
761 writable: true,
762 configurable: true
763 }
764 })
765 }
766 };
767} else {
768 // old school shim for old browsers
769 module.exports = function inherits(ctor, superCtor) {
770 if (superCtor) {
771 ctor.super_ = superCtor
772 var TempCtor = function () {}
773 TempCtor.prototype = superCtor.prototype
774 ctor.prototype = new TempCtor()
775 ctor.prototype.constructor = ctor
776 }
777 }
778}
779
780},{}],11:[function(_dereq_,module,exports){
781// shim for using process in browser
782var process = module.exports = {};
783
784// cached from whatever global is present so that test runners that stub it
785// don't break things. But we need to wrap it in a try catch in case it is
786// wrapped in strict mode code which doesn't define any globals. It's inside a
787// function because try/catches deoptimize in certain engines.
788
789var cachedSetTimeout;
790var cachedClearTimeout;
791
792function defaultSetTimout() {
793 throw new Error('setTimeout has not been defined');
794}
795function defaultClearTimeout () {
796 throw new Error('clearTimeout has not been defined');
797}
798(function () {
799 try {
800 if (typeof setTimeout === 'function') {
801 cachedSetTimeout = setTimeout;
802 } else {
803 cachedSetTimeout = defaultSetTimout;
804 }
805 } catch (e) {
806 cachedSetTimeout = defaultSetTimout;
807 }
808 try {
809 if (typeof clearTimeout === 'function') {
810 cachedClearTimeout = clearTimeout;
811 } else {
812 cachedClearTimeout = defaultClearTimeout;
813 }
814 } catch (e) {
815 cachedClearTimeout = defaultClearTimeout;
816 }
817} ())
818function runTimeout(fun) {
819 if (cachedSetTimeout === setTimeout) {
820 //normal enviroments in sane situations
821 return setTimeout(fun, 0);
822 }
823 // if setTimeout wasn't available but was latter defined
824 if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
825 cachedSetTimeout = setTimeout;
826 return setTimeout(fun, 0);
827 }
828 try {
829 // when when somebody has screwed with setTimeout but no I.E. maddness
830 return cachedSetTimeout(fun, 0);
831 } catch(e){
832 try {
833 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
834 return cachedSetTimeout.call(null, fun, 0);
835 } catch(e){
836 // 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
837 return cachedSetTimeout.call(this, fun, 0);
838 }
839 }
840
841
842}
843function runClearTimeout(marker) {
844 if (cachedClearTimeout === clearTimeout) {
845 //normal enviroments in sane situations
846 return clearTimeout(marker);
847 }
848 // if clearTimeout wasn't available but was latter defined
849 if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
850 cachedClearTimeout = clearTimeout;
851 return clearTimeout(marker);
852 }
853 try {
854 // when when somebody has screwed with setTimeout but no I.E. maddness
855 return cachedClearTimeout(marker);
856 } catch (e){
857 try {
858 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
859 return cachedClearTimeout.call(null, marker);
860 } catch (e){
861 // 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.
862 // Some versions of I.E. have different rules for clearTimeout vs setTimeout
863 return cachedClearTimeout.call(this, marker);
864 }
865 }
866
867
868
869}
870var queue = [];
871var draining = false;
872var currentQueue;
873var queueIndex = -1;
874
875function cleanUpNextTick() {
876 if (!draining || !currentQueue) {
877 return;
878 }
879 draining = false;
880 if (currentQueue.length) {
881 queue = currentQueue.concat(queue);
882 } else {
883 queueIndex = -1;
884 }
885 if (queue.length) {
886 drainQueue();
887 }
888}
889
890function drainQueue() {
891 if (draining) {
892 return;
893 }
894 var timeout = runTimeout(cleanUpNextTick);
895 draining = true;
896
897 var len = queue.length;
898 while(len) {
899 currentQueue = queue;
900 queue = [];
901 while (++queueIndex < len) {
902 if (currentQueue) {
903 currentQueue[queueIndex].run();
904 }
905 }
906 queueIndex = -1;
907 len = queue.length;
908 }
909 currentQueue = null;
910 draining = false;
911 runClearTimeout(timeout);
912}
913
914process.nextTick = function (fun) {
915 var args = new Array(arguments.length - 1);
916 if (arguments.length > 1) {
917 for (var i = 1; i < arguments.length; i++) {
918 args[i - 1] = arguments[i];
919 }
920 }
921 queue.push(new Item(fun, args));
922 if (queue.length === 1 && !draining) {
923 runTimeout(drainQueue);
924 }
925};
926
927// v8 likes predictible objects
928function Item(fun, array) {
929 this.fun = fun;
930 this.array = array;
931}
932Item.prototype.run = function () {
933 this.fun.apply(null, this.array);
934};
935process.title = 'browser';
936process.browser = true;
937process.env = {};
938process.argv = [];
939process.version = ''; // empty string to avoid regexp issues
940process.versions = {};
941
942function noop() {}
943
944process.on = noop;
945process.addListener = noop;
946process.once = noop;
947process.off = noop;
948process.removeListener = noop;
949process.removeAllListeners = noop;
950process.emit = noop;
951process.prependListener = noop;
952process.prependOnceListener = noop;
953
954process.listeners = function (name) { return [] }
955
956process.binding = function (name) {
957 throw new Error('process.binding is not supported');
958};
959
960process.cwd = function () { return '/' };
961process.chdir = function (dir) {
962 throw new Error('process.chdir is not supported');
963};
964process.umask = function() { return 0; };
965
966},{}],12:[function(_dereq_,module,exports){
967(function (factory) {
968 if (typeof exports === 'object') {
969 // Node/CommonJS
970 module.exports = factory();
971 } else if (typeof define === 'function' && define.amd) {
972 // AMD
973 define(factory);
974 } else {
975 // Browser globals (with support for web workers)
976 var glob;
977
978 try {
979 glob = window;
980 } catch (e) {
981 glob = self;
982 }
983
984 glob.SparkMD5 = factory();
985 }
986}(function (undefined) {
987
988 'use strict';
989
990 /*
991 * Fastest md5 implementation around (JKM md5).
992 * Credits: Joseph Myers
993 *
994 * @see http://www.myersdaily.org/joseph/javascript/md5-text.html
995 * @see http://jsperf.com/md5-shootout/7
996 */
997
998 /* this function is much faster,
999 so if possible we use it. Some IEs
1000 are the only ones I know of that
1001 need the idiotic second function,
1002 generated by an if clause. */
1003 var add32 = function (a, b) {
1004 return (a + b) & 0xFFFFFFFF;
1005 },
1006 hex_chr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
1007
1008
1009 function cmn(q, a, b, x, s, t) {
1010 a = add32(add32(a, q), add32(x, t));
1011 return add32((a << s) | (a >>> (32 - s)), b);
1012 }
1013
1014 function md5cycle(x, k) {
1015 var a = x[0],
1016 b = x[1],
1017 c = x[2],
1018 d = x[3];
1019
1020 a += (b & c | ~b & d) + k[0] - 680876936 | 0;
1021 a = (a << 7 | a >>> 25) + b | 0;
1022 d += (a & b | ~a & c) + k[1] - 389564586 | 0;
1023 d = (d << 12 | d >>> 20) + a | 0;
1024 c += (d & a | ~d & b) + k[2] + 606105819 | 0;
1025 c = (c << 17 | c >>> 15) + d | 0;
1026 b += (c & d | ~c & a) + k[3] - 1044525330 | 0;
1027 b = (b << 22 | b >>> 10) + c | 0;
1028 a += (b & c | ~b & d) + k[4] - 176418897 | 0;
1029 a = (a << 7 | a >>> 25) + b | 0;
1030 d += (a & b | ~a & c) + k[5] + 1200080426 | 0;
1031 d = (d << 12 | d >>> 20) + a | 0;
1032 c += (d & a | ~d & b) + k[6] - 1473231341 | 0;
1033 c = (c << 17 | c >>> 15) + d | 0;
1034 b += (c & d | ~c & a) + k[7] - 45705983 | 0;
1035 b = (b << 22 | b >>> 10) + c | 0;
1036 a += (b & c | ~b & d) + k[8] + 1770035416 | 0;
1037 a = (a << 7 | a >>> 25) + b | 0;
1038 d += (a & b | ~a & c) + k[9] - 1958414417 | 0;
1039 d = (d << 12 | d >>> 20) + a | 0;
1040 c += (d & a | ~d & b) + k[10] - 42063 | 0;
1041 c = (c << 17 | c >>> 15) + d | 0;
1042 b += (c & d | ~c & a) + k[11] - 1990404162 | 0;
1043 b = (b << 22 | b >>> 10) + c | 0;
1044 a += (b & c | ~b & d) + k[12] + 1804603682 | 0;
1045 a = (a << 7 | a >>> 25) + b | 0;
1046 d += (a & b | ~a & c) + k[13] - 40341101 | 0;
1047 d = (d << 12 | d >>> 20) + a | 0;
1048 c += (d & a | ~d & b) + k[14] - 1502002290 | 0;
1049 c = (c << 17 | c >>> 15) + d | 0;
1050 b += (c & d | ~c & a) + k[15] + 1236535329 | 0;
1051 b = (b << 22 | b >>> 10) + c | 0;
1052
1053 a += (b & d | c & ~d) + k[1] - 165796510 | 0;
1054 a = (a << 5 | a >>> 27) + b | 0;
1055 d += (a & c | b & ~c) + k[6] - 1069501632 | 0;
1056 d = (d << 9 | d >>> 23) + a | 0;
1057 c += (d & b | a & ~b) + k[11] + 643717713 | 0;
1058 c = (c << 14 | c >>> 18) + d | 0;
1059 b += (c & a | d & ~a) + k[0] - 373897302 | 0;
1060 b = (b << 20 | b >>> 12) + c | 0;
1061 a += (b & d | c & ~d) + k[5] - 701558691 | 0;
1062 a = (a << 5 | a >>> 27) + b | 0;
1063 d += (a & c | b & ~c) + k[10] + 38016083 | 0;
1064 d = (d << 9 | d >>> 23) + a | 0;
1065 c += (d & b | a & ~b) + k[15] - 660478335 | 0;
1066 c = (c << 14 | c >>> 18) + d | 0;
1067 b += (c & a | d & ~a) + k[4] - 405537848 | 0;
1068 b = (b << 20 | b >>> 12) + c | 0;
1069 a += (b & d | c & ~d) + k[9] + 568446438 | 0;
1070 a = (a << 5 | a >>> 27) + b | 0;
1071 d += (a & c | b & ~c) + k[14] - 1019803690 | 0;
1072 d = (d << 9 | d >>> 23) + a | 0;
1073 c += (d & b | a & ~b) + k[3] - 187363961 | 0;
1074 c = (c << 14 | c >>> 18) + d | 0;
1075 b += (c & a | d & ~a) + k[8] + 1163531501 | 0;
1076 b = (b << 20 | b >>> 12) + c | 0;
1077 a += (b & d | c & ~d) + k[13] - 1444681467 | 0;
1078 a = (a << 5 | a >>> 27) + b | 0;
1079 d += (a & c | b & ~c) + k[2] - 51403784 | 0;
1080 d = (d << 9 | d >>> 23) + a | 0;
1081 c += (d & b | a & ~b) + k[7] + 1735328473 | 0;
1082 c = (c << 14 | c >>> 18) + d | 0;
1083 b += (c & a | d & ~a) + k[12] - 1926607734 | 0;
1084 b = (b << 20 | b >>> 12) + c | 0;
1085
1086 a += (b ^ c ^ d) + k[5] - 378558 | 0;
1087 a = (a << 4 | a >>> 28) + b | 0;
1088 d += (a ^ b ^ c) + k[8] - 2022574463 | 0;
1089 d = (d << 11 | d >>> 21) + a | 0;
1090 c += (d ^ a ^ b) + k[11] + 1839030562 | 0;
1091 c = (c << 16 | c >>> 16) + d | 0;
1092 b += (c ^ d ^ a) + k[14] - 35309556 | 0;
1093 b = (b << 23 | b >>> 9) + c | 0;
1094 a += (b ^ c ^ d) + k[1] - 1530992060 | 0;
1095 a = (a << 4 | a >>> 28) + b | 0;
1096 d += (a ^ b ^ c) + k[4] + 1272893353 | 0;
1097 d = (d << 11 | d >>> 21) + a | 0;
1098 c += (d ^ a ^ b) + k[7] - 155497632 | 0;
1099 c = (c << 16 | c >>> 16) + d | 0;
1100 b += (c ^ d ^ a) + k[10] - 1094730640 | 0;
1101 b = (b << 23 | b >>> 9) + c | 0;
1102 a += (b ^ c ^ d) + k[13] + 681279174 | 0;
1103 a = (a << 4 | a >>> 28) + b | 0;
1104 d += (a ^ b ^ c) + k[0] - 358537222 | 0;
1105 d = (d << 11 | d >>> 21) + a | 0;
1106 c += (d ^ a ^ b) + k[3] - 722521979 | 0;
1107 c = (c << 16 | c >>> 16) + d | 0;
1108 b += (c ^ d ^ a) + k[6] + 76029189 | 0;
1109 b = (b << 23 | b >>> 9) + c | 0;
1110 a += (b ^ c ^ d) + k[9] - 640364487 | 0;
1111 a = (a << 4 | a >>> 28) + b | 0;
1112 d += (a ^ b ^ c) + k[12] - 421815835 | 0;
1113 d = (d << 11 | d >>> 21) + a | 0;
1114 c += (d ^ a ^ b) + k[15] + 530742520 | 0;
1115 c = (c << 16 | c >>> 16) + d | 0;
1116 b += (c ^ d ^ a) + k[2] - 995338651 | 0;
1117 b = (b << 23 | b >>> 9) + c | 0;
1118
1119 a += (c ^ (b | ~d)) + k[0] - 198630844 | 0;
1120 a = (a << 6 | a >>> 26) + b | 0;
1121 d += (b ^ (a | ~c)) + k[7] + 1126891415 | 0;
1122 d = (d << 10 | d >>> 22) + a | 0;
1123 c += (a ^ (d | ~b)) + k[14] - 1416354905 | 0;
1124 c = (c << 15 | c >>> 17) + d | 0;
1125 b += (d ^ (c | ~a)) + k[5] - 57434055 | 0;
1126 b = (b << 21 |b >>> 11) + c | 0;
1127 a += (c ^ (b | ~d)) + k[12] + 1700485571 | 0;
1128 a = (a << 6 | a >>> 26) + b | 0;
1129 d += (b ^ (a | ~c)) + k[3] - 1894986606 | 0;
1130 d = (d << 10 | d >>> 22) + a | 0;
1131 c += (a ^ (d | ~b)) + k[10] - 1051523 | 0;
1132 c = (c << 15 | c >>> 17) + d | 0;
1133 b += (d ^ (c | ~a)) + k[1] - 2054922799 | 0;
1134 b = (b << 21 |b >>> 11) + c | 0;
1135 a += (c ^ (b | ~d)) + k[8] + 1873313359 | 0;
1136 a = (a << 6 | a >>> 26) + b | 0;
1137 d += (b ^ (a | ~c)) + k[15] - 30611744 | 0;
1138 d = (d << 10 | d >>> 22) + a | 0;
1139 c += (a ^ (d | ~b)) + k[6] - 1560198380 | 0;
1140 c = (c << 15 | c >>> 17) + d | 0;
1141 b += (d ^ (c | ~a)) + k[13] + 1309151649 | 0;
1142 b = (b << 21 |b >>> 11) + c | 0;
1143 a += (c ^ (b | ~d)) + k[4] - 145523070 | 0;
1144 a = (a << 6 | a >>> 26) + b | 0;
1145 d += (b ^ (a | ~c)) + k[11] - 1120210379 | 0;
1146 d = (d << 10 | d >>> 22) + a | 0;
1147 c += (a ^ (d | ~b)) + k[2] + 718787259 | 0;
1148 c = (c << 15 | c >>> 17) + d | 0;
1149 b += (d ^ (c | ~a)) + k[9] - 343485551 | 0;
1150 b = (b << 21 | b >>> 11) + c | 0;
1151
1152 x[0] = a + x[0] | 0;
1153 x[1] = b + x[1] | 0;
1154 x[2] = c + x[2] | 0;
1155 x[3] = d + x[3] | 0;
1156 }
1157
1158 function md5blk(s) {
1159 var md5blks = [],
1160 i; /* Andy King said do it this way. */
1161
1162 for (i = 0; i < 64; i += 4) {
1163 md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) << 24);
1164 }
1165 return md5blks;
1166 }
1167
1168 function md5blk_array(a) {
1169 var md5blks = [],
1170 i; /* Andy King said do it this way. */
1171
1172 for (i = 0; i < 64; i += 4) {
1173 md5blks[i >> 2] = a[i] + (a[i + 1] << 8) + (a[i + 2] << 16) + (a[i + 3] << 24);
1174 }
1175 return md5blks;
1176 }
1177
1178 function md51(s) {
1179 var n = s.length,
1180 state = [1732584193, -271733879, -1732584194, 271733878],
1181 i,
1182 length,
1183 tail,
1184 tmp,
1185 lo,
1186 hi;
1187
1188 for (i = 64; i <= n; i += 64) {
1189 md5cycle(state, md5blk(s.substring(i - 64, i)));
1190 }
1191 s = s.substring(i - 64);
1192 length = s.length;
1193 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
1194 for (i = 0; i < length; i += 1) {
1195 tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3);
1196 }
1197 tail[i >> 2] |= 0x80 << ((i % 4) << 3);
1198 if (i > 55) {
1199 md5cycle(state, tail);
1200 for (i = 0; i < 16; i += 1) {
1201 tail[i] = 0;
1202 }
1203 }
1204
1205 // Beware that the final length might not fit in 32 bits so we take care of that
1206 tmp = n * 8;
1207 tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
1208 lo = parseInt(tmp[2], 16);
1209 hi = parseInt(tmp[1], 16) || 0;
1210
1211 tail[14] = lo;
1212 tail[15] = hi;
1213
1214 md5cycle(state, tail);
1215 return state;
1216 }
1217
1218 function md51_array(a) {
1219 var n = a.length,
1220 state = [1732584193, -271733879, -1732584194, 271733878],
1221 i,
1222 length,
1223 tail,
1224 tmp,
1225 lo,
1226 hi;
1227
1228 for (i = 64; i <= n; i += 64) {
1229 md5cycle(state, md5blk_array(a.subarray(i - 64, i)));
1230 }
1231
1232 // Not sure if it is a bug, however IE10 will always produce a sub array of length 1
1233 // containing the last element of the parent array if the sub array specified starts
1234 // beyond the length of the parent array - weird.
1235 // https://connect.microsoft.com/IE/feedback/details/771452/typed-array-subarray-issue
1236 a = (i - 64) < n ? a.subarray(i - 64) : new Uint8Array(0);
1237
1238 length = a.length;
1239 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
1240 for (i = 0; i < length; i += 1) {
1241 tail[i >> 2] |= a[i] << ((i % 4) << 3);
1242 }
1243
1244 tail[i >> 2] |= 0x80 << ((i % 4) << 3);
1245 if (i > 55) {
1246 md5cycle(state, tail);
1247 for (i = 0; i < 16; i += 1) {
1248 tail[i] = 0;
1249 }
1250 }
1251
1252 // Beware that the final length might not fit in 32 bits so we take care of that
1253 tmp = n * 8;
1254 tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
1255 lo = parseInt(tmp[2], 16);
1256 hi = parseInt(tmp[1], 16) || 0;
1257
1258 tail[14] = lo;
1259 tail[15] = hi;
1260
1261 md5cycle(state, tail);
1262
1263 return state;
1264 }
1265
1266 function rhex(n) {
1267 var s = '',
1268 j;
1269 for (j = 0; j < 4; j += 1) {
1270 s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F];
1271 }
1272 return s;
1273 }
1274
1275 function hex(x) {
1276 var i;
1277 for (i = 0; i < x.length; i += 1) {
1278 x[i] = rhex(x[i]);
1279 }
1280 return x.join('');
1281 }
1282
1283 // In some cases the fast add32 function cannot be used..
1284 if (hex(md51('hello')) !== '5d41402abc4b2a76b9719d911017c592') {
1285 add32 = function (x, y) {
1286 var lsw = (x & 0xFFFF) + (y & 0xFFFF),
1287 msw = (x >> 16) + (y >> 16) + (lsw >> 16);
1288 return (msw << 16) | (lsw & 0xFFFF);
1289 };
1290 }
1291
1292 // ---------------------------------------------------
1293
1294 /**
1295 * ArrayBuffer slice polyfill.
1296 *
1297 * @see https://github.com/ttaubert/node-arraybuffer-slice
1298 */
1299
1300 if (typeof ArrayBuffer !== 'undefined' && !ArrayBuffer.prototype.slice) {
1301 (function () {
1302 function clamp(val, length) {
1303 val = (val | 0) || 0;
1304
1305 if (val < 0) {
1306 return Math.max(val + length, 0);
1307 }
1308
1309 return Math.min(val, length);
1310 }
1311
1312 ArrayBuffer.prototype.slice = function (from, to) {
1313 var length = this.byteLength,
1314 begin = clamp(from, length),
1315 end = length,
1316 num,
1317 target,
1318 targetArray,
1319 sourceArray;
1320
1321 if (to !== undefined) {
1322 end = clamp(to, length);
1323 }
1324
1325 if (begin > end) {
1326 return new ArrayBuffer(0);
1327 }
1328
1329 num = end - begin;
1330 target = new ArrayBuffer(num);
1331 targetArray = new Uint8Array(target);
1332
1333 sourceArray = new Uint8Array(this, begin, num);
1334 targetArray.set(sourceArray);
1335
1336 return target;
1337 };
1338 })();
1339 }
1340
1341 // ---------------------------------------------------
1342
1343 /**
1344 * Helpers.
1345 */
1346
1347 function toUtf8(str) {
1348 if (/[\u0080-\uFFFF]/.test(str)) {
1349 str = unescape(encodeURIComponent(str));
1350 }
1351
1352 return str;
1353 }
1354
1355 function utf8Str2ArrayBuffer(str, returnUInt8Array) {
1356 var length = str.length,
1357 buff = new ArrayBuffer(length),
1358 arr = new Uint8Array(buff),
1359 i;
1360
1361 for (i = 0; i < length; i += 1) {
1362 arr[i] = str.charCodeAt(i);
1363 }
1364
1365 return returnUInt8Array ? arr : buff;
1366 }
1367
1368 function arrayBuffer2Utf8Str(buff) {
1369 return String.fromCharCode.apply(null, new Uint8Array(buff));
1370 }
1371
1372 function concatenateArrayBuffers(first, second, returnUInt8Array) {
1373 var result = new Uint8Array(first.byteLength + second.byteLength);
1374
1375 result.set(new Uint8Array(first));
1376 result.set(new Uint8Array(second), first.byteLength);
1377
1378 return returnUInt8Array ? result : result.buffer;
1379 }
1380
1381 function hexToBinaryString(hex) {
1382 var bytes = [],
1383 length = hex.length,
1384 x;
1385
1386 for (x = 0; x < length - 1; x += 2) {
1387 bytes.push(parseInt(hex.substr(x, 2), 16));
1388 }
1389
1390 return String.fromCharCode.apply(String, bytes);
1391 }
1392
1393 // ---------------------------------------------------
1394
1395 /**
1396 * SparkMD5 OOP implementation.
1397 *
1398 * Use this class to perform an incremental md5, otherwise use the
1399 * static methods instead.
1400 */
1401
1402 function SparkMD5() {
1403 // call reset to init the instance
1404 this.reset();
1405 }
1406
1407 /**
1408 * Appends a string.
1409 * A conversion will be applied if an utf8 string is detected.
1410 *
1411 * @param {String} str The string to be appended
1412 *
1413 * @return {SparkMD5} The instance itself
1414 */
1415 SparkMD5.prototype.append = function (str) {
1416 // Converts the string to utf8 bytes if necessary
1417 // Then append as binary
1418 this.appendBinary(toUtf8(str));
1419
1420 return this;
1421 };
1422
1423 /**
1424 * Appends a binary string.
1425 *
1426 * @param {String} contents The binary string to be appended
1427 *
1428 * @return {SparkMD5} The instance itself
1429 */
1430 SparkMD5.prototype.appendBinary = function (contents) {
1431 this._buff += contents;
1432 this._length += contents.length;
1433
1434 var length = this._buff.length,
1435 i;
1436
1437 for (i = 64; i <= length; i += 64) {
1438 md5cycle(this._hash, md5blk(this._buff.substring(i - 64, i)));
1439 }
1440
1441 this._buff = this._buff.substring(i - 64);
1442
1443 return this;
1444 };
1445
1446 /**
1447 * Finishes the incremental computation, reseting the internal state and
1448 * returning the result.
1449 *
1450 * @param {Boolean} raw True to get the raw string, false to get the hex string
1451 *
1452 * @return {String} The result
1453 */
1454 SparkMD5.prototype.end = function (raw) {
1455 var buff = this._buff,
1456 length = buff.length,
1457 i,
1458 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
1459 ret;
1460
1461 for (i = 0; i < length; i += 1) {
1462 tail[i >> 2] |= buff.charCodeAt(i) << ((i % 4) << 3);
1463 }
1464
1465 this._finish(tail, length);
1466 ret = hex(this._hash);
1467
1468 if (raw) {
1469 ret = hexToBinaryString(ret);
1470 }
1471
1472 this.reset();
1473
1474 return ret;
1475 };
1476
1477 /**
1478 * Resets the internal state of the computation.
1479 *
1480 * @return {SparkMD5} The instance itself
1481 */
1482 SparkMD5.prototype.reset = function () {
1483 this._buff = '';
1484 this._length = 0;
1485 this._hash = [1732584193, -271733879, -1732584194, 271733878];
1486
1487 return this;
1488 };
1489
1490 /**
1491 * Gets the internal state of the computation.
1492 *
1493 * @return {Object} The state
1494 */
1495 SparkMD5.prototype.getState = function () {
1496 return {
1497 buff: this._buff,
1498 length: this._length,
1499 hash: this._hash.slice()
1500 };
1501 };
1502
1503 /**
1504 * Gets the internal state of the computation.
1505 *
1506 * @param {Object} state The state
1507 *
1508 * @return {SparkMD5} The instance itself
1509 */
1510 SparkMD5.prototype.setState = function (state) {
1511 this._buff = state.buff;
1512 this._length = state.length;
1513 this._hash = state.hash;
1514
1515 return this;
1516 };
1517
1518 /**
1519 * Releases memory used by the incremental buffer and other additional
1520 * resources. If you plan to use the instance again, use reset instead.
1521 */
1522 SparkMD5.prototype.destroy = function () {
1523 delete this._hash;
1524 delete this._buff;
1525 delete this._length;
1526 };
1527
1528 /**
1529 * Finish the final calculation based on the tail.
1530 *
1531 * @param {Array} tail The tail (will be modified)
1532 * @param {Number} length The length of the remaining buffer
1533 */
1534 SparkMD5.prototype._finish = function (tail, length) {
1535 var i = length,
1536 tmp,
1537 lo,
1538 hi;
1539
1540 tail[i >> 2] |= 0x80 << ((i % 4) << 3);
1541 if (i > 55) {
1542 md5cycle(this._hash, tail);
1543 for (i = 0; i < 16; i += 1) {
1544 tail[i] = 0;
1545 }
1546 }
1547
1548 // Do the final computation based on the tail and length
1549 // Beware that the final length may not fit in 32 bits so we take care of that
1550 tmp = this._length * 8;
1551 tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
1552 lo = parseInt(tmp[2], 16);
1553 hi = parseInt(tmp[1], 16) || 0;
1554
1555 tail[14] = lo;
1556 tail[15] = hi;
1557 md5cycle(this._hash, tail);
1558 };
1559
1560 /**
1561 * Performs the md5 hash on a string.
1562 * A conversion will be applied if utf8 string is detected.
1563 *
1564 * @param {String} str The string
1565 * @param {Boolean} [raw] True to get the raw string, false to get the hex string
1566 *
1567 * @return {String} The result
1568 */
1569 SparkMD5.hash = function (str, raw) {
1570 // Converts the string to utf8 bytes if necessary
1571 // Then compute it using the binary function
1572 return SparkMD5.hashBinary(toUtf8(str), raw);
1573 };
1574
1575 /**
1576 * Performs the md5 hash on a binary string.
1577 *
1578 * @param {String} content The binary string
1579 * @param {Boolean} [raw] True to get the raw string, false to get the hex string
1580 *
1581 * @return {String} The result
1582 */
1583 SparkMD5.hashBinary = function (content, raw) {
1584 var hash = md51(content),
1585 ret = hex(hash);
1586
1587 return raw ? hexToBinaryString(ret) : ret;
1588 };
1589
1590 // ---------------------------------------------------
1591
1592 /**
1593 * SparkMD5 OOP implementation for array buffers.
1594 *
1595 * Use this class to perform an incremental md5 ONLY for array buffers.
1596 */
1597 SparkMD5.ArrayBuffer = function () {
1598 // call reset to init the instance
1599 this.reset();
1600 };
1601
1602 /**
1603 * Appends an array buffer.
1604 *
1605 * @param {ArrayBuffer} arr The array to be appended
1606 *
1607 * @return {SparkMD5.ArrayBuffer} The instance itself
1608 */
1609 SparkMD5.ArrayBuffer.prototype.append = function (arr) {
1610 var buff = concatenateArrayBuffers(this._buff.buffer, arr, true),
1611 length = buff.length,
1612 i;
1613
1614 this._length += arr.byteLength;
1615
1616 for (i = 64; i <= length; i += 64) {
1617 md5cycle(this._hash, md5blk_array(buff.subarray(i - 64, i)));
1618 }
1619
1620 this._buff = (i - 64) < length ? new Uint8Array(buff.buffer.slice(i - 64)) : new Uint8Array(0);
1621
1622 return this;
1623 };
1624
1625 /**
1626 * Finishes the incremental computation, reseting the internal state and
1627 * returning the result.
1628 *
1629 * @param {Boolean} raw True to get the raw string, false to get the hex string
1630 *
1631 * @return {String} The result
1632 */
1633 SparkMD5.ArrayBuffer.prototype.end = function (raw) {
1634 var buff = this._buff,
1635 length = buff.length,
1636 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
1637 i,
1638 ret;
1639
1640 for (i = 0; i < length; i += 1) {
1641 tail[i >> 2] |= buff[i] << ((i % 4) << 3);
1642 }
1643
1644 this._finish(tail, length);
1645 ret = hex(this._hash);
1646
1647 if (raw) {
1648 ret = hexToBinaryString(ret);
1649 }
1650
1651 this.reset();
1652
1653 return ret;
1654 };
1655
1656 /**
1657 * Resets the internal state of the computation.
1658 *
1659 * @return {SparkMD5.ArrayBuffer} The instance itself
1660 */
1661 SparkMD5.ArrayBuffer.prototype.reset = function () {
1662 this._buff = new Uint8Array(0);
1663 this._length = 0;
1664 this._hash = [1732584193, -271733879, -1732584194, 271733878];
1665
1666 return this;
1667 };
1668
1669 /**
1670 * Gets the internal state of the computation.
1671 *
1672 * @return {Object} The state
1673 */
1674 SparkMD5.ArrayBuffer.prototype.getState = function () {
1675 var state = SparkMD5.prototype.getState.call(this);
1676
1677 // Convert buffer to a string
1678 state.buff = arrayBuffer2Utf8Str(state.buff);
1679
1680 return state;
1681 };
1682
1683 /**
1684 * Gets the internal state of the computation.
1685 *
1686 * @param {Object} state The state
1687 *
1688 * @return {SparkMD5.ArrayBuffer} The instance itself
1689 */
1690 SparkMD5.ArrayBuffer.prototype.setState = function (state) {
1691 // Convert string to buffer
1692 state.buff = utf8Str2ArrayBuffer(state.buff, true);
1693
1694 return SparkMD5.prototype.setState.call(this, state);
1695 };
1696
1697 SparkMD5.ArrayBuffer.prototype.destroy = SparkMD5.prototype.destroy;
1698
1699 SparkMD5.ArrayBuffer.prototype._finish = SparkMD5.prototype._finish;
1700
1701 /**
1702 * Performs the md5 hash on an array buffer.
1703 *
1704 * @param {ArrayBuffer} arr The array buffer
1705 * @param {Boolean} [raw] True to get the raw string, false to get the hex one
1706 *
1707 * @return {String} The result
1708 */
1709 SparkMD5.ArrayBuffer.hash = function (arr, raw) {
1710 var hash = md51_array(new Uint8Array(arr)),
1711 ret = hex(hash);
1712
1713 return raw ? hexToBinaryString(ret) : ret;
1714 };
1715
1716 return SparkMD5;
1717}));
1718
1719},{}],13:[function(_dereq_,module,exports){
1720"use strict";
1721
1722Object.defineProperty(exports, "__esModule", {
1723 value: true
1724});
1725Object.defineProperty(exports, "v1", {
1726 enumerable: true,
1727 get: function () {
1728 return _v.default;
1729 }
1730});
1731Object.defineProperty(exports, "v3", {
1732 enumerable: true,
1733 get: function () {
1734 return _v2.default;
1735 }
1736});
1737Object.defineProperty(exports, "v4", {
1738 enumerable: true,
1739 get: function () {
1740 return _v3.default;
1741 }
1742});
1743Object.defineProperty(exports, "v5", {
1744 enumerable: true,
1745 get: function () {
1746 return _v4.default;
1747 }
1748});
1749Object.defineProperty(exports, "NIL", {
1750 enumerable: true,
1751 get: function () {
1752 return _nil.default;
1753 }
1754});
1755Object.defineProperty(exports, "version", {
1756 enumerable: true,
1757 get: function () {
1758 return _version.default;
1759 }
1760});
1761Object.defineProperty(exports, "validate", {
1762 enumerable: true,
1763 get: function () {
1764 return _validate.default;
1765 }
1766});
1767Object.defineProperty(exports, "stringify", {
1768 enumerable: true,
1769 get: function () {
1770 return _stringify.default;
1771 }
1772});
1773Object.defineProperty(exports, "parse", {
1774 enumerable: true,
1775 get: function () {
1776 return _parse.default;
1777 }
1778});
1779
1780var _v = _interopRequireDefault(_dereq_(21));
1781
1782var _v2 = _interopRequireDefault(_dereq_(22));
1783
1784var _v3 = _interopRequireDefault(_dereq_(24));
1785
1786var _v4 = _interopRequireDefault(_dereq_(25));
1787
1788var _nil = _interopRequireDefault(_dereq_(15));
1789
1790var _version = _interopRequireDefault(_dereq_(27));
1791
1792var _validate = _interopRequireDefault(_dereq_(26));
1793
1794var _stringify = _interopRequireDefault(_dereq_(20));
1795
1796var _parse = _interopRequireDefault(_dereq_(16));
1797
1798function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
1799},{"15":15,"16":16,"20":20,"21":21,"22":22,"24":24,"25":25,"26":26,"27":27}],14:[function(_dereq_,module,exports){
1800"use strict";
1801
1802Object.defineProperty(exports, "__esModule", {
1803 value: true
1804});
1805exports.default = void 0;
1806
1807/*
1808 * Browser-compatible JavaScript MD5
1809 *
1810 * Modification of JavaScript MD5
1811 * https://github.com/blueimp/JavaScript-MD5
1812 *
1813 * Copyright 2011, Sebastian Tschan
1814 * https://blueimp.net
1815 *
1816 * Licensed under the MIT license:
1817 * https://opensource.org/licenses/MIT
1818 *
1819 * Based on
1820 * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
1821 * Digest Algorithm, as defined in RFC 1321.
1822 * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009
1823 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
1824 * Distributed under the BSD License
1825 * See http://pajhome.org.uk/crypt/md5 for more info.
1826 */
1827function md5(bytes) {
1828 if (typeof bytes === 'string') {
1829 const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape
1830
1831 bytes = new Uint8Array(msg.length);
1832
1833 for (let i = 0; i < msg.length; ++i) {
1834 bytes[i] = msg.charCodeAt(i);
1835 }
1836 }
1837
1838 return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes), bytes.length * 8));
1839}
1840/*
1841 * Convert an array of little-endian words to an array of bytes
1842 */
1843
1844
1845function md5ToHexEncodedArray(input) {
1846 const output = [];
1847 const length32 = input.length * 32;
1848 const hexTab = '0123456789abcdef';
1849
1850 for (let i = 0; i < length32; i += 8) {
1851 const x = input[i >> 5] >>> i % 32 & 0xff;
1852 const hex = parseInt(hexTab.charAt(x >>> 4 & 0x0f) + hexTab.charAt(x & 0x0f), 16);
1853 output.push(hex);
1854 }
1855
1856 return output;
1857}
1858/**
1859 * Calculate output length with padding and bit length
1860 */
1861
1862
1863function getOutputLength(inputLength8) {
1864 return (inputLength8 + 64 >>> 9 << 4) + 14 + 1;
1865}
1866/*
1867 * Calculate the MD5 of an array of little-endian words, and a bit length.
1868 */
1869
1870
1871function wordsToMd5(x, len) {
1872 /* append padding */
1873 x[len >> 5] |= 0x80 << len % 32;
1874 x[getOutputLength(len) - 1] = len;
1875 let a = 1732584193;
1876 let b = -271733879;
1877 let c = -1732584194;
1878 let d = 271733878;
1879
1880 for (let i = 0; i < x.length; i += 16) {
1881 const olda = a;
1882 const oldb = b;
1883 const oldc = c;
1884 const oldd = d;
1885 a = md5ff(a, b, c, d, x[i], 7, -680876936);
1886 d = md5ff(d, a, b, c, x[i + 1], 12, -389564586);
1887 c = md5ff(c, d, a, b, x[i + 2], 17, 606105819);
1888 b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330);
1889 a = md5ff(a, b, c, d, x[i + 4], 7, -176418897);
1890 d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426);
1891 c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341);
1892 b = md5ff(b, c, d, a, x[i + 7], 22, -45705983);
1893 a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416);
1894 d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417);
1895 c = md5ff(c, d, a, b, x[i + 10], 17, -42063);
1896 b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162);
1897 a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682);
1898 d = md5ff(d, a, b, c, x[i + 13], 12, -40341101);
1899 c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290);
1900 b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329);
1901 a = md5gg(a, b, c, d, x[i + 1], 5, -165796510);
1902 d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632);
1903 c = md5gg(c, d, a, b, x[i + 11], 14, 643717713);
1904 b = md5gg(b, c, d, a, x[i], 20, -373897302);
1905 a = md5gg(a, b, c, d, x[i + 5], 5, -701558691);
1906 d = md5gg(d, a, b, c, x[i + 10], 9, 38016083);
1907 c = md5gg(c, d, a, b, x[i + 15], 14, -660478335);
1908 b = md5gg(b, c, d, a, x[i + 4], 20, -405537848);
1909 a = md5gg(a, b, c, d, x[i + 9], 5, 568446438);
1910 d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690);
1911 c = md5gg(c, d, a, b, x[i + 3], 14, -187363961);
1912 b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501);
1913 a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467);
1914 d = md5gg(d, a, b, c, x[i + 2], 9, -51403784);
1915 c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473);
1916 b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734);
1917 a = md5hh(a, b, c, d, x[i + 5], 4, -378558);
1918 d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463);
1919 c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562);
1920 b = md5hh(b, c, d, a, x[i + 14], 23, -35309556);
1921 a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060);
1922 d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353);
1923 c = md5hh(c, d, a, b, x[i + 7], 16, -155497632);
1924 b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640);
1925 a = md5hh(a, b, c, d, x[i + 13], 4, 681279174);
1926 d = md5hh(d, a, b, c, x[i], 11, -358537222);
1927 c = md5hh(c, d, a, b, x[i + 3], 16, -722521979);
1928 b = md5hh(b, c, d, a, x[i + 6], 23, 76029189);
1929 a = md5hh(a, b, c, d, x[i + 9], 4, -640364487);
1930 d = md5hh(d, a, b, c, x[i + 12], 11, -421815835);
1931 c = md5hh(c, d, a, b, x[i + 15], 16, 530742520);
1932 b = md5hh(b, c, d, a, x[i + 2], 23, -995338651);
1933 a = md5ii(a, b, c, d, x[i], 6, -198630844);
1934 d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415);
1935 c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905);
1936 b = md5ii(b, c, d, a, x[i + 5], 21, -57434055);
1937 a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571);
1938 d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606);
1939 c = md5ii(c, d, a, b, x[i + 10], 15, -1051523);
1940 b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799);
1941 a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359);
1942 d = md5ii(d, a, b, c, x[i + 15], 10, -30611744);
1943 c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380);
1944 b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649);
1945 a = md5ii(a, b, c, d, x[i + 4], 6, -145523070);
1946 d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379);
1947 c = md5ii(c, d, a, b, x[i + 2], 15, 718787259);
1948 b = md5ii(b, c, d, a, x[i + 9], 21, -343485551);
1949 a = safeAdd(a, olda);
1950 b = safeAdd(b, oldb);
1951 c = safeAdd(c, oldc);
1952 d = safeAdd(d, oldd);
1953 }
1954
1955 return [a, b, c, d];
1956}
1957/*
1958 * Convert an array bytes to an array of little-endian words
1959 * Characters >255 have their high-byte silently ignored.
1960 */
1961
1962
1963function bytesToWords(input) {
1964 if (input.length === 0) {
1965 return [];
1966 }
1967
1968 const length8 = input.length * 8;
1969 const output = new Uint32Array(getOutputLength(length8));
1970
1971 for (let i = 0; i < length8; i += 8) {
1972 output[i >> 5] |= (input[i / 8] & 0xff) << i % 32;
1973 }
1974
1975 return output;
1976}
1977/*
1978 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
1979 * to work around bugs in some JS interpreters.
1980 */
1981
1982
1983function safeAdd(x, y) {
1984 const lsw = (x & 0xffff) + (y & 0xffff);
1985 const msw = (x >> 16) + (y >> 16) + (lsw >> 16);
1986 return msw << 16 | lsw & 0xffff;
1987}
1988/*
1989 * Bitwise rotate a 32-bit number to the left.
1990 */
1991
1992
1993function bitRotateLeft(num, cnt) {
1994 return num << cnt | num >>> 32 - cnt;
1995}
1996/*
1997 * These functions implement the four basic operations the algorithm uses.
1998 */
1999
2000
2001function md5cmn(q, a, b, x, s, t) {
2002 return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b);
2003}
2004
2005function md5ff(a, b, c, d, x, s, t) {
2006 return md5cmn(b & c | ~b & d, a, b, x, s, t);
2007}
2008
2009function md5gg(a, b, c, d, x, s, t) {
2010 return md5cmn(b & d | c & ~d, a, b, x, s, t);
2011}
2012
2013function md5hh(a, b, c, d, x, s, t) {
2014 return md5cmn(b ^ c ^ d, a, b, x, s, t);
2015}
2016
2017function md5ii(a, b, c, d, x, s, t) {
2018 return md5cmn(c ^ (b | ~d), a, b, x, s, t);
2019}
2020
2021var _default = md5;
2022exports.default = _default;
2023},{}],15:[function(_dereq_,module,exports){
2024"use strict";
2025
2026Object.defineProperty(exports, "__esModule", {
2027 value: true
2028});
2029exports.default = void 0;
2030var _default = '00000000-0000-0000-0000-000000000000';
2031exports.default = _default;
2032},{}],16:[function(_dereq_,module,exports){
2033"use strict";
2034
2035Object.defineProperty(exports, "__esModule", {
2036 value: true
2037});
2038exports.default = void 0;
2039
2040var _validate = _interopRequireDefault(_dereq_(26));
2041
2042function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
2043
2044function parse(uuid) {
2045 if (!(0, _validate.default)(uuid)) {
2046 throw TypeError('Invalid UUID');
2047 }
2048
2049 let v;
2050 const arr = new Uint8Array(16); // Parse ########-....-....-....-............
2051
2052 arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;
2053 arr[1] = v >>> 16 & 0xff;
2054 arr[2] = v >>> 8 & 0xff;
2055 arr[3] = v & 0xff; // Parse ........-####-....-....-............
2056
2057 arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;
2058 arr[5] = v & 0xff; // Parse ........-....-####-....-............
2059
2060 arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;
2061 arr[7] = v & 0xff; // Parse ........-....-....-####-............
2062
2063 arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;
2064 arr[9] = v & 0xff; // Parse ........-....-....-....-############
2065 // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes)
2066
2067 arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff;
2068 arr[11] = v / 0x100000000 & 0xff;
2069 arr[12] = v >>> 24 & 0xff;
2070 arr[13] = v >>> 16 & 0xff;
2071 arr[14] = v >>> 8 & 0xff;
2072 arr[15] = v & 0xff;
2073 return arr;
2074}
2075
2076var _default = parse;
2077exports.default = _default;
2078},{"26":26}],17:[function(_dereq_,module,exports){
2079"use strict";
2080
2081Object.defineProperty(exports, "__esModule", {
2082 value: true
2083});
2084exports.default = void 0;
2085var _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;
2086exports.default = _default;
2087},{}],18:[function(_dereq_,module,exports){
2088"use strict";
2089
2090Object.defineProperty(exports, "__esModule", {
2091 value: true
2092});
2093exports.default = rng;
2094// Unique ID creation requires a high quality random # generator. In the browser we therefore
2095// require the crypto API and do not support built-in fallback to lower quality random number
2096// generators (like Math.random()).
2097let getRandomValues;
2098const rnds8 = new Uint8Array(16);
2099
2100function rng() {
2101 // lazy load so that environments that need to polyfill have a chance to do so
2102 if (!getRandomValues) {
2103 // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. Also,
2104 // find the complete implementation of crypto (msCrypto) on IE11.
2105 getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== 'undefined' && typeof msCrypto.getRandomValues === 'function' && msCrypto.getRandomValues.bind(msCrypto);
2106
2107 if (!getRandomValues) {
2108 throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
2109 }
2110 }
2111
2112 return getRandomValues(rnds8);
2113}
2114},{}],19:[function(_dereq_,module,exports){
2115"use strict";
2116
2117Object.defineProperty(exports, "__esModule", {
2118 value: true
2119});
2120exports.default = void 0;
2121
2122// Adapted from Chris Veness' SHA1 code at
2123// http://www.movable-type.co.uk/scripts/sha1.html
2124function f(s, x, y, z) {
2125 switch (s) {
2126 case 0:
2127 return x & y ^ ~x & z;
2128
2129 case 1:
2130 return x ^ y ^ z;
2131
2132 case 2:
2133 return x & y ^ x & z ^ y & z;
2134
2135 case 3:
2136 return x ^ y ^ z;
2137 }
2138}
2139
2140function ROTL(x, n) {
2141 return x << n | x >>> 32 - n;
2142}
2143
2144function sha1(bytes) {
2145 const K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6];
2146 const H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0];
2147
2148 if (typeof bytes === 'string') {
2149 const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape
2150
2151 bytes = [];
2152
2153 for (let i = 0; i < msg.length; ++i) {
2154 bytes.push(msg.charCodeAt(i));
2155 }
2156 } else if (!Array.isArray(bytes)) {
2157 // Convert Array-like to Array
2158 bytes = Array.prototype.slice.call(bytes);
2159 }
2160
2161 bytes.push(0x80);
2162 const l = bytes.length / 4 + 2;
2163 const N = Math.ceil(l / 16);
2164 const M = new Array(N);
2165
2166 for (let i = 0; i < N; ++i) {
2167 const arr = new Uint32Array(16);
2168
2169 for (let j = 0; j < 16; ++j) {
2170 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];
2171 }
2172
2173 M[i] = arr;
2174 }
2175
2176 M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32);
2177 M[N - 1][14] = Math.floor(M[N - 1][14]);
2178 M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff;
2179
2180 for (let i = 0; i < N; ++i) {
2181 const W = new Uint32Array(80);
2182
2183 for (let t = 0; t < 16; ++t) {
2184 W[t] = M[i][t];
2185 }
2186
2187 for (let t = 16; t < 80; ++t) {
2188 W[t] = ROTL(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1);
2189 }
2190
2191 let a = H[0];
2192 let b = H[1];
2193 let c = H[2];
2194 let d = H[3];
2195 let e = H[4];
2196
2197 for (let t = 0; t < 80; ++t) {
2198 const s = Math.floor(t / 20);
2199 const T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[t] >>> 0;
2200 e = d;
2201 d = c;
2202 c = ROTL(b, 30) >>> 0;
2203 b = a;
2204 a = T;
2205 }
2206
2207 H[0] = H[0] + a >>> 0;
2208 H[1] = H[1] + b >>> 0;
2209 H[2] = H[2] + c >>> 0;
2210 H[3] = H[3] + d >>> 0;
2211 H[4] = H[4] + e >>> 0;
2212 }
2213
2214 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];
2215}
2216
2217var _default = sha1;
2218exports.default = _default;
2219},{}],20:[function(_dereq_,module,exports){
2220"use strict";
2221
2222Object.defineProperty(exports, "__esModule", {
2223 value: true
2224});
2225exports.default = void 0;
2226
2227var _validate = _interopRequireDefault(_dereq_(26));
2228
2229function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
2230
2231/**
2232 * Convert array of 16 byte values to UUID string format of the form:
2233 * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
2234 */
2235const byteToHex = [];
2236
2237for (let i = 0; i < 256; ++i) {
2238 byteToHex.push((i + 0x100).toString(16).substr(1));
2239}
2240
2241function stringify(arr, offset = 0) {
2242 // Note: Be careful editing this code! It's been tuned for performance
2243 // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
2244 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
2245 // of the following:
2246 // - One or more input array values don't map to a hex octet (leading to
2247 // "undefined" in the uuid)
2248 // - Invalid input values for the RFC `version` or `variant` fields
2249
2250 if (!(0, _validate.default)(uuid)) {
2251 throw TypeError('Stringified UUID is invalid');
2252 }
2253
2254 return uuid;
2255}
2256
2257var _default = stringify;
2258exports.default = _default;
2259},{"26":26}],21:[function(_dereq_,module,exports){
2260"use strict";
2261
2262Object.defineProperty(exports, "__esModule", {
2263 value: true
2264});
2265exports.default = void 0;
2266
2267var _rng = _interopRequireDefault(_dereq_(18));
2268
2269var _stringify = _interopRequireDefault(_dereq_(20));
2270
2271function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
2272
2273// **`v1()` - Generate time-based UUID**
2274//
2275// Inspired by https://github.com/LiosK/UUID.js
2276// and http://docs.python.org/library/uuid.html
2277let _nodeId;
2278
2279let _clockseq; // Previous uuid creation time
2280
2281
2282let _lastMSecs = 0;
2283let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details
2284
2285function v1(options, buf, offset) {
2286 let i = buf && offset || 0;
2287 const b = buf || new Array(16);
2288 options = options || {};
2289 let node = options.node || _nodeId;
2290 let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not
2291 // specified. We do this lazily to minimize issues related to insufficient
2292 // system entropy. See #189
2293
2294 if (node == null || clockseq == null) {
2295 const seedBytes = options.random || (options.rng || _rng.default)();
2296
2297 if (node == null) {
2298 // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
2299 node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]];
2300 }
2301
2302 if (clockseq == null) {
2303 // Per 4.2.2, randomize (14 bit) clockseq
2304 clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;
2305 }
2306 } // UUID timestamps are 100 nano-second units since the Gregorian epoch,
2307 // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
2308 // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
2309 // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
2310
2311
2312 let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock
2313 // cycle to simulate higher resolution clock
2314
2315 let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs)
2316
2317 const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression
2318
2319 if (dt < 0 && options.clockseq === undefined) {
2320 clockseq = clockseq + 1 & 0x3fff;
2321 } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
2322 // time interval
2323
2324
2325 if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {
2326 nsecs = 0;
2327 } // Per 4.2.1.2 Throw error if too many uuids are requested
2328
2329
2330 if (nsecs >= 10000) {
2331 throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");
2332 }
2333
2334 _lastMSecs = msecs;
2335 _lastNSecs = nsecs;
2336 _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
2337
2338 msecs += 12219292800000; // `time_low`
2339
2340 const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
2341 b[i++] = tl >>> 24 & 0xff;
2342 b[i++] = tl >>> 16 & 0xff;
2343 b[i++] = tl >>> 8 & 0xff;
2344 b[i++] = tl & 0xff; // `time_mid`
2345
2346 const tmh = msecs / 0x100000000 * 10000 & 0xfffffff;
2347 b[i++] = tmh >>> 8 & 0xff;
2348 b[i++] = tmh & 0xff; // `time_high_and_version`
2349
2350 b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
2351
2352 b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
2353
2354 b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low`
2355
2356 b[i++] = clockseq & 0xff; // `node`
2357
2358 for (let n = 0; n < 6; ++n) {
2359 b[i + n] = node[n];
2360 }
2361
2362 return buf || (0, _stringify.default)(b);
2363}
2364
2365var _default = v1;
2366exports.default = _default;
2367},{"18":18,"20":20}],22:[function(_dereq_,module,exports){
2368"use strict";
2369
2370Object.defineProperty(exports, "__esModule", {
2371 value: true
2372});
2373exports.default = void 0;
2374
2375var _v = _interopRequireDefault(_dereq_(23));
2376
2377var _md = _interopRequireDefault(_dereq_(14));
2378
2379function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
2380
2381const v3 = (0, _v.default)('v3', 0x30, _md.default);
2382var _default = v3;
2383exports.default = _default;
2384},{"14":14,"23":23}],23:[function(_dereq_,module,exports){
2385"use strict";
2386
2387Object.defineProperty(exports, "__esModule", {
2388 value: true
2389});
2390exports.default = _default;
2391exports.URL = exports.DNS = void 0;
2392
2393var _stringify = _interopRequireDefault(_dereq_(20));
2394
2395var _parse = _interopRequireDefault(_dereq_(16));
2396
2397function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
2398
2399function stringToBytes(str) {
2400 str = unescape(encodeURIComponent(str)); // UTF8 escape
2401
2402 const bytes = [];
2403
2404 for (let i = 0; i < str.length; ++i) {
2405 bytes.push(str.charCodeAt(i));
2406 }
2407
2408 return bytes;
2409}
2410
2411const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
2412exports.DNS = DNS;
2413const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';
2414exports.URL = URL;
2415
2416function _default(name, version, hashfunc) {
2417 function generateUUID(value, namespace, buf, offset) {
2418 if (typeof value === 'string') {
2419 value = stringToBytes(value);
2420 }
2421
2422 if (typeof namespace === 'string') {
2423 namespace = (0, _parse.default)(namespace);
2424 }
2425
2426 if (namespace.length !== 16) {
2427 throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)');
2428 } // Compute hash of namespace and value, Per 4.3
2429 // Future: Use spread syntax when supported on all platforms, e.g. `bytes =
2430 // hashfunc([...namespace, ... value])`
2431
2432
2433 let bytes = new Uint8Array(16 + value.length);
2434 bytes.set(namespace);
2435 bytes.set(value, namespace.length);
2436 bytes = hashfunc(bytes);
2437 bytes[6] = bytes[6] & 0x0f | version;
2438 bytes[8] = bytes[8] & 0x3f | 0x80;
2439
2440 if (buf) {
2441 offset = offset || 0;
2442
2443 for (let i = 0; i < 16; ++i) {
2444 buf[offset + i] = bytes[i];
2445 }
2446
2447 return buf;
2448 }
2449
2450 return (0, _stringify.default)(bytes);
2451 } // Function#name is not settable on some platforms (#270)
2452
2453
2454 try {
2455 generateUUID.name = name; // eslint-disable-next-line no-empty
2456 } catch (err) {} // For CommonJS default export support
2457
2458
2459 generateUUID.DNS = DNS;
2460 generateUUID.URL = URL;
2461 return generateUUID;
2462}
2463},{"16":16,"20":20}],24:[function(_dereq_,module,exports){
2464"use strict";
2465
2466Object.defineProperty(exports, "__esModule", {
2467 value: true
2468});
2469exports.default = void 0;
2470
2471var _rng = _interopRequireDefault(_dereq_(18));
2472
2473var _stringify = _interopRequireDefault(_dereq_(20));
2474
2475function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
2476
2477function v4(options, buf, offset) {
2478 options = options || {};
2479
2480 const rnds = options.random || (options.rng || _rng.default)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
2481
2482
2483 rnds[6] = rnds[6] & 0x0f | 0x40;
2484 rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided
2485
2486 if (buf) {
2487 offset = offset || 0;
2488
2489 for (let i = 0; i < 16; ++i) {
2490 buf[offset + i] = rnds[i];
2491 }
2492
2493 return buf;
2494 }
2495
2496 return (0, _stringify.default)(rnds);
2497}
2498
2499var _default = v4;
2500exports.default = _default;
2501},{"18":18,"20":20}],25:[function(_dereq_,module,exports){
2502"use strict";
2503
2504Object.defineProperty(exports, "__esModule", {
2505 value: true
2506});
2507exports.default = void 0;
2508
2509var _v = _interopRequireDefault(_dereq_(23));
2510
2511var _sha = _interopRequireDefault(_dereq_(19));
2512
2513function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
2514
2515const v5 = (0, _v.default)('v5', 0x50, _sha.default);
2516var _default = v5;
2517exports.default = _default;
2518},{"19":19,"23":23}],26:[function(_dereq_,module,exports){
2519"use strict";
2520
2521Object.defineProperty(exports, "__esModule", {
2522 value: true
2523});
2524exports.default = void 0;
2525
2526var _regex = _interopRequireDefault(_dereq_(17));
2527
2528function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
2529
2530function validate(uuid) {
2531 return typeof uuid === 'string' && _regex.default.test(uuid);
2532}
2533
2534var _default = validate;
2535exports.default = _default;
2536},{"17":17}],27:[function(_dereq_,module,exports){
2537"use strict";
2538
2539Object.defineProperty(exports, "__esModule", {
2540 value: true
2541});
2542exports.default = void 0;
2543
2544var _validate = _interopRequireDefault(_dereq_(26));
2545
2546function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
2547
2548function version(uuid) {
2549 if (!(0, _validate.default)(uuid)) {
2550 throw TypeError('Invalid UUID');
2551 }
2552
2553 return parseInt(uuid.substr(14, 1), 16);
2554}
2555
2556var _default = version;
2557exports.default = _default;
2558},{"26":26}],28:[function(_dereq_,module,exports){
2559'use strict';
2560
2561/**
2562 * Stringify/parse functions that don't operate
2563 * recursively, so they avoid call stack exceeded
2564 * errors.
2565 */
2566exports.stringify = function stringify(input) {
2567 var queue = [];
2568 queue.push({obj: input});
2569
2570 var res = '';
2571 var next, obj, prefix, val, i, arrayPrefix, keys, k, key, value, objPrefix;
2572 while ((next = queue.pop())) {
2573 obj = next.obj;
2574 prefix = next.prefix || '';
2575 val = next.val || '';
2576 res += prefix;
2577 if (val) {
2578 res += val;
2579 } else if (typeof obj !== 'object') {
2580 res += typeof obj === 'undefined' ? null : JSON.stringify(obj);
2581 } else if (obj === null) {
2582 res += 'null';
2583 } else if (Array.isArray(obj)) {
2584 queue.push({val: ']'});
2585 for (i = obj.length - 1; i >= 0; i--) {
2586 arrayPrefix = i === 0 ? '' : ',';
2587 queue.push({obj: obj[i], prefix: arrayPrefix});
2588 }
2589 queue.push({val: '['});
2590 } else { // object
2591 keys = [];
2592 for (k in obj) {
2593 if (obj.hasOwnProperty(k)) {
2594 keys.push(k);
2595 }
2596 }
2597 queue.push({val: '}'});
2598 for (i = keys.length - 1; i >= 0; i--) {
2599 key = keys[i];
2600 value = obj[key];
2601 objPrefix = (i > 0 ? ',' : '');
2602 objPrefix += JSON.stringify(key) + ':';
2603 queue.push({obj: value, prefix: objPrefix});
2604 }
2605 queue.push({val: '{'});
2606 }
2607 }
2608 return res;
2609};
2610
2611// Convenience function for the parse function.
2612// This pop function is basically copied from
2613// pouchCollate.parseIndexableString
2614function pop(obj, stack, metaStack) {
2615 var lastMetaElement = metaStack[metaStack.length - 1];
2616 if (obj === lastMetaElement.element) {
2617 // popping a meta-element, e.g. an object whose value is another object
2618 metaStack.pop();
2619 lastMetaElement = metaStack[metaStack.length - 1];
2620 }
2621 var element = lastMetaElement.element;
2622 var lastElementIndex = lastMetaElement.index;
2623 if (Array.isArray(element)) {
2624 element.push(obj);
2625 } else if (lastElementIndex === stack.length - 2) { // obj with key+value
2626 var key = stack.pop();
2627 element[key] = obj;
2628 } else {
2629 stack.push(obj); // obj with key only
2630 }
2631}
2632
2633exports.parse = function (str) {
2634 var stack = [];
2635 var metaStack = []; // stack for arrays and objects
2636 var i = 0;
2637 var collationIndex,parsedNum,numChar;
2638 var parsedString,lastCh,numConsecutiveSlashes,ch;
2639 var arrayElement, objElement;
2640 while (true) {
2641 collationIndex = str[i++];
2642 if (collationIndex === '}' ||
2643 collationIndex === ']' ||
2644 typeof collationIndex === 'undefined') {
2645 if (stack.length === 1) {
2646 return stack.pop();
2647 } else {
2648 pop(stack.pop(), stack, metaStack);
2649 continue;
2650 }
2651 }
2652 switch (collationIndex) {
2653 case ' ':
2654 case '\t':
2655 case '\n':
2656 case ':':
2657 case ',':
2658 break;
2659 case 'n':
2660 i += 3; // 'ull'
2661 pop(null, stack, metaStack);
2662 break;
2663 case 't':
2664 i += 3; // 'rue'
2665 pop(true, stack, metaStack);
2666 break;
2667 case 'f':
2668 i += 4; // 'alse'
2669 pop(false, stack, metaStack);
2670 break;
2671 case '0':
2672 case '1':
2673 case '2':
2674 case '3':
2675 case '4':
2676 case '5':
2677 case '6':
2678 case '7':
2679 case '8':
2680 case '9':
2681 case '-':
2682 parsedNum = '';
2683 i--;
2684 while (true) {
2685 numChar = str[i++];
2686 if (/[\d\.\-e\+]/.test(numChar)) {
2687 parsedNum += numChar;
2688 } else {
2689 i--;
2690 break;
2691 }
2692 }
2693 pop(parseFloat(parsedNum), stack, metaStack);
2694 break;
2695 case '"':
2696 parsedString = '';
2697 lastCh = void 0;
2698 numConsecutiveSlashes = 0;
2699 while (true) {
2700 ch = str[i++];
2701 if (ch !== '"' || (lastCh === '\\' &&
2702 numConsecutiveSlashes % 2 === 1)) {
2703 parsedString += ch;
2704 lastCh = ch;
2705 if (lastCh === '\\') {
2706 numConsecutiveSlashes++;
2707 } else {
2708 numConsecutiveSlashes = 0;
2709 }
2710 } else {
2711 break;
2712 }
2713 }
2714 pop(JSON.parse('"' + parsedString + '"'), stack, metaStack);
2715 break;
2716 case '[':
2717 arrayElement = { element: [], index: stack.length };
2718 stack.push(arrayElement.element);
2719 metaStack.push(arrayElement);
2720 break;
2721 case '{':
2722 objElement = { element: {}, index: stack.length };
2723 stack.push(objElement.element);
2724 metaStack.push(objElement);
2725 break;
2726 default:
2727 throw new Error(
2728 'unexpectedly reached end of input: ' + collationIndex);
2729 }
2730 }
2731};
2732
2733},{}],29:[function(_dereq_,module,exports){
2734(function (process){(function (){
2735'use strict';
2736
2737function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
2738
2739var immediate = _interopDefault(_dereq_(4));
2740var uuid = _dereq_(13);
2741var Md5 = _interopDefault(_dereq_(12));
2742var vuvuzela = _interopDefault(_dereq_(28));
2743var getArguments = _interopDefault(_dereq_(1));
2744var inherits = _interopDefault(_dereq_(10));
2745var EE = _interopDefault(_dereq_(3));
2746
2747function mangle(key) {
2748 return '$' + key;
2749}
2750function unmangle(key) {
2751 return key.substring(1);
2752}
2753function Map$1() {
2754 this._store = {};
2755}
2756Map$1.prototype.get = function (key) {
2757 var mangled = mangle(key);
2758 return this._store[mangled];
2759};
2760Map$1.prototype.set = function (key, value) {
2761 var mangled = mangle(key);
2762 this._store[mangled] = value;
2763 return true;
2764};
2765Map$1.prototype.has = function (key) {
2766 var mangled = mangle(key);
2767 return mangled in this._store;
2768};
2769Map$1.prototype.keys = function () {
2770 return Object.keys(this._store).map(k => unmangle(k));
2771};
2772Map$1.prototype["delete"] = function (key) {
2773 var mangled = mangle(key);
2774 var res = mangled in this._store;
2775 delete this._store[mangled];
2776 return res;
2777};
2778Map$1.prototype.forEach = function (cb) {
2779 var keys = Object.keys(this._store);
2780 for (var i = 0, len = keys.length; i < len; i++) {
2781 var key = keys[i];
2782 var value = this._store[key];
2783 key = unmangle(key);
2784 cb(value, key);
2785 }
2786};
2787Object.defineProperty(Map$1.prototype, 'size', {
2788 get: function () {
2789 return Object.keys(this._store).length;
2790 }
2791});
2792
2793function Set$1(array) {
2794 this._store = new Map$1();
2795
2796 // init with an array
2797 if (array && Array.isArray(array)) {
2798 for (var i = 0, len = array.length; i < len; i++) {
2799 this.add(array[i]);
2800 }
2801 }
2802}
2803Set$1.prototype.add = function (key) {
2804 return this._store.set(key, true);
2805};
2806Set$1.prototype.has = function (key) {
2807 return this._store.has(key);
2808};
2809Set$1.prototype.forEach = function (cb) {
2810 this._store.forEach(function (value, key) {
2811 cb(key);
2812 });
2813};
2814Object.defineProperty(Set$1.prototype, 'size', {
2815 get: function () {
2816 return this._store.size;
2817 }
2818});
2819
2820// Based on https://kangax.github.io/compat-table/es6/ we can sniff out
2821// incomplete Map/Set implementations which would otherwise cause our tests to fail.
2822// Notably they fail in IE11 and iOS 8.4, which this prevents.
2823function supportsMapAndSet() {
2824 if (typeof Symbol === 'undefined' || typeof Map === 'undefined' || typeof Set === 'undefined') {
2825 return false;
2826 }
2827 var prop = Object.getOwnPropertyDescriptor(Map, Symbol.species);
2828 return prop && 'get' in prop && Map[Symbol.species] === Map;
2829}
2830
2831// based on https://github.com/montagejs/collections
2832
2833var ExportedSet;
2834var ExportedMap;
2835
2836{
2837 if (supportsMapAndSet()) { // prefer built-in Map/Set
2838 ExportedSet = Set;
2839 ExportedMap = Map;
2840 } else { // fall back to our polyfill
2841 ExportedSet = Set$1;
2842 ExportedMap = Map$1;
2843 }
2844}
2845
2846function isBinaryObject(object) {
2847 return (typeof ArrayBuffer !== 'undefined' && object instanceof ArrayBuffer) ||
2848 (typeof Blob !== 'undefined' && object instanceof Blob);
2849}
2850
2851function cloneArrayBuffer(buff) {
2852 if (typeof buff.slice === 'function') {
2853 return buff.slice(0);
2854 }
2855 // IE10-11 slice() polyfill
2856 var target = new ArrayBuffer(buff.byteLength);
2857 var targetArray = new Uint8Array(target);
2858 var sourceArray = new Uint8Array(buff);
2859 targetArray.set(sourceArray);
2860 return target;
2861}
2862
2863function cloneBinaryObject(object) {
2864 if (object instanceof ArrayBuffer) {
2865 return cloneArrayBuffer(object);
2866 }
2867 var size = object.size;
2868 var type = object.type;
2869 // Blob
2870 if (typeof object.slice === 'function') {
2871 return object.slice(0, size, type);
2872 }
2873 // PhantomJS slice() replacement
2874 return object.webkitSlice(0, size, type);
2875}
2876
2877// most of this is borrowed from lodash.isPlainObject:
2878// https://github.com/fis-components/lodash.isplainobject/
2879// blob/29c358140a74f252aeb08c9eb28bef86f2217d4a/index.js
2880
2881var funcToString = Function.prototype.toString;
2882var objectCtorString = funcToString.call(Object);
2883
2884function isPlainObject(value) {
2885 var proto = Object.getPrototypeOf(value);
2886 /* istanbul ignore if */
2887 if (proto === null) { // not sure when this happens, but I guess it can
2888 return true;
2889 }
2890 var Ctor = proto.constructor;
2891 return (typeof Ctor == 'function' &&
2892 Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString);
2893}
2894
2895function clone(object) {
2896 var newObject;
2897 var i;
2898 var len;
2899
2900 if (!object || typeof object !== 'object') {
2901 return object;
2902 }
2903
2904 if (Array.isArray(object)) {
2905 newObject = [];
2906 for (i = 0, len = object.length; i < len; i++) {
2907 newObject[i] = clone(object[i]);
2908 }
2909 return newObject;
2910 }
2911
2912 // special case: to avoid inconsistencies between IndexedDB
2913 // and other backends, we automatically stringify Dates
2914 if (object instanceof Date && isFinite(object)) {
2915 return object.toISOString();
2916 }
2917
2918 if (isBinaryObject(object)) {
2919 return cloneBinaryObject(object);
2920 }
2921
2922 if (!isPlainObject(object)) {
2923 return object; // don't clone objects like Workers
2924 }
2925
2926 newObject = {};
2927 for (i in object) {
2928 /* istanbul ignore else */
2929 if (Object.prototype.hasOwnProperty.call(object, i)) {
2930 var value = clone(object[i]);
2931 if (typeof value !== 'undefined') {
2932 newObject[i] = value;
2933 }
2934 }
2935 }
2936 return newObject;
2937}
2938
2939function once(fun) {
2940 var called = false;
2941 return getArguments(function (args) {
2942 /* istanbul ignore if */
2943 if (called) {
2944 // this is a smoke test and should never actually happen
2945 throw new Error('once called more than once');
2946 } else {
2947 called = true;
2948 fun.apply(this, args);
2949 }
2950 });
2951}
2952
2953function toPromise(func) {
2954 //create the function we will be returning
2955 return getArguments(function (args) {
2956 // Clone arguments
2957 args = clone(args);
2958 var self = this;
2959 // if the last argument is a function, assume its a callback
2960 var usedCB = (typeof args[args.length - 1] === 'function') ? args.pop() : false;
2961 var promise = new Promise(function (fulfill, reject) {
2962 var resp;
2963 try {
2964 var callback = once(function (err, mesg) {
2965 if (err) {
2966 reject(err);
2967 } else {
2968 fulfill(mesg);
2969 }
2970 });
2971 // create a callback for this invocation
2972 // apply the function in the orig context
2973 args.push(callback);
2974 resp = func.apply(self, args);
2975 if (resp && typeof resp.then === 'function') {
2976 fulfill(resp);
2977 }
2978 } catch (e) {
2979 reject(e);
2980 }
2981 });
2982 // if there is a callback, call it back
2983 if (usedCB) {
2984 promise.then(function (result) {
2985 usedCB(null, result);
2986 }, usedCB);
2987 }
2988 return promise;
2989 });
2990}
2991
2992function logApiCall(self, name, args) {
2993 /* istanbul ignore if */
2994 if (self.constructor.listeners('debug').length) {
2995 var logArgs = ['api', self.name, name];
2996 for (var i = 0; i < args.length - 1; i++) {
2997 logArgs.push(args[i]);
2998 }
2999 self.constructor.emit('debug', logArgs);
3000
3001 // override the callback itself to log the response
3002 var origCallback = args[args.length - 1];
3003 args[args.length - 1] = function (err, res) {
3004 var responseArgs = ['api', self.name, name];
3005 responseArgs = responseArgs.concat(
3006 err ? ['error', err] : ['success', res]
3007 );
3008 self.constructor.emit('debug', responseArgs);
3009 origCallback(err, res);
3010 };
3011 }
3012}
3013
3014function adapterFun(name, callback) {
3015 return toPromise(getArguments(function (args) {
3016 if (this._closed) {
3017 return Promise.reject(new Error('database is closed'));
3018 }
3019 if (this._destroyed) {
3020 return Promise.reject(new Error('database is destroyed'));
3021 }
3022 var self = this;
3023 logApiCall(self, name, args);
3024 if (!this.taskqueue.isReady) {
3025 return new Promise(function (fulfill, reject) {
3026 self.taskqueue.addTask(function (failed) {
3027 if (failed) {
3028 reject(failed);
3029 } else {
3030 fulfill(self[name].apply(self, args));
3031 }
3032 });
3033 });
3034 }
3035 return callback.apply(this, args);
3036 }));
3037}
3038
3039// like underscore/lodash _.pick()
3040function pick(obj, arr) {
3041 var res = {};
3042 for (var i = 0, len = arr.length; i < len; i++) {
3043 var prop = arr[i];
3044 if (prop in obj) {
3045 res[prop] = obj[prop];
3046 }
3047 }
3048 return res;
3049}
3050
3051// Most browsers throttle concurrent requests at 6, so it's silly
3052// to shim _bulk_get by trying to launch potentially hundreds of requests
3053// and then letting the majority time out. We can handle this ourselves.
3054var MAX_NUM_CONCURRENT_REQUESTS = 6;
3055
3056function identityFunction(x) {
3057 return x;
3058}
3059
3060function formatResultForOpenRevsGet(result) {
3061 return [{
3062 ok: result
3063 }];
3064}
3065
3066// shim for P/CouchDB adapters that don't directly implement _bulk_get
3067function bulkGet(db, opts, callback) {
3068 var requests = opts.docs;
3069
3070 // consolidate into one request per doc if possible
3071 var requestsById = new ExportedMap();
3072 requests.forEach(function (request) {
3073 if (requestsById.has(request.id)) {
3074 requestsById.get(request.id).push(request);
3075 } else {
3076 requestsById.set(request.id, [request]);
3077 }
3078 });
3079
3080 var numDocs = requestsById.size;
3081 var numDone = 0;
3082 var perDocResults = new Array(numDocs);
3083
3084 function collapseResultsAndFinish() {
3085 var results = [];
3086 perDocResults.forEach(function (res) {
3087 res.docs.forEach(function (info) {
3088 results.push({
3089 id: res.id,
3090 docs: [info]
3091 });
3092 });
3093 });
3094 callback(null, {results: results});
3095 }
3096
3097 function checkDone() {
3098 if (++numDone === numDocs) {
3099 collapseResultsAndFinish();
3100 }
3101 }
3102
3103 function gotResult(docIndex, id, docs) {
3104 perDocResults[docIndex] = {id: id, docs: docs};
3105 checkDone();
3106 }
3107
3108 var allRequests = [];
3109 requestsById.forEach(function (value, key) {
3110 allRequests.push(key);
3111 });
3112
3113 var i = 0;
3114
3115 function nextBatch() {
3116
3117 if (i >= allRequests.length) {
3118 return;
3119 }
3120
3121 var upTo = Math.min(i + MAX_NUM_CONCURRENT_REQUESTS, allRequests.length);
3122 var batch = allRequests.slice(i, upTo);
3123 processBatch(batch, i);
3124 i += batch.length;
3125 }
3126
3127 function processBatch(batch, offset) {
3128 batch.forEach(function (docId, j) {
3129 var docIdx = offset + j;
3130 var docRequests = requestsById.get(docId);
3131
3132 // just use the first request as the "template"
3133 // TODO: The _bulk_get API allows for more subtle use cases than this,
3134 // but for now it is unlikely that there will be a mix of different
3135 // "atts_since" or "attachments" in the same request, since it's just
3136 // replicate.js that is using this for the moment.
3137 // Also, atts_since is aspirational, since we don't support it yet.
3138 var docOpts = pick(docRequests[0], ['atts_since', 'attachments']);
3139 docOpts.open_revs = docRequests.map(function (request) {
3140 // rev is optional, open_revs disallowed
3141 return request.rev;
3142 });
3143
3144 // remove falsey / undefined revisions
3145 docOpts.open_revs = docOpts.open_revs.filter(identityFunction);
3146
3147 var formatResult = identityFunction;
3148
3149 if (docOpts.open_revs.length === 0) {
3150 delete docOpts.open_revs;
3151
3152 // when fetching only the "winning" leaf,
3153 // transform the result so it looks like an open_revs
3154 // request
3155 formatResult = formatResultForOpenRevsGet;
3156 }
3157
3158 // globally-supplied options
3159 ['revs', 'attachments', 'binary', 'ajax', 'latest'].forEach(function (param) {
3160 if (param in opts) {
3161 docOpts[param] = opts[param];
3162 }
3163 });
3164 db.get(docId, docOpts, function (err, res) {
3165 var result;
3166 /* istanbul ignore if */
3167 if (err) {
3168 result = [{error: err}];
3169 } else {
3170 result = formatResult(res);
3171 }
3172 gotResult(docIdx, docId, result);
3173 nextBatch();
3174 });
3175 });
3176 }
3177
3178 nextBatch();
3179
3180}
3181
3182var hasLocal;
3183
3184try {
3185 localStorage.setItem('_pouch_check_localstorage', 1);
3186 hasLocal = !!localStorage.getItem('_pouch_check_localstorage');
3187} catch (e) {
3188 hasLocal = false;
3189}
3190
3191function hasLocalStorage() {
3192 return hasLocal;
3193}
3194
3195// Custom nextTick() shim for browsers. In node, this will just be process.nextTick(). We
3196
3197inherits(Changes, EE);
3198
3199/* istanbul ignore next */
3200function attachBrowserEvents(self) {
3201 if (hasLocalStorage()) {
3202 addEventListener("storage", function (e) {
3203 self.emit(e.key);
3204 });
3205 }
3206}
3207
3208function Changes() {
3209 EE.call(this);
3210 this._listeners = {};
3211
3212 attachBrowserEvents(this);
3213}
3214Changes.prototype.addListener = function (dbName, id, db, opts) {
3215 /* istanbul ignore if */
3216 if (this._listeners[id]) {
3217 return;
3218 }
3219 var self = this;
3220 var inprogress = false;
3221 function eventFunction() {
3222 /* istanbul ignore if */
3223 if (!self._listeners[id]) {
3224 return;
3225 }
3226 if (inprogress) {
3227 inprogress = 'waiting';
3228 return;
3229 }
3230 inprogress = true;
3231 var changesOpts = pick(opts, [
3232 'style', 'include_docs', 'attachments', 'conflicts', 'filter',
3233 'doc_ids', 'view', 'since', 'query_params', 'binary', 'return_docs'
3234 ]);
3235
3236 /* istanbul ignore next */
3237 function onError() {
3238 inprogress = false;
3239 }
3240
3241 db.changes(changesOpts).on('change', function (c) {
3242 if (c.seq > opts.since && !opts.cancelled) {
3243 opts.since = c.seq;
3244 opts.onChange(c);
3245 }
3246 }).on('complete', function () {
3247 if (inprogress === 'waiting') {
3248 immediate(eventFunction);
3249 }
3250 inprogress = false;
3251 }).on('error', onError);
3252 }
3253 this._listeners[id] = eventFunction;
3254 this.on(dbName, eventFunction);
3255};
3256
3257Changes.prototype.removeListener = function (dbName, id) {
3258 /* istanbul ignore if */
3259 if (!(id in this._listeners)) {
3260 return;
3261 }
3262 EE.prototype.removeListener.call(this, dbName,
3263 this._listeners[id]);
3264 delete this._listeners[id];
3265};
3266
3267
3268/* istanbul ignore next */
3269Changes.prototype.notifyLocalWindows = function (dbName) {
3270 //do a useless change on a storage thing
3271 //in order to get other windows's listeners to activate
3272 if (hasLocalStorage()) {
3273 localStorage[dbName] = (localStorage[dbName] === "a") ? "b" : "a";
3274 }
3275};
3276
3277Changes.prototype.notify = function (dbName) {
3278 this.emit(dbName);
3279 this.notifyLocalWindows(dbName);
3280};
3281
3282function guardedConsole(method) {
3283 /* istanbul ignore else */
3284 if (typeof console !== 'undefined' && typeof console[method] === 'function') {
3285 var args = Array.prototype.slice.call(arguments, 1);
3286 console[method].apply(console, args);
3287 }
3288}
3289
3290function randomNumber(min, max) {
3291 var maxTimeout = 600000; // Hard-coded default of 10 minutes
3292 min = parseInt(min, 10) || 0;
3293 max = parseInt(max, 10);
3294 if (max !== max || max <= min) {
3295 max = (min || 1) << 1; //doubling
3296 } else {
3297 max = max + 1;
3298 }
3299 // In order to not exceed maxTimeout, pick a random value between half of maxTimeout and maxTimeout
3300 if (max > maxTimeout) {
3301 min = maxTimeout >> 1; // divide by two
3302 max = maxTimeout;
3303 }
3304 var ratio = Math.random();
3305 var range = max - min;
3306
3307 return ~~(range * ratio + min); // ~~ coerces to an int, but fast.
3308}
3309
3310function defaultBackOff(min) {
3311 var max = 0;
3312 if (!min) {
3313 max = 2000;
3314 }
3315 return randomNumber(min, max);
3316}
3317
3318// designed to give info to browser users, who are disturbed
3319// when they see http errors in the console
3320function explainError(status, str) {
3321 guardedConsole('info', 'The above ' + status + ' is totally normal. ' + str);
3322}
3323
3324var assign;
3325{
3326 if (typeof Object.assign === 'function') {
3327 assign = Object.assign;
3328 } else {
3329 // lite Object.assign polyfill based on
3330 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
3331 assign = function (target) {
3332 var to = Object(target);
3333
3334 for (var index = 1; index < arguments.length; index++) {
3335 var nextSource = arguments[index];
3336
3337 if (nextSource != null) { // Skip over if undefined or null
3338 for (var nextKey in nextSource) {
3339 // Avoid bugs when hasOwnProperty is shadowed
3340 if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
3341 to[nextKey] = nextSource[nextKey];
3342 }
3343 }
3344 }
3345 }
3346 return to;
3347 };
3348 }
3349}
3350
3351var $inject_Object_assign = assign;
3352
3353inherits(PouchError, Error);
3354
3355function PouchError(status, error, reason) {
3356 Error.call(this, reason);
3357 this.status = status;
3358 this.name = error;
3359 this.message = reason;
3360 this.error = true;
3361}
3362
3363PouchError.prototype.toString = function () {
3364 return JSON.stringify({
3365 status: this.status,
3366 name: this.name,
3367 message: this.message,
3368 reason: this.reason
3369 });
3370};
3371
3372var UNAUTHORIZED = new PouchError(401, 'unauthorized', "Name or password is incorrect.");
3373var MISSING_BULK_DOCS = new PouchError(400, 'bad_request', "Missing JSON list of 'docs'");
3374var MISSING_DOC = new PouchError(404, 'not_found', 'missing');
3375var REV_CONFLICT = new PouchError(409, 'conflict', 'Document update conflict');
3376var INVALID_ID = new PouchError(400, 'bad_request', '_id field must contain a string');
3377var MISSING_ID = new PouchError(412, 'missing_id', '_id is required for puts');
3378var RESERVED_ID = new PouchError(400, 'bad_request', 'Only reserved document ids may start with underscore.');
3379var NOT_OPEN = new PouchError(412, 'precondition_failed', 'Database not open');
3380var UNKNOWN_ERROR = new PouchError(500, 'unknown_error', 'Database encountered an unknown error');
3381var BAD_ARG = new PouchError(500, 'badarg', 'Some query argument is invalid');
3382var INVALID_REQUEST = new PouchError(400, 'invalid_request', 'Request was invalid');
3383var QUERY_PARSE_ERROR = new PouchError(400, 'query_parse_error', 'Some query parameter is invalid');
3384var DOC_VALIDATION = new PouchError(500, 'doc_validation', 'Bad special document member');
3385var BAD_REQUEST = new PouchError(400, 'bad_request', 'Something wrong with the request');
3386var NOT_AN_OBJECT = new PouchError(400, 'bad_request', 'Document must be a JSON object');
3387var DB_MISSING = new PouchError(404, 'not_found', 'Database not found');
3388var IDB_ERROR = new PouchError(500, 'indexed_db_went_bad', 'unknown');
3389var WSQ_ERROR = new PouchError(500, 'web_sql_went_bad', 'unknown');
3390var LDB_ERROR = new PouchError(500, 'levelDB_went_went_bad', 'unknown');
3391var FORBIDDEN = new PouchError(403, 'forbidden', 'Forbidden by design doc validate_doc_update function');
3392var INVALID_REV = new PouchError(400, 'bad_request', 'Invalid rev format');
3393var FILE_EXISTS = new PouchError(412, 'file_exists', 'The database could not be created, the file already exists.');
3394var MISSING_STUB = new PouchError(412, 'missing_stub', 'A pre-existing attachment stub wasn\'t found');
3395var INVALID_URL = new PouchError(413, 'invalid_url', 'Provided URL is invalid');
3396
3397function createError(error, reason) {
3398 function CustomPouchError(reason) {
3399 // inherit error properties from our parent error manually
3400 // so as to allow proper JSON parsing.
3401 /* jshint ignore:start */
3402 var names = Object.getOwnPropertyNames(error);
3403 for (var i = 0, len = names.length; i < len; i++) {
3404 if (typeof error[names[i]] !== 'function') {
3405 this[names[i]] = error[names[i]];
3406 }
3407 }
3408
3409 if (this.stack === undefined) {
3410 this.stack = (new Error()).stack;
3411 }
3412
3413 /* jshint ignore:end */
3414 if (reason !== undefined) {
3415 this.reason = reason;
3416 }
3417 }
3418 CustomPouchError.prototype = PouchError.prototype;
3419 return new CustomPouchError(reason);
3420}
3421
3422function generateErrorFromResponse(err) {
3423
3424 if (typeof err !== 'object') {
3425 var data = err;
3426 err = UNKNOWN_ERROR;
3427 err.data = data;
3428 }
3429
3430 if ('error' in err && err.error === 'conflict') {
3431 err.name = 'conflict';
3432 err.status = 409;
3433 }
3434
3435 if (!('name' in err)) {
3436 err.name = err.error || 'unknown';
3437 }
3438
3439 if (!('status' in err)) {
3440 err.status = 500;
3441 }
3442
3443 if (!('message' in err)) {
3444 err.message = err.message || err.reason;
3445 }
3446
3447 if (!('stack' in err)) {
3448 err.stack = (new Error()).stack;
3449 }
3450
3451 return err;
3452}
3453
3454function tryFilter(filter, doc, req) {
3455 try {
3456 return !filter(doc, req);
3457 } catch (err) {
3458 var msg = 'Filter function threw: ' + err.toString();
3459 return createError(BAD_REQUEST, msg);
3460 }
3461}
3462
3463function filterChange(opts) {
3464 var req = {};
3465 var hasFilter = opts.filter && typeof opts.filter === 'function';
3466 req.query = opts.query_params;
3467
3468 return function filter(change) {
3469 if (!change.doc) {
3470 // CSG sends events on the changes feed that don't have documents,
3471 // this hack makes a whole lot of existing code robust.
3472 change.doc = {};
3473 }
3474
3475 var filterReturn = hasFilter && tryFilter(opts.filter, change.doc, req);
3476
3477 if (typeof filterReturn === 'object') {
3478 return filterReturn;
3479 }
3480
3481 if (filterReturn) {
3482 return false;
3483 }
3484
3485 if (!opts.include_docs) {
3486 delete change.doc;
3487 } else if (!opts.attachments) {
3488 for (var att in change.doc._attachments) {
3489 /* istanbul ignore else */
3490 if (Object.prototype.hasOwnProperty.call(change.doc._attachments, att)) {
3491 change.doc._attachments[att].stub = true;
3492 }
3493 }
3494 }
3495 return true;
3496 };
3497}
3498
3499function flatten(arrs) {
3500 var res = [];
3501 for (var i = 0, len = arrs.length; i < len; i++) {
3502 res = res.concat(arrs[i]);
3503 }
3504 return res;
3505}
3506
3507// shim for Function.prototype.name,
3508
3509// Determine id an ID is valid
3510// - invalid IDs begin with an underescore that does not begin '_design' or
3511// '_local'
3512// - any other string value is a valid id
3513// Returns the specific error object for each case
3514function invalidIdError(id) {
3515 var err;
3516 if (!id) {
3517 err = createError(MISSING_ID);
3518 } else if (typeof id !== 'string') {
3519 err = createError(INVALID_ID);
3520 } else if (/^_/.test(id) && !(/^_(design|local)/).test(id)) {
3521 err = createError(RESERVED_ID);
3522 }
3523 if (err) {
3524 throw err;
3525 }
3526}
3527
3528// Checks if a PouchDB object is "remote" or not. This is
3529
3530function isRemote(db) {
3531 if (typeof db._remote === 'boolean') {
3532 return db._remote;
3533 }
3534 /* istanbul ignore next */
3535 if (typeof db.type === 'function') {
3536 guardedConsole('warn',
3537 'db.type() is deprecated and will be removed in ' +
3538 'a future version of PouchDB');
3539 return db.type() === 'http';
3540 }
3541 /* istanbul ignore next */
3542 return false;
3543}
3544
3545function listenerCount(ee, type) {
3546 return 'listenerCount' in ee ? ee.listenerCount(type) :
3547 EE.listenerCount(ee, type);
3548}
3549
3550function parseDesignDocFunctionName(s) {
3551 if (!s) {
3552 return null;
3553 }
3554 var parts = s.split('/');
3555 if (parts.length === 2) {
3556 return parts;
3557 }
3558 if (parts.length === 1) {
3559 return [s, s];
3560 }
3561 return null;
3562}
3563
3564function normalizeDesignDocFunctionName(s) {
3565 var normalized = parseDesignDocFunctionName(s);
3566 return normalized ? normalized.join('/') : null;
3567}
3568
3569// originally parseUri 1.2.2, now patched by us
3570// (c) Steven Levithan <stevenlevithan.com>
3571// MIT License
3572var keys = ["source", "protocol", "authority", "userInfo", "user", "password",
3573 "host", "port", "relative", "path", "directory", "file", "query", "anchor"];
3574var qName ="queryKey";
3575var qParser = /(?:^|&)([^&=]*)=?([^&]*)/g;
3576
3577// use the "loose" parser
3578/* eslint no-useless-escape: 0 */
3579var parser = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
3580
3581function parseUri(str) {
3582 var m = parser.exec(str);
3583 var uri = {};
3584 var i = 14;
3585
3586 while (i--) {
3587 var key = keys[i];
3588 var value = m[i] || "";
3589 var encoded = ['user', 'password'].indexOf(key) !== -1;
3590 uri[key] = encoded ? decodeURIComponent(value) : value;
3591 }
3592
3593 uri[qName] = {};
3594 uri[keys[12]].replace(qParser, function ($0, $1, $2) {
3595 if ($1) {
3596 uri[qName][$1] = $2;
3597 }
3598 });
3599
3600 return uri;
3601}
3602
3603// Based on https://github.com/alexdavid/scope-eval v0.0.3
3604// (source: https://unpkg.com/scope-eval@0.0.3/scope_eval.js)
3605// This is basically just a wrapper around new Function()
3606
3607function scopeEval(source, scope) {
3608 var keys = [];
3609 var values = [];
3610 for (var key in scope) {
3611 if (Object.prototype.hasOwnProperty.call(scope, key)) {
3612 keys.push(key);
3613 values.push(scope[key]);
3614 }
3615 }
3616 keys.push(source);
3617 return Function.apply(null, keys).apply(null, values);
3618}
3619
3620// this is essentially the "update sugar" function from daleharvey/pouchdb#1388
3621// the diffFun tells us what delta to apply to the doc. it either returns
3622// the doc, or false if it doesn't need to do an update after all
3623function upsert(db, docId, diffFun) {
3624 return db.get(docId)[
3625 "catch"](function (err) {
3626 /* istanbul ignore next */
3627 if (err.status !== 404) {
3628 throw err;
3629 }
3630 return {};
3631 })
3632 .then(function (doc) {
3633 // the user might change the _rev, so save it for posterity
3634 var docRev = doc._rev;
3635 var newDoc = diffFun(doc);
3636
3637 if (!newDoc) {
3638 // if the diffFun returns falsy, we short-circuit as
3639 // an optimization
3640 return {updated: false, rev: docRev};
3641 }
3642
3643 // users aren't allowed to modify these values,
3644 // so reset them here
3645 newDoc._id = docId;
3646 newDoc._rev = docRev;
3647 return tryAndPut(db, newDoc, diffFun);
3648 });
3649}
3650
3651function tryAndPut(db, doc, diffFun) {
3652 return db.put(doc).then(function (res) {
3653 return {
3654 updated: true,
3655 rev: res.rev
3656 };
3657 }, function (err) {
3658 /* istanbul ignore next */
3659 if (err.status !== 409) {
3660 throw err;
3661 }
3662 return upsert(db, doc._id, diffFun);
3663 });
3664}
3665
3666var thisAtob = function (str) {
3667 return atob(str);
3668};
3669
3670var thisBtoa = function (str) {
3671 return btoa(str);
3672};
3673
3674// Abstracts constructing a Blob object, so it also works in older
3675// browsers that don't support the native Blob constructor (e.g.
3676// old QtWebKit versions, Android < 4.4).
3677function createBlob(parts, properties) {
3678 /* global BlobBuilder,MSBlobBuilder,MozBlobBuilder,WebKitBlobBuilder */
3679 parts = parts || [];
3680 properties = properties || {};
3681 try {
3682 return new Blob(parts, properties);
3683 } catch (e) {
3684 if (e.name !== "TypeError") {
3685 throw e;
3686 }
3687 var Builder = typeof BlobBuilder !== 'undefined' ? BlobBuilder :
3688 typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder :
3689 typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder :
3690 WebKitBlobBuilder;
3691 var builder = new Builder();
3692 for (var i = 0; i < parts.length; i += 1) {
3693 builder.append(parts[i]);
3694 }
3695 return builder.getBlob(properties.type);
3696 }
3697}
3698
3699// From http://stackoverflow.com/questions/14967647/ (continues on next line)
3700// encode-decode-image-with-base64-breaks-image (2013-04-21)
3701function binaryStringToArrayBuffer(bin) {
3702 var length = bin.length;
3703 var buf = new ArrayBuffer(length);
3704 var arr = new Uint8Array(buf);
3705 for (var i = 0; i < length; i++) {
3706 arr[i] = bin.charCodeAt(i);
3707 }
3708 return buf;
3709}
3710
3711function binStringToBluffer(binString, type) {
3712 return createBlob([binaryStringToArrayBuffer(binString)], {type: type});
3713}
3714
3715function b64ToBluffer(b64, type) {
3716 return binStringToBluffer(thisAtob(b64), type);
3717}
3718
3719//Can't find original post, but this is close
3720//http://stackoverflow.com/questions/6965107/ (continues on next line)
3721//converting-between-strings-and-arraybuffers
3722function arrayBufferToBinaryString(buffer) {
3723 var binary = '';
3724 var bytes = new Uint8Array(buffer);
3725 var length = bytes.byteLength;
3726 for (var i = 0; i < length; i++) {
3727 binary += String.fromCharCode(bytes[i]);
3728 }
3729 return binary;
3730}
3731
3732// shim for browsers that don't support it
3733function readAsBinaryString(blob, callback) {
3734 var reader = new FileReader();
3735 var hasBinaryString = typeof reader.readAsBinaryString === 'function';
3736 reader.onloadend = function (e) {
3737 var result = e.target.result || '';
3738 if (hasBinaryString) {
3739 return callback(result);
3740 }
3741 callback(arrayBufferToBinaryString(result));
3742 };
3743 if (hasBinaryString) {
3744 reader.readAsBinaryString(blob);
3745 } else {
3746 reader.readAsArrayBuffer(blob);
3747 }
3748}
3749
3750function blobToBinaryString(blobOrBuffer, callback) {
3751 readAsBinaryString(blobOrBuffer, function (bin) {
3752 callback(bin);
3753 });
3754}
3755
3756function blobToBase64(blobOrBuffer, callback) {
3757 blobToBinaryString(blobOrBuffer, function (base64) {
3758 callback(thisBtoa(base64));
3759 });
3760}
3761
3762// simplified API. universal browser support is assumed
3763function readAsArrayBuffer(blob, callback) {
3764 var reader = new FileReader();
3765 reader.onloadend = function (e) {
3766 var result = e.target.result || new ArrayBuffer(0);
3767 callback(result);
3768 };
3769 reader.readAsArrayBuffer(blob);
3770}
3771
3772// this is not used in the browser
3773
3774var setImmediateShim = self.setImmediate || self.setTimeout;
3775var MD5_CHUNK_SIZE = 32768;
3776
3777function rawToBase64(raw) {
3778 return thisBtoa(raw);
3779}
3780
3781function sliceBlob(blob, start, end) {
3782 if (blob.webkitSlice) {
3783 return blob.webkitSlice(start, end);
3784 }
3785 return blob.slice(start, end);
3786}
3787
3788function appendBlob(buffer, blob, start, end, callback) {
3789 if (start > 0 || end < blob.size) {
3790 // only slice blob if we really need to
3791 blob = sliceBlob(blob, start, end);
3792 }
3793 readAsArrayBuffer(blob, function (arrayBuffer) {
3794 buffer.append(arrayBuffer);
3795 callback();
3796 });
3797}
3798
3799function appendString(buffer, string, start, end, callback) {
3800 if (start > 0 || end < string.length) {
3801 // only create a substring if we really need to
3802 string = string.substring(start, end);
3803 }
3804 buffer.appendBinary(string);
3805 callback();
3806}
3807
3808function binaryMd5(data, callback) {
3809 var inputIsString = typeof data === 'string';
3810 var len = inputIsString ? data.length : data.size;
3811 var chunkSize = Math.min(MD5_CHUNK_SIZE, len);
3812 var chunks = Math.ceil(len / chunkSize);
3813 var currentChunk = 0;
3814 var buffer = inputIsString ? new Md5() : new Md5.ArrayBuffer();
3815
3816 var append = inputIsString ? appendString : appendBlob;
3817
3818 function next() {
3819 setImmediateShim(loadNextChunk);
3820 }
3821
3822 function done() {
3823 var raw = buffer.end(true);
3824 var base64 = rawToBase64(raw);
3825 callback(base64);
3826 buffer.destroy();
3827 }
3828
3829 function loadNextChunk() {
3830 var start = currentChunk * chunkSize;
3831 var end = start + chunkSize;
3832 currentChunk++;
3833 if (currentChunk < chunks) {
3834 append(buffer, data, start, end, next);
3835 } else {
3836 append(buffer, data, start, end, done);
3837 }
3838 }
3839 loadNextChunk();
3840}
3841
3842function stringMd5(string) {
3843 return Md5.hash(string);
3844}
3845
3846/**
3847 * Creates a new revision string that does NOT include the revision height
3848 * For example '56649f1b0506c6ca9fda0746eb0cacdf'
3849 */
3850function rev$$1(doc, deterministic_revs) {
3851 if (!deterministic_revs) {
3852 return uuid.v4().replace(/-/g, '').toLowerCase();
3853 }
3854
3855 var mutateableDoc = $inject_Object_assign({}, doc);
3856 delete mutateableDoc._rev_tree;
3857 return stringMd5(JSON.stringify(mutateableDoc));
3858}
3859
3860var uuid$1 = uuid.v4; // mimic old import, only v4 is ever used elsewhere
3861
3862// We fetch all leafs of the revision tree, and sort them based on tree length
3863// and whether they were deleted, undeleted documents with the longest revision
3864// tree (most edits) win
3865// The final sort algorithm is slightly documented in a sidebar here:
3866// http://guide.couchdb.org/draft/conflicts.html
3867function winningRev(metadata) {
3868 var winningId;
3869 var winningPos;
3870 var winningDeleted;
3871 var toVisit = metadata.rev_tree.slice();
3872 var node;
3873 while ((node = toVisit.pop())) {
3874 var tree = node.ids;
3875 var branches = tree[2];
3876 var pos = node.pos;
3877 if (branches.length) { // non-leaf
3878 for (var i = 0, len = branches.length; i < len; i++) {
3879 toVisit.push({pos: pos + 1, ids: branches[i]});
3880 }
3881 continue;
3882 }
3883 var deleted = !!tree[1].deleted;
3884 var id = tree[0];
3885 // sort by deleted, then pos, then id
3886 if (!winningId || (winningDeleted !== deleted ? winningDeleted :
3887 winningPos !== pos ? winningPos < pos : winningId < id)) {
3888 winningId = id;
3889 winningPos = pos;
3890 winningDeleted = deleted;
3891 }
3892 }
3893
3894 return winningPos + '-' + winningId;
3895}
3896
3897// Pretty much all below can be combined into a higher order function to
3898// traverse revisions
3899// The return value from the callback will be passed as context to all
3900// children of that node
3901function traverseRevTree(revs, callback) {
3902 var toVisit = revs.slice();
3903
3904 var node;
3905 while ((node = toVisit.pop())) {
3906 var pos = node.pos;
3907 var tree = node.ids;
3908 var branches = tree[2];
3909 var newCtx =
3910 callback(branches.length === 0, pos, tree[0], node.ctx, tree[1]);
3911 for (var i = 0, len = branches.length; i < len; i++) {
3912 toVisit.push({pos: pos + 1, ids: branches[i], ctx: newCtx});
3913 }
3914 }
3915}
3916
3917function sortByPos(a, b) {
3918 return a.pos - b.pos;
3919}
3920
3921function collectLeaves(revs) {
3922 var leaves = [];
3923 traverseRevTree(revs, function (isLeaf, pos, id, acc, opts) {
3924 if (isLeaf) {
3925 leaves.push({rev: pos + "-" + id, pos: pos, opts: opts});
3926 }
3927 });
3928 leaves.sort(sortByPos).reverse();
3929 for (var i = 0, len = leaves.length; i < len; i++) {
3930 delete leaves[i].pos;
3931 }
3932 return leaves;
3933}
3934
3935// returns revs of all conflicts that is leaves such that
3936// 1. are not deleted and
3937// 2. are different than winning revision
3938function collectConflicts(metadata) {
3939 var win = winningRev(metadata);
3940 var leaves = collectLeaves(metadata.rev_tree);
3941 var conflicts = [];
3942 for (var i = 0, len = leaves.length; i < len; i++) {
3943 var leaf = leaves[i];
3944 if (leaf.rev !== win && !leaf.opts.deleted) {
3945 conflicts.push(leaf.rev);
3946 }
3947 }
3948 return conflicts;
3949}
3950
3951// compact a tree by marking its non-leafs as missing,
3952// and return a list of revs to delete
3953function compactTree(metadata) {
3954 var revs = [];
3955 traverseRevTree(metadata.rev_tree, function (isLeaf, pos,
3956 revHash, ctx, opts) {
3957 if (opts.status === 'available' && !isLeaf) {
3958 revs.push(pos + '-' + revHash);
3959 opts.status = 'missing';
3960 }
3961 });
3962 return revs;
3963}
3964
3965// build up a list of all the paths to the leafs in this revision tree
3966function rootToLeaf(revs) {
3967 var paths = [];
3968 var toVisit = revs.slice();
3969 var node;
3970 while ((node = toVisit.pop())) {
3971 var pos = node.pos;
3972 var tree = node.ids;
3973 var id = tree[0];
3974 var opts = tree[1];
3975 var branches = tree[2];
3976 var isLeaf = branches.length === 0;
3977
3978 var history = node.history ? node.history.slice() : [];
3979 history.push({id: id, opts: opts});
3980 if (isLeaf) {
3981 paths.push({pos: (pos + 1 - history.length), ids: history});
3982 }
3983 for (var i = 0, len = branches.length; i < len; i++) {
3984 toVisit.push({pos: pos + 1, ids: branches[i], history: history});
3985 }
3986 }
3987 return paths.reverse();
3988}
3989
3990// for a better overview of what this is doing, read:
3991
3992function sortByPos$1(a, b) {
3993 return a.pos - b.pos;
3994}
3995
3996// classic binary search
3997function binarySearch(arr, item, comparator) {
3998 var low = 0;
3999 var high = arr.length;
4000 var mid;
4001 while (low < high) {
4002 mid = (low + high) >>> 1;
4003 if (comparator(arr[mid], item) < 0) {
4004 low = mid + 1;
4005 } else {
4006 high = mid;
4007 }
4008 }
4009 return low;
4010}
4011
4012// assuming the arr is sorted, insert the item in the proper place
4013function insertSorted(arr, item, comparator) {
4014 var idx = binarySearch(arr, item, comparator);
4015 arr.splice(idx, 0, item);
4016}
4017
4018// Turn a path as a flat array into a tree with a single branch.
4019// If any should be stemmed from the beginning of the array, that's passed
4020// in as the second argument
4021function pathToTree(path, numStemmed) {
4022 var root;
4023 var leaf;
4024 for (var i = numStemmed, len = path.length; i < len; i++) {
4025 var node = path[i];
4026 var currentLeaf = [node.id, node.opts, []];
4027 if (leaf) {
4028 leaf[2].push(currentLeaf);
4029 leaf = currentLeaf;
4030 } else {
4031 root = leaf = currentLeaf;
4032 }
4033 }
4034 return root;
4035}
4036
4037// compare the IDs of two trees
4038function compareTree(a, b) {
4039 return a[0] < b[0] ? -1 : 1;
4040}
4041
4042// Merge two trees together
4043// The roots of tree1 and tree2 must be the same revision
4044function mergeTree(in_tree1, in_tree2) {
4045 var queue = [{tree1: in_tree1, tree2: in_tree2}];
4046 var conflicts = false;
4047 while (queue.length > 0) {
4048 var item = queue.pop();
4049 var tree1 = item.tree1;
4050 var tree2 = item.tree2;
4051
4052 if (tree1[1].status || tree2[1].status) {
4053 tree1[1].status =
4054 (tree1[1].status === 'available' ||
4055 tree2[1].status === 'available') ? 'available' : 'missing';
4056 }
4057
4058 for (var i = 0; i < tree2[2].length; i++) {
4059 if (!tree1[2][0]) {
4060 conflicts = 'new_leaf';
4061 tree1[2][0] = tree2[2][i];
4062 continue;
4063 }
4064
4065 var merged = false;
4066 for (var j = 0; j < tree1[2].length; j++) {
4067 if (tree1[2][j][0] === tree2[2][i][0]) {
4068 queue.push({tree1: tree1[2][j], tree2: tree2[2][i]});
4069 merged = true;
4070 }
4071 }
4072 if (!merged) {
4073 conflicts = 'new_branch';
4074 insertSorted(tree1[2], tree2[2][i], compareTree);
4075 }
4076 }
4077 }
4078 return {conflicts: conflicts, tree: in_tree1};
4079}
4080
4081function doMerge(tree, path, dontExpand) {
4082 var restree = [];
4083 var conflicts = false;
4084 var merged = false;
4085 var res;
4086
4087 if (!tree.length) {
4088 return {tree: [path], conflicts: 'new_leaf'};
4089 }
4090
4091 for (var i = 0, len = tree.length; i < len; i++) {
4092 var branch = tree[i];
4093 if (branch.pos === path.pos && branch.ids[0] === path.ids[0]) {
4094 // Paths start at the same position and have the same root, so they need
4095 // merged
4096 res = mergeTree(branch.ids, path.ids);
4097 restree.push({pos: branch.pos, ids: res.tree});
4098 conflicts = conflicts || res.conflicts;
4099 merged = true;
4100 } else if (dontExpand !== true) {
4101 // The paths start at a different position, take the earliest path and
4102 // traverse up until it as at the same point from root as the path we
4103 // want to merge. If the keys match we return the longer path with the
4104 // other merged After stemming we dont want to expand the trees
4105
4106 var t1 = branch.pos < path.pos ? branch : path;
4107 var t2 = branch.pos < path.pos ? path : branch;
4108 var diff = t2.pos - t1.pos;
4109
4110 var candidateParents = [];
4111
4112 var trees = [];
4113 trees.push({ids: t1.ids, diff: diff, parent: null, parentIdx: null});
4114 while (trees.length > 0) {
4115 var item = trees.pop();
4116 if (item.diff === 0) {
4117 if (item.ids[0] === t2.ids[0]) {
4118 candidateParents.push(item);
4119 }
4120 continue;
4121 }
4122 var elements = item.ids[2];
4123 for (var j = 0, elementsLen = elements.length; j < elementsLen; j++) {
4124 trees.push({
4125 ids: elements[j],
4126 diff: item.diff - 1,
4127 parent: item.ids,
4128 parentIdx: j
4129 });
4130 }
4131 }
4132
4133 var el = candidateParents[0];
4134
4135 if (!el) {
4136 restree.push(branch);
4137 } else {
4138 res = mergeTree(el.ids, t2.ids);
4139 el.parent[2][el.parentIdx] = res.tree;
4140 restree.push({pos: t1.pos, ids: t1.ids});
4141 conflicts = conflicts || res.conflicts;
4142 merged = true;
4143 }
4144 } else {
4145 restree.push(branch);
4146 }
4147 }
4148
4149 // We didnt find
4150 if (!merged) {
4151 restree.push(path);
4152 }
4153
4154 restree.sort(sortByPos$1);
4155
4156 return {
4157 tree: restree,
4158 conflicts: conflicts || 'internal_node'
4159 };
4160}
4161
4162// To ensure we dont grow the revision tree infinitely, we stem old revisions
4163function stem(tree, depth) {
4164 // First we break out the tree into a complete list of root to leaf paths
4165 var paths = rootToLeaf(tree);
4166 var stemmedRevs;
4167
4168 var result;
4169 for (var i = 0, len = paths.length; i < len; i++) {
4170 // Then for each path, we cut off the start of the path based on the
4171 // `depth` to stem to, and generate a new set of flat trees
4172 var path = paths[i];
4173 var stemmed = path.ids;
4174 var node;
4175 if (stemmed.length > depth) {
4176 // only do the stemming work if we actually need to stem
4177 if (!stemmedRevs) {
4178 stemmedRevs = {}; // avoid allocating this object unnecessarily
4179 }
4180 var numStemmed = stemmed.length - depth;
4181 node = {
4182 pos: path.pos + numStemmed,
4183 ids: pathToTree(stemmed, numStemmed)
4184 };
4185
4186 for (var s = 0; s < numStemmed; s++) {
4187 var rev = (path.pos + s) + '-' + stemmed[s].id;
4188 stemmedRevs[rev] = true;
4189 }
4190 } else { // no need to actually stem
4191 node = {
4192 pos: path.pos,
4193 ids: pathToTree(stemmed, 0)
4194 };
4195 }
4196
4197 // Then we remerge all those flat trees together, ensuring that we dont
4198 // connect trees that would go beyond the depth limit
4199 if (result) {
4200 result = doMerge(result, node, true).tree;
4201 } else {
4202 result = [node];
4203 }
4204 }
4205
4206 // this is memory-heavy per Chrome profiler, avoid unless we actually stemmed
4207 if (stemmedRevs) {
4208 traverseRevTree(result, function (isLeaf, pos, revHash) {
4209 // some revisions may have been removed in a branch but not in another
4210 delete stemmedRevs[pos + '-' + revHash];
4211 });
4212 }
4213
4214 return {
4215 tree: result,
4216 revs: stemmedRevs ? Object.keys(stemmedRevs) : []
4217 };
4218}
4219
4220function merge(tree, path, depth) {
4221 var newTree = doMerge(tree, path);
4222 var stemmed = stem(newTree.tree, depth);
4223 return {
4224 tree: stemmed.tree,
4225 stemmedRevs: stemmed.revs,
4226 conflicts: newTree.conflicts
4227 };
4228}
4229
4230// return true if a rev exists in the rev tree, false otherwise
4231function revExists(revs, rev) {
4232 var toVisit = revs.slice();
4233 var splitRev = rev.split('-');
4234 var targetPos = parseInt(splitRev[0], 10);
4235 var targetId = splitRev[1];
4236
4237 var node;
4238 while ((node = toVisit.pop())) {
4239 if (node.pos === targetPos && node.ids[0] === targetId) {
4240 return true;
4241 }
4242 var branches = node.ids[2];
4243 for (var i = 0, len = branches.length; i < len; i++) {
4244 toVisit.push({pos: node.pos + 1, ids: branches[i]});
4245 }
4246 }
4247 return false;
4248}
4249
4250function getTrees(node) {
4251 return node.ids;
4252}
4253
4254// check if a specific revision of a doc has been deleted
4255// - metadata: the metadata object from the doc store
4256// - rev: (optional) the revision to check. defaults to winning revision
4257function isDeleted(metadata, rev) {
4258 if (!rev) {
4259 rev = winningRev(metadata);
4260 }
4261 var id = rev.substring(rev.indexOf('-') + 1);
4262 var toVisit = metadata.rev_tree.map(getTrees);
4263
4264 var tree;
4265 while ((tree = toVisit.pop())) {
4266 if (tree[0] === id) {
4267 return !!tree[1].deleted;
4268 }
4269 toVisit = toVisit.concat(tree[2]);
4270 }
4271}
4272
4273function isLocalId(id) {
4274 return (/^_local/).test(id);
4275}
4276
4277// returns the current leaf node for a given revision
4278function latest(rev, metadata) {
4279 var toVisit = metadata.rev_tree.slice();
4280 var node;
4281 while ((node = toVisit.pop())) {
4282 var pos = node.pos;
4283 var tree = node.ids;
4284 var id = tree[0];
4285 var opts = tree[1];
4286 var branches = tree[2];
4287 var isLeaf = branches.length === 0;
4288
4289 var history = node.history ? node.history.slice() : [];
4290 history.push({id: id, pos: pos, opts: opts});
4291
4292 if (isLeaf) {
4293 for (var i = 0, len = history.length; i < len; i++) {
4294 var historyNode = history[i];
4295 var historyRev = historyNode.pos + '-' + historyNode.id;
4296
4297 if (historyRev === rev) {
4298 // return the rev of this leaf
4299 return pos + '-' + id;
4300 }
4301 }
4302 }
4303
4304 for (var j = 0, l = branches.length; j < l; j++) {
4305 toVisit.push({pos: pos + 1, ids: branches[j], history: history});
4306 }
4307 }
4308
4309 /* istanbul ignore next */
4310 throw new Error('Unable to resolve latest revision for id ' + metadata.id + ', rev ' + rev);
4311}
4312
4313inherits(Changes$1, EE);
4314
4315function tryCatchInChangeListener(self, change, pending, lastSeq) {
4316 // isolate try/catches to avoid V8 deoptimizations
4317 try {
4318 self.emit('change', change, pending, lastSeq);
4319 } catch (e) {
4320 guardedConsole('error', 'Error in .on("change", function):', e);
4321 }
4322}
4323
4324function Changes$1(db, opts, callback) {
4325 EE.call(this);
4326 var self = this;
4327 this.db = db;
4328 opts = opts ? clone(opts) : {};
4329 var complete = opts.complete = once(function (err, resp) {
4330 if (err) {
4331 if (listenerCount(self, 'error') > 0) {
4332 self.emit('error', err);
4333 }
4334 } else {
4335 self.emit('complete', resp);
4336 }
4337 self.removeAllListeners();
4338 db.removeListener('destroyed', onDestroy);
4339 });
4340 if (callback) {
4341 self.on('complete', function (resp) {
4342 callback(null, resp);
4343 });
4344 self.on('error', callback);
4345 }
4346 function onDestroy() {
4347 self.cancel();
4348 }
4349 db.once('destroyed', onDestroy);
4350
4351 opts.onChange = function (change, pending, lastSeq) {
4352 /* istanbul ignore if */
4353 if (self.isCancelled) {
4354 return;
4355 }
4356 tryCatchInChangeListener(self, change, pending, lastSeq);
4357 };
4358
4359 var promise = new Promise(function (fulfill, reject) {
4360 opts.complete = function (err, res) {
4361 if (err) {
4362 reject(err);
4363 } else {
4364 fulfill(res);
4365 }
4366 };
4367 });
4368 self.once('cancel', function () {
4369 db.removeListener('destroyed', onDestroy);
4370 opts.complete(null, {status: 'cancelled'});
4371 });
4372 this.then = promise.then.bind(promise);
4373 this['catch'] = promise['catch'].bind(promise);
4374 this.then(function (result) {
4375 complete(null, result);
4376 }, complete);
4377
4378
4379
4380 if (!db.taskqueue.isReady) {
4381 db.taskqueue.addTask(function (failed) {
4382 if (failed) {
4383 opts.complete(failed);
4384 } else if (self.isCancelled) {
4385 self.emit('cancel');
4386 } else {
4387 self.validateChanges(opts);
4388 }
4389 });
4390 } else {
4391 self.validateChanges(opts);
4392 }
4393}
4394Changes$1.prototype.cancel = function () {
4395 this.isCancelled = true;
4396 if (this.db.taskqueue.isReady) {
4397 this.emit('cancel');
4398 }
4399};
4400function processChange(doc, metadata, opts) {
4401 var changeList = [{rev: doc._rev}];
4402 if (opts.style === 'all_docs') {
4403 changeList = collectLeaves(metadata.rev_tree)
4404 .map(function (x) { return {rev: x.rev}; });
4405 }
4406 var change = {
4407 id: metadata.id,
4408 changes: changeList,
4409 doc: doc
4410 };
4411
4412 if (isDeleted(metadata, doc._rev)) {
4413 change.deleted = true;
4414 }
4415 if (opts.conflicts) {
4416 change.doc._conflicts = collectConflicts(metadata);
4417 if (!change.doc._conflicts.length) {
4418 delete change.doc._conflicts;
4419 }
4420 }
4421 return change;
4422}
4423
4424Changes$1.prototype.validateChanges = function (opts) {
4425 var callback = opts.complete;
4426 var self = this;
4427
4428 /* istanbul ignore else */
4429 if (PouchDB._changesFilterPlugin) {
4430 PouchDB._changesFilterPlugin.validate(opts, function (err) {
4431 if (err) {
4432 return callback(err);
4433 }
4434 self.doChanges(opts);
4435 });
4436 } else {
4437 self.doChanges(opts);
4438 }
4439};
4440
4441Changes$1.prototype.doChanges = function (opts) {
4442 var self = this;
4443 var callback = opts.complete;
4444
4445 opts = clone(opts);
4446 if ('live' in opts && !('continuous' in opts)) {
4447 opts.continuous = opts.live;
4448 }
4449 opts.processChange = processChange;
4450
4451 if (opts.since === 'latest') {
4452 opts.since = 'now';
4453 }
4454 if (!opts.since) {
4455 opts.since = 0;
4456 }
4457 if (opts.since === 'now') {
4458 this.db.info().then(function (info) {
4459 /* istanbul ignore if */
4460 if (self.isCancelled) {
4461 callback(null, {status: 'cancelled'});
4462 return;
4463 }
4464 opts.since = info.update_seq;
4465 self.doChanges(opts);
4466 }, callback);
4467 return;
4468 }
4469
4470 /* istanbul ignore else */
4471 if (PouchDB._changesFilterPlugin) {
4472 PouchDB._changesFilterPlugin.normalize(opts);
4473 if (PouchDB._changesFilterPlugin.shouldFilter(this, opts)) {
4474 return PouchDB._changesFilterPlugin.filter(this, opts);
4475 }
4476 } else {
4477 ['doc_ids', 'filter', 'selector', 'view'].forEach(function (key) {
4478 if (key in opts) {
4479 guardedConsole('warn',
4480 'The "' + key + '" option was passed in to changes/replicate, ' +
4481 'but pouchdb-changes-filter plugin is not installed, so it ' +
4482 'was ignored. Please install the plugin to enable filtering.'
4483 );
4484 }
4485 });
4486 }
4487
4488 if (!('descending' in opts)) {
4489 opts.descending = false;
4490 }
4491
4492 // 0 and 1 should return 1 document
4493 opts.limit = opts.limit === 0 ? 1 : opts.limit;
4494 opts.complete = callback;
4495 var newPromise = this.db._changes(opts);
4496 /* istanbul ignore else */
4497 if (newPromise && typeof newPromise.cancel === 'function') {
4498 var cancel = self.cancel;
4499 self.cancel = getArguments(function (args) {
4500 newPromise.cancel();
4501 cancel.apply(this, args);
4502 });
4503 }
4504};
4505
4506/*
4507 * A generic pouch adapter
4508 */
4509
4510function compare(left, right) {
4511 return left < right ? -1 : left > right ? 1 : 0;
4512}
4513
4514// Wrapper for functions that call the bulkdocs api with a single doc,
4515// if the first result is an error, return an error
4516function yankError(callback, docId) {
4517 return function (err, results) {
4518 if (err || (results[0] && results[0].error)) {
4519 err = err || results[0];
4520 err.docId = docId;
4521 callback(err);
4522 } else {
4523 callback(null, results.length ? results[0] : results);
4524 }
4525 };
4526}
4527
4528// clean docs given to us by the user
4529function cleanDocs(docs) {
4530 for (var i = 0; i < docs.length; i++) {
4531 var doc = docs[i];
4532 if (doc._deleted) {
4533 delete doc._attachments; // ignore atts for deleted docs
4534 } else if (doc._attachments) {
4535 // filter out extraneous keys from _attachments
4536 var atts = Object.keys(doc._attachments);
4537 for (var j = 0; j < atts.length; j++) {
4538 var att = atts[j];
4539 doc._attachments[att] = pick(doc._attachments[att],
4540 ['data', 'digest', 'content_type', 'length', 'revpos', 'stub']);
4541 }
4542 }
4543 }
4544}
4545
4546// compare two docs, first by _id then by _rev
4547function compareByIdThenRev(a, b) {
4548 var idCompare = compare(a._id, b._id);
4549 if (idCompare !== 0) {
4550 return idCompare;
4551 }
4552 var aStart = a._revisions ? a._revisions.start : 0;
4553 var bStart = b._revisions ? b._revisions.start : 0;
4554 return compare(aStart, bStart);
4555}
4556
4557// for every node in a revision tree computes its distance from the closest
4558// leaf
4559function computeHeight(revs) {
4560 var height = {};
4561 var edges = [];
4562 traverseRevTree(revs, function (isLeaf, pos, id, prnt) {
4563 var rev = pos + "-" + id;
4564 if (isLeaf) {
4565 height[rev] = 0;
4566 }
4567 if (prnt !== undefined) {
4568 edges.push({from: prnt, to: rev});
4569 }
4570 return rev;
4571 });
4572
4573 edges.reverse();
4574 edges.forEach(function (edge) {
4575 if (height[edge.from] === undefined) {
4576 height[edge.from] = 1 + height[edge.to];
4577 } else {
4578 height[edge.from] = Math.min(height[edge.from], 1 + height[edge.to]);
4579 }
4580 });
4581 return height;
4582}
4583
4584function allDocsKeysParse(opts) {
4585 var keys = ('limit' in opts) ?
4586 opts.keys.slice(opts.skip, opts.limit + opts.skip) :
4587 (opts.skip > 0) ? opts.keys.slice(opts.skip) : opts.keys;
4588 opts.keys = keys;
4589 opts.skip = 0;
4590 delete opts.limit;
4591 if (opts.descending) {
4592 keys.reverse();
4593 opts.descending = false;
4594 }
4595}
4596
4597// all compaction is done in a queue, to avoid attaching
4598// too many listeners at once
4599function doNextCompaction(self) {
4600 var task = self._compactionQueue[0];
4601 var opts = task.opts;
4602 var callback = task.callback;
4603 self.get('_local/compaction')["catch"](function () {
4604 return false;
4605 }).then(function (doc) {
4606 if (doc && doc.last_seq) {
4607 opts.last_seq = doc.last_seq;
4608 }
4609 self._compact(opts, function (err, res) {
4610 /* istanbul ignore if */
4611 if (err) {
4612 callback(err);
4613 } else {
4614 callback(null, res);
4615 }
4616 immediate(function () {
4617 self._compactionQueue.shift();
4618 if (self._compactionQueue.length) {
4619 doNextCompaction(self);
4620 }
4621 });
4622 });
4623 });
4624}
4625
4626function attachmentNameError(name) {
4627 if (name.charAt(0) === '_') {
4628 return name + ' is not a valid attachment name, attachment ' +
4629 'names cannot start with \'_\'';
4630 }
4631 return false;
4632}
4633
4634inherits(AbstractPouchDB, EE);
4635
4636function AbstractPouchDB() {
4637 EE.call(this);
4638
4639 // re-bind prototyped methods
4640 for (var p in AbstractPouchDB.prototype) {
4641 if (typeof this[p] === 'function') {
4642 this[p] = this[p].bind(this);
4643 }
4644 }
4645}
4646
4647AbstractPouchDB.prototype.post =
4648 adapterFun('post', function (doc, opts, callback) {
4649 if (typeof opts === 'function') {
4650 callback = opts;
4651 opts = {};
4652 }
4653 if (typeof doc !== 'object' || Array.isArray(doc)) {
4654 return callback(createError(NOT_AN_OBJECT));
4655 }
4656 this.bulkDocs({docs: [doc]}, opts, yankError(callback, doc._id));
4657});
4658
4659AbstractPouchDB.prototype.put = adapterFun('put', function (doc, opts, cb) {
4660 if (typeof opts === 'function') {
4661 cb = opts;
4662 opts = {};
4663 }
4664 if (typeof doc !== 'object' || Array.isArray(doc)) {
4665 return cb(createError(NOT_AN_OBJECT));
4666 }
4667 invalidIdError(doc._id);
4668 if (isLocalId(doc._id) && typeof this._putLocal === 'function') {
4669 if (doc._deleted) {
4670 return this._removeLocal(doc, cb);
4671 } else {
4672 return this._putLocal(doc, cb);
4673 }
4674 }
4675 var self = this;
4676 if (opts.force && doc._rev) {
4677 transformForceOptionToNewEditsOption();
4678 putDoc(function (err) {
4679 var result = err ? null : {ok: true, id: doc._id, rev: doc._rev};
4680 cb(err, result);
4681 });
4682 } else {
4683 putDoc(cb);
4684 }
4685
4686 function transformForceOptionToNewEditsOption() {
4687 var parts = doc._rev.split('-');
4688 var oldRevId = parts[1];
4689 var oldRevNum = parseInt(parts[0], 10);
4690
4691 var newRevNum = oldRevNum + 1;
4692 var newRevId = rev$$1();
4693
4694 doc._revisions = {
4695 start: newRevNum,
4696 ids: [newRevId, oldRevId]
4697 };
4698 doc._rev = newRevNum + '-' + newRevId;
4699 opts.new_edits = false;
4700 }
4701 function putDoc(next) {
4702 if (typeof self._put === 'function' && opts.new_edits !== false) {
4703 self._put(doc, opts, next);
4704 } else {
4705 self.bulkDocs({docs: [doc]}, opts, yankError(next, doc._id));
4706 }
4707 }
4708});
4709
4710AbstractPouchDB.prototype.putAttachment =
4711 adapterFun('putAttachment', function (docId, attachmentId, rev,
4712 blob, type) {
4713 var api = this;
4714 if (typeof type === 'function') {
4715 type = blob;
4716 blob = rev;
4717 rev = null;
4718 }
4719 // Lets fix in https://github.com/pouchdb/pouchdb/issues/3267
4720 /* istanbul ignore if */
4721 if (typeof type === 'undefined') {
4722 type = blob;
4723 blob = rev;
4724 rev = null;
4725 }
4726 if (!type) {
4727 guardedConsole('warn', 'Attachment', attachmentId, 'on document', docId, 'is missing content_type');
4728 }
4729
4730 function createAttachment(doc) {
4731 var prevrevpos = '_rev' in doc ? parseInt(doc._rev, 10) : 0;
4732 doc._attachments = doc._attachments || {};
4733 doc._attachments[attachmentId] = {
4734 content_type: type,
4735 data: blob,
4736 revpos: ++prevrevpos
4737 };
4738 return api.put(doc);
4739 }
4740
4741 return api.get(docId).then(function (doc) {
4742 if (doc._rev !== rev) {
4743 throw createError(REV_CONFLICT);
4744 }
4745
4746 return createAttachment(doc);
4747 }, function (err) {
4748 // create new doc
4749 /* istanbul ignore else */
4750 if (err.reason === MISSING_DOC.message) {
4751 return createAttachment({_id: docId});
4752 } else {
4753 throw err;
4754 }
4755 });
4756});
4757
4758AbstractPouchDB.prototype.removeAttachment =
4759 adapterFun('removeAttachment', function (docId, attachmentId, rev,
4760 callback) {
4761 var self = this;
4762 self.get(docId, function (err, obj) {
4763 /* istanbul ignore if */
4764 if (err) {
4765 callback(err);
4766 return;
4767 }
4768 if (obj._rev !== rev) {
4769 callback(createError(REV_CONFLICT));
4770 return;
4771 }
4772 /* istanbul ignore if */
4773 if (!obj._attachments) {
4774 return callback();
4775 }
4776 delete obj._attachments[attachmentId];
4777 if (Object.keys(obj._attachments).length === 0) {
4778 delete obj._attachments;
4779 }
4780 self.put(obj, callback);
4781 });
4782});
4783
4784AbstractPouchDB.prototype.remove =
4785 adapterFun('remove', function (docOrId, optsOrRev, opts, callback) {
4786 var doc;
4787 if (typeof optsOrRev === 'string') {
4788 // id, rev, opts, callback style
4789 doc = {
4790 _id: docOrId,
4791 _rev: optsOrRev
4792 };
4793 if (typeof opts === 'function') {
4794 callback = opts;
4795 opts = {};
4796 }
4797 } else {
4798 // doc, opts, callback style
4799 doc = docOrId;
4800 if (typeof optsOrRev === 'function') {
4801 callback = optsOrRev;
4802 opts = {};
4803 } else {
4804 callback = opts;
4805 opts = optsOrRev;
4806 }
4807 }
4808 opts = opts || {};
4809 opts.was_delete = true;
4810 var newDoc = {_id: doc._id, _rev: (doc._rev || opts.rev)};
4811 newDoc._deleted = true;
4812 if (isLocalId(newDoc._id) && typeof this._removeLocal === 'function') {
4813 return this._removeLocal(doc, callback);
4814 }
4815 this.bulkDocs({docs: [newDoc]}, opts, yankError(callback, newDoc._id));
4816});
4817
4818AbstractPouchDB.prototype.revsDiff =
4819 adapterFun('revsDiff', function (req, opts, callback) {
4820 if (typeof opts === 'function') {
4821 callback = opts;
4822 opts = {};
4823 }
4824 var ids = Object.keys(req);
4825
4826 if (!ids.length) {
4827 return callback(null, {});
4828 }
4829
4830 var count = 0;
4831 var missing = new ExportedMap();
4832
4833 function addToMissing(id, revId) {
4834 if (!missing.has(id)) {
4835 missing.set(id, {missing: []});
4836 }
4837 missing.get(id).missing.push(revId);
4838 }
4839
4840 function processDoc(id, rev_tree) {
4841 // Is this fast enough? Maybe we should switch to a set simulated by a map
4842 var missingForId = req[id].slice(0);
4843 traverseRevTree(rev_tree, function (isLeaf, pos, revHash, ctx,
4844 opts) {
4845 var rev = pos + '-' + revHash;
4846 var idx = missingForId.indexOf(rev);
4847 if (idx === -1) {
4848 return;
4849 }
4850
4851 missingForId.splice(idx, 1);
4852 /* istanbul ignore if */
4853 if (opts.status !== 'available') {
4854 addToMissing(id, rev);
4855 }
4856 });
4857
4858 // Traversing the tree is synchronous, so now `missingForId` contains
4859 // revisions that were not found in the tree
4860 missingForId.forEach(function (rev) {
4861 addToMissing(id, rev);
4862 });
4863 }
4864
4865 ids.map(function (id) {
4866 this._getRevisionTree(id, function (err, rev_tree) {
4867 if (err && err.status === 404 && err.message === 'missing') {
4868 missing.set(id, {missing: req[id]});
4869 } else if (err) {
4870 /* istanbul ignore next */
4871 return callback(err);
4872 } else {
4873 processDoc(id, rev_tree);
4874 }
4875
4876 if (++count === ids.length) {
4877 // convert LazyMap to object
4878 var missingObj = {};
4879 missing.forEach(function (value, key) {
4880 missingObj[key] = value;
4881 });
4882 return callback(null, missingObj);
4883 }
4884 });
4885 }, this);
4886});
4887
4888// _bulk_get API for faster replication, as described in
4889// https://github.com/apache/couchdb-chttpd/pull/33
4890// At the "abstract" level, it will just run multiple get()s in
4891// parallel, because this isn't much of a performance cost
4892// for local databases (except the cost of multiple transactions, which is
4893// small). The http adapter overrides this in order
4894// to do a more efficient single HTTP request.
4895AbstractPouchDB.prototype.bulkGet =
4896 adapterFun('bulkGet', function (opts, callback) {
4897 bulkGet(this, opts, callback);
4898});
4899
4900// compact one document and fire callback
4901// by compacting we mean removing all revisions which
4902// are further from the leaf in revision tree than max_height
4903AbstractPouchDB.prototype.compactDocument =
4904 adapterFun('compactDocument', function (docId, maxHeight, callback) {
4905 var self = this;
4906 this._getRevisionTree(docId, function (err, revTree) {
4907 /* istanbul ignore if */
4908 if (err) {
4909 return callback(err);
4910 }
4911 var height = computeHeight(revTree);
4912 var candidates = [];
4913 var revs = [];
4914 Object.keys(height).forEach(function (rev) {
4915 if (height[rev] > maxHeight) {
4916 candidates.push(rev);
4917 }
4918 });
4919
4920 traverseRevTree(revTree, function (isLeaf, pos, revHash, ctx, opts) {
4921 var rev = pos + '-' + revHash;
4922 if (opts.status === 'available' && candidates.indexOf(rev) !== -1) {
4923 revs.push(rev);
4924 }
4925 });
4926 self._doCompaction(docId, revs, callback);
4927 });
4928});
4929
4930// compact the whole database using single document
4931// compaction
4932AbstractPouchDB.prototype.compact =
4933 adapterFun('compact', function (opts, callback) {
4934 if (typeof opts === 'function') {
4935 callback = opts;
4936 opts = {};
4937 }
4938
4939 var self = this;
4940 opts = opts || {};
4941
4942 self._compactionQueue = self._compactionQueue || [];
4943 self._compactionQueue.push({opts: opts, callback: callback});
4944 if (self._compactionQueue.length === 1) {
4945 doNextCompaction(self);
4946 }
4947});
4948AbstractPouchDB.prototype._compact = function (opts, callback) {
4949 var self = this;
4950 var changesOpts = {
4951 return_docs: false,
4952 last_seq: opts.last_seq || 0
4953 };
4954 var promises = [];
4955
4956 function onChange(row) {
4957 promises.push(self.compactDocument(row.id, 0));
4958 }
4959 function onComplete(resp) {
4960 var lastSeq = resp.last_seq;
4961 Promise.all(promises).then(function () {
4962 return upsert(self, '_local/compaction', function deltaFunc(doc) {
4963 if (!doc.last_seq || doc.last_seq < lastSeq) {
4964 doc.last_seq = lastSeq;
4965 return doc;
4966 }
4967 return false; // somebody else got here first, don't update
4968 });
4969 }).then(function () {
4970 callback(null, {ok: true});
4971 })["catch"](callback);
4972 }
4973 self.changes(changesOpts)
4974 .on('change', onChange)
4975 .on('complete', onComplete)
4976 .on('error', callback);
4977};
4978
4979/* Begin api wrappers. Specific functionality to storage belongs in the
4980 _[method] */
4981AbstractPouchDB.prototype.get = adapterFun('get', function (id, opts, cb) {
4982 if (typeof opts === 'function') {
4983 cb = opts;
4984 opts = {};
4985 }
4986 if (typeof id !== 'string') {
4987 return cb(createError(INVALID_ID));
4988 }
4989 if (isLocalId(id) && typeof this._getLocal === 'function') {
4990 return this._getLocal(id, cb);
4991 }
4992 var leaves = [], self = this;
4993
4994 function finishOpenRevs() {
4995 var result = [];
4996 var count = leaves.length;
4997 /* istanbul ignore if */
4998 if (!count) {
4999 return cb(null, result);
5000 }
5001
5002 // order with open_revs is unspecified
5003 leaves.forEach(function (leaf) {
5004 self.get(id, {
5005 rev: leaf,
5006 revs: opts.revs,
5007 latest: opts.latest,
5008 attachments: opts.attachments,
5009 binary: opts.binary
5010 }, function (err, doc) {
5011 if (!err) {
5012 // using latest=true can produce duplicates
5013 var existing;
5014 for (var i = 0, l = result.length; i < l; i++) {
5015 if (result[i].ok && result[i].ok._rev === doc._rev) {
5016 existing = true;
5017 break;
5018 }
5019 }
5020 if (!existing) {
5021 result.push({ok: doc});
5022 }
5023 } else {
5024 result.push({missing: leaf});
5025 }
5026 count--;
5027 if (!count) {
5028 cb(null, result);
5029 }
5030 });
5031 });
5032 }
5033
5034 if (opts.open_revs) {
5035 if (opts.open_revs === "all") {
5036 this._getRevisionTree(id, function (err, rev_tree) {
5037 /* istanbul ignore if */
5038 if (err) {
5039 return cb(err);
5040 }
5041 leaves = collectLeaves(rev_tree).map(function (leaf) {
5042 return leaf.rev;
5043 });
5044 finishOpenRevs();
5045 });
5046 } else {
5047 if (Array.isArray(opts.open_revs)) {
5048 leaves = opts.open_revs;
5049 for (var i = 0; i < leaves.length; i++) {
5050 var l = leaves[i];
5051 // looks like it's the only thing couchdb checks
5052 if (!(typeof (l) === "string" && /^\d+-/.test(l))) {
5053 return cb(createError(INVALID_REV));
5054 }
5055 }
5056 finishOpenRevs();
5057 } else {
5058 return cb(createError(UNKNOWN_ERROR, 'function_clause'));
5059 }
5060 }
5061 return; // open_revs does not like other options
5062 }
5063
5064 return this._get(id, opts, function (err, result) {
5065 if (err) {
5066 err.docId = id;
5067 return cb(err);
5068 }
5069
5070 var doc = result.doc;
5071 var metadata = result.metadata;
5072 var ctx = result.ctx;
5073
5074 if (opts.conflicts) {
5075 var conflicts = collectConflicts(metadata);
5076 if (conflicts.length) {
5077 doc._conflicts = conflicts;
5078 }
5079 }
5080
5081 if (isDeleted(metadata, doc._rev)) {
5082 doc._deleted = true;
5083 }
5084
5085 if (opts.revs || opts.revs_info) {
5086 var splittedRev = doc._rev.split('-');
5087 var revNo = parseInt(splittedRev[0], 10);
5088 var revHash = splittedRev[1];
5089
5090 var paths = rootToLeaf(metadata.rev_tree);
5091 var path = null;
5092
5093 for (var i = 0; i < paths.length; i++) {
5094 var currentPath = paths[i];
5095 var hashIndex = currentPath.ids.map(function (x) { return x.id; })
5096 .indexOf(revHash);
5097 var hashFoundAtRevPos = hashIndex === (revNo - 1);
5098
5099 if (hashFoundAtRevPos || (!path && hashIndex !== -1)) {
5100 path = currentPath;
5101 }
5102 }
5103
5104 /* istanbul ignore if */
5105 if (!path) {
5106 err = new Error('invalid rev tree');
5107 err.docId = id;
5108 return cb(err);
5109 }
5110
5111 var indexOfRev = path.ids.map(function (x) { return x.id; })
5112 .indexOf(doc._rev.split('-')[1]) + 1;
5113 var howMany = path.ids.length - indexOfRev;
5114 path.ids.splice(indexOfRev, howMany);
5115 path.ids.reverse();
5116
5117 if (opts.revs) {
5118 doc._revisions = {
5119 start: (path.pos + path.ids.length) - 1,
5120 ids: path.ids.map(function (rev) {
5121 return rev.id;
5122 })
5123 };
5124 }
5125 if (opts.revs_info) {
5126 var pos = path.pos + path.ids.length;
5127 doc._revs_info = path.ids.map(function (rev) {
5128 pos--;
5129 return {
5130 rev: pos + '-' + rev.id,
5131 status: rev.opts.status
5132 };
5133 });
5134 }
5135 }
5136
5137 if (opts.attachments && doc._attachments) {
5138 var attachments = doc._attachments;
5139 var count = Object.keys(attachments).length;
5140 if (count === 0) {
5141 return cb(null, doc);
5142 }
5143 Object.keys(attachments).forEach(function (key) {
5144 this._getAttachment(doc._id, key, attachments[key], {
5145 // Previously the revision handling was done in adapter.js
5146 // getAttachment, however since idb-next doesnt we need to
5147 // pass the rev through
5148 rev: doc._rev,
5149 binary: opts.binary,
5150 ctx: ctx
5151 }, function (err, data) {
5152 var att = doc._attachments[key];
5153 att.data = data;
5154 delete att.stub;
5155 delete att.length;
5156 if (!--count) {
5157 cb(null, doc);
5158 }
5159 });
5160 }, self);
5161 } else {
5162 if (doc._attachments) {
5163 for (var key in doc._attachments) {
5164 /* istanbul ignore else */
5165 if (Object.prototype.hasOwnProperty.call(doc._attachments, key)) {
5166 doc._attachments[key].stub = true;
5167 }
5168 }
5169 }
5170 cb(null, doc);
5171 }
5172 });
5173});
5174
5175// TODO: I dont like this, it forces an extra read for every
5176// attachment read and enforces a confusing api between
5177// adapter.js and the adapter implementation
5178AbstractPouchDB.prototype.getAttachment =
5179 adapterFun('getAttachment', function (docId, attachmentId, opts, callback) {
5180 var self = this;
5181 if (opts instanceof Function) {
5182 callback = opts;
5183 opts = {};
5184 }
5185 this._get(docId, opts, function (err, res) {
5186 if (err) {
5187 return callback(err);
5188 }
5189 if (res.doc._attachments && res.doc._attachments[attachmentId]) {
5190 opts.ctx = res.ctx;
5191 opts.binary = true;
5192 self._getAttachment(docId, attachmentId,
5193 res.doc._attachments[attachmentId], opts, callback);
5194 } else {
5195 return callback(createError(MISSING_DOC));
5196 }
5197 });
5198});
5199
5200AbstractPouchDB.prototype.allDocs =
5201 adapterFun('allDocs', function (opts, callback) {
5202 if (typeof opts === 'function') {
5203 callback = opts;
5204 opts = {};
5205 }
5206 opts.skip = typeof opts.skip !== 'undefined' ? opts.skip : 0;
5207 if (opts.start_key) {
5208 opts.startkey = opts.start_key;
5209 }
5210 if (opts.end_key) {
5211 opts.endkey = opts.end_key;
5212 }
5213 if ('keys' in opts) {
5214 if (!Array.isArray(opts.keys)) {
5215 return callback(new TypeError('options.keys must be an array'));
5216 }
5217 var incompatibleOpt =
5218 ['startkey', 'endkey', 'key'].filter(function (incompatibleOpt) {
5219 return incompatibleOpt in opts;
5220 })[0];
5221 if (incompatibleOpt) {
5222 callback(createError(QUERY_PARSE_ERROR,
5223 'Query parameter `' + incompatibleOpt +
5224 '` is not compatible with multi-get'
5225 ));
5226 return;
5227 }
5228 if (!isRemote(this)) {
5229 allDocsKeysParse(opts);
5230 if (opts.keys.length === 0) {
5231 return this._allDocs({limit: 0}, callback);
5232 }
5233 }
5234 }
5235
5236 return this._allDocs(opts, callback);
5237});
5238
5239AbstractPouchDB.prototype.changes = function (opts, callback) {
5240 if (typeof opts === 'function') {
5241 callback = opts;
5242 opts = {};
5243 }
5244
5245 opts = opts || {};
5246
5247 // By default set return_docs to false if the caller has opts.live = true,
5248 // this will prevent us from collecting the set of changes indefinitely
5249 // resulting in growing memory
5250 opts.return_docs = ('return_docs' in opts) ? opts.return_docs : !opts.live;
5251
5252 return new Changes$1(this, opts, callback);
5253};
5254
5255AbstractPouchDB.prototype.close = adapterFun('close', function (callback) {
5256 this._closed = true;
5257 this.emit('closed');
5258 return this._close(callback);
5259});
5260
5261AbstractPouchDB.prototype.info = adapterFun('info', function (callback) {
5262 var self = this;
5263 this._info(function (err, info) {
5264 if (err) {
5265 return callback(err);
5266 }
5267 // assume we know better than the adapter, unless it informs us
5268 info.db_name = info.db_name || self.name;
5269 info.auto_compaction = !!(self.auto_compaction && !isRemote(self));
5270 info.adapter = self.adapter;
5271 callback(null, info);
5272 });
5273});
5274
5275AbstractPouchDB.prototype.id = adapterFun('id', function (callback) {
5276 return this._id(callback);
5277});
5278
5279/* istanbul ignore next */
5280AbstractPouchDB.prototype.type = function () {
5281 return (typeof this._type === 'function') ? this._type() : this.adapter;
5282};
5283
5284AbstractPouchDB.prototype.bulkDocs =
5285 adapterFun('bulkDocs', function (req, opts, callback) {
5286 if (typeof opts === 'function') {
5287 callback = opts;
5288 opts = {};
5289 }
5290
5291 opts = opts || {};
5292
5293 if (Array.isArray(req)) {
5294 req = {
5295 docs: req
5296 };
5297 }
5298
5299 if (!req || !req.docs || !Array.isArray(req.docs)) {
5300 return callback(createError(MISSING_BULK_DOCS));
5301 }
5302
5303 for (var i = 0; i < req.docs.length; ++i) {
5304 if (typeof req.docs[i] !== 'object' || Array.isArray(req.docs[i])) {
5305 return callback(createError(NOT_AN_OBJECT));
5306 }
5307 }
5308
5309 var attachmentError;
5310 req.docs.forEach(function (doc) {
5311 if (doc._attachments) {
5312 Object.keys(doc._attachments).forEach(function (name) {
5313 attachmentError = attachmentError || attachmentNameError(name);
5314 if (!doc._attachments[name].content_type) {
5315 guardedConsole('warn', 'Attachment', name, 'on document', doc._id, 'is missing content_type');
5316 }
5317 });
5318 }
5319 });
5320
5321 if (attachmentError) {
5322 return callback(createError(BAD_REQUEST, attachmentError));
5323 }
5324
5325 if (!('new_edits' in opts)) {
5326 if ('new_edits' in req) {
5327 opts.new_edits = req.new_edits;
5328 } else {
5329 opts.new_edits = true;
5330 }
5331 }
5332
5333 var adapter = this;
5334 if (!opts.new_edits && !isRemote(adapter)) {
5335 // ensure revisions of the same doc are sorted, so that
5336 // the local adapter processes them correctly (#2935)
5337 req.docs.sort(compareByIdThenRev);
5338 }
5339
5340 cleanDocs(req.docs);
5341
5342 // in the case of conflicts, we want to return the _ids to the user
5343 // however, the underlying adapter may destroy the docs array, so
5344 // create a copy here
5345 var ids = req.docs.map(function (doc) {
5346 return doc._id;
5347 });
5348
5349 return this._bulkDocs(req, opts, function (err, res) {
5350 if (err) {
5351 return callback(err);
5352 }
5353 if (!opts.new_edits) {
5354 // this is what couch does when new_edits is false
5355 res = res.filter(function (x) {
5356 return x.error;
5357 });
5358 }
5359 // add ids for error/conflict responses (not required for CouchDB)
5360 if (!isRemote(adapter)) {
5361 for (var i = 0, l = res.length; i < l; i++) {
5362 res[i].id = res[i].id || ids[i];
5363 }
5364 }
5365
5366 callback(null, res);
5367 });
5368});
5369
5370AbstractPouchDB.prototype.registerDependentDatabase =
5371 adapterFun('registerDependentDatabase', function (dependentDb,
5372 callback) {
5373 var dbOptions = clone(this.__opts);
5374 if (this.__opts.view_adapter) {
5375 dbOptions.adapter = this.__opts.view_adapter;
5376 }
5377
5378 var depDB = new this.constructor(dependentDb, dbOptions);
5379
5380 function diffFun(doc) {
5381 doc.dependentDbs = doc.dependentDbs || {};
5382 if (doc.dependentDbs[dependentDb]) {
5383 return false; // no update required
5384 }
5385 doc.dependentDbs[dependentDb] = true;
5386 return doc;
5387 }
5388 upsert(this, '_local/_pouch_dependentDbs', diffFun)
5389 .then(function () {
5390 callback(null, {db: depDB});
5391 })["catch"](callback);
5392});
5393
5394AbstractPouchDB.prototype.destroy =
5395 adapterFun('destroy', function (opts, callback) {
5396
5397 if (typeof opts === 'function') {
5398 callback = opts;
5399 opts = {};
5400 }
5401
5402 var self = this;
5403 var usePrefix = 'use_prefix' in self ? self.use_prefix : true;
5404
5405 function destroyDb() {
5406 // call destroy method of the particular adaptor
5407 self._destroy(opts, function (err, resp) {
5408 if (err) {
5409 return callback(err);
5410 }
5411 self._destroyed = true;
5412 self.emit('destroyed');
5413 callback(null, resp || { 'ok': true });
5414 });
5415 }
5416
5417 if (isRemote(self)) {
5418 // no need to check for dependent DBs if it's a remote DB
5419 return destroyDb();
5420 }
5421
5422 self.get('_local/_pouch_dependentDbs', function (err, localDoc) {
5423 if (err) {
5424 /* istanbul ignore if */
5425 if (err.status !== 404) {
5426 return callback(err);
5427 } else { // no dependencies
5428 return destroyDb();
5429 }
5430 }
5431 var dependentDbs = localDoc.dependentDbs;
5432 var PouchDB = self.constructor;
5433 var deletedMap = Object.keys(dependentDbs).map(function (name) {
5434 // use_prefix is only false in the browser
5435 /* istanbul ignore next */
5436 var trueName = usePrefix ?
5437 name.replace(new RegExp('^' + PouchDB.prefix), '') : name;
5438 return new PouchDB(trueName, self.__opts).destroy();
5439 });
5440 Promise.all(deletedMap).then(destroyDb, callback);
5441 });
5442});
5443
5444function TaskQueue() {
5445 this.isReady = false;
5446 this.failed = false;
5447 this.queue = [];
5448}
5449
5450TaskQueue.prototype.execute = function () {
5451 var fun;
5452 if (this.failed) {
5453 while ((fun = this.queue.shift())) {
5454 fun(this.failed);
5455 }
5456 } else {
5457 while ((fun = this.queue.shift())) {
5458 fun();
5459 }
5460 }
5461};
5462
5463TaskQueue.prototype.fail = function (err) {
5464 this.failed = err;
5465 this.execute();
5466};
5467
5468TaskQueue.prototype.ready = function (db) {
5469 this.isReady = true;
5470 this.db = db;
5471 this.execute();
5472};
5473
5474TaskQueue.prototype.addTask = function (fun) {
5475 this.queue.push(fun);
5476 if (this.failed) {
5477 this.execute();
5478 }
5479};
5480
5481function parseAdapter(name, opts) {
5482 var match = name.match(/([a-z-]*):\/\/(.*)/);
5483 if (match) {
5484 // the http adapter expects the fully qualified name
5485 return {
5486 name: /https?/.test(match[1]) ? match[1] + '://' + match[2] : match[2],
5487 adapter: match[1]
5488 };
5489 }
5490
5491 var adapters = PouchDB.adapters;
5492 var preferredAdapters = PouchDB.preferredAdapters;
5493 var prefix = PouchDB.prefix;
5494 var adapterName = opts.adapter;
5495
5496 if (!adapterName) { // automatically determine adapter
5497 for (var i = 0; i < preferredAdapters.length; ++i) {
5498 adapterName = preferredAdapters[i];
5499 // check for browsers that have been upgraded from websql-only to websql+idb
5500 /* istanbul ignore if */
5501 if (adapterName === 'idb' && 'websql' in adapters &&
5502 hasLocalStorage() && localStorage['_pouch__websqldb_' + prefix + name]) {
5503 // log it, because this can be confusing during development
5504 guardedConsole('log', 'PouchDB is downgrading "' + name + '" to WebSQL to' +
5505 ' avoid data loss, because it was already opened with WebSQL.');
5506 continue; // keep using websql to avoid user data loss
5507 }
5508 break;
5509 }
5510 }
5511
5512 var adapter = adapters[adapterName];
5513
5514 // if adapter is invalid, then an error will be thrown later
5515 var usePrefix = (adapter && 'use_prefix' in adapter) ?
5516 adapter.use_prefix : true;
5517
5518 return {
5519 name: usePrefix ? (prefix + name) : name,
5520 adapter: adapterName
5521 };
5522}
5523
5524// OK, so here's the deal. Consider this code:
5525// var db1 = new PouchDB('foo');
5526// var db2 = new PouchDB('foo');
5527// db1.destroy();
5528// ^ these two both need to emit 'destroyed' events,
5529// as well as the PouchDB constructor itself.
5530// So we have one db object (whichever one got destroy() called on it)
5531// responsible for emitting the initial event, which then gets emitted
5532// by the constructor, which then broadcasts it to any other dbs
5533// that may have been created with the same name.
5534function prepareForDestruction(self) {
5535
5536 function onDestroyed(from_constructor) {
5537 self.removeListener('closed', onClosed);
5538 if (!from_constructor) {
5539 self.constructor.emit('destroyed', self.name);
5540 }
5541 }
5542
5543 function onClosed() {
5544 self.removeListener('destroyed', onDestroyed);
5545 self.constructor.emit('unref', self);
5546 }
5547
5548 self.once('destroyed', onDestroyed);
5549 self.once('closed', onClosed);
5550 self.constructor.emit('ref', self);
5551}
5552
5553inherits(PouchDB, AbstractPouchDB);
5554function PouchDB(name, opts) {
5555 // In Node our test suite only tests this for PouchAlt unfortunately
5556 /* istanbul ignore if */
5557 if (!(this instanceof PouchDB)) {
5558 return new PouchDB(name, opts);
5559 }
5560
5561 var self = this;
5562 opts = opts || {};
5563
5564 if (name && typeof name === 'object') {
5565 opts = name;
5566 name = opts.name;
5567 delete opts.name;
5568 }
5569
5570 if (opts.deterministic_revs === undefined) {
5571 opts.deterministic_revs = true;
5572 }
5573
5574 this.__opts = opts = clone(opts);
5575
5576 self.auto_compaction = opts.auto_compaction;
5577 self.prefix = PouchDB.prefix;
5578
5579 if (typeof name !== 'string') {
5580 throw new Error('Missing/invalid DB name');
5581 }
5582
5583 var prefixedName = (opts.prefix || '') + name;
5584 var backend = parseAdapter(prefixedName, opts);
5585
5586 opts.name = backend.name;
5587 opts.adapter = opts.adapter || backend.adapter;
5588
5589 self.name = name;
5590 self._adapter = opts.adapter;
5591 PouchDB.emit('debug', ['adapter', 'Picked adapter: ', opts.adapter]);
5592
5593 if (!PouchDB.adapters[opts.adapter] ||
5594 !PouchDB.adapters[opts.adapter].valid()) {
5595 throw new Error('Invalid Adapter: ' + opts.adapter);
5596 }
5597
5598 if (opts.view_adapter) {
5599 if (!PouchDB.adapters[opts.view_adapter] ||
5600 !PouchDB.adapters[opts.view_adapter].valid()) {
5601 throw new Error('Invalid View Adapter: ' + opts.view_adapter);
5602 }
5603 }
5604
5605 AbstractPouchDB.call(self);
5606 self.taskqueue = new TaskQueue();
5607
5608 self.adapter = opts.adapter;
5609
5610 PouchDB.adapters[opts.adapter].call(self, opts, function (err) {
5611 if (err) {
5612 return self.taskqueue.fail(err);
5613 }
5614 prepareForDestruction(self);
5615
5616 self.emit('created', self);
5617 PouchDB.emit('created', self.name);
5618 self.taskqueue.ready(self);
5619 });
5620
5621}
5622
5623// AbortController was introduced quite a while after fetch and
5624// isnt required for PouchDB to function so polyfill if needed
5625var a = (typeof AbortController !== 'undefined')
5626 ? AbortController
5627 : function () { return {abort: function () {}}; };
5628
5629var f$1 = fetch;
5630var h = Headers;
5631
5632PouchDB.adapters = {};
5633PouchDB.preferredAdapters = [];
5634
5635PouchDB.prefix = '_pouch_';
5636
5637var eventEmitter = new EE();
5638
5639function setUpEventEmitter(Pouch) {
5640 Object.keys(EE.prototype).forEach(function (key) {
5641 if (typeof EE.prototype[key] === 'function') {
5642 Pouch[key] = eventEmitter[key].bind(eventEmitter);
5643 }
5644 });
5645
5646 // these are created in constructor.js, and allow us to notify each DB with
5647 // the same name that it was destroyed, via the constructor object
5648 var destructListeners = Pouch._destructionListeners = new ExportedMap();
5649
5650 Pouch.on('ref', function onConstructorRef(db) {
5651 if (!destructListeners.has(db.name)) {
5652 destructListeners.set(db.name, []);
5653 }
5654 destructListeners.get(db.name).push(db);
5655 });
5656
5657 Pouch.on('unref', function onConstructorUnref(db) {
5658 if (!destructListeners.has(db.name)) {
5659 return;
5660 }
5661 var dbList = destructListeners.get(db.name);
5662 var pos = dbList.indexOf(db);
5663 if (pos < 0) {
5664 /* istanbul ignore next */
5665 return;
5666 }
5667 dbList.splice(pos, 1);
5668 if (dbList.length > 1) {
5669 /* istanbul ignore next */
5670 destructListeners.set(db.name, dbList);
5671 } else {
5672 destructListeners["delete"](db.name);
5673 }
5674 });
5675
5676 Pouch.on('destroyed', function onConstructorDestroyed(name) {
5677 if (!destructListeners.has(name)) {
5678 return;
5679 }
5680 var dbList = destructListeners.get(name);
5681 destructListeners["delete"](name);
5682 dbList.forEach(function (db) {
5683 db.emit('destroyed',true);
5684 });
5685 });
5686}
5687
5688setUpEventEmitter(PouchDB);
5689
5690PouchDB.adapter = function (id, obj, addToPreferredAdapters) {
5691 /* istanbul ignore else */
5692 if (obj.valid()) {
5693 PouchDB.adapters[id] = obj;
5694 if (addToPreferredAdapters) {
5695 PouchDB.preferredAdapters.push(id);
5696 }
5697 }
5698};
5699
5700PouchDB.plugin = function (obj) {
5701 if (typeof obj === 'function') { // function style for plugins
5702 obj(PouchDB);
5703 } else if (typeof obj !== 'object' || Object.keys(obj).length === 0) {
5704 throw new Error('Invalid plugin: got "' + obj + '", expected an object or a function');
5705 } else {
5706 Object.keys(obj).forEach(function (id) { // object style for plugins
5707 PouchDB.prototype[id] = obj[id];
5708 });
5709 }
5710 if (this.__defaults) {
5711 PouchDB.__defaults = $inject_Object_assign({}, this.__defaults);
5712 }
5713 return PouchDB;
5714};
5715
5716PouchDB.defaults = function (defaultOpts) {
5717 function PouchAlt(name, opts) {
5718 if (!(this instanceof PouchAlt)) {
5719 return new PouchAlt(name, opts);
5720 }
5721
5722 opts = opts || {};
5723
5724 if (name && typeof name === 'object') {
5725 opts = name;
5726 name = opts.name;
5727 delete opts.name;
5728 }
5729
5730 opts = $inject_Object_assign({}, PouchAlt.__defaults, opts);
5731 PouchDB.call(this, name, opts);
5732 }
5733
5734 inherits(PouchAlt, PouchDB);
5735
5736 PouchAlt.preferredAdapters = PouchDB.preferredAdapters.slice();
5737 Object.keys(PouchDB).forEach(function (key) {
5738 if (!(key in PouchAlt)) {
5739 PouchAlt[key] = PouchDB[key];
5740 }
5741 });
5742
5743 // make default options transitive
5744 // https://github.com/pouchdb/pouchdb/issues/5922
5745 PouchAlt.__defaults = $inject_Object_assign({}, this.__defaults, defaultOpts);
5746
5747 return PouchAlt;
5748};
5749
5750PouchDB.fetch = function (url, opts) {
5751 return f$1(url, opts);
5752};
5753
5754// managed automatically by set-version.js
5755var version = "7.3.0";
5756
5757// this would just be "return doc[field]", but fields
5758// can be "deep" due to dot notation
5759function getFieldFromDoc(doc, parsedField) {
5760 var value = doc;
5761 for (var i = 0, len = parsedField.length; i < len; i++) {
5762 var key = parsedField[i];
5763 value = value[key];
5764 if (!value) {
5765 break;
5766 }
5767 }
5768 return value;
5769}
5770
5771function compare$1(left, right) {
5772 return left < right ? -1 : left > right ? 1 : 0;
5773}
5774
5775// Converts a string in dot notation to an array of its components, with backslash escaping
5776function parseField(fieldName) {
5777 // fields may be deep (e.g. "foo.bar.baz"), so parse
5778 var fields = [];
5779 var current = '';
5780 for (var i = 0, len = fieldName.length; i < len; i++) {
5781 var ch = fieldName[i];
5782 if (i > 0 && fieldName[i - 1] === '\\' && (ch === '$' || ch === '.')) {
5783 // escaped delimiter
5784 current = current.substring(0, current.length - 1) + ch;
5785 } else if (ch === '.') {
5786 // When `.` is not escaped (above), it is a field delimiter
5787 fields.push(current);
5788 current = '';
5789 } else { // normal character
5790 current += ch;
5791 }
5792 }
5793 fields.push(current);
5794 return fields;
5795}
5796
5797var combinationFields = ['$or', '$nor', '$not'];
5798function isCombinationalField(field) {
5799 return combinationFields.indexOf(field) > -1;
5800}
5801
5802function getKey(obj) {
5803 return Object.keys(obj)[0];
5804}
5805
5806function getValue(obj) {
5807 return obj[getKey(obj)];
5808}
5809
5810
5811// flatten an array of selectors joined by an $and operator
5812function mergeAndedSelectors(selectors) {
5813
5814 // sort to ensure that e.g. if the user specified
5815 // $and: [{$gt: 'a'}, {$gt: 'b'}], then it's collapsed into
5816 // just {$gt: 'b'}
5817 var res = {};
5818 var first = {$or: true, $nor: true};
5819
5820 selectors.forEach(function (selector) {
5821 Object.keys(selector).forEach(function (field) {
5822 var matcher = selector[field];
5823 if (typeof matcher !== 'object') {
5824 matcher = {$eq: matcher};
5825 }
5826
5827 if (isCombinationalField(field)) {
5828 // or, nor
5829 if (matcher instanceof Array) {
5830 if (first[field]) {
5831 first[field] = false;
5832 res[field] = matcher;
5833 return;
5834 }
5835
5836 var entries = [];
5837 res[field].forEach(function (existing) {
5838 Object.keys(matcher).forEach(function (key) {
5839 var m = matcher[key];
5840 var longest = Math.max(Object.keys(existing).length, Object.keys(m).length);
5841 var merged = mergeAndedSelectors([existing, m]);
5842 if (Object.keys(merged).length <= longest) {
5843 // we have a situation like: (a :{$eq :1} || ...) && (a {$eq: 2} || ...)
5844 // merging would produce a $eq 2 when actually we shouldn't ever match against these merged conditions
5845 // merged should always contain more values to be valid
5846 return;
5847 }
5848 entries.push(merged);
5849 });
5850 });
5851 res[field] = entries;
5852 } else {
5853 // not
5854 res[field] = mergeAndedSelectors([matcher]);
5855 }
5856 } else {
5857 var fieldMatchers = res[field] = res[field] || {};
5858 Object.keys(matcher).forEach(function (operator) {
5859 var value = matcher[operator];
5860
5861 if (operator === '$gt' || operator === '$gte') {
5862 return mergeGtGte(operator, value, fieldMatchers);
5863 } else if (operator === '$lt' || operator === '$lte') {
5864 return mergeLtLte(operator, value, fieldMatchers);
5865 } else if (operator === '$ne') {
5866 return mergeNe(value, fieldMatchers);
5867 } else if (operator === '$eq') {
5868 return mergeEq(value, fieldMatchers);
5869 } else if (operator === "$regex") {
5870 return mergeRegex(value, fieldMatchers);
5871 }
5872 fieldMatchers[operator] = value;
5873 });
5874 }
5875 });
5876 });
5877
5878 return res;
5879}
5880
5881
5882
5883// collapse logically equivalent gt/gte values
5884function mergeGtGte(operator, value, fieldMatchers) {
5885 if (typeof fieldMatchers.$eq !== 'undefined') {
5886 return; // do nothing
5887 }
5888 if (typeof fieldMatchers.$gte !== 'undefined') {
5889 if (operator === '$gte') {
5890 if (value > fieldMatchers.$gte) { // more specificity
5891 fieldMatchers.$gte = value;
5892 }
5893 } else { // operator === '$gt'
5894 if (value >= fieldMatchers.$gte) { // more specificity
5895 delete fieldMatchers.$gte;
5896 fieldMatchers.$gt = value;
5897 }
5898 }
5899 } else if (typeof fieldMatchers.$gt !== 'undefined') {
5900 if (operator === '$gte') {
5901 if (value > fieldMatchers.$gt) { // more specificity
5902 delete fieldMatchers.$gt;
5903 fieldMatchers.$gte = value;
5904 }
5905 } else { // operator === '$gt'
5906 if (value > fieldMatchers.$gt) { // more specificity
5907 fieldMatchers.$gt = value;
5908 }
5909 }
5910 } else {
5911 fieldMatchers[operator] = value;
5912 }
5913}
5914
5915// collapse logically equivalent lt/lte values
5916function mergeLtLte(operator, value, fieldMatchers) {
5917 if (typeof fieldMatchers.$eq !== 'undefined') {
5918 return; // do nothing
5919 }
5920 if (typeof fieldMatchers.$lte !== 'undefined') {
5921 if (operator === '$lte') {
5922 if (value < fieldMatchers.$lte) { // more specificity
5923 fieldMatchers.$lte = value;
5924 }
5925 } else { // operator === '$gt'
5926 if (value <= fieldMatchers.$lte) { // more specificity
5927 delete fieldMatchers.$lte;
5928 fieldMatchers.$lt = value;
5929 }
5930 }
5931 } else if (typeof fieldMatchers.$lt !== 'undefined') {
5932 if (operator === '$lte') {
5933 if (value < fieldMatchers.$lt) { // more specificity
5934 delete fieldMatchers.$lt;
5935 fieldMatchers.$lte = value;
5936 }
5937 } else { // operator === '$gt'
5938 if (value < fieldMatchers.$lt) { // more specificity
5939 fieldMatchers.$lt = value;
5940 }
5941 }
5942 } else {
5943 fieldMatchers[operator] = value;
5944 }
5945}
5946
5947// combine $ne values into one array
5948function mergeNe(value, fieldMatchers) {
5949 if ('$ne' in fieldMatchers) {
5950 // there are many things this could "not" be
5951 fieldMatchers.$ne.push(value);
5952 } else { // doesn't exist yet
5953 fieldMatchers.$ne = [value];
5954 }
5955}
5956
5957// add $eq into the mix
5958function mergeEq(value, fieldMatchers) {
5959 // these all have less specificity than the $eq
5960 // TODO: check for user errors here
5961 delete fieldMatchers.$gt;
5962 delete fieldMatchers.$gte;
5963 delete fieldMatchers.$lt;
5964 delete fieldMatchers.$lte;
5965 delete fieldMatchers.$ne;
5966 fieldMatchers.$eq = value;
5967}
5968
5969// combine $regex values into one array
5970function mergeRegex(value, fieldMatchers) {
5971 if ('$regex' in fieldMatchers) {
5972 // a value could match multiple regexes
5973 fieldMatchers.$regex.push(value);
5974 } else { // doesn't exist yet
5975 fieldMatchers.$regex = [value];
5976 }
5977}
5978
5979//#7458: execute function mergeAndedSelectors on nested $and
5980function mergeAndedSelectorsNested(obj) {
5981 for (var prop in obj) {
5982 if (Array.isArray(obj)) {
5983 for (var i in obj) {
5984 if (obj[i]['$and']) {
5985 obj[i] = mergeAndedSelectors(obj[i]['$and']);
5986 }
5987 }
5988 }
5989 var value = obj[prop];
5990 if (typeof value === 'object') {
5991 mergeAndedSelectorsNested(value); // <- recursive call
5992 }
5993 }
5994 return obj;
5995}
5996
5997//#7458: determine id $and is present in selector (at any level)
5998function isAndInSelector(obj, isAnd) {
5999 for (var prop in obj) {
6000 if (prop === '$and') {
6001 isAnd = true;
6002 }
6003 var value = obj[prop];
6004 if (typeof value === 'object') {
6005 isAnd = isAndInSelector(value, isAnd); // <- recursive call
6006 }
6007 }
6008 return isAnd;
6009}
6010
6011//
6012// normalize the selector
6013//
6014function massageSelector(input) {
6015 var result = clone(input);
6016 var wasAnded = false;
6017 //#7458: if $and is present in selector (at any level) merge nested $and
6018 if (isAndInSelector(result, false)) {
6019 result = mergeAndedSelectorsNested(result);
6020 if ('$and' in result) {
6021 result = mergeAndedSelectors(result['$and']);
6022 }
6023 wasAnded = true;
6024 }
6025
6026 ['$or', '$nor'].forEach(function (orOrNor) {
6027 if (orOrNor in result) {
6028 // message each individual selector
6029 // e.g. {foo: 'bar'} becomes {foo: {$eq: 'bar'}}
6030 result[orOrNor].forEach(function (subSelector) {
6031 var fields = Object.keys(subSelector);
6032 for (var i = 0; i < fields.length; i++) {
6033 var field = fields[i];
6034 var matcher = subSelector[field];
6035 if (typeof matcher !== 'object' || matcher === null) {
6036 subSelector[field] = {$eq: matcher};
6037 }
6038 }
6039 });
6040 }
6041 });
6042
6043 if ('$not' in result) {
6044 //This feels a little like forcing, but it will work for now,
6045 //I would like to come back to this and make the merging of selectors a little more generic
6046 result['$not'] = mergeAndedSelectors([result['$not']]);
6047 }
6048
6049 var fields = Object.keys(result);
6050
6051 for (var i = 0; i < fields.length; i++) {
6052 var field = fields[i];
6053 var matcher = result[field];
6054
6055 if (typeof matcher !== 'object' || matcher === null) {
6056 matcher = {$eq: matcher};
6057 } else if (!wasAnded) {
6058 // These values must be placed in an array because these operators can be used multiple times on the same field
6059 // when $and is used, mergeAndedSelectors takes care of putting them into arrays, otherwise it's done here:
6060 if ('$ne' in matcher) {
6061 matcher.$ne = [matcher.$ne];
6062 }
6063 if ('$regex' in matcher) {
6064 matcher.$regex = [matcher.$regex];
6065 }
6066 }
6067 result[field] = matcher;
6068 }
6069
6070 return result;
6071}
6072
6073function pad(str, padWith, upToLength) {
6074 var padding = '';
6075 var targetLength = upToLength - str.length;
6076 /* istanbul ignore next */
6077 while (padding.length < targetLength) {
6078 padding += padWith;
6079 }
6080 return padding;
6081}
6082
6083function padLeft(str, padWith, upToLength) {
6084 var padding = pad(str, padWith, upToLength);
6085 return padding + str;
6086}
6087
6088var MIN_MAGNITUDE = -324; // verified by -Number.MIN_VALUE
6089var MAGNITUDE_DIGITS = 3; // ditto
6090var SEP = ''; // set to '_' for easier debugging
6091
6092function collate(a, b) {
6093
6094 if (a === b) {
6095 return 0;
6096 }
6097
6098 a = normalizeKey(a);
6099 b = normalizeKey(b);
6100
6101 var ai = collationIndex(a);
6102 var bi = collationIndex(b);
6103 if ((ai - bi) !== 0) {
6104 return ai - bi;
6105 }
6106 switch (typeof a) {
6107 case 'number':
6108 return a - b;
6109 case 'boolean':
6110 return a < b ? -1 : 1;
6111 case 'string':
6112 return stringCollate(a, b);
6113 }
6114 return Array.isArray(a) ? arrayCollate(a, b) : objectCollate(a, b);
6115}
6116
6117// couch considers null/NaN/Infinity/-Infinity === undefined,
6118// for the purposes of mapreduce indexes. also, dates get stringified.
6119function normalizeKey(key) {
6120 switch (typeof key) {
6121 case 'undefined':
6122 return null;
6123 case 'number':
6124 if (key === Infinity || key === -Infinity || isNaN(key)) {
6125 return null;
6126 }
6127 return key;
6128 case 'object':
6129 var origKey = key;
6130 if (Array.isArray(key)) {
6131 var len = key.length;
6132 key = new Array(len);
6133 for (var i = 0; i < len; i++) {
6134 key[i] = normalizeKey(origKey[i]);
6135 }
6136 /* istanbul ignore next */
6137 } else if (key instanceof Date) {
6138 return key.toJSON();
6139 } else if (key !== null) { // generic object
6140 key = {};
6141 for (var k in origKey) {
6142 if (Object.prototype.hasOwnProperty.call(origKey, k)) {
6143 var val = origKey[k];
6144 if (typeof val !== 'undefined') {
6145 key[k] = normalizeKey(val);
6146 }
6147 }
6148 }
6149 }
6150 }
6151 return key;
6152}
6153
6154function indexify(key) {
6155 if (key !== null) {
6156 switch (typeof key) {
6157 case 'boolean':
6158 return key ? 1 : 0;
6159 case 'number':
6160 return numToIndexableString(key);
6161 case 'string':
6162 // We've to be sure that key does not contain \u0000
6163 // Do order-preserving replacements:
6164 // 0 -> 1, 1
6165 // 1 -> 1, 2
6166 // 2 -> 2, 2
6167 /* eslint-disable no-control-regex */
6168 return key
6169 .replace(/\u0002/g, '\u0002\u0002')
6170 .replace(/\u0001/g, '\u0001\u0002')
6171 .replace(/\u0000/g, '\u0001\u0001');
6172 /* eslint-enable no-control-regex */
6173 case 'object':
6174 var isArray = Array.isArray(key);
6175 var arr = isArray ? key : Object.keys(key);
6176 var i = -1;
6177 var len = arr.length;
6178 var result = '';
6179 if (isArray) {
6180 while (++i < len) {
6181 result += toIndexableString(arr[i]);
6182 }
6183 } else {
6184 while (++i < len) {
6185 var objKey = arr[i];
6186 result += toIndexableString(objKey) +
6187 toIndexableString(key[objKey]);
6188 }
6189 }
6190 return result;
6191 }
6192 }
6193 return '';
6194}
6195
6196// convert the given key to a string that would be appropriate
6197// for lexical sorting, e.g. within a database, where the
6198// sorting is the same given by the collate() function.
6199function toIndexableString(key) {
6200 var zero = '\u0000';
6201 key = normalizeKey(key);
6202 return collationIndex(key) + SEP + indexify(key) + zero;
6203}
6204
6205function parseNumber(str, i) {
6206 var originalIdx = i;
6207 var num;
6208 var zero = str[i] === '1';
6209 if (zero) {
6210 num = 0;
6211 i++;
6212 } else {
6213 var neg = str[i] === '0';
6214 i++;
6215 var numAsString = '';
6216 var magAsString = str.substring(i, i + MAGNITUDE_DIGITS);
6217 var magnitude = parseInt(magAsString, 10) + MIN_MAGNITUDE;
6218 /* istanbul ignore next */
6219 if (neg) {
6220 magnitude = -magnitude;
6221 }
6222 i += MAGNITUDE_DIGITS;
6223 while (true) {
6224 var ch = str[i];
6225 if (ch === '\u0000') {
6226 break;
6227 } else {
6228 numAsString += ch;
6229 }
6230 i++;
6231 }
6232 numAsString = numAsString.split('.');
6233 if (numAsString.length === 1) {
6234 num = parseInt(numAsString, 10);
6235 } else {
6236 /* istanbul ignore next */
6237 num = parseFloat(numAsString[0] + '.' + numAsString[1]);
6238 }
6239 /* istanbul ignore next */
6240 if (neg) {
6241 num = num - 10;
6242 }
6243 /* istanbul ignore next */
6244 if (magnitude !== 0) {
6245 // parseFloat is more reliable than pow due to rounding errors
6246 // e.g. Number.MAX_VALUE would return Infinity if we did
6247 // num * Math.pow(10, magnitude);
6248 num = parseFloat(num + 'e' + magnitude);
6249 }
6250 }
6251 return {num: num, length : i - originalIdx};
6252}
6253
6254// move up the stack while parsing
6255// this function moved outside of parseIndexableString for performance
6256function pop(stack, metaStack) {
6257 var obj = stack.pop();
6258
6259 if (metaStack.length) {
6260 var lastMetaElement = metaStack[metaStack.length - 1];
6261 if (obj === lastMetaElement.element) {
6262 // popping a meta-element, e.g. an object whose value is another object
6263 metaStack.pop();
6264 lastMetaElement = metaStack[metaStack.length - 1];
6265 }
6266 var element = lastMetaElement.element;
6267 var lastElementIndex = lastMetaElement.index;
6268 if (Array.isArray(element)) {
6269 element.push(obj);
6270 } else if (lastElementIndex === stack.length - 2) { // obj with key+value
6271 var key = stack.pop();
6272 element[key] = obj;
6273 } else {
6274 stack.push(obj); // obj with key only
6275 }
6276 }
6277}
6278
6279function parseIndexableString(str) {
6280 var stack = [];
6281 var metaStack = []; // stack for arrays and objects
6282 var i = 0;
6283
6284 /*eslint no-constant-condition: ["error", { "checkLoops": false }]*/
6285 while (true) {
6286 var collationIndex = str[i++];
6287 if (collationIndex === '\u0000') {
6288 if (stack.length === 1) {
6289 return stack.pop();
6290 } else {
6291 pop(stack, metaStack);
6292 continue;
6293 }
6294 }
6295 switch (collationIndex) {
6296 case '1':
6297 stack.push(null);
6298 break;
6299 case '2':
6300 stack.push(str[i] === '1');
6301 i++;
6302 break;
6303 case '3':
6304 var parsedNum = parseNumber(str, i);
6305 stack.push(parsedNum.num);
6306 i += parsedNum.length;
6307 break;
6308 case '4':
6309 var parsedStr = '';
6310 /*eslint no-constant-condition: ["error", { "checkLoops": false }]*/
6311 while (true) {
6312 var ch = str[i];
6313 if (ch === '\u0000') {
6314 break;
6315 }
6316 parsedStr += ch;
6317 i++;
6318 }
6319 // perform the reverse of the order-preserving replacement
6320 // algorithm (see above)
6321 /* eslint-disable no-control-regex */
6322 parsedStr = parsedStr.replace(/\u0001\u0001/g, '\u0000')
6323 .replace(/\u0001\u0002/g, '\u0001')
6324 .replace(/\u0002\u0002/g, '\u0002');
6325 /* eslint-enable no-control-regex */
6326 stack.push(parsedStr);
6327 break;
6328 case '5':
6329 var arrayElement = { element: [], index: stack.length };
6330 stack.push(arrayElement.element);
6331 metaStack.push(arrayElement);
6332 break;
6333 case '6':
6334 var objElement = { element: {}, index: stack.length };
6335 stack.push(objElement.element);
6336 metaStack.push(objElement);
6337 break;
6338 /* istanbul ignore next */
6339 default:
6340 throw new Error(
6341 'bad collationIndex or unexpectedly reached end of input: ' +
6342 collationIndex);
6343 }
6344 }
6345}
6346
6347function arrayCollate(a, b) {
6348 var len = Math.min(a.length, b.length);
6349 for (var i = 0; i < len; i++) {
6350 var sort = collate(a[i], b[i]);
6351 if (sort !== 0) {
6352 return sort;
6353 }
6354 }
6355 return (a.length === b.length) ? 0 :
6356 (a.length > b.length) ? 1 : -1;
6357}
6358function stringCollate(a, b) {
6359 // See: https://github.com/daleharvey/pouchdb/issues/40
6360 // This is incompatible with the CouchDB implementation, but its the
6361 // best we can do for now
6362 return (a === b) ? 0 : ((a > b) ? 1 : -1);
6363}
6364function objectCollate(a, b) {
6365 var ak = Object.keys(a), bk = Object.keys(b);
6366 var len = Math.min(ak.length, bk.length);
6367 for (var i = 0; i < len; i++) {
6368 // First sort the keys
6369 var sort = collate(ak[i], bk[i]);
6370 if (sort !== 0) {
6371 return sort;
6372 }
6373 // if the keys are equal sort the values
6374 sort = collate(a[ak[i]], b[bk[i]]);
6375 if (sort !== 0) {
6376 return sort;
6377 }
6378
6379 }
6380 return (ak.length === bk.length) ? 0 :
6381 (ak.length > bk.length) ? 1 : -1;
6382}
6383// The collation is defined by erlangs ordered terms
6384// the atoms null, true, false come first, then numbers, strings,
6385// arrays, then objects
6386// null/undefined/NaN/Infinity/-Infinity are all considered null
6387function collationIndex(x) {
6388 var id = ['boolean', 'number', 'string', 'object'];
6389 var idx = id.indexOf(typeof x);
6390 //false if -1 otherwise true, but fast!!!!1
6391 if (~idx) {
6392 if (x === null) {
6393 return 1;
6394 }
6395 if (Array.isArray(x)) {
6396 return 5;
6397 }
6398 return idx < 3 ? (idx + 2) : (idx + 3);
6399 }
6400 /* istanbul ignore next */
6401 if (Array.isArray(x)) {
6402 return 5;
6403 }
6404}
6405
6406// conversion:
6407// x yyy zz...zz
6408// x = 0 for negative, 1 for 0, 2 for positive
6409// y = exponent (for negative numbers negated) moved so that it's >= 0
6410// z = mantisse
6411function numToIndexableString(num) {
6412
6413 if (num === 0) {
6414 return '1';
6415 }
6416
6417 // convert number to exponential format for easier and
6418 // more succinct string sorting
6419 var expFormat = num.toExponential().split(/e\+?/);
6420 var magnitude = parseInt(expFormat[1], 10);
6421
6422 var neg = num < 0;
6423
6424 var result = neg ? '0' : '2';
6425
6426 // first sort by magnitude
6427 // it's easier if all magnitudes are positive
6428 var magForComparison = ((neg ? -magnitude : magnitude) - MIN_MAGNITUDE);
6429 var magString = padLeft((magForComparison).toString(), '0', MAGNITUDE_DIGITS);
6430
6431 result += SEP + magString;
6432
6433 // then sort by the factor
6434 var factor = Math.abs(parseFloat(expFormat[0])); // [1..10)
6435 /* istanbul ignore next */
6436 if (neg) { // for negative reverse ordering
6437 factor = 10 - factor;
6438 }
6439
6440 var factorStr = factor.toFixed(20);
6441
6442 // strip zeros from the end
6443 factorStr = factorStr.replace(/\.?0+$/, '');
6444
6445 result += SEP + factorStr;
6446
6447 return result;
6448}
6449
6450// create a comparator based on the sort object
6451function createFieldSorter(sort) {
6452
6453 function getFieldValuesAsArray(doc) {
6454 return sort.map(function (sorting) {
6455 var fieldName = getKey(sorting);
6456 var parsedField = parseField(fieldName);
6457 var docFieldValue = getFieldFromDoc(doc, parsedField);
6458 return docFieldValue;
6459 });
6460 }
6461
6462 return function (aRow, bRow) {
6463 var aFieldValues = getFieldValuesAsArray(aRow.doc);
6464 var bFieldValues = getFieldValuesAsArray(bRow.doc);
6465 var collation = collate(aFieldValues, bFieldValues);
6466 if (collation !== 0) {
6467 return collation;
6468 }
6469 // this is what mango seems to do
6470 return compare$1(aRow.doc._id, bRow.doc._id);
6471 };
6472}
6473
6474function filterInMemoryFields(rows, requestDef, inMemoryFields) {
6475 rows = rows.filter(function (row) {
6476 return rowFilter(row.doc, requestDef.selector, inMemoryFields);
6477 });
6478
6479 if (requestDef.sort) {
6480 // in-memory sort
6481 var fieldSorter = createFieldSorter(requestDef.sort);
6482 rows = rows.sort(fieldSorter);
6483 if (typeof requestDef.sort[0] !== 'string' &&
6484 getValue(requestDef.sort[0]) === 'desc') {
6485 rows = rows.reverse();
6486 }
6487 }
6488
6489 if ('limit' in requestDef || 'skip' in requestDef) {
6490 // have to do the limit in-memory
6491 var skip = requestDef.skip || 0;
6492 var limit = ('limit' in requestDef ? requestDef.limit : rows.length) + skip;
6493 rows = rows.slice(skip, limit);
6494 }
6495 return rows;
6496}
6497
6498function rowFilter(doc, selector, inMemoryFields) {
6499 return inMemoryFields.every(function (field) {
6500 var matcher = selector[field];
6501 var parsedField = parseField(field);
6502 var docFieldValue = getFieldFromDoc(doc, parsedField);
6503 if (isCombinationalField(field)) {
6504 return matchCominationalSelector(field, matcher, doc);
6505 }
6506
6507 return matchSelector(matcher, doc, parsedField, docFieldValue);
6508 });
6509}
6510
6511function matchSelector(matcher, doc, parsedField, docFieldValue) {
6512 if (!matcher) {
6513 // no filtering necessary; this field is just needed for sorting
6514 return true;
6515 }
6516
6517 // is matcher an object, if so continue recursion
6518 if (typeof matcher === 'object') {
6519 return Object.keys(matcher).every(function (maybeUserOperator) {
6520 var userValue = matcher[ maybeUserOperator ];
6521 // explicit operator
6522 if (maybeUserOperator.indexOf("$") === 0) {
6523 return match(maybeUserOperator, doc, userValue, parsedField, docFieldValue);
6524 } else {
6525 var subParsedField = parseField(maybeUserOperator);
6526
6527 if (
6528 docFieldValue === undefined &&
6529 typeof userValue !== "object" &&
6530 subParsedField.length > 0
6531 ) {
6532 // the field does not exist, return or getFieldFromDoc will throw
6533 return false;
6534 }
6535
6536 var subDocFieldValue = getFieldFromDoc(docFieldValue, subParsedField);
6537
6538 if (typeof userValue === "object") {
6539 // field value is an object that might contain more operators
6540 return matchSelector(userValue, doc, parsedField, subDocFieldValue);
6541 }
6542
6543 // implicit operator
6544 return match("$eq", doc, userValue, subParsedField, subDocFieldValue);
6545 }
6546 });
6547 }
6548
6549 // no more depth, No need to recurse further
6550 return matcher === docFieldValue;
6551}
6552
6553function matchCominationalSelector(field, matcher, doc) {
6554
6555 if (field === '$or') {
6556 return matcher.some(function (orMatchers) {
6557 return rowFilter(doc, orMatchers, Object.keys(orMatchers));
6558 });
6559 }
6560
6561 if (field === '$not') {
6562 return !rowFilter(doc, matcher, Object.keys(matcher));
6563 }
6564
6565 //`$nor`
6566 return !matcher.find(function (orMatchers) {
6567 return rowFilter(doc, orMatchers, Object.keys(orMatchers));
6568 });
6569
6570}
6571
6572function match(userOperator, doc, userValue, parsedField, docFieldValue) {
6573 if (!matchers[userOperator]) {
6574 /* istanbul ignore next */
6575 throw new Error('unknown operator "' + userOperator +
6576 '" - should be one of $eq, $lte, $lt, $gt, $gte, $exists, $ne, $in, ' +
6577 '$nin, $size, $mod, $regex, $elemMatch, $type, $allMatch or $all');
6578 }
6579 return matchers[userOperator](doc, userValue, parsedField, docFieldValue);
6580}
6581
6582function fieldExists(docFieldValue) {
6583 return typeof docFieldValue !== 'undefined' && docFieldValue !== null;
6584}
6585
6586function fieldIsNotUndefined(docFieldValue) {
6587 return typeof docFieldValue !== 'undefined';
6588}
6589
6590function modField(docFieldValue, userValue) {
6591 if (typeof docFieldValue !== "number" ||
6592 parseInt(docFieldValue, 10) !== docFieldValue) {
6593 return false;
6594 }
6595
6596 var divisor = userValue[0];
6597 var mod = userValue[1];
6598
6599 return docFieldValue % divisor === mod;
6600}
6601
6602function arrayContainsValue(docFieldValue, userValue) {
6603 return userValue.some(function (val) {
6604 if (docFieldValue instanceof Array) {
6605 return docFieldValue.some(function (docFieldValueItem) {
6606 return collate(val, docFieldValueItem) === 0;
6607 });
6608 }
6609
6610 return collate(val, docFieldValue) === 0;
6611 });
6612}
6613
6614function arrayContainsAllValues(docFieldValue, userValue) {
6615 return userValue.every(function (val) {
6616 return docFieldValue.some(function (docFieldValueItem) {
6617 return collate(val, docFieldValueItem) === 0;
6618 });
6619 });
6620}
6621
6622function arraySize(docFieldValue, userValue) {
6623 return docFieldValue.length === userValue;
6624}
6625
6626function regexMatch(docFieldValue, userValue) {
6627 var re = new RegExp(userValue);
6628
6629 return re.test(docFieldValue);
6630}
6631
6632function typeMatch(docFieldValue, userValue) {
6633
6634 switch (userValue) {
6635 case 'null':
6636 return docFieldValue === null;
6637 case 'boolean':
6638 return typeof (docFieldValue) === 'boolean';
6639 case 'number':
6640 return typeof (docFieldValue) === 'number';
6641 case 'string':
6642 return typeof (docFieldValue) === 'string';
6643 case 'array':
6644 return docFieldValue instanceof Array;
6645 case 'object':
6646 return ({}).toString.call(docFieldValue) === '[object Object]';
6647 }
6648}
6649
6650var matchers = {
6651
6652 '$elemMatch': function (doc, userValue, parsedField, docFieldValue) {
6653 if (!Array.isArray(docFieldValue)) {
6654 return false;
6655 }
6656
6657 if (docFieldValue.length === 0) {
6658 return false;
6659 }
6660
6661 if (typeof docFieldValue[0] === 'object') {
6662 return docFieldValue.some(function (val) {
6663 return rowFilter(val, userValue, Object.keys(userValue));
6664 });
6665 }
6666
6667 return docFieldValue.some(function (val) {
6668 return matchSelector(userValue, doc, parsedField, val);
6669 });
6670 },
6671
6672 '$allMatch': function (doc, userValue, parsedField, docFieldValue) {
6673 if (!Array.isArray(docFieldValue)) {
6674 return false;
6675 }
6676
6677 /* istanbul ignore next */
6678 if (docFieldValue.length === 0) {
6679 return false;
6680 }
6681
6682 if (typeof docFieldValue[0] === 'object') {
6683 return docFieldValue.every(function (val) {
6684 return rowFilter(val, userValue, Object.keys(userValue));
6685 });
6686 }
6687
6688 return docFieldValue.every(function (val) {
6689 return matchSelector(userValue, doc, parsedField, val);
6690 });
6691 },
6692
6693 '$eq': function (doc, userValue, parsedField, docFieldValue) {
6694 return fieldIsNotUndefined(docFieldValue) && collate(docFieldValue, userValue) === 0;
6695 },
6696
6697 '$gte': function (doc, userValue, parsedField, docFieldValue) {
6698 return fieldIsNotUndefined(docFieldValue) && collate(docFieldValue, userValue) >= 0;
6699 },
6700
6701 '$gt': function (doc, userValue, parsedField, docFieldValue) {
6702 return fieldIsNotUndefined(docFieldValue) && collate(docFieldValue, userValue) > 0;
6703 },
6704
6705 '$lte': function (doc, userValue, parsedField, docFieldValue) {
6706 return fieldIsNotUndefined(docFieldValue) && collate(docFieldValue, userValue) <= 0;
6707 },
6708
6709 '$lt': function (doc, userValue, parsedField, docFieldValue) {
6710 return fieldIsNotUndefined(docFieldValue) && collate(docFieldValue, userValue) < 0;
6711 },
6712
6713 '$exists': function (doc, userValue, parsedField, docFieldValue) {
6714 //a field that is null is still considered to exist
6715 if (userValue) {
6716 return fieldIsNotUndefined(docFieldValue);
6717 }
6718
6719 return !fieldIsNotUndefined(docFieldValue);
6720 },
6721
6722 '$mod': function (doc, userValue, parsedField, docFieldValue) {
6723 return fieldExists(docFieldValue) && modField(docFieldValue, userValue);
6724 },
6725
6726 '$ne': function (doc, userValue, parsedField, docFieldValue) {
6727 return userValue.every(function (neValue) {
6728 return collate(docFieldValue, neValue) !== 0;
6729 });
6730 },
6731 '$in': function (doc, userValue, parsedField, docFieldValue) {
6732 return fieldExists(docFieldValue) && arrayContainsValue(docFieldValue, userValue);
6733 },
6734
6735 '$nin': function (doc, userValue, parsedField, docFieldValue) {
6736 return fieldExists(docFieldValue) && !arrayContainsValue(docFieldValue, userValue);
6737 },
6738
6739 '$size': function (doc, userValue, parsedField, docFieldValue) {
6740 return fieldExists(docFieldValue) &&
6741 Array.isArray(docFieldValue) &&
6742 arraySize(docFieldValue, userValue);
6743 },
6744
6745 '$all': function (doc, userValue, parsedField, docFieldValue) {
6746 return Array.isArray(docFieldValue) && arrayContainsAllValues(docFieldValue, userValue);
6747 },
6748
6749 '$regex': function (doc, userValue, parsedField, docFieldValue) {
6750 return fieldExists(docFieldValue) &&
6751 typeof docFieldValue == "string" &&
6752 userValue.every(function (regexValue) {
6753 return regexMatch(docFieldValue, regexValue);
6754 });
6755 },
6756
6757 '$type': function (doc, userValue, parsedField, docFieldValue) {
6758 return typeMatch(docFieldValue, userValue);
6759 }
6760};
6761
6762// return true if the given doc matches the supplied selector
6763function matchesSelector(doc, selector) {
6764 /* istanbul ignore if */
6765 if (typeof selector !== 'object') {
6766 // match the CouchDB error message
6767 throw new Error('Selector error: expected a JSON object');
6768 }
6769
6770 selector = massageSelector(selector);
6771 var row = {
6772 'doc': doc
6773 };
6774
6775 var rowsMatched = filterInMemoryFields([row], { 'selector': selector }, Object.keys(selector));
6776 return rowsMatched && rowsMatched.length === 1;
6777}
6778
6779function evalFilter(input) {
6780 return scopeEval('"use strict";\nreturn ' + input + ';', {});
6781}
6782
6783function evalView(input) {
6784 var code = [
6785 'return function(doc) {',
6786 ' "use strict";',
6787 ' var emitted = false;',
6788 ' var emit = function (a, b) {',
6789 ' emitted = true;',
6790 ' };',
6791 ' var view = ' + input + ';',
6792 ' view(doc);',
6793 ' if (emitted) {',
6794 ' return true;',
6795 ' }',
6796 '};'
6797 ].join('\n');
6798
6799 return scopeEval(code, {});
6800}
6801
6802function validate(opts, callback) {
6803 if (opts.selector) {
6804 if (opts.filter && opts.filter !== '_selector') {
6805 var filterName = typeof opts.filter === 'string' ?
6806 opts.filter : 'function';
6807 return callback(new Error('selector invalid for filter "' + filterName + '"'));
6808 }
6809 }
6810 callback();
6811}
6812
6813function normalize(opts) {
6814 if (opts.view && !opts.filter) {
6815 opts.filter = '_view';
6816 }
6817
6818 if (opts.selector && !opts.filter) {
6819 opts.filter = '_selector';
6820 }
6821
6822 if (opts.filter && typeof opts.filter === 'string') {
6823 if (opts.filter === '_view') {
6824 opts.view = normalizeDesignDocFunctionName(opts.view);
6825 } else {
6826 opts.filter = normalizeDesignDocFunctionName(opts.filter);
6827 }
6828 }
6829}
6830
6831function shouldFilter(changesHandler, opts) {
6832 return opts.filter && typeof opts.filter === 'string' &&
6833 !opts.doc_ids && !isRemote(changesHandler.db);
6834}
6835
6836function filter(changesHandler, opts) {
6837 var callback = opts.complete;
6838 if (opts.filter === '_view') {
6839 if (!opts.view || typeof opts.view !== 'string') {
6840 var err = createError(BAD_REQUEST,
6841 '`view` filter parameter not found or invalid.');
6842 return callback(err);
6843 }
6844 // fetch a view from a design doc, make it behave like a filter
6845 var viewName = parseDesignDocFunctionName(opts.view);
6846 changesHandler.db.get('_design/' + viewName[0], function (err, ddoc) {
6847 /* istanbul ignore if */
6848 if (changesHandler.isCancelled) {
6849 return callback(null, {status: 'cancelled'});
6850 }
6851 /* istanbul ignore next */
6852 if (err) {
6853 return callback(generateErrorFromResponse(err));
6854 }
6855 var mapFun = ddoc && ddoc.views && ddoc.views[viewName[1]] &&
6856 ddoc.views[viewName[1]].map;
6857 if (!mapFun) {
6858 return callback(createError(MISSING_DOC,
6859 (ddoc.views ? 'missing json key: ' + viewName[1] :
6860 'missing json key: views')));
6861 }
6862 opts.filter = evalView(mapFun);
6863 changesHandler.doChanges(opts);
6864 });
6865 } else if (opts.selector) {
6866 opts.filter = function (doc) {
6867 return matchesSelector(doc, opts.selector);
6868 };
6869 changesHandler.doChanges(opts);
6870 } else {
6871 // fetch a filter from a design doc
6872 var filterName = parseDesignDocFunctionName(opts.filter);
6873 changesHandler.db.get('_design/' + filterName[0], function (err, ddoc) {
6874 /* istanbul ignore if */
6875 if (changesHandler.isCancelled) {
6876 return callback(null, {status: 'cancelled'});
6877 }
6878 /* istanbul ignore next */
6879 if (err) {
6880 return callback(generateErrorFromResponse(err));
6881 }
6882 var filterFun = ddoc && ddoc.filters && ddoc.filters[filterName[1]];
6883 if (!filterFun) {
6884 return callback(createError(MISSING_DOC,
6885 ((ddoc && ddoc.filters) ? 'missing json key: ' + filterName[1]
6886 : 'missing json key: filters')));
6887 }
6888 opts.filter = evalFilter(filterFun);
6889 changesHandler.doChanges(opts);
6890 });
6891 }
6892}
6893
6894function applyChangesFilterPlugin(PouchDB) {
6895 PouchDB._changesFilterPlugin = {
6896 validate: validate,
6897 normalize: normalize,
6898 shouldFilter: shouldFilter,
6899 filter: filter
6900 };
6901}
6902
6903// TODO: remove from pouchdb-core (breaking)
6904PouchDB.plugin(applyChangesFilterPlugin);
6905
6906PouchDB.version = version;
6907
6908function toObject(array) {
6909 return array.reduce(function (obj, item) {
6910 obj[item] = true;
6911 return obj;
6912 }, {});
6913}
6914// List of top level reserved words for doc
6915var reservedWords = toObject([
6916 '_id',
6917 '_rev',
6918 '_access',
6919 '_attachments',
6920 '_deleted',
6921 '_revisions',
6922 '_revs_info',
6923 '_conflicts',
6924 '_deleted_conflicts',
6925 '_local_seq',
6926 '_rev_tree',
6927 // replication documents
6928 '_replication_id',
6929 '_replication_state',
6930 '_replication_state_time',
6931 '_replication_state_reason',
6932 '_replication_stats',
6933 // Specific to Couchbase Sync Gateway
6934 '_removed'
6935]);
6936
6937// List of reserved words that should end up in the document
6938var dataWords = toObject([
6939 '_access',
6940 '_attachments',
6941 // replication documents
6942 '_replication_id',
6943 '_replication_state',
6944 '_replication_state_time',
6945 '_replication_state_reason',
6946 '_replication_stats'
6947]);
6948
6949function parseRevisionInfo(rev) {
6950 if (!/^\d+-/.test(rev)) {
6951 return createError(INVALID_REV);
6952 }
6953 var idx = rev.indexOf('-');
6954 var left = rev.substring(0, idx);
6955 var right = rev.substring(idx + 1);
6956 return {
6957 prefix: parseInt(left, 10),
6958 id: right
6959 };
6960}
6961
6962function makeRevTreeFromRevisions(revisions, opts) {
6963 var pos = revisions.start - revisions.ids.length + 1;
6964
6965 var revisionIds = revisions.ids;
6966 var ids = [revisionIds[0], opts, []];
6967
6968 for (var i = 1, len = revisionIds.length; i < len; i++) {
6969 ids = [revisionIds[i], {status: 'missing'}, [ids]];
6970 }
6971
6972 return [{
6973 pos: pos,
6974 ids: ids
6975 }];
6976}
6977
6978// Preprocess documents, parse their revisions, assign an id and a
6979// revision for new writes that are missing them, etc
6980function parseDoc(doc, newEdits, dbOpts) {
6981 if (!dbOpts) {
6982 dbOpts = {
6983 deterministic_revs: true
6984 };
6985 }
6986
6987 var nRevNum;
6988 var newRevId;
6989 var revInfo;
6990 var opts = {status: 'available'};
6991 if (doc._deleted) {
6992 opts.deleted = true;
6993 }
6994
6995 if (newEdits) {
6996 if (!doc._id) {
6997 doc._id = uuid$1();
6998 }
6999 newRevId = rev$$1(doc, dbOpts.deterministic_revs);
7000 if (doc._rev) {
7001 revInfo = parseRevisionInfo(doc._rev);
7002 if (revInfo.error) {
7003 return revInfo;
7004 }
7005 doc._rev_tree = [{
7006 pos: revInfo.prefix,
7007 ids: [revInfo.id, {status: 'missing'}, [[newRevId, opts, []]]]
7008 }];
7009 nRevNum = revInfo.prefix + 1;
7010 } else {
7011 doc._rev_tree = [{
7012 pos: 1,
7013 ids : [newRevId, opts, []]
7014 }];
7015 nRevNum = 1;
7016 }
7017 } else {
7018 if (doc._revisions) {
7019 doc._rev_tree = makeRevTreeFromRevisions(doc._revisions, opts);
7020 nRevNum = doc._revisions.start;
7021 newRevId = doc._revisions.ids[0];
7022 }
7023 if (!doc._rev_tree) {
7024 revInfo = parseRevisionInfo(doc._rev);
7025 if (revInfo.error) {
7026 return revInfo;
7027 }
7028 nRevNum = revInfo.prefix;
7029 newRevId = revInfo.id;
7030 doc._rev_tree = [{
7031 pos: nRevNum,
7032 ids: [newRevId, opts, []]
7033 }];
7034 }
7035 }
7036
7037 invalidIdError(doc._id);
7038
7039 doc._rev = nRevNum + '-' + newRevId;
7040
7041 var result = {metadata : {}, data : {}};
7042 for (var key in doc) {
7043 /* istanbul ignore else */
7044 if (Object.prototype.hasOwnProperty.call(doc, key)) {
7045 var specialKey = key[0] === '_';
7046 if (specialKey && !reservedWords[key]) {
7047 var error = createError(DOC_VALIDATION, key);
7048 error.message = DOC_VALIDATION.message + ': ' + key;
7049 throw error;
7050 } else if (specialKey && !dataWords[key]) {
7051 result.metadata[key.slice(1)] = doc[key];
7052 } else {
7053 result.data[key] = doc[key];
7054 }
7055 }
7056 }
7057 return result;
7058}
7059
7060function parseBase64(data) {
7061 try {
7062 return thisAtob(data);
7063 } catch (e) {
7064 var err = createError(BAD_ARG,
7065 'Attachment is not a valid base64 string');
7066 return {error: err};
7067 }
7068}
7069
7070function preprocessString(att, blobType, callback) {
7071 var asBinary = parseBase64(att.data);
7072 if (asBinary.error) {
7073 return callback(asBinary.error);
7074 }
7075
7076 att.length = asBinary.length;
7077 if (blobType === 'blob') {
7078 att.data = binStringToBluffer(asBinary, att.content_type);
7079 } else if (blobType === 'base64') {
7080 att.data = thisBtoa(asBinary);
7081 } else { // binary
7082 att.data = asBinary;
7083 }
7084 binaryMd5(asBinary, function (result) {
7085 att.digest = 'md5-' + result;
7086 callback();
7087 });
7088}
7089
7090function preprocessBlob(att, blobType, callback) {
7091 binaryMd5(att.data, function (md5) {
7092 att.digest = 'md5-' + md5;
7093 // size is for blobs (browser), length is for buffers (node)
7094 att.length = att.data.size || att.data.length || 0;
7095 if (blobType === 'binary') {
7096 blobToBinaryString(att.data, function (binString) {
7097 att.data = binString;
7098 callback();
7099 });
7100 } else if (blobType === 'base64') {
7101 blobToBase64(att.data, function (b64) {
7102 att.data = b64;
7103 callback();
7104 });
7105 } else {
7106 callback();
7107 }
7108 });
7109}
7110
7111function preprocessAttachment(att, blobType, callback) {
7112 if (att.stub) {
7113 return callback();
7114 }
7115 if (typeof att.data === 'string') { // input is a base64 string
7116 preprocessString(att, blobType, callback);
7117 } else { // input is a blob
7118 preprocessBlob(att, blobType, callback);
7119 }
7120}
7121
7122function preprocessAttachments(docInfos, blobType, callback) {
7123
7124 if (!docInfos.length) {
7125 return callback();
7126 }
7127
7128 var docv = 0;
7129 var overallErr;
7130
7131 docInfos.forEach(function (docInfo) {
7132 var attachments = docInfo.data && docInfo.data._attachments ?
7133 Object.keys(docInfo.data._attachments) : [];
7134 var recv = 0;
7135
7136 if (!attachments.length) {
7137 return done();
7138 }
7139
7140 function processedAttachment(err) {
7141 overallErr = err;
7142 recv++;
7143 if (recv === attachments.length) {
7144 done();
7145 }
7146 }
7147
7148 for (var key in docInfo.data._attachments) {
7149 if (Object.prototype.hasOwnProperty.call(docInfo.data._attachments, key)) {
7150 preprocessAttachment(docInfo.data._attachments[key],
7151 blobType, processedAttachment);
7152 }
7153 }
7154 });
7155
7156 function done() {
7157 docv++;
7158 if (docInfos.length === docv) {
7159 if (overallErr) {
7160 callback(overallErr);
7161 } else {
7162 callback();
7163 }
7164 }
7165 }
7166}
7167
7168function updateDoc(revLimit, prev, docInfo, results,
7169 i, cb, writeDoc, newEdits) {
7170
7171 if (revExists(prev.rev_tree, docInfo.metadata.rev) && !newEdits) {
7172 results[i] = docInfo;
7173 return cb();
7174 }
7175
7176 // sometimes this is pre-calculated. historically not always
7177 var previousWinningRev = prev.winningRev || winningRev(prev);
7178 var previouslyDeleted = 'deleted' in prev ? prev.deleted :
7179 isDeleted(prev, previousWinningRev);
7180 var deleted = 'deleted' in docInfo.metadata ? docInfo.metadata.deleted :
7181 isDeleted(docInfo.metadata);
7182 var isRoot = /^1-/.test(docInfo.metadata.rev);
7183
7184 if (previouslyDeleted && !deleted && newEdits && isRoot) {
7185 var newDoc = docInfo.data;
7186 newDoc._rev = previousWinningRev;
7187 newDoc._id = docInfo.metadata.id;
7188 docInfo = parseDoc(newDoc, newEdits);
7189 }
7190
7191 var merged = merge(prev.rev_tree, docInfo.metadata.rev_tree[0], revLimit);
7192
7193 var inConflict = newEdits && ((
7194 (previouslyDeleted && deleted && merged.conflicts !== 'new_leaf') ||
7195 (!previouslyDeleted && merged.conflicts !== 'new_leaf') ||
7196 (previouslyDeleted && !deleted && merged.conflicts === 'new_branch')));
7197
7198 if (inConflict) {
7199 var err = createError(REV_CONFLICT);
7200 results[i] = err;
7201 return cb();
7202 }
7203
7204 var newRev = docInfo.metadata.rev;
7205 docInfo.metadata.rev_tree = merged.tree;
7206 docInfo.stemmedRevs = merged.stemmedRevs || [];
7207 /* istanbul ignore else */
7208 if (prev.rev_map) {
7209 docInfo.metadata.rev_map = prev.rev_map; // used only by leveldb
7210 }
7211
7212 // recalculate
7213 var winningRev$$1 = winningRev(docInfo.metadata);
7214 var winningRevIsDeleted = isDeleted(docInfo.metadata, winningRev$$1);
7215
7216 // calculate the total number of documents that were added/removed,
7217 // from the perspective of total_rows/doc_count
7218 var delta = (previouslyDeleted === winningRevIsDeleted) ? 0 :
7219 previouslyDeleted < winningRevIsDeleted ? -1 : 1;
7220
7221 var newRevIsDeleted;
7222 if (newRev === winningRev$$1) {
7223 // if the new rev is the same as the winning rev, we can reuse that value
7224 newRevIsDeleted = winningRevIsDeleted;
7225 } else {
7226 // if they're not the same, then we need to recalculate
7227 newRevIsDeleted = isDeleted(docInfo.metadata, newRev);
7228 }
7229
7230 writeDoc(docInfo, winningRev$$1, winningRevIsDeleted, newRevIsDeleted,
7231 true, delta, i, cb);
7232}
7233
7234function rootIsMissing(docInfo) {
7235 return docInfo.metadata.rev_tree[0].ids[1].status === 'missing';
7236}
7237
7238function processDocs(revLimit, docInfos, api, fetchedDocs, tx, results,
7239 writeDoc, opts, overallCallback) {
7240
7241 // Default to 1000 locally
7242 revLimit = revLimit || 1000;
7243
7244 function insertDoc(docInfo, resultsIdx, callback) {
7245 // Cant insert new deleted documents
7246 var winningRev$$1 = winningRev(docInfo.metadata);
7247 var deleted = isDeleted(docInfo.metadata, winningRev$$1);
7248 if ('was_delete' in opts && deleted) {
7249 results[resultsIdx] = createError(MISSING_DOC, 'deleted');
7250 return callback();
7251 }
7252
7253 // 4712 - detect whether a new document was inserted with a _rev
7254 var inConflict = newEdits && rootIsMissing(docInfo);
7255
7256 if (inConflict) {
7257 var err = createError(REV_CONFLICT);
7258 results[resultsIdx] = err;
7259 return callback();
7260 }
7261
7262 var delta = deleted ? 0 : 1;
7263
7264 writeDoc(docInfo, winningRev$$1, deleted, deleted, false,
7265 delta, resultsIdx, callback);
7266 }
7267
7268 var newEdits = opts.new_edits;
7269 var idsToDocs = new ExportedMap();
7270
7271 var docsDone = 0;
7272 var docsToDo = docInfos.length;
7273
7274 function checkAllDocsDone() {
7275 if (++docsDone === docsToDo && overallCallback) {
7276 overallCallback();
7277 }
7278 }
7279
7280 docInfos.forEach(function (currentDoc, resultsIdx) {
7281
7282 if (currentDoc._id && isLocalId(currentDoc._id)) {
7283 var fun = currentDoc._deleted ? '_removeLocal' : '_putLocal';
7284 api[fun](currentDoc, {ctx: tx}, function (err, res) {
7285 results[resultsIdx] = err || res;
7286 checkAllDocsDone();
7287 });
7288 return;
7289 }
7290
7291 var id = currentDoc.metadata.id;
7292 if (idsToDocs.has(id)) {
7293 docsToDo--; // duplicate
7294 idsToDocs.get(id).push([currentDoc, resultsIdx]);
7295 } else {
7296 idsToDocs.set(id, [[currentDoc, resultsIdx]]);
7297 }
7298 });
7299
7300 // in the case of new_edits, the user can provide multiple docs
7301 // with the same id. these need to be processed sequentially
7302 idsToDocs.forEach(function (docs, id) {
7303 var numDone = 0;
7304
7305 function docWritten() {
7306 if (++numDone < docs.length) {
7307 nextDoc();
7308 } else {
7309 checkAllDocsDone();
7310 }
7311 }
7312 function nextDoc() {
7313 var value = docs[numDone];
7314 var currentDoc = value[0];
7315 var resultsIdx = value[1];
7316
7317 if (fetchedDocs.has(id)) {
7318 updateDoc(revLimit, fetchedDocs.get(id), currentDoc, results,
7319 resultsIdx, docWritten, writeDoc, newEdits);
7320 } else {
7321 // Ensure stemming applies to new writes as well
7322 var merged = merge([], currentDoc.metadata.rev_tree[0], revLimit);
7323 currentDoc.metadata.rev_tree = merged.tree;
7324 currentDoc.stemmedRevs = merged.stemmedRevs || [];
7325 insertDoc(currentDoc, resultsIdx, docWritten);
7326 }
7327 }
7328 nextDoc();
7329 });
7330}
7331
7332// IndexedDB requires a versioned database structure, so we use the
7333// version here to manage migrations.
7334var ADAPTER_VERSION = 5;
7335
7336// The object stores created for each database
7337// DOC_STORE stores the document meta data, its revision history and state
7338// Keyed by document id
7339var DOC_STORE = 'document-store';
7340// BY_SEQ_STORE stores a particular version of a document, keyed by its
7341// sequence id
7342var BY_SEQ_STORE = 'by-sequence';
7343// Where we store attachments
7344var ATTACH_STORE = 'attach-store';
7345// Where we store many-to-many relations
7346// between attachment digests and seqs
7347var ATTACH_AND_SEQ_STORE = 'attach-seq-store';
7348
7349// Where we store database-wide meta data in a single record
7350// keyed by id: META_STORE
7351var META_STORE = 'meta-store';
7352// Where we store local documents
7353var LOCAL_STORE = 'local-store';
7354// Where we detect blob support
7355var DETECT_BLOB_SUPPORT_STORE = 'detect-blob-support';
7356
7357function safeJsonParse(str) {
7358 // This try/catch guards against stack overflow errors.
7359 // JSON.parse() is faster than vuvuzela.parse() but vuvuzela
7360 // cannot overflow.
7361 try {
7362 return JSON.parse(str);
7363 } catch (e) {
7364 /* istanbul ignore next */
7365 return vuvuzela.parse(str);
7366 }
7367}
7368
7369function safeJsonStringify(json) {
7370 try {
7371 return JSON.stringify(json);
7372 } catch (e) {
7373 /* istanbul ignore next */
7374 return vuvuzela.stringify(json);
7375 }
7376}
7377
7378function idbError(callback) {
7379 return function (evt) {
7380 var message = 'unknown_error';
7381 if (evt.target && evt.target.error) {
7382 message = evt.target.error.name || evt.target.error.message;
7383 }
7384 callback(createError(IDB_ERROR, message, evt.type));
7385 };
7386}
7387
7388// Unfortunately, the metadata has to be stringified
7389// when it is put into the database, because otherwise
7390// IndexedDB can throw errors for deeply-nested objects.
7391// Originally we just used JSON.parse/JSON.stringify; now
7392// we use this custom vuvuzela library that avoids recursion.
7393// If we could do it all over again, we'd probably use a
7394// format for the revision trees other than JSON.
7395function encodeMetadata(metadata, winningRev, deleted) {
7396 return {
7397 data: safeJsonStringify(metadata),
7398 winningRev: winningRev,
7399 deletedOrLocal: deleted ? '1' : '0',
7400 seq: metadata.seq, // highest seq for this doc
7401 id: metadata.id
7402 };
7403}
7404
7405function decodeMetadata(storedObject) {
7406 if (!storedObject) {
7407 return null;
7408 }
7409 var metadata = safeJsonParse(storedObject.data);
7410 metadata.winningRev = storedObject.winningRev;
7411 metadata.deleted = storedObject.deletedOrLocal === '1';
7412 metadata.seq = storedObject.seq;
7413 return metadata;
7414}
7415
7416// read the doc back out from the database. we don't store the
7417// _id or _rev because we already have _doc_id_rev.
7418function decodeDoc(doc) {
7419 if (!doc) {
7420 return doc;
7421 }
7422 var idx = doc._doc_id_rev.lastIndexOf(':');
7423 doc._id = doc._doc_id_rev.substring(0, idx - 1);
7424 doc._rev = doc._doc_id_rev.substring(idx + 1);
7425 delete doc._doc_id_rev;
7426 return doc;
7427}
7428
7429// Read a blob from the database, encoding as necessary
7430// and translating from base64 if the IDB doesn't support
7431// native Blobs
7432function readBlobData(body, type, asBlob, callback) {
7433 if (asBlob) {
7434 if (!body) {
7435 callback(createBlob([''], {type: type}));
7436 } else if (typeof body !== 'string') { // we have blob support
7437 callback(body);
7438 } else { // no blob support
7439 callback(b64ToBluffer(body, type));
7440 }
7441 } else { // as base64 string
7442 if (!body) {
7443 callback('');
7444 } else if (typeof body !== 'string') { // we have blob support
7445 readAsBinaryString(body, function (binary) {
7446 callback(thisBtoa(binary));
7447 });
7448 } else { // no blob support
7449 callback(body);
7450 }
7451 }
7452}
7453
7454function fetchAttachmentsIfNecessary(doc, opts, txn, cb) {
7455 var attachments = Object.keys(doc._attachments || {});
7456 if (!attachments.length) {
7457 return cb && cb();
7458 }
7459 var numDone = 0;
7460
7461 function checkDone() {
7462 if (++numDone === attachments.length && cb) {
7463 cb();
7464 }
7465 }
7466
7467 function fetchAttachment(doc, att) {
7468 var attObj = doc._attachments[att];
7469 var digest = attObj.digest;
7470 var req = txn.objectStore(ATTACH_STORE).get(digest);
7471 req.onsuccess = function (e) {
7472 attObj.body = e.target.result.body;
7473 checkDone();
7474 };
7475 }
7476
7477 attachments.forEach(function (att) {
7478 if (opts.attachments && opts.include_docs) {
7479 fetchAttachment(doc, att);
7480 } else {
7481 doc._attachments[att].stub = true;
7482 checkDone();
7483 }
7484 });
7485}
7486
7487// IDB-specific postprocessing necessary because
7488// we don't know whether we stored a true Blob or
7489// a base64-encoded string, and if it's a Blob it
7490// needs to be read outside of the transaction context
7491function postProcessAttachments(results, asBlob) {
7492 return Promise.all(results.map(function (row) {
7493 if (row.doc && row.doc._attachments) {
7494 var attNames = Object.keys(row.doc._attachments);
7495 return Promise.all(attNames.map(function (att) {
7496 var attObj = row.doc._attachments[att];
7497 if (!('body' in attObj)) { // already processed
7498 return;
7499 }
7500 var body = attObj.body;
7501 var type = attObj.content_type;
7502 return new Promise(function (resolve) {
7503 readBlobData(body, type, asBlob, function (data) {
7504 row.doc._attachments[att] = $inject_Object_assign(
7505 pick(attObj, ['digest', 'content_type']),
7506 {data: data}
7507 );
7508 resolve();
7509 });
7510 });
7511 }));
7512 }
7513 }));
7514}
7515
7516function compactRevs(revs, docId, txn) {
7517
7518 var possiblyOrphanedDigests = [];
7519 var seqStore = txn.objectStore(BY_SEQ_STORE);
7520 var attStore = txn.objectStore(ATTACH_STORE);
7521 var attAndSeqStore = txn.objectStore(ATTACH_AND_SEQ_STORE);
7522 var count = revs.length;
7523
7524 function checkDone() {
7525 count--;
7526 if (!count) { // done processing all revs
7527 deleteOrphanedAttachments();
7528 }
7529 }
7530
7531 function deleteOrphanedAttachments() {
7532 if (!possiblyOrphanedDigests.length) {
7533 return;
7534 }
7535 possiblyOrphanedDigests.forEach(function (digest) {
7536 var countReq = attAndSeqStore.index('digestSeq').count(
7537 IDBKeyRange.bound(
7538 digest + '::', digest + '::\uffff', false, false));
7539 countReq.onsuccess = function (e) {
7540 var count = e.target.result;
7541 if (!count) {
7542 // orphaned
7543 attStore["delete"](digest);
7544 }
7545 };
7546 });
7547 }
7548
7549 revs.forEach(function (rev) {
7550 var index = seqStore.index('_doc_id_rev');
7551 var key = docId + "::" + rev;
7552 index.getKey(key).onsuccess = function (e) {
7553 var seq = e.target.result;
7554 if (typeof seq !== 'number') {
7555 return checkDone();
7556 }
7557 seqStore["delete"](seq);
7558
7559 var cursor = attAndSeqStore.index('seq')
7560 .openCursor(IDBKeyRange.only(seq));
7561
7562 cursor.onsuccess = function (event) {
7563 var cursor = event.target.result;
7564 if (cursor) {
7565 var digest = cursor.value.digestSeq.split('::')[0];
7566 possiblyOrphanedDigests.push(digest);
7567 attAndSeqStore["delete"](cursor.primaryKey);
7568 cursor["continue"]();
7569 } else { // done
7570 checkDone();
7571 }
7572 };
7573 };
7574 });
7575}
7576
7577function openTransactionSafely(idb, stores, mode) {
7578 try {
7579 return {
7580 txn: idb.transaction(stores, mode)
7581 };
7582 } catch (err) {
7583 return {
7584 error: err
7585 };
7586 }
7587}
7588
7589var changesHandler = new Changes();
7590
7591function idbBulkDocs(dbOpts, req, opts, api, idb, callback) {
7592 var docInfos = req.docs;
7593 var txn;
7594 var docStore;
7595 var bySeqStore;
7596 var attachStore;
7597 var attachAndSeqStore;
7598 var metaStore;
7599 var docInfoError;
7600 var metaDoc;
7601
7602 for (var i = 0, len = docInfos.length; i < len; i++) {
7603 var doc = docInfos[i];
7604 if (doc._id && isLocalId(doc._id)) {
7605 continue;
7606 }
7607 doc = docInfos[i] = parseDoc(doc, opts.new_edits, dbOpts);
7608 if (doc.error && !docInfoError) {
7609 docInfoError = doc;
7610 }
7611 }
7612
7613 if (docInfoError) {
7614 return callback(docInfoError);
7615 }
7616
7617 var allDocsProcessed = false;
7618 var docCountDelta = 0;
7619 var results = new Array(docInfos.length);
7620 var fetchedDocs = new ExportedMap();
7621 var preconditionErrored = false;
7622 var blobType = api._meta.blobSupport ? 'blob' : 'base64';
7623
7624 preprocessAttachments(docInfos, blobType, function (err) {
7625 if (err) {
7626 return callback(err);
7627 }
7628 startTransaction();
7629 });
7630
7631 function startTransaction() {
7632
7633 var stores = [
7634 DOC_STORE, BY_SEQ_STORE,
7635 ATTACH_STORE,
7636 LOCAL_STORE, ATTACH_AND_SEQ_STORE,
7637 META_STORE
7638 ];
7639 var txnResult = openTransactionSafely(idb, stores, 'readwrite');
7640 if (txnResult.error) {
7641 return callback(txnResult.error);
7642 }
7643 txn = txnResult.txn;
7644 txn.onabort = idbError(callback);
7645 txn.ontimeout = idbError(callback);
7646 txn.oncomplete = complete;
7647 docStore = txn.objectStore(DOC_STORE);
7648 bySeqStore = txn.objectStore(BY_SEQ_STORE);
7649 attachStore = txn.objectStore(ATTACH_STORE);
7650 attachAndSeqStore = txn.objectStore(ATTACH_AND_SEQ_STORE);
7651 metaStore = txn.objectStore(META_STORE);
7652
7653 metaStore.get(META_STORE).onsuccess = function (e) {
7654 metaDoc = e.target.result;
7655 updateDocCountIfReady();
7656 };
7657
7658 verifyAttachments(function (err) {
7659 if (err) {
7660 preconditionErrored = true;
7661 return callback(err);
7662 }
7663 fetchExistingDocs();
7664 });
7665 }
7666
7667 function onAllDocsProcessed() {
7668 allDocsProcessed = true;
7669 updateDocCountIfReady();
7670 }
7671
7672 function idbProcessDocs() {
7673 processDocs(dbOpts.revs_limit, docInfos, api, fetchedDocs,
7674 txn, results, writeDoc, opts, onAllDocsProcessed);
7675 }
7676
7677 function updateDocCountIfReady() {
7678 if (!metaDoc || !allDocsProcessed) {
7679 return;
7680 }
7681 // caching the docCount saves a lot of time in allDocs() and
7682 // info(), which is why we go to all the trouble of doing this
7683 metaDoc.docCount += docCountDelta;
7684 metaStore.put(metaDoc);
7685 }
7686
7687 function fetchExistingDocs() {
7688
7689 if (!docInfos.length) {
7690 return;
7691 }
7692
7693 var numFetched = 0;
7694
7695 function checkDone() {
7696 if (++numFetched === docInfos.length) {
7697 idbProcessDocs();
7698 }
7699 }
7700
7701 function readMetadata(event) {
7702 var metadata = decodeMetadata(event.target.result);
7703
7704 if (metadata) {
7705 fetchedDocs.set(metadata.id, metadata);
7706 }
7707 checkDone();
7708 }
7709
7710 for (var i = 0, len = docInfos.length; i < len; i++) {
7711 var docInfo = docInfos[i];
7712 if (docInfo._id && isLocalId(docInfo._id)) {
7713 checkDone(); // skip local docs
7714 continue;
7715 }
7716 var req = docStore.get(docInfo.metadata.id);
7717 req.onsuccess = readMetadata;
7718 }
7719 }
7720
7721 function complete() {
7722 if (preconditionErrored) {
7723 return;
7724 }
7725
7726 changesHandler.notify(api._meta.name);
7727 callback(null, results);
7728 }
7729
7730 function verifyAttachment(digest, callback) {
7731
7732 var req = attachStore.get(digest);
7733 req.onsuccess = function (e) {
7734 if (!e.target.result) {
7735 var err = createError(MISSING_STUB,
7736 'unknown stub attachment with digest ' +
7737 digest);
7738 err.status = 412;
7739 callback(err);
7740 } else {
7741 callback();
7742 }
7743 };
7744 }
7745
7746 function verifyAttachments(finish) {
7747
7748
7749 var digests = [];
7750 docInfos.forEach(function (docInfo) {
7751 if (docInfo.data && docInfo.data._attachments) {
7752 Object.keys(docInfo.data._attachments).forEach(function (filename) {
7753 var att = docInfo.data._attachments[filename];
7754 if (att.stub) {
7755 digests.push(att.digest);
7756 }
7757 });
7758 }
7759 });
7760 if (!digests.length) {
7761 return finish();
7762 }
7763 var numDone = 0;
7764 var err;
7765
7766 function checkDone() {
7767 if (++numDone === digests.length) {
7768 finish(err);
7769 }
7770 }
7771 digests.forEach(function (digest) {
7772 verifyAttachment(digest, function (attErr) {
7773 if (attErr && !err) {
7774 err = attErr;
7775 }
7776 checkDone();
7777 });
7778 });
7779 }
7780
7781 function writeDoc(docInfo, winningRev$$1, winningRevIsDeleted, newRevIsDeleted,
7782 isUpdate, delta, resultsIdx, callback) {
7783
7784 docInfo.metadata.winningRev = winningRev$$1;
7785 docInfo.metadata.deleted = winningRevIsDeleted;
7786
7787 var doc = docInfo.data;
7788 doc._id = docInfo.metadata.id;
7789 doc._rev = docInfo.metadata.rev;
7790
7791 if (newRevIsDeleted) {
7792 doc._deleted = true;
7793 }
7794
7795 var hasAttachments = doc._attachments &&
7796 Object.keys(doc._attachments).length;
7797 if (hasAttachments) {
7798 return writeAttachments(docInfo, winningRev$$1, winningRevIsDeleted,
7799 isUpdate, resultsIdx, callback);
7800 }
7801
7802 docCountDelta += delta;
7803 updateDocCountIfReady();
7804
7805 finishDoc(docInfo, winningRev$$1, winningRevIsDeleted,
7806 isUpdate, resultsIdx, callback);
7807 }
7808
7809 function finishDoc(docInfo, winningRev$$1, winningRevIsDeleted,
7810 isUpdate, resultsIdx, callback) {
7811
7812 var doc = docInfo.data;
7813 var metadata = docInfo.metadata;
7814
7815 doc._doc_id_rev = metadata.id + '::' + metadata.rev;
7816 delete doc._id;
7817 delete doc._rev;
7818
7819 function afterPutDoc(e) {
7820 var revsToDelete = docInfo.stemmedRevs || [];
7821
7822 if (isUpdate && api.auto_compaction) {
7823 revsToDelete = revsToDelete.concat(compactTree(docInfo.metadata));
7824 }
7825
7826 if (revsToDelete && revsToDelete.length) {
7827 compactRevs(revsToDelete, docInfo.metadata.id, txn);
7828 }
7829
7830 metadata.seq = e.target.result;
7831 // Current _rev is calculated from _rev_tree on read
7832 // delete metadata.rev;
7833 var metadataToStore = encodeMetadata(metadata, winningRev$$1,
7834 winningRevIsDeleted);
7835 var metaDataReq = docStore.put(metadataToStore);
7836 metaDataReq.onsuccess = afterPutMetadata;
7837 }
7838
7839 function afterPutDocError(e) {
7840 // ConstraintError, need to update, not put (see #1638 for details)
7841 e.preventDefault(); // avoid transaction abort
7842 e.stopPropagation(); // avoid transaction onerror
7843 var index = bySeqStore.index('_doc_id_rev');
7844 var getKeyReq = index.getKey(doc._doc_id_rev);
7845 getKeyReq.onsuccess = function (e) {
7846 var putReq = bySeqStore.put(doc, e.target.result);
7847 putReq.onsuccess = afterPutDoc;
7848 };
7849 }
7850
7851 function afterPutMetadata() {
7852 results[resultsIdx] = {
7853 ok: true,
7854 id: metadata.id,
7855 rev: metadata.rev
7856 };
7857 fetchedDocs.set(docInfo.metadata.id, docInfo.metadata);
7858 insertAttachmentMappings(docInfo, metadata.seq, callback);
7859 }
7860
7861 var putReq = bySeqStore.put(doc);
7862
7863 putReq.onsuccess = afterPutDoc;
7864 putReq.onerror = afterPutDocError;
7865 }
7866
7867 function writeAttachments(docInfo, winningRev$$1, winningRevIsDeleted,
7868 isUpdate, resultsIdx, callback) {
7869
7870
7871 var doc = docInfo.data;
7872
7873 var numDone = 0;
7874 var attachments = Object.keys(doc._attachments);
7875
7876 function collectResults() {
7877 if (numDone === attachments.length) {
7878 finishDoc(docInfo, winningRev$$1, winningRevIsDeleted,
7879 isUpdate, resultsIdx, callback);
7880 }
7881 }
7882
7883 function attachmentSaved() {
7884 numDone++;
7885 collectResults();
7886 }
7887
7888 attachments.forEach(function (key) {
7889 var att = docInfo.data._attachments[key];
7890 if (!att.stub) {
7891 var data = att.data;
7892 delete att.data;
7893 att.revpos = parseInt(winningRev$$1, 10);
7894 var digest = att.digest;
7895 saveAttachment(digest, data, attachmentSaved);
7896 } else {
7897 numDone++;
7898 collectResults();
7899 }
7900 });
7901 }
7902
7903 // map seqs to attachment digests, which
7904 // we will need later during compaction
7905 function insertAttachmentMappings(docInfo, seq, callback) {
7906
7907 var attsAdded = 0;
7908 var attsToAdd = Object.keys(docInfo.data._attachments || {});
7909
7910 if (!attsToAdd.length) {
7911 return callback();
7912 }
7913
7914 function checkDone() {
7915 if (++attsAdded === attsToAdd.length) {
7916 callback();
7917 }
7918 }
7919
7920 function add(att) {
7921 var digest = docInfo.data._attachments[att].digest;
7922 var req = attachAndSeqStore.put({
7923 seq: seq,
7924 digestSeq: digest + '::' + seq
7925 });
7926
7927 req.onsuccess = checkDone;
7928 req.onerror = function (e) {
7929 // this callback is for a constaint error, which we ignore
7930 // because this docid/rev has already been associated with
7931 // the digest (e.g. when new_edits == false)
7932 e.preventDefault(); // avoid transaction abort
7933 e.stopPropagation(); // avoid transaction onerror
7934 checkDone();
7935 };
7936 }
7937 for (var i = 0; i < attsToAdd.length; i++) {
7938 add(attsToAdd[i]); // do in parallel
7939 }
7940 }
7941
7942 function saveAttachment(digest, data, callback) {
7943
7944
7945 var getKeyReq = attachStore.count(digest);
7946 getKeyReq.onsuccess = function (e) {
7947 var count = e.target.result;
7948 if (count) {
7949 return callback(); // already exists
7950 }
7951 var newAtt = {
7952 digest: digest,
7953 body: data
7954 };
7955 var putReq = attachStore.put(newAtt);
7956 putReq.onsuccess = callback;
7957 };
7958 }
7959}
7960
7961// Abstraction over IDBCursor and getAll()/getAllKeys() that allows us to batch our operations
7962// while falling back to a normal IDBCursor operation on browsers that don't support getAll() or
7963// getAllKeys(). This allows for a much faster implementation than just straight-up cursors, because
7964// we're not processing each document one-at-a-time.
7965function runBatchedCursor(objectStore, keyRange, descending, batchSize, onBatch) {
7966
7967 if (batchSize === -1) {
7968 batchSize = 1000;
7969 }
7970
7971 // Bail out of getAll()/getAllKeys() in the following cases:
7972 // 1) either method is unsupported - we need both
7973 // 2) batchSize is 1 (might as well use IDBCursor)
7974 // 3) descending – no real way to do this via getAll()/getAllKeys()
7975
7976 var useGetAll = typeof objectStore.getAll === 'function' &&
7977 typeof objectStore.getAllKeys === 'function' &&
7978 batchSize > 1 && !descending;
7979
7980 var keysBatch;
7981 var valuesBatch;
7982 var pseudoCursor;
7983
7984 function onGetAll(e) {
7985 valuesBatch = e.target.result;
7986 if (keysBatch) {
7987 onBatch(keysBatch, valuesBatch, pseudoCursor);
7988 }
7989 }
7990
7991 function onGetAllKeys(e) {
7992 keysBatch = e.target.result;
7993 if (valuesBatch) {
7994 onBatch(keysBatch, valuesBatch, pseudoCursor);
7995 }
7996 }
7997
7998 function continuePseudoCursor() {
7999 if (!keysBatch.length) { // no more results
8000 return onBatch();
8001 }
8002 // fetch next batch, exclusive start
8003 var lastKey = keysBatch[keysBatch.length - 1];
8004 var newKeyRange;
8005 if (keyRange && keyRange.upper) {
8006 try {
8007 newKeyRange = IDBKeyRange.bound(lastKey, keyRange.upper,
8008 true, keyRange.upperOpen);
8009 } catch (e) {
8010 if (e.name === "DataError" && e.code === 0) {
8011 return onBatch(); // we're done, startkey and endkey are equal
8012 }
8013 }
8014 } else {
8015 newKeyRange = IDBKeyRange.lowerBound(lastKey, true);
8016 }
8017 keyRange = newKeyRange;
8018 keysBatch = null;
8019 valuesBatch = null;
8020 objectStore.getAll(keyRange, batchSize).onsuccess = onGetAll;
8021 objectStore.getAllKeys(keyRange, batchSize).onsuccess = onGetAllKeys;
8022 }
8023
8024 function onCursor(e) {
8025 var cursor = e.target.result;
8026 if (!cursor) { // done
8027 return onBatch();
8028 }
8029 // regular IDBCursor acts like a batch where batch size is always 1
8030 onBatch([cursor.key], [cursor.value], cursor);
8031 }
8032
8033 if (useGetAll) {
8034 pseudoCursor = {"continue": continuePseudoCursor};
8035 objectStore.getAll(keyRange, batchSize).onsuccess = onGetAll;
8036 objectStore.getAllKeys(keyRange, batchSize).onsuccess = onGetAllKeys;
8037 } else if (descending) {
8038 objectStore.openCursor(keyRange, 'prev').onsuccess = onCursor;
8039 } else {
8040 objectStore.openCursor(keyRange).onsuccess = onCursor;
8041 }
8042}
8043
8044// simple shim for objectStore.getAll(), falling back to IDBCursor
8045function getAll(objectStore, keyRange, onSuccess) {
8046 if (typeof objectStore.getAll === 'function') {
8047 // use native getAll
8048 objectStore.getAll(keyRange).onsuccess = onSuccess;
8049 return;
8050 }
8051 // fall back to cursors
8052 var values = [];
8053
8054 function onCursor(e) {
8055 var cursor = e.target.result;
8056 if (cursor) {
8057 values.push(cursor.value);
8058 cursor["continue"]();
8059 } else {
8060 onSuccess({
8061 target: {
8062 result: values
8063 }
8064 });
8065 }
8066 }
8067
8068 objectStore.openCursor(keyRange).onsuccess = onCursor;
8069}
8070
8071function allDocsKeys(keys, docStore, onBatch) {
8072 // It's not guaranted to be returned in right order
8073 var valuesBatch = new Array(keys.length);
8074 var count = 0;
8075 keys.forEach(function (key, index) {
8076 docStore.get(key).onsuccess = function (event) {
8077 if (event.target.result) {
8078 valuesBatch[index] = event.target.result;
8079 } else {
8080 valuesBatch[index] = {key: key, error: 'not_found'};
8081 }
8082 count++;
8083 if (count === keys.length) {
8084 onBatch(keys, valuesBatch, {});
8085 }
8086 };
8087 });
8088}
8089
8090function createKeyRange(start, end, inclusiveEnd, key, descending) {
8091 try {
8092 if (start && end) {
8093 if (descending) {
8094 return IDBKeyRange.bound(end, start, !inclusiveEnd, false);
8095 } else {
8096 return IDBKeyRange.bound(start, end, false, !inclusiveEnd);
8097 }
8098 } else if (start) {
8099 if (descending) {
8100 return IDBKeyRange.upperBound(start);
8101 } else {
8102 return IDBKeyRange.lowerBound(start);
8103 }
8104 } else if (end) {
8105 if (descending) {
8106 return IDBKeyRange.lowerBound(end, !inclusiveEnd);
8107 } else {
8108 return IDBKeyRange.upperBound(end, !inclusiveEnd);
8109 }
8110 } else if (key) {
8111 return IDBKeyRange.only(key);
8112 }
8113 } catch (e) {
8114 return {error: e};
8115 }
8116 return null;
8117}
8118
8119function idbAllDocs(opts, idb, callback) {
8120 var start = 'startkey' in opts ? opts.startkey : false;
8121 var end = 'endkey' in opts ? opts.endkey : false;
8122 var key = 'key' in opts ? opts.key : false;
8123 var keys = 'keys' in opts ? opts.keys : false;
8124 var skip = opts.skip || 0;
8125 var limit = typeof opts.limit === 'number' ? opts.limit : -1;
8126 var inclusiveEnd = opts.inclusive_end !== false;
8127
8128 var keyRange ;
8129 var keyRangeError;
8130 if (!keys) {
8131 keyRange = createKeyRange(start, end, inclusiveEnd, key, opts.descending);
8132 keyRangeError = keyRange && keyRange.error;
8133 if (keyRangeError &&
8134 !(keyRangeError.name === "DataError" && keyRangeError.code === 0)) {
8135 // DataError with error code 0 indicates start is less than end, so
8136 // can just do an empty query. Else need to throw
8137 return callback(createError(IDB_ERROR,
8138 keyRangeError.name, keyRangeError.message));
8139 }
8140 }
8141
8142 var stores = [DOC_STORE, BY_SEQ_STORE, META_STORE];
8143
8144 if (opts.attachments) {
8145 stores.push(ATTACH_STORE);
8146 }
8147 var txnResult = openTransactionSafely(idb, stores, 'readonly');
8148 if (txnResult.error) {
8149 return callback(txnResult.error);
8150 }
8151 var txn = txnResult.txn;
8152 txn.oncomplete = onTxnComplete;
8153 txn.onabort = idbError(callback);
8154 var docStore = txn.objectStore(DOC_STORE);
8155 var seqStore = txn.objectStore(BY_SEQ_STORE);
8156 var metaStore = txn.objectStore(META_STORE);
8157 var docIdRevIndex = seqStore.index('_doc_id_rev');
8158 var results = [];
8159 var docCount;
8160 var updateSeq;
8161
8162 metaStore.get(META_STORE).onsuccess = function (e) {
8163 docCount = e.target.result.docCount;
8164 };
8165
8166 /* istanbul ignore if */
8167 if (opts.update_seq) {
8168 getMaxUpdateSeq(seqStore, function (e) {
8169 if (e.target.result && e.target.result.length > 0) {
8170 updateSeq = e.target.result[0];
8171 }
8172 });
8173 }
8174
8175 function getMaxUpdateSeq(objectStore, onSuccess) {
8176 function onCursor(e) {
8177 var cursor = e.target.result;
8178 var maxKey = undefined;
8179 if (cursor && cursor.key) {
8180 maxKey = cursor.key;
8181 }
8182 return onSuccess({
8183 target: {
8184 result: [maxKey]
8185 }
8186 });
8187 }
8188 objectStore.openCursor(null, 'prev').onsuccess = onCursor;
8189 }
8190
8191 // if the user specifies include_docs=true, then we don't
8192 // want to block the main cursor while we're fetching the doc
8193 function fetchDocAsynchronously(metadata, row, winningRev$$1) {
8194 var key = metadata.id + "::" + winningRev$$1;
8195 docIdRevIndex.get(key).onsuccess = function onGetDoc(e) {
8196 row.doc = decodeDoc(e.target.result) || {};
8197 if (opts.conflicts) {
8198 var conflicts = collectConflicts(metadata);
8199 if (conflicts.length) {
8200 row.doc._conflicts = conflicts;
8201 }
8202 }
8203 fetchAttachmentsIfNecessary(row.doc, opts, txn);
8204 };
8205 }
8206
8207 function allDocsInner(winningRev$$1, metadata) {
8208 var row = {
8209 id: metadata.id,
8210 key: metadata.id,
8211 value: {
8212 rev: winningRev$$1
8213 }
8214 };
8215 var deleted = metadata.deleted;
8216 if (deleted) {
8217 if (keys) {
8218 results.push(row);
8219 // deleted docs are okay with "keys" requests
8220 row.value.deleted = true;
8221 row.doc = null;
8222 }
8223 } else if (skip-- <= 0) {
8224 results.push(row);
8225 if (opts.include_docs) {
8226 fetchDocAsynchronously(metadata, row, winningRev$$1);
8227 }
8228 }
8229 }
8230
8231 function processBatch(batchValues) {
8232 for (var i = 0, len = batchValues.length; i < len; i++) {
8233 if (results.length === limit) {
8234 break;
8235 }
8236 var batchValue = batchValues[i];
8237 if (batchValue.error && keys) {
8238 // key was not found with "keys" requests
8239 results.push(batchValue);
8240 continue;
8241 }
8242 var metadata = decodeMetadata(batchValue);
8243 var winningRev$$1 = metadata.winningRev;
8244 allDocsInner(winningRev$$1, metadata);
8245 }
8246 }
8247
8248 function onBatch(batchKeys, batchValues, cursor) {
8249 if (!cursor) {
8250 return;
8251 }
8252 processBatch(batchValues);
8253 if (results.length < limit) {
8254 cursor["continue"]();
8255 }
8256 }
8257
8258 function onGetAll(e) {
8259 var values = e.target.result;
8260 if (opts.descending) {
8261 values = values.reverse();
8262 }
8263 processBatch(values);
8264 }
8265
8266 function onResultsReady() {
8267 var returnVal = {
8268 total_rows: docCount,
8269 offset: opts.skip,
8270 rows: results
8271 };
8272
8273 /* istanbul ignore if */
8274 if (opts.update_seq && updateSeq !== undefined) {
8275 returnVal.update_seq = updateSeq;
8276 }
8277 callback(null, returnVal);
8278 }
8279
8280 function onTxnComplete() {
8281 if (opts.attachments) {
8282 postProcessAttachments(results, opts.binary).then(onResultsReady);
8283 } else {
8284 onResultsReady();
8285 }
8286 }
8287
8288 // don't bother doing any requests if start > end or limit === 0
8289 if (keyRangeError || limit === 0) {
8290 return;
8291 }
8292 if (keys) {
8293 return allDocsKeys(opts.keys, docStore, onBatch);
8294 }
8295 if (limit === -1) { // just fetch everything
8296 return getAll(docStore, keyRange, onGetAll);
8297 }
8298 // else do a cursor
8299 // choose a batch size based on the skip, since we'll need to skip that many
8300 runBatchedCursor(docStore, keyRange, opts.descending, limit + skip, onBatch);
8301}
8302
8303//
8304// Blobs are not supported in all versions of IndexedDB, notably
8305// Chrome <37 and Android <5. In those versions, storing a blob will throw.
8306//
8307// Various other blob bugs exist in Chrome v37-42 (inclusive).
8308// Detecting them is expensive and confusing to users, and Chrome 37-42
8309// is at very low usage worldwide, so we do a hacky userAgent check instead.
8310//
8311// content-type bug: https://code.google.com/p/chromium/issues/detail?id=408120
8312// 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916
8313// FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836
8314//
8315function checkBlobSupport(txn) {
8316 return new Promise(function (resolve) {
8317 var blob$$1 = createBlob(['']);
8318 var req = txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob$$1, 'key');
8319
8320 req.onsuccess = function () {
8321 var matchedChrome = navigator.userAgent.match(/Chrome\/(\d+)/);
8322 var matchedEdge = navigator.userAgent.match(/Edge\//);
8323 // MS Edge pretends to be Chrome 42:
8324 // https://msdn.microsoft.com/en-us/library/hh869301%28v=vs.85%29.aspx
8325 resolve(matchedEdge || !matchedChrome ||
8326 parseInt(matchedChrome[1], 10) >= 43);
8327 };
8328
8329 req.onerror = txn.onabort = function (e) {
8330 // If the transaction aborts now its due to not being able to
8331 // write to the database, likely due to the disk being full
8332 e.preventDefault();
8333 e.stopPropagation();
8334 resolve(false);
8335 };
8336 })["catch"](function () {
8337 return false; // error, so assume unsupported
8338 });
8339}
8340
8341function countDocs(txn, cb) {
8342 var index = txn.objectStore(DOC_STORE).index('deletedOrLocal');
8343 index.count(IDBKeyRange.only('0')).onsuccess = function (e) {
8344 cb(e.target.result);
8345 };
8346}
8347
8348// This task queue ensures that IDB open calls are done in their own tick
8349
8350var running = false;
8351var queue = [];
8352
8353function tryCode(fun, err, res, PouchDB) {
8354 try {
8355 fun(err, res);
8356 } catch (err) {
8357 // Shouldn't happen, but in some odd cases
8358 // IndexedDB implementations might throw a sync
8359 // error, in which case this will at least log it.
8360 PouchDB.emit('error', err);
8361 }
8362}
8363
8364function applyNext() {
8365 if (running || !queue.length) {
8366 return;
8367 }
8368 running = true;
8369 queue.shift()();
8370}
8371
8372function enqueueTask(action, callback, PouchDB) {
8373 queue.push(function runAction() {
8374 action(function runCallback(err, res) {
8375 tryCode(callback, err, res, PouchDB);
8376 running = false;
8377 immediate(function runNext() {
8378 applyNext(PouchDB);
8379 });
8380 });
8381 });
8382 applyNext();
8383}
8384
8385function changes(opts, api, dbName, idb) {
8386 opts = clone(opts);
8387
8388 if (opts.continuous) {
8389 var id = dbName + ':' + uuid$1();
8390 changesHandler.addListener(dbName, id, api, opts);
8391 changesHandler.notify(dbName);
8392 return {
8393 cancel: function () {
8394 changesHandler.removeListener(dbName, id);
8395 }
8396 };
8397 }
8398
8399 var docIds = opts.doc_ids && new ExportedSet(opts.doc_ids);
8400
8401 opts.since = opts.since || 0;
8402 var lastSeq = opts.since;
8403
8404 var limit = 'limit' in opts ? opts.limit : -1;
8405 if (limit === 0) {
8406 limit = 1; // per CouchDB _changes spec
8407 }
8408
8409 var results = [];
8410 var numResults = 0;
8411 var filter = filterChange(opts);
8412 var docIdsToMetadata = new ExportedMap();
8413
8414 var txn;
8415 var bySeqStore;
8416 var docStore;
8417 var docIdRevIndex;
8418
8419 function onBatch(batchKeys, batchValues, cursor) {
8420 if (!cursor || !batchKeys.length) { // done
8421 return;
8422 }
8423
8424 var winningDocs = new Array(batchKeys.length);
8425 var metadatas = new Array(batchKeys.length);
8426
8427 function processMetadataAndWinningDoc(metadata, winningDoc) {
8428 var change = opts.processChange(winningDoc, metadata, opts);
8429 lastSeq = change.seq = metadata.seq;
8430
8431 var filtered = filter(change);
8432 if (typeof filtered === 'object') { // anything but true/false indicates error
8433 return Promise.reject(filtered);
8434 }
8435
8436 if (!filtered) {
8437 return Promise.resolve();
8438 }
8439 numResults++;
8440 if (opts.return_docs) {
8441 results.push(change);
8442 }
8443 // process the attachment immediately
8444 // for the benefit of live listeners
8445 if (opts.attachments && opts.include_docs) {
8446 return new Promise(function (resolve) {
8447 fetchAttachmentsIfNecessary(winningDoc, opts, txn, function () {
8448 postProcessAttachments([change], opts.binary).then(function () {
8449 resolve(change);
8450 });
8451 });
8452 });
8453 } else {
8454 return Promise.resolve(change);
8455 }
8456 }
8457
8458 function onBatchDone() {
8459 var promises = [];
8460 for (var i = 0, len = winningDocs.length; i < len; i++) {
8461 if (numResults === limit) {
8462 break;
8463 }
8464 var winningDoc = winningDocs[i];
8465 if (!winningDoc) {
8466 continue;
8467 }
8468 var metadata = metadatas[i];
8469 promises.push(processMetadataAndWinningDoc(metadata, winningDoc));
8470 }
8471
8472 Promise.all(promises).then(function (changes) {
8473 for (var i = 0, len = changes.length; i < len; i++) {
8474 if (changes[i]) {
8475 opts.onChange(changes[i]);
8476 }
8477 }
8478 })["catch"](opts.complete);
8479
8480 if (numResults !== limit) {
8481 cursor["continue"]();
8482 }
8483 }
8484
8485 // Fetch all metadatas/winningdocs from this batch in parallel, then process
8486 // them all only once all data has been collected. This is done in parallel
8487 // because it's faster than doing it one-at-a-time.
8488 var numDone = 0;
8489 batchValues.forEach(function (value, i) {
8490 var doc = decodeDoc(value);
8491 var seq = batchKeys[i];
8492 fetchWinningDocAndMetadata(doc, seq, function (metadata, winningDoc) {
8493 metadatas[i] = metadata;
8494 winningDocs[i] = winningDoc;
8495 if (++numDone === batchKeys.length) {
8496 onBatchDone();
8497 }
8498 });
8499 });
8500 }
8501
8502 function onGetMetadata(doc, seq, metadata, cb) {
8503 if (metadata.seq !== seq) {
8504 // some other seq is later
8505 return cb();
8506 }
8507
8508 if (metadata.winningRev === doc._rev) {
8509 // this is the winning doc
8510 return cb(metadata, doc);
8511 }
8512
8513 // fetch winning doc in separate request
8514 var docIdRev = doc._id + '::' + metadata.winningRev;
8515 var req = docIdRevIndex.get(docIdRev);
8516 req.onsuccess = function (e) {
8517 cb(metadata, decodeDoc(e.target.result));
8518 };
8519 }
8520
8521 function fetchWinningDocAndMetadata(doc, seq, cb) {
8522 if (docIds && !docIds.has(doc._id)) {
8523 return cb();
8524 }
8525
8526 var metadata = docIdsToMetadata.get(doc._id);
8527 if (metadata) { // cached
8528 return onGetMetadata(doc, seq, metadata, cb);
8529 }
8530 // metadata not cached, have to go fetch it
8531 docStore.get(doc._id).onsuccess = function (e) {
8532 metadata = decodeMetadata(e.target.result);
8533 docIdsToMetadata.set(doc._id, metadata);
8534 onGetMetadata(doc, seq, metadata, cb);
8535 };
8536 }
8537
8538 function finish() {
8539 opts.complete(null, {
8540 results: results,
8541 last_seq: lastSeq
8542 });
8543 }
8544
8545 function onTxnComplete() {
8546 if (!opts.continuous && opts.attachments) {
8547 // cannot guarantee that postProcessing was already done,
8548 // so do it again
8549 postProcessAttachments(results).then(finish);
8550 } else {
8551 finish();
8552 }
8553 }
8554
8555 var objectStores = [DOC_STORE, BY_SEQ_STORE];
8556 if (opts.attachments) {
8557 objectStores.push(ATTACH_STORE);
8558 }
8559 var txnResult = openTransactionSafely(idb, objectStores, 'readonly');
8560 if (txnResult.error) {
8561 return opts.complete(txnResult.error);
8562 }
8563 txn = txnResult.txn;
8564 txn.onabort = idbError(opts.complete);
8565 txn.oncomplete = onTxnComplete;
8566
8567 bySeqStore = txn.objectStore(BY_SEQ_STORE);
8568 docStore = txn.objectStore(DOC_STORE);
8569 docIdRevIndex = bySeqStore.index('_doc_id_rev');
8570
8571 var keyRange = (opts.since && !opts.descending) ?
8572 IDBKeyRange.lowerBound(opts.since, true) : null;
8573
8574 runBatchedCursor(bySeqStore, keyRange, opts.descending, limit, onBatch);
8575}
8576
8577var cachedDBs = new ExportedMap();
8578var blobSupportPromise;
8579var openReqList = new ExportedMap();
8580
8581function IdbPouch(opts, callback) {
8582 var api = this;
8583
8584 enqueueTask(function (thisCallback) {
8585 init(api, opts, thisCallback);
8586 }, callback, api.constructor);
8587}
8588
8589function init(api, opts, callback) {
8590
8591 var dbName = opts.name;
8592
8593 var idb = null;
8594 var idbGlobalFailureError = null;
8595 api._meta = null;
8596
8597 function enrichCallbackError(callback) {
8598 return function (error, result) {
8599 if (error && error instanceof Error && !error.reason) {
8600 if (idbGlobalFailureError) {
8601 error.reason = idbGlobalFailureError;
8602 }
8603 }
8604
8605 callback(error, result);
8606 };
8607 }
8608
8609 // called when creating a fresh new database
8610 function createSchema(db) {
8611 var docStore = db.createObjectStore(DOC_STORE, {keyPath : 'id'});
8612 db.createObjectStore(BY_SEQ_STORE, {autoIncrement: true})
8613 .createIndex('_doc_id_rev', '_doc_id_rev', {unique: true});
8614 db.createObjectStore(ATTACH_STORE, {keyPath: 'digest'});
8615 db.createObjectStore(META_STORE, {keyPath: 'id', autoIncrement: false});
8616 db.createObjectStore(DETECT_BLOB_SUPPORT_STORE);
8617
8618 // added in v2
8619 docStore.createIndex('deletedOrLocal', 'deletedOrLocal', {unique : false});
8620
8621 // added in v3
8622 db.createObjectStore(LOCAL_STORE, {keyPath: '_id'});
8623
8624 // added in v4
8625 var attAndSeqStore = db.createObjectStore(ATTACH_AND_SEQ_STORE,
8626 {autoIncrement: true});
8627 attAndSeqStore.createIndex('seq', 'seq');
8628 attAndSeqStore.createIndex('digestSeq', 'digestSeq', {unique: true});
8629 }
8630
8631 // migration to version 2
8632 // unfortunately "deletedOrLocal" is a misnomer now that we no longer
8633 // store local docs in the main doc-store, but whaddyagonnado
8634 function addDeletedOrLocalIndex(txn, callback) {
8635 var docStore = txn.objectStore(DOC_STORE);
8636 docStore.createIndex('deletedOrLocal', 'deletedOrLocal', {unique : false});
8637
8638 docStore.openCursor().onsuccess = function (event) {
8639 var cursor = event.target.result;
8640 if (cursor) {
8641 var metadata = cursor.value;
8642 var deleted = isDeleted(metadata);
8643 metadata.deletedOrLocal = deleted ? "1" : "0";
8644 docStore.put(metadata);
8645 cursor["continue"]();
8646 } else {
8647 callback();
8648 }
8649 };
8650 }
8651
8652 // migration to version 3 (part 1)
8653 function createLocalStoreSchema(db) {
8654 db.createObjectStore(LOCAL_STORE, {keyPath: '_id'})
8655 .createIndex('_doc_id_rev', '_doc_id_rev', {unique: true});
8656 }
8657
8658 // migration to version 3 (part 2)
8659 function migrateLocalStore(txn, cb) {
8660 var localStore = txn.objectStore(LOCAL_STORE);
8661 var docStore = txn.objectStore(DOC_STORE);
8662 var seqStore = txn.objectStore(BY_SEQ_STORE);
8663
8664 var cursor = docStore.openCursor();
8665 cursor.onsuccess = function (event) {
8666 var cursor = event.target.result;
8667 if (cursor) {
8668 var metadata = cursor.value;
8669 var docId = metadata.id;
8670 var local = isLocalId(docId);
8671 var rev = winningRev(metadata);
8672 if (local) {
8673 var docIdRev = docId + "::" + rev;
8674 // remove all seq entries
8675 // associated with this docId
8676 var start = docId + "::";
8677 var end = docId + "::~";
8678 var index = seqStore.index('_doc_id_rev');
8679 var range = IDBKeyRange.bound(start, end, false, false);
8680 var seqCursor = index.openCursor(range);
8681 seqCursor.onsuccess = function (e) {
8682 seqCursor = e.target.result;
8683 if (!seqCursor) {
8684 // done
8685 docStore["delete"](cursor.primaryKey);
8686 cursor["continue"]();
8687 } else {
8688 var data = seqCursor.value;
8689 if (data._doc_id_rev === docIdRev) {
8690 localStore.put(data);
8691 }
8692 seqStore["delete"](seqCursor.primaryKey);
8693 seqCursor["continue"]();
8694 }
8695 };
8696 } else {
8697 cursor["continue"]();
8698 }
8699 } else if (cb) {
8700 cb();
8701 }
8702 };
8703 }
8704
8705 // migration to version 4 (part 1)
8706 function addAttachAndSeqStore(db) {
8707 var attAndSeqStore = db.createObjectStore(ATTACH_AND_SEQ_STORE,
8708 {autoIncrement: true});
8709 attAndSeqStore.createIndex('seq', 'seq');
8710 attAndSeqStore.createIndex('digestSeq', 'digestSeq', {unique: true});
8711 }
8712
8713 // migration to version 4 (part 2)
8714 function migrateAttsAndSeqs(txn, callback) {
8715 var seqStore = txn.objectStore(BY_SEQ_STORE);
8716 var attStore = txn.objectStore(ATTACH_STORE);
8717 var attAndSeqStore = txn.objectStore(ATTACH_AND_SEQ_STORE);
8718
8719 // need to actually populate the table. this is the expensive part,
8720 // so as an optimization, check first that this database even
8721 // contains attachments
8722 var req = attStore.count();
8723 req.onsuccess = function (e) {
8724 var count = e.target.result;
8725 if (!count) {
8726 return callback(); // done
8727 }
8728
8729 seqStore.openCursor().onsuccess = function (e) {
8730 var cursor = e.target.result;
8731 if (!cursor) {
8732 return callback(); // done
8733 }
8734 var doc = cursor.value;
8735 var seq = cursor.primaryKey;
8736 var atts = Object.keys(doc._attachments || {});
8737 var digestMap = {};
8738 for (var j = 0; j < atts.length; j++) {
8739 var att = doc._attachments[atts[j]];
8740 digestMap[att.digest] = true; // uniq digests, just in case
8741 }
8742 var digests = Object.keys(digestMap);
8743 for (j = 0; j < digests.length; j++) {
8744 var digest = digests[j];
8745 attAndSeqStore.put({
8746 seq: seq,
8747 digestSeq: digest + '::' + seq
8748 });
8749 }
8750 cursor["continue"]();
8751 };
8752 };
8753 }
8754
8755 // migration to version 5
8756 // Instead of relying on on-the-fly migration of metadata,
8757 // this brings the doc-store to its modern form:
8758 // - metadata.winningrev
8759 // - metadata.seq
8760 // - stringify the metadata when storing it
8761 function migrateMetadata(txn) {
8762
8763 function decodeMetadataCompat(storedObject) {
8764 if (!storedObject.data) {
8765 // old format, when we didn't store it stringified
8766 storedObject.deleted = storedObject.deletedOrLocal === '1';
8767 return storedObject;
8768 }
8769 return decodeMetadata(storedObject);
8770 }
8771
8772 // ensure that every metadata has a winningRev and seq,
8773 // which was previously created on-the-fly but better to migrate
8774 var bySeqStore = txn.objectStore(BY_SEQ_STORE);
8775 var docStore = txn.objectStore(DOC_STORE);
8776 var cursor = docStore.openCursor();
8777 cursor.onsuccess = function (e) {
8778 var cursor = e.target.result;
8779 if (!cursor) {
8780 return; // done
8781 }
8782 var metadata = decodeMetadataCompat(cursor.value);
8783
8784 metadata.winningRev = metadata.winningRev ||
8785 winningRev(metadata);
8786
8787 function fetchMetadataSeq() {
8788 // metadata.seq was added post-3.2.0, so if it's missing,
8789 // we need to fetch it manually
8790 var start = metadata.id + '::';
8791 var end = metadata.id + '::\uffff';
8792 var req = bySeqStore.index('_doc_id_rev').openCursor(
8793 IDBKeyRange.bound(start, end));
8794
8795 var metadataSeq = 0;
8796 req.onsuccess = function (e) {
8797 var cursor = e.target.result;
8798 if (!cursor) {
8799 metadata.seq = metadataSeq;
8800 return onGetMetadataSeq();
8801 }
8802 var seq = cursor.primaryKey;
8803 if (seq > metadataSeq) {
8804 metadataSeq = seq;
8805 }
8806 cursor["continue"]();
8807 };
8808 }
8809
8810 function onGetMetadataSeq() {
8811 var metadataToStore = encodeMetadata(metadata,
8812 metadata.winningRev, metadata.deleted);
8813
8814 var req = docStore.put(metadataToStore);
8815 req.onsuccess = function () {
8816 cursor["continue"]();
8817 };
8818 }
8819
8820 if (metadata.seq) {
8821 return onGetMetadataSeq();
8822 }
8823
8824 fetchMetadataSeq();
8825 };
8826
8827 }
8828
8829 api._remote = false;
8830 api.type = function () {
8831 return 'idb';
8832 };
8833
8834 api._id = toPromise(function (callback) {
8835 callback(null, api._meta.instanceId);
8836 });
8837
8838 api._bulkDocs = function idb_bulkDocs(req, reqOpts, callback) {
8839 idbBulkDocs(opts, req, reqOpts, api, idb, enrichCallbackError(callback));
8840 };
8841
8842 // First we look up the metadata in the ids database, then we fetch the
8843 // current revision(s) from the by sequence store
8844 api._get = function idb_get(id, opts, callback) {
8845 var doc;
8846 var metadata;
8847 var err;
8848 var txn = opts.ctx;
8849 if (!txn) {
8850 var txnResult = openTransactionSafely(idb,
8851 [DOC_STORE, BY_SEQ_STORE, ATTACH_STORE], 'readonly');
8852 if (txnResult.error) {
8853 return callback(txnResult.error);
8854 }
8855 txn = txnResult.txn;
8856 }
8857
8858 function finish() {
8859 callback(err, {doc: doc, metadata: metadata, ctx: txn});
8860 }
8861
8862 txn.objectStore(DOC_STORE).get(id).onsuccess = function (e) {
8863 metadata = decodeMetadata(e.target.result);
8864 // we can determine the result here if:
8865 // 1. there is no such document
8866 // 2. the document is deleted and we don't ask about specific rev
8867 // When we ask with opts.rev we expect the answer to be either
8868 // doc (possibly with _deleted=true) or missing error
8869 if (!metadata) {
8870 err = createError(MISSING_DOC, 'missing');
8871 return finish();
8872 }
8873
8874 var rev;
8875 if (!opts.rev) {
8876 rev = metadata.winningRev;
8877 var deleted = isDeleted(metadata);
8878 if (deleted) {
8879 err = createError(MISSING_DOC, "deleted");
8880 return finish();
8881 }
8882 } else {
8883 rev = opts.latest ? latest(opts.rev, metadata) : opts.rev;
8884 }
8885
8886 var objectStore = txn.objectStore(BY_SEQ_STORE);
8887 var key = metadata.id + '::' + rev;
8888
8889 objectStore.index('_doc_id_rev').get(key).onsuccess = function (e) {
8890 doc = e.target.result;
8891 if (doc) {
8892 doc = decodeDoc(doc);
8893 }
8894 if (!doc) {
8895 err = createError(MISSING_DOC, 'missing');
8896 return finish();
8897 }
8898 finish();
8899 };
8900 };
8901 };
8902
8903 api._getAttachment = function (docId, attachId, attachment, opts, callback) {
8904 var txn;
8905 if (opts.ctx) {
8906 txn = opts.ctx;
8907 } else {
8908 var txnResult = openTransactionSafely(idb,
8909 [DOC_STORE, BY_SEQ_STORE, ATTACH_STORE], 'readonly');
8910 if (txnResult.error) {
8911 return callback(txnResult.error);
8912 }
8913 txn = txnResult.txn;
8914 }
8915 var digest = attachment.digest;
8916 var type = attachment.content_type;
8917
8918 txn.objectStore(ATTACH_STORE).get(digest).onsuccess = function (e) {
8919 var body = e.target.result.body;
8920 readBlobData(body, type, opts.binary, function (blobData) {
8921 callback(null, blobData);
8922 });
8923 };
8924 };
8925
8926 api._info = function idb_info(callback) {
8927 var updateSeq;
8928 var docCount;
8929
8930 var txnResult = openTransactionSafely(idb, [META_STORE, BY_SEQ_STORE], 'readonly');
8931 if (txnResult.error) {
8932 return callback(txnResult.error);
8933 }
8934 var txn = txnResult.txn;
8935 txn.objectStore(META_STORE).get(META_STORE).onsuccess = function (e) {
8936 docCount = e.target.result.docCount;
8937 };
8938 txn.objectStore(BY_SEQ_STORE).openCursor(null, 'prev').onsuccess = function (e) {
8939 var cursor = e.target.result;
8940 updateSeq = cursor ? cursor.key : 0;
8941 };
8942
8943 txn.oncomplete = function () {
8944 callback(null, {
8945 doc_count: docCount,
8946 update_seq: updateSeq,
8947 // for debugging
8948 idb_attachment_format: (api._meta.blobSupport ? 'binary' : 'base64')
8949 });
8950 };
8951 };
8952
8953 api._allDocs = function idb_allDocs(opts, callback) {
8954 idbAllDocs(opts, idb, enrichCallbackError(callback));
8955 };
8956
8957 api._changes = function idbChanges(opts) {
8958 return changes(opts, api, dbName, idb);
8959 };
8960
8961 api._close = function (callback) {
8962 // https://developer.mozilla.org/en-US/docs/IndexedDB/IDBDatabase#close
8963 // "Returns immediately and closes the connection in a separate thread..."
8964 idb.close();
8965 cachedDBs["delete"](dbName);
8966 callback();
8967 };
8968
8969 api._getRevisionTree = function (docId, callback) {
8970 var txnResult = openTransactionSafely(idb, [DOC_STORE], 'readonly');
8971 if (txnResult.error) {
8972 return callback(txnResult.error);
8973 }
8974 var txn = txnResult.txn;
8975 var req = txn.objectStore(DOC_STORE).get(docId);
8976 req.onsuccess = function (event) {
8977 var doc = decodeMetadata(event.target.result);
8978 if (!doc) {
8979 callback(createError(MISSING_DOC));
8980 } else {
8981 callback(null, doc.rev_tree);
8982 }
8983 };
8984 };
8985
8986 // This function removes revisions of document docId
8987 // which are listed in revs and sets this document
8988 // revision to to rev_tree
8989 api._doCompaction = function (docId, revs, callback) {
8990 var stores = [
8991 DOC_STORE,
8992 BY_SEQ_STORE,
8993 ATTACH_STORE,
8994 ATTACH_AND_SEQ_STORE
8995 ];
8996 var txnResult = openTransactionSafely(idb, stores, 'readwrite');
8997 if (txnResult.error) {
8998 return callback(txnResult.error);
8999 }
9000 var txn = txnResult.txn;
9001
9002 var docStore = txn.objectStore(DOC_STORE);
9003
9004 docStore.get(docId).onsuccess = function (event) {
9005 var metadata = decodeMetadata(event.target.result);
9006 traverseRevTree(metadata.rev_tree, function (isLeaf, pos,
9007 revHash, ctx, opts) {
9008 var rev = pos + '-' + revHash;
9009 if (revs.indexOf(rev) !== -1) {
9010 opts.status = 'missing';
9011 }
9012 });
9013 compactRevs(revs, docId, txn);
9014 var winningRev$$1 = metadata.winningRev;
9015 var deleted = metadata.deleted;
9016 txn.objectStore(DOC_STORE).put(
9017 encodeMetadata(metadata, winningRev$$1, deleted));
9018 };
9019 txn.onabort = idbError(callback);
9020 txn.oncomplete = function () {
9021 callback();
9022 };
9023 };
9024
9025
9026 api._getLocal = function (id, callback) {
9027 var txnResult = openTransactionSafely(idb, [LOCAL_STORE], 'readonly');
9028 if (txnResult.error) {
9029 return callback(txnResult.error);
9030 }
9031 var tx = txnResult.txn;
9032 var req = tx.objectStore(LOCAL_STORE).get(id);
9033
9034 req.onerror = idbError(callback);
9035 req.onsuccess = function (e) {
9036 var doc = e.target.result;
9037 if (!doc) {
9038 callback(createError(MISSING_DOC));
9039 } else {
9040 delete doc['_doc_id_rev']; // for backwards compat
9041 callback(null, doc);
9042 }
9043 };
9044 };
9045
9046 api._putLocal = function (doc, opts, callback) {
9047 if (typeof opts === 'function') {
9048 callback = opts;
9049 opts = {};
9050 }
9051 delete doc._revisions; // ignore this, trust the rev
9052 var oldRev = doc._rev;
9053 var id = doc._id;
9054 if (!oldRev) {
9055 doc._rev = '0-1';
9056 } else {
9057 doc._rev = '0-' + (parseInt(oldRev.split('-')[1], 10) + 1);
9058 }
9059
9060 var tx = opts.ctx;
9061 var ret;
9062 if (!tx) {
9063 var txnResult = openTransactionSafely(idb, [LOCAL_STORE], 'readwrite');
9064 if (txnResult.error) {
9065 return callback(txnResult.error);
9066 }
9067 tx = txnResult.txn;
9068 tx.onerror = idbError(callback);
9069 tx.oncomplete = function () {
9070 if (ret) {
9071 callback(null, ret);
9072 }
9073 };
9074 }
9075
9076 var oStore = tx.objectStore(LOCAL_STORE);
9077 var req;
9078 if (oldRev) {
9079 req = oStore.get(id);
9080 req.onsuccess = function (e) {
9081 var oldDoc = e.target.result;
9082 if (!oldDoc || oldDoc._rev !== oldRev) {
9083 callback(createError(REV_CONFLICT));
9084 } else { // update
9085 var req = oStore.put(doc);
9086 req.onsuccess = function () {
9087 ret = {ok: true, id: doc._id, rev: doc._rev};
9088 if (opts.ctx) { // return immediately
9089 callback(null, ret);
9090 }
9091 };
9092 }
9093 };
9094 } else { // new doc
9095 req = oStore.add(doc);
9096 req.onerror = function (e) {
9097 // constraint error, already exists
9098 callback(createError(REV_CONFLICT));
9099 e.preventDefault(); // avoid transaction abort
9100 e.stopPropagation(); // avoid transaction onerror
9101 };
9102 req.onsuccess = function () {
9103 ret = {ok: true, id: doc._id, rev: doc._rev};
9104 if (opts.ctx) { // return immediately
9105 callback(null, ret);
9106 }
9107 };
9108 }
9109 };
9110
9111 api._removeLocal = function (doc, opts, callback) {
9112 if (typeof opts === 'function') {
9113 callback = opts;
9114 opts = {};
9115 }
9116 var tx = opts.ctx;
9117 if (!tx) {
9118 var txnResult = openTransactionSafely(idb, [LOCAL_STORE], 'readwrite');
9119 if (txnResult.error) {
9120 return callback(txnResult.error);
9121 }
9122 tx = txnResult.txn;
9123 tx.oncomplete = function () {
9124 if (ret) {
9125 callback(null, ret);
9126 }
9127 };
9128 }
9129 var ret;
9130 var id = doc._id;
9131 var oStore = tx.objectStore(LOCAL_STORE);
9132 var req = oStore.get(id);
9133
9134 req.onerror = idbError(callback);
9135 req.onsuccess = function (e) {
9136 var oldDoc = e.target.result;
9137 if (!oldDoc || oldDoc._rev !== doc._rev) {
9138 callback(createError(MISSING_DOC));
9139 } else {
9140 oStore["delete"](id);
9141 ret = {ok: true, id: id, rev: '0-0'};
9142 if (opts.ctx) { // return immediately
9143 callback(null, ret);
9144 }
9145 }
9146 };
9147 };
9148
9149 api._destroy = function (opts, callback) {
9150 changesHandler.removeAllListeners(dbName);
9151
9152 //Close open request for "dbName" database to fix ie delay.
9153 var openReq = openReqList.get(dbName);
9154 if (openReq && openReq.result) {
9155 openReq.result.close();
9156 cachedDBs["delete"](dbName);
9157 }
9158 var req = indexedDB.deleteDatabase(dbName);
9159
9160 req.onsuccess = function () {
9161 //Remove open request from the list.
9162 openReqList["delete"](dbName);
9163 if (hasLocalStorage() && (dbName in localStorage)) {
9164 delete localStorage[dbName];
9165 }
9166 callback(null, { 'ok': true });
9167 };
9168
9169 req.onerror = idbError(callback);
9170 };
9171
9172 var cached = cachedDBs.get(dbName);
9173
9174 if (cached) {
9175 idb = cached.idb;
9176 api._meta = cached.global;
9177 return immediate(function () {
9178 callback(null, api);
9179 });
9180 }
9181
9182 var req = indexedDB.open(dbName, ADAPTER_VERSION);
9183 openReqList.set(dbName, req);
9184
9185 req.onupgradeneeded = function (e) {
9186 var db = e.target.result;
9187 if (e.oldVersion < 1) {
9188 return createSchema(db); // new db, initial schema
9189 }
9190 // do migrations
9191
9192 var txn = e.currentTarget.transaction;
9193 // these migrations have to be done in this function, before
9194 // control is returned to the event loop, because IndexedDB
9195
9196 if (e.oldVersion < 3) {
9197 createLocalStoreSchema(db); // v2 -> v3
9198 }
9199 if (e.oldVersion < 4) {
9200 addAttachAndSeqStore(db); // v3 -> v4
9201 }
9202
9203 var migrations = [
9204 addDeletedOrLocalIndex, // v1 -> v2
9205 migrateLocalStore, // v2 -> v3
9206 migrateAttsAndSeqs, // v3 -> v4
9207 migrateMetadata // v4 -> v5
9208 ];
9209
9210 var i = e.oldVersion;
9211
9212 function next() {
9213 var migration = migrations[i - 1];
9214 i++;
9215 if (migration) {
9216 migration(txn, next);
9217 }
9218 }
9219
9220 next();
9221 };
9222
9223 req.onsuccess = function (e) {
9224
9225 idb = e.target.result;
9226
9227 idb.onversionchange = function () {
9228 idb.close();
9229 cachedDBs["delete"](dbName);
9230 };
9231
9232 idb.onabort = function (e) {
9233 guardedConsole('error', 'Database has a global failure', e.target.error);
9234 idbGlobalFailureError = e.target.error;
9235 idb.close();
9236 cachedDBs["delete"](dbName);
9237 };
9238
9239 // Do a few setup operations (in parallel as much as possible):
9240 // 1. Fetch meta doc
9241 // 2. Check blob support
9242 // 3. Calculate docCount
9243 // 4. Generate an instanceId if necessary
9244 // 5. Store docCount and instanceId on meta doc
9245
9246 var txn = idb.transaction([
9247 META_STORE,
9248 DETECT_BLOB_SUPPORT_STORE,
9249 DOC_STORE
9250 ], 'readwrite');
9251
9252 var storedMetaDoc = false;
9253 var metaDoc;
9254 var docCount;
9255 var blobSupport;
9256 var instanceId;
9257
9258 function completeSetup() {
9259 if (typeof blobSupport === 'undefined' || !storedMetaDoc) {
9260 return;
9261 }
9262 api._meta = {
9263 name: dbName,
9264 instanceId: instanceId,
9265 blobSupport: blobSupport
9266 };
9267
9268 cachedDBs.set(dbName, {
9269 idb: idb,
9270 global: api._meta
9271 });
9272 callback(null, api);
9273 }
9274
9275 function storeMetaDocIfReady() {
9276 if (typeof docCount === 'undefined' || typeof metaDoc === 'undefined') {
9277 return;
9278 }
9279 var instanceKey = dbName + '_id';
9280 if (instanceKey in metaDoc) {
9281 instanceId = metaDoc[instanceKey];
9282 } else {
9283 metaDoc[instanceKey] = instanceId = uuid$1();
9284 }
9285 metaDoc.docCount = docCount;
9286 txn.objectStore(META_STORE).put(metaDoc);
9287 }
9288
9289 //
9290 // fetch or generate the instanceId
9291 //
9292 txn.objectStore(META_STORE).get(META_STORE).onsuccess = function (e) {
9293 metaDoc = e.target.result || { id: META_STORE };
9294 storeMetaDocIfReady();
9295 };
9296
9297 //
9298 // countDocs
9299 //
9300 countDocs(txn, function (count) {
9301 docCount = count;
9302 storeMetaDocIfReady();
9303 });
9304
9305 //
9306 // check blob support
9307 //
9308 if (!blobSupportPromise) {
9309 // make sure blob support is only checked once
9310 blobSupportPromise = checkBlobSupport(txn);
9311 }
9312
9313 blobSupportPromise.then(function (val) {
9314 blobSupport = val;
9315 completeSetup();
9316 });
9317
9318 // only when the metadata put transaction has completed,
9319 // consider the setup done
9320 txn.oncomplete = function () {
9321 storedMetaDoc = true;
9322 completeSetup();
9323 };
9324 txn.onabort = idbError(callback);
9325 };
9326
9327 req.onerror = function (e) {
9328 var msg = e.target.error && e.target.error.message;
9329
9330 if (!msg) {
9331 msg = 'Failed to open indexedDB, are you in private browsing mode?';
9332 } else if (msg.indexOf("stored database is a higher version") !== -1) {
9333 msg = new Error('This DB was created with the newer "indexeddb" adapter, but you are trying to open it with the older "idb" adapter');
9334 }
9335
9336 guardedConsole('error', msg);
9337 callback(createError(IDB_ERROR, msg));
9338 };
9339}
9340
9341IdbPouch.valid = function () {
9342 // Following #7085 buggy idb versions (typically Safari < 10.1) are
9343 // considered valid.
9344
9345 // On Firefox SecurityError is thrown while referencing indexedDB if cookies
9346 // are not allowed. `typeof indexedDB` also triggers the error.
9347 try {
9348 // some outdated implementations of IDB that appear on Samsung
9349 // and HTC Android devices <4.4 are missing IDBKeyRange
9350 return typeof indexedDB !== 'undefined' && typeof IDBKeyRange !== 'undefined';
9351 } catch (e) {
9352 return false;
9353 }
9354};
9355
9356function IDBPouch (PouchDB) {
9357 PouchDB.adapter('idb', IdbPouch, true);
9358}
9359
9360// dead simple promise pool, inspired by https://github.com/timdp/es6-promise-pool
9361// but much smaller in code size. limits the number of concurrent promises that are executed
9362
9363
9364function pool(promiseFactories, limit) {
9365 return new Promise(function (resolve, reject) {
9366 var running = 0;
9367 var current = 0;
9368 var done = 0;
9369 var len = promiseFactories.length;
9370 var err;
9371
9372 function runNext() {
9373 running++;
9374 promiseFactories[current++]().then(onSuccess, onError);
9375 }
9376
9377 function doNext() {
9378 if (++done === len) {
9379 /* istanbul ignore if */
9380 if (err) {
9381 reject(err);
9382 } else {
9383 resolve();
9384 }
9385 } else {
9386 runNextBatch();
9387 }
9388 }
9389
9390 function onSuccess() {
9391 running--;
9392 doNext();
9393 }
9394
9395 /* istanbul ignore next */
9396 function onError(thisErr) {
9397 running--;
9398 err = err || thisErr;
9399 doNext();
9400 }
9401
9402 function runNextBatch() {
9403 while (running < limit && current < len) {
9404 runNext();
9405 }
9406 }
9407
9408 runNextBatch();
9409 });
9410}
9411
9412var CHANGES_BATCH_SIZE = 25;
9413var MAX_SIMULTANEOUS_REVS = 50;
9414var CHANGES_TIMEOUT_BUFFER = 5000;
9415var DEFAULT_HEARTBEAT = 10000;
9416
9417var supportsBulkGetMap = {};
9418
9419function readAttachmentsAsBlobOrBuffer(row) {
9420 var doc = row.doc || row.ok;
9421 var atts = doc && doc._attachments;
9422 if (!atts) {
9423 return;
9424 }
9425 Object.keys(atts).forEach(function (filename) {
9426 var att = atts[filename];
9427 att.data = b64ToBluffer(att.data, att.content_type);
9428 });
9429}
9430
9431function encodeDocId(id) {
9432 if (/^_design/.test(id)) {
9433 return '_design/' + encodeURIComponent(id.slice(8));
9434 }
9435 if (/^_local/.test(id)) {
9436 return '_local/' + encodeURIComponent(id.slice(7));
9437 }
9438 return encodeURIComponent(id);
9439}
9440
9441function preprocessAttachments$1(doc) {
9442 if (!doc._attachments || !Object.keys(doc._attachments)) {
9443 return Promise.resolve();
9444 }
9445
9446 return Promise.all(Object.keys(doc._attachments).map(function (key) {
9447 var attachment = doc._attachments[key];
9448 if (attachment.data && typeof attachment.data !== 'string') {
9449 return new Promise(function (resolve) {
9450 blobToBase64(attachment.data, resolve);
9451 }).then(function (b64) {
9452 attachment.data = b64;
9453 });
9454 }
9455 }));
9456}
9457
9458function hasUrlPrefix(opts) {
9459 if (!opts.prefix) {
9460 return false;
9461 }
9462 var protocol = parseUri(opts.prefix).protocol;
9463 return protocol === 'http' || protocol === 'https';
9464}
9465
9466// Get all the information you possibly can about the URI given by name and
9467// return it as a suitable object.
9468function getHost(name, opts) {
9469 // encode db name if opts.prefix is a url (#5574)
9470 if (hasUrlPrefix(opts)) {
9471 var dbName = opts.name.substr(opts.prefix.length);
9472 // Ensure prefix has a trailing slash
9473 var prefix = opts.prefix.replace(/\/?$/, '/');
9474 name = prefix + encodeURIComponent(dbName);
9475 }
9476
9477 var uri = parseUri(name);
9478 if (uri.user || uri.password) {
9479 uri.auth = {username: uri.user, password: uri.password};
9480 }
9481
9482 // Split the path part of the URI into parts using '/' as the delimiter
9483 // after removing any leading '/' and any trailing '/'
9484 var parts = uri.path.replace(/(^\/|\/$)/g, '').split('/');
9485
9486 uri.db = parts.pop();
9487 // Prevent double encoding of URI component
9488 if (uri.db.indexOf('%') === -1) {
9489 uri.db = encodeURIComponent(uri.db);
9490 }
9491
9492 uri.path = parts.join('/');
9493
9494 return uri;
9495}
9496
9497// Generate a URL with the host data given by opts and the given path
9498function genDBUrl(opts, path) {
9499 return genUrl(opts, opts.db + '/' + path);
9500}
9501
9502// Generate a URL with the host data given by opts and the given path
9503function genUrl(opts, path) {
9504 // If the host already has a path, then we need to have a path delimiter
9505 // Otherwise, the path delimiter is the empty string
9506 var pathDel = !opts.path ? '' : '/';
9507
9508 // If the host already has a path, then we need to have a path delimiter
9509 // Otherwise, the path delimiter is the empty string
9510 return opts.protocol + '://' + opts.host +
9511 (opts.port ? (':' + opts.port) : '') +
9512 '/' + opts.path + pathDel + path;
9513}
9514
9515function paramsToStr(params) {
9516 return '?' + Object.keys(params).map(function (k) {
9517 return k + '=' + encodeURIComponent(params[k]);
9518 }).join('&');
9519}
9520
9521function shouldCacheBust(opts) {
9522 var ua = (typeof navigator !== 'undefined' && navigator.userAgent) ?
9523 navigator.userAgent.toLowerCase() : '';
9524 var isIE = ua.indexOf('msie') !== -1;
9525 var isTrident = ua.indexOf('trident') !== -1;
9526 var isEdge = ua.indexOf('edge') !== -1;
9527 var isGET = !('method' in opts) || opts.method === 'GET';
9528 return (isIE || isTrident || isEdge) && isGET;
9529}
9530
9531// Implements the PouchDB API for dealing with CouchDB instances over HTTP
9532function HttpPouch(opts, callback) {
9533
9534 // The functions that will be publicly available for HttpPouch
9535 var api = this;
9536
9537 var host = getHost(opts.name, opts);
9538 var dbUrl = genDBUrl(host, '');
9539
9540 opts = clone(opts);
9541
9542 var ourFetch = function (url, options) {
9543
9544 options = options || {};
9545 options.headers = options.headers || new h();
9546
9547 options.credentials = 'include';
9548
9549 if (opts.auth || host.auth) {
9550 var nAuth = opts.auth || host.auth;
9551 var str = nAuth.username + ':' + nAuth.password;
9552 var token = thisBtoa(unescape(encodeURIComponent(str)));
9553 options.headers.set('Authorization', 'Basic ' + token);
9554 }
9555
9556 var headers = opts.headers || {};
9557 Object.keys(headers).forEach(function (key) {
9558 options.headers.append(key, headers[key]);
9559 });
9560
9561 /* istanbul ignore if */
9562 if (shouldCacheBust(options)) {
9563 url += (url.indexOf('?') === -1 ? '?' : '&') + '_nonce=' + Date.now();
9564 }
9565
9566 var fetchFun = opts.fetch || f$1;
9567 return fetchFun(url, options);
9568 };
9569
9570 function adapterFun$$1(name, fun) {
9571 return adapterFun(name, getArguments(function (args) {
9572 setup().then(function () {
9573 return fun.apply(this, args);
9574 })["catch"](function (e) {
9575 var callback = args.pop();
9576 callback(e);
9577 });
9578 })).bind(api);
9579 }
9580
9581 function fetchJSON(url, options, callback) {
9582
9583 var result = {};
9584
9585 options = options || {};
9586 options.headers = options.headers || new h();
9587
9588 if (!options.headers.get('Content-Type')) {
9589 options.headers.set('Content-Type', 'application/json');
9590 }
9591 if (!options.headers.get('Accept')) {
9592 options.headers.set('Accept', 'application/json');
9593 }
9594
9595 return ourFetch(url, options).then(function (response) {
9596 result.ok = response.ok;
9597 result.status = response.status;
9598 return response.json();
9599 }).then(function (json) {
9600 result.data = json;
9601 if (!result.ok) {
9602 result.data.status = result.status;
9603 var err = generateErrorFromResponse(result.data);
9604 if (callback) {
9605 return callback(err);
9606 } else {
9607 throw err;
9608 }
9609 }
9610
9611 if (Array.isArray(result.data)) {
9612 result.data = result.data.map(function (v) {
9613 if (v.error || v.missing) {
9614 return generateErrorFromResponse(v);
9615 } else {
9616 return v;
9617 }
9618 });
9619 }
9620
9621 if (callback) {
9622 callback(null, result.data);
9623 } else {
9624 return result;
9625 }
9626 });
9627 }
9628
9629 var setupPromise;
9630
9631 function setup() {
9632 if (opts.skip_setup) {
9633 return Promise.resolve();
9634 }
9635
9636 // If there is a setup in process or previous successful setup
9637 // done then we will use that
9638 // If previous setups have been rejected we will try again
9639 if (setupPromise) {
9640 return setupPromise;
9641 }
9642
9643 setupPromise = fetchJSON(dbUrl)["catch"](function (err) {
9644 if (err && err.status && err.status === 404) {
9645 // Doesnt exist, create it
9646 explainError(404, 'PouchDB is just detecting if the remote exists.');
9647 return fetchJSON(dbUrl, {method: 'PUT'});
9648 } else {
9649 return Promise.reject(err);
9650 }
9651 })["catch"](function (err) {
9652 // If we try to create a database that already exists, skipped in
9653 // istanbul since its catching a race condition.
9654 /* istanbul ignore if */
9655 if (err && err.status && err.status === 412) {
9656 return true;
9657 }
9658 return Promise.reject(err);
9659 });
9660
9661 setupPromise["catch"](function () {
9662 setupPromise = null;
9663 });
9664
9665 return setupPromise;
9666 }
9667
9668 immediate(function () {
9669 callback(null, api);
9670 });
9671
9672 api._remote = true;
9673
9674 /* istanbul ignore next */
9675 api.type = function () {
9676 return 'http';
9677 };
9678
9679 api.id = adapterFun$$1('id', function (callback) {
9680 ourFetch(genUrl(host, '')).then(function (response) {
9681 return response.json();
9682 })["catch"](function () {
9683 return {};
9684 }).then(function (result) {
9685 // Bad response or missing `uuid` should not prevent ID generation.
9686 var uuid$$1 = (result && result.uuid) ?
9687 (result.uuid + host.db) : genDBUrl(host, '');
9688 callback(null, uuid$$1);
9689 });
9690 });
9691
9692 // Sends a POST request to the host calling the couchdb _compact function
9693 // version: The version of CouchDB it is running
9694 api.compact = adapterFun$$1('compact', function (opts, callback) {
9695 if (typeof opts === 'function') {
9696 callback = opts;
9697 opts = {};
9698 }
9699 opts = clone(opts);
9700
9701 fetchJSON(genDBUrl(host, '_compact'), {method: 'POST'}).then(function () {
9702 function ping() {
9703 api.info(function (err, res) {
9704 // CouchDB may send a "compact_running:true" if it's
9705 // already compacting. PouchDB Server doesn't.
9706 /* istanbul ignore else */
9707 if (res && !res.compact_running) {
9708 callback(null, {ok: true});
9709 } else {
9710 setTimeout(ping, opts.interval || 200);
9711 }
9712 });
9713 }
9714 // Ping the http if it's finished compaction
9715 ping();
9716 });
9717 });
9718
9719 api.bulkGet = adapterFun('bulkGet', function (opts, callback) {
9720 var self = this;
9721
9722 function doBulkGet(cb) {
9723 var params = {};
9724 if (opts.revs) {
9725 params.revs = true;
9726 }
9727 if (opts.attachments) {
9728 /* istanbul ignore next */
9729 params.attachments = true;
9730 }
9731 if (opts.latest) {
9732 params.latest = true;
9733 }
9734 fetchJSON(genDBUrl(host, '_bulk_get' + paramsToStr(params)), {
9735 method: 'POST',
9736 body: JSON.stringify({ docs: opts.docs})
9737 }).then(function (result) {
9738 if (opts.attachments && opts.binary) {
9739 result.data.results.forEach(function (res) {
9740 res.docs.forEach(readAttachmentsAsBlobOrBuffer);
9741 });
9742 }
9743 cb(null, result.data);
9744 })["catch"](cb);
9745 }
9746
9747 /* istanbul ignore next */
9748 function doBulkGetShim() {
9749 // avoid "url too long error" by splitting up into multiple requests
9750 var batchSize = MAX_SIMULTANEOUS_REVS;
9751 var numBatches = Math.ceil(opts.docs.length / batchSize);
9752 var numDone = 0;
9753 var results = new Array(numBatches);
9754
9755 function onResult(batchNum) {
9756 return function (err, res) {
9757 // err is impossible because shim returns a list of errs in that case
9758 results[batchNum] = res.results;
9759 if (++numDone === numBatches) {
9760 callback(null, {results: flatten(results)});
9761 }
9762 };
9763 }
9764
9765 for (var i = 0; i < numBatches; i++) {
9766 var subOpts = pick(opts, ['revs', 'attachments', 'binary', 'latest']);
9767 subOpts.docs = opts.docs.slice(i * batchSize,
9768 Math.min(opts.docs.length, (i + 1) * batchSize));
9769 bulkGet(self, subOpts, onResult(i));
9770 }
9771 }
9772
9773 // mark the whole database as either supporting or not supporting _bulk_get
9774 var dbUrl = genUrl(host, '');
9775 var supportsBulkGet = supportsBulkGetMap[dbUrl];
9776
9777 /* istanbul ignore next */
9778 if (typeof supportsBulkGet !== 'boolean') {
9779 // check if this database supports _bulk_get
9780 doBulkGet(function (err, res) {
9781 if (err) {
9782 supportsBulkGetMap[dbUrl] = false;
9783 explainError(
9784 err.status,
9785 'PouchDB is just detecting if the remote ' +
9786 'supports the _bulk_get API.'
9787 );
9788 doBulkGetShim();
9789 } else {
9790 supportsBulkGetMap[dbUrl] = true;
9791 callback(null, res);
9792 }
9793 });
9794 } else if (supportsBulkGet) {
9795 doBulkGet(callback);
9796 } else {
9797 doBulkGetShim();
9798 }
9799 });
9800
9801 // Calls GET on the host, which gets back a JSON string containing
9802 // couchdb: A welcome string
9803 // version: The version of CouchDB it is running
9804 api._info = function (callback) {
9805 setup().then(function () {
9806 return ourFetch(genDBUrl(host, ''));
9807 }).then(function (response) {
9808 return response.json();
9809 }).then(function (info) {
9810 info.host = genDBUrl(host, '');
9811 callback(null, info);
9812 })["catch"](callback);
9813 };
9814
9815 api.fetch = function (path, options) {
9816 return setup().then(function () {
9817 var url = path.substring(0, 1) === '/' ?
9818 genUrl(host, path.substring(1)) :
9819 genDBUrl(host, path);
9820 return ourFetch(url, options);
9821 });
9822 };
9823
9824 // Get the document with the given id from the database given by host.
9825 // The id could be solely the _id in the database, or it may be a
9826 // _design/ID or _local/ID path
9827 api.get = adapterFun$$1('get', function (id, opts, callback) {
9828 // If no options were given, set the callback to the second parameter
9829 if (typeof opts === 'function') {
9830 callback = opts;
9831 opts = {};
9832 }
9833 opts = clone(opts);
9834
9835 // List of parameters to add to the GET request
9836 var params = {};
9837
9838 if (opts.revs) {
9839 params.revs = true;
9840 }
9841
9842 if (opts.revs_info) {
9843 params.revs_info = true;
9844 }
9845
9846 if (opts.latest) {
9847 params.latest = true;
9848 }
9849
9850 if (opts.open_revs) {
9851 if (opts.open_revs !== "all") {
9852 opts.open_revs = JSON.stringify(opts.open_revs);
9853 }
9854 params.open_revs = opts.open_revs;
9855 }
9856
9857 if (opts.rev) {
9858 params.rev = opts.rev;
9859 }
9860
9861 if (opts.conflicts) {
9862 params.conflicts = opts.conflicts;
9863 }
9864
9865 /* istanbul ignore if */
9866 if (opts.update_seq) {
9867 params.update_seq = opts.update_seq;
9868 }
9869
9870 id = encodeDocId(id);
9871
9872 function fetchAttachments(doc) {
9873 var atts = doc._attachments;
9874 var filenames = atts && Object.keys(atts);
9875 if (!atts || !filenames.length) {
9876 return;
9877 }
9878 // we fetch these manually in separate XHRs, because
9879 // Sync Gateway would normally send it back as multipart/mixed,
9880 // which we cannot parse. Also, this is more efficient than
9881 // receiving attachments as base64-encoded strings.
9882 function fetchData(filename) {
9883 var att = atts[filename];
9884 var path = encodeDocId(doc._id) + '/' + encodeAttachmentId(filename) +
9885 '?rev=' + doc._rev;
9886 return ourFetch(genDBUrl(host, path)).then(function (response) {
9887 if ('buffer' in response) {
9888 return response.buffer();
9889 } else {
9890 /* istanbul ignore next */
9891 return response.blob();
9892 }
9893 }).then(function (blob) {
9894 if (opts.binary) {
9895 var typeFieldDescriptor = Object.getOwnPropertyDescriptor(blob.__proto__, 'type');
9896 if (!typeFieldDescriptor || typeFieldDescriptor.set) {
9897 blob.type = att.content_type;
9898 }
9899 return blob;
9900 }
9901 return new Promise(function (resolve) {
9902 blobToBase64(blob, resolve);
9903 });
9904 }).then(function (data) {
9905 delete att.stub;
9906 delete att.length;
9907 att.data = data;
9908 });
9909 }
9910
9911 var promiseFactories = filenames.map(function (filename) {
9912 return function () {
9913 return fetchData(filename);
9914 };
9915 });
9916
9917 // This limits the number of parallel xhr requests to 5 any time
9918 // to avoid issues with maximum browser request limits
9919 return pool(promiseFactories, 5);
9920 }
9921
9922 function fetchAllAttachments(docOrDocs) {
9923 if (Array.isArray(docOrDocs)) {
9924 return Promise.all(docOrDocs.map(function (doc) {
9925 if (doc.ok) {
9926 return fetchAttachments(doc.ok);
9927 }
9928 }));
9929 }
9930 return fetchAttachments(docOrDocs);
9931 }
9932
9933 var url = genDBUrl(host, id + paramsToStr(params));
9934 fetchJSON(url).then(function (res) {
9935 return Promise.resolve().then(function () {
9936 if (opts.attachments) {
9937 return fetchAllAttachments(res.data);
9938 }
9939 }).then(function () {
9940 callback(null, res.data);
9941 });
9942 })["catch"](function (e) {
9943 e.docId = id;
9944 callback(e);
9945 });
9946 });
9947
9948
9949 // Delete the document given by doc from the database given by host.
9950 api.remove = adapterFun$$1('remove', function (docOrId, optsOrRev, opts, cb) {
9951 var doc;
9952 if (typeof optsOrRev === 'string') {
9953 // id, rev, opts, callback style
9954 doc = {
9955 _id: docOrId,
9956 _rev: optsOrRev
9957 };
9958 if (typeof opts === 'function') {
9959 cb = opts;
9960 opts = {};
9961 }
9962 } else {
9963 // doc, opts, callback style
9964 doc = docOrId;
9965 if (typeof optsOrRev === 'function') {
9966 cb = optsOrRev;
9967 opts = {};
9968 } else {
9969 cb = opts;
9970 opts = optsOrRev;
9971 }
9972 }
9973
9974 var rev = (doc._rev || opts.rev);
9975 var url = genDBUrl(host, encodeDocId(doc._id)) + '?rev=' + rev;
9976
9977 fetchJSON(url, {method: 'DELETE'}, cb)["catch"](cb);
9978 });
9979
9980 function encodeAttachmentId(attachmentId) {
9981 return attachmentId.split("/").map(encodeURIComponent).join("/");
9982 }
9983
9984 // Get the attachment
9985 api.getAttachment = adapterFun$$1('getAttachment', function (docId, attachmentId,
9986 opts, callback) {
9987 if (typeof opts === 'function') {
9988 callback = opts;
9989 opts = {};
9990 }
9991 var params = opts.rev ? ('?rev=' + opts.rev) : '';
9992 var url = genDBUrl(host, encodeDocId(docId)) + '/' +
9993 encodeAttachmentId(attachmentId) + params;
9994 var contentType;
9995 ourFetch(url, {method: 'GET'}).then(function (response) {
9996 contentType = response.headers.get('content-type');
9997 if (!response.ok) {
9998 throw response;
9999 } else {
10000 if (typeof process !== 'undefined' && !process.browser && typeof response.buffer === 'function') {
10001 return response.buffer();
10002 } else {
10003 /* istanbul ignore next */
10004 return response.blob();
10005 }
10006 }
10007 }).then(function (blob) {
10008 // TODO: also remove
10009 if (typeof process !== 'undefined' && !process.browser) {
10010 blob.type = contentType;
10011 }
10012 callback(null, blob);
10013 })["catch"](function (err) {
10014 callback(err);
10015 });
10016 });
10017
10018 // Remove the attachment given by the id and rev
10019 api.removeAttachment = adapterFun$$1('removeAttachment', function (docId,
10020 attachmentId,
10021 rev,
10022 callback) {
10023 var url = genDBUrl(host, encodeDocId(docId) + '/' +
10024 encodeAttachmentId(attachmentId)) + '?rev=' + rev;
10025 fetchJSON(url, {method: 'DELETE'}, callback)["catch"](callback);
10026 });
10027
10028 // Add the attachment given by blob and its contentType property
10029 // to the document with the given id, the revision given by rev, and
10030 // add it to the database given by host.
10031 api.putAttachment = adapterFun$$1('putAttachment', function (docId, attachmentId,
10032 rev, blob,
10033 type, callback) {
10034 if (typeof type === 'function') {
10035 callback = type;
10036 type = blob;
10037 blob = rev;
10038 rev = null;
10039 }
10040 var id = encodeDocId(docId) + '/' + encodeAttachmentId(attachmentId);
10041 var url = genDBUrl(host, id);
10042 if (rev) {
10043 url += '?rev=' + rev;
10044 }
10045
10046 if (typeof blob === 'string') {
10047 // input is assumed to be a base64 string
10048 var binary;
10049 try {
10050 binary = thisAtob(blob);
10051 } catch (err) {
10052 return callback(createError(BAD_ARG,
10053 'Attachment is not a valid base64 string'));
10054 }
10055 blob = binary ? binStringToBluffer(binary, type) : '';
10056 }
10057
10058 // Add the attachment
10059 fetchJSON(url, {
10060 headers: new h({'Content-Type': type}),
10061 method: 'PUT',
10062 body: blob
10063 }, callback)["catch"](callback);
10064 });
10065
10066 // Update/create multiple documents given by req in the database
10067 // given by host.
10068 api._bulkDocs = function (req, opts, callback) {
10069 // If new_edits=false then it prevents the database from creating
10070 // new revision numbers for the documents. Instead it just uses
10071 // the old ones. This is used in database replication.
10072 req.new_edits = opts.new_edits;
10073
10074 setup().then(function () {
10075 return Promise.all(req.docs.map(preprocessAttachments$1));
10076 }).then(function () {
10077 // Update/create the documents
10078 return fetchJSON(genDBUrl(host, '_bulk_docs'), {
10079 method: 'POST',
10080 body: JSON.stringify(req)
10081 }, callback);
10082 })["catch"](callback);
10083 };
10084
10085
10086 // Update/create document
10087 api._put = function (doc, opts, callback) {
10088 setup().then(function () {
10089 return preprocessAttachments$1(doc);
10090 }).then(function () {
10091 return fetchJSON(genDBUrl(host, encodeDocId(doc._id)), {
10092 method: 'PUT',
10093 body: JSON.stringify(doc)
10094 });
10095 }).then(function (result) {
10096 callback(null, result.data);
10097 })["catch"](function (err) {
10098 err.docId = doc && doc._id;
10099 callback(err);
10100 });
10101 };
10102
10103
10104 // Get a listing of the documents in the database given
10105 // by host and ordered by increasing id.
10106 api.allDocs = adapterFun$$1('allDocs', function (opts, callback) {
10107 if (typeof opts === 'function') {
10108 callback = opts;
10109 opts = {};
10110 }
10111 opts = clone(opts);
10112
10113 // List of parameters to add to the GET request
10114 var params = {};
10115 var body;
10116 var method = 'GET';
10117
10118 if (opts.conflicts) {
10119 params.conflicts = true;
10120 }
10121
10122 /* istanbul ignore if */
10123 if (opts.update_seq) {
10124 params.update_seq = true;
10125 }
10126
10127 if (opts.descending) {
10128 params.descending = true;
10129 }
10130
10131 if (opts.include_docs) {
10132 params.include_docs = true;
10133 }
10134
10135 // added in CouchDB 1.6.0
10136 if (opts.attachments) {
10137 params.attachments = true;
10138 }
10139
10140 if (opts.key) {
10141 params.key = JSON.stringify(opts.key);
10142 }
10143
10144 if (opts.start_key) {
10145 opts.startkey = opts.start_key;
10146 }
10147
10148 if (opts.startkey) {
10149 params.startkey = JSON.stringify(opts.startkey);
10150 }
10151
10152 if (opts.end_key) {
10153 opts.endkey = opts.end_key;
10154 }
10155
10156 if (opts.endkey) {
10157 params.endkey = JSON.stringify(opts.endkey);
10158 }
10159
10160 if (typeof opts.inclusive_end !== 'undefined') {
10161 params.inclusive_end = !!opts.inclusive_end;
10162 }
10163
10164 if (typeof opts.limit !== 'undefined') {
10165 params.limit = opts.limit;
10166 }
10167
10168 if (typeof opts.skip !== 'undefined') {
10169 params.skip = opts.skip;
10170 }
10171
10172 var paramStr = paramsToStr(params);
10173
10174 if (typeof opts.keys !== 'undefined') {
10175 method = 'POST';
10176 body = {keys: opts.keys};
10177 }
10178
10179 fetchJSON(genDBUrl(host, '_all_docs' + paramStr), {
10180 method: method,
10181 body: JSON.stringify(body)
10182 }).then(function (result) {
10183 if (opts.include_docs && opts.attachments && opts.binary) {
10184 result.data.rows.forEach(readAttachmentsAsBlobOrBuffer);
10185 }
10186 callback(null, result.data);
10187 })["catch"](callback);
10188 });
10189
10190 // Get a list of changes made to documents in the database given by host.
10191 // TODO According to the README, there should be two other methods here,
10192 // api.changes.addListener and api.changes.removeListener.
10193 api._changes = function (opts) {
10194
10195 // We internally page the results of a changes request, this means
10196 // if there is a large set of changes to be returned we can start
10197 // processing them quicker instead of waiting on the entire
10198 // set of changes to return and attempting to process them at once
10199 var batchSize = 'batch_size' in opts ? opts.batch_size : CHANGES_BATCH_SIZE;
10200
10201 opts = clone(opts);
10202
10203 if (opts.continuous && !('heartbeat' in opts)) {
10204 opts.heartbeat = DEFAULT_HEARTBEAT;
10205 }
10206
10207 var requestTimeout = ('timeout' in opts) ? opts.timeout : 30 * 1000;
10208
10209 // ensure CHANGES_TIMEOUT_BUFFER applies
10210 if ('timeout' in opts && opts.timeout &&
10211 (requestTimeout - opts.timeout) < CHANGES_TIMEOUT_BUFFER) {
10212 requestTimeout = opts.timeout + CHANGES_TIMEOUT_BUFFER;
10213 }
10214
10215 /* istanbul ignore if */
10216 if ('heartbeat' in opts && opts.heartbeat &&
10217 (requestTimeout - opts.heartbeat) < CHANGES_TIMEOUT_BUFFER) {
10218 requestTimeout = opts.heartbeat + CHANGES_TIMEOUT_BUFFER;
10219 }
10220
10221 var params = {};
10222 if ('timeout' in opts && opts.timeout) {
10223 params.timeout = opts.timeout;
10224 }
10225
10226 var limit = (typeof opts.limit !== 'undefined') ? opts.limit : false;
10227 var leftToFetch = limit;
10228
10229 if (opts.style) {
10230 params.style = opts.style;
10231 }
10232
10233 if (opts.include_docs || opts.filter && typeof opts.filter === 'function') {
10234 params.include_docs = true;
10235 }
10236
10237 if (opts.attachments) {
10238 params.attachments = true;
10239 }
10240
10241 if (opts.continuous) {
10242 params.feed = 'longpoll';
10243 }
10244
10245 if (opts.seq_interval) {
10246 params.seq_interval = opts.seq_interval;
10247 }
10248
10249 if (opts.conflicts) {
10250 params.conflicts = true;
10251 }
10252
10253 if (opts.descending) {
10254 params.descending = true;
10255 }
10256
10257 /* istanbul ignore if */
10258 if (opts.update_seq) {
10259 params.update_seq = true;
10260 }
10261
10262 if ('heartbeat' in opts) {
10263 // If the heartbeat value is false, it disables the default heartbeat
10264 if (opts.heartbeat) {
10265 params.heartbeat = opts.heartbeat;
10266 }
10267 }
10268
10269 if (opts.filter && typeof opts.filter === 'string') {
10270 params.filter = opts.filter;
10271 }
10272
10273 if (opts.view && typeof opts.view === 'string') {
10274 params.filter = '_view';
10275 params.view = opts.view;
10276 }
10277
10278 // If opts.query_params exists, pass it through to the changes request.
10279 // These parameters may be used by the filter on the source database.
10280 if (opts.query_params && typeof opts.query_params === 'object') {
10281 for (var param_name in opts.query_params) {
10282 /* istanbul ignore else */
10283 if (Object.prototype.hasOwnProperty.call(opts.query_params, param_name)) {
10284 params[param_name] = opts.query_params[param_name];
10285 }
10286 }
10287 }
10288
10289 var method = 'GET';
10290 var body;
10291
10292 if (opts.doc_ids) {
10293 // set this automagically for the user; it's annoying that couchdb
10294 // requires both a "filter" and a "doc_ids" param.
10295 params.filter = '_doc_ids';
10296 method = 'POST';
10297 body = {doc_ids: opts.doc_ids };
10298 }
10299 /* istanbul ignore next */
10300 else if (opts.selector) {
10301 // set this automagically for the user, similar to above
10302 params.filter = '_selector';
10303 method = 'POST';
10304 body = {selector: opts.selector };
10305 }
10306
10307 var controller = new a();
10308 var lastFetchedSeq;
10309
10310 // Get all the changes starting wtih the one immediately after the
10311 // sequence number given by since.
10312 var fetchData = function (since, callback) {
10313 if (opts.aborted) {
10314 return;
10315 }
10316 params.since = since;
10317 // "since" can be any kind of json object in Cloudant/CouchDB 2.x
10318 /* istanbul ignore next */
10319 if (typeof params.since === "object") {
10320 params.since = JSON.stringify(params.since);
10321 }
10322
10323 if (opts.descending) {
10324 if (limit) {
10325 params.limit = leftToFetch;
10326 }
10327 } else {
10328 params.limit = (!limit || leftToFetch > batchSize) ?
10329 batchSize : leftToFetch;
10330 }
10331
10332 // Set the options for the ajax call
10333 var url = genDBUrl(host, '_changes' + paramsToStr(params));
10334 var fetchOpts = {
10335 signal: controller.signal,
10336 method: method,
10337 body: JSON.stringify(body)
10338 };
10339 lastFetchedSeq = since;
10340
10341 /* istanbul ignore if */
10342 if (opts.aborted) {
10343 return;
10344 }
10345
10346 // Get the changes
10347 setup().then(function () {
10348 return fetchJSON(url, fetchOpts, callback);
10349 })["catch"](callback);
10350 };
10351
10352 // If opts.since exists, get all the changes from the sequence
10353 // number given by opts.since. Otherwise, get all the changes
10354 // from the sequence number 0.
10355 var results = {results: []};
10356
10357 var fetched = function (err, res) {
10358 if (opts.aborted) {
10359 return;
10360 }
10361 var raw_results_length = 0;
10362 // If the result of the ajax call (res) contains changes (res.results)
10363 if (res && res.results) {
10364 raw_results_length = res.results.length;
10365 results.last_seq = res.last_seq;
10366 var pending = null;
10367 var lastSeq = null;
10368 // Attach 'pending' property if server supports it (CouchDB 2.0+)
10369 /* istanbul ignore if */
10370 if (typeof res.pending === 'number') {
10371 pending = res.pending;
10372 }
10373 if (typeof results.last_seq === 'string' || typeof results.last_seq === 'number') {
10374 lastSeq = results.last_seq;
10375 }
10376 // For each change
10377 var req = {};
10378 req.query = opts.query_params;
10379 res.results = res.results.filter(function (c) {
10380 leftToFetch--;
10381 var ret = filterChange(opts)(c);
10382 if (ret) {
10383 if (opts.include_docs && opts.attachments && opts.binary) {
10384 readAttachmentsAsBlobOrBuffer(c);
10385 }
10386 if (opts.return_docs) {
10387 results.results.push(c);
10388 }
10389 opts.onChange(c, pending, lastSeq);
10390 }
10391 return ret;
10392 });
10393 } else if (err) {
10394 // In case of an error, stop listening for changes and call
10395 // opts.complete
10396 opts.aborted = true;
10397 opts.complete(err);
10398 return;
10399 }
10400
10401 // The changes feed may have timed out with no results
10402 // if so reuse last update sequence
10403 if (res && res.last_seq) {
10404 lastFetchedSeq = res.last_seq;
10405 }
10406
10407 var finished = (limit && leftToFetch <= 0) ||
10408 (res && raw_results_length < batchSize) ||
10409 (opts.descending);
10410
10411 if ((opts.continuous && !(limit && leftToFetch <= 0)) || !finished) {
10412 // Queue a call to fetch again with the newest sequence number
10413 immediate(function () { fetchData(lastFetchedSeq, fetched); });
10414 } else {
10415 // We're done, call the callback
10416 opts.complete(null, results);
10417 }
10418 };
10419
10420 fetchData(opts.since || 0, fetched);
10421
10422 // Return a method to cancel this method from processing any more
10423 return {
10424 cancel: function () {
10425 opts.aborted = true;
10426 controller.abort();
10427 }
10428 };
10429 };
10430
10431 // Given a set of document/revision IDs (given by req), tets the subset of
10432 // those that do NOT correspond to revisions stored in the database.
10433 // See http://wiki.apache.org/couchdb/HttpPostRevsDiff
10434 api.revsDiff = adapterFun$$1('revsDiff', function (req, opts, callback) {
10435 // If no options were given, set the callback to be the second parameter
10436 if (typeof opts === 'function') {
10437 callback = opts;
10438 opts = {};
10439 }
10440
10441 // Get the missing document/revision IDs
10442 fetchJSON(genDBUrl(host, '_revs_diff'), {
10443 method: 'POST',
10444 body: JSON.stringify(req)
10445 }, callback)["catch"](callback);
10446 });
10447
10448 api._close = function (callback) {
10449 callback();
10450 };
10451
10452 api._destroy = function (options, callback) {
10453 fetchJSON(genDBUrl(host, ''), {method: 'DELETE'}).then(function (json) {
10454 callback(null, json);
10455 })["catch"](function (err) {
10456 /* istanbul ignore if */
10457 if (err.status === 404) {
10458 callback(null, {ok: true});
10459 } else {
10460 callback(err);
10461 }
10462 });
10463 };
10464}
10465
10466// HttpPouch is a valid adapter.
10467HttpPouch.valid = function () {
10468 return true;
10469};
10470
10471function HttpPouch$1 (PouchDB) {
10472 PouchDB.adapter('http', HttpPouch, false);
10473 PouchDB.adapter('https', HttpPouch, false);
10474}
10475
10476function QueryParseError(message) {
10477 this.status = 400;
10478 this.name = 'query_parse_error';
10479 this.message = message;
10480 this.error = true;
10481 try {
10482 Error.captureStackTrace(this, QueryParseError);
10483 } catch (e) {}
10484}
10485
10486inherits(QueryParseError, Error);
10487
10488function NotFoundError(message) {
10489 this.status = 404;
10490 this.name = 'not_found';
10491 this.message = message;
10492 this.error = true;
10493 try {
10494 Error.captureStackTrace(this, NotFoundError);
10495 } catch (e) {}
10496}
10497
10498inherits(NotFoundError, Error);
10499
10500function BuiltInError(message) {
10501 this.status = 500;
10502 this.name = 'invalid_value';
10503 this.message = message;
10504 this.error = true;
10505 try {
10506 Error.captureStackTrace(this, BuiltInError);
10507 } catch (e) {}
10508}
10509
10510inherits(BuiltInError, Error);
10511
10512function promisedCallback(promise, callback) {
10513 if (callback) {
10514 promise.then(function (res) {
10515 immediate(function () {
10516 callback(null, res);
10517 });
10518 }, function (reason) {
10519 immediate(function () {
10520 callback(reason);
10521 });
10522 });
10523 }
10524 return promise;
10525}
10526
10527function callbackify(fun) {
10528 return getArguments(function (args) {
10529 var cb = args.pop();
10530 var promise = fun.apply(this, args);
10531 if (typeof cb === 'function') {
10532 promisedCallback(promise, cb);
10533 }
10534 return promise;
10535 });
10536}
10537
10538// Promise finally util similar to Q.finally
10539function fin(promise, finalPromiseFactory) {
10540 return promise.then(function (res) {
10541 return finalPromiseFactory().then(function () {
10542 return res;
10543 });
10544 }, function (reason) {
10545 return finalPromiseFactory().then(function () {
10546 throw reason;
10547 });
10548 });
10549}
10550
10551function sequentialize(queue, promiseFactory) {
10552 return function () {
10553 var args = arguments;
10554 var that = this;
10555 return queue.add(function () {
10556 return promiseFactory.apply(that, args);
10557 });
10558 };
10559}
10560
10561// uniq an array of strings, order not guaranteed
10562// similar to underscore/lodash _.uniq
10563function uniq(arr) {
10564 var theSet = new ExportedSet(arr);
10565 var result = new Array(theSet.size);
10566 var index = -1;
10567 theSet.forEach(function (value) {
10568 result[++index] = value;
10569 });
10570 return result;
10571}
10572
10573function mapToKeysArray(map) {
10574 var result = new Array(map.size);
10575 var index = -1;
10576 map.forEach(function (value, key) {
10577 result[++index] = key;
10578 });
10579 return result;
10580}
10581
10582function createBuiltInError(name) {
10583 var message = 'builtin ' + name +
10584 ' function requires map values to be numbers' +
10585 ' or number arrays';
10586 return new BuiltInError(message);
10587}
10588
10589function sum(values) {
10590 var result = 0;
10591 for (var i = 0, len = values.length; i < len; i++) {
10592 var num = values[i];
10593 if (typeof num !== 'number') {
10594 if (Array.isArray(num)) {
10595 // lists of numbers are also allowed, sum them separately
10596 result = typeof result === 'number' ? [result] : result;
10597 for (var j = 0, jLen = num.length; j < jLen; j++) {
10598 var jNum = num[j];
10599 if (typeof jNum !== 'number') {
10600 throw createBuiltInError('_sum');
10601 } else if (typeof result[j] === 'undefined') {
10602 result.push(jNum);
10603 } else {
10604 result[j] += jNum;
10605 }
10606 }
10607 } else { // not array/number
10608 throw createBuiltInError('_sum');
10609 }
10610 } else if (typeof result === 'number') {
10611 result += num;
10612 } else { // add number to array
10613 result[0] += num;
10614 }
10615 }
10616 return result;
10617}
10618
10619var log = guardedConsole.bind(null, 'log');
10620var isArray = Array.isArray;
10621var toJSON = JSON.parse;
10622
10623function evalFunctionWithEval(func, emit) {
10624 return scopeEval(
10625 "return (" + func.replace(/;\s*$/, "") + ");",
10626 {
10627 emit: emit,
10628 sum: sum,
10629 log: log,
10630 isArray: isArray,
10631 toJSON: toJSON
10632 }
10633 );
10634}
10635
10636/*
10637 * Simple task queue to sequentialize actions. Assumes
10638 * callbacks will eventually fire (once).
10639 */
10640
10641
10642function TaskQueue$1() {
10643 this.promise = new Promise(function (fulfill) {fulfill(); });
10644}
10645TaskQueue$1.prototype.add = function (promiseFactory) {
10646 this.promise = this.promise["catch"](function () {
10647 // just recover
10648 }).then(function () {
10649 return promiseFactory();
10650 });
10651 return this.promise;
10652};
10653TaskQueue$1.prototype.finish = function () {
10654 return this.promise;
10655};
10656
10657function stringify(input) {
10658 if (!input) {
10659 return 'undefined'; // backwards compat for empty reduce
10660 }
10661 // for backwards compat with mapreduce, functions/strings are stringified
10662 // as-is. everything else is JSON-stringified.
10663 switch (typeof input) {
10664 case 'function':
10665 // e.g. a mapreduce map
10666 return input.toString();
10667 case 'string':
10668 // e.g. a mapreduce built-in _reduce function
10669 return input.toString();
10670 default:
10671 // e.g. a JSON object in the case of mango queries
10672 return JSON.stringify(input);
10673 }
10674}
10675
10676/* create a string signature for a view so we can cache it and uniq it */
10677function createViewSignature(mapFun, reduceFun) {
10678 // the "undefined" part is for backwards compatibility
10679 return stringify(mapFun) + stringify(reduceFun) + 'undefined';
10680}
10681
10682function createView(sourceDB, viewName, mapFun, reduceFun, temporary, localDocName) {
10683 var viewSignature = createViewSignature(mapFun, reduceFun);
10684
10685 var cachedViews;
10686 if (!temporary) {
10687 // cache this to ensure we don't try to update the same view twice
10688 cachedViews = sourceDB._cachedViews = sourceDB._cachedViews || {};
10689 if (cachedViews[viewSignature]) {
10690 return cachedViews[viewSignature];
10691 }
10692 }
10693
10694 var promiseForView = sourceDB.info().then(function (info) {
10695
10696 var depDbName = info.db_name + '-mrview-' +
10697 (temporary ? 'temp' : stringMd5(viewSignature));
10698
10699 // save the view name in the source db so it can be cleaned up if necessary
10700 // (e.g. when the _design doc is deleted, remove all associated view data)
10701 function diffFunction(doc) {
10702 doc.views = doc.views || {};
10703 var fullViewName = viewName;
10704 if (fullViewName.indexOf('/') === -1) {
10705 fullViewName = viewName + '/' + viewName;
10706 }
10707 var depDbs = doc.views[fullViewName] = doc.views[fullViewName] || {};
10708 /* istanbul ignore if */
10709 if (depDbs[depDbName]) {
10710 return; // no update necessary
10711 }
10712 depDbs[depDbName] = true;
10713 return doc;
10714 }
10715 return upsert(sourceDB, '_local/' + localDocName, diffFunction).then(function () {
10716 return sourceDB.registerDependentDatabase(depDbName).then(function (res) {
10717 var db = res.db;
10718 db.auto_compaction = true;
10719 var view = {
10720 name: depDbName,
10721 db: db,
10722 sourceDB: sourceDB,
10723 adapter: sourceDB.adapter,
10724 mapFun: mapFun,
10725 reduceFun: reduceFun
10726 };
10727 return view.db.get('_local/lastSeq')["catch"](function (err) {
10728 /* istanbul ignore if */
10729 if (err.status !== 404) {
10730 throw err;
10731 }
10732 }).then(function (lastSeqDoc) {
10733 view.seq = lastSeqDoc ? lastSeqDoc.seq : 0;
10734 if (cachedViews) {
10735 view.db.once('destroyed', function () {
10736 delete cachedViews[viewSignature];
10737 });
10738 }
10739 return view;
10740 });
10741 });
10742 });
10743 });
10744
10745 if (cachedViews) {
10746 cachedViews[viewSignature] = promiseForView;
10747 }
10748 return promiseForView;
10749}
10750
10751var persistentQueues = {};
10752var tempViewQueue = new TaskQueue$1();
10753var CHANGES_BATCH_SIZE$1 = 50;
10754
10755function parseViewName(name) {
10756 // can be either 'ddocname/viewname' or just 'viewname'
10757 // (where the ddoc name is the same)
10758 return name.indexOf('/') === -1 ? [name, name] : name.split('/');
10759}
10760
10761function isGenOne(changes) {
10762 // only return true if the current change is 1-
10763 // and there are no other leafs
10764 return changes.length === 1 && /^1-/.test(changes[0].rev);
10765}
10766
10767function emitError(db, e) {
10768 try {
10769 db.emit('error', e);
10770 } catch (err) {
10771 guardedConsole('error',
10772 'The user\'s map/reduce function threw an uncaught error.\n' +
10773 'You can debug this error by doing:\n' +
10774 'myDatabase.on(\'error\', function (err) { debugger; });\n' +
10775 'Please double-check your map/reduce function.');
10776 guardedConsole('error', e);
10777 }
10778}
10779
10780/**
10781 * Returns an "abstract" mapreduce object of the form:
10782 *
10783 * {
10784 * query: queryFun,
10785 * viewCleanup: viewCleanupFun
10786 * }
10787 *
10788 * Arguments are:
10789 *
10790 * localDoc: string
10791 * This is for the local doc that gets saved in order to track the
10792 * "dependent" DBs and clean them up for viewCleanup. It should be
10793 * unique, so that indexer plugins don't collide with each other.
10794 * mapper: function (mapFunDef, emit)
10795 * Returns a map function based on the mapFunDef, which in the case of
10796 * normal map/reduce is just the de-stringified function, but may be
10797 * something else, such as an object in the case of pouchdb-find.
10798 * reducer: function (reduceFunDef)
10799 * Ditto, but for reducing. Modules don't have to support reducing
10800 * (e.g. pouchdb-find).
10801 * ddocValidator: function (ddoc, viewName)
10802 * Throws an error if the ddoc or viewName is not valid.
10803 * This could be a way to communicate to the user that the configuration for the
10804 * indexer is invalid.
10805 */
10806function createAbstractMapReduce(localDocName, mapper, reducer, ddocValidator) {
10807
10808 function tryMap(db, fun, doc) {
10809 // emit an event if there was an error thrown by a map function.
10810 // putting try/catches in a single function also avoids deoptimizations.
10811 try {
10812 fun(doc);
10813 } catch (e) {
10814 emitError(db, e);
10815 }
10816 }
10817
10818 function tryReduce(db, fun, keys, values, rereduce) {
10819 // same as above, but returning the result or an error. there are two separate
10820 // functions to avoid extra memory allocations since the tryCode() case is used
10821 // for custom map functions (common) vs this function, which is only used for
10822 // custom reduce functions (rare)
10823 try {
10824 return {output : fun(keys, values, rereduce)};
10825 } catch (e) {
10826 emitError(db, e);
10827 return {error: e};
10828 }
10829 }
10830
10831 function sortByKeyThenValue(x, y) {
10832 var keyCompare = collate(x.key, y.key);
10833 return keyCompare !== 0 ? keyCompare : collate(x.value, y.value);
10834 }
10835
10836 function sliceResults(results, limit, skip) {
10837 skip = skip || 0;
10838 if (typeof limit === 'number') {
10839 return results.slice(skip, limit + skip);
10840 } else if (skip > 0) {
10841 return results.slice(skip);
10842 }
10843 return results;
10844 }
10845
10846 function rowToDocId(row) {
10847 var val = row.value;
10848 // Users can explicitly specify a joined doc _id, or it
10849 // defaults to the doc _id that emitted the key/value.
10850 var docId = (val && typeof val === 'object' && val._id) || row.id;
10851 return docId;
10852 }
10853
10854 function readAttachmentsAsBlobOrBuffer(res) {
10855 res.rows.forEach(function (row) {
10856 var atts = row.doc && row.doc._attachments;
10857 if (!atts) {
10858 return;
10859 }
10860 Object.keys(atts).forEach(function (filename) {
10861 var att = atts[filename];
10862 atts[filename].data = b64ToBluffer(att.data, att.content_type);
10863 });
10864 });
10865 }
10866
10867 function postprocessAttachments(opts) {
10868 return function (res) {
10869 if (opts.include_docs && opts.attachments && opts.binary) {
10870 readAttachmentsAsBlobOrBuffer(res);
10871 }
10872 return res;
10873 };
10874 }
10875
10876 function addHttpParam(paramName, opts, params, asJson) {
10877 // add an http param from opts to params, optionally json-encoded
10878 var val = opts[paramName];
10879 if (typeof val !== 'undefined') {
10880 if (asJson) {
10881 val = encodeURIComponent(JSON.stringify(val));
10882 }
10883 params.push(paramName + '=' + val);
10884 }
10885 }
10886
10887 function coerceInteger(integerCandidate) {
10888 if (typeof integerCandidate !== 'undefined') {
10889 var asNumber = Number(integerCandidate);
10890 // prevents e.g. '1foo' or '1.1' being coerced to 1
10891 if (!isNaN(asNumber) && asNumber === parseInt(integerCandidate, 10)) {
10892 return asNumber;
10893 } else {
10894 return integerCandidate;
10895 }
10896 }
10897 }
10898
10899 function coerceOptions(opts) {
10900 opts.group_level = coerceInteger(opts.group_level);
10901 opts.limit = coerceInteger(opts.limit);
10902 opts.skip = coerceInteger(opts.skip);
10903 return opts;
10904 }
10905
10906 function checkPositiveInteger(number) {
10907 if (number) {
10908 if (typeof number !== 'number') {
10909 return new QueryParseError('Invalid value for integer: "' +
10910 number + '"');
10911 }
10912 if (number < 0) {
10913 return new QueryParseError('Invalid value for positive integer: ' +
10914 '"' + number + '"');
10915 }
10916 }
10917 }
10918
10919 function checkQueryParseError(options, fun) {
10920 var startkeyName = options.descending ? 'endkey' : 'startkey';
10921 var endkeyName = options.descending ? 'startkey' : 'endkey';
10922
10923 if (typeof options[startkeyName] !== 'undefined' &&
10924 typeof options[endkeyName] !== 'undefined' &&
10925 collate(options[startkeyName], options[endkeyName]) > 0) {
10926 throw new QueryParseError('No rows can match your key range, ' +
10927 'reverse your start_key and end_key or set {descending : true}');
10928 } else if (fun.reduce && options.reduce !== false) {
10929 if (options.include_docs) {
10930 throw new QueryParseError('{include_docs:true} is invalid for reduce');
10931 } else if (options.keys && options.keys.length > 1 &&
10932 !options.group && !options.group_level) {
10933 throw new QueryParseError('Multi-key fetches for reduce views must use ' +
10934 '{group: true}');
10935 }
10936 }
10937 ['group_level', 'limit', 'skip'].forEach(function (optionName) {
10938 var error = checkPositiveInteger(options[optionName]);
10939 if (error) {
10940 throw error;
10941 }
10942 });
10943 }
10944
10945 function httpQuery(db, fun, opts) {
10946 // List of parameters to add to the PUT request
10947 var params = [];
10948 var body;
10949 var method = 'GET';
10950 var ok, status;
10951
10952 // If opts.reduce exists and is defined, then add it to the list
10953 // of parameters.
10954 // If reduce=false then the results are that of only the map function
10955 // not the final result of map and reduce.
10956 addHttpParam('reduce', opts, params);
10957 addHttpParam('include_docs', opts, params);
10958 addHttpParam('attachments', opts, params);
10959 addHttpParam('limit', opts, params);
10960 addHttpParam('descending', opts, params);
10961 addHttpParam('group', opts, params);
10962 addHttpParam('group_level', opts, params);
10963 addHttpParam('skip', opts, params);
10964 addHttpParam('stale', opts, params);
10965 addHttpParam('conflicts', opts, params);
10966 addHttpParam('startkey', opts, params, true);
10967 addHttpParam('start_key', opts, params, true);
10968 addHttpParam('endkey', opts, params, true);
10969 addHttpParam('end_key', opts, params, true);
10970 addHttpParam('inclusive_end', opts, params);
10971 addHttpParam('key', opts, params, true);
10972 addHttpParam('update_seq', opts, params);
10973
10974 // Format the list of parameters into a valid URI query string
10975 params = params.join('&');
10976 params = params === '' ? '' : '?' + params;
10977
10978 // If keys are supplied, issue a POST to circumvent GET query string limits
10979 // see http://wiki.apache.org/couchdb/HTTP_view_API#Querying_Options
10980 if (typeof opts.keys !== 'undefined') {
10981 var MAX_URL_LENGTH = 2000;
10982 // according to http://stackoverflow.com/a/417184/680742,
10983 // the de facto URL length limit is 2000 characters
10984
10985 var keysAsString =
10986 'keys=' + encodeURIComponent(JSON.stringify(opts.keys));
10987 if (keysAsString.length + params.length + 1 <= MAX_URL_LENGTH) {
10988 // If the keys are short enough, do a GET. we do this to work around
10989 // Safari not understanding 304s on POSTs (see pouchdb/pouchdb#1239)
10990 params += (params[0] === '?' ? '&' : '?') + keysAsString;
10991 } else {
10992 method = 'POST';
10993 if (typeof fun === 'string') {
10994 body = {keys: opts.keys};
10995 } else { // fun is {map : mapfun}, so append to this
10996 fun.keys = opts.keys;
10997 }
10998 }
10999 }
11000
11001 // We are referencing a query defined in the design doc
11002 if (typeof fun === 'string') {
11003 var parts = parseViewName(fun);
11004 return db.fetch('_design/' + parts[0] + '/_view/' + parts[1] + params, {
11005 headers: new h({'Content-Type': 'application/json'}),
11006 method: method,
11007 body: JSON.stringify(body)
11008 }).then(function (response) {
11009 ok = response.ok;
11010 status = response.status;
11011 return response.json();
11012 }).then(function (result) {
11013 if (!ok) {
11014 result.status = status;
11015 throw generateErrorFromResponse(result);
11016 }
11017 // fail the entire request if the result contains an error
11018 result.rows.forEach(function (row) {
11019 /* istanbul ignore if */
11020 if (row.value && row.value.error && row.value.error === "builtin_reduce_error") {
11021 throw new Error(row.reason);
11022 }
11023 });
11024 return result;
11025 }).then(postprocessAttachments(opts));
11026 }
11027
11028 // We are using a temporary view, terrible for performance, good for testing
11029 body = body || {};
11030 Object.keys(fun).forEach(function (key) {
11031 if (Array.isArray(fun[key])) {
11032 body[key] = fun[key];
11033 } else {
11034 body[key] = fun[key].toString();
11035 }
11036 });
11037
11038 return db.fetch('_temp_view' + params, {
11039 headers: new h({'Content-Type': 'application/json'}),
11040 method: 'POST',
11041 body: JSON.stringify(body)
11042 }).then(function (response) {
11043 ok = response.ok;
11044 status = response.status;
11045 return response.json();
11046 }).then(function (result) {
11047 if (!ok) {
11048 result.status = status;
11049 throw generateErrorFromResponse(result);
11050 }
11051 return result;
11052 }).then(postprocessAttachments(opts));
11053 }
11054
11055 // custom adapters can define their own api._query
11056 // and override the default behavior
11057 /* istanbul ignore next */
11058 function customQuery(db, fun, opts) {
11059 return new Promise(function (resolve, reject) {
11060 db._query(fun, opts, function (err, res) {
11061 if (err) {
11062 return reject(err);
11063 }
11064 resolve(res);
11065 });
11066 });
11067 }
11068
11069 // custom adapters can define their own api._viewCleanup
11070 // and override the default behavior
11071 /* istanbul ignore next */
11072 function customViewCleanup(db) {
11073 return new Promise(function (resolve, reject) {
11074 db._viewCleanup(function (err, res) {
11075 if (err) {
11076 return reject(err);
11077 }
11078 resolve(res);
11079 });
11080 });
11081 }
11082
11083 function defaultsTo(value) {
11084 return function (reason) {
11085 /* istanbul ignore else */
11086 if (reason.status === 404) {
11087 return value;
11088 } else {
11089 throw reason;
11090 }
11091 };
11092 }
11093
11094 // returns a promise for a list of docs to update, based on the input docId.
11095 // the order doesn't matter, because post-3.2.0, bulkDocs
11096 // is an atomic operation in all three adapters.
11097 function getDocsToPersist(docId, view, docIdsToChangesAndEmits) {
11098 var metaDocId = '_local/doc_' + docId;
11099 var defaultMetaDoc = {_id: metaDocId, keys: []};
11100 var docData = docIdsToChangesAndEmits.get(docId);
11101 var indexableKeysToKeyValues = docData[0];
11102 var changes = docData[1];
11103
11104 function getMetaDoc() {
11105 if (isGenOne(changes)) {
11106 // generation 1, so we can safely assume initial state
11107 // for performance reasons (avoids unnecessary GETs)
11108 return Promise.resolve(defaultMetaDoc);
11109 }
11110 return view.db.get(metaDocId)["catch"](defaultsTo(defaultMetaDoc));
11111 }
11112
11113 function getKeyValueDocs(metaDoc) {
11114 if (!metaDoc.keys.length) {
11115 // no keys, no need for a lookup
11116 return Promise.resolve({rows: []});
11117 }
11118 return view.db.allDocs({
11119 keys: metaDoc.keys,
11120 include_docs: true
11121 });
11122 }
11123
11124 function processKeyValueDocs(metaDoc, kvDocsRes) {
11125 var kvDocs = [];
11126 var oldKeys = new ExportedSet();
11127
11128 for (var i = 0, len = kvDocsRes.rows.length; i < len; i++) {
11129 var row = kvDocsRes.rows[i];
11130 var doc = row.doc;
11131 if (!doc) { // deleted
11132 continue;
11133 }
11134 kvDocs.push(doc);
11135 oldKeys.add(doc._id);
11136 doc._deleted = !indexableKeysToKeyValues.has(doc._id);
11137 if (!doc._deleted) {
11138 var keyValue = indexableKeysToKeyValues.get(doc._id);
11139 if ('value' in keyValue) {
11140 doc.value = keyValue.value;
11141 }
11142 }
11143 }
11144 var newKeys = mapToKeysArray(indexableKeysToKeyValues);
11145 newKeys.forEach(function (key) {
11146 if (!oldKeys.has(key)) {
11147 // new doc
11148 var kvDoc = {
11149 _id: key
11150 };
11151 var keyValue = indexableKeysToKeyValues.get(key);
11152 if ('value' in keyValue) {
11153 kvDoc.value = keyValue.value;
11154 }
11155 kvDocs.push(kvDoc);
11156 }
11157 });
11158 metaDoc.keys = uniq(newKeys.concat(metaDoc.keys));
11159 kvDocs.push(metaDoc);
11160
11161 return kvDocs;
11162 }
11163
11164 return getMetaDoc().then(function (metaDoc) {
11165 return getKeyValueDocs(metaDoc).then(function (kvDocsRes) {
11166 return processKeyValueDocs(metaDoc, kvDocsRes);
11167 });
11168 });
11169 }
11170
11171 // updates all emitted key/value docs and metaDocs in the mrview database
11172 // for the given batch of documents from the source database
11173 function saveKeyValues(view, docIdsToChangesAndEmits, seq) {
11174 var seqDocId = '_local/lastSeq';
11175 return view.db.get(seqDocId)[
11176 "catch"](defaultsTo({_id: seqDocId, seq: 0}))
11177 .then(function (lastSeqDoc) {
11178 var docIds = mapToKeysArray(docIdsToChangesAndEmits);
11179 return Promise.all(docIds.map(function (docId) {
11180 return getDocsToPersist(docId, view, docIdsToChangesAndEmits);
11181 })).then(function (listOfDocsToPersist) {
11182 var docsToPersist = flatten(listOfDocsToPersist);
11183 lastSeqDoc.seq = seq;
11184 docsToPersist.push(lastSeqDoc);
11185 // write all docs in a single operation, update the seq once
11186 return view.db.bulkDocs({docs : docsToPersist});
11187 });
11188 });
11189 }
11190
11191 function getQueue(view) {
11192 var viewName = typeof view === 'string' ? view : view.name;
11193 var queue = persistentQueues[viewName];
11194 if (!queue) {
11195 queue = persistentQueues[viewName] = new TaskQueue$1();
11196 }
11197 return queue;
11198 }
11199
11200 function updateView(view, opts) {
11201 return sequentialize(getQueue(view), function () {
11202 return updateViewInQueue(view, opts);
11203 })();
11204 }
11205
11206 function updateViewInQueue(view, opts) {
11207 // bind the emit function once
11208 var mapResults;
11209 var doc;
11210
11211 function emit(key, value) {
11212 var output = {id: doc._id, key: normalizeKey(key)};
11213 // Don't explicitly store the value unless it's defined and non-null.
11214 // This saves on storage space, because often people don't use it.
11215 if (typeof value !== 'undefined' && value !== null) {
11216 output.value = normalizeKey(value);
11217 }
11218 mapResults.push(output);
11219 }
11220
11221 var mapFun = mapper(view.mapFun, emit);
11222
11223 var currentSeq = view.seq || 0;
11224
11225 function processChange(docIdsToChangesAndEmits, seq) {
11226 return function () {
11227 return saveKeyValues(view, docIdsToChangesAndEmits, seq);
11228 };
11229 }
11230
11231 let indexed_docs = 0;
11232 let progress = {
11233 view: view.name,
11234 indexed_docs: indexed_docs
11235 };
11236 view.sourceDB.emit('indexing', progress);
11237
11238 var queue = new TaskQueue$1();
11239
11240 function processNextBatch() {
11241 return view.sourceDB.changes({
11242 return_docs: true,
11243 conflicts: true,
11244 include_docs: true,
11245 style: 'all_docs',
11246 since: currentSeq,
11247 limit: opts.changes_batch_size
11248 }).then(processBatch);
11249 }
11250
11251 function processBatch(response) {
11252 var results = response.results;
11253 if (!results.length) {
11254 return;
11255 }
11256 var docIdsToChangesAndEmits = createDocIdsToChangesAndEmits(results);
11257 queue.add(processChange(docIdsToChangesAndEmits, currentSeq));
11258
11259 indexed_docs = indexed_docs + results.length;
11260 let progress = {
11261 view: view.name,
11262 last_seq: response.last_seq,
11263 results_count: results.length,
11264 indexed_docs: indexed_docs
11265 };
11266 view.sourceDB.emit('indexing', progress);
11267
11268 if (results.length < opts.changes_batch_size) {
11269 return;
11270 }
11271 return processNextBatch();
11272 }
11273
11274 function createDocIdsToChangesAndEmits(results) {
11275 var docIdsToChangesAndEmits = new ExportedMap();
11276 for (var i = 0, len = results.length; i < len; i++) {
11277 var change = results[i];
11278 if (change.doc._id[0] !== '_') {
11279 mapResults = [];
11280 doc = change.doc;
11281
11282 if (!doc._deleted) {
11283 tryMap(view.sourceDB, mapFun, doc);
11284 }
11285 mapResults.sort(sortByKeyThenValue);
11286
11287 var indexableKeysToKeyValues = createIndexableKeysToKeyValues(mapResults);
11288 docIdsToChangesAndEmits.set(change.doc._id, [
11289 indexableKeysToKeyValues,
11290 change.changes
11291 ]);
11292 }
11293 currentSeq = change.seq;
11294 }
11295 return docIdsToChangesAndEmits;
11296 }
11297
11298 function createIndexableKeysToKeyValues(mapResults) {
11299 var indexableKeysToKeyValues = new ExportedMap();
11300 var lastKey;
11301 for (var i = 0, len = mapResults.length; i < len; i++) {
11302 var emittedKeyValue = mapResults[i];
11303 var complexKey = [emittedKeyValue.key, emittedKeyValue.id];
11304 if (i > 0 && collate(emittedKeyValue.key, lastKey) === 0) {
11305 complexKey.push(i); // dup key+id, so make it unique
11306 }
11307 indexableKeysToKeyValues.set(toIndexableString(complexKey), emittedKeyValue);
11308 lastKey = emittedKeyValue.key;
11309 }
11310 return indexableKeysToKeyValues;
11311 }
11312
11313 return processNextBatch().then(function () {
11314 return queue.finish();
11315 }).then(function () {
11316 view.seq = currentSeq;
11317 });
11318 }
11319
11320 function reduceView(view, results, options) {
11321 if (options.group_level === 0) {
11322 delete options.group_level;
11323 }
11324
11325 var shouldGroup = options.group || options.group_level;
11326
11327 var reduceFun = reducer(view.reduceFun);
11328
11329 var groups = [];
11330 var lvl = isNaN(options.group_level) ? Number.POSITIVE_INFINITY :
11331 options.group_level;
11332 results.forEach(function (e) {
11333 var last = groups[groups.length - 1];
11334 var groupKey = shouldGroup ? e.key : null;
11335
11336 // only set group_level for array keys
11337 if (shouldGroup && Array.isArray(groupKey)) {
11338 groupKey = groupKey.slice(0, lvl);
11339 }
11340
11341 if (last && collate(last.groupKey, groupKey) === 0) {
11342 last.keys.push([e.key, e.id]);
11343 last.values.push(e.value);
11344 return;
11345 }
11346 groups.push({
11347 keys: [[e.key, e.id]],
11348 values: [e.value],
11349 groupKey: groupKey
11350 });
11351 });
11352 results = [];
11353 for (var i = 0, len = groups.length; i < len; i++) {
11354 var e = groups[i];
11355 var reduceTry = tryReduce(view.sourceDB, reduceFun, e.keys, e.values, false);
11356 if (reduceTry.error && reduceTry.error instanceof BuiltInError) {
11357 // CouchDB returns an error if a built-in errors out
11358 throw reduceTry.error;
11359 }
11360 results.push({
11361 // CouchDB just sets the value to null if a non-built-in errors out
11362 value: reduceTry.error ? null : reduceTry.output,
11363 key: e.groupKey
11364 });
11365 }
11366 // no total_rows/offset when reducing
11367 return {rows: sliceResults(results, options.limit, options.skip)};
11368 }
11369
11370 function queryView(view, opts) {
11371 return sequentialize(getQueue(view), function () {
11372 return queryViewInQueue(view, opts);
11373 })();
11374 }
11375
11376 function queryViewInQueue(view, opts) {
11377 var totalRows;
11378 var shouldReduce = view.reduceFun && opts.reduce !== false;
11379 var skip = opts.skip || 0;
11380 if (typeof opts.keys !== 'undefined' && !opts.keys.length) {
11381 // equivalent query
11382 opts.limit = 0;
11383 delete opts.keys;
11384 }
11385
11386 function fetchFromView(viewOpts) {
11387 viewOpts.include_docs = true;
11388 return view.db.allDocs(viewOpts).then(function (res) {
11389 totalRows = res.total_rows;
11390 return res.rows.map(function (result) {
11391
11392 // implicit migration - in older versions of PouchDB,
11393 // we explicitly stored the doc as {id: ..., key: ..., value: ...}
11394 // this is tested in a migration test
11395 /* istanbul ignore next */
11396 if ('value' in result.doc && typeof result.doc.value === 'object' &&
11397 result.doc.value !== null) {
11398 var keys = Object.keys(result.doc.value).sort();
11399 // this detection method is not perfect, but it's unlikely the user
11400 // emitted a value which was an object with these 3 exact keys
11401 var expectedKeys = ['id', 'key', 'value'];
11402 if (!(keys < expectedKeys || keys > expectedKeys)) {
11403 return result.doc.value;
11404 }
11405 }
11406
11407 var parsedKeyAndDocId = parseIndexableString(result.doc._id);
11408 return {
11409 key: parsedKeyAndDocId[0],
11410 id: parsedKeyAndDocId[1],
11411 value: ('value' in result.doc ? result.doc.value : null)
11412 };
11413 });
11414 });
11415 }
11416
11417 function onMapResultsReady(rows) {
11418 var finalResults;
11419 if (shouldReduce) {
11420 finalResults = reduceView(view, rows, opts);
11421 } else if (typeof opts.keys === 'undefined') {
11422 finalResults = {
11423 total_rows: totalRows,
11424 offset: skip,
11425 rows: rows
11426 };
11427 } else {
11428 // support limit, skip for keys query
11429 finalResults = {
11430 total_rows: totalRows,
11431 offset: skip,
11432 rows: sliceResults(rows,opts.limit,opts.skip)
11433 };
11434 }
11435 /* istanbul ignore if */
11436 if (opts.update_seq) {
11437 finalResults.update_seq = view.seq;
11438 }
11439 if (opts.include_docs) {
11440 var docIds = uniq(rows.map(rowToDocId));
11441
11442 return view.sourceDB.allDocs({
11443 keys: docIds,
11444 include_docs: true,
11445 conflicts: opts.conflicts,
11446 attachments: opts.attachments,
11447 binary: opts.binary
11448 }).then(function (allDocsRes) {
11449 var docIdsToDocs = new ExportedMap();
11450 allDocsRes.rows.forEach(function (row) {
11451 docIdsToDocs.set(row.id, row.doc);
11452 });
11453 rows.forEach(function (row) {
11454 var docId = rowToDocId(row);
11455 var doc = docIdsToDocs.get(docId);
11456 if (doc) {
11457 row.doc = doc;
11458 }
11459 });
11460 return finalResults;
11461 });
11462 } else {
11463 return finalResults;
11464 }
11465 }
11466
11467 if (typeof opts.keys !== 'undefined') {
11468 var keys = opts.keys;
11469 var fetchPromises = keys.map(function (key) {
11470 var viewOpts = {
11471 startkey : toIndexableString([key]),
11472 endkey : toIndexableString([key, {}])
11473 };
11474 /* istanbul ignore if */
11475 if (opts.update_seq) {
11476 viewOpts.update_seq = true;
11477 }
11478 return fetchFromView(viewOpts);
11479 });
11480 return Promise.all(fetchPromises).then(flatten).then(onMapResultsReady);
11481 } else { // normal query, no 'keys'
11482 var viewOpts = {
11483 descending : opts.descending
11484 };
11485 /* istanbul ignore if */
11486 if (opts.update_seq) {
11487 viewOpts.update_seq = true;
11488 }
11489 var startkey;
11490 var endkey;
11491 if ('start_key' in opts) {
11492 startkey = opts.start_key;
11493 }
11494 if ('startkey' in opts) {
11495 startkey = opts.startkey;
11496 }
11497 if ('end_key' in opts) {
11498 endkey = opts.end_key;
11499 }
11500 if ('endkey' in opts) {
11501 endkey = opts.endkey;
11502 }
11503 if (typeof startkey !== 'undefined') {
11504 viewOpts.startkey = opts.descending ?
11505 toIndexableString([startkey, {}]) :
11506 toIndexableString([startkey]);
11507 }
11508 if (typeof endkey !== 'undefined') {
11509 var inclusiveEnd = opts.inclusive_end !== false;
11510 if (opts.descending) {
11511 inclusiveEnd = !inclusiveEnd;
11512 }
11513
11514 viewOpts.endkey = toIndexableString(
11515 inclusiveEnd ? [endkey, {}] : [endkey]);
11516 }
11517 if (typeof opts.key !== 'undefined') {
11518 var keyStart = toIndexableString([opts.key]);
11519 var keyEnd = toIndexableString([opts.key, {}]);
11520 if (viewOpts.descending) {
11521 viewOpts.endkey = keyStart;
11522 viewOpts.startkey = keyEnd;
11523 } else {
11524 viewOpts.startkey = keyStart;
11525 viewOpts.endkey = keyEnd;
11526 }
11527 }
11528 if (!shouldReduce) {
11529 if (typeof opts.limit === 'number') {
11530 viewOpts.limit = opts.limit;
11531 }
11532 viewOpts.skip = skip;
11533 }
11534 return fetchFromView(viewOpts).then(onMapResultsReady);
11535 }
11536 }
11537
11538 function httpViewCleanup(db) {
11539 return db.fetch('_view_cleanup', {
11540 headers: new h({'Content-Type': 'application/json'}),
11541 method: 'POST'
11542 }).then(function (response) {
11543 return response.json();
11544 });
11545 }
11546
11547 function localViewCleanup(db) {
11548 return db.get('_local/' + localDocName).then(function (metaDoc) {
11549 var docsToViews = new ExportedMap();
11550 Object.keys(metaDoc.views).forEach(function (fullViewName) {
11551 var parts = parseViewName(fullViewName);
11552 var designDocName = '_design/' + parts[0];
11553 var viewName = parts[1];
11554 var views = docsToViews.get(designDocName);
11555 if (!views) {
11556 views = new ExportedSet();
11557 docsToViews.set(designDocName, views);
11558 }
11559 views.add(viewName);
11560 });
11561 var opts = {
11562 keys : mapToKeysArray(docsToViews),
11563 include_docs : true
11564 };
11565 return db.allDocs(opts).then(function (res) {
11566 var viewsToStatus = {};
11567 res.rows.forEach(function (row) {
11568 var ddocName = row.key.substring(8); // cuts off '_design/'
11569 docsToViews.get(row.key).forEach(function (viewName) {
11570 var fullViewName = ddocName + '/' + viewName;
11571 /* istanbul ignore if */
11572 if (!metaDoc.views[fullViewName]) {
11573 // new format, without slashes, to support PouchDB 2.2.0
11574 // migration test in pouchdb's browser.migration.js verifies this
11575 fullViewName = viewName;
11576 }
11577 var viewDBNames = Object.keys(metaDoc.views[fullViewName]);
11578 // design doc deleted, or view function nonexistent
11579 var statusIsGood = row.doc && row.doc.views &&
11580 row.doc.views[viewName];
11581 viewDBNames.forEach(function (viewDBName) {
11582 viewsToStatus[viewDBName] =
11583 viewsToStatus[viewDBName] || statusIsGood;
11584 });
11585 });
11586 });
11587 var dbsToDelete = Object.keys(viewsToStatus).filter(
11588 function (viewDBName) { return !viewsToStatus[viewDBName]; });
11589 var destroyPromises = dbsToDelete.map(function (viewDBName) {
11590 return sequentialize(getQueue(viewDBName), function () {
11591 return new db.constructor(viewDBName, db.__opts).destroy();
11592 })();
11593 });
11594 return Promise.all(destroyPromises).then(function () {
11595 return {ok: true};
11596 });
11597 });
11598 }, defaultsTo({ok: true}));
11599 }
11600
11601 function queryPromised(db, fun, opts) {
11602 /* istanbul ignore next */
11603 if (typeof db._query === 'function') {
11604 return customQuery(db, fun, opts);
11605 }
11606 if (isRemote(db)) {
11607 return httpQuery(db, fun, opts);
11608 }
11609
11610 var updateViewOpts = {
11611 changes_batch_size: db.__opts.view_update_changes_batch_size || CHANGES_BATCH_SIZE$1
11612 };
11613
11614 if (typeof fun !== 'string') {
11615 // temp_view
11616 checkQueryParseError(opts, fun);
11617
11618 tempViewQueue.add(function () {
11619 var createViewPromise = createView(
11620 /* sourceDB */ db,
11621 /* viewName */ 'temp_view/temp_view',
11622 /* mapFun */ fun.map,
11623 /* reduceFun */ fun.reduce,
11624 /* temporary */ true,
11625 /* localDocName */ localDocName);
11626 return createViewPromise.then(function (view) {
11627 return fin(updateView(view, updateViewOpts).then(function () {
11628 return queryView(view, opts);
11629 }), function () {
11630 return view.db.destroy();
11631 });
11632 });
11633 });
11634 return tempViewQueue.finish();
11635 } else {
11636 // persistent view
11637 var fullViewName = fun;
11638 var parts = parseViewName(fullViewName);
11639 var designDocName = parts[0];
11640 var viewName = parts[1];
11641 return db.get('_design/' + designDocName).then(function (doc) {
11642 var fun = doc.views && doc.views[viewName];
11643
11644 if (!fun) {
11645 // basic validator; it's assumed that every subclass would want this
11646 throw new NotFoundError('ddoc ' + doc._id + ' has no view named ' +
11647 viewName);
11648 }
11649
11650 ddocValidator(doc, viewName);
11651 checkQueryParseError(opts, fun);
11652
11653 var createViewPromise = createView(
11654 /* sourceDB */ db,
11655 /* viewName */ fullViewName,
11656 /* mapFun */ fun.map,
11657 /* reduceFun */ fun.reduce,
11658 /* temporary */ false,
11659 /* localDocName */ localDocName);
11660 return createViewPromise.then(function (view) {
11661 if (opts.stale === 'ok' || opts.stale === 'update_after') {
11662 if (opts.stale === 'update_after') {
11663 immediate(function () {
11664 updateView(view, updateViewOpts);
11665 });
11666 }
11667 return queryView(view, opts);
11668 } else { // stale not ok
11669 return updateView(view, updateViewOpts).then(function () {
11670 return queryView(view, opts);
11671 });
11672 }
11673 });
11674 });
11675 }
11676 }
11677
11678 function abstractQuery(fun, opts, callback) {
11679 var db = this;
11680 if (typeof opts === 'function') {
11681 callback = opts;
11682 opts = {};
11683 }
11684 opts = opts ? coerceOptions(opts) : {};
11685
11686 if (typeof fun === 'function') {
11687 fun = {map : fun};
11688 }
11689
11690 var promise = Promise.resolve().then(function () {
11691 return queryPromised(db, fun, opts);
11692 });
11693 promisedCallback(promise, callback);
11694 return promise;
11695 }
11696
11697 var abstractViewCleanup = callbackify(function () {
11698 var db = this;
11699 /* istanbul ignore next */
11700 if (typeof db._viewCleanup === 'function') {
11701 return customViewCleanup(db);
11702 }
11703 if (isRemote(db)) {
11704 return httpViewCleanup(db);
11705 }
11706 return localViewCleanup(db);
11707 });
11708
11709 return {
11710 query: abstractQuery,
11711 viewCleanup: abstractViewCleanup
11712 };
11713}
11714
11715var builtInReduce = {
11716 _sum: function (keys, values) {
11717 return sum(values);
11718 },
11719
11720 _count: function (keys, values) {
11721 return values.length;
11722 },
11723
11724 _stats: function (keys, values) {
11725 // no need to implement rereduce=true, because Pouch
11726 // will never call it
11727 function sumsqr(values) {
11728 var _sumsqr = 0;
11729 for (var i = 0, len = values.length; i < len; i++) {
11730 var num = values[i];
11731 _sumsqr += (num * num);
11732 }
11733 return _sumsqr;
11734 }
11735 return {
11736 sum : sum(values),
11737 min : Math.min.apply(null, values),
11738 max : Math.max.apply(null, values),
11739 count : values.length,
11740 sumsqr : sumsqr(values)
11741 };
11742 }
11743};
11744
11745function getBuiltIn(reduceFunString) {
11746 if (/^_sum/.test(reduceFunString)) {
11747 return builtInReduce._sum;
11748 } else if (/^_count/.test(reduceFunString)) {
11749 return builtInReduce._count;
11750 } else if (/^_stats/.test(reduceFunString)) {
11751 return builtInReduce._stats;
11752 } else if (/^_/.test(reduceFunString)) {
11753 throw new Error(reduceFunString + ' is not a supported reduce function.');
11754 }
11755}
11756
11757function mapper(mapFun, emit) {
11758 // for temp_views one can use emit(doc, emit), see #38
11759 if (typeof mapFun === "function" && mapFun.length === 2) {
11760 var origMap = mapFun;
11761 return function (doc) {
11762 return origMap(doc, emit);
11763 };
11764 } else {
11765 return evalFunctionWithEval(mapFun.toString(), emit);
11766 }
11767}
11768
11769function reducer(reduceFun) {
11770 var reduceFunString = reduceFun.toString();
11771 var builtIn = getBuiltIn(reduceFunString);
11772 if (builtIn) {
11773 return builtIn;
11774 } else {
11775 return evalFunctionWithEval(reduceFunString);
11776 }
11777}
11778
11779function ddocValidator(ddoc, viewName) {
11780 var fun = ddoc.views && ddoc.views[viewName];
11781 if (typeof fun.map !== 'string') {
11782 throw new NotFoundError('ddoc ' + ddoc._id + ' has no string view named ' +
11783 viewName + ', instead found object of type: ' + typeof fun.map);
11784 }
11785}
11786
11787var localDocName = 'mrviews';
11788var abstract = createAbstractMapReduce(localDocName, mapper, reducer, ddocValidator);
11789
11790function query(fun, opts, callback) {
11791 return abstract.query.call(this, fun, opts, callback);
11792}
11793
11794function viewCleanup(callback) {
11795 return abstract.viewCleanup.call(this, callback);
11796}
11797
11798var mapreduce = {
11799 query: query,
11800 viewCleanup: viewCleanup
11801};
11802
11803function isGenOne$1(rev) {
11804 return /^1-/.test(rev);
11805}
11806
11807function fileHasChanged(localDoc, remoteDoc, filename) {
11808 return !localDoc._attachments ||
11809 !localDoc._attachments[filename] ||
11810 localDoc._attachments[filename].digest !== remoteDoc._attachments[filename].digest;
11811}
11812
11813function getDocAttachments(db, doc) {
11814 var filenames = Object.keys(doc._attachments);
11815 return Promise.all(filenames.map(function (filename) {
11816 return db.getAttachment(doc._id, filename, {rev: doc._rev});
11817 }));
11818}
11819
11820function getDocAttachmentsFromTargetOrSource(target, src, doc) {
11821 var doCheckForLocalAttachments = isRemote(src) && !isRemote(target);
11822 var filenames = Object.keys(doc._attachments);
11823
11824 if (!doCheckForLocalAttachments) {
11825 return getDocAttachments(src, doc);
11826 }
11827
11828 return target.get(doc._id).then(function (localDoc) {
11829 return Promise.all(filenames.map(function (filename) {
11830 if (fileHasChanged(localDoc, doc, filename)) {
11831 return src.getAttachment(doc._id, filename);
11832 }
11833
11834 return target.getAttachment(localDoc._id, filename);
11835 }));
11836 })["catch"](function (error) {
11837 /* istanbul ignore if */
11838 if (error.status !== 404) {
11839 throw error;
11840 }
11841
11842 return getDocAttachments(src, doc);
11843 });
11844}
11845
11846function createBulkGetOpts(diffs) {
11847 var requests = [];
11848 Object.keys(diffs).forEach(function (id) {
11849 var missingRevs = diffs[id].missing;
11850 missingRevs.forEach(function (missingRev) {
11851 requests.push({
11852 id: id,
11853 rev: missingRev
11854 });
11855 });
11856 });
11857
11858 return {
11859 docs: requests,
11860 revs: true,
11861 latest: true
11862 };
11863}
11864
11865//
11866// Fetch all the documents from the src as described in the "diffs",
11867// which is a mapping of docs IDs to revisions. If the state ever
11868// changes to "cancelled", then the returned promise will be rejected.
11869// Else it will be resolved with a list of fetched documents.
11870//
11871function getDocs(src, target, diffs, state) {
11872 diffs = clone(diffs); // we do not need to modify this
11873
11874 var resultDocs = [],
11875 ok = true;
11876
11877 function getAllDocs() {
11878
11879 var bulkGetOpts = createBulkGetOpts(diffs);
11880
11881 if (!bulkGetOpts.docs.length) { // optimization: skip empty requests
11882 return;
11883 }
11884
11885 return src.bulkGet(bulkGetOpts).then(function (bulkGetResponse) {
11886 /* istanbul ignore if */
11887 if (state.cancelled) {
11888 throw new Error('cancelled');
11889 }
11890 return Promise.all(bulkGetResponse.results.map(function (bulkGetInfo) {
11891 return Promise.all(bulkGetInfo.docs.map(function (doc) {
11892 var remoteDoc = doc.ok;
11893
11894 if (doc.error) {
11895 // when AUTO_COMPACTION is set, docs can be returned which look
11896 // like this: {"missing":"1-7c3ac256b693c462af8442f992b83696"}
11897 ok = false;
11898 }
11899
11900 if (!remoteDoc || !remoteDoc._attachments) {
11901 return remoteDoc;
11902 }
11903
11904 return getDocAttachmentsFromTargetOrSource(target, src, remoteDoc)
11905 .then(function (attachments) {
11906 var filenames = Object.keys(remoteDoc._attachments);
11907 attachments
11908 .forEach(function (attachment, i) {
11909 var att = remoteDoc._attachments[filenames[i]];
11910 delete att.stub;
11911 delete att.length;
11912 att.data = attachment;
11913 });
11914
11915 return remoteDoc;
11916 });
11917 }));
11918 }))
11919
11920 .then(function (results) {
11921 resultDocs = resultDocs.concat(flatten(results).filter(Boolean));
11922 });
11923 });
11924 }
11925
11926 function hasAttachments(doc) {
11927 return doc._attachments && Object.keys(doc._attachments).length > 0;
11928 }
11929
11930 function hasConflicts(doc) {
11931 return doc._conflicts && doc._conflicts.length > 0;
11932 }
11933
11934 function fetchRevisionOneDocs(ids) {
11935 // Optimization: fetch gen-1 docs and attachments in
11936 // a single request using _all_docs
11937 return src.allDocs({
11938 keys: ids,
11939 include_docs: true,
11940 conflicts: true
11941 }).then(function (res) {
11942 if (state.cancelled) {
11943 throw new Error('cancelled');
11944 }
11945 res.rows.forEach(function (row) {
11946 if (row.deleted || !row.doc || !isGenOne$1(row.value.rev) ||
11947 hasAttachments(row.doc) || hasConflicts(row.doc)) {
11948 // if any of these conditions apply, we need to fetch using get()
11949 return;
11950 }
11951
11952 // strip _conflicts array to appease CSG (#5793)
11953 /* istanbul ignore if */
11954 if (row.doc._conflicts) {
11955 delete row.doc._conflicts;
11956 }
11957
11958 // the doc we got back from allDocs() is sufficient
11959 resultDocs.push(row.doc);
11960 delete diffs[row.id];
11961 });
11962 });
11963 }
11964
11965 function getRevisionOneDocs() {
11966 // filter out the generation 1 docs and get them
11967 // leaving the non-generation one docs to be got otherwise
11968 var ids = Object.keys(diffs).filter(function (id) {
11969 var missing = diffs[id].missing;
11970 return missing.length === 1 && isGenOne$1(missing[0]);
11971 });
11972 if (ids.length > 0) {
11973 return fetchRevisionOneDocs(ids);
11974 }
11975 }
11976
11977 function returnResult() {
11978 return { ok:ok, docs:resultDocs };
11979 }
11980
11981 return Promise.resolve()
11982 .then(getRevisionOneDocs)
11983 .then(getAllDocs)
11984 .then(returnResult);
11985}
11986
11987var CHECKPOINT_VERSION = 1;
11988var REPLICATOR = "pouchdb";
11989// This is an arbitrary number to limit the
11990// amount of replication history we save in the checkpoint.
11991// If we save too much, the checkpoing docs will become very big,
11992// if we save fewer, we'll run a greater risk of having to
11993// read all the changes from 0 when checkpoint PUTs fail
11994// CouchDB 2.0 has a more involved history pruning,
11995// but let's go for the simple version for now.
11996var CHECKPOINT_HISTORY_SIZE = 5;
11997var LOWEST_SEQ = 0;
11998
11999function updateCheckpoint(db, id, checkpoint, session, returnValue) {
12000 return db.get(id)["catch"](function (err) {
12001 if (err.status === 404) {
12002 if (db.adapter === 'http' || db.adapter === 'https') {
12003 explainError(
12004 404, 'PouchDB is just checking if a remote checkpoint exists.'
12005 );
12006 }
12007 return {
12008 session_id: session,
12009 _id: id,
12010 history: [],
12011 replicator: REPLICATOR,
12012 version: CHECKPOINT_VERSION
12013 };
12014 }
12015 throw err;
12016 }).then(function (doc) {
12017 if (returnValue.cancelled) {
12018 return;
12019 }
12020
12021 // if the checkpoint has not changed, do not update
12022 if (doc.last_seq === checkpoint) {
12023 return;
12024 }
12025
12026 // Filter out current entry for this replication
12027 doc.history = (doc.history || []).filter(function (item) {
12028 return item.session_id !== session;
12029 });
12030
12031 // Add the latest checkpoint to history
12032 doc.history.unshift({
12033 last_seq: checkpoint,
12034 session_id: session
12035 });
12036
12037 // Just take the last pieces in history, to
12038 // avoid really big checkpoint docs.
12039 // see comment on history size above
12040 doc.history = doc.history.slice(0, CHECKPOINT_HISTORY_SIZE);
12041
12042 doc.version = CHECKPOINT_VERSION;
12043 doc.replicator = REPLICATOR;
12044
12045 doc.session_id = session;
12046 doc.last_seq = checkpoint;
12047
12048 return db.put(doc)["catch"](function (err) {
12049 if (err.status === 409) {
12050 // retry; someone is trying to write a checkpoint simultaneously
12051 return updateCheckpoint(db, id, checkpoint, session, returnValue);
12052 }
12053 throw err;
12054 });
12055 });
12056}
12057
12058function Checkpointer(src, target, id, returnValue, opts) {
12059 this.src = src;
12060 this.target = target;
12061 this.id = id;
12062 this.returnValue = returnValue;
12063 this.opts = opts || {};
12064}
12065
12066Checkpointer.prototype.writeCheckpoint = function (checkpoint, session) {
12067 var self = this;
12068 return this.updateTarget(checkpoint, session).then(function () {
12069 return self.updateSource(checkpoint, session);
12070 });
12071};
12072
12073Checkpointer.prototype.updateTarget = function (checkpoint, session) {
12074 if (this.opts.writeTargetCheckpoint) {
12075 return updateCheckpoint(this.target, this.id, checkpoint,
12076 session, this.returnValue);
12077 } else {
12078 return Promise.resolve(true);
12079 }
12080};
12081
12082Checkpointer.prototype.updateSource = function (checkpoint, session) {
12083 if (this.opts.writeSourceCheckpoint) {
12084 var self = this;
12085 return updateCheckpoint(this.src, this.id, checkpoint,
12086 session, this.returnValue)[
12087 "catch"](function (err) {
12088 if (isForbiddenError(err)) {
12089 self.opts.writeSourceCheckpoint = false;
12090 return true;
12091 }
12092 throw err;
12093 });
12094 } else {
12095 return Promise.resolve(true);
12096 }
12097};
12098
12099var comparisons = {
12100 "undefined": function (targetDoc, sourceDoc) {
12101 // This is the previous comparison function
12102 if (collate(targetDoc.last_seq, sourceDoc.last_seq) === 0) {
12103 return sourceDoc.last_seq;
12104 }
12105 /* istanbul ignore next */
12106 return 0;
12107 },
12108 "1": function (targetDoc, sourceDoc) {
12109 // This is the comparison function ported from CouchDB
12110 return compareReplicationLogs(sourceDoc, targetDoc).last_seq;
12111 }
12112};
12113
12114Checkpointer.prototype.getCheckpoint = function () {
12115 var self = this;
12116
12117 if (self.opts && self.opts.writeSourceCheckpoint && !self.opts.writeTargetCheckpoint) {
12118 return self.src.get(self.id).then(function (sourceDoc) {
12119 return sourceDoc.last_seq || LOWEST_SEQ;
12120 })["catch"](function (err) {
12121 /* istanbul ignore if */
12122 if (err.status !== 404) {
12123 throw err;
12124 }
12125 return LOWEST_SEQ;
12126 });
12127 }
12128
12129 return self.target.get(self.id).then(function (targetDoc) {
12130 if (self.opts && self.opts.writeTargetCheckpoint && !self.opts.writeSourceCheckpoint) {
12131 return targetDoc.last_seq || LOWEST_SEQ;
12132 }
12133
12134 return self.src.get(self.id).then(function (sourceDoc) {
12135 // Since we can't migrate an old version doc to a new one
12136 // (no session id), we just go with the lowest seq in this case
12137 /* istanbul ignore if */
12138 if (targetDoc.version !== sourceDoc.version) {
12139 return LOWEST_SEQ;
12140 }
12141
12142 var version;
12143 if (targetDoc.version) {
12144 version = targetDoc.version.toString();
12145 } else {
12146 version = "undefined";
12147 }
12148
12149 if (version in comparisons) {
12150 return comparisons[version](targetDoc, sourceDoc);
12151 }
12152 /* istanbul ignore next */
12153 return LOWEST_SEQ;
12154 }, function (err) {
12155 if (err.status === 404 && targetDoc.last_seq) {
12156 return self.src.put({
12157 _id: self.id,
12158 last_seq: LOWEST_SEQ
12159 }).then(function () {
12160 return LOWEST_SEQ;
12161 }, function (err) {
12162 if (isForbiddenError(err)) {
12163 self.opts.writeSourceCheckpoint = false;
12164 return targetDoc.last_seq;
12165 }
12166 /* istanbul ignore next */
12167 return LOWEST_SEQ;
12168 });
12169 }
12170 throw err;
12171 });
12172 })["catch"](function (err) {
12173 if (err.status !== 404) {
12174 throw err;
12175 }
12176 return LOWEST_SEQ;
12177 });
12178};
12179// This checkpoint comparison is ported from CouchDBs source
12180// they come from here:
12181// https://github.com/apache/couchdb-couch-replicator/blob/master/src/couch_replicator.erl#L863-L906
12182
12183function compareReplicationLogs(srcDoc, tgtDoc) {
12184 if (srcDoc.session_id === tgtDoc.session_id) {
12185 return {
12186 last_seq: srcDoc.last_seq,
12187 history: srcDoc.history
12188 };
12189 }
12190
12191 return compareReplicationHistory(srcDoc.history, tgtDoc.history);
12192}
12193
12194function compareReplicationHistory(sourceHistory, targetHistory) {
12195 // the erlang loop via function arguments is not so easy to repeat in JS
12196 // therefore, doing this as recursion
12197 var S = sourceHistory[0];
12198 var sourceRest = sourceHistory.slice(1);
12199 var T = targetHistory[0];
12200 var targetRest = targetHistory.slice(1);
12201
12202 if (!S || targetHistory.length === 0) {
12203 return {
12204 last_seq: LOWEST_SEQ,
12205 history: []
12206 };
12207 }
12208
12209 var sourceId = S.session_id;
12210 /* istanbul ignore if */
12211 if (hasSessionId(sourceId, targetHistory)) {
12212 return {
12213 last_seq: S.last_seq,
12214 history: sourceHistory
12215 };
12216 }
12217
12218 var targetId = T.session_id;
12219 if (hasSessionId(targetId, sourceRest)) {
12220 return {
12221 last_seq: T.last_seq,
12222 history: targetRest
12223 };
12224 }
12225
12226 return compareReplicationHistory(sourceRest, targetRest);
12227}
12228
12229function hasSessionId(sessionId, history) {
12230 var props = history[0];
12231 var rest = history.slice(1);
12232
12233 if (!sessionId || history.length === 0) {
12234 return false;
12235 }
12236
12237 if (sessionId === props.session_id) {
12238 return true;
12239 }
12240
12241 return hasSessionId(sessionId, rest);
12242}
12243
12244function isForbiddenError(err) {
12245 return typeof err.status === 'number' && Math.floor(err.status / 100) === 4;
12246}
12247
12248var STARTING_BACK_OFF = 0;
12249
12250function backOff(opts, returnValue, error, callback) {
12251 if (opts.retry === false) {
12252 returnValue.emit('error', error);
12253 returnValue.removeAllListeners();
12254 return;
12255 }
12256 /* istanbul ignore if */
12257 if (typeof opts.back_off_function !== 'function') {
12258 opts.back_off_function = defaultBackOff;
12259 }
12260 returnValue.emit('requestError', error);
12261 if (returnValue.state === 'active' || returnValue.state === 'pending') {
12262 returnValue.emit('paused', error);
12263 returnValue.state = 'stopped';
12264 var backOffSet = function backoffTimeSet() {
12265 opts.current_back_off = STARTING_BACK_OFF;
12266 };
12267 var removeBackOffSetter = function removeBackOffTimeSet() {
12268 returnValue.removeListener('active', backOffSet);
12269 };
12270 returnValue.once('paused', removeBackOffSetter);
12271 returnValue.once('active', backOffSet);
12272 }
12273
12274 opts.current_back_off = opts.current_back_off || STARTING_BACK_OFF;
12275 opts.current_back_off = opts.back_off_function(opts.current_back_off);
12276 setTimeout(callback, opts.current_back_off);
12277}
12278
12279function sortObjectPropertiesByKey(queryParams) {
12280 return Object.keys(queryParams).sort(collate).reduce(function (result, key) {
12281 result[key] = queryParams[key];
12282 return result;
12283 }, {});
12284}
12285
12286// Generate a unique id particular to this replication.
12287// Not guaranteed to align perfectly with CouchDB's rep ids.
12288function generateReplicationId(src, target, opts) {
12289 var docIds = opts.doc_ids ? opts.doc_ids.sort(collate) : '';
12290 var filterFun = opts.filter ? opts.filter.toString() : '';
12291 var queryParams = '';
12292 var filterViewName = '';
12293 var selector = '';
12294
12295 // possibility for checkpoints to be lost here as behaviour of
12296 // JSON.stringify is not stable (see #6226)
12297 /* istanbul ignore if */
12298 if (opts.selector) {
12299 selector = JSON.stringify(opts.selector);
12300 }
12301
12302 if (opts.filter && opts.query_params) {
12303 queryParams = JSON.stringify(sortObjectPropertiesByKey(opts.query_params));
12304 }
12305
12306 if (opts.filter && opts.filter === '_view') {
12307 filterViewName = opts.view.toString();
12308 }
12309
12310 return Promise.all([src.id(), target.id()]).then(function (res) {
12311 var queryData = res[0] + res[1] + filterFun + filterViewName +
12312 queryParams + docIds + selector;
12313 return new Promise(function (resolve) {
12314 binaryMd5(queryData, resolve);
12315 });
12316 }).then(function (md5sum) {
12317 // can't use straight-up md5 alphabet, because
12318 // the char '/' is interpreted as being for attachments,
12319 // and + is also not url-safe
12320 md5sum = md5sum.replace(/\//g, '.').replace(/\+/g, '_');
12321 return '_local/' + md5sum;
12322 });
12323}
12324
12325function replicate(src, target, opts, returnValue, result) {
12326 var batches = []; // list of batches to be processed
12327 var currentBatch; // the batch currently being processed
12328 var pendingBatch = {
12329 seq: 0,
12330 changes: [],
12331 docs: []
12332 }; // next batch, not yet ready to be processed
12333 var writingCheckpoint = false; // true while checkpoint is being written
12334 var changesCompleted = false; // true when all changes received
12335 var replicationCompleted = false; // true when replication has completed
12336 var last_seq = 0;
12337 var continuous = opts.continuous || opts.live || false;
12338 var batch_size = opts.batch_size || 100;
12339 var batches_limit = opts.batches_limit || 10;
12340 var style = opts.style || 'all_docs';
12341 var changesPending = false; // true while src.changes is running
12342 var doc_ids = opts.doc_ids;
12343 var selector = opts.selector;
12344 var repId;
12345 var checkpointer;
12346 var changedDocs = [];
12347 // Like couchdb, every replication gets a unique session id
12348 var session = uuid$1();
12349
12350 result = result || {
12351 ok: true,
12352 start_time: new Date().toISOString(),
12353 docs_read: 0,
12354 docs_written: 0,
12355 doc_write_failures: 0,
12356 errors: []
12357 };
12358
12359 var changesOpts = {};
12360 returnValue.ready(src, target);
12361
12362 function initCheckpointer() {
12363 if (checkpointer) {
12364 return Promise.resolve();
12365 }
12366 return generateReplicationId(src, target, opts).then(function (res) {
12367 repId = res;
12368
12369 var checkpointOpts = {};
12370 if (opts.checkpoint === false) {
12371 checkpointOpts = { writeSourceCheckpoint: false, writeTargetCheckpoint: false };
12372 } else if (opts.checkpoint === 'source') {
12373 checkpointOpts = { writeSourceCheckpoint: true, writeTargetCheckpoint: false };
12374 } else if (opts.checkpoint === 'target') {
12375 checkpointOpts = { writeSourceCheckpoint: false, writeTargetCheckpoint: true };
12376 } else {
12377 checkpointOpts = { writeSourceCheckpoint: true, writeTargetCheckpoint: true };
12378 }
12379
12380 checkpointer = new Checkpointer(src, target, repId, returnValue, checkpointOpts);
12381 });
12382 }
12383
12384 function writeDocs() {
12385 changedDocs = [];
12386
12387 if (currentBatch.docs.length === 0) {
12388 return;
12389 }
12390 var docs = currentBatch.docs;
12391 var bulkOpts = {timeout: opts.timeout};
12392 return target.bulkDocs({docs: docs, new_edits: false}, bulkOpts).then(function (res) {
12393 /* istanbul ignore if */
12394 if (returnValue.cancelled) {
12395 completeReplication();
12396 throw new Error('cancelled');
12397 }
12398
12399 // `res` doesn't include full documents (which live in `docs`), so we create a map of
12400 // (id -> error), and check for errors while iterating over `docs`
12401 var errorsById = Object.create(null);
12402 res.forEach(function (res) {
12403 if (res.error) {
12404 errorsById[res.id] = res;
12405 }
12406 });
12407
12408 var errorsNo = Object.keys(errorsById).length;
12409 result.doc_write_failures += errorsNo;
12410 result.docs_written += docs.length - errorsNo;
12411
12412 docs.forEach(function (doc) {
12413 var error = errorsById[doc._id];
12414 if (error) {
12415 result.errors.push(error);
12416 // Normalize error name. i.e. 'Unauthorized' -> 'unauthorized' (eg Sync Gateway)
12417 var errorName = (error.name || '').toLowerCase();
12418 if (errorName === 'unauthorized' || errorName === 'forbidden') {
12419 returnValue.emit('denied', clone(error));
12420 } else {
12421 throw error;
12422 }
12423 } else {
12424 changedDocs.push(doc);
12425 }
12426 });
12427
12428 }, function (err) {
12429 result.doc_write_failures += docs.length;
12430 throw err;
12431 });
12432 }
12433
12434 function finishBatch() {
12435 if (currentBatch.error) {
12436 throw new Error('There was a problem getting docs.');
12437 }
12438 result.last_seq = last_seq = currentBatch.seq;
12439 var outResult = clone(result);
12440 if (changedDocs.length) {
12441 outResult.docs = changedDocs;
12442 // Attach 'pending' property if server supports it (CouchDB 2.0+)
12443 /* istanbul ignore if */
12444 if (typeof currentBatch.pending === 'number') {
12445 outResult.pending = currentBatch.pending;
12446 delete currentBatch.pending;
12447 }
12448 returnValue.emit('change', outResult);
12449 }
12450 writingCheckpoint = true;
12451 return checkpointer.writeCheckpoint(currentBatch.seq,
12452 session).then(function () {
12453 returnValue.emit('checkpoint', { 'checkpoint': currentBatch.seq });
12454 writingCheckpoint = false;
12455 /* istanbul ignore if */
12456 if (returnValue.cancelled) {
12457 completeReplication();
12458 throw new Error('cancelled');
12459 }
12460 currentBatch = undefined;
12461 getChanges();
12462 })["catch"](function (err) {
12463 onCheckpointError(err);
12464 throw err;
12465 });
12466 }
12467
12468 function getDiffs() {
12469 var diff = {};
12470 currentBatch.changes.forEach(function (change) {
12471 returnValue.emit('checkpoint', { 'revs_diff': change });
12472 // Couchbase Sync Gateway emits these, but we can ignore them
12473 /* istanbul ignore if */
12474 if (change.id === "_user/") {
12475 return;
12476 }
12477 diff[change.id] = change.changes.map(function (x) {
12478 return x.rev;
12479 });
12480 });
12481 return target.revsDiff(diff).then(function (diffs) {
12482 /* istanbul ignore if */
12483 if (returnValue.cancelled) {
12484 completeReplication();
12485 throw new Error('cancelled');
12486 }
12487 // currentBatch.diffs elements are deleted as the documents are written
12488 currentBatch.diffs = diffs;
12489 });
12490 }
12491
12492 function getBatchDocs() {
12493 return getDocs(src, target, currentBatch.diffs, returnValue).then(function (got) {
12494 currentBatch.error = !got.ok;
12495 got.docs.forEach(function (doc) {
12496 delete currentBatch.diffs[doc._id];
12497 result.docs_read++;
12498 currentBatch.docs.push(doc);
12499 });
12500 });
12501 }
12502
12503 function startNextBatch() {
12504 if (returnValue.cancelled || currentBatch) {
12505 return;
12506 }
12507 if (batches.length === 0) {
12508 processPendingBatch(true);
12509 return;
12510 }
12511 currentBatch = batches.shift();
12512 returnValue.emit('checkpoint', { 'start_next_batch': currentBatch.seq });
12513 getDiffs()
12514 .then(getBatchDocs)
12515 .then(writeDocs)
12516 .then(finishBatch)
12517 .then(startNextBatch)[
12518 "catch"](function (err) {
12519 abortReplication('batch processing terminated with error', err);
12520 });
12521 }
12522
12523
12524 function processPendingBatch(immediate$$1) {
12525 if (pendingBatch.changes.length === 0) {
12526 if (batches.length === 0 && !currentBatch) {
12527 if ((continuous && changesOpts.live) || changesCompleted) {
12528 returnValue.state = 'pending';
12529 returnValue.emit('paused');
12530 }
12531 if (changesCompleted) {
12532 completeReplication();
12533 }
12534 }
12535 return;
12536 }
12537 if (
12538 immediate$$1 ||
12539 changesCompleted ||
12540 pendingBatch.changes.length >= batch_size
12541 ) {
12542 batches.push(pendingBatch);
12543 pendingBatch = {
12544 seq: 0,
12545 changes: [],
12546 docs: []
12547 };
12548 if (returnValue.state === 'pending' || returnValue.state === 'stopped') {
12549 returnValue.state = 'active';
12550 returnValue.emit('active');
12551 }
12552 startNextBatch();
12553 }
12554 }
12555
12556
12557 function abortReplication(reason, err) {
12558 if (replicationCompleted) {
12559 return;
12560 }
12561 if (!err.message) {
12562 err.message = reason;
12563 }
12564 result.ok = false;
12565 result.status = 'aborting';
12566 batches = [];
12567 pendingBatch = {
12568 seq: 0,
12569 changes: [],
12570 docs: []
12571 };
12572 completeReplication(err);
12573 }
12574
12575
12576 function completeReplication(fatalError) {
12577 if (replicationCompleted) {
12578 return;
12579 }
12580 /* istanbul ignore if */
12581 if (returnValue.cancelled) {
12582 result.status = 'cancelled';
12583 if (writingCheckpoint) {
12584 return;
12585 }
12586 }
12587 result.status = result.status || 'complete';
12588 result.end_time = new Date().toISOString();
12589 result.last_seq = last_seq;
12590 replicationCompleted = true;
12591
12592 if (fatalError) {
12593 // need to extend the error because Firefox considers ".result" read-only
12594 fatalError = createError(fatalError);
12595 fatalError.result = result;
12596
12597 // Normalize error name. i.e. 'Unauthorized' -> 'unauthorized' (eg Sync Gateway)
12598 var errorName = (fatalError.name || '').toLowerCase();
12599 if (errorName === 'unauthorized' || errorName === 'forbidden') {
12600 returnValue.emit('error', fatalError);
12601 returnValue.removeAllListeners();
12602 } else {
12603 backOff(opts, returnValue, fatalError, function () {
12604 replicate(src, target, opts, returnValue);
12605 });
12606 }
12607 } else {
12608 returnValue.emit('complete', result);
12609 returnValue.removeAllListeners();
12610 }
12611 }
12612
12613
12614 function onChange(change, pending, lastSeq) {
12615 /* istanbul ignore if */
12616 if (returnValue.cancelled) {
12617 return completeReplication();
12618 }
12619 // Attach 'pending' property if server supports it (CouchDB 2.0+)
12620 /* istanbul ignore if */
12621 if (typeof pending === 'number') {
12622 pendingBatch.pending = pending;
12623 }
12624
12625 var filter = filterChange(opts)(change);
12626 if (!filter) {
12627 return;
12628 }
12629 pendingBatch.seq = change.seq || lastSeq;
12630 pendingBatch.changes.push(change);
12631 returnValue.emit('checkpoint', { 'pending_batch': pendingBatch.seq });
12632 immediate(function () {
12633 processPendingBatch(batches.length === 0 && changesOpts.live);
12634 });
12635 }
12636
12637
12638 function onChangesComplete(changes) {
12639 changesPending = false;
12640 /* istanbul ignore if */
12641 if (returnValue.cancelled) {
12642 return completeReplication();
12643 }
12644
12645 // if no results were returned then we're done,
12646 // else fetch more
12647 if (changes.results.length > 0) {
12648 changesOpts.since = changes.results[changes.results.length - 1].seq;
12649 getChanges();
12650 processPendingBatch(true);
12651 } else {
12652
12653 var complete = function () {
12654 if (continuous) {
12655 changesOpts.live = true;
12656 getChanges();
12657 } else {
12658 changesCompleted = true;
12659 }
12660 processPendingBatch(true);
12661 };
12662
12663 // update the checkpoint so we start from the right seq next time
12664 if (!currentBatch && changes.results.length === 0) {
12665 writingCheckpoint = true;
12666 checkpointer.writeCheckpoint(changes.last_seq,
12667 session).then(function () {
12668 writingCheckpoint = false;
12669 result.last_seq = last_seq = changes.last_seq;
12670 complete();
12671 })[
12672 "catch"](onCheckpointError);
12673 } else {
12674 complete();
12675 }
12676 }
12677 }
12678
12679
12680 function onChangesError(err) {
12681 changesPending = false;
12682 /* istanbul ignore if */
12683 if (returnValue.cancelled) {
12684 return completeReplication();
12685 }
12686 abortReplication('changes rejected', err);
12687 }
12688
12689
12690 function getChanges() {
12691 if (!(
12692 !changesPending &&
12693 !changesCompleted &&
12694 batches.length < batches_limit
12695 )) {
12696 return;
12697 }
12698 changesPending = true;
12699 function abortChanges() {
12700 changes.cancel();
12701 }
12702 function removeListener() {
12703 returnValue.removeListener('cancel', abortChanges);
12704 }
12705
12706 if (returnValue._changes) { // remove old changes() and listeners
12707 returnValue.removeListener('cancel', returnValue._abortChanges);
12708 returnValue._changes.cancel();
12709 }
12710 returnValue.once('cancel', abortChanges);
12711
12712 var changes = src.changes(changesOpts)
12713 .on('change', onChange);
12714 changes.then(removeListener, removeListener);
12715 changes.then(onChangesComplete)[
12716 "catch"](onChangesError);
12717
12718 if (opts.retry) {
12719 // save for later so we can cancel if necessary
12720 returnValue._changes = changes;
12721 returnValue._abortChanges = abortChanges;
12722 }
12723 }
12724
12725
12726 function startChanges() {
12727 initCheckpointer().then(function () {
12728 /* istanbul ignore if */
12729 if (returnValue.cancelled) {
12730 completeReplication();
12731 return;
12732 }
12733 return checkpointer.getCheckpoint().then(function (checkpoint) {
12734 last_seq = checkpoint;
12735 changesOpts = {
12736 since: last_seq,
12737 limit: batch_size,
12738 batch_size: batch_size,
12739 style: style,
12740 doc_ids: doc_ids,
12741 selector: selector,
12742 return_docs: true // required so we know when we're done
12743 };
12744 if (opts.filter) {
12745 if (typeof opts.filter !== 'string') {
12746 // required for the client-side filter in onChange
12747 changesOpts.include_docs = true;
12748 } else { // ddoc filter
12749 changesOpts.filter = opts.filter;
12750 }
12751 }
12752 if ('heartbeat' in opts) {
12753 changesOpts.heartbeat = opts.heartbeat;
12754 }
12755 if ('timeout' in opts) {
12756 changesOpts.timeout = opts.timeout;
12757 }
12758 if (opts.query_params) {
12759 changesOpts.query_params = opts.query_params;
12760 }
12761 if (opts.view) {
12762 changesOpts.view = opts.view;
12763 }
12764 getChanges();
12765 });
12766 })["catch"](function (err) {
12767 abortReplication('getCheckpoint rejected with ', err);
12768 });
12769 }
12770
12771 /* istanbul ignore next */
12772 function onCheckpointError(err) {
12773 writingCheckpoint = false;
12774 abortReplication('writeCheckpoint completed with error', err);
12775 }
12776
12777 /* istanbul ignore if */
12778 if (returnValue.cancelled) { // cancelled immediately
12779 completeReplication();
12780 return;
12781 }
12782
12783 if (!returnValue._addedListeners) {
12784 returnValue.once('cancel', completeReplication);
12785
12786 if (typeof opts.complete === 'function') {
12787 returnValue.once('error', opts.complete);
12788 returnValue.once('complete', function (result) {
12789 opts.complete(null, result);
12790 });
12791 }
12792 returnValue._addedListeners = true;
12793 }
12794
12795 if (typeof opts.since === 'undefined') {
12796 startChanges();
12797 } else {
12798 initCheckpointer().then(function () {
12799 writingCheckpoint = true;
12800 return checkpointer.writeCheckpoint(opts.since, session);
12801 }).then(function () {
12802 writingCheckpoint = false;
12803 /* istanbul ignore if */
12804 if (returnValue.cancelled) {
12805 completeReplication();
12806 return;
12807 }
12808 last_seq = opts.since;
12809 startChanges();
12810 })["catch"](onCheckpointError);
12811 }
12812}
12813
12814// We create a basic promise so the caller can cancel the replication possibly
12815// before we have actually started listening to changes etc
12816inherits(Replication, EE);
12817function Replication() {
12818 EE.call(this);
12819 this.cancelled = false;
12820 this.state = 'pending';
12821 var self = this;
12822 var promise = new Promise(function (fulfill, reject) {
12823 self.once('complete', fulfill);
12824 self.once('error', reject);
12825 });
12826 self.then = function (resolve, reject) {
12827 return promise.then(resolve, reject);
12828 };
12829 self["catch"] = function (reject) {
12830 return promise["catch"](reject);
12831 };
12832 // As we allow error handling via "error" event as well,
12833 // put a stub in here so that rejecting never throws UnhandledError.
12834 self["catch"](function () {});
12835}
12836
12837Replication.prototype.cancel = function () {
12838 this.cancelled = true;
12839 this.state = 'cancelled';
12840 this.emit('cancel');
12841};
12842
12843Replication.prototype.ready = function (src, target) {
12844 var self = this;
12845 if (self._readyCalled) {
12846 return;
12847 }
12848 self._readyCalled = true;
12849
12850 function onDestroy() {
12851 self.cancel();
12852 }
12853 src.once('destroyed', onDestroy);
12854 target.once('destroyed', onDestroy);
12855 function cleanup() {
12856 src.removeListener('destroyed', onDestroy);
12857 target.removeListener('destroyed', onDestroy);
12858 }
12859 self.once('complete', cleanup);
12860 self.once('error', cleanup);
12861};
12862
12863function toPouch(db, opts) {
12864 var PouchConstructor = opts.PouchConstructor;
12865 if (typeof db === 'string') {
12866 return new PouchConstructor(db, opts);
12867 } else {
12868 return db;
12869 }
12870}
12871
12872function replicateWrapper(src, target, opts, callback) {
12873
12874 if (typeof opts === 'function') {
12875 callback = opts;
12876 opts = {};
12877 }
12878 if (typeof opts === 'undefined') {
12879 opts = {};
12880 }
12881
12882 if (opts.doc_ids && !Array.isArray(opts.doc_ids)) {
12883 throw createError(BAD_REQUEST,
12884 "`doc_ids` filter parameter is not a list.");
12885 }
12886
12887 opts.complete = callback;
12888 opts = clone(opts);
12889 opts.continuous = opts.continuous || opts.live;
12890 opts.retry = ('retry' in opts) ? opts.retry : false;
12891 /*jshint validthis:true */
12892 opts.PouchConstructor = opts.PouchConstructor || this;
12893 var replicateRet = new Replication(opts);
12894 var srcPouch = toPouch(src, opts);
12895 var targetPouch = toPouch(target, opts);
12896 replicate(srcPouch, targetPouch, opts, replicateRet);
12897 return replicateRet;
12898}
12899
12900inherits(Sync, EE);
12901function sync(src, target, opts, callback) {
12902 if (typeof opts === 'function') {
12903 callback = opts;
12904 opts = {};
12905 }
12906 if (typeof opts === 'undefined') {
12907 opts = {};
12908 }
12909 opts = clone(opts);
12910 /*jshint validthis:true */
12911 opts.PouchConstructor = opts.PouchConstructor || this;
12912 src = toPouch(src, opts);
12913 target = toPouch(target, opts);
12914 return new Sync(src, target, opts, callback);
12915}
12916
12917function Sync(src, target, opts, callback) {
12918 var self = this;
12919 this.canceled = false;
12920
12921 var optsPush = opts.push ? $inject_Object_assign({}, opts, opts.push) : opts;
12922 var optsPull = opts.pull ? $inject_Object_assign({}, opts, opts.pull) : opts;
12923
12924 this.push = replicateWrapper(src, target, optsPush);
12925 this.pull = replicateWrapper(target, src, optsPull);
12926
12927 this.pushPaused = true;
12928 this.pullPaused = true;
12929
12930 function pullChange(change) {
12931 self.emit('change', {
12932 direction: 'pull',
12933 change: change
12934 });
12935 }
12936 function pushChange(change) {
12937 self.emit('change', {
12938 direction: 'push',
12939 change: change
12940 });
12941 }
12942 function pushDenied(doc) {
12943 self.emit('denied', {
12944 direction: 'push',
12945 doc: doc
12946 });
12947 }
12948 function pullDenied(doc) {
12949 self.emit('denied', {
12950 direction: 'pull',
12951 doc: doc
12952 });
12953 }
12954 function pushPaused() {
12955 self.pushPaused = true;
12956 /* istanbul ignore if */
12957 if (self.pullPaused) {
12958 self.emit('paused');
12959 }
12960 }
12961 function pullPaused() {
12962 self.pullPaused = true;
12963 /* istanbul ignore if */
12964 if (self.pushPaused) {
12965 self.emit('paused');
12966 }
12967 }
12968 function pushActive() {
12969 self.pushPaused = false;
12970 /* istanbul ignore if */
12971 if (self.pullPaused) {
12972 self.emit('active', {
12973 direction: 'push'
12974 });
12975 }
12976 }
12977 function pullActive() {
12978 self.pullPaused = false;
12979 /* istanbul ignore if */
12980 if (self.pushPaused) {
12981 self.emit('active', {
12982 direction: 'pull'
12983 });
12984 }
12985 }
12986
12987 var removed = {};
12988
12989 function removeAll(type) { // type is 'push' or 'pull'
12990 return function (event, func) {
12991 var isChange = event === 'change' &&
12992 (func === pullChange || func === pushChange);
12993 var isDenied = event === 'denied' &&
12994 (func === pullDenied || func === pushDenied);
12995 var isPaused = event === 'paused' &&
12996 (func === pullPaused || func === pushPaused);
12997 var isActive = event === 'active' &&
12998 (func === pullActive || func === pushActive);
12999
13000 if (isChange || isDenied || isPaused || isActive) {
13001 if (!(event in removed)) {
13002 removed[event] = {};
13003 }
13004 removed[event][type] = true;
13005 if (Object.keys(removed[event]).length === 2) {
13006 // both push and pull have asked to be removed
13007 self.removeAllListeners(event);
13008 }
13009 }
13010 };
13011 }
13012
13013 if (opts.live) {
13014 this.push.on('complete', self.pull.cancel.bind(self.pull));
13015 this.pull.on('complete', self.push.cancel.bind(self.push));
13016 }
13017
13018 function addOneListener(ee, event, listener) {
13019 if (ee.listeners(event).indexOf(listener) == -1) {
13020 ee.on(event, listener);
13021 }
13022 }
13023
13024 this.on('newListener', function (event) {
13025 if (event === 'change') {
13026 addOneListener(self.pull, 'change', pullChange);
13027 addOneListener(self.push, 'change', pushChange);
13028 } else if (event === 'denied') {
13029 addOneListener(self.pull, 'denied', pullDenied);
13030 addOneListener(self.push, 'denied', pushDenied);
13031 } else if (event === 'active') {
13032 addOneListener(self.pull, 'active', pullActive);
13033 addOneListener(self.push, 'active', pushActive);
13034 } else if (event === 'paused') {
13035 addOneListener(self.pull, 'paused', pullPaused);
13036 addOneListener(self.push, 'paused', pushPaused);
13037 }
13038 });
13039
13040 this.on('removeListener', function (event) {
13041 if (event === 'change') {
13042 self.pull.removeListener('change', pullChange);
13043 self.push.removeListener('change', pushChange);
13044 } else if (event === 'denied') {
13045 self.pull.removeListener('denied', pullDenied);
13046 self.push.removeListener('denied', pushDenied);
13047 } else if (event === 'active') {
13048 self.pull.removeListener('active', pullActive);
13049 self.push.removeListener('active', pushActive);
13050 } else if (event === 'paused') {
13051 self.pull.removeListener('paused', pullPaused);
13052 self.push.removeListener('paused', pushPaused);
13053 }
13054 });
13055
13056 this.pull.on('removeListener', removeAll('pull'));
13057 this.push.on('removeListener', removeAll('push'));
13058
13059 var promise = Promise.all([
13060 this.push,
13061 this.pull
13062 ]).then(function (resp) {
13063 var out = {
13064 push: resp[0],
13065 pull: resp[1]
13066 };
13067 self.emit('complete', out);
13068 if (callback) {
13069 callback(null, out);
13070 }
13071 self.removeAllListeners();
13072 return out;
13073 }, function (err) {
13074 self.cancel();
13075 if (callback) {
13076 // if there's a callback, then the callback can receive
13077 // the error event
13078 callback(err);
13079 } else {
13080 // if there's no callback, then we're safe to emit an error
13081 // event, which would otherwise throw an unhandled error
13082 // due to 'error' being a special event in EventEmitters
13083 self.emit('error', err);
13084 }
13085 self.removeAllListeners();
13086 if (callback) {
13087 // no sense throwing if we're already emitting an 'error' event
13088 throw err;
13089 }
13090 });
13091
13092 this.then = function (success, err) {
13093 return promise.then(success, err);
13094 };
13095
13096 this["catch"] = function (err) {
13097 return promise["catch"](err);
13098 };
13099}
13100
13101Sync.prototype.cancel = function () {
13102 if (!this.canceled) {
13103 this.canceled = true;
13104 this.push.cancel();
13105 this.pull.cancel();
13106 }
13107};
13108
13109function replication(PouchDB) {
13110 PouchDB.replicate = replicateWrapper;
13111 PouchDB.sync = sync;
13112
13113 Object.defineProperty(PouchDB.prototype, 'replicate', {
13114 get: function () {
13115 var self = this;
13116 if (typeof this.replicateMethods === 'undefined') {
13117 this.replicateMethods = {
13118 from: function (other, opts, callback) {
13119 return self.constructor.replicate(other, self, opts, callback);
13120 },
13121 to: function (other, opts, callback) {
13122 return self.constructor.replicate(self, other, opts, callback);
13123 }
13124 };
13125 }
13126 return this.replicateMethods;
13127 }
13128 });
13129
13130 PouchDB.prototype.sync = function (dbName, opts, callback) {
13131 return this.constructor.sync(this, dbName, opts, callback);
13132 };
13133}
13134
13135PouchDB.plugin(IDBPouch)
13136 .plugin(HttpPouch$1)
13137 .plugin(mapreduce)
13138 .plugin(replication);
13139
13140// Pull from src because pouchdb-node/pouchdb-browser themselves
13141
13142module.exports = PouchDB;
13143
13144}).call(this)}).call(this,_dereq_(11))
13145},{"1":1,"10":10,"11":11,"12":12,"13":13,"28":28,"3":3,"4":4}]},{},[29])(29)
13146});