diff --git a/CHANGELOG.md b/CHANGELOG.md index 25b6b4ad..972c0746 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,12 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Removed - none yet + +## [v0.9.0] - 2018-04-27 +### Added +- Intent composition +- Code is formatted using Prettier + ## [v0.8.3] - 2018-04-18 ### Changed - Intent service now force document height to 100% @@ -320,7 +326,8 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - Refactoring on offline to return Promise -[Unreleased]: https://github.com/cozy/cozy-client-js/compare/v0.8.3...HEAD +[Unreleased]: https://github.com/cozy/cozy-client-js/compare/v0.9.0...HEAD +[v0.9.0]: https://github.com/cozy/cozy-client-js/compare/v0.8.3...v0.9.0 [v0.8.3]: https://github.com/cozy/cozy-client-js/compare/v0.8.2...v0.8.3 [v0.8.2]: https://github.com/cozy/cozy-client-js/compare/v0.8.1...v0.8.2 [v0.8.1]: https://github.com/cozy/cozy-client-js/compare/v0.8.0...v0.8.1 diff --git a/dist/cozy-client.js b/dist/cozy-client.js index f6e86f64..95a58812 100644 --- a/dist/cozy-client.js +++ b/dist/cozy-client.js @@ -578,19 +578,19 @@ return /******/ (function(modules) { // webpackBootstrap var intents = _interopRequireWildcard(_intents); - var _jobs = __webpack_require__(55); + var _jobs = __webpack_require__(58); var jobs = _interopRequireWildcard(_jobs); - var _offline = __webpack_require__(56); + var _offline = __webpack_require__(59); var offline = _interopRequireWildcard(_offline); - var _settings = __webpack_require__(98); + var _settings = __webpack_require__(101); var settings = _interopRequireWildcard(_settings); - var _relations = __webpack_require__(99); + var _relations = __webpack_require__(102); var relations = _interopRequireWildcard(_relations); @@ -2104,11 +2104,11 @@ return /******/ (function(modules) { // webpackBootstrap } var state = generateRandomState(); var query = { - 'client_id': client.clientID, - 'redirect_uri': client.redirectURI, - 'state': state, - 'response_type': 'code', - 'scope': scopes.join(' ') + client_id: client.clientID, + redirect_uri: client.redirectURI, + state: state, + response_type: 'code', + scope: scopes.join(' ') }; return { url: cozy._url + ('/auth/authorize?' + (0, _utils.encodeQuery)(query)), @@ -2137,8 +2137,8 @@ return /******/ (function(modules) { // webpackBootstrap return Promise.reject(new Error('Given state does not match url query state')); } return retrieveToken(cozy, client, null, { - 'grant_type': 'authorization_code', - 'code': grantQueries.code + grant_type: 'authorization_code', + code: grantQueries.code }); } @@ -2146,8 +2146,8 @@ return /******/ (function(modules) { // webpackBootstrap // refresh_token grant type in order to refresh the given token. function refreshToken(cozy, client, token) { return retrieveToken(cozy, client, token, { - 'grant_type': 'refresh_token', - 'refresh_token': token.refreshToken + grant_type: 'refresh_token', + refresh_token: token.refreshToken }); } @@ -2267,8 +2267,8 @@ return /******/ (function(modules) { // webpackBootstrap return Promise.reject(new Error('Client not registered')); } var body = (0, _utils.encodeQuery)(Object.assign({}, query, { - 'client_id': client.clientID, - 'client_secret': client.clientSecret + client_id: client.clientID, + client_secret: client.clientSecret })); return (0, _fetch.cozyFetchJSON)(cozy, 'POST', '/auth/access_token', body, { disableAuth: token === null, @@ -2310,7 +2310,9 @@ return /******/ (function(modules) { // webpackBootstrap } else { try { buffer = __webpack_require__(!(function webpackMissingModule() { var e = new Error("Cannot find module \"crypto\""); e.code = 'MODULE_NOT_FOUND'; throw e; }())).randomBytes(StateSize); - } catch (e) {} + } catch (e) { + buffer = null; + } } if (!buffer) { buffer = new Array(StateSize); @@ -2495,7 +2497,7 @@ return /******/ (function(modules) { // webpackBootstrap var requestUrl = error.url; if (requestUrl.indexOf(currentOrigin.replace(/^(https?:\/\/\w+)-\w+\./, '$1.')) === 0) { - var redirectURL = currentOrigin + '?' + (0, _utils.encodeQuery)({ 'disconnect': 1 }); + var redirectURL = currentOrigin + '?' + (0, _utils.encodeQuery)({ disconnect: 1 }); window.location = redirectURL; } } catch (e) { @@ -2691,7 +2693,9 @@ return /******/ (function(modules) { // webpackBootstrap return Promise.reject(new Error('findMany is not available on v2')); } - var path = (0, _utils.createPath)(cozy, isV2, doctype, '_all_docs', { include_docs: true }); + var path = (0, _utils.createPath)(cozy, isV2, doctype, '_all_docs', { + include_docs: true + }); return (0, _fetch.cozyFetchJSON)(cozy, 'POST', path, { keys: ids }).then(function (resp) { var docs = {}; @@ -2768,7 +2772,9 @@ return /******/ (function(modules) { // webpackBootstrap return Promise.reject(new Error('findAll is not available on v2')); } - var path = (0, _utils.createPath)(cozy, isV2, doctype, '_all_docs', { include_docs: true }); + var path = (0, _utils.createPath)(cozy, isV2, doctype, '_all_docs', { + include_docs: true + }); return (0, _fetch.cozyFetchJSON)(cozy, 'POST', path, {}).then(function (resp) { var docs = []; @@ -2911,12 +2917,12 @@ return /******/ (function(modules) { // webpackBootstrap var DOCTYPE_FILES = exports.DOCTYPE_FILES = 'io.cozy.files'; var KNOWN_DOCTYPES = { - 'files': DOCTYPE_FILES, - 'folder': DOCTYPE_FILES, - 'contact': 'io.cozy.contacts', - 'event': 'io.cozy.events', - 'track': 'io.cozy.labs.music.track', - 'playlist': 'io.cozy.labs.music.playlist' + files: DOCTYPE_FILES, + folder: DOCTYPE_FILES, + contact: 'io.cozy.contacts', + event: 'io.cozy.events', + track: 'io.cozy.labs.music.track', + playlist: 'io.cozy.labs.music.playlist' }; var REVERSE_KNOWN = {}; @@ -3024,26 +3030,39 @@ return /******/ (function(modules) { // webpackBootstrap // It transforms the index fields into a map reduce view. function defineIndexV2(cozy, doctype, fields) { var indexName = 'by' + fields.map(capitalize).join(''); - var indexDefinition = { map: makeMapFunction(doctype, fields), reduce: '_count' }; + var indexDefinition = { + map: makeMapFunction(doctype, fields), + reduce: '_count' + }; var path = '/request/' + doctype + '/' + indexName + '/'; return (0, _fetch.cozyFetchJSON)(cozy, 'PUT', path, indexDefinition).then(function () { - return { doctype: doctype, type: 'mapreduce', name: indexName, fields: fields }; + return { + doctype: doctype, + type: 'mapreduce', + name: indexName, + fields: fields + }; }); } function defineIndexV3(cozy, doctype, fields) { var path = (0, _utils.createPath)(cozy, false, doctype, '_index'); - var indexDefinition = { 'index': { fields: fields } }; + var indexDefinition = { index: { fields: fields } }; return (0, _fetch.cozyFetchJSON)(cozy, 'POST', path, indexDefinition).then(function (response) { - var indexResult = { doctype: doctype, type: 'mango', name: response.id, fields: fields }; + var indexResult = { + doctype: doctype, + type: 'mango', + name: response.id, + fields: fields + }; if (response.result === 'exists') return indexResult; // indexes might not be usable right after being created; so we delay the resolving until they are var selector = {}; - selector[fields[0]] = { '$gt': null }; + selector[fields[0]] = { $gt: null }; - var opts = getV3Options(indexResult, { 'selector': selector }); + var opts = getV3Options(indexResult, { selector: selector }); var path = (0, _utils.createPath)(cozy, false, indexResult.doctype, '_find'); return (0, _fetch.cozyFetchJSON)(cozy, 'POST', path, opts).then(function () { return indexResult; @@ -3449,7 +3468,7 @@ return /******/ (function(modules) { // webpackBootstrap var query = '?Name=' + encodeURIComponent(name) + '&Type=directory'; return (0, _fetch.cozyFetchJSON)(cozy, 'POST', '' + path + query, undefined, { headers: { - 'Date': lastModifiedDate ? lastModifiedDate.toGMTString() : '' + Date: lastModifiedDate ? lastModifiedDate.toGMTString() : '' } }); } @@ -3503,7 +3522,9 @@ return /******/ (function(modules) { // webpackBootstrap var body = { data: { - attributes: Object.assign({}, attrs, { name: sanitizeFileName(attrs.name) }) + attributes: Object.assign({}, attrs, { + name: sanitizeFileName(attrs.name) + }) } }; return (0, _fetch.cozyFetchJSON)(cozy, 'PATCH', path, body, { @@ -3542,7 +3563,7 @@ return /******/ (function(modules) { // webpackBootstrap if (offline && cozy.offline.hasDatabase(_doctypes.DOCTYPE_FILES)) { var db = cozy.offline.getDatabase(_doctypes.DOCTYPE_FILES); - return Promise.all([db.get(id), db.find(Object.assign({ selector: { 'dir_id': id } }, options))]).then(function (_ref6) { + return Promise.all([db.get(id), db.find(Object.assign({ selector: { dir_id: id } }, options))]).then(function (_ref6) { var _ref7 = _slicedToArray(_ref6, 2), doc = _ref7[0], children = _ref7[1]; @@ -3625,7 +3646,10 @@ return /******/ (function(modules) { // webpackBootstrap } } }).then(function (data) { - return { sharecode: 'sharecode=' + data.attributes.codes.email, id: 'id=' + id }; + return { + sharecode: 'sharecode=' + data.attributes.codes.email, + id: 'id=' + id + }; }); } @@ -3774,7 +3798,7 @@ return /******/ (function(modules) { // webpackBootstrap case 4: intent = _context.sent; - service = pickService(intent); + service = (0, _helpers.pickService)(intent); if (service) { _context.next = 8; @@ -3849,132 +3873,21 @@ return /******/ (function(modules) { // webpackBootstrap var _fetch = __webpack_require__(44); - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - - function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } - - var intentClass = 'coz-intent'; - - // helper to serialize/deserialize an error for/from postMessage - var errorSerializer = function () { - function mapErrorProperties(from, to) { - var result = Object.assign(to, from); - var nativeProperties = ['name', 'message']; - return nativeProperties.reduce(function (result, property) { - if (from[property]) { - to[property] = from[property]; - } - return result; - }, result); - } - return { - serialize: function serialize(error) { - return mapErrorProperties(error, {}); - }, - deserialize: function deserialize(data) { - return mapErrorProperties(data, new Error(data.message)); - } - }; - }(); - - // inject iframe for service in given element - function injectService(url, element, intent, data, onReadyCallback) { - var document = element.ownerDocument; - if (!document) return Promise.reject(new Error('Cannot retrieve document object from given element')); + var _helpers = __webpack_require__(55); - var window = document.defaultView; - if (!window) return Promise.reject(new Error('Cannot retrieve window object from document')); + var _client = __webpack_require__(56); - var iframe = document.createElement('iframe'); - // if callback provided for when iframe is loaded - if (typeof onReadyCallback === 'function') iframe.onload = onReadyCallback; - // TODO: implement 'title' attribute - iframe.setAttribute('src', url); - iframe.classList.add(intentClass); - element.appendChild(iframe); - iframe.focus(); + var client = _interopRequireWildcard(_client); - // Keeps only http://domain:port/ - var serviceOrigin = url.split('/', 3).join('/'); + var _service = __webpack_require__(57); - return new Promise(function (resolve, reject) { - var handshaken = false; - var messageHandler = function messageHandler(event) { - if (event.origin !== serviceOrigin) return; - - var eventType = event.data.type; - if (eventType === 'load') { - // Safari 9.1 (At least) send a MessageEvent when the iframe loads, - // making the handshake fails. - console.warn && console.warn('Cozy Client ignored MessageEvent having data.type `load`.'); - return; - } - - if (eventType === 'intent-' + intent._id + ':ready') { - handshaken = true; - return event.source.postMessage(data, event.origin); - } - - if (handshaken && eventType === 'intent-' + intent._id + ':resize') { - ['width', 'height', 'maxWidth', 'maxHeight'].forEach(function (prop) { - if (event.data.transition) element.style.transition = event.data.transition; - if (event.data.dimensions[prop]) element.style[prop] = event.data.dimensions[prop] + 'px'; - }); + var service = _interopRequireWildcard(_service); - return true; - } - - window.removeEventListener('message', messageHandler); - var removeIntentFrame = function removeIntentFrame() { - // check if the parent node has not been already removed from the DOM - iframe.parentNode && iframe.parentNode.removeChild(iframe); - }; - - if (handshaken && eventType === 'intent-' + intent._id + ':exposeFrameRemoval') { - return resolve({ removeIntentFrame: removeIntentFrame, doc: event.data.document }); - } - - removeIntentFrame(); - - if (eventType === 'intent-' + intent._id + ':error') { - return reject(errorSerializer.deserialize(event.data.error)); - } - - if (handshaken && eventType === 'intent-' + intent._id + ':cancel') { - return resolve(null); - } - - if (handshaken && eventType === 'intent-' + intent._id + ':done') { - return resolve(event.data.document); - } - - if (!handshaken) { - return reject(new Error('Unexpected handshake message from intent service')); - } - - // We may be in a state where the messageHandler is still attached to then - // window, but will not be needed anymore. For example, the service failed - // before adding the `unload` listener, so no `intent:cancel` message has - // never been sent. - // So we simply ignore other messages, and this listener will stay here, - // waiting for a message which will never come, forever (almost). - }; + function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - window.addEventListener('message', messageHandler); - }); - } + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - var first = function first(arr) { - return arr && arr[0]; - }; - // In a far future, the user will have to pick the desired service from a list. - // For now it's our job, an easy job as we arbitrary pick the first service of - // the list. - function pickService(intent, filterServices) { - var services = intent.attributes.services; - var filteredServices = filterServices ? (services || []).filter(filterServices) : services; - return first(filteredServices); - } + function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } function create(cozy, action, type) { var data = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; @@ -3996,124 +3909,24 @@ return /******/ (function(modules) { // webpackBootstrap }); createPromise.start = function (element, onReadyCallback) { - return createPromise.then(function (intent) { - var service = pickService(intent, data.filterServices); - var restData = Object.assign({}, data); - delete restData.filterServices; + var options = { + filteredServices: data.filteredServices, + onReadyCallback: onReadyCallback + }; - if (!service) { - return Promise.reject(new Error('Unable to find a service')); - } + delete data.filteredServices; - return injectService(service.href, element, intent, restData, onReadyCallback); + return createPromise.then(function (intent) { + return client.start(cozy, intent, element, data, options); }); }; return createPromise; } - function listenClientData(intent, window) { - return new Promise(function (resolve, reject) { - var messageEventListener = function messageEventListener(event) { - if (event.origin !== intent.attributes.client) return; - - window.removeEventListener('message', messageEventListener); - resolve(event.data); - }; - - window.addEventListener('message', messageEventListener); - window.parent.postMessage({ - type: 'intent-' + intent._id + ':ready' - }, intent.attributes.client); - }); - } - - // maximize the height of an element - function maximize(element) { - if (element && element.style) { - element.style.height = '100%'; - } - } - // returns a service to communicate with intent client function createService(cozy, intentId, serviceWindow) { - serviceWindow = serviceWindow || typeof window !== 'undefined' && window; - if (!serviceWindow || !serviceWindow.document) { - return Promise.reject(new Error('Intent service should be used in browser')); - } - - // Maximize document, the whole iframe is handled by intents, clients and - // services - serviceWindow.addEventListener('load', function () { - var _serviceWindow = serviceWindow, - document = _serviceWindow.document; - [document.documentElement, document.body].forEach(maximize); - }); - - intentId = intentId || serviceWindow.location.search.split('=')[1]; - if (!intentId) return Promise.reject(new Error('Cannot retrieve intent from URL')); - - return (0, _fetch.cozyFetchJSON)(cozy, 'GET', '/intents/' + intentId).then(function (intent) { - var terminated = false; - - var _terminate = function _terminate(message) { - if (terminated) throw new Error('Intent service has already been terminated'); - terminated = true; - serviceWindow.parent.postMessage(message, intent.attributes.client); - }; - - var resizeClient = function resizeClient(dimensions, transitionProperty) { - if (terminated) throw new Error('Intent service has been terminated'); - - var message = { - type: 'intent-' + intent._id + ':resize', - // if a dom element is passed, calculate its size - dimensions: dimensions.element ? Object.assign({}, dimensions, { - maxHeight: dimensions.element.clientHeight, - maxWidth: dimensions.element.clientWidth - }) : dimensions, - transition: transitionProperty - }; - - serviceWindow.parent.postMessage(message, intent.attributes.client); - }; - - var cancel = function cancel() { - _terminate({ type: 'intent-' + intent._id + ':cancel' }); - }; - - // Prevent unfulfilled client promises when this window unloads for a - // reason or another. - serviceWindow.addEventListener('unload', function () { - if (!terminated) cancel(); - }); - - return listenClientData(intent, serviceWindow).then(function (data) { - return { - getData: function getData() { - return data; - }, - getIntent: function getIntent() { - return intent; - }, - terminate: function terminate(doc) { - var eventName = data && data.exposeIntentFrameRemoval ? 'exposeFrameRemoval' : 'done'; - return _terminate({ - type: 'intent-' + intent._id + ':' + eventName, - document: doc - }); - }, - throw: function _throw(error) { - return _terminate({ - type: 'intent-' + intent._id + ':error', - error: errorSerializer.serialize(error) - }); - }, - resizeClient: resizeClient, - cancel: cancel - }; - }); - }); + return service.start(cozy, intentId, serviceWindow); } function isSerializable(value) { @@ -4997,102 +4810,546 @@ return /******/ (function(modules) { // webpackBootstrap - } - var queue = []; - var draining = false; - var currentQueue; - var queueIndex = -1; + } + 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; }; + + +/***/ }, +/* 55 */ +/***/ function(module, exports) { + + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.pickService = pickService; + // helper to serialize/deserialize an error for/from postMessage + var errorSerializer = exports.errorSerializer = function () { + function mapErrorProperties(from, to) { + var result = Object.assign(to, from); + var nativeProperties = ['name', 'message']; + return nativeProperties.reduce(function (result, property) { + if (from[property]) { + to[property] = from[property]; + } + return result; + }, result); + } + return { + serialize: function serialize(error) { + return mapErrorProperties(error, {}); + }, + deserialize: function deserialize(data) { + return mapErrorProperties(data, new Error(data.message)); + } + }; + }(); + + var first = function first(arr) { + return arr && arr[0]; + }; + // In a far future, the user will have to pick the desired service from a list. + // For now it's our job, an easy job as we arbitrary pick the first service of + // the list. + function pickService(intent, filterServices) { + var services = intent.attributes.services; + var filteredServices = filterServices ? (services || []).filter(filterServices) : services; + return first(filteredServices); + } + +/***/ }, +/* 56 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + var _regenerator = __webpack_require__(51); + + var _regenerator2 = _interopRequireDefault(_regenerator); + + var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; + + exports.start = start; + + var _helpers = __webpack_require__(55); + + var _ = __webpack_require__(50); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } + + var intentClass = 'coz-intent'; + + function hideIntentIframe(iframe) { + iframe.style.display = 'none'; + } + + function showIntentFrame(iframe) { + iframe.style.display = 'block'; + } + + function buildIntentIframe(intent, element, url) { + var document = element.ownerDocument; + if (!document) return Promise.reject(new Error('Cannot retrieve document object from given element')); + + var iframe = document.createElement('iframe'); + // TODO: implement 'title' attribute + iframe.setAttribute('id', 'intent-' + intent._id); + iframe.setAttribute('src', url); + iframe.classList.add(intentClass); + return iframe; + } + + function injectIntentIframe(intent, element, url, options) { + var onReadyCallback = options.onReadyCallback; + + var iframe = buildIntentIframe(intent, element, url, options.onReadyCallback); + // if callback provided for when iframe is loaded + if (typeof onReadyCallback === 'function') iframe.onload = onReadyCallback; + element.appendChild(iframe); + iframe.focus(); + return iframe; + } + + // inject iframe for service in given element + function connectIntentIframe(cozy, iframe, element, intent, data) { + var _this = this; + + var compose = function () { + var _ref = _asyncToGenerator( /*#__PURE__*/_regenerator2.default.mark(function _callee(cozy, action, doctype, data) { + var intent, doc; + return _regenerator2.default.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return (0, _.create)(cozy, action, doctype, data); + + case 2: + intent = _context.sent; + + hideIntentIframe(iframe); + _context.next = 6; + return start(cozy, intent, element, _extends({}, data, { + exposeIntentFrameRemoval: false + })); + + case 6: + doc = _context.sent; + + showIntentFrame(iframe); + return _context.abrupt('return', doc); + + case 9: + case 'end': + return _context.stop(); + } + } + }, _callee, this); + })); + + return function compose(_x, _x2, _x3, _x4) { + return _ref.apply(this, arguments); + }; + }(); + + var document = element.ownerDocument; + if (!document) return Promise.reject(new Error('Cannot retrieve document object from given element')); + + var window = document.defaultView; + if (!window) return Promise.reject(new Error('Cannot retrieve window object from document')); + + // Keeps only http://domain:port/ + var serviceOrigin = iframe.src.split('/', 3).join('/'); + + return new Promise(function (resolve, reject) { + var handshaken = false; + var messageHandler = function () { + var _ref2 = _asyncToGenerator( /*#__PURE__*/_regenerator2.default.mark(function _callee2(event) { + var eventType, _event$data, action, doctype, _data, doc, removeIntentFrame; + + return _regenerator2.default.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + if (!(event.origin !== serviceOrigin)) { + _context2.next = 2; + break; + } + + return _context2.abrupt('return'); + + case 2: + eventType = event.data.type; + + if (!(eventType === 'load')) { + _context2.next = 6; + break; + } + + // Safari 9.1 (At least) send a MessageEvent when the iframe loads, + // making the handshake fails. + console.warn && console.warn('Cozy Client ignored MessageEvent having data.type `load`.'); + return _context2.abrupt('return'); + + case 6: + if (!(eventType === 'intent-' + intent._id + ':ready')) { + _context2.next = 9; + break; + } + + handshaken = true; + return _context2.abrupt('return', event.source.postMessage(data, event.origin)); + + case 9: + if (!(handshaken && eventType === 'intent-' + intent._id + ':resize')) { + _context2.next = 13; + break; + } + + ;['width', 'height', 'maxWidth', 'maxHeight'].forEach(function (prop) { + if (event.data.transition) element.style.transition = event.data.transition; + if (event.data.dimensions[prop]) element.style[prop] = event.data.dimensions[prop] + 'px'; + }); + + return _context2.abrupt('return', true); + + case 13: + if (!(handshaken && eventType === 'intent-' + intent._id + ':compose')) { + _context2.next = 19; + break; + } + + // Let start to name `type` as `doctype`, as `event.data` already have a `type` attribute. + _event$data = event.data, action = _event$data.action, doctype = _event$data.doctype, _data = _event$data.data; + _context2.next = 17; + return compose(cozy, action, doctype, _data); + + case 17: + doc = _context2.sent; + return _context2.abrupt('return', event.source.postMessage(doc, event.origin)); + + case 19: + + window.removeEventListener('message', messageHandler); + + removeIntentFrame = function removeIntentFrame() { + // check if the parent node has not been already removed from the DOM + iframe.parentNode && iframe.parentNode.removeChild(iframe); + }; + + if (!(handshaken && eventType === 'intent-' + intent._id + ':exposeFrameRemoval')) { + _context2.next = 23; + break; + } + + return _context2.abrupt('return', resolve({ removeIntentFrame: removeIntentFrame, doc: event.data.document })); + + case 23: + + removeIntentFrame(); + + if (!(eventType === 'intent-' + intent._id + ':error')) { + _context2.next = 26; + break; + } + + return _context2.abrupt('return', reject(_helpers.errorSerializer.deserialize(event.data.error))); + + case 26: + if (!(handshaken && eventType === 'intent-' + intent._id + ':cancel')) { + _context2.next = 28; + break; + } + + return _context2.abrupt('return', resolve(null)); + + case 28: + if (!(handshaken && eventType === 'intent-' + intent._id + ':done')) { + _context2.next = 30; + break; + } + + return _context2.abrupt('return', resolve(event.data.document)); + + case 30: + if (handshaken) { + _context2.next = 32; + break; + } + + return _context2.abrupt('return', reject(new Error('Unexpected handshake message from intent service'))); + + case 32: + case 'end': + return _context2.stop(); + } + } + }, _callee2, _this); + })); + + return function messageHandler(_x5) { + return _ref2.apply(this, arguments); + }; + }(); + + window.addEventListener('message', messageHandler); + }); + } + + function start(cozy, intent, element) { + var data = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; + var options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {}; + + var service = (0, _helpers.pickService)(intent, options.filterServices); + + if (!service) { + throw new Error('Unable to find a service'); + } + + var iframe = injectIntentIframe(intent, element, service.href, options); + + return connectIntentIframe(cozy, iframe, element, intent, data, options.onReadyCallback); + } + +/***/ }, +/* 57 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.start = start; + + var _fetch = __webpack_require__(44); + + var _helpers = __webpack_require__(55); + + function listenClientData(intent, window) { + return new Promise(function (resolve) { + var messageEventListener = function messageEventListener(event) { + if (event.origin !== intent.attributes.client) return; + + window.removeEventListener('message', messageEventListener); + resolve(event.data); + }; + + window.addEventListener('message', messageEventListener); + window.parent.postMessage({ + type: 'intent-' + intent._id + ':ready' + }, intent.attributes.client); + }); + } + + // maximize the height of an element + function maximize(element) { + if (element && element.style) { + element.style.height = '100%'; + } + } + + function start(cozy, intentId, serviceWindow) { + serviceWindow = serviceWindow || typeof window !== 'undefined' && window; + if (!serviceWindow || !serviceWindow.document) { + return Promise.reject(new Error('Intent service should be used in browser')); + } + + // Maximize document, the whole iframe is handled by intents, clients and + // services + serviceWindow.addEventListener('load', function () { + var _serviceWindow = serviceWindow, + document = _serviceWindow.document; + [document.documentElement, document.body].forEach(maximize); + }); - function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); - } - } + intentId = intentId || serviceWindow.location.search.split('=')[1]; + if (!intentId) return Promise.reject(new Error('Cannot retrieve intent from URL')); - function drainQueue() { - if (draining) { - return; - } - var timeout = runTimeout(cleanUpNextTick); - draining = true; + return (0, _fetch.cozyFetchJSON)(cozy, 'GET', '/intents/' + intentId).then(function (intent) { + var terminated = false; - 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); - } + var sendMessage = function sendMessage(message) { + if (terminated) throw new Error('Intent service has already been terminated'); + serviceWindow.parent.postMessage(message, intent.attributes.client); + }; - 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); - } - }; + var compose = function compose(action, doctype, data) { + return new Promise(function (resolve) { + var composeEventListener = function composeEventListener(event) { + if (event.origin !== intent.attributes.client) return; + serviceWindow.removeEventListener('message', composeEventListener); + return resolve(event.data); + }; - // 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 = {}; + serviceWindow.addEventListener('message', composeEventListener); - function noop() {} + sendMessage({ + type: 'intent-' + intent._id + ':compose', + action: action, + doctype: doctype, + data: data + }); + }); + }; - process.on = noop; - process.addListener = noop; - process.once = noop; - process.off = noop; - process.removeListener = noop; - process.removeAllListeners = noop; - process.emit = noop; + var _terminate = function _terminate(message) { + sendMessage(message); + terminated = true; + }; - process.binding = function (name) { - throw new Error('process.binding is not supported'); - }; + var resizeClient = function resizeClient(dimensions, transitionProperty) { + if (terminated) throw new Error('Intent service has been terminated'); - process.cwd = function () { return '/' }; - process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); - }; - process.umask = function() { return 0; }; - + sendMessage({ + type: 'intent-' + intent._id + ':resize', + // if a dom element is passed, calculate its size + dimensions: dimensions.element ? Object.assign({}, dimensions, { + maxHeight: dimensions.element.clientHeight, + maxWidth: dimensions.element.clientWidth + }) : dimensions, + transition: transitionProperty + }); + }; + + var cancel = function cancel() { + _terminate({ type: 'intent-' + intent._id + ':cancel' }); + }; + + // Prevent unfulfilled client promises when this window unloads for a + // reason or another. + serviceWindow.addEventListener('unload', function () { + if (!terminated) cancel(); + }); + + return listenClientData(intent, serviceWindow).then(function (data) { + return { + compose: compose, + getData: function getData() { + return data; + }, + getIntent: function getIntent() { + return intent; + }, + terminate: function terminate(doc) { + var eventName = data && data.exposeIntentFrameRemoval ? 'exposeFrameRemoval' : 'done'; + return _terminate({ + type: 'intent-' + intent._id + ':' + eventName, + document: doc + }); + }, + throw: function _throw(error) { + return _terminate({ + type: 'intent-' + intent._id + ':error', + error: _helpers.errorSerializer.serialize(error) + }); + }, + resizeClient: resizeClient, + cancel: cancel + }; + }); + }); + } /***/ }, -/* 55 */ +/* 58 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -5129,7 +5386,7 @@ return /******/ (function(modules) { // webpackBootstrap } /***/ }, -/* 56 */ +/* 59 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -5161,11 +5418,11 @@ return /******/ (function(modules) { // webpackBootstrap var _utils = __webpack_require__(40); - var _pouchdb = __webpack_require__(57); + var _pouchdb = __webpack_require__(60); var _pouchdb2 = _interopRequireDefault(_pouchdb); - var _pouchdbFind = __webpack_require__(69); + var _pouchdbFind = __webpack_require__(72); var _pouchdbFind2 = _interopRequireDefault(_pouchdbFind); @@ -5291,7 +5548,9 @@ return /******/ (function(modules) { // webpackBootstrap function createIndexes(cozy, doctype) { if (doctype === _doctypes.DOCTYPE_FILES) { - return getDatabase(cozy, doctype).createIndex({ index: { fields: ['dir_id'] } }); + return getDatabase(cozy, doctype).createIndex({ + index: { fields: ['dir_id'] } + }); } return Promise.resolve(); } @@ -5337,7 +5596,7 @@ return /******/ (function(modules) { // webpackBootstrap createDatabase(cozy, doctype); } if (options.live === true) { - return reject(new Error('You can\'t use `live` option with Cozy couchdb.')); + return reject(new Error("You can't use `live` option with Cozy couchdb.")); } if ((0, _utils.isOffline)()) { @@ -5359,7 +5618,7 @@ return /******/ (function(modules) { // webpackBootstrap (0, _auth_v.refreshToken)(cozy, client, token).then(function (newToken) { return cozy.saveCredentials(client, newToken); - }).then(function (credentials) { + }).then(function () { return replicateFromCozy(cozy, doctype, options); }); }); @@ -5459,22 +5718,22 @@ return /******/ (function(modules) { // webpackBootstrap } /***/ }, -/* 57 */ +/* 60 */ /***/ 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__(58)); - var getArguments = _interopDefault(__webpack_require__(60)); - var debug = _interopDefault(__webpack_require__(61)); - var events = __webpack_require__(64); - var inherits = _interopDefault(__webpack_require__(65)); - var nextTick = _interopDefault(__webpack_require__(59)); - var scopedEval = _interopDefault(__webpack_require__(66)); - var Md5 = _interopDefault(__webpack_require__(67)); - var vuvuzela = _interopDefault(__webpack_require__(68)); + var lie = _interopDefault(__webpack_require__(61)); + var getArguments = _interopDefault(__webpack_require__(63)); + var debug = _interopDefault(__webpack_require__(64)); + var events = __webpack_require__(67); + var inherits = _interopDefault(__webpack_require__(68)); + var nextTick = _interopDefault(__webpack_require__(62)); + var scopedEval = _interopDefault(__webpack_require__(69)); + var Md5 = _interopDefault(__webpack_require__(70)); + var vuvuzela = _interopDefault(__webpack_require__(71)); /* istanbul ignore next */ var PouchPromise$1 = typeof Promise === 'function' ? Promise : lie; @@ -16800,11 +17059,11 @@ return /******/ (function(modules) { // webpackBootstrap /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, -/* 58 */ +/* 61 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var immediate = __webpack_require__(59); + var immediate = __webpack_require__(62); /* istanbul ignore next */ function INTERNAL() {} @@ -17059,7 +17318,7 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, -/* 59 */ +/* 62 */ /***/ function(module, exports) { /* WEBPACK VAR INJECTION */(function(global) {'use strict'; @@ -17135,7 +17394,7 @@ return /******/ (function(modules) { // webpackBootstrap /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, -/* 60 */ +/* 63 */ /***/ function(module, exports) { 'use strict'; @@ -17159,7 +17418,7 @@ return /******/ (function(modules) { // webpackBootstrap } /***/ }, -/* 61 */ +/* 64 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** @@ -17168,7 +17427,7 @@ return /******/ (function(modules) { // webpackBootstrap * Expose `debug()` as the module. */ - exports = module.exports = __webpack_require__(62); + exports = module.exports = __webpack_require__(65); exports.log = log; exports.formatArgs = formatArgs; exports.save = save; @@ -17348,7 +17607,7 @@ return /******/ (function(modules) { // webpackBootstrap /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(54))) /***/ }, -/* 62 */ +/* 65 */ /***/ function(module, exports, __webpack_require__) { @@ -17364,7 +17623,7 @@ return /******/ (function(modules) { // webpackBootstrap exports.disable = disable; exports.enable = enable; exports.enabled = enabled; - exports.humanize = __webpack_require__(63); + exports.humanize = __webpack_require__(66); /** * The currently active debug mode names, and names to skip. @@ -17553,7 +17812,7 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, -/* 63 */ +/* 66 */ /***/ function(module, exports) { /** @@ -17708,7 +17967,7 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, -/* 64 */ +/* 67 */ /***/ function(module, exports) { // Copyright Joyent, Inc. and other Node contributors. @@ -18016,7 +18275,7 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, -/* 65 */ +/* 68 */ /***/ function(module, exports) { if (typeof Object.create === 'function') { @@ -18045,7 +18304,7 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, -/* 66 */ +/* 69 */ /***/ function(module, exports) { // Generated by CoffeeScript 1.9.2 @@ -18073,7 +18332,7 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, -/* 67 */ +/* 70 */ /***/ function(module, exports, __webpack_require__) { (function (factory) { @@ -18830,7 +19089,7 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, -/* 68 */ +/* 71 */ /***/ function(module, exports) { 'use strict'; @@ -19009,15 +19268,15 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, -/* 69 */ +/* 72 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var utils = __webpack_require__(70); + var utils = __webpack_require__(73); - var httpIndexes = __webpack_require__(76); - var localIndexes = __webpack_require__(78); + var httpIndexes = __webpack_require__(79); + var localIndexes = __webpack_require__(81); var plugin = {}; plugin.createIndex = utils.toPromise(function (requestDef, callback) { @@ -19074,12 +19333,12 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, -/* 70 */ +/* 73 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {'use strict'; - var Promise = __webpack_require__(71); + var Promise = __webpack_require__(74); /* istanbul ignore next */ exports.once = function (fun) { @@ -19153,14 +19412,14 @@ return /******/ (function(modules) { // webpackBootstrap }); }; - exports.inherits = __webpack_require__(65); + exports.inherits = __webpack_require__(68); exports.Promise = Promise; exports.clone = function (obj) { return exports.extend(true, {}, obj); }; - exports.extend = __webpack_require__(73); + exports.extend = __webpack_require__(76); exports.callbackify = function (fun) { return exports.getArguments(function (args) { @@ -19184,8 +19443,8 @@ return /******/ (function(modules) { // webpackBootstrap return promise; }; - var crypto = __webpack_require__(74); - var Md5 = __webpack_require__(75); + var crypto = __webpack_require__(77); + var Md5 = __webpack_require__(78); exports.MD5 = function (string) { /* istanbul ignore else */ @@ -19363,19 +19622,19 @@ return /******/ (function(modules) { // webpackBootstrap }); }; - exports.log = __webpack_require__(61)('pouchdb:find'); + exports.log = __webpack_require__(64)('pouchdb:find'); /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(54))) /***/ }, -/* 71 */ +/* 74 */ /***/ 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__(72)); + var lie = _interopDefault(__webpack_require__(75)); /* istanbul ignore next */ var PouchPromise = typeof Promise === 'function' ? Promise : lie; @@ -19383,11 +19642,11 @@ return /******/ (function(modules) { // webpackBootstrap module.exports = PouchPromise; /***/ }, -/* 72 */ +/* 75 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {'use strict'; - var immediate = __webpack_require__(59); + var immediate = __webpack_require__(62); /* istanbul ignore next */ function INTERNAL() {} @@ -19668,7 +19927,7 @@ return /******/ (function(modules) { // webpackBootstrap /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(54))) /***/ }, -/* 73 */ +/* 76 */ /***/ function(module, exports) { "use strict"; @@ -19853,13 +20112,13 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, -/* 74 */ +/* 77 */ /***/ function(module, exports) { /* (ignored) */ /***/ }, -/* 75 */ +/* 78 */ /***/ function(module, exports, __webpack_require__) { /*jshint bitwise:false*/ @@ -20464,12 +20723,12 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, -/* 76 */ +/* 79 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var massageCreateIndexRequest = __webpack_require__(77); + var massageCreateIndexRequest = __webpack_require__(80); function createIndex(db, requestDef, callback) { requestDef = massageCreateIndexRequest(requestDef); @@ -20525,12 +20784,12 @@ return /******/ (function(modules) { // webpackBootstrap exports.deleteIndex = deleteIndex; /***/ }, -/* 77 */ +/* 80 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var utils = __webpack_require__(70); + var utils = __webpack_require__(73); var clone = utils.clone; // we restucture the supplied JSON considerably, because the official @@ -20563,34 +20822,34 @@ return /******/ (function(modules) { // webpackBootstrap }; /***/ }, -/* 78 */ +/* 81 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var utils = __webpack_require__(70); + var utils = __webpack_require__(73); var callbackify = utils.callbackify; - exports.createIndex = callbackify(__webpack_require__(79)); - exports.find = callbackify(__webpack_require__(92)); - exports.getIndexes = callbackify(__webpack_require__(93)); - exports.deleteIndex = callbackify(__webpack_require__(97)); + exports.createIndex = callbackify(__webpack_require__(82)); + exports.find = callbackify(__webpack_require__(95)); + exports.getIndexes = callbackify(__webpack_require__(96)); + exports.deleteIndex = callbackify(__webpack_require__(100)); /***/ }, -/* 79 */ +/* 82 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var utils = __webpack_require__(70); + var utils = __webpack_require__(73); var log = utils.log; - var pouchUpsert = __webpack_require__(80); - var abstractMapper = __webpack_require__(82); - var localUtils = __webpack_require__(83); + var pouchUpsert = __webpack_require__(83); + var abstractMapper = __webpack_require__(85); + var localUtils = __webpack_require__(86); var validateIndex = localUtils.validateIndex; var massageIndexDef = localUtils.massageIndexDef; - var massageCreateIndexRequest = __webpack_require__(77); + var massageCreateIndexRequest = __webpack_require__(80); function upsert(db, docId, diffFun) { return pouchUpsert.upsert.call(db, docId, diffFun); @@ -20669,12 +20928,12 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, -/* 80 */ +/* 83 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var PouchPromise = __webpack_require__(81); + var PouchPromise = __webpack_require__(84); // 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 @@ -20768,14 +21027,14 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, -/* 81 */ +/* 84 */ /***/ 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__(72)); + var lie = _interopDefault(__webpack_require__(75)); /* istanbul ignore next */ var PouchPromise = typeof Promise === 'function' ? Promise : lie; @@ -20783,13 +21042,13 @@ return /******/ (function(modules) { // webpackBootstrap module.exports = PouchPromise; /***/ }, -/* 82 */ +/* 85 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var localUtils = __webpack_require__(83); - var abstractMapReduce = __webpack_require__(86); + var localUtils = __webpack_require__(86); + var abstractMapReduce = __webpack_require__(89); var parseField = localUtils.parseField; // @@ -20920,13 +21179,13 @@ return /******/ (function(modules) { // webpackBootstrap module.exports = abstractMapper; /***/ }, -/* 83 */ +/* 86 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var utils = __webpack_require__(70); - var collate = __webpack_require__(84); + var utils = __webpack_require__(73); + var collate = __webpack_require__(87); function getKey(obj) { return Object.keys(obj)[0]; @@ -21303,7 +21562,7 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, -/* 84 */ +/* 87 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -21312,7 +21571,7 @@ return /******/ (function(modules) { // webpackBootstrap var MAGNITUDE_DIGITS = 3; // ditto var SEP = ''; // set to '_' for easier debugging - var utils = __webpack_require__(85); + var utils = __webpack_require__(88); exports.collate = function (a, b) { @@ -21662,7 +21921,7 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, -/* 85 */ +/* 88 */ /***/ function(module, exports) { 'use strict'; @@ -21737,17 +21996,17 @@ return /******/ (function(modules) { // webpackBootstrap }; /***/ }, -/* 86 */ +/* 89 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {'use strict'; - var pouchCollate = __webpack_require__(84); - var TaskQueue = __webpack_require__(87); + var pouchCollate = __webpack_require__(87); + var TaskQueue = __webpack_require__(90); var collate = pouchCollate.collate; var toIndexableString = pouchCollate.toIndexableString; var normalizeKey = pouchCollate.normalizeKey; - var createView = __webpack_require__(90); + var createView = __webpack_require__(93); var log; /* istanbul ignore else */ if ((typeof console !== 'undefined') && (typeof console.log === 'function')) { @@ -21755,7 +22014,7 @@ return /******/ (function(modules) { // webpackBootstrap } else { log = function () {}; } - var utils = __webpack_require__(88); + var utils = __webpack_require__(91); var Promise = utils.Promise; var persistentQueues = {}; var tempViewQueue = new TaskQueue(); @@ -22440,7 +22699,7 @@ return /******/ (function(modules) { // webpackBootstrap /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(54))) /***/ }, -/* 87 */ +/* 90 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -22448,7 +22707,7 @@ return /******/ (function(modules) { // webpackBootstrap * Simple task queue to sequentialize actions. Assumes callbacks will eventually fire (once). */ - var Promise = __webpack_require__(88).Promise; + var Promise = __webpack_require__(91).Promise; function TaskQueue() { this.promise = new Promise(function (fulfill) {fulfill(); }); @@ -22469,16 +22728,16 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, -/* 88 */ +/* 91 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {'use strict'; /* istanbul ignore if */ - exports.Promise = __webpack_require__(71); + exports.Promise = __webpack_require__(74); - exports.inherits = __webpack_require__(65); - exports.extend = __webpack_require__(73); - var argsarray = __webpack_require__(60); + exports.inherits = __webpack_require__(68); + exports.extend = __webpack_require__(76); + var argsarray = __webpack_require__(63); /* istanbul ignore next */ exports.promisedCallback = function (promise, callback) { @@ -22566,8 +22825,8 @@ return /******/ (function(modules) { // webpackBootstrap return output; }; - var crypto = __webpack_require__(89); - var Md5 = __webpack_require__(75); + var crypto = __webpack_require__(92); + var Md5 = __webpack_require__(78); exports.MD5 = function (string) { /* istanbul ignore else */ @@ -22580,19 +22839,19 @@ return /******/ (function(modules) { // webpackBootstrap /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(54))) /***/ }, -/* 89 */ +/* 92 */ /***/ function(module, exports) { /* (ignored) */ /***/ }, -/* 90 */ +/* 93 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var upsert = __webpack_require__(91); - var utils = __webpack_require__(88); + var upsert = __webpack_require__(94); + var utils = __webpack_require__(91); var Promise = utils.Promise; function stringify(input) { @@ -22689,31 +22948,31 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, -/* 91 */ +/* 94 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var upsert = __webpack_require__(80).upsert; + var upsert = __webpack_require__(83).upsert; module.exports = function (db, doc, diffFun) { return upsert.apply(db, [doc, diffFun]); }; /***/ }, -/* 92 */ +/* 95 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var utils = __webpack_require__(70); + var utils = __webpack_require__(73); var clone = utils.clone; - var getIndexes = __webpack_require__(93); - var collate = __webpack_require__(84).collate; - var abstractMapper = __webpack_require__(82); - var planQuery = __webpack_require__(94); - var localUtils = __webpack_require__(83); - var filterInMemoryFields = __webpack_require__(95); + var getIndexes = __webpack_require__(96); + var collate = __webpack_require__(87).collate; + var abstractMapper = __webpack_require__(85); + var planQuery = __webpack_require__(97); + var localUtils = __webpack_require__(86); + var filterInMemoryFields = __webpack_require__(98); var massageSelector = localUtils.massageSelector; var massageSort = localUtils.massageSort; var getValue = localUtils.getValue; @@ -22850,14 +23109,14 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, -/* 93 */ +/* 96 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var utils = __webpack_require__(70); + var utils = __webpack_require__(73); - var localUtils = __webpack_require__(83); + var localUtils = __webpack_require__(86); var massageIndexDef = localUtils.massageIndexDef; function getIndexes(db) { @@ -22908,14 +23167,14 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, -/* 94 */ +/* 97 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var utils = __webpack_require__(70); + var utils = __webpack_require__(73); var log = utils.log; - var localUtils = __webpack_require__(83); + var localUtils = __webpack_require__(86); var getKey = localUtils.getKey; var getUserFields = localUtils.getUserFields; @@ -23353,7 +23612,7 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, -/* 95 */ +/* 98 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -23365,14 +23624,14 @@ return /******/ (function(modules) { // webpackBootstrap // "bar". // - var isArray = __webpack_require__(96); - var collate = __webpack_require__(84).collate; - var localUtils = __webpack_require__(83); + var isArray = __webpack_require__(99); + var collate = __webpack_require__(87).collate; + var localUtils = __webpack_require__(86); var isCombinationalField = localUtils.isCombinationalField; var getKey = localUtils.getKey; var getValue = localUtils.getValue; var parseField = localUtils.parseField; - var utils = __webpack_require__(70); + var utils = __webpack_require__(73); var getFieldFromDoc = utils.getFieldFromDoc; // create a comparator based on the sort object @@ -23643,7 +23902,7 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, -/* 96 */ +/* 99 */ /***/ function(module, exports) { @@ -23682,13 +23941,13 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, -/* 97 */ +/* 100 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var abstractMapper = __webpack_require__(82); - var upsert = __webpack_require__(91); + var abstractMapper = __webpack_require__(85); + var upsert = __webpack_require__(94); function deleteIndex(db, index) { @@ -23723,7 +23982,7 @@ return /******/ (function(modules) { // webpackBootstrap module.exports = deleteIndex; /***/ }, -/* 98 */ +/* 101 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -23773,7 +24032,7 @@ return /******/ (function(modules) { // webpackBootstrap } /***/ }, -/* 99 */ +/* 102 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; diff --git a/dist/cozy-client.js.map b/dist/cozy-client.js.map index d811dbf3..99c7d571 100644 --- a/dist/cozy-client.js.map +++ b/dist/cozy-client.js.map @@ -1 +1 @@ -{"version":3,"sources":["webpack:///webpack/universalModuleDefinition","webpack:///webpack/bootstrap 7539e0d15f172b2bfa14","webpack:///./~/isomorphic-fetch/fetch-npm-browserify.js","webpack:///./~/whatwg-fetch/fetch.js","webpack:///./src/index.js","webpack:///./~/core-js/modules/es6.object.assign.js","webpack:///./~/core-js/modules/_export.js","webpack:///./~/core-js/modules/_global.js","webpack:///./~/core-js/modules/_core.js","webpack:///./~/core-js/modules/_hide.js","webpack:///./~/core-js/modules/_object-dp.js","webpack:///./~/core-js/modules/_an-object.js","webpack:///./~/core-js/modules/_is-object.js","webpack:///./~/core-js/modules/_ie8-dom-define.js","webpack:///./~/core-js/modules/_descriptors.js","webpack:///./~/core-js/modules/_fails.js","webpack:///./~/core-js/modules/_dom-create.js","webpack:///./~/core-js/modules/_to-primitive.js","webpack:///./~/core-js/modules/_property-desc.js","webpack:///./~/core-js/modules/_redefine.js","webpack:///./~/core-js/modules/_has.js","webpack:///./~/core-js/modules/_uid.js","webpack:///./~/core-js/modules/_ctx.js","webpack:///./~/core-js/modules/_a-function.js","webpack:///./~/core-js/modules/_object-assign.js","webpack:///./~/core-js/modules/_object-keys.js","webpack:///./~/core-js/modules/_object-keys-internal.js","webpack:///./~/core-js/modules/_to-iobject.js","webpack:///./~/core-js/modules/_iobject.js","webpack:///./~/core-js/modules/_cof.js","webpack:///./~/core-js/modules/_defined.js","webpack:///./~/core-js/modules/_array-includes.js","webpack:///./~/core-js/modules/_to-length.js","webpack:///./~/core-js/modules/_to-integer.js","webpack:///./~/core-js/modules/_to-absolute-index.js","webpack:///./~/core-js/modules/_shared-key.js","webpack:///./~/core-js/modules/_shared.js","webpack:///./~/core-js/modules/_enum-bug-keys.js","webpack:///./~/core-js/modules/_object-gops.js","webpack:///./~/core-js/modules/_object-pie.js","webpack:///./~/core-js/modules/_to-object.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:///./~/babel-runtime/regenerator/index.js","webpack:///./~/regenerator-runtime/runtime-module.js","webpack:///./~/regenerator-runtime/runtime.js","webpack:///./~/process/browser.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)?ae2e","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","getRedirectionURL","redirect","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","ensureHasReconnectParam","url","URL","_url","searchParams","has","append","search","indexOf","toString","options","AppTokenV2","LocalStorage","MemoryStorage","_inited","_oauth","_token","_authstate","_authcreds","_storage","_version","version","_offline","token","oauth","Error","storage","_clientParams","Object","assign","clientParams","_onRegistered","onRegistered","nopOnRegistered","cozyURL","length","slice","_invalidTokenErrorHandler","onInvalidTokenError","undefined","handleInvalidTokenError","disablePromises","addToProto","fetchJSON","_fetchJSON","args","concat","Array","prototype","call","arguments","cozyFetchJSON","apply","forceTokenRefresh","state","isV2","then","redirectURI","oauthFlow","Promise","resolve","creds","save","CredsKey","path","pathprefix","fetch","res","ok","json","status","datasystem","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","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","notificationPlatform","notification_platform","notificationDeviceToken","notification_device_token","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","invalidTokenErrorHandler","contentType","get","error","FetchError","isInvalidToken","currentOrigin","requestUrl","redirectURL","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","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","sanitizeFileName","trim","getFileTypeFromName","test","doUpload","ArrayBuffer","isBuffer","isFile","File","isBlob","Blob","isStream","readable","pipe","isString","contentLength","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","service","pickService","baseURL","sanitizedURL","buildRedirectionURL","redirectionURL","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","eventType","source","transition","style","dimensions","prop","removeIntentFrame","parentNode","removeChild","first","arr","filterServices","services","filteredServices","createPromise","start","restData","listenClientData","messageEventListener","maximize","height","intentId","serviceWindow","documentElement","terminated","terminate","resizeClient","transitionProperty","maxHeight","clientHeight","maxWidth","clientWidth","cancel","getData","getIntent","eventName","exposeIntentFrameRemoval","throw","isSerializable","includes","parameterStrings","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;AAC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F;;AAEDM,QAAOC,OAAP,GAAiB,IAAIzK,MAAJ,EAAjB;AACAoH,QAAOC,MAAP,CAAcmD,OAAOC,OAArB,EAA8B,EAACzK,cAAD,EAASoG,wCAAT,EAAuBC,0CAAvB,EAA9B,E;;;;;;ACnUA;AACA;;AAEA,2CAA0C,kCAAsC;;;;;;;ACHhF;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,mFAAkF,uBAAuB;AACzG,kEAAiE;AACjE,gEAA+D;AAC/D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAc;AACd,eAAc;AACd,eAAc;AACd,eAAc;AACd,gBAAe;AACf,gBAAe;AACf,gBAAe;AACf,iBAAgB;AAChB;;;;;;;AC1CA;AACA;AACA;AACA;AACA;AACA,0CAAyC;;;;;;;ACLzC,8BAA6B;AAC7B,wCAAuC;;;;;;;ACDvC;AACA;AACA;AACA;AACA,EAAC;AACD;AACA;AACA;;;;;;;ACPA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG,YAAY;AACf;AACA;AACA;AACA;;;;;;;ACfA;AACA;AACA;AACA;AACA;;;;;;;ACJA;AACA;AACA;;;;;;;ACFA;AACA,sEAAsE,mBAAmB,UAAU,EAAE,EAAE;AACvG,EAAC;;;;;;;ACFD;AACA;AACA,kCAAiC,QAAQ,mBAAmB,UAAU,EAAE,EAAE;AAC1E,EAAC;;;;;;;ACHD;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;;;;;;;ACNA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACXA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACPA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA,IAAG;AACH;AACA,IAAG;AACH;AACA;AACA;AACA,EAAC;AACD;AACA,EAAC;;;;;;;AC9BD,wBAAuB;AACvB;AACA;AACA;;;;;;;ACHA;AACA;AACA;AACA;AACA;;;;;;;ACJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACnBA;AACA;AACA;AACA;;;;;;;ACHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qCAAoC,UAAU,EAAE;AAChD,oBAAmB,sCAAsC;AACzD,EAAC,qCAAqC;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH,EAAC;;;;;;;ACjCD;AACA;AACA;;AAEA;AACA;AACA;;;;;;;ACNA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;AChBA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACLA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACLA,kBAAiB;;AAEjB;AACA;AACA;;;;;;;ACJA;AACA;AACA;AACA;AACA;;;;;;;ACJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK,YAAY,eAAe;AAChC;AACA,MAAK;AACL;AACA;;;;;;;ACtBA;AACA;AACA;AACA;AACA,4DAA2D;AAC3D;;;;;;;ACLA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACLA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACNA;AACA;AACA;AACA;AACA;;;;;;;ACJA;AACA;AACA,mDAAkD;AAClD;AACA,wCAAuC;AACvC;;;;;;;ACLA;AACA;AACA;AACA;;;;;;;ACHA;;;;;;;ACAA,eAA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;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,0DAAyD;AACzD;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,aAAY;AACZ;;AAEA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAW;AACX;AACA,YAAW;AACX;;AAEA;AACA;AACA,yCAAwC,WAAW;AACnD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAS;AACT;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA,UAAS;AACT;;AAEA;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;;AAEA;AACA,4BAA2B;AAC3B;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,UAAS;AACT;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA,UAAS;AACT;AACA;AACA;AACA;;AAEA;;AAEA,UAAS;AACT;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA,UAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,qCAAoC,cAAc;AAClD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,MAAK;AACL;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA,kCAAiC,kBAAkB;AACnD;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA,kBAAiB;;AAEjB;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,yBAAwB,iBAAiB;AACzC;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;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA,aAAY;AACZ;AACA;;AAEA;AACA,aAAY;AACZ;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;;AAEL;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA,MAAK;;AAEL;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA,+CAA8C,QAAQ;AACtD;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,cAAa;AACb;AACA;;AAEA,YAAW;AACX;AACA;AACA;;AAEA,YAAW;AACX;AACA;AACA;;AAEA,YAAW;AACX;AACA;AACA;AACA;AACA,MAAK;;AAEL;AACA,+CAA8C,QAAQ;AACtD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA,MAAK;;AAEL;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA;AACA,QAAO;AACP;AACA;;AAEA;AACA,MAAK;;AAEL;AACA,+CAA8C,QAAQ;AACtD;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;;AAEL;AACA,+CAA8C,QAAQ;AACtD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,MAAK;;AAEL;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACltBA;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;A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;AAEM,UAASrE,0BAAT,CAAqCyH,IAArC,EAA2C;AAChD,OAAM6Y,WAAWnhB,YAAYsI,IAAZ,CAAjB;AACA,OAAMqa,OAAO,SAAPA,IAAO,CAACpa,OAAD;AAAA,YAAa3H,wBAAwB0H,IAAxB,EAA8BC,OAA9B,CAAb;AAAA,IAAb;AACA,UAAOtD,QAAQmK,GAAR,CAAY+R,SAAS5N,GAAT,CAAaoP,IAAb,CAAZ,CAAP;AACD,E;;;;;;ACxPD;;AAEA,gCAA+B,iFAAiF;;AAEhH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;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;;AAEA;AACA;;AAEA;AACA;AACA;AACA,wBAAuB;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,4D;;;;;;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;A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C;AAC9C,OAAI,CAACA,GAAL,EAAU,MAAM,IAAItP,KAAJ,CAAU,sBAAV,CAAN;AACV,UAAO,0BAAcuF,IAAd,EAAoB,KAApB,EAA2Bob,mBAAmBrR,GAAnB,CAA3B,EACJvN,IADI,CACC,UAAC3J,KAAD;AAAA,YAAWA,MAAMoY,GAAN,CAAU,UAACyH,IAAD;AAAA,cAAUA,KAAKlI,GAAf;AAAA,MAAV,CAAX;AAAA,IADD,CAAP;AAED;;AAEM,UAAS1V,oBAAT,CAA+BkL,IAA/B,EAAqC+J,GAArC,EAA0CrQ,OAA1C,EAAmD;AACxD,OAAI,CAACqQ,GAAL,EAAU,MAAM,IAAItP,KAAJ,CAAU,sBAAV,CAAN;AACV,OAAM4gB,SAASzgB,OAAO+Q,IAAP,CAAYjS,OAAZ,EAAqBuR,GAArB,CAAyB;AAAA,uBAAgBzJ,GAAhB,UAAwB9H,QAAQ8H,GAAR,CAAxB;AAAA,IAAzB,EAAiE2E,IAAjE,CAAsE,EAAtE,CAAf;AACA;AACA,UAAO,6BAAiBnG,IAAjB,EAAuB,KAAvB,EAAiCob,mBAAmBrR,GAAnB,CAAjC,oCAAuFsR,MAAvF,CAAP;AACD;;AAED,UAASD,kBAAT,CAA6BrR,GAA7B,EAAkC;AAChC,OAAMC,OAAO5J,mBAAmB2J,IAAIU,KAAvB,CAAb;AACA,OAAMvK,KAAKE,mBAAmB2J,IAAIS,GAAvB,CAAX;AACA,qBAAgBR,IAAhB,SAAwB9J,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 7539e0d15f172b2bfa14","// 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 */\nimport 'core-js/modules/es6.object.assign'\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 getRedirectionURL: intents.getRedirectionURL,\n redirect: intents.redirect\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\nconst ensureHasReconnectParam = _url => {\n const url = new URL(_url)\n if (url.searchParams && !url.searchParams.has('reconnect')) {\n url.searchParams.append('reconnect', 1)\n } else if (!url.search || url.search.indexOf('reconnect') === -1) {\n // Some old navigators do not have the searchParams API\n // and it is not polyfilled by babel-polyfill\n url.search = url.search + '&reconnect=1'\n }\n return url.toString()\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 this._invalidTokenErrorHandler = options.onInvalidTokenError !== undefined ? options.onInvalidTokenError : cozyFetch.handleInvalidTokenError\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 this._clientParams.redirectURI = ensureHasReconnectParam(this._clientParams.redirectURI)\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","// 19.1.3.1 Object.assign(target, source)\nvar $export = require('./_export');\n\n$export($export.S + $export.F, 'Object', { assign: require('./_object-assign') });\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/core-js/modules/es6.object.assign.js\n// module id = 4\n// module chunks = 0","var global = require('./_global');\nvar core = require('./_core');\nvar hide = require('./_hide');\nvar redefine = require('./_redefine');\nvar ctx = require('./_ctx');\nvar PROTOTYPE = 'prototype';\n\nvar $export = function (type, name, source) {\n var IS_FORCED = type & $export.F;\n var IS_GLOBAL = type & $export.G;\n var IS_STATIC = type & $export.S;\n var IS_PROTO = type & $export.P;\n var IS_BIND = type & $export.B;\n var target = IS_GLOBAL ? global : IS_STATIC ? global[name] || (global[name] = {}) : (global[name] || {})[PROTOTYPE];\n var exports = IS_GLOBAL ? core : core[name] || (core[name] = {});\n var expProto = exports[PROTOTYPE] || (exports[PROTOTYPE] = {});\n var key, own, out, exp;\n if (IS_GLOBAL) source = name;\n for (key in source) {\n // contains in native\n own = !IS_FORCED && target && target[key] !== undefined;\n // export native or passed\n out = (own ? target : source)[key];\n // bind timers to global for call from export context\n exp = IS_BIND && own ? ctx(out, global) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;\n // extend global\n if (target) redefine(target, key, out, type & $export.U);\n // export\n if (exports[key] != out) hide(exports, key, exp);\n if (IS_PROTO && expProto[key] != out) expProto[key] = out;\n }\n};\nglobal.core = core;\n// type bitmap\n$export.F = 1; // forced\n$export.G = 2; // global\n$export.S = 4; // static\n$export.P = 8; // proto\n$export.B = 16; // bind\n$export.W = 32; // wrap\n$export.U = 64; // safe\n$export.R = 128; // real proto method for `library`\nmodule.exports = $export;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/core-js/modules/_export.js\n// module id = 5\n// module chunks = 0","// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028\nvar global = module.exports = typeof window != 'undefined' && window.Math == Math\n ? window : typeof self != 'undefined' && self.Math == Math ? self\n // eslint-disable-next-line no-new-func\n : Function('return this')();\nif (typeof __g == 'number') __g = global; // eslint-disable-line no-undef\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/core-js/modules/_global.js\n// module id = 6\n// module chunks = 0","var core = module.exports = { version: '2.5.3' };\nif (typeof __e == 'number') __e = core; // eslint-disable-line no-undef\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/core-js/modules/_core.js\n// module id = 7\n// module chunks = 0","var dP = require('./_object-dp');\nvar createDesc = require('./_property-desc');\nmodule.exports = require('./_descriptors') ? function (object, key, value) {\n return dP.f(object, key, createDesc(1, value));\n} : function (object, key, value) {\n object[key] = value;\n return object;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/core-js/modules/_hide.js\n// module id = 8\n// module chunks = 0","var anObject = require('./_an-object');\nvar IE8_DOM_DEFINE = require('./_ie8-dom-define');\nvar toPrimitive = require('./_to-primitive');\nvar dP = Object.defineProperty;\n\nexports.f = require('./_descriptors') ? Object.defineProperty : function defineProperty(O, P, Attributes) {\n anObject(O);\n P = toPrimitive(P, true);\n anObject(Attributes);\n if (IE8_DOM_DEFINE) try {\n return dP(O, P, Attributes);\n } catch (e) { /* empty */ }\n if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!');\n if ('value' in Attributes) O[P] = Attributes.value;\n return O;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/core-js/modules/_object-dp.js\n// module id = 9\n// module chunks = 0","var isObject = require('./_is-object');\nmodule.exports = function (it) {\n if (!isObject(it)) throw TypeError(it + ' is not an object!');\n return it;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/core-js/modules/_an-object.js\n// module id = 10\n// module chunks = 0","module.exports = function (it) {\n return typeof it === 'object' ? it !== null : typeof it === 'function';\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/core-js/modules/_is-object.js\n// module id = 11\n// module chunks = 0","module.exports = !require('./_descriptors') && !require('./_fails')(function () {\n return Object.defineProperty(require('./_dom-create')('div'), 'a', { get: function () { return 7; } }).a != 7;\n});\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/core-js/modules/_ie8-dom-define.js\n// module id = 12\n// module chunks = 0","// Thank's IE8 for his funny defineProperty\nmodule.exports = !require('./_fails')(function () {\n return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7;\n});\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/core-js/modules/_descriptors.js\n// module id = 13\n// module chunks = 0","module.exports = function (exec) {\n try {\n return !!exec();\n } catch (e) {\n return true;\n }\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/core-js/modules/_fails.js\n// module id = 14\n// module chunks = 0","var isObject = require('./_is-object');\nvar document = require('./_global').document;\n// typeof document.createElement is 'object' in old IE\nvar is = isObject(document) && isObject(document.createElement);\nmodule.exports = function (it) {\n return is ? document.createElement(it) : {};\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/core-js/modules/_dom-create.js\n// module id = 15\n// module chunks = 0","// 7.1.1 ToPrimitive(input [, PreferredType])\nvar isObject = require('./_is-object');\n// instead of the ES6 spec version, we didn't implement @@toPrimitive case\n// and the second argument - flag - preferred type is a string\nmodule.exports = function (it, S) {\n if (!isObject(it)) return it;\n var fn, val;\n if (S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val;\n if (typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it))) return val;\n if (!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val;\n throw TypeError(\"Can't convert object to primitive value\");\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/core-js/modules/_to-primitive.js\n// module id = 16\n// module chunks = 0","module.exports = function (bitmap, value) {\n return {\n enumerable: !(bitmap & 1),\n configurable: !(bitmap & 2),\n writable: !(bitmap & 4),\n value: value\n };\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/core-js/modules/_property-desc.js\n// module id = 17\n// module chunks = 0","var global = require('./_global');\nvar hide = require('./_hide');\nvar has = require('./_has');\nvar SRC = require('./_uid')('src');\nvar TO_STRING = 'toString';\nvar $toString = Function[TO_STRING];\nvar TPL = ('' + $toString).split(TO_STRING);\n\nrequire('./_core').inspectSource = function (it) {\n return $toString.call(it);\n};\n\n(module.exports = function (O, key, val, safe) {\n var isFunction = typeof val == 'function';\n if (isFunction) has(val, 'name') || hide(val, 'name', key);\n if (O[key] === val) return;\n if (isFunction) has(val, SRC) || hide(val, SRC, O[key] ? '' + O[key] : TPL.join(String(key)));\n if (O === global) {\n O[key] = val;\n } else if (!safe) {\n delete O[key];\n hide(O, key, val);\n } else if (O[key]) {\n O[key] = val;\n } else {\n hide(O, key, val);\n }\n// add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative\n})(Function.prototype, TO_STRING, function toString() {\n return typeof this == 'function' && this[SRC] || $toString.call(this);\n});\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/core-js/modules/_redefine.js\n// module id = 18\n// module chunks = 0","var hasOwnProperty = {}.hasOwnProperty;\nmodule.exports = function (it, key) {\n return hasOwnProperty.call(it, key);\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/core-js/modules/_has.js\n// module id = 19\n// module chunks = 0","var id = 0;\nvar px = Math.random();\nmodule.exports = function (key) {\n return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36));\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/core-js/modules/_uid.js\n// module id = 20\n// module chunks = 0","// optional / simple context binding\nvar aFunction = require('./_a-function');\nmodule.exports = function (fn, that, length) {\n aFunction(fn);\n if (that === undefined) return fn;\n switch (length) {\n case 1: return function (a) {\n return fn.call(that, a);\n };\n case 2: return function (a, b) {\n return fn.call(that, a, b);\n };\n case 3: return function (a, b, c) {\n return fn.call(that, a, b, c);\n };\n }\n return function (/* ...args */) {\n return fn.apply(that, arguments);\n };\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/core-js/modules/_ctx.js\n// module id = 21\n// module chunks = 0","module.exports = function (it) {\n if (typeof it != 'function') throw TypeError(it + ' is not a function!');\n return it;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/core-js/modules/_a-function.js\n// module id = 22\n// module chunks = 0","'use strict';\n// 19.1.2.1 Object.assign(target, source, ...)\nvar getKeys = require('./_object-keys');\nvar gOPS = require('./_object-gops');\nvar pIE = require('./_object-pie');\nvar toObject = require('./_to-object');\nvar IObject = require('./_iobject');\nvar $assign = Object.assign;\n\n// should work with symbols and should have deterministic property order (V8 bug)\nmodule.exports = !$assign || require('./_fails')(function () {\n var A = {};\n var B = {};\n // eslint-disable-next-line no-undef\n var S = Symbol();\n var K = 'abcdefghijklmnopqrst';\n A[S] = 7;\n K.split('').forEach(function (k) { B[k] = k; });\n return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K;\n}) ? function assign(target, source) { // eslint-disable-line no-unused-vars\n var T = toObject(target);\n var aLen = arguments.length;\n var index = 1;\n var getSymbols = gOPS.f;\n var isEnum = pIE.f;\n while (aLen > index) {\n var S = IObject(arguments[index++]);\n var keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S);\n var length = keys.length;\n var j = 0;\n var key;\n while (length > j) if (isEnum.call(S, key = keys[j++])) T[key] = S[key];\n } return T;\n} : $assign;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/core-js/modules/_object-assign.js\n// module id = 23\n// module chunks = 0","// 19.1.2.14 / 15.2.3.14 Object.keys(O)\nvar $keys = require('./_object-keys-internal');\nvar enumBugKeys = require('./_enum-bug-keys');\n\nmodule.exports = Object.keys || function keys(O) {\n return $keys(O, enumBugKeys);\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/core-js/modules/_object-keys.js\n// module id = 24\n// module chunks = 0","var has = require('./_has');\nvar toIObject = require('./_to-iobject');\nvar arrayIndexOf = require('./_array-includes')(false);\nvar IE_PROTO = require('./_shared-key')('IE_PROTO');\n\nmodule.exports = function (object, names) {\n var O = toIObject(object);\n var i = 0;\n var result = [];\n var key;\n for (key in O) if (key != IE_PROTO) has(O, key) && result.push(key);\n // Don't enum bug & hidden keys\n while (names.length > i) if (has(O, key = names[i++])) {\n ~arrayIndexOf(result, key) || result.push(key);\n }\n return result;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/core-js/modules/_object-keys-internal.js\n// module id = 25\n// module chunks = 0","// to indexed object, toObject with fallback for non-array-like ES3 strings\nvar IObject = require('./_iobject');\nvar defined = require('./_defined');\nmodule.exports = function (it) {\n return IObject(defined(it));\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/core-js/modules/_to-iobject.js\n// module id = 26\n// module chunks = 0","// fallback for non-array-like ES3 and non-enumerable old V8 strings\nvar cof = require('./_cof');\n// eslint-disable-next-line no-prototype-builtins\nmodule.exports = Object('z').propertyIsEnumerable(0) ? Object : function (it) {\n return cof(it) == 'String' ? it.split('') : Object(it);\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/core-js/modules/_iobject.js\n// module id = 27\n// module chunks = 0","var toString = {}.toString;\n\nmodule.exports = function (it) {\n return toString.call(it).slice(8, -1);\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/core-js/modules/_cof.js\n// module id = 28\n// module chunks = 0","// 7.2.1 RequireObjectCoercible(argument)\nmodule.exports = function (it) {\n if (it == undefined) throw TypeError(\"Can't call method on \" + it);\n return it;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/core-js/modules/_defined.js\n// module id = 29\n// module chunks = 0","// false -> Array#indexOf\n// true -> Array#includes\nvar toIObject = require('./_to-iobject');\nvar toLength = require('./_to-length');\nvar toAbsoluteIndex = require('./_to-absolute-index');\nmodule.exports = function (IS_INCLUDES) {\n return function ($this, el, fromIndex) {\n var O = toIObject($this);\n var length = toLength(O.length);\n var index = toAbsoluteIndex(fromIndex, length);\n var value;\n // Array#includes uses SameValueZero equality algorithm\n // eslint-disable-next-line no-self-compare\n if (IS_INCLUDES && el != el) while (length > index) {\n value = O[index++];\n // eslint-disable-next-line no-self-compare\n if (value != value) return true;\n // Array#indexOf ignores holes, Array#includes - not\n } else for (;length > index; index++) if (IS_INCLUDES || index in O) {\n if (O[index] === el) return IS_INCLUDES || index || 0;\n } return !IS_INCLUDES && -1;\n };\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/core-js/modules/_array-includes.js\n// module id = 30\n// module chunks = 0","// 7.1.15 ToLength\nvar toInteger = require('./_to-integer');\nvar min = Math.min;\nmodule.exports = function (it) {\n return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/core-js/modules/_to-length.js\n// module id = 31\n// module chunks = 0","// 7.1.4 ToInteger\nvar ceil = Math.ceil;\nvar floor = Math.floor;\nmodule.exports = function (it) {\n return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it);\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/core-js/modules/_to-integer.js\n// module id = 32\n// module chunks = 0","var toInteger = require('./_to-integer');\nvar max = Math.max;\nvar min = Math.min;\nmodule.exports = function (index, length) {\n index = toInteger(index);\n return index < 0 ? max(index + length, 0) : min(index, length);\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/core-js/modules/_to-absolute-index.js\n// module id = 33\n// module chunks = 0","var shared = require('./_shared')('keys');\nvar uid = require('./_uid');\nmodule.exports = function (key) {\n return shared[key] || (shared[key] = uid(key));\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/core-js/modules/_shared-key.js\n// module id = 34\n// module chunks = 0","var global = require('./_global');\nvar SHARED = '__core-js_shared__';\nvar store = global[SHARED] || (global[SHARED] = {});\nmodule.exports = function (key) {\n return store[key] || (store[key] = {});\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/core-js/modules/_shared.js\n// module id = 35\n// module chunks = 0","// IE 8- don't enum bug keys\nmodule.exports = (\n 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf'\n).split(',');\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/core-js/modules/_enum-bug-keys.js\n// module id = 36\n// module chunks = 0","exports.f = Object.getOwnPropertySymbols;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/core-js/modules/_object-gops.js\n// module id = 37\n// module chunks = 0","exports.f = {}.propertyIsEnumerable;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/core-js/modules/_object-pie.js\n// module id = 38\n// module chunks = 0","// 7.1.13 ToObject(argument)\nvar defined = require('./_defined');\nmodule.exports = function (it) {\n return Object(defined(it));\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/core-js/modules/_to-object.js\n// module id = 39\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 this.notificationPlatform = opts.notificationPlatform || opts.notification_platform || ''\n this.notificationDeviceToken = opts.notificationDeviceToken || opts.notification_device_token || ''\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 notification_platform: this.notificationPlatform,\n notification_device_token: this.notificationDeviceToken\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, encodeQuery} 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(res => handleResponse(res, cozy._invalidTokenErrorHandler))\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, invalidTokenErrorHandler) {\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 const error = new FetchError(res, err)\n if (FetchError.isInvalidToken(error) && invalidTokenErrorHandler) {\n invalidTokenErrorHandler(error)\n }\n throw error\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 function handleInvalidTokenError (error) {\n try {\n const currentOrigin = window.location.origin\n const requestUrl = error.url\n\n if (requestUrl.indexOf(currentOrigin.replace(/^(https?:\\/\\/\\w+)-\\w+\\./, '$1.')) === 0) {\n const redirectURL = `${currentOrigin}?${encodeQuery({ 'disconnect': 1 })}`\n window.location = redirectURL\n }\n } catch (e) {\n console.warn('Unable to handle invalid token error', e, error)\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\nFetchError.isInvalidToken = function (err) {\n // XXX We can't use err instanceof FetchError because of the caveats of babel\n return err.name === 'FetchError' && err.status === 400 && err.reason && (err.reason.error === 'Invalid JWT token' || err.reason.error === 'Expired token')\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 sanitizeFileName (name) {\n return name && name.trim()\n}\n\nfunction getFileTypeFromName (name) {\n if (/\\.heic$/i.test(name)) return 'image/heic'\n else if (/\\.heif$/i.test(name)) return 'image/heif'\n else return null\n}\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, contentLength, checksum, lastModifiedDate, ifMatch} = options || {}\n if (!contentType) {\n if (isBuffer) {\n contentType = contentTypeOctetStream\n } else if (isFile) {\n contentType = data.type || getFileTypeFromName(data.name.toLowerCase()) || 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 const headers = {\n 'Content-Type': contentType\n }\n if (contentLength) headers['Content-Length'] = String(contentLength)\n if (checksum) headers['Content-MD5'] = checksum\n if (lastModifiedDate) headers['Date'] = lastModifiedDate.toGMTString()\n if (ifMatch) headers['If-Match'] = ifMatch\n\n return cozyFetch(cozy, path, {\n method: method,\n headers: headers,\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 name = sanitizeFileName(name)\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 name = sanitizeFileName(name)\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 name = sanitizeFileName(name)\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, offline) {\n const parts = path.split('/').filter(part => part !== '')\n\n const rootDirectoryPromise = cozy.files.statById(ROOT_DIR_ID, offline)\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 = {\n data: {\n attributes: Object.assign(\n {},\n attrs,\n { name: sanitizeFileName(attrs.name) }\n )\n }\n }\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) return Promise.reject(new Error('Cannot retrieve document object from given element'))\n\n const window = document.defaultView\n if (!window) return Promise.reject(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 const eventType = event.data.type\n if (eventType === '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 (eventType === `intent-${intent._id}:ready`) {\n handshaken = true\n return event.source.postMessage(data, event.origin)\n }\n\n if (handshaken && eventType === `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 && eventType === `intent-${intent._id}:exposeFrameRemoval`) {\n return resolve({removeIntentFrame, doc: event.data.document})\n }\n\n removeIntentFrame()\n\n if (eventType === `intent-${intent._id}:error`) {\n return reject(errorSerializer.deserialize(event.data.error))\n }\n\n if (handshaken && eventType === `intent-${intent._id}:cancel`) {\n return resolve(null)\n }\n\n if (handshaken && eventType === `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\nconst first = arr => arr && arr[0]\n// In a far future, the user will have to pick the desired service from a list.\n// For now it's our job, an easy job as we arbitrary pick the first service of\n// the list.\nfunction pickService (intent, filterServices) {\n const services = intent.attributes.services\n const filteredServices = filterServices\n ? (services || []).filter(filterServices)\n : services\n return first(filteredServices)\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 const service = pickService(intent, data.filterServices)\n const restData = Object.assign({}, data)\n delete restData.filterServices\n\n if (!service) {\n return Promise.reject(new Error('Unable to find a service'))\n }\n\n return injectService(service.href, element, intent, restData, 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// maximize the height of an element\nfunction maximize (element) {\n if (element && element.style) {\n element.style.height = '100%'\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 || !serviceWindow.document) {\n return Promise.reject(new Error('Intent service should be used in browser'))\n }\n\n // Maximize document, the whole iframe is handled by intents, clients and\n // services\n serviceWindow.addEventListener('load', () => {\n const { document } = serviceWindow\n ;[document.documentElement, document.body].forEach(maximize)\n })\n\n intentId = intentId || serviceWindow.location.search.split('=')[1]\n if (!intentId) return Promise.reject(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 const eventName = (data && data.exposeIntentFrameRemoval\n ? 'exposeFrameRemoval' : 'done'\n )\n return terminate({\n type: `intent-${intent._id}:${eventName}`,\n document: doc\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// Redirect to an app able to handle the doctype\n// Redirections are more or less a hack of the intent API to retrieve an URL for\n// accessing a given doctype or a given document.\n// It needs to use a special action `REDIRECT`\nexport async function getRedirectionURL (cozy, type, data) {\n if (!type && !data) throw new Error(`Cannot retrieve redirection, at least type or doc must be provided`)\n\n const intent = await create(cozy, 'REDIRECT', type, data)\n\n const service = pickService(intent)\n if (!service) throw new Error('Unable to find a service')\n\n // Intents cannot be deleted now\n // await deleteIntent(cozy, intent)\n\n // ignore query string and intent id\n const baseURL = service.href.split('?')[0]\n // FIXME: Handle the fact that the stack encode the '#' character in the URL\n const sanitizedURL = baseURL.replace('%23', '#')\n return data ? buildRedirectionURL(sanitizedURL, data) : sanitizedURL\n}\n\nfunction isSerializable (value) {\n return !['object', 'function'].includes(typeof value)\n}\n\nfunction buildRedirectionURL (url, data) {\n const parameterStrings = Object.keys(data)\n .filter(key => isSerializable(data[key]))\n .map(key => `${key}=${data[key]}`)\n\n return parameterStrings.length ? `${url}?${parameterStrings.join('&')}` : url\n}\n\nexport async function redirect (cozy, type, doc) {\n if (!window) throw new Error('redirect() method can only be called in a browser')\n const redirectionURL = await getRedirectionURL(cozy, type, doc)\n window.location.href = redirectionURL\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/intents.js","module.exports = require(\"regenerator-runtime\");\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/babel-runtime/regenerator/index.js\n// module id = 51\n// module chunks = 0","// This method of obtaining a reference to the global object needs to be\n// kept identical to the way it is obtained in runtime.js\nvar g =\n typeof global === \"object\" ? global :\n typeof window === \"object\" ? window :\n typeof self === \"object\" ? self : this;\n\n// Use `getOwnPropertyNames` because not all browsers support calling\n// `hasOwnProperty` on the global `self` object in a worker. See #183.\nvar hadRuntime = g.regeneratorRuntime &&\n Object.getOwnPropertyNames(g).indexOf(\"regeneratorRuntime\") >= 0;\n\n// Save the old regeneratorRuntime in case it needs to be restored later.\nvar oldRuntime = hadRuntime && g.regeneratorRuntime;\n\n// Force reevalutation of runtime.js.\ng.regeneratorRuntime = undefined;\n\nmodule.exports = require(\"./runtime\");\n\nif (hadRuntime) {\n // Restore the original runtime.\n g.regeneratorRuntime = oldRuntime;\n} else {\n // Remove the global property added by runtime.js.\n try {\n delete g.regeneratorRuntime;\n } catch(e) {\n g.regeneratorRuntime = undefined;\n }\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/regenerator-runtime/runtime-module.js\n// module id = 52\n// module chunks = 0","/**\n * Copyright (c) 2014, Facebook, Inc.\n * All rights reserved.\n *\n * This source code is licensed under the BSD-style license found in the\n * https://raw.github.com/facebook/regenerator/master/LICENSE file. An\n * additional grant of patent rights can be found in the PATENTS file in\n * the same directory.\n */\n\n!(function(global) {\n \"use strict\";\n\n var Op = Object.prototype;\n var hasOwn = Op.hasOwnProperty;\n var undefined; // More compressible than void 0.\n var $Symbol = typeof Symbol === \"function\" ? Symbol : {};\n var iteratorSymbol = $Symbol.iterator || \"@@iterator\";\n var toStringTagSymbol = $Symbol.toStringTag || \"@@toStringTag\";\n\n var inModule = typeof module === \"object\";\n var runtime = global.regeneratorRuntime;\n if (runtime) {\n if (inModule) {\n // If regeneratorRuntime is defined globally and we're in a module,\n // make the exports object identical to regeneratorRuntime.\n module.exports = runtime;\n }\n // Don't bother evaluating the rest of this file if the runtime was\n // already defined globally.\n return;\n }\n\n // Define the runtime globally (as expected by generated code) as either\n // module.exports (if we're in a module) or a new, empty object.\n runtime = global.regeneratorRuntime = inModule ? module.exports : {};\n\n function wrap(innerFn, outerFn, self, tryLocsList) {\n // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.\n var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;\n var generator = Object.create(protoGenerator.prototype);\n var context = new Context(tryLocsList || []);\n\n // The ._invoke method unifies the implementations of the .next,\n // .throw, and .return methods.\n generator._invoke = makeInvokeMethod(innerFn, self, context);\n\n return generator;\n }\n runtime.wrap = wrap;\n\n // Try/catch helper to minimize deoptimizations. Returns a completion\n // record like context.tryEntries[i].completion. This interface could\n // have been (and was previously) designed to take a closure to be\n // invoked without arguments, but in all the cases we care about we\n // already have an existing method we want to call, so there's no need\n // to create a new function object. We can even get away with assuming\n // the method takes exactly one argument, since that happens to be true\n // in every case, so we don't have to touch the arguments object. The\n // only additional allocation required is the completion record, which\n // has a stable shape and so hopefully should be cheap to allocate.\n function tryCatch(fn, obj, arg) {\n try {\n return { type: \"normal\", arg: fn.call(obj, arg) };\n } catch (err) {\n return { type: \"throw\", arg: err };\n }\n }\n\n var GenStateSuspendedStart = \"suspendedStart\";\n var GenStateSuspendedYield = \"suspendedYield\";\n var GenStateExecuting = \"executing\";\n var GenStateCompleted = \"completed\";\n\n // Returning this object from the innerFn has the same effect as\n // breaking out of the dispatch switch statement.\n var ContinueSentinel = {};\n\n // Dummy constructor functions that we use as the .constructor and\n // .constructor.prototype properties for functions that return Generator\n // objects. For full spec compliance, you may wish to configure your\n // minifier not to mangle the names of these two functions.\n function Generator() {}\n function GeneratorFunction() {}\n function GeneratorFunctionPrototype() {}\n\n // This is a polyfill for %IteratorPrototype% for environments that\n // don't natively support it.\n var IteratorPrototype = {};\n IteratorPrototype[iteratorSymbol] = function () {\n return this;\n };\n\n var getProto = Object.getPrototypeOf;\n var NativeIteratorPrototype = getProto && getProto(getProto(values([])));\n if (NativeIteratorPrototype &&\n NativeIteratorPrototype !== Op &&\n hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {\n // This environment has a native %IteratorPrototype%; use it instead\n // of the polyfill.\n IteratorPrototype = NativeIteratorPrototype;\n }\n\n var Gp = GeneratorFunctionPrototype.prototype =\n Generator.prototype = Object.create(IteratorPrototype);\n GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;\n GeneratorFunctionPrototype.constructor = GeneratorFunction;\n GeneratorFunctionPrototype[toStringTagSymbol] =\n GeneratorFunction.displayName = \"GeneratorFunction\";\n\n // Helper for defining the .next, .throw, and .return methods of the\n // Iterator interface in terms of a single ._invoke method.\n function defineIteratorMethods(prototype) {\n [\"next\", \"throw\", \"return\"].forEach(function(method) {\n prototype[method] = function(arg) {\n return this._invoke(method, arg);\n };\n });\n }\n\n runtime.isGeneratorFunction = function(genFun) {\n var ctor = typeof genFun === \"function\" && genFun.constructor;\n return ctor\n ? ctor === GeneratorFunction ||\n // For the native GeneratorFunction constructor, the best we can\n // do is to check its .name property.\n (ctor.displayName || ctor.name) === \"GeneratorFunction\"\n : false;\n };\n\n runtime.mark = function(genFun) {\n if (Object.setPrototypeOf) {\n Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);\n } else {\n genFun.__proto__ = GeneratorFunctionPrototype;\n if (!(toStringTagSymbol in genFun)) {\n genFun[toStringTagSymbol] = \"GeneratorFunction\";\n }\n }\n genFun.prototype = Object.create(Gp);\n return genFun;\n };\n\n // Within the body of any async function, `await x` is transformed to\n // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test\n // `hasOwn.call(value, \"__await\")` to determine if the yielded value is\n // meant to be awaited.\n runtime.awrap = function(arg) {\n return { __await: arg };\n };\n\n function AsyncIterator(generator) {\n function invoke(method, arg, resolve, reject) {\n var record = tryCatch(generator[method], generator, arg);\n if (record.type === \"throw\") {\n reject(record.arg);\n } else {\n var result = record.arg;\n var value = result.value;\n if (value &&\n typeof value === \"object\" &&\n hasOwn.call(value, \"__await\")) {\n return Promise.resolve(value.__await).then(function(value) {\n invoke(\"next\", value, resolve, reject);\n }, function(err) {\n invoke(\"throw\", err, resolve, reject);\n });\n }\n\n return Promise.resolve(value).then(function(unwrapped) {\n // When a yielded Promise is resolved, its final value becomes\n // the .value of the Promise<{value,done}> result for the\n // current iteration. If the Promise is rejected, however, the\n // result for this iteration will be rejected with the same\n // reason. Note that rejections of yielded Promises are not\n // thrown back into the generator function, as is the case\n // when an awaited Promise is rejected. This difference in\n // behavior between yield and await is important, because it\n // allows the consumer to decide what to do with the yielded\n // rejection (swallow it and continue, manually .throw it back\n // into the generator, abandon iteration, whatever). With\n // await, by contrast, there is no opportunity to examine the\n // rejection reason outside the generator function, so the\n // only option is to throw it from the await expression, and\n // let the generator function handle the exception.\n result.value = unwrapped;\n resolve(result);\n }, reject);\n }\n }\n\n if (typeof process === \"object\" && process.domain) {\n invoke = process.domain.bind(invoke);\n }\n\n var previousPromise;\n\n function enqueue(method, arg) {\n function callInvokeWithMethodAndArg() {\n return new Promise(function(resolve, reject) {\n invoke(method, arg, resolve, reject);\n });\n }\n\n return previousPromise =\n // If enqueue has been called before, then we want to wait until\n // all previous Promises have been resolved before calling invoke,\n // so that results are always delivered in the correct order. If\n // enqueue has not been called before, then it is important to\n // call invoke immediately, without waiting on a callback to fire,\n // so that the async generator function has the opportunity to do\n // any necessary setup in a predictable way. This predictability\n // is why the Promise constructor synchronously invokes its\n // executor callback, and why async functions synchronously\n // execute code before the first await. Since we implement simple\n // async functions in terms of async generators, it is especially\n // important to get this right, even though it requires care.\n previousPromise ? previousPromise.then(\n callInvokeWithMethodAndArg,\n // Avoid propagating failures to Promises returned by later\n // invocations of the iterator.\n callInvokeWithMethodAndArg\n ) : callInvokeWithMethodAndArg();\n }\n\n // Define the unified helper method that is used to implement .next,\n // .throw, and .return (see defineIteratorMethods).\n this._invoke = enqueue;\n }\n\n defineIteratorMethods(AsyncIterator.prototype);\n runtime.AsyncIterator = AsyncIterator;\n\n // Note that simple async functions are implemented on top of\n // AsyncIterator objects; they just return a Promise for the value of\n // the final result produced by the iterator.\n runtime.async = function(innerFn, outerFn, self, tryLocsList) {\n var iter = new AsyncIterator(\n wrap(innerFn, outerFn, self, tryLocsList)\n );\n\n return runtime.isGeneratorFunction(outerFn)\n ? iter // If outerFn is a generator, return the full iterator.\n : iter.next().then(function(result) {\n return result.done ? result.value : iter.next();\n });\n };\n\n function makeInvokeMethod(innerFn, self, context) {\n var state = GenStateSuspendedStart;\n\n return function invoke(method, arg) {\n if (state === GenStateExecuting) {\n throw new Error(\"Generator is already running\");\n }\n\n if (state === GenStateCompleted) {\n if (method === \"throw\") {\n throw arg;\n }\n\n // Be forgiving, per 25.3.3.3.3 of the spec:\n // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume\n return doneResult();\n }\n\n context.method = method;\n context.arg = arg;\n\n while (true) {\n var delegate = context.delegate;\n if (delegate) {\n var delegateResult = maybeInvokeDelegate(delegate, context);\n if (delegateResult) {\n if (delegateResult === ContinueSentinel) continue;\n return delegateResult;\n }\n }\n\n if (context.method === \"next\") {\n // Setting context._sent for legacy support of Babel's\n // function.sent implementation.\n context.sent = context._sent = context.arg;\n\n } else if (context.method === \"throw\") {\n if (state === GenStateSuspendedStart) {\n state = GenStateCompleted;\n throw context.arg;\n }\n\n context.dispatchException(context.arg);\n\n } else if (context.method === \"return\") {\n context.abrupt(\"return\", context.arg);\n }\n\n state = GenStateExecuting;\n\n var record = tryCatch(innerFn, self, context);\n if (record.type === \"normal\") {\n // If an exception is thrown from innerFn, we leave state ===\n // GenStateExecuting and loop back for another invocation.\n state = context.done\n ? GenStateCompleted\n : GenStateSuspendedYield;\n\n if (record.arg === ContinueSentinel) {\n continue;\n }\n\n return {\n value: record.arg,\n done: context.done\n };\n\n } else if (record.type === \"throw\") {\n state = GenStateCompleted;\n // Dispatch the exception by looping back around to the\n // context.dispatchException(context.arg) call above.\n context.method = \"throw\";\n context.arg = record.arg;\n }\n }\n };\n }\n\n // Call delegate.iterator[context.method](context.arg) and handle the\n // result, either by returning a { value, done } result from the\n // delegate iterator, or by modifying context.method and context.arg,\n // setting context.delegate to null, and returning the ContinueSentinel.\n function maybeInvokeDelegate(delegate, context) {\n var method = delegate.iterator[context.method];\n if (method === undefined) {\n // A .throw or .return when the delegate iterator has no .throw\n // method always terminates the yield* loop.\n context.delegate = null;\n\n if (context.method === \"throw\") {\n if (delegate.iterator.return) {\n // If the delegate iterator has a return method, give it a\n // chance to clean up.\n context.method = \"return\";\n context.arg = undefined;\n maybeInvokeDelegate(delegate, context);\n\n if (context.method === \"throw\") {\n // If maybeInvokeDelegate(context) changed context.method from\n // \"return\" to \"throw\", let that override the TypeError below.\n return ContinueSentinel;\n }\n }\n\n context.method = \"throw\";\n context.arg = new TypeError(\n \"The iterator does not provide a 'throw' method\");\n }\n\n return ContinueSentinel;\n }\n\n var record = tryCatch(method, delegate.iterator, context.arg);\n\n if (record.type === \"throw\") {\n context.method = \"throw\";\n context.arg = record.arg;\n context.delegate = null;\n return ContinueSentinel;\n }\n\n var info = record.arg;\n\n if (! info) {\n context.method = \"throw\";\n context.arg = new TypeError(\"iterator result is not an object\");\n context.delegate = null;\n return ContinueSentinel;\n }\n\n if (info.done) {\n // Assign the result of the finished delegate to the temporary\n // variable specified by delegate.resultName (see delegateYield).\n context[delegate.resultName] = info.value;\n\n // Resume execution at the desired location (see delegateYield).\n context.next = delegate.nextLoc;\n\n // If context.method was \"throw\" but the delegate handled the\n // exception, let the outer generator proceed normally. If\n // context.method was \"next\", forget context.arg since it has been\n // \"consumed\" by the delegate iterator. If context.method was\n // \"return\", allow the original .return call to continue in the\n // outer generator.\n if (context.method !== \"return\") {\n context.method = \"next\";\n context.arg = undefined;\n }\n\n } else {\n // Re-yield the result returned by the delegate method.\n return info;\n }\n\n // The delegate iterator is finished, so forget it and continue with\n // the outer generator.\n context.delegate = null;\n return ContinueSentinel;\n }\n\n // Define Generator.prototype.{next,throw,return} in terms of the\n // unified ._invoke helper method.\n defineIteratorMethods(Gp);\n\n Gp[toStringTagSymbol] = \"Generator\";\n\n Gp.toString = function() {\n return \"[object Generator]\";\n };\n\n function pushTryEntry(locs) {\n var entry = { tryLoc: locs[0] };\n\n if (1 in locs) {\n entry.catchLoc = locs[1];\n }\n\n if (2 in locs) {\n entry.finallyLoc = locs[2];\n entry.afterLoc = locs[3];\n }\n\n this.tryEntries.push(entry);\n }\n\n function resetTryEntry(entry) {\n var record = entry.completion || {};\n record.type = \"normal\";\n delete record.arg;\n entry.completion = record;\n }\n\n function Context(tryLocsList) {\n // The root entry object (effectively a try statement without a catch\n // or a finally block) gives us a place to store values thrown from\n // locations where there is no enclosing try statement.\n this.tryEntries = [{ tryLoc: \"root\" }];\n tryLocsList.forEach(pushTryEntry, this);\n this.reset(true);\n }\n\n runtime.keys = function(object) {\n var keys = [];\n for (var key in object) {\n keys.push(key);\n }\n keys.reverse();\n\n // Rather than returning an object with a next method, we keep\n // things simple and return the next function itself.\n return function next() {\n while (keys.length) {\n var key = keys.pop();\n if (key in object) {\n next.value = key;\n next.done = false;\n return next;\n }\n }\n\n // To avoid creating an additional object, we just hang the .value\n // and .done properties off the next function object itself. This\n // also ensures that the minifier will not anonymize the function.\n next.done = true;\n return next;\n };\n };\n\n function values(iterable) {\n if (iterable) {\n var iteratorMethod = iterable[iteratorSymbol];\n if (iteratorMethod) {\n return iteratorMethod.call(iterable);\n }\n\n if (typeof iterable.next === \"function\") {\n return iterable;\n }\n\n if (!isNaN(iterable.length)) {\n var i = -1, next = function next() {\n while (++i < iterable.length) {\n if (hasOwn.call(iterable, i)) {\n next.value = iterable[i];\n next.done = false;\n return next;\n }\n }\n\n next.value = undefined;\n next.done = true;\n\n return next;\n };\n\n return next.next = next;\n }\n }\n\n // Return an iterator with no values.\n return { next: doneResult };\n }\n runtime.values = values;\n\n function doneResult() {\n return { value: undefined, done: true };\n }\n\n Context.prototype = {\n constructor: Context,\n\n reset: function(skipTempReset) {\n this.prev = 0;\n this.next = 0;\n // Resetting context._sent for legacy support of Babel's\n // function.sent implementation.\n this.sent = this._sent = undefined;\n this.done = false;\n this.delegate = null;\n\n this.method = \"next\";\n this.arg = undefined;\n\n this.tryEntries.forEach(resetTryEntry);\n\n if (!skipTempReset) {\n for (var name in this) {\n // Not sure about the optimal order of these conditions:\n if (name.charAt(0) === \"t\" &&\n hasOwn.call(this, name) &&\n !isNaN(+name.slice(1))) {\n this[name] = undefined;\n }\n }\n }\n },\n\n stop: function() {\n this.done = true;\n\n var rootEntry = this.tryEntries[0];\n var rootRecord = rootEntry.completion;\n if (rootRecord.type === \"throw\") {\n throw rootRecord.arg;\n }\n\n return this.rval;\n },\n\n dispatchException: function(exception) {\n if (this.done) {\n throw exception;\n }\n\n var context = this;\n function handle(loc, caught) {\n record.type = \"throw\";\n record.arg = exception;\n context.next = loc;\n\n if (caught) {\n // If the dispatched exception was caught by a catch block,\n // then let that catch block handle the exception normally.\n context.method = \"next\";\n context.arg = undefined;\n }\n\n return !! caught;\n }\n\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n var record = entry.completion;\n\n if (entry.tryLoc === \"root\") {\n // Exception thrown outside of any try block that could handle\n // it, so set the completion value of the entire function to\n // throw the exception.\n return handle(\"end\");\n }\n\n if (entry.tryLoc <= this.prev) {\n var hasCatch = hasOwn.call(entry, \"catchLoc\");\n var hasFinally = hasOwn.call(entry, \"finallyLoc\");\n\n if (hasCatch && hasFinally) {\n if (this.prev < entry.catchLoc) {\n return handle(entry.catchLoc, true);\n } else if (this.prev < entry.finallyLoc) {\n return handle(entry.finallyLoc);\n }\n\n } else if (hasCatch) {\n if (this.prev < entry.catchLoc) {\n return handle(entry.catchLoc, true);\n }\n\n } else if (hasFinally) {\n if (this.prev < entry.finallyLoc) {\n return handle(entry.finallyLoc);\n }\n\n } else {\n throw new Error(\"try statement without catch or finally\");\n }\n }\n }\n },\n\n abrupt: function(type, arg) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc <= this.prev &&\n hasOwn.call(entry, \"finallyLoc\") &&\n this.prev < entry.finallyLoc) {\n var finallyEntry = entry;\n break;\n }\n }\n\n if (finallyEntry &&\n (type === \"break\" ||\n type === \"continue\") &&\n finallyEntry.tryLoc <= arg &&\n arg <= finallyEntry.finallyLoc) {\n // Ignore the finally entry if control is not jumping to a\n // location outside the try/catch block.\n finallyEntry = null;\n }\n\n var record = finallyEntry ? finallyEntry.completion : {};\n record.type = type;\n record.arg = arg;\n\n if (finallyEntry) {\n this.method = \"next\";\n this.next = finallyEntry.finallyLoc;\n return ContinueSentinel;\n }\n\n return this.complete(record);\n },\n\n complete: function(record, afterLoc) {\n if (record.type === \"throw\") {\n throw record.arg;\n }\n\n if (record.type === \"break\" ||\n record.type === \"continue\") {\n this.next = record.arg;\n } else if (record.type === \"return\") {\n this.rval = this.arg = record.arg;\n this.method = \"return\";\n this.next = \"end\";\n } else if (record.type === \"normal\" && afterLoc) {\n this.next = afterLoc;\n }\n\n return ContinueSentinel;\n },\n\n finish: function(finallyLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.finallyLoc === finallyLoc) {\n this.complete(entry.completion, entry.afterLoc);\n resetTryEntry(entry);\n return ContinueSentinel;\n }\n }\n },\n\n \"catch\": function(tryLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc === tryLoc) {\n var record = entry.completion;\n if (record.type === \"throw\") {\n var thrown = record.arg;\n resetTryEntry(entry);\n }\n return thrown;\n }\n }\n\n // The context.catch method must only be called with a location\n // argument that corresponds to a known catch block.\n throw new Error(\"illegal catch attempt\");\n },\n\n delegateYield: function(iterable, resultName, nextLoc) {\n this.delegate = {\n iterator: values(iterable),\n resultName: resultName,\n nextLoc: nextLoc\n };\n\n if (this.method === \"next\") {\n // Deliberately forget the last sent value so that we don't\n // accidentally pass it on to the delegate.\n this.arg = undefined;\n }\n\n return ContinueSentinel;\n }\n };\n})(\n // Among the various tricks for obtaining a reference to the global\n // object, this seems to be the most reliable technique that does not\n // use indirect eval (which violates Content Security Policy).\n typeof global === \"object\" ? global :\n typeof window === \"object\" ? window :\n typeof self === \"object\" ? self : this\n);\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/regenerator-runtime/runtime.js\n// module id = 53\n// module chunks = 0","// 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 = 54\n// module chunks = 0","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 = 57\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 = 58\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