From b697c82279101c3b97d283998f8511915caedb7b Mon Sep 17 00:00:00 2001 From: Enguerran Date: Thu, 30 Nov 2017 17:51:20 +0100 Subject: [PATCH] release 0.4.3 --- dist/cozy-client.js | 919 ++++++++++++++--------------------- dist/cozy-client.js.map | 2 +- dist/cozy-client.min.js | 18 +- dist/cozy-client.min.js.map | 2 +- dist/cozy-client.node.js | 823 +++---------------------------- dist/cozy-client.node.js.map | 2 +- 6 files changed, 458 insertions(+), 1308 deletions(-) diff --git a/dist/cozy-client.js b/dist/cozy-client.js index 5c29f704..4b169887 100644 --- a/dist/cozy-client.js +++ b/dist/cozy-client.js @@ -545,49 +545,49 @@ return /******/ (function(modules) { // webpackBootstrap var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /* global fetch URL */ - var _utils = __webpack_require__(192); + var _utils = __webpack_require__(4); - var _auth_storage = __webpack_require__(193); + var _auth_storage = __webpack_require__(5); - var _auth_v = __webpack_require__(194); + var _auth_v = __webpack_require__(6); - var _auth_v2 = __webpack_require__(195); + var _auth_v2 = __webpack_require__(7); var auth = _interopRequireWildcard(_auth_v2); - var _data = __webpack_require__(198); + var _data = __webpack_require__(10); var data = _interopRequireWildcard(_data); - var _fetch = __webpack_require__(196); + var _fetch = __webpack_require__(8); var cozyFetch = _interopRequireWildcard(_fetch); - var _mango = __webpack_require__(200); + var _mango = __webpack_require__(12); var mango = _interopRequireWildcard(_mango); - var _files = __webpack_require__(201); + var _files = __webpack_require__(13); var files = _interopRequireWildcard(_files); - var _intents = __webpack_require__(202); + var _intents = __webpack_require__(14); var intents = _interopRequireWildcard(_intents); - var _jobs = __webpack_require__(203); + var _jobs = __webpack_require__(15); var jobs = _interopRequireWildcard(_jobs); - var _offline = __webpack_require__(204); + var _offline = __webpack_require__(16); var offline = _interopRequireWildcard(_offline); - var _settings = __webpack_require__(246); + var _settings = __webpack_require__(59); var settings = _interopRequireWildcard(_settings); - var _relations = __webpack_require__(247); + var _relations = __webpack_require__(60); var relations = _interopRequireWildcard(_relations); @@ -911,380 +911,7 @@ return /******/ (function(modules) { // webpackBootstrap Object.assign(module.exports, { Client: Client, LocalStorage: _auth_storage.LocalStorage, MemoryStorage: _auth_storage.MemoryStorage }); /***/ }, -/* 4 */, -/* 5 */, -/* 6 */, -/* 7 */, -/* 8 */, -/* 9 */, -/* 10 */, -/* 11 */, -/* 12 */, -/* 13 */, -/* 14 */, -/* 15 */, -/* 16 */, -/* 17 */, -/* 18 */, -/* 19 */, -/* 20 */, -/* 21 */, -/* 22 */, -/* 23 */, -/* 24 */, -/* 25 */, -/* 26 */, -/* 27 */, -/* 28 */, -/* 29 */, -/* 30 */, -/* 31 */, -/* 32 */, -/* 33 */, -/* 34 */, -/* 35 */, -/* 36 */, -/* 37 */, -/* 38 */, -/* 39 */, -/* 40 */, -/* 41 */, -/* 42 */, -/* 43 */, -/* 44 */, -/* 45 */, -/* 46 */, -/* 47 */, -/* 48 */, -/* 49 */, -/* 50 */, -/* 51 */, -/* 52 */, -/* 53 */, -/* 54 */, -/* 55 */, -/* 56 */, -/* 57 */, -/* 58 */, -/* 59 */, -/* 60 */, -/* 61 */, -/* 62 */, -/* 63 */, -/* 64 */, -/* 65 */, -/* 66 */, -/* 67 */, -/* 68 */, -/* 69 */, -/* 70 */, -/* 71 */, -/* 72 */, -/* 73 */, -/* 74 */, -/* 75 */, -/* 76 */, -/* 77 */, -/* 78 */, -/* 79 */, -/* 80 */, -/* 81 */, -/* 82 */, -/* 83 */, -/* 84 */, -/* 85 */, -/* 86 */, -/* 87 */, -/* 88 */, -/* 89 */, -/* 90 */, -/* 91 */, -/* 92 */, -/* 93 */, -/* 94 */, -/* 95 */, -/* 96 */, -/* 97 */, -/* 98 */, -/* 99 */, -/* 100 */, -/* 101 */, -/* 102 */, -/* 103 */, -/* 104 */, -/* 105 */, -/* 106 */, -/* 107 */, -/* 108 */, -/* 109 */, -/* 110 */, -/* 111 */, -/* 112 */, -/* 113 */, -/* 114 */, -/* 115 */, -/* 116 */, -/* 117 */, -/* 118 */, -/* 119 */, -/* 120 */, -/* 121 */, -/* 122 */, -/* 123 */, -/* 124 */, -/* 125 */, -/* 126 */, -/* 127 */, -/* 128 */, -/* 129 */, -/* 130 */, -/* 131 */, -/* 132 */, -/* 133 */, -/* 134 */, -/* 135 */, -/* 136 */, -/* 137 */, -/* 138 */, -/* 139 */, -/* 140 */, -/* 141 */, -/* 142 */, -/* 143 */, -/* 144 */, -/* 145 */, -/* 146 */, -/* 147 */, -/* 148 */, -/* 149 */, -/* 150 */, -/* 151 */, -/* 152 */, -/* 153 */, -/* 154 */, -/* 155 */, -/* 156 */, -/* 157 */, -/* 158 */, -/* 159 */, -/* 160 */, -/* 161 */, -/* 162 */, -/* 163 */, -/* 164 */, -/* 165 */, -/* 166 */, -/* 167 */, -/* 168 */, -/* 169 */, -/* 170 */, -/* 171 */, -/* 172 */, -/* 173 */, -/* 174 */, -/* 175 */, -/* 176 */, -/* 177 */, -/* 178 */, -/* 179 */, -/* 180 */, -/* 181 */, -/* 182 */, -/* 183 */, -/* 184 */, -/* 185 */, -/* 186 */, -/* 187 */, -/* 188 */, -/* 189 */, -/* 190 */, -/* 191 */ -/***/ function(module, exports) { - - // shim for using process in browser - var process = module.exports = {}; - - // cached from whatever global is present so that test runners that stub it - // don't break things. But we need to wrap it in a try catch in case it is - // wrapped in strict mode code which doesn't define any globals. It's inside a - // function because try/catches deoptimize in certain engines. - - var cachedSetTimeout; - var cachedClearTimeout; - - function defaultSetTimout() { - throw new Error('setTimeout has not been defined'); - } - function defaultClearTimeout () { - throw new Error('clearTimeout has not been defined'); - } - (function () { - try { - if (typeof setTimeout === 'function') { - cachedSetTimeout = setTimeout; - } else { - cachedSetTimeout = defaultSetTimout; - } - } catch (e) { - cachedSetTimeout = defaultSetTimout; - } - try { - if (typeof clearTimeout === 'function') { - cachedClearTimeout = clearTimeout; - } else { - cachedClearTimeout = defaultClearTimeout; - } - } catch (e) { - cachedClearTimeout = defaultClearTimeout; - } - } ()) - function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); - } - // if setTimeout wasn't available but was latter defined - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch(e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch(e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); - } - } - - - } - function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } - // if clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); - } - } - - - - } - var queue = []; - var draining = false; - var currentQueue; - var queueIndex = -1; - - function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); - } - } - - function drainQueue() { - if (draining) { - return; - } - var timeout = runTimeout(cleanUpNextTick); - draining = true; - - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; - } - currentQueue = null; - draining = false; - runClearTimeout(timeout); - } - - process.nextTick = function (fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); - } - }; - - // v8 likes predictible objects - function Item(fun, array) { - this.fun = fun; - this.array = array; - } - Item.prototype.run = function () { - this.fun.apply(null, this.array); - }; - process.title = 'browser'; - process.browser = true; - process.env = {}; - process.argv = []; - process.version = ''; // empty string to avoid regexp issues - process.versions = {}; - - function noop() {} - - process.on = noop; - process.addListener = noop; - process.once = noop; - process.off = noop; - process.removeListener = noop; - process.removeAllListeners = noop; - process.emit = noop; - - process.binding = function (name) { - throw new Error('process.binding is not supported'); - }; - - process.cwd = function () { return '/' }; - process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); - }; - process.umask = function() { return 0; }; - - -/***/ }, -/* 192 */ +/* 4 */ /***/ function(module, exports) { 'use strict'; @@ -1457,7 +1084,7 @@ return /******/ (function(modules) { // webpackBootstrap } /***/ }, -/* 193 */ +/* 5 */ /***/ function(module, exports) { 'use strict'; @@ -1571,7 +1198,7 @@ return /******/ (function(modules) { // webpackBootstrap }(); /***/ }, -/* 194 */ +/* 6 */ /***/ function(module, exports) { 'use strict'; @@ -1643,7 +1270,7 @@ return /******/ (function(modules) { // webpackBootstrap }(); /***/ }, -/* 195 */ +/* 7 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -1668,9 +1295,9 @@ return /******/ (function(modules) { // webpackBootstrap exports.refreshToken = refreshToken; exports.oauthFlow = oauthFlow; - var _utils = __webpack_require__(192); + var _utils = __webpack_require__(4); - var _fetch = __webpack_require__(196); + var _fetch = __webpack_require__(8); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } @@ -2121,7 +1748,7 @@ return /******/ (function(modules) { // webpackBootstrap } /***/ }, -/* 196 */ +/* 8 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -2138,11 +1765,11 @@ return /******/ (function(modules) { // webpackBootstrap exports.cozyFetchJSON = cozyFetchJSON; exports.cozyFetchRawJSON = cozyFetchRawJSON; - var _auth_v = __webpack_require__(195); + var _auth_v = __webpack_require__(7); - var _utils = __webpack_require__(192); + var _utils = __webpack_require__(4); - var _jsonapi = __webpack_require__(197); + var _jsonapi = __webpack_require__(9); var _jsonapi2 = _interopRequireDefault(_jsonapi); @@ -2319,7 +1946,7 @@ return /******/ (function(modules) { // webpackBootstrap }; /***/ }, -/* 197 */ +/* 9 */ /***/ function(module, exports) { 'use strict'; @@ -2385,7 +2012,7 @@ return /******/ (function(modules) { // webpackBootstrap exports.default = handleTopLevel; /***/ }, -/* 198 */ +/* 10 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -2402,11 +2029,11 @@ return /******/ (function(modules) { // webpackBootstrap exports.updateAttributes = updateAttributes; exports._delete = _delete; - var _utils = __webpack_require__(192); + var _utils = __webpack_require__(4); - var _doctypes = __webpack_require__(199); + var _doctypes = __webpack_require__(11); - var _fetch = __webpack_require__(196); + var _fetch = __webpack_require__(8); var NOREV = 'stack-v2-no-rev'; @@ -2668,7 +2295,7 @@ return /******/ (function(modules) { // webpackBootstrap } /***/ }, -/* 199 */ +/* 11 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -2679,7 +2306,7 @@ return /******/ (function(modules) { // webpackBootstrap exports.DOCTYPE_FILES = undefined; exports.normalizeDoctype = normalizeDoctype; - var _utils = __webpack_require__(192); + var _utils = __webpack_require__(4); var DOCTYPE_FILES = exports.DOCTYPE_FILES = 'io.cozy.files'; @@ -2716,7 +2343,7 @@ return /******/ (function(modules) { // webpackBootstrap } /***/ }, -/* 200 */ +/* 12 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -2736,11 +2363,11 @@ return /******/ (function(modules) { // webpackBootstrap exports.normalizeSelector = normalizeSelector; exports.makeMapReduceQuery = makeMapReduceQuery; - var _utils = __webpack_require__(192); + var _utils = __webpack_require__(4); - var _doctypes = __webpack_require__(199); + var _doctypes = __webpack_require__(11); - var _fetch = __webpack_require__(196); + var _fetch = __webpack_require__(8); function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } @@ -3041,7 +2668,7 @@ return /******/ (function(modules) { // webpackBootstrap } /***/ }, -/* 201 */ +/* 13 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -3078,13 +2705,13 @@ return /******/ (function(modules) { // webpackBootstrap exports.restoreById = restoreById; exports.destroyById = destroyById; - var _fetch = __webpack_require__(196); + var _fetch = __webpack_require__(8); - var _jsonapi = __webpack_require__(197); + var _jsonapi = __webpack_require__(9); var _jsonapi2 = _interopRequireDefault(_jsonapi); - var _doctypes = __webpack_require__(199); + var _doctypes = __webpack_require__(11); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -3094,6 +2721,10 @@ return /******/ (function(modules) { // webpackBootstrap var contentTypeOctetStream = 'application/octet-stream'; + function sanitizeFileName(name) { + return name && name.trim(); + } + function doUpload(cozy, data, method, path, options) { if (!data) { throw new Error('missing data argument'); @@ -3175,6 +2806,8 @@ return /******/ (function(modules) { // webpackBootstrap name = data.name; } + name = sanitizeFileName(name); + if (typeof name !== 'string' || name === '') { throw new Error('missing name argument'); } @@ -3194,6 +2827,8 @@ return /******/ (function(modules) { // webpackBootstrap dirID = _ref3.dirID, lastModifiedDate = _ref3.lastModifiedDate; + name = sanitizeFileName(name); + if (typeof name !== 'string' || name === '') { throw new Error('missing name argument'); } @@ -3214,6 +2849,8 @@ return /******/ (function(modules) { // webpackBootstrap function getDirectoryOrCreate(cozy, name, parentDirectory) { if (parentDirectory && !parentDirectory.attributes) throw new Error('Malformed parent directory'); + name = sanitizeFileName(name); + var path = (parentDirectory._id === ROOT_DIR_ID ? '' : parentDirectory.attributes.path) + '/' + name; return cozy.files.statByPath(path || '/').catch(function (error) { @@ -3256,7 +2893,11 @@ return /******/ (function(modules) { // webpackBootstrap var _ref4 = options || {}, ifMatch = _ref4.ifMatch; - var body = { data: { attributes: attrs } }; + var body = { + data: { + attributes: Object.assign({}, attrs, { name: sanitizeFileName(attrs.name) }) + } + }; return (0, _fetch.cozyFetchJSON)(cozy, 'PATCH', path, body, { headers: { 'If-Match': ifMatch || '' @@ -3485,7 +3126,7 @@ return /******/ (function(modules) { // webpackBootstrap } /***/ }, -/* 202 */ +/* 14 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -3496,7 +3137,7 @@ return /******/ (function(modules) { // webpackBootstrap exports.create = create; exports.createService = createService; - var _fetch = __webpack_require__(196); + var _fetch = __webpack_require__(8); var intentClass = 'coz-intent'; @@ -3736,7 +3377,7 @@ return /******/ (function(modules) { // webpackBootstrap } /***/ }, -/* 203 */ +/* 15 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -3748,7 +3389,7 @@ return /******/ (function(modules) { // webpackBootstrap exports.queued = queued; exports.create = create; - var _fetch = __webpack_require__(196); + var _fetch = __webpack_require__(8); function count(cozy, workerType) { return (0, _fetch.cozyFetchJSON)(cozy, 'GET', '/jobs/queue/' + workerType).then(function (data) { @@ -3773,7 +3414,7 @@ return /******/ (function(modules) { // webpackBootstrap } /***/ }, -/* 204 */ +/* 16 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -3799,17 +3440,17 @@ return /******/ (function(modules) { // webpackBootstrap exports.stopRepeatedReplication = stopRepeatedReplication; exports.stopAllRepeatedReplication = stopAllRepeatedReplication; - var _doctypes = __webpack_require__(199); + var _doctypes = __webpack_require__(11); - var _auth_v = __webpack_require__(195); + var _auth_v = __webpack_require__(7); - var _utils = __webpack_require__(192); + var _utils = __webpack_require__(4); - var _pouchdb = __webpack_require__(205); + var _pouchdb = __webpack_require__(17); var _pouchdb2 = _interopRequireDefault(_pouchdb); - var _pouchdbFind = __webpack_require__(217); + var _pouchdbFind = __webpack_require__(30); var _pouchdbFind2 = _interopRequireDefault(_pouchdbFind); @@ -4103,22 +3744,22 @@ return /******/ (function(modules) { // webpackBootstrap } /***/ }, -/* 205 */ +/* 17 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {'use strict'; function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - var lie = _interopDefault(__webpack_require__(206)); - var getArguments = _interopDefault(__webpack_require__(208)); - var debug = _interopDefault(__webpack_require__(209)); - var events = __webpack_require__(212); - var inherits = _interopDefault(__webpack_require__(213)); - var nextTick = _interopDefault(__webpack_require__(207)); - var scopedEval = _interopDefault(__webpack_require__(214)); - var Md5 = _interopDefault(__webpack_require__(215)); - var vuvuzela = _interopDefault(__webpack_require__(216)); + var lie = _interopDefault(__webpack_require__(18)); + var getArguments = _interopDefault(__webpack_require__(20)); + var debug = _interopDefault(__webpack_require__(21)); + var events = __webpack_require__(25); + var inherits = _interopDefault(__webpack_require__(26)); + var nextTick = _interopDefault(__webpack_require__(19)); + var scopedEval = _interopDefault(__webpack_require__(27)); + var Md5 = _interopDefault(__webpack_require__(28)); + var vuvuzela = _interopDefault(__webpack_require__(29)); /* istanbul ignore next */ var PouchPromise$1 = typeof Promise === 'function' ? Promise : lie; @@ -15444,11 +15085,11 @@ return /******/ (function(modules) { // webpackBootstrap /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, -/* 206 */ +/* 18 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var immediate = __webpack_require__(207); + var immediate = __webpack_require__(19); /* istanbul ignore next */ function INTERNAL() {} @@ -15703,7 +15344,7 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, -/* 207 */ +/* 19 */ /***/ function(module, exports) { /* WEBPACK VAR INJECTION */(function(global) {'use strict'; @@ -15779,7 +15420,7 @@ return /******/ (function(modules) { // webpackBootstrap /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, -/* 208 */ +/* 20 */ /***/ function(module, exports) { 'use strict'; @@ -15803,7 +15444,7 @@ return /******/ (function(modules) { // webpackBootstrap } /***/ }, -/* 209 */ +/* 21 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** @@ -15812,7 +15453,7 @@ return /******/ (function(modules) { // webpackBootstrap * Expose `debug()` as the module. */ - exports = module.exports = __webpack_require__(210); + exports = module.exports = __webpack_require__(23); exports.log = log; exports.formatArgs = formatArgs; exports.save = save; @@ -15989,10 +15630,196 @@ return /******/ (function(modules) { // webpackBootstrap } catch (e) {} } - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(191))) + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(22))) + +/***/ }, +/* 22 */ +/***/ function(module, exports) { + + // shim for using process in browser + var process = module.exports = {}; + + // cached from whatever global is present so that test runners that stub it + // don't break things. But we need to wrap it in a try catch in case it is + // wrapped in strict mode code which doesn't define any globals. It's inside a + // function because try/catches deoptimize in certain engines. + + var cachedSetTimeout; + var cachedClearTimeout; + + function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); + } + function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); + } + (function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } + } ()) + function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + + } + function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + + } + var queue = []; + var draining = false; + var currentQueue; + var queueIndex = -1; + + function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } + } + + function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); + } + + process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } + }; + + // v8 likes predictible objects + function Item(fun, array) { + this.fun = fun; + this.array = array; + } + Item.prototype.run = function () { + this.fun.apply(null, this.array); + }; + process.title = 'browser'; + process.browser = true; + process.env = {}; + process.argv = []; + process.version = ''; // empty string to avoid regexp issues + process.versions = {}; + + function noop() {} + + process.on = noop; + process.addListener = noop; + process.once = noop; + process.off = noop; + process.removeListener = noop; + process.removeAllListeners = noop; + process.emit = noop; + + process.binding = function (name) { + throw new Error('process.binding is not supported'); + }; + + process.cwd = function () { return '/' }; + process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); + }; + process.umask = function() { return 0; }; + /***/ }, -/* 210 */ +/* 23 */ /***/ function(module, exports, __webpack_require__) { @@ -16008,7 +15835,7 @@ return /******/ (function(modules) { // webpackBootstrap exports.disable = disable; exports.enable = enable; exports.enabled = enabled; - exports.humanize = __webpack_require__(211); + exports.humanize = __webpack_require__(24); /** * The currently active debug mode names, and names to skip. @@ -16197,7 +16024,7 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, -/* 211 */ +/* 24 */ /***/ function(module, exports) { /** @@ -16352,7 +16179,7 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, -/* 212 */ +/* 25 */ /***/ function(module, exports) { // Copyright Joyent, Inc. and other Node contributors. @@ -16660,7 +16487,7 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, -/* 213 */ +/* 26 */ /***/ function(module, exports) { if (typeof Object.create === 'function') { @@ -16689,7 +16516,7 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, -/* 214 */ +/* 27 */ /***/ function(module, exports) { // Generated by CoffeeScript 1.9.2 @@ -16717,7 +16544,7 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, -/* 215 */ +/* 28 */ /***/ function(module, exports, __webpack_require__) { (function (factory) { @@ -17474,7 +17301,7 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, -/* 216 */ +/* 29 */ /***/ function(module, exports) { 'use strict'; @@ -17653,15 +17480,15 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, -/* 217 */ +/* 30 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var utils = __webpack_require__(218); + var utils = __webpack_require__(31); - var httpIndexes = __webpack_require__(224); - var localIndexes = __webpack_require__(226); + var httpIndexes = __webpack_require__(37); + var localIndexes = __webpack_require__(39); var plugin = {}; plugin.createIndex = utils.toPromise(function (requestDef, callback) { @@ -17718,12 +17545,12 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, -/* 218 */ +/* 31 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {'use strict'; - var Promise = __webpack_require__(219); + var Promise = __webpack_require__(32); /* istanbul ignore next */ exports.once = function (fun) { @@ -17797,14 +17624,14 @@ return /******/ (function(modules) { // webpackBootstrap }); }; - exports.inherits = __webpack_require__(213); + exports.inherits = __webpack_require__(26); exports.Promise = Promise; exports.clone = function (obj) { return exports.extend(true, {}, obj); }; - exports.extend = __webpack_require__(221); + exports.extend = __webpack_require__(34); exports.callbackify = function (fun) { return exports.getArguments(function (args) { @@ -17828,8 +17655,8 @@ return /******/ (function(modules) { // webpackBootstrap return promise; }; - var crypto = __webpack_require__(222); - var Md5 = __webpack_require__(223); + var crypto = __webpack_require__(35); + var Md5 = __webpack_require__(36); exports.MD5 = function (string) { /* istanbul ignore else */ @@ -18007,19 +17834,19 @@ return /******/ (function(modules) { // webpackBootstrap }); }; - exports.log = __webpack_require__(209)('pouchdb:find'); + exports.log = __webpack_require__(21)('pouchdb:find'); - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(191))) + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(22))) /***/ }, -/* 219 */ +/* 32 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - var lie = _interopDefault(__webpack_require__(220)); + var lie = _interopDefault(__webpack_require__(33)); /* istanbul ignore next */ var PouchPromise = typeof Promise === 'function' ? Promise : lie; @@ -18027,11 +17854,11 @@ return /******/ (function(modules) { // webpackBootstrap module.exports = PouchPromise; /***/ }, -/* 220 */ +/* 33 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {'use strict'; - var immediate = __webpack_require__(207); + var immediate = __webpack_require__(19); /* istanbul ignore next */ function INTERNAL() {} @@ -18309,10 +18136,10 @@ return /******/ (function(modules) { // webpackBootstrap } } - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(191))) + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(22))) /***/ }, -/* 221 */ +/* 34 */ /***/ function(module, exports) { "use strict"; @@ -18497,13 +18324,13 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, -/* 222 */ +/* 35 */ /***/ function(module, exports) { /* (ignored) */ /***/ }, -/* 223 */ +/* 36 */ /***/ function(module, exports, __webpack_require__) { /*jshint bitwise:false*/ @@ -19108,12 +18935,12 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, -/* 224 */ +/* 37 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var massageCreateIndexRequest = __webpack_require__(225); + var massageCreateIndexRequest = __webpack_require__(38); function createIndex(db, requestDef, callback) { requestDef = massageCreateIndexRequest(requestDef); @@ -19169,12 +18996,12 @@ return /******/ (function(modules) { // webpackBootstrap exports.deleteIndex = deleteIndex; /***/ }, -/* 225 */ +/* 38 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var utils = __webpack_require__(218); + var utils = __webpack_require__(31); var clone = utils.clone; // we restucture the supplied JSON considerably, because the official @@ -19207,34 +19034,34 @@ return /******/ (function(modules) { // webpackBootstrap }; /***/ }, -/* 226 */ +/* 39 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var utils = __webpack_require__(218); + var utils = __webpack_require__(31); var callbackify = utils.callbackify; - exports.createIndex = callbackify(__webpack_require__(227)); - exports.find = callbackify(__webpack_require__(240)); - exports.getIndexes = callbackify(__webpack_require__(241)); - exports.deleteIndex = callbackify(__webpack_require__(245)); + exports.createIndex = callbackify(__webpack_require__(40)); + exports.find = callbackify(__webpack_require__(53)); + exports.getIndexes = callbackify(__webpack_require__(54)); + exports.deleteIndex = callbackify(__webpack_require__(58)); /***/ }, -/* 227 */ +/* 40 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var utils = __webpack_require__(218); + var utils = __webpack_require__(31); var log = utils.log; - var pouchUpsert = __webpack_require__(228); - var abstractMapper = __webpack_require__(230); - var localUtils = __webpack_require__(231); + var pouchUpsert = __webpack_require__(41); + var abstractMapper = __webpack_require__(43); + var localUtils = __webpack_require__(44); var validateIndex = localUtils.validateIndex; var massageIndexDef = localUtils.massageIndexDef; - var massageCreateIndexRequest = __webpack_require__(225); + var massageCreateIndexRequest = __webpack_require__(38); function upsert(db, docId, diffFun) { return pouchUpsert.upsert.call(db, docId, diffFun); @@ -19313,12 +19140,12 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, -/* 228 */ +/* 41 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var PouchPromise = __webpack_require__(229); + var PouchPromise = __webpack_require__(42); // this is essentially the "update sugar" function from daleharvey/pouchdb#1388 // the diffFun tells us what delta to apply to the doc. it either returns @@ -19412,14 +19239,14 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, -/* 229 */ +/* 42 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - var lie = _interopDefault(__webpack_require__(220)); + var lie = _interopDefault(__webpack_require__(33)); /* istanbul ignore next */ var PouchPromise = typeof Promise === 'function' ? Promise : lie; @@ -19427,13 +19254,13 @@ return /******/ (function(modules) { // webpackBootstrap module.exports = PouchPromise; /***/ }, -/* 230 */ +/* 43 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var localUtils = __webpack_require__(231); - var abstractMapReduce = __webpack_require__(234); + var localUtils = __webpack_require__(44); + var abstractMapReduce = __webpack_require__(47); var parseField = localUtils.parseField; // @@ -19564,13 +19391,13 @@ return /******/ (function(modules) { // webpackBootstrap module.exports = abstractMapper; /***/ }, -/* 231 */ +/* 44 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var utils = __webpack_require__(218); - var collate = __webpack_require__(232); + var utils = __webpack_require__(31); + var collate = __webpack_require__(45); function getKey(obj) { return Object.keys(obj)[0]; @@ -19947,7 +19774,7 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, -/* 232 */ +/* 45 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -19956,7 +19783,7 @@ return /******/ (function(modules) { // webpackBootstrap var MAGNITUDE_DIGITS = 3; // ditto var SEP = ''; // set to '_' for easier debugging - var utils = __webpack_require__(233); + var utils = __webpack_require__(46); exports.collate = function (a, b) { @@ -20306,7 +20133,7 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, -/* 233 */ +/* 46 */ /***/ function(module, exports) { 'use strict'; @@ -20381,17 +20208,17 @@ return /******/ (function(modules) { // webpackBootstrap }; /***/ }, -/* 234 */ +/* 47 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {'use strict'; - var pouchCollate = __webpack_require__(232); - var TaskQueue = __webpack_require__(235); + var pouchCollate = __webpack_require__(45); + var TaskQueue = __webpack_require__(48); var collate = pouchCollate.collate; var toIndexableString = pouchCollate.toIndexableString; var normalizeKey = pouchCollate.normalizeKey; - var createView = __webpack_require__(238); + var createView = __webpack_require__(51); var log; /* istanbul ignore else */ if ((typeof console !== 'undefined') && (typeof console.log === 'function')) { @@ -20399,7 +20226,7 @@ return /******/ (function(modules) { // webpackBootstrap } else { log = function () {}; } - var utils = __webpack_require__(236); + var utils = __webpack_require__(49); var Promise = utils.Promise; var persistentQueues = {}; var tempViewQueue = new TaskQueue(); @@ -21081,10 +20908,10 @@ return /******/ (function(modules) { // webpackBootstrap module.exports = createIndexer; - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(191))) + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(22))) /***/ }, -/* 235 */ +/* 48 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -21092,7 +20919,7 @@ return /******/ (function(modules) { // webpackBootstrap * Simple task queue to sequentialize actions. Assumes callbacks will eventually fire (once). */ - var Promise = __webpack_require__(236).Promise; + var Promise = __webpack_require__(49).Promise; function TaskQueue() { this.promise = new Promise(function (fulfill) {fulfill(); }); @@ -21113,16 +20940,16 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, -/* 236 */ +/* 49 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {'use strict'; /* istanbul ignore if */ - exports.Promise = __webpack_require__(219); + exports.Promise = __webpack_require__(32); - exports.inherits = __webpack_require__(213); - exports.extend = __webpack_require__(221); - var argsarray = __webpack_require__(208); + exports.inherits = __webpack_require__(26); + exports.extend = __webpack_require__(34); + var argsarray = __webpack_require__(20); /* istanbul ignore next */ exports.promisedCallback = function (promise, callback) { @@ -21210,8 +21037,8 @@ return /******/ (function(modules) { // webpackBootstrap return output; }; - var crypto = __webpack_require__(237); - var Md5 = __webpack_require__(223); + var crypto = __webpack_require__(50); + var Md5 = __webpack_require__(36); exports.MD5 = function (string) { /* istanbul ignore else */ @@ -21221,22 +21048,22 @@ return /******/ (function(modules) { // webpackBootstrap return Md5.hash(string); } }; - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(191))) + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(22))) /***/ }, -/* 237 */ +/* 50 */ /***/ function(module, exports) { /* (ignored) */ /***/ }, -/* 238 */ +/* 51 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var upsert = __webpack_require__(239); - var utils = __webpack_require__(236); + var upsert = __webpack_require__(52); + var utils = __webpack_require__(49); var Promise = utils.Promise; function stringify(input) { @@ -21333,31 +21160,31 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, -/* 239 */ +/* 52 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var upsert = __webpack_require__(228).upsert; + var upsert = __webpack_require__(41).upsert; module.exports = function (db, doc, diffFun) { return upsert.apply(db, [doc, diffFun]); }; /***/ }, -/* 240 */ +/* 53 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var utils = __webpack_require__(218); + var utils = __webpack_require__(31); var clone = utils.clone; - var getIndexes = __webpack_require__(241); - var collate = __webpack_require__(232).collate; - var abstractMapper = __webpack_require__(230); - var planQuery = __webpack_require__(242); - var localUtils = __webpack_require__(231); - var filterInMemoryFields = __webpack_require__(243); + var getIndexes = __webpack_require__(54); + var collate = __webpack_require__(45).collate; + var abstractMapper = __webpack_require__(43); + var planQuery = __webpack_require__(55); + var localUtils = __webpack_require__(44); + var filterInMemoryFields = __webpack_require__(56); var massageSelector = localUtils.massageSelector; var massageSort = localUtils.massageSort; var getValue = localUtils.getValue; @@ -21494,14 +21321,14 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, -/* 241 */ +/* 54 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var utils = __webpack_require__(218); + var utils = __webpack_require__(31); - var localUtils = __webpack_require__(231); + var localUtils = __webpack_require__(44); var massageIndexDef = localUtils.massageIndexDef; function getIndexes(db) { @@ -21552,14 +21379,14 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, -/* 242 */ +/* 55 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var utils = __webpack_require__(218); + var utils = __webpack_require__(31); var log = utils.log; - var localUtils = __webpack_require__(231); + var localUtils = __webpack_require__(44); var getKey = localUtils.getKey; var getUserFields = localUtils.getUserFields; @@ -21997,7 +21824,7 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, -/* 243 */ +/* 56 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -22009,14 +21836,14 @@ return /******/ (function(modules) { // webpackBootstrap // "bar". // - var isArray = __webpack_require__(244); - var collate = __webpack_require__(232).collate; - var localUtils = __webpack_require__(231); + var isArray = __webpack_require__(57); + var collate = __webpack_require__(45).collate; + var localUtils = __webpack_require__(44); var isCombinationalField = localUtils.isCombinationalField; var getKey = localUtils.getKey; var getValue = localUtils.getValue; var parseField = localUtils.parseField; - var utils = __webpack_require__(218); + var utils = __webpack_require__(31); var getFieldFromDoc = utils.getFieldFromDoc; // create a comparator based on the sort object @@ -22287,7 +22114,7 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, -/* 244 */ +/* 57 */ /***/ function(module, exports) { @@ -22326,13 +22153,13 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, -/* 245 */ +/* 58 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var abstractMapper = __webpack_require__(230); - var upsert = __webpack_require__(239); + var abstractMapper = __webpack_require__(43); + var upsert = __webpack_require__(52); function deleteIndex(db, index) { @@ -22367,7 +22194,7 @@ return /******/ (function(modules) { // webpackBootstrap module.exports = deleteIndex; /***/ }, -/* 246 */ +/* 59 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -22383,7 +22210,7 @@ return /******/ (function(modules) { // webpackBootstrap exports.deleteClientById = deleteClientById; exports.updateLastSync = updateLastSync; - var _fetch = __webpack_require__(196); + var _fetch = __webpack_require__(8); function diskUsage(cozy) { return (0, _fetch.cozyFetchJSON)(cozy, 'GET', '/settings/disk-usage'); @@ -22417,7 +22244,7 @@ return /******/ (function(modules) { // webpackBootstrap } /***/ }, -/* 247 */ +/* 60 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -22429,9 +22256,9 @@ return /******/ (function(modules) { // webpackBootstrap exports.listReferencedFiles = listReferencedFiles; exports.fetchReferencedFiles = fetchReferencedFiles; - var _fetch = __webpack_require__(196); + var _fetch = __webpack_require__(8); - var _doctypes = __webpack_require__(199); + var _doctypes = __webpack_require__(11); function updateRelations(verb) { return function (cozy, doc, ids) { diff --git a/dist/cozy-client.js.map b/dist/cozy-client.js.map index ce79d831..b6b15bd3 100644 --- a/dist/cozy-client.js.map +++ b/dist/cozy-client.js.map @@ -1 +1 @@ -{"version":3,"sources":["webpack:///webpack/universalModuleDefinition","webpack:///webpack/bootstrap 5da2cef222e8ad09f168","webpack:///./~/isomorphic-fetch/fetch-npm-browserify.js","webpack:///./~/whatwg-fetch/fetch.js","webpack:///./src/index.js","webpack:///./~/process/browser.js","webpack:///./src/utils.js","webpack:///./src/auth_storage.js","webpack:///./src/auth_v2.js","webpack:///./src/auth_v3.js","webpack:///./src/fetch.js","webpack:///./src/jsonapi.js","webpack:///./src/data.js","webpack:///./src/doctypes.js","webpack:///./src/mango.js","webpack:///./src/files.js","webpack:///./src/intents.js","webpack:///./src/jobs.js","webpack:///./src/offline.js","webpack:///./~/pouchdb/lib/index-browser.js","webpack:///./~/pouchdb/~/lie/lib/browser.js","webpack:///./~/immediate/lib/browser.js","webpack:///./~/argsarray/index.js","webpack:///./~/debug/src/browser.js","webpack:///./~/debug/src/debug.js","webpack:///./~/debug/~/ms/index.js","webpack:///./~/events/events.js","webpack:///./~/inherits/inherits_browser.js","webpack:///./~/scope-eval/scope_eval.js","webpack:///./~/spark-md5/spark-md5.js","webpack:///./~/vuvuzela/index.js","webpack:///./~/pouchdb-find/lib/index.js","webpack:///./~/pouchdb-find/lib/utils.js","webpack:///./~/pouchdb-find/~/pouchdb-promise/lib/index.js","webpack:///./~/lie/lib/index.js","webpack:///./~/pouchdb-extend/index.js","webpack:///crypto (ignored)","webpack:///./~/pouchdb-find/~/spark-md5/spark-md5.js","webpack:///./~/pouchdb-find/lib/adapters/http/index.js","webpack:///./~/pouchdb-find/lib/massageCreateIndexRequest.js","webpack:///./~/pouchdb-find/lib/adapters/local/index.js","webpack:///./~/pouchdb-find/lib/adapters/local/create-index/index.js","webpack:///./~/pouchdb-upsert/index.js","webpack:///./~/pouchdb-upsert/~/pouchdb-promise/lib/index.js","webpack:///./~/pouchdb-find/lib/adapters/local/abstract-mapper.js","webpack:///./~/pouchdb-find/lib/adapters/local/utils.js","webpack:///./~/pouchdb-collate/lib/index.js","webpack:///./~/pouchdb-collate/lib/utils.js","webpack:///./~/pouchdb-find/lib/abstract-mapreduce/index.js","webpack:///./~/pouchdb-find/lib/abstract-mapreduce/taskqueue.js","webpack:///./~/pouchdb-find/lib/abstract-mapreduce/utils.js","webpack:///crypto (ignored)?5c06","webpack:///./~/pouchdb-find/lib/abstract-mapreduce/create-view.js","webpack:///./~/pouchdb-find/lib/abstract-mapreduce/upsert.js","webpack:///./~/pouchdb-find/lib/adapters/local/find/index.js","webpack:///./~/pouchdb-find/lib/adapters/local/get-indexes/index.js","webpack:///./~/pouchdb-find/lib/adapters/local/find/query-planner.js","webpack:///./~/pouchdb-find/lib/adapters/local/find/in-memory-filter.js","webpack:///./~/is-array/index.js","webpack:///./~/pouchdb-find/lib/adapters/local/delete-index/index.js","webpack:///./src/settings.js","webpack:///./src/relations.js"],"names":["auth","data","cozyFetch","mango","files","intents","jobs","offline","settings","relations","AppTokenV3","AppToken","AccessTokenV3","AccessToken","ClientV3","Client","AuthNone","AuthRunning","AuthError","AuthOK","defaultClientParams","softwareID","dataProto","create","find","findMany","findAll","update","delete","_delete","updateAttributes","changesFeed","defineIndex","query","addReferencedFiles","removeReferencedFiles","listReferencedFiles","fetchReferencedFiles","destroy","authProto","client","registerClient","updateClient","unregisterClient","getClient","getAuthCodeURL","getAccessToken","refreshToken","filesProto","createDirectory","createDirectoryByPath","updateById","updateAttributesById","updateAttributesByPath","trashById","statById","statByPath","downloadById","downloadByPath","getDownloadLinkById","getDownloadLink","getDownloadLinkByPath","getArchiveLink","getArchiveLinkByPaths","getArchiveLinkByIds","getFilePath","getCollectionShareLink","queryFiles","listTrash","clearTrash","restoreById","destroyById","intentsProto","createService","jobsProto","count","queued","offlineProto","init","getDoctypes","hasDatabase","getDatabase","createDatabase","destroyDatabase","destroyAllDatabase","hasReplication","replicateFromCozy","stopReplication","stopAllReplication","hasRepeatedReplication","startRepeatedReplication","stopRepeatedReplication","stopAllRepeatedReplication","settingsProto","diskUsage","changePassphrase","getInstance","updateInstance","getClients","deleteClientById","updateLastSync","options","AppTokenV2","LocalStorage","MemoryStorage","_inited","_oauth","_token","_authstate","_authcreds","_storage","_version","version","_offline","token","oauth","Error","storage","_clientParams","Object","assign","clientParams","_onRegistered","onRegistered","nopOnRegistered","url","cozyURL","length","slice","_url","disablePromises","addToProto","fetchJSON","_fetchJSON","args","concat","Array","prototype","call","arguments","cozyFetchJSON","apply","forceTokenRefresh","state","isV2","then","redirectURI","URL","searchParams","has","append","toString","oauthFlow","Promise","resolve","creds","save","CredsKey","path","pathprefix","fetch","res","ok","json","status","datasystem","undefined","protoify","context","fn","prototyped","ctx","obj","proto","attr","module","exports","unpromiser","isPromise","isOnline","isOffline","sleep","retry","getFuzzedDelay","getBackedoffDelay","createPath","encodeQuery","decodeQuery","warn","FuzzFactor","value","l","cb","err","navigator","onLine","time","setTimeout","delay","doTry","catch","retryDelay","fuzzingFactor","Math","random","retryCount","pow","cozy","doctype","id","route","encodeURIComponent","q","qname","queryIndex","indexOf","queries","fragIndex","queryStr","parts","split","i","pair","decodeURIComponent","hasOwnProperty","warned","text","push","console","prefix","window","localStorage","key","setItem","JSON","stringify","item","getItem","parse","removeItem","hash","deleted","getAppToken","V2TOKEN_ABORT_TIMEOUT","reject","parent","postMessage","origin","location","intent","action","timeout","receiver","event","appName","e","removeEventListener","clearTimeout","addEventListener","opts","btoa","StateSize","StateKey","clientID","client_id","clientSecret","client_secret","registrationAccessToken","registration_access_token","redirect_uris","software_id","softwareVersion","software_version","clientName","client_name","clientKind","client_kind","clientURI","client_uri","logoURI","logo_uri","policyURI","policy_uri","tokenType","token_type","accessToken","access_token","refresh_token","scope","cli","isRegistered","toRegisterJSON","disableAuth","resetSecret","manualAuthCredentials","createClient","isUnauthorized","isNotFound","oldClient","newClient","shouldPassRegistration","scopes","generateRandomState","join","pageURL","grantQueries","getGrantCodeFromPageURL","retrieveToken","code","ignoreCachedCredentials","clear","tryCount","clearAndRetry","registerNewClient","all","load","credentials","storedState","statePromise","t","body","dontRetry","headers","href","buffer","crypto","getRandomValues","Uint8Array","require","randomBytes","floor","String","fromCharCode","replace","cozyFetchRawJSON","fullpath","resp","cozyFetchWithAuth","authorize","handleResponse","toAuthHeader","newToken","saveCredentials","method","processJSONAPI","handleJSONResponse","response","contentType","get","FetchError","reason","captureStackTrace","constructor","name","defineProperty","message","indexKey","doc","type","findByRef","resources","ref","handleResource","rawResource","links","resource","_id","_type","_rev","meta","rev","attributes","rels","relationships","isArray","map","handleTopLevel","included","forEach","r","NOREV","docType","httpVerb","ids","include_docs","keys","docs","rows","row","error","match","changes","tries","normalizeDoctype","DOCTYPE_FILES","KNOWN_DOCTYPES","REVERSE_KNOWN","k","isQualified","known","parseSelector","normalizeSelector","makeMapReduceQuery","fields","defineIndexV2","defineIndexV3","indexRef","queryV2","queryV3","getV3Options","wholeResponse","VALUEOPERATORS","LOGICOPERATORS","MAP_TEMPLATE","toLowerCase","emit","FIELDSPLACEHOLDER","COUCHDB_INFINITY","COUCHDB_LOWEST","indexName","capitalize","indexDefinition","makeMapFunction","reduce","indexResult","result","selector","use_index","limit","skip","since","sort","descending","f","charAt","toUpperCase","operator","acc","filters","filter","op","field","applySelector","lower","upper","inclusiveEnd","startkey","endkey","inclusive_end","mrquery","firstFreeValueField","normalizedSelector","used","isFreeValue","ROOT_DIR_ID","TRASH_DIR_ID","contentTypeOctetStream","doUpload","ArrayBuffer","isBuffer","isFile","File","isBlob","Blob","isStream","readable","pipe","isString","checksum","lastModifiedDate","ifMatch","Date","toGMTString","dirID","executable","getDirectoryOrCreate","parentDirectory","parsedError","errors","part","rootDirectoryPromise","parentDirectoryPromise","doUpdateAttributes","attrs","db","children","sortFiles","addIsDir","toJsonApi","encodePageOptions","extractResponseLinkRelated","related","file","folder","folderPath","endsWith","collectionType","permissions","verbs","values","collection","sharecode","codes","email","paths","archive","isDir","contents","clone","allFiles","folders","a","b","localeCompare","intentClass","errorSerializer","mapErrorProperties","from","to","nativeProperties","property","serialize","deserialize","injectService","element","onReadyCallback","document","ownerDocument","defaultView","iframe","createElement","onload","setAttribute","classList","add","appendChild","focus","serviceOrigin","handshaken","messageHandler","source","transition","style","dimensions","prop","removeIntentFrame","parentNode","removeChild","createPromise","start","service","services","listenClientData","messageEventListener","intentId","serviceWindow","search","terminated","terminate","resizeClient","transitionProperty","maxHeight","clientHeight","maxWidth","clientWidth","cancel","getData","getIntent","exposeIntentFrameRemoval","throw","workerType","setDatabase","replicationOfflineError","pluginLoaded","doctypes","getInfo","database","plugin","pouchdbAdapterCordovaSqlite","createIndexes","createIndex","index","getReplication","replication","setReplication","getReplicationUrl","basic","toBasicAuth","getReplicationPromise","replicationPromise","setReplicationPromise","promise","live","onError","replicate","on","info","onComplete","stop","getRepeatedReplication","interval","setRepeatedReplication","timer","setInterval","clearInterval","currentPassPhrase","newPassPhrase","current_passphrase","new_passphrase","instance","updateRelations","verb","refs","makeReferencesPath","params"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,mCAAmC;AACnC,CAAC;AACD,O;ACVA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA,uBAAe;AACf;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;;AAGA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;;;;;;;;;;;;;;ACtCA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACLA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA,MAAK;AACL;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,iBAAgB;AAChB;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,QAAO;AACP,MAAK;AACL;AACA;AACA,QAAO;AACP,MAAK;AACL;AACA;AACA,QAAO;AACP;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,yCAAwC,mBAAmB;AAC3D;AACA;;AAEA;AACA;AACA,mCAAkC,oBAAoB;AACtD;AACA;;AAEA;AACA;AACA,yCAAwC,4BAA4B;AACpE;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA,oBAAmB,iBAAiB;AACpC;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA,QAAO;AACP;AACA,QAAO;AACP;AACA,QAAO;AACP;AACA,QAAO;AACP;AACA;AACA;AACA,QAAO;AACP;AACA,QAAO;AACP;AACA;;AAEA;AACA;AACA,wDAAuD;AACvD,UAAS;AACT;AACA,UAAS;AACT,+EAA8E;AAC9E;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,UAAS;AACT;AACA,UAAS;AACT;AACA,UAAS;AACT;AACA;AACA;;AAEA;AACA;AACA;AACA,UAAS;AACT;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,QAAO;AACP;AACA,QAAO;AACP;AACA,QAAO;AACP;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA,+BAA8B,uBAAuB;AACrD;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;;AAEA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;;AAEA;AACA,wCAAuC,0BAA0B;AACjE;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;;AAEA,gCAA+B,0BAA0B,eAAe;AACxE;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA,QAAO;;AAEP;AACA,MAAK;AACL;AACA;AACA,EAAC;;;;;;;;;sjBC5cD;;AAEA;;AACA;;AACA;;AACA;;KAAYA,I;;AACZ;;KAAYC,I;;AACZ;;KAAYC,S;;AACZ;;KAAYC,K;;AACZ;;KAAYC,K;;AACZ;;KAAYC,O;;AACZ;;KAAYC,I;;AACZ;;KAAYC,O;;AACZ;;KAAYC,Q;;AACZ;;KAAYC,S;;;;;;KAGAC,U,GAG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nBuC,YAAK,uBAAWA,EAAX,CAAL;AACD;AACDG,SAAIE,IAAJ,IAAYL,EAAZ;AACD;AACF;;AAEDM,QAAOC,OAAP,GAAiB,IAAIjK,MAAJ,EAAjB;AACAwG,QAAOC,MAAP,CAAcuD,OAAOC,OAArB,EAA8B,EAAEjK,cAAF,EAAUwF,wCAAV,EAAwBC,0CAAxB,EAA9B,E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACrTA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAS;AACT;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA;AACA,UAAS;AACT;AACA;AACA,MAAK;AACL;AACA;AACA,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA,UAAS;AACT;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA,UAAS;AACT;AACA;AACA;AACA;AACA;;;;AAIA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,wBAAuB,sBAAsB;AAC7C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AAC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AACvB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA,qCAAoC,SAAS;AAC7C;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA,mBAAkB;AAClB;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA,IAAG;AACH;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAW;AACX;AACA;AACA,UAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA,IAAG;AACH;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA,sBAAqB,qBAAqB;AAC1C;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAW;AACX;AACA;AACA,UAAS;AACT,QAAO;AACP;AACA;AACA,IAAG;AACH;;AAEA;AACA;AACA;AACA,oCAAmC,SAAS;AAC5C;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qCAAoC,SAAS;AAC7C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,EAAC;;AAED;AACA;;AAEA;AACA;AACA,wCAAuC,SAAS;AAChD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;AACA;AACA,EAAC;;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA,6BAA4B;AAC5B;AACA;AACA,IAAG,OAAO;AACV;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,IAAG;AACH;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA,IAAG;;AAEH;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAS;AACT,QAAO;AACP,MAAK;AACL,qBAAoB,iBAAiB;AACrC;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA,gCAA+B;AAC/B;AACA;;AAEA;AACA;AACA;AACA,IAAG;;AAEH;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;;AAEP;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA;AACA;AACA,sBAAqB,WAAW;AAChC,UAAS;AACT;AACA;AACA;AACA;AACA,QAAO;AACP,MAAK;AACL;;AAEA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA,EAAC;AACD;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL,IAAG;AACH;AACA;AACA;AACA,QAAO;AACP,MAAK,OAAO;AACZ;AACA;AACA,QAAO;AACP;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACA;AACA;AACA,+BAA8B,eAAe;AAC7C,IAAG;AACH;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,2BAA0B;AAC1B;AACA;AACA;AACA,2BAA0B;AAC1B,IAAG;AACH;AACA;AACA;AACA;AACA,2BAA0B;AAC1B;AACA;AACA;AACA;;AAEA,kCAAiC;AACjC;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;;AAEA,0BAAyB,0BAA0B;AACnD;;AAEA,kCAAiC;AACjC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,qCAAoC,SAAS;AAC7C;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,EAAC;AACD;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA,IAAG;AACH;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,IAAG;;AAEH;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,yBAAwB,4BAA4B;AACpD;;AAEA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL,IAAG;AACH;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;;AAEA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,2BAA0B;AAC1B,6CAA4C,SAAS;AACrD,uBAAsB,+BAA+B;AACrD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,2CAA0C,SAAS;AACnD,qBAAoB,4CAA4C;AAChE;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,oBAAmB,0CAA0C;AAC7D;AACA,IAAG;AACH;AACA,uCAAsC,SAAS;AAC/C;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,uCAAsC,SAAS;AAC/C;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,mBAAkB,mBAAmB;AACrC;AACA,mBAAkB,8CAA8C;AAChE;AACA,2CAA0C,SAAS;AACnD,qBAAoB,iDAAiD;AACrE;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAW;AACX;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,8CAA6C,SAAS;AACtD;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,iBAAgB,iCAAiC;AACjD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA,oBAAmB,qBAAqB;AACxC;AACA;AACA;AACA;AACA;;AAEA;AACA,sBAAqB,qBAAqB;AAC1C;AACA,uBAAsB,uCAAuC;AAC7D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAU;AACV;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA,aAAY;AACZ;;AAEA,qCAAoC,SAAS;AAC7C;AACA;AACA;AACA;AACA;AACA,qBAAoB,+BAA+B;AACnD;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA,mBAAkB,uDAAuD;AACzE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,uDAAsD,iBAAiB;AACvE;AACA;AACA;AACA;AACA;AACA,YAAW;AACX;AACA;;AAEA;;AAEA;AACA;AACA,QAAO;AACP;AACA;AACA,uBAAsB,yBAAyB;AAC/C;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA,sCAAqC,SAAS;AAC9C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,oBAAmB,gBAAgB;AACnC;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;;AAEA;AACA;AACA;AACA,IAAG;;AAEH;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,2CAA0C,SAAS;AACnD,qBAAoB,oCAAoC;AACxD;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,mBAAkB,6BAA6B;;AAE/C;AACA,4CAA2C,SAAS;AACpD;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA,yCAAwC,OAAO;AAC/C,qBAAoB,iDAAiD;AACrE;AACA;;AAEA;AACA;AACA;;AAEA;AACA,mCAAkC,uBAAuB,KAAK;AAC9D;;AAEA;AACA;AACA,4BAA2B;AAC3B,qBAAoB;AACpB,4BAA2B;AAC3B,oCAAmC;AACnC,yBAAwB;AACxB,UAAS;AACT,iCAAgC;AAChC,kBAAiB;AACjB,sBAAqB;AACrB,sBAAqB;AACrB,SAAQ;AACR,QAAO;AACP;;AAEA,6BAA4B;AAC5B;;AAEA;;AAEA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA;AACA,IAAG;AACH;AACA;AACA,0BAAyB,oBAAoB;AAC7C,IAAG;AACH;AACA;AACA;AACA;AACA,IAAG;;;;AAIH;AACA;AACA;AACA;AACA,QAAO;AACP;AACA,QAAO;AACP;AACA;AACA,MAAK;AACL,IAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sBAAqB,cAAc;AACnC;AACA;AACA,wBAAuB,SAAS,YAAY,EAAE;AAC9C;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,yBAAwB,oBAAoB;AAC5C;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;;;AAGA;AACA;AACA;;AAEA;AACA;AACA;AACA,MAAK;AACL;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gCAA+B,oBAAoB;AACnD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL,IAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gCAA+B,oBAAoB;AACnD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;;AAEA;AACA;AACA,kBAAiB,iBAAiB;AAClC;AACA;AACA,+BAA8B;AAC9B,MAAK;AACL;AACA;AACA,sBAAqB,iBAAiB;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,mBAAkB,oBAAoB;AACtC;AACA;AACA,IAAG;;AAEH;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA,IAAG;AACH;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0BAAyB,SAAS;AAClC;AACA;AACA;AACA;AACA;AACA,6BAA4B,wBAAwB;AACpD;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iCAAgC,6BAA6B;AAC7D,QAAO;AACP,MAAK;AACL,IAAG;AACH;AACA;AACA,IAAG;AACH;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP,MAAK;AACL,IAAG;AACH;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kBAAiB,YAAY;AAC7B,EAAC;;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA;AACA,IAAG;AACH,oBAAmB,YAAY;AAC/B;AACA,EAAC;;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA,IAAG;AACH;AACA;AACA;AACA,gCAA+B,WAAW;AAC1C,MAAK;AACL;AACA;AACA,IAAG;AACH,EAAC;;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH,EAAC;;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA,iBAAgB;AAChB;AACA;AACA;AACA;AACA,kBAAiB,eAAe;AAChC,EAAC;;AAED;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,6BAA4B;AAC5B;;AAEA;AACA;;AAEA;AACA;AACA,wBAAuB,YAAY;AACnC;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,QAAO;;AAEP;AACA;AACA;AACA;AACA,MAAK;AACL;;AAEA;AACA;AACA;AACA,0BAAyB,iBAAiB;AAC1C,QAAO;AACP;AACA;AACA,QAAO;AACP;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,UAAS;AACT;AACA;AACA,MAAK;AACL,IAAG;AACH,EAAC;;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,EAAC;;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;;AAEL;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA,IAAG;AACH,EAAC;;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA,+BAA8B,+BAA+B;AAC7D;AACA;AACA;AACA,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sBAAqB;AACrB,QAAO;AACP,MAAK;AACL,uBAAsB,SAAS;AAC/B,MAAK;AACL;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA;AACA,6CAA4C,OAAO;AACnD;AACA;AACA;AACA;AACA;AACA;AACA,0BAAyB,QAAQ;AACjC;AACA,UAAS;AACT,wBAAuB,cAAc;AACrC;AACA;AACA;AACA;AACA;AACA,QAAO;AACP,MAAK;AACL;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAS;AACT;AACA,QAAO;AACP,MAAK;AACL;AACA;AACA,wBAAuB,mBAAmB;AAC1C;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA;AACA,YAAW;AACX;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA,sBAAqB,kBAAkB;AACvC;AACA,2DAA0D,aAAa,EAAE;AACzE;AACA;;AAEA;AACA;AACA;AACA;;AAEA,mDAAkD,aAAa,EAAE;AACjE;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,YAAW;AACX;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAS;AACT;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAS;AACT,QAAO;AACP,MAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH,EAAC;;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA,IAAG;AACH,EAAC;;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,EAAC;;AAED;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,EAAC;;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH,EAAC;;AAED;AACA;AACA,EAAC;;AAED;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA,kBAAiB,qBAAqB;AACtC;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA,IAAG;;AAEH;AACA;AACA;;AAEA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA,IAAG;;AAEH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA;AACA,sCAAqC,OAAO;AAC5C;AACA;AACA;;AAEA;AACA,IAAG;AACH,EAAC;;AAED;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,oBAAmB;AACnB;AACA;AACA;AACA;AACA;AACA;AACA,uBAAsB,UAAU;AAChC,MAAK;AACL,EAAC;;AAED;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,+BAA8B,aAAa;AAC3C,MAAK;AACL;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,QAAO,OAAO;AACd;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA,IAAG;AACH,EAAC;;AAED;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA,sBAAqB;AACrB,oBAAmB,8BAA8B;AACjD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kBAAiB;AACjB;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,IAAG;;AAEH;;AAEA;;AAEA;AACA;;AAEA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA,IAAG;;AAEH;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA,IAAG;AACH;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,mCAAkC;AAClC;AACA,IAAG;AACH;AACA,IAAG;AACH,6CAA4C;AAC5C;AACA,MAAK;AACL;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;;AAEA,uBAAsB;AACtB;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA,IAAG;;AAEH;AACA;AACA,oCAAmC;;AAEnC;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA,IAAG,IAAI;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA,4CAA2C,SAAS;AACpD,6BAA4B,kBAAkB;AAC9C;;AAEA;AACA;AACA;AACA,IAAG;AACH;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,eAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4BAA2B,kBAAkB;AAC7C,QAAO;AACP;AACA,MAAK;AACL;AACA;AACA;AACA,QAAO;AACP;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;;AAEA;;AAEA;;AAEA,iBAAgB,aAAa;AAC7B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA,QAAO;AACP;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAmB,kBAAkB;AACrC;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,kBAAiB,YAAY;AAC7B;AACA;AACA;AACA;;AAEA;AACA,8DAA6D,WAAW;AACxE;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kBAAiB,YAAY;AAC7B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;;AAEA;AACA;AACA;AACA,IAAG;AACH;;AAEA;AACA;AACA;AACA,IAAG;AACH;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA,aAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,IAAG;AACH;AACA,IAAG,OAAO;AACV;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP,MAAK;AACL;AACA;AACA;AACA,QAAO;AACP,MAAK;AACL;AACA;AACA,IAAG;AACH;;AAEA;AACA;AACA;AACA;AACA,sCAAqC;AACrC;AACA,IAAG,OAAO;AACV;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;;AAEH;AACA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,6CAA4C;AAC5C;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA,6BAA4B,QAAQ;AACpC;AACA;AACA,QAAO;AACP;AACA;;AAEA;AACA;AACA,kBAAiB;AACjB;AACA,MAAK;AACL;AACA;AACA,IAAG;;AAEH;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,sDAAqD;AACrD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,kCAAiC,WAAW;AAC5C,MAAK,qCAAqC;AAC1C;AACA,MAAK,OAAO;AACZ;AACA;AACA,IAAG,OAAO;AACV;AACA;AACA,MAAK,qCAAqC;AAC1C;AACA;AACA,QAAO;AACP,MAAK,OAAO;AACZ;AACA;AACA;AACA;;AAEA;AACA,uDAAsD;AACtD;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA,IAAG;AACH;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,mCAAkC;AAClC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gBAAe;AACf;AACA;AACA,YAAW;AACX,UAAS;AACT,QAAO;AACP;AACA,IAAG;AACH;;AAEA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,kBAAiB;AACjB;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAS,OAAO;AAChB;AACA;AACA;AACA;AACA,IAAG;AACH;;AAEA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,yCAAwC,SAAS;AACjD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,IAAG;;AAEH;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA,2CAA0C,SAAS;AACnD;AACA;AACA,qBAAoB;AACpB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA;AACA;;AAEA;;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAS;AACT;AACA,MAAK;AACL;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP,MAAK;AACL;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,0BAAyB;AACzB,2BAA0B;AAC1B;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;;;AAGA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA;AACA,MAAK;AACL;;AAEA;AACA;AACA;;AAEA;AACA,gEAA+D;;AAE/D;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,QAAO;;AAEP;AACA;AACA;AACA;AACA;AACA,4BAA2B;AAC3B,6BAA4B;AAC5B;AACA;AACA;AACA,oBAAmB,sBAAsB;AACzC,yBAAwB;AACxB;AACA;;AAEA;;;AAGA;AACA;AACA;AACA;AACA,2BAA0B;AAC1B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,6BAA4B;AAC5B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA,4BAA2B;AAC3B;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,mBAAkB;AAClB;AACA;AACA;AACA;AACA;;AAEA;AACA,qBAAoB;AACpB;AACA;AACA,IAAG;AACH;AACA,IAAG;AACH;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA,MAAK;AACL;AACA;AACA,QAAO;AACP;AACA;AACA,MAAK;AACL;AACA;AACA,QAAO;AACP;AACA;AACA,MAAK;AACL;AACA;AACA,IAAG;AACH,aAAY;AACZ;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,8CAA6C,SAAS;AACtD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;;AAEA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,sBAAqB;AACrB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH,kBAAiB;AACjB,IAAG;AACH;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP,MAAK;AACL,IAAG;AACH;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA,eAAc;AACd;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA,IAAG;AACH;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA,wCAAuC;AACvC;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA,0CAAyC;AACzC;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,cAAa;AACb,YAAW;AACX,UAAS;AACT;AACA;AACA;AACA;;AAEA;AACA,gDAA+C,SAAS;AACxD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP,MAAK;AACL;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA,oBAAmB;AACnB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,MAAK;AACL;;AAEA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,IAAG;AACH;;AAEA;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA,qDAAoD,eAAe;AACnE,yCAAwC,oBAAoB;AAC5D,mDAAkD,aAAa;AAC/D,yCAAwC,kBAAkB;AAC1D,uCAAsC,oCAAoC;AAC1E;;AAEA;AACA,+DAA8D,eAAe;;AAE7E;AACA,wCAAuC,eAAe;;AAEtD;AACA;AACA,QAAO,oBAAoB;AAC3B;AACA,2DAA0D,aAAa;AACvE;;AAEA;AACA;AACA;AACA;AACA;AACA,+DAA8D,eAAe;;AAE7E;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA;AACA;;AAEA;AACA;AACA,wCAAuC,eAAe;AACtD,mDAAkD,aAAa;AAC/D;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,cAAa;AACb;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAS;AACT;AACA;AACA,QAAO;AACP;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,QAAO,oBAAoB;AAC3B;AACA,2DAA0D,aAAa;AACvE;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,2BAA0B;AAC1B;;AAEA;AACA;AACA;AACA,6BAA4B;AAC5B;AACA;AACA;AACA,sDAAqD;AACrD;AACA,wBAAuB,iBAAiB;AACxC;AACA,wCAAuC;AACvC;AACA;AACA,oBAAmB,oBAAoB;AACvC;AACA;AACA;AACA;AACA,YAAW;AACX;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gBAAe;AACf;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA,IAAG;;AAEH;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,sBAAqB,uCAAuC;AAC5D;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP,mCAAkC;AAClC;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,2BAA0B;AAC1B;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAS,OAAO;AAChB;AACA;AACA,oBAAmB;AACnB,4BAA2B;AAC3B;AACA;AACA;AACA;AACA;AACA,MAAK,OAAO;AACZ;AACA;AACA;AACA;AACA,4BAA2B;AAC3B,6BAA4B;AAC5B;AACA;AACA,gBAAe;AACf,wBAAuB;AACvB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA,gBAAe;AACf,wBAAuB;AACvB;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,uBAAsB,aAAa;AACnC;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;;AAEA;AACA;AACA;AACA,IAAG;AACH;AACA;;AAEA;;AAEA;AACA;AACA;AACA,+BAA8B;AAC9B;AACA;;AAEA;AACA;AACA;;AAEA;AACA,kCAAiC;AACjC;AACA;AACA,gCAA+B;AAC/B;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;;AAEA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,QAAO;AACP;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,qCAAoC;AACpC;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;;AAEL;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,MAAK;;AAEL;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA,QAAO;AACP;AACA;AACA;AACA,MAAK;AACL,IAAG;AACH;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;;AAEA;AACA;AACA;;AAEA,2BAA0B;;AAE1B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA,qCAAoC;AACpC;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA,sBAAqB,qBAAqB;AAC1C;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,+BAA8B,YAAY,EAAE;AAC5C;AACA;;AAEA;AACA;AACA,2CAA0C,YAAY,EAAE;AACxD;AACA;AACA;AACA,0BAAyB,qBAAqB;AAC9C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAW;AACX,UAAS;AACT,QAAO;AACP,MAAK;AACL;;AAEA;AACA;AACA;AACA;;AAEA;AACA,8BAA6B;AAC7B;AACA;AACA;AACA;;AAEA;AACA;AACA,MAAK;AACL,IAAG;AACH;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kCAAiC;AACjC;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;;AAEH;AACA;AACA,IAAG;AACH;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA,MAAK;AACL;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAS;AACT;AACA,MAAK;AACL;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP,MAAK;AACL;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,4DAA2D;AAC3D;;AAEA;AACA;AACA;AACA;AACA,4DAA2D;;AAE3D;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wBAAuB;AACvB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wBAAuB,sBAAsB;AAC7C,6BAA4B;AAC5B;AACA;;AAEA;AACA;AACA;AACA;AACA,UAAS;AACT,QAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA,8DAA6D;AAC7D;AACA;AACA;AACA;AACA,cAAa;AACb,YAAW;AACX,UAAS;AACT,sBAAqB;AACrB,QAAO;AACP;;AAEA;AACA;AACA;AACA;AACA;AACA,UAAS;AACT;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,kEAAiE;;;AAGjE;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA;AACA,MAAK;;AAEL;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,0DAAyD;AACzD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,4BAA2B;AAC3B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP,MAAK;AACL;;AAEA;AACA;AACA;AACA,gCAA+B;AAC/B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA,sBAAqB;AACrB,QAAO;AACP,MAAK;AACL;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAS;AACT;AACA;AACA,QAAO;AACP,MAAK;AACL,IAAG;AACH;;AAEA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA,uDAAsD;AACtD;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,oBAAmB;AACnB;AACA;AACA;AACA,UAAS;AACT;AACA;AACA,MAAK;AACL;;AAEA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA,IAAG;AACH;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA,+BAA8B;AAC9B;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;;AAEA,0BAAyB,wBAAwB;AACjD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAW;AACX,UAAS;AACT,QAAO;AACP,MAAK;AACL;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wBAAuB,qBAAqB;AAC5C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gBAAe;AACf,cAAa;AACb,YAAW;AACX;AACA;AACA,QAAO;AACP,MAAK;AACL;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAS;AACT;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4BAA2B,qBAAqB;AAChD;AACA;AACA;AACA,YAAW;AACX,UAAS;AACT,QAAO;AACP,MAAK;AACL;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4BAA2B,qBAAqB;AAChD;AACA;AACA,4DAA2D;AAC3D,8BAA6B,iBAAiB;AAC9C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gBAAe;AACf,cAAa;AACb;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gBAAe;AACf,cAAa;AACb,YAAW;AACX;AACA;AACA,QAAO;AACP;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAS;AACT,MAAK;AACL;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP,MAAK;AACL;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,cAAa;AACb,YAAW;AACX,UAAS;AACT,QAAO;AACP,MAAK,OAAO;;AAEZ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAS;AACT;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP,MAAK;AACL;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA,UAAS;AACT,QAAO,OAAO;AACd;AACA;AACA;AACA;AACA,UAAS;AACT;AACA,MAAK;AACL;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,MAAK;AACL;;AAEA;AACA;AACA;;AAEA;AACA;AACA,IAAG;;AAEH;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA,QAAO;AACP,MAAK;AACL;AACA;AACA;AACA;AACA,QAAO;AACP,MAAK;AACL;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,gCAA+B,SAAS;AACxC,QAAO;AACP;;AAEA;AACA,sBAAqB,sCAAsC;AAC3D;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA,QAAO;AACP;AACA,MAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,QAAO;;AAEP;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,gDAA+C,OAAO;AACtD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qBAAoB;AACpB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,cAAa;AACb;AACA;AACA;AACA;AACA;AACA,QAAO;AACP,MAAK;AACL;AACA;AACA;AACA;AACA,QAAO;AACP,MAAK;AACL;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA,iBAAgB;AAChB;;AAEA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kDAAiD,OAAO;AACxD;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gBAAe;AACf;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAS;AACT,QAAO;AACP;AACA;AACA;AACA;AACA,YAAW;AACX;AACA,QAAO;AACP;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA;AACA,MAAK;AACL;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,UAAS;AACT;AACA;AACA;AACA,QAAO;AACP,MAAK;AACL;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAS;;AAET;AACA;AACA,QAAO;;AAEP;AACA,MAAK;AACL;AACA,MAAK;AACL;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAS;AACT;AACA;AACA,QAAO;AACP,MAAK;AACL;;AAEA;AACA;AACA;AACA;AACA;AACA,2BAA0B;AAC1B;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA;AACA;AACA;AACA,kBAAiB;AACjB,0BAAyB;AACzB;AACA;AACA,UAAS;AACT;AACA;AACA,QAAO;AACP;AACA,sBAAqB;AACrB,QAAO;AACP;;AAEA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gBAAe;AACf,wBAAuB;AACvB;AACA;AACA,QAAO;AACP;;AAEA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP,MAAK;AACL;AACA;AACA;AACA;AACA,uBAAsB,WAAW;AACjC,MAAK;AACL;AACA;;AAEA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,4BAA2B;AAC3B;AACA;AACA,4BAA2B,GAAG,mCAAmC;AACjE;AACA;AACA;AACA,4BAA2B;AAC3B;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,IAAG;;AAEH;AACA;;AAEA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,IAAG;;AAEH;;AAEA,kBAAiB,iBAAiB;AAClC;AACA;;AAEA;;AAEA;AACA;AACA,IAAG;AACH;AACA,IAAG;AACH;AACA,IAAG;;AAEH;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA,IAAG;AACH;AACA;;AAEA;AACA;AACA;AACA;AACA,IAAG;;AAEH;;AAEA;AACA;AACA;AACA;AACA,MAAK;AACL;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA,IAAG;AACH;AACA;AACA,MAAK;AACL;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;AACA;AACA,IAAG;;AAEH,WAAU;AACV;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA,cAAa;;AAEb;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,IAAG;AACH;AACA;;AAEA;AACA;AACA,IAAG;AACH;AACA;;AAEA;AACA;;AAEA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6CAA4C;AAC5C;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,UAAS;AACT,QAAO;AACP;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA,UAAS;AACT;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,MAAK;AACL,IAAG;AACH;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;;AAEA,gCAA+B;AAC/B;;AAEA;AACA;AACA;;AAEA;;AAEA;;AAEA;AACA;AACA,gBAAe;AACf;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAS;AACT;AACA;AACA,QAAO;AACP;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA,uBAAsB,MAAM;AAC5B;AACA;AACA;AACA,oBAAmB,mBAAmB;AACtC;AACA;AACA,QAAO;AACP;;AAEA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA,IAAG;AACH;;AAEA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA,2CAA0C;;AAE1C;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,UAAS;AACT;AACA;AACA,QAAO;AACP;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA,IAAG;AACH;;AAEA;AACA;;AAEA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA,QAAO;AACP;AACA,IAAG;AACH;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,iBAAgB;AAChB;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,IAAG;AACH;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP,MAAK;AACL;;AAEA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA,QAAO;AACP,MAAK;AACL;;AAEA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA,wBAAuB;AACvB,kCAAiC;AACjC;AACA;AACA;AACA,8BAA6B,GAAG,0BAA0B;AAC1D,QAAO;AACP;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;;AAEL;AACA;AACA,MAAK;;AAEL;AACA;;AAEA;AACA;AACA,IAAG;;AAEH;AACA;AACA;;AAEA;AACA,eAAc,GAAG,qCAAqC;AACtD;AACA;AACA;AACA,MAAK;AACL,IAAG;;AAEH;AACA;AACA,eAAc;AACd,IAAG;;AAEH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA,6BAA4B,SAAS;AACrC,YAAW;AACX;AACA;AACA,UAAS;AACT;AACA;AACA;AACA,MAAK;AACL,IAAG;;AAEH;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gBAAe;AACf,QAAO;AACP;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,6BAA4B,0BAA0B;AACtD;AACA;AACA;;AAEA,sBAAqB,gBAAgB;AACrC;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAS;AACT;AACA;AACA;AACA,QAAO;AACP,MAAK;AACL;AACA;AACA,MAAK;AACL;AACA;AACA,IAAG;;AAEH;AACA;AACA;AACA;AACA;AACA,iBAAgB;AAChB;AACA;AACA,QAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP,MAAK;AACL;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAS;AACT;AACA;AACA;AACA;AACA;AACA,YAAW;AACX,UAAS;AACT;AACA;AACA;AACA,UAAS;AACT;;AAEA;AACA;AACA;AACA;AACA,QAAO;;AAEP;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,UAAS;AACT;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA,QAAO;AACP,MAAK;AACL,IAAG;;AAEH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA,MAAK;AACL,IAAG;;AAEH;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL,IAAG;;AAEH;AACA;AACA;AACA;;AAEA;AACA;;AAEA,eAAc;AACd;AACA;AACA,MAAK;AACL,IAAG;;AAEH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA;AACA;AACA;;AAEA;AACA,iBAAgB,qBAAqB;AACrC;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAc;AACd,IAAG;;AAEH;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA;AACA;AACA,4BAA2B;AAC3B,UAAS;AACT;AACA,QAAO;AACP,MAAK;AACL;;;AAGA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA;AACA;AACA,QAAO;AACP,MAAK;AACL;;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA,eAAc;AACd;;AAEA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA,MAAK;AACL,IAAG;;AAEH;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA,kCAAiC,mCAAmC;AACpE;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA,8CAA6C;AAC7C;AACA;AACA;AACA,eAAc;AACd;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,QAAO;AACP;;AAEA;AACA;AACA;AACA,oBAAmB;;AAEnB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAS;AACT,QAAO;AACP;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA,+BAA8B,gCAAgC,EAAE;AAChE,QAAO;AACP;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL,IAAG;;AAEH;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA,0BAAyB;AACzB,0BAAyB;AACzB,cAAa;;AAEb;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wBAAuB,SAAS;AAChC;AACA;AACA;AACA,QAAO;AACP;AACA,QAAO,yBAAyB;AAChC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAU;AACV;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK,kDAAkD;AACvD;AACA;AACA,MAAK;AACL,uBAAsB;AACtB;AACA;AACA;;AAEA;AACA;AACA,sBAAqB;AACrB;;AAEA,8CAA6C,sBAAsB;AACnE;AACA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oDAAmD,sBAAsB;AACzE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6BAA4B;AAC5B;AACA;AACA;AACA;AACA,2BAA0B,YAAY;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,kBAAiB,SAAS;AAC1B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kBAAiB,SAAS;AAC1B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA;AACA,mDAAkD;AAClD;AACA,aAAY;AACZ;AACA;;AAEA;;AAEA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA,yDAAwD,UAAU,EAAE;AACpE;AACA;AACA;AACA;AACA,IAAG;AACH;AACA,IAAG;AACH;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gBAAe;AACf;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAS;AACT;AACA;AACA;AACA;AACA,cAAa;AACb;AACA;AACA,UAAS;AACT,QAAO;AACP,MAAK;AACL,IAAG;;AAEH;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,uCAAsC,SAAS;AAC/C;AACA;AACA;AACA;AACA;AACA,2CAA0C,UAAU;AACpD;AACA;AACA;AACA,YAAW;AACX;AACA,YAAW;AACX;AACA;AACA;AACA,QAAO,OAAO;AACd;AACA;AACA,MAAK;AACL;AACA,MAAK,OAAO;AACZ;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA,iCAAgC,gBAAgB;AAChD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP,MAAK;AACL;AACA;AACA,QAAO;AACP,MAAK;AACL;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;;AAEA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL,IAAG;AACH;AACA;AACA,MAAK;AACL,IAAG;AACH;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA,iDAAgD,UAAU,EAAE,EAAE;AAC9D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,aAAY;AACZ,IAAG;AACH;AACA,aAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL,IAAG;AACH;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,IAAG;;AAEH;AACA;AACA,IAAG;;AAEH;AACA;AACA;AACA;AACA;AACA,2CAA0C,SAAS;AACnD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,iDAAgD,kBAAkB;AAClE,IAAG;AACH;AACA,mCAAkC,kBAAkB;AACpD,MAAK;AACL;AACA;AACA,SAAQ,YAAY;AACpB;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA,iBAAgB;AAChB,QAAO,OAAO,YAAY,aAAa;AACvC;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;;AAEA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;AACA,IAAG;AACH;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL,IAAG;AACH;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL,IAAG;AACH;;AAEA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,yBAAwB;AACxB;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,sCAAqC,SAAS;AAC9C;AACA;AACA;AACA;AACA,MAAK;AACL;;AAEA;AACA;AACA;;AAEA,iDAAgD,SAAS;AACzD;AACA;AACA,kBAAiB;AACjB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,MAAK;AACL,IAAG;AACH;;AAEA;AACA;AACA;AACA;AACA;AACA,sBAAqB,sBAAsB;AAC3C;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA,gCAA+B,qBAAqB;AACpD,MAAK;AACL,IAAG;AACH;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,IAAG;AACH;;AAEA;AACA;AACA;AACA;;AAEA;AACA,mBAAkB;AAClB;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,0CAAyC,SAAS;AAClD;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,6CAA4C,SAAS;AACrD;AACA;AACA;AACA,4BAA2B;AAC3B;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,IAAG;AACH;AACA,IAAG;AACH;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA,IAAG;AACH;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL,IAAG;AACH;AACA,uCAAsC,SAAS;AAC/C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA,WAAU;AACV;;AAEA;AACA;AACA;AACA,IAAG;AACH;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA,6CAA4C;AAC5C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP,MAAK;AACL;;AAEA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA;AACA,UAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA,UAAS;AACT;AACA,QAAO;AACP,MAAK;AACL;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,8CAA6C;AAC7C;AACA;AACA,MAAK;AACL;AACA,IAAG,OAAO;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6CAA4C;AAC5C;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,wCAAuC;AACvC;AACA;AACA;AACA,mDAAkD;AAClD;AACA;AACA;AACA,QAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,IAAG;AACH;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6CAA4C;AAC5C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAW;AACX,UAAS;AACT,QAAO;AACP;AACA,gCAA+B,mCAAmC,EAAE;AACpE;AACA;AACA;AACA,UAAS;AACT,QAAO;AACP;AACA,iBAAgB;AAChB,QAAO;AACP,MAAK;AACL,IAAG,cAAc,SAAS;AAC1B;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,EAAC;;AAED;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAS;AACT,QAAO;AACP,MAAK;AACL;AACA,IAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,cAAa;AACb;AACA;AACA,UAAS,OAAO;AAChB;AACA;AACA,YAAW;AACX;AACA,QAAO;AACP,MAAK;AACL;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,YAAW;AACX;;AAEA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;;;AAGA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,iDAAgD,cAAc;AAC9D,IAAG;AACH;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA,MAAK;AACL,IAAG;AACH;AACA;AACA;AACA;;AAEA;AACA,IAAG;AACH;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP,MAAK;AACL,IAAG;;AAEH;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wBAAuB;;AAEvB;AACA;;AAEA;;AAEA;;AAEA,oCAAmC;AACnC;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,4BAA2B;AAC3B;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,cAAa;;AAEb;AACA,YAAW;AACX,UAAS;AACT,QAAO;;AAEP;AACA;AACA,QAAO;AACP,MAAK;AACL;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,QAAO;AACP,MAAK;AACL;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;;AAEA;AACA,aAAY;AACZ;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,MAAK;;AAEL;AACA;AACA;AACA;AACA,MAAK;;AAEL;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,kBAAiB;AACjB;AACA;AACA;AACA,MAAK;AACL,IAAG;AACH;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,IAAG;AACH;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,QAAO;AACP;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA,UAAS;AACT;AACA,UAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA,UAAS;AACT;AACA;AACA,MAAK;AACL,IAAG;AACH;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,IAAG,IAAI;AACP;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL,IAAG;AACH;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;;AAEA;AACA,oBAAmB;AACnB,oBAAmB;AACnB;AACA;AACA;AACA;AACA,KAAI;AACJ,iCAAgC;AAChC,gCAA+B;AAC/B,oCAAmC;AACnC;AACA;AACA;AACA;AACA,8BAA6B;AAC7B;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA,qBAAoB;AACpB,6BAA4B,6BAA6B;AACzD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;;AAEP;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,YAAW;AACX;AACA;AACA,UAAS;AACT;AACA;AACA,QAAO;;AAEP,MAAK;AACL;AACA;AACA,MAAK;AACL;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA,MAAK;AACL;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP,MAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP,MAAK;AACL;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP;;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA,UAAS;AACT;AACA,MAAK;AACL;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;;AAEL;AACA;AACA;AACA;AACA,UAAS;AACT;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAS;AACT;AACA,QAAO;AACP;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,gCAA+B;AAC/B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAW,OAAO;AAClB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP,MAAK;AACL;AACA,MAAK;AACL;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA,+BAA8B;AAC9B;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA;;AAEA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4BAA2B;AAC3B;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA,yCAAwC;AACxC,yCAAwC;;AAExC;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;;AAEA;;AAEA,6BAA4B;AAC5B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA,MAAK;AACL;AACA;AACA,MAAK;AACL;AACA;AACA;AACA,IAAG;;AAEH;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA,MAAK;AACL;AACA;AACA,MAAK;AACL;AACA;AACA;AACA,IAAG;;AAEH;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;;AAEH;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,UAAS;AACT;AACA;AACA;AACA;AACA;AACA,IAAG;;AAEH;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;;;;;;;;ACrkWA;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA,IAAG;AACH;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;;;;;;;AC5PA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;;AAEA,oCAAmC;AACnC;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACpEA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA,E;;;;;;AClBA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;;;AAGA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;;AAEH;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,YAAW,OAAO;AAClB;AACA;;AAEA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA,IAAG;AACH;;AAEA;AACA;AACA;AACA,aAAY,OAAO;AACnB;AACA;;AAEA;AACA;AACA;AACA,IAAG;;AAEH;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA,IAAG;AACH;;;;;;;;;ACpLA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA,YAAW,OAAO;AAClB,aAAY;AACZ;AACA;;AAEA;AACA;;AAEA;AACA;AACA,eAAc;AACd;;AAEA;AACA;;AAEA;AACA;AACA;AACA,YAAW,OAAO;AAClB,aAAY;AACZ;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,oBAAmB,iBAAiB;AACpC;AACA;;AAEA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,MAAK;;AAEL;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA,YAAW,OAAO;AAClB;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA,kBAAiB,SAAS;AAC1B,6BAA4B;AAC5B;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,YAAW,OAAO;AAClB,aAAY;AACZ;AACA;;AAEA;AACA;AACA,0CAAyC,SAAS;AAClD;AACA;AACA;AACA;AACA,0CAAyC,SAAS;AAClD;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,YAAW,MAAM;AACjB,aAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA;;;;;;;ACtMA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAW,cAAc;AACzB,YAAW,OAAO;AAClB,aAAY,MAAM;AAClB,aAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,YAAW,OAAO;AAClB,aAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,YAAW,OAAO;AAClB,aAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,YAAW,OAAO;AAClB,aAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACpJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,kBAAiB;AACjB,QAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA,gBAAe,SAAS;AACxB;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA,IAAG;AACH,qBAAoB,SAAS;AAC7B;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,MAAK;AACL;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;;;;;;AC7SA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACtBA;AACA;AACA,mBAAkB;AAClB;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,EAAC;;;;;;;ACrBD;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA,MAAK;AACL;AACA;;AAEA;AACA;AACA,UAAS;AACT;AACA;;AAEA;AACA;AACA,EAAC;;AAED;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;;;AAGA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAc;;AAEd,oBAAmB,QAAQ;AAC3B;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAc;;AAEd,oBAAmB,QAAQ;AAC3B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,qBAAoB,QAAQ;AAC5B;AACA;AACA;AACA;AACA;AACA,oBAAmB,YAAY;AAC/B;AACA;AACA;AACA;AACA;AACA,wBAAuB,QAAQ;AAC/B;AACA;AACA;;AAEA;AACA;AACA,+CAA8C,IAAI;AAClD;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,qBAAoB,QAAQ;AAC5B;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,oBAAmB,YAAY;AAC/B;AACA;;AAEA;AACA;AACA;AACA,wBAAuB,QAAQ;AAC/B;AACA;AACA;;AAEA;AACA;AACA,+CAA8C,IAAI;AAClD;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,oBAAmB,OAAO;AAC1B;AACA;AACA;AACA;;AAEA;AACA;AACA,oBAAmB,cAAc;AACjC;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,UAAS;AACT;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA,oBAAmB,YAAY;AAC/B;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA,oBAAmB,gBAAgB;AACnC;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,gBAAe,OAAO;AACtB;AACA,iBAAgB,SAAS;AACzB;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,gBAAe,OAAO;AACtB;AACA,iBAAgB,SAAS;AACzB;AACA;AACA;AACA;;AAEA;AACA;;AAEA,qBAAoB,aAAa;AACjC;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA,gBAAe,QAAQ;AACvB;AACA,iBAAgB,OAAO;AACvB;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,oBAAmB,YAAY;AAC/B;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,iBAAgB,SAAS;AACzB;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,iBAAgB,OAAO;AACvB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,gBAAe,OAAO;AACtB;AACA,iBAAgB,SAAS;AACzB;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,gBAAe,MAAM;AACrB,gBAAe,OAAO;AACtB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,wBAAuB,QAAQ;AAC/B;AACA;AACA;;AAEA;AACA;AACA;AACA,+CAA8C,IAAI;AAClD;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,gBAAe,OAAO;AACtB,gBAAe,QAAQ;AACvB;AACA,iBAAgB,OAAO;AACvB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,gBAAe,OAAO;AACtB,gBAAe,QAAQ;AACvB;AACA,iBAAgB,OAAO;AACvB;AACA;AACA;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,gBAAe,YAAY;AAC3B;AACA,iBAAgB,qBAAqB;AACrC;AACA;AACA;AACA;AACA;;AAEA;;AAEA,qBAAoB,aAAa;AACjC;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA,gBAAe,QAAQ;AACvB;AACA,iBAAgB,OAAO;AACvB;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,oBAAmB,YAAY;AAC/B;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,iBAAgB,qBAAqB;AACrC;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,iBAAgB,OAAO;AACvB;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,gBAAe,OAAO;AACtB;AACA,iBAAgB,qBAAqB;AACrC;AACA;AACA;AACA;;AAEA;AACA;;AAEA;;AAEA;;AAEA;AACA;AACA;AACA,gBAAe,YAAY;AAC3B,gBAAe,QAAQ;AACvB;AACA,iBAAgB,OAAO;AACvB;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA,EAAC;;;;;;;AC9uBD;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAc,WAAW;;AAEzB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA,MAAK;AACL;AACA,MAAK;AACL,mBAAkB,SAAS;AAC3B,+BAA8B,QAAQ;AACtC;AACA,qBAAoB,iCAAiC;AACrD;AACA,mBAAkB,SAAS;AAC3B,MAAK,OAAO;AACZ;AACA;AACA;AACA;AACA;AACA;AACA,mBAAkB,OAAO,EAAE;AAC3B,gCAA+B,QAAQ;AACvC;AACA;AACA;AACA;AACA,qBAAoB,8BAA8B;AAClD;AACA,mBAAkB,OAAO,EAAE;AAC3B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG,kDAAkD;AACrD;AACA;AACA,IAAG;AACH,qBAAoB;AACpB;AACA;;AAEA;AACA;AACA,sBAAqB;AACrB;AACA;AACA;AACA;AACA;AACA;AACA,8BAA6B;AAC7B;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gBAAe;AACf;AACA;AACA;AACA,gBAAe;AACf;AACA;AACA;AACA,gBAAe;AACf;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAW;AACX;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,cAAa;AACb;AACA;AACA,YAAW;AACX;AACA;AACA;AACA;AACA;AACA;AACA,yBAAwB;AACxB;AACA;AACA;AACA,cAAa;AACb,uBAAsB,YAAY;AAClC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;AC5KA;;AAEA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA,EAAC;;AAED;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA,EAAC;;AAED;;AAEA;;AAEA;AACA,EAAC;;AAED;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA,EAAC;;AAED;;AAEA;AACA;AACA;AACA;;;;;;;AC1DA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAW;AACX;AACA;AACA,UAAS;AACT;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;;AAEA;AACA;;AAEA;AACA,iCAAgC;AAChC;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;;AAEA;AACA;AACA;AACA;AACA,MAAK;AACL,IAAG;AACH;AACA;AACA,MAAK;AACL,IAAG;AACH;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;;AAEA;AACA;AACA,qCAAoC,SAAS;AAC7C;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA,EAAC;;AAED;AACA;AACA,oCAAmC,SAAS;AAC5C;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,4CAA2C,SAAS;AACpD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,4CAA2C,WAAW;AACtD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,0CAAyC,SAAS;AAClD;AACA;AACA,gDAA+C;AAC/C;AACA,QAAO,OAAO;AACd;AACA;AACA;AACA,MAAK,OAAO;AACZ;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,oCAAmC,SAAS;AAC5C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA,6DAA4D,SAAS;AACrE;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA,sCAAqC,SAAS;AAC9C;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA,oCAAmC,SAAS;AAC5C;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,oCAAmC,SAAS;AAC5C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,qCAAoC,SAAS;AAC7C;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,kBAAiB,gBAAgB;AACjC;AACA;AACA;AACA;AACA,IAAG;AACH;;AAEA;;;;;;;;AC9RA;;AAEA,gCAA+B,iFAAiF;;AAEhH;;AAEA;AACA;;AAEA,+B;;;;;;ACTA;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA,IAAG;AACH;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;;;;;;;;ACrRA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,gBAAe,kBAAkB;AACjC;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;;AAGA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAc,qBAAqB,kCAAkC;AACrE;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,2BAA0B;AAC1B;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAAQ,YAAY;AACpB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA,cAAa;AACb;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,cAAa;;AAEb;AACA,YAAW;AACX;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;;AAGA;;;;;;;;;AChLA,gB;;;;;;ACAA;AACA;;AAEA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA,UAAS;AACT;AACA;;AAEA;AACA;AACA,EAAC;;AAED;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;;AAEL;AACA;AACA;AACA,MAAK;;AAEL;AACA;AACA,MAAK;;AAEL;AACA;AACA,MAAK;;AAEL;AACA;AACA,MAAK;;AAEL;AACA;AACA,MAAK;;AAEL;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,MAAK;;AAEL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,2CAA0C;AAC1C;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAc;;AAEd,oBAAmB,QAAQ;AAC3B;AACA;AACA;AACA,MAAK;;AAEL;AACA;AACA,eAAc;;AAEd,oBAAmB,QAAQ;AAC3B;AACA;AACA;AACA,MAAK;;AAEL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,qBAAoB,QAAQ;AAC5B;AACA;AACA;AACA;AACA;AACA,oBAAmB,YAAY;AAC/B;AACA;AACA;AACA;AACA;AACA,wBAAuB,QAAQ;AAC/B;AACA;AACA;;AAEA;AACA;AACA,+CAA8C,IAAI;AAClD;AACA;;AAEA;AACA;;AAEA;AACA;AACA,MAAK;;AAEL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,qBAAoB,QAAQ;AAC5B;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,oBAAmB,YAAY;AAC/B;AACA;;AAEA;AACA;AACA;AACA,wBAAuB,QAAQ;AAC/B;AACA;AACA;;AAEA;AACA;AACA,+CAA8C,IAAI;AAClD;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA,MAAK;;AAEL;;AAEA;AACA;AACA;AACA,oBAAmB,OAAO;AAC1B;AACA;AACA;AACA,MAAK;;AAEL;AACA;AACA,oBAAmB,cAAc;AACjC;AACA;AACA;AACA,MAAK;;AAEL;AACA;AACA,MAAK;;;;AAIL;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACA;AACA,gBAAe,OAAO;AACtB;AACA,iBAAgB,SAAS;AACzB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,gBAAe,OAAO;AACtB;AACA,iBAAgB,SAAS;AACzB;AACA;AACA;AACA;;AAEA;AACA;;AAEA,qBAAoB,aAAa;AACjC;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,gBAAe,QAAQ;AACvB;AACA,iBAAgB,aAAa;AAC7B;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,oBAAmB,YAAY;AAC/B;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,gBAAe,MAAM;AACrB,gBAAe,OAAO;AACtB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,wBAAuB,QAAQ;AAC/B;AACA;AACA;;AAEA;AACA;AACA;AACA,+CAA8C,IAAI;AAClD;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,iBAAgB,SAAS;AACzB;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACA;AACA,gBAAe,OAAO;AACtB,gBAAe,QAAQ;AACvB;AACA,iBAAgB,aAAa;AAC7B;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,gBAAe,OAAO;AACtB,gBAAe,QAAQ;AACvB;AACA,iBAAgB,aAAa;AAC7B;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA,gBAAe,YAAY;AAC3B;AACA,iBAAgB,qBAAqB;AACrC;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA,qBAAoB,aAAa;AACjC;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,gBAAe,QAAQ;AACvB;AACA,iBAAgB,aAAa;AAC7B;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,oBAAmB,YAAY;AAC/B;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA;AACA,iBAAgB,qBAAqB;AACrC;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,iBAAgB,YAAY;AAC5B,iBAAgB,YAAY;AAC5B;AACA,iBAAgB,YAAY;AAC5B;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,gBAAe,YAAY;AAC3B,gBAAe,QAAQ;AACvB;AACA,iBAAgB,aAAa;AAC7B;AACA;AACA;;AAEA;AACA;;AAEA;AACA,EAAC;;;;;;;ACtlBD;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA,IAAG;AACH;;AAEA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;;AAEA;AACA;AACA;AACA;AACA,IAAG;AACH;;AAEA;;;AAGA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA,IAAG;AACH;;AAEA;AACA;AACA;AACA,mC;;;;;;ACvDA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,IAAG;;AAEH;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,G;;;;;;AChCA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,6D;;;;;;ACRA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA;;AAEA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA;AACA,MAAK;AACL,IAAG;AACH;;AAEA;;;;;;;ACrFA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;;AAEA;AACA;AACA;AACA,eAAc;AACd;;AAEA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,oBAAmB;AACnB;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;;;AAGA;AACA;AACA;AACA;;;;;;;AC5FA;;AAEA,gCAA+B,iFAAiF;;AAEhH;;AAEA;AACA;;AAEA,+B;;;;;;ACTA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACA,0CAAyC,UAAU;AACnD;AACA;AACA,iDAAgD,UAAU;AAC1D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,8CAA6C,SAAS;AACtD;AACA;AACA;AACA,gBAAe;AACf;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,yCAAwC,SAAS;AACjD;AACA;AACA;AACA;AACA;;AAEA;AACA,uCAAsC,SAAS;AAC/C;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,MAAK,OAAO;AACZ;AACA;AACA,IAAG,OAAO;AACV;AACA;AACA,MAAK,OAAO;AACZ;AACA;AACA;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,EAAC;;AAED,iC;;;;;;ACnIA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA,IAAG;AACH;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,YAAW;AACX;AACA;AACA;AACA,wCAAuC;AACvC;AACA;AACA,MAAK,OAAO;AACZ,yCAAwC;AACxC;AACA;AACA;AACA;AACA,IAAG;AACH;AACA,uCAAsC;AACtC;AACA;AACA;AACA,MAAK,OAAO;AACZ,uCAAsC;AACtC;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;;AAEA;AACA;AACA;AACA,YAAW;AACX;AACA;AACA;AACA,wCAAuC;AACvC;AACA;AACA,MAAK,OAAO;AACZ,yCAAwC;AACxC;AACA;AACA;AACA;AACA,IAAG;AACH;AACA,uCAAsC;AACtC;AACA;AACA;AACA,MAAK,OAAO;AACZ,uCAAsC;AACtC;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,IAAG,OAAO;AACV;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA,cAAa,SAAS,GAAG,SAAS;AAClC,YAAW;AACX;;AAEA;AACA;AACA;AACA;AACA,oBAAmB;AACnB;;AAEA;AACA;AACA;AACA;AACA,YAAW;AACX,UAAS;AACT;AACA;AACA,QAAO;AACP;AACA;AACA;;AAEA;AACA;AACA,YAAW;AACX;AACA,YAAW;AACX;AACA,YAAW;AACX;AACA;AACA;AACA,UAAS;AACT;AACA,MAAK;AACL,IAAG;;AAEH;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;;AAEA,kBAAiB,mBAAmB;AACpC;AACA;;AAEA;AACA,kBAAiB;AACjB,MAAK;AACL;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;;AAEA;AACA;AACA,kBAAiB,6BAA6B;AAC9C;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,qCAAoC,SAAS;AAC7C;;AAEA;AACA;;AAEA;AACA;AACA,0BAAyB;AACzB,MAAK,OAAO;AACZ,wDAAuD,MAAM;AAC7D;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wCAAuC;AACvC;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA,MAAK;;AAEL;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA,kBAAiB,sBAAsB;AACvC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;;AAEH;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACxXA;;AAEA,0BAAyB;AACzB,0BAAyB;AACzB,cAAa;;AAEb;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wBAAuB,SAAS;AAChC;AACA;AACA,QAAO;AACP;AACA,QAAO,yBAAyB;AAChC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAU;AACV;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK,kDAAkD;AACvD;AACA;AACA,MAAK;AACL,uBAAsB;AACtB;AACA;AACA;;AAEA;AACA;AACA,sBAAqB;AACrB;;AAEA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6BAA4B;AAC5B;AACA;AACA;AACA;AACA,2BAA0B,YAAY;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,kBAAiB,SAAS;AAC1B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kBAAiB,SAAS;AAC1B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA;AACA,mDAAkD;AAClD,aAAY;AACZ;AACA;;AAEA;;AAEA;AACA;;AAEA;;AAEA;AACA;;;;;;;AChWA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA,cAAa,UAAU;AACvB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,IAAG;;;AAGH;AACA;AACA;;AAEA;AACA,G;;;;;;ACrEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;;AAEA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA,iDAAgD,UAAU,EAAE,EAAE;AAC9D;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA,aAAY;AACZ;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,oCAAmC,kBAAkB;AACrD,IAAG;AACH;AACA,mCAAkC,kBAAkB;AACpD,MAAK;AACL;AACA,+EAA8E,YAAY;AAC1F;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACA;AACA;AACA,2BAA0B;AAC1B;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,iCAAgC,SAAS;AACzC;AACA;AACA;AACA;AACA,QAAO;AACP;;AAEA;AACA;AACA;;AAEA,mDAAkD,SAAS;AAC3D;AACA;AACA,oBAAmB;AACnB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,QAAO;AACP,MAAK;AACL;;AAEA;AACA;AACA;AACA;AACA;AACA,wBAAuB,sBAAsB;AAC7C;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA;AACA;AACA,kCAAiC,qBAAqB;AACtD,QAAO;AACP,MAAK;AACL;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,MAAK;AACL;;AAEA;AACA;AACA;AACA;;AAEA;AACA,qBAAoB;AACpB;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;;AAEA;AACA;AACA;AACA;AACA,UAAS;AACT;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAS;AACT;AACA;AACA;AACA;AACA;AACA,8CAA6C,OAAO;AACpD;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA,sDAAqD,QAAQ;AAC7D;AACA;AACA;AACA,sCAAqC;AACrC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAS;AACT;AACA;AACA;AACA;AACA;;AAEA;AACA,MAAK;AACL;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,oBAAmB;AACnB;AACA,2BAA0B;AAC1B,MAAK;AACL,yCAAwC,SAAS;AACjD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAY;AACZ;;AAEA;AACA;AACA;AACA,MAAK;AACL;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA,+CAA8C;AAC9C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,UAAS;AACT,QAAO;AACP;;AAEA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,UAAS;AACT;AACA;AACA;AACA;AACA;AACA,YAAW;AACX;AACA;AACA;AACA;AACA;AACA;AACA,YAAW;AACX;AACA,UAAS;AACT,QAAO;AACP;AACA;AACA;;AAEA;AACA;AACA;AACA,QAAO;AACP;;AAEA;AACA;AACA;AACA;AACA;AACA,gDAA+C;AAC/C;AACA;AACA,QAAO;AACP;AACA,MAAK,OAAO;AACZ;AACA;AACA;AACA;AACA;AACA,+CAA8C;AAC9C;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,4EAA2E;AAC3E;AACA;AACA;AACA,qDAAoD;AACpD;AACA;AACA;AACA,UAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,cAAa;AACb,YAAW;AACX,UAAS;AACT;AACA;AACA,UAAS;AACT;AACA;AACA;AACA,YAAW;AACX,UAAS;AACT;AACA,mBAAkB;AAClB,UAAS;AACT,QAAO;AACP,MAAK,cAAc,SAAS;AAC5B;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAW;AACX,UAAS;AACT,QAAO;AACP;AACA,MAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,8BAA6B;AAC7B;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gBAAe;AACf;AACA;AACA,YAAW,OAAO;AAClB;AACA;AACA,cAAa;AACb;AACA,UAAS;AACT,QAAO;AACP;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,iCAAgC;;AAEhC;AACA,cAAa;AACb;;AAEA;AACA;AACA,MAAK;AACL;AACA;AACA;;AAEA;AACA;AACA;AACA,IAAG;;AAEH;AACA;AACA;AACA;AACA;;AAEA;;;;;;;;ACvrBA;AACA;AACA;AACA;;AAEA;;AAEA;AACA,kDAAiD,UAAU,EAAE;AAC7D;AACA;AACA;AACA;AACA,IAAG;AACH;AACA,IAAG;AACH;AACA;AACA;AACA;AACA;;AAEA;;;;;;;ACtBA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP,MAAK;AACL;AACA;AACA,QAAO;AACP,MAAK;AACL;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA,IAAG;AACH;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;;AAEA;AACA;AACA,qCAAoC,SAAS;AAC7C;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA,oCAAmC,SAAS;AAC5C;AACA;;AAEA;AACA;;AAEA,iCAAgC,SAAS;AACzC;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA,G;;;;;;;ACxGA,gB;;;;;;ACAA;;AAEA;AACA;AACA;;AAEA;AACA;AACA,wBAAuB;AACvB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gBAAe;AACf;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA,cAAa;AACb;AACA;AACA,UAAS;AACT,QAAO;AACP,MAAK;AACL,IAAG;AACH;;;;;;;AChGA;;AAEA;;AAEA;AACA;AACA,G;;;;;;ACNA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;;AAEA;;AAEA;;AAEA;;AAEA;AACA;AACA;AACA,MAAK;;AAEL;AACA;AACA;AACA,eAAc;AACd;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA;AACA,MAAK;;AAEL;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAS;AACT;;AAEA;AACA;AACA;;AAEA;AACA,MAAK;AACL,IAAG;AACH;;AAEA;;;;;;;AC9IA;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA,qBAAoB,WAAW;AAC/B;AACA,QAAO;AACP;;AAEA;AACA;AACA,MAAK;AACL;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP,MAAK;;AAEL;AACA;AACA;AACA,MAAK;AACL;AACA;AACA,IAAG;AACH;;AAEA;;;;;;;ACnDA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA,mBAAkB;;AAElB;;AAEA;AACA;AACA,4CAA2C,SAAS;AACpD;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA,2CAA0C,SAAS;AACnD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL,IAAG;AACH;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA,8BAA6B,MAAM,WAAW,QAAQ,YAAY;AAClE;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,IAAG;;AAEH;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;;AAEA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA,8CAA6C,SAAS;AACtD;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,eAAc;AACd;AACA,eAAc;AACd;AACA,eAAc;AACd;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA;;AAEA;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA;;AAEA;AACA;AACA,MAAK;AACL;AACA;AACA,IAAG;;AAEH;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;;;AAGA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,4CAA2C,SAAS;AACpD;;AAEA;;AAEA,oBAAmB;AACnB;AACA;AACA,MAAK;AACL,8BAA6B;AAC7B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;;AAEA,oBAAmB,0BAA0B;AAC7C;AACA;;AAEA;;AAEA;AACA;AACA,QAAO;AACP;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,iBAAgB,eAAe;AAC/B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;;;;;;ACtbA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,IAAG;;AAEH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,IAAG;AACH;;AAEA;AACA;AACA,+BAA8B;AAC9B;AACA;;AAEA;AACA;AACA;AACA,IAAG;AACH;;AAEA;;AAEA;AACA;AACA;AACA,MAAK;AACL;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,IAAG;;AAEH;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA,IAAG;AACH;;AAEA;AACA;AACA;AACA,IAAG;AACH;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iBAAgB;AAChB;;AAEA;AACA;;AAEA;;AAEA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,QAAO;AACP;;AAEA;AACA;AACA,MAAK;AACL,IAAG;;AAEH;AACA;AACA,IAAG;;AAEH;AACA;AACA,IAAG;;AAEH;AACA;AACA,IAAG;;AAEH;AACA;AACA,IAAG;;AAEH;AACA;AACA,IAAG;;AAEH;AACA;AACA;AACA;AACA;;AAEA;AACA,IAAG;;AAEH;AACA;AACA,IAAG;;AAEH;AACA;AACA;AACA,MAAK;AACL,IAAG;AACH;AACA;AACA,IAAG;;AAEH;AACA;AACA,IAAG;;AAEH;AACA;AACA,IAAG;;AAEH;AACA;AACA,IAAG;;AAEH;AACA;AACA,IAAG;;AAEH;AACA;AACA;AACA;;AAEA;;;;;;;;AC1RA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAW,MAAM;AACjB,aAAY;AACZ;;AAEA;AACA;AACA;;;;;;;AChCA;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,eAAc;A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I,GAAR,CAAxB;AAAA,IAAzB,EAAiEuE,IAAjE,CAAsE,EAAtE,CAAf;AACA;AACA,UAAO,6BAAiBhG,IAAjB,EAAuB,KAAvB,EAAiCsZ,mBAAmBhQ,GAAnB,CAAjC,oCAAuFiQ,MAAvF,CAAP;AACD;;AAED,UAASD,kBAAT,CAA6BhQ,GAA7B,EAAkC;AAChC,OAAMC,OAAOnJ,mBAAmBkJ,IAAIU,KAAvB,CAAb;AACA,OAAM9J,KAAKE,mBAAmBkJ,IAAIS,GAAvB,CAAX;AACA,qBAAgBR,IAAhB,SAAwBrJ,EAAxB;AACD,E","file":"cozy-client.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine(\"client\", [], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"client\"] = factory();\n\telse\n\t\troot[\"cozy\"] = root[\"cozy\"] || {}, root[\"cozy\"][\"client\"] = factory();\n})(this, function() {\nreturn \n\n\n// WEBPACK FOOTER //\n// webpack/universalModuleDefinition"," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId])\n \t\t\treturn installedModules[moduleId].exports;\n\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\texports: {},\n \t\t\tid: moduleId,\n \t\t\tloaded: false\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.loaded = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(0);\n\n\n\n// WEBPACK FOOTER //\n// webpack/bootstrap 5da2cef222e8ad09f168","// the whatwg-fetch polyfill installs the fetch() function\n// on the global object (window or self)\n//\n// Return that as the export for use in Webpack, Browserify etc.\nrequire('whatwg-fetch');\nmodule.exports = self.fetch.bind(self);\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/isomorphic-fetch/fetch-npm-browserify.js\n// module id = 1\n// module chunks = 0","(function(self) {\n 'use strict';\n\n if (self.fetch) {\n return\n }\n\n var support = {\n searchParams: 'URLSearchParams' in self,\n iterable: 'Symbol' in self && 'iterator' in Symbol,\n blob: 'FileReader' in self && 'Blob' in self && (function() {\n try {\n new Blob()\n return true\n } catch(e) {\n return false\n }\n })(),\n formData: 'FormData' in self,\n arrayBuffer: 'ArrayBuffer' in self\n }\n\n if (support.arrayBuffer) {\n var viewClasses = [\n '[object Int8Array]',\n '[object Uint8Array]',\n '[object Uint8ClampedArray]',\n '[object Int16Array]',\n '[object Uint16Array]',\n '[object Int32Array]',\n '[object Uint32Array]',\n '[object Float32Array]',\n '[object Float64Array]'\n ]\n\n var isDataView = function(obj) {\n return obj && DataView.prototype.isPrototypeOf(obj)\n }\n\n var isArrayBufferView = ArrayBuffer.isView || function(obj) {\n return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1\n }\n }\n\n function normalizeName(name) {\n if (typeof name !== 'string') {\n name = String(name)\n }\n if (/[^a-z0-9\\-#$%&'*+.\\^_`|~]/i.test(name)) {\n throw new TypeError('Invalid character in header field name')\n }\n return name.toLowerCase()\n }\n\n function normalizeValue(value) {\n if (typeof value !== 'string') {\n value = String(value)\n }\n return value\n }\n\n // Build a destructive iterator for the value list\n function iteratorFor(items) {\n var iterator = {\n next: function() {\n var value = items.shift()\n return {done: value === undefined, value: value}\n }\n }\n\n if (support.iterable) {\n iterator[Symbol.iterator] = function() {\n return iterator\n }\n }\n\n return iterator\n }\n\n function Headers(headers) {\n this.map = {}\n\n if (headers instanceof Headers) {\n headers.forEach(function(value, name) {\n this.append(name, value)\n }, this)\n } else if (Array.isArray(headers)) {\n headers.forEach(function(header) {\n this.append(header[0], header[1])\n }, this)\n } else if (headers) {\n Object.getOwnPropertyNames(headers).forEach(function(name) {\n this.append(name, headers[name])\n }, this)\n }\n }\n\n Headers.prototype.append = function(name, value) {\n name = normalizeName(name)\n value = normalizeValue(value)\n var oldValue = this.map[name]\n this.map[name] = oldValue ? oldValue+','+value : value\n }\n\n Headers.prototype['delete'] = function(name) {\n delete this.map[normalizeName(name)]\n }\n\n Headers.prototype.get = function(name) {\n name = normalizeName(name)\n return this.has(name) ? this.map[name] : null\n }\n\n Headers.prototype.has = function(name) {\n return this.map.hasOwnProperty(normalizeName(name))\n }\n\n Headers.prototype.set = function(name, value) {\n this.map[normalizeName(name)] = normalizeValue(value)\n }\n\n Headers.prototype.forEach = function(callback, thisArg) {\n for (var name in this.map) {\n if (this.map.hasOwnProperty(name)) {\n callback.call(thisArg, this.map[name], name, this)\n }\n }\n }\n\n Headers.prototype.keys = function() {\n var items = []\n this.forEach(function(value, name) { items.push(name) })\n return iteratorFor(items)\n }\n\n Headers.prototype.values = function() {\n var items = []\n this.forEach(function(value) { items.push(value) })\n return iteratorFor(items)\n }\n\n Headers.prototype.entries = function() {\n var items = []\n this.forEach(function(value, name) { items.push([name, value]) })\n return iteratorFor(items)\n }\n\n if (support.iterable) {\n Headers.prototype[Symbol.iterator] = Headers.prototype.entries\n }\n\n function consumed(body) {\n if (body.bodyUsed) {\n return Promise.reject(new TypeError('Already read'))\n }\n body.bodyUsed = true\n }\n\n function fileReaderReady(reader) {\n return new Promise(function(resolve, reject) {\n reader.onload = function() {\n resolve(reader.result)\n }\n reader.onerror = function() {\n reject(reader.error)\n }\n })\n }\n\n function readBlobAsArrayBuffer(blob) {\n var reader = new FileReader()\n var promise = fileReaderReady(reader)\n reader.readAsArrayBuffer(blob)\n return promise\n }\n\n function readBlobAsText(blob) {\n var reader = new FileReader()\n var promise = fileReaderReady(reader)\n reader.readAsText(blob)\n return promise\n }\n\n function readArrayBufferAsText(buf) {\n var view = new Uint8Array(buf)\n var chars = new Array(view.length)\n\n for (var i = 0; i < view.length; i++) {\n chars[i] = String.fromCharCode(view[i])\n }\n return chars.join('')\n }\n\n function bufferClone(buf) {\n if (buf.slice) {\n return buf.slice(0)\n } else {\n var view = new Uint8Array(buf.byteLength)\n view.set(new Uint8Array(buf))\n return view.buffer\n }\n }\n\n function Body() {\n this.bodyUsed = false\n\n this._initBody = function(body) {\n this._bodyInit = body\n if (!body) {\n this._bodyText = ''\n } else if (typeof body === 'string') {\n this._bodyText = body\n } else if (support.blob && Blob.prototype.isPrototypeOf(body)) {\n this._bodyBlob = body\n } else if (support.formData && FormData.prototype.isPrototypeOf(body)) {\n this._bodyFormData = body\n } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {\n this._bodyText = body.toString()\n } else if (support.arrayBuffer && support.blob && isDataView(body)) {\n this._bodyArrayBuffer = bufferClone(body.buffer)\n // IE 10-11 can't handle a DataView body.\n this._bodyInit = new Blob([this._bodyArrayBuffer])\n } else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) {\n this._bodyArrayBuffer = bufferClone(body)\n } else {\n throw new Error('unsupported BodyInit type')\n }\n\n if (!this.headers.get('content-type')) {\n if (typeof body === 'string') {\n this.headers.set('content-type', 'text/plain;charset=UTF-8')\n } else if (this._bodyBlob && this._bodyBlob.type) {\n this.headers.set('content-type', this._bodyBlob.type)\n } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {\n this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8')\n }\n }\n }\n\n if (support.blob) {\n this.blob = function() {\n var rejected = consumed(this)\n if (rejected) {\n return rejected\n }\n\n if (this._bodyBlob) {\n return Promise.resolve(this._bodyBlob)\n } else if (this._bodyArrayBuffer) {\n return Promise.resolve(new Blob([this._bodyArrayBuffer]))\n } else if (this._bodyFormData) {\n throw new Error('could not read FormData body as blob')\n } else {\n return Promise.resolve(new Blob([this._bodyText]))\n }\n }\n\n this.arrayBuffer = function() {\n if (this._bodyArrayBuffer) {\n return consumed(this) || Promise.resolve(this._bodyArrayBuffer)\n } else {\n return this.blob().then(readBlobAsArrayBuffer)\n }\n }\n }\n\n this.text = function() {\n var rejected = consumed(this)\n if (rejected) {\n return rejected\n }\n\n if (this._bodyBlob) {\n return readBlobAsText(this._bodyBlob)\n } else if (this._bodyArrayBuffer) {\n return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer))\n } else if (this._bodyFormData) {\n throw new Error('could not read FormData body as text')\n } else {\n return Promise.resolve(this._bodyText)\n }\n }\n\n if (support.formData) {\n this.formData = function() {\n return this.text().then(decode)\n }\n }\n\n this.json = function() {\n return this.text().then(JSON.parse)\n }\n\n return this\n }\n\n // HTTP methods whose capitalization should be normalized\n var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']\n\n function normalizeMethod(method) {\n var upcased = method.toUpperCase()\n return (methods.indexOf(upcased) > -1) ? upcased : method\n }\n\n function Request(input, options) {\n options = options || {}\n var body = options.body\n\n if (input instanceof Request) {\n if (input.bodyUsed) {\n throw new TypeError('Already read')\n }\n this.url = input.url\n this.credentials = input.credentials\n if (!options.headers) {\n this.headers = new Headers(input.headers)\n }\n this.method = input.method\n this.mode = input.mode\n if (!body && input._bodyInit != null) {\n body = input._bodyInit\n input.bodyUsed = true\n }\n } else {\n this.url = String(input)\n }\n\n this.credentials = options.credentials || this.credentials || 'omit'\n if (options.headers || !this.headers) {\n this.headers = new Headers(options.headers)\n }\n this.method = normalizeMethod(options.method || this.method || 'GET')\n this.mode = options.mode || this.mode || null\n this.referrer = null\n\n if ((this.method === 'GET' || this.method === 'HEAD') && body) {\n throw new TypeError('Body not allowed for GET or HEAD requests')\n }\n this._initBody(body)\n }\n\n Request.prototype.clone = function() {\n return new Request(this, { body: this._bodyInit })\n }\n\n function decode(body) {\n var form = new FormData()\n body.trim().split('&').forEach(function(bytes) {\n if (bytes) {\n var split = bytes.split('=')\n var name = split.shift().replace(/\\+/g, ' ')\n var value = split.join('=').replace(/\\+/g, ' ')\n form.append(decodeURIComponent(name), decodeURIComponent(value))\n }\n })\n return form\n }\n\n function parseHeaders(rawHeaders) {\n var headers = new Headers()\n rawHeaders.split(/\\r?\\n/).forEach(function(line) {\n var parts = line.split(':')\n var key = parts.shift().trim()\n if (key) {\n var value = parts.join(':').trim()\n headers.append(key, value)\n }\n })\n return headers\n }\n\n Body.call(Request.prototype)\n\n function Response(bodyInit, options) {\n if (!options) {\n options = {}\n }\n\n this.type = 'default'\n this.status = 'status' in options ? options.status : 200\n this.ok = this.status >= 200 && this.status < 300\n this.statusText = 'statusText' in options ? options.statusText : 'OK'\n this.headers = new Headers(options.headers)\n this.url = options.url || ''\n this._initBody(bodyInit)\n }\n\n Body.call(Response.prototype)\n\n Response.prototype.clone = function() {\n return new Response(this._bodyInit, {\n status: this.status,\n statusText: this.statusText,\n headers: new Headers(this.headers),\n url: this.url\n })\n }\n\n Response.error = function() {\n var response = new Response(null, {status: 0, statusText: ''})\n response.type = 'error'\n return response\n }\n\n var redirectStatuses = [301, 302, 303, 307, 308]\n\n Response.redirect = function(url, status) {\n if (redirectStatuses.indexOf(status) === -1) {\n throw new RangeError('Invalid status code')\n }\n\n return new Response(null, {status: status, headers: {location: url}})\n }\n\n self.Headers = Headers\n self.Request = Request\n self.Response = Response\n\n self.fetch = function(input, init) {\n return new Promise(function(resolve, reject) {\n var request = new Request(input, init)\n var xhr = new XMLHttpRequest()\n\n xhr.onload = function() {\n var options = {\n status: xhr.status,\n statusText: xhr.statusText,\n headers: parseHeaders(xhr.getAllResponseHeaders() || '')\n }\n options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL')\n var body = 'response' in xhr ? xhr.response : xhr.responseText\n resolve(new Response(body, options))\n }\n\n xhr.onerror = function() {\n reject(new TypeError('Network request failed'))\n }\n\n xhr.ontimeout = function() {\n reject(new TypeError('Network request failed'))\n }\n\n xhr.open(request.method, request.url, true)\n\n if (request.credentials === 'include') {\n xhr.withCredentials = true\n }\n\n if ('responseType' in xhr && support.blob) {\n xhr.responseType = 'blob'\n }\n\n request.headers.forEach(function(value, name) {\n xhr.setRequestHeader(name, value)\n })\n\n xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit)\n })\n }\n self.fetch.polyfill = true\n})(typeof self !== 'undefined' ? self : this);\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/whatwg-fetch/fetch.js\n// module id = 2\n// module chunks = 0","/* global fetch URL */\n\nimport { unpromiser, retry, warn } from './utils'\nimport { LocalStorage, MemoryStorage } from './auth_storage'\nimport { AppToken as AppTokenV2, getAppToken as getAppTokenV2 } from './auth_v2'\nimport * as auth from './auth_v3'\nimport * as data from './data'\nimport * as cozyFetch from './fetch'\nimport * as mango from './mango'\nimport * as files from './files'\nimport * as intents from './intents'\nimport * as jobs from './jobs'\nimport * as offline from './offline'\nimport * as settings from './settings'\nimport * as relations from './relations'\n\nconst {\n AppToken: AppTokenV3,\n AccessToken: AccessTokenV3,\n Client: ClientV3\n} = auth\n\nconst AuthNone = 0\nconst AuthRunning = 1\nconst AuthError = 2\nconst AuthOK = 3\n\nconst defaultClientParams = {\n softwareID: 'github.com/cozy/cozy-client-js'\n}\n\nconst dataProto = {\n create: data.create,\n find: data.find,\n findMany: data.findMany,\n findAll: data.findAll,\n update: data.update,\n delete: data._delete,\n updateAttributes: data.updateAttributes,\n changesFeed: data.changesFeed,\n defineIndex: mango.defineIndex,\n query: mango.query,\n addReferencedFiles: relations.addReferencedFiles,\n removeReferencedFiles: relations.removeReferencedFiles,\n listReferencedFiles: relations.listReferencedFiles,\n fetchReferencedFiles: relations.fetchReferencedFiles,\n destroy: function (...args) {\n warn('destroy is deprecated, use cozy.data.delete instead.')\n return data._delete(...args)\n }\n}\n\nconst authProto = {\n client: auth.client,\n registerClient: auth.registerClient,\n updateClient: auth.updateClient,\n unregisterClient: auth.unregisterClient,\n getClient: auth.getClient,\n getAuthCodeURL: auth.getAuthCodeURL,\n getAccessToken: auth.getAccessToken,\n refreshToken: auth.refreshToken\n}\n\nconst filesProto = {\n create: files.create,\n createDirectory: files.createDirectory,\n createDirectoryByPath: files.createDirectoryByPath,\n updateById: files.updateById,\n updateAttributesById: files.updateAttributesById,\n updateAttributesByPath: files.updateAttributesByPath,\n trashById: files.trashById,\n statById: files.statById,\n statByPath: files.statByPath,\n downloadById: files.downloadById,\n downloadByPath: files.downloadByPath,\n getDownloadLinkById: files.getDownloadLinkById,\n getDownloadLink: files.getDownloadLinkByPath, // DEPRECATED, should be removed very soon\n getDownloadLinkByPath: files.getDownloadLinkByPath,\n getArchiveLink: function (...args) {\n warn('getArchiveLink is deprecated, use cozy.files.getArchiveLinkByPaths instead.')\n return files.getArchiveLinkByPaths(...args)\n },\n getArchiveLinkByPaths: files.getArchiveLinkByPaths,\n getArchiveLinkByIds: files.getArchiveLinkByIds,\n getFilePath: files.getFilePath,\n getCollectionShareLink: files.getCollectionShareLink,\n query: mango.queryFiles,\n listTrash: files.listTrash,\n clearTrash: files.clearTrash,\n restoreById: files.restoreById,\n destroyById: files.destroyById\n}\n\nconst intentsProto = {\n create: intents.create,\n createService: intents.createService\n}\n\nconst jobsProto = {\n create: jobs.create,\n count: jobs.count,\n queued: jobs.queued\n}\n\nconst offlineProto = {\n init: offline.init,\n getDoctypes: offline.getDoctypes,\n // database\n hasDatabase: offline.hasDatabase,\n getDatabase: offline.getDatabase,\n createDatabase: offline.createDatabase,\n destroyDatabase: offline.destroyDatabase,\n destroyAllDatabase: offline.destroyAllDatabase,\n // replication\n hasReplication: offline.hasReplication,\n replicateFromCozy: offline.replicateFromCozy,\n stopReplication: offline.stopReplication,\n stopAllReplication: offline.stopAllReplication,\n // repeated replication\n hasRepeatedReplication: offline.hasRepeatedReplication,\n startRepeatedReplication: offline.startRepeatedReplication,\n stopRepeatedReplication: offline.stopRepeatedReplication,\n stopAllRepeatedReplication: offline.stopAllRepeatedReplication\n}\n\nconst settingsProto = {\n diskUsage: settings.diskUsage,\n changePassphrase: settings.changePassphrase,\n getInstance: settings.getInstance,\n updateInstance: settings.updateInstance,\n getClients: settings.getClients,\n deleteClientById: settings.deleteClientById,\n updateLastSync: settings.updateLastSync\n}\n\nclass Client {\n constructor(options) {\n this.data = {}\n this.files = {}\n this.intents = {}\n this.jobs = {}\n this.offline = {}\n this.settings = {}\n this.auth = {\n Client: ClientV3,\n AccessToken: AccessTokenV3,\n AppToken: AppTokenV3,\n AppTokenV2: AppTokenV2,\n LocalStorage: LocalStorage,\n MemoryStorage: MemoryStorage\n }\n this._inited = false\n if (options) {\n this.init(options)\n }\n }\n\n init(options = {}) {\n this._inited = true\n this._oauth = false // is oauth activated or not\n this._token = null // application token\n this._authstate = AuthNone\n this._authcreds = null\n this._storage = null\n this._version = options.version || null\n this._offline = null\n\n const token = options.token\n const oauth = options.oauth\n if (token && oauth) {\n throw new Error('Cannot specify an application token with a oauth activated')\n }\n\n if (token) {\n this._token = new AppTokenV3({ token })\n } else if (oauth) {\n this._oauth = true\n this._storage = oauth.storage\n this._clientParams = Object.assign({}, defaultClientParams, oauth.clientParams)\n this._onRegistered = oauth.onRegistered || nopOnRegistered\n }\n\n let url = options.cozyURL || ''\n while (url[url.length - 1] === '/') {\n url = url.slice(0, -1)\n }\n\n this._url = url\n\n const disablePromises = !!options.disablePromises\n addToProto(this, this.data, dataProto, disablePromises)\n addToProto(this, this.auth, authProto, disablePromises)\n addToProto(this, this.files, filesProto, disablePromises)\n addToProto(this, this.intents, intentsProto, disablePromises)\n addToProto(this, this.jobs, jobsProto, disablePromises)\n addToProto(this, this.offline, offlineProto, disablePromises)\n addToProto(this, this.settings, settingsProto, disablePromises)\n\n if (options.offline) {\n this.offline.init(options.offline)\n }\n\n // Exposing cozyFetchJSON to make some development easier. Should be temporary.\n this.fetchJSON = function _fetchJSON() {\n const args = [this].concat(Array.prototype.slice.call(arguments))\n return cozyFetch.cozyFetchJSON.apply(this, args)\n }\n }\n\n authorize(forceTokenRefresh = false) {\n const state = this._authstate\n if (state === AuthOK || state === AuthRunning) {\n return this._authcreds\n }\n\n this._authstate = AuthRunning\n this._authcreds = this.isV2().then((isV2) => {\n if (isV2 && this._oauth) {\n throw new Error('OAuth is not supported on the V2 stack')\n }\n if (this._oauth) {\n if (forceTokenRefresh && this._clientParams.redirectURI) {\n const url = new URL(this._clientParams.redirectURI)\n if (!url.searchParams.has('reconnect')) url.searchParams.append('reconnect', 1)\n this._clientParams.redirectURI = url.toString()\n }\n return auth.oauthFlow(\n this,\n this._storage,\n this._clientParams,\n this._onRegistered,\n forceTokenRefresh\n )\n }\n // we expect to be on a client side application running in a browser\n // with cookie-based authentication.\n if (isV2) {\n return getAppTokenV2()\n } else if (this._token) {\n return Promise.resolve({ client: null, token: this._token })\n } else {\n throw new Error('Missing application token')\n }\n })\n\n this._authcreds.then(\n () => { this._authstate = AuthOK },\n () => { this._authstate = AuthError })\n\n return this._authcreds\n }\n\n saveCredentials(client, token) {\n const creds = { client, token }\n if (!this._storage || this._authstate === AuthRunning) {\n return Promise.resolve(creds)\n }\n this._storage.save(auth.CredsKey, creds)\n this._authcreds = Promise.resolve(creds)\n return this._authcreds\n }\n\n fullpath(path) {\n return this.isV2().then((isV2) => {\n const pathprefix = isV2 ? '/ds-api' : ''\n return this._url + pathprefix + path\n })\n }\n\n isV2() {\n if (!this._version) {\n return retry(() => fetch(`${this._url}/status/`), 3)()\n .then((res) => {\n if (!res.ok) {\n throw new Error('Could not fetch cozy status')\n } else {\n return res.json()\n }\n })\n .then((status) => {\n this._version = status.datasystem !== undefined ? 2 : 3\n return this.isV2()\n })\n }\n return Promise.resolve(this._version === 2)\n }\n}\n\nfunction nopOnRegistered() {\n throw new Error('Missing onRegistered callback')\n}\n\nfunction protoify(context, fn) {\n return function prototyped(...args) {\n return fn(context, ...args)\n }\n}\n\nfunction addToProto(ctx, obj, proto, disablePromises) {\n for (const attr in proto) {\n let fn = protoify(ctx, proto[attr])\n if (disablePromises) {\n fn = unpromiser(fn)\n }\n obj[attr] = fn\n }\n}\n\nmodule.exports = new Client()\nObject.assign(module.exports, { Client, LocalStorage, MemoryStorage })\n\n\n\n// WEBPACK FOOTER //\n// ./src/index.js","// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/process/browser.js\n// module id = 191\n// module chunks = 0","/* global navigator */\nconst FuzzFactor = 0.3\n\nexport function unpromiser (fn) {\n return function (...args) {\n const value = fn.apply(this, args)\n if (!isPromise(value)) {\n return value\n }\n const l = args.length\n if (l === 0 || typeof args[l - 1] !== 'function') {\n return\n }\n const cb = args[l - 1]\n value.then(\n (res) => cb(null, res),\n (err) => cb(err, null)\n )\n }\n}\n\nexport function isPromise (value) {\n return !!value && typeof value.then === 'function'\n}\n\nexport function isOnline () {\n return typeof navigator !== 'undefined' ? navigator.onLine : true\n}\n\nexport function isOffline () {\n return !isOnline()\n}\n\nexport function sleep (time, args) {\n return new Promise((resolve) => {\n setTimeout(resolve, time, args)\n })\n}\n\nexport function retry (fn, count, delay = 300) {\n return function doTry (...args) {\n return fn(...args).catch((err) => {\n if (--count < 0) {\n throw err\n }\n return sleep(getBackedoffDelay(delay, count))\n .then(() => doTry(...args))\n })\n }\n}\n\nexport function getFuzzedDelay (retryDelay) {\n const fuzzingFactor = ((Math.random() * 2) - 1) * FuzzFactor\n return retryDelay * (1.0 + fuzzingFactor)\n}\n\nexport function getBackedoffDelay (retryDelay, retryCount = 1) {\n return getFuzzedDelay(retryDelay * Math.pow(2, retryCount - 1))\n}\n\nexport function createPath (cozy, isV2, doctype, id = '', query = null) {\n let route = '/data/'\n if (!isV2) {\n route += `${encodeURIComponent(doctype)}/`\n }\n if (id !== '') {\n route += encodeURIComponent(id)\n }\n const q = encodeQuery(query)\n if (q !== '') {\n route += '?' + q\n }\n return route\n}\n\nexport function encodeQuery (query) {\n if (!query) {\n return ''\n }\n let q = ''\n for (const qname in query) {\n if (q !== '') {\n q += '&'\n }\n q += `${encodeURIComponent(qname)}=${encodeURIComponent(query[qname])}`\n }\n return q\n}\n\nexport function decodeQuery (url) {\n let queryIndex = url.indexOf('?')\n if (queryIndex < 0) {\n queryIndex = url.length\n }\n const queries = {}\n let fragIndex = url.indexOf('#')\n if (fragIndex < 0) {\n fragIndex = url.length\n }\n if (fragIndex < queryIndex) {\n return queries\n }\n const queryStr = url.slice(queryIndex + 1, fragIndex)\n if (queryStr === '') {\n return queries\n }\n const parts = queryStr.split('&')\n for (let i = 0; i < parts.length; i++) {\n let pair = parts[i].split('=')\n if (pair.length === 0 || pair[0] === '') {\n continue\n }\n const qname = decodeURIComponent(pair[0])\n if (queries.hasOwnProperty(qname)) {\n continue\n }\n if (pair.length === 1) {\n queries[qname] = true\n } else if (pair.length === 2) {\n queries[qname] = decodeURIComponent(pair[1])\n } else {\n throw new Error('Malformed URL')\n }\n }\n return queries\n}\n\nconst warned = []\nexport function warn (text) {\n if (warned.indexOf(text) === -1) {\n warned.push(text)\n console.warn('cozy-client-js', text)\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils.js","export class LocalStorage {\n constructor (storage, prefix) {\n if (!storage && typeof window !== 'undefined') {\n storage = window.localStorage\n }\n this.storage = storage\n this.prefix = prefix || 'cozy:oauth:'\n }\n\n save (key, value) {\n return new Promise(resolve => {\n this.storage.setItem(this.prefix + key, JSON.stringify(value))\n resolve(value)\n })\n }\n\n load (key) {\n return new Promise(resolve => {\n const item = this.storage.getItem(this.prefix + key)\n if (!item) {\n resolve()\n } else {\n resolve(JSON.parse(item))\n }\n })\n }\n\n delete (key) {\n return new Promise(resolve => resolve(\n this.storage.removeItem(this.prefix + key)))\n }\n\n clear () {\n return new Promise(resolve => {\n const storage = this.storage\n for (let i = 0; i < storage.length; i++) {\n const key = storage.key(i)\n if (key.indexOf(this.prefix) === 0) {\n storage.removeItem(key)\n }\n }\n resolve()\n })\n }\n}\n\nexport class MemoryStorage {\n constructor () {\n this.hash = Object.create(null)\n }\n\n save (key, value) {\n this.hash[key] = value\n return Promise.resolve(value)\n }\n\n load (key) {\n return Promise.resolve(this.hash[key])\n }\n\n delete (key) {\n const deleted = delete this.hash[key]\n return Promise.resolve(deleted)\n }\n\n clear () {\n this.hash = Object.create(null)\n return Promise.resolve()\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/auth_storage.js","/* global btoa */\nconst V2TOKEN_ABORT_TIMEOUT = 3000\n\nexport function getAppToken () {\n return new Promise(function (resolve, reject) {\n if (typeof window === 'undefined') {\n return reject(new Error('getV2Token should be used in browser'))\n } else if (!window.parent) {\n return reject(new Error('getV2Token should be used in iframe'))\n } else if (!window.parent.postMessage) {\n return reject(new Error('getV2Token should be used in modern browser'))\n }\n const origin = window.location.origin\n const intent = {action: 'getToken'}\n let timeout = null\n const receiver = function (event) {\n let token\n try {\n token = new AppToken({\n appName: event.data.appName,\n token: event.data.token\n })\n } catch (e) {\n reject(e)\n return\n }\n window.removeEventListener('message', receiver)\n clearTimeout(timeout)\n resolve({ client: null, token })\n }\n window.addEventListener('message', receiver, false)\n window.parent.postMessage(intent, origin)\n timeout = setTimeout(() => {\n reject(new Error('No response from parent iframe after 3s'))\n }, V2TOKEN_ABORT_TIMEOUT)\n })\n}\n\nexport class AppToken {\n constructor (opts) {\n this.appName = opts.appName || ''\n this.token = opts.token || ''\n }\n\n toAuthHeader () {\n return 'Basic ' + btoa(`${this.appName}:${this.token}`)\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/auth_v2.js","/* global btoa */\nimport {encodeQuery, decodeQuery, isOffline} from './utils'\nimport {cozyFetchJSON, FetchError} from './fetch'\n\nconst StateSize = 16\n\nexport const CredsKey = 'creds'\nexport const StateKey = 'state'\n\nexport class Client {\n constructor (opts) {\n this.clientID = opts.clientID || opts.client_id || ''\n this.clientSecret = opts.clientSecret || opts.client_secret || ''\n this.registrationAccessToken = opts.registrationAccessToken || opts.registration_access_token || ''\n\n if (opts.redirect_uris) {\n this.redirectURI = opts.redirect_uris[0] || ''\n } else {\n this.redirectURI = opts.redirectURI || ''\n }\n\n this.softwareID = opts.softwareID || opts.software_id || ''\n this.softwareVersion = opts.softwareVersion || opts.software_version || ''\n this.clientName = opts.clientName || opts.client_name || ''\n this.clientKind = opts.clientKind || opts.client_kind || ''\n this.clientURI = opts.clientURI || opts.client_uri || ''\n\n this.logoURI = opts.logoURI || opts.logo_uri || ''\n this.policyURI = opts.policyURI || opts.policy_uri || ''\n\n if (!this.registrationAccessToken) {\n if (this.redirectURI === '') {\n throw new Error('Missing redirectURI field')\n }\n if (this.softwareID === '') {\n throw new Error('Missing softwareID field')\n }\n if (this.clientName === '') {\n throw new Error('Missing clientName field')\n }\n }\n }\n\n isRegistered () {\n return this.clientID !== ''\n }\n\n toRegisterJSON () {\n return {\n redirect_uris: [this.redirectURI],\n software_id: this.softwareID,\n software_version: this.softwareVersion,\n client_name: this.clientName,\n client_kind: this.clientKind,\n client_uri: this.clientURI,\n logo_uri: this.logoURI,\n policy_uri: this.policyURI\n }\n }\n\n toAuthHeader () {\n return 'Bearer ' + this.registrationAccessToken\n }\n}\n\nexport class AccessToken {\n constructor (opts) {\n this.tokenType = opts.tokenType || opts.token_type\n this.accessToken = opts.accessToken || opts.access_token\n this.refreshToken = opts.refreshToken || opts.refresh_token\n this.scope = opts.scope\n }\n\n toAuthHeader () {\n return 'Bearer ' + this.accessToken\n }\n\n toBasicAuth () {\n return `user:${this.accessToken}@`\n }\n}\n\nexport class AppToken {\n constructor (opts) {\n this.token = opts.token || ''\n }\n\n toAuthHeader () {\n return 'Bearer ' + this.token\n }\n\n toBasicAuth () {\n return `user:${this.token}@`\n }\n}\n\nexport function client (cozy, clientParams) {\n if (!clientParams) {\n clientParams = cozy._clientParams\n }\n if (clientParams instanceof Client) {\n return clientParams\n }\n return new Client(clientParams)\n}\n\nexport function registerClient (cozy, clientParams) {\n const cli = client(cozy, clientParams)\n if (cli.isRegistered()) {\n return Promise.reject(new Error('Client already registered'))\n }\n return cozyFetchJSON(cozy, 'POST', '/auth/register', cli.toRegisterJSON(), {\n disableAuth: true\n })\n .then((data) => new Client(data))\n}\n\nexport function updateClient (cozy, clientParams, resetSecret = false) {\n const cli = client(cozy, clientParams)\n if (!cli.isRegistered()) {\n return Promise.reject(new Error('Client not registered'))\n }\n let data = cli.toRegisterJSON()\n data.client_id = cli.clientID\n if (resetSecret) data.client_secret = cli.clientSecret\n\n return cozyFetchJSON(cozy, 'PUT', `/auth/register/${cli.clientID}`, data, {\n manualAuthCredentials: {\n token: cli\n }\n }).then((data) => createClient(data, cli))\n}\n\nexport function unregisterClient (cozy, clientParams) {\n const cli = client(cozy, clientParams)\n if (!cli.isRegistered()) {\n return Promise.reject(new Error('Client not registered'))\n }\n return cozyFetchJSON(cozy, 'DELETE', `/auth/register/${cli.clientID}`, null, {\n manualAuthCredentials: {\n token: cli\n }\n })\n}\n\n// getClient will retrive the registered client informations from the server.\nexport function getClient (cozy, clientParams) {\n const cli = client(cozy, clientParams)\n if (!cli.isRegistered()) {\n return Promise.reject(new Error('Client not registered'))\n }\n if (isOffline()) {\n return Promise.resolve(cli)\n }\n return cozyFetchJSON(cozy, 'GET', `/auth/register/${cli.clientID}`, null,\n {\n manualAuthCredentials: {\n token: cli\n }\n })\n .then((data) => createClient(data, cli))\n .catch((err) => {\n // If we fall into an error while fetching the client (because of a\n // bad connectivity for instance), we do not bail the whole process\n // since the client should be able to continue with the persisted\n // client and token.\n //\n // If it is an explicit Unauthorized error though, we bail, clear th\n // cache and retry.\n if (FetchError.isUnauthorized(err) || FetchError.isNotFound(err)) {\n throw new Error('Client has been revoked')\n }\n throw err\n })\n}\n\n// createClient returns a new Client instance given on object containing the\n// data of the client, from the API, and an old instance of the client.\nfunction createClient (data, oldClient) {\n const newClient = new Client(data)\n // we need to keep track of the registrationAccessToken since it is send\n // only on registration. The GET /auth/register/:client-id endpoint does\n // not return this token.\n const shouldPassRegistration = (\n !!oldClient &&\n oldClient.registrationAccessToken !== '' &&\n newClient.registrationAccessToken === ''\n )\n if (shouldPassRegistration) {\n newClient.registrationAccessToken = oldClient.registrationAccessToken\n }\n return newClient\n}\n\n// getAuthCodeURL returns a pair {authURL,state} given a registered client. The\n// state should be stored in order to be checked against on the user validation\n// phase.\nexport function getAuthCodeURL (cozy, client, scopes = []) {\n if (!(client instanceof Client)) {\n client = new Client(client)\n }\n if (!client.isRegistered()) {\n throw new Error('Client not registered')\n }\n const state = generateRandomState()\n const query = {\n 'client_id': client.clientID,\n 'redirect_uri': client.redirectURI,\n 'state': state,\n 'response_type': 'code',\n 'scope': scopes.join(' ')\n }\n return {\n url: cozy._url + `/auth/authorize?${encodeQuery(query)}`,\n state: state\n }\n}\n\n// getAccessToken perform a request on the access_token entrypoint with the\n// authorization_code grant type in order to generate a new access token for a\n// newly registered client.\n//\n// This method extracts the access code and state from the given URL. By\n// default it uses window.location.href. Also, it checks the given state with\n// the one specified in the URL query parameter to prevent CSRF attacks.\nexport function getAccessToken (cozy, client, state, pageURL = '') {\n if (!state) {\n return Promise.reject(new Error('Missing state value'))\n }\n const grantQueries = getGrantCodeFromPageURL(pageURL)\n if (grantQueries === null) {\n return Promise.reject(new Error('Missing states from current URL'))\n }\n if (state !== grantQueries.state) {\n return Promise.reject(new Error('Given state does not match url query state'))\n }\n return retrieveToken(cozy, client, null, {\n 'grant_type': 'authorization_code',\n 'code': grantQueries.code\n })\n}\n\n// refreshToken perform a request on the access_token entrypoint with the\n// refresh_token grant type in order to refresh the given token.\nexport function refreshToken (cozy, client, token) {\n return retrieveToken(cozy, client, token, {\n 'grant_type': 'refresh_token',\n 'refresh_token': token.refreshToken\n })\n}\n\n// oauthFlow performs the stateful registration and access granting of an OAuth\n// client.\nexport function oauthFlow (cozy, storage, clientParams, onRegistered, ignoreCachedCredentials = false) {\n if (ignoreCachedCredentials) {\n return storage.clear().then(() => oauthFlow(cozy, storage, clientParams, onRegistered, false))\n }\n\n let tryCount = 0\n\n function clearAndRetry (err) {\n if (tryCount++ > 0) {\n throw err\n }\n return storage.clear().then(() =>\n oauthFlow(cozy, storage, clientParams, onRegistered))\n }\n\n function registerNewClient () {\n return storage.clear()\n .then(() => registerClient(cozy, clientParams))\n .then((client) => {\n const {url, state} = getAuthCodeURL(cozy, client, clientParams.scopes)\n return storage.save(StateKey, {client, url, state})\n })\n }\n\n return Promise.all([\n storage.load(CredsKey),\n storage.load(StateKey)\n ]).then(([credentials, storedState]) => {\n // If credentials are cached we re-fetch the registered client with the\n // said token. Fetching the client, if the token is outdated we should try\n // the token is refreshed.\n if (credentials) {\n let oldClient, token\n try {\n oldClient = new Client(credentials.client)\n token = new AccessToken(credentials.token)\n } catch (err) {\n // bad cache, we should clear and retry the process\n return clearAndRetry(err)\n }\n return getClient(cozy, oldClient)\n .then((client) => ({client, token}))\n .catch((err) => {\n // If we fall into an error while fetching the client (because of a\n // bad connectivity for instance), we do not bail the whole process\n // since the client should be able to continue with the persisted\n // client and token.\n //\n // If it is an explicit Unauthorized error though, we bail, clear th\n // cache and retry.\n if (FetchError.isUnauthorized(err) || FetchError.isNotFound(err)) {\n throw new Error('Client has been revoked')\n }\n return { client: oldClient, token }\n })\n }\n\n // Otherwise register a new client if necessary (ie. no client is stored)\n // and call the onRegistered callback to wait for the user to grant the\n // access. Finally fetches to access token on success.\n let statePromise\n if (!storedState) {\n statePromise = registerNewClient()\n } else {\n statePromise = Promise.resolve(storedState)\n }\n\n let client, state, token\n return statePromise\n .then((data) => {\n client = data.client\n state = data.state\n return Promise.resolve(onRegistered(client, data.url))\n })\n .then((pageURL) => getAccessToken(cozy, client, state, pageURL))\n .then((t) => { token = t })\n .then(() => storage.delete(StateKey))\n .then(() => ({client, token}))\n })\n .then(\n (creds) => storage.save(CredsKey, creds),\n (err) => {\n if (FetchError.isUnauthorized(err)) {\n return clearAndRetry(err)\n } else {\n throw err\n }\n })\n}\n\n// retrieveToken perform a request on the access_token entrypoint in order to\n// fetch a token.\nfunction retrieveToken (cozy, client, token, query) {\n if (!(client instanceof Client)) {\n client = new Client(client)\n }\n if (!client.isRegistered()) {\n return Promise.reject(new Error('Client not registered'))\n }\n const body = encodeQuery(Object.assign({}, query, {\n 'client_id': client.clientID,\n 'client_secret': client.clientSecret\n }))\n return cozyFetchJSON(cozy, 'POST', '/auth/access_token', body, {\n disableAuth: (token === null),\n dontRetry: true,\n manualAuthCredentials: { client, token },\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' }\n })\n .then((data) => {\n data.refreshToken = data.refreshToken || query.refresh_token\n return new AccessToken(data)\n })\n}\n\n// getGrantCodeFromPageURL extract the state and access_code query parameters\n// from the given url\nfunction getGrantCodeFromPageURL (pageURL = '') {\n if (pageURL === '' && typeof window !== 'undefined') {\n pageURL = window.location.href\n }\n const queries = decodeQuery(pageURL)\n if (!queries.hasOwnProperty('state')) {\n return null\n }\n return {\n state: queries['state'],\n code: queries['access_code']\n }\n}\n\n// generateRandomState will try to generate a 128bits random value from a secure\n// pseudo random generator. It will fallback on Math.random if it cannot find\n// such generator.\nfunction generateRandomState () {\n let buffer\n if (typeof window !== 'undefined' &&\n typeof window.crypto !== 'undefined' &&\n typeof window.crypto.getRandomValues === 'function') {\n buffer = new Uint8Array(StateSize)\n window.crypto.getRandomValues(buffer)\n } else {\n try {\n buffer = require('crypto').randomBytes(StateSize)\n } catch (e) {}\n }\n if (!buffer) {\n buffer = new Array(StateSize)\n for (let i = 0; i < buffer.length; i++) {\n buffer[i] = Math.floor((Math.random() * 255))\n }\n }\n return btoa(String.fromCharCode.apply(null, buffer))\n .replace(/=+$/, '')\n .replace(/\\//g, '_')\n .replace(/\\+/g, '-')\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/auth_v3.js","/* global fetch */\nimport {refreshToken, AccessToken} from './auth_v3'\nimport {retry} from './utils'\nimport jsonapi from './jsonapi'\n\nexport function cozyFetch (cozy, path, options = {}) {\n return cozy.fullpath(path).then((fullpath) => {\n let resp\n if (options.disableAuth) {\n resp = fetch(fullpath, options)\n } else if (options.manualAuthCredentials) {\n resp = cozyFetchWithAuth(cozy, fullpath, options, options.manualAuthCredentials)\n } else {\n resp = cozy.authorize().then((credentials) =>\n cozyFetchWithAuth(cozy, fullpath, options, credentials))\n }\n return resp.then(handleResponse)\n })\n}\n\nfunction cozyFetchWithAuth (cozy, fullpath, options, credentials) {\n if (credentials) {\n options.headers = options.headers || {}\n options.headers['Authorization'] = credentials.token.toAuthHeader()\n }\n\n // the option credentials:include tells fetch to include the cookies in the\n // request even for cross-origin requests\n options.credentials = 'include'\n\n return Promise.all([\n cozy.isV2(),\n fetch(fullpath, options)\n ]).then(([isV2, res]) => {\n if ((res.status !== 400 && res.status !== 401) || isV2 || !credentials || options.dontRetry) {\n return res\n }\n // we try to refresh the token only for OAuth, ie, the client defined\n // and the token is an instance of AccessToken.\n const { client, token } = credentials\n if (!client || !(token instanceof AccessToken)) {\n return res\n }\n options.dontRetry = true\n return retry(() => refreshToken(cozy, client, token), 3)()\n .then((newToken) => cozy.saveCredentials(client, newToken))\n .then((credentials) => cozyFetchWithAuth(cozy, fullpath, options, credentials))\n })\n}\n\nexport function cozyFetchJSON (cozy, method, path, body, options = {}) {\n const processJSONAPI = typeof options.processJSONAPI === 'undefined' || options.processJSONAPI\n return fetchJSON(cozy, method, path, body, options)\n .then(response => handleJSONResponse(response, processJSONAPI))\n}\n\nexport function cozyFetchRawJSON (cozy, method, path, body, options = {}) {\n return fetchJSON(cozy, method, path, body, options)\n .then(response => handleJSONResponse(response, false))\n}\n\nfunction fetchJSON (cozy, method, path, body, options = {}) {\n options.method = method\n\n const headers = options.headers = options.headers || {}\n\n headers['Accept'] = 'application/json'\n\n if (method !== 'GET' && method !== 'HEAD' && body !== undefined) {\n if (headers['Content-Type']) {\n options.body = body\n } else {\n headers['Content-Type'] = 'application/json'\n options.body = JSON.stringify(body)\n }\n }\n\n return cozyFetch(cozy, path, options)\n}\n\nfunction handleResponse (res) {\n if (res.ok) {\n return res\n }\n let data\n const contentType = res.headers.get('content-type')\n if (contentType && contentType.indexOf('json') >= 0) {\n data = res.json()\n } else {\n data = res.text()\n }\n return data.then(err => {\n throw new FetchError(res, err)\n })\n}\n\nfunction handleJSONResponse (res, processJSONAPI = true) {\n const contentType = res.headers.get('content-type')\n if (!contentType || contentType.indexOf('json') < 0) {\n return res.text((data) => {\n throw new FetchError(res, new Error('Response is not JSON: ' + data))\n })\n }\n\n const json = res.json()\n if (contentType.indexOf('application/vnd.api+json') === 0 && processJSONAPI) {\n return json.then(jsonapi)\n } else {\n return json\n }\n}\n\nexport class FetchError extends Error {\n constructor (res, reason) {\n super()\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor)\n }\n // XXX We have to hardcode this because babel doesn't play nice when extending Error\n this.name = 'FetchError'\n this.response = res\n this.url = res.url\n this.status = res.status\n this.reason = reason\n\n Object.defineProperty(this, 'message', {\n value: reason.message ||\n (typeof reason === 'string' ? reason : JSON.stringify(reason))\n })\n }\n}\n\nFetchError.isUnauthorized = function (err) {\n // XXX We can't use err instanceof FetchError because of the caveats of babel\n return err.name === 'FetchError' && err.status === 401\n}\n\nFetchError.isNotFound = function (err) {\n // XXX We can't use err instanceof FetchError because of the caveats of babel\n return err.name === 'FetchError' && err.status === 404\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/fetch.js","function indexKey (doc) {\n return doc.type + '/' + doc.id\n}\n\nfunction findByRef (resources, ref) {\n return resources[indexKey(ref)]\n}\n\nfunction handleResource (rawResource, resources, links) {\n let resource = {\n _id: rawResource.id,\n _type: rawResource.type,\n _rev: (rawResource.meta && rawResource.meta.rev),\n links: Object.assign({}, rawResource.links, links),\n attributes: rawResource.attributes,\n relations: (name) => {\n let rels = rawResource.relationships[name]\n if (rels === undefined || rels.data === undefined) return undefined\n if (rels.data === null) return null\n if (!Array.isArray(rels.data)) return findByRef(resources, rels.data)\n return rels.data.map(ref => findByRef(resources, ref))\n }\n }\n if (rawResource.relationships) {\n resource.relationships = rawResource.relationships\n }\n\n resources[indexKey(rawResource)] = resource\n\n return resource\n}\n\nfunction handleTopLevel (doc, resources = {}) {\n // build an index of included resource by Type & ID\n const included = doc.included\n\n if (Array.isArray(included)) {\n included.forEach((r) => handleResource(r, resources, doc.links))\n }\n\n if (Array.isArray(doc.data)) {\n return doc.data.map((r) => handleResource(r, resources, doc.links))\n } else {\n return handleResource(doc.data, resources, doc.links)\n }\n}\n\nexport default handleTopLevel\n\n\n\n// WEBPACK FOOTER //\n// ./src/jsonapi.js","import {createPath} from './utils'\nimport {normalizeDoctype} from './doctypes'\nimport {cozyFetchJSON} from './fetch'\n\nconst NOREV = 'stack-v2-no-rev'\n\nexport function create (cozy, doctype, attributes) {\n return cozy.isV2().then((isV2) => {\n doctype = normalizeDoctype(cozy, isV2, doctype)\n if (isV2) {\n attributes.docType = doctype\n }\n const path = createPath(cozy, isV2, doctype, attributes._id)\n const httpVerb = attributes._id ? 'PUT' : 'POST'\n delete attributes._id\n return cozyFetchJSON(cozy, httpVerb, path, attributes).then((resp) => {\n if (isV2) {\n return find(cozy, doctype, resp._id)\n } else {\n return resp.data\n }\n })\n })\n}\n\nexport function find (cozy, doctype, id) {\n return cozy.isV2().then((isV2) => {\n doctype = normalizeDoctype(cozy, isV2, doctype)\n\n if (!id) {\n return Promise.reject(new Error('Missing id parameter'))\n }\n\n const path = createPath(cozy, isV2, doctype, id)\n return cozyFetchJSON(cozy, 'GET', path).then((resp) => {\n if (isV2) {\n return Object.assign(resp, {_rev: NOREV})\n } else {\n return resp\n }\n })\n })\n}\n\nexport function findMany (cozy, doctype, ids) {\n if (!(ids instanceof Array)) {\n return Promise.reject(new Error('Parameter ids must be a non-empty array'))\n }\n if (ids.length === 0) {\n // So users don't need to be defensive regarding the array content.\n // This should not hide issues in user code since the result will be an\n // empty object anyway.\n return Promise.resolve({})\n }\n\n return cozy.isV2().then((isV2) => {\n if (isV2) {\n return Promise.reject(new Error('findMany is not available on v2'))\n }\n\n const path = createPath(cozy, isV2, doctype, '_all_docs', {include_docs: true})\n\n return cozyFetchJSON(cozy, 'POST', path, {keys: ids})\n .then((resp) => {\n const docs = {}\n\n for (const row of resp.rows) {\n const {key, doc, error} = row\n docs[key] = error ? {error} : {doc}\n }\n\n return docs\n })\n .catch((error) => {\n if (error.status !== 404) return Promise.reject(error)\n\n // When no doc was ever created and the database does not exist yet,\n // the response will be a 404 error.\n const docs = {}\n\n for (const id of ids) {\n docs[id] = {error}\n }\n\n return docs\n })\n })\n}\n\nexport function findAll (cozy, doctype) {\n return cozy.isV2().then((isV2) => {\n if (isV2) {\n return Promise.reject(new Error('findAll is not available on v2'))\n }\n\n const path = createPath(cozy, isV2, doctype, '_all_docs', {include_docs: true})\n\n return cozyFetchJSON(cozy, 'POST', path, {})\n .then((resp) => {\n const docs = []\n\n for (const row of resp.rows) {\n const { doc } = row\n // if not couchDB indexes\n if (!doc._id.match(/_design\\//)) docs.push(doc)\n }\n return docs\n })\n .catch(error => {\n // the _all_docs endpoint returns a 404 error if no document with the given\n // doctype exists.\n if (error.status === 404) return []\n throw error\n })\n })\n}\n\nexport function changesFeed (cozy, doctype, options) {\n return cozy.isV2().then((isV2) => {\n doctype = normalizeDoctype(cozy, isV2, doctype)\n const path = createPath(cozy, isV2, doctype, '_changes', options)\n return cozyFetchJSON(cozy, 'GET', path)\n })\n}\n\nexport function update (cozy, doctype, doc, changes) {\n return cozy.isV2().then((isV2) => {\n doctype = normalizeDoctype(cozy, isV2, doctype)\n const {_id, _rev} = doc\n\n if (!_id) {\n return Promise.reject(new Error('Missing _id field in passed document'))\n }\n\n if (!isV2 && !_rev) {\n return Promise.reject(new Error('Missing _rev field in passed document'))\n }\n\n if (isV2) {\n changes = Object.assign({ _id }, changes)\n } else {\n changes = Object.assign({ _id, _rev }, changes)\n }\n\n const path = createPath(cozy, isV2, doctype, _id)\n return cozyFetchJSON(cozy, 'PUT', path, changes).then((resp) => {\n if (isV2) {\n return find(cozy, doctype, _id)\n } else {\n return resp.data\n }\n })\n })\n}\n\nexport function updateAttributes (cozy, doctype, _id, changes, tries = 3) {\n return cozy.isV2().then((isV2) => {\n doctype = normalizeDoctype(cozy, isV2, doctype)\n return find(cozy, doctype, _id)\n .then((doc) => {\n return update(cozy, doctype, doc, Object.assign({ _id }, doc, changes))\n })\n .catch((err) => {\n if (tries > 0) {\n return updateAttributes(cozy, doctype, _id, changes, tries - 1)\n } else {\n throw err\n }\n })\n })\n}\n\nexport function _delete (cozy, doctype, doc) {\n return cozy.isV2().then((isV2) => {\n doctype = normalizeDoctype(cozy, isV2, doctype)\n const {_id, _rev} = doc\n\n if (!_id) {\n return Promise.reject(new Error('Missing _id field in passed document'))\n }\n\n if (!isV2 && !_rev) {\n return Promise.reject(new Error('Missing _rev field in passed document'))\n }\n\n const query = isV2 ? null : { rev: _rev }\n const path = createPath(cozy, isV2, doctype, _id, query)\n return cozyFetchJSON(cozy, 'DELETE', path).then((resp) => {\n if (isV2) {\n return {id: _id, rev: NOREV}\n } else {\n return resp\n }\n })\n })\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/data.js","import {warn} from './utils'\n\nexport const DOCTYPE_FILES = 'io.cozy.files'\n\nconst KNOWN_DOCTYPES = {\n 'files': DOCTYPE_FILES,\n 'folder': DOCTYPE_FILES,\n 'contact': 'io.cozy.contacts',\n 'event': 'io.cozy.events',\n 'track': 'io.cozy.labs.music.track',\n 'playlist': 'io.cozy.labs.music.playlist'\n}\n\nconst REVERSE_KNOWN = {}\nObject.keys(KNOWN_DOCTYPES).forEach(k => {\n REVERSE_KNOWN[KNOWN_DOCTYPES[k]] = k\n})\n\nexport function normalizeDoctype (cozy, isV2, doctype) {\n let isQualified = doctype.indexOf('.') !== -1\n if (isV2 && isQualified) {\n let known = REVERSE_KNOWN[doctype]\n if (known) return known\n return doctype.replace(/\\./g, '-')\n }\n if (!isV2 && !isQualified) {\n let known = KNOWN_DOCTYPES[doctype]\n if (known) {\n warn('you are using a non-qualified doctype ' + doctype + ' assumed to be ' + known)\n return known\n }\n throw new Error('Doctype ' + doctype + ' should be qualified.')\n }\n return doctype\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/doctypes.js","import {warn, createPath, sleep} from './utils'\nimport {normalizeDoctype} from './doctypes'\nimport {cozyFetchJSON, cozyFetchRawJSON} from './fetch'\n\nexport function defineIndex (cozy, doctype, fields) {\n return cozy.isV2().then((isV2) => {\n doctype = normalizeDoctype(cozy, isV2, doctype)\n if (!Array.isArray(fields) || fields.length === 0) {\n throw new Error('defineIndex fields should be a non-empty array')\n }\n if (isV2) {\n return defineIndexV2(cozy, doctype, fields)\n } else {\n return defineIndexV3(cozy, doctype, fields)\n }\n })\n}\n\nexport function query (cozy, indexRef, options) {\n return cozy.isV2().then((isV2) => {\n if (!indexRef) {\n throw new Error('query should be passed the indexRef')\n }\n if (isV2) {\n return queryV2(cozy, indexRef, options)\n } else {\n return queryV3(cozy, indexRef, options)\n }\n })\n}\n\nexport function queryFiles (cozy, indexRef, options) {\n const opts = getV3Options(indexRef, options)\n return cozyFetchRawJSON(cozy, 'POST', '/files/_find', opts)\n .then((response) => options.wholeResponse ? response : response.docs)\n}\n\n// Internals\n\nconst VALUEOPERATORS = ['$eq', '$gt', '$gte', '$lt', '$lte']\nconst LOGICOPERATORS = ['$or', '$and', '$not']\n\n/* eslint-disable */\nconst MAP_TEMPLATE = (function (doc) {\n if (doc.docType.toLowerCase() === 'DOCTYPEPLACEHOLDER'){\n emit(FIELDSPLACEHOLDER, doc)\n }\n}).toString().replace(/ /g, '').replace(/\\n/g, '')\nconst COUCHDB_INFINITY = {\"\\uFFFF\": \"\\uFFFF\"}\nconst COUCHDB_LOWEST = null\n/* eslint-enable */\n\n// defineIndexV2 is equivalent to defineIndex but only works for V2.\n// It transforms the index fields into a map reduce view.\nfunction defineIndexV2 (cozy, doctype, fields) {\n let indexName = 'by' + fields.map(capitalize).join('')\n let indexDefinition = { map: makeMapFunction(doctype, fields), reduce: '_count' }\n let path = `/request/${doctype}/${indexName}/`\n return cozyFetchJSON(cozy, 'PUT', path, indexDefinition)\n .then(() => ({ doctype: doctype, type: 'mapreduce', name: indexName, fields: fields }))\n}\n\nfunction defineIndexV3 (cozy, doctype, fields) {\n let path = createPath(cozy, false, doctype, '_index')\n let indexDefinition = {'index': {fields}}\n return cozyFetchJSON(cozy, 'POST', path, indexDefinition)\n .then((response) => {\n const indexResult = { doctype: doctype, type: 'mango', name: response.id, fields }\n\n if (response.result === 'exists') return indexResult\n\n // indexes might not be usable right after being created; so we delay the resolving until they are\n const selector = {}\n selector[fields[0]] = {'$gt': null}\n\n const opts = getV3Options(indexResult, {'selector': selector})\n let path = createPath(cozy, false, indexResult.doctype, '_find')\n return cozyFetchJSON(cozy, 'POST', path, opts)\n .then(() => indexResult)\n .catch(() => { // one retry\n return sleep(1000)\n .then(() => cozyFetchJSON(cozy, 'POST', path, opts))\n .then(() => indexResult)\n .catch(() => {\n return sleep(500).then(() => indexResult)\n })\n })\n })\n}\n\n// queryV2 is equivalent to query but only works for V2.\n// It transforms the query into a _views call using makeMapReduceQuery\nfunction queryV2 (cozy, indexRef, options) {\n if (indexRef.type !== 'mapreduce') {\n throw new Error('query indexRef should be the return value of defineIndexV2')\n }\n if (options.fields) {\n warn('query fields will be ignored on v2')\n }\n\n let path = `/request/${indexRef.doctype}/${indexRef.name}/`\n let opts = makeMapReduceQuery(indexRef, options)\n return cozyFetchJSON(cozy, 'POST', path, opts)\n .then((response) => response.map(r => r.value))\n}\n\n// queryV3 is equivalent to query but only works for V3\nfunction queryV3 (cozy, indexRef, options) {\n const opts = getV3Options(indexRef, options)\n\n let path = createPath(cozy, false, indexRef.doctype, '_find')\n return cozyFetchJSON(cozy, 'POST', path, opts)\n .then((response) => options.wholeResponse ? response : response.docs)\n}\n\nfunction getV3Options (indexRef, options) {\n if (indexRef.type !== 'mango') {\n throw new Error('indexRef should be the return value of defineIndexV3')\n }\n\n let opts = {\n use_index: indexRef.name,\n fields: options.fields,\n selector: options.selector,\n limit: options.limit,\n skip: options.skip,\n since: options.since,\n sort: options.sort\n }\n\n if (options.descending) {\n opts.sort = indexRef.fields.map(f => ({ [f]: 'desc' }))\n }\n\n return opts\n}\n\n// misc\nfunction capitalize (name) {\n return name.charAt(0).toUpperCase() + name.slice(1)\n}\n\nfunction makeMapFunction (doctype, fields) {\n fields = '[' + fields.map(name => 'doc.' + name).join(',') + ']'\n\n return MAP_TEMPLATE.replace('DOCTYPEPLACEHOLDER', doctype.toLowerCase())\n .replace('FIELDSPLACEHOLDER', fields)\n}\n\n// parseSelector takes a mango selector and returns it as an array of filter\n// a filter is [path, operator, value] array\n// a path is an array of field names\n// This function is only exported so it can be unit tested.\n// Example :\n// parseSelector({\"test\":{\"deep\": {\"$gt\": 3}}})\n// [[['test', 'deep'], '$gt', 3 ]]\nexport function parseSelector (selector, path = [], operator = '$eq') {\n if ((typeof selector) !== 'object') {\n return [[path, operator, selector]]\n }\n\n let keys = Object.keys(selector)\n if (keys.length === 0) {\n throw new Error('empty selector')\n } else {\n return keys.reduce(function (acc, k) {\n if (LOGICOPERATORS.indexOf(k) !== -1) {\n throw new Error('cozy-client-js does not support mango logic ops')\n } else if (VALUEOPERATORS.indexOf(k) !== -1) {\n return acc.concat(parseSelector(selector[k], path, k))\n } else {\n return acc.concat(parseSelector(selector[k], path.concat(k), '$eq'))\n }\n }, [])\n }\n}\n\n// normalizeSelector takes a mango selector and returns it as an object\n// normalized.\n// This function is only exported so it can be unit tested.\n// Example :\n// parseSelector({\"test\":{\"deep\": {\"$gt\": 3}}})\n// {\"test.deep\": {\"$gt\": 3}}\nexport function normalizeSelector (selector) {\n var filters = parseSelector(selector)\n return filters.reduce(function (acc, filter) {\n let [path, op, value] = filter\n let field = path.join('.')\n acc[field] = acc[field] || {}\n acc[field][op] = value\n return acc\n }, {})\n}\n\n// applySelector takes the normalized selector for the current field\n// and append the proper values to opts.startkey, opts.endkey\nfunction applySelector (selector, opts) {\n let value = selector['$eq']\n let lower = COUCHDB_LOWEST\n let upper = COUCHDB_INFINITY\n let inclusiveEnd\n\n if (value) {\n opts.startkey.push(value)\n opts.endkey.push(value)\n return false\n }\n\n value = selector['$gt']\n if (value) {\n throw new Error('operator $gt (strict greater than) not supported')\n }\n\n value = selector['$gte']\n if (value) {\n lower = value\n }\n\n value = selector['$lte']\n if (value) {\n upper = value\n inclusiveEnd = true\n }\n\n value = selector['$lt']\n if (value) {\n upper = value\n inclusiveEnd = false\n }\n\n opts.startkey.push(lower)\n opts.endkey.push(upper)\n if (inclusiveEnd !== undefined) opts.inclusive_end = inclusiveEnd\n return true\n}\n\n// makeMapReduceQuery takes a mango query and generate _views call parameters\n// to obtain same results depending on fields in the passed indexRef.\nexport function makeMapReduceQuery (indexRef, query) {\n let mrquery = {\n startkey: [],\n endkey: [],\n reduce: false\n }\n let firstFreeValueField = null\n let normalizedSelector = normalizeSelector(query.selector)\n\n indexRef.fields.forEach(function (field) {\n let selector = normalizedSelector[field]\n\n if (selector && firstFreeValueField != null) {\n throw new Error('Selector on field ' + field + ', but not on ' + firstFreeValueField + ' which is higher in index fields.')\n } else if (selector) {\n selector.used = true\n let isFreeValue = applySelector(selector, mrquery)\n if (isFreeValue) firstFreeValueField = field\n } else if (firstFreeValueField == null) {\n firstFreeValueField = field\n mrquery.endkey.push(COUCHDB_INFINITY)\n }\n })\n\n Object.keys(normalizedSelector).forEach(function (field) {\n if (!normalizedSelector[field].used) {\n throw new Error('Cant apply selector on ' + field + ', it is not in index')\n }\n })\n\n if (query.descending) {\n mrquery = {\n descending: true,\n reduce: false,\n startkey: mrquery.endkey,\n endkey: mrquery.startkey,\n inclusive_end: mrquery.inclusive_end\n }\n }\n\n return mrquery\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/mango.js","/* global Blob, File */\nimport { cozyFetch, cozyFetchJSON } from './fetch'\nimport jsonapi from './jsonapi'\nimport { DOCTYPE_FILES } from './doctypes'\n\n// global variables\nexport const ROOT_DIR_ID = 'io.cozy.files.root-dir'\nexport const TRASH_DIR_ID = 'io.cozy.files.trash-dir'\n\nconst contentTypeOctetStream = 'application/octet-stream'\n\nfunction doUpload (cozy, data, method, path, options) {\n if (!data) {\n throw new Error('missing data argument')\n }\n\n // transform any ArrayBufferView to ArrayBuffer\n if (data.buffer && data.buffer instanceof ArrayBuffer) {\n data = data.buffer\n }\n\n const isBuffer = (typeof ArrayBuffer !== 'undefined' && data instanceof ArrayBuffer)\n const isFile = (typeof File !== 'undefined' && data instanceof File)\n const isBlob = (typeof Blob !== 'undefined' && data instanceof Blob)\n const isStream = (data.readable === true && typeof data.pipe === 'function')\n const isString = (typeof data === 'string')\n\n if (!isBuffer && !isFile && !isBlob && !isStream && !isString) {\n throw new Error('invalid data type')\n }\n\n let {contentType, checksum, lastModifiedDate, ifMatch} = options || {}\n if (!contentType) {\n if (isBuffer) {\n contentType = contentTypeOctetStream\n } else if (isFile) {\n contentType = data.type || contentTypeOctetStream\n if (!lastModifiedDate) {\n lastModifiedDate = data.lastModifiedDate\n }\n } else if (isBlob) {\n contentType = data.type || contentTypeOctetStream\n } else if (isStream) {\n contentType = contentTypeOctetStream\n } else if (typeof data === 'string') {\n contentType = 'text/plain'\n }\n }\n\n if (lastModifiedDate && typeof lastModifiedDate === 'string') {\n lastModifiedDate = new Date(lastModifiedDate)\n }\n\n return cozyFetch(cozy, path, {\n method: method,\n headers: {\n 'Content-Type': contentType,\n 'Content-MD5': checksum || '',\n 'Date': lastModifiedDate ? lastModifiedDate.toGMTString() : '',\n 'If-Match': ifMatch || ''\n },\n body: data\n })\n .then((res) => {\n const json = res.json()\n if (!res.ok) {\n return json.then(err => { throw err })\n } else {\n return json.then(jsonapi)\n }\n })\n}\n\nexport function create (cozy, data, options) {\n let {name, dirID, executable} = options || {}\n\n // handle case where data is a file and contains the name\n if (!name && typeof data.name === 'string') {\n name = data.name\n }\n\n if (typeof name !== 'string' || name === '') {\n throw new Error('missing name argument')\n }\n\n if (executable === undefined) {\n executable = false\n }\n\n const path = `/files/${encodeURIComponent(dirID || '')}`\n const query = `?Name=${encodeURIComponent(name)}&Type=file&Executable=${executable}`\n return doUpload(cozy, data, 'POST', `${path}${query}`, options)\n}\n\nexport function createDirectory (cozy, options) {\n let {name, dirID, lastModifiedDate} = options || {}\n\n if (typeof name !== 'string' || name === '') {\n throw new Error('missing name argument')\n }\n\n if (lastModifiedDate && typeof lastModifiedDate === 'string') {\n lastModifiedDate = new Date(lastModifiedDate)\n }\n\n const path = `/files/${encodeURIComponent(dirID || '')}`\n const query = `?Name=${encodeURIComponent(name)}&Type=directory`\n return cozyFetchJSON(cozy, 'POST', `${path}${query}`, undefined, {\n headers: {\n 'Date': lastModifiedDate ? lastModifiedDate.toGMTString() : ''\n }\n })\n}\n\nfunction getDirectoryOrCreate (cozy, name, parentDirectory) {\n if (parentDirectory && !parentDirectory.attributes) throw new Error('Malformed parent directory')\n\n const path = `${parentDirectory._id === ROOT_DIR_ID ? '' : parentDirectory.attributes.path}/${name}`\n\n return cozy.files.statByPath(path || '/')\n .catch(error => {\n const parsedError = JSON.parse(error.message)\n const errors = parsedError.errors\n if (errors && errors.length && errors[0].status === '404') {\n return cozy.files.createDirectory({\n name: name,\n dirID: parentDirectory && parentDirectory._id\n })\n }\n\n throw errors\n })\n}\n\nexport function createDirectoryByPath (cozy, path) {\n const parts = path.split('/').filter(part => part !== '')\n\n const rootDirectoryPromise = cozy.files.statById(ROOT_DIR_ID)\n\n return parts.length\n ? parts.reduce((parentDirectoryPromise, part) => {\n return parentDirectoryPromise\n .then(parentDirectory => getDirectoryOrCreate(cozy, part, parentDirectory))\n }, rootDirectoryPromise)\n : rootDirectoryPromise\n}\n\nexport function updateById (cozy, id, data, options) {\n return doUpload(cozy, data, 'PUT', `/files/${encodeURIComponent(id)}`, options)\n}\n\nfunction doUpdateAttributes (cozy, attrs, path, options) {\n if (!attrs || typeof attrs !== 'object') {\n throw new Error('missing attrs argument')\n }\n\n const {ifMatch} = options || {}\n const body = { data: { attributes: attrs } }\n return cozyFetchJSON(cozy, 'PATCH', path, body, {\n headers: {\n 'If-Match': ifMatch || ''\n }\n })\n}\n\nexport function updateAttributesById (cozy, id, attrs, options) {\n return doUpdateAttributes(cozy, attrs,\n `/files/${encodeURIComponent(id)}`, options)\n}\n\nexport function updateAttributesByPath (cozy, path, attrs, options) {\n return doUpdateAttributes(cozy, attrs,\n `/files/metadata?Path=${encodeURIComponent(path)}`, options)\n}\n\nexport function trashById (cozy, id, options) {\n if (typeof id !== 'string' || id === '') {\n throw new Error('missing id argument')\n }\n const {ifMatch} = options || {}\n return cozyFetchJSON(cozy, 'DELETE', `/files/${encodeURIComponent(id)}`, undefined, {\n headers: {\n 'If-Match': ifMatch || ''\n }\n })\n}\n\nexport function statById (cozy, id, offline = true, options = {}) {\n if (offline && cozy.offline.hasDatabase(DOCTYPE_FILES)) {\n let db = cozy.offline.getDatabase(DOCTYPE_FILES)\n return Promise.all([\n db.get(id),\n db.find(Object.assign({ selector: { 'dir_id': id } }, options))\n ]).then(([doc, children]) => {\n if (id === ROOT_DIR_ID) {\n children.docs = children.docs.filter(doc => doc._id !== TRASH_DIR_ID)\n }\n children = sortFiles(children.docs.map(doc => addIsDir(toJsonApi(cozy, doc))))\n return addIsDir(toJsonApi(cozy, doc, children))\n })\n }\n const query = Object.keys(options).length === 0 ? '' : `?${encodePageOptions(options)}`\n return cozyFetchJSON(cozy, 'GET', `/files/${encodeURIComponent(id)}${query}`)\n .then(addIsDir)\n}\n\nexport function statByPath (cozy, path) {\n return cozyFetchJSON(cozy, 'GET', `/files/metadata?Path=${encodeURIComponent(path)}`)\n .then(addIsDir)\n}\n\nexport function downloadById (cozy, id) {\n return cozyFetch(cozy, `/files/download/${encodeURIComponent(id)}`)\n}\n\nexport function downloadByPath (cozy, path) {\n return cozyFetch(cozy, `/files/download?Path=${encodeURIComponent(path)}`)\n}\n\nfunction extractResponseLinkRelated (res) {\n let href = res.links && res.links.related\n if (!href) throw new Error('No related link in server response')\n return href\n}\n\nexport function getDownloadLinkByPath (cozy, path) {\n return cozyFetchJSON(cozy, 'POST', `/files/downloads?Path=${encodeURIComponent(path)}`)\n .then(extractResponseLinkRelated)\n}\n\nexport function getDownloadLinkById (cozy, id) {\n return cozyFetchJSON(cozy, 'POST', `/files/downloads?Id=${encodeURIComponent(id)}`)\n .then(extractResponseLinkRelated)\n}\n\nexport function getFilePath (cozy, file = {}, folder) {\n if (!folder || !folder.attributes) {\n throw Error('Folder should be valid with an attributes.path property')\n }\n\n const folderPath = folder.attributes.path.endsWith('/')\n ? folder.attributes.path\n : `${folder.attributes.path}/`\n\n return `${folderPath}${file.name}`\n}\n\nexport function getCollectionShareLink (cozy, id, collectionType) {\n if (!id) {\n return Promise.reject(Error('An id should be provided to create a share link'))\n }\n return cozyFetchJSON(cozy, 'POST', `/permissions?codes=email`, {\n data: {\n type: 'io.cozy.permissions',\n attributes: {\n permissions: {\n files: {\n type: 'io.cozy.files',\n verbs: ['GET'],\n values: [id],\n selector: 'referenced_by'\n },\n collection: {\n type: collectionType,\n verbs: ['GET'],\n values: [id]\n }\n }\n }\n }\n }).then(data => ({sharecode: `sharecode=${data.attributes.codes.email}`, id: `id=${id}`}))\n}\n\nexport function getArchiveLinkByPaths (cozy, paths, name = 'files') {\n const archive = {\n type: 'io.cozy.archives',\n attributes: {\n name: name,\n files: paths\n }\n }\n return cozyFetchJSON(cozy, 'POST', `/files/archive`, {data: archive})\n .then(extractResponseLinkRelated)\n}\n\nexport function getArchiveLinkByIds (cozy, ids, name = 'files') {\n const archive = {\n type: 'io.cozy.archives',\n attributes: {\n name: name,\n ids: ids\n }\n }\n return cozyFetchJSON(cozy, 'POST', `/files/archive`, {data: archive})\n .then(extractResponseLinkRelated)\n}\n\nexport function listTrash (cozy) {\n return cozyFetchJSON(cozy, 'GET', `/files/trash`)\n}\n\nexport function clearTrash (cozy) {\n return cozyFetchJSON(cozy, 'DELETE', `/files/trash`)\n}\n\nexport function restoreById (cozy, id) {\n return cozyFetchJSON(cozy, 'POST', `/files/trash/${encodeURIComponent(id)}`)\n}\n\nexport function destroyById (cozy, id, options) {\n const {ifMatch} = options || {}\n return cozyFetchJSON(cozy, 'DELETE', `/files/trash/${encodeURIComponent(id)}`, undefined, {\n headers: {\n 'If-Match': ifMatch || ''\n }\n })\n}\n\nfunction addIsDir (obj) {\n obj.isDir = obj.attributes.type === 'directory'\n return obj\n}\n\nfunction encodePageOptions (options) {\n let opts = []\n for (const name in options) {\n opts.push(`page[${encodeURIComponent(name)}]=${encodeURIComponent(options[name])}`)\n }\n return opts.join('&')\n}\n\nfunction toJsonApi (cozy, doc, contents = []) {\n let clone = JSON.parse(JSON.stringify(doc))\n delete clone._id\n delete clone._rev\n return {\n _id: doc._id,\n _rev: doc._rev,\n _type: DOCTYPE_FILES,\n attributes: clone,\n relationships: {\n contents: {\n data: contents,\n meta: {\n count: contents.length\n }\n }\n },\n relations: (name) => {\n if (name === 'contents') {\n return contents\n }\n }\n }\n}\n\nfunction sortFiles (allFiles) {\n const folders = allFiles.filter(f => f.attributes.type === 'directory')\n const files = allFiles.filter(f => f.attributes.type !== 'directory')\n const sort = files => files.sort((a, b) => a.attributes.name.localeCompare(b.attributes.name))\n return sort(folders).concat(sort(files))\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/files.js","import {cozyFetchJSON} from './fetch'\n\nconst intentClass = 'coz-intent'\n\n// helper to serialize/deserialize an error for/from postMessage\nconst errorSerializer = (() => {\n function mapErrorProperties (from, to) {\n const result = Object.assign(to, from)\n const nativeProperties = ['name', 'message']\n return nativeProperties.reduce((result, property) => {\n if (from[property]) {\n to[property] = from[property]\n }\n return result\n }, result)\n }\n return {\n serialize: (error) => mapErrorProperties(error, {}),\n deserialize: (data) => mapErrorProperties(data, new Error(data.message))\n }\n})()\n\n// inject iframe for service in given element\nfunction injectService (url, element, intent, data, onReadyCallback) {\n const document = element.ownerDocument\n if (!document) throw new Error('Cannot retrieve document object from given element')\n\n const window = document.defaultView\n if (!window) throw new Error('Cannot retrieve window object from document')\n\n const iframe = document.createElement('iframe')\n // if callback provided for when iframe is loaded\n if (typeof onReadyCallback === 'function') iframe.onload = onReadyCallback\n // TODO: implement 'title' attribute\n iframe.setAttribute('src', url)\n iframe.classList.add(intentClass)\n element.appendChild(iframe)\n iframe.focus()\n\n // Keeps only http://domain:port/\n const serviceOrigin = url.split('/', 3).join('/')\n\n return new Promise((resolve, reject) => {\n let handshaken = false\n const messageHandler = (event) => {\n if (event.origin !== serviceOrigin) return\n\n if (event.data.type === 'load') {\n // Safari 9.1 (At least) send a MessageEvent when the iframe loads,\n // making the handshake fails.\n console.warn && console.warn('Cozy Client ignored MessageEvent having data.type `load`.')\n return\n }\n\n if (event.data.type === `intent-${intent._id}:ready`) {\n handshaken = true\n return event.source.postMessage(data, event.origin)\n }\n\n if (handshaken && event.data.type === `intent-${intent._id}:resize`) {\n ['width', 'height', 'maxWidth', 'maxHeight'].forEach(prop => {\n if (event.data.transition) element.style.transition = event.data.transition\n if (event.data.dimensions[prop]) element.style[prop] = `${event.data.dimensions[prop]}px`\n })\n\n return true\n }\n\n window.removeEventListener('message', messageHandler)\n const removeIntentFrame = () => {\n // check if the parent node has not been already removed from the DOM\n iframe.parentNode && iframe.parentNode.removeChild(iframe)\n }\n\n if (handshaken && event.data.type === `intent-${intent._id}:exposeFrameRemoval`) {\n return resolve({removeIntentFrame, doc: event.data.document})\n }\n\n removeIntentFrame()\n\n if (event.data.type === `intent-${intent._id}:error`) {\n return reject(errorSerializer.deserialize(event.data.error))\n }\n\n if (handshaken && event.data.type === `intent-${intent._id}:cancel`) {\n return resolve(null)\n }\n\n if (handshaken && event.data.type === `intent-${intent._id}:done`) {\n return resolve(event.data.document)\n }\n\n if (!handshaken) {\n return reject(new Error('Unexpected handshake message from intent service'))\n }\n\n // We may be in a state where the messageHandler is still attached to then\n // window, but will not be needed anymore. For example, the service failed\n // before adding the `unload` listener, so no `intent:cancel` message has\n // never been sent.\n // So we simply ignore other messages, and this listener will stay here,\n // waiting for a message which will never come, forever (almost).\n }\n\n window.addEventListener('message', messageHandler)\n })\n}\n\nexport function create (cozy, action, type, data = {}, permissions = []) {\n if (!action) throw new Error(`Misformed intent, \"action\" property must be provided`)\n if (!type) throw new Error(`Misformed intent, \"type\" property must be provided`)\n\n const createPromise = cozyFetchJSON(cozy, 'POST', '/intents', {\n data: {\n type: 'io.cozy.intents',\n attributes: {\n action: action,\n type: type,\n data: data,\n permissions: permissions\n }\n }\n })\n\n createPromise.start = (element, onReadyCallback) => {\n return createPromise.then(intent => {\n let service = intent.attributes.services && intent.attributes.services[0]\n\n if (!service) {\n return Promise.reject(new Error('Unable to find a service'))\n }\n\n return injectService(service.href, element, intent, data, onReadyCallback)\n })\n }\n\n return createPromise\n}\n\nfunction listenClientData (intent, window) {\n return new Promise((resolve, reject) => {\n const messageEventListener = (event) => {\n if (event.origin !== intent.attributes.client) return\n\n window.removeEventListener('message', messageEventListener)\n resolve(event.data)\n }\n\n window.addEventListener('message', messageEventListener)\n window.parent.postMessage({\n type: `intent-${intent._id}:ready`\n }, intent.attributes.client)\n })\n}\n\n// returns a service to communicate with intent client\nexport function createService (cozy, intentId, serviceWindow) {\n serviceWindow = serviceWindow || typeof window !== 'undefined' && window\n if (!serviceWindow) throw new Error('Intent service should be used in browser')\n\n intentId = intentId || serviceWindow.location.search.split('=')[1]\n if (!intentId) throw new Error('Cannot retrieve intent from URL')\n\n return cozyFetchJSON(cozy, 'GET', `/intents/${intentId}`)\n .then(intent => {\n let terminated = false\n\n const terminate = (message) => {\n if (terminated) throw new Error('Intent service has already been terminated')\n terminated = true\n serviceWindow.parent.postMessage(message, intent.attributes.client)\n }\n\n const resizeClient = (dimensions, transitionProperty) => {\n if (terminated) throw new Error('Intent service has been terminated')\n\n const message = {\n type: `intent-${intent._id}:resize`,\n // if a dom element is passed, calculate its size\n dimensions: dimensions.element\n ? Object.assign({}, dimensions, {\n maxHeight: dimensions.element.clientHeight,\n maxWidth: dimensions.element.clientWidth\n })\n : dimensions,\n transition: transitionProperty\n }\n\n serviceWindow.parent.postMessage(message, intent.attributes.client)\n }\n\n const cancel = () => {\n terminate({type: `intent-${intent._id}:cancel`})\n }\n\n // Prevent unfulfilled client promises when this window unloads for a\n // reason or another.\n serviceWindow.addEventListener('unload', () => {\n if (!terminated) cancel()\n })\n\n return listenClientData(intent, serviceWindow)\n .then(data => {\n return {\n getData: () => data,\n getIntent: () => intent,\n terminate: (doc) => {\n if (data && data.exposeIntentFrameRemoval) {\n return terminate({\n type: `intent-${intent._id}:exposeFrameRemoval`,\n document: doc\n })\n } else {\n return terminate({\n type: `intent-${intent._id}:done`,\n document: doc\n })\n }\n },\n throw: error => terminate({\n type: `intent-${intent._id}:error`,\n error: errorSerializer.serialize(error)\n }),\n resizeClient: resizeClient,\n cancel: cancel\n }\n })\n })\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/intents.js","import {cozyFetchJSON} from './fetch'\n\nexport function count (cozy, workerType) {\n return cozyFetchJSON(cozy, 'GET', `/jobs/queue/${workerType}`)\n .then(data => data.length)\n}\n\nexport function queued (cozy, workerType) {\n return cozyFetchJSON(cozy, 'GET', `/jobs/queue/${workerType}`)\n}\n\nexport function create (cozy, workerType, args, options) {\n return cozyFetchJSON(cozy, 'POST', `/jobs/queue/${workerType}`, {\n data: {\n type: 'io.cozy.jobs',\n attributes: {\n arguments: args || {},\n options: options || {}\n }\n }\n })\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/jobs.js","/* global pouchdbAdapterCordovaSqlite */\nimport {DOCTYPE_FILES} from './doctypes'\nimport {refreshToken} from './auth_v3'\nimport {isOffline} from './utils'\nimport PouchDB from 'pouchdb'\nimport pouchdbFind from 'pouchdb-find'\n\nexport const replicationOfflineError = 'Replication abort, your device is actually offline.'\n\nlet pluginLoaded = false\n\n/*\n For each doctype we have some parameters:\n cozy._offline[doctype] = {\n database: pouchdb database\n replication: the pouchdb replication\n replicationPromise: promise of replication\n interval: repeated replication interval\n }\n*/\n\nexport function init (cozy, { options = {}, doctypes = [] }) {\n for (let doctype of doctypes) {\n createDatabase(cozy, doctype, options)\n }\n}\n\n// helper\n\nfunction getInfo (cozy, doctype) {\n cozy._offline = cozy._offline || []\n cozy._offline[doctype] = cozy._offline[doctype] || {}\n return cozy._offline[doctype]\n}\n\nexport function getDoctypes (cozy) {\n cozy._offline = cozy._offline || []\n return Object.keys(cozy._offline)\n}\n\n//\n// DATABASE\n//\n\nexport function hasDatabase (cozy, doctype) {\n return getDatabase(cozy, doctype) !== undefined\n}\n\nexport function getDatabase (cozy, doctype) {\n return getInfo(cozy, doctype).database\n}\n\nexport function setDatabase (cozy, doctype, database) {\n cozy._offline[doctype].database = database\n return getDatabase(cozy, doctype)\n}\n\nexport function createDatabase (cozy, doctype, options = {}) {\n if (!pluginLoaded) {\n PouchDB.plugin(pouchdbFind)\n if (typeof pouchdbAdapterCordovaSqlite !== 'undefined') PouchDB.plugin(pouchdbAdapterCordovaSqlite)\n pluginLoaded = true\n }\n\n if (hasDatabase(cozy, doctype)) {\n return Promise.resolve(getDatabase(cozy, doctype))\n }\n\n setDatabase(cozy, doctype, new PouchDB(doctype, options))\n return createIndexes(cozy, doctype).then(() => getDatabase(cozy, doctype))\n}\n\nexport function destroyDatabase (cozy, doctype) {\n if (!hasDatabase(cozy, doctype)) {\n return Promise.resolve(false)\n }\n\n return stopRepeatedReplication(cozy, doctype)\n .then(() => stopReplication(cozy, doctype))\n .then(() => getDatabase(cozy, doctype).destroy())\n .then(response => {\n setDatabase(cozy, doctype, undefined)\n return response\n })\n}\n\nexport function destroyAllDatabase (cozy) {\n const doctypes = getDoctypes(cozy)\n const destroy = (doctype) => destroyDatabase(cozy, doctype)\n return Promise.all(doctypes.map(destroy))\n}\n\nfunction createIndexes (cozy, doctype) {\n if (doctype === DOCTYPE_FILES) {\n return getDatabase(cozy, doctype).createIndex({index: {fields: ['dir_id']}})\n }\n return Promise.resolve()\n}\n\n//\n// REPLICATION\n//\n\nexport function hasReplication (cozy, doctype) {\n return getReplication(cozy, doctype) !== undefined\n}\n\nfunction getReplication (cozy, doctype) {\n return getInfo(cozy, doctype).replication\n}\n\nfunction setReplication (cozy, doctype, replication) {\n cozy._offline[doctype].replication = replication\n return getReplication(cozy, doctype)\n}\n\nfunction getReplicationUrl (cozy, doctype) {\n return cozy.authorize()\n .then(credentials => {\n const basic = credentials.token.toBasicAuth()\n return (cozy._url + '/data/' + doctype).replace('//', `//${basic}`)\n })\n}\n\nfunction getReplicationPromise (cozy, doctype) {\n return getInfo(cozy, doctype).replicationPromise\n}\n\nfunction setReplicationPromise (cozy, doctype, promise) {\n cozy._offline[doctype].replicationPromise = promise\n return getReplicationPromise(cozy, doctype)\n}\n\nexport function replicateFromCozy (cozy, doctype, options = {}) {\n return setReplicationPromise(cozy, doctype, new Promise((resolve, reject) => {\n if (!hasDatabase(cozy, doctype)) {\n createDatabase(cozy, doctype)\n }\n if (options.live === true) {\n return reject(new Error('You can\\'t use `live` option with Cozy couchdb.'))\n }\n\n if (isOffline()) {\n reject(replicationOfflineError)\n options.onError && options.onError(replicationOfflineError)\n return\n }\n\n getReplicationUrl(cozy, doctype)\n .then(url => setReplication(cozy, doctype,\n getDatabase(cozy, doctype).replicate.from(url, options).on('complete', (info) => {\n setReplication(cozy, doctype, undefined)\n resolve(info)\n options.onComplete && options.onComplete(info)\n }).on('error', (err) => {\n if (err.error === 'code=400, message=Expired token') {\n cozy.authorize().then(({client, token}) => {\n refreshToken(cozy, client, token)\n .then((newToken) => cozy.saveCredentials(client, newToken))\n .then((credentials) => replicateFromCozy(cozy, doctype, options))\n })\n } else {\n console.warn(`ReplicateFromCozy '${doctype}' Error:`)\n console.warn(err)\n setReplication(cozy, doctype, undefined)\n reject(err)\n options.onError && options.onError(err)\n }\n })\n ))\n }))\n}\n\nexport function stopReplication (cozy, doctype) {\n if (!getDatabase(cozy, doctype) || !hasReplication(cozy, doctype)) {\n return Promise.resolve()\n }\n\n return new Promise(resolve => {\n try {\n getReplicationPromise(cozy, doctype).then(() => {\n resolve()\n })\n getReplication(cozy, doctype).cancel()\n // replication is set to undefined by complete replication\n } catch (e) {\n resolve()\n }\n })\n}\n\nexport function stopAllReplication (cozy) {\n const doctypes = getDoctypes(cozy)\n const stop = (doctype) => stopReplication(cozy, doctype)\n return Promise.all(doctypes.map(stop))\n}\n\n//\n// REPEATED REPLICATION\n//\n\nfunction getRepeatedReplication (cozy, doctype) {\n return getInfo(cozy, doctype).interval\n}\n\nfunction setRepeatedReplication (cozy, doctype, interval) {\n cozy._offline[doctype].interval = interval\n}\n\nexport function hasRepeatedReplication (cozy, doctype) {\n return getRepeatedReplication(cozy, doctype) !== undefined\n}\n\nexport function startRepeatedReplication (cozy, doctype, timer, options = {}) {\n // TODO: add timer limitation for not flooding Gozy\n if (hasRepeatedReplication(cozy, doctype)) {\n return getRepeatedReplication(cozy, doctype)\n }\n\n return setRepeatedReplication(cozy, doctype, setInterval(() => {\n if (isOffline()) {\n // network is offline, replication cannot be launched\n console.info(replicationOfflineError)\n return\n }\n if (!hasReplication(cozy, doctype)) {\n replicateFromCozy(cozy, doctype, options)\n // TODO: add replicationToCozy\n }\n }, timer * 1000))\n}\n\nexport function stopRepeatedReplication (cozy, doctype) {\n if (hasRepeatedReplication(cozy, doctype)) {\n clearInterval(getRepeatedReplication(cozy, doctype))\n setRepeatedReplication(cozy, doctype, undefined)\n }\n if (hasReplication(cozy, doctype)) {\n return stopReplication(cozy, doctype)\n }\n\n return Promise.resolve()\n}\n\nexport function stopAllRepeatedReplication (cozy) {\n const doctypes = getDoctypes(cozy)\n const stop = (doctype) => stopRepeatedReplication(cozy, doctype)\n return Promise.all(doctypes.map(stop))\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/offline.js","'use strict';\n\nfunction _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }\n\nvar lie = _interopDefault(require('lie'));\nvar getArguments = _interopDefault(require('argsarray'));\nvar debug = _interopDefault(require('debug'));\nvar events = require('events');\nvar inherits = _interopDefault(require('inherits'));\nvar nextTick = _interopDefault(require('immediate'));\nvar scopedEval = _interopDefault(require('scope-eval'));\nvar Md5 = _interopDefault(require('spark-md5'));\nvar vuvuzela = _interopDefault(require('vuvuzela'));\n\n/* istanbul ignore next */\nvar PouchPromise$1 = typeof Promise === 'function' ? Promise : lie;\n\nfunction isBinaryObject(object) {\n return (typeof ArrayBuffer !== 'undefined' && object instanceof ArrayBuffer) ||\n (typeof Blob !== 'undefined' && object instanceof Blob);\n}\n\nfunction cloneArrayBuffer(buff) {\n if (typeof buff.slice === 'function') {\n return buff.slice(0);\n }\n // IE10-11 slice() polyfill\n var target = new ArrayBuffer(buff.byteLength);\n var targetArray = new Uint8Array(target);\n var sourceArray = new Uint8Array(buff);\n targetArray.set(sourceArray);\n return target;\n}\n\nfunction cloneBinaryObject(object) {\n if (object instanceof ArrayBuffer) {\n return cloneArrayBuffer(object);\n }\n var size = object.size;\n var type = object.type;\n // Blob\n if (typeof object.slice === 'function') {\n return object.slice(0, size, type);\n }\n // PhantomJS slice() replacement\n return object.webkitSlice(0, size, type);\n}\n\n// most of this is borrowed from lodash.isPlainObject:\n// https://github.com/fis-components/lodash.isplainobject/\n// blob/29c358140a74f252aeb08c9eb28bef86f2217d4a/index.js\n\nvar funcToString = Function.prototype.toString;\nvar objectCtorString = funcToString.call(Object);\n\nfunction isPlainObject(value) {\n var proto = Object.getPrototypeOf(value);\n /* istanbul ignore if */\n if (proto === null) { // not sure when this happens, but I guess it can\n return true;\n }\n var Ctor = proto.constructor;\n return (typeof Ctor == 'function' &&\n Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString);\n}\n\nfunction clone(object) {\n var newObject;\n var i;\n var len;\n\n if (!object || typeof object !== 'object') {\n return object;\n }\n\n if (Array.isArray(object)) {\n newObject = [];\n for (i = 0, len = object.length; i < len; i++) {\n newObject[i] = clone(object[i]);\n }\n return newObject;\n }\n\n // special case: to avoid inconsistencies between IndexedDB\n // and other backends, we automatically stringify Dates\n if (object instanceof Date) {\n return object.toISOString();\n }\n\n if (isBinaryObject(object)) {\n return cloneBinaryObject(object);\n }\n\n if (!isPlainObject(object)) {\n return object; // don't clone objects like Workers\n }\n\n newObject = {};\n for (i in object) {\n /* istanbul ignore else */\n if (Object.prototype.hasOwnProperty.call(object, i)) {\n var value = clone(object[i]);\n if (typeof value !== 'undefined') {\n newObject[i] = value;\n }\n }\n }\n return newObject;\n}\n\nfunction once(fun) {\n var called = false;\n return getArguments(function (args) {\n /* istanbul ignore if */\n if (called) {\n // this is a smoke test and should never actually happen\n throw new Error('once called more than once');\n } else {\n called = true;\n fun.apply(this, args);\n }\n });\n}\n\nfunction toPromise(func) {\n //create the function we will be returning\n return getArguments(function (args) {\n // Clone arguments\n args = clone(args);\n var self = this;\n // if the last argument is a function, assume its a callback\n var usedCB = (typeof args[args.length - 1] === 'function') ? args.pop() : false;\n var promise = new PouchPromise$1(function (fulfill, reject) {\n var resp;\n try {\n var callback = once(function (err, mesg) {\n if (err) {\n reject(err);\n } else {\n fulfill(mesg);\n }\n });\n // create a callback for this invocation\n // apply the function in the orig context\n args.push(callback);\n resp = func.apply(self, args);\n if (resp && typeof resp.then === 'function') {\n fulfill(resp);\n }\n } catch (e) {\n reject(e);\n }\n });\n // if there is a callback, call it back\n if (usedCB) {\n promise.then(function (result) {\n usedCB(null, result);\n }, usedCB);\n }\n return promise;\n });\n}\n\nvar log = debug('pouchdb:api');\n\nfunction adapterFun(name, callback) {\n function logApiCall(self, name, args) {\n /* istanbul ignore if */\n if (log.enabled) {\n var logArgs = [self.name, name];\n for (var i = 0; i < args.length - 1; i++) {\n logArgs.push(args[i]);\n }\n log.apply(null, logArgs);\n\n // override the callback itself to log the response\n var origCallback = args[args.length - 1];\n args[args.length - 1] = function (err, res) {\n var responseArgs = [self.name, name];\n responseArgs = responseArgs.concat(\n err ? ['error', err] : ['success', res]\n );\n log.apply(null, responseArgs);\n origCallback(err, res);\n };\n }\n }\n\n return toPromise(getArguments(function (args) {\n if (this._closed) {\n return PouchPromise$1.reject(new Error('database is closed'));\n }\n if (this._destroyed) {\n return PouchPromise$1.reject(new Error('database is destroyed'));\n }\n var self = this;\n logApiCall(self, name, args);\n if (!this.taskqueue.isReady) {\n return new PouchPromise$1(function (fulfill, reject) {\n self.taskqueue.addTask(function (failed) {\n if (failed) {\n reject(failed);\n } else {\n fulfill(self[name].apply(self, args));\n }\n });\n });\n }\n return callback.apply(this, args);\n }));\n}\n\n// like underscore/lodash _.pick()\nfunction pick(obj, arr) {\n var res = {};\n for (var i = 0, len = arr.length; i < len; i++) {\n var prop = arr[i];\n if (prop in obj) {\n res[prop] = obj[prop];\n }\n }\n return res;\n}\n\nfunction mangle(key) {\n return '$' + key;\n}\nfunction unmangle(key) {\n return key.substring(1);\n}\nfunction Map$1() {\n this._store = {};\n}\nMap$1.prototype.get = function (key) {\n var mangled = mangle(key);\n return this._store[mangled];\n};\nMap$1.prototype.set = function (key, value) {\n var mangled = mangle(key);\n this._store[mangled] = value;\n return true;\n};\nMap$1.prototype.has = function (key) {\n var mangled = mangle(key);\n return mangled in this._store;\n};\nMap$1.prototype.delete = function (key) {\n var mangled = mangle(key);\n var res = mangled in this._store;\n delete this._store[mangled];\n return res;\n};\nMap$1.prototype.forEach = function (cb) {\n var keys = Object.keys(this._store);\n for (var i = 0, len = keys.length; i < len; i++) {\n var key = keys[i];\n var value = this._store[key];\n key = unmangle(key);\n cb(value, key);\n }\n};\nObject.defineProperty(Map$1.prototype, 'size', {\n get: function () {\n return Object.keys(this._store).length;\n }\n});\n\nfunction Set$1(array) {\n this._store = new Map$1();\n\n // init with an array\n if (array && Array.isArray(array)) {\n for (var i = 0, len = array.length; i < len; i++) {\n this.add(array[i]);\n }\n }\n}\nSet$1.prototype.add = function (key) {\n return this._store.set(key, true);\n};\nSet$1.prototype.has = function (key) {\n return this._store.has(key);\n};\nSet$1.prototype.forEach = function (cb) {\n this._store.forEach(function (value, key) {\n cb(key);\n });\n};\nObject.defineProperty(Set$1.prototype, 'size', {\n get: function () {\n return this._store.size;\n }\n});\n\n/* global Map,Set,Symbol */\n// Based on https://kangax.github.io/compat-table/es6/ we can sniff out\n// incomplete Map/Set implementations which would otherwise cause our tests to fail.\n// Notably they fail in IE11 and iOS 8.4, which this prevents.\nfunction supportsMapAndSet() {\n if (typeof Symbol === 'undefined' || typeof Map === 'undefined' || typeof Set === 'undefined') {\n return false;\n }\n var prop = Object.getOwnPropertyDescriptor(Map, Symbol.species);\n return prop && 'get' in prop && Map[Symbol.species] === Map;\n}\n\n// based on https://github.com/montagejs/collections\n/* global Map,Set */\n\nvar ExportedSet;\nvar ExportedMap;\n\n{\n if (supportsMapAndSet()) { // prefer built-in Map/Set\n ExportedSet = Set;\n ExportedMap = Map;\n } else { // fall back to our polyfill\n ExportedSet = Set$1;\n ExportedMap = Map$1;\n }\n}\n\n// Most browsers throttle concurrent requests at 6, so it's silly\n// to shim _bulk_get by trying to launch potentially hundreds of requests\n// and then letting the majority time out. We can handle this ourselves.\nvar MAX_NUM_CONCURRENT_REQUESTS = 6;\n\nfunction identityFunction(x) {\n return x;\n}\n\nfunction formatResultForOpenRevsGet(result) {\n return [{\n ok: result\n }];\n}\n\n// shim for P/CouchDB adapters that don't directly implement _bulk_get\nfunction bulkGet(db, opts, callback) {\n var requests = opts.docs;\n\n // consolidate into one request per doc if possible\n var requestsById = new ExportedMap();\n requests.forEach(function (request) {\n if (requestsById.has(request.id)) {\n requestsById.get(request.id).push(request);\n } else {\n requestsById.set(request.id, [request]);\n }\n });\n\n var numDocs = requestsById.size;\n var numDone = 0;\n var perDocResults = new Array(numDocs);\n\n function collapseResultsAndFinish() {\n var results = [];\n perDocResults.forEach(function (res) {\n res.docs.forEach(function (info) {\n results.push({\n id: res.id,\n docs: [info]\n });\n });\n });\n callback(null, {results: results});\n }\n\n function checkDone() {\n if (++numDone === numDocs) {\n collapseResultsAndFinish();\n }\n }\n\n function gotResult(docIndex, id, docs) {\n perDocResults[docIndex] = {id: id, docs: docs};\n checkDone();\n }\n\n var allRequests = [];\n requestsById.forEach(function (value, key) {\n allRequests.push(key);\n });\n\n var i = 0;\n\n function nextBatch() {\n\n if (i >= allRequests.length) {\n return;\n }\n\n var upTo = Math.min(i + MAX_NUM_CONCURRENT_REQUESTS, allRequests.length);\n var batch = allRequests.slice(i, upTo);\n processBatch(batch, i);\n i += batch.length;\n }\n\n function processBatch(batch, offset) {\n batch.forEach(function (docId, j) {\n var docIdx = offset + j;\n var docRequests = requestsById.get(docId);\n\n // just use the first request as the \"template\"\n // TODO: The _bulk_get API allows for more subtle use cases than this,\n // but for now it is unlikely that there will be a mix of different\n // \"atts_since\" or \"attachments\" in the same request, since it's just\n // replicate.js that is using this for the moment.\n // Also, atts_since is aspirational, since we don't support it yet.\n var docOpts = pick(docRequests[0], ['atts_since', 'attachments']);\n docOpts.open_revs = docRequests.map(function (request) {\n // rev is optional, open_revs disallowed\n return request.rev;\n });\n\n // remove falsey / undefined revisions\n docOpts.open_revs = docOpts.open_revs.filter(identityFunction);\n\n var formatResult = identityFunction;\n\n if (docOpts.open_revs.length === 0) {\n delete docOpts.open_revs;\n\n // when fetching only the \"winning\" leaf,\n // transform the result so it looks like an open_revs\n // request\n formatResult = formatResultForOpenRevsGet;\n }\n\n // globally-supplied options\n ['revs', 'attachments', 'binary', 'ajax', 'latest'].forEach(function (param) {\n if (param in opts) {\n docOpts[param] = opts[param];\n }\n });\n db.get(docId, docOpts, function (err, res) {\n var result;\n /* istanbul ignore if */\n if (err) {\n result = [{error: err}];\n } else {\n result = formatResult(res);\n }\n gotResult(docIdx, docId, result);\n nextBatch();\n });\n });\n }\n\n nextBatch();\n\n}\n\nfunction isChromeApp() {\n return (typeof chrome !== \"undefined\" &&\n typeof chrome.storage !== \"undefined\" &&\n typeof chrome.storage.local !== \"undefined\");\n}\n\nvar hasLocal;\n\nif (isChromeApp()) {\n hasLocal = false;\n} else {\n try {\n localStorage.setItem('_pouch_check_localstorage', 1);\n hasLocal = !!localStorage.getItem('_pouch_check_localstorage');\n } catch (e) {\n hasLocal = false;\n }\n}\n\nfunction hasLocalStorage() {\n return hasLocal;\n}\n\ninherits(Changes, events.EventEmitter);\n\n/* istanbul ignore next */\nfunction attachBrowserEvents(self) {\n if (isChromeApp()) {\n chrome.storage.onChanged.addListener(function (e) {\n // make sure it's event addressed to us\n if (e.db_name != null) {\n //object only has oldValue, newValue members\n self.emit(e.dbName.newValue);\n }\n });\n } else if (hasLocalStorage()) {\n if (typeof addEventListener !== 'undefined') {\n addEventListener(\"storage\", function (e) {\n self.emit(e.key);\n });\n } else { // old IE\n window.attachEvent(\"storage\", function (e) {\n self.emit(e.key);\n });\n }\n }\n}\n\nfunction Changes() {\n events.EventEmitter.call(this);\n this._listeners = {};\n\n attachBrowserEvents(this);\n}\nChanges.prototype.addListener = function (dbName, id, db, opts) {\n /* istanbul ignore if */\n if (this._listeners[id]) {\n return;\n }\n var self = this;\n var inprogress = false;\n function eventFunction() {\n /* istanbul ignore if */\n if (!self._listeners[id]) {\n return;\n }\n if (inprogress) {\n inprogress = 'waiting';\n return;\n }\n inprogress = true;\n var changesOpts = pick(opts, [\n 'style', 'include_docs', 'attachments', 'conflicts', 'filter',\n 'doc_ids', 'view', 'since', 'query_params', 'binary'\n ]);\n\n /* istanbul ignore next */\n function onError() {\n inprogress = false;\n }\n\n db.changes(changesOpts).on('change', function (c) {\n if (c.seq > opts.since && !opts.cancelled) {\n opts.since = c.seq;\n opts.onChange(c);\n }\n }).on('complete', function () {\n if (inprogress === 'waiting') {\n nextTick(eventFunction);\n }\n inprogress = false;\n }).on('error', onError);\n }\n this._listeners[id] = eventFunction;\n this.on(dbName, eventFunction);\n};\n\nChanges.prototype.removeListener = function (dbName, id) {\n /* istanbul ignore if */\n if (!(id in this._listeners)) {\n return;\n }\n events.EventEmitter.prototype.removeListener.call(this, dbName,\n this._listeners[id]);\n delete this._listeners[id];\n};\n\n\n/* istanbul ignore next */\nChanges.prototype.notifyLocalWindows = function (dbName) {\n //do a useless change on a storage thing\n //in order to get other windows's listeners to activate\n if (isChromeApp()) {\n chrome.storage.local.set({dbName: dbName});\n } else if (hasLocalStorage()) {\n localStorage[dbName] = (localStorage[dbName] === \"a\") ? \"b\" : \"a\";\n }\n};\n\nChanges.prototype.notify = function (dbName) {\n this.emit(dbName);\n this.notifyLocalWindows(dbName);\n};\n\nfunction guardedConsole(method) {\n /* istanbul ignore else */\n if (console !== 'undefined' && method in console) {\n var args = Array.prototype.slice.call(arguments, 1);\n console[method].apply(console, args);\n }\n}\n\nfunction randomNumber(min, max) {\n var maxTimeout = 600000; // Hard-coded default of 10 minutes\n min = parseInt(min, 10) || 0;\n max = parseInt(max, 10);\n if (max !== max || max <= min) {\n max = (min || 1) << 1; //doubling\n } else {\n max = max + 1;\n }\n // In order to not exceed maxTimeout, pick a random value between half of maxTimeout and maxTimeout\n if(max > maxTimeout) {\n min = maxTimeout >> 1; // divide by two\n max = maxTimeout;\n }\n var ratio = Math.random();\n var range = max - min;\n\n return ~~(range * ratio + min); // ~~ coerces to an int, but fast.\n}\n\nfunction defaultBackOff(min) {\n var max = 0;\n if (!min) {\n max = 2000;\n }\n return randomNumber(min, max);\n}\n\n// designed to give info to browser users, who are disturbed\n// when they see http errors in the console\nfunction explainError(status, str) {\n guardedConsole('info', 'The above ' + status + ' is totally normal. ' + str);\n}\n\nvar assign;\n{\n if (typeof Object.assign === 'function') {\n assign = Object.assign;\n } else {\n // lite Object.assign polyfill based on\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign\n assign = function (target) {\n var to = Object(target);\n\n for (var index = 1; index < arguments.length; index++) {\n var nextSource = arguments[index];\n\n if (nextSource != null) { // Skip over if undefined or null\n for (var nextKey in nextSource) {\n // Avoid bugs when hasOwnProperty is shadowed\n if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {\n to[nextKey] = nextSource[nextKey];\n }\n }\n }\n }\n return to;\n };\n }\n}\n\nvar assign$1 = assign;\n\ninherits(PouchError, Error);\n\nfunction PouchError(status, error, reason) {\n Error.call(this, reason);\n this.status = status;\n this.name = error;\n this.message = reason;\n this.error = true;\n}\n\nPouchError.prototype.toString = function () {\n return JSON.stringify({\n status: this.status,\n name: this.name,\n message: this.message,\n reason: this.reason\n });\n};\n\nvar UNAUTHORIZED = new PouchError(401, 'unauthorized', \"Name or password is incorrect.\");\nvar MISSING_BULK_DOCS = new PouchError(400, 'bad_request', \"Missing JSON list of 'docs'\");\nvar MISSING_DOC = new PouchError(404, 'not_found', 'missing');\nvar REV_CONFLICT = new PouchError(409, 'conflict', 'Document update conflict');\nvar INVALID_ID = new PouchError(400, 'bad_request', '_id field must contain a string');\nvar MISSING_ID = new PouchError(412, 'missing_id', '_id is required for puts');\nvar RESERVED_ID = new PouchError(400, 'bad_request', 'Only reserved document ids may start with underscore.');\nvar NOT_OPEN = new PouchError(412, 'precondition_failed', 'Database not open');\nvar UNKNOWN_ERROR = new PouchError(500, 'unknown_error', 'Database encountered an unknown error');\nvar BAD_ARG = new PouchError(500, 'badarg', 'Some query argument is invalid');\nvar INVALID_REQUEST = new PouchError(400, 'invalid_request', 'Request was invalid');\nvar QUERY_PARSE_ERROR = new PouchError(400, 'query_parse_error', 'Some query parameter is invalid');\nvar DOC_VALIDATION = new PouchError(500, 'doc_validation', 'Bad special document member');\nvar BAD_REQUEST = new PouchError(400, 'bad_request', 'Something wrong with the request');\nvar NOT_AN_OBJECT = new PouchError(400, 'bad_request', 'Document must be a JSON object');\nvar DB_MISSING = new PouchError(404, 'not_found', 'Database not found');\nvar IDB_ERROR = new PouchError(500, 'indexed_db_went_bad', 'unknown');\nvar WSQ_ERROR = new PouchError(500, 'web_sql_went_bad', 'unknown');\nvar LDB_ERROR = new PouchError(500, 'levelDB_went_went_bad', 'unknown');\nvar FORBIDDEN = new PouchError(403, 'forbidden', 'Forbidden by design doc validate_doc_update function');\nvar INVALID_REV = new PouchError(400, 'bad_request', 'Invalid rev format');\nvar FILE_EXISTS = new PouchError(412, 'file_exists', 'The database could not be created, the file already exists.');\nvar MISSING_STUB = new PouchError(412, 'missing_stub', 'A pre-existing attachment stub wasn\\'t found');\nvar INVALID_URL = new PouchError(413, 'invalid_url', 'Provided URL is invalid');\n\nfunction createError(error, reason) {\n function CustomPouchError(reason) {\n // inherit error properties from our parent error manually\n // so as to allow proper JSON parsing.\n /* jshint ignore:start */\n for (var p in error) {\n if (typeof error[p] !== 'function') {\n this[p] = error[p];\n }\n }\n /* jshint ignore:end */\n if (reason !== undefined) {\n this.reason = reason;\n }\n }\n CustomPouchError.prototype = PouchError.prototype;\n return new CustomPouchError(reason);\n}\n\nfunction generateErrorFromResponse(err) {\n\n if (typeof err !== 'object') {\n var data = err;\n err = UNKNOWN_ERROR;\n err.data = data;\n }\n\n if ('error' in err && err.error === 'conflict') {\n err.name = 'conflict';\n err.status = 409;\n }\n\n if (!('name' in err)) {\n err.name = err.error || 'unknown';\n }\n\n if (!('status' in err)) {\n err.status = 500;\n }\n\n if (!('message' in err)) {\n err.message = err.message || err.reason;\n }\n\n return err;\n}\n\nfunction tryFilter(filter, doc, req) {\n try {\n return !filter(doc, req);\n } catch (err) {\n var msg = 'Filter function threw: ' + err.toString();\n return createError(BAD_REQUEST, msg);\n }\n}\n\nfunction filterChange(opts) {\n var req = {};\n var hasFilter = opts.filter && typeof opts.filter === 'function';\n req.query = opts.query_params;\n\n return function filter(change) {\n if (!change.doc) {\n // CSG sends events on the changes feed that don't have documents,\n // this hack makes a whole lot of existing code robust.\n change.doc = {};\n }\n\n var filterReturn = hasFilter && tryFilter(opts.filter, change.doc, req);\n\n if (typeof filterReturn === 'object') {\n return filterReturn;\n }\n\n if (filterReturn) {\n return false;\n }\n\n if (!opts.include_docs) {\n delete change.doc;\n } else if (!opts.attachments) {\n for (var att in change.doc._attachments) {\n /* istanbul ignore else */\n if (change.doc._attachments.hasOwnProperty(att)) {\n change.doc._attachments[att].stub = true;\n }\n }\n }\n return true;\n };\n}\n\nfunction flatten(arrs) {\n var res = [];\n for (var i = 0, len = arrs.length; i < len; i++) {\n res = res.concat(arrs[i]);\n }\n return res;\n}\n\n// shim for Function.prototype.name,\n// for browsers that don't support it like IE\n\n/* istanbul ignore next */\nfunction f() {}\n\nvar hasName = f.name;\nvar res;\n\n// We dont run coverage in IE\n/* istanbul ignore else */\nif (hasName) {\n res = function (fun) {\n return fun.name;\n };\n} else {\n res = function (fun) {\n return fun.toString().match(/^\\s*function\\s*(\\S*)\\s*\\(/)[1];\n };\n}\n\n// Determine id an ID is valid\n// - invalid IDs begin with an underescore that does not begin '_design' or\n// '_local'\n// - any other string value is a valid id\n// Returns the specific error object for each case\nfunction invalidIdError(id) {\n var err;\n if (!id) {\n err = createError(MISSING_ID);\n } else if (typeof id !== 'string') {\n err = createError(INVALID_ID);\n } else if (/^_/.test(id) && !(/^_(design|local)/).test(id)) {\n err = createError(RESERVED_ID);\n }\n if (err) {\n throw err;\n }\n}\n\nfunction listenerCount(ee, type) {\n return 'listenerCount' in ee ? ee.listenerCount(type) :\n events.EventEmitter.listenerCount(ee, type);\n}\n\n// Custom nextTick() shim for browsers. In node, this will just be process.nextTick(). We\n// avoid using process.nextTick() directly because the polyfill is very large and we don't\n// need all of it (see: https://github.com/defunctzombie/node-process).\n// \"immediate\" 3.0.8 is used by lie, and it's a smaller version of the latest \"immediate\"\n// package, so it's the one we use.\n// When we use nextTick() in our codebase, we only care about not releasing Zalgo\n// (see: http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony).\n// Microtask vs macrotask doesn't matter to us. So we're free to use the fastest\n// (least latency) option, which is \"immediate\" due to use of microtasks.\n// All of our nextTicks are isolated to this one function so we can easily swap out one\n// implementation for another.\n\nfunction parseDesignDocFunctionName(s) {\n if (!s) {\n return null;\n }\n var parts = s.split('/');\n if (parts.length === 2) {\n return parts;\n }\n if (parts.length === 1) {\n return [s, s];\n }\n return null;\n}\n\nfunction normalizeDesignDocFunctionName(s) {\n var normalized = parseDesignDocFunctionName(s);\n return normalized ? normalized.join('/') : null;\n}\n\n// originally parseUri 1.2.2, now patched by us\n// (c) Steven Levithan \n// MIT License\nvar keys = [\"source\", \"protocol\", \"authority\", \"userInfo\", \"user\", \"password\",\n \"host\", \"port\", \"relative\", \"path\", \"directory\", \"file\", \"query\", \"anchor\"];\nvar qName =\"queryKey\";\nvar qParser = /(?:^|&)([^&=]*)=?([^&]*)/g;\n\n// use the \"loose\" parser\n/* jshint maxlen: false */\nvar parser = /^(?:(?![^:@]+:[^:@\\/]*@)([^:\\/?#.]+):)?(?:\\/\\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\\/?#]*)(?::(\\d*))?)(((\\/(?:[^?#](?![^?#\\/]*\\.[^?#\\/.]+(?:[?#]|$)))*\\/?)?([^?#\\/]*))(?:\\?([^#]*))?(?:#(.*))?)/;\n\nfunction parseUri(str) {\n var m = parser.exec(str);\n var uri = {};\n var i = 14;\n\n while (i--) {\n var key = keys[i];\n var value = m[i] || \"\";\n var encoded = ['user', 'password'].indexOf(key) !== -1;\n uri[key] = encoded ? decodeURIComponent(value) : value;\n }\n\n uri[qName] = {};\n uri[keys[12]].replace(qParser, function ($0, $1, $2) {\n if ($1) {\n uri[qName][$1] = $2;\n }\n });\n\n return uri;\n}\n\n// this is essentially the \"update sugar\" function from daleharvey/pouchdb#1388\n// the diffFun tells us what delta to apply to the doc. it either returns\n// the doc, or false if it doesn't need to do an update after all\nfunction upsert(db, docId, diffFun) {\n return new PouchPromise$1(function (fulfill, reject) {\n db.get(docId, function (err, doc) {\n if (err) {\n /* istanbul ignore next */\n if (err.status !== 404) {\n return reject(err);\n }\n doc = {};\n }\n\n // the user might change the _rev, so save it for posterity\n var docRev = doc._rev;\n var newDoc = diffFun(doc);\n\n if (!newDoc) {\n // if the diffFun returns falsy, we short-circuit as\n // an optimization\n return fulfill({updated: false, rev: docRev});\n }\n\n // users aren't allowed to modify these values,\n // so reset them here\n newDoc._id = docId;\n newDoc._rev = docRev;\n fulfill(tryAndPut(db, newDoc, diffFun));\n });\n });\n}\n\nfunction tryAndPut(db, doc, diffFun) {\n return db.put(doc).then(function (res) {\n return {\n updated: true,\n rev: res.rev\n };\n }, function (err) {\n /* istanbul ignore next */\n if (err.status !== 409) {\n throw err;\n }\n return upsert(db, doc._id, diffFun);\n });\n}\n\n// BEGIN Math.uuid.js\n\n/*!\nMath.uuid.js (v1.4)\nhttp://www.broofa.com\nmailto:robert@broofa.com\n\nCopyright (c) 2010 Robert Kieffer\nDual licensed under the MIT and GPL licenses.\n*/\n\n/*\n * Generate a random uuid.\n *\n * USAGE: Math.uuid(length, radix)\n * length - the desired number of characters\n * radix - the number of allowable values for each character.\n *\n * EXAMPLES:\n * // No arguments - returns RFC4122, version 4 ID\n * >>> Math.uuid()\n * \"92329D39-6F5C-4520-ABFC-AAB64544E172\"\n *\n * // One argument - returns ID of the specified length\n * >>> Math.uuid(15) // 15 character ID (default base=62)\n * \"VcydxgltxrVZSTV\"\n *\n * // Two arguments - returns ID of the specified length, and radix. \n * // (Radix must be <= 62)\n * >>> Math.uuid(8, 2) // 8 character ID (base=2)\n * \"01001010\"\n * >>> Math.uuid(8, 10) // 8 character ID (base=10)\n * \"47473046\"\n * >>> Math.uuid(8, 16) // 8 character ID (base=16)\n * \"098F4D35\"\n */\nvar chars = (\n '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' +\n 'abcdefghijklmnopqrstuvwxyz'\n).split('');\nfunction getValue(radix) {\n return 0 | Math.random() * radix;\n}\nfunction uuid(len, radix) {\n radix = radix || chars.length;\n var out = '';\n var i = -1;\n\n if (len) {\n // Compact form\n while (++i < len) {\n out += chars[getValue(radix)];\n }\n return out;\n }\n // rfc4122, version 4 form\n // Fill in random data. At i==19 set the high bits of clock sequence as\n // per rfc4122, sec. 4.1.5\n while (++i < 36) {\n switch (i) {\n case 8:\n case 13:\n case 18:\n case 23:\n out += '-';\n break;\n case 19:\n out += chars[(getValue(16) & 0x3) | 0x8];\n break;\n default:\n out += chars[getValue(16)];\n }\n }\n\n return out;\n}\n\n// We fetch all leafs of the revision tree, and sort them based on tree length\n// and whether they were deleted, undeleted documents with the longest revision\n// tree (most edits) win\n// The final sort algorithm is slightly documented in a sidebar here:\n// http://guide.couchdb.org/draft/conflicts.html\nfunction winningRev(metadata) {\n var winningId;\n var winningPos;\n var winningDeleted;\n var toVisit = metadata.rev_tree.slice();\n var node;\n while ((node = toVisit.pop())) {\n var tree = node.ids;\n var branches = tree[2];\n var pos = node.pos;\n if (branches.length) { // non-leaf\n for (var i = 0, len = branches.length; i < len; i++) {\n toVisit.push({pos: pos + 1, ids: branches[i]});\n }\n continue;\n }\n var deleted = !!tree[1].deleted;\n var id = tree[0];\n // sort by deleted, then pos, then id\n if (!winningId || (winningDeleted !== deleted ? winningDeleted :\n winningPos !== pos ? winningPos < pos : winningId < id)) {\n winningId = id;\n winningPos = pos;\n winningDeleted = deleted;\n }\n }\n\n return winningPos + '-' + winningId;\n}\n\n// Pretty much all below can be combined into a higher order function to\n// traverse revisions\n// The return value from the callback will be passed as context to all\n// children of that node\nfunction traverseRevTree(revs, callback) {\n var toVisit = revs.slice();\n\n var node;\n while ((node = toVisit.pop())) {\n var pos = node.pos;\n var tree = node.ids;\n var branches = tree[2];\n var newCtx =\n callback(branches.length === 0, pos, tree[0], node.ctx, tree[1]);\n for (var i = 0, len = branches.length; i < len; i++) {\n toVisit.push({pos: pos + 1, ids: branches[i], ctx: newCtx});\n }\n }\n}\n\nfunction sortByPos(a, b) {\n return a.pos - b.pos;\n}\n\nfunction collectLeaves(revs) {\n var leaves = [];\n traverseRevTree(revs, function (isLeaf, pos, id, acc, opts) {\n if (isLeaf) {\n leaves.push({rev: pos + \"-\" + id, pos: pos, opts: opts});\n }\n });\n leaves.sort(sortByPos).reverse();\n for (var i = 0, len = leaves.length; i < len; i++) {\n delete leaves[i].pos;\n }\n return leaves;\n}\n\n// returns revs of all conflicts that is leaves such that\n// 1. are not deleted and\n// 2. are different than winning revision\nfunction collectConflicts(metadata) {\n var win = winningRev(metadata);\n var leaves = collectLeaves(metadata.rev_tree);\n var conflicts = [];\n for (var i = 0, len = leaves.length; i < len; i++) {\n var leaf = leaves[i];\n if (leaf.rev !== win && !leaf.opts.deleted) {\n conflicts.push(leaf.rev);\n }\n }\n return conflicts;\n}\n\n// compact a tree by marking its non-leafs as missing,\n// and return a list of revs to delete\nfunction compactTree(metadata) {\n var revs = [];\n traverseRevTree(metadata.rev_tree, function (isLeaf, pos,\n revHash, ctx, opts) {\n if (opts.status === 'available' && !isLeaf) {\n revs.push(pos + '-' + revHash);\n opts.status = 'missing';\n }\n });\n return revs;\n}\n\n// build up a list of all the paths to the leafs in this revision tree\nfunction rootToLeaf(revs) {\n var paths = [];\n var toVisit = revs.slice();\n var node;\n while ((node = toVisit.pop())) {\n var pos = node.pos;\n var tree = node.ids;\n var id = tree[0];\n var opts = tree[1];\n var branches = tree[2];\n var isLeaf = branches.length === 0;\n\n var history = node.history ? node.history.slice() : [];\n history.push({id: id, opts: opts});\n if (isLeaf) {\n paths.push({pos: (pos + 1 - history.length), ids: history});\n }\n for (var i = 0, len = branches.length; i < len; i++) {\n toVisit.push({pos: pos + 1, ids: branches[i], history: history});\n }\n }\n return paths.reverse();\n}\n\n// for a better overview of what this is doing, read:\n// https://github.com/apache/couchdb-couch/blob/master/src/couch_key_tree.erl\n//\n// But for a quick intro, CouchDB uses a revision tree to store a documents\n// history, A -> B -> C, when a document has conflicts, that is a branch in the\n// tree, A -> (B1 | B2 -> C), We store these as a nested array in the format\n//\n// KeyTree = [Path ... ]\n// Path = {pos: position_from_root, ids: Tree}\n// Tree = [Key, Opts, [Tree, ...]], in particular single node: [Key, []]\n\nfunction sortByPos$1(a, b) {\n return a.pos - b.pos;\n}\n\n// classic binary search\nfunction binarySearch(arr, item, comparator) {\n var low = 0;\n var high = arr.length;\n var mid;\n while (low < high) {\n mid = (low + high) >>> 1;\n if (comparator(arr[mid], item) < 0) {\n low = mid + 1;\n } else {\n high = mid;\n }\n }\n return low;\n}\n\n// assuming the arr is sorted, insert the item in the proper place\nfunction insertSorted(arr, item, comparator) {\n var idx = binarySearch(arr, item, comparator);\n arr.splice(idx, 0, item);\n}\n\n// Turn a path as a flat array into a tree with a single branch.\n// If any should be stemmed from the beginning of the array, that's passed\n// in as the second argument\nfunction pathToTree(path, numStemmed) {\n var root;\n var leaf;\n for (var i = numStemmed, len = path.length; i < len; i++) {\n var node = path[i];\n var currentLeaf = [node.id, node.opts, []];\n if (leaf) {\n leaf[2].push(currentLeaf);\n leaf = currentLeaf;\n } else {\n root = leaf = currentLeaf;\n }\n }\n return root;\n}\n\n// compare the IDs of two trees\nfunction compareTree(a, b) {\n return a[0] < b[0] ? -1 : 1;\n}\n\n// Merge two trees together\n// The roots of tree1 and tree2 must be the same revision\nfunction mergeTree(in_tree1, in_tree2) {\n var queue = [{tree1: in_tree1, tree2: in_tree2}];\n var conflicts = false;\n while (queue.length > 0) {\n var item = queue.pop();\n var tree1 = item.tree1;\n var tree2 = item.tree2;\n\n if (tree1[1].status || tree2[1].status) {\n tree1[1].status =\n (tree1[1].status === 'available' ||\n tree2[1].status === 'available') ? 'available' : 'missing';\n }\n\n for (var i = 0; i < tree2[2].length; i++) {\n if (!tree1[2][0]) {\n conflicts = 'new_leaf';\n tree1[2][0] = tree2[2][i];\n continue;\n }\n\n var merged = false;\n for (var j = 0; j < tree1[2].length; j++) {\n if (tree1[2][j][0] === tree2[2][i][0]) {\n queue.push({tree1: tree1[2][j], tree2: tree2[2][i]});\n merged = true;\n }\n }\n if (!merged) {\n conflicts = 'new_branch';\n insertSorted(tree1[2], tree2[2][i], compareTree);\n }\n }\n }\n return {conflicts: conflicts, tree: in_tree1};\n}\n\nfunction doMerge(tree, path, dontExpand) {\n var restree = [];\n var conflicts = false;\n var merged = false;\n var res;\n\n if (!tree.length) {\n return {tree: [path], conflicts: 'new_leaf'};\n }\n\n for (var i = 0, len = tree.length; i < len; i++) {\n var branch = tree[i];\n if (branch.pos === path.pos && branch.ids[0] === path.ids[0]) {\n // Paths start at the same position and have the same root, so they need\n // merged\n res = mergeTree(branch.ids, path.ids);\n restree.push({pos: branch.pos, ids: res.tree});\n conflicts = conflicts || res.conflicts;\n merged = true;\n } else if (dontExpand !== true) {\n // The paths start at a different position, take the earliest path and\n // traverse up until it as at the same point from root as the path we\n // want to merge. If the keys match we return the longer path with the\n // other merged After stemming we dont want to expand the trees\n\n var t1 = branch.pos < path.pos ? branch : path;\n var t2 = branch.pos < path.pos ? path : branch;\n var diff = t2.pos - t1.pos;\n\n var candidateParents = [];\n\n var trees = [];\n trees.push({ids: t1.ids, diff: diff, parent: null, parentIdx: null});\n while (trees.length > 0) {\n var item = trees.pop();\n if (item.diff === 0) {\n if (item.ids[0] === t2.ids[0]) {\n candidateParents.push(item);\n }\n continue;\n }\n var elements = item.ids[2];\n for (var j = 0, elementsLen = elements.length; j < elementsLen; j++) {\n trees.push({\n ids: elements[j],\n diff: item.diff - 1,\n parent: item.ids,\n parentIdx: j\n });\n }\n }\n\n var el = candidateParents[0];\n\n if (!el) {\n restree.push(branch);\n } else {\n res = mergeTree(el.ids, t2.ids);\n el.parent[2][el.parentIdx] = res.tree;\n restree.push({pos: t1.pos, ids: t1.ids});\n conflicts = conflicts || res.conflicts;\n merged = true;\n }\n } else {\n restree.push(branch);\n }\n }\n\n // We didnt find\n if (!merged) {\n restree.push(path);\n }\n\n restree.sort(sortByPos$1);\n\n return {\n tree: restree,\n conflicts: conflicts || 'internal_node'\n };\n}\n\n// To ensure we dont grow the revision tree infinitely, we stem old revisions\nfunction stem(tree, depth) {\n // First we break out the tree into a complete list of root to leaf paths\n var paths = rootToLeaf(tree);\n var maybeStem = {};\n\n var result;\n for (var i = 0, len = paths.length; i < len; i++) {\n // Then for each path, we cut off the start of the path based on the\n // `depth` to stem to, and generate a new set of flat trees\n var path = paths[i];\n var stemmed = path.ids;\n var numStemmed = Math.max(0, stemmed.length - depth);\n var stemmedNode = {\n pos: path.pos + numStemmed,\n ids: pathToTree(stemmed, numStemmed)\n };\n\n for (var s = 0; s < numStemmed; s++) {\n var rev = (path.pos + s) + '-' + stemmed[s].id;\n maybeStem[rev] = true;\n }\n\n // Then we remerge all those flat trees together, ensuring that we dont\n // connect trees that would go beyond the depth limit\n if (result) {\n result = doMerge(result, stemmedNode, true).tree;\n } else {\n result = [stemmedNode];\n }\n }\n\n traverseRevTree(result, function (isLeaf, pos, revHash) {\n // some revisions may have been removed in a branch but not in another\n delete maybeStem[pos + '-' + revHash];\n });\n\n return {\n tree: result,\n revs: Object.keys(maybeStem)\n };\n}\n\nfunction merge(tree, path, depth) {\n var newTree = doMerge(tree, path);\n var stemmed = stem(newTree.tree, depth);\n return {\n tree: stemmed.tree,\n stemmedRevs: stemmed.revs,\n conflicts: newTree.conflicts\n };\n}\n\n// return true if a rev exists in the rev tree, false otherwise\nfunction revExists(revs, rev) {\n var toVisit = revs.slice();\n var splitRev = rev.split('-');\n var targetPos = parseInt(splitRev[0], 10);\n var targetId = splitRev[1];\n\n var node;\n while ((node = toVisit.pop())) {\n if (node.pos === targetPos && node.ids[0] === targetId) {\n return true;\n }\n var branches = node.ids[2];\n for (var i = 0, len = branches.length; i < len; i++) {\n toVisit.push({pos: node.pos + 1, ids: branches[i]});\n }\n }\n return false;\n}\n\nfunction getTrees(node) {\n return node.ids;\n}\n\n// check if a specific revision of a doc has been deleted\n// - metadata: the metadata object from the doc store\n// - rev: (optional) the revision to check. defaults to winning revision\nfunction isDeleted(metadata, rev) {\n if (!rev) {\n rev = winningRev(metadata);\n }\n var id = rev.substring(rev.indexOf('-') + 1);\n var toVisit = metadata.rev_tree.map(getTrees);\n\n var tree;\n while ((tree = toVisit.pop())) {\n if (tree[0] === id) {\n return !!tree[1].deleted;\n }\n toVisit = toVisit.concat(tree[2]);\n }\n}\n\nfunction isLocalId(id) {\n return (/^_local/).test(id);\n}\n\n// returns the current leaf node for a given revision\nfunction latest(rev, metadata) {\n var toVisit = metadata.rev_tree.slice();\n var node;\n while ((node = toVisit.pop())) {\n var pos = node.pos;\n var tree = node.ids;\n var id = tree[0];\n var opts = tree[1];\n var branches = tree[2];\n var isLeaf = branches.length === 0;\n\n var history = node.history ? node.history.slice() : [];\n history.push({id: id, pos: pos, opts: opts});\n\n if (isLeaf) {\n for (var i = 0, len = history.length; i < len; i++) {\n var historyNode = history[i];\n var historyRev = historyNode.pos + '-' + historyNode.id;\n\n if (historyRev === rev) {\n // return the rev of this leaf\n return pos + '-' + id;\n }\n }\n }\n\n for (var j = 0, l = branches.length; j < l; j++) {\n toVisit.push({pos: pos + 1, ids: branches[j], history: history});\n }\n }\n\n /* istanbul ignore next */\n throw new Error('Unable to resolve latest revision for id ' + metadata.id + ', rev ' + rev);\n}\n\nfunction evalFilter(input) {\n return scopedEval('\"use strict\";\\nreturn ' + input + ';', {});\n}\n\nfunction evalView(input) {\n var code = [\n 'return function(doc) {',\n ' \"use strict\";',\n ' var emitted = false;',\n ' var emit = function (a, b) {',\n ' emitted = true;',\n ' };',\n ' var view = ' + input + ';',\n ' view(doc);',\n ' if (emitted) {',\n ' return true;',\n ' }',\n '};'\n ].join('\\n');\n\n return scopedEval(code, {});\n}\n\ninherits(Changes$2, events.EventEmitter);\n\nfunction tryCatchInChangeListener(self, change) {\n // isolate try/catches to avoid V8 deoptimizations\n try {\n self.emit('change', change);\n } catch (e) {\n guardedConsole('error', 'Error in .on(\"change\", function):', e);\n }\n}\n\nfunction Changes$2(db, opts, callback) {\n events.EventEmitter.call(this);\n var self = this;\n this.db = db;\n opts = opts ? clone(opts) : {};\n var complete = opts.complete = once(function (err, resp) {\n if (err) {\n if (listenerCount(self, 'error') > 0) {\n self.emit('error', err);\n }\n } else {\n self.emit('complete', resp);\n }\n self.removeAllListeners();\n db.removeListener('destroyed', onDestroy);\n });\n if (callback) {\n self.on('complete', function (resp) {\n callback(null, resp);\n });\n self.on('error', callback);\n }\n function onDestroy() {\n self.cancel();\n }\n db.once('destroyed', onDestroy);\n\n opts.onChange = function (change) {\n /* istanbul ignore if */\n if (self.isCancelled) {\n return;\n }\n tryCatchInChangeListener(self, change);\n };\n\n var promise = new PouchPromise$1(function (fulfill, reject) {\n opts.complete = function (err, res) {\n if (err) {\n reject(err);\n } else {\n fulfill(res);\n }\n };\n });\n self.once('cancel', function () {\n db.removeListener('destroyed', onDestroy);\n opts.complete(null, {status: 'cancelled'});\n });\n this.then = promise.then.bind(promise);\n this['catch'] = promise['catch'].bind(promise);\n this.then(function (result) {\n complete(null, result);\n }, complete);\n\n\n\n if (!db.taskqueue.isReady) {\n db.taskqueue.addTask(function (failed) {\n if (failed) {\n opts.complete(failed);\n } else if (self.isCancelled) {\n self.emit('cancel');\n } else {\n self.doChanges(opts);\n }\n });\n } else {\n self.doChanges(opts);\n }\n}\nChanges$2.prototype.cancel = function () {\n this.isCancelled = true;\n if (this.db.taskqueue.isReady) {\n this.emit('cancel');\n }\n};\nfunction processChange(doc, metadata, opts) {\n var changeList = [{rev: doc._rev}];\n if (opts.style === 'all_docs') {\n changeList = collectLeaves(metadata.rev_tree)\n .map(function (x) { return {rev: x.rev}; });\n }\n var change = {\n id: metadata.id,\n changes: changeList,\n doc: doc\n };\n\n if (isDeleted(metadata, doc._rev)) {\n change.deleted = true;\n }\n if (opts.conflicts) {\n change.doc._conflicts = collectConflicts(metadata);\n if (!change.doc._conflicts.length) {\n delete change.doc._conflicts;\n }\n }\n return change;\n}\n\nChanges$2.prototype.doChanges = function (opts) {\n var self = this;\n var callback = opts.complete;\n\n opts = clone(opts);\n if ('live' in opts && !('continuous' in opts)) {\n opts.continuous = opts.live;\n }\n opts.processChange = processChange;\n\n if (opts.since === 'latest') {\n opts.since = 'now';\n }\n if (!opts.since) {\n opts.since = 0;\n }\n if (opts.since === 'now') {\n this.db.info().then(function (info) {\n /* istanbul ignore if */\n if (self.isCancelled) {\n callback(null, {status: 'cancelled'});\n return;\n }\n opts.since = info.update_seq;\n self.doChanges(opts);\n }, callback);\n return;\n }\n\n\n if (opts.view && !opts.filter) {\n opts.filter = '_view';\n }\n\n if (opts.filter && typeof opts.filter === 'string') {\n if (opts.filter === '_view') {\n opts.view = normalizeDesignDocFunctionName(opts.view);\n } else {\n opts.filter = normalizeDesignDocFunctionName(opts.filter);\n }\n\n if (this.db.type() !== 'http' && !opts.doc_ids) {\n return this.filterChanges(opts);\n }\n }\n\n if (!('descending' in opts)) {\n opts.descending = false;\n }\n\n // 0 and 1 should return 1 document\n opts.limit = opts.limit === 0 ? 1 : opts.limit;\n opts.complete = callback;\n var newPromise = this.db._changes(opts);\n /* istanbul ignore else */\n if (newPromise && typeof newPromise.cancel === 'function') {\n var cancel = self.cancel;\n self.cancel = getArguments(function (args) {\n newPromise.cancel();\n cancel.apply(this, args);\n });\n }\n};\n\nChanges$2.prototype.filterChanges = function (opts) {\n var self = this;\n var callback = opts.complete;\n if (opts.filter === '_view') {\n if (!opts.view || typeof opts.view !== 'string') {\n var err = createError(BAD_REQUEST,\n '`view` filter parameter not found or invalid.');\n return callback(err);\n }\n // fetch a view from a design doc, make it behave like a filter\n var viewName = parseDesignDocFunctionName(opts.view);\n this.db.get('_design/' + viewName[0], function (err, ddoc) {\n /* istanbul ignore if */\n if (self.isCancelled) {\n return callback(null, {status: 'cancelled'});\n }\n /* istanbul ignore next */\n if (err) {\n return callback(generateErrorFromResponse(err));\n }\n var mapFun = ddoc && ddoc.views && ddoc.views[viewName[1]] &&\n ddoc.views[viewName[1]].map;\n if (!mapFun) {\n return callback(createError(MISSING_DOC,\n (ddoc.views ? 'missing json key: ' + viewName[1] :\n 'missing json key: views')));\n }\n opts.filter = evalView(mapFun);\n self.doChanges(opts);\n });\n } else {\n // fetch a filter from a design doc\n var filterName = parseDesignDocFunctionName(opts.filter);\n if (!filterName) {\n return self.doChanges(opts);\n }\n this.db.get('_design/' + filterName[0], function (err, ddoc) {\n /* istanbul ignore if */\n if (self.isCancelled) {\n return callback(null, {status: 'cancelled'});\n }\n /* istanbul ignore next */\n if (err) {\n return callback(generateErrorFromResponse(err));\n }\n var filterFun = ddoc && ddoc.filters && ddoc.filters[filterName[1]];\n if (!filterFun) {\n return callback(createError(MISSING_DOC,\n ((ddoc && ddoc.filters) ? 'missing json key: ' + filterName[1]\n : 'missing json key: filters')));\n }\n opts.filter = evalFilter(filterFun);\n self.doChanges(opts);\n });\n }\n};\n\n/*\n * A generic pouch adapter\n */\n\nfunction compare(left, right) {\n return left < right ? -1 : left > right ? 1 : 0;\n}\n\n// Wrapper for functions that call the bulkdocs api with a single doc,\n// if the first result is an error, return an error\nfunction yankError(callback) {\n return function (err, results) {\n if (err || (results[0] && results[0].error)) {\n callback(err || results[0]);\n } else {\n callback(null, results.length ? results[0] : results);\n }\n };\n}\n\n// clean docs given to us by the user\nfunction cleanDocs(docs) {\n for (var i = 0; i < docs.length; i++) {\n var doc = docs[i];\n if (doc._deleted) {\n delete doc._attachments; // ignore atts for deleted docs\n } else if (doc._attachments) {\n // filter out extraneous keys from _attachments\n var atts = Object.keys(doc._attachments);\n for (var j = 0; j < atts.length; j++) {\n var att = atts[j];\n doc._attachments[att] = pick(doc._attachments[att],\n ['data', 'digest', 'content_type', 'length', 'revpos', 'stub']);\n }\n }\n }\n}\n\n// compare two docs, first by _id then by _rev\nfunction compareByIdThenRev(a, b) {\n var idCompare = compare(a._id, b._id);\n if (idCompare !== 0) {\n return idCompare;\n }\n var aStart = a._revisions ? a._revisions.start : 0;\n var bStart = b._revisions ? b._revisions.start : 0;\n return compare(aStart, bStart);\n}\n\n// for every node in a revision tree computes its distance from the closest\n// leaf\nfunction computeHeight(revs) {\n var height = {};\n var edges = [];\n traverseRevTree(revs, function (isLeaf, pos, id, prnt) {\n var rev = pos + \"-\" + id;\n if (isLeaf) {\n height[rev] = 0;\n }\n if (prnt !== undefined) {\n edges.push({from: prnt, to: rev});\n }\n return rev;\n });\n\n edges.reverse();\n edges.forEach(function (edge) {\n if (height[edge.from] === undefined) {\n height[edge.from] = 1 + height[edge.to];\n } else {\n height[edge.from] = Math.min(height[edge.from], 1 + height[edge.to]);\n }\n });\n return height;\n}\n\nfunction allDocsKeysQuery(api, opts, callback) {\n var keys = ('limit' in opts) ?\n opts.keys.slice(opts.skip, opts.limit + opts.skip) :\n (opts.skip > 0) ? opts.keys.slice(opts.skip) : opts.keys;\n if (opts.descending) {\n keys.reverse();\n }\n if (!keys.length) {\n return api._allDocs({limit: 0}, callback);\n }\n var finalResults = {\n offset: opts.skip\n };\n return PouchPromise$1.all(keys.map(function (key) {\n var subOpts = assign$1({key: key, deleted: 'ok'}, opts);\n ['limit', 'skip', 'keys'].forEach(function (optKey) {\n delete subOpts[optKey];\n });\n return new PouchPromise$1(function (resolve, reject) {\n api._allDocs(subOpts, function (err, res) {\n /* istanbul ignore if */\n if (err) {\n return reject(err);\n }\n finalResults.total_rows = res.total_rows;\n resolve(res.rows[0] || {key: key, error: 'not_found'});\n });\n });\n })).then(function (results) {\n finalResults.rows = results;\n return finalResults;\n });\n}\n\n// all compaction is done in a queue, to avoid attaching\n// too many listeners at once\nfunction doNextCompaction(self) {\n var task = self._compactionQueue[0];\n var opts = task.opts;\n var callback = task.callback;\n self.get('_local/compaction').catch(function () {\n return false;\n }).then(function (doc) {\n if (doc && doc.last_seq) {\n opts.last_seq = doc.last_seq;\n }\n self._compact(opts, function (err, res) {\n /* istanbul ignore if */\n if (err) {\n callback(err);\n } else {\n callback(null, res);\n }\n nextTick(function () {\n self._compactionQueue.shift();\n if (self._compactionQueue.length) {\n doNextCompaction(self);\n }\n });\n });\n });\n}\n\nfunction attachmentNameError(name) {\n if (name.charAt(0) === '_') {\n return name + 'is not a valid attachment name, attachment ' +\n 'names cannot start with \\'_\\'';\n }\n return false;\n}\n\ninherits(AbstractPouchDB, events.EventEmitter);\n\nfunction AbstractPouchDB() {\n events.EventEmitter.call(this);\n}\n\nAbstractPouchDB.prototype.post =\n adapterFun('post', function (doc, opts, callback) {\n if (typeof opts === 'function') {\n callback = opts;\n opts = {};\n }\n if (typeof doc !== 'object' || Array.isArray(doc)) {\n return callback(createError(NOT_AN_OBJECT));\n }\n this.bulkDocs({docs: [doc]}, opts, yankError(callback));\n});\n\nAbstractPouchDB.prototype.put = adapterFun('put', function (doc, opts, cb) {\n if (typeof opts === 'function') {\n cb = opts;\n opts = {};\n }\n if (typeof doc !== 'object' || Array.isArray(doc)) {\n return cb(createError(NOT_AN_OBJECT));\n }\n invalidIdError(doc._id);\n if (isLocalId(doc._id) && typeof this._putLocal === 'function') {\n if (doc._deleted) {\n return this._removeLocal(doc, cb);\n } else {\n return this._putLocal(doc, cb);\n }\n }\n if (typeof this._put === 'function' && opts.new_edits !== false) {\n this._put(doc, opts, cb);\n } else {\n this.bulkDocs({docs: [doc]}, opts, yankError(cb));\n }\n});\n\nAbstractPouchDB.prototype.putAttachment =\n adapterFun('putAttachment', function (docId, attachmentId, rev,\n blob, type) {\n var api = this;\n if (typeof type === 'function') {\n type = blob;\n blob = rev;\n rev = null;\n }\n // Lets fix in https://github.com/pouchdb/pouchdb/issues/3267\n /* istanbul ignore if */\n if (typeof type === 'undefined') {\n type = blob;\n blob = rev;\n rev = null;\n }\n if (!type) {\n guardedConsole('warn', 'Attachment', attachmentId, 'on document', docId, 'is missing content_type');\n }\n\n function createAttachment(doc) {\n var prevrevpos = '_rev' in doc ? parseInt(doc._rev, 10) : 0;\n doc._attachments = doc._attachments || {};\n doc._attachments[attachmentId] = {\n content_type: type,\n data: blob,\n revpos: ++prevrevpos\n };\n return api.put(doc);\n }\n\n return api.get(docId).then(function (doc) {\n if (doc._rev !== rev) {\n throw createError(REV_CONFLICT);\n }\n\n return createAttachment(doc);\n }, function (err) {\n // create new doc\n /* istanbul ignore else */\n if (err.reason === MISSING_DOC.message) {\n return createAttachment({_id: docId});\n } else {\n throw err;\n }\n });\n});\n\nAbstractPouchDB.prototype.removeAttachment =\n adapterFun('removeAttachment', function (docId, attachmentId, rev,\n callback) {\n var self = this;\n self.get(docId, function (err, obj) {\n /* istanbul ignore if */\n if (err) {\n callback(err);\n return;\n }\n if (obj._rev !== rev) {\n callback(createError(REV_CONFLICT));\n return;\n }\n /* istanbul ignore if */\n if (!obj._attachments) {\n return callback();\n }\n delete obj._attachments[attachmentId];\n if (Object.keys(obj._attachments).length === 0) {\n delete obj._attachments;\n }\n self.put(obj, callback);\n });\n});\n\nAbstractPouchDB.prototype.remove =\n adapterFun('remove', function (docOrId, optsOrRev, opts, callback) {\n var doc;\n if (typeof optsOrRev === 'string') {\n // id, rev, opts, callback style\n doc = {\n _id: docOrId,\n _rev: optsOrRev\n };\n if (typeof opts === 'function') {\n callback = opts;\n opts = {};\n }\n } else {\n // doc, opts, callback style\n doc = docOrId;\n if (typeof optsOrRev === 'function') {\n callback = optsOrRev;\n opts = {};\n } else {\n callback = opts;\n opts = optsOrRev;\n }\n }\n opts = opts || {};\n opts.was_delete = true;\n var newDoc = {_id: doc._id, _rev: (doc._rev || opts.rev)};\n newDoc._deleted = true;\n if (isLocalId(newDoc._id) && typeof this._removeLocal === 'function') {\n return this._removeLocal(doc, callback);\n }\n this.bulkDocs({docs: [newDoc]}, opts, yankError(callback));\n});\n\nAbstractPouchDB.prototype.revsDiff =\n adapterFun('revsDiff', function (req, opts, callback) {\n if (typeof opts === 'function') {\n callback = opts;\n opts = {};\n }\n var ids = Object.keys(req);\n\n if (!ids.length) {\n return callback(null, {});\n }\n\n var count = 0;\n var missing = new ExportedMap();\n\n function addToMissing(id, revId) {\n if (!missing.has(id)) {\n missing.set(id, {missing: []});\n }\n missing.get(id).missing.push(revId);\n }\n\n function processDoc(id, rev_tree) {\n // Is this fast enough? Maybe we should switch to a set simulated by a map\n var missingForId = req[id].slice(0);\n traverseRevTree(rev_tree, function (isLeaf, pos, revHash, ctx,\n opts) {\n var rev = pos + '-' + revHash;\n var idx = missingForId.indexOf(rev);\n if (idx === -1) {\n return;\n }\n\n missingForId.splice(idx, 1);\n /* istanbul ignore if */\n if (opts.status !== 'available') {\n addToMissing(id, rev);\n }\n });\n\n // Traversing the tree is synchronous, so now `missingForId` contains\n // revisions that were not found in the tree\n missingForId.forEach(function (rev) {\n addToMissing(id, rev);\n });\n }\n\n ids.map(function (id) {\n this._getRevisionTree(id, function (err, rev_tree) {\n if (err && err.status === 404 && err.message === 'missing') {\n missing.set(id, {missing: req[id]});\n } else if (err) {\n /* istanbul ignore next */\n return callback(err);\n } else {\n processDoc(id, rev_tree);\n }\n\n if (++count === ids.length) {\n // convert LazyMap to object\n var missingObj = {};\n missing.forEach(function (value, key) {\n missingObj[key] = value;\n });\n return callback(null, missingObj);\n }\n });\n }, this);\n});\n\n// _bulk_get API for faster replication, as described in\n// https://github.com/apache/couchdb-chttpd/pull/33\n// At the \"abstract\" level, it will just run multiple get()s in\n// parallel, because this isn't much of a performance cost\n// for local databases (except the cost of multiple transactions, which is\n// small). The http adapter overrides this in order\n// to do a more efficient single HTTP request.\nAbstractPouchDB.prototype.bulkGet =\n adapterFun('bulkGet', function (opts, callback) {\n bulkGet(this, opts, callback);\n});\n\n// compact one document and fire callback\n// by compacting we mean removing all revisions which\n// are further from the leaf in revision tree than max_height\nAbstractPouchDB.prototype.compactDocument =\n adapterFun('compactDocument', function (docId, maxHeight, callback) {\n var self = this;\n this._getRevisionTree(docId, function (err, revTree) {\n /* istanbul ignore if */\n if (err) {\n return callback(err);\n }\n var height = computeHeight(revTree);\n var candidates = [];\n var revs = [];\n Object.keys(height).forEach(function (rev) {\n if (height[rev] > maxHeight) {\n candidates.push(rev);\n }\n });\n\n traverseRevTree(revTree, function (isLeaf, pos, revHash, ctx, opts) {\n var rev = pos + '-' + revHash;\n if (opts.status === 'available' && candidates.indexOf(rev) !== -1) {\n revs.push(rev);\n }\n });\n self._doCompaction(docId, revs, callback);\n });\n});\n\n// compact the whole database using single document\n// compaction\nAbstractPouchDB.prototype.compact =\n adapterFun('compact', function (opts, callback) {\n if (typeof opts === 'function') {\n callback = opts;\n opts = {};\n }\n\n var self = this;\n opts = opts || {};\n\n self._compactionQueue = self._compactionQueue || [];\n self._compactionQueue.push({opts: opts, callback: callback});\n if (self._compactionQueue.length === 1) {\n doNextCompaction(self);\n }\n});\nAbstractPouchDB.prototype._compact = function (opts, callback) {\n var self = this;\n var changesOpts = {\n return_docs: false,\n last_seq: opts.last_seq || 0\n };\n var promises = [];\n\n function onChange(row) {\n promises.push(self.compactDocument(row.id, 0));\n }\n function onComplete(resp) {\n var lastSeq = resp.last_seq;\n PouchPromise$1.all(promises).then(function () {\n return upsert(self, '_local/compaction', function deltaFunc(doc) {\n if (!doc.last_seq || doc.last_seq < lastSeq) {\n doc.last_seq = lastSeq;\n return doc;\n }\n return false; // somebody else got here first, don't update\n });\n }).then(function () {\n callback(null, {ok: true});\n }).catch(callback);\n }\n self.changes(changesOpts)\n .on('change', onChange)\n .on('complete', onComplete)\n .on('error', callback);\n};\n\n/* Begin api wrappers. Specific functionality to storage belongs in the\n _[method] */\nAbstractPouchDB.prototype.get = adapterFun('get', function (id, opts, cb) {\n if (typeof opts === 'function') {\n cb = opts;\n opts = {};\n }\n if (typeof id !== 'string') {\n return cb(createError(INVALID_ID));\n }\n if (isLocalId(id) && typeof this._getLocal === 'function') {\n return this._getLocal(id, cb);\n }\n var leaves = [], self = this;\n\n function finishOpenRevs() {\n var result = [];\n var count = leaves.length;\n /* istanbul ignore if */\n if (!count) {\n return cb(null, result);\n }\n\n // order with open_revs is unspecified\n leaves.forEach(function (leaf) {\n self.get(id, {\n rev: leaf,\n revs: opts.revs,\n latest: opts.latest,\n attachments: opts.attachments\n }, function (err, doc) {\n if (!err) {\n // using latest=true can produce duplicates\n var existing;\n for (var i = 0, l = result.length; i < l; i++) {\n if (result[i].ok && result[i].ok._rev === doc._rev) {\n existing = true;\n break;\n }\n }\n if (!existing) {\n result.push({ok: doc});\n }\n } else {\n result.push({missing: leaf});\n }\n count--;\n if (!count) {\n cb(null, result);\n }\n });\n });\n }\n\n if (opts.open_revs) {\n if (opts.open_revs === \"all\") {\n this._getRevisionTree(id, function (err, rev_tree) {\n if (err) {\n return cb(err);\n }\n leaves = collectLeaves(rev_tree).map(function (leaf) {\n return leaf.rev;\n });\n finishOpenRevs();\n });\n } else {\n if (Array.isArray(opts.open_revs)) {\n leaves = opts.open_revs;\n for (var i = 0; i < leaves.length; i++) {\n var l = leaves[i];\n // looks like it's the only thing couchdb checks\n if (!(typeof (l) === \"string\" && /^\\d+-/.test(l))) {\n return cb(createError(INVALID_REV));\n }\n }\n finishOpenRevs();\n } else {\n return cb(createError(UNKNOWN_ERROR, 'function_clause'));\n }\n }\n return; // open_revs does not like other options\n }\n\n return this._get(id, opts, function (err, result) {\n if (err) {\n return cb(err);\n }\n\n var doc = result.doc;\n var metadata = result.metadata;\n var ctx = result.ctx;\n\n if (opts.conflicts) {\n var conflicts = collectConflicts(metadata);\n if (conflicts.length) {\n doc._conflicts = conflicts;\n }\n }\n\n if (isDeleted(metadata, doc._rev)) {\n doc._deleted = true;\n }\n\n if (opts.revs || opts.revs_info) {\n var splittedRev = doc._rev.split('-');\n var revNo = parseInt(splittedRev[0], 10);\n var revHash = splittedRev[1];\n\n var paths = rootToLeaf(metadata.rev_tree);\n var path = null;\n\n for (var i = 0; i < paths.length; i++) {\n var currentPath = paths[i];\n var hashIndex = currentPath.ids.map(function (x) { return x.id; })\n .indexOf(revHash);\n var hashFoundAtRevPos = hashIndex === (revNo - 1);\n\n if (hashFoundAtRevPos || (!path && hashIndex !== -1)) {\n path = currentPath;\n }\n }\n\n var indexOfRev = path.ids.map(function (x) { return x.id; })\n .indexOf(doc._rev.split('-')[1]) + 1;\n var howMany = path.ids.length - indexOfRev;\n path.ids.splice(indexOfRev, howMany);\n path.ids.reverse();\n\n if (opts.revs) {\n doc._revisions = {\n start: (path.pos + path.ids.length) - 1,\n ids: path.ids.map(function (rev) {\n return rev.id;\n })\n };\n }\n if (opts.revs_info) {\n var pos = path.pos + path.ids.length;\n doc._revs_info = path.ids.map(function (rev) {\n pos--;\n return {\n rev: pos + '-' + rev.id,\n status: rev.opts.status\n };\n });\n }\n }\n\n if (opts.attachments && doc._attachments) {\n var attachments = doc._attachments;\n var count = Object.keys(attachments).length;\n if (count === 0) {\n return cb(null, doc);\n }\n Object.keys(attachments).forEach(function (key) {\n this._getAttachment(doc._id, key, attachments[key], {\n // Previously the revision handling was done in adapter.js\n // getAttachment, however since idb-next doesnt we need to\n // pass the rev through\n rev: doc._rev,\n binary: opts.binary,\n ctx: ctx\n }, function (err, data) {\n var att = doc._attachments[key];\n att.data = data;\n delete att.stub;\n delete att.length;\n if (!--count) {\n cb(null, doc);\n }\n });\n }, self);\n } else {\n if (doc._attachments) {\n for (var key in doc._attachments) {\n /* istanbul ignore else */\n if (doc._attachments.hasOwnProperty(key)) {\n doc._attachments[key].stub = true;\n }\n }\n }\n cb(null, doc);\n }\n });\n});\n\n// TODO: I dont like this, it forces an extra read for every\n// attachment read and enforces a confusing api between\n// adapter.js and the adapter implementation\nAbstractPouchDB.prototype.getAttachment =\n adapterFun('getAttachment', function (docId, attachmentId, opts, callback) {\n var self = this;\n if (opts instanceof Function) {\n callback = opts;\n opts = {};\n }\n this._get(docId, opts, function (err, res) {\n if (err) {\n return callback(err);\n }\n if (res.doc._attachments && res.doc._attachments[attachmentId]) {\n opts.ctx = res.ctx;\n opts.binary = true;\n self._getAttachment(docId, attachmentId,\n res.doc._attachments[attachmentId], opts, callback);\n } else {\n return callback(createError(MISSING_DOC));\n }\n });\n});\n\nAbstractPouchDB.prototype.allDocs =\n adapterFun('allDocs', function (opts, callback) {\n if (typeof opts === 'function') {\n callback = opts;\n opts = {};\n }\n opts.skip = typeof opts.skip !== 'undefined' ? opts.skip : 0;\n if (opts.start_key) {\n opts.startkey = opts.start_key;\n }\n if (opts.end_key) {\n opts.endkey = opts.end_key;\n }\n if ('keys' in opts) {\n if (!Array.isArray(opts.keys)) {\n return callback(new TypeError('options.keys must be an array'));\n }\n var incompatibleOpt =\n ['startkey', 'endkey', 'key'].filter(function (incompatibleOpt) {\n return incompatibleOpt in opts;\n })[0];\n if (incompatibleOpt) {\n callback(createError(QUERY_PARSE_ERROR,\n 'Query parameter `' + incompatibleOpt +\n '` is not compatible with multi-get'\n ));\n return;\n }\n if (this.type() !== 'http') {\n return allDocsKeysQuery(this, opts, callback);\n }\n }\n\n return this._allDocs(opts, callback);\n});\n\nAbstractPouchDB.prototype.changes = function (opts, callback) {\n if (typeof opts === 'function') {\n callback = opts;\n opts = {};\n }\n return new Changes$2(this, opts, callback);\n};\n\nAbstractPouchDB.prototype.close = adapterFun('close', function (callback) {\n this._closed = true;\n this.emit('closed');\n return this._close(callback);\n});\n\nAbstractPouchDB.prototype.info = adapterFun('info', function (callback) {\n var self = this;\n this._info(function (err, info) {\n if (err) {\n return callback(err);\n }\n // assume we know better than the adapter, unless it informs us\n info.db_name = info.db_name || self.name;\n info.auto_compaction = !!(self.auto_compaction && self.type() !== 'http');\n info.adapter = self.type();\n callback(null, info);\n });\n});\n\nAbstractPouchDB.prototype.id = adapterFun('id', function (callback) {\n return this._id(callback);\n});\n\n/* istanbul ignore next */\nAbstractPouchDB.prototype.type = function () {\n return (typeof this._type === 'function') ? this._type() : this.adapter;\n};\n\nAbstractPouchDB.prototype.bulkDocs =\n adapterFun('bulkDocs', function (req, opts, callback) {\n if (typeof opts === 'function') {\n callback = opts;\n opts = {};\n }\n\n opts = opts || {};\n\n if (Array.isArray(req)) {\n req = {\n docs: req\n };\n }\n\n if (!req || !req.docs || !Array.isArray(req.docs)) {\n return callback(createError(MISSING_BULK_DOCS));\n }\n\n for (var i = 0; i < req.docs.length; ++i) {\n if (typeof req.docs[i] !== 'object' || Array.isArray(req.docs[i])) {\n return callback(createError(NOT_AN_OBJECT));\n }\n }\n\n var attachmentError;\n req.docs.forEach(function (doc) {\n if (doc._attachments) {\n Object.keys(doc._attachments).forEach(function (name) {\n attachmentError = attachmentError || attachmentNameError(name);\n if (!doc._attachments[name].content_type) {\n guardedConsole('warn', 'Attachment', name, 'on document', doc._id, 'is missing content_type');\n }\n });\n }\n });\n\n if (attachmentError) {\n return callback(createError(BAD_REQUEST, attachmentError));\n }\n\n if (!('new_edits' in opts)) {\n if ('new_edits' in req) {\n opts.new_edits = req.new_edits;\n } else {\n opts.new_edits = true;\n }\n }\n\n var adapter = this;\n if (!opts.new_edits && adapter.type() !== 'http') {\n // ensure revisions of the same doc are sorted, so that\n // the local adapter processes them correctly (#2935)\n req.docs.sort(compareByIdThenRev);\n }\n\n cleanDocs(req.docs);\n\n // in the case of conflicts, we want to return the _ids to the user\n // however, the underlying adapter may destroy the docs array, so\n // create a copy here\n var ids = req.docs.map(function (doc) {\n return doc._id;\n });\n\n return this._bulkDocs(req, opts, function (err, res) {\n if (err) {\n return callback(err);\n }\n if (!opts.new_edits) {\n // this is what couch does when new_edits is false\n res = res.filter(function (x) {\n return x.error;\n });\n }\n // add ids for error/conflict responses (not required for CouchDB)\n if (adapter.type() !== 'http') {\n for (var i = 0, l = res.length; i < l; i++) {\n res[i].id = res[i].id || ids[i];\n }\n }\n\n callback(null, res);\n });\n});\n\nAbstractPouchDB.prototype.registerDependentDatabase =\n adapterFun('registerDependentDatabase', function (dependentDb,\n callback) {\n var depDB = new this.constructor(dependentDb, this.__opts);\n\n function diffFun(doc) {\n doc.dependentDbs = doc.dependentDbs || {};\n if (doc.dependentDbs[dependentDb]) {\n return false; // no update required\n }\n doc.dependentDbs[dependentDb] = true;\n return doc;\n }\n upsert(this, '_local/_pouch_dependentDbs', diffFun)\n .then(function () {\n callback(null, {db: depDB});\n }).catch(callback);\n});\n\nAbstractPouchDB.prototype.destroy =\n adapterFun('destroy', function (opts, callback) {\n\n if (typeof opts === 'function') {\n callback = opts;\n opts = {};\n }\n\n var self = this;\n var usePrefix = 'use_prefix' in self ? self.use_prefix : true;\n\n function destroyDb() {\n // call destroy method of the particular adaptor\n self._destroy(opts, function (err, resp) {\n if (err) {\n return callback(err);\n }\n self._destroyed = true;\n self.emit('destroyed');\n callback(null, resp || { 'ok': true });\n });\n }\n\n if (self.type() === 'http') {\n // no need to check for dependent DBs if it's a remote DB\n return destroyDb();\n }\n\n self.get('_local/_pouch_dependentDbs', function (err, localDoc) {\n if (err) {\n /* istanbul ignore if */\n if (err.status !== 404) {\n return callback(err);\n } else { // no dependencies\n return destroyDb();\n }\n }\n var dependentDbs = localDoc.dependentDbs;\n var PouchDB = self.constructor;\n var deletedMap = Object.keys(dependentDbs).map(function (name) {\n // use_prefix is only false in the browser\n /* istanbul ignore next */\n var trueName = usePrefix ?\n name.replace(new RegExp('^' + PouchDB.prefix), '') : name;\n return new PouchDB(trueName, self.__opts).destroy();\n });\n PouchPromise$1.all(deletedMap).then(destroyDb, callback);\n });\n});\n\nfunction TaskQueue$1() {\n this.isReady = false;\n this.failed = false;\n this.queue = [];\n}\n\nTaskQueue$1.prototype.execute = function () {\n var fun;\n if (this.failed) {\n while ((fun = this.queue.shift())) {\n fun(this.failed);\n }\n } else {\n while ((fun = this.queue.shift())) {\n fun();\n }\n }\n};\n\nTaskQueue$1.prototype.fail = function (err) {\n this.failed = err;\n this.execute();\n};\n\nTaskQueue$1.prototype.ready = function (db) {\n this.isReady = true;\n this.db = db;\n this.execute();\n};\n\nTaskQueue$1.prototype.addTask = function (fun) {\n this.queue.push(fun);\n if (this.failed) {\n this.execute();\n }\n};\n\nfunction parseAdapter(name, opts) {\n var match = name.match(/([a-z\\-]*):\\/\\/(.*)/);\n if (match) {\n // the http adapter expects the fully qualified name\n return {\n name: /https?/.test(match[1]) ? match[1] + '://' + match[2] : match[2],\n adapter: match[1]\n };\n }\n\n var adapters = PouchDB$5.adapters;\n var preferredAdapters = PouchDB$5.preferredAdapters;\n var prefix = PouchDB$5.prefix;\n var adapterName = opts.adapter;\n\n if (!adapterName) { // automatically determine adapter\n for (var i = 0; i < preferredAdapters.length; ++i) {\n adapterName = preferredAdapters[i];\n // check for browsers that have been upgraded from websql-only to websql+idb\n /* istanbul ignore if */\n if (adapterName === 'idb' && 'websql' in adapters &&\n hasLocalStorage() && localStorage['_pouch__websqldb_' + prefix + name]) {\n // log it, because this can be confusing during development\n guardedConsole('log', 'PouchDB is downgrading \"' + name + '\" to WebSQL to' +\n ' avoid data loss, because it was already opened with WebSQL.');\n continue; // keep using websql to avoid user data loss\n }\n break;\n }\n }\n\n var adapter = adapters[adapterName];\n\n // if adapter is invalid, then an error will be thrown later\n var usePrefix = (adapter && 'use_prefix' in adapter) ?\n adapter.use_prefix : true;\n\n return {\n name: usePrefix ? (prefix + name) : name,\n adapter: adapterName\n };\n}\n\n// OK, so here's the deal. Consider this code:\n// var db1 = new PouchDB('foo');\n// var db2 = new PouchDB('foo');\n// db1.destroy();\n// ^ these two both need to emit 'destroyed' events,\n// as well as the PouchDB constructor itself.\n// So we have one db object (whichever one got destroy() called on it)\n// responsible for emitting the initial event, which then gets emitted\n// by the constructor, which then broadcasts it to any other dbs\n// that may have been created with the same name.\nfunction prepareForDestruction(self) {\n\n var destructionListeners = self.constructor._destructionListeners;\n\n function onDestroyed() {\n self.removeListener('closed', onClosed);\n self.constructor.emit('destroyed', self.name);\n }\n\n function onConstructorDestroyed() {\n self.removeListener('destroyed', onDestroyed);\n self.removeListener('closed', onClosed);\n self.emit('destroyed');\n }\n\n function onClosed() {\n self.removeListener('destroyed', onDestroyed);\n destructionListeners.delete(self.name);\n }\n\n self.once('destroyed', onDestroyed);\n self.once('closed', onClosed);\n\n // in setup.js, the constructor is primed to listen for destroy events\n if (!destructionListeners.has(self.name)) {\n destructionListeners.set(self.name, []);\n }\n destructionListeners.get(self.name).push(onConstructorDestroyed);\n}\n\ninherits(PouchDB$5, AbstractPouchDB);\nfunction PouchDB$5(name, opts) {\n // In Node our test suite only tests this for PouchAlt unfortunately\n /* istanbul ignore if */\n if (!(this instanceof PouchDB$5)) {\n return new PouchDB$5(name, opts);\n }\n\n var self = this;\n opts = opts || {};\n\n if (name && typeof name === 'object') {\n opts = name;\n name = opts.name;\n delete opts.name;\n }\n\n this.__opts = opts = clone(opts);\n\n self.auto_compaction = opts.auto_compaction;\n self.prefix = PouchDB$5.prefix;\n\n if (typeof name !== 'string') {\n throw new Error('Missing/invalid DB name');\n }\n\n var prefixedName = (opts.prefix || '') + name;\n var backend = parseAdapter(prefixedName, opts);\n\n opts.name = backend.name;\n opts.adapter = opts.adapter || backend.adapter;\n\n self.name = name;\n self._adapter = opts.adapter;\n debug('pouchdb:adapter')('Picked adapter: ' + opts.adapter);\n\n if (!PouchDB$5.adapters[opts.adapter] ||\n !PouchDB$5.adapters[opts.adapter].valid()) {\n throw new Error('Invalid Adapter: ' + opts.adapter);\n }\n\n AbstractPouchDB.call(self);\n self.taskqueue = new TaskQueue$1();\n\n self.adapter = opts.adapter;\n\n PouchDB$5.adapters[opts.adapter].call(self, opts, function (err) {\n if (err) {\n return self.taskqueue.fail(err);\n }\n prepareForDestruction(self);\n\n self.emit('created', self);\n PouchDB$5.emit('created', self.name);\n self.taskqueue.ready(self);\n });\n\n}\n\nPouchDB$5.debug = debug;\n\nPouchDB$5.adapters = {};\nPouchDB$5.preferredAdapters = [];\n\nPouchDB$5.prefix = '_pouch_';\n\nvar eventEmitter = new events.EventEmitter();\n\nfunction setUpEventEmitter(Pouch) {\n Object.keys(events.EventEmitter.prototype).forEach(function (key) {\n if (typeof events.EventEmitter.prototype[key] === 'function') {\n Pouch[key] = eventEmitter[key].bind(eventEmitter);\n }\n });\n\n // these are created in constructor.js, and allow us to notify each DB with\n // the same name that it was destroyed, via the constructor object\n var destructListeners = Pouch._destructionListeners = new ExportedMap();\n Pouch.on('destroyed', function onConstructorDestroyed(name) {\n destructListeners.get(name).forEach(function (callback) {\n callback();\n });\n destructListeners.delete(name);\n });\n}\n\nsetUpEventEmitter(PouchDB$5);\n\nPouchDB$5.adapter = function (id, obj, addToPreferredAdapters) {\n /* istanbul ignore else */\n if (obj.valid()) {\n PouchDB$5.adapters[id] = obj;\n if (addToPreferredAdapters) {\n PouchDB$5.preferredAdapters.push(id);\n }\n }\n};\n\nPouchDB$5.plugin = function (obj) {\n if (typeof obj === 'function') { // function style for plugins\n obj(PouchDB$5);\n } else if (typeof obj !== 'object' || Object.keys(obj).length === 0){\n throw new Error('Invalid plugin: got \\\"' + obj + '\\\", expected an object or a function');\n } else {\n Object.keys(obj).forEach(function (id) { // object style for plugins\n PouchDB$5.prototype[id] = obj[id];\n });\n }\n return PouchDB$5;\n};\n\nPouchDB$5.defaults = function (defaultOpts) {\n function PouchAlt(name, opts) {\n if (!(this instanceof PouchAlt)) {\n return new PouchAlt(name, opts);\n }\n\n opts = opts || {};\n\n if (name && typeof name === 'object') {\n opts = name;\n name = opts.name;\n delete opts.name;\n }\n\n opts = assign$1({}, PouchAlt.__defaults, opts);\n PouchDB$5.call(this, name, opts);\n }\n\n inherits(PouchAlt, PouchDB$5);\n\n PouchAlt.preferredAdapters = PouchDB$5.preferredAdapters.slice();\n Object.keys(PouchDB$5).forEach(function (key) {\n if (!(key in PouchAlt)) {\n PouchAlt[key] = PouchDB$5[key];\n }\n });\n\n // make default options transitive\n // https://github.com/pouchdb/pouchdb/issues/5922\n PouchAlt.__defaults = assign$1({}, this.__defaults, defaultOpts);\n\n return PouchAlt;\n};\n\n// managed automatically by set-version.js\nvar version = \"6.1.1\";\n\nPouchDB$5.version = version;\n\nfunction toObject(array) {\n return array.reduce(function (obj, item) {\n obj[item] = true;\n return obj;\n }, {});\n}\n// List of top level reserved words for doc\nvar reservedWords = toObject([\n '_id',\n '_rev',\n '_attachments',\n '_deleted',\n '_revisions',\n '_revs_info',\n '_conflicts',\n '_deleted_conflicts',\n '_local_seq',\n '_rev_tree',\n //replication documents\n '_replication_id',\n '_replication_state',\n '_replication_state_time',\n '_replication_state_reason',\n '_replication_stats',\n // Specific to Couchbase Sync Gateway\n '_removed'\n]);\n\n// List of reserved words that should end up the document\nvar dataWords = toObject([\n '_attachments',\n //replication documents\n '_replication_id',\n '_replication_state',\n '_replication_state_time',\n '_replication_state_reason',\n '_replication_stats'\n]);\n\nfunction parseRevisionInfo(rev) {\n if (!/^\\d+\\-./.test(rev)) {\n return createError(INVALID_REV);\n }\n var idx = rev.indexOf('-');\n var left = rev.substring(0, idx);\n var right = rev.substring(idx + 1);\n return {\n prefix: parseInt(left, 10),\n id: right\n };\n}\n\nfunction makeRevTreeFromRevisions(revisions, opts) {\n var pos = revisions.start - revisions.ids.length + 1;\n\n var revisionIds = revisions.ids;\n var ids = [revisionIds[0], opts, []];\n\n for (var i = 1, len = revisionIds.length; i < len; i++) {\n ids = [revisionIds[i], {status: 'missing'}, [ids]];\n }\n\n return [{\n pos: pos,\n ids: ids\n }];\n}\n\n// Preprocess documents, parse their revisions, assign an id and a\n// revision for new writes that are missing them, etc\nfunction parseDoc(doc, newEdits) {\n\n var nRevNum;\n var newRevId;\n var revInfo;\n var opts = {status: 'available'};\n if (doc._deleted) {\n opts.deleted = true;\n }\n\n if (newEdits) {\n if (!doc._id) {\n doc._id = uuid();\n }\n newRevId = uuid(32, 16).toLowerCase();\n if (doc._rev) {\n revInfo = parseRevisionInfo(doc._rev);\n if (revInfo.error) {\n return revInfo;\n }\n doc._rev_tree = [{\n pos: revInfo.prefix,\n ids: [revInfo.id, {status: 'missing'}, [[newRevId, opts, []]]]\n }];\n nRevNum = revInfo.prefix + 1;\n } else {\n doc._rev_tree = [{\n pos: 1,\n ids : [newRevId, opts, []]\n }];\n nRevNum = 1;\n }\n } else {\n if (doc._revisions) {\n doc._rev_tree = makeRevTreeFromRevisions(doc._revisions, opts);\n nRevNum = doc._revisions.start;\n newRevId = doc._revisions.ids[0];\n }\n if (!doc._rev_tree) {\n revInfo = parseRevisionInfo(doc._rev);\n if (revInfo.error) {\n return revInfo;\n }\n nRevNum = revInfo.prefix;\n newRevId = revInfo.id;\n doc._rev_tree = [{\n pos: nRevNum,\n ids: [newRevId, opts, []]\n }];\n }\n }\n\n invalidIdError(doc._id);\n\n doc._rev = nRevNum + '-' + newRevId;\n\n var result = {metadata : {}, data : {}};\n for (var key in doc) {\n /* istanbul ignore else */\n if (Object.prototype.hasOwnProperty.call(doc, key)) {\n var specialKey = key[0] === '_';\n if (specialKey && !reservedWords[key]) {\n var error = createError(DOC_VALIDATION, key);\n error.message = DOC_VALIDATION.message + ': ' + key;\n throw error;\n } else if (specialKey && !dataWords[key]) {\n result.metadata[key.slice(1)] = doc[key];\n } else {\n result.data[key] = doc[key];\n }\n }\n }\n return result;\n}\n\nvar thisAtob = function (str) {\n return atob(str);\n};\n\nvar thisBtoa = function (str) {\n return btoa(str);\n};\n\n// Abstracts constructing a Blob object, so it also works in older\n// browsers that don't support the native Blob constructor (e.g.\n// old QtWebKit versions, Android < 4.4).\nfunction createBlob(parts, properties) {\n /* global BlobBuilder,MSBlobBuilder,MozBlobBuilder,WebKitBlobBuilder */\n parts = parts || [];\n properties = properties || {};\n try {\n return new Blob(parts, properties);\n } catch (e) {\n if (e.name !== \"TypeError\") {\n throw e;\n }\n var Builder = typeof BlobBuilder !== 'undefined' ? BlobBuilder :\n typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder :\n typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder :\n WebKitBlobBuilder;\n var builder = new Builder();\n for (var i = 0; i < parts.length; i += 1) {\n builder.append(parts[i]);\n }\n return builder.getBlob(properties.type);\n }\n}\n\n// From http://stackoverflow.com/questions/14967647/ (continues on next line)\n// encode-decode-image-with-base64-breaks-image (2013-04-21)\nfunction binaryStringToArrayBuffer(bin) {\n var length = bin.length;\n var buf = new ArrayBuffer(length);\n var arr = new Uint8Array(buf);\n for (var i = 0; i < length; i++) {\n arr[i] = bin.charCodeAt(i);\n }\n return buf;\n}\n\nfunction binStringToBluffer(binString, type) {\n return createBlob([binaryStringToArrayBuffer(binString)], {type: type});\n}\n\nfunction b64ToBluffer(b64, type) {\n return binStringToBluffer(thisAtob(b64), type);\n}\n\n//Can't find original post, but this is close\n//http://stackoverflow.com/questions/6965107/ (continues on next line)\n//converting-between-strings-and-arraybuffers\nfunction arrayBufferToBinaryString(buffer) {\n var binary = '';\n var bytes = new Uint8Array(buffer);\n var length = bytes.byteLength;\n for (var i = 0; i < length; i++) {\n binary += String.fromCharCode(bytes[i]);\n }\n return binary;\n}\n\n// shim for browsers that don't support it\nfunction readAsBinaryString(blob, callback) {\n if (typeof FileReader === 'undefined') {\n // fix for Firefox in a web worker\n // https://bugzilla.mozilla.org/show_bug.cgi?id=901097\n return callback(arrayBufferToBinaryString(\n new FileReaderSync().readAsArrayBuffer(blob)));\n }\n\n var reader = new FileReader();\n var hasBinaryString = typeof reader.readAsBinaryString === 'function';\n reader.onloadend = function (e) {\n var result = e.target.result || '';\n if (hasBinaryString) {\n return callback(result);\n }\n callback(arrayBufferToBinaryString(result));\n };\n if (hasBinaryString) {\n reader.readAsBinaryString(blob);\n } else {\n reader.readAsArrayBuffer(blob);\n }\n}\n\nfunction blobToBinaryString(blobOrBuffer, callback) {\n readAsBinaryString(blobOrBuffer, function (bin) {\n callback(bin);\n });\n}\n\nfunction blobToBase64(blobOrBuffer, callback) {\n blobToBinaryString(blobOrBuffer, function (base64) {\n callback(thisBtoa(base64));\n });\n}\n\n// simplified API. universal browser support is assumed\nfunction readAsArrayBuffer(blob, callback) {\n if (typeof FileReader === 'undefined') {\n // fix for Firefox in a web worker:\n // https://bugzilla.mozilla.org/show_bug.cgi?id=901097\n return callback(new FileReaderSync().readAsArrayBuffer(blob));\n }\n\n var reader = new FileReader();\n reader.onloadend = function (e) {\n var result = e.target.result || new ArrayBuffer(0);\n callback(result);\n };\n reader.readAsArrayBuffer(blob);\n}\n\n// this is not used in the browser\n\nvar setImmediateShim = global.setImmediate || global.setTimeout;\nvar MD5_CHUNK_SIZE = 32768;\n\nfunction rawToBase64(raw) {\n return thisBtoa(raw);\n}\n\nfunction sliceBlob(blob$$1, start, end) {\n if (blob$$1.webkitSlice) {\n return blob$$1.webkitSlice(start, end);\n }\n return blob$$1.slice(start, end);\n}\n\nfunction appendBlob(buffer, blob$$1, start, end, callback) {\n if (start > 0 || end < blob$$1.size) {\n // only slice blob if we really need to\n blob$$1 = sliceBlob(blob$$1, start, end);\n }\n readAsArrayBuffer(blob$$1, function (arrayBuffer) {\n buffer.append(arrayBuffer);\n callback();\n });\n}\n\nfunction appendString(buffer, string, start, end, callback) {\n if (start > 0 || end < string.length) {\n // only create a substring if we really need to\n string = string.substring(start, end);\n }\n buffer.appendBinary(string);\n callback();\n}\n\nfunction binaryMd5(data, callback) {\n var inputIsString = typeof data === 'string';\n var len = inputIsString ? data.length : data.size;\n var chunkSize = Math.min(MD5_CHUNK_SIZE, len);\n var chunks = Math.ceil(len / chunkSize);\n var currentChunk = 0;\n var buffer = inputIsString ? new Md5() : new Md5.ArrayBuffer();\n\n var append = inputIsString ? appendString : appendBlob;\n\n function next() {\n setImmediateShim(loadNextChunk);\n }\n\n function done() {\n var raw = buffer.end(true);\n var base64 = rawToBase64(raw);\n callback(base64);\n buffer.destroy();\n }\n\n function loadNextChunk() {\n var start = currentChunk * chunkSize;\n var end = start + chunkSize;\n currentChunk++;\n if (currentChunk < chunks) {\n append(buffer, data, start, end, next);\n } else {\n append(buffer, data, start, end, done);\n }\n }\n loadNextChunk();\n}\n\nfunction stringMd5(string) {\n return Md5.hash(string);\n}\n\nfunction parseBase64(data) {\n try {\n return thisAtob(data);\n } catch (e) {\n var err = createError(BAD_ARG,\n 'Attachment is not a valid base64 string');\n return {error: err};\n }\n}\n\nfunction preprocessString(att, blobType, callback) {\n var asBinary = parseBase64(att.data);\n if (asBinary.error) {\n return callback(asBinary.error);\n }\n\n att.length = asBinary.length;\n if (blobType === 'blob') {\n att.data = binStringToBluffer(asBinary, att.content_type);\n } else if (blobType === 'base64') {\n att.data = thisBtoa(asBinary);\n } else { // binary\n att.data = asBinary;\n }\n binaryMd5(asBinary, function (result) {\n att.digest = 'md5-' + result;\n callback();\n });\n}\n\nfunction preprocessBlob(att, blobType, callback) {\n binaryMd5(att.data, function (md5) {\n att.digest = 'md5-' + md5;\n // size is for blobs (browser), length is for buffers (node)\n att.length = att.data.size || att.data.length || 0;\n if (blobType === 'binary') {\n blobToBinaryString(att.data, function (binString) {\n att.data = binString;\n callback();\n });\n } else if (blobType === 'base64') {\n blobToBase64(att.data, function (b64) {\n att.data = b64;\n callback();\n });\n } else {\n callback();\n }\n });\n}\n\nfunction preprocessAttachment(att, blobType, callback) {\n if (att.stub) {\n return callback();\n }\n if (typeof att.data === 'string') { // input is a base64 string\n preprocessString(att, blobType, callback);\n } else { // input is a blob\n preprocessBlob(att, blobType, callback);\n }\n}\n\nfunction preprocessAttachments(docInfos, blobType, callback) {\n\n if (!docInfos.length) {\n return callback();\n }\n\n var docv = 0;\n var overallErr;\n\n docInfos.forEach(function (docInfo) {\n var attachments = docInfo.data && docInfo.data._attachments ?\n Object.keys(docInfo.data._attachments) : [];\n var recv = 0;\n\n if (!attachments.length) {\n return done();\n }\n\n function processedAttachment(err) {\n overallErr = err;\n recv++;\n if (recv === attachments.length) {\n done();\n }\n }\n\n for (var key in docInfo.data._attachments) {\n if (docInfo.data._attachments.hasOwnProperty(key)) {\n preprocessAttachment(docInfo.data._attachments[key],\n blobType, processedAttachment);\n }\n }\n });\n\n function done() {\n docv++;\n if (docInfos.length === docv) {\n if (overallErr) {\n callback(overallErr);\n } else {\n callback();\n }\n }\n }\n}\n\nfunction updateDoc(revLimit, prev, docInfo, results,\n i, cb, writeDoc, newEdits) {\n\n if (revExists(prev.rev_tree, docInfo.metadata.rev)) {\n results[i] = docInfo;\n return cb();\n }\n\n // sometimes this is pre-calculated. historically not always\n var previousWinningRev = prev.winningRev || winningRev(prev);\n var previouslyDeleted = 'deleted' in prev ? prev.deleted :\n isDeleted(prev, previousWinningRev);\n var deleted = 'deleted' in docInfo.metadata ? docInfo.metadata.deleted :\n isDeleted(docInfo.metadata);\n var isRoot = /^1-/.test(docInfo.metadata.rev);\n\n if (previouslyDeleted && !deleted && newEdits && isRoot) {\n var newDoc = docInfo.data;\n newDoc._rev = previousWinningRev;\n newDoc._id = docInfo.metadata.id;\n docInfo = parseDoc(newDoc, newEdits);\n }\n\n var merged = merge(prev.rev_tree, docInfo.metadata.rev_tree[0], revLimit);\n\n var inConflict = newEdits && (((previouslyDeleted && deleted) ||\n (!previouslyDeleted && merged.conflicts !== 'new_leaf') ||\n (previouslyDeleted && !deleted && merged.conflicts === 'new_branch')));\n\n if (inConflict) {\n var err = createError(REV_CONFLICT);\n results[i] = err;\n return cb();\n }\n\n var newRev = docInfo.metadata.rev;\n docInfo.metadata.rev_tree = merged.tree;\n docInfo.stemmedRevs = merged.stemmedRevs || [];\n /* istanbul ignore else */\n if (prev.rev_map) {\n docInfo.metadata.rev_map = prev.rev_map; // used only by leveldb\n }\n\n // recalculate\n var winningRev$$1 = winningRev(docInfo.metadata);\n var winningRevIsDeleted = isDeleted(docInfo.metadata, winningRev$$1);\n\n // calculate the total number of documents that were added/removed,\n // from the perspective of total_rows/doc_count\n var delta = (previouslyDeleted === winningRevIsDeleted) ? 0 :\n previouslyDeleted < winningRevIsDeleted ? -1 : 1;\n\n var newRevIsDeleted;\n if (newRev === winningRev$$1) {\n // if the new rev is the same as the winning rev, we can reuse that value\n newRevIsDeleted = winningRevIsDeleted;\n } else {\n // if they're not the same, then we need to recalculate\n newRevIsDeleted = isDeleted(docInfo.metadata, newRev);\n }\n\n writeDoc(docInfo, winningRev$$1, winningRevIsDeleted, newRevIsDeleted,\n true, delta, i, cb);\n}\n\nfunction rootIsMissing(docInfo) {\n return docInfo.metadata.rev_tree[0].ids[1].status === 'missing';\n}\n\nfunction processDocs(revLimit, docInfos, api, fetchedDocs, tx, results,\n writeDoc, opts, overallCallback) {\n\n // Default to 1000 locally\n revLimit = revLimit || 1000;\n\n function insertDoc(docInfo, resultsIdx, callback) {\n // Cant insert new deleted documents\n var winningRev$$1 = winningRev(docInfo.metadata);\n var deleted = isDeleted(docInfo.metadata, winningRev$$1);\n if ('was_delete' in opts && deleted) {\n results[resultsIdx] = createError(MISSING_DOC, 'deleted');\n return callback();\n }\n\n // 4712 - detect whether a new document was inserted with a _rev\n var inConflict = newEdits && rootIsMissing(docInfo);\n\n if (inConflict) {\n var err = createError(REV_CONFLICT);\n results[resultsIdx] = err;\n return callback();\n }\n\n var delta = deleted ? 0 : 1;\n\n writeDoc(docInfo, winningRev$$1, deleted, deleted, false,\n delta, resultsIdx, callback);\n }\n\n var newEdits = opts.new_edits;\n var idsToDocs = new ExportedMap();\n\n var docsDone = 0;\n var docsToDo = docInfos.length;\n\n function checkAllDocsDone() {\n if (++docsDone === docsToDo && overallCallback) {\n overallCallback();\n }\n }\n\n docInfos.forEach(function (currentDoc, resultsIdx) {\n\n if (currentDoc._id && isLocalId(currentDoc._id)) {\n var fun = currentDoc._deleted ? '_removeLocal' : '_putLocal';\n api[fun](currentDoc, {ctx: tx}, function (err, res) {\n results[resultsIdx] = err || res;\n checkAllDocsDone();\n });\n return;\n }\n\n var id = currentDoc.metadata.id;\n if (idsToDocs.has(id)) {\n docsToDo--; // duplicate\n idsToDocs.get(id).push([currentDoc, resultsIdx]);\n } else {\n idsToDocs.set(id, [[currentDoc, resultsIdx]]);\n }\n });\n\n // in the case of new_edits, the user can provide multiple docs\n // with the same id. these need to be processed sequentially\n idsToDocs.forEach(function (docs, id) {\n var numDone = 0;\n\n function docWritten() {\n if (++numDone < docs.length) {\n nextDoc();\n } else {\n checkAllDocsDone();\n }\n }\n function nextDoc() {\n var value = docs[numDone];\n var currentDoc = value[0];\n var resultsIdx = value[1];\n\n if (fetchedDocs.has(id)) {\n updateDoc(revLimit, fetchedDocs.get(id), currentDoc, results,\n resultsIdx, docWritten, writeDoc, newEdits);\n } else {\n // Ensure stemming applies to new writes as well\n var merged = merge([], currentDoc.metadata.rev_tree[0], revLimit);\n currentDoc.metadata.rev_tree = merged.tree;\n currentDoc.stemmedRevs = merged.stemmedRevs || [];\n insertDoc(currentDoc, resultsIdx, docWritten);\n }\n }\n nextDoc();\n });\n}\n\n// IndexedDB requires a versioned database structure, so we use the\n// version here to manage migrations.\nvar ADAPTER_VERSION = 5;\n\n// The object stores created for each database\n// DOC_STORE stores the document meta data, its revision history and state\n// Keyed by document id\nvar DOC_STORE = 'document-store';\n// BY_SEQ_STORE stores a particular version of a document, keyed by its\n// sequence id\nvar BY_SEQ_STORE = 'by-sequence';\n// Where we store attachments\nvar ATTACH_STORE = 'attach-store';\n// Where we store many-to-many relations\n// between attachment digests and seqs\nvar ATTACH_AND_SEQ_STORE = 'attach-seq-store';\n\n// Where we store database-wide meta data in a single record\n// keyed by id: META_STORE\nvar META_STORE = 'meta-store';\n// Where we store local documents\nvar LOCAL_STORE = 'local-store';\n// Where we detect blob support\nvar DETECT_BLOB_SUPPORT_STORE = 'detect-blob-support';\n\nfunction safeJsonParse(str) {\n // This try/catch guards against stack overflow errors.\n // JSON.parse() is faster than vuvuzela.parse() but vuvuzela\n // cannot overflow.\n try {\n return JSON.parse(str);\n } catch (e) {\n /* istanbul ignore next */\n return vuvuzela.parse(str);\n }\n}\n\nfunction safeJsonStringify(json) {\n try {\n return JSON.stringify(json);\n } catch (e) {\n /* istanbul ignore next */\n return vuvuzela.stringify(json);\n }\n}\n\nfunction idbError(callback) {\n return function (evt) {\n var message = 'unknown_error';\n if (evt.target && evt.target.error) {\n message = evt.target.error.name || evt.target.error.message;\n }\n callback(createError(IDB_ERROR, message, evt.type));\n };\n}\n\n// Unfortunately, the metadata has to be stringified\n// when it is put into the database, because otherwise\n// IndexedDB can throw errors for deeply-nested objects.\n// Originally we just used JSON.parse/JSON.stringify; now\n// we use this custom vuvuzela library that avoids recursion.\n// If we could do it all over again, we'd probably use a\n// format for the revision trees other than JSON.\nfunction encodeMetadata(metadata, winningRev, deleted) {\n return {\n data: safeJsonStringify(metadata),\n winningRev: winningRev,\n deletedOrLocal: deleted ? '1' : '0',\n seq: metadata.seq, // highest seq for this doc\n id: metadata.id\n };\n}\n\nfunction decodeMetadata(storedObject) {\n if (!storedObject) {\n return null;\n }\n var metadata = safeJsonParse(storedObject.data);\n metadata.winningRev = storedObject.winningRev;\n metadata.deleted = storedObject.deletedOrLocal === '1';\n metadata.seq = storedObject.seq;\n return metadata;\n}\n\n// read the doc back out from the database. we don't store the\n// _id or _rev because we already have _doc_id_rev.\nfunction decodeDoc(doc) {\n if (!doc) {\n return doc;\n }\n var idx = doc._doc_id_rev.lastIndexOf(':');\n doc._id = doc._doc_id_rev.substring(0, idx - 1);\n doc._rev = doc._doc_id_rev.substring(idx + 1);\n delete doc._doc_id_rev;\n return doc;\n}\n\n// Read a blob from the database, encoding as necessary\n// and translating from base64 if the IDB doesn't support\n// native Blobs\nfunction readBlobData(body, type, asBlob, callback) {\n if (asBlob) {\n if (!body) {\n callback(createBlob([''], {type: type}));\n } else if (typeof body !== 'string') { // we have blob support\n callback(body);\n } else { // no blob support\n callback(b64ToBluffer(body, type));\n }\n } else { // as base64 string\n if (!body) {\n callback('');\n } else if (typeof body !== 'string') { // we have blob support\n readAsBinaryString(body, function (binary) {\n callback(thisBtoa(binary));\n });\n } else { // no blob support\n callback(body);\n }\n }\n}\n\nfunction fetchAttachmentsIfNecessary(doc, opts, txn, cb) {\n var attachments = Object.keys(doc._attachments || {});\n if (!attachments.length) {\n return cb && cb();\n }\n var numDone = 0;\n\n function checkDone() {\n if (++numDone === attachments.length && cb) {\n cb();\n }\n }\n\n function fetchAttachment(doc, att) {\n var attObj = doc._attachments[att];\n var digest = attObj.digest;\n var req = txn.objectStore(ATTACH_STORE).get(digest);\n req.onsuccess = function (e) {\n attObj.body = e.target.result.body;\n checkDone();\n };\n }\n\n attachments.forEach(function (att) {\n if (opts.attachments && opts.include_docs) {\n fetchAttachment(doc, att);\n } else {\n doc._attachments[att].stub = true;\n checkDone();\n }\n });\n}\n\n// IDB-specific postprocessing necessary because\n// we don't know whether we stored a true Blob or\n// a base64-encoded string, and if it's a Blob it\n// needs to be read outside of the transaction context\nfunction postProcessAttachments(results, asBlob) {\n return PouchPromise$1.all(results.map(function (row) {\n if (row.doc && row.doc._attachments) {\n var attNames = Object.keys(row.doc._attachments);\n return PouchPromise$1.all(attNames.map(function (att) {\n var attObj = row.doc._attachments[att];\n if (!('body' in attObj)) { // already processed\n return;\n }\n var body = attObj.body;\n var type = attObj.content_type;\n return new PouchPromise$1(function (resolve) {\n readBlobData(body, type, asBlob, function (data) {\n row.doc._attachments[att] = assign$1(\n pick(attObj, ['digest', 'content_type']),\n {data: data}\n );\n resolve();\n });\n });\n }));\n }\n }));\n}\n\nfunction compactRevs(revs, docId, txn) {\n\n var possiblyOrphanedDigests = [];\n var seqStore = txn.objectStore(BY_SEQ_STORE);\n var attStore = txn.objectStore(ATTACH_STORE);\n var attAndSeqStore = txn.objectStore(ATTACH_AND_SEQ_STORE);\n var count = revs.length;\n\n function checkDone() {\n count--;\n if (!count) { // done processing all revs\n deleteOrphanedAttachments();\n }\n }\n\n function deleteOrphanedAttachments() {\n if (!possiblyOrphanedDigests.length) {\n return;\n }\n possiblyOrphanedDigests.forEach(function (digest) {\n var countReq = attAndSeqStore.index('digestSeq').count(\n IDBKeyRange.bound(\n digest + '::', digest + '::\\uffff', false, false));\n countReq.onsuccess = function (e) {\n var count = e.target.result;\n if (!count) {\n // orphaned\n attStore.delete(digest);\n }\n };\n });\n }\n\n revs.forEach(function (rev) {\n var index = seqStore.index('_doc_id_rev');\n var key = docId + \"::\" + rev;\n index.getKey(key).onsuccess = function (e) {\n var seq = e.target.result;\n if (typeof seq !== 'number') {\n return checkDone();\n }\n seqStore.delete(seq);\n\n var cursor = attAndSeqStore.index('seq')\n .openCursor(IDBKeyRange.only(seq));\n\n cursor.onsuccess = function (event) {\n var cursor = event.target.result;\n if (cursor) {\n var digest = cursor.value.digestSeq.split('::')[0];\n possiblyOrphanedDigests.push(digest);\n attAndSeqStore.delete(cursor.primaryKey);\n cursor.continue();\n } else { // done\n checkDone();\n }\n };\n };\n });\n}\n\nfunction openTransactionSafely(idb, stores, mode) {\n try {\n return {\n txn: idb.transaction(stores, mode)\n };\n } catch (err) {\n return {\n error: err\n };\n }\n}\n\nvar changesHandler$$1 = new Changes();\n\nfunction idbBulkDocs(dbOpts, req, opts, api, idb, callback) {\n var docInfos = req.docs;\n var txn;\n var docStore;\n var bySeqStore;\n var attachStore;\n var attachAndSeqStore;\n var metaStore;\n var docInfoError;\n var metaDoc;\n\n for (var i = 0, len = docInfos.length; i < len; i++) {\n var doc = docInfos[i];\n if (doc._id && isLocalId(doc._id)) {\n continue;\n }\n doc = docInfos[i] = parseDoc(doc, opts.new_edits);\n if (doc.error && !docInfoError) {\n docInfoError = doc;\n }\n }\n\n if (docInfoError) {\n return callback(docInfoError);\n }\n\n var allDocsProcessed = false;\n var docCountDelta = 0;\n var results = new Array(docInfos.length);\n var fetchedDocs = new ExportedMap();\n var preconditionErrored = false;\n var blobType = api._meta.blobSupport ? 'blob' : 'base64';\n\n preprocessAttachments(docInfos, blobType, function (err) {\n if (err) {\n return callback(err);\n }\n startTransaction();\n });\n\n function startTransaction() {\n\n var stores = [\n DOC_STORE, BY_SEQ_STORE,\n ATTACH_STORE,\n LOCAL_STORE, ATTACH_AND_SEQ_STORE,\n META_STORE\n ];\n var txnResult = openTransactionSafely(idb, stores, 'readwrite');\n if (txnResult.error) {\n return callback(txnResult.error);\n }\n txn = txnResult.txn;\n txn.onabort = idbError(callback);\n txn.ontimeout = idbError(callback);\n txn.oncomplete = complete;\n docStore = txn.objectStore(DOC_STORE);\n bySeqStore = txn.objectStore(BY_SEQ_STORE);\n attachStore = txn.objectStore(ATTACH_STORE);\n attachAndSeqStore = txn.objectStore(ATTACH_AND_SEQ_STORE);\n metaStore = txn.objectStore(META_STORE);\n\n metaStore.get(META_STORE).onsuccess = function (e) {\n metaDoc = e.target.result;\n updateDocCountIfReady();\n };\n\n verifyAttachments(function (err) {\n if (err) {\n preconditionErrored = true;\n return callback(err);\n }\n fetchExistingDocs();\n });\n }\n\n function onAllDocsProcessed() {\n allDocsProcessed = true;\n updateDocCountIfReady();\n }\n\n function idbProcessDocs() {\n processDocs(dbOpts.revs_limit, docInfos, api, fetchedDocs,\n txn, results, writeDoc, opts, onAllDocsProcessed);\n }\n\n function updateDocCountIfReady() {\n if (!metaDoc || !allDocsProcessed) {\n return;\n }\n // caching the docCount saves a lot of time in allDocs() and\n // info(), which is why we go to all the trouble of doing this\n metaDoc.docCount += docCountDelta;\n metaStore.put(metaDoc);\n }\n\n function fetchExistingDocs() {\n\n if (!docInfos.length) {\n return;\n }\n\n var numFetched = 0;\n\n function checkDone() {\n if (++numFetched === docInfos.length) {\n idbProcessDocs();\n }\n }\n\n function readMetadata(event) {\n var metadata = decodeMetadata(event.target.result);\n\n if (metadata) {\n fetchedDocs.set(metadata.id, metadata);\n }\n checkDone();\n }\n\n for (var i = 0, len = docInfos.length; i < len; i++) {\n var docInfo = docInfos[i];\n if (docInfo._id && isLocalId(docInfo._id)) {\n checkDone(); // skip local docs\n continue;\n }\n var req = docStore.get(docInfo.metadata.id);\n req.onsuccess = readMetadata;\n }\n }\n\n function complete() {\n if (preconditionErrored) {\n return;\n }\n\n changesHandler$$1.notify(api._meta.name);\n callback(null, results);\n }\n\n function verifyAttachment(digest, callback) {\n\n var req = attachStore.get(digest);\n req.onsuccess = function (e) {\n if (!e.target.result) {\n var err = createError(MISSING_STUB,\n 'unknown stub attachment with digest ' +\n digest);\n err.status = 412;\n callback(err);\n } else {\n callback();\n }\n };\n }\n\n function verifyAttachments(finish) {\n\n\n var digests = [];\n docInfos.forEach(function (docInfo) {\n if (docInfo.data && docInfo.data._attachments) {\n Object.keys(docInfo.data._attachments).forEach(function (filename) {\n var att = docInfo.data._attachments[filename];\n if (att.stub) {\n digests.push(att.digest);\n }\n });\n }\n });\n if (!digests.length) {\n return finish();\n }\n var numDone = 0;\n var err;\n\n function checkDone() {\n if (++numDone === digests.length) {\n finish(err);\n }\n }\n digests.forEach(function (digest) {\n verifyAttachment(digest, function (attErr) {\n if (attErr && !err) {\n err = attErr;\n }\n checkDone();\n });\n });\n }\n\n function writeDoc(docInfo, winningRev$$1, winningRevIsDeleted, newRevIsDeleted,\n isUpdate, delta, resultsIdx, callback) {\n\n docInfo.metadata.winningRev = winningRev$$1;\n docInfo.metadata.deleted = winningRevIsDeleted;\n\n var doc = docInfo.data;\n doc._id = docInfo.metadata.id;\n doc._rev = docInfo.metadata.rev;\n\n if (newRevIsDeleted) {\n doc._deleted = true;\n }\n\n var hasAttachments = doc._attachments &&\n Object.keys(doc._attachments).length;\n if (hasAttachments) {\n return writeAttachments(docInfo, winningRev$$1, winningRevIsDeleted,\n isUpdate, resultsIdx, callback);\n }\n\n docCountDelta += delta;\n updateDocCountIfReady();\n\n finishDoc(docInfo, winningRev$$1, winningRevIsDeleted,\n isUpdate, resultsIdx, callback);\n }\n\n function finishDoc(docInfo, winningRev$$1, winningRevIsDeleted,\n isUpdate, resultsIdx, callback) {\n\n var doc = docInfo.data;\n var metadata = docInfo.metadata;\n\n doc._doc_id_rev = metadata.id + '::' + metadata.rev;\n delete doc._id;\n delete doc._rev;\n\n function afterPutDoc(e) {\n var revsToDelete = docInfo.stemmedRevs || [];\n\n if (isUpdate && api.auto_compaction) {\n revsToDelete = revsToDelete.concat(compactTree(docInfo.metadata));\n }\n\n if (revsToDelete && revsToDelete.length) {\n compactRevs(revsToDelete, docInfo.metadata.id, txn);\n }\n\n metadata.seq = e.target.result;\n // Current _rev is calculated from _rev_tree on read\n // delete metadata.rev;\n var metadataToStore = encodeMetadata(metadata, winningRev$$1,\n winningRevIsDeleted);\n var metaDataReq = docStore.put(metadataToStore);\n metaDataReq.onsuccess = afterPutMetadata;\n }\n\n function afterPutDocError(e) {\n // ConstraintError, need to update, not put (see #1638 for details)\n e.preventDefault(); // avoid transaction abort\n e.stopPropagation(); // avoid transaction onerror\n var index = bySeqStore.index('_doc_id_rev');\n var getKeyReq = index.getKey(doc._doc_id_rev);\n getKeyReq.onsuccess = function (e) {\n var putReq = bySeqStore.put(doc, e.target.result);\n putReq.onsuccess = afterPutDoc;\n };\n }\n\n function afterPutMetadata() {\n results[resultsIdx] = {\n ok: true,\n id: metadata.id,\n rev: metadata.rev\n };\n fetchedDocs.set(docInfo.metadata.id, docInfo.metadata);\n insertAttachmentMappings(docInfo, metadata.seq, callback);\n }\n\n var putReq = bySeqStore.put(doc);\n\n putReq.onsuccess = afterPutDoc;\n putReq.onerror = afterPutDocError;\n }\n\n function writeAttachments(docInfo, winningRev$$1, winningRevIsDeleted,\n isUpdate, resultsIdx, callback) {\n\n\n var doc = docInfo.data;\n\n var numDone = 0;\n var attachments = Object.keys(doc._attachments);\n\n function collectResults() {\n if (numDone === attachments.length) {\n finishDoc(docInfo, winningRev$$1, winningRevIsDeleted,\n isUpdate, resultsIdx, callback);\n }\n }\n\n function attachmentSaved() {\n numDone++;\n collectResults();\n }\n\n attachments.forEach(function (key) {\n var att = docInfo.data._attachments[key];\n if (!att.stub) {\n var data = att.data;\n delete att.data;\n att.revpos = parseInt(winningRev$$1, 10);\n var digest = att.digest;\n saveAttachment(digest, data, attachmentSaved);\n } else {\n numDone++;\n collectResults();\n }\n });\n }\n\n // map seqs to attachment digests, which\n // we will need later during compaction\n function insertAttachmentMappings(docInfo, seq, callback) {\n\n var attsAdded = 0;\n var attsToAdd = Object.keys(docInfo.data._attachments || {});\n\n if (!attsToAdd.length) {\n return callback();\n }\n\n function checkDone() {\n if (++attsAdded === attsToAdd.length) {\n callback();\n }\n }\n\n function add(att) {\n var digest = docInfo.data._attachments[att].digest;\n var req = attachAndSeqStore.put({\n seq: seq,\n digestSeq: digest + '::' + seq\n });\n\n req.onsuccess = checkDone;\n req.onerror = function (e) {\n // this callback is for a constaint error, which we ignore\n // because this docid/rev has already been associated with\n // the digest (e.g. when new_edits == false)\n e.preventDefault(); // avoid transaction abort\n e.stopPropagation(); // avoid transaction onerror\n checkDone();\n };\n }\n for (var i = 0; i < attsToAdd.length; i++) {\n add(attsToAdd[i]); // do in parallel\n }\n }\n\n function saveAttachment(digest, data, callback) {\n\n\n var getKeyReq = attachStore.count(digest);\n getKeyReq.onsuccess = function (e) {\n var count = e.target.result;\n if (count) {\n return callback(); // already exists\n }\n var newAtt = {\n digest: digest,\n body: data\n };\n var putReq = attachStore.put(newAtt);\n putReq.onsuccess = callback;\n };\n }\n}\n\n// Abstraction over IDBCursor and getAll()/getAllKeys() that allows us to batch our operations\n// while falling back to a normal IDBCursor operation on browsers that don't support getAll() or\n// getAllKeys(). This allows for a much faster implementation than just straight-up cursors, because\n// we're not processing each document one-at-a-time.\nfunction runBatchedCursor(objectStore, keyRange, descending, batchSize, onBatch) {\n\n // Bail out of getAll()/getAllKeys() in the following cases:\n // 1) either method is unsupported - we need both\n // 2) batchSize is 1 (might as well use IDBCursor), or batchSize is -1 (i.e. batchSize unlimited,\n // not really clear the user wants a batched approach where the entire DB is read into memory,\n // perhaps they are filtering on a per-doc basis)\n // 3) descending – no real way to do this via getAll()/getAllKeys()\n\n var useGetAll = typeof objectStore.getAll === 'function' &&\n typeof objectStore.getAllKeys === 'function' &&\n batchSize > 1 && !descending;\n\n var keysBatch;\n var valuesBatch;\n var pseudoCursor;\n\n function onGetAll(e) {\n valuesBatch = e.target.result;\n if (keysBatch) {\n onBatch(keysBatch, valuesBatch, pseudoCursor);\n }\n }\n\n function onGetAllKeys(e) {\n keysBatch = e.target.result;\n if (valuesBatch) {\n onBatch(keysBatch, valuesBatch, pseudoCursor);\n }\n }\n\n function continuePseudoCursor() {\n if (!keysBatch.length) { // no more results\n return onBatch();\n }\n // fetch next batch, exclusive start\n var lastKey = keysBatch[keysBatch.length - 1];\n var newKeyRange;\n if (keyRange && keyRange.upper) {\n try {\n newKeyRange = IDBKeyRange.bound(lastKey, keyRange.upper,\n true, keyRange.upperOpen);\n } catch (e) {\n if (e.name === \"DataError\" && e.code === 0) {\n return onBatch(); // we're done, startkey and endkey are equal\n }\n }\n } else {\n newKeyRange = IDBKeyRange.lowerBound(lastKey, true);\n }\n keyRange = newKeyRange;\n keysBatch = null;\n valuesBatch = null;\n objectStore.getAll(keyRange, batchSize).onsuccess = onGetAll;\n objectStore.getAllKeys(keyRange, batchSize).onsuccess = onGetAllKeys;\n }\n\n function onCursor(e) {\n var cursor = e.target.result;\n if (!cursor) { // done\n return onBatch();\n }\n // regular IDBCursor acts like a batch where batch size is always 1\n onBatch([cursor.key], [cursor.value], cursor);\n }\n\n if (useGetAll) {\n pseudoCursor = {\"continue\": continuePseudoCursor};\n objectStore.getAll(keyRange, batchSize).onsuccess = onGetAll;\n objectStore.getAllKeys(keyRange, batchSize).onsuccess = onGetAllKeys;\n } else if (descending) {\n objectStore.openCursor(keyRange, 'prev').onsuccess = onCursor;\n } else {\n objectStore.openCursor(keyRange).onsuccess = onCursor;\n }\n}\n\n// simple shim for objectStore.getAll(), falling back to IDBCursor\nfunction getAll(objectStore, keyRange, onSuccess) {\n if (typeof objectStore.getAll === 'function') {\n // use native getAll\n objectStore.getAll(keyRange).onsuccess = onSuccess;\n return;\n }\n // fall back to cursors\n var values = [];\n\n function onCursor(e) {\n var cursor = e.target.result;\n if (cursor) {\n values.push(cursor.value);\n cursor.continue();\n } else {\n onSuccess({\n target: {\n result: values\n }\n });\n }\n }\n\n objectStore.openCursor(keyRange).onsuccess = onCursor;\n}\n\nfunction createKeyRange(start, end, inclusiveEnd, key, descending) {\n try {\n if (start && end) {\n if (descending) {\n return IDBKeyRange.bound(end, start, !inclusiveEnd, false);\n } else {\n return IDBKeyRange.bound(start, end, false, !inclusiveEnd);\n }\n } else if (start) {\n if (descending) {\n return IDBKeyRange.upperBound(start);\n } else {\n return IDBKeyRange.lowerBound(start);\n }\n } else if (end) {\n if (descending) {\n return IDBKeyRange.lowerBound(end, !inclusiveEnd);\n } else {\n return IDBKeyRange.upperBound(end, !inclusiveEnd);\n }\n } else if (key) {\n return IDBKeyRange.only(key);\n }\n } catch (e) {\n return {error: e};\n }\n return null;\n}\n\nfunction idbAllDocs(opts, idb, callback) {\n var start = 'startkey' in opts ? opts.startkey : false;\n var end = 'endkey' in opts ? opts.endkey : false;\n var key = 'key' in opts ? opts.key : false;\n var skip = opts.skip || 0;\n var limit = typeof opts.limit === 'number' ? opts.limit : -1;\n var inclusiveEnd = opts.inclusive_end !== false;\n\n var keyRange = createKeyRange(start, end, inclusiveEnd, key, opts.descending);\n var keyRangeError = keyRange && keyRange.error;\n if (keyRangeError && !(keyRangeError.name === \"DataError\" &&\n keyRangeError.code === 0)) {\n // DataError with error code 0 indicates start is less than end, so\n // can just do an empty query. Else need to throw\n return callback(createError(IDB_ERROR,\n keyRangeError.name, keyRangeError.message));\n }\n\n var stores = [DOC_STORE, BY_SEQ_STORE, META_STORE];\n\n if (opts.attachments) {\n stores.push(ATTACH_STORE);\n }\n var txnResult = openTransactionSafely(idb, stores, 'readonly');\n if (txnResult.error) {\n return callback(txnResult.error);\n }\n var txn = txnResult.txn;\n txn.oncomplete = onTxnComplete;\n txn.onabort = idbError(callback);\n var docStore = txn.objectStore(DOC_STORE);\n var seqStore = txn.objectStore(BY_SEQ_STORE);\n var metaStore = txn.objectStore(META_STORE);\n var docIdRevIndex = seqStore.index('_doc_id_rev');\n var results = [];\n var docCount;\n\n metaStore.get(META_STORE).onsuccess = function (e) {\n docCount = e.target.result.docCount;\n };\n\n // if the user specifies include_docs=true, then we don't\n // want to block the main cursor while we're fetching the doc\n function fetchDocAsynchronously(metadata, row, winningRev$$1) {\n var key = metadata.id + \"::\" + winningRev$$1;\n docIdRevIndex.get(key).onsuccess = function onGetDoc(e) {\n row.doc = decodeDoc(e.target.result);\n if (opts.conflicts) {\n var conflicts = collectConflicts(metadata);\n if (conflicts.length) {\n row.doc._conflicts = conflicts;\n }\n }\n fetchAttachmentsIfNecessary(row.doc, opts, txn);\n };\n }\n\n function allDocsInner(winningRev$$1, metadata) {\n var row = {\n id: metadata.id,\n key: metadata.id,\n value: {\n rev: winningRev$$1\n }\n };\n var deleted = metadata.deleted;\n if (opts.deleted === 'ok') {\n results.push(row);\n // deleted docs are okay with \"keys\" requests\n if (deleted) {\n row.value.deleted = true;\n row.doc = null;\n } else if (opts.include_docs) {\n fetchDocAsynchronously(metadata, row, winningRev$$1);\n }\n } else if (!deleted && skip-- <= 0) {\n results.push(row);\n if (opts.include_docs) {\n fetchDocAsynchronously(metadata, row, winningRev$$1);\n }\n }\n }\n\n function processBatch(batchValues) {\n for (var i = 0, len = batchValues.length; i < len; i++) {\n if (results.length === limit) {\n break;\n }\n var batchValue = batchValues[i];\n var metadata = decodeMetadata(batchValue);\n var winningRev$$1 = metadata.winningRev;\n allDocsInner(winningRev$$1, metadata);\n }\n }\n\n function onBatch(batchKeys, batchValues, cursor) {\n if (!cursor) {\n return;\n }\n processBatch(batchValues);\n if (results.length < limit) {\n cursor.continue();\n }\n }\n\n function onGetAll(e) {\n var values = e.target.result;\n if (opts.descending) {\n values = values.reverse();\n }\n processBatch(values);\n }\n\n function onResultsReady() {\n callback(null, {\n total_rows: docCount,\n offset: opts.skip,\n rows: results\n });\n }\n\n function onTxnComplete() {\n if (opts.attachments) {\n postProcessAttachments(results, opts.binary).then(onResultsReady);\n } else {\n onResultsReady();\n }\n }\n\n // don't bother doing any requests if start > end or limit === 0\n if (keyRangeError || limit === 0) {\n return;\n }\n if (limit === -1) { // just fetch everything\n return getAll(docStore, keyRange, onGetAll);\n }\n // else do a cursor\n // choose a batch size based on the skip, since we'll need to skip that many\n runBatchedCursor(docStore, keyRange, opts.descending, limit + skip, onBatch);\n}\n\n//\n// Blobs are not supported in all versions of IndexedDB, notably\n// Chrome <37 and Android <5. In those versions, storing a blob will throw.\n//\n// Various other blob bugs exist in Chrome v37-42 (inclusive).\n// Detecting them is expensive and confusing to users, and Chrome 37-42\n// is at very low usage worldwide, so we do a hacky userAgent check instead.\n//\n// content-type bug: https://code.google.com/p/chromium/issues/detail?id=408120\n// 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916\n// FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836\n//\nfunction checkBlobSupport(txn) {\n return new PouchPromise$1(function (resolve) {\n var blob$$1 = createBlob(['']);\n var req = txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob$$1, 'key');\n\n req.onsuccess = function () {\n var matchedChrome = navigator.userAgent.match(/Chrome\\/(\\d+)/);\n var matchedEdge = navigator.userAgent.match(/Edge\\//);\n // MS Edge pretends to be Chrome 42:\n // https://msdn.microsoft.com/en-us/library/hh869301%28v=vs.85%29.aspx\n resolve(matchedEdge || !matchedChrome ||\n parseInt(matchedChrome[1], 10) >= 43);\n };\n\n txn.onabort = function (e) {\n // If the transaction aborts now its due to not being able to\n // write to the database, likely due to the disk being full\n e.preventDefault();\n e.stopPropagation();\n resolve(false);\n };\n }).catch(function () {\n return false; // error, so assume unsupported\n });\n}\n\nfunction countDocs(txn, cb) {\n var index = txn.objectStore(DOC_STORE).index('deletedOrLocal');\n index.count(IDBKeyRange.only('0')).onsuccess = function (e) {\n cb(e.target.result);\n };\n}\n\n// This task queue ensures that IDB open calls are done in their own tick\n// and sequentially - i.e. we wait for the async IDB open to *fully* complete\n// before calling the next one. This works around IE/Edge race conditions in IDB.\n\nvar running = false;\nvar queue = [];\n\nfunction tryCode(fun, err, res, PouchDB) {\n try {\n fun(err, res);\n } catch (err) {\n // Shouldn't happen, but in some odd cases\n // IndexedDB implementations might throw a sync\n // error, in which case this will at least log it.\n PouchDB.emit('error', err);\n }\n}\n\nfunction applyNext() {\n if (running || !queue.length) {\n return;\n }\n running = true;\n queue.shift()();\n}\n\nfunction enqueueTask(action, callback, PouchDB) {\n queue.push(function runAction() {\n action(function runCallback(err, res) {\n tryCode(callback, err, res, PouchDB);\n running = false;\n nextTick(function runNext() {\n applyNext(PouchDB);\n });\n });\n });\n applyNext();\n}\n\nfunction changes(opts, api, dbName, idb) {\n opts = clone(opts);\n\n if (opts.continuous) {\n var id = dbName + ':' + uuid();\n changesHandler$$1.addListener(dbName, id, api, opts);\n changesHandler$$1.notify(dbName);\n return {\n cancel: function () {\n changesHandler$$1.removeListener(dbName, id);\n }\n };\n }\n\n var docIds = opts.doc_ids && new ExportedSet(opts.doc_ids);\n\n opts.since = opts.since || 0;\n var lastSeq = opts.since;\n\n var limit = 'limit' in opts ? opts.limit : -1;\n if (limit === 0) {\n limit = 1; // per CouchDB _changes spec\n }\n var returnDocs;\n if ('return_docs' in opts) {\n returnDocs = opts.return_docs;\n } else if ('returnDocs' in opts) {\n // TODO: Remove 'returnDocs' in favor of 'return_docs' in a future release\n returnDocs = opts.returnDocs;\n } else {\n returnDocs = true;\n }\n\n var results = [];\n var numResults = 0;\n var filter = filterChange(opts);\n var docIdsToMetadata = new ExportedMap();\n\n var txn;\n var bySeqStore;\n var docStore;\n var docIdRevIndex;\n\n function onBatch(batchKeys, batchValues, cursor) {\n if (!cursor || !batchKeys.length) { // done\n return;\n }\n\n var winningDocs = new Array(batchKeys.length);\n var metadatas = new Array(batchKeys.length);\n\n function processMetadataAndWinningDoc(metadata, winningDoc) {\n var change = opts.processChange(winningDoc, metadata, opts);\n lastSeq = change.seq = metadata.seq;\n\n var filtered = filter(change);\n if (typeof filtered === 'object') { // anything but true/false indicates error\n return opts.complete(filtered);\n }\n\n if (filtered) {\n numResults++;\n if (returnDocs) {\n results.push(change);\n }\n // process the attachment immediately\n // for the benefit of live listeners\n if (opts.attachments && opts.include_docs) {\n fetchAttachmentsIfNecessary(winningDoc, opts, txn, function () {\n postProcessAttachments([change], opts.binary).then(function () {\n opts.onChange(change);\n });\n });\n } else {\n opts.onChange(change);\n }\n }\n }\n\n function onBatchDone() {\n for (var i = 0, len = winningDocs.length; i < len; i++) {\n if (numResults === limit) {\n break;\n }\n var winningDoc = winningDocs[i];\n if (!winningDoc) {\n continue;\n }\n var metadata = metadatas[i];\n processMetadataAndWinningDoc(metadata, winningDoc);\n }\n\n if (numResults !== limit) {\n cursor.continue();\n }\n }\n\n // Fetch all metadatas/winningdocs from this batch in parallel, then process\n // them all only once all data has been collected. This is done in parallel\n // because it's faster than doing it one-at-a-time.\n var numDone = 0;\n batchValues.forEach(function (value, i) {\n var doc = decodeDoc(value);\n var seq = batchKeys[i];\n fetchWinningDocAndMetadata(doc, seq, function (metadata, winningDoc) {\n metadatas[i] = metadata;\n winningDocs[i] = winningDoc;\n if (++numDone === batchKeys.length) {\n onBatchDone();\n }\n });\n });\n }\n\n function onGetMetadata(doc, seq, metadata, cb) {\n if (metadata.seq !== seq) {\n // some other seq is later\n return cb();\n }\n\n if (metadata.winningRev === doc._rev) {\n // this is the winning doc\n return cb(metadata, doc);\n }\n\n // fetch winning doc in separate request\n var docIdRev = doc._id + '::' + metadata.winningRev;\n var req = docIdRevIndex.get(docIdRev);\n req.onsuccess = function (e) {\n cb(metadata, decodeDoc(e.target.result));\n };\n }\n\n function fetchWinningDocAndMetadata(doc, seq, cb) {\n if (docIds && !docIds.has(doc._id)) {\n return cb();\n }\n\n var metadata = docIdsToMetadata.get(doc._id);\n if (metadata) { // cached\n return onGetMetadata(doc, seq, metadata, cb);\n }\n // metadata not cached, have to go fetch it\n docStore.get(doc._id).onsuccess = function (e) {\n metadata = decodeMetadata(e.target.result);\n docIdsToMetadata.set(doc._id, metadata);\n onGetMetadata(doc, seq, metadata, cb);\n };\n }\n\n function finish() {\n opts.complete(null, {\n results: results,\n last_seq: lastSeq\n });\n }\n\n function onTxnComplete() {\n if (!opts.continuous && opts.attachments) {\n // cannot guarantee that postProcessing was already done,\n // so do it again\n postProcessAttachments(results).then(finish);\n } else {\n finish();\n }\n }\n\n var objectStores = [DOC_STORE, BY_SEQ_STORE];\n if (opts.attachments) {\n objectStores.push(ATTACH_STORE);\n }\n var txnResult = openTransactionSafely(idb, objectStores, 'readonly');\n if (txnResult.error) {\n return opts.complete(txnResult.error);\n }\n txn = txnResult.txn;\n txn.onabort = idbError(opts.complete);\n txn.oncomplete = onTxnComplete;\n\n bySeqStore = txn.objectStore(BY_SEQ_STORE);\n docStore = txn.objectStore(DOC_STORE);\n docIdRevIndex = bySeqStore.index('_doc_id_rev');\n\n var keyRange = (opts.since && !opts.descending) ?\n IDBKeyRange.lowerBound(opts.since, true) : null;\n\n runBatchedCursor(bySeqStore, keyRange, opts.descending, limit, onBatch);\n}\n\nvar cachedDBs = new ExportedMap();\nvar blobSupportPromise;\nvar openReqList = new ExportedMap();\n\nfunction IdbPouch(opts, callback) {\n var api = this;\n\n enqueueTask(function (thisCallback) {\n init(api, opts, thisCallback);\n }, callback, api.constructor);\n}\n\nfunction init(api, opts, callback) {\n\n var dbName = opts.name;\n\n var idb = null;\n api._meta = null;\n\n // called when creating a fresh new database\n function createSchema(db) {\n var docStore = db.createObjectStore(DOC_STORE, {keyPath : 'id'});\n db.createObjectStore(BY_SEQ_STORE, {autoIncrement: true})\n .createIndex('_doc_id_rev', '_doc_id_rev', {unique: true});\n db.createObjectStore(ATTACH_STORE, {keyPath: 'digest'});\n db.createObjectStore(META_STORE, {keyPath: 'id', autoIncrement: false});\n db.createObjectStore(DETECT_BLOB_SUPPORT_STORE);\n\n // added in v2\n docStore.createIndex('deletedOrLocal', 'deletedOrLocal', {unique : false});\n\n // added in v3\n db.createObjectStore(LOCAL_STORE, {keyPath: '_id'});\n\n // added in v4\n var attAndSeqStore = db.createObjectStore(ATTACH_AND_SEQ_STORE,\n {autoIncrement: true});\n attAndSeqStore.createIndex('seq', 'seq');\n attAndSeqStore.createIndex('digestSeq', 'digestSeq', {unique: true});\n }\n\n // migration to version 2\n // unfortunately \"deletedOrLocal\" is a misnomer now that we no longer\n // store local docs in the main doc-store, but whaddyagonnado\n function addDeletedOrLocalIndex(txn, callback) {\n var docStore = txn.objectStore(DOC_STORE);\n docStore.createIndex('deletedOrLocal', 'deletedOrLocal', {unique : false});\n\n docStore.openCursor().onsuccess = function (event) {\n var cursor = event.target.result;\n if (cursor) {\n var metadata = cursor.value;\n var deleted = isDeleted(metadata);\n metadata.deletedOrLocal = deleted ? \"1\" : \"0\";\n docStore.put(metadata);\n cursor.continue();\n } else {\n callback();\n }\n };\n }\n\n // migration to version 3 (part 1)\n function createLocalStoreSchema(db) {\n db.createObjectStore(LOCAL_STORE, {keyPath: '_id'})\n .createIndex('_doc_id_rev', '_doc_id_rev', {unique: true});\n }\n\n // migration to version 3 (part 2)\n function migrateLocalStore(txn, cb) {\n var localStore = txn.objectStore(LOCAL_STORE);\n var docStore = txn.objectStore(DOC_STORE);\n var seqStore = txn.objectStore(BY_SEQ_STORE);\n\n var cursor = docStore.openCursor();\n cursor.onsuccess = function (event) {\n var cursor = event.target.result;\n if (cursor) {\n var metadata = cursor.value;\n var docId = metadata.id;\n var local = isLocalId(docId);\n var rev = winningRev(metadata);\n if (local) {\n var docIdRev = docId + \"::\" + rev;\n // remove all seq entries\n // associated with this docId\n var start = docId + \"::\";\n var end = docId + \"::~\";\n var index = seqStore.index('_doc_id_rev');\n var range = IDBKeyRange.bound(start, end, false, false);\n var seqCursor = index.openCursor(range);\n seqCursor.onsuccess = function (e) {\n seqCursor = e.target.result;\n if (!seqCursor) {\n // done\n docStore.delete(cursor.primaryKey);\n cursor.continue();\n } else {\n var data = seqCursor.value;\n if (data._doc_id_rev === docIdRev) {\n localStore.put(data);\n }\n seqStore.delete(seqCursor.primaryKey);\n seqCursor.continue();\n }\n };\n } else {\n cursor.continue();\n }\n } else if (cb) {\n cb();\n }\n };\n }\n\n // migration to version 4 (part 1)\n function addAttachAndSeqStore(db) {\n var attAndSeqStore = db.createObjectStore(ATTACH_AND_SEQ_STORE,\n {autoIncrement: true});\n attAndSeqStore.createIndex('seq', 'seq');\n attAndSeqStore.createIndex('digestSeq', 'digestSeq', {unique: true});\n }\n\n // migration to version 4 (part 2)\n function migrateAttsAndSeqs(txn, callback) {\n var seqStore = txn.objectStore(BY_SEQ_STORE);\n var attStore = txn.objectStore(ATTACH_STORE);\n var attAndSeqStore = txn.objectStore(ATTACH_AND_SEQ_STORE);\n\n // need to actually populate the table. this is the expensive part,\n // so as an optimization, check first that this database even\n // contains attachments\n var req = attStore.count();\n req.onsuccess = function (e) {\n var count = e.target.result;\n if (!count) {\n return callback(); // done\n }\n\n seqStore.openCursor().onsuccess = function (e) {\n var cursor = e.target.result;\n if (!cursor) {\n return callback(); // done\n }\n var doc = cursor.value;\n var seq = cursor.primaryKey;\n var atts = Object.keys(doc._attachments || {});\n var digestMap = {};\n for (var j = 0; j < atts.length; j++) {\n var att = doc._attachments[atts[j]];\n digestMap[att.digest] = true; // uniq digests, just in case\n }\n var digests = Object.keys(digestMap);\n for (j = 0; j < digests.length; j++) {\n var digest = digests[j];\n attAndSeqStore.put({\n seq: seq,\n digestSeq: digest + '::' + seq\n });\n }\n cursor.continue();\n };\n };\n }\n\n // migration to version 5\n // Instead of relying on on-the-fly migration of metadata,\n // this brings the doc-store to its modern form:\n // - metadata.winningrev\n // - metadata.seq\n // - stringify the metadata when storing it\n function migrateMetadata(txn) {\n\n function decodeMetadataCompat(storedObject) {\n if (!storedObject.data) {\n // old format, when we didn't store it stringified\n storedObject.deleted = storedObject.deletedOrLocal === '1';\n return storedObject;\n }\n return decodeMetadata(storedObject);\n }\n\n // ensure that every metadata has a winningRev and seq,\n // which was previously created on-the-fly but better to migrate\n var bySeqStore = txn.objectStore(BY_SEQ_STORE);\n var docStore = txn.objectStore(DOC_STORE);\n var cursor = docStore.openCursor();\n cursor.onsuccess = function (e) {\n var cursor = e.target.result;\n if (!cursor) {\n return; // done\n }\n var metadata = decodeMetadataCompat(cursor.value);\n\n metadata.winningRev = metadata.winningRev ||\n winningRev(metadata);\n\n function fetchMetadataSeq() {\n // metadata.seq was added post-3.2.0, so if it's missing,\n // we need to fetch it manually\n var start = metadata.id + '::';\n var end = metadata.id + '::\\uffff';\n var req = bySeqStore.index('_doc_id_rev').openCursor(\n IDBKeyRange.bound(start, end));\n\n var metadataSeq = 0;\n req.onsuccess = function (e) {\n var cursor = e.target.result;\n if (!cursor) {\n metadata.seq = metadataSeq;\n return onGetMetadataSeq();\n }\n var seq = cursor.primaryKey;\n if (seq > metadataSeq) {\n metadataSeq = seq;\n }\n cursor.continue();\n };\n }\n\n function onGetMetadataSeq() {\n var metadataToStore = encodeMetadata(metadata,\n metadata.winningRev, metadata.deleted);\n\n var req = docStore.put(metadataToStore);\n req.onsuccess = function () {\n cursor.continue();\n };\n }\n\n if (metadata.seq) {\n return onGetMetadataSeq();\n }\n\n fetchMetadataSeq();\n };\n\n }\n\n api.type = function () {\n return 'idb';\n };\n\n api._id = toPromise(function (callback) {\n callback(null, api._meta.instanceId);\n });\n\n api._bulkDocs = function idb_bulkDocs(req, reqOpts, callback) {\n idbBulkDocs(opts, req, reqOpts, api, idb, callback);\n };\n\n // First we look up the metadata in the ids database, then we fetch the\n // current revision(s) from the by sequence store\n api._get = function idb_get(id, opts, callback) {\n var doc;\n var metadata;\n var err;\n var txn = opts.ctx;\n if (!txn) {\n var txnResult = openTransactionSafely(idb,\n [DOC_STORE, BY_SEQ_STORE, ATTACH_STORE], 'readonly');\n if (txnResult.error) {\n return callback(txnResult.error);\n }\n txn = txnResult.txn;\n }\n\n function finish() {\n callback(err, {doc: doc, metadata: metadata, ctx: txn});\n }\n\n txn.objectStore(DOC_STORE).get(id).onsuccess = function (e) {\n metadata = decodeMetadata(e.target.result);\n // we can determine the result here if:\n // 1. there is no such document\n // 2. the document is deleted and we don't ask about specific rev\n // When we ask with opts.rev we expect the answer to be either\n // doc (possibly with _deleted=true) or missing error\n if (!metadata) {\n err = createError(MISSING_DOC, 'missing');\n return finish();\n }\n\n var rev;\n if(!opts.rev) {\n rev = metadata.winningRev;\n var deleted = isDeleted(metadata);\n if (deleted) {\n err = createError(MISSING_DOC, \"deleted\");\n return finish();\n }\n } else {\n rev = opts.latest ? latest(opts.rev, metadata) : opts.rev;\n }\n\n var objectStore = txn.objectStore(BY_SEQ_STORE);\n var key = metadata.id + '::' + rev;\n\n objectStore.index('_doc_id_rev').get(key).onsuccess = function (e) {\n doc = e.target.result;\n if (doc) {\n doc = decodeDoc(doc);\n }\n if (!doc) {\n err = createError(MISSING_DOC, 'missing');\n return finish();\n }\n finish();\n };\n };\n };\n\n api._getAttachment = function (docId, attachId, attachment, opts, callback) {\n var txn;\n if (opts.ctx) {\n txn = opts.ctx;\n } else {\n var txnResult = openTransactionSafely(idb,\n [DOC_STORE, BY_SEQ_STORE, ATTACH_STORE], 'readonly');\n if (txnResult.error) {\n return callback(txnResult.error);\n }\n txn = txnResult.txn;\n }\n var digest = attachment.digest;\n var type = attachment.content_type;\n\n txn.objectStore(ATTACH_STORE).get(digest).onsuccess = function (e) {\n var body = e.target.result.body;\n readBlobData(body, type, opts.binary, function (blobData) {\n callback(null, blobData);\n });\n };\n };\n\n api._info = function idb_info(callback) {\n var updateSeq;\n var docCount;\n\n var txnResult = openTransactionSafely(idb, [META_STORE, BY_SEQ_STORE], 'readonly');\n if (txnResult.error) {\n return callback(txnResult.error);\n }\n var txn = txnResult.txn;\n txn.objectStore(META_STORE).get(META_STORE).onsuccess = function (e) {\n docCount = e.target.result.docCount;\n };\n txn.objectStore(BY_SEQ_STORE).openCursor(null, 'prev').onsuccess = function (e) {\n var cursor = e.target.result;\n updateSeq = cursor ? cursor.key : 0;\n };\n\n txn.oncomplete = function () {\n callback(null, {\n doc_count: docCount,\n update_seq: updateSeq,\n // for debugging\n idb_attachment_format: (api._meta.blobSupport ? 'binary' : 'base64')\n });\n };\n };\n\n api._allDocs = function idb_allDocs(opts, callback) {\n idbAllDocs(opts, idb, callback);\n };\n\n api._changes = function idbChanges(opts) {\n changes(opts, api, dbName, idb);\n };\n\n api._close = function (callback) {\n // https://developer.mozilla.org/en-US/docs/IndexedDB/IDBDatabase#close\n // \"Returns immediately and closes the connection in a separate thread...\"\n idb.close();\n cachedDBs.delete(dbName);\n callback();\n };\n\n api._getRevisionTree = function (docId, callback) {\n var txnResult = openTransactionSafely(idb, [DOC_STORE], 'readonly');\n if (txnResult.error) {\n return callback(txnResult.error);\n }\n var txn = txnResult.txn;\n var req = txn.objectStore(DOC_STORE).get(docId);\n req.onsuccess = function (event) {\n var doc = decodeMetadata(event.target.result);\n if (!doc) {\n callback(createError(MISSING_DOC));\n } else {\n callback(null, doc.rev_tree);\n }\n };\n };\n\n // This function removes revisions of document docId\n // which are listed in revs and sets this document\n // revision to to rev_tree\n api._doCompaction = function (docId, revs, callback) {\n var stores = [\n DOC_STORE,\n BY_SEQ_STORE,\n ATTACH_STORE,\n ATTACH_AND_SEQ_STORE\n ];\n var txnResult = openTransactionSafely(idb, stores, 'readwrite');\n if (txnResult.error) {\n return callback(txnResult.error);\n }\n var txn = txnResult.txn;\n\n var docStore = txn.objectStore(DOC_STORE);\n\n docStore.get(docId).onsuccess = function (event) {\n var metadata = decodeMetadata(event.target.result);\n traverseRevTree(metadata.rev_tree, function (isLeaf, pos,\n revHash, ctx, opts) {\n var rev = pos + '-' + revHash;\n if (revs.indexOf(rev) !== -1) {\n opts.status = 'missing';\n }\n });\n compactRevs(revs, docId, txn);\n var winningRev$$1 = metadata.winningRev;\n var deleted = metadata.deleted;\n txn.objectStore(DOC_STORE).put(\n encodeMetadata(metadata, winningRev$$1, deleted));\n };\n txn.onabort = idbError(callback);\n txn.oncomplete = function () {\n callback();\n };\n };\n\n\n api._getLocal = function (id, callback) {\n var txnResult = openTransactionSafely(idb, [LOCAL_STORE], 'readonly');\n if (txnResult.error) {\n return callback(txnResult.error);\n }\n var tx = txnResult.txn;\n var req = tx.objectStore(LOCAL_STORE).get(id);\n\n req.onerror = idbError(callback);\n req.onsuccess = function (e) {\n var doc = e.target.result;\n if (!doc) {\n callback(createError(MISSING_DOC));\n } else {\n delete doc['_doc_id_rev']; // for backwards compat\n callback(null, doc);\n }\n };\n };\n\n api._putLocal = function (doc, opts, callback) {\n if (typeof opts === 'function') {\n callback = opts;\n opts = {};\n }\n delete doc._revisions; // ignore this, trust the rev\n var oldRev = doc._rev;\n var id = doc._id;\n if (!oldRev) {\n doc._rev = '0-1';\n } else {\n doc._rev = '0-' + (parseInt(oldRev.split('-')[1], 10) + 1);\n }\n\n var tx = opts.ctx;\n var ret;\n if (!tx) {\n var txnResult = openTransactionSafely(idb, [LOCAL_STORE], 'readwrite');\n if (txnResult.error) {\n return callback(txnResult.error);\n }\n tx = txnResult.txn;\n tx.onerror = idbError(callback);\n tx.oncomplete = function () {\n if (ret) {\n callback(null, ret);\n }\n };\n }\n\n var oStore = tx.objectStore(LOCAL_STORE);\n var req;\n if (oldRev) {\n req = oStore.get(id);\n req.onsuccess = function (e) {\n var oldDoc = e.target.result;\n if (!oldDoc || oldDoc._rev !== oldRev) {\n callback(createError(REV_CONFLICT));\n } else { // update\n var req = oStore.put(doc);\n req.onsuccess = function () {\n ret = {ok: true, id: doc._id, rev: doc._rev};\n if (opts.ctx) { // return immediately\n callback(null, ret);\n }\n };\n }\n };\n } else { // new doc\n req = oStore.add(doc);\n req.onerror = function (e) {\n // constraint error, already exists\n callback(createError(REV_CONFLICT));\n e.preventDefault(); // avoid transaction abort\n e.stopPropagation(); // avoid transaction onerror\n };\n req.onsuccess = function () {\n ret = {ok: true, id: doc._id, rev: doc._rev};\n if (opts.ctx) { // return immediately\n callback(null, ret);\n }\n };\n }\n };\n\n api._removeLocal = function (doc, opts, callback) {\n if (typeof opts === 'function') {\n callback = opts;\n opts = {};\n }\n var tx = opts.ctx;\n if (!tx) {\n var txnResult = openTransactionSafely(idb, [LOCAL_STORE], 'readwrite');\n if (txnResult.error) {\n return callback(txnResult.error);\n }\n tx = txnResult.txn;\n tx.oncomplete = function () {\n if (ret) {\n callback(null, ret);\n }\n };\n }\n var ret;\n var id = doc._id;\n var oStore = tx.objectStore(LOCAL_STORE);\n var req = oStore.get(id);\n\n req.onerror = idbError(callback);\n req.onsuccess = function (e) {\n var oldDoc = e.target.result;\n if (!oldDoc || oldDoc._rev !== doc._rev) {\n callback(createError(MISSING_DOC));\n } else {\n oStore.delete(id);\n ret = {ok: true, id: id, rev: '0-0'};\n if (opts.ctx) { // return immediately\n callback(null, ret);\n }\n }\n };\n };\n\n api._destroy = function (opts, callback) {\n changesHandler$$1.removeAllListeners(dbName);\n\n //Close open request for \"dbName\" database to fix ie delay.\n var openReq = openReqList.get(dbName);\n if (openReq && openReq.result) {\n openReq.result.close();\n cachedDBs.delete(dbName);\n }\n var req = indexedDB.deleteDatabase(dbName);\n\n req.onsuccess = function () {\n //Remove open request from the list.\n openReqList.delete(dbName);\n if (hasLocalStorage() && (dbName in localStorage)) {\n delete localStorage[dbName];\n }\n callback(null, { 'ok': true });\n };\n\n req.onerror = idbError(callback);\n };\n\n var cached = cachedDBs.get(dbName);\n\n if (cached) {\n idb = cached.idb;\n api._meta = cached.global;\n return nextTick(function () {\n callback(null, api);\n });\n }\n\n var req;\n if (opts.storage) {\n req = tryStorageOption(dbName, opts.storage);\n } else {\n req = indexedDB.open(dbName, ADAPTER_VERSION);\n }\n\n openReqList.set(dbName, req);\n\n req.onupgradeneeded = function (e) {\n var db = e.target.result;\n if (e.oldVersion < 1) {\n return createSchema(db); // new db, initial schema\n }\n // do migrations\n\n var txn = e.currentTarget.transaction;\n // these migrations have to be done in this function, before\n // control is returned to the event loop, because IndexedDB\n\n if (e.oldVersion < 3) {\n createLocalStoreSchema(db); // v2 -> v3\n }\n if (e.oldVersion < 4) {\n addAttachAndSeqStore(db); // v3 -> v4\n }\n\n var migrations = [\n addDeletedOrLocalIndex, // v1 -> v2\n migrateLocalStore, // v2 -> v3\n migrateAttsAndSeqs, // v3 -> v4\n migrateMetadata // v4 -> v5\n ];\n\n var i = e.oldVersion;\n\n function next() {\n var migration = migrations[i - 1];\n i++;\n if (migration) {\n migration(txn, next);\n }\n }\n\n next();\n };\n\n req.onsuccess = function (e) {\n\n idb = e.target.result;\n\n idb.onversionchange = function () {\n idb.close();\n cachedDBs.delete(dbName);\n };\n\n idb.onabort = function (e) {\n guardedConsole('error', 'Database has a global failure', e.target.error);\n idb.close();\n cachedDBs.delete(dbName);\n };\n\n // Do a few setup operations (in parallel as much as possible):\n // 1. Fetch meta doc\n // 2. Check blob support\n // 3. Calculate docCount\n // 4. Generate an instanceId if necessary\n // 5. Store docCount and instanceId on meta doc\n\n var txn = idb.transaction([\n META_STORE,\n DETECT_BLOB_SUPPORT_STORE,\n DOC_STORE\n ], 'readwrite');\n\n var storedMetaDoc = false;\n var metaDoc;\n var docCount;\n var blobSupport;\n var instanceId;\n\n function completeSetup() {\n if (typeof blobSupport === 'undefined' || !storedMetaDoc) {\n return;\n }\n api._meta = {\n name: dbName,\n instanceId: instanceId,\n blobSupport: blobSupport\n };\n\n cachedDBs.set(dbName, {\n idb: idb,\n global: api._meta\n });\n callback(null, api);\n }\n\n function storeMetaDocIfReady() {\n if (typeof docCount === 'undefined' || typeof metaDoc === 'undefined') {\n return;\n }\n var instanceKey = dbName + '_id';\n if (instanceKey in metaDoc) {\n instanceId = metaDoc[instanceKey];\n } else {\n metaDoc[instanceKey] = instanceId = uuid();\n }\n metaDoc.docCount = docCount;\n txn.objectStore(META_STORE).put(metaDoc);\n }\n\n //\n // fetch or generate the instanceId\n //\n txn.objectStore(META_STORE).get(META_STORE).onsuccess = function (e) {\n metaDoc = e.target.result || { id: META_STORE };\n storeMetaDocIfReady();\n };\n\n //\n // countDocs\n //\n countDocs(txn, function (count) {\n docCount = count;\n storeMetaDocIfReady();\n });\n\n //\n // check blob support\n //\n if (!blobSupportPromise) {\n // make sure blob support is only checked once\n blobSupportPromise = checkBlobSupport(txn);\n }\n\n blobSupportPromise.then(function (val) {\n blobSupport = val;\n completeSetup();\n });\n\n // only when the metadata put transaction has completed,\n // consider the setup done\n txn.oncomplete = function () {\n storedMetaDoc = true;\n completeSetup();\n };\n };\n\n req.onerror = function () {\n var msg = 'Failed to open indexedDB, are you in private browsing mode?';\n guardedConsole('error', msg);\n callback(createError(IDB_ERROR, msg));\n };\n}\n\nIdbPouch.valid = function () {\n // Issue #2533, we finally gave up on doing bug\n // detection instead of browser sniffing. Safari brought us\n // to our knees.\n var isSafari = typeof openDatabase !== 'undefined' &&\n /(Safari|iPhone|iPad|iPod)/.test(navigator.userAgent) &&\n !/Chrome/.test(navigator.userAgent) &&\n !/BlackBerry/.test(navigator.platform);\n\n // some outdated implementations of IDB that appear on Samsung\n // and HTC Android devices <4.4 are missing IDBKeyRange\n return !isSafari && typeof indexedDB !== 'undefined' &&\n typeof IDBKeyRange !== 'undefined';\n};\n\nfunction tryStorageOption(dbName, storage) {\n try { // option only available in Firefox 26+\n return indexedDB.open(dbName, {\n version: ADAPTER_VERSION,\n storage: storage\n });\n } catch(err) {\n return indexedDB.open(dbName, ADAPTER_VERSION);\n }\n}\n\nvar IDBPouch = function (PouchDB) {\n PouchDB.adapter('idb', IdbPouch, true);\n};\n\n//\n// Parsing hex strings. Yeah.\n//\n// So basically we need this because of a bug in WebSQL:\n// https://code.google.com/p/chromium/issues/detail?id=422690\n// https://bugs.webkit.org/show_bug.cgi?id=137637\n//\n// UTF-8 and UTF-16 are provided as separate functions\n// for meager performance improvements\n//\n\nfunction decodeUtf8(str) {\n return decodeURIComponent(escape(str));\n}\n\nfunction hexToInt(charCode) {\n // '0'-'9' is 48-57\n // 'A'-'F' is 65-70\n // SQLite will only give us uppercase hex\n return charCode < 65 ? (charCode - 48) : (charCode - 55);\n}\n\n\n// Example:\n// pragma encoding=utf8;\n// select hex('A');\n// returns '41'\nfunction parseHexUtf8(str, start, end) {\n var result = '';\n while (start < end) {\n result += String.fromCharCode(\n (hexToInt(str.charCodeAt(start++)) << 4) |\n hexToInt(str.charCodeAt(start++)));\n }\n return result;\n}\n\n// Example:\n// pragma encoding=utf16;\n// select hex('A');\n// returns '4100'\n// notice that the 00 comes after the 41 (i.e. it's swizzled)\nfunction parseHexUtf16(str, start, end) {\n var result = '';\n while (start < end) {\n // UTF-16, so swizzle the bytes\n result += String.fromCharCode(\n (hexToInt(str.charCodeAt(start + 2)) << 12) |\n (hexToInt(str.charCodeAt(start + 3)) << 8) |\n (hexToInt(str.charCodeAt(start)) << 4) |\n hexToInt(str.charCodeAt(start + 1)));\n start += 4;\n }\n return result;\n}\n\nfunction parseHexString(str, encoding) {\n if (encoding === 'UTF-8') {\n return decodeUtf8(parseHexUtf8(str, 0, str.length));\n } else {\n return parseHexUtf16(str, 0, str.length);\n }\n}\n\nfunction quote(str) {\n return \"'\" + str + \"'\";\n}\n\nvar ADAPTER_VERSION$1 = 7; // used to manage migrations\n\n// The object stores created for each database\n// DOC_STORE stores the document meta data, its revision history and state\nvar DOC_STORE$1 = quote('document-store');\n// BY_SEQ_STORE stores a particular version of a document, keyed by its\n// sequence id\nvar BY_SEQ_STORE$1 = quote('by-sequence');\n// Where we store attachments\nvar ATTACH_STORE$1 = quote('attach-store');\nvar LOCAL_STORE$1 = quote('local-store');\nvar META_STORE$1 = quote('metadata-store');\n// where we store many-to-many relations between attachment\n// digests and seqs\nvar ATTACH_AND_SEQ_STORE$1 = quote('attach-seq-store');\n\n// escapeBlob and unescapeBlob are workarounds for a websql bug:\n// https://code.google.com/p/chromium/issues/detail?id=422690\n// https://bugs.webkit.org/show_bug.cgi?id=137637\n// The goal is to never actually insert the \\u0000 character\n// in the database.\nfunction escapeBlob(str) {\n return str\n .replace(/\\u0002/g, '\\u0002\\u0002')\n .replace(/\\u0001/g, '\\u0001\\u0002')\n .replace(/\\u0000/g, '\\u0001\\u0001');\n}\n\nfunction unescapeBlob(str) {\n return str\n .replace(/\\u0001\\u0001/g, '\\u0000')\n .replace(/\\u0001\\u0002/g, '\\u0001')\n .replace(/\\u0002\\u0002/g, '\\u0002');\n}\n\nfunction stringifyDoc(doc) {\n // don't bother storing the id/rev. it uses lots of space,\n // in persistent map/reduce especially\n delete doc._id;\n delete doc._rev;\n return JSON.stringify(doc);\n}\n\nfunction unstringifyDoc(doc, id, rev) {\n doc = JSON.parse(doc);\n doc._id = id;\n doc._rev = rev;\n return doc;\n}\n\n// question mark groups IN queries, e.g. 3 -> '(?,?,?)'\nfunction qMarks(num) {\n var s = '(';\n while (num--) {\n s += '?';\n if (num) {\n s += ',';\n }\n }\n return s + ')';\n}\n\nfunction select(selector, table, joiner, where, orderBy) {\n return 'SELECT ' + selector + ' FROM ' +\n (typeof table === 'string' ? table : table.join(' JOIN ')) +\n (joiner ? (' ON ' + joiner) : '') +\n (where ? (' WHERE ' +\n (typeof where === 'string' ? where : where.join(' AND '))) : '') +\n (orderBy ? (' ORDER BY ' + orderBy) : '');\n}\n\nfunction compactRevs$1(revs, docId, tx) {\n\n if (!revs.length) {\n return;\n }\n\n var numDone = 0;\n var seqs = [];\n\n function checkDone() {\n if (++numDone === revs.length) { // done\n deleteOrphans();\n }\n }\n\n function deleteOrphans() {\n // find orphaned attachment digests\n\n if (!seqs.length) {\n return;\n }\n\n var sql = 'SELECT DISTINCT digest AS digest FROM ' +\n ATTACH_AND_SEQ_STORE$1 + ' WHERE seq IN ' + qMarks(seqs.length);\n\n tx.executeSql(sql, seqs, function (tx, res) {\n\n var digestsToCheck = [];\n for (var i = 0; i < res.rows.length; i++) {\n digestsToCheck.push(res.rows.item(i).digest);\n }\n if (!digestsToCheck.length) {\n return;\n }\n\n var sql = 'DELETE FROM ' + ATTACH_AND_SEQ_STORE$1 +\n ' WHERE seq IN (' +\n seqs.map(function () { return '?'; }).join(',') +\n ')';\n tx.executeSql(sql, seqs, function (tx) {\n\n var sql = 'SELECT digest FROM ' + ATTACH_AND_SEQ_STORE$1 +\n ' WHERE digest IN (' +\n digestsToCheck.map(function () { return '?'; }).join(',') +\n ')';\n tx.executeSql(sql, digestsToCheck, function (tx, res) {\n var nonOrphanedDigests = new ExportedSet();\n for (var i = 0; i < res.rows.length; i++) {\n nonOrphanedDigests.add(res.rows.item(i).digest);\n }\n digestsToCheck.forEach(function (digest) {\n if (nonOrphanedDigests.has(digest)) {\n return;\n }\n tx.executeSql(\n 'DELETE FROM ' + ATTACH_AND_SEQ_STORE$1 + ' WHERE digest=?',\n [digest]);\n tx.executeSql(\n 'DELETE FROM ' + ATTACH_STORE$1 + ' WHERE digest=?', [digest]);\n });\n });\n });\n });\n }\n\n // update by-seq and attach stores in parallel\n revs.forEach(function (rev) {\n var sql = 'SELECT seq FROM ' + BY_SEQ_STORE$1 +\n ' WHERE doc_id=? AND rev=?';\n\n tx.executeSql(sql, [docId, rev], function (tx, res) {\n if (!res.rows.length) { // already deleted\n return checkDone();\n }\n var seq = res.rows.item(0).seq;\n seqs.push(seq);\n\n tx.executeSql(\n 'DELETE FROM ' + BY_SEQ_STORE$1 + ' WHERE seq=?', [seq], checkDone);\n });\n });\n}\n\nfunction websqlError(callback) {\n return function (event) {\n guardedConsole('error', 'WebSQL threw an error', event);\n // event may actually be a SQLError object, so report is as such\n var errorNameMatch = event && event.constructor.toString()\n .match(/function ([^\\(]+)/);\n var errorName = (errorNameMatch && errorNameMatch[1]) || event.type;\n var errorReason = event.target || event.message;\n callback(createError(WSQ_ERROR, errorReason, errorName));\n };\n}\n\nfunction getSize(opts) {\n if ('size' in opts) {\n // triggers immediate popup in iOS, fixes #2347\n // e.g. 5000001 asks for 5 MB, 10000001 asks for 10 MB,\n return opts.size * 1000000;\n }\n // In iOS, doesn't matter as long as it's <= 5000000.\n // Except that if you request too much, our tests fail\n // because of the native \"do you accept?\" popup.\n // In Android <=4.3, this value is actually used as an\n // honest-to-god ceiling for data, so we need to\n // set it to a decently high number.\n var isAndroid = typeof navigator !== 'undefined' &&\n /Android/.test(navigator.userAgent);\n return isAndroid ? 5000000 : 1; // in PhantomJS, if you use 0 it will crash\n}\n\nfunction websqlBulkDocs(dbOpts, req, opts, api, db, websqlChanges, callback) {\n var newEdits = opts.new_edits;\n var userDocs = req.docs;\n\n // Parse the docs, give them a sequence number for the result\n var docInfos = userDocs.map(function (doc) {\n if (doc._id && isLocalId(doc._id)) {\n return doc;\n }\n var newDoc = parseDoc(doc, newEdits);\n return newDoc;\n });\n\n var docInfoErrors = docInfos.filter(function (docInfo) {\n return docInfo.error;\n });\n if (docInfoErrors.length) {\n return callback(docInfoErrors[0]);\n }\n\n var tx;\n var results = new Array(docInfos.length);\n var fetchedDocs = new ExportedMap();\n\n var preconditionErrored;\n function complete() {\n if (preconditionErrored) {\n return callback(preconditionErrored);\n }\n websqlChanges.notify(api._name);\n callback(null, results);\n }\n\n function verifyAttachment(digest, callback) {\n var sql = 'SELECT count(*) as cnt FROM ' + ATTACH_STORE$1 +\n ' WHERE digest=?';\n tx.executeSql(sql, [digest], function (tx, result) {\n if (result.rows.item(0).cnt === 0) {\n var err = createError(MISSING_STUB,\n 'unknown stub attachment with digest ' +\n digest);\n callback(err);\n } else {\n callback();\n }\n });\n }\n\n function verifyAttachments(finish) {\n var digests = [];\n docInfos.forEach(function (docInfo) {\n if (docInfo.data && docInfo.data._attachments) {\n Object.keys(docInfo.data._attachments).forEach(function (filename) {\n var att = docInfo.data._attachments[filename];\n if (att.stub) {\n digests.push(att.digest);\n }\n });\n }\n });\n if (!digests.length) {\n return finish();\n }\n var numDone = 0;\n var err;\n\n function checkDone() {\n if (++numDone === digests.length) {\n finish(err);\n }\n }\n digests.forEach(function (digest) {\n verifyAttachment(digest, function (attErr) {\n if (attErr && !err) {\n err = attErr;\n }\n checkDone();\n });\n });\n }\n\n function writeDoc(docInfo, winningRev$$1, winningRevIsDeleted, newRevIsDeleted,\n isUpdate, delta, resultsIdx, callback) {\n\n function finish() {\n var data = docInfo.data;\n var deletedInt = newRevIsDeleted ? 1 : 0;\n\n var id = data._id;\n var rev = data._rev;\n var json = stringifyDoc(data);\n var sql = 'INSERT INTO ' + BY_SEQ_STORE$1 +\n ' (doc_id, rev, json, deleted) VALUES (?, ?, ?, ?);';\n var sqlArgs = [id, rev, json, deletedInt];\n\n // map seqs to attachment digests, which\n // we will need later during compaction\n function insertAttachmentMappings(seq, callback) {\n var attsAdded = 0;\n var attsToAdd = Object.keys(data._attachments || {});\n\n if (!attsToAdd.length) {\n return callback();\n }\n function checkDone() {\n if (++attsAdded === attsToAdd.length) {\n callback();\n }\n return false; // ack handling a constraint error\n }\n function add(att) {\n var sql = 'INSERT INTO ' + ATTACH_AND_SEQ_STORE$1 +\n ' (digest, seq) VALUES (?,?)';\n var sqlArgs = [data._attachments[att].digest, seq];\n tx.executeSql(sql, sqlArgs, checkDone, checkDone);\n // second callback is for a constaint error, which we ignore\n // because this docid/rev has already been associated with\n // the digest (e.g. when new_edits == false)\n }\n for (var i = 0; i < attsToAdd.length; i++) {\n add(attsToAdd[i]); // do in parallel\n }\n }\n\n tx.executeSql(sql, sqlArgs, function (tx, result) {\n var seq = result.insertId;\n insertAttachmentMappings(seq, function () {\n dataWritten(tx, seq);\n });\n }, function () {\n // constraint error, recover by updating instead (see #1638)\n var fetchSql = select('seq', BY_SEQ_STORE$1, null,\n 'doc_id=? AND rev=?');\n tx.executeSql(fetchSql, [id, rev], function (tx, res) {\n var seq = res.rows.item(0).seq;\n var sql = 'UPDATE ' + BY_SEQ_STORE$1 +\n ' SET json=?, deleted=? WHERE doc_id=? AND rev=?;';\n var sqlArgs = [json, deletedInt, id, rev];\n tx.executeSql(sql, sqlArgs, function (tx) {\n insertAttachmentMappings(seq, function () {\n dataWritten(tx, seq);\n });\n });\n });\n return false; // ack that we've handled the error\n });\n }\n\n function collectResults(attachmentErr) {\n if (!err) {\n if (attachmentErr) {\n err = attachmentErr;\n callback(err);\n } else if (recv === attachments.length) {\n finish();\n }\n }\n }\n\n var err = null;\n var recv = 0;\n\n docInfo.data._id = docInfo.metadata.id;\n docInfo.data._rev = docInfo.metadata.rev;\n var attachments = Object.keys(docInfo.data._attachments || {});\n\n\n if (newRevIsDeleted) {\n docInfo.data._deleted = true;\n }\n\n function attachmentSaved(err) {\n recv++;\n collectResults(err);\n }\n\n attachments.forEach(function (key) {\n var att = docInfo.data._attachments[key];\n if (!att.stub) {\n var data = att.data;\n delete att.data;\n att.revpos = parseInt(winningRev$$1, 10);\n var digest = att.digest;\n saveAttachment(digest, data, attachmentSaved);\n } else {\n recv++;\n collectResults();\n }\n });\n\n if (!attachments.length) {\n finish();\n }\n\n function dataWritten(tx, seq) {\n var id = docInfo.metadata.id;\n\n var revsToCompact = docInfo.stemmedRevs || [];\n if (isUpdate && api.auto_compaction) {\n revsToCompact = compactTree(docInfo.metadata).concat(revsToCompact);\n }\n if (revsToCompact.length) {\n compactRevs$1(revsToCompact, id, tx);\n }\n\n docInfo.metadata.seq = seq;\n var rev = docInfo.metadata.rev;\n delete docInfo.metadata.rev;\n\n var sql = isUpdate ?\n 'UPDATE ' + DOC_STORE$1 +\n ' SET json=?, max_seq=?, winningseq=' +\n '(SELECT seq FROM ' + BY_SEQ_STORE$1 +\n ' WHERE doc_id=' + DOC_STORE$1 + '.id AND rev=?) WHERE id=?'\n : 'INSERT INTO ' + DOC_STORE$1 +\n ' (id, winningseq, max_seq, json) VALUES (?,?,?,?);';\n var metadataStr = safeJsonStringify(docInfo.metadata);\n var params = isUpdate ?\n [metadataStr, seq, winningRev$$1, id] :\n [id, seq, seq, metadataStr];\n tx.executeSql(sql, params, function () {\n results[resultsIdx] = {\n ok: true,\n id: docInfo.metadata.id,\n rev: rev\n };\n fetchedDocs.set(id, docInfo.metadata);\n callback();\n });\n }\n }\n\n function websqlProcessDocs() {\n processDocs(dbOpts.revs_limit, docInfos, api, fetchedDocs, tx,\n results, writeDoc, opts);\n }\n\n function fetchExistingDocs(callback) {\n if (!docInfos.length) {\n return callback();\n }\n\n var numFetched = 0;\n\n function checkDone() {\n if (++numFetched === docInfos.length) {\n callback();\n }\n }\n\n docInfos.forEach(function (docInfo) {\n if (docInfo._id && isLocalId(docInfo._id)) {\n return checkDone(); // skip local docs\n }\n var id = docInfo.metadata.id;\n tx.executeSql('SELECT json FROM ' + DOC_STORE$1 +\n ' WHERE id = ?', [id], function (tx, result) {\n if (result.rows.length) {\n var metadata = safeJsonParse(result.rows.item(0).json);\n fetchedDocs.set(id, metadata);\n }\n checkDone();\n });\n });\n }\n\n function saveAttachment(digest, data, callback) {\n var sql = 'SELECT digest FROM ' + ATTACH_STORE$1 + ' WHERE digest=?';\n tx.executeSql(sql, [digest], function (tx, result) {\n if (result.rows.length) { // attachment already exists\n return callback();\n }\n // we could just insert before selecting and catch the error,\n // but my hunch is that it's cheaper not to serialize the blob\n // from JS to C if we don't have to (TODO: confirm this)\n sql = 'INSERT INTO ' + ATTACH_STORE$1 +\n ' (digest, body, escaped) VALUES (?,?,1)';\n tx.executeSql(sql, [digest, escapeBlob(data)], function () {\n callback();\n }, function () {\n // ignore constaint errors, means it already exists\n callback();\n return false; // ack we handled the error\n });\n });\n }\n\n preprocessAttachments(docInfos, 'binary', function (err) {\n if (err) {\n return callback(err);\n }\n db.transaction(function (txn) {\n tx = txn;\n verifyAttachments(function (err) {\n if (err) {\n preconditionErrored = err;\n } else {\n fetchExistingDocs(websqlProcessDocs);\n }\n });\n }, websqlError(callback), complete);\n });\n}\n\nvar cachedDatabases = new ExportedMap();\n\n// openDatabase passed in through opts (e.g. for node-websql)\nfunction openDatabaseWithOpts(opts) {\n return opts.websql(opts.name, opts.version, opts.description, opts.size);\n}\n\nfunction openDBSafely(opts) {\n try {\n return {\n db: openDatabaseWithOpts(opts)\n };\n } catch (err) {\n return {\n error: err\n };\n }\n}\n\nfunction openDB$1(opts) {\n var cachedResult = cachedDatabases.get(opts.name);\n if (!cachedResult) {\n cachedResult = openDBSafely(opts);\n cachedDatabases.set(opts.name, cachedResult);\n }\n return cachedResult;\n}\n\nvar websqlChanges = new Changes();\n\nfunction fetchAttachmentsIfNecessary$1(doc, opts, api, txn, cb) {\n var attachments = Object.keys(doc._attachments || {});\n if (!attachments.length) {\n return cb && cb();\n }\n var numDone = 0;\n\n function checkDone() {\n if (++numDone === attachments.length && cb) {\n cb();\n }\n }\n\n function fetchAttachment(doc, att) {\n var attObj = doc._attachments[att];\n var attOpts = {binary: opts.binary, ctx: txn};\n api._getAttachment(doc._id, att, attObj, attOpts, function (_, data) {\n doc._attachments[att] = assign$1(\n pick(attObj, ['digest', 'content_type']),\n { data: data }\n );\n checkDone();\n });\n }\n\n attachments.forEach(function (att) {\n if (opts.attachments && opts.include_docs) {\n fetchAttachment(doc, att);\n } else {\n doc._attachments[att].stub = true;\n checkDone();\n }\n });\n}\n\nvar POUCH_VERSION = 1;\n\n// these indexes cover the ground for most allDocs queries\nvar BY_SEQ_STORE_DELETED_INDEX_SQL =\n 'CREATE INDEX IF NOT EXISTS \\'by-seq-deleted-idx\\' ON ' +\n BY_SEQ_STORE$1 + ' (seq, deleted)';\nvar BY_SEQ_STORE_DOC_ID_REV_INDEX_SQL =\n 'CREATE UNIQUE INDEX IF NOT EXISTS \\'by-seq-doc-id-rev\\' ON ' +\n BY_SEQ_STORE$1 + ' (doc_id, rev)';\nvar DOC_STORE_WINNINGSEQ_INDEX_SQL =\n 'CREATE INDEX IF NOT EXISTS \\'doc-winningseq-idx\\' ON ' +\n DOC_STORE$1 + ' (winningseq)';\nvar ATTACH_AND_SEQ_STORE_SEQ_INDEX_SQL =\n 'CREATE INDEX IF NOT EXISTS \\'attach-seq-seq-idx\\' ON ' +\n ATTACH_AND_SEQ_STORE$1 + ' (seq)';\nvar ATTACH_AND_SEQ_STORE_ATTACH_INDEX_SQL =\n 'CREATE UNIQUE INDEX IF NOT EXISTS \\'attach-seq-digest-idx\\' ON ' +\n ATTACH_AND_SEQ_STORE$1 + ' (digest, seq)';\n\nvar DOC_STORE_AND_BY_SEQ_JOINER = BY_SEQ_STORE$1 +\n '.seq = ' + DOC_STORE$1 + '.winningseq';\n\nvar SELECT_DOCS = BY_SEQ_STORE$1 + '.seq AS seq, ' +\n BY_SEQ_STORE$1 + '.deleted AS deleted, ' +\n BY_SEQ_STORE$1 + '.json AS data, ' +\n BY_SEQ_STORE$1 + '.rev AS rev, ' +\n DOC_STORE$1 + '.json AS metadata';\n\nfunction WebSqlPouch$1(opts, callback) {\n var api = this;\n var instanceId = null;\n var size = getSize(opts);\n var idRequests = [];\n var encoding;\n\n api._name = opts.name;\n\n // extend the options here, because sqlite plugin has a ton of options\n // and they are constantly changing, so it's more prudent to allow anything\n var websqlOpts = assign$1({}, opts, {\n version: POUCH_VERSION,\n description: opts.name,\n size: size\n });\n var openDBResult = openDB$1(websqlOpts);\n if (openDBResult.error) {\n return websqlError(callback)(openDBResult.error);\n }\n var db = openDBResult.db;\n if (typeof db.readTransaction !== 'function') {\n // doesn't exist in sqlite plugin\n db.readTransaction = db.transaction;\n }\n\n function dbCreated() {\n // note the db name in case the browser upgrades to idb\n if (hasLocalStorage()) {\n window.localStorage['_pouch__websqldb_' + api._name] = true;\n }\n callback(null, api);\n }\n\n // In this migration, we added the 'deleted' and 'local' columns to the\n // by-seq and doc store tables.\n // To preserve existing user data, we re-process all the existing JSON\n // and add these values.\n // Called migration2 because it corresponds to adapter version (db_version) #2\n function runMigration2(tx, callback) {\n // index used for the join in the allDocs query\n tx.executeSql(DOC_STORE_WINNINGSEQ_INDEX_SQL);\n\n tx.executeSql('ALTER TABLE ' + BY_SEQ_STORE$1 +\n ' ADD COLUMN deleted TINYINT(1) DEFAULT 0', [], function () {\n tx.executeSql(BY_SEQ_STORE_DELETED_INDEX_SQL);\n tx.executeSql('ALTER TABLE ' + DOC_STORE$1 +\n ' ADD COLUMN local TINYINT(1) DEFAULT 0', [], function () {\n tx.executeSql('CREATE INDEX IF NOT EXISTS \\'doc-store-local-idx\\' ON ' +\n DOC_STORE$1 + ' (local, id)');\n\n var sql = 'SELECT ' + DOC_STORE$1 + '.winningseq AS seq, ' + DOC_STORE$1 +\n '.json AS metadata FROM ' + BY_SEQ_STORE$1 + ' JOIN ' + DOC_STORE$1 +\n ' ON ' + BY_SEQ_STORE$1 + '.seq = ' + DOC_STORE$1 + '.winningseq';\n\n tx.executeSql(sql, [], function (tx, result) {\n\n var deleted = [];\n var local = [];\n\n for (var i = 0; i < result.rows.length; i++) {\n var item = result.rows.item(i);\n var seq = item.seq;\n var metadata = JSON.parse(item.metadata);\n if (isDeleted(metadata)) {\n deleted.push(seq);\n }\n if (isLocalId(metadata.id)) {\n local.push(metadata.id);\n }\n }\n tx.executeSql('UPDATE ' + DOC_STORE$1 + 'SET local = 1 WHERE id IN ' +\n qMarks(local.length), local, function () {\n tx.executeSql('UPDATE ' + BY_SEQ_STORE$1 +\n ' SET deleted = 1 WHERE seq IN ' +\n qMarks(deleted.length), deleted, callback);\n });\n });\n });\n });\n }\n\n // in this migration, we make all the local docs unversioned\n function runMigration3(tx, callback) {\n var local = 'CREATE TABLE IF NOT EXISTS ' + LOCAL_STORE$1 +\n ' (id UNIQUE, rev, json)';\n tx.executeSql(local, [], function () {\n var sql = 'SELECT ' + DOC_STORE$1 + '.id AS id, ' +\n BY_SEQ_STORE$1 + '.json AS data ' +\n 'FROM ' + BY_SEQ_STORE$1 + ' JOIN ' +\n DOC_STORE$1 + ' ON ' + BY_SEQ_STORE$1 + '.seq = ' +\n DOC_STORE$1 + '.winningseq WHERE local = 1';\n tx.executeSql(sql, [], function (tx, res) {\n var rows = [];\n for (var i = 0; i < res.rows.length; i++) {\n rows.push(res.rows.item(i));\n }\n function doNext() {\n if (!rows.length) {\n return callback(tx);\n }\n var row = rows.shift();\n var rev = JSON.parse(row.data)._rev;\n tx.executeSql('INSERT INTO ' + LOCAL_STORE$1 +\n ' (id, rev, json) VALUES (?,?,?)',\n [row.id, rev, row.data], function (tx) {\n tx.executeSql('DELETE FROM ' + DOC_STORE$1 + ' WHERE id=?',\n [row.id], function (tx) {\n tx.executeSql('DELETE FROM ' + BY_SEQ_STORE$1 + ' WHERE seq=?',\n [row.seq], function () {\n doNext();\n });\n });\n });\n }\n doNext();\n });\n });\n }\n\n // in this migration, we remove doc_id_rev and just use rev\n function runMigration4(tx, callback) {\n\n function updateRows(rows) {\n function doNext() {\n if (!rows.length) {\n return callback(tx);\n }\n var row = rows.shift();\n var doc_id_rev = parseHexString(row.hex, encoding);\n var idx = doc_id_rev.lastIndexOf('::');\n var doc_id = doc_id_rev.substring(0, idx);\n var rev = doc_id_rev.substring(idx + 2);\n var sql = 'UPDATE ' + BY_SEQ_STORE$1 +\n ' SET doc_id=?, rev=? WHERE doc_id_rev=?';\n tx.executeSql(sql, [doc_id, rev, doc_id_rev], function () {\n doNext();\n });\n }\n doNext();\n }\n\n var sql = 'ALTER TABLE ' + BY_SEQ_STORE$1 + ' ADD COLUMN doc_id';\n tx.executeSql(sql, [], function (tx) {\n var sql = 'ALTER TABLE ' + BY_SEQ_STORE$1 + ' ADD COLUMN rev';\n tx.executeSql(sql, [], function (tx) {\n tx.executeSql(BY_SEQ_STORE_DOC_ID_REV_INDEX_SQL, [], function (tx) {\n var sql = 'SELECT hex(doc_id_rev) as hex FROM ' + BY_SEQ_STORE$1;\n tx.executeSql(sql, [], function (tx, res) {\n var rows = [];\n for (var i = 0; i < res.rows.length; i++) {\n rows.push(res.rows.item(i));\n }\n updateRows(rows);\n });\n });\n });\n });\n }\n\n // in this migration, we add the attach_and_seq table\n // for issue #2818\n function runMigration5(tx, callback) {\n\n function migrateAttsAndSeqs(tx) {\n // need to actually populate the table. this is the expensive part,\n // so as an optimization, check first that this database even\n // contains attachments\n var sql = 'SELECT COUNT(*) AS cnt FROM ' + ATTACH_STORE$1;\n tx.executeSql(sql, [], function (tx, res) {\n var count = res.rows.item(0).cnt;\n if (!count) {\n return callback(tx);\n }\n\n var offset = 0;\n var pageSize = 10;\n function nextPage() {\n var sql = select(\n SELECT_DOCS + ', ' + DOC_STORE$1 + '.id AS id',\n [DOC_STORE$1, BY_SEQ_STORE$1],\n DOC_STORE_AND_BY_SEQ_JOINER,\n null,\n DOC_STORE$1 + '.id '\n );\n sql += ' LIMIT ' + pageSize + ' OFFSET ' + offset;\n offset += pageSize;\n tx.executeSql(sql, [], function (tx, res) {\n if (!res.rows.length) {\n return callback(tx);\n }\n var digestSeqs = {};\n function addDigestSeq(digest, seq) {\n // uniq digest/seq pairs, just in case there are dups\n var seqs = digestSeqs[digest] = (digestSeqs[digest] || []);\n if (seqs.indexOf(seq) === -1) {\n seqs.push(seq);\n }\n }\n for (var i = 0; i < res.rows.length; i++) {\n var row = res.rows.item(i);\n var doc = unstringifyDoc(row.data, row.id, row.rev);\n var atts = Object.keys(doc._attachments || {});\n for (var j = 0; j < atts.length; j++) {\n var att = doc._attachments[atts[j]];\n addDigestSeq(att.digest, row.seq);\n }\n }\n var digestSeqPairs = [];\n Object.keys(digestSeqs).forEach(function (digest) {\n var seqs = digestSeqs[digest];\n seqs.forEach(function (seq) {\n digestSeqPairs.push([digest, seq]);\n });\n });\n if (!digestSeqPairs.length) {\n return nextPage();\n }\n var numDone = 0;\n digestSeqPairs.forEach(function (pair) {\n var sql = 'INSERT INTO ' + ATTACH_AND_SEQ_STORE$1 +\n ' (digest, seq) VALUES (?,?)';\n tx.executeSql(sql, pair, function () {\n if (++numDone === digestSeqPairs.length) {\n nextPage();\n }\n });\n });\n });\n }\n nextPage();\n });\n }\n\n var attachAndRev = 'CREATE TABLE IF NOT EXISTS ' +\n ATTACH_AND_SEQ_STORE$1 + ' (digest, seq INTEGER)';\n tx.executeSql(attachAndRev, [], function (tx) {\n tx.executeSql(\n ATTACH_AND_SEQ_STORE_ATTACH_INDEX_SQL, [], function (tx) {\n tx.executeSql(\n ATTACH_AND_SEQ_STORE_SEQ_INDEX_SQL, [],\n migrateAttsAndSeqs);\n });\n });\n }\n\n // in this migration, we use escapeBlob() and unescapeBlob()\n // instead of reading out the binary as HEX, which is slow\n function runMigration6(tx, callback) {\n var sql = 'ALTER TABLE ' + ATTACH_STORE$1 +\n ' ADD COLUMN escaped TINYINT(1) DEFAULT 0';\n tx.executeSql(sql, [], callback);\n }\n\n // issue #3136, in this migration we need a \"latest seq\" as well\n // as the \"winning seq\" in the doc store\n function runMigration7(tx, callback) {\n var sql = 'ALTER TABLE ' + DOC_STORE$1 +\n ' ADD COLUMN max_seq INTEGER';\n tx.executeSql(sql, [], function (tx) {\n var sql = 'UPDATE ' + DOC_STORE$1 + ' SET max_seq=(SELECT MAX(seq) FROM ' +\n BY_SEQ_STORE$1 + ' WHERE doc_id=id)';\n tx.executeSql(sql, [], function (tx) {\n // add unique index after filling, else we'll get a constraint\n // error when we do the ALTER TABLE\n var sql =\n 'CREATE UNIQUE INDEX IF NOT EXISTS \\'doc-max-seq-idx\\' ON ' +\n DOC_STORE$1 + ' (max_seq)';\n tx.executeSql(sql, [], callback);\n });\n });\n }\n\n function checkEncoding(tx, cb) {\n // UTF-8 on chrome/android, UTF-16 on safari < 7.1\n tx.executeSql('SELECT HEX(\"a\") AS hex', [], function (tx, res) {\n var hex = res.rows.item(0).hex;\n encoding = hex.length === 2 ? 'UTF-8' : 'UTF-16';\n cb();\n }\n );\n }\n\n function onGetInstanceId() {\n while (idRequests.length > 0) {\n var idCallback = idRequests.pop();\n idCallback(null, instanceId);\n }\n }\n\n function onGetVersion(tx, dbVersion) {\n if (dbVersion === 0) {\n // initial schema\n\n var meta = 'CREATE TABLE IF NOT EXISTS ' + META_STORE$1 +\n ' (dbid, db_version INTEGER)';\n var attach = 'CREATE TABLE IF NOT EXISTS ' + ATTACH_STORE$1 +\n ' (digest UNIQUE, escaped TINYINT(1), body BLOB)';\n var attachAndRev = 'CREATE TABLE IF NOT EXISTS ' +\n ATTACH_AND_SEQ_STORE$1 + ' (digest, seq INTEGER)';\n // TODO: migrate winningseq to INTEGER\n var doc = 'CREATE TABLE IF NOT EXISTS ' + DOC_STORE$1 +\n ' (id unique, json, winningseq, max_seq INTEGER UNIQUE)';\n var seq = 'CREATE TABLE IF NOT EXISTS ' + BY_SEQ_STORE$1 +\n ' (seq INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, ' +\n 'json, deleted TINYINT(1), doc_id, rev)';\n var local = 'CREATE TABLE IF NOT EXISTS ' + LOCAL_STORE$1 +\n ' (id UNIQUE, rev, json)';\n\n // creates\n tx.executeSql(attach);\n tx.executeSql(local);\n tx.executeSql(attachAndRev, [], function () {\n tx.executeSql(ATTACH_AND_SEQ_STORE_SEQ_INDEX_SQL);\n tx.executeSql(ATTACH_AND_SEQ_STORE_ATTACH_INDEX_SQL);\n });\n tx.executeSql(doc, [], function () {\n tx.executeSql(DOC_STORE_WINNINGSEQ_INDEX_SQL);\n tx.executeSql(seq, [], function () {\n tx.executeSql(BY_SEQ_STORE_DELETED_INDEX_SQL);\n tx.executeSql(BY_SEQ_STORE_DOC_ID_REV_INDEX_SQL);\n tx.executeSql(meta, [], function () {\n // mark the db version, and new dbid\n var initSeq = 'INSERT INTO ' + META_STORE$1 +\n ' (db_version, dbid) VALUES (?,?)';\n instanceId = uuid();\n var initSeqArgs = [ADAPTER_VERSION$1, instanceId];\n tx.executeSql(initSeq, initSeqArgs, function () {\n onGetInstanceId();\n });\n });\n });\n });\n } else { // version > 0\n\n var setupDone = function () {\n var migrated = dbVersion < ADAPTER_VERSION$1;\n if (migrated) {\n // update the db version within this transaction\n tx.executeSql('UPDATE ' + META_STORE$1 + ' SET db_version = ' +\n ADAPTER_VERSION$1);\n }\n // notify db.id() callers\n var sql = 'SELECT dbid FROM ' + META_STORE$1;\n tx.executeSql(sql, [], function (tx, result) {\n instanceId = result.rows.item(0).dbid;\n onGetInstanceId();\n });\n };\n\n // would love to use promises here, but then websql\n // ends the transaction early\n var tasks = [\n runMigration2,\n runMigration3,\n runMigration4,\n runMigration5,\n runMigration6,\n runMigration7,\n setupDone\n ];\n\n // run each migration sequentially\n var i = dbVersion;\n var nextMigration = function (tx) {\n tasks[i - 1](tx, nextMigration);\n i++;\n };\n nextMigration(tx);\n }\n }\n\n function setup() {\n db.transaction(function (tx) {\n // first check the encoding\n checkEncoding(tx, function () {\n // then get the version\n fetchVersion(tx);\n });\n }, websqlError(callback), dbCreated);\n }\n\n function fetchVersion(tx) {\n var sql = 'SELECT sql FROM sqlite_master WHERE tbl_name = ' + META_STORE$1;\n tx.executeSql(sql, [], function (tx, result) {\n if (!result.rows.length) {\n // database hasn't even been created yet (version 0)\n onGetVersion(tx, 0);\n } else if (!/db_version/.test(result.rows.item(0).sql)) {\n // table was created, but without the new db_version column,\n // so add it.\n tx.executeSql('ALTER TABLE ' + META_STORE$1 +\n ' ADD COLUMN db_version INTEGER', [], function () {\n // before version 2, this column didn't even exist\n onGetVersion(tx, 1);\n });\n } else { // column exists, we can safely get it\n tx.executeSql('SELECT db_version FROM ' + META_STORE$1,\n [], function (tx, result) {\n var dbVersion = result.rows.item(0).db_version;\n onGetVersion(tx, dbVersion);\n });\n }\n });\n }\n\n setup();\n\n function getMaxSeq(tx, callback) {\n var sql = 'SELECT MAX(seq) AS seq FROM ' + BY_SEQ_STORE$1;\n tx.executeSql(sql, [], function (tx, res) {\n var updateSeq = res.rows.item(0).seq || 0;\n callback(updateSeq);\n });\n }\n\n function countDocs(tx, callback) {\n // count the total rows\n var sql = select(\n 'COUNT(' + DOC_STORE$1 + '.id) AS \\'num\\'',\n [DOC_STORE$1, BY_SEQ_STORE$1],\n DOC_STORE_AND_BY_SEQ_JOINER,\n BY_SEQ_STORE$1 + '.deleted=0');\n\n tx.executeSql(sql, [], function (tx, result) {\n callback(result.rows.item(0).num);\n });\n }\n\n api.type = function () {\n return 'websql';\n };\n\n api._id = toPromise(function (callback) {\n callback(null, instanceId);\n });\n\n api._info = function (callback) {\n var seq;\n var docCount;\n db.readTransaction(function (tx) {\n getMaxSeq(tx, function (theSeq) {\n seq = theSeq;\n });\n countDocs(tx, function (theDocCount) {\n docCount = theDocCount;\n });\n }, websqlError(callback), function () {\n callback(null, {\n doc_count: docCount,\n update_seq: seq,\n websql_encoding: encoding\n });\n });\n };\n\n api._bulkDocs = function (req, reqOpts, callback) {\n websqlBulkDocs(opts, req, reqOpts, api, db, websqlChanges, callback);\n };\n\n function latest$$1(tx, id, rev, callback, finish) {\n var sql = select(\n SELECT_DOCS,\n [DOC_STORE$1, BY_SEQ_STORE$1],\n DOC_STORE_AND_BY_SEQ_JOINER,\n DOC_STORE$1 + '.id=?');\n var sqlArgs = [id];\n\n tx.executeSql(sql, sqlArgs, function (a, results) {\n if (!results.rows.length) {\n var err = createError(MISSING_DOC, 'missing');\n return finish(err);\n }\n var item = results.rows.item(0);\n var metadata = safeJsonParse(item.metadata);\n callback(latest(rev, metadata));\n });\n }\n\n api._get = function (id, opts, callback) {\n var doc;\n var metadata;\n var tx = opts.ctx;\n if (!tx) {\n return db.readTransaction(function (txn) {\n api._get(id, assign$1({ctx: txn}, opts), callback);\n });\n }\n\n function finish(err) {\n callback(err, {doc: doc, metadata: metadata, ctx: tx});\n }\n\n var sql;\n var sqlArgs;\n\n if(!opts.rev) {\n sql = select(\n SELECT_DOCS,\n [DOC_STORE$1, BY_SEQ_STORE$1],\n DOC_STORE_AND_BY_SEQ_JOINER,\n DOC_STORE$1 + '.id=?');\n sqlArgs = [id];\n } else if (opts.latest) {\n latest$$1(tx, id, opts.rev, function (latestRev) {\n opts.latest = false;\n opts.rev = latestRev;\n api._get(id, opts, callback);\n }, finish);\n return;\n } else {\n sql = select(\n SELECT_DOCS,\n [DOC_STORE$1, BY_SEQ_STORE$1],\n DOC_STORE$1 + '.id=' + BY_SEQ_STORE$1 + '.doc_id',\n [BY_SEQ_STORE$1 + '.doc_id=?', BY_SEQ_STORE$1 + '.rev=?']);\n sqlArgs = [id, opts.rev];\n }\n\n tx.executeSql(sql, sqlArgs, function (a, results) {\n if (!results.rows.length) {\n var missingErr = createError(MISSING_DOC, 'missing');\n return finish(missingErr);\n }\n var item = results.rows.item(0);\n metadata = safeJsonParse(item.metadata);\n if (item.deleted && !opts.rev) {\n var deletedErr = createError(MISSING_DOC, 'deleted');\n return finish(deletedErr);\n }\n doc = unstringifyDoc(item.data, metadata.id, item.rev);\n finish();\n });\n };\n\n api._allDocs = function (opts, callback) {\n var results = [];\n var totalRows;\n\n var start = 'startkey' in opts ? opts.startkey : false;\n var end = 'endkey' in opts ? opts.endkey : false;\n var key = 'key' in opts ? opts.key : false;\n var descending = 'descending' in opts ? opts.descending : false;\n var limit = 'limit' in opts ? opts.limit : -1;\n var offset = 'skip' in opts ? opts.skip : 0;\n var inclusiveEnd = opts.inclusive_end !== false;\n\n var sqlArgs = [];\n var criteria = [];\n\n if (key !== false) {\n criteria.push(DOC_STORE$1 + '.id = ?');\n sqlArgs.push(key);\n } else if (start !== false || end !== false) {\n if (start !== false) {\n criteria.push(DOC_STORE$1 + '.id ' + (descending ? '<=' : '>=') + ' ?');\n sqlArgs.push(start);\n }\n if (end !== false) {\n var comparator = descending ? '>' : '<';\n if (inclusiveEnd) {\n comparator += '=';\n }\n criteria.push(DOC_STORE$1 + '.id ' + comparator + ' ?');\n sqlArgs.push(end);\n }\n if (key !== false) {\n criteria.push(DOC_STORE$1 + '.id = ?');\n sqlArgs.push(key);\n }\n }\n\n if (opts.deleted !== 'ok') {\n // report deleted if keys are specified\n criteria.push(BY_SEQ_STORE$1 + '.deleted = 0');\n }\n\n db.readTransaction(function (tx) {\n // count the docs in parallel to other operations\n countDocs(tx, function (docCount) {\n totalRows = docCount;\n });\n\n if (limit === 0) {\n return;\n }\n\n // do a single query to fetch the documents\n var sql = select(\n SELECT_DOCS,\n [DOC_STORE$1, BY_SEQ_STORE$1],\n DOC_STORE_AND_BY_SEQ_JOINER,\n criteria,\n DOC_STORE$1 + '.id ' + (descending ? 'DESC' : 'ASC')\n );\n sql += ' LIMIT ' + limit + ' OFFSET ' + offset;\n\n tx.executeSql(sql, sqlArgs, function (tx, result) {\n for (var i = 0, l = result.rows.length; i < l; i++) {\n var item = result.rows.item(i);\n var metadata = safeJsonParse(item.metadata);\n var id = metadata.id;\n var data = unstringifyDoc(item.data, id, item.rev);\n var winningRev$$1 = data._rev;\n var doc = {\n id: id,\n key: id,\n value: {rev: winningRev$$1}\n };\n if (opts.include_docs) {\n doc.doc = data;\n doc.doc._rev = winningRev$$1;\n if (opts.conflicts) {\n var conflicts = collectConflicts(metadata);\n if (conflicts.length) {\n doc.doc._conflicts = conflicts;\n }\n }\n fetchAttachmentsIfNecessary$1(doc.doc, opts, api, tx);\n }\n if (item.deleted) {\n if (opts.deleted === 'ok') {\n doc.value.deleted = true;\n doc.doc = null;\n } else {\n continue;\n }\n }\n results.push(doc);\n }\n });\n }, websqlError(callback), function () {\n callback(null, {\n total_rows: totalRows,\n offset: opts.skip,\n rows: results\n });\n });\n };\n\n api._changes = function (opts) {\n opts = clone(opts);\n\n if (opts.continuous) {\n var id = api._name + ':' + uuid();\n websqlChanges.addListener(api._name, id, api, opts);\n websqlChanges.notify(api._name);\n return {\n cancel: function () {\n websqlChanges.removeListener(api._name, id);\n }\n };\n }\n\n var descending = opts.descending;\n\n // Ignore the `since` parameter when `descending` is true\n opts.since = opts.since && !descending ? opts.since : 0;\n\n var limit = 'limit' in opts ? opts.limit : -1;\n if (limit === 0) {\n limit = 1; // per CouchDB _changes spec\n }\n\n var returnDocs;\n if ('return_docs' in opts) {\n returnDocs = opts.return_docs;\n } else if ('returnDocs' in opts) {\n // TODO: Remove 'returnDocs' in favor of 'return_docs' in a future release\n returnDocs = opts.returnDocs;\n } else {\n returnDocs = true;\n }\n var results = [];\n var numResults = 0;\n\n function fetchChanges() {\n\n var selectStmt =\n DOC_STORE$1 + '.json AS metadata, ' +\n DOC_STORE$1 + '.max_seq AS maxSeq, ' +\n BY_SEQ_STORE$1 + '.json AS winningDoc, ' +\n BY_SEQ_STORE$1 + '.rev AS winningRev ';\n\n var from = DOC_STORE$1 + ' JOIN ' + BY_SEQ_STORE$1;\n\n var joiner = DOC_STORE$1 + '.id=' + BY_SEQ_STORE$1 + '.doc_id' +\n ' AND ' + DOC_STORE$1 + '.winningseq=' + BY_SEQ_STORE$1 + '.seq';\n\n var criteria = ['maxSeq > ?'];\n var sqlArgs = [opts.since];\n\n if (opts.doc_ids) {\n criteria.push(DOC_STORE$1 + '.id IN ' + qMarks(opts.doc_ids.length));\n sqlArgs = sqlArgs.concat(opts.doc_ids);\n }\n\n var orderBy = 'maxSeq ' + (descending ? 'DESC' : 'ASC');\n\n var sql = select(selectStmt, from, joiner, criteria, orderBy);\n\n var filter = filterChange(opts);\n if (!opts.view && !opts.filter) {\n // we can just limit in the query\n sql += ' LIMIT ' + limit;\n }\n\n var lastSeq = opts.since || 0;\n db.readTransaction(function (tx) {\n tx.executeSql(sql, sqlArgs, function (tx, result) {\n function reportChange(change) {\n return function () {\n opts.onChange(change);\n };\n }\n for (var i = 0, l = result.rows.length; i < l; i++) {\n var item = result.rows.item(i);\n var metadata = safeJsonParse(item.metadata);\n lastSeq = item.maxSeq;\n\n var doc = unstringifyDoc(item.winningDoc, metadata.id,\n item.winningRev);\n var change = opts.processChange(doc, metadata, opts);\n change.seq = item.maxSeq;\n\n var filtered = filter(change);\n if (typeof filtered === 'object') {\n return opts.complete(filtered);\n }\n\n if (filtered) {\n numResults++;\n if (returnDocs) {\n results.push(change);\n }\n // process the attachment immediately\n // for the benefit of live listeners\n if (opts.attachments && opts.include_docs) {\n fetchAttachmentsIfNecessary$1(doc, opts, api, tx,\n reportChange(change));\n } else {\n reportChange(change)();\n }\n }\n if (numResults === limit) {\n break;\n }\n }\n });\n }, websqlError(opts.complete), function () {\n if (!opts.continuous) {\n opts.complete(null, {\n results: results,\n last_seq: lastSeq\n });\n }\n });\n }\n\n fetchChanges();\n };\n\n api._close = function (callback) {\n //WebSQL databases do not need to be closed\n callback();\n };\n\n api._getAttachment = function (docId, attachId, attachment, opts, callback) {\n var res;\n var tx = opts.ctx;\n var digest = attachment.digest;\n var type = attachment.content_type;\n var sql = 'SELECT escaped, ' +\n 'CASE WHEN escaped = 1 THEN body ELSE HEX(body) END AS body FROM ' +\n ATTACH_STORE$1 + ' WHERE digest=?';\n tx.executeSql(sql, [digest], function (tx, result) {\n // websql has a bug where \\u0000 causes early truncation in strings\n // and blobs. to work around this, we used to use the hex() function,\n // but that's not performant. after migration 6, we remove \\u0000\n // and add it back in afterwards\n var item = result.rows.item(0);\n var data = item.escaped ? unescapeBlob(item.body) :\n parseHexString(item.body, encoding);\n if (opts.binary) {\n res = binStringToBluffer(data, type);\n } else {\n res = thisBtoa(data);\n }\n callback(null, res);\n });\n };\n\n api._getRevisionTree = function (docId, callback) {\n db.readTransaction(function (tx) {\n var sql = 'SELECT json AS metadata FROM ' + DOC_STORE$1 + ' WHERE id = ?';\n tx.executeSql(sql, [docId], function (tx, result) {\n if (!result.rows.length) {\n callback(createError(MISSING_DOC));\n } else {\n var data = safeJsonParse(result.rows.item(0).metadata);\n callback(null, data.rev_tree);\n }\n });\n });\n };\n\n api._doCompaction = function (docId, revs, callback) {\n if (!revs.length) {\n return callback();\n }\n db.transaction(function (tx) {\n\n // update doc store\n var sql = 'SELECT json AS metadata FROM ' + DOC_STORE$1 + ' WHERE id = ?';\n tx.executeSql(sql, [docId], function (tx, result) {\n var metadata = safeJsonParse(result.rows.item(0).metadata);\n traverseRevTree(metadata.rev_tree, function (isLeaf, pos,\n revHash, ctx, opts) {\n var rev = pos + '-' + revHash;\n if (revs.indexOf(rev) !== -1) {\n opts.status = 'missing';\n }\n });\n\n var sql = 'UPDATE ' + DOC_STORE$1 + ' SET json = ? WHERE id = ?';\n tx.executeSql(sql, [safeJsonStringify(metadata), docId]);\n });\n\n compactRevs$1(revs, docId, tx);\n }, websqlError(callback), function () {\n callback();\n });\n };\n\n api._getLocal = function (id, callback) {\n db.readTransaction(function (tx) {\n var sql = 'SELECT json, rev FROM ' + LOCAL_STORE$1 + ' WHERE id=?';\n tx.executeSql(sql, [id], function (tx, res) {\n if (res.rows.length) {\n var item = res.rows.item(0);\n var doc = unstringifyDoc(item.json, id, item.rev);\n callback(null, doc);\n } else {\n callback(createError(MISSING_DOC));\n }\n });\n });\n };\n\n api._putLocal = function (doc, opts, callback) {\n if (typeof opts === 'function') {\n callback = opts;\n opts = {};\n }\n delete doc._revisions; // ignore this, trust the rev\n var oldRev = doc._rev;\n var id = doc._id;\n var newRev;\n if (!oldRev) {\n newRev = doc._rev = '0-1';\n } else {\n newRev = doc._rev = '0-' + (parseInt(oldRev.split('-')[1], 10) + 1);\n }\n var json = stringifyDoc(doc);\n\n var ret;\n function putLocal(tx) {\n var sql;\n var values;\n if (oldRev) {\n sql = 'UPDATE ' + LOCAL_STORE$1 + ' SET rev=?, json=? ' +\n 'WHERE id=? AND rev=?';\n values = [newRev, json, id, oldRev];\n } else {\n sql = 'INSERT INTO ' + LOCAL_STORE$1 + ' (id, rev, json) VALUES (?,?,?)';\n values = [id, newRev, json];\n }\n tx.executeSql(sql, values, function (tx, res) {\n if (res.rowsAffected) {\n ret = {ok: true, id: id, rev: newRev};\n if (opts.ctx) { // return immediately\n callback(null, ret);\n }\n } else {\n callback(createError(REV_CONFLICT));\n }\n }, function () {\n callback(createError(REV_CONFLICT));\n return false; // ack that we handled the error\n });\n }\n\n if (opts.ctx) {\n putLocal(opts.ctx);\n } else {\n db.transaction(putLocal, websqlError(callback), function () {\n if (ret) {\n callback(null, ret);\n }\n });\n }\n };\n\n api._removeLocal = function (doc, opts, callback) {\n if (typeof opts === 'function') {\n callback = opts;\n opts = {};\n }\n var ret;\n\n function removeLocal(tx) {\n var sql = 'DELETE FROM ' + LOCAL_STORE$1 + ' WHERE id=? AND rev=?';\n var params = [doc._id, doc._rev];\n tx.executeSql(sql, params, function (tx, res) {\n if (!res.rowsAffected) {\n return callback(createError(MISSING_DOC));\n }\n ret = {ok: true, id: doc._id, rev: '0-0'};\n if (opts.ctx) { // return immediately\n callback(null, ret);\n }\n });\n }\n\n if (opts.ctx) {\n removeLocal(opts.ctx);\n } else {\n db.transaction(removeLocal, websqlError(callback), function () {\n if (ret) {\n callback(null, ret);\n }\n });\n }\n };\n\n api._destroy = function (opts, callback) {\n websqlChanges.removeAllListeners(api._name);\n db.transaction(function (tx) {\n var stores = [DOC_STORE$1, BY_SEQ_STORE$1, ATTACH_STORE$1, META_STORE$1,\n LOCAL_STORE$1, ATTACH_AND_SEQ_STORE$1];\n stores.forEach(function (store) {\n tx.executeSql('DROP TABLE IF EXISTS ' + store, []);\n });\n }, websqlError(callback), function () {\n if (hasLocalStorage()) {\n delete window.localStorage['_pouch__websqldb_' + api._name];\n delete window.localStorage[api._name];\n }\n callback(null, {'ok': true});\n });\n };\n}\n\nfunction canOpenTestDB() {\n try {\n openDatabase('_pouch_validate_websql', 1, '', 1);\n return true;\n } catch (err) {\n return false;\n }\n}\n\n// WKWebView had a bug where WebSQL would throw a DOM Exception 18\n// (see https://bugs.webkit.org/show_bug.cgi?id=137760 and\n// https://github.com/pouchdb/pouchdb/issues/5079)\n// This has been fixed in latest WebKit, so we try to detect it here.\nfunction isValidWebSQL() {\n // WKWebView UA:\n // Mozilla/5.0 (iPhone; CPU iPhone OS 9_2 like Mac OS X)\n // AppleWebKit/601.1.46 (KHTML, like Gecko) Mobile/13C75\n // Chrome for iOS UA:\n // Mozilla/5.0 (iPhone; U; CPU iPhone OS 5_1_1 like Mac OS X; en)\n // AppleWebKit/534.46.0 (KHTML, like Gecko) CriOS/19.0.1084.60\n // Mobile/9B206 Safari/7534.48.3\n // Firefox for iOS UA:\n // Mozilla/5.0 (iPhone; CPU iPhone OS 8_3 like Mac OS X) AppleWebKit/600.1.4\n // (KHTML, like Gecko) FxiOS/1.0 Mobile/12F69 Safari/600.1.4\n\n // indexedDB is null on some UIWebViews and undefined in others\n // see: https://bugs.webkit.org/show_bug.cgi?id=137034\n if (typeof indexedDB === 'undefined' || indexedDB === null ||\n !/iP(hone|od|ad)/.test(navigator.userAgent)) {\n // definitely not WKWebView, avoid creating an unnecessary database\n return true;\n }\n // Cache the result in LocalStorage. Reason we do this is because if we\n // call openDatabase() too many times, Safari craps out in SauceLabs and\n // starts throwing DOM Exception 14s.\n var hasLS = hasLocalStorage();\n // Include user agent in the hash, so that if Safari is upgraded, we don't\n // continually think it's broken.\n var localStorageKey = '_pouch__websqldb_valid_' + navigator.userAgent;\n if (hasLS && localStorage[localStorageKey]) {\n return localStorage[localStorageKey] === '1';\n }\n var openedTestDB = canOpenTestDB();\n if (hasLS) {\n localStorage[localStorageKey] = openedTestDB ? '1' : '0';\n }\n return openedTestDB;\n}\n\nfunction valid() {\n if (typeof openDatabase !== 'function') {\n return false;\n }\n return isValidWebSQL();\n}\n\nfunction openDB(name, version, description, size) {\n // Traditional WebSQL API\n return openDatabase(name, version, description, size);\n}\n\nfunction WebSQLPouch(opts, callback) {\n var _opts = assign$1({\n websql: openDB\n }, opts);\n\n WebSqlPouch$1.call(this, _opts, callback);\n}\n\nWebSQLPouch.valid = valid;\n\nWebSQLPouch.use_prefix = true;\n\nvar WebSqlPouch = function (PouchDB) {\n PouchDB.adapter('websql', WebSQLPouch, true);\n};\n\n/* global fetch */\n/* global Headers */\nfunction wrappedFetch() {\n var wrappedPromise = {};\n\n var promise = new PouchPromise$1(function (resolve, reject) {\n wrappedPromise.resolve = resolve;\n wrappedPromise.reject = reject;\n });\n\n var args = new Array(arguments.length);\n\n for (var i = 0; i < args.length; i++) {\n args[i] = arguments[i];\n }\n\n wrappedPromise.promise = promise;\n\n PouchPromise$1.resolve().then(function () {\n return fetch.apply(null, args);\n }).then(function (response) {\n wrappedPromise.resolve(response);\n }).catch(function (error) {\n wrappedPromise.reject(error);\n });\n\n return wrappedPromise;\n}\n\nfunction fetchRequest(options, callback) {\n var wrappedPromise, timer, response;\n\n var headers = new Headers();\n\n var fetchOptions = {\n method: options.method,\n credentials: 'include',\n headers: headers\n };\n\n if (options.json) {\n headers.set('Accept', 'application/json');\n headers.set('Content-Type', options.headers['Content-Type'] ||\n 'application/json');\n }\n\n if (options.body &&\n options.processData &&\n typeof options.body !== 'string') {\n fetchOptions.body = JSON.stringify(options.body);\n } else if ('body' in options) {\n fetchOptions.body = options.body;\n } else {\n fetchOptions.body = null;\n }\n\n Object.keys(options.headers).forEach(function (key) {\n if (options.headers.hasOwnProperty(key)) {\n headers.set(key, options.headers[key]);\n }\n });\n\n wrappedPromise = wrappedFetch(options.url, fetchOptions);\n\n if (options.timeout > 0) {\n timer = setTimeout(function () {\n wrappedPromise.reject(new Error('Load timeout for resource: ' +\n options.url));\n }, options.timeout);\n }\n\n wrappedPromise.promise.then(function (fetchResponse) {\n response = {\n statusCode: fetchResponse.status\n };\n\n if (options.timeout > 0) {\n clearTimeout(timer);\n }\n\n if (response.statusCode >= 200 && response.statusCode < 300) {\n return options.binary ? fetchResponse.blob() : fetchResponse.text();\n }\n\n return fetchResponse.json();\n }).then(function (result) {\n if (response.statusCode >= 200 && response.statusCode < 300) {\n callback(null, response, result);\n } else {\n result.status = response.statusCode;\n callback(result);\n }\n }).catch(function (error) {\n if (!error) {\n // this happens when the listener is canceled\n error = new Error('canceled');\n }\n callback(error);\n });\n\n return {abort: wrappedPromise.reject};\n}\n\nfunction xhRequest(options, callback) {\n\n var xhr, timer;\n var timedout = false;\n\n var abortReq = function () {\n xhr.abort();\n cleanUp();\n };\n\n var timeoutReq = function () {\n timedout = true;\n xhr.abort();\n cleanUp();\n };\n\n var ret = {abort: abortReq};\n\n var cleanUp = function () {\n clearTimeout(timer);\n ret.abort = function () {};\n if (xhr) {\n xhr.onprogress = undefined;\n if (xhr.upload) {\n xhr.upload.onprogress = undefined;\n }\n xhr.onreadystatechange = undefined;\n xhr = undefined;\n }\n };\n\n if (options.xhr) {\n xhr = new options.xhr();\n } else {\n xhr = new XMLHttpRequest();\n }\n\n try {\n xhr.open(options.method, options.url);\n } catch (exception) {\n return callback(new Error(exception.name || 'Url is invalid'));\n }\n\n xhr.withCredentials = ('withCredentials' in options) ?\n options.withCredentials : true;\n\n if (options.method === 'GET') {\n delete options.headers['Content-Type'];\n } else if (options.json) {\n options.headers.Accept = 'application/json';\n options.headers['Content-Type'] = options.headers['Content-Type'] ||\n 'application/json';\n if (options.body &&\n options.processData &&\n typeof options.body !== \"string\") {\n options.body = JSON.stringify(options.body);\n }\n }\n\n if (options.binary) {\n xhr.responseType = 'arraybuffer';\n }\n\n if (!('body' in options)) {\n options.body = null;\n }\n\n for (var key in options.headers) {\n if (options.headers.hasOwnProperty(key)) {\n xhr.setRequestHeader(key, options.headers[key]);\n }\n }\n\n if (options.timeout > 0) {\n timer = setTimeout(timeoutReq, options.timeout);\n xhr.onprogress = function () {\n clearTimeout(timer);\n if(xhr.readyState !== 4) {\n timer = setTimeout(timeoutReq, options.timeout);\n }\n };\n if (typeof xhr.upload !== 'undefined') { // does not exist in ie9\n xhr.upload.onprogress = xhr.onprogress;\n }\n }\n\n xhr.onreadystatechange = function () {\n if (xhr.readyState !== 4) {\n return;\n }\n\n var response = {\n statusCode: xhr.status\n };\n\n if (xhr.status >= 200 && xhr.status < 300) {\n var data;\n if (options.binary) {\n data = createBlob([xhr.response || ''], {\n type: xhr.getResponseHeader('Content-Type')\n });\n } else {\n data = xhr.responseText;\n }\n callback(null, response, data);\n } else {\n var err = {};\n if (timedout) {\n err = new Error('ETIMEDOUT');\n err.code = 'ETIMEDOUT';\n } else if (typeof xhr.response === 'string') {\n try {\n err = JSON.parse(xhr.response);\n } catch(e) {}\n }\n err.status = xhr.status;\n callback(err);\n }\n cleanUp();\n };\n\n if (options.body && (options.body instanceof Blob)) {\n readAsArrayBuffer(options.body, function (arrayBuffer) {\n xhr.send(arrayBuffer);\n });\n } else {\n xhr.send(options.body);\n }\n\n return ret;\n}\n\nfunction testXhr() {\n try {\n new XMLHttpRequest();\n return true;\n } catch (err) {\n return false;\n }\n}\n\nvar hasXhr = testXhr();\n\nfunction ajax$1(options, callback) {\n if (!false && (hasXhr || options.xhr)) {\n return xhRequest(options, callback);\n } else {\n return fetchRequest(options, callback);\n }\n}\n\n// the blob already has a type; do nothing\nvar res$2 = function () {};\n\nfunction defaultBody() {\n return '';\n}\n\nfunction ajaxCore$1(options, callback) {\n\n options = clone(options);\n\n var defaultOptions = {\n method : \"GET\",\n headers: {},\n json: true,\n processData: true,\n timeout: 10000,\n cache: false\n };\n\n options = assign$1(defaultOptions, options);\n\n function onSuccess(obj, resp, cb) {\n if (!options.binary && options.json && typeof obj === 'string') {\n /* istanbul ignore next */\n try {\n obj = JSON.parse(obj);\n } catch (e) {\n // Probably a malformed JSON from server\n return cb(e);\n }\n }\n if (Array.isArray(obj)) {\n obj = obj.map(function (v) {\n if (v.error || v.missing) {\n return generateErrorFromResponse(v);\n } else {\n return v;\n }\n });\n }\n if (options.binary) {\n res$2(obj, resp);\n }\n cb(null, obj, resp);\n }\n\n if (options.json) {\n if (!options.binary) {\n options.headers.Accept = 'application/json';\n }\n options.headers['Content-Type'] = options.headers['Content-Type'] ||\n 'application/json';\n }\n\n if (options.binary) {\n options.encoding = null;\n options.json = false;\n }\n\n if (!options.processData) {\n options.json = false;\n }\n\n return ajax$1(options, function (err, response, body) {\n\n if (err) {\n return callback(generateErrorFromResponse(err));\n }\n\n var error;\n var content_type = response.headers && response.headers['content-type'];\n var data = body || defaultBody();\n\n // CouchDB doesn't always return the right content-type for JSON data, so\n // we check for ^{ and }$ (ignoring leading/trailing whitespace)\n if (!options.binary && (options.json || !options.processData) &&\n typeof data !== 'object' &&\n (/json/.test(content_type) ||\n (/^[\\s]*\\{/.test(data) && /\\}[\\s]*$/.test(data)))) {\n try {\n data = JSON.parse(data.toString());\n } catch (e) {}\n }\n\n if (response.statusCode >= 200 && response.statusCode < 300) {\n onSuccess(data, response, callback);\n } else {\n error = generateErrorFromResponse(data);\n error.status = response.statusCode;\n callback(error);\n }\n });\n}\n\nfunction ajax(opts, callback) {\n\n // cache-buster, specifically designed to work around IE's aggressive caching\n // see http://www.dashbay.com/2011/05/internet-explorer-caches-ajax/\n // Also Safari caches POSTs, so we need to cache-bust those too.\n var ua = (navigator && navigator.userAgent) ?\n navigator.userAgent.toLowerCase() : '';\n\n var isSafari = ua.indexOf('safari') !== -1 && ua.indexOf('chrome') === -1;\n var isIE = ua.indexOf('msie') !== -1;\n var isEdge = ua.indexOf('edge') !== -1;\n\n // it appears the new version of safari also caches GETs,\n // see https://github.com/pouchdb/pouchdb/issues/5010\n var shouldCacheBust = (isSafari ||\n ((isIE || isEdge) && opts.method === 'GET'));\n\n var cache = 'cache' in opts ? opts.cache : true;\n\n var isBlobUrl = /^blob:/.test(opts.url); // don't append nonces for blob URLs\n\n if (!isBlobUrl && (shouldCacheBust || !cache)) {\n var hasArgs = opts.url.indexOf('?') !== -1;\n opts.url += (hasArgs ? '&' : '?') + '_nonce=' + Date.now();\n }\n\n return ajaxCore$1(opts, callback);\n}\n\n// dead simple promise pool, inspired by https://github.com/timdp/es6-promise-pool\n// but much smaller in code size. limits the number of concurrent promises that are executed\n\nfunction pool(promiseFactories, limit) {\n return new PouchPromise$1(function (resolve, reject) {\n var running = 0;\n var current = 0;\n var done = 0;\n var len = promiseFactories.length;\n var err;\n\n function runNext() {\n running++;\n promiseFactories[current++]().then(onSuccess, onError);\n }\n\n function doNext() {\n if (++done === len) {\n /* istanbul ignore if */\n if (err) {\n reject(err);\n } else {\n resolve();\n }\n } else {\n runNextBatch();\n }\n }\n\n function onSuccess() {\n running--;\n doNext();\n }\n\n /* istanbul ignore next */\n function onError(thisErr) {\n running--;\n err = err || thisErr;\n doNext();\n }\n\n function runNextBatch() {\n while (running < limit && current < len) {\n runNext();\n }\n }\n\n runNextBatch();\n });\n}\n\nvar CHANGES_BATCH_SIZE = 25;\nvar MAX_SIMULTANEOUS_REVS = 50;\n\nvar supportsBulkGetMap = {};\n\nvar log$1 = debug('pouchdb:http');\n\nfunction readAttachmentsAsBlobOrBuffer(row) {\n var atts = row.doc && row.doc._attachments;\n if (!atts) {\n return;\n }\n Object.keys(atts).forEach(function (filename) {\n var att = atts[filename];\n att.data = b64ToBluffer(att.data, att.content_type);\n });\n}\n\nfunction encodeDocId(id) {\n if (/^_design/.test(id)) {\n return '_design/' + encodeURIComponent(id.slice(8));\n }\n if (/^_local/.test(id)) {\n return '_local/' + encodeURIComponent(id.slice(7));\n }\n return encodeURIComponent(id);\n}\n\nfunction preprocessAttachments$2(doc) {\n if (!doc._attachments || !Object.keys(doc._attachments)) {\n return PouchPromise$1.resolve();\n }\n\n return PouchPromise$1.all(Object.keys(doc._attachments).map(function (key) {\n var attachment = doc._attachments[key];\n if (attachment.data && typeof attachment.data !== 'string') {\n return new PouchPromise$1(function (resolve) {\n blobToBase64(attachment.data, resolve);\n }).then(function (b64) {\n attachment.data = b64;\n });\n }\n }));\n}\n\nfunction hasUrlPrefix(opts) {\n if (!opts.prefix) {\n return false;\n }\n\n var protocol = parseUri(opts.prefix).protocol;\n\n return protocol === 'http' || protocol === 'https';\n}\n\n// Get all the information you possibly can about the URI given by name and\n// return it as a suitable object.\nfunction getHost(name, opts) {\n\n // encode db name if opts.prefix is a url (#5574)\n if (hasUrlPrefix(opts)) {\n var dbName = opts.name.substr(opts.prefix.length);\n name = opts.prefix + encodeURIComponent(dbName);\n }\n\n // Prase the URI into all its little bits\n var uri = parseUri(name);\n\n // Store the user and password as a separate auth object\n if (uri.user || uri.password) {\n uri.auth = {username: uri.user, password: uri.password};\n }\n\n // Split the path part of the URI into parts using '/' as the delimiter\n // after removing any leading '/' and any trailing '/'\n var parts = uri.path.replace(/(^\\/|\\/$)/g, '').split('/');\n\n // Store the first part as the database name and remove it from the parts\n // array\n uri.db = parts.pop();\n // Prevent double encoding of URI component\n if (uri.db.indexOf('%') === -1) {\n uri.db = encodeURIComponent(uri.db);\n }\n\n // Restore the path by joining all the remaining parts (all the parts\n // except for the database name) with '/'s\n uri.path = parts.join('/');\n\n return uri;\n}\n\n// Generate a URL with the host data given by opts and the given path\nfunction genDBUrl(opts, path) {\n return genUrl(opts, opts.db + '/' + path);\n}\n\n// Generate a URL with the host data given by opts and the given path\nfunction genUrl(opts, path) {\n // If the host already has a path, then we need to have a path delimiter\n // Otherwise, the path delimiter is the empty string\n var pathDel = !opts.path ? '' : '/';\n\n // If the host already has a path, then we need to have a path delimiter\n // Otherwise, the path delimiter is the empty string\n return opts.protocol + '://' + opts.host +\n (opts.port ? (':' + opts.port) : '') +\n '/' + opts.path + pathDel + path;\n}\n\nfunction paramsToStr(params) {\n return '?' + Object.keys(params).map(function (k) {\n return k + '=' + encodeURIComponent(params[k]);\n }).join('&');\n}\n\n// Implements the PouchDB API for dealing with CouchDB instances over HTTP\nfunction HttpPouch(opts, callback) {\n\n // The functions that will be publicly available for HttpPouch\n var api = this;\n\n var host = getHost(opts.name, opts);\n var dbUrl = genDBUrl(host, '');\n\n opts = clone(opts);\n var ajaxOpts = opts.ajax || {};\n\n if (opts.auth || host.auth) {\n var nAuth = opts.auth || host.auth;\n var str = nAuth.username + ':' + nAuth.password;\n var token = thisBtoa(unescape(encodeURIComponent(str)));\n ajaxOpts.headers = ajaxOpts.headers || {};\n ajaxOpts.headers.Authorization = 'Basic ' + token;\n }\n\n // Not strictly necessary, but we do this because numerous tests\n // rely on swapping ajax in and out.\n api._ajax = ajax;\n\n function ajax$$1(userOpts, options, callback) {\n var reqAjax = userOpts.ajax || {};\n var reqOpts = assign$1(clone(ajaxOpts), reqAjax, options);\n log$1(reqOpts.method + ' ' + reqOpts.url);\n return api._ajax(reqOpts, callback);\n }\n\n function ajaxPromise(userOpts, opts) {\n return new PouchPromise$1(function (resolve, reject) {\n ajax$$1(userOpts, opts, function (err, res) {\n /* istanbul ignore if */\n if (err) {\n return reject(err);\n }\n resolve(res);\n });\n });\n }\n\n function adapterFun$$1(name, fun) {\n return adapterFun(name, getArguments(function (args) {\n setup().then(function () {\n return fun.apply(this, args);\n }).catch(function (e) {\n var callback = args.pop();\n callback(e);\n });\n }));\n }\n\n var setupPromise;\n\n function setup() {\n // TODO: Remove `skipSetup` in favor of `skip_setup` in a future release\n if (opts.skipSetup || opts.skip_setup) {\n return PouchPromise$1.resolve();\n }\n\n // If there is a setup in process or previous successful setup\n // done then we will use that\n // If previous setups have been rejected we will try again\n if (setupPromise) {\n return setupPromise;\n }\n\n var checkExists = {method: 'GET', url: dbUrl};\n setupPromise = ajaxPromise({}, checkExists).catch(function (err) {\n if (err && err.status && err.status === 404) {\n // Doesnt exist, create it\n explainError(404, 'PouchDB is just detecting if the remote exists.');\n return ajaxPromise({}, {method: 'PUT', url: dbUrl});\n } else {\n return PouchPromise$1.reject(err);\n }\n }).catch(function (err) {\n // If we try to create a database that already exists, skipped in\n // istanbul since its catching a race condition.\n /* istanbul ignore if */\n if (err && err.status && err.status === 412) {\n return true;\n }\n return PouchPromise$1.reject(err);\n });\n\n setupPromise.catch(function () {\n setupPromise = null;\n });\n\n return setupPromise;\n }\n\n nextTick(function () {\n callback(null, api);\n });\n\n api.type = function () {\n return 'http';\n };\n\n api.id = adapterFun$$1('id', function (callback) {\n ajax$$1({}, {method: 'GET', url: genUrl(host, '')}, function (err, result) {\n var uuid$$1 = (result && result.uuid) ?\n (result.uuid + host.db) : genDBUrl(host, '');\n callback(null, uuid$$1);\n });\n });\n\n api.request = adapterFun$$1('request', function (options, callback) {\n options.url = genDBUrl(host, options.url);\n ajax$$1({}, options, callback);\n });\n\n // Sends a POST request to the host calling the couchdb _compact function\n // version: The version of CouchDB it is running\n api.compact = adapterFun$$1('compact', function (opts, callback) {\n if (typeof opts === 'function') {\n callback = opts;\n opts = {};\n }\n opts = clone(opts);\n ajax$$1(opts, {\n url: genDBUrl(host, '_compact'),\n method: 'POST'\n }, function () {\n function ping() {\n api.info(function (err, res) {\n if (res && !res.compact_running) {\n callback(null, {ok: true});\n } else {\n setTimeout(ping, opts.interval || 200);\n }\n });\n }\n // Ping the http if it's finished compaction\n ping();\n });\n });\n\n api.bulkGet = adapterFun('bulkGet', function (opts, callback) {\n var self = this;\n\n function doBulkGet(cb) {\n var params = {};\n if (opts.revs) {\n params.revs = true;\n }\n if (opts.attachments) {\n /* istanbul ignore next */\n params.attachments = true;\n }\n if (opts.latest) {\n params.latest = true;\n }\n ajax$$1(opts, {\n url: genDBUrl(host, '_bulk_get' + paramsToStr(params)),\n method: 'POST',\n body: { docs: opts.docs}\n }, cb);\n }\n\n function doBulkGetShim() {\n // avoid \"url too long error\" by splitting up into multiple requests\n var batchSize = MAX_SIMULTANEOUS_REVS;\n var numBatches = Math.ceil(opts.docs.length / batchSize);\n var numDone = 0;\n var results = new Array(numBatches);\n\n function onResult(batchNum) {\n return function (err, res) {\n // err is impossible because shim returns a list of errs in that case\n results[batchNum] = res.results;\n if (++numDone === numBatches) {\n callback(null, {results: flatten(results)});\n }\n };\n }\n\n for (var i = 0; i < numBatches; i++) {\n var subOpts = pick(opts, ['revs', 'attachments', 'latest']);\n subOpts.ajax = ajaxOpts;\n subOpts.docs = opts.docs.slice(i * batchSize,\n Math.min(opts.docs.length, (i + 1) * batchSize));\n bulkGet(self, subOpts, onResult(i));\n }\n }\n\n // mark the whole database as either supporting or not supporting _bulk_get\n var dbUrl = genUrl(host, '');\n var supportsBulkGet = supportsBulkGetMap[dbUrl];\n\n if (typeof supportsBulkGet !== 'boolean') {\n // check if this database supports _bulk_get\n doBulkGet(function (err, res) {\n /* istanbul ignore else */\n if (err) {\n supportsBulkGetMap[dbUrl] = false;\n explainError(\n err.status,\n 'PouchDB is just detecting if the remote ' +\n 'supports the _bulk_get API.'\n );\n doBulkGetShim();\n } else {\n supportsBulkGetMap[dbUrl] = true;\n callback(null, res);\n }\n });\n } else if (supportsBulkGet) {\n /* istanbul ignore next */\n doBulkGet(callback);\n } else {\n doBulkGetShim();\n }\n });\n\n // Calls GET on the host, which gets back a JSON string containing\n // couchdb: A welcome string\n // version: The version of CouchDB it is running\n api._info = function (callback) {\n setup().then(function () {\n ajax$$1({}, {\n method: 'GET',\n url: genDBUrl(host, '')\n }, function (err, res) {\n /* istanbul ignore next */\n if (err) {\n return callback(err);\n }\n res.host = genDBUrl(host, '');\n callback(null, res);\n });\n }).catch(callback);\n };\n\n // Get the document with the given id from the database given by host.\n // The id could be solely the _id in the database, or it may be a\n // _design/ID or _local/ID path\n api.get = adapterFun$$1('get', function (id, opts, callback) {\n // If no options were given, set the callback to the second parameter\n if (typeof opts === 'function') {\n callback = opts;\n opts = {};\n }\n opts = clone(opts);\n\n // List of parameters to add to the GET request\n var params = {};\n\n if (opts.revs) {\n params.revs = true;\n }\n\n if (opts.revs_info) {\n params.revs_info = true;\n }\n\n if (opts.latest) {\n params.latest = true;\n }\n\n if (opts.open_revs) {\n if (opts.open_revs !== \"all\") {\n opts.open_revs = JSON.stringify(opts.open_revs);\n }\n params.open_revs = opts.open_revs;\n }\n\n if (opts.rev) {\n params.rev = opts.rev;\n }\n\n if (opts.conflicts) {\n params.conflicts = opts.conflicts;\n }\n\n id = encodeDocId(id);\n\n // Set the options for the ajax call\n var options = {\n method: 'GET',\n url: genDBUrl(host, id + paramsToStr(params))\n };\n\n function fetchAttachments(doc) {\n var atts = doc._attachments;\n var filenames = atts && Object.keys(atts);\n if (!atts || !filenames.length) {\n return;\n }\n // we fetch these manually in separate XHRs, because\n // Sync Gateway would normally send it back as multipart/mixed,\n // which we cannot parse. Also, this is more efficient than\n // receiving attachments as base64-encoded strings.\n function fetch(filename) {\n var att = atts[filename];\n var path = encodeDocId(doc._id) + '/' + encodeAttachmentId(filename) +\n '?rev=' + doc._rev;\n return ajaxPromise(opts, {\n method: 'GET',\n url: genDBUrl(host, path),\n binary: true\n }).then(function (blob$$1) {\n if (opts.binary) {\n return blob$$1;\n }\n return new PouchPromise$1(function (resolve) {\n blobToBase64(blob$$1, resolve);\n });\n }).then(function (data) {\n delete att.stub;\n delete att.length;\n att.data = data;\n });\n }\n\n var promiseFactories = filenames.map(function (filename) {\n return function () {\n return fetch(filename);\n };\n });\n\n // This limits the number of parallel xhr requests to 5 any time\n // to avoid issues with maximum browser request limits\n return pool(promiseFactories, 5);\n }\n\n function fetchAllAttachments(docOrDocs) {\n if (Array.isArray(docOrDocs)) {\n return PouchPromise$1.all(docOrDocs.map(function (doc) {\n if (doc.ok) {\n return fetchAttachments(doc.ok);\n }\n }));\n }\n return fetchAttachments(docOrDocs);\n }\n\n ajaxPromise(opts, options).then(function (res) {\n return PouchPromise$1.resolve().then(function () {\n if (opts.attachments) {\n return fetchAllAttachments(res);\n }\n }).then(function () {\n callback(null, res);\n });\n }).catch(callback);\n });\n\n // Delete the document given by doc from the database given by host.\n api.remove = adapterFun$$1('remove',\n function (docOrId, optsOrRev, opts, callback) {\n var doc;\n if (typeof optsOrRev === 'string') {\n // id, rev, opts, callback style\n doc = {\n _id: docOrId,\n _rev: optsOrRev\n };\n if (typeof opts === 'function') {\n callback = opts;\n opts = {};\n }\n } else {\n // doc, opts, callback style\n doc = docOrId;\n if (typeof optsOrRev === 'function') {\n callback = optsOrRev;\n opts = {};\n } else {\n callback = opts;\n opts = optsOrRev;\n }\n }\n\n var rev = (doc._rev || opts.rev);\n\n // Delete the document\n ajax$$1(opts, {\n method: 'DELETE',\n url: genDBUrl(host, encodeDocId(doc._id)) + '?rev=' + rev\n }, callback);\n });\n\n function encodeAttachmentId(attachmentId) {\n return attachmentId.split(\"/\").map(encodeURIComponent).join(\"/\");\n }\n\n // Get the attachment\n api.getAttachment =\n adapterFun$$1('getAttachment', function (docId, attachmentId, opts,\n callback) {\n if (typeof opts === 'function') {\n callback = opts;\n opts = {};\n }\n var params = opts.rev ? ('?rev=' + opts.rev) : '';\n var url = genDBUrl(host, encodeDocId(docId)) + '/' +\n encodeAttachmentId(attachmentId) + params;\n ajax$$1(opts, {\n method: 'GET',\n url: url,\n binary: true\n }, callback);\n });\n\n // Remove the attachment given by the id and rev\n api.removeAttachment =\n adapterFun$$1('removeAttachment', function (docId, attachmentId, rev,\n callback) {\n\n var url = genDBUrl(host, encodeDocId(docId) + '/' +\n encodeAttachmentId(attachmentId)) + '?rev=' + rev;\n\n ajax$$1({}, {\n method: 'DELETE',\n url: url\n }, callback);\n });\n\n // Add the attachment given by blob and its contentType property\n // to the document with the given id, the revision given by rev, and\n // add it to the database given by host.\n api.putAttachment =\n adapterFun$$1('putAttachment', function (docId, attachmentId, rev, blob$$1,\n type, callback) {\n if (typeof type === 'function') {\n callback = type;\n type = blob$$1;\n blob$$1 = rev;\n rev = null;\n }\n var id = encodeDocId(docId) + '/' + encodeAttachmentId(attachmentId);\n var url = genDBUrl(host, id);\n if (rev) {\n url += '?rev=' + rev;\n }\n\n if (typeof blob$$1 === 'string') {\n // input is assumed to be a base64 string\n var binary;\n try {\n binary = thisAtob(blob$$1);\n } catch (err) {\n return callback(createError(BAD_ARG,\n 'Attachment is not a valid base64 string'));\n }\n blob$$1 = binary ? binStringToBluffer(binary, type) : '';\n }\n\n var opts = {\n headers: {'Content-Type': type},\n method: 'PUT',\n url: url,\n processData: false,\n body: blob$$1,\n timeout: ajaxOpts.timeout || 60000\n };\n // Add the attachment\n ajax$$1({}, opts, callback);\n });\n\n // Update/create multiple documents given by req in the database\n // given by host.\n api._bulkDocs = function (req, opts, callback) {\n // If new_edits=false then it prevents the database from creating\n // new revision numbers for the documents. Instead it just uses\n // the old ones. This is used in database replication.\n req.new_edits = opts.new_edits;\n\n setup().then(function () {\n return PouchPromise$1.all(req.docs.map(preprocessAttachments$2));\n }).then(function () {\n // Update/create the documents\n ajax$$1(opts, {\n method: 'POST',\n url: genDBUrl(host, '_bulk_docs'),\n timeout: opts.timeout,\n body: req\n }, function (err, results) {\n if (err) {\n return callback(err);\n }\n results.forEach(function (result) {\n result.ok = true; // smooths out cloudant not adding this\n });\n callback(null, results);\n });\n }).catch(callback);\n };\n\n\n // Update/create document\n api._put = function (doc, opts, callback) {\n setup().then(function () {\n return preprocessAttachments$2(doc);\n }).then(function () {\n // Update/create the document\n ajax$$1(opts, {\n method: 'PUT',\n url: genDBUrl(host, encodeDocId(doc._id)),\n body: doc\n }, function (err, result) {\n if (err) {\n return callback(err);\n }\n callback(null, result);\n });\n }).catch(callback);\n };\n\n\n // Get a listing of the documents in the database given\n // by host and ordered by increasing id.\n api.allDocs = adapterFun$$1('allDocs', function (opts, callback) {\n if (typeof opts === 'function') {\n callback = opts;\n opts = {};\n }\n opts = clone(opts);\n\n // List of parameters to add to the GET request\n var params = {};\n var body;\n var method = 'GET';\n\n if (opts.conflicts) {\n params.conflicts = true;\n }\n\n if (opts.descending) {\n params.descending = true;\n }\n\n if (opts.include_docs) {\n params.include_docs = true;\n }\n\n // added in CouchDB 1.6.0\n if (opts.attachments) {\n params.attachments = true;\n }\n\n if (opts.key) {\n params.key = JSON.stringify(opts.key);\n }\n\n if (opts.start_key) {\n opts.startkey = opts.start_key;\n }\n\n if (opts.startkey) {\n params.startkey = JSON.stringify(opts.startkey);\n }\n\n if (opts.end_key) {\n opts.endkey = opts.end_key;\n }\n\n if (opts.endkey) {\n params.endkey = JSON.stringify(opts.endkey);\n }\n\n if (typeof opts.inclusive_end !== 'undefined') {\n params.inclusive_end = !!opts.inclusive_end;\n }\n\n if (typeof opts.limit !== 'undefined') {\n params.limit = opts.limit;\n }\n\n if (typeof opts.skip !== 'undefined') {\n params.skip = opts.skip;\n }\n\n var paramStr = paramsToStr(params);\n\n if (typeof opts.keys !== 'undefined') {\n method = 'POST';\n body = {keys: opts.keys};\n }\n\n // Get the document listing\n ajaxPromise(opts, {\n method: method,\n url: genDBUrl(host, '_all_docs' + paramStr),\n body: body\n }).then(function (res) {\n if (opts.include_docs && opts.attachments && opts.binary) {\n res.rows.forEach(readAttachmentsAsBlobOrBuffer);\n }\n callback(null, res);\n }).catch(callback);\n });\n\n // Get a list of changes made to documents in the database given by host.\n // TODO According to the README, there should be two other methods here,\n // api.changes.addListener and api.changes.removeListener.\n api._changes = function (opts) {\n\n // We internally page the results of a changes request, this means\n // if there is a large set of changes to be returned we can start\n // processing them quicker instead of waiting on the entire\n // set of changes to return and attempting to process them at once\n var batchSize = 'batch_size' in opts ? opts.batch_size : CHANGES_BATCH_SIZE;\n\n opts = clone(opts);\n opts.timeout = ('timeout' in opts) ? opts.timeout :\n ('timeout' in ajaxOpts) ? ajaxOpts.timeout :\n 30 * 1000;\n\n // We give a 5 second buffer for CouchDB changes to respond with\n // an ok timeout (if a timeout it set)\n var params = opts.timeout ? {timeout: opts.timeout - (5 * 1000)} : {};\n var limit = (typeof opts.limit !== 'undefined') ? opts.limit : false;\n var returnDocs;\n if ('return_docs' in opts) {\n returnDocs = opts.return_docs;\n } else if ('returnDocs' in opts) {\n // TODO: Remove 'returnDocs' in favor of 'return_docs' in a future release\n returnDocs = opts.returnDocs;\n } else {\n returnDocs = true;\n }\n //\n var leftToFetch = limit;\n\n if (opts.style) {\n params.style = opts.style;\n }\n\n if (opts.include_docs || opts.filter && typeof opts.filter === 'function') {\n params.include_docs = true;\n }\n\n if (opts.attachments) {\n params.attachments = true;\n }\n\n if (opts.continuous) {\n params.feed = 'longpoll';\n }\n\n if (opts.conflicts) {\n params.conflicts = true;\n }\n\n if (opts.descending) {\n params.descending = true;\n }\n\n if ('heartbeat' in opts) {\n // If the heartbeat value is false, it disables the default heartbeat\n if (opts.heartbeat) {\n params.heartbeat = opts.heartbeat;\n }\n } else if (opts.continuous) {\n // Default heartbeat to 10 seconds\n params.heartbeat = 10000;\n }\n\n if (opts.filter && typeof opts.filter === 'string') {\n params.filter = opts.filter;\n }\n\n if (opts.view && typeof opts.view === 'string') {\n params.filter = '_view';\n params.view = opts.view;\n }\n\n // If opts.query_params exists, pass it through to the changes request.\n // These parameters may be used by the filter on the source database.\n if (opts.query_params && typeof opts.query_params === 'object') {\n for (var param_name in opts.query_params) {\n /* istanbul ignore else */\n if (opts.query_params.hasOwnProperty(param_name)) {\n params[param_name] = opts.query_params[param_name];\n }\n }\n }\n\n var method = 'GET';\n var body;\n\n if (opts.doc_ids) {\n // set this automagically for the user; it's annoying that couchdb\n // requires both a \"filter\" and a \"doc_ids\" param.\n params.filter = '_doc_ids';\n method = 'POST';\n body = {doc_ids: opts.doc_ids };\n }\n\n var xhr;\n var lastFetchedSeq;\n\n // Get all the changes starting wtih the one immediately after the\n // sequence number given by since.\n var fetch = function (since, callback) {\n if (opts.aborted) {\n return;\n }\n params.since = since;\n // \"since\" can be any kind of json object in Coudant/CouchDB 2.x\n /* istanbul ignore next */\n if (typeof params.since === \"object\") {\n params.since = JSON.stringify(params.since);\n }\n\n if (opts.descending) {\n if (limit) {\n params.limit = leftToFetch;\n }\n } else {\n params.limit = (!limit || leftToFetch > batchSize) ?\n batchSize : leftToFetch;\n }\n\n // Set the options for the ajax call\n var xhrOpts = {\n method: method,\n url: genDBUrl(host, '_changes' + paramsToStr(params)),\n timeout: opts.timeout,\n body: body\n };\n lastFetchedSeq = since;\n\n /* istanbul ignore if */\n if (opts.aborted) {\n return;\n }\n\n // Get the changes\n setup().then(function () {\n xhr = ajax$$1(opts, xhrOpts, callback);\n }).catch(callback);\n };\n\n // If opts.since exists, get all the changes from the sequence\n // number given by opts.since. Otherwise, get all the changes\n // from the sequence number 0.\n var results = {results: []};\n\n var fetched = function (err, res) {\n if (opts.aborted) {\n return;\n }\n var raw_results_length = 0;\n // If the result of the ajax call (res) contains changes (res.results)\n if (res && res.results) {\n raw_results_length = res.results.length;\n results.last_seq = res.last_seq;\n // For each change\n var req = {};\n req.query = opts.query_params;\n res.results = res.results.filter(function (c) {\n leftToFetch--;\n var ret = filterChange(opts)(c);\n if (ret) {\n if (opts.include_docs && opts.attachments && opts.binary) {\n readAttachmentsAsBlobOrBuffer(c);\n }\n if (returnDocs) {\n results.results.push(c);\n }\n opts.onChange(c);\n }\n return ret;\n });\n } else if (err) {\n // In case of an error, stop listening for changes and call\n // opts.complete\n opts.aborted = true;\n opts.complete(err);\n return;\n }\n\n // The changes feed may have timed out with no results\n // if so reuse last update sequence\n if (res && res.last_seq) {\n lastFetchedSeq = res.last_seq;\n }\n\n var finished = (limit && leftToFetch <= 0) ||\n (res && raw_results_length < batchSize) ||\n (opts.descending);\n\n if ((opts.continuous && !(limit && leftToFetch <= 0)) || !finished) {\n // Queue a call to fetch again with the newest sequence number\n nextTick(function () { fetch(lastFetchedSeq, fetched); });\n } else {\n // We're done, call the callback\n opts.complete(null, results);\n }\n };\n\n fetch(opts.since || 0, fetched);\n\n // Return a method to cancel this method from processing any more\n return {\n cancel: function () {\n opts.aborted = true;\n if (xhr) {\n xhr.abort();\n }\n }\n };\n };\n\n // Given a set of document/revision IDs (given by req), tets the subset of\n // those that do NOT correspond to revisions stored in the database.\n // See http://wiki.apache.org/couchdb/HttpPostRevsDiff\n api.revsDiff = adapterFun$$1('revsDiff', function (req, opts, callback) {\n // If no options were given, set the callback to be the second parameter\n if (typeof opts === 'function') {\n callback = opts;\n opts = {};\n }\n\n // Get the missing document/revision IDs\n ajax$$1(opts, {\n method: 'POST',\n url: genDBUrl(host, '_revs_diff'),\n body: req\n }, callback);\n });\n\n api._close = function (callback) {\n callback();\n };\n\n api._destroy = function (options, callback) {\n ajax$$1(options, {\n url: genDBUrl(host, ''),\n method: 'DELETE'\n }, function (err, resp) {\n if (err && err.status && err.status !== 404) {\n return callback(err);\n }\n callback(null, resp);\n });\n };\n}\n\n// HttpPouch is a valid adapter.\nHttpPouch.valid = function () {\n return true;\n};\n\nvar HttpPouch$1 = function (PouchDB) {\n PouchDB.adapter('http', HttpPouch, false);\n PouchDB.adapter('https', HttpPouch, false);\n};\n\nfunction pad(str, padWith, upToLength) {\n var padding = '';\n var targetLength = upToLength - str.length;\n /* istanbul ignore next */\n while (padding.length < targetLength) {\n padding += padWith;\n }\n return padding;\n}\n\nfunction padLeft(str, padWith, upToLength) {\n var padding = pad(str, padWith, upToLength);\n return padding + str;\n}\n\nvar MIN_MAGNITUDE = -324; // verified by -Number.MIN_VALUE\nvar MAGNITUDE_DIGITS = 3; // ditto\nvar SEP = ''; // set to '_' for easier debugging \n\nfunction collate(a, b) {\n\n if (a === b) {\n return 0;\n }\n\n a = normalizeKey(a);\n b = normalizeKey(b);\n\n var ai = collationIndex(a);\n var bi = collationIndex(b);\n if ((ai - bi) !== 0) {\n return ai - bi;\n }\n switch (typeof a) {\n case 'number':\n return a - b;\n case 'boolean':\n return a < b ? -1 : 1;\n case 'string':\n return stringCollate(a, b);\n }\n return Array.isArray(a) ? arrayCollate(a, b) : objectCollate(a, b);\n}\n\n// couch considers null/NaN/Infinity/-Infinity === undefined,\n// for the purposes of mapreduce indexes. also, dates get stringified.\nfunction normalizeKey(key) {\n switch (typeof key) {\n case 'undefined':\n return null;\n case 'number':\n if (key === Infinity || key === -Infinity || isNaN(key)) {\n return null;\n }\n return key;\n case 'object':\n var origKey = key;\n if (Array.isArray(key)) {\n var len = key.length;\n key = new Array(len);\n for (var i = 0; i < len; i++) {\n key[i] = normalizeKey(origKey[i]);\n }\n /* istanbul ignore next */\n } else if (key instanceof Date) {\n return key.toJSON();\n } else if (key !== null) { // generic object\n key = {};\n for (var k in origKey) {\n if (origKey.hasOwnProperty(k)) {\n var val = origKey[k];\n if (typeof val !== 'undefined') {\n key[k] = normalizeKey(val);\n }\n }\n }\n }\n }\n return key;\n}\n\nfunction indexify(key) {\n if (key !== null) {\n switch (typeof key) {\n case 'boolean':\n return key ? 1 : 0;\n case 'number':\n return numToIndexableString(key);\n case 'string':\n // We've to be sure that key does not contain \\u0000\n // Do order-preserving replacements:\n // 0 -> 1, 1\n // 1 -> 1, 2\n // 2 -> 2, 2\n return key\n .replace(/\\u0002/g, '\\u0002\\u0002')\n .replace(/\\u0001/g, '\\u0001\\u0002')\n .replace(/\\u0000/g, '\\u0001\\u0001');\n case 'object':\n var isArray = Array.isArray(key);\n var arr = isArray ? key : Object.keys(key);\n var i = -1;\n var len = arr.length;\n var result = '';\n if (isArray) {\n while (++i < len) {\n result += toIndexableString(arr[i]);\n }\n } else {\n while (++i < len) {\n var objKey = arr[i];\n result += toIndexableString(objKey) +\n toIndexableString(key[objKey]);\n }\n }\n return result;\n }\n }\n return '';\n}\n\n// convert the given key to a string that would be appropriate\n// for lexical sorting, e.g. within a database, where the\n// sorting is the same given by the collate() function.\nfunction toIndexableString(key) {\n var zero = '\\u0000';\n key = normalizeKey(key);\n return collationIndex(key) + SEP + indexify(key) + zero;\n}\n\nfunction parseNumber(str, i) {\n var originalIdx = i;\n var num;\n var zero = str[i] === '1';\n if (zero) {\n num = 0;\n i++;\n } else {\n var neg = str[i] === '0';\n i++;\n var numAsString = '';\n var magAsString = str.substring(i, i + MAGNITUDE_DIGITS);\n var magnitude = parseInt(magAsString, 10) + MIN_MAGNITUDE;\n /* istanbul ignore next */\n if (neg) {\n magnitude = -magnitude;\n }\n i += MAGNITUDE_DIGITS;\n while (true) {\n var ch = str[i];\n if (ch === '\\u0000') {\n break;\n } else {\n numAsString += ch;\n }\n i++;\n }\n numAsString = numAsString.split('.');\n if (numAsString.length === 1) {\n num = parseInt(numAsString, 10);\n } else {\n /* istanbul ignore next */\n num = parseFloat(numAsString[0] + '.' + numAsString[1]);\n }\n /* istanbul ignore next */\n if (neg) {\n num = num - 10;\n }\n /* istanbul ignore next */\n if (magnitude !== 0) {\n // parseFloat is more reliable than pow due to rounding errors\n // e.g. Number.MAX_VALUE would return Infinity if we did\n // num * Math.pow(10, magnitude);\n num = parseFloat(num + 'e' + magnitude);\n }\n }\n return {num: num, length : i - originalIdx};\n}\n\n// move up the stack while parsing\n// this function moved outside of parseIndexableString for performance\nfunction pop(stack, metaStack) {\n var obj = stack.pop();\n\n if (metaStack.length) {\n var lastMetaElement = metaStack[metaStack.length - 1];\n if (obj === lastMetaElement.element) {\n // popping a meta-element, e.g. an object whose value is another object\n metaStack.pop();\n lastMetaElement = metaStack[metaStack.length - 1];\n }\n var element = lastMetaElement.element;\n var lastElementIndex = lastMetaElement.index;\n if (Array.isArray(element)) {\n element.push(obj);\n } else if (lastElementIndex === stack.length - 2) { // obj with key+value\n var key = stack.pop();\n element[key] = obj;\n } else {\n stack.push(obj); // obj with key only\n }\n }\n}\n\nfunction parseIndexableString(str) {\n var stack = [];\n var metaStack = []; // stack for arrays and objects\n var i = 0;\n\n /*eslint no-constant-condition: [\"error\", { \"checkLoops\": false }]*/\n while (true) {\n var collationIndex = str[i++];\n if (collationIndex === '\\u0000') {\n if (stack.length === 1) {\n return stack.pop();\n } else {\n pop(stack, metaStack);\n continue;\n }\n }\n switch (collationIndex) {\n case '1':\n stack.push(null);\n break;\n case '2':\n stack.push(str[i] === '1');\n i++;\n break;\n case '3':\n var parsedNum = parseNumber(str, i);\n stack.push(parsedNum.num);\n i += parsedNum.length;\n break;\n case '4':\n var parsedStr = '';\n /*eslint no-constant-condition: [\"error\", { \"checkLoops\": false }]*/\n while (true) {\n var ch = str[i];\n if (ch === '\\u0000') {\n break;\n }\n parsedStr += ch;\n i++;\n }\n // perform the reverse of the order-preserving replacement\n // algorithm (see above)\n parsedStr = parsedStr.replace(/\\u0001\\u0001/g, '\\u0000')\n .replace(/\\u0001\\u0002/g, '\\u0001')\n .replace(/\\u0002\\u0002/g, '\\u0002');\n stack.push(parsedStr);\n break;\n case '5':\n var arrayElement = { element: [], index: stack.length };\n stack.push(arrayElement.element);\n metaStack.push(arrayElement);\n break;\n case '6':\n var objElement = { element: {}, index: stack.length };\n stack.push(objElement.element);\n metaStack.push(objElement);\n break;\n /* istanbul ignore next */\n default:\n throw new Error(\n 'bad collationIndex or unexpectedly reached end of input: ' +\n collationIndex);\n }\n }\n}\n\nfunction arrayCollate(a, b) {\n var len = Math.min(a.length, b.length);\n for (var i = 0; i < len; i++) {\n var sort = collate(a[i], b[i]);\n if (sort !== 0) {\n return sort;\n }\n }\n return (a.length === b.length) ? 0 :\n (a.length > b.length) ? 1 : -1;\n}\nfunction stringCollate(a, b) {\n // See: https://github.com/daleharvey/pouchdb/issues/40\n // This is incompatible with the CouchDB implementation, but its the\n // best we can do for now\n return (a === b) ? 0 : ((a > b) ? 1 : -1);\n}\nfunction objectCollate(a, b) {\n var ak = Object.keys(a), bk = Object.keys(b);\n var len = Math.min(ak.length, bk.length);\n for (var i = 0; i < len; i++) {\n // First sort the keys\n var sort = collate(ak[i], bk[i]);\n if (sort !== 0) {\n return sort;\n }\n // if the keys are equal sort the values\n sort = collate(a[ak[i]], b[bk[i]]);\n if (sort !== 0) {\n return sort;\n }\n\n }\n return (ak.length === bk.length) ? 0 :\n (ak.length > bk.length) ? 1 : -1;\n}\n// The collation is defined by erlangs ordered terms\n// the atoms null, true, false come first, then numbers, strings,\n// arrays, then objects\n// null/undefined/NaN/Infinity/-Infinity are all considered null\nfunction collationIndex(x) {\n var id = ['boolean', 'number', 'string', 'object'];\n var idx = id.indexOf(typeof x);\n //false if -1 otherwise true, but fast!!!!1\n if (~idx) {\n if (x === null) {\n return 1;\n }\n if (Array.isArray(x)) {\n return 5;\n }\n return idx < 3 ? (idx + 2) : (idx + 3);\n }\n /* istanbul ignore next */\n if (Array.isArray(x)) {\n return 5;\n }\n}\n\n// conversion:\n// x yyy zz...zz\n// x = 0 for negative, 1 for 0, 2 for positive\n// y = exponent (for negative numbers negated) moved so that it's >= 0\n// z = mantisse\nfunction numToIndexableString(num) {\n\n if (num === 0) {\n return '1';\n }\n\n // convert number to exponential format for easier and\n // more succinct string sorting\n var expFormat = num.toExponential().split(/e\\+?/);\n var magnitude = parseInt(expFormat[1], 10);\n\n var neg = num < 0;\n\n var result = neg ? '0' : '2';\n\n // first sort by magnitude\n // it's easier if all magnitudes are positive\n var magForComparison = ((neg ? -magnitude : magnitude) - MIN_MAGNITUDE);\n var magString = padLeft((magForComparison).toString(), '0', MAGNITUDE_DIGITS);\n\n result += SEP + magString;\n\n // then sort by the factor\n var factor = Math.abs(parseFloat(expFormat[0])); // [1..10)\n /* istanbul ignore next */\n if (neg) { // for negative reverse ordering\n factor = 10 - factor;\n }\n\n var factorStr = factor.toFixed(20);\n\n // strip zeros from the end\n factorStr = factorStr.replace(/\\.?0+$/, '');\n\n result += SEP + factorStr;\n\n return result;\n}\n\n/*\n * Simple task queue to sequentialize actions. Assumes\n * callbacks will eventually fire (once).\n */\n\nfunction TaskQueue$2() {\n this.promise = new PouchPromise$1(function (fulfill) {fulfill(); });\n}\nTaskQueue$2.prototype.add = function (promiseFactory) {\n this.promise = this.promise.catch(function () {\n // just recover\n }).then(function () {\n return promiseFactory();\n });\n return this.promise;\n};\nTaskQueue$2.prototype.finish = function () {\n return this.promise;\n};\n\nfunction createView(opts) {\n var sourceDB = opts.db;\n var viewName = opts.viewName;\n var mapFun = opts.map;\n var reduceFun = opts.reduce;\n var temporary = opts.temporary;\n\n // the \"undefined\" part is for backwards compatibility\n var viewSignature = mapFun.toString() + (reduceFun && reduceFun.toString()) +\n 'undefined';\n\n var cachedViews;\n if (!temporary) {\n // cache this to ensure we don't try to update the same view twice\n cachedViews = sourceDB._cachedViews = sourceDB._cachedViews || {};\n if (cachedViews[viewSignature]) {\n return cachedViews[viewSignature];\n }\n }\n\n var promiseForView = sourceDB.info().then(function (info) {\n\n var depDbName = info.db_name + '-mrview-' +\n (temporary ? 'temp' : stringMd5(viewSignature));\n\n // save the view name in the source db so it can be cleaned up if necessary\n // (e.g. when the _design doc is deleted, remove all associated view data)\n function diffFunction(doc) {\n doc.views = doc.views || {};\n var fullViewName = viewName;\n if (fullViewName.indexOf('/') === -1) {\n fullViewName = viewName + '/' + viewName;\n }\n var depDbs = doc.views[fullViewName] = doc.views[fullViewName] || {};\n /* istanbul ignore if */\n if (depDbs[depDbName]) {\n return; // no update necessary\n }\n depDbs[depDbName] = true;\n return doc;\n }\n return upsert(sourceDB, '_local/mrviews', diffFunction).then(function () {\n return sourceDB.registerDependentDatabase(depDbName).then(function (res) {\n var db = res.db;\n db.auto_compaction = true;\n var view = {\n name: depDbName,\n db: db,\n sourceDB: sourceDB,\n adapter: sourceDB.adapter,\n mapFun: mapFun,\n reduceFun: reduceFun\n };\n return view.db.get('_local/lastSeq').catch(function (err) {\n /* istanbul ignore if */\n if (err.status !== 404) {\n throw err;\n }\n }).then(function (lastSeqDoc) {\n view.seq = lastSeqDoc ? lastSeqDoc.seq : 0;\n if (cachedViews) {\n view.db.once('destroyed', function () {\n delete cachedViews[viewSignature];\n });\n }\n return view;\n });\n });\n });\n });\n\n if (cachedViews) {\n cachedViews[viewSignature] = promiseForView;\n }\n return promiseForView;\n}\n\nfunction QueryParseError(message) {\n this.status = 400;\n this.name = 'query_parse_error';\n this.message = message;\n this.error = true;\n try {\n Error.captureStackTrace(this, QueryParseError);\n } catch (e) {}\n}\n\ninherits(QueryParseError, Error);\n\nfunction NotFoundError(message) {\n this.status = 404;\n this.name = 'not_found';\n this.message = message;\n this.error = true;\n try {\n Error.captureStackTrace(this, NotFoundError);\n } catch (e) {}\n}\n\ninherits(NotFoundError, Error);\n\nfunction BuiltInError(message) {\n this.status = 500;\n this.name = 'invalid_value';\n this.message = message;\n this.error = true;\n try {\n Error.captureStackTrace(this, BuiltInError);\n } catch (e) {}\n}\n\ninherits(BuiltInError, Error);\n\nfunction createBuiltInError(name) {\n var message = 'builtin ' + name +\n ' function requires map values to be numbers' +\n ' or number arrays';\n return new BuiltInError(message);\n}\n\nfunction sum(values) {\n var result = 0;\n for (var i = 0, len = values.length; i < len; i++) {\n var num = values[i];\n if (typeof num !== 'number') {\n if (Array.isArray(num)) {\n // lists of numbers are also allowed, sum them separately\n result = typeof result === 'number' ? [result] : result;\n for (var j = 0, jLen = num.length; j < jLen; j++) {\n var jNum = num[j];\n if (typeof jNum !== 'number') {\n throw createBuiltInError('_sum');\n } else if (typeof result[j] === 'undefined') {\n result.push(jNum);\n } else {\n result[j] += jNum;\n }\n }\n } else { // not array/number\n throw createBuiltInError('_sum');\n }\n } else if (typeof result === 'number') {\n result += num;\n } else { // add number to array\n result[0] += num;\n }\n }\n return result;\n}\n\nvar log$2 = guardedConsole.bind(null, 'log');\nvar isArray = Array.isArray;\nvar toJSON = JSON.parse;\n\nfunction evalFunctionWithEval(func, emit) {\n return scopedEval(\n \"return (\" + func.replace(/;\\s*$/, \"\") + \");\",\n {\n emit: emit,\n sum: sum,\n log: log$2,\n isArray: isArray,\n toJSON: toJSON\n }\n );\n}\n\nfunction promisedCallback(promise, callback) {\n if (callback) {\n promise.then(function (res) {\n nextTick(function () {\n callback(null, res);\n });\n }, function (reason) {\n nextTick(function () {\n callback(reason);\n });\n });\n }\n return promise;\n}\n\nfunction callbackify(fun) {\n return getArguments(function (args) {\n var cb = args.pop();\n var promise = fun.apply(this, args);\n if (typeof cb === 'function') {\n promisedCallback(promise, cb);\n }\n return promise;\n });\n}\n\n// Promise finally util similar to Q.finally\nfunction fin(promise, finalPromiseFactory) {\n return promise.then(function (res) {\n return finalPromiseFactory().then(function () {\n return res;\n });\n }, function (reason) {\n return finalPromiseFactory().then(function () {\n throw reason;\n });\n });\n}\n\nfunction sequentialize(queue, promiseFactory) {\n return function () {\n var args = arguments;\n var that = this;\n return queue.add(function () {\n return promiseFactory.apply(that, args);\n });\n };\n}\n\n// uniq an array of strings, order not guaranteed\n// similar to underscore/lodash _.uniq\nfunction uniq(arr) {\n var theSet = new ExportedSet(arr);\n var result = new Array(theSet.size);\n var index = -1;\n theSet.forEach(function (value) {\n result[++index] = value;\n });\n return result;\n}\n\nfunction mapToKeysArray(map) {\n var result = new Array(map.size);\n var index = -1;\n map.forEach(function (value, key) {\n result[++index] = key;\n });\n return result;\n}\n\nvar persistentQueues = {};\nvar tempViewQueue = new TaskQueue$2();\nvar CHANGES_BATCH_SIZE$1 = 50;\n\nfunction parseViewName(name) {\n // can be either 'ddocname/viewname' or just 'viewname'\n // (where the ddoc name is the same)\n return name.indexOf('/') === -1 ? [name, name] : name.split('/');\n}\n\nfunction isGenOne(changes) {\n // only return true if the current change is 1-\n // and there are no other leafs\n return changes.length === 1 && /^1-/.test(changes[0].rev);\n}\n\nfunction emitError(db, e) {\n try {\n db.emit('error', e);\n } catch (err) {\n guardedConsole('error',\n 'The user\\'s map/reduce function threw an uncaught error.\\n' +\n 'You can debug this error by doing:\\n' +\n 'myDatabase.on(\\'error\\', function (err) { debugger; });\\n' +\n 'Please double-check your map/reduce function.');\n guardedConsole('error', e);\n }\n}\nfunction tryMap(db, fun, doc) {\n // emit an event if there was an error thrown by a map function.\n // putting try/catches in a single function also avoids deoptimizations.\n try {\n fun(doc);\n } catch (e) {\n emitError(db, e);\n }\n}\n\nfunction tryReduce(db, fun, keys, values, rereduce) {\n // same as above, but returning the result or an error. there are two separate\n // functions to avoid extra memory allocations since the tryCode() case is used\n // for custom map functions (common) vs this function, which is only used for\n // custom reduce functions (rare)\n try {\n return {output : fun(keys, values, rereduce)};\n } catch (e) {\n emitError(db, e);\n return {error: e};\n }\n}\n\nfunction sortByKeyThenValue(x, y) {\n var keyCompare = collate(x.key, y.key);\n return keyCompare !== 0 ? keyCompare : collate(x.value, y.value);\n}\n\nfunction sliceResults(results, limit, skip) {\n skip = skip || 0;\n if (typeof limit === 'number') {\n return results.slice(skip, limit + skip);\n } else if (skip > 0) {\n return results.slice(skip);\n }\n return results;\n}\n\nfunction rowToDocId(row) {\n var val = row.value;\n // Users can explicitly specify a joined doc _id, or it\n // defaults to the doc _id that emitted the key/value.\n var docId = (val && typeof val === 'object' && val._id) || row.id;\n return docId;\n}\n\nfunction readAttachmentsAsBlobOrBuffer$1(res) {\n res.rows.forEach(function (row) {\n var atts = row.doc && row.doc._attachments;\n if (!atts) {\n return;\n }\n Object.keys(atts).forEach(function (filename) {\n var att = atts[filename];\n atts[filename].data = b64ToBluffer(att.data, att.content_type);\n });\n });\n}\n\nfunction postprocessAttachments(opts) {\n return function (res) {\n if (opts.include_docs && opts.attachments && opts.binary) {\n readAttachmentsAsBlobOrBuffer$1(res);\n }\n return res;\n };\n}\n\nvar builtInReduce = {\n _sum: function (keys, values) {\n return sum(values);\n },\n\n _count: function (keys, values) {\n return values.length;\n },\n\n _stats: function (keys, values) {\n // no need to implement rereduce=true, because Pouch\n // will never call it\n function sumsqr(values) {\n var _sumsqr = 0;\n for (var i = 0, len = values.length; i < len; i++) {\n var num = values[i];\n _sumsqr += (num * num);\n }\n return _sumsqr;\n }\n return {\n sum : sum(values),\n min : Math.min.apply(null, values),\n max : Math.max.apply(null, values),\n count : values.length,\n sumsqr : sumsqr(values)\n };\n }\n};\n\nfunction addHttpParam(paramName, opts, params, asJson) {\n // add an http param from opts to params, optionally json-encoded\n var val = opts[paramName];\n if (typeof val !== 'undefined') {\n if (asJson) {\n val = encodeURIComponent(JSON.stringify(val));\n }\n params.push(paramName + '=' + val);\n }\n}\n\nfunction coerceInteger(integerCandidate) {\n if (typeof integerCandidate !== 'undefined') {\n var asNumber = Number(integerCandidate);\n // prevents e.g. '1foo' or '1.1' being coerced to 1\n if (!isNaN(asNumber) && asNumber === parseInt(integerCandidate, 10)) {\n return asNumber;\n } else {\n return integerCandidate;\n }\n }\n}\n\nfunction coerceOptions(opts) {\n opts.group_level = coerceInteger(opts.group_level);\n opts.limit = coerceInteger(opts.limit);\n opts.skip = coerceInteger(opts.skip);\n return opts;\n}\n\nfunction checkPositiveInteger(number) {\n if (number) {\n if (typeof number !== 'number') {\n return new QueryParseError('Invalid value for integer: \"' +\n number + '\"');\n }\n if (number < 0) {\n return new QueryParseError('Invalid value for positive integer: ' +\n '\"' + number + '\"');\n }\n }\n}\n\nfunction checkQueryParseError(options, fun) {\n var startkeyName = options.descending ? 'endkey' : 'startkey';\n var endkeyName = options.descending ? 'startkey' : 'endkey';\n\n if (typeof options[startkeyName] !== 'undefined' &&\n typeof options[endkeyName] !== 'undefined' &&\n collate(options[startkeyName], options[endkeyName]) > 0) {\n throw new QueryParseError('No rows can match your key range, ' +\n 'reverse your start_key and end_key or set {descending : true}');\n } else if (fun.reduce && options.reduce !== false) {\n if (options.include_docs) {\n throw new QueryParseError('{include_docs:true} is invalid for reduce');\n } else if (options.keys && options.keys.length > 1 &&\n !options.group && !options.group_level) {\n throw new QueryParseError('Multi-key fetches for reduce views must use ' +\n '{group: true}');\n }\n }\n ['group_level', 'limit', 'skip'].forEach(function (optionName) {\n var error = checkPositiveInteger(options[optionName]);\n if (error) {\n throw error;\n }\n });\n}\n\nfunction httpQuery(db, fun, opts) {\n // List of parameters to add to the PUT request\n var params = [];\n var body;\n var method = 'GET';\n\n // If opts.reduce exists and is defined, then add it to the list\n // of parameters.\n // If reduce=false then the results are that of only the map function\n // not the final result of map and reduce.\n addHttpParam('reduce', opts, params);\n addHttpParam('include_docs', opts, params);\n addHttpParam('attachments', opts, params);\n addHttpParam('limit', opts, params);\n addHttpParam('descending', opts, params);\n addHttpParam('group', opts, params);\n addHttpParam('group_level', opts, params);\n addHttpParam('skip', opts, params);\n addHttpParam('stale', opts, params);\n addHttpParam('conflicts', opts, params);\n addHttpParam('startkey', opts, params, true);\n addHttpParam('start_key', opts, params, true);\n addHttpParam('endkey', opts, params, true);\n addHttpParam('end_key', opts, params, true);\n addHttpParam('inclusive_end', opts, params);\n addHttpParam('key', opts, params, true);\n\n // Format the list of parameters into a valid URI query string\n params = params.join('&');\n params = params === '' ? '' : '?' + params;\n\n // If keys are supplied, issue a POST to circumvent GET query string limits\n // see http://wiki.apache.org/couchdb/HTTP_view_API#Querying_Options\n if (typeof opts.keys !== 'undefined') {\n var MAX_URL_LENGTH = 2000;\n // according to http://stackoverflow.com/a/417184/680742,\n // the de facto URL length limit is 2000 characters\n\n var keysAsString =\n 'keys=' + encodeURIComponent(JSON.stringify(opts.keys));\n if (keysAsString.length + params.length + 1 <= MAX_URL_LENGTH) {\n // If the keys are short enough, do a GET. we do this to work around\n // Safari not understanding 304s on POSTs (see pouchdb/pouchdb#1239)\n params += (params[0] === '?' ? '&' : '?') + keysAsString;\n } else {\n method = 'POST';\n if (typeof fun === 'string') {\n body = {keys: opts.keys};\n } else { // fun is {map : mapfun}, so append to this\n fun.keys = opts.keys;\n }\n }\n }\n\n // We are referencing a query defined in the design doc\n if (typeof fun === 'string') {\n var parts = parseViewName(fun);\n return db.request({\n method: method,\n url: '_design/' + parts[0] + '/_view/' + parts[1] + params,\n body: body\n }).then(postprocessAttachments(opts));\n }\n\n // We are using a temporary view, terrible for performance, good for testing\n body = body || {};\n Object.keys(fun).forEach(function (key) {\n if (Array.isArray(fun[key])) {\n body[key] = fun[key];\n } else {\n body[key] = fun[key].toString();\n }\n });\n return db.request({\n method: 'POST',\n url: '_temp_view' + params,\n body: body\n }).then(postprocessAttachments(opts));\n}\n\n// custom adapters can define their own api._query\n// and override the default behavior\n/* istanbul ignore next */\nfunction customQuery(db, fun, opts) {\n return new PouchPromise$1(function (resolve, reject) {\n db._query(fun, opts, function (err, res) {\n if (err) {\n return reject(err);\n }\n resolve(res);\n });\n });\n}\n\n// custom adapters can define their own api._viewCleanup\n// and override the default behavior\n/* istanbul ignore next */\nfunction customViewCleanup(db) {\n return new PouchPromise$1(function (resolve, reject) {\n db._viewCleanup(function (err, res) {\n if (err) {\n return reject(err);\n }\n resolve(res);\n });\n });\n}\n\nfunction defaultsTo(value) {\n return function (reason) {\n /* istanbul ignore else */\n if (reason.status === 404) {\n return value;\n } else {\n throw reason;\n }\n };\n}\n\n// returns a promise for a list of docs to update, based on the input docId.\n// the order doesn't matter, because post-3.2.0, bulkDocs\n// is an atomic operation in all three adapters.\nfunction getDocsToPersist(docId, view, docIdsToChangesAndEmits) {\n var metaDocId = '_local/doc_' + docId;\n var defaultMetaDoc = {_id: metaDocId, keys: []};\n var docData = docIdsToChangesAndEmits.get(docId);\n var indexableKeysToKeyValues = docData[0];\n var changes = docData[1];\n\n function getMetaDoc() {\n if (isGenOne(changes)) {\n // generation 1, so we can safely assume initial state\n // for performance reasons (avoids unnecessary GETs)\n return PouchPromise$1.resolve(defaultMetaDoc);\n }\n return view.db.get(metaDocId).catch(defaultsTo(defaultMetaDoc));\n }\n\n function getKeyValueDocs(metaDoc) {\n if (!metaDoc.keys.length) {\n // no keys, no need for a lookup\n return PouchPromise$1.resolve({rows: []});\n }\n return view.db.allDocs({\n keys: metaDoc.keys,\n include_docs: true\n });\n }\n\n function processKeyValueDocs(metaDoc, kvDocsRes) {\n var kvDocs = [];\n var oldKeys = new ExportedSet();\n\n for (var i = 0, len = kvDocsRes.rows.length; i < len; i++) {\n var row = kvDocsRes.rows[i];\n var doc = row.doc;\n if (!doc) { // deleted\n continue;\n }\n kvDocs.push(doc);\n oldKeys.add(doc._id);\n doc._deleted = !indexableKeysToKeyValues.has(doc._id);\n if (!doc._deleted) {\n var keyValue = indexableKeysToKeyValues.get(doc._id);\n if ('value' in keyValue) {\n doc.value = keyValue.value;\n }\n }\n }\n var newKeys = mapToKeysArray(indexableKeysToKeyValues);\n newKeys.forEach(function (key) {\n if (!oldKeys.has(key)) {\n // new doc\n var kvDoc = {\n _id: key\n };\n var keyValue = indexableKeysToKeyValues.get(key);\n if ('value' in keyValue) {\n kvDoc.value = keyValue.value;\n }\n kvDocs.push(kvDoc);\n }\n });\n metaDoc.keys = uniq(newKeys.concat(metaDoc.keys));\n kvDocs.push(metaDoc);\n\n return kvDocs;\n }\n\n return getMetaDoc().then(function (metaDoc) {\n return getKeyValueDocs(metaDoc).then(function (kvDocsRes) {\n return processKeyValueDocs(metaDoc, kvDocsRes);\n });\n });\n}\n\n// updates all emitted key/value docs and metaDocs in the mrview database\n// for the given batch of documents from the source database\nfunction saveKeyValues(view, docIdsToChangesAndEmits, seq) {\n var seqDocId = '_local/lastSeq';\n return view.db.get(seqDocId)\n .catch(defaultsTo({_id: seqDocId, seq: 0}))\n .then(function (lastSeqDoc) {\n var docIds = mapToKeysArray(docIdsToChangesAndEmits);\n return PouchPromise$1.all(docIds.map(function (docId) {\n return getDocsToPersist(docId, view, docIdsToChangesAndEmits);\n })).then(function (listOfDocsToPersist) {\n var docsToPersist = flatten(listOfDocsToPersist);\n lastSeqDoc.seq = seq;\n docsToPersist.push(lastSeqDoc);\n // write all docs in a single operation, update the seq once\n return view.db.bulkDocs({docs : docsToPersist});\n });\n });\n}\n\nfunction getQueue(view) {\n var viewName = typeof view === 'string' ? view : view.name;\n var queue = persistentQueues[viewName];\n if (!queue) {\n queue = persistentQueues[viewName] = new TaskQueue$2();\n }\n return queue;\n}\n\nfunction updateView(view) {\n return sequentialize(getQueue(view), function () {\n return updateViewInQueue(view);\n })();\n}\n\nfunction updateViewInQueue(view) {\n // bind the emit function once\n var mapResults;\n var doc;\n\n function emit(key, value) {\n var output = {id: doc._id, key: normalizeKey(key)};\n // Don't explicitly store the value unless it's defined and non-null.\n // This saves on storage space, because often people don't use it.\n if (typeof value !== 'undefined' && value !== null) {\n output.value = normalizeKey(value);\n }\n mapResults.push(output);\n }\n\n var mapFun;\n // for temp_views one can use emit(doc, emit), see #38\n if (typeof view.mapFun === \"function\" && view.mapFun.length === 2) {\n var origMap = view.mapFun;\n mapFun = function (doc) {\n return origMap(doc, emit);\n };\n } else {\n mapFun = evalFunctionWithEval(view.mapFun.toString(), emit);\n }\n\n var currentSeq = view.seq || 0;\n\n function processChange(docIdsToChangesAndEmits, seq) {\n return function () {\n return saveKeyValues(view, docIdsToChangesAndEmits, seq);\n };\n }\n\n var queue = new TaskQueue$2();\n\n function processNextBatch() {\n return view.sourceDB.changes({\n conflicts: true,\n include_docs: true,\n style: 'all_docs',\n since: currentSeq,\n limit: CHANGES_BATCH_SIZE$1\n }).then(processBatch);\n }\n\n function processBatch(response) {\n var results = response.results;\n if (!results.length) {\n return;\n }\n var docIdsToChangesAndEmits = createDocIdsToChangesAndEmits(results);\n queue.add(processChange(docIdsToChangesAndEmits, currentSeq));\n if (results.length < CHANGES_BATCH_SIZE$1) {\n return;\n }\n return processNextBatch();\n }\n\n function createDocIdsToChangesAndEmits(results) {\n var docIdsToChangesAndEmits = new ExportedMap();\n for (var i = 0, len = results.length; i < len; i++) {\n var change = results[i];\n if (change.doc._id[0] !== '_') {\n mapResults = [];\n doc = change.doc;\n\n if (!doc._deleted) {\n tryMap(view.sourceDB, mapFun, doc);\n }\n mapResults.sort(sortByKeyThenValue);\n\n var indexableKeysToKeyValues = createIndexableKeysToKeyValues(mapResults);\n docIdsToChangesAndEmits.set(change.doc._id, [\n indexableKeysToKeyValues,\n change.changes\n ]);\n }\n currentSeq = change.seq;\n }\n return docIdsToChangesAndEmits;\n }\n\n function createIndexableKeysToKeyValues(mapResults) {\n var indexableKeysToKeyValues = new ExportedMap();\n var lastKey;\n for (var i = 0, len = mapResults.length; i < len; i++) {\n var emittedKeyValue = mapResults[i];\n var complexKey = [emittedKeyValue.key, emittedKeyValue.id];\n if (i > 0 && collate(emittedKeyValue.key, lastKey) === 0) {\n complexKey.push(i); // dup key+id, so make it unique\n }\n indexableKeysToKeyValues.set(toIndexableString(complexKey), emittedKeyValue);\n lastKey = emittedKeyValue.key;\n }\n return indexableKeysToKeyValues;\n }\n\n return processNextBatch().then(function () {\n return queue.finish();\n }).then(function () {\n view.seq = currentSeq;\n });\n}\n\nfunction reduceView(view, results, options) {\n if (options.group_level === 0) {\n delete options.group_level;\n }\n\n var shouldGroup = options.group || options.group_level;\n\n var reduceFun;\n if (builtInReduce[view.reduceFun]) {\n reduceFun = builtInReduce[view.reduceFun];\n } else {\n reduceFun = evalFunctionWithEval(view.reduceFun.toString());\n }\n\n var groups = [];\n var lvl = isNaN(options.group_level) ? Number.POSITIVE_INFINITY :\n options.group_level;\n results.forEach(function (e) {\n var last = groups[groups.length - 1];\n var groupKey = shouldGroup ? e.key : null;\n\n // only set group_level for array keys\n if (shouldGroup && Array.isArray(groupKey)) {\n groupKey = groupKey.slice(0, lvl);\n }\n\n if (last && collate(last.groupKey, groupKey) === 0) {\n last.keys.push([e.key, e.id]);\n last.values.push(e.value);\n return;\n }\n groups.push({\n keys: [[e.key, e.id]],\n values: [e.value],\n groupKey: groupKey\n });\n });\n results = [];\n for (var i = 0, len = groups.length; i < len; i++) {\n var e = groups[i];\n var reduceTry = tryReduce(view.sourceDB, reduceFun, e.keys, e.values, false);\n if (reduceTry.error && reduceTry.error instanceof BuiltInError) {\n // CouchDB returns an error if a built-in errors out\n throw reduceTry.error;\n }\n results.push({\n // CouchDB just sets the value to null if a non-built-in errors out\n value: reduceTry.error ? null : reduceTry.output,\n key: e.groupKey\n });\n }\n // no total_rows/offset when reducing\n return {rows: sliceResults(results, options.limit, options.skip)};\n}\n\nfunction queryView(view, opts) {\n return sequentialize(getQueue(view), function () {\n return queryViewInQueue(view, opts);\n })();\n}\n\nfunction queryViewInQueue(view, opts) {\n var totalRows;\n var shouldReduce = view.reduceFun && opts.reduce !== false;\n var skip = opts.skip || 0;\n if (typeof opts.keys !== 'undefined' && !opts.keys.length) {\n // equivalent query\n opts.limit = 0;\n delete opts.keys;\n }\n\n function fetchFromView(viewOpts) {\n viewOpts.include_docs = true;\n return view.db.allDocs(viewOpts).then(function (res) {\n totalRows = res.total_rows;\n return res.rows.map(function (result) {\n\n // implicit migration - in older versions of PouchDB,\n // we explicitly stored the doc as {id: ..., key: ..., value: ...}\n // this is tested in a migration test\n /* istanbul ignore next */\n if ('value' in result.doc && typeof result.doc.value === 'object' &&\n result.doc.value !== null) {\n var keys = Object.keys(result.doc.value).sort();\n // this detection method is not perfect, but it's unlikely the user\n // emitted a value which was an object with these 3 exact keys\n var expectedKeys = ['id', 'key', 'value'];\n if (!(keys < expectedKeys || keys > expectedKeys)) {\n return result.doc.value;\n }\n }\n\n var parsedKeyAndDocId = parseIndexableString(result.doc._id);\n return {\n key: parsedKeyAndDocId[0],\n id: parsedKeyAndDocId[1],\n value: ('value' in result.doc ? result.doc.value : null)\n };\n });\n });\n }\n\n function onMapResultsReady(rows) {\n var finalResults;\n if (shouldReduce) {\n finalResults = reduceView(view, rows, opts);\n } else {\n finalResults = {\n total_rows: totalRows,\n offset: skip,\n rows: rows\n };\n }\n if (opts.include_docs) {\n var docIds = uniq(rows.map(rowToDocId));\n\n return view.sourceDB.allDocs({\n keys: docIds,\n include_docs: true,\n conflicts: opts.conflicts,\n attachments: opts.attachments,\n binary: opts.binary\n }).then(function (allDocsRes) {\n var docIdsToDocs = new ExportedMap();\n allDocsRes.rows.forEach(function (row) {\n docIdsToDocs.set(row.id, row.doc);\n });\n rows.forEach(function (row) {\n var docId = rowToDocId(row);\n var doc = docIdsToDocs.get(docId);\n if (doc) {\n row.doc = doc;\n }\n });\n return finalResults;\n });\n } else {\n return finalResults;\n }\n }\n\n if (typeof opts.keys !== 'undefined') {\n var keys = opts.keys;\n var fetchPromises = keys.map(function (key) {\n var viewOpts = {\n startkey : toIndexableString([key]),\n endkey : toIndexableString([key, {}])\n };\n return fetchFromView(viewOpts);\n });\n return PouchPromise$1.all(fetchPromises).then(flatten).then(onMapResultsReady);\n } else { // normal query, no 'keys'\n var viewOpts = {\n descending : opts.descending\n };\n if (opts.start_key) {\n opts.startkey = opts.start_key;\n }\n if (opts.end_key) {\n opts.endkey = opts.end_key;\n }\n if (typeof opts.startkey !== 'undefined') {\n viewOpts.startkey = opts.descending ?\n toIndexableString([opts.startkey, {}]) :\n toIndexableString([opts.startkey]);\n }\n if (typeof opts.endkey !== 'undefined') {\n var inclusiveEnd = opts.inclusive_end !== false;\n if (opts.descending) {\n inclusiveEnd = !inclusiveEnd;\n }\n\n viewOpts.endkey = toIndexableString(\n inclusiveEnd ? [opts.endkey, {}] : [opts.endkey]);\n }\n if (typeof opts.key !== 'undefined') {\n var keyStart = toIndexableString([opts.key]);\n var keyEnd = toIndexableString([opts.key, {}]);\n if (viewOpts.descending) {\n viewOpts.endkey = keyStart;\n viewOpts.startkey = keyEnd;\n } else {\n viewOpts.startkey = keyStart;\n viewOpts.endkey = keyEnd;\n }\n }\n if (!shouldReduce) {\n if (typeof opts.limit === 'number') {\n viewOpts.limit = opts.limit;\n }\n viewOpts.skip = skip;\n }\n return fetchFromView(viewOpts).then(onMapResultsReady);\n }\n}\n\nfunction httpViewCleanup(db) {\n return db.request({\n method: 'POST',\n url: '_view_cleanup'\n });\n}\n\nfunction localViewCleanup(db) {\n return db.get('_local/mrviews').then(function (metaDoc) {\n var docsToViews = new ExportedMap();\n Object.keys(metaDoc.views).forEach(function (fullViewName) {\n var parts = parseViewName(fullViewName);\n var designDocName = '_design/' + parts[0];\n var viewName = parts[1];\n var views = docsToViews.get(designDocName);\n if (!views) {\n views = new ExportedSet();\n docsToViews.set(designDocName, views);\n }\n views.add(viewName);\n });\n var opts = {\n keys : mapToKeysArray(docsToViews),\n include_docs : true\n };\n return db.allDocs(opts).then(function (res) {\n var viewsToStatus = {};\n res.rows.forEach(function (row) {\n var ddocName = row.key.substring(8); // cuts off '_design/'\n docsToViews.get(row.key).forEach(function (viewName) {\n var fullViewName = ddocName + '/' + viewName;\n /* istanbul ignore if */\n if (!metaDoc.views[fullViewName]) {\n // new format, without slashes, to support PouchDB 2.2.0\n // migration test in pouchdb's browser.migration.js verifies this\n fullViewName = viewName;\n }\n var viewDBNames = Object.keys(metaDoc.views[fullViewName]);\n // design doc deleted, or view function nonexistent\n var statusIsGood = row.doc && row.doc.views &&\n row.doc.views[viewName];\n viewDBNames.forEach(function (viewDBName) {\n viewsToStatus[viewDBName] =\n viewsToStatus[viewDBName] || statusIsGood;\n });\n });\n });\n var dbsToDelete = Object.keys(viewsToStatus).filter(\n function (viewDBName) { return !viewsToStatus[viewDBName]; });\n var destroyPromises = dbsToDelete.map(function (viewDBName) {\n return sequentialize(getQueue(viewDBName), function () {\n return new db.constructor(viewDBName, db.__opts).destroy();\n })();\n });\n return PouchPromise$1.all(destroyPromises).then(function () {\n return {ok: true};\n });\n });\n }, defaultsTo({ok: true}));\n}\n\nvar viewCleanup = callbackify(function () {\n var db = this;\n if (db.type() === 'http') {\n return httpViewCleanup(db);\n }\n /* istanbul ignore next */\n if (typeof db._viewCleanup === 'function') {\n return customViewCleanup(db);\n }\n return localViewCleanup(db);\n});\n\nfunction queryPromised(db, fun, opts) {\n if (db.type() === 'http') {\n return httpQuery(db, fun, opts);\n }\n\n /* istanbul ignore next */\n if (typeof db._query === 'function') {\n return customQuery(db, fun, opts);\n }\n\n if (typeof fun !== 'string') {\n // temp_view\n checkQueryParseError(opts, fun);\n\n var createViewOpts = {\n db : db,\n viewName : 'temp_view/temp_view',\n map : fun.map,\n reduce : fun.reduce,\n temporary : true\n };\n tempViewQueue.add(function () {\n return createView(createViewOpts).then(function (view) {\n function cleanup() {\n return view.db.destroy();\n }\n return fin(updateView(view).then(function () {\n return queryView(view, opts);\n }), cleanup);\n });\n });\n return tempViewQueue.finish();\n } else {\n // persistent view\n var fullViewName = fun;\n var parts = parseViewName(fullViewName);\n var designDocName = parts[0];\n var viewName = parts[1];\n return db.get('_design/' + designDocName).then(function (doc) {\n var fun = doc.views && doc.views[viewName];\n\n if (!fun || typeof fun.map !== 'string') {\n throw new NotFoundError('ddoc ' + designDocName +\n ' has no view named ' + viewName);\n }\n checkQueryParseError(opts, fun);\n\n var createViewOpts = {\n db : db,\n viewName : fullViewName,\n map : fun.map,\n reduce : fun.reduce\n };\n return createView(createViewOpts).then(function (view) {\n if (opts.stale === 'ok' || opts.stale === 'update_after') {\n if (opts.stale === 'update_after') {\n nextTick(function () {\n updateView(view);\n });\n }\n return queryView(view, opts);\n } else { // stale not ok\n return updateView(view).then(function () {\n return queryView(view, opts);\n });\n }\n });\n });\n }\n}\n\nvar query = function (fun, opts, callback) {\n if (typeof opts === 'function') {\n callback = opts;\n opts = {};\n }\n opts = opts ? coerceOptions(opts) : {};\n\n if (typeof fun === 'function') {\n fun = {map : fun};\n }\n\n var db = this;\n var promise = PouchPromise$1.resolve().then(function () {\n return queryPromised(db, fun, opts);\n });\n promisedCallback(promise, callback);\n return promise;\n};\n\n\nvar mapreduce = {\n query: query,\n viewCleanup: viewCleanup\n};\n\nfunction isGenOne$1(rev) {\n return /^1-/.test(rev);\n}\n\nfunction fileHasChanged(localDoc, remoteDoc, filename) {\n return !localDoc._attachments ||\n !localDoc._attachments[filename] ||\n localDoc._attachments[filename].digest !== remoteDoc._attachments[filename].digest;\n}\n\nfunction getDocAttachments(db, doc) {\n var filenames = Object.keys(doc._attachments);\n return PouchPromise$1.all(filenames.map(function (filename) {\n return db.getAttachment(doc._id, filename, {rev: doc._rev});\n }));\n}\n\nfunction getDocAttachmentsFromTargetOrSource(target, src, doc) {\n var doCheckForLocalAttachments = src.type() === 'http' && target.type() !== 'http';\n var filenames = Object.keys(doc._attachments);\n\n if (!doCheckForLocalAttachments) {\n return getDocAttachments(src, doc);\n }\n\n return target.get(doc._id).then(function (localDoc) {\n return PouchPromise$1.all(filenames.map(function (filename) {\n if (fileHasChanged(localDoc, doc, filename)) {\n return src.getAttachment(doc._id, filename);\n }\n\n return target.getAttachment(localDoc._id, filename);\n }));\n }).catch(function (error) {\n /* istanbul ignore if */\n if (error.status !== 404) {\n throw error;\n }\n\n return getDocAttachments(src, doc);\n });\n}\n\nfunction createBulkGetOpts(diffs) {\n var requests = [];\n Object.keys(diffs).forEach(function (id) {\n var missingRevs = diffs[id].missing;\n missingRevs.forEach(function (missingRev) {\n requests.push({\n id: id,\n rev: missingRev\n });\n });\n });\n\n return {\n docs: requests,\n revs: true,\n latest: true\n };\n}\n\n//\n// Fetch all the documents from the src as described in the \"diffs\",\n// which is a mapping of docs IDs to revisions. If the state ever\n// changes to \"cancelled\", then the returned promise will be rejected.\n// Else it will be resolved with a list of fetched documents.\n//\nfunction getDocs(src, target, diffs, state) {\n diffs = clone(diffs); // we do not need to modify this\n\n var resultDocs = [],\n ok = true;\n\n function getAllDocs() {\n\n var bulkGetOpts = createBulkGetOpts(diffs);\n\n if (!bulkGetOpts.docs.length) { // optimization: skip empty requests\n return;\n }\n\n return src.bulkGet(bulkGetOpts).then(function (bulkGetResponse) {\n /* istanbul ignore if */\n if (state.cancelled) {\n throw new Error('cancelled');\n }\n return PouchPromise$1.all(bulkGetResponse.results.map(function (bulkGetInfo) {\n return PouchPromise$1.all(bulkGetInfo.docs.map(function (doc) {\n var remoteDoc = doc.ok;\n\n if (doc.error) {\n // when AUTO_COMPACTION is set, docs can be returned which look\n // like this: {\"missing\":\"1-7c3ac256b693c462af8442f992b83696\"}\n ok = false;\n }\n\n if (!remoteDoc || !remoteDoc._attachments) {\n return remoteDoc;\n }\n\n return getDocAttachmentsFromTargetOrSource(target, src, remoteDoc).then(function (attachments) {\n var filenames = Object.keys(remoteDoc._attachments);\n attachments.forEach(function (attachment, i) {\n var att = remoteDoc._attachments[filenames[i]];\n delete att.stub;\n delete att.length;\n att.data = attachment;\n });\n\n return remoteDoc;\n });\n }));\n }))\n\n .then(function (results) {\n resultDocs = resultDocs.concat(flatten(results).filter(Boolean));\n });\n });\n }\n\n function hasAttachments(doc) {\n return doc._attachments && Object.keys(doc._attachments).length > 0;\n }\n\n function hasConflicts(doc) {\n return doc._conflicts && doc._conflicts.length > 0;\n }\n\n function fetchRevisionOneDocs(ids) {\n // Optimization: fetch gen-1 docs and attachments in\n // a single request using _all_docs\n return src.allDocs({\n keys: ids,\n include_docs: true,\n conflicts: true\n }).then(function (res) {\n if (state.cancelled) {\n throw new Error('cancelled');\n }\n res.rows.forEach(function (row) {\n if (row.deleted || !row.doc || !isGenOne$1(row.value.rev) ||\n hasAttachments(row.doc) || hasConflicts(row.doc)) {\n // if any of these conditions apply, we need to fetch using get()\n return;\n }\n\n // strip _conflicts array to appease CSG (#5793)\n /* istanbul ignore if */\n if (row.doc._conflicts) {\n delete row.doc._conflicts;\n }\n\n // the doc we got back from allDocs() is sufficient\n resultDocs.push(row.doc);\n delete diffs[row.id];\n });\n });\n }\n\n function getRevisionOneDocs() {\n // filter out the generation 1 docs and get them\n // leaving the non-generation one docs to be got otherwise\n var ids = Object.keys(diffs).filter(function (id) {\n var missing = diffs[id].missing;\n return missing.length === 1 && isGenOne$1(missing[0]);\n });\n if (ids.length > 0) {\n return fetchRevisionOneDocs(ids);\n }\n }\n\n function returnResult() {\n return { ok:ok, docs:resultDocs };\n }\n\n return PouchPromise$1.resolve()\n .then(getRevisionOneDocs)\n .then(getAllDocs)\n .then(returnResult);\n}\n\nvar CHECKPOINT_VERSION = 1;\nvar REPLICATOR = \"pouchdb\";\n// This is an arbitrary number to limit the\n// amount of replication history we save in the checkpoint.\n// If we save too much, the checkpoing docs will become very big,\n// if we save fewer, we'll run a greater risk of having to\n// read all the changes from 0 when checkpoint PUTs fail\n// CouchDB 2.0 has a more involved history pruning,\n// but let's go for the simple version for now.\nvar CHECKPOINT_HISTORY_SIZE = 5;\nvar LOWEST_SEQ = 0;\n\nfunction updateCheckpoint(db, id, checkpoint, session, returnValue) {\n return db.get(id).catch(function (err) {\n if (err.status === 404) {\n if (db.type() === 'http') {\n explainError(\n 404, 'PouchDB is just checking if a remote checkpoint exists.'\n );\n }\n return {\n session_id: session,\n _id: id,\n history: [],\n replicator: REPLICATOR,\n version: CHECKPOINT_VERSION\n };\n }\n throw err;\n }).then(function (doc) {\n if (returnValue.cancelled) {\n return;\n }\n\n // if the checkpoint has not changed, do not update\n if (doc.last_seq === checkpoint) {\n return;\n }\n\n // Filter out current entry for this replication\n doc.history = (doc.history || []).filter(function (item) {\n return item.session_id !== session;\n });\n\n // Add the latest checkpoint to history\n doc.history.unshift({\n last_seq: checkpoint,\n session_id: session\n });\n\n // Just take the last pieces in history, to\n // avoid really big checkpoint docs.\n // see comment on history size above\n doc.history = doc.history.slice(0, CHECKPOINT_HISTORY_SIZE);\n\n doc.version = CHECKPOINT_VERSION;\n doc.replicator = REPLICATOR;\n\n doc.session_id = session;\n doc.last_seq = checkpoint;\n\n return db.put(doc).catch(function (err) {\n if (err.status === 409) {\n // retry; someone is trying to write a checkpoint simultaneously\n return updateCheckpoint(db, id, checkpoint, session, returnValue);\n }\n throw err;\n });\n });\n}\n\nfunction Checkpointer(src, target, id, returnValue) {\n this.src = src;\n this.target = target;\n this.id = id;\n this.returnValue = returnValue;\n}\n\nCheckpointer.prototype.writeCheckpoint = function (checkpoint, session) {\n var self = this;\n return this.updateTarget(checkpoint, session).then(function () {\n return self.updateSource(checkpoint, session);\n });\n};\n\nCheckpointer.prototype.updateTarget = function (checkpoint, session) {\n return updateCheckpoint(this.target, this.id, checkpoint,\n session, this.returnValue);\n};\n\nCheckpointer.prototype.updateSource = function (checkpoint, session) {\n var self = this;\n if (this.readOnlySource) {\n return PouchPromise$1.resolve(true);\n }\n return updateCheckpoint(this.src, this.id, checkpoint,\n session, this.returnValue)\n .catch(function (err) {\n if (isForbiddenError(err)) {\n self.readOnlySource = true;\n return true;\n }\n throw err;\n });\n};\n\nvar comparisons = {\n \"undefined\": function (targetDoc, sourceDoc) {\n // This is the previous comparison function\n if (collate(targetDoc.last_seq, sourceDoc.last_seq) === 0) {\n return sourceDoc.last_seq;\n }\n /* istanbul ignore next */\n return 0;\n },\n \"1\": function (targetDoc, sourceDoc) {\n // This is the comparison function ported from CouchDB\n return compareReplicationLogs(sourceDoc, targetDoc).last_seq;\n }\n};\n\nCheckpointer.prototype.getCheckpoint = function () {\n var self = this;\n return self.target.get(self.id).then(function (targetDoc) {\n if (self.readOnlySource) {\n return PouchPromise$1.resolve(targetDoc.last_seq);\n }\n\n return self.src.get(self.id).then(function (sourceDoc) {\n // Since we can't migrate an old version doc to a new one\n // (no session id), we just go with the lowest seq in this case\n /* istanbul ignore if */\n if (targetDoc.version !== sourceDoc.version) {\n return LOWEST_SEQ;\n }\n\n var version;\n if (targetDoc.version) {\n version = targetDoc.version.toString();\n } else {\n version = \"undefined\";\n }\n\n if (version in comparisons) {\n return comparisons[version](targetDoc, sourceDoc);\n }\n /* istanbul ignore next */\n return LOWEST_SEQ;\n }, function (err) {\n if (err.status === 404 && targetDoc.last_seq) {\n return self.src.put({\n _id: self.id,\n last_seq: LOWEST_SEQ\n }).then(function () {\n return LOWEST_SEQ;\n }, function (err) {\n if (isForbiddenError(err)) {\n self.readOnlySource = true;\n return targetDoc.last_seq;\n }\n /* istanbul ignore next */\n return LOWEST_SEQ;\n });\n }\n throw err;\n });\n }).catch(function (err) {\n if (err.status !== 404) {\n throw err;\n }\n return LOWEST_SEQ;\n });\n};\n// This checkpoint comparison is ported from CouchDBs source\n// they come from here:\n// https://github.com/apache/couchdb-couch-replicator/blob/master/src/couch_replicator.erl#L863-L906\n\nfunction compareReplicationLogs(srcDoc, tgtDoc) {\n if (srcDoc.session_id === tgtDoc.session_id) {\n return {\n last_seq: srcDoc.last_seq,\n history: srcDoc.history\n };\n }\n\n return compareReplicationHistory(srcDoc.history, tgtDoc.history);\n}\n\nfunction compareReplicationHistory(sourceHistory, targetHistory) {\n // the erlang loop via function arguments is not so easy to repeat in JS\n // therefore, doing this as recursion\n var S = sourceHistory[0];\n var sourceRest = sourceHistory.slice(1);\n var T = targetHistory[0];\n var targetRest = targetHistory.slice(1);\n\n if (!S || targetHistory.length === 0) {\n return {\n last_seq: LOWEST_SEQ,\n history: []\n };\n }\n\n var sourceId = S.session_id;\n /* istanbul ignore if */\n if (hasSessionId(sourceId, targetHistory)) {\n return {\n last_seq: S.last_seq,\n history: sourceHistory\n };\n }\n\n var targetId = T.session_id;\n if (hasSessionId(targetId, sourceRest)) {\n return {\n last_seq: T.last_seq,\n history: targetRest\n };\n }\n\n return compareReplicationHistory(sourceRest, targetRest);\n}\n\nfunction hasSessionId(sessionId, history) {\n var props = history[0];\n var rest = history.slice(1);\n\n if (!sessionId || history.length === 0) {\n return false;\n }\n\n if (sessionId === props.session_id) {\n return true;\n }\n\n return hasSessionId(sessionId, rest);\n}\n\nfunction isForbiddenError(err) {\n return typeof err.status === 'number' && Math.floor(err.status / 100) === 4;\n}\n\nvar STARTING_BACK_OFF = 0;\n\nfunction backOff(opts, returnValue, error, callback) {\n if (opts.retry === false) {\n returnValue.emit('error', error);\n returnValue.removeAllListeners();\n return;\n }\n if (typeof opts.back_off_function !== 'function') {\n opts.back_off_function = defaultBackOff;\n }\n returnValue.emit('requestError', error);\n if (returnValue.state === 'active' || returnValue.state === 'pending') {\n returnValue.emit('paused', error);\n returnValue.state = 'stopped';\n var backOffSet = function backoffTimeSet() {\n opts.current_back_off = STARTING_BACK_OFF;\n };\n var removeBackOffSetter = function removeBackOffTimeSet() {\n returnValue.removeListener('active', backOffSet);\n };\n returnValue.once('paused', removeBackOffSetter);\n returnValue.once('active', backOffSet);\n }\n\n opts.current_back_off = opts.current_back_off || STARTING_BACK_OFF;\n opts.current_back_off = opts.back_off_function(opts.current_back_off);\n setTimeout(callback, opts.current_back_off);\n}\n\nfunction sortObjectPropertiesByKey(queryParams) {\n return Object.keys(queryParams).sort(collate).reduce(function (result, key) {\n result[key] = queryParams[key];\n return result;\n }, {});\n}\n\n// Generate a unique id particular to this replication.\n// Not guaranteed to align perfectly with CouchDB's rep ids.\nfunction generateReplicationId(src, target, opts) {\n var docIds = opts.doc_ids ? opts.doc_ids.sort(collate) : '';\n var filterFun = opts.filter ? opts.filter.toString() : '';\n var queryParams = '';\n var filterViewName = '';\n\n if (opts.filter && opts.query_params) {\n queryParams = JSON.stringify(sortObjectPropertiesByKey(opts.query_params));\n }\n\n if (opts.filter && opts.filter === '_view') {\n filterViewName = opts.view.toString();\n }\n\n return PouchPromise$1.all([src.id(), target.id()]).then(function (res) {\n var queryData = res[0] + res[1] + filterFun + filterViewName +\n queryParams + docIds;\n return new PouchPromise$1(function (resolve) {\n binaryMd5(queryData, resolve);\n });\n }).then(function (md5sum) {\n // can't use straight-up md5 alphabet, because\n // the char '/' is interpreted as being for attachments,\n // and + is also not url-safe\n md5sum = md5sum.replace(/\\//g, '.').replace(/\\+/g, '_');\n return '_local/' + md5sum;\n });\n}\n\nfunction replicate(src, target, opts, returnValue, result) {\n var batches = []; // list of batches to be processed\n var currentBatch; // the batch currently being processed\n var pendingBatch = {\n seq: 0,\n changes: [],\n docs: []\n }; // next batch, not yet ready to be processed\n var writingCheckpoint = false; // true while checkpoint is being written\n var changesCompleted = false; // true when all changes received\n var replicationCompleted = false; // true when replication has completed\n var last_seq = 0;\n var continuous = opts.continuous || opts.live || false;\n var batch_size = opts.batch_size || 100;\n var batches_limit = opts.batches_limit || 10;\n var changesPending = false; // true while src.changes is running\n var doc_ids = opts.doc_ids;\n var repId;\n var checkpointer;\n var changedDocs = [];\n // Like couchdb, every replication gets a unique session id\n var session = uuid();\n\n result = result || {\n ok: true,\n start_time: new Date(),\n docs_read: 0,\n docs_written: 0,\n doc_write_failures: 0,\n errors: []\n };\n\n var changesOpts = {};\n returnValue.ready(src, target);\n\n function initCheckpointer() {\n if (checkpointer) {\n return PouchPromise$1.resolve();\n }\n return generateReplicationId(src, target, opts).then(function (res) {\n repId = res;\n checkpointer = new Checkpointer(src, target, repId, returnValue);\n });\n }\n\n function writeDocs() {\n changedDocs = [];\n\n if (currentBatch.docs.length === 0) {\n return;\n }\n var docs = currentBatch.docs;\n var bulkOpts = {timeout: opts.timeout};\n return target.bulkDocs({docs: docs, new_edits: false}, bulkOpts).then(function (res) {\n /* istanbul ignore if */\n if (returnValue.cancelled) {\n completeReplication();\n throw new Error('cancelled');\n }\n\n // `res` doesn't include full documents (which live in `docs`), so we create a map of \n // (id -> error), and check for errors while iterating over `docs`\n var errorsById = Object.create(null);\n res.forEach(function (res) {\n if (res.error) {\n errorsById[res.id] = res;\n }\n });\n\n var errorsNo = Object.keys(errorsById).length;\n result.doc_write_failures += errorsNo;\n result.docs_written += docs.length - errorsNo;\n\n docs.forEach(function (doc) {\n var error = errorsById[doc._id];\n if (error) {\n result.errors.push(error);\n if (error.name === 'unauthorized' || error.name === 'forbidden') {\n returnValue.emit('denied', clone(error));\n } else {\n throw error;\n }\n } else {\n changedDocs.push(doc);\n }\n });\n\n }, function (err) {\n result.doc_write_failures += docs.length;\n throw err;\n });\n }\n\n function finishBatch() {\n if (currentBatch.error) {\n throw new Error('There was a problem getting docs.');\n }\n result.last_seq = last_seq = currentBatch.seq;\n var outResult = clone(result);\n if (changedDocs.length) {\n outResult.docs = changedDocs;\n returnValue.emit('change', outResult);\n }\n writingCheckpoint = true;\n return checkpointer.writeCheckpoint(currentBatch.seq,\n session).then(function () {\n writingCheckpoint = false;\n /* istanbul ignore if */\n if (returnValue.cancelled) {\n completeReplication();\n throw new Error('cancelled');\n }\n currentBatch = undefined;\n getChanges();\n }).catch(function (err) {\n onCheckpointError(err);\n throw err;\n });\n }\n\n function getDiffs() {\n var diff = {};\n currentBatch.changes.forEach(function (change) {\n // Couchbase Sync Gateway emits these, but we can ignore them\n /* istanbul ignore if */\n if (change.id === \"_user/\") {\n return;\n }\n diff[change.id] = change.changes.map(function (x) {\n return x.rev;\n });\n });\n return target.revsDiff(diff).then(function (diffs) {\n /* istanbul ignore if */\n if (returnValue.cancelled) {\n completeReplication();\n throw new Error('cancelled');\n }\n // currentBatch.diffs elements are deleted as the documents are written\n currentBatch.diffs = diffs;\n });\n }\n\n function getBatchDocs() {\n return getDocs(src, target, currentBatch.diffs, returnValue).then(function (got) {\n currentBatch.error = !got.ok;\n got.docs.forEach(function (doc) {\n delete currentBatch.diffs[doc._id];\n result.docs_read++;\n currentBatch.docs.push(doc);\n });\n });\n }\n\n function startNextBatch() {\n if (returnValue.cancelled || currentBatch) {\n return;\n }\n if (batches.length === 0) {\n processPendingBatch(true);\n return;\n }\n currentBatch = batches.shift();\n getDiffs()\n .then(getBatchDocs)\n .then(writeDocs)\n .then(finishBatch)\n .then(startNextBatch)\n .catch(function (err) {\n abortReplication('batch processing terminated with error', err);\n });\n }\n\n\n function processPendingBatch(immediate) {\n if (pendingBatch.changes.length === 0) {\n if (batches.length === 0 && !currentBatch) {\n if ((continuous && changesOpts.live) || changesCompleted) {\n returnValue.state = 'pending';\n returnValue.emit('paused');\n }\n if (changesCompleted) {\n completeReplication();\n }\n }\n return;\n }\n if (\n immediate ||\n changesCompleted ||\n pendingBatch.changes.length >= batch_size\n ) {\n batches.push(pendingBatch);\n pendingBatch = {\n seq: 0,\n changes: [],\n docs: []\n };\n if (returnValue.state === 'pending' || returnValue.state === 'stopped') {\n returnValue.state = 'active';\n returnValue.emit('active');\n }\n startNextBatch();\n }\n }\n\n\n function abortReplication(reason, err) {\n if (replicationCompleted) {\n return;\n }\n if (!err.message) {\n err.message = reason;\n }\n result.ok = false;\n result.status = 'aborting';\n batches = [];\n pendingBatch = {\n seq: 0,\n changes: [],\n docs: []\n };\n completeReplication(err);\n }\n\n\n function completeReplication(fatalError) {\n if (replicationCompleted) {\n return;\n }\n /* istanbul ignore if */\n if (returnValue.cancelled) {\n result.status = 'cancelled';\n if (writingCheckpoint) {\n return;\n }\n }\n result.status = result.status || 'complete';\n result.end_time = new Date();\n result.last_seq = last_seq;\n replicationCompleted = true;\n\n if (fatalError) {\n fatalError.result = result;\n\n if (fatalError.name === 'unauthorized' || fatalError.name === 'forbidden') {\n returnValue.emit('error', fatalError);\n returnValue.removeAllListeners();\n } else {\n backOff(opts, returnValue, fatalError, function () {\n replicate(src, target, opts, returnValue);\n });\n }\n } else {\n returnValue.emit('complete', result);\n returnValue.removeAllListeners();\n }\n }\n\n\n function onChange(change) {\n /* istanbul ignore if */\n if (returnValue.cancelled) {\n return completeReplication();\n }\n var filter = filterChange(opts)(change);\n if (!filter) {\n return;\n }\n pendingBatch.seq = change.seq;\n pendingBatch.changes.push(change);\n processPendingBatch(batches.length === 0 && changesOpts.live);\n }\n\n\n function onChangesComplete(changes) {\n changesPending = false;\n /* istanbul ignore if */\n if (returnValue.cancelled) {\n return completeReplication();\n }\n\n // if no results were returned then we're done,\n // else fetch more\n if (changes.results.length > 0) {\n changesOpts.since = changes.last_seq;\n getChanges();\n processPendingBatch(true);\n } else {\n\n var complete = function () {\n if (continuous) {\n changesOpts.live = true;\n getChanges();\n } else {\n changesCompleted = true;\n }\n processPendingBatch(true);\n };\n\n // update the checkpoint so we start from the right seq next time\n if (!currentBatch && changes.results.length === 0) {\n writingCheckpoint = true;\n checkpointer.writeCheckpoint(changes.last_seq,\n session).then(function () {\n writingCheckpoint = false;\n result.last_seq = last_seq = changes.last_seq;\n complete();\n })\n .catch(onCheckpointError);\n } else {\n complete();\n }\n }\n }\n\n\n function onChangesError(err) {\n changesPending = false;\n /* istanbul ignore if */\n if (returnValue.cancelled) {\n return completeReplication();\n }\n abortReplication('changes rejected', err);\n }\n\n\n function getChanges() {\n if (!(\n !changesPending &&\n !changesCompleted &&\n batches.length < batches_limit\n )) {\n return;\n }\n changesPending = true;\n function abortChanges() {\n changes.cancel();\n }\n function removeListener() {\n returnValue.removeListener('cancel', abortChanges);\n }\n\n if (returnValue._changes) { // remove old changes() and listeners\n returnValue.removeListener('cancel', returnValue._abortChanges);\n returnValue._changes.cancel();\n }\n returnValue.once('cancel', abortChanges);\n\n var changes = src.changes(changesOpts)\n .on('change', onChange);\n changes.then(removeListener, removeListener);\n changes.then(onChangesComplete)\n .catch(onChangesError);\n\n if (opts.retry) {\n // save for later so we can cancel if necessary\n returnValue._changes = changes;\n returnValue._abortChanges = abortChanges;\n }\n }\n\n\n function startChanges() {\n initCheckpointer().then(function () {\n /* istanbul ignore if */\n if (returnValue.cancelled) {\n completeReplication();\n return;\n }\n return checkpointer.getCheckpoint().then(function (checkpoint) {\n last_seq = checkpoint;\n changesOpts = {\n since: last_seq,\n limit: batch_size,\n batch_size: batch_size,\n style: 'all_docs',\n doc_ids: doc_ids,\n return_docs: true // required so we know when we're done\n };\n if (opts.filter) {\n if (typeof opts.filter !== 'string') {\n // required for the client-side filter in onChange\n changesOpts.include_docs = true;\n } else { // ddoc filter\n changesOpts.filter = opts.filter;\n }\n }\n if ('heartbeat' in opts) {\n changesOpts.heartbeat = opts.heartbeat;\n }\n if ('timeout' in opts) {\n changesOpts.timeout = opts.timeout;\n }\n if (opts.query_params) {\n changesOpts.query_params = opts.query_params;\n }\n if (opts.view) {\n changesOpts.view = opts.view;\n }\n getChanges();\n });\n }).catch(function (err) {\n abortReplication('getCheckpoint rejected with ', err);\n });\n }\n\n /* istanbul ignore next */\n function onCheckpointError(err) {\n writingCheckpoint = false;\n abortReplication('writeCheckpoint completed with error', err);\n }\n\n /* istanbul ignore if */\n if (returnValue.cancelled) { // cancelled immediately\n completeReplication();\n return;\n }\n\n if (!returnValue._addedListeners) {\n returnValue.once('cancel', completeReplication);\n\n if (typeof opts.complete === 'function') {\n returnValue.once('error', opts.complete);\n returnValue.once('complete', function (result) {\n opts.complete(null, result);\n });\n }\n returnValue._addedListeners = true;\n }\n\n if (typeof opts.since === 'undefined') {\n startChanges();\n } else {\n initCheckpointer().then(function () {\n writingCheckpoint = true;\n return checkpointer.writeCheckpoint(opts.since, session);\n }).then(function () {\n writingCheckpoint = false;\n /* istanbul ignore if */\n if (returnValue.cancelled) {\n completeReplication();\n return;\n }\n last_seq = opts.since;\n startChanges();\n }).catch(onCheckpointError);\n }\n}\n\n// We create a basic promise so the caller can cancel the replication possibly\n// before we have actually started listening to changes etc\ninherits(Replication, events.EventEmitter);\nfunction Replication() {\n events.EventEmitter.call(this);\n this.cancelled = false;\n this.state = 'pending';\n var self = this;\n var promise = new PouchPromise$1(function (fulfill, reject) {\n self.once('complete', fulfill);\n self.once('error', reject);\n });\n self.then = function (resolve, reject) {\n return promise.then(resolve, reject);\n };\n self.catch = function (reject) {\n return promise.catch(reject);\n };\n // As we allow error handling via \"error\" event as well,\n // put a stub in here so that rejecting never throws UnhandledError.\n self.catch(function () {});\n}\n\nReplication.prototype.cancel = function () {\n this.cancelled = true;\n this.state = 'cancelled';\n this.emit('cancel');\n};\n\nReplication.prototype.ready = function (src, target) {\n var self = this;\n if (self._readyCalled) {\n return;\n }\n self._readyCalled = true;\n\n function onDestroy() {\n self.cancel();\n }\n src.once('destroyed', onDestroy);\n target.once('destroyed', onDestroy);\n function cleanup() {\n src.removeListener('destroyed', onDestroy);\n target.removeListener('destroyed', onDestroy);\n }\n self.once('complete', cleanup);\n};\n\nfunction toPouch(db, opts) {\n var PouchConstructor = opts.PouchConstructor;\n if (typeof db === 'string') {\n return new PouchConstructor(db, opts);\n } else {\n return db;\n }\n}\n\nfunction replicateWrapper(src, target, opts, callback) {\n\n if (typeof opts === 'function') {\n callback = opts;\n opts = {};\n }\n if (typeof opts === 'undefined') {\n opts = {};\n }\n\n if (opts.doc_ids && !Array.isArray(opts.doc_ids)) {\n throw createError(BAD_REQUEST,\n \"`doc_ids` filter parameter is not a list.\");\n }\n\n opts.complete = callback;\n opts = clone(opts);\n opts.continuous = opts.continuous || opts.live;\n opts.retry = ('retry' in opts) ? opts.retry : false;\n /*jshint validthis:true */\n opts.PouchConstructor = opts.PouchConstructor || this;\n var replicateRet = new Replication(opts);\n var srcPouch = toPouch(src, opts);\n var targetPouch = toPouch(target, opts);\n replicate(srcPouch, targetPouch, opts, replicateRet);\n return replicateRet;\n}\n\ninherits(Sync, events.EventEmitter);\nfunction sync$1(src, target, opts, callback) {\n if (typeof opts === 'function') {\n callback = opts;\n opts = {};\n }\n if (typeof opts === 'undefined') {\n opts = {};\n }\n opts = clone(opts);\n /*jshint validthis:true */\n opts.PouchConstructor = opts.PouchConstructor || this;\n src = toPouch(src, opts);\n target = toPouch(target, opts);\n return new Sync(src, target, opts, callback);\n}\n\nfunction Sync(src, target, opts, callback) {\n var self = this;\n this.canceled = false;\n\n var optsPush = opts.push ? assign$1({}, opts, opts.push) : opts;\n var optsPull = opts.pull ? assign$1({}, opts, opts.pull) : opts;\n\n this.push = replicateWrapper(src, target, optsPush);\n this.pull = replicateWrapper(target, src, optsPull);\n\n this.pushPaused = true;\n this.pullPaused = true;\n\n function pullChange(change) {\n self.emit('change', {\n direction: 'pull',\n change: change\n });\n }\n function pushChange(change) {\n self.emit('change', {\n direction: 'push',\n change: change\n });\n }\n function pushDenied(doc) {\n self.emit('denied', {\n direction: 'push',\n doc: doc\n });\n }\n function pullDenied(doc) {\n self.emit('denied', {\n direction: 'pull',\n doc: doc\n });\n }\n function pushPaused() {\n self.pushPaused = true;\n /* istanbul ignore if */\n if (self.pullPaused) {\n self.emit('paused');\n }\n }\n function pullPaused() {\n self.pullPaused = true;\n /* istanbul ignore if */\n if (self.pushPaused) {\n self.emit('paused');\n }\n }\n function pushActive() {\n self.pushPaused = false;\n /* istanbul ignore if */\n if (self.pullPaused) {\n self.emit('active', {\n direction: 'push'\n });\n }\n }\n function pullActive() {\n self.pullPaused = false;\n /* istanbul ignore if */\n if (self.pushPaused) {\n self.emit('active', {\n direction: 'pull'\n });\n }\n }\n\n var removed = {};\n\n function removeAll(type) { // type is 'push' or 'pull'\n return function (event, func) {\n var isChange = event === 'change' &&\n (func === pullChange || func === pushChange);\n var isDenied = event === 'denied' &&\n (func === pullDenied || func === pushDenied);\n var isPaused = event === 'paused' &&\n (func === pullPaused || func === pushPaused);\n var isActive = event === 'active' &&\n (func === pullActive || func === pushActive);\n\n if (isChange || isDenied || isPaused || isActive) {\n if (!(event in removed)) {\n removed[event] = {};\n }\n removed[event][type] = true;\n if (Object.keys(removed[event]).length === 2) {\n // both push and pull have asked to be removed\n self.removeAllListeners(event);\n }\n }\n };\n }\n\n if (opts.live) {\n this.push.on('complete', self.pull.cancel.bind(self.pull));\n this.pull.on('complete', self.push.cancel.bind(self.push));\n }\n\n function addOneListener(ee, event, listener) {\n if (ee.listeners(event).indexOf(listener) == -1) {\n ee.on(event, listener);\n }\n }\n\n this.on('newListener', function (event) {\n if (event === 'change') {\n addOneListener(self.pull, 'change', pullChange);\n addOneListener(self.push, 'change', pushChange);\n } else if (event === 'denied') {\n addOneListener(self.pull, 'denied', pullDenied);\n addOneListener(self.push, 'denied', pushDenied);\n } else if (event === 'active') {\n addOneListener(self.pull, 'active', pullActive);\n addOneListener(self.push, 'active', pushActive);\n } else if (event === 'paused') {\n addOneListener(self.pull, 'paused', pullPaused);\n addOneListener(self.push, 'paused', pushPaused);\n }\n });\n\n this.on('removeListener', function (event) {\n if (event === 'change') {\n self.pull.removeListener('change', pullChange);\n self.push.removeListener('change', pushChange);\n } else if (event === 'denied') {\n self.pull.removeListener('denied', pullDenied);\n self.push.removeListener('denied', pushDenied);\n } else if (event === 'active') {\n self.pull.removeListener('active', pullActive);\n self.push.removeListener('active', pushActive);\n } else if (event === 'paused') {\n self.pull.removeListener('paused', pullPaused);\n self.push.removeListener('paused', pushPaused);\n }\n });\n\n this.pull.on('removeListener', removeAll('pull'));\n this.push.on('removeListener', removeAll('push'));\n\n var promise = PouchPromise$1.all([\n this.push,\n this.pull\n ]).then(function (resp) {\n var out = {\n push: resp[0],\n pull: resp[1]\n };\n self.emit('complete', out);\n if (callback) {\n callback(null, out);\n }\n self.removeAllListeners();\n return out;\n }, function (err) {\n self.cancel();\n if (callback) {\n // if there's a callback, then the callback can receive\n // the error event\n callback(err);\n } else {\n // if there's no callback, then we're safe to emit an error\n // event, which would otherwise throw an unhandled error\n // due to 'error' being a special event in EventEmitters\n self.emit('error', err);\n }\n self.removeAllListeners();\n if (callback) {\n // no sense throwing if we're already emitting an 'error' event\n throw err;\n }\n });\n\n this.then = function (success, err) {\n return promise.then(success, err);\n };\n\n this.catch = function (err) {\n return promise.catch(err);\n };\n}\n\nSync.prototype.cancel = function () {\n if (!this.canceled) {\n this.canceled = true;\n this.push.cancel();\n this.pull.cancel();\n }\n};\n\nfunction replication(PouchDB) {\n PouchDB.replicate = replicateWrapper;\n PouchDB.sync = sync$1;\n\n Object.defineProperty(PouchDB.prototype, 'replicate', {\n get: function () {\n var self = this;\n return {\n from: function (other, opts, callback) {\n return self.constructor.replicate(other, self, opts, callback);\n },\n to: function (other, opts, callback) {\n return self.constructor.replicate(self, other, opts, callback);\n }\n };\n }\n });\n\n PouchDB.prototype.sync = function (dbName, opts, callback) {\n return this.constructor.sync(this, dbName, opts, callback);\n };\n}\n\nPouchDB$5.plugin(IDBPouch)\n .plugin(WebSqlPouch)\n .plugin(HttpPouch$1)\n .plugin(mapreduce)\n .plugin(replication);\n\n// Pull from src because pouchdb-node/pouchdb-browser themselves\n// are aggressively optimized and jsnext:main would normally give us this\n// aggressive bundle.\n\nmodule.exports = PouchDB$5;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/pouchdb/lib/index-browser.js\n// module id = 205\n// module chunks = 0","'use strict';\nvar immediate = require('immediate');\n\n/* istanbul ignore next */\nfunction INTERNAL() {}\n\nvar handlers = {};\n\nvar REJECTED = ['REJECTED'];\nvar FULFILLED = ['FULFILLED'];\nvar PENDING = ['PENDING'];\n\nmodule.exports = Promise;\n\nfunction Promise(resolver) {\n if (typeof resolver !== 'function') {\n throw new TypeError('resolver must be a function');\n }\n this.state = PENDING;\n this.queue = [];\n this.outcome = void 0;\n if (resolver !== INTERNAL) {\n safelyResolveThenable(this, resolver);\n }\n}\n\nPromise.prototype[\"catch\"] = function (onRejected) {\n return this.then(null, onRejected);\n};\nPromise.prototype.then = function (onFulfilled, onRejected) {\n if (typeof onFulfilled !== 'function' && this.state === FULFILLED ||\n typeof onRejected !== 'function' && this.state === REJECTED) {\n return this;\n }\n var promise = new this.constructor(INTERNAL);\n if (this.state !== PENDING) {\n var resolver = this.state === FULFILLED ? onFulfilled : onRejected;\n unwrap(promise, resolver, this.outcome);\n } else {\n this.queue.push(new QueueItem(promise, onFulfilled, onRejected));\n }\n\n return promise;\n};\nfunction QueueItem(promise, onFulfilled, onRejected) {\n this.promise = promise;\n if (typeof onFulfilled === 'function') {\n this.onFulfilled = onFulfilled;\n this.callFulfilled = this.otherCallFulfilled;\n }\n if (typeof onRejected === 'function') {\n this.onRejected = onRejected;\n this.callRejected = this.otherCallRejected;\n }\n}\nQueueItem.prototype.callFulfilled = function (value) {\n handlers.resolve(this.promise, value);\n};\nQueueItem.prototype.otherCallFulfilled = function (value) {\n unwrap(this.promise, this.onFulfilled, value);\n};\nQueueItem.prototype.callRejected = function (value) {\n handlers.reject(this.promise, value);\n};\nQueueItem.prototype.otherCallRejected = function (value) {\n unwrap(this.promise, this.onRejected, value);\n};\n\nfunction unwrap(promise, func, value) {\n immediate(function () {\n var returnValue;\n try {\n returnValue = func(value);\n } catch (e) {\n return handlers.reject(promise, e);\n }\n if (returnValue === promise) {\n handlers.reject(promise, new TypeError('Cannot resolve promise with itself'));\n } else {\n handlers.resolve(promise, returnValue);\n }\n });\n}\n\nhandlers.resolve = function (self, value) {\n var result = tryCatch(getThen, value);\n if (result.status === 'error') {\n return handlers.reject(self, result.value);\n }\n var thenable = result.value;\n\n if (thenable) {\n safelyResolveThenable(self, thenable);\n } else {\n self.state = FULFILLED;\n self.outcome = value;\n var i = -1;\n var len = self.queue.length;\n while (++i < len) {\n self.queue[i].callFulfilled(value);\n }\n }\n return self;\n};\nhandlers.reject = function (self, error) {\n self.state = REJECTED;\n self.outcome = error;\n var i = -1;\n var len = self.queue.length;\n while (++i < len) {\n self.queue[i].callRejected(error);\n }\n return self;\n};\n\nfunction getThen(obj) {\n // Make sure we only access the accessor once as required by the spec\n var then = obj && obj.then;\n if (obj && typeof obj === 'object' && typeof then === 'function') {\n return function appyThen() {\n then.apply(obj, arguments);\n };\n }\n}\n\nfunction safelyResolveThenable(self, thenable) {\n // Either fulfill, reject or reject with error\n var called = false;\n function onError(value) {\n if (called) {\n return;\n }\n called = true;\n handlers.reject(self, value);\n }\n\n function onSuccess(value) {\n if (called) {\n return;\n }\n called = true;\n handlers.resolve(self, value);\n }\n\n function tryToUnwrap() {\n thenable(onSuccess, onError);\n }\n\n var result = tryCatch(tryToUnwrap);\n if (result.status === 'error') {\n onError(result.value);\n }\n}\n\nfunction tryCatch(func, value) {\n var out = {};\n try {\n out.value = func(value);\n out.status = 'success';\n } catch (e) {\n out.status = 'error';\n out.value = e;\n }\n return out;\n}\n\nPromise.resolve = resolve;\nfunction resolve(value) {\n if (value instanceof this) {\n return value;\n }\n return handlers.resolve(new this(INTERNAL), value);\n}\n\nPromise.reject = reject;\nfunction reject(reason) {\n var promise = new this(INTERNAL);\n return handlers.reject(promise, reason);\n}\n\nPromise.all = all;\nfunction all(iterable) {\n var self = this;\n if (Object.prototype.toString.call(iterable) !== '[object Array]') {\n return this.reject(new TypeError('must be an array'));\n }\n\n var len = iterable.length;\n var called = false;\n if (!len) {\n return this.resolve([]);\n }\n\n var values = new Array(len);\n var resolved = 0;\n var i = -1;\n var promise = new this(INTERNAL);\n\n while (++i < len) {\n allResolver(iterable[i], i);\n }\n return promise;\n function allResolver(value, i) {\n self.resolve(value).then(resolveFromAll, function (error) {\n if (!called) {\n called = true;\n handlers.reject(promise, error);\n }\n });\n function resolveFromAll(outValue) {\n values[i] = outValue;\n if (++resolved === len && !called) {\n called = true;\n handlers.resolve(promise, values);\n }\n }\n }\n}\n\nPromise.race = race;\nfunction race(iterable) {\n var self = this;\n if (Object.prototype.toString.call(iterable) !== '[object Array]') {\n return this.reject(new TypeError('must be an array'));\n }\n\n var len = iterable.length;\n var called = false;\n if (!len) {\n return this.resolve([]);\n }\n\n var i = -1;\n var promise = new this(INTERNAL);\n\n while (++i < len) {\n resolver(iterable[i]);\n }\n return promise;\n function resolver(value) {\n self.resolve(value).then(function (response) {\n if (!called) {\n called = true;\n handlers.resolve(promise, response);\n }\n }, function (error) {\n if (!called) {\n called = true;\n handlers.reject(promise, error);\n }\n });\n }\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/pouchdb/~/lie/lib/browser.js\n// module id = 206\n// module chunks = 0","'use strict';\nvar Mutation = global.MutationObserver || global.WebKitMutationObserver;\n\nvar scheduleDrain;\n\n{\n if (Mutation) {\n var called = 0;\n var observer = new Mutation(nextTick);\n var element = global.document.createTextNode('');\n observer.observe(element, {\n characterData: true\n });\n scheduleDrain = function () {\n element.data = (called = ++called % 2);\n };\n } else if (!global.setImmediate && typeof global.MessageChannel !== 'undefined') {\n var channel = new global.MessageChannel();\n channel.port1.onmessage = nextTick;\n scheduleDrain = function () {\n channel.port2.postMessage(0);\n };\n } else if ('document' in global && 'onreadystatechange' in global.document.createElement('script')) {\n scheduleDrain = function () {\n\n // Create a