UNPKG

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