From 6fd4c2f3057f940b3dbef8b492aba52760d17bc7 Mon Sep 17 00:00:00 2001 From: Bruno Michel Date: Tue, 14 Feb 2017 10:50:15 +0100 Subject: [PATCH] Build --- dist/cozy-client.js | 5172 +++++++++++++++++++++++++++++++++- dist/cozy-client.js.map | 2 +- dist/cozy-client.node.js | 55 +- dist/cozy-client.node.js.map | 2 +- 4 files changed, 5069 insertions(+), 162 deletions(-) diff --git a/dist/cozy-client.js b/dist/cozy-client.js index 2ba9799b..627b3a54 100644 --- a/dist/cozy-client.js +++ b/dist/cozy-client.js @@ -7,7 +7,7 @@ exports["cozy-client-js"] = factory(require("pouchdb"), require("pouchdb-find")); else root["cozy-client-js"] = factory(root["pouchdb"], root["pouchdb-find"]); -})(this, function(__WEBPACK_EXTERNAL_MODULE_15__, __WEBPACK_EXTERNAL_MODULE_16__) { +})(this, function(__WEBPACK_EXTERNAL_MODULE_37__, __WEBPACK_EXTERNAL_MODULE_38__) { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; @@ -570,15 +570,15 @@ return /******/ (function(modules) { // webpackBootstrap var files = _interopRequireWildcard(_files); - var _offline = __webpack_require__(14); + var _offline = __webpack_require__(36); var offline = _interopRequireWildcard(_offline); - var _settings = __webpack_require__(17); + var _settings = __webpack_require__(39); var settings = _interopRequireWildcard(_settings); - var _relations = __webpack_require__(18); + var _relations = __webpack_require__(40); var relations = _interopRequireWildcard(_relations); @@ -2376,6 +2376,11 @@ return /******/ (function(modules) { // webpackBootstrap function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + var Readable = void 0; + try { + Readable = __webpack_require__(14).Readable; + } catch (_) {} + var contentTypeOctetStream = 'application/octet-stream'; function doUpload(cozy, data, method, path, options) { @@ -2391,9 +2396,10 @@ return /******/ (function(modules) { // webpackBootstrap var isBuffer = typeof ArrayBuffer !== 'undefined' && data instanceof ArrayBuffer; var isFile = typeof File !== 'undefined' && data instanceof File; var isBlob = typeof Blob !== 'undefined' && data instanceof Blob; + var isStream = typeof Readable !== 'undefined' && data instanceof Readable; var isString = typeof data === 'string'; - if (!isBuffer && !isFile && !isBlob && !isString) { + if (!isBuffer && !isFile && !isBlob && !isStream && !isString) { throw new Error('invalid data type'); } @@ -2411,6 +2417,8 @@ return /******/ (function(modules) { // webpackBootstrap } } else if (isBlob) { contentType = contentTypeOctetStream; + } else if (isStream) { + contentType = contentTypeOctetStream; } else if (typeof data === 'string') { contentType = 'text/plain'; } @@ -2420,185 +2428,5073 @@ return /******/ (function(modules) { // webpackBootstrap lastModifiedDate = new Date(lastModifiedDate); } - return (0, _fetch.cozyFetch)(cozy, path, { - method: method, - headers: { - 'Content-Type': contentType, - 'Date': lastModifiedDate ? lastModifiedDate.toISOString() : '' - }, - body: data - }).then(function (res) { - var json = res.json(); - if (!res.ok) { - return json.then(function (err) { - throw err; - }); - } else { - return json.then(_jsonapi2.default); - } - }); + return (0, _fetch.cozyFetch)(cozy, path, { + method: method, + headers: { + 'Content-Type': contentType, + 'Date': lastModifiedDate ? lastModifiedDate.toGMTString() : '' + }, + body: data + }).then(function (res) { + var json = res.json(); + if (!res.ok) { + return json.then(function (err) { + throw err; + }); + } else { + return json.then(_jsonapi2.default); + } + }); + } + + function create(cozy, data, options) { + var _ref2 = options || {}, + name = _ref2.name, + dirID = _ref2.dirID; + + // handle case where data is a file and contains the name + + + if (!name && typeof data.name === 'string') { + name = data.name; + } + + if (typeof name !== 'string' || name === '') { + throw new Error('missing name argument'); + } + + var path = '/files/' + encodeURIComponent(dirID || ''); + var query = '?Name=' + encodeURIComponent(name) + '&Type=file'; + return doUpload(cozy, data, 'POST', '' + path + query, options); + } + + function createDirectory(cozy, options) { + var _ref3 = options || {}, + name = _ref3.name, + dirID = _ref3.dirID, + lastModifiedDate = _ref3.lastModifiedDate; + + if (typeof name !== 'string' || name === '') { + throw new Error('missing name argument'); + } + + if (lastModifiedDate && typeof lastModifiedDate === 'string') { + lastModifiedDate = new Date(lastModifiedDate); + } + + var path = '/files/' + encodeURIComponent(dirID || ''); + var query = '?Name=' + encodeURIComponent(name) + '&Type=directory'; + return (0, _fetch.cozyFetchJSON)(cozy, 'POST', '' + path + query, undefined, { + headers: { + 'Date': lastModifiedDate ? lastModifiedDate.toGMTString() : '' + } + }); + } + + function updateById(cozy, id, data, options) { + return doUpload(cozy, data, 'PUT', '/files/' + encodeURIComponent(id), options); + } + + function updateAttributesById(cozy, id, attrs) { + if (!attrs || (typeof attrs === 'undefined' ? 'undefined' : _typeof(attrs)) !== 'object') { + throw new Error('missing attrs argument'); + } + + var body = { data: { attributes: attrs } }; + return (0, _fetch.cozyFetchJSON)(cozy, 'PATCH', '/files/' + encodeURIComponent(id), body); + } + + function updateAttributesByPath(cozy, path, attrs) { + if (!attrs || (typeof attrs === 'undefined' ? 'undefined' : _typeof(attrs)) !== 'object') { + throw new Error('missing attrs argument'); + } + + var body = { data: { attributes: attrs } }; + return (0, _fetch.cozyFetchJSON)(cozy, 'PATCH', '/files/metadata?Path=' + encodeURIComponent(path), body); + } + + function trashById(cozy, id) { + if (typeof id !== 'string' || id === '') { + throw new Error('missing id argument'); + } + return (0, _fetch.cozyFetchJSON)(cozy, 'DELETE', '/files/' + encodeURIComponent(id)); + } + + function statById(cozy, id) { + var offline = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; + + if (offline && cozy.offline.hasDatabase(_doctypes.DOCTYPE_FILES)) { + var db = cozy.offline.getDatabase(_doctypes.DOCTYPE_FILES); + return Promise.all([db.get(id), db.find({ selector: { 'dir_id': id } })]).then(function (_ref4) { + var _ref5 = _slicedToArray(_ref4, 2), + doc = _ref5[0], + children = _ref5[1]; + + children = children.docs.map(function (doc) { + return addIsDir(toJsonApi(cozy, doc)); + }); + return addIsDir(toJsonApi(cozy, doc, children)); + }); + } + return (0, _fetch.cozyFetchJSON)(cozy, 'GET', '/files/' + encodeURIComponent(id)).then(addIsDir); + } + + function statByPath(cozy, path) { + return (0, _fetch.cozyFetchJSON)(cozy, 'GET', '/files/metadata?Path=' + encodeURIComponent(path)).then(addIsDir); + } + + function downloadById(cozy, id) { + return (0, _fetch.cozyFetch)(cozy, '/files/download/' + encodeURIComponent(id)); + } + + function downloadByPath(cozy, path) { + return (0, _fetch.cozyFetch)(cozy, '/files/download?Path=' + encodeURIComponent(path)); + } + + function extractResponseLinkRelated(res) { + var href = res.links && res.links.related; + if (!href) throw new Error('No related link in server response'); + return href; + } + + function getDowloadLink(cozy, path) { + return (0, _fetch.cozyFetchJSON)(cozy, 'POST', '/files/downloads?Path=' + encodeURIComponent(path)).then(extractResponseLinkRelated); + } + + function getArchiveLink(cozy, paths) { + var name = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'files'; + + var archive = { + type: 'io.cozy.archives', + attributes: { + name: name, + files: paths + } + }; + return (0, _fetch.cozyFetchJSON)(cozy, 'POST', '/files/archive', { data: archive }).then(extractResponseLinkRelated); + } + + function listTrash(cozy) { + return (0, _fetch.cozyFetchJSON)(cozy, 'GET', '/files/trash'); + } + + function clearTrash(cozy) { + return (0, _fetch.cozyFetchJSON)(cozy, 'DELETE', '/files/trash'); + } + + function restoreById(cozy, id) { + return (0, _fetch.cozyFetchJSON)(cozy, 'POST', '/files/trash/' + encodeURIComponent(id)); + } + + function destroyById(cozy, id) { + return (0, _fetch.cozyFetchJSON)(cozy, 'DELETE', '/files/trash/' + encodeURIComponent(id)); + } + + function addIsDir(obj) { + obj.isDir = obj.attributes.type === 'directory'; + return obj; + } + + function toJsonApi(cozy, doc) { + var contents = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; + + var clone = JSON.parse(JSON.stringify(doc)); + delete clone._id; + delete clone._rev; + return { + _id: doc._id, + _rev: doc._rev, + _type: _doctypes.DOCTYPE_FILES, + attributes: clone, + relations: function relations(name) { + if (name === 'contents') { + return contents; + } + } + }; + } + +/***/ }, +/* 14 */ +/***/ function(module, exports, __webpack_require__) { + + // Copyright Joyent, Inc. and other Node contributors. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + module.exports = Stream; + + var EE = __webpack_require__(15).EventEmitter; + var inherits = __webpack_require__(16); + + inherits(Stream, EE); + Stream.Readable = __webpack_require__(17); + Stream.Writable = __webpack_require__(32); + Stream.Duplex = __webpack_require__(33); + Stream.Transform = __webpack_require__(34); + Stream.PassThrough = __webpack_require__(35); + + // Backwards-compat with node 0.4.x + Stream.Stream = Stream; + + + + // old-style streams. Note that the pipe method (the only relevant + // part of this class) is overridden in the Readable class. + + function Stream() { + EE.call(this); + } + + Stream.prototype.pipe = function(dest, options) { + var source = this; + + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } + } + } + + source.on('data', ondata); + + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } + } + + dest.on('drain', ondrain); + + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); + } + + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; + + dest.end(); + } + + + function onclose() { + if (didOnEnd) return; + didOnEnd = true; + + if (typeof dest.destroy === 'function') dest.destroy(); + } + + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EE.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. + } + } + + source.on('error', onerror); + dest.on('error', onerror); + + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); + + source.removeListener('end', onend); + source.removeListener('close', onclose); + + source.removeListener('error', onerror); + dest.removeListener('error', onerror); + + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); + + dest.removeListener('close', cleanup); + } + + source.on('end', cleanup); + source.on('close', cleanup); + + dest.on('close', cleanup); + + dest.emit('pipe', source); + + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; + }; + + +/***/ }, +/* 15 */ +/***/ function(module, exports) { + + // Copyright Joyent, Inc. and other Node contributors. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + function EventEmitter() { + this._events = this._events || {}; + this._maxListeners = this._maxListeners || undefined; + } + module.exports = EventEmitter; + + // Backwards-compat with node 0.10.x + EventEmitter.EventEmitter = EventEmitter; + + EventEmitter.prototype._events = undefined; + EventEmitter.prototype._maxListeners = undefined; + + // By default EventEmitters will print a warning if more than 10 listeners are + // added to it. This is a useful default which helps finding memory leaks. + EventEmitter.defaultMaxListeners = 10; + + // Obviously not all Emitters should be limited to 10. This function allows + // that to be increased. Set to zero for unlimited. + EventEmitter.prototype.setMaxListeners = function(n) { + if (!isNumber(n) || n < 0 || isNaN(n)) + throw TypeError('n must be a positive number'); + this._maxListeners = n; + return this; + }; + + EventEmitter.prototype.emit = function(type) { + var er, handler, len, args, i, listeners; + + if (!this._events) + this._events = {}; + + // If there is no 'error' event listener then throw. + if (type === 'error') { + if (!this._events.error || + (isObject(this._events.error) && !this._events.error.length)) { + er = arguments[1]; + if (er instanceof Error) { + throw er; // Unhandled 'error' event + } else { + // At least give some kind of context to the user + var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); + err.context = er; + throw err; + } + } + } + + handler = this._events[type]; + + if (isUndefined(handler)) + return false; + + if (isFunction(handler)) { + switch (arguments.length) { + // fast cases + case 1: + handler.call(this); + break; + case 2: + handler.call(this, arguments[1]); + break; + case 3: + handler.call(this, arguments[1], arguments[2]); + break; + // slower + default: + args = Array.prototype.slice.call(arguments, 1); + handler.apply(this, args); + } + } else if (isObject(handler)) { + args = Array.prototype.slice.call(arguments, 1); + listeners = handler.slice(); + len = listeners.length; + for (i = 0; i < len; i++) + listeners[i].apply(this, args); + } + + return true; + }; + + EventEmitter.prototype.addListener = function(type, listener) { + var m; + + if (!isFunction(listener)) + throw TypeError('listener must be a function'); + + if (!this._events) + this._events = {}; + + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (this._events.newListener) + this.emit('newListener', type, + isFunction(listener.listener) ? + listener.listener : listener); + + if (!this._events[type]) + // Optimize the case of one listener. Don't need the extra array object. + this._events[type] = listener; + else if (isObject(this._events[type])) + // If we've already got an array, just append. + this._events[type].push(listener); + else + // Adding the second element, need to change to array. + this._events[type] = [this._events[type], listener]; + + // Check for listener leak + if (isObject(this._events[type]) && !this._events[type].warned) { + if (!isUndefined(this._maxListeners)) { + m = this._maxListeners; + } else { + m = EventEmitter.defaultMaxListeners; + } + + if (m && m > 0 && this._events[type].length > m) { + this._events[type].warned = true; + console.error('(node) warning: possible EventEmitter memory ' + + 'leak detected. %d listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit.', + this._events[type].length); + if (typeof console.trace === 'function') { + // not supported in IE 10 + console.trace(); + } + } + } + + return this; + }; + + EventEmitter.prototype.on = EventEmitter.prototype.addListener; + + EventEmitter.prototype.once = function(type, listener) { + if (!isFunction(listener)) + throw TypeError('listener must be a function'); + + var fired = false; + + function g() { + this.removeListener(type, g); + + if (!fired) { + fired = true; + listener.apply(this, arguments); + } + } + + g.listener = listener; + this.on(type, g); + + return this; + }; + + // emits a 'removeListener' event iff the listener was removed + EventEmitter.prototype.removeListener = function(type, listener) { + var list, position, length, i; + + if (!isFunction(listener)) + throw TypeError('listener must be a function'); + + if (!this._events || !this._events[type]) + return this; + + list = this._events[type]; + length = list.length; + position = -1; + + if (list === listener || + (isFunction(list.listener) && list.listener === listener)) { + delete this._events[type]; + if (this._events.removeListener) + this.emit('removeListener', type, listener); + + } else if (isObject(list)) { + for (i = length; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + position = i; + break; + } + } + + if (position < 0) + return this; + + if (list.length === 1) { + list.length = 0; + delete this._events[type]; + } else { + list.splice(position, 1); + } + + if (this._events.removeListener) + this.emit('removeListener', type, listener); + } + + return this; + }; + + EventEmitter.prototype.removeAllListeners = function(type) { + var key, listeners; + + if (!this._events) + return this; + + // not listening for removeListener, no need to emit + if (!this._events.removeListener) { + if (arguments.length === 0) + this._events = {}; + else if (this._events[type]) + delete this._events[type]; + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + for (key in this._events) { + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = {}; + return this; + } + + listeners = this._events[type]; + + if (isFunction(listeners)) { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + while (listeners.length) + this.removeListener(type, listeners[listeners.length - 1]); + } + delete this._events[type]; + + return this; + }; + + EventEmitter.prototype.listeners = function(type) { + var ret; + if (!this._events || !this._events[type]) + ret = []; + else if (isFunction(this._events[type])) + ret = [this._events[type]]; + else + ret = this._events[type].slice(); + return ret; + }; + + EventEmitter.prototype.listenerCount = function(type) { + if (this._events) { + var evlistener = this._events[type]; + + if (isFunction(evlistener)) + return 1; + else if (evlistener) + return evlistener.length; + } + return 0; + }; + + EventEmitter.listenerCount = function(emitter, type) { + return emitter.listenerCount(type); + }; + + function isFunction(arg) { + return typeof arg === 'function'; + } + + function isNumber(arg) { + return typeof arg === 'number'; + } + + function isObject(arg) { + return typeof arg === 'object' && arg !== null; + } + + function isUndefined(arg) { + return arg === void 0; + } + + +/***/ }, +/* 16 */ +/***/ function(module, exports) { + + if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; + } else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } + } + + +/***/ }, +/* 17 */ +/***/ function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(process) {exports = module.exports = __webpack_require__(19); + exports.Stream = __webpack_require__(14); + exports.Readable = exports; + exports.Writable = __webpack_require__(28); + exports.Duplex = __webpack_require__(27); + exports.Transform = __webpack_require__(30); + exports.PassThrough = __webpack_require__(31); + if (!process.browser && process.env.READABLE_STREAM === 'disable') { + module.exports = __webpack_require__(14); + } + + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(18))) + +/***/ }, +/* 18 */ +/***/ function(module, exports) { + + // shim for using process in browser + var process = module.exports = {}; + + // cached from whatever global is present so that test runners that stub it + // don't break things. But we need to wrap it in a try catch in case it is + // wrapped in strict mode code which doesn't define any globals. It's inside a + // function because try/catches deoptimize in certain engines. + + var cachedSetTimeout; + var cachedClearTimeout; + + function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); + } + function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); + } + (function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } + } ()) + function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + + } + function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + + } + var queue = []; + var draining = false; + var currentQueue; + var queueIndex = -1; + + function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } + } + + function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); + } + + process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } + }; + + // v8 likes predictible objects + function Item(fun, array) { + this.fun = fun; + this.array = array; + } + Item.prototype.run = function () { + this.fun.apply(null, this.array); + }; + process.title = 'browser'; + process.browser = true; + process.env = {}; + process.argv = []; + process.version = ''; // empty string to avoid regexp issues + process.versions = {}; + + function noop() {} + + process.on = noop; + process.addListener = noop; + process.once = noop; + process.off = noop; + process.removeListener = noop; + process.removeAllListeners = noop; + process.emit = noop; + + process.binding = function (name) { + throw new Error('process.binding is not supported'); + }; + + process.cwd = function () { return '/' }; + process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); + }; + process.umask = function() { return 0; }; + + +/***/ }, +/* 19 */ +/***/ function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(process) {// Copyright Joyent, Inc. and other Node contributors. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + module.exports = Readable; + + /**/ + var isArray = __webpack_require__(20); + /**/ + + + /**/ + var Buffer = __webpack_require__(21).Buffer; + /**/ + + Readable.ReadableState = ReadableState; + + var EE = __webpack_require__(15).EventEmitter; + + /**/ + if (!EE.listenerCount) EE.listenerCount = function(emitter, type) { + return emitter.listeners(type).length; + }; + /**/ + + var Stream = __webpack_require__(14); + + /**/ + var util = __webpack_require__(25); + util.inherits = __webpack_require__(16); + /**/ + + var StringDecoder; + + + /**/ + var debug = __webpack_require__(26); + if (debug && debug.debuglog) { + debug = debug.debuglog('stream'); + } else { + debug = function () {}; + } + /**/ + + + util.inherits(Readable, Stream); + + function ReadableState(options, stream) { + var Duplex = __webpack_require__(27); + + options = options || {}; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var defaultHwm = options.objectMode ? 16 : 16 * 1024; + this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~~this.highWaterMark; + + this.buffer = []; + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) + this.objectMode = this.objectMode || !!options.readableObjectMode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) + StringDecoder = __webpack_require__(29).StringDecoder; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } + } + + function Readable(options) { + var Duplex = __webpack_require__(27); + + if (!(this instanceof Readable)) + return new Readable(options); + + this._readableState = new ReadableState(options, this); + + // legacy + this.readable = true; + + Stream.call(this); + } + + // Manually shove something into the read() buffer. + // This returns true if the highWaterMark has not been hit yet, + // similar to how Writable.write() returns true if you should + // write() some more. + Readable.prototype.push = function(chunk, encoding) { + var state = this._readableState; + + if (util.isString(chunk) && !state.objectMode) { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = new Buffer(chunk, encoding); + encoding = ''; + } + } + + return readableAddChunk(this, state, chunk, encoding, false); + }; + + // Unshift should *always* be something directly out of read() + Readable.prototype.unshift = function(chunk) { + var state = this._readableState; + return readableAddChunk(this, state, chunk, '', true); + }; + + function readableAddChunk(stream, state, chunk, encoding, addToFront) { + var er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (util.isNullOrUndefined(chunk)) { + state.reading = false; + if (!state.ended) + onEofChunk(stream, state); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (state.ended && !addToFront) { + var e = new Error('stream.push() after EOF'); + stream.emit('error', e); + } else if (state.endEmitted && addToFront) { + var e = new Error('stream.unshift() after end event'); + stream.emit('error', e); + } else { + if (state.decoder && !addToFront && !encoding) + chunk = state.decoder.write(chunk); + + if (!addToFront) + state.reading = false; + + // if we want the data now, just emit it. + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) + state.buffer.unshift(chunk); + else + state.buffer.push(chunk); + + if (state.needReadable) + emitReadable(stream); + } + + maybeReadMore(stream, state); + } + } else if (!addToFront) { + state.reading = false; + } + + return needMoreData(state); + } + + + + // if it's past the high water mark, we can push in some more. + // Also, if we have no data yet, we can stand some + // more bytes. This is to work around cases where hwm=0, + // such as the repl. Also, if the push() triggered a + // readable event, and the user called read(largeNumber) such that + // needReadable was set, then we ought to push more, so that another + // 'readable' event will be triggered. + function needMoreData(state) { + return !state.ended && + (state.needReadable || + state.length < state.highWaterMark || + state.length === 0); + } + + // backwards compatibility. + Readable.prototype.setEncoding = function(enc) { + if (!StringDecoder) + StringDecoder = __webpack_require__(29).StringDecoder; + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; + }; + + // Don't raise the hwm > 128MB + var MAX_HWM = 0x800000; + function roundUpToNextPowerOf2(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 + n--; + for (var p = 1; p < 32; p <<= 1) n |= n >> p; + n++; + } + return n; + } + + function howMuchToRead(n, state) { + if (state.length === 0 && state.ended) + return 0; + + if (state.objectMode) + return n === 0 ? 0 : 1; + + if (isNaN(n) || util.isNull(n)) { + // only flow one buffer at a time + if (state.flowing && state.buffer.length) + return state.buffer[0].length; + else + return state.length; + } + + if (n <= 0) + return 0; + + // If we're asking for more than the target buffer level, + // then raise the water mark. Bump up to the next highest + // power of 2, to prevent increasing it excessively in tiny + // amounts. + if (n > state.highWaterMark) + state.highWaterMark = roundUpToNextPowerOf2(n); + + // don't have that much. return null, unless we've ended. + if (n > state.length) { + if (!state.ended) { + state.needReadable = true; + return 0; + } else + return state.length; + } + + return n; + } + + // you can override either this method, or the async _read(n) below. + Readable.prototype.read = function(n) { + debug('read', n); + var state = this._readableState; + var nOrig = n; + + if (!util.isNumber(n) || n > 0) + state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && + state.needReadable && + (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) + endReadable(this); + else + emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) + endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } + + if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) + state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + } + + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (doRead && !state.reading) + n = howMuchToRead(nOrig, state); + + var ret; + if (n > 0) + ret = fromList(n, state); + else + ret = null; + + if (util.isNull(ret)) { + state.needReadable = true; + n = 0; + } + + state.length -= n; + + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (state.length === 0 && !state.ended) + state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended && state.length === 0) + endReadable(this); + + if (!util.isNull(ret)) + this.emit('data', ret); + + return ret; + }; + + function chunkInvalid(state, chunk) { + var er = null; + if (!util.isBuffer(chunk) && + !util.isString(chunk) && + !util.isNullOrUndefined(chunk) && + !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; + } + + + function onEofChunk(stream, state) { + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); + } + + // Don't emit readable right away in sync mode, because this can trigger + // another read() call => stack overflow. This way, it might trigger + // a nextTick recursion warning, but that's not so bad. + function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) + process.nextTick(function() { + emitReadable_(stream); + }); + else + emitReadable_(stream); + } + } + + function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); + } + + + // at this point, the user has presumably seen the 'readable' event, + // and called read() to consume some data. that may have triggered + // in turn another _read(n) call, in which case reading = true if + // it's in progress. + // However, if we're not ended, or reading, and the length < hwm, + // then go ahead and try to read some more preemptively. + function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + process.nextTick(function() { + maybeReadMore_(stream, state); + }); + } + } + + function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && + state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break; + else + len = state.length; + } + state.readingMore = false; + } + + // abstract method. to be overridden in specific implementation classes. + // call cb(er, data) where data is <= n in length. + // for virtual (non-string, non-buffer) streams, "length" is somewhat + // arbitrary, and perhaps not very meaningful. + Readable.prototype._read = function(n) { + this.emit('error', new Error('not implemented')); + }; + + Readable.prototype.pipe = function(dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + + var doEnd = (!pipeOpts || pipeOpts.end !== false) && + dest !== process.stdout && + dest !== process.stderr; + + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) + process.nextTick(endFn); + else + src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + debug('onunpipe'); + if (readable === src) { + cleanup(); + } + } + + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', cleanup); + src.removeListener('data', ondata); + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && + (!dest._writableState || dest._writableState.needDrain)) + ondrain(); + } + + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + var ret = dest.write(chunk); + if (false === ret) { + debug('false write response, pause', + src._readableState.awaitDrain); + src._readableState.awaitDrain++; + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EE.listenerCount(dest, 'error') === 0) + dest.emit('error', er); + } + // This is a brutally ugly hack to make sure that our error handler + // is attached before any userland ones. NEVER DO THIS. + if (!dest._events || !dest._events.error) + dest.on('error', onerror); + else if (isArray(dest._events.error)) + dest._events.error.unshift(onerror); + else + dest._events.error = [onerror, dest._events.error]; + + + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + + return dest; + }; + + function pipeOnDrain(src) { + return function() { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) + state.awaitDrain--; + if (state.awaitDrain === 0 && EE.listenerCount(src, 'data')) { + state.flowing = true; + flow(src); + } + }; + } + + + Readable.prototype.unpipe = function(dest) { + var state = this._readableState; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) + return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) + return this; + + if (!dest) + dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) + dest.emit('unpipe', this); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var i = 0; i < len; i++) + dests[i].emit('unpipe', this); + return this; + } + + // try to find the right one. + var i = indexOf(state.pipes, dest); + if (i === -1) + return this; + + state.pipes.splice(i, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) + state.pipes = state.pipes[0]; + + dest.emit('unpipe', this); + + return this; + }; + + // set up data events if they are asked for + // Ensure readable listeners eventually get something + Readable.prototype.on = function(ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + + // If listening to data, and it has not explicitly been paused, + // then call resume to start the flow of data on the next tick. + if (ev === 'data' && false !== this._readableState.flowing) { + this.resume(); + } + + if (ev === 'readable' && this.readable) { + var state = this._readableState; + if (!state.readableListening) { + state.readableListening = true; + state.emittedReadable = false; + state.needReadable = true; + if (!state.reading) { + var self = this; + process.nextTick(function() { + debug('readable nexttick read 0'); + self.read(0); + }); + } else if (state.length) { + emitReadable(this, state); + } + } + } + + return res; + }; + Readable.prototype.addListener = Readable.prototype.on; + + // pause() and resume() are remnants of the legacy readable stream API + // If the user uses them, then switch into old mode. + Readable.prototype.resume = function() { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + if (!state.reading) { + debug('resume read 0'); + this.read(0); + } + resume(this, state); + } + return this; + }; + + function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + process.nextTick(function() { + resume_(stream, state); + }); + } + } + + function resume_(stream, state) { + state.resumeScheduled = false; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) + stream.read(0); + } + + Readable.prototype.pause = function() { + debug('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; + }; + + function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + if (state.flowing) { + do { + var chunk = stream.read(); + } while (null !== chunk && state.flowing); + } + } + + // wrap an old-style stream as the async data source. + // This is *not* part of the readable stream interface. + // It is an ugly unfortunate mess of history. + Readable.prototype.wrap = function(stream) { + var state = this._readableState; + var paused = false; + + var self = this; + stream.on('end', function() { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) + self.push(chunk); + } + + self.push(null); + }); + + stream.on('data', function(chunk) { + debug('wrapped data'); + if (state.decoder) + chunk = state.decoder.write(chunk); + if (!chunk || !state.objectMode && !chunk.length) + return; + + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (util.isFunction(stream[i]) && util.isUndefined(this[i])) { + this[i] = function(method) { return function() { + return stream[method].apply(stream, arguments); + }}(i); + } + } + + // proxy certain important events. + var events = ['error', 'close', 'destroy', 'pause', 'resume']; + forEach(events, function(ev) { + stream.on(ev, self.emit.bind(self, ev)); + }); + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function(n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + + return self; + }; + + + + // exposed for testing purposes only. + Readable._fromList = fromList; + + // Pluck off n bytes from an array of buffers. + // Length is the combined lengths of all the buffers in the list. + function fromList(n, state) { + var list = state.buffer; + var length = state.length; + var stringMode = !!state.decoder; + var objectMode = !!state.objectMode; + var ret; + + // nothing in the list, definitely empty. + if (list.length === 0) + return null; + + if (length === 0) + ret = null; + else if (objectMode) + ret = list.shift(); + else if (!n || n >= length) { + // read it all, truncate the array. + if (stringMode) + ret = list.join(''); + else + ret = Buffer.concat(list, length); + list.length = 0; + } else { + // read just some of it. + if (n < list[0].length) { + // just take a part of the first list item. + // slice is the same for buffers and strings. + var buf = list[0]; + ret = buf.slice(0, n); + list[0] = buf.slice(n); + } else if (n === list[0].length) { + // first list is a perfect match + ret = list.shift(); + } else { + // complex case. + // we have enough to cover it, but it spans past the first buffer. + if (stringMode) + ret = ''; + else + ret = new Buffer(n); + + var c = 0; + for (var i = 0, l = list.length; i < l && c < n; i++) { + var buf = list[0]; + var cpy = Math.min(n - c, buf.length); + + if (stringMode) + ret += buf.slice(0, cpy); + else + buf.copy(ret, c, 0, cpy); + + if (cpy < buf.length) + list[0] = buf.slice(cpy); + else + list.shift(); + + c += cpy; + } + } + } + + return ret; + } + + function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) + throw new Error('endReadable called on non-empty stream'); + + if (!state.endEmitted) { + state.ended = true; + process.nextTick(function() { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } + }); + } + } + + function forEach (xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } + } + + function indexOf (xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; + } + + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(18))) + +/***/ }, +/* 20 */ +/***/ function(module, exports) { + + module.exports = Array.isArray || function (arr) { + return Object.prototype.toString.call(arr) == '[object Array]'; + }; + + +/***/ }, +/* 21 */ +/***/ function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(Buffer, global) {/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ + /* eslint-disable no-proto */ + + 'use strict' + + var base64 = __webpack_require__(22) + var ieee754 = __webpack_require__(23) + var isArray = __webpack_require__(24) + + exports.Buffer = Buffer + exports.SlowBuffer = SlowBuffer + exports.INSPECT_MAX_BYTES = 50 + + /** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ + Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined + ? global.TYPED_ARRAY_SUPPORT + : typedArraySupport() + + /* + * Export kMaxLength after typed array support is determined. + */ + exports.kMaxLength = kMaxLength() + + function typedArraySupport () { + try { + var arr = new Uint8Array(1) + arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} + return arr.foo() === 42 && // typed array instances can be augmented + typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` + arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` + } catch (e) { + return false + } + } + + function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff + } + + function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length) + that.__proto__ = Buffer.prototype + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length) + } + that.length = length + } + + return that + } + + /** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + + function Buffer (arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) + } + return from(this, arg, encodingOrOffset, length) + } + + Buffer.poolSize = 8192 // not used by this implementation + + // TODO: Legacy, not needed anymore. Remove in next major version. + Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype + return arr + } + + function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } + + return fromObject(that, value) + } + + /** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ + Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype + Buffer.__proto__ = Uint8Array + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) { + // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 + Object.defineProperty(Buffer, Symbol.species, { + value: null, + configurable: true + }) + } + } + + function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } + } + + function alloc (that, size, fill, encoding) { + assertSize(size) + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) + } + + /** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ + Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) + } + + function allocUnsafe (that, size) { + assertSize(size) + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0) + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0 + } + } + return that + } + + /** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ + Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size) + } + /** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ + Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) + } + + function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength(string, encoding) | 0 + that = createBuffer(that, length) + + var actual = that.write(string, encoding) + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual) + } + + return that + } + + function fromArrayLike (that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0 + that = createBuffer(that, length) + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255 + } + return that + } + + function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array) + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset) + } else { + array = new Uint8Array(array, byteOffset, length) + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array + that.__proto__ = Buffer.prototype + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array) + } + return that + } + + function fromObject (that, obj) { + if (Buffer.isBuffer(obj)) { + var len = checked(obj.length) | 0 + that = createBuffer(that, len) + + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len) + return that + } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && isArray(obj.data)) { + return fromArrayLike(that, obj.data) + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') + } + + function checked (length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 + } + + function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0 + } + return Buffer.alloc(+length) + } + + Buffer.isBuffer = function isBuffer (b) { + return !!(b != null && b._isBuffer) + } + + Buffer.compare = function compare (a, b) { + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length + var y = b.length + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i] + y = b[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + } + + Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } + } + + Buffer.concat = function concat (list, length) { + if (!isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i + if (length === undefined) { + length = 0 + for (i = 0; i < list.length; ++i) { + length += list[i].length + } + } + + var buffer = Buffer.allocUnsafe(length) + var pos = 0 + for (i = 0; i < list.length; ++i) { + var buf = list[i] + if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos) + pos += buf.length + } + return buffer + } + + function byteLength (string, encoding) { + if (Buffer.isBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string + } + + var len = string.length + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } + } + Buffer.byteLength = byteLength + + function slowToString (encoding, start, end) { + var loweredCase = false + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0 + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0 + start >>>= 0 + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8' + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true + } + } + } + + // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect + // Buffer instances. + Buffer.prototype._isBuffer = true + + function swap (b, n, m) { + var i = b[n] + b[n] = b[m] + b[m] = i + } + + Buffer.prototype.swap16 = function swap16 () { + var len = this.length + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1) + } + return this + } + + Buffer.prototype.swap32 = function swap32 () { + var len = this.length + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3) + swap(this, i + 1, i + 2) + } + return this + } + + Buffer.prototype.swap64 = function swap64 () { + var len = this.length + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7) + swap(this, i + 1, i + 6) + swap(this, i + 2, i + 5) + swap(this, i + 3, i + 4) + } + return this + } + + Buffer.prototype.toString = function toString () { + var length = this.length | 0 + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) + } + + Buffer.prototype.equals = function equals (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 + } + + Buffer.prototype.inspect = function inspect () { + var str = '' + var max = exports.INSPECT_MAX_BYTES + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') + if (this.length > max) str += ' ... ' + } + return '' + } + + Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!Buffer.isBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0 + } + if (end === undefined) { + end = target ? target.length : 0 + } + if (thisStart === undefined) { + thisStart = 0 + } + if (thisEnd === undefined) { + thisEnd = this.length + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0 + end >>>= 0 + thisStart >>>= 0 + thisEnd >>>= 0 + + if (this === target) return 0 + + var x = thisEnd - thisStart + var y = end - start + var len = Math.min(x, y) + + var thisCopy = this.slice(thisStart, thisEnd) + var targetCopy = target.slice(start, end) + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i] + y = targetCopy[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + } + + // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, + // OR the last index of `val` in `buffer` at offset <= `byteOffset`. + // + // Arguments: + // - buffer - a Buffer to search + // - val - a string, Buffer, or number + // - byteOffset - an index into `buffer`; will be clamped to an int32 + // - encoding - an optional encoding, relevant is val is a string + // - dir - true for indexOf, false for lastIndexOf + function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000 + } + byteOffset = +byteOffset // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1) + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1 + } else if (byteOffset < 0) { + if (dir) byteOffset = 0 + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding) + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (Buffer.isBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF // Search for a byte value [0-255] + if (Buffer.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') + } + + function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1 + var arrLength = arr.length + var valLength = val.length + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase() + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2 + arrLength /= 2 + valLength /= 2 + byteOffset /= 2 + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i + if (dir) { + var foundIndex = -1 + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex + foundIndex = -1 + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength + for (i = byteOffset; i >= 0; i--) { + var found = true + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false + break + } + } + if (found) return i + } + } + + return -1 + } + + Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 + } + + Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) + } + + Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) + } + + function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0 + var remaining = buf.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } + + // must be an even number of digits + var strLen = string.length + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2 + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16) + if (isNaN(parsed)) return i + buf[offset + i] = parsed + } + return i + } + + function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) + } + + function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) + } + + function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) + } + + function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) + } + + function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) + } + + Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8' + length = this.length + offset = 0 + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset + length = this.length + offset = 0 + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0 + if (isFinite(length)) { + length = length | 0 + if (encoding === undefined) encoding = 'utf8' + } else { + encoding = length + length = undefined + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset + if (length === undefined || length > remaining) length = remaining + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8' + + var loweredCase = false + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } + } + + Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } + } + + function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } + } + + function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end) + var res = [] + + var i = start + while (i < end) { + var firstByte = buf[i] + var codePoint = null + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1 + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte + } + break + case 2: + secondByte = buf[i + 1] + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint + } + } + break + case 3: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint + } + } + break + case 4: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + fourthByte = buf[i + 3] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD + bytesPerSequence = 1 + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000 + res.push(codePoint >>> 10 & 0x3FF | 0xD800) + codePoint = 0xDC00 | codePoint & 0x3FF + } + + res.push(codePoint) + i += bytesPerSequence + } + + return decodeCodePointsArray(res) + } + + // Based on http://stackoverflow.com/a/22747272/680742, the browser with + // the lowest limit is Chrome, with 0x10000 args. + // We go 1 magnitude less, for safety + var MAX_ARGUMENTS_LENGTH = 0x1000 + + function decodeCodePointsArray (codePoints) { + var len = codePoints.length + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = '' + var i = 0 + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ) + } + return res + } + + function asciiSlice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F) + } + return ret + } + + function latin1Slice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]) + } + return ret + } + + function hexSlice (buf, start, end) { + var len = buf.length + + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len + + var out = '' + for (var i = start; i < end; ++i) { + out += toHex(buf[i]) + } + return out + } + + function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end) + var res = '' + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) + } + return res + } + + Buffer.prototype.slice = function slice (start, end) { + var len = this.length + start = ~~start + end = end === undefined ? len : ~~end + + if (start < 0) { + start += len + if (start < 0) start = 0 + } else if (start > len) { + start = len + } + + if (end < 0) { + end += len + if (end < 0) end = 0 + } else if (end > len) { + end = len + } + + if (end < start) end = start + + var newBuf + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end) + newBuf.__proto__ = Buffer.prototype + } else { + var sliceLen = end - start + newBuf = new Buffer(sliceLen, undefined) + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start] + } + } + + return newBuf + } + + /* + * Need to make sure that buffer isn't trying to write out of bounds. + */ + function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') + } + + Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + + return val + } + + Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + checkOffset(offset, byteLength, this.length) + } + + var val = this[offset + --byteLength] + var mul = 1 + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul + } + + return val + } + + Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length) + return this[offset] + } + + Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) + } + + Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] + } + + Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) + } + + Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) + } + + Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val + } + + Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var i = byteLength + var mul = 1 + var val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val + } + + Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length) + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) + } + + Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset] | (this[offset + 1] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val + } + + Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset + 1] | (this[offset] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val + } + + Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) + } + + Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) + } + + Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, true, 23, 4) + } + + Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, false, 23, 4) + } + + Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, true, 52, 8) + } + + Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, false, 52, 8) + } + + function checkInt (buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') + } + + Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var mul = 1 + var i = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength + } + + Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var i = byteLength - 1 + var mul = 1 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength + } + + Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) + this[offset] = (value & 0xff) + return offset + 1 + } + + function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1 + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8 + } + } + + Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + } else { + objectWriteUInt16(this, value, offset, true) + } + return offset + 2 + } + + Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + } else { + objectWriteUInt16(this, value, offset, false) + } + return offset + 2 + } + + function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1 + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff + } + } + + Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, true) + } + return offset + 4 + } + + Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, false) + } + return offset + 4 + } + + Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = 0 + var mul = 1 + var sub = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength + } + + Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = byteLength - 1 + var mul = 1 + var sub = 0 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength + } + + Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) + if (value < 0) value = 0xff + value + 1 + this[offset] = (value & 0xff) + return offset + 1 + } + + Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + } else { + objectWriteUInt16(this, value, offset, true) + } + return offset + 2 + } + + Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + } else { + objectWriteUInt16(this, value, offset, false) + } + return offset + 2 + } + + Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + this[offset + 2] = (value >>> 16) + this[offset + 3] = (value >>> 24) + } else { + objectWriteUInt32(this, value, offset, true) + } + return offset + 4 + } + + Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (value < 0) value = 0xffffffff + value + 1 + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, false) + } + return offset + 4 + } + + function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') + } + + function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) + } + ieee754.write(buf, value, offset, littleEndian, 23, 4) + return offset + 4 + } + + Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) + } + + Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) + } + + function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) + } + ieee754.write(buf, value, offset, littleEndian, 52, 8) + return offset + 8 + } + + Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) + } + + Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) + } + + // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) + Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (targetStart >= target.length) targetStart = target.length + if (!targetStart) targetStart = 0 + if (end > 0 && end < start) end = start + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start + } + + var len = end - start + var i + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start] + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start] + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ) + } + + return len + } + + // Usage: + // buffer.fill(number[, offset[, end]]) + // buffer.fill(buffer[, offset[, end]]) + // buffer.fill(string[, offset[, end]][, encoding]) + Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start + start = 0 + end = this.length + } else if (typeof end === 'string') { + encoding = end + end = this.length + } + if (val.length === 1) { + var code = val.charCodeAt(0) + if (code < 256) { + val = code + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255 + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0 + end = end === undefined ? this.length : end >>> 0 + + if (!val) val = 0 + + var i + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val + } + } else { + var bytes = Buffer.isBuffer(val) + ? val + : utf8ToBytes(new Buffer(val, encoding).toString()) + var len = bytes.length + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len] + } + } + + return this + } + + // HELPER FUNCTIONS + // ================ + + var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g + + function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, '') + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '=' + } + return str + } + + function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') + } + + function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) + } + + function utf8ToBytes (string, units) { + units = units || Infinity + var codePoint + var length = string.length + var leadSurrogate = null + var bytes = [] + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i) + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } + + // valid lead + leadSurrogate = codePoint + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = codePoint + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + } + + leadSurrogate = null + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint) + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else { + throw new Error('Invalid code point') + } + } + + return bytes + } + + function asciiToBytes (str) { + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF) + } + return byteArray + } + + function utf16leToBytes (str, units) { + var c, hi, lo + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } + + return byteArray + } + + function base64ToBytes (str) { + return base64.toByteArray(base64clean(str)) + } + + function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i] + } + return i + } + + function isnan (val) { + return val !== val // eslint-disable-line no-self-compare + } + + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(21).Buffer, (function() { return this; }()))) + +/***/ }, +/* 22 */ +/***/ function(module, exports) { + + 'use strict' + + exports.byteLength = byteLength + exports.toByteArray = toByteArray + exports.fromByteArray = fromByteArray + + var lookup = [] + var revLookup = [] + var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array + + var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i] + revLookup[code.charCodeAt(i)] = i + } + + revLookup['-'.charCodeAt(0)] = 62 + revLookup['_'.charCodeAt(0)] = 63 + + function placeHoldersCount (b64) { + var len = b64.length + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 + } + + function byteLength (b64) { + // base64 is 4/3 + up to two characters of the original data + return b64.length * 3 / 4 - placeHoldersCount(b64) + } + + function toByteArray (b64) { + var i, j, l, tmp, placeHolders, arr + var len = b64.length + placeHolders = placeHoldersCount(b64) + + arr = new Arr(len * 3 / 4 - placeHolders) + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len + + var L = 0 + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)] + arr[L++] = (tmp >> 16) & 0xFF + arr[L++] = (tmp >> 8) & 0xFF + arr[L++] = tmp & 0xFF + } + + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) + arr[L++] = tmp & 0xFF + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) + arr[L++] = (tmp >> 8) & 0xFF + arr[L++] = tmp & 0xFF + } + + return arr + } + + function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] + } + + function encodeChunk (uint8, start, end) { + var tmp + var output = [] + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) + output.push(tripletToBase64(tmp)) + } + return output.join('') + } + + function fromByteArray (uint8) { + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var output = '' + var parts = [] + var maxChunkLength = 16383 // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1] + output += lookup[tmp >> 2] + output += lookup[(tmp << 4) & 0x3F] + output += '==' + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]) + output += lookup[tmp >> 10] + output += lookup[(tmp >> 4) & 0x3F] + output += lookup[(tmp << 2) & 0x3F] + output += '=' + } + + parts.push(output) + + return parts.join('') + } + + +/***/ }, +/* 23 */ +/***/ function(module, exports) { + + exports.read = function (buffer, offset, isLE, mLen, nBytes) { + var e, m + var eLen = nBytes * 8 - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var nBits = -7 + var i = isLE ? (nBytes - 1) : 0 + var d = isLE ? -1 : 1 + var s = buffer[offset + i] + + i += d + + e = s & ((1 << (-nBits)) - 1) + s >>= (-nBits) + nBits += eLen + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1) + e >>= (-nBits) + nBits += mLen + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen) + e = e - eBias + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) + } + + exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c + var eLen = nBytes * 8 - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) + var i = isLE ? 0 : (nBytes - 1) + var d = isLE ? 1 : -1 + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 + + value = Math.abs(value) + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0 + e = eMax + } else { + e = Math.floor(Math.log(value) / Math.LN2) + if (value * (c = Math.pow(2, -e)) < 1) { + e-- + c *= 2 + } + if (e + eBias >= 1) { + value += rt / c + } else { + value += rt * Math.pow(2, 1 - eBias) + } + if (value * c >= 2) { + e++ + c /= 2 + } + + if (e + eBias >= eMax) { + m = 0 + e = eMax + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen) + e = e + eBias + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) + e = 0 + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m + eLen += mLen + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128 + } + + +/***/ }, +/* 24 */ +/***/ function(module, exports) { + + var toString = {}.toString; + + module.exports = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; + }; + + +/***/ }, +/* 25 */ +/***/ function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(Buffer) {// Copyright Joyent, Inc. and other Node contributors. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + // NOTE: These type checking functions intentionally don't use `instanceof` + // because it is fragile and can be easily faked with `Object.create()`. + + function isArray(arg) { + if (Array.isArray) { + return Array.isArray(arg); + } + return objectToString(arg) === '[object Array]'; + } + exports.isArray = isArray; + + function isBoolean(arg) { + return typeof arg === 'boolean'; + } + exports.isBoolean = isBoolean; + + function isNull(arg) { + return arg === null; + } + exports.isNull = isNull; + + function isNullOrUndefined(arg) { + return arg == null; + } + exports.isNullOrUndefined = isNullOrUndefined; + + function isNumber(arg) { + return typeof arg === 'number'; + } + exports.isNumber = isNumber; + + function isString(arg) { + return typeof arg === 'string'; + } + exports.isString = isString; + + function isSymbol(arg) { + return typeof arg === 'symbol'; + } + exports.isSymbol = isSymbol; + + function isUndefined(arg) { + return arg === void 0; + } + exports.isUndefined = isUndefined; + + function isRegExp(re) { + return objectToString(re) === '[object RegExp]'; + } + exports.isRegExp = isRegExp; + + function isObject(arg) { + return typeof arg === 'object' && arg !== null; + } + exports.isObject = isObject; + + function isDate(d) { + return objectToString(d) === '[object Date]'; + } + exports.isDate = isDate; + + function isError(e) { + return (objectToString(e) === '[object Error]' || e instanceof Error); + } + exports.isError = isError; + + function isFunction(arg) { + return typeof arg === 'function'; + } + exports.isFunction = isFunction; + + function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; + } + exports.isPrimitive = isPrimitive; + + exports.isBuffer = Buffer.isBuffer; + + function objectToString(o) { + return Object.prototype.toString.call(o); + } + + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(21).Buffer)) + +/***/ }, +/* 26 */ +/***/ function(module, exports) { + + /* (ignored) */ + +/***/ }, +/* 27 */ +/***/ function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(process) {// Copyright Joyent, Inc. and other Node contributors. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + // a duplex stream is just a stream that is both readable and writable. + // Since JS doesn't have multiple prototypal inheritance, this class + // prototypally inherits from Readable, and then parasitically from + // Writable. + + module.exports = Duplex; + + /**/ + var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) keys.push(key); + return keys; + } + /**/ + + + /**/ + var util = __webpack_require__(25); + util.inherits = __webpack_require__(16); + /**/ + + var Readable = __webpack_require__(19); + var Writable = __webpack_require__(28); + + util.inherits(Duplex, Readable); + + forEach(objectKeys(Writable.prototype), function(method) { + if (!Duplex.prototype[method]) + Duplex.prototype[method] = Writable.prototype[method]; + }); + + function Duplex(options) { + if (!(this instanceof Duplex)) + return new Duplex(options); + + Readable.call(this, options); + Writable.call(this, options); + + if (options && options.readable === false) + this.readable = false; + + if (options && options.writable === false) + this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) + this.allowHalfOpen = false; + + this.once('end', onend); + } + + // the no-half-open enforcer + function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) + return; + + // no more data can be written. + // But allow more writes to happen in this tick. + process.nextTick(this.end.bind(this)); + } + + function forEach (xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } + } + + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(18))) + +/***/ }, +/* 28 */ +/***/ function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(process) {// Copyright Joyent, Inc. and other Node contributors. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + // A bit simpler than readable streams. + // Implement an async ._write(chunk, cb), and it'll handle all + // the drain event emission and buffering. + + module.exports = Writable; + + /**/ + var Buffer = __webpack_require__(21).Buffer; + /**/ + + Writable.WritableState = WritableState; + + + /**/ + var util = __webpack_require__(25); + util.inherits = __webpack_require__(16); + /**/ + + var Stream = __webpack_require__(14); + + util.inherits(Writable, Stream); + + function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + } + + function WritableState(options, stream) { + var Duplex = __webpack_require__(27); + + options = options || {}; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var defaultHwm = options.objectMode ? 16 : 16 * 1024; + this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) + this.objectMode = this.objectMode || !!options.writableObjectMode; + + // cast to ints. + this.highWaterMark = ~~this.highWaterMark; + + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function(er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.buffer = []; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + } + + function Writable(options) { + var Duplex = __webpack_require__(27); + + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. + if (!(this instanceof Writable) && !(this instanceof Duplex)) + return new Writable(options); + + this._writableState = new WritableState(options, this); + + // legacy. + this.writable = true; + + Stream.call(this); + } + + // Otherwise people can pipe Writable streams, which is just wrong. + Writable.prototype.pipe = function() { + this.emit('error', new Error('Cannot pipe. Not readable.')); + }; + + + function writeAfterEnd(stream, state, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + process.nextTick(function() { + cb(er); + }); + } + + // If we get something that is not a buffer, string, null, or undefined, + // and we're not in objectMode, then that's an error. + // Otherwise stream chunks are all considered to be of length=1, and the + // watermarks determine how many objects to keep in the buffer, rather than + // how many bytes or characters. + function validChunk(stream, state, chunk, cb) { + var valid = true; + if (!util.isBuffer(chunk) && + !util.isString(chunk) && + !util.isNullOrUndefined(chunk) && + !state.objectMode) { + var er = new TypeError('Invalid non-string/buffer chunk'); + stream.emit('error', er); + process.nextTick(function() { + cb(er); + }); + valid = false; + } + return valid; + } + + Writable.prototype.write = function(chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + + if (util.isFunction(encoding)) { + cb = encoding; + encoding = null; + } + + if (util.isBuffer(chunk)) + encoding = 'buffer'; + else if (!encoding) + encoding = state.defaultEncoding; + + if (!util.isFunction(cb)) + cb = function() {}; + + if (state.ended) + writeAfterEnd(this, state, cb); + else if (validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, chunk, encoding, cb); + } + + return ret; + }; + + Writable.prototype.cork = function() { + var state = this._writableState; + + state.corked++; + }; + + Writable.prototype.uncork = function() { + var state = this._writableState; + + if (state.corked) { + state.corked--; + + if (!state.writing && + !state.corked && + !state.finished && + !state.bufferProcessing && + state.buffer.length) + clearBuffer(this, state); + } + }; + + function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && + state.decodeStrings !== false && + util.isString(chunk)) { + chunk = new Buffer(chunk, encoding); + } + return chunk; + } + + // if we're already writing something, then just put this + // in the queue, and wait our turn. Otherwise, call _write + // If we return false, then we need a drain event, so set that flag. + function writeOrBuffer(stream, state, chunk, encoding, cb) { + chunk = decodeChunk(state, chunk, encoding); + if (util.isBuffer(chunk)) + encoding = 'buffer'; + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) + state.needDrain = true; + + if (state.writing || state.corked) + state.buffer.push(new WriteReq(chunk, encoding, cb)); + else + doWrite(stream, state, false, len, chunk, encoding, cb); + + return ret; + } + + function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) + stream._writev(chunk, state.onwrite); + else + stream._write(chunk, encoding, state.onwrite); + state.sync = false; + } + + function onwriteError(stream, state, sync, er, cb) { + if (sync) + process.nextTick(function() { + state.pendingcb--; + cb(er); + }); + else { + state.pendingcb--; + cb(er); + } + + stream._writableState.errorEmitted = true; + stream.emit('error', er); + } + + function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; + } + + function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + onwriteStateUpdate(state); + + if (er) + onwriteError(stream, state, sync, er, cb); + else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(stream, state); + + if (!finished && + !state.corked && + !state.bufferProcessing && + state.buffer.length) { + clearBuffer(stream, state); + } + + if (sync) { + process.nextTick(function() { + afterWrite(stream, state, finished, cb); + }); + } else { + afterWrite(stream, state, finished, cb); + } + } + } + + function afterWrite(stream, state, finished, cb) { + if (!finished) + onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); + } + + // Must force callback to be called on nextTick, so that we don't + // emit 'drain' before the write() consumer gets the 'false' return + // value, and has a chance to attach a 'drain' listener. + function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } + } + + + // if there's something in the buffer waiting, then process it + function clearBuffer(stream, state) { + state.bufferProcessing = true; + + if (stream._writev && state.buffer.length > 1) { + // Fast case, write everything using _writev() + var cbs = []; + for (var c = 0; c < state.buffer.length; c++) + cbs.push(state.buffer[c].callback); + + // count the one we are adding, as well. + // TODO(isaacs) clean this up + state.pendingcb++; + doWrite(stream, state, true, state.length, state.buffer, '', function(err) { + for (var i = 0; i < cbs.length; i++) { + state.pendingcb--; + cbs[i](err); + } + }); + + // Clear buffer + state.buffer = []; + } else { + // Slow case, write chunks one-by-one + for (var c = 0; c < state.buffer.length; c++) { + var entry = state.buffer[c]; + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, false, len, chunk, encoding, cb); + + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + c++; + break; + } + } + + if (c < state.buffer.length) + state.buffer = state.buffer.slice(c); + else + state.buffer.length = 0; + } + + state.bufferProcessing = false; } - function create(cozy, data, options) { - var _ref2 = options || {}, - name = _ref2.name, - dirID = _ref2.dirID; + Writable.prototype._write = function(chunk, encoding, cb) { + cb(new Error('not implemented')); - // handle case where data is a file and contains the name + }; + Writable.prototype._writev = null; - if (!name && typeof data.name === 'string') { - name = data.name; + Writable.prototype.end = function(chunk, encoding, cb) { + var state = this._writableState; + + if (util.isFunction(chunk)) { + cb = chunk; + chunk = null; + encoding = null; + } else if (util.isFunction(encoding)) { + cb = encoding; + encoding = null; } - if (typeof name !== 'string' || name === '') { - throw new Error('missing name argument'); + if (!util.isNullOrUndefined(chunk)) + this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); } - var path = '/files/' + encodeURIComponent(dirID || ''); - var query = '?Name=' + encodeURIComponent(name) + '&Type=file'; - return doUpload(cozy, data, 'POST', '' + path + query, options); + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) + endWritable(this, state, cb); + }; + + + function needFinish(stream, state) { + return (state.ending && + state.length === 0 && + !state.finished && + !state.writing); } - function createDirectory(cozy, options) { - var _ref3 = options || {}, - name = _ref3.name, - dirID = _ref3.dirID; + function prefinish(stream, state) { + if (!state.prefinished) { + state.prefinished = true; + stream.emit('prefinish'); + } + } - if (typeof name !== 'string' || name === '') { - throw new Error('missing name argument'); + function finishMaybe(stream, state) { + var need = needFinish(stream, state); + if (need) { + if (state.pendingcb === 0) { + prefinish(stream, state); + state.finished = true; + stream.emit('finish'); + } else + prefinish(stream, state); } + return need; + } - var path = '/files/' + encodeURIComponent(dirID || ''); - var query = '?Name=' + encodeURIComponent(name) + '&Type=directory'; - return (0, _fetch.cozyFetchJSON)(cozy, 'POST', '' + path + query); + function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) + process.nextTick(cb); + else + stream.once('finish', cb); + } + state.ended = true; } - function updateById(cozy, id, data, options) { - return doUpload(cozy, data, 'PUT', '/files/' + encodeURIComponent(id), options); + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(18))) + +/***/ }, +/* 29 */ +/***/ function(module, exports, __webpack_require__) { + + // Copyright Joyent, Inc. and other Node contributors. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + var Buffer = __webpack_require__(21).Buffer; + + var isBufferEncoding = Buffer.isEncoding + || function(encoding) { + switch (encoding && encoding.toLowerCase()) { + case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; + default: return false; + } + } + + + function assertEncoding(encoding) { + if (encoding && !isBufferEncoding(encoding)) { + throw new Error('Unknown encoding: ' + encoding); + } } - function updateAttributesById(cozy, id, attrs) { - if (!attrs || (typeof attrs === 'undefined' ? 'undefined' : _typeof(attrs)) !== 'object') { - throw new Error('missing attrs argument'); + // StringDecoder provides an interface for efficiently splitting a series of + // buffers into a series of JS strings without breaking apart multi-byte + // characters. CESU-8 is handled as part of the UTF-8 encoding. + // + // @TODO Handling all encodings inside a single object makes it very difficult + // to reason about this code, so it should be split up in the future. + // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code + // points as used by CESU-8. + var StringDecoder = exports.StringDecoder = function(encoding) { + this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); + assertEncoding(encoding); + switch (this.encoding) { + case 'utf8': + // CESU-8 represents each of Surrogate Pair by 3-bytes + this.surrogateSize = 3; + break; + case 'ucs2': + case 'utf16le': + // UTF-16 represents each of Surrogate Pair by 2-bytes + this.surrogateSize = 2; + this.detectIncompleteChar = utf16DetectIncompleteChar; + break; + case 'base64': + // Base-64 stores 3 bytes in 4 chars, and pads the remainder. + this.surrogateSize = 3; + this.detectIncompleteChar = base64DetectIncompleteChar; + break; + default: + this.write = passThroughWrite; + return; } - var body = { data: { attributes: attrs } }; - return (0, _fetch.cozyFetchJSON)(cozy, 'PATCH', '/files/' + encodeURIComponent(id), body); - } + // Enough space to store all bytes of a single character. UTF-8 needs 4 + // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). + this.charBuffer = new Buffer(6); + // Number of bytes received for the current incomplete multi-byte character. + this.charReceived = 0; + // Number of bytes expected for the current incomplete multi-byte character. + this.charLength = 0; + }; - function updateAttributesByPath(cozy, path, attrs) { - if (!attrs || (typeof attrs === 'undefined' ? 'undefined' : _typeof(attrs)) !== 'object') { - throw new Error('missing attrs argument'); + + // write decodes the given buffer and returns it as JS string that is + // guaranteed to not contain any partial multi-byte characters. Any partial + // character found at the end of the buffer is buffered up, and will be + // returned when calling write again with the remaining bytes. + // + // Note: Converting a Buffer containing an orphan surrogate to a String + // currently works, but converting a String to a Buffer (via `new Buffer`, or + // Buffer#write) will replace incomplete surrogates with the unicode + // replacement character. See https://codereview.chromium.org/121173009/ . + StringDecoder.prototype.write = function(buffer) { + var charStr = ''; + // if our last write ended with an incomplete multibyte character + while (this.charLength) { + // determine how many remaining bytes this buffer has to offer for this char + var available = (buffer.length >= this.charLength - this.charReceived) ? + this.charLength - this.charReceived : + buffer.length; + + // add the new bytes to the char buffer + buffer.copy(this.charBuffer, this.charReceived, 0, available); + this.charReceived += available; + + if (this.charReceived < this.charLength) { + // still not enough chars in this buffer? wait for more ... + return ''; + } + + // remove bytes belonging to the current character from the buffer + buffer = buffer.slice(available, buffer.length); + + // get the character that was split + charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); + + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + var charCode = charStr.charCodeAt(charStr.length - 1); + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + this.charLength += this.surrogateSize; + charStr = ''; + continue; + } + this.charReceived = this.charLength = 0; + + // if there are no more bytes in this buffer, just emit our char + if (buffer.length === 0) { + return charStr; + } + break; } - var body = { data: { attributes: attrs } }; - return (0, _fetch.cozyFetchJSON)(cozy, 'PATCH', '/files/metadata?Path=' + encodeURIComponent(path), body); - } + // determine and set charLength / charReceived + this.detectIncompleteChar(buffer); - function trashById(cozy, id) { - if (typeof id !== 'string' || id === '') { - throw new Error('missing id argument'); + var end = buffer.length; + if (this.charLength) { + // buffer the incomplete character bytes we got + buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); + end -= this.charReceived; } - return (0, _fetch.cozyFetchJSON)(cozy, 'DELETE', '/files/' + encodeURIComponent(id)); - } - function statById(cozy, id) { - var offline = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; + charStr += buffer.toString(this.encoding, 0, end); + + var end = charStr.length - 1; + var charCode = charStr.charCodeAt(end); + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + var size = this.surrogateSize; + this.charLength += size; + this.charReceived += size; + this.charBuffer.copy(this.charBuffer, size, 0, size); + buffer.copy(this.charBuffer, 0, 0, size); + return charStr.substring(0, end); + } - if (offline && cozy.offline.hasDatabase(_doctypes.DOCTYPE_FILES)) { - var db = cozy.offline.getDatabase(_doctypes.DOCTYPE_FILES); - return Promise.all([db.get(id), db.find({ selector: { 'dir_id': id } })]).then(function (_ref4) { - var _ref5 = _slicedToArray(_ref4, 2), - doc = _ref5[0], - children = _ref5[1]; + // or just emit the charStr + return charStr; + }; - children = children.docs.map(function (doc) { - return addIsDir(toJsonApi(cozy, doc)); - }); - return addIsDir(toJsonApi(cozy, doc, children)); - }); + // detectIncompleteChar determines if there is an incomplete UTF-8 character at + // the end of the given buffer. If so, it sets this.charLength to the byte + // length that character, and sets this.charReceived to the number of bytes + // that are available for this character. + StringDecoder.prototype.detectIncompleteChar = function(buffer) { + // determine how many bytes we have to check at the end of this buffer + var i = (buffer.length >= 3) ? 3 : buffer.length; + + // Figure out if one of the last i bytes of our buffer announces an + // incomplete char. + for (; i > 0; i--) { + var c = buffer[buffer.length - i]; + + // See http://en.wikipedia.org/wiki/UTF-8#Description + + // 110XXXXX + if (i == 1 && c >> 5 == 0x06) { + this.charLength = 2; + break; + } + + // 1110XXXX + if (i <= 2 && c >> 4 == 0x0E) { + this.charLength = 3; + break; + } + + // 11110XXX + if (i <= 3 && c >> 3 == 0x1E) { + this.charLength = 4; + break; + } } - return (0, _fetch.cozyFetchJSON)(cozy, 'GET', '/files/' + encodeURIComponent(id)).then(addIsDir); - } + this.charReceived = i; + }; - function statByPath(cozy, path) { - return (0, _fetch.cozyFetchJSON)(cozy, 'GET', '/files/metadata?Path=' + encodeURIComponent(path)).then(addIsDir); - } + StringDecoder.prototype.end = function(buffer) { + var res = ''; + if (buffer && buffer.length) + res = this.write(buffer); - function downloadById(cozy, id) { - return (0, _fetch.cozyFetch)(cozy, '/files/download/' + encodeURIComponent(id)); - } + if (this.charReceived) { + var cr = this.charReceived; + var buf = this.charBuffer; + var enc = this.encoding; + res += buf.slice(0, cr).toString(enc); + } - function downloadByPath(cozy, path) { - return (0, _fetch.cozyFetch)(cozy, '/files/download?Path=' + encodeURIComponent(path)); + return res; + }; + + function passThroughWrite(buffer) { + return buffer.toString(this.encoding); } - function extractResponseLinkRelated(res) { - var href = res.links && res.links.related; - if (!href) throw new Error('No related link in server response'); - return href; + function utf16DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 2; + this.charLength = this.charReceived ? 2 : 0; } - function getDowloadLink(cozy, path) { - return (0, _fetch.cozyFetchJSON)(cozy, 'POST', '/files/downloads?Path=' + encodeURIComponent(path)).then(extractResponseLinkRelated); + function base64DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 3; + this.charLength = this.charReceived ? 3 : 0; } + + +/***/ }, +/* 30 */ +/***/ function(module, exports, __webpack_require__) { + + // Copyright Joyent, Inc. and other Node contributors. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + + // a transform stream is a readable/writable stream where you do + // something with the data. Sometimes it's called a "filter", + // but that's not a great name for it, since that implies a thing where + // some bits pass through, and others are simply ignored. (That would + // be a valid example of a transform, of course.) + // + // While the output is causally related to the input, it's not a + // necessarily symmetric or synchronous transformation. For example, + // a zlib stream might take multiple plain-text writes(), and then + // emit a single compressed chunk some time in the future. + // + // Here's how this works: + // + // The Transform stream has all the aspects of the readable and writable + // stream classes. When you write(chunk), that calls _write(chunk,cb) + // internally, and returns false if there's a lot of pending writes + // buffered up. When you call read(), that calls _read(n) until + // there's enough pending readable data buffered up. + // + // In a transform stream, the written data is placed in a buffer. When + // _read(n) is called, it transforms the queued up data, calling the + // buffered _write cb's as it consumes chunks. If consuming a single + // written chunk would result in multiple output chunks, then the first + // outputted bit calls the readcb, and subsequent chunks just go into + // the read buffer, and will cause it to emit 'readable' if necessary. + // + // This way, back-pressure is actually determined by the reading side, + // since _read has to be called to start processing a new chunk. However, + // a pathological inflate type of transform can cause excessive buffering + // here. For example, imagine a stream where every byte of input is + // interpreted as an integer from 0-255, and then results in that many + // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in + // 1kb of data being output. In this case, you could write a very small + // amount of input, and end up with a very large amount of output. In + // such a pathological inflating mechanism, there'd be no way to tell + // the system to stop doing the transform. A single 4MB write could + // cause the system to run out of memory. + // + // However, even in such a pathological case, only a single written chunk + // would be consumed, and then the rest would wait (un-transformed) until + // the results of the previous transformed chunk were consumed. - function getArchiveLink(cozy, paths) { - var name = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'files'; + module.exports = Transform; - var archive = { - type: 'io.cozy.archives', - attributes: { - name: name, - files: paths - } + var Duplex = __webpack_require__(27); + + /**/ + var util = __webpack_require__(25); + util.inherits = __webpack_require__(16); + /**/ + + util.inherits(Transform, Duplex); + + + function TransformState(options, stream) { + this.afterTransform = function(er, data) { + return afterTransform(stream, er, data); }; - return (0, _fetch.cozyFetchJSON)(cozy, 'POST', '/files/archive', { data: archive }).then(extractResponseLinkRelated); - } - function listTrash(cozy) { - return (0, _fetch.cozyFetchJSON)(cozy, 'GET', '/files/trash'); + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; } - function clearTrash(cozy) { - return (0, _fetch.cozyFetchJSON)(cozy, 'DELETE', '/files/trash'); - } + function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; - function restoreById(cozy, id) { - return (0, _fetch.cozyFetchJSON)(cozy, 'POST', '/files/trash/' + encodeURIComponent(id)); + var cb = ts.writecb; + + if (!cb) + return stream.emit('error', new Error('no writecb in Transform class')); + + ts.writechunk = null; + ts.writecb = null; + + if (!util.isNullOrUndefined(data)) + stream.push(data); + + if (cb) + cb(er); + + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); + } } - function destroyById(cozy, id) { - return (0, _fetch.cozyFetchJSON)(cozy, 'DELETE', '/files/trash/' + encodeURIComponent(id)); + + function Transform(options) { + if (!(this instanceof Transform)) + return new Transform(options); + + Duplex.call(this, options); + + this._transformState = new TransformState(options, this); + + // when the writable side finishes, then flush out anything remaining. + var stream = this; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + + this.once('prefinish', function() { + if (util.isFunction(this._flush)) + this._flush(function(er) { + done(stream, er); + }); + else + done(stream); + }); } - function addIsDir(obj) { - obj.isDir = obj.attributes.type === 'directory'; - return obj; + Transform.prototype.push = function(chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); + }; + + // This is the part where you do stuff! + // override this function in implementation classes. + // 'chunk' is an input chunk. + // + // Call `push(newChunk)` to pass along transformed output + // to the readable side. You may call 'push' zero or more times. + // + // Call `cb(err)` when you are done with this chunk. If you pass + // an error, then that'll put the hurt on the whole operation. If you + // never call cb(), then you'll never get another chunk. + Transform.prototype._transform = function(chunk, encoding, cb) { + throw new Error('not implemented'); + }; + + Transform.prototype._write = function(chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || + rs.needReadable || + rs.length < rs.highWaterMark) + this._read(rs.highWaterMark); + } + }; + + // Doesn't matter what the args are here. + // _transform does all the work. + // That we got here means that the readable side wants more data. + Transform.prototype._read = function(n) { + var ts = this._transformState; + + if (!util.isNull(ts.writechunk) && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } + }; + + + function done(stream, er) { + if (er) + return stream.emit('error', er); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var ts = stream._transformState; + + if (ws.length) + throw new Error('calling transform done when ws.length != 0'); + + if (ts.transforming) + throw new Error('calling transform done when still transforming'); + + return stream.push(null); } + + +/***/ }, +/* 31 */ +/***/ function(module, exports, __webpack_require__) { + + // Copyright Joyent, Inc. and other Node contributors. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. - function toJsonApi(cozy, doc) { - var contents = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; + // a passthrough stream. + // basically just the most minimal sort of Transform stream. + // Every written chunk gets output as-is. - var clone = JSON.parse(JSON.stringify(doc)); - delete clone._id; - delete clone._rev; - return { - _id: doc._id, - _rev: doc._rev, - _type: _doctypes.DOCTYPE_FILES, - attributes: clone, - relations: function relations(name) { - if (name === 'contents') { - return contents; - } - } - }; + module.exports = PassThrough; + + var Transform = __webpack_require__(30); + + /**/ + var util = __webpack_require__(25); + util.inherits = __webpack_require__(16); + /**/ + + util.inherits(PassThrough, Transform); + + function PassThrough(options) { + if (!(this instanceof PassThrough)) + return new PassThrough(options); + + Transform.call(this, options); } + + PassThrough.prototype._transform = function(chunk, encoding, cb) { + cb(null, chunk); + }; + /***/ }, -/* 14 */ +/* 32 */ +/***/ function(module, exports, __webpack_require__) { + + module.exports = __webpack_require__(28) + + +/***/ }, +/* 33 */ +/***/ function(module, exports, __webpack_require__) { + + module.exports = __webpack_require__(27) + + +/***/ }, +/* 34 */ +/***/ function(module, exports, __webpack_require__) { + + module.exports = __webpack_require__(30) + + +/***/ }, +/* 35 */ +/***/ function(module, exports, __webpack_require__) { + + module.exports = __webpack_require__(31) + + +/***/ }, +/* 36 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -2622,11 +7518,11 @@ return /******/ (function(modules) { // webpackBootstrap exports.stopSync = stopSync; exports.replicateFromCozy = replicateFromCozy; - var _pouchdb = __webpack_require__(15); + var _pouchdb = __webpack_require__(37); var _pouchdb2 = _interopRequireDefault(_pouchdb); - var _pouchdbFind = __webpack_require__(16); + var _pouchdbFind = __webpack_require__(38); var _pouchdbFind2 = _interopRequireDefault(_pouchdbFind); @@ -2838,19 +7734,19 @@ return /******/ (function(modules) { // webpackBootstrap } /***/ }, -/* 15 */ +/* 37 */ /***/ function(module, exports) { - module.exports = __WEBPACK_EXTERNAL_MODULE_15__; + module.exports = __WEBPACK_EXTERNAL_MODULE_37__; /***/ }, -/* 16 */ +/* 38 */ /***/ function(module, exports) { - module.exports = __WEBPACK_EXTERNAL_MODULE_16__; + module.exports = __WEBPACK_EXTERNAL_MODULE_38__; /***/ }, -/* 17 */ +/* 39 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -2867,7 +7763,7 @@ return /******/ (function(modules) { // webpackBootstrap } /***/ }, -/* 18 */ +/* 40 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; diff --git a/dist/cozy-client.js.map b/dist/cozy-client.js.map index f3cec053..425c7f30 100644 --- a/dist/cozy-client.js.map +++ b/dist/cozy-client.js.map @@ -1 +1 @@ -{"version":3,"sources":["webpack:///webpack/universalModuleDefinition","webpack:///webpack/bootstrap b53f6c90274b1de549f7","webpack:///./~/isomorphic-fetch/fetch-npm-browserify.js","webpack:///./~/whatwg-fetch/fetch.js","webpack:///./src/index.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/crud.js","webpack:///./src/doctypes.js","webpack:///./src/mango.js","webpack:///./src/files.js","webpack:///./src/offline.js","webpack:///external \"pouchdb\"","webpack:///external \"pouchdb-find\"","webpack:///./src/settings.js","webpack:///./src/relations.js"],"names":["auth","crud","mango","files","offline","settings","relations","AppTokenV3","AppToken","AccessTokenV3","AccessToken","ClientV3","Client","AuthNone","AuthRunning","AuthError","AuthOK","defaultClientParams","softwareID","mainProto","create","find","update","delete","_delete","updateAttributes","defineIndex","query","addReferencedFiles","listReferencedFiles","destroy","authProto","registerClient","updateClient","unregisterClient","getClient","getAuthCodeURL","getAccessToken","refreshToken","filesProto","createDirectory","updateById","updateAttributesById","updateAttributesByPath","trashById","statById","statByPath","downloadById","downloadByPath","getDowloadLink","getArchiveLink","listTrash","clearTrash","restoreById","destroyById","offlineProto","init","getDoctypes","createDatabase","hasDatabase","getDatabase","destroyDatabase","replicateFromCozy","hasSync","startAllSync","startSync","stopAllSync","stopSync","settingsProto","diskUsage","Cozy","options","AppTokenV2","LocalStorage","MemoryStorage","_inited","_oauth","_token","_authstate","_authcreds","_storage","_version","_offline","token","oauth","Error","storage","_clientParams","Object","assign","clientParams","_onRegistered","onRegistered","nopOnRegistered","url","cozyURL","length","slice","_url","disablePromises","addToProto","state","isV2","then","oauthFlow","Promise","resolve","client","creds","save","CredsKey","path","pathprefix","fetch","res","ok","json","status","datasystem","undefined","protoify","context","fn","prototyped","args","ctx","obj","proto","attr","cozy","window","unpromiser","isPromise","sleep","retry","getFuzzedDelay","getBackedoffDelay","createPath","encodeQuery","decodeQuery","warn","FuzzFactor","value","apply","l","cb","err","time","setTimeout","count","delay","doTry","catch","retryDelay","fuzzingFactor","Math","random","retryCount","pow","doctype","id","route","encodeURIComponent","q","qname","queryIndex","indexOf","queries","fragIndex","queryStr","parts","split","i","pair","decodeURIComponent","hasOwnProperty","warned","text","push","console","prefix","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","data","e","removeEventListener","clearTimeout","addEventListener","opts","btoa","StateSize","StateKey","clientID","client_id","clientSecret","client_secret","registrationAccessToken","registration_access_token","redirect_uris","redirectURI","software_id","softwareVersion","software_version","clientName","client_name","clientKind","client_kind","clientURI","client_uri","logoURI","logo_uri","policyURI","policy_uri","tokenType","token_type","accessToken","access_token","refresh_token","scope","isRegistered","toRegisterJSON","disableAuth","resetSecret","createClient","manualAuthCredentials","oldClient","newClient","shouldPassRegistration","scopes","generateRandomState","join","pageURL","grantQueries","getGrantCodeFromPageURL","retrieveToken","code","tryCount","clearAndRetry","clear","registerNewClient","all","load","credentials","storedState","isUnauthorized","statePromise","t","body","headers","href","buffer","crypto","getRandomValues","Uint8Array","require","randomBytes","Array","floor","String","fromCharCode","replace","cozyFetch","cozyFetchJSON","fullpath","resp","cozyFetchWithAuth","authorize","handleResponse","toAuthHeader","newToken","saveCredentials","method","handleJSONResponse","contentType","get","FetchError","reason","response","indexKey","doc","type","findByRef","resources","ref","handleResource","rawResource","links","resource","_id","_type","_rev","meta","rev","attributes","name","rels","relationships","isArray","map","handleTopLevel","included","forEach","r","NOREV","docType","changes","tries","normalizeDoctype","DOCTYPE_FILES","KNOWN_DOCTYPES","REVERSE_KNOWN","keys","k","isQualified","known","parseSelector","normalizeSelector","makeMapReduceQuery","fields","defineIndexV2","defineIndexV3","indexRef","queryV2","queryV3","VALUEOPERATORS","LOGICOPERATORS","MAP_TEMPLATE","toLowerCase","emit","FIELDSPLACEHOLDER","toString","COUCHDB_INFINITY","COUCHDB_LOWEST","indexName","capitalize","indexDefinition","makeMapFunction","reduce","use_index","selector","limit","since","descending","sort","f","docs","charAt","toUpperCase","operator","acc","concat","filters","filter","op","field","applySelector","lower","upper","inclusiveEnd","startkey","endkey","inclusive_end","mrquery","firstFreeValueField","normalizedSelector","used","isFreeValue","contentTypeOctetStream","doUpload","ArrayBuffer","isBuffer","isFile","File","isBlob","Blob","isString","lastModifiedDate","Date","toISOString","dirID","attrs","db","children","addIsDir","toJsonApi","extractResponseLinkRelated","related","paths","archive","isDir","contents","clone","pluginLoaded","doctypes","timer","plugin","database","autoSync","createIndexes","setInterval","replicate","on","info","replication","cancel","clearInterval","events","live","from","eventNames","eventName","createIndex","index","ids","refs","makeReferencesPath","file"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,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;;AAEP,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,MAAK;AACL;AACA;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;;AAEA;AACA,+BAA8B,uBAAuB;AACrD;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;;AAEA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;;AA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,IAAd,EAAoB,KAApB,EAA2BoT,mBAAmBxI,GAAnB,CAA3B,EACJtM,IADI,CACC,UAACpG,KAAD;AAAA,YAAWA,MAAM6T,GAAN,CAAU,UAACsH,IAAD;AAAA,cAAUA,KAAKhI,GAAf;AAAA,MAAV,CAAX;AAAA,IADD,CAAP;AAED;;AAED,UAAS+H,kBAAT,CAA6BxI,GAA7B,EAAkC;AAChC,OAAMC,OAAO5I,mBAAmB2I,IAAIU,KAAvB,CAAb;AACA,OAAMvJ,KAAKE,mBAAmB2I,IAAIS,GAAvB,CAAX;AACA,qBAAgBR,IAAhB,SAAwB9I,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(require(\"pouchdb\"), require(\"pouchdb-find\"));\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine(\"cozy-client-js\", [\"pouchdb\", \"pouchdb-find\"], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"cozy-client-js\"] = factory(require(\"pouchdb\"), require(\"pouchdb-find\"));\n\telse\n\t\troot[\"cozy-client-js\"] = factory(root[\"pouchdb\"], root[\"pouchdb-find\"]);\n})(this, function(__WEBPACK_EXTERNAL_MODULE_15__, __WEBPACK_EXTERNAL_MODULE_16__) {\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 b53f6c90274b1de549f7","// 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\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 (typeof input === 'string') {\n this.url = input\n } else {\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 }\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 */\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 crud from './crud'\nimport * as mango from './mango'\nimport * as files from './files'\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 mainProto = {\n create: crud.create,\n find: crud.find,\n update: crud.update,\n delete: crud._delete,\n updateAttributes: crud.updateAttributes,\n defineIndex: mango.defineIndex,\n query: mango.query,\n addReferencedFiles: relations.addReferencedFiles,\n listReferencedFiles: relations.listReferencedFiles,\n destroy: function (...args) {\n warn('destroy is deprecated, use cozy.delete instead.')\n return crud._delete(...args)\n }\n}\n\nconst authProto = {\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 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 getDowloadLink: files.getDowloadLink,\n getArchiveLink: files.getArchiveLink,\n listTrash: files.listTrash,\n clearTrash: files.clearTrash,\n restoreById: files.restoreById,\n destroyById: files.destroyById\n}\n\nconst offlineProto = {\n init: offline.init,\n getDoctypes: offline.getDoctypes,\n // database\n createDatabase: offline.createDatabase,\n hasDatabase: offline.hasDatabase,\n getDatabase: offline.getDatabase,\n destroyDatabase: offline.destroyDatabase,\n // replication\n replicateFromCozy: offline.replicateFromCozy,\n hasSync: offline.hasSync,\n startAllSync: offline.startAllSync,\n startSync: offline.startSync,\n stopAllSync: offline.stopAllSync,\n stopSync: offline.stopSync\n}\n\nconst settingsProto = {\n diskUsage: settings.diskUsage\n}\n\nclass Cozy {\n constructor (options) {\n this.files = {}\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 = null\n this._offline = null\n\n const token = options.token\n const oauth = options.oauth\n if (token && oauth) {\n throw new Error('Cannot specify an application token with a oauth activated')\n }\n\n if (token) {\n this._token = new AppTokenV3({ token })\n } else if (oauth) {\n this._oauth = true\n this._storage = oauth.storage\n this._clientParams = Object.assign({}, defaultClientParams, oauth.clientParams)\n this._onRegistered = oauth.onRegistered || nopOnRegistered\n }\n\n let url = options.cozyURL || ''\n while (url[url.length - 1] === '/') {\n url = url.slice(0, -1)\n }\n\n this._url = url\n\n const disablePromises = !!options.disablePromises\n addToProto(this, this, mainProto, disablePromises)\n addToProto(this, this.auth, authProto, disablePromises)\n addToProto(this, this.files, filesProto, 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\n authorize () {\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 return auth.oauthFlow(\n this,\n this._storage,\n this._clientParams,\n this._onRegistered\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 this._version = 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) => status.datasystem !== undefined)\n }\n return this._version\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\nconst cozy = new Cozy()\n\nexport default cozy\nexport { Cozy, LocalStorage, MemoryStorage }\n\nif ((typeof window) !== 'undefined') {\n window.cozy = cozy\n window.Cozy = Cozy\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/index.js","const 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 return\n }\n}\n\nexport function isPromise (value) {\n return !!value && typeof value.then === 'function'\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} from './utils'\nimport {cozyFetchJSON, FetchError} from './fetch'\n\nconst StateSize = 16\n\nexport const CredsKey = 'creds'\nexport const StateKey = 'state'\n\nexport class Client {\n constructor (opts) {\n this.clientID = opts.clientID || opts.client_id || ''\n this.clientSecret = opts.clientSecret || opts.client_secret || ''\n this.registrationAccessToken = opts.registrationAccessToken || opts.registration_access_token || ''\n\n if (opts.redirect_uris) {\n this.redirectURI = opts.redirect_uris[0] || ''\n } else {\n this.redirectURI = opts.redirectURI || ''\n }\n\n this.softwareID = opts.softwareID || opts.software_id || ''\n this.softwareVersion = opts.softwareVersion || opts.software_version || ''\n this.clientName = opts.clientName || opts.client_name || ''\n this.clientKind = opts.clientKind || opts.client_kind || ''\n this.clientURI = opts.clientURI || opts.client_uri || ''\n\n this.logoURI = opts.logoURI || opts.logo_uri || ''\n this.policyURI = opts.policyURI || opts.policy_uri || ''\n\n if (this.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 isRegistered () {\n return this.clientID !== ''\n }\n\n toRegisterJSON () {\n return {\n redirect_uris: [this.redirectURI],\n software_id: this.softwareID,\n software_version: this.softwareVersion,\n client_name: this.clientName,\n client_kind: this.clientKind,\n client_uri: this.clientURI,\n logo_uri: this.logoURI,\n policy_uri: this.policyURI\n }\n }\n\n toAuthHeader () {\n return 'Bearer ' + this.registrationAccessToken\n }\n}\n\nexport class AccessToken {\n constructor (opts) {\n this.tokenType = opts.tokenType || opts.token_type\n this.accessToken = opts.accessToken || opts.access_token\n this.refreshToken = opts.refreshToken || opts.refresh_token\n this.scope = opts.scope\n }\n\n toAuthHeader () {\n return 'Bearer ' + this.accessToken\n }\n}\n\nexport class AppToken {\n constructor (opts) {\n this.token = opts.token || ''\n }\n\n toAuthHeader () {\n return 'Bearer ' + this.token\n }\n}\n\nexport function registerClient (cozy, client) {\n if (!(client instanceof Client)) {\n client = new Client(client)\n }\n if (client.isRegistered()) {\n return Promise.reject(new Error('Client already registered'))\n }\n return cozyFetchJSON(cozy, 'POST', '/auth/register', client.toRegisterJSON(), {\n disableAuth: true\n })\n .then((data) => new Client(data))\n}\n\nexport function updateClient (cozy, client, resetSecret = false) {\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 let data = client.toRegisterJSON()\n data.client_id = client.clientID\n if (resetSecret) data.client_secret = client.clientSecret\n\n return cozyFetchJSON(cozy, 'PUT', `/auth/register/${client.clientID}`, data)\n .then((data) => createClient(data, client))\n}\n\nexport function unregisterClient (cozy, client) {\n return cozyFetchJSON(cozy, 'DELETE', `/auth/register/${client.clientID}`)\n}\n\n// getClient will retrive the registered client informations from the server.\nexport function getClient (cozy, client) {\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 return cozyFetchJSON(cozy, 'GET', `/auth/register/${client.clientID}`, null, {\n manualAuthCredentials: {\n client: client,\n token: client\n }\n })\n .then((data) => createClient(data, client))\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 'code': 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) {\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 ])\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)) {\n throw err\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 manualAuthCredentials: { client, token },\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' }\n })\n .then((data) => new AccessToken(data))\n}\n\n// getGrantCodeFromPageURL extract the state and access_code query parameters\n// from the given url\nfunction getGrantCodeFromPageURL (pageURL = '') {\n if (pageURL === '' && typeof window !== 'undefined') {\n pageURL = window.location.href\n }\n const queries = decodeQuery(pageURL)\n if (!queries.hasOwnProperty('state')) {\n return null\n }\n return {\n state: queries['state'],\n code: queries['access_code']\n }\n}\n\n// generateRandomState will try to generate a 128bits random value from a secure\n// pseudo random generator. It will fallback on Math.random if it cannot find\n// such generator.\nfunction generateRandomState () {\n let buffer\n if (typeof window !== 'undefined' &&\n typeof window.crypto !== 'undefined' &&\n typeof window.crypto.getRandomValues === 'function') {\n buffer = new Uint8Array(StateSize)\n window.crypto.getRandomValues(buffer)\n } else {\n try {\n buffer = require('crypto').randomBytes(StateSize)\n } catch (e) {}\n }\n if (!buffer) {\n buffer = new Array(StateSize)\n for (let i = 0; i < buffer.length; i++) {\n buffer[i] = Math.floor((Math.random() * 255))\n }\n }\n return btoa(String.fromCharCode.apply(null, buffer))\n .replace(/=+$/, '')\n .replace(/\\//g, '_')\n .replace(/\\+/g, '-')\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/auth_v3.js","/* global fetch */\nimport {refreshToken, AccessToken} from './auth_v3'\nimport {retry} from './utils'\nimport jsonapi from './jsonapi'\n\nexport function cozyFetch (cozy, path, options = {}) {\n return cozy.fullpath(path).then((fullpath) => {\n let resp\n if (options.disableAuth) {\n resp = fetch(fullpath, options)\n } else if (options.manualAuthCredentials) {\n resp = cozyFetchWithAuth(cozy, fullpath, options, options.manualAuthCredentials)\n } else {\n resp = cozy.authorize().then((credentials) =>\n cozyFetchWithAuth(cozy, fullpath, options, credentials))\n }\n return resp.then(handleResponse)\n })\n}\n\nfunction cozyFetchWithAuth (cozy, fullpath, options, credentials) {\n if (credentials) {\n options.headers = options.headers || {}\n options.headers['Authorization'] = credentials.token.toAuthHeader()\n }\n\n // the option credentials:include tells fetch to include the cookies in the\n // request even for cross-origin requests\n options.credentials = 'include'\n\n return Promise.all([\n cozy.isV2(),\n fetch(fullpath, options)\n ]).then(([isV2, res]) => {\n if (res.status !== 401 || isV2 || !credentials) {\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 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 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 .then(handleJSONResponse)\n}\n\nfunction handleResponse (res) {\n if (res.ok) {\n return res\n }\n let data\n const contentType = res.headers.get('content-type')\n if (contentType && contentType.indexOf('json') >= 0) {\n data = res.json()\n } else {\n data = res.text()\n }\n return data.then(err => {\n throw new FetchError(res, err)\n })\n}\n\nfunction handleJSONResponse (res) {\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) {\n return json.then(jsonapi)\n } else {\n return json\n }\n}\n\nexport class FetchError {\n constructor (res, reason) {\n this.response = res\n this.url = res.url\n this.status = res.status\n this.reason = reason\n }\n\n isUnauthorized () {\n return this.status === 401\n }\n}\n\nFetchError.isUnauthorized = function (err) {\n return (err instanceof FetchError && err.isUnauthorized())\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\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)\n return cozyFetchJSON(cozy, 'POST', 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 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/crud.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} from './utils'\nimport {normalizeDoctype} from './doctypes'\nimport {cozyFetchJSON} 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\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\n// defineIndexV2 is equivalent to defineIndex but only works for V2.\n// It transforms the index fields into a map reduce view.\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) => ({ doctype: doctype, type: 'mango', name: response.id, fields: fields }))\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 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 since: options.since\n }\n\n if (options.descending) {\n opts.sort = indexRef.fields.map(f => ({ [f]: 'desc' }))\n }\n\n let path = createPath(cozy, false, indexRef.doctype, '_find')\n return cozyFetchJSON(cozy, 'POST', path, opts)\n .then((response) => response.docs)\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\nconst contentTypeOctetStream = 'application/octet-stream'\n\nfunction doUpload (cozy, data, method, path, options) {\n if (!data) {\n throw new Error('missing data argument')\n }\n\n // transform any ArrayBufferView to ArrayBuffer\n if (data.buffer && data.buffer instanceof ArrayBuffer) {\n data = data.buffer\n }\n\n const isBuffer = (typeof ArrayBuffer !== 'undefined' && data instanceof ArrayBuffer)\n const isFile = (typeof File !== 'undefined' && data instanceof File)\n const isBlob = (typeof Blob !== 'undefined' && data instanceof Blob)\n const isString = (typeof data === 'string')\n\n if (!isBuffer && !isFile && !isBlob && !isString) {\n throw new Error('invalid data type')\n }\n\n let {contentType, lastModifiedDate} = options || {}\n if (!contentType) {\n if (isBuffer) {\n contentType = contentTypeOctetStream\n } else if (isFile) {\n contentType = data.type || contentTypeOctetStream\n if (!lastModifiedDate) {\n lastModifiedDate = data.lastModifiedDate\n }\n } else if (isBlob) {\n contentType = contentTypeOctetStream\n } else if (typeof data === 'string') {\n contentType = 'text/plain'\n }\n }\n\n if (lastModifiedDate && typeof lastModifiedDate === 'string') {\n lastModifiedDate = new Date(lastModifiedDate)\n }\n\n return cozyFetch(cozy, path, {\n method: method,\n headers: {\n 'Content-Type': contentType,\n 'Date': lastModifiedDate ? lastModifiedDate.toISOString() : ''\n },\n body: data\n })\n .then((res) => {\n const json = res.json()\n if (!res.ok) {\n return json.then(err => { throw err })\n } else {\n return json.then(jsonapi)\n }\n })\n}\n\nexport function create (cozy, data, options) {\n let {name, dirID} = options || {}\n\n // handle case where data is a file and contains the name\n if (!name && typeof data.name === 'string') {\n name = data.name\n }\n\n if (typeof name !== 'string' || name === '') {\n throw new Error('missing name argument')\n }\n\n const path = `/files/${encodeURIComponent(dirID || '')}`\n const query = `?Name=${encodeURIComponent(name)}&Type=file`\n return doUpload(cozy, data, 'POST', `${path}${query}`, options)\n}\n\nexport function createDirectory (cozy, options) {\n const {name, dirID} = options || {}\n\n if (typeof name !== 'string' || name === '') {\n throw new Error('missing name argument')\n }\n\n const path = `/files/${encodeURIComponent(dirID || '')}`\n const query = `?Name=${encodeURIComponent(name)}&Type=directory`\n return cozyFetchJSON(cozy, 'POST', `${path}${query}`)\n}\n\nexport function updateById (cozy, id, data, options) {\n return doUpload(cozy, data, 'PUT', `/files/${encodeURIComponent(id)}`, options)\n}\n\nexport function updateAttributesById (cozy, id, attrs) {\n if (!attrs || typeof attrs !== 'object') {\n throw new Error('missing attrs argument')\n }\n\n const body = { data: { attributes: attrs } }\n return cozyFetchJSON(cozy, 'PATCH',\n `/files/${encodeURIComponent(id)}`, body)\n}\n\nexport function updateAttributesByPath (cozy, path, attrs) {\n if (!attrs || typeof attrs !== 'object') {\n throw new Error('missing attrs argument')\n }\n\n const body = { data: { attributes: attrs } }\n return cozyFetchJSON(cozy, 'PATCH',\n `/files/metadata?Path=${encodeURIComponent(path)}`, body)\n}\n\nexport function trashById (cozy, id) {\n if (typeof id !== 'string' || id === '') {\n throw new Error('missing id argument')\n }\n return cozyFetchJSON(cozy, 'DELETE', `/files/${encodeURIComponent(id)}`)\n}\n\nexport function statById (cozy, id, offline = true) {\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({selector: {'dir_id': id}})\n ]).then(([doc, children]) => {\n children = children.docs.map(doc => {\n return addIsDir(toJsonApi(cozy, doc))\n })\n return addIsDir(toJsonApi(cozy, doc, children))\n })\n }\n return cozyFetchJSON(cozy, 'GET', `/files/${encodeURIComponent(id)}`)\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 getDowloadLink (cozy, path) {\n return cozyFetchJSON(cozy, 'POST', `/files/downloads?Path=${encodeURIComponent(path)}`)\n .then(extractResponseLinkRelated)\n}\n\nexport function getArchiveLink (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 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) {\n return cozyFetchJSON(cozy, 'DELETE', `/files/trash/${encodeURIComponent(id)}`)\n}\n\nfunction addIsDir (obj) {\n obj.isDir = obj.attributes.type === 'directory'\n return obj\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 relations: (name) => {\n if (name === 'contents') {\n return contents\n }\n }\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/files.js","import PouchDB from 'pouchdb'\nimport pouchdbFind from 'pouchdb-find'\nimport { DOCTYPE_FILES } from './doctypes'\n\nlet pluginLoaded = false\n\nexport function init (cozy, { options = {}, doctypes = [], timer = false }) {\n for (let doctype of doctypes) {\n createDatabase(cozy, doctype, options)\n }\n if (timer) { startAllSync(cozy, timer) }\n}\n\nexport function createDatabase (cozy, doctype, options = {}, timer = false) {\n if (!pluginLoaded) {\n PouchDB.plugin(pouchdbFind)\n pluginLoaded = true\n }\n cozy._offline = cozy._offline || []\n cozy._offline[doctype] = cozy._offline[doctype] || {}\n let offline = cozy._offline[doctype]\n if (offline && offline.database) { return offline.database }\n offline.database = new PouchDB(doctype, options)\n offline.timer = timer\n offline.autoSync = null\n if (timer) { startSync(cozy, doctype, timer) }\n createIndexes(cozy, offline.database, doctype)\n return offline.database\n}\n\nexport function hasDatabase (cozy, doctype) {\n return cozy._offline !== null &&\n doctype in cozy._offline &&\n cozy._offline[doctype].database !== undefined\n}\n\nexport function getDatabase (cozy, doctype) {\n if (hasDatabase(cozy, doctype)) {\n return cozy._offline[doctype].database\n }\n return\n}\n\nexport function destroyDatabase (cozy, doctype) {\n if (hasDatabase(cozy, doctype)) {\n stopSync(cozy, doctype)\n getDatabase(cozy, doctype).destroy()\n delete getDatabase(cozy, doctype)\n }\n}\n\nexport function getDoctypes (cozy) {\n if (cozy._offline === null) { return [] }\n return Object.keys(cozy._offline)\n}\n\n//\n// SYNC\n//\n\nexport function startAllSync (cozy, timer) {\n if (timer) {\n const doctypes = getDoctypes(cozy)\n doctypes.forEach((doctype) => {\n startSync(cozy, doctype, timer)\n })\n }\n}\n\nexport function stopAllSync (cozy) {\n const doctypes = getDoctypes(cozy)\n doctypes.forEach((doctype) => {\n stopSync(cozy, doctype)\n })\n}\n\nexport function startSync (cozy, doctype, timer) {\n // TODO: add timer limitation for not flooding Gozy\n if (hasDatabase(cozy, doctype)) {\n if (hasSync(cozy, doctype)) {\n if (timer === cozy._offline[doctype].timer) { return }\n stopSync(cozy, doctype)\n }\n let offline = cozy._offline[doctype]\n offline.timer = timer\n offline.autoSync = setInterval(() => {\n if (offline.replicate === undefined) {\n offline.replicate = replicateFromCozy(cozy, doctype)\n .on('complete', (info) => {\n delete offline.replicate\n })\n // TODO: add replicationToCozy\n }\n }, timer * 1000)\n }\n}\n\nexport function hasSync (cozy, doctype) {\n return cozy._offline !== null &&\n doctype in cozy._offline &&\n cozy._offline[doctype].autoSync !== null\n}\n\nexport function stopSync (cozy, doctype) {\n if (hasSync(cozy, doctype)) {\n let offline = cozy._offline[doctype]\n if (offline.replication) { offline.replication.cancel() }\n clearInterval(offline.autoSync)\n delete offline.autoSync\n }\n}\n\nexport function replicateFromCozy (cozy, doctype, options = {}, events = {}) {\n if (hasDatabase(cozy, doctype)) {\n if (options.live === true) {\n throw new Error('You can\\'t use `live` option with Cozy couchdb.')\n }\n const url = cozy._url + '/data/' + doctype\n let db = getDatabase(cozy, doctype)\n let replication = db.replicate.from(url, options)\n const eventNames = [\n 'change', 'paused', 'active', 'denied', 'complete', 'error'\n ]\n for (let eventName of eventNames) {\n if (typeof events[eventName] === 'function') {\n replication.on(eventName, events[eventName])\n }\n }\n return replication\n } else {\n throw new Error(`You should add this doctype: ${doctype} to offline.`)\n }\n}\n\nfunction createIndexes (cozy, db, doctype) {\n if (doctype === DOCTYPE_FILES) {\n db.createIndex({index: {fields: ['dir_id']}})\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/offline.js","module.exports = __WEBPACK_EXTERNAL_MODULE_15__;\n\n\n//////////////////\n// WEBPACK FOOTER\n// external \"pouchdb\"\n// module id = 15\n// module chunks = 0","module.exports = __WEBPACK_EXTERNAL_MODULE_16__;\n\n\n//////////////////\n// WEBPACK FOOTER\n// external \"pouchdb-find\"\n// module id = 16\n// module chunks = 0","import {cozyFetchJSON} from './fetch'\n\nexport function diskUsage (cozy) {\n return cozyFetchJSON(cozy, 'GET', `/settings/disk-usage`)\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/settings.js","import {cozyFetchJSON} from './fetch'\nimport { DOCTYPE_FILES } from './doctypes'\n\nexport function addReferencedFiles (cozy, doc, ids) {\n if (!doc) throw new Error('missing doc argument')\n if (!Array.isArray(ids)) ids = [ids]\n\n const refs = ids.map((id) => ({type: DOCTYPE_FILES, id: id}))\n\n return cozyFetchJSON(cozy, 'POST', makeReferencesPath(doc), {data: refs})\n}\n\nexport function listReferencedFiles (cozy, doc) {\n if (!doc) throw new Error('missing doc argument')\n return cozyFetchJSON(cozy, 'GET', makeReferencesPath(doc))\n .then((files) => files.map((file) => file._id))\n}\n\nfunction makeReferencesPath (doc) {\n const type = encodeURIComponent(doc._type)\n const id = encodeURIComponent(doc._id)\n return `/data/${type}/${id}/relationships/references`\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/relations.js"],"sourceRoot":""} \ No newline at end of file +{"version":3,"sources":["webpack:///webpack/universalModuleDefinition","webpack:///webpack/bootstrap 9fd762492a84e90d8bde","webpack:///./~/isomorphic-fetch/fetch-npm-browserify.js","webpack:///./~/whatwg-fetch/fetch.js","webpack:///./src/index.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/crud.js","webpack:///./src/doctypes.js","webpack:///./src/mango.js","webpack:///./src/files.js","webpack:///./~/stream-browserify/index.js","webpack:///./~/events/events.js","webpack:///./~/inherits/inherits_browser.js","webpack:///./~/readable-stream/readable.js","webpack:///./~/process/browser.js","webpack:///./~/readable-stream/lib/_stream_readable.js","webpack:///./~/isarray/index.js","webpack:///./~/buffer/index.js","webpack:///./~/base64-js/index.js","webpack:///./~/ieee754/index.js","webpack:///./~/buffer/~/isarray/index.js","webpack:///./~/core-util-is/lib/util.js","webpack:///util (ignored)","webpack:///./~/readable-stream/lib/_stream_duplex.js","webpack:///./~/readable-stream/lib/_stream_writable.js","webpack:///./~/string_decoder/index.js","webpack:///./~/readable-stream/lib/_stream_transform.js","webpack:///./~/readable-stream/lib/_stream_passthrough.js","webpack:///./~/readable-stream/writable.js","webpack:///./~/readable-stream/duplex.js","webpack:///./~/readable-stream/transform.js","webpack:///./~/readable-stream/passthrough.js","webpack:///./src/offline.js","webpack:///external \"pouchdb\"","webpack:///external \"pouchdb-find\"","webpack:///./src/settings.js","webpack:///./src/relations.js"],"names":["auth","crud","mango","files","offline","settings","relations","AppTokenV3","AppToken","AccessTokenV3","AccessToken","ClientV3","Client","AuthNone","AuthRunning","AuthError","AuthOK","defaultClientParams","softwareID","mainProto","create","find","update","delete","_delete","updateAttributes","defineIndex","query","addReferencedFiles","listReferencedFiles","destroy","authProto","registerClient","updateClient","unregisterClient","getClient","getAuthCodeURL","getAccessToken","refreshToken","filesProto","createDirectory","updateById","updateAttributesById","updateAttributesByPath","trashById","statById","statByPath","downloadById","downloadByPath","getDowloadLink","getArchiveLink","listTrash","clearTrash","restoreById","destroyById","offlineProto","init","getDoctypes","createDatabase","hasDatabase","getDatabase","destroyDatabase","replicateFromCozy","hasSync","startAllSync","startSync","stopAllSync","stopSync","settingsProto","diskUsage","Cozy","options","AppTokenV2","LocalStorage","MemoryStorage","_inited","_oauth","_token","_authstate","_authcreds","_storage","_version","_offline","token","oauth","Error","storage","_clientParams","Object","assign","clientParams","_onRegistered","onRegistered","nopOnRegistered","url","cozyURL","length","slice","_url","disablePromises","addToProto","state","isV2","then","oauthFlow","Promise","resolve","client","creds","save","CredsKey","path","pathprefix","fetch","res","ok","json","status","datasystem","undefined","protoify","context","fn","prototyped","args","ctx","obj","proto","attr","cozy","window","unpromiser","isPromise","sleep","retry","getFuzzedDelay","getBackedoffDelay","createPath","encodeQuery","decodeQuery","warn","FuzzFactor","value","apply","l","cb","err","time","setTimeout","count","delay","doTry","catch","retryDelay","fuzzingFactor","Math","random","retryCount","pow","doctype","id","route","encodeURIComponent","q","qname","queryIndex","indexOf","queries","fragIndex","queryStr","parts","split","i","pair","decodeURIComponent","hasOwnProperty","warned","text","push","console","prefix","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","data","e","removeEventListener","clearTimeout","addEventListener","opts","btoa","StateSize","StateKey","clientID","client_id","clientSecret","client_secret","registrationAccessToken","registration_access_token","redirect_uris","redirectURI","software_id","softwareVersion","software_version","clientName","client_name","clientKind","client_kind","clientURI","client_uri","logoURI","logo_uri","policyURI","policy_uri","tokenType","token_type","accessToken","access_token","refresh_token","scope","isRegistered","toRegisterJSON","disableAuth","resetSecret","createClient","manualAuthCredentials","oldClient","newClient","shouldPassRegistration","scopes","generateRandomState","join","pageURL","grantQueries","getGrantCodeFromPageURL","retrieveToken","code","tryCount","clearAndRetry","clear","registerNewClient","all","load","credentials","storedState","isUnauthorized","statePromise","t","body","headers","href","buffer","crypto","getRandomValues","Uint8Array","require","randomBytes","Array","floor","String","fromCharCode","replace","cozyFetch","cozyFetchJSON","fullpath","resp","cozyFetchWithAuth","authorize","handleResponse","toAuthHeader","newToken","saveCredentials","method","handleJSONResponse","contentType","get","FetchError","reason","response","indexKey","doc","type","findByRef","resources","ref","handleResource","rawResource","links","resource","_id","_type","_rev","meta","rev","attributes","name","rels","relationships","isArray","map","handleTopLevel","included","forEach","r","NOREV","docType","changes","tries","normalizeDoctype","DOCTYPE_FILES","KNOWN_DOCTYPES","REVERSE_KNOWN","keys","k","isQualified","known","parseSelector","normalizeSelector","makeMapReduceQuery","fields","defineIndexV2","defineIndexV3","indexRef","queryV2","queryV3","VALUEOPERATORS","LOGICOPERATORS","MAP_TEMPLATE","toLowerCase","emit","FIELDSPLACEHOLDER","toString","COUCHDB_INFINITY","COUCHDB_LOWEST","indexName","capitalize","indexDefinition","makeMapFunction","reduce","use_index","selector","limit","since","descending","sort","f","docs","charAt","toUpperCase","operator","acc","concat","filters","filter","op","field","applySelector","lower","upper","inclusiveEnd","startkey","endkey","inclusive_end","mrquery","firstFreeValueField","normalizedSelector","used","isFreeValue","Readable","_","contentTypeOctetStream","doUpload","ArrayBuffer","isBuffer","isFile","File","isBlob","Blob","isStream","isString","lastModifiedDate","Date","toGMTString","dirID","attrs","db","children","addIsDir","toJsonApi","extractResponseLinkRelated","related","paths","archive","isDir","contents","clone","pluginLoaded","doctypes","timer","plugin","database","autoSync","createIndexes","setInterval","replicate","on","info","replication","cancel","clearInterval","events","live","from","eventNames","eventName","createIndex","index","ids","refs","makeReferencesPath","file"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,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;;AAEP,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,MAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAC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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;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACTA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAS;AACT;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA;AACA,UAAS;AACT;AACA;AACA,MAAK;AACL;AACA;AACA,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA,UAAS;AACT;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA,UAAS;AACT;AACA;AACA;AACA;AACA;;;;AAIA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,wBAAuB,sBAAsB;AAC7C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sBAAqB;AACrB;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA,4BAA2B;AAC3B;AACA;AACA;AACA,6BAA4B,UAAU;;;;;;;ACnLtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;;AAGA;AACA;AACA;;AAEA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;;AAEA;;;AAGA;AACA;AACA;AACA;AACA,EAAC;AACD;AACA;AACA;;;AAGA;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA,MAAK;AACL;AACA;AACA,MAAK;AACL;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA,IAAG;AACH;AACA;;AAEA;AACA;;;;AAIA;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,IAAG;AACH;AACA;AACA,oBAAmB,QAAQ;AAC3B;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;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;;AAEA;AACA;AACA;;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;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;;AAGA;AACA;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;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;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;;AAEA;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;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;;;;AAIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,oBAAmB,SAAS;AAC5B;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAS;AACT,QAAO;AACP;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,MAAK;AACL;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,IAAG;;AAEH;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,IAAG;;AAEH;AACA;AACA;AACA;AACA,mCAAkC;AAClC;AACA,SAAQ;AACR;AACA;;AAEA;AACA;AACA;AACA;AACA,IAAG;;AAEH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;;;AAIA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,uCAAsC,gBAAgB;AACtD;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;;AAEA;AACA,iCAAgC,OAAO;AACvC;AACA;AACA;;AAEA;AACA,iCAAgC,OAAO;AACvC;AACA;AACA;AACA;;;;;;;;ACt7BA;AACA;AACA;;;;;;;ACFA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;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;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,sBAAqB,mDAAmD;AACxE;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;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;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;;AAEA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;;AAEA;AACA;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,oBAAmB,UAAU;AAC7B;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,kBAAiB,YAAY;AAC7B;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA,IAAG;AACH;AACA,IAAG;AACH;AACA;;AAEA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,2BAA0B;AAC1B;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;;AAEA,wCAAuC,SAAS;AAChD;AACA;AACA;AACA;AACA;AACA;;AAEA;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;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,gBAAe,iBAAiB;AAChC;AACA;AACA;;AAEA;AACA;AACA,cAAa,iBAAiB;AAC9B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,UAAS;AACT;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;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;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,kBAAiB,SAAS;AAC1B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,kBAAiB,SAAS;AAC1B;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,kBAAiB,SAAS;AAC1B;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,iDAAgD,EAAE;AAClD;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA,kBAAiB,SAAS;AAC1B;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,0CAAyC;AACzC;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA,IAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;;AAEA;AACA;AACA;AACA,yBAAwB,eAAe;AACvC;AACA;AACA;AACA,QAAO;AACP;AACA;AACA;AACA;AACA,IAAG;AACH;AACA,yBAAwB,QAAQ;AAChC;AACA,sBAAqB,eAAe;AACpC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,kBAAiB,YAAY;AAC7B;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA,UAAS;AACT;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;;AAEA;AACA;AACA;;AAEA;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;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;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA,sBAAqB,SAAS;AAC9B;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA,sBAAqB,SAAS;AAC9B;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA,sBAAqB,SAAS;AAC9B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,kBAAiB,kBAAkB;AACnC;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,IAAG;AACH;AACA;;AAEA;AACA;AACA;AACA,IAAG;AACH;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA,oBAAmB,cAAc;AACjC;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,wDAAuD,OAAO;AAC9D;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;;AAEA;AACA;AACA,wDAAuD,OAAO;AAC9D;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,mBAAkB;AAClB;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,sBAAqB,QAAQ;AAC7B;AACA;AACA,IAAG;AACH;AACA,gBAAe,SAAS;AACxB;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA,oBAAmB,SAAS;AAC5B;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;AACA,gBAAe,iBAAiB;AAChC;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA,kBAAiB,YAAY;AAC7B;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAS;AACT;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,MAAK;AACL;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,kBAAiB,gBAAgB;AACjC;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,kBAAiB,gBAAgB;AACjC;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA,kBAAiB,YAAY;AAC7B;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;;;;;;;AC5vDA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA,mCAAkC,SAAS;AAC3C;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;;AAEA;;AAEA,qBAAoB,OAAO;AAC3B;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,sBAAqB,SAAS;AAC9B;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,2CAA0C,UAAU;AACpD;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;;;;;;;ACjHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA,SAAQ,WAAW;;AAEnB;AACA;AACA;AACA,SAAQ,WAAW;;AAEnB;AACA;AACA,IAAG;AACH;AACA,IAAG;AACH;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;;AAEA,SAAQ,WAAW;;AAEnB;AACA;AACA,SAAQ,UAAU;;AAElB;AACA;;;;;;;ACnFA,kBAAiB;;AAEjB;AACA;AACA;;;;;;;ACJA;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;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;;;;;;;AC1GA,gB;;;;;;ACAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA;AACA,EAAC;;AAED;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA,iCAAgC,OAAO;AACvC;AACA;AACA;;;;;;;;ACxFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;;;AAGA;AACA;AACA;AACA;;AAEA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA,IAAG;AACH;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,QAAO;AACP,MAAK;AACL;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA;;AAEA;AACA;AACA;AACA,oBAAmB,yBAAyB;AAC5C;;AAEA;AACA;AACA;AACA;AACA,sBAAqB,gBAAgB;AACrC;AACA;AACA;AACA,MAAK;;AAEL;AACA;AACA,IAAG;AACH;AACA,oBAAmB,yBAAyB;AAC5C;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;AC5dA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;;AAGA;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;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,SAAQ,OAAO;AACf;;AAEA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;;;;;;AC5NA;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;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,2CAA0C,YAAY;AACtD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;;AAEA;AACA;AACA;AACA;;AAEA;;;AAGA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA;;AAEA;;AAEA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA,IAAG;AACH;;AAEA;AACA;AACA;AACA;;AAEA;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;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,IAAG;AACH;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;;;;;;AChNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;;;;;;AC7CA;;;;;;;ACAA;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sB9I,IAAIA,EAA1B,EAAT;AAAA,IAAR,CAAb;;AAEA,UAAO,0BAAc/B,IAAd,EAAoB,MAApB,EAA4BuT,mBAAmB3I,GAAnB,CAA5B,EAAqD,EAAChG,MAAM0O,IAAP,EAArD,CAAP;AACD;;AAEM,UAAS1Z,mBAAT,CAA8BoG,IAA9B,EAAoC4K,GAApC,EAAyC;AAC9C,OAAI,CAACA,GAAL,EAAU,MAAM,IAAIxN,KAAJ,CAAU,sBAAV,CAAN;AACV,UAAO,0BAAc4C,IAAd,EAAoB,KAApB,EAA2BuT,mBAAmB3I,GAAnB,CAA3B,EACJtM,IADI,CACC,UAACpG,KAAD;AAAA,YAAWA,MAAM6T,GAAN,CAAU,UAACyH,IAAD;AAAA,cAAUA,KAAKnI,GAAf;AAAA,MAAV,CAAX;AAAA,IADD,CAAP;AAED;;AAED,UAASkI,kBAAT,CAA6B3I,GAA7B,EAAkC;AAChC,OAAMC,OAAO5I,mBAAmB2I,IAAIU,KAAvB,CAAb;AACA,OAAMvJ,KAAKE,mBAAmB2I,IAAIS,GAAvB,CAAX;AACA,qBAAgBR,IAAhB,SAAwB9I,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(require(\"pouchdb\"), require(\"pouchdb-find\"));\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine(\"cozy-client-js\", [\"pouchdb\", \"pouchdb-find\"], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"cozy-client-js\"] = factory(require(\"pouchdb\"), require(\"pouchdb-find\"));\n\telse\n\t\troot[\"cozy-client-js\"] = factory(root[\"pouchdb\"], root[\"pouchdb-find\"]);\n})(this, function(__WEBPACK_EXTERNAL_MODULE_37__, __WEBPACK_EXTERNAL_MODULE_38__) {\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 9fd762492a84e90d8bde","// 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\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 (typeof input === 'string') {\n this.url = input\n } else {\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 }\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 */\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 crud from './crud'\nimport * as mango from './mango'\nimport * as files from './files'\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 mainProto = {\n create: crud.create,\n find: crud.find,\n update: crud.update,\n delete: crud._delete,\n updateAttributes: crud.updateAttributes,\n defineIndex: mango.defineIndex,\n query: mango.query,\n addReferencedFiles: relations.addReferencedFiles,\n listReferencedFiles: relations.listReferencedFiles,\n destroy: function (...args) {\n warn('destroy is deprecated, use cozy.delete instead.')\n return crud._delete(...args)\n }\n}\n\nconst authProto = {\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 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 getDowloadLink: files.getDowloadLink,\n getArchiveLink: files.getArchiveLink,\n listTrash: files.listTrash,\n clearTrash: files.clearTrash,\n restoreById: files.restoreById,\n destroyById: files.destroyById\n}\n\nconst offlineProto = {\n init: offline.init,\n getDoctypes: offline.getDoctypes,\n // database\n createDatabase: offline.createDatabase,\n hasDatabase: offline.hasDatabase,\n getDatabase: offline.getDatabase,\n destroyDatabase: offline.destroyDatabase,\n // replication\n replicateFromCozy: offline.replicateFromCozy,\n hasSync: offline.hasSync,\n startAllSync: offline.startAllSync,\n startSync: offline.startSync,\n stopAllSync: offline.stopAllSync,\n stopSync: offline.stopSync\n}\n\nconst settingsProto = {\n diskUsage: settings.diskUsage\n}\n\nclass Cozy {\n constructor (options) {\n this.files = {}\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 = null\n this._offline = null\n\n const token = options.token\n const oauth = options.oauth\n if (token && oauth) {\n throw new Error('Cannot specify an application token with a oauth activated')\n }\n\n if (token) {\n this._token = new AppTokenV3({ token })\n } else if (oauth) {\n this._oauth = true\n this._storage = oauth.storage\n this._clientParams = Object.assign({}, defaultClientParams, oauth.clientParams)\n this._onRegistered = oauth.onRegistered || nopOnRegistered\n }\n\n let url = options.cozyURL || ''\n while (url[url.length - 1] === '/') {\n url = url.slice(0, -1)\n }\n\n this._url = url\n\n const disablePromises = !!options.disablePromises\n addToProto(this, this, mainProto, disablePromises)\n addToProto(this, this.auth, authProto, disablePromises)\n addToProto(this, this.files, filesProto, 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\n authorize () {\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 return auth.oauthFlow(\n this,\n this._storage,\n this._clientParams,\n this._onRegistered\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 this._version = 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) => status.datasystem !== undefined)\n }\n return this._version\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\nconst cozy = new Cozy()\n\nexport default cozy\nexport { Cozy, LocalStorage, MemoryStorage }\n\nif ((typeof window) !== 'undefined') {\n window.cozy = cozy\n window.Cozy = Cozy\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/index.js","const 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 return\n }\n}\n\nexport function isPromise (value) {\n return !!value && typeof value.then === 'function'\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} from './utils'\nimport {cozyFetchJSON, FetchError} from './fetch'\n\nconst StateSize = 16\n\nexport const CredsKey = 'creds'\nexport const StateKey = 'state'\n\nexport class Client {\n constructor (opts) {\n this.clientID = opts.clientID || opts.client_id || ''\n this.clientSecret = opts.clientSecret || opts.client_secret || ''\n this.registrationAccessToken = opts.registrationAccessToken || opts.registration_access_token || ''\n\n if (opts.redirect_uris) {\n this.redirectURI = opts.redirect_uris[0] || ''\n } else {\n this.redirectURI = opts.redirectURI || ''\n }\n\n this.softwareID = opts.softwareID || opts.software_id || ''\n this.softwareVersion = opts.softwareVersion || opts.software_version || ''\n this.clientName = opts.clientName || opts.client_name || ''\n this.clientKind = opts.clientKind || opts.client_kind || ''\n this.clientURI = opts.clientURI || opts.client_uri || ''\n\n this.logoURI = opts.logoURI || opts.logo_uri || ''\n this.policyURI = opts.policyURI || opts.policy_uri || ''\n\n if (this.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 isRegistered () {\n return this.clientID !== ''\n }\n\n toRegisterJSON () {\n return {\n redirect_uris: [this.redirectURI],\n software_id: this.softwareID,\n software_version: this.softwareVersion,\n client_name: this.clientName,\n client_kind: this.clientKind,\n client_uri: this.clientURI,\n logo_uri: this.logoURI,\n policy_uri: this.policyURI\n }\n }\n\n toAuthHeader () {\n return 'Bearer ' + this.registrationAccessToken\n }\n}\n\nexport class AccessToken {\n constructor (opts) {\n this.tokenType = opts.tokenType || opts.token_type\n this.accessToken = opts.accessToken || opts.access_token\n this.refreshToken = opts.refreshToken || opts.refresh_token\n this.scope = opts.scope\n }\n\n toAuthHeader () {\n return 'Bearer ' + this.accessToken\n }\n}\n\nexport class AppToken {\n constructor (opts) {\n this.token = opts.token || ''\n }\n\n toAuthHeader () {\n return 'Bearer ' + this.token\n }\n}\n\nexport function registerClient (cozy, client) {\n if (!(client instanceof Client)) {\n client = new Client(client)\n }\n if (client.isRegistered()) {\n return Promise.reject(new Error('Client already registered'))\n }\n return cozyFetchJSON(cozy, 'POST', '/auth/register', client.toRegisterJSON(), {\n disableAuth: true\n })\n .then((data) => new Client(data))\n}\n\nexport function updateClient (cozy, client, resetSecret = false) {\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 let data = client.toRegisterJSON()\n data.client_id = client.clientID\n if (resetSecret) data.client_secret = client.clientSecret\n\n return cozyFetchJSON(cozy, 'PUT', `/auth/register/${client.clientID}`, data)\n .then((data) => createClient(data, client))\n}\n\nexport function unregisterClient (cozy, client) {\n return cozyFetchJSON(cozy, 'DELETE', `/auth/register/${client.clientID}`)\n}\n\n// getClient will retrive the registered client informations from the server.\nexport function getClient (cozy, client) {\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 return cozyFetchJSON(cozy, 'GET', `/auth/register/${client.clientID}`, null, {\n manualAuthCredentials: {\n client: client,\n token: client\n }\n })\n .then((data) => createClient(data, client))\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 'code': 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) {\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 ])\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)) {\n throw err\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 manualAuthCredentials: { client, token },\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' }\n })\n .then((data) => new AccessToken(data))\n}\n\n// getGrantCodeFromPageURL extract the state and access_code query parameters\n// from the given url\nfunction getGrantCodeFromPageURL (pageURL = '') {\n if (pageURL === '' && typeof window !== 'undefined') {\n pageURL = window.location.href\n }\n const queries = decodeQuery(pageURL)\n if (!queries.hasOwnProperty('state')) {\n return null\n }\n return {\n state: queries['state'],\n code: queries['access_code']\n }\n}\n\n// generateRandomState will try to generate a 128bits random value from a secure\n// pseudo random generator. It will fallback on Math.random if it cannot find\n// such generator.\nfunction generateRandomState () {\n let buffer\n if (typeof window !== 'undefined' &&\n typeof window.crypto !== 'undefined' &&\n typeof window.crypto.getRandomValues === 'function') {\n buffer = new Uint8Array(StateSize)\n window.crypto.getRandomValues(buffer)\n } else {\n try {\n buffer = require('crypto').randomBytes(StateSize)\n } catch (e) {}\n }\n if (!buffer) {\n buffer = new Array(StateSize)\n for (let i = 0; i < buffer.length; i++) {\n buffer[i] = Math.floor((Math.random() * 255))\n }\n }\n return btoa(String.fromCharCode.apply(null, buffer))\n .replace(/=+$/, '')\n .replace(/\\//g, '_')\n .replace(/\\+/g, '-')\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/auth_v3.js","/* global fetch */\nimport {refreshToken, AccessToken} from './auth_v3'\nimport {retry} from './utils'\nimport jsonapi from './jsonapi'\n\nexport function cozyFetch (cozy, path, options = {}) {\n return cozy.fullpath(path).then((fullpath) => {\n let resp\n if (options.disableAuth) {\n resp = fetch(fullpath, options)\n } else if (options.manualAuthCredentials) {\n resp = cozyFetchWithAuth(cozy, fullpath, options, options.manualAuthCredentials)\n } else {\n resp = cozy.authorize().then((credentials) =>\n cozyFetchWithAuth(cozy, fullpath, options, credentials))\n }\n return resp.then(handleResponse)\n })\n}\n\nfunction cozyFetchWithAuth (cozy, fullpath, options, credentials) {\n if (credentials) {\n options.headers = options.headers || {}\n options.headers['Authorization'] = credentials.token.toAuthHeader()\n }\n\n // the option credentials:include tells fetch to include the cookies in the\n // request even for cross-origin requests\n options.credentials = 'include'\n\n return Promise.all([\n cozy.isV2(),\n fetch(fullpath, options)\n ]).then(([isV2, res]) => {\n if (res.status !== 401 || isV2 || !credentials) {\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 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 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 .then(handleJSONResponse)\n}\n\nfunction handleResponse (res) {\n if (res.ok) {\n return res\n }\n let data\n const contentType = res.headers.get('content-type')\n if (contentType && contentType.indexOf('json') >= 0) {\n data = res.json()\n } else {\n data = res.text()\n }\n return data.then(err => {\n throw new FetchError(res, err)\n })\n}\n\nfunction handleJSONResponse (res) {\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) {\n return json.then(jsonapi)\n } else {\n return json\n }\n}\n\nexport class FetchError {\n constructor (res, reason) {\n this.response = res\n this.url = res.url\n this.status = res.status\n this.reason = reason\n }\n\n isUnauthorized () {\n return this.status === 401\n }\n}\n\nFetchError.isUnauthorized = function (err) {\n return (err instanceof FetchError && err.isUnauthorized())\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\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)\n return cozyFetchJSON(cozy, 'POST', 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 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/crud.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} from './utils'\nimport {normalizeDoctype} from './doctypes'\nimport {cozyFetchJSON} 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\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\n// defineIndexV2 is equivalent to defineIndex but only works for V2.\n// It transforms the index fields into a map reduce view.\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) => ({ doctype: doctype, type: 'mango', name: response.id, fields: fields }))\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 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 since: options.since\n }\n\n if (options.descending) {\n opts.sort = indexRef.fields.map(f => ({ [f]: 'desc' }))\n }\n\n let path = createPath(cozy, false, indexRef.doctype, '_find')\n return cozyFetchJSON(cozy, 'POST', path, opts)\n .then((response) => response.docs)\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\nlet Readable\ntry {\n Readable = require('stream').Readable\n} catch (_) {}\n\nconst contentTypeOctetStream = 'application/octet-stream'\n\nfunction doUpload (cozy, data, method, path, options) {\n if (!data) {\n throw new Error('missing data argument')\n }\n\n // transform any ArrayBufferView to ArrayBuffer\n if (data.buffer && data.buffer instanceof ArrayBuffer) {\n data = data.buffer\n }\n\n const isBuffer = (typeof ArrayBuffer !== 'undefined' && data instanceof ArrayBuffer)\n const isFile = (typeof File !== 'undefined' && data instanceof File)\n const isBlob = (typeof Blob !== 'undefined' && data instanceof Blob)\n const isStream = (typeof Readable !== 'undefined' && data instanceof Readable)\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, lastModifiedDate} = options || {}\n if (!contentType) {\n if (isBuffer) {\n contentType = contentTypeOctetStream\n } else if (isFile) {\n contentType = data.type || contentTypeOctetStream\n if (!lastModifiedDate) {\n lastModifiedDate = data.lastModifiedDate\n }\n } else if (isBlob) {\n contentType = contentTypeOctetStream\n } else if (isStream) {\n contentType = contentTypeOctetStream\n } else if (typeof data === 'string') {\n contentType = 'text/plain'\n }\n }\n\n if (lastModifiedDate && typeof lastModifiedDate === 'string') {\n lastModifiedDate = new Date(lastModifiedDate)\n }\n\n return cozyFetch(cozy, path, {\n method: method,\n headers: {\n 'Content-Type': contentType,\n 'Date': lastModifiedDate ? lastModifiedDate.toGMTString() : ''\n },\n body: data\n })\n .then((res) => {\n const json = res.json()\n if (!res.ok) {\n return json.then(err => { throw err })\n } else {\n return json.then(jsonapi)\n }\n })\n}\n\nexport function create (cozy, data, options) {\n let {name, dirID} = options || {}\n\n // handle case where data is a file and contains the name\n if (!name && typeof data.name === 'string') {\n name = data.name\n }\n\n if (typeof name !== 'string' || name === '') {\n throw new Error('missing name argument')\n }\n\n const path = `/files/${encodeURIComponent(dirID || '')}`\n const query = `?Name=${encodeURIComponent(name)}&Type=file`\n return doUpload(cozy, data, 'POST', `${path}${query}`, options)\n}\n\nexport function createDirectory (cozy, options) {\n let {name, dirID, lastModifiedDate} = options || {}\n\n if (typeof name !== 'string' || name === '') {\n throw new Error('missing name argument')\n }\n\n if (lastModifiedDate && typeof lastModifiedDate === 'string') {\n lastModifiedDate = new Date(lastModifiedDate)\n }\n\n const path = `/files/${encodeURIComponent(dirID || '')}`\n const query = `?Name=${encodeURIComponent(name)}&Type=directory`\n return cozyFetchJSON(cozy, 'POST', `${path}${query}`, undefined, {\n headers: {\n 'Date': lastModifiedDate ? lastModifiedDate.toGMTString() : ''\n }\n })\n}\n\nexport function updateById (cozy, id, data, options) {\n return doUpload(cozy, data, 'PUT', `/files/${encodeURIComponent(id)}`, options)\n}\n\nexport function updateAttributesById (cozy, id, attrs) {\n if (!attrs || typeof attrs !== 'object') {\n throw new Error('missing attrs argument')\n }\n\n const body = { data: { attributes: attrs } }\n return cozyFetchJSON(cozy, 'PATCH',\n `/files/${encodeURIComponent(id)}`, body)\n}\n\nexport function updateAttributesByPath (cozy, path, attrs) {\n if (!attrs || typeof attrs !== 'object') {\n throw new Error('missing attrs argument')\n }\n\n const body = { data: { attributes: attrs } }\n return cozyFetchJSON(cozy, 'PATCH',\n `/files/metadata?Path=${encodeURIComponent(path)}`, body)\n}\n\nexport function trashById (cozy, id) {\n if (typeof id !== 'string' || id === '') {\n throw new Error('missing id argument')\n }\n return cozyFetchJSON(cozy, 'DELETE', `/files/${encodeURIComponent(id)}`)\n}\n\nexport function statById (cozy, id, offline = true) {\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({selector: {'dir_id': id}})\n ]).then(([doc, children]) => {\n children = children.docs.map(doc => {\n return addIsDir(toJsonApi(cozy, doc))\n })\n return addIsDir(toJsonApi(cozy, doc, children))\n })\n }\n return cozyFetchJSON(cozy, 'GET', `/files/${encodeURIComponent(id)}`)\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 getDowloadLink (cozy, path) {\n return cozyFetchJSON(cozy, 'POST', `/files/downloads?Path=${encodeURIComponent(path)}`)\n .then(extractResponseLinkRelated)\n}\n\nexport function getArchiveLink (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 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) {\n return cozyFetchJSON(cozy, 'DELETE', `/files/trash/${encodeURIComponent(id)}`)\n}\n\nfunction addIsDir (obj) {\n obj.isDir = obj.attributes.type === 'directory'\n return obj\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 relations: (name) => {\n if (name === 'contents') {\n return contents\n }\n }\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/files.js","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nmodule.exports = Stream;\n\nvar EE = require('events').EventEmitter;\nvar inherits = require('inherits');\n\ninherits(Stream, EE);\nStream.Readable = require('readable-stream/readable.js');\nStream.Writable = require('readable-stream/writable.js');\nStream.Duplex = require('readable-stream/duplex.js');\nStream.Transform = require('readable-stream/transform.js');\nStream.PassThrough = require('readable-stream/passthrough.js');\n\n// Backwards-compat with node 0.4.x\nStream.Stream = Stream;\n\n\n\n// old-style streams. Note that the pipe method (the only relevant\n// part of this class) is overridden in the Readable class.\n\nfunction Stream() {\n EE.call(this);\n}\n\nStream.prototype.pipe = function(dest, options) {\n var source = this;\n\n function ondata(chunk) {\n if (dest.writable) {\n if (false === dest.write(chunk) && source.pause) {\n source.pause();\n }\n }\n }\n\n source.on('data', ondata);\n\n function ondrain() {\n if (source.readable && source.resume) {\n source.resume();\n }\n }\n\n dest.on('drain', ondrain);\n\n // If the 'end' option is not supplied, dest.end() will be called when\n // source gets the 'end' or 'close' events. Only dest.end() once.\n if (!dest._isStdio && (!options || options.end !== false)) {\n source.on('end', onend);\n source.on('close', onclose);\n }\n\n var didOnEnd = false;\n function onend() {\n if (didOnEnd) return;\n didOnEnd = true;\n\n dest.end();\n }\n\n\n function onclose() {\n if (didOnEnd) return;\n didOnEnd = true;\n\n if (typeof dest.destroy === 'function') dest.destroy();\n }\n\n // don't leave dangling pipes when there are errors.\n function onerror(er) {\n cleanup();\n if (EE.listenerCount(this, 'error') === 0) {\n throw er; // Unhandled stream error in pipe.\n }\n }\n\n source.on('error', onerror);\n dest.on('error', onerror);\n\n // remove all the event listeners that were added.\n function cleanup() {\n source.removeListener('data', ondata);\n dest.removeListener('drain', ondrain);\n\n source.removeListener('end', onend);\n source.removeListener('close', onclose);\n\n source.removeListener('error', onerror);\n dest.removeListener('error', onerror);\n\n source.removeListener('end', cleanup);\n source.removeListener('close', cleanup);\n\n dest.removeListener('close', cleanup);\n }\n\n source.on('end', cleanup);\n source.on('close', cleanup);\n\n dest.on('close', cleanup);\n\n dest.emit('pipe', source);\n\n // Allow for unix-like usage: A.pipe(B).pipe(C)\n return dest;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/stream-browserify/index.js\n// module id = 14\n// module chunks = 0","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nfunction EventEmitter() {\n this._events = this._events || {};\n this._maxListeners = this._maxListeners || undefined;\n}\nmodule.exports = EventEmitter;\n\n// Backwards-compat with node 0.10.x\nEventEmitter.EventEmitter = EventEmitter;\n\nEventEmitter.prototype._events = undefined;\nEventEmitter.prototype._maxListeners = undefined;\n\n// By default EventEmitters will print a warning if more than 10 listeners are\n// added to it. This is a useful default which helps finding memory leaks.\nEventEmitter.defaultMaxListeners = 10;\n\n// Obviously not all Emitters should be limited to 10. This function allows\n// that to be increased. Set to zero for unlimited.\nEventEmitter.prototype.setMaxListeners = function(n) {\n if (!isNumber(n) || n < 0 || isNaN(n))\n throw TypeError('n must be a positive number');\n this._maxListeners = n;\n return this;\n};\n\nEventEmitter.prototype.emit = function(type) {\n var er, handler, len, args, i, listeners;\n\n if (!this._events)\n this._events = {};\n\n // If there is no 'error' event listener then throw.\n if (type === 'error') {\n if (!this._events.error ||\n (isObject(this._events.error) && !this._events.error.length)) {\n er = arguments[1];\n if (er instanceof Error) {\n throw er; // Unhandled 'error' event\n } else {\n // At least give some kind of context to the user\n var err = new Error('Uncaught, unspecified \"error\" event. (' + er + ')');\n err.context = er;\n throw err;\n }\n }\n }\n\n handler = this._events[type];\n\n if (isUndefined(handler))\n return false;\n\n if (isFunction(handler)) {\n switch (arguments.length) {\n // fast cases\n case 1:\n handler.call(this);\n break;\n case 2:\n handler.call(this, arguments[1]);\n break;\n case 3:\n handler.call(this, arguments[1], arguments[2]);\n break;\n // slower\n default:\n args = Array.prototype.slice.call(arguments, 1);\n handler.apply(this, args);\n }\n } else if (isObject(handler)) {\n args = Array.prototype.slice.call(arguments, 1);\n listeners = handler.slice();\n len = listeners.length;\n for (i = 0; i < len; i++)\n listeners[i].apply(this, args);\n }\n\n return true;\n};\n\nEventEmitter.prototype.addListener = function(type, listener) {\n var m;\n\n if (!isFunction(listener))\n throw TypeError('listener must be a function');\n\n if (!this._events)\n this._events = {};\n\n // To avoid recursion in the case that type === \"newListener\"! Before\n // adding it to the listeners, first emit \"newListener\".\n if (this._events.newListener)\n this.emit('newListener', type,\n isFunction(listener.listener) ?\n listener.listener : listener);\n\n if (!this._events[type])\n // Optimize the case of one listener. Don't need the extra array object.\n this._events[type] = listener;\n else if (isObject(this._events[type]))\n // If we've already got an array, just append.\n this._events[type].push(listener);\n else\n // Adding the second element, need to change to array.\n this._events[type] = [this._events[type], listener];\n\n // Check for listener leak\n if (isObject(this._events[type]) && !this._events[type].warned) {\n if (!isUndefined(this._maxListeners)) {\n m = this._maxListeners;\n } else {\n m = EventEmitter.defaultMaxListeners;\n }\n\n if (m && m > 0 && this._events[type].length > m) {\n this._events[type].warned = true;\n console.error('(node) warning: possible EventEmitter memory ' +\n 'leak detected. %d listeners added. ' +\n 'Use emitter.setMaxListeners() to increase limit.',\n this._events[type].length);\n if (typeof console.trace === 'function') {\n // not supported in IE 10\n console.trace();\n }\n }\n }\n\n return this;\n};\n\nEventEmitter.prototype.on = EventEmitter.prototype.addListener;\n\nEventEmitter.prototype.once = function(type, listener) {\n if (!isFunction(listener))\n throw TypeError('listener must be a function');\n\n var fired = false;\n\n function g() {\n this.removeListener(type, g);\n\n if (!fired) {\n fired = true;\n listener.apply(this, arguments);\n }\n }\n\n g.listener = listener;\n this.on(type, g);\n\n return this;\n};\n\n// emits a 'removeListener' event iff the listener was removed\nEventEmitter.prototype.removeListener = function(type, listener) {\n var list, position, length, i;\n\n if (!isFunction(listener))\n throw TypeError('listener must be a function');\n\n if (!this._events || !this._events[type])\n return this;\n\n list = this._events[type];\n length = list.length;\n position = -1;\n\n if (list === listener ||\n (isFunction(list.listener) && list.listener === listener)) {\n delete this._events[type];\n if (this._events.removeListener)\n this.emit('removeListener', type, listener);\n\n } else if (isObject(list)) {\n for (i = length; i-- > 0;) {\n if (list[i] === listener ||\n (list[i].listener && list[i].listener === listener)) {\n position = i;\n break;\n }\n }\n\n if (position < 0)\n return this;\n\n if (list.length === 1) {\n list.length = 0;\n delete this._events[type];\n } else {\n list.splice(position, 1);\n }\n\n if (this._events.removeListener)\n this.emit('removeListener', type, listener);\n }\n\n return this;\n};\n\nEventEmitter.prototype.removeAllListeners = function(type) {\n var key, listeners;\n\n if (!this._events)\n return this;\n\n // not listening for removeListener, no need to emit\n if (!this._events.removeListener) {\n if (arguments.length === 0)\n this._events = {};\n else if (this._events[type])\n delete this._events[type];\n return this;\n }\n\n // emit removeListener for all listeners on all events\n if (arguments.length === 0) {\n for (key in this._events) {\n if (key === 'removeListener') continue;\n this.removeAllListeners(key);\n }\n this.removeAllListeners('removeListener');\n this._events = {};\n return this;\n }\n\n listeners = this._events[type];\n\n if (isFunction(listeners)) {\n this.removeListener(type, listeners);\n } else if (listeners) {\n // LIFO order\n while (listeners.length)\n this.removeListener(type, listeners[listeners.length - 1]);\n }\n delete this._events[type];\n\n return this;\n};\n\nEventEmitter.prototype.listeners = function(type) {\n var ret;\n if (!this._events || !this._events[type])\n ret = [];\n else if (isFunction(this._events[type]))\n ret = [this._events[type]];\n else\n ret = this._events[type].slice();\n return ret;\n};\n\nEventEmitter.prototype.listenerCount = function(type) {\n if (this._events) {\n var evlistener = this._events[type];\n\n if (isFunction(evlistener))\n return 1;\n else if (evlistener)\n return evlistener.length;\n }\n return 0;\n};\n\nEventEmitter.listenerCount = function(emitter, type) {\n return emitter.listenerCount(type);\n};\n\nfunction isFunction(arg) {\n return typeof arg === 'function';\n}\n\nfunction isNumber(arg) {\n return typeof arg === 'number';\n}\n\nfunction isObject(arg) {\n return typeof arg === 'object' && arg !== null;\n}\n\nfunction isUndefined(arg) {\n return arg === void 0;\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/events/events.js\n// module id = 15\n// module chunks = 0","if (typeof Object.create === 'function') {\n // implementation from standard node.js 'util' module\n module.exports = function inherits(ctor, superCtor) {\n ctor.super_ = superCtor\n ctor.prototype = Object.create(superCtor.prototype, {\n constructor: {\n value: ctor,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n };\n} else {\n // old school shim for old browsers\n module.exports = function inherits(ctor, superCtor) {\n ctor.super_ = superCtor\n var TempCtor = function () {}\n TempCtor.prototype = superCtor.prototype\n ctor.prototype = new TempCtor()\n ctor.prototype.constructor = ctor\n }\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/inherits/inherits_browser.js\n// module id = 16\n// module chunks = 0","exports = module.exports = require('./lib/_stream_readable.js');\nexports.Stream = require('stream');\nexports.Readable = exports;\nexports.Writable = require('./lib/_stream_writable.js');\nexports.Duplex = require('./lib/_stream_duplex.js');\nexports.Transform = require('./lib/_stream_transform.js');\nexports.PassThrough = require('./lib/_stream_passthrough.js');\nif (!process.browser && process.env.READABLE_STREAM === 'disable') {\n module.exports = require('stream');\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/readable-stream/readable.js\n// module id = 17\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 = 18\n// module chunks = 0","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nmodule.exports = Readable;\n\n/**/\nvar isArray = require('isarray');\n/**/\n\n\n/**/\nvar Buffer = require('buffer').Buffer;\n/**/\n\nReadable.ReadableState = ReadableState;\n\nvar EE = require('events').EventEmitter;\n\n/**/\nif (!EE.listenerCount) EE.listenerCount = function(emitter, type) {\n return emitter.listeners(type).length;\n};\n/**/\n\nvar Stream = require('stream');\n\n/**/\nvar util = require('core-util-is');\nutil.inherits = require('inherits');\n/**/\n\nvar StringDecoder;\n\n\n/**/\nvar debug = require('util');\nif (debug && debug.debuglog) {\n debug = debug.debuglog('stream');\n} else {\n debug = function () {};\n}\n/**/\n\n\nutil.inherits(Readable, Stream);\n\nfunction ReadableState(options, stream) {\n var Duplex = require('./_stream_duplex');\n\n options = options || {};\n\n // the point at which it stops calling _read() to fill the buffer\n // Note: 0 is a valid value, means \"don't call _read preemptively ever\"\n var hwm = options.highWaterMark;\n var defaultHwm = options.objectMode ? 16 : 16 * 1024;\n this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;\n\n // cast to ints.\n this.highWaterMark = ~~this.highWaterMark;\n\n this.buffer = [];\n this.length = 0;\n this.pipes = null;\n this.pipesCount = 0;\n this.flowing = null;\n this.ended = false;\n this.endEmitted = false;\n this.reading = false;\n\n // a flag to be able to tell if the onwrite cb is called immediately,\n // or on a later tick. We set this to true at first, because any\n // actions that shouldn't happen until \"later\" should generally also\n // not happen before the first write call.\n this.sync = true;\n\n // whenever we return null, then we set a flag to say\n // that we're awaiting a 'readable' event emission.\n this.needReadable = false;\n this.emittedReadable = false;\n this.readableListening = false;\n\n\n // object stream flag. Used to make read(n) ignore n and to\n // make all the buffer merging and length checks go away\n this.objectMode = !!options.objectMode;\n\n if (stream instanceof Duplex)\n this.objectMode = this.objectMode || !!options.readableObjectMode;\n\n // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n this.defaultEncoding = options.defaultEncoding || 'utf8';\n\n // when piping, we only care about 'readable' events that happen\n // after read()ing all the bytes and not getting any pushback.\n this.ranOut = false;\n\n // the number of writers that are awaiting a drain event in .pipe()s\n this.awaitDrain = 0;\n\n // if true, a maybeReadMore has been scheduled\n this.readingMore = false;\n\n this.decoder = null;\n this.encoding = null;\n if (options.encoding) {\n if (!StringDecoder)\n StringDecoder = require('string_decoder/').StringDecoder;\n this.decoder = new StringDecoder(options.encoding);\n this.encoding = options.encoding;\n }\n}\n\nfunction Readable(options) {\n var Duplex = require('./_stream_duplex');\n\n if (!(this instanceof Readable))\n return new Readable(options);\n\n this._readableState = new ReadableState(options, this);\n\n // legacy\n this.readable = true;\n\n Stream.call(this);\n}\n\n// Manually shove something into the read() buffer.\n// This returns true if the highWaterMark has not been hit yet,\n// similar to how Writable.write() returns true if you should\n// write() some more.\nReadable.prototype.push = function(chunk, encoding) {\n var state = this._readableState;\n\n if (util.isString(chunk) && !state.objectMode) {\n encoding = encoding || state.defaultEncoding;\n if (encoding !== state.encoding) {\n chunk = new Buffer(chunk, encoding);\n encoding = '';\n }\n }\n\n return readableAddChunk(this, state, chunk, encoding, false);\n};\n\n// Unshift should *always* be something directly out of read()\nReadable.prototype.unshift = function(chunk) {\n var state = this._readableState;\n return readableAddChunk(this, state, chunk, '', true);\n};\n\nfunction readableAddChunk(stream, state, chunk, encoding, addToFront) {\n var er = chunkInvalid(state, chunk);\n if (er) {\n stream.emit('error', er);\n } else if (util.isNullOrUndefined(chunk)) {\n state.reading = false;\n if (!state.ended)\n onEofChunk(stream, state);\n } else if (state.objectMode || chunk && chunk.length > 0) {\n if (state.ended && !addToFront) {\n var e = new Error('stream.push() after EOF');\n stream.emit('error', e);\n } else if (state.endEmitted && addToFront) {\n var e = new Error('stream.unshift() after end event');\n stream.emit('error', e);\n } else {\n if (state.decoder && !addToFront && !encoding)\n chunk = state.decoder.write(chunk);\n\n if (!addToFront)\n state.reading = false;\n\n // if we want the data now, just emit it.\n if (state.flowing && state.length === 0 && !state.sync) {\n stream.emit('data', chunk);\n stream.read(0);\n } else {\n // update the buffer info.\n state.length += state.objectMode ? 1 : chunk.length;\n if (addToFront)\n state.buffer.unshift(chunk);\n else\n state.buffer.push(chunk);\n\n if (state.needReadable)\n emitReadable(stream);\n }\n\n maybeReadMore(stream, state);\n }\n } else if (!addToFront) {\n state.reading = false;\n }\n\n return needMoreData(state);\n}\n\n\n\n// if it's past the high water mark, we can push in some more.\n// Also, if we have no data yet, we can stand some\n// more bytes. This is to work around cases where hwm=0,\n// such as the repl. Also, if the push() triggered a\n// readable event, and the user called read(largeNumber) such that\n// needReadable was set, then we ought to push more, so that another\n// 'readable' event will be triggered.\nfunction needMoreData(state) {\n return !state.ended &&\n (state.needReadable ||\n state.length < state.highWaterMark ||\n state.length === 0);\n}\n\n// backwards compatibility.\nReadable.prototype.setEncoding = function(enc) {\n if (!StringDecoder)\n StringDecoder = require('string_decoder/').StringDecoder;\n this._readableState.decoder = new StringDecoder(enc);\n this._readableState.encoding = enc;\n return this;\n};\n\n// Don't raise the hwm > 128MB\nvar MAX_HWM = 0x800000;\nfunction roundUpToNextPowerOf2(n) {\n if (n >= MAX_HWM) {\n n = MAX_HWM;\n } else {\n // Get the next highest power of 2\n n--;\n for (var p = 1; p < 32; p <<= 1) n |= n >> p;\n n++;\n }\n return n;\n}\n\nfunction howMuchToRead(n, state) {\n if (state.length === 0 && state.ended)\n return 0;\n\n if (state.objectMode)\n return n === 0 ? 0 : 1;\n\n if (isNaN(n) || util.isNull(n)) {\n // only flow one buffer at a time\n if (state.flowing && state.buffer.length)\n return state.buffer[0].length;\n else\n return state.length;\n }\n\n if (n <= 0)\n return 0;\n\n // If we're asking for more than the target buffer level,\n // then raise the water mark. Bump up to the next highest\n // power of 2, to prevent increasing it excessively in tiny\n // amounts.\n if (n > state.highWaterMark)\n state.highWaterMark = roundUpToNextPowerOf2(n);\n\n // don't have that much. return null, unless we've ended.\n if (n > state.length) {\n if (!state.ended) {\n state.needReadable = true;\n return 0;\n } else\n return state.length;\n }\n\n return n;\n}\n\n// you can override either this method, or the async _read(n) below.\nReadable.prototype.read = function(n) {\n debug('read', n);\n var state = this._readableState;\n var nOrig = n;\n\n if (!util.isNumber(n) || n > 0)\n state.emittedReadable = false;\n\n // if we're doing read(0) to trigger a readable event, but we\n // already have a bunch of data in the buffer, then just trigger\n // the 'readable' event and move on.\n if (n === 0 &&\n state.needReadable &&\n (state.length >= state.highWaterMark || state.ended)) {\n debug('read: emitReadable', state.length, state.ended);\n if (state.length === 0 && state.ended)\n endReadable(this);\n else\n emitReadable(this);\n return null;\n }\n\n n = howMuchToRead(n, state);\n\n // if we've ended, and we're now clear, then finish it up.\n if (n === 0 && state.ended) {\n if (state.length === 0)\n endReadable(this);\n return null;\n }\n\n // All the actual chunk generation logic needs to be\n // *below* the call to _read. The reason is that in certain\n // synthetic stream cases, such as passthrough streams, _read\n // may be a completely synchronous operation which may change\n // the state of the read buffer, providing enough data when\n // before there was *not* enough.\n //\n // So, the steps are:\n // 1. Figure out what the state of things will be after we do\n // a read from the buffer.\n //\n // 2. If that resulting state will trigger a _read, then call _read.\n // Note that this may be asynchronous, or synchronous. Yes, it is\n // deeply ugly to write APIs this way, but that still doesn't mean\n // that the Readable class should behave improperly, as streams are\n // designed to be sync/async agnostic.\n // Take note if the _read call is sync or async (ie, if the read call\n // has returned yet), so that we know whether or not it's safe to emit\n // 'readable' etc.\n //\n // 3. Actually pull the requested chunks out of the buffer and return.\n\n // if we need a readable event, then we need to do some reading.\n var doRead = state.needReadable;\n debug('need readable', doRead);\n\n // if we currently have less than the highWaterMark, then also read some\n if (state.length === 0 || state.length - n < state.highWaterMark) {\n doRead = true;\n debug('length less than watermark', doRead);\n }\n\n // however, if we've ended, then there's no point, and if we're already\n // reading, then it's unnecessary.\n if (state.ended || state.reading) {\n doRead = false;\n debug('reading or ended', doRead);\n }\n\n if (doRead) {\n debug('do read');\n state.reading = true;\n state.sync = true;\n // if the length is currently zero, then we *need* a readable event.\n if (state.length === 0)\n state.needReadable = true;\n // call internal read method\n this._read(state.highWaterMark);\n state.sync = false;\n }\n\n // If _read pushed data synchronously, then `reading` will be false,\n // and we need to re-evaluate how much data we can return to the user.\n if (doRead && !state.reading)\n n = howMuchToRead(nOrig, state);\n\n var ret;\n if (n > 0)\n ret = fromList(n, state);\n else\n ret = null;\n\n if (util.isNull(ret)) {\n state.needReadable = true;\n n = 0;\n }\n\n state.length -= n;\n\n // If we have nothing in the buffer, then we want to know\n // as soon as we *do* get something into the buffer.\n if (state.length === 0 && !state.ended)\n state.needReadable = true;\n\n // If we tried to read() past the EOF, then emit end on the next tick.\n if (nOrig !== n && state.ended && state.length === 0)\n endReadable(this);\n\n if (!util.isNull(ret))\n this.emit('data', ret);\n\n return ret;\n};\n\nfunction chunkInvalid(state, chunk) {\n var er = null;\n if (!util.isBuffer(chunk) &&\n !util.isString(chunk) &&\n !util.isNullOrUndefined(chunk) &&\n !state.objectMode) {\n er = new TypeError('Invalid non-string/buffer chunk');\n }\n return er;\n}\n\n\nfunction onEofChunk(stream, state) {\n if (state.decoder && !state.ended) {\n var chunk = state.decoder.end();\n if (chunk && chunk.length) {\n state.buffer.push(chunk);\n state.length += state.objectMode ? 1 : chunk.length;\n }\n }\n state.ended = true;\n\n // emit 'readable' now to make sure it gets picked up.\n emitReadable(stream);\n}\n\n// Don't emit readable right away in sync mode, because this can trigger\n// another read() call => stack overflow. This way, it might trigger\n// a nextTick recursion warning, but that's not so bad.\nfunction emitReadable(stream) {\n var state = stream._readableState;\n state.needReadable = false;\n if (!state.emittedReadable) {\n debug('emitReadable', state.flowing);\n state.emittedReadable = true;\n if (state.sync)\n process.nextTick(function() {\n emitReadable_(stream);\n });\n else\n emitReadable_(stream);\n }\n}\n\nfunction emitReadable_(stream) {\n debug('emit readable');\n stream.emit('readable');\n flow(stream);\n}\n\n\n// at this point, the user has presumably seen the 'readable' event,\n// and called read() to consume some data. that may have triggered\n// in turn another _read(n) call, in which case reading = true if\n// it's in progress.\n// However, if we're not ended, or reading, and the length < hwm,\n// then go ahead and try to read some more preemptively.\nfunction maybeReadMore(stream, state) {\n if (!state.readingMore) {\n state.readingMore = true;\n process.nextTick(function() {\n maybeReadMore_(stream, state);\n });\n }\n}\n\nfunction maybeReadMore_(stream, state) {\n var len = state.length;\n while (!state.reading && !state.flowing && !state.ended &&\n state.length < state.highWaterMark) {\n debug('maybeReadMore read 0');\n stream.read(0);\n if (len === state.length)\n // didn't get any data, stop spinning.\n break;\n else\n len = state.length;\n }\n state.readingMore = false;\n}\n\n// abstract method. to be overridden in specific implementation classes.\n// call cb(er, data) where data is <= n in length.\n// for virtual (non-string, non-buffer) streams, \"length\" is somewhat\n// arbitrary, and perhaps not very meaningful.\nReadable.prototype._read = function(n) {\n this.emit('error', new Error('not implemented'));\n};\n\nReadable.prototype.pipe = function(dest, pipeOpts) {\n var src = this;\n var state = this._readableState;\n\n switch (state.pipesCount) {\n case 0:\n state.pipes = dest;\n break;\n case 1:\n state.pipes = [state.pipes, dest];\n break;\n default:\n state.pipes.push(dest);\n break;\n }\n state.pipesCount += 1;\n debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);\n\n var doEnd = (!pipeOpts || pipeOpts.end !== false) &&\n dest !== process.stdout &&\n dest !== process.stderr;\n\n var endFn = doEnd ? onend : cleanup;\n if (state.endEmitted)\n process.nextTick(endFn);\n else\n src.once('end', endFn);\n\n dest.on('unpipe', onunpipe);\n function onunpipe(readable) {\n debug('onunpipe');\n if (readable === src) {\n cleanup();\n }\n }\n\n function onend() {\n debug('onend');\n dest.end();\n }\n\n // when the dest drains, it reduces the awaitDrain counter\n // on the source. This would be more elegant with a .once()\n // handler in flow(), but adding and removing repeatedly is\n // too slow.\n var ondrain = pipeOnDrain(src);\n dest.on('drain', ondrain);\n\n function cleanup() {\n debug('cleanup');\n // cleanup event handlers once the pipe is broken\n dest.removeListener('close', onclose);\n dest.removeListener('finish', onfinish);\n dest.removeListener('drain', ondrain);\n dest.removeListener('error', onerror);\n dest.removeListener('unpipe', onunpipe);\n src.removeListener('end', onend);\n src.removeListener('end', cleanup);\n src.removeListener('data', ondata);\n\n // if the reader is waiting for a drain event from this\n // specific writer, then it would cause it to never start\n // flowing again.\n // So, if this is awaiting a drain, then we just call it now.\n // If we don't know, then assume that we are waiting for one.\n if (state.awaitDrain &&\n (!dest._writableState || dest._writableState.needDrain))\n ondrain();\n }\n\n src.on('data', ondata);\n function ondata(chunk) {\n debug('ondata');\n var ret = dest.write(chunk);\n if (false === ret) {\n debug('false write response, pause',\n src._readableState.awaitDrain);\n src._readableState.awaitDrain++;\n src.pause();\n }\n }\n\n // if the dest has an error, then stop piping into it.\n // however, don't suppress the throwing behavior for this.\n function onerror(er) {\n debug('onerror', er);\n unpipe();\n dest.removeListener('error', onerror);\n if (EE.listenerCount(dest, 'error') === 0)\n dest.emit('error', er);\n }\n // This is a brutally ugly hack to make sure that our error handler\n // is attached before any userland ones. NEVER DO THIS.\n if (!dest._events || !dest._events.error)\n dest.on('error', onerror);\n else if (isArray(dest._events.error))\n dest._events.error.unshift(onerror);\n else\n dest._events.error = [onerror, dest._events.error];\n\n\n\n // Both close and finish should trigger unpipe, but only once.\n function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }\n dest.once('close', onclose);\n function onfinish() {\n debug('onfinish');\n dest.removeListener('close', onclose);\n unpipe();\n }\n dest.once('finish', onfinish);\n\n function unpipe() {\n debug('unpipe');\n src.unpipe(dest);\n }\n\n // tell the dest that it's being piped to\n dest.emit('pipe', src);\n\n // start the flow if it hasn't been started already.\n if (!state.flowing) {\n debug('pipe resume');\n src.resume();\n }\n\n return dest;\n};\n\nfunction pipeOnDrain(src) {\n return function() {\n var state = src._readableState;\n debug('pipeOnDrain', state.awaitDrain);\n if (state.awaitDrain)\n state.awaitDrain--;\n if (state.awaitDrain === 0 && EE.listenerCount(src, 'data')) {\n state.flowing = true;\n flow(src);\n }\n };\n}\n\n\nReadable.prototype.unpipe = function(dest) {\n var state = this._readableState;\n\n // if we're not piping anywhere, then do nothing.\n if (state.pipesCount === 0)\n return this;\n\n // just one destination. most common case.\n if (state.pipesCount === 1) {\n // passed in one, but it's not the right one.\n if (dest && dest !== state.pipes)\n return this;\n\n if (!dest)\n dest = state.pipes;\n\n // got a match.\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n if (dest)\n dest.emit('unpipe', this);\n return this;\n }\n\n // slow case. multiple pipe destinations.\n\n if (!dest) {\n // remove all.\n var dests = state.pipes;\n var len = state.pipesCount;\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n\n for (var i = 0; i < len; i++)\n dests[i].emit('unpipe', this);\n return this;\n }\n\n // try to find the right one.\n var i = indexOf(state.pipes, dest);\n if (i === -1)\n return this;\n\n state.pipes.splice(i, 1);\n state.pipesCount -= 1;\n if (state.pipesCount === 1)\n state.pipes = state.pipes[0];\n\n dest.emit('unpipe', this);\n\n return this;\n};\n\n// set up data events if they are asked for\n// Ensure readable listeners eventually get something\nReadable.prototype.on = function(ev, fn) {\n var res = Stream.prototype.on.call(this, ev, fn);\n\n // If listening to data, and it has not explicitly been paused,\n // then call resume to start the flow of data on the next tick.\n if (ev === 'data' && false !== this._readableState.flowing) {\n this.resume();\n }\n\n if (ev === 'readable' && this.readable) {\n var state = this._readableState;\n if (!state.readableListening) {\n state.readableListening = true;\n state.emittedReadable = false;\n state.needReadable = true;\n if (!state.reading) {\n var self = this;\n process.nextTick(function() {\n debug('readable nexttick read 0');\n self.read(0);\n });\n } else if (state.length) {\n emitReadable(this, state);\n }\n }\n }\n\n return res;\n};\nReadable.prototype.addListener = Readable.prototype.on;\n\n// pause() and resume() are remnants of the legacy readable stream API\n// If the user uses them, then switch into old mode.\nReadable.prototype.resume = function() {\n var state = this._readableState;\n if (!state.flowing) {\n debug('resume');\n state.flowing = true;\n if (!state.reading) {\n debug('resume read 0');\n this.read(0);\n }\n resume(this, state);\n }\n return this;\n};\n\nfunction resume(stream, state) {\n if (!state.resumeScheduled) {\n state.resumeScheduled = true;\n process.nextTick(function() {\n resume_(stream, state);\n });\n }\n}\n\nfunction resume_(stream, state) {\n state.resumeScheduled = false;\n stream.emit('resume');\n flow(stream);\n if (state.flowing && !state.reading)\n stream.read(0);\n}\n\nReadable.prototype.pause = function() {\n debug('call pause flowing=%j', this._readableState.flowing);\n if (false !== this._readableState.flowing) {\n debug('pause');\n this._readableState.flowing = false;\n this.emit('pause');\n }\n return this;\n};\n\nfunction flow(stream) {\n var state = stream._readableState;\n debug('flow', state.flowing);\n if (state.flowing) {\n do {\n var chunk = stream.read();\n } while (null !== chunk && state.flowing);\n }\n}\n\n// wrap an old-style stream as the async data source.\n// This is *not* part of the readable stream interface.\n// It is an ugly unfortunate mess of history.\nReadable.prototype.wrap = function(stream) {\n var state = this._readableState;\n var paused = false;\n\n var self = this;\n stream.on('end', function() {\n debug('wrapped end');\n if (state.decoder && !state.ended) {\n var chunk = state.decoder.end();\n if (chunk && chunk.length)\n self.push(chunk);\n }\n\n self.push(null);\n });\n\n stream.on('data', function(chunk) {\n debug('wrapped data');\n if (state.decoder)\n chunk = state.decoder.write(chunk);\n if (!chunk || !state.objectMode && !chunk.length)\n return;\n\n var ret = self.push(chunk);\n if (!ret) {\n paused = true;\n stream.pause();\n }\n });\n\n // proxy all the other methods.\n // important when wrapping filters and duplexes.\n for (var i in stream) {\n if (util.isFunction(stream[i]) && util.isUndefined(this[i])) {\n this[i] = function(method) { return function() {\n return stream[method].apply(stream, arguments);\n }}(i);\n }\n }\n\n // proxy certain important events.\n var events = ['error', 'close', 'destroy', 'pause', 'resume'];\n forEach(events, function(ev) {\n stream.on(ev, self.emit.bind(self, ev));\n });\n\n // when we try to consume some more bytes, simply unpause the\n // underlying stream.\n self._read = function(n) {\n debug('wrapped _read', n);\n if (paused) {\n paused = false;\n stream.resume();\n }\n };\n\n return self;\n};\n\n\n\n// exposed for testing purposes only.\nReadable._fromList = fromList;\n\n// Pluck off n bytes from an array of buffers.\n// Length is the combined lengths of all the buffers in the list.\nfunction fromList(n, state) {\n var list = state.buffer;\n var length = state.length;\n var stringMode = !!state.decoder;\n var objectMode = !!state.objectMode;\n var ret;\n\n // nothing in the list, definitely empty.\n if (list.length === 0)\n return null;\n\n if (length === 0)\n ret = null;\n else if (objectMode)\n ret = list.shift();\n else if (!n || n >= length) {\n // read it all, truncate the array.\n if (stringMode)\n ret = list.join('');\n else\n ret = Buffer.concat(list, length);\n list.length = 0;\n } else {\n // read just some of it.\n if (n < list[0].length) {\n // just take a part of the first list item.\n // slice is the same for buffers and strings.\n var buf = list[0];\n ret = buf.slice(0, n);\n list[0] = buf.slice(n);\n } else if (n === list[0].length) {\n // first list is a perfect match\n ret = list.shift();\n } else {\n // complex case.\n // we have enough to cover it, but it spans past the first buffer.\n if (stringMode)\n ret = '';\n else\n ret = new Buffer(n);\n\n var c = 0;\n for (var i = 0, l = list.length; i < l && c < n; i++) {\n var buf = list[0];\n var cpy = Math.min(n - c, buf.length);\n\n if (stringMode)\n ret += buf.slice(0, cpy);\n else\n buf.copy(ret, c, 0, cpy);\n\n if (cpy < buf.length)\n list[0] = buf.slice(cpy);\n else\n list.shift();\n\n c += cpy;\n }\n }\n }\n\n return ret;\n}\n\nfunction endReadable(stream) {\n var state = stream._readableState;\n\n // If we get here before consuming all the bytes, then that is a\n // bug in node. Should never happen.\n if (state.length > 0)\n throw new Error('endReadable called on non-empty stream');\n\n if (!state.endEmitted) {\n state.ended = true;\n process.nextTick(function() {\n // Check that we didn't get one last unshift.\n if (!state.endEmitted && state.length === 0) {\n state.endEmitted = true;\n stream.readable = false;\n stream.emit('end');\n }\n });\n }\n}\n\nfunction forEach (xs, f) {\n for (var i = 0, l = xs.length; i < l; i++) {\n f(xs[i], i);\n }\n}\n\nfunction indexOf (xs, x) {\n for (var i = 0, l = xs.length; i < l; i++) {\n if (xs[i] === x) return i;\n }\n return -1;\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/readable-stream/lib/_stream_readable.js\n// module id = 19\n// module chunks = 0","module.exports = Array.isArray || function (arr) {\n return Object.prototype.toString.call(arr) == '[object Array]';\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/isarray/index.js\n// module id = 20\n// module chunks = 0","/*!\n * The buffer module from node.js, for the browser.\n *\n * @author Feross Aboukhadijeh \n * @license MIT\n */\n/* eslint-disable no-proto */\n\n'use strict'\n\nvar base64 = require('base64-js')\nvar ieee754 = require('ieee754')\nvar isArray = require('isarray')\n\nexports.Buffer = Buffer\nexports.SlowBuffer = SlowBuffer\nexports.INSPECT_MAX_BYTES = 50\n\n/**\n * If `Buffer.TYPED_ARRAY_SUPPORT`:\n * === true Use Uint8Array implementation (fastest)\n * === false Use Object implementation (most compatible, even IE6)\n *\n * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,\n * Opera 11.6+, iOS 4.2+.\n *\n * Due to various browser bugs, sometimes the Object implementation will be used even\n * when the browser supports typed arrays.\n *\n * Note:\n *\n * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,\n * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.\n *\n * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.\n *\n * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of\n * incorrect length in some situations.\n\n * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they\n * get the Object implementation, which is slower but behaves correctly.\n */\nBuffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined\n ? global.TYPED_ARRAY_SUPPORT\n : typedArraySupport()\n\n/*\n * Export kMaxLength after typed array support is determined.\n */\nexports.kMaxLength = kMaxLength()\n\nfunction typedArraySupport () {\n try {\n var arr = new Uint8Array(1)\n arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}\n return arr.foo() === 42 && // typed array instances can be augmented\n typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`\n arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`\n } catch (e) {\n return false\n }\n}\n\nfunction kMaxLength () {\n return Buffer.TYPED_ARRAY_SUPPORT\n ? 0x7fffffff\n : 0x3fffffff\n}\n\nfunction createBuffer (that, length) {\n if (kMaxLength() < length) {\n throw new RangeError('Invalid typed array length')\n }\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n // Return an augmented `Uint8Array` instance, for best performance\n that = new Uint8Array(length)\n that.__proto__ = Buffer.prototype\n } else {\n // Fallback: Return an object instance of the Buffer class\n if (that === null) {\n that = new Buffer(length)\n }\n that.length = length\n }\n\n return that\n}\n\n/**\n * The Buffer constructor returns instances of `Uint8Array` that have their\n * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of\n * `Uint8Array`, so the returned instances will have all the node `Buffer` methods\n * and the `Uint8Array` methods. Square bracket notation works as expected -- it\n * returns a single octet.\n *\n * The `Uint8Array` prototype remains unmodified.\n */\n\nfunction Buffer (arg, encodingOrOffset, length) {\n if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {\n return new Buffer(arg, encodingOrOffset, length)\n }\n\n // Common case.\n if (typeof arg === 'number') {\n if (typeof encodingOrOffset === 'string') {\n throw new Error(\n 'If encoding is specified then the first argument must be a string'\n )\n }\n return allocUnsafe(this, arg)\n }\n return from(this, arg, encodingOrOffset, length)\n}\n\nBuffer.poolSize = 8192 // not used by this implementation\n\n// TODO: Legacy, not needed anymore. Remove in next major version.\nBuffer._augment = function (arr) {\n arr.__proto__ = Buffer.prototype\n return arr\n}\n\nfunction from (that, value, encodingOrOffset, length) {\n if (typeof value === 'number') {\n throw new TypeError('\"value\" argument must not be a number')\n }\n\n if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {\n return fromArrayBuffer(that, value, encodingOrOffset, length)\n }\n\n if (typeof value === 'string') {\n return fromString(that, value, encodingOrOffset)\n }\n\n return fromObject(that, value)\n}\n\n/**\n * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError\n * if value is a number.\n * Buffer.from(str[, encoding])\n * Buffer.from(array)\n * Buffer.from(buffer)\n * Buffer.from(arrayBuffer[, byteOffset[, length]])\n **/\nBuffer.from = function (value, encodingOrOffset, length) {\n return from(null, value, encodingOrOffset, length)\n}\n\nif (Buffer.TYPED_ARRAY_SUPPORT) {\n Buffer.prototype.__proto__ = Uint8Array.prototype\n Buffer.__proto__ = Uint8Array\n if (typeof Symbol !== 'undefined' && Symbol.species &&\n Buffer[Symbol.species] === Buffer) {\n // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97\n Object.defineProperty(Buffer, Symbol.species, {\n value: null,\n configurable: true\n })\n }\n}\n\nfunction assertSize (size) {\n if (typeof size !== 'number') {\n throw new TypeError('\"size\" argument must be a number')\n } else if (size < 0) {\n throw new RangeError('\"size\" argument must not be negative')\n }\n}\n\nfunction alloc (that, size, fill, encoding) {\n assertSize(size)\n if (size <= 0) {\n return createBuffer(that, size)\n }\n if (fill !== undefined) {\n // Only pay attention to encoding if it's a string. This\n // prevents accidentally sending in a number that would\n // be interpretted as a start offset.\n return typeof encoding === 'string'\n ? createBuffer(that, size).fill(fill, encoding)\n : createBuffer(that, size).fill(fill)\n }\n return createBuffer(that, size)\n}\n\n/**\n * Creates a new filled Buffer instance.\n * alloc(size[, fill[, encoding]])\n **/\nBuffer.alloc = function (size, fill, encoding) {\n return alloc(null, size, fill, encoding)\n}\n\nfunction allocUnsafe (that, size) {\n assertSize(size)\n that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)\n if (!Buffer.TYPED_ARRAY_SUPPORT) {\n for (var i = 0; i < size; ++i) {\n that[i] = 0\n }\n }\n return that\n}\n\n/**\n * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.\n * */\nBuffer.allocUnsafe = function (size) {\n return allocUnsafe(null, size)\n}\n/**\n * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.\n */\nBuffer.allocUnsafeSlow = function (size) {\n return allocUnsafe(null, size)\n}\n\nfunction fromString (that, string, encoding) {\n if (typeof encoding !== 'string' || encoding === '') {\n encoding = 'utf8'\n }\n\n if (!Buffer.isEncoding(encoding)) {\n throw new TypeError('\"encoding\" must be a valid string encoding')\n }\n\n var length = byteLength(string, encoding) | 0\n that = createBuffer(that, length)\n\n var actual = that.write(string, encoding)\n\n if (actual !== length) {\n // Writing a hex string, for example, that contains invalid characters will\n // cause everything after the first invalid character to be ignored. (e.g.\n // 'abxxcd' will be treated as 'ab')\n that = that.slice(0, actual)\n }\n\n return that\n}\n\nfunction fromArrayLike (that, array) {\n var length = array.length < 0 ? 0 : checked(array.length) | 0\n that = createBuffer(that, length)\n for (var i = 0; i < length; i += 1) {\n that[i] = array[i] & 255\n }\n return that\n}\n\nfunction fromArrayBuffer (that, array, byteOffset, length) {\n array.byteLength // this throws if `array` is not a valid ArrayBuffer\n\n if (byteOffset < 0 || array.byteLength < byteOffset) {\n throw new RangeError('\\'offset\\' is out of bounds')\n }\n\n if (array.byteLength < byteOffset + (length || 0)) {\n throw new RangeError('\\'length\\' is out of bounds')\n }\n\n if (byteOffset === undefined && length === undefined) {\n array = new Uint8Array(array)\n } else if (length === undefined) {\n array = new Uint8Array(array, byteOffset)\n } else {\n array = new Uint8Array(array, byteOffset, length)\n }\n\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n // Return an augmented `Uint8Array` instance, for best performance\n that = array\n that.__proto__ = Buffer.prototype\n } else {\n // Fallback: Return an object instance of the Buffer class\n that = fromArrayLike(that, array)\n }\n return that\n}\n\nfunction fromObject (that, obj) {\n if (Buffer.isBuffer(obj)) {\n var len = checked(obj.length) | 0\n that = createBuffer(that, len)\n\n if (that.length === 0) {\n return that\n }\n\n obj.copy(that, 0, 0, len)\n return that\n }\n\n if (obj) {\n if ((typeof ArrayBuffer !== 'undefined' &&\n obj.buffer instanceof ArrayBuffer) || 'length' in obj) {\n if (typeof obj.length !== 'number' || isnan(obj.length)) {\n return createBuffer(that, 0)\n }\n return fromArrayLike(that, obj)\n }\n\n if (obj.type === 'Buffer' && isArray(obj.data)) {\n return fromArrayLike(that, obj.data)\n }\n }\n\n throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')\n}\n\nfunction checked (length) {\n // Note: cannot use `length < kMaxLength()` here because that fails when\n // length is NaN (which is otherwise coerced to zero.)\n if (length >= kMaxLength()) {\n throw new RangeError('Attempt to allocate Buffer larger than maximum ' +\n 'size: 0x' + kMaxLength().toString(16) + ' bytes')\n }\n return length | 0\n}\n\nfunction SlowBuffer (length) {\n if (+length != length) { // eslint-disable-line eqeqeq\n length = 0\n }\n return Buffer.alloc(+length)\n}\n\nBuffer.isBuffer = function isBuffer (b) {\n return !!(b != null && b._isBuffer)\n}\n\nBuffer.compare = function compare (a, b) {\n if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {\n throw new TypeError('Arguments must be Buffers')\n }\n\n if (a === b) return 0\n\n var x = a.length\n var y = b.length\n\n for (var i = 0, len = Math.min(x, y); i < len; ++i) {\n if (a[i] !== b[i]) {\n x = a[i]\n y = b[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\nBuffer.isEncoding = function isEncoding (encoding) {\n switch (String(encoding).toLowerCase()) {\n case 'hex':\n case 'utf8':\n case 'utf-8':\n case 'ascii':\n case 'latin1':\n case 'binary':\n case 'base64':\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return true\n default:\n return false\n }\n}\n\nBuffer.concat = function concat (list, length) {\n if (!isArray(list)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n\n if (list.length === 0) {\n return Buffer.alloc(0)\n }\n\n var i\n if (length === undefined) {\n length = 0\n for (i = 0; i < list.length; ++i) {\n length += list[i].length\n }\n }\n\n var buffer = Buffer.allocUnsafe(length)\n var pos = 0\n for (i = 0; i < list.length; ++i) {\n var buf = list[i]\n if (!Buffer.isBuffer(buf)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n buf.copy(buffer, pos)\n pos += buf.length\n }\n return buffer\n}\n\nfunction byteLength (string, encoding) {\n if (Buffer.isBuffer(string)) {\n return string.length\n }\n if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&\n (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {\n return string.byteLength\n }\n if (typeof string !== 'string') {\n string = '' + string\n }\n\n var len = string.length\n if (len === 0) return 0\n\n // Use a for loop to avoid recursion\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'ascii':\n case 'latin1':\n case 'binary':\n return len\n case 'utf8':\n case 'utf-8':\n case undefined:\n return utf8ToBytes(string).length\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return len * 2\n case 'hex':\n return len >>> 1\n case 'base64':\n return base64ToBytes(string).length\n default:\n if (loweredCase) return utf8ToBytes(string).length // assume utf8\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\nBuffer.byteLength = byteLength\n\nfunction slowToString (encoding, start, end) {\n var loweredCase = false\n\n // No need to verify that \"this.length <= MAX_UINT32\" since it's a read-only\n // property of a typed array.\n\n // This behaves neither like String nor Uint8Array in that we set start/end\n // to their upper/lower bounds if the value passed is out of range.\n // undefined is handled specially as per ECMA-262 6th Edition,\n // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.\n if (start === undefined || start < 0) {\n start = 0\n }\n // Return early if start > this.length. Done here to prevent potential uint32\n // coercion fail below.\n if (start > this.length) {\n return ''\n }\n\n if (end === undefined || end > this.length) {\n end = this.length\n }\n\n if (end <= 0) {\n return ''\n }\n\n // Force coersion to uint32. This will also coerce falsey/NaN values to 0.\n end >>>= 0\n start >>>= 0\n\n if (end <= start) {\n return ''\n }\n\n if (!encoding) encoding = 'utf8'\n\n while (true) {\n switch (encoding) {\n case 'hex':\n return hexSlice(this, start, end)\n\n case 'utf8':\n case 'utf-8':\n return utf8Slice(this, start, end)\n\n case 'ascii':\n return asciiSlice(this, start, end)\n\n case 'latin1':\n case 'binary':\n return latin1Slice(this, start, end)\n\n case 'base64':\n return base64Slice(this, start, end)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return utf16leSlice(this, start, end)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = (encoding + '').toLowerCase()\n loweredCase = true\n }\n }\n}\n\n// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect\n// Buffer instances.\nBuffer.prototype._isBuffer = true\n\nfunction swap (b, n, m) {\n var i = b[n]\n b[n] = b[m]\n b[m] = i\n}\n\nBuffer.prototype.swap16 = function swap16 () {\n var len = this.length\n if (len % 2 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 16-bits')\n }\n for (var i = 0; i < len; i += 2) {\n swap(this, i, i + 1)\n }\n return this\n}\n\nBuffer.prototype.swap32 = function swap32 () {\n var len = this.length\n if (len % 4 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 32-bits')\n }\n for (var i = 0; i < len; i += 4) {\n swap(this, i, i + 3)\n swap(this, i + 1, i + 2)\n }\n return this\n}\n\nBuffer.prototype.swap64 = function swap64 () {\n var len = this.length\n if (len % 8 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 64-bits')\n }\n for (var i = 0; i < len; i += 8) {\n swap(this, i, i + 7)\n swap(this, i + 1, i + 6)\n swap(this, i + 2, i + 5)\n swap(this, i + 3, i + 4)\n }\n return this\n}\n\nBuffer.prototype.toString = function toString () {\n var length = this.length | 0\n if (length === 0) return ''\n if (arguments.length === 0) return utf8Slice(this, 0, length)\n return slowToString.apply(this, arguments)\n}\n\nBuffer.prototype.equals = function equals (b) {\n if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')\n if (this === b) return true\n return Buffer.compare(this, b) === 0\n}\n\nBuffer.prototype.inspect = function inspect () {\n var str = ''\n var max = exports.INSPECT_MAX_BYTES\n if (this.length > 0) {\n str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')\n if (this.length > max) str += ' ... '\n }\n return ''\n}\n\nBuffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {\n if (!Buffer.isBuffer(target)) {\n throw new TypeError('Argument must be a Buffer')\n }\n\n if (start === undefined) {\n start = 0\n }\n if (end === undefined) {\n end = target ? target.length : 0\n }\n if (thisStart === undefined) {\n thisStart = 0\n }\n if (thisEnd === undefined) {\n thisEnd = this.length\n }\n\n if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {\n throw new RangeError('out of range index')\n }\n\n if (thisStart >= thisEnd && start >= end) {\n return 0\n }\n if (thisStart >= thisEnd) {\n return -1\n }\n if (start >= end) {\n return 1\n }\n\n start >>>= 0\n end >>>= 0\n thisStart >>>= 0\n thisEnd >>>= 0\n\n if (this === target) return 0\n\n var x = thisEnd - thisStart\n var y = end - start\n var len = Math.min(x, y)\n\n var thisCopy = this.slice(thisStart, thisEnd)\n var targetCopy = target.slice(start, end)\n\n for (var i = 0; i < len; ++i) {\n if (thisCopy[i] !== targetCopy[i]) {\n x = thisCopy[i]\n y = targetCopy[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\n// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,\n// OR the last index of `val` in `buffer` at offset <= `byteOffset`.\n//\n// Arguments:\n// - buffer - a Buffer to search\n// - val - a string, Buffer, or number\n// - byteOffset - an index into `buffer`; will be clamped to an int32\n// - encoding - an optional encoding, relevant is val is a string\n// - dir - true for indexOf, false for lastIndexOf\nfunction bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {\n // Empty buffer means no match\n if (buffer.length === 0) return -1\n\n // Normalize byteOffset\n if (typeof byteOffset === 'string') {\n encoding = byteOffset\n byteOffset = 0\n } else if (byteOffset > 0x7fffffff) {\n byteOffset = 0x7fffffff\n } else if (byteOffset < -0x80000000) {\n byteOffset = -0x80000000\n }\n byteOffset = +byteOffset // Coerce to Number.\n if (isNaN(byteOffset)) {\n // byteOffset: it it's undefined, null, NaN, \"foo\", etc, search whole buffer\n byteOffset = dir ? 0 : (buffer.length - 1)\n }\n\n // Normalize byteOffset: negative offsets start from the end of the buffer\n if (byteOffset < 0) byteOffset = buffer.length + byteOffset\n if (byteOffset >= buffer.length) {\n if (dir) return -1\n else byteOffset = buffer.length - 1\n } else if (byteOffset < 0) {\n if (dir) byteOffset = 0\n else return -1\n }\n\n // Normalize val\n if (typeof val === 'string') {\n val = Buffer.from(val, encoding)\n }\n\n // Finally, search either indexOf (if dir is true) or lastIndexOf\n if (Buffer.isBuffer(val)) {\n // Special case: looking for empty string/buffer always fails\n if (val.length === 0) {\n return -1\n }\n return arrayIndexOf(buffer, val, byteOffset, encoding, dir)\n } else if (typeof val === 'number') {\n val = val & 0xFF // Search for a byte value [0-255]\n if (Buffer.TYPED_ARRAY_SUPPORT &&\n typeof Uint8Array.prototype.indexOf === 'function') {\n if (dir) {\n return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)\n } else {\n return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)\n }\n }\n return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)\n }\n\n throw new TypeError('val must be string, number or Buffer')\n}\n\nfunction arrayIndexOf (arr, val, byteOffset, encoding, dir) {\n var indexSize = 1\n var arrLength = arr.length\n var valLength = val.length\n\n if (encoding !== undefined) {\n encoding = String(encoding).toLowerCase()\n if (encoding === 'ucs2' || encoding === 'ucs-2' ||\n encoding === 'utf16le' || encoding === 'utf-16le') {\n if (arr.length < 2 || val.length < 2) {\n return -1\n }\n indexSize = 2\n arrLength /= 2\n valLength /= 2\n byteOffset /= 2\n }\n }\n\n function read (buf, i) {\n if (indexSize === 1) {\n return buf[i]\n } else {\n return buf.readUInt16BE(i * indexSize)\n }\n }\n\n var i\n if (dir) {\n var foundIndex = -1\n for (i = byteOffset; i < arrLength; i++) {\n if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {\n if (foundIndex === -1) foundIndex = i\n if (i - foundIndex + 1 === valLength) return foundIndex * indexSize\n } else {\n if (foundIndex !== -1) i -= i - foundIndex\n foundIndex = -1\n }\n }\n } else {\n if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength\n for (i = byteOffset; i >= 0; i--) {\n var found = true\n for (var j = 0; j < valLength; j++) {\n if (read(arr, i + j) !== read(val, j)) {\n found = false\n break\n }\n }\n if (found) return i\n }\n }\n\n return -1\n}\n\nBuffer.prototype.includes = function includes (val, byteOffset, encoding) {\n return this.indexOf(val, byteOffset, encoding) !== -1\n}\n\nBuffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, true)\n}\n\nBuffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, false)\n}\n\nfunction hexWrite (buf, string, offset, length) {\n offset = Number(offset) || 0\n var remaining = buf.length - offset\n if (!length) {\n length = remaining\n } else {\n length = Number(length)\n if (length > remaining) {\n length = remaining\n }\n }\n\n // must be an even number of digits\n var strLen = string.length\n if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')\n\n if (length > strLen / 2) {\n length = strLen / 2\n }\n for (var i = 0; i < length; ++i) {\n var parsed = parseInt(string.substr(i * 2, 2), 16)\n if (isNaN(parsed)) return i\n buf[offset + i] = parsed\n }\n return i\n}\n\nfunction utf8Write (buf, string, offset, length) {\n return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nfunction asciiWrite (buf, string, offset, length) {\n return blitBuffer(asciiToBytes(string), buf, offset, length)\n}\n\nfunction latin1Write (buf, string, offset, length) {\n return asciiWrite(buf, string, offset, length)\n}\n\nfunction base64Write (buf, string, offset, length) {\n return blitBuffer(base64ToBytes(string), buf, offset, length)\n}\n\nfunction ucs2Write (buf, string, offset, length) {\n return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nBuffer.prototype.write = function write (string, offset, length, encoding) {\n // Buffer#write(string)\n if (offset === undefined) {\n encoding = 'utf8'\n length = this.length\n offset = 0\n // Buffer#write(string, encoding)\n } else if (length === undefined && typeof offset === 'string') {\n encoding = offset\n length = this.length\n offset = 0\n // Buffer#write(string, offset[, length][, encoding])\n } else if (isFinite(offset)) {\n offset = offset | 0\n if (isFinite(length)) {\n length = length | 0\n if (encoding === undefined) encoding = 'utf8'\n } else {\n encoding = length\n length = undefined\n }\n // legacy write(string, encoding, offset, length) - remove in v0.13\n } else {\n throw new Error(\n 'Buffer.write(string, encoding, offset[, length]) is no longer supported'\n )\n }\n\n var remaining = this.length - offset\n if (length === undefined || length > remaining) length = remaining\n\n if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {\n throw new RangeError('Attempt to write outside buffer bounds')\n }\n\n if (!encoding) encoding = 'utf8'\n\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'hex':\n return hexWrite(this, string, offset, length)\n\n case 'utf8':\n case 'utf-8':\n return utf8Write(this, string, offset, length)\n\n case 'ascii':\n return asciiWrite(this, string, offset, length)\n\n case 'latin1':\n case 'binary':\n return latin1Write(this, string, offset, length)\n\n case 'base64':\n // Warning: maxLength not taken into account in base64Write\n return base64Write(this, string, offset, length)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return ucs2Write(this, string, offset, length)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\n\nBuffer.prototype.toJSON = function toJSON () {\n return {\n type: 'Buffer',\n data: Array.prototype.slice.call(this._arr || this, 0)\n }\n}\n\nfunction base64Slice (buf, start, end) {\n if (start === 0 && end === buf.length) {\n return base64.fromByteArray(buf)\n } else {\n return base64.fromByteArray(buf.slice(start, end))\n }\n}\n\nfunction utf8Slice (buf, start, end) {\n end = Math.min(buf.length, end)\n var res = []\n\n var i = start\n while (i < end) {\n var firstByte = buf[i]\n var codePoint = null\n var bytesPerSequence = (firstByte > 0xEF) ? 4\n : (firstByte > 0xDF) ? 3\n : (firstByte > 0xBF) ? 2\n : 1\n\n if (i + bytesPerSequence <= end) {\n var secondByte, thirdByte, fourthByte, tempCodePoint\n\n switch (bytesPerSequence) {\n case 1:\n if (firstByte < 0x80) {\n codePoint = firstByte\n }\n break\n case 2:\n secondByte = buf[i + 1]\n if ((secondByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)\n if (tempCodePoint > 0x7F) {\n codePoint = tempCodePoint\n }\n }\n break\n case 3:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)\n if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {\n codePoint = tempCodePoint\n }\n }\n break\n case 4:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n fourthByte = buf[i + 3]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)\n if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {\n codePoint = tempCodePoint\n }\n }\n }\n }\n\n if (codePoint === null) {\n // we did not generate a valid codePoint so insert a\n // replacement char (U+FFFD) and advance only 1 byte\n codePoint = 0xFFFD\n bytesPerSequence = 1\n } else if (codePoint > 0xFFFF) {\n // encode to utf16 (surrogate pair dance)\n codePoint -= 0x10000\n res.push(codePoint >>> 10 & 0x3FF | 0xD800)\n codePoint = 0xDC00 | codePoint & 0x3FF\n }\n\n res.push(codePoint)\n i += bytesPerSequence\n }\n\n return decodeCodePointsArray(res)\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nvar MAX_ARGUMENTS_LENGTH = 0x1000\n\nfunction decodeCodePointsArray (codePoints) {\n var len = codePoints.length\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n }\n\n // Decode in chunks to avoid \"call stack size exceeded\".\n var res = ''\n var i = 0\n while (i < len) {\n res += String.fromCharCode.apply(\n String,\n codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n )\n }\n return res\n}\n\nfunction asciiSlice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i] & 0x7F)\n }\n return ret\n}\n\nfunction latin1Slice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i])\n }\n return ret\n}\n\nfunction hexSlice (buf, start, end) {\n var len = buf.length\n\n if (!start || start < 0) start = 0\n if (!end || end < 0 || end > len) end = len\n\n var out = ''\n for (var i = start; i < end; ++i) {\n out += toHex(buf[i])\n }\n return out\n}\n\nfunction utf16leSlice (buf, start, end) {\n var bytes = buf.slice(start, end)\n var res = ''\n for (var i = 0; i < bytes.length; i += 2) {\n res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)\n }\n return res\n}\n\nBuffer.prototype.slice = function slice (start, end) {\n var len = this.length\n start = ~~start\n end = end === undefined ? len : ~~end\n\n if (start < 0) {\n start += len\n if (start < 0) start = 0\n } else if (start > len) {\n start = len\n }\n\n if (end < 0) {\n end += len\n if (end < 0) end = 0\n } else if (end > len) {\n end = len\n }\n\n if (end < start) end = start\n\n var newBuf\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n newBuf = this.subarray(start, end)\n newBuf.__proto__ = Buffer.prototype\n } else {\n var sliceLen = end - start\n newBuf = new Buffer(sliceLen, undefined)\n for (var i = 0; i < sliceLen; ++i) {\n newBuf[i] = this[i + start]\n }\n }\n\n return newBuf\n}\n\n/*\n * Need to make sure that buffer isn't trying to write out of bounds.\n */\nfunction checkOffset (offset, ext, length) {\n if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')\n if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')\n}\n\nBuffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n checkOffset(offset, byteLength, this.length)\n }\n\n var val = this[offset + --byteLength]\n var mul = 1\n while (byteLength > 0 && (mul *= 0x100)) {\n val += this[offset + --byteLength] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 1, this.length)\n return this[offset]\n}\n\nBuffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n return this[offset] | (this[offset + 1] << 8)\n}\n\nBuffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n return (this[offset] << 8) | this[offset + 1]\n}\n\nBuffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return ((this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16)) +\n (this[offset + 3] * 0x1000000)\n}\n\nBuffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] * 0x1000000) +\n ((this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n this[offset + 3])\n}\n\nBuffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var i = byteLength\n var mul = 1\n var val = this[offset + --i]\n while (i > 0 && (mul *= 0x100)) {\n val += this[offset + --i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readInt8 = function readInt8 (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 1, this.length)\n if (!(this[offset] & 0x80)) return (this[offset])\n return ((0xff - this[offset] + 1) * -1)\n}\n\nBuffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset] | (this[offset + 1] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset + 1] | (this[offset] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16) |\n (this[offset + 3] << 24)\n}\n\nBuffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] << 24) |\n (this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n (this[offset + 3])\n}\n\nBuffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, true, 23, 4)\n}\n\nBuffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, false, 23, 4)\n}\n\nBuffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, true, 52, 8)\n}\n\nBuffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, false, 52, 8)\n}\n\nfunction checkInt (buf, value, offset, ext, max, min) {\n if (!Buffer.isBuffer(buf)) throw new TypeError('\"buffer\" argument must be a Buffer instance')\n if (value > max || value < min) throw new RangeError('\"value\" argument is out of bounds')\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n}\n\nBuffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var mul = 1\n var i = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var i = byteLength - 1\n var mul = 1\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)\n if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nfunction objectWriteUInt16 (buf, value, offset, littleEndian) {\n if (value < 0) value = 0xffff + value + 1\n for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {\n buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>\n (littleEndian ? i : 1 - i) * 8\n }\n}\n\nBuffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n } else {\n objectWriteUInt16(this, value, offset, true)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n } else {\n objectWriteUInt16(this, value, offset, false)\n }\n return offset + 2\n}\n\nfunction objectWriteUInt32 (buf, value, offset, littleEndian) {\n if (value < 0) value = 0xffffffff + value + 1\n for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {\n buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff\n }\n}\n\nBuffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset + 3] = (value >>> 24)\n this[offset + 2] = (value >>> 16)\n this[offset + 1] = (value >>> 8)\n this[offset] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, true)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, false)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) {\n var limit = Math.pow(2, 8 * byteLength - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = 0\n var mul = 1\n var sub = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) {\n var limit = Math.pow(2, 8 * byteLength - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = byteLength - 1\n var mul = 1\n var sub = 0\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)\n if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)\n if (value < 0) value = 0xff + value + 1\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n } else {\n objectWriteUInt16(this, value, offset, true)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n } else {\n objectWriteUInt16(this, value, offset, false)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n this[offset + 2] = (value >>> 16)\n this[offset + 3] = (value >>> 24)\n } else {\n objectWriteUInt32(this, value, offset, true)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (value < 0) value = 0xffffffff + value + 1\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, false)\n }\n return offset + 4\n}\n\nfunction checkIEEE754 (buf, value, offset, ext, max, min) {\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n if (offset < 0) throw new RangeError('Index out of range')\n}\n\nfunction writeFloat (buf, value, offset, littleEndian, noAssert) {\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)\n }\n ieee754.write(buf, value, offset, littleEndian, 23, 4)\n return offset + 4\n}\n\nBuffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {\n return writeFloat(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {\n return writeFloat(this, value, offset, false, noAssert)\n}\n\nfunction writeDouble (buf, value, offset, littleEndian, noAssert) {\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)\n }\n ieee754.write(buf, value, offset, littleEndian, 52, 8)\n return offset + 8\n}\n\nBuffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {\n return writeDouble(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {\n return writeDouble(this, value, offset, false, noAssert)\n}\n\n// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)\nBuffer.prototype.copy = function copy (target, targetStart, start, end) {\n if (!start) start = 0\n if (!end && end !== 0) end = this.length\n if (targetStart >= target.length) targetStart = target.length\n if (!targetStart) targetStart = 0\n if (end > 0 && end < start) end = start\n\n // Copy 0 bytes; we're done\n if (end === start) return 0\n if (target.length === 0 || this.length === 0) return 0\n\n // Fatal error conditions\n if (targetStart < 0) {\n throw new RangeError('targetStart out of bounds')\n }\n if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')\n if (end < 0) throw new RangeError('sourceEnd out of bounds')\n\n // Are we oob?\n if (end > this.length) end = this.length\n if (target.length - targetStart < end - start) {\n end = target.length - targetStart + start\n }\n\n var len = end - start\n var i\n\n if (this === target && start < targetStart && targetStart < end) {\n // descending copy from end\n for (i = len - 1; i >= 0; --i) {\n target[i + targetStart] = this[i + start]\n }\n } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {\n // ascending copy from start\n for (i = 0; i < len; ++i) {\n target[i + targetStart] = this[i + start]\n }\n } else {\n Uint8Array.prototype.set.call(\n target,\n this.subarray(start, start + len),\n targetStart\n )\n }\n\n return len\n}\n\n// Usage:\n// buffer.fill(number[, offset[, end]])\n// buffer.fill(buffer[, offset[, end]])\n// buffer.fill(string[, offset[, end]][, encoding])\nBuffer.prototype.fill = function fill (val, start, end, encoding) {\n // Handle string cases:\n if (typeof val === 'string') {\n if (typeof start === 'string') {\n encoding = start\n start = 0\n end = this.length\n } else if (typeof end === 'string') {\n encoding = end\n end = this.length\n }\n if (val.length === 1) {\n var code = val.charCodeAt(0)\n if (code < 256) {\n val = code\n }\n }\n if (encoding !== undefined && typeof encoding !== 'string') {\n throw new TypeError('encoding must be a string')\n }\n if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n } else if (typeof val === 'number') {\n val = val & 255\n }\n\n // Invalid ranges are not set to a default, so can range check early.\n if (start < 0 || this.length < start || this.length < end) {\n throw new RangeError('Out of range index')\n }\n\n if (end <= start) {\n return this\n }\n\n start = start >>> 0\n end = end === undefined ? this.length : end >>> 0\n\n if (!val) val = 0\n\n var i\n if (typeof val === 'number') {\n for (i = start; i < end; ++i) {\n this[i] = val\n }\n } else {\n var bytes = Buffer.isBuffer(val)\n ? val\n : utf8ToBytes(new Buffer(val, encoding).toString())\n var len = bytes.length\n for (i = 0; i < end - start; ++i) {\n this[i + start] = bytes[i % len]\n }\n }\n\n return this\n}\n\n// HELPER FUNCTIONS\n// ================\n\nvar INVALID_BASE64_RE = /[^+\\/0-9A-Za-z-_]/g\n\nfunction base64clean (str) {\n // Node strips out invalid characters like \\n and \\t from the string, base64-js does not\n str = stringtrim(str).replace(INVALID_BASE64_RE, '')\n // Node converts strings with length < 2 to ''\n if (str.length < 2) return ''\n // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not\n while (str.length % 4 !== 0) {\n str = str + '='\n }\n return str\n}\n\nfunction stringtrim (str) {\n if (str.trim) return str.trim()\n return str.replace(/^\\s+|\\s+$/g, '')\n}\n\nfunction toHex (n) {\n if (n < 16) return '0' + n.toString(16)\n return n.toString(16)\n}\n\nfunction utf8ToBytes (string, units) {\n units = units || Infinity\n var codePoint\n var length = string.length\n var leadSurrogate = null\n var bytes = []\n\n for (var i = 0; i < length; ++i) {\n codePoint = string.charCodeAt(i)\n\n // is surrogate component\n if (codePoint > 0xD7FF && codePoint < 0xE000) {\n // last char was a lead\n if (!leadSurrogate) {\n // no lead yet\n if (codePoint > 0xDBFF) {\n // unexpected trail\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n } else if (i + 1 === length) {\n // unpaired lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n }\n\n // valid lead\n leadSurrogate = codePoint\n\n continue\n }\n\n // 2 leads in a row\n if (codePoint < 0xDC00) {\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n leadSurrogate = codePoint\n continue\n }\n\n // valid surrogate pair\n codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000\n } else if (leadSurrogate) {\n // valid bmp char, but last char was a lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n }\n\n leadSurrogate = null\n\n // encode utf8\n if (codePoint < 0x80) {\n if ((units -= 1) < 0) break\n bytes.push(codePoint)\n } else if (codePoint < 0x800) {\n if ((units -= 2) < 0) break\n bytes.push(\n codePoint >> 0x6 | 0xC0,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x10000) {\n if ((units -= 3) < 0) break\n bytes.push(\n codePoint >> 0xC | 0xE0,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x110000) {\n if ((units -= 4) < 0) break\n bytes.push(\n codePoint >> 0x12 | 0xF0,\n codePoint >> 0xC & 0x3F | 0x80,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else {\n throw new Error('Invalid code point')\n }\n }\n\n return bytes\n}\n\nfunction asciiToBytes (str) {\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n // Node's code seems to be doing this and not & 0x7F..\n byteArray.push(str.charCodeAt(i) & 0xFF)\n }\n return byteArray\n}\n\nfunction utf16leToBytes (str, units) {\n var c, hi, lo\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n if ((units -= 2) < 0) break\n\n c = str.charCodeAt(i)\n hi = c >> 8\n lo = c % 256\n byteArray.push(lo)\n byteArray.push(hi)\n }\n\n return byteArray\n}\n\nfunction base64ToBytes (str) {\n return base64.toByteArray(base64clean(str))\n}\n\nfunction blitBuffer (src, dst, offset, length) {\n for (var i = 0; i < length; ++i) {\n if ((i + offset >= dst.length) || (i >= src.length)) break\n dst[i + offset] = src[i]\n }\n return i\n}\n\nfunction isnan (val) {\n return val !== val // eslint-disable-line no-self-compare\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/buffer/index.js\n// module id = 21\n// module chunks = 0","'use strict'\n\nexports.byteLength = byteLength\nexports.toByteArray = toByteArray\nexports.fromByteArray = fromByteArray\n\nvar lookup = []\nvar revLookup = []\nvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array\n\nvar code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\nfor (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i]\n revLookup[code.charCodeAt(i)] = i\n}\n\nrevLookup['-'.charCodeAt(0)] = 62\nrevLookup['_'.charCodeAt(0)] = 63\n\nfunction placeHoldersCount (b64) {\n var len = b64.length\n if (len % 4 > 0) {\n throw new Error('Invalid string. Length must be a multiple of 4')\n }\n\n // the number of equal signs (place holders)\n // if there are two placeholders, than the two characters before it\n // represent one byte\n // if there is only one, then the three characters before it represent 2 bytes\n // this is just a cheap hack to not do indexOf twice\n return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0\n}\n\nfunction byteLength (b64) {\n // base64 is 4/3 + up to two characters of the original data\n return b64.length * 3 / 4 - placeHoldersCount(b64)\n}\n\nfunction toByteArray (b64) {\n var i, j, l, tmp, placeHolders, arr\n var len = b64.length\n placeHolders = placeHoldersCount(b64)\n\n arr = new Arr(len * 3 / 4 - placeHolders)\n\n // if there are placeholders, only get up to the last complete 4 chars\n l = placeHolders > 0 ? len - 4 : len\n\n var L = 0\n\n for (i = 0, j = 0; i < l; i += 4, j += 3) {\n tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]\n arr[L++] = (tmp >> 16) & 0xFF\n arr[L++] = (tmp >> 8) & 0xFF\n arr[L++] = tmp & 0xFF\n }\n\n if (placeHolders === 2) {\n tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)\n arr[L++] = tmp & 0xFF\n } else if (placeHolders === 1) {\n tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)\n arr[L++] = (tmp >> 8) & 0xFF\n arr[L++] = tmp & 0xFF\n }\n\n return arr\n}\n\nfunction tripletToBase64 (num) {\n return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]\n}\n\nfunction encodeChunk (uint8, start, end) {\n var tmp\n var output = []\n for (var i = start; i < end; i += 3) {\n tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])\n output.push(tripletToBase64(tmp))\n }\n return output.join('')\n}\n\nfunction fromByteArray (uint8) {\n var tmp\n var len = uint8.length\n var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes\n var output = ''\n var parts = []\n var maxChunkLength = 16383 // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1]\n output += lookup[tmp >> 2]\n output += lookup[(tmp << 4) & 0x3F]\n output += '=='\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + (uint8[len - 1])\n output += lookup[tmp >> 10]\n output += lookup[(tmp >> 4) & 0x3F]\n output += lookup[(tmp << 2) & 0x3F]\n output += '='\n }\n\n parts.push(output)\n\n return parts.join('')\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/base64-js/index.js\n// module id = 22\n// module chunks = 0","exports.read = function (buffer, offset, isLE, mLen, nBytes) {\n var e, m\n var eLen = nBytes * 8 - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var nBits = -7\n var i = isLE ? (nBytes - 1) : 0\n var d = isLE ? -1 : 1\n var s = buffer[offset + i]\n\n i += d\n\n e = s & ((1 << (-nBits)) - 1)\n s >>= (-nBits)\n nBits += eLen\n for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}\n\n m = e & ((1 << (-nBits)) - 1)\n e >>= (-nBits)\n nBits += mLen\n for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}\n\n if (e === 0) {\n e = 1 - eBias\n } else if (e === eMax) {\n return m ? NaN : ((s ? -1 : 1) * Infinity)\n } else {\n m = m + Math.pow(2, mLen)\n e = e - eBias\n }\n return (s ? -1 : 1) * m * Math.pow(2, e - mLen)\n}\n\nexports.write = function (buffer, value, offset, isLE, mLen, nBytes) {\n var e, m, c\n var eLen = nBytes * 8 - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)\n var i = isLE ? 0 : (nBytes - 1)\n var d = isLE ? 1 : -1\n var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0\n\n value = Math.abs(value)\n\n if (isNaN(value) || value === Infinity) {\n m = isNaN(value) ? 1 : 0\n e = eMax\n } else {\n e = Math.floor(Math.log(value) / Math.LN2)\n if (value * (c = Math.pow(2, -e)) < 1) {\n e--\n c *= 2\n }\n if (e + eBias >= 1) {\n value += rt / c\n } else {\n value += rt * Math.pow(2, 1 - eBias)\n }\n if (value * c >= 2) {\n e++\n c /= 2\n }\n\n if (e + eBias >= eMax) {\n m = 0\n e = eMax\n } else if (e + eBias >= 1) {\n m = (value * c - 1) * Math.pow(2, mLen)\n e = e + eBias\n } else {\n m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)\n e = 0\n }\n }\n\n for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}\n\n e = (e << mLen) | m\n eLen += mLen\n for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}\n\n buffer[offset + i - d] |= s * 128\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ieee754/index.js\n// module id = 23\n// module chunks = 0","var toString = {}.toString;\n\nmodule.exports = Array.isArray || function (arr) {\n return toString.call(arr) == '[object Array]';\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/buffer/~/isarray/index.js\n// module id = 24\n// module chunks = 0","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// NOTE: These type checking functions intentionally don't use `instanceof`\n// because it is fragile and can be easily faked with `Object.create()`.\n\nfunction isArray(arg) {\n if (Array.isArray) {\n return Array.isArray(arg);\n }\n return objectToString(arg) === '[object Array]';\n}\nexports.isArray = isArray;\n\nfunction isBoolean(arg) {\n return typeof arg === 'boolean';\n}\nexports.isBoolean = isBoolean;\n\nfunction isNull(arg) {\n return arg === null;\n}\nexports.isNull = isNull;\n\nfunction isNullOrUndefined(arg) {\n return arg == null;\n}\nexports.isNullOrUndefined = isNullOrUndefined;\n\nfunction isNumber(arg) {\n return typeof arg === 'number';\n}\nexports.isNumber = isNumber;\n\nfunction isString(arg) {\n return typeof arg === 'string';\n}\nexports.isString = isString;\n\nfunction isSymbol(arg) {\n return typeof arg === 'symbol';\n}\nexports.isSymbol = isSymbol;\n\nfunction isUndefined(arg) {\n return arg === void 0;\n}\nexports.isUndefined = isUndefined;\n\nfunction isRegExp(re) {\n return objectToString(re) === '[object RegExp]';\n}\nexports.isRegExp = isRegExp;\n\nfunction isObject(arg) {\n return typeof arg === 'object' && arg !== null;\n}\nexports.isObject = isObject;\n\nfunction isDate(d) {\n return objectToString(d) === '[object Date]';\n}\nexports.isDate = isDate;\n\nfunction isError(e) {\n return (objectToString(e) === '[object Error]' || e instanceof Error);\n}\nexports.isError = isError;\n\nfunction isFunction(arg) {\n return typeof arg === 'function';\n}\nexports.isFunction = isFunction;\n\nfunction isPrimitive(arg) {\n return arg === null ||\n typeof arg === 'boolean' ||\n typeof arg === 'number' ||\n typeof arg === 'string' ||\n typeof arg === 'symbol' || // ES6 symbol\n typeof arg === 'undefined';\n}\nexports.isPrimitive = isPrimitive;\n\nexports.isBuffer = Buffer.isBuffer;\n\nfunction objectToString(o) {\n return Object.prototype.toString.call(o);\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/core-util-is/lib/util.js\n// module id = 25\n// module chunks = 0","/* (ignored) */\n\n\n//////////////////\n// WEBPACK FOOTER\n// util (ignored)\n// module id = 26\n// module chunks = 0","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a duplex stream is just a stream that is both readable and writable.\n// Since JS doesn't have multiple prototypal inheritance, this class\n// prototypally inherits from Readable, and then parasitically from\n// Writable.\n\nmodule.exports = Duplex;\n\n/**/\nvar objectKeys = Object.keys || function (obj) {\n var keys = [];\n for (var key in obj) keys.push(key);\n return keys;\n}\n/**/\n\n\n/**/\nvar util = require('core-util-is');\nutil.inherits = require('inherits');\n/**/\n\nvar Readable = require('./_stream_readable');\nvar Writable = require('./_stream_writable');\n\nutil.inherits(Duplex, Readable);\n\nforEach(objectKeys(Writable.prototype), function(method) {\n if (!Duplex.prototype[method])\n Duplex.prototype[method] = Writable.prototype[method];\n});\n\nfunction Duplex(options) {\n if (!(this instanceof Duplex))\n return new Duplex(options);\n\n Readable.call(this, options);\n Writable.call(this, options);\n\n if (options && options.readable === false)\n this.readable = false;\n\n if (options && options.writable === false)\n this.writable = false;\n\n this.allowHalfOpen = true;\n if (options && options.allowHalfOpen === false)\n this.allowHalfOpen = false;\n\n this.once('end', onend);\n}\n\n// the no-half-open enforcer\nfunction onend() {\n // if we allow half-open state, or if the writable side ended,\n // then we're ok.\n if (this.allowHalfOpen || this._writableState.ended)\n return;\n\n // no more data can be written.\n // But allow more writes to happen in this tick.\n process.nextTick(this.end.bind(this));\n}\n\nfunction forEach (xs, f) {\n for (var i = 0, l = xs.length; i < l; i++) {\n f(xs[i], i);\n }\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/readable-stream/lib/_stream_duplex.js\n// module id = 27\n// module chunks = 0","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// A bit simpler than readable streams.\n// Implement an async ._write(chunk, cb), and it'll handle all\n// the drain event emission and buffering.\n\nmodule.exports = Writable;\n\n/**/\nvar Buffer = require('buffer').Buffer;\n/**/\n\nWritable.WritableState = WritableState;\n\n\n/**/\nvar util = require('core-util-is');\nutil.inherits = require('inherits');\n/**/\n\nvar Stream = require('stream');\n\nutil.inherits(Writable, Stream);\n\nfunction WriteReq(chunk, encoding, cb) {\n this.chunk = chunk;\n this.encoding = encoding;\n this.callback = cb;\n}\n\nfunction WritableState(options, stream) {\n var Duplex = require('./_stream_duplex');\n\n options = options || {};\n\n // the point at which write() starts returning false\n // Note: 0 is a valid value, means that we always return false if\n // the entire buffer is not flushed immediately on write()\n var hwm = options.highWaterMark;\n var defaultHwm = options.objectMode ? 16 : 16 * 1024;\n this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;\n\n // object stream flag to indicate whether or not this stream\n // contains buffers or objects.\n this.objectMode = !!options.objectMode;\n\n if (stream instanceof Duplex)\n this.objectMode = this.objectMode || !!options.writableObjectMode;\n\n // cast to ints.\n this.highWaterMark = ~~this.highWaterMark;\n\n this.needDrain = false;\n // at the start of calling end()\n this.ending = false;\n // when end() has been called, and returned\n this.ended = false;\n // when 'finish' is emitted\n this.finished = false;\n\n // should we decode strings into buffers before passing to _write?\n // this is here so that some node-core streams can optimize string\n // handling at a lower level.\n var noDecode = options.decodeStrings === false;\n this.decodeStrings = !noDecode;\n\n // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n this.defaultEncoding = options.defaultEncoding || 'utf8';\n\n // not an actual buffer we keep track of, but a measurement\n // of how much we're waiting to get pushed to some underlying\n // socket or file.\n this.length = 0;\n\n // a flag to see when we're in the middle of a write.\n this.writing = false;\n\n // when true all writes will be buffered until .uncork() call\n this.corked = 0;\n\n // a flag to be able to tell if the onwrite cb is called immediately,\n // or on a later tick. We set this to true at first, because any\n // actions that shouldn't happen until \"later\" should generally also\n // not happen before the first write call.\n this.sync = true;\n\n // a flag to know if we're processing previously buffered items, which\n // may call the _write() callback in the same tick, so that we don't\n // end up in an overlapped onwrite situation.\n this.bufferProcessing = false;\n\n // the callback that's passed to _write(chunk,cb)\n this.onwrite = function(er) {\n onwrite(stream, er);\n };\n\n // the callback that the user supplies to write(chunk,encoding,cb)\n this.writecb = null;\n\n // the amount that is being written when _write is called.\n this.writelen = 0;\n\n this.buffer = [];\n\n // number of pending user-supplied write callbacks\n // this must be 0 before 'finish' can be emitted\n this.pendingcb = 0;\n\n // emit prefinish if the only thing we're waiting for is _write cbs\n // This is relevant for synchronous Transform streams\n this.prefinished = false;\n\n // True if the error was already emitted and should not be thrown again\n this.errorEmitted = false;\n}\n\nfunction Writable(options) {\n var Duplex = require('./_stream_duplex');\n\n // Writable ctor is applied to Duplexes, though they're not\n // instanceof Writable, they're instanceof Readable.\n if (!(this instanceof Writable) && !(this instanceof Duplex))\n return new Writable(options);\n\n this._writableState = new WritableState(options, this);\n\n // legacy.\n this.writable = true;\n\n Stream.call(this);\n}\n\n// Otherwise people can pipe Writable streams, which is just wrong.\nWritable.prototype.pipe = function() {\n this.emit('error', new Error('Cannot pipe. Not readable.'));\n};\n\n\nfunction writeAfterEnd(stream, state, cb) {\n var er = new Error('write after end');\n // TODO: defer error events consistently everywhere, not just the cb\n stream.emit('error', er);\n process.nextTick(function() {\n cb(er);\n });\n}\n\n// If we get something that is not a buffer, string, null, or undefined,\n// and we're not in objectMode, then that's an error.\n// Otherwise stream chunks are all considered to be of length=1, and the\n// watermarks determine how many objects to keep in the buffer, rather than\n// how many bytes or characters.\nfunction validChunk(stream, state, chunk, cb) {\n var valid = true;\n if (!util.isBuffer(chunk) &&\n !util.isString(chunk) &&\n !util.isNullOrUndefined(chunk) &&\n !state.objectMode) {\n var er = new TypeError('Invalid non-string/buffer chunk');\n stream.emit('error', er);\n process.nextTick(function() {\n cb(er);\n });\n valid = false;\n }\n return valid;\n}\n\nWritable.prototype.write = function(chunk, encoding, cb) {\n var state = this._writableState;\n var ret = false;\n\n if (util.isFunction(encoding)) {\n cb = encoding;\n encoding = null;\n }\n\n if (util.isBuffer(chunk))\n encoding = 'buffer';\n else if (!encoding)\n encoding = state.defaultEncoding;\n\n if (!util.isFunction(cb))\n cb = function() {};\n\n if (state.ended)\n writeAfterEnd(this, state, cb);\n else if (validChunk(this, state, chunk, cb)) {\n state.pendingcb++;\n ret = writeOrBuffer(this, state, chunk, encoding, cb);\n }\n\n return ret;\n};\n\nWritable.prototype.cork = function() {\n var state = this._writableState;\n\n state.corked++;\n};\n\nWritable.prototype.uncork = function() {\n var state = this._writableState;\n\n if (state.corked) {\n state.corked--;\n\n if (!state.writing &&\n !state.corked &&\n !state.finished &&\n !state.bufferProcessing &&\n state.buffer.length)\n clearBuffer(this, state);\n }\n};\n\nfunction decodeChunk(state, chunk, encoding) {\n if (!state.objectMode &&\n state.decodeStrings !== false &&\n util.isString(chunk)) {\n chunk = new Buffer(chunk, encoding);\n }\n return chunk;\n}\n\n// if we're already writing something, then just put this\n// in the queue, and wait our turn. Otherwise, call _write\n// If we return false, then we need a drain event, so set that flag.\nfunction writeOrBuffer(stream, state, chunk, encoding, cb) {\n chunk = decodeChunk(state, chunk, encoding);\n if (util.isBuffer(chunk))\n encoding = 'buffer';\n var len = state.objectMode ? 1 : chunk.length;\n\n state.length += len;\n\n var ret = state.length < state.highWaterMark;\n // we must ensure that previous needDrain will not be reset to false.\n if (!ret)\n state.needDrain = true;\n\n if (state.writing || state.corked)\n state.buffer.push(new WriteReq(chunk, encoding, cb));\n else\n doWrite(stream, state, false, len, chunk, encoding, cb);\n\n return ret;\n}\n\nfunction doWrite(stream, state, writev, len, chunk, encoding, cb) {\n state.writelen = len;\n state.writecb = cb;\n state.writing = true;\n state.sync = true;\n if (writev)\n stream._writev(chunk, state.onwrite);\n else\n stream._write(chunk, encoding, state.onwrite);\n state.sync = false;\n}\n\nfunction onwriteError(stream, state, sync, er, cb) {\n if (sync)\n process.nextTick(function() {\n state.pendingcb--;\n cb(er);\n });\n else {\n state.pendingcb--;\n cb(er);\n }\n\n stream._writableState.errorEmitted = true;\n stream.emit('error', er);\n}\n\nfunction onwriteStateUpdate(state) {\n state.writing = false;\n state.writecb = null;\n state.length -= state.writelen;\n state.writelen = 0;\n}\n\nfunction onwrite(stream, er) {\n var state = stream._writableState;\n var sync = state.sync;\n var cb = state.writecb;\n\n onwriteStateUpdate(state);\n\n if (er)\n onwriteError(stream, state, sync, er, cb);\n else {\n // Check if we're actually ready to finish, but don't emit yet\n var finished = needFinish(stream, state);\n\n if (!finished &&\n !state.corked &&\n !state.bufferProcessing &&\n state.buffer.length) {\n clearBuffer(stream, state);\n }\n\n if (sync) {\n process.nextTick(function() {\n afterWrite(stream, state, finished, cb);\n });\n } else {\n afterWrite(stream, state, finished, cb);\n }\n }\n}\n\nfunction afterWrite(stream, state, finished, cb) {\n if (!finished)\n onwriteDrain(stream, state);\n state.pendingcb--;\n cb();\n finishMaybe(stream, state);\n}\n\n// Must force callback to be called on nextTick, so that we don't\n// emit 'drain' before the write() consumer gets the 'false' return\n// value, and has a chance to attach a 'drain' listener.\nfunction onwriteDrain(stream, state) {\n if (state.length === 0 && state.needDrain) {\n state.needDrain = false;\n stream.emit('drain');\n }\n}\n\n\n// if there's something in the buffer waiting, then process it\nfunction clearBuffer(stream, state) {\n state.bufferProcessing = true;\n\n if (stream._writev && state.buffer.length > 1) {\n // Fast case, write everything using _writev()\n var cbs = [];\n for (var c = 0; c < state.buffer.length; c++)\n cbs.push(state.buffer[c].callback);\n\n // count the one we are adding, as well.\n // TODO(isaacs) clean this up\n state.pendingcb++;\n doWrite(stream, state, true, state.length, state.buffer, '', function(err) {\n for (var i = 0; i < cbs.length; i++) {\n state.pendingcb--;\n cbs[i](err);\n }\n });\n\n // Clear buffer\n state.buffer = [];\n } else {\n // Slow case, write chunks one-by-one\n for (var c = 0; c < state.buffer.length; c++) {\n var entry = state.buffer[c];\n var chunk = entry.chunk;\n var encoding = entry.encoding;\n var cb = entry.callback;\n var len = state.objectMode ? 1 : chunk.length;\n\n doWrite(stream, state, false, len, chunk, encoding, cb);\n\n // if we didn't call the onwrite immediately, then\n // it means that we need to wait until it does.\n // also, that means that the chunk and cb are currently\n // being processed, so move the buffer counter past them.\n if (state.writing) {\n c++;\n break;\n }\n }\n\n if (c < state.buffer.length)\n state.buffer = state.buffer.slice(c);\n else\n state.buffer.length = 0;\n }\n\n state.bufferProcessing = false;\n}\n\nWritable.prototype._write = function(chunk, encoding, cb) {\n cb(new Error('not implemented'));\n\n};\n\nWritable.prototype._writev = null;\n\nWritable.prototype.end = function(chunk, encoding, cb) {\n var state = this._writableState;\n\n if (util.isFunction(chunk)) {\n cb = chunk;\n chunk = null;\n encoding = null;\n } else if (util.isFunction(encoding)) {\n cb = encoding;\n encoding = null;\n }\n\n if (!util.isNullOrUndefined(chunk))\n this.write(chunk, encoding);\n\n // .end() fully uncorks\n if (state.corked) {\n state.corked = 1;\n this.uncork();\n }\n\n // ignore unnecessary end() calls.\n if (!state.ending && !state.finished)\n endWritable(this, state, cb);\n};\n\n\nfunction needFinish(stream, state) {\n return (state.ending &&\n state.length === 0 &&\n !state.finished &&\n !state.writing);\n}\n\nfunction prefinish(stream, state) {\n if (!state.prefinished) {\n state.prefinished = true;\n stream.emit('prefinish');\n }\n}\n\nfunction finishMaybe(stream, state) {\n var need = needFinish(stream, state);\n if (need) {\n if (state.pendingcb === 0) {\n prefinish(stream, state);\n state.finished = true;\n stream.emit('finish');\n } else\n prefinish(stream, state);\n }\n return need;\n}\n\nfunction endWritable(stream, state, cb) {\n state.ending = true;\n finishMaybe(stream, state);\n if (cb) {\n if (state.finished)\n process.nextTick(cb);\n else\n stream.once('finish', cb);\n }\n state.ended = true;\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/readable-stream/lib/_stream_writable.js\n// module id = 28\n// module chunks = 0","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nvar Buffer = require('buffer').Buffer;\n\nvar isBufferEncoding = Buffer.isEncoding\n || function(encoding) {\n switch (encoding && encoding.toLowerCase()) {\n case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true;\n default: return false;\n }\n }\n\n\nfunction assertEncoding(encoding) {\n if (encoding && !isBufferEncoding(encoding)) {\n throw new Error('Unknown encoding: ' + encoding);\n }\n}\n\n// StringDecoder provides an interface for efficiently splitting a series of\n// buffers into a series of JS strings without breaking apart multi-byte\n// characters. CESU-8 is handled as part of the UTF-8 encoding.\n//\n// @TODO Handling all encodings inside a single object makes it very difficult\n// to reason about this code, so it should be split up in the future.\n// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code\n// points as used by CESU-8.\nvar StringDecoder = exports.StringDecoder = function(encoding) {\n this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');\n assertEncoding(encoding);\n switch (this.encoding) {\n case 'utf8':\n // CESU-8 represents each of Surrogate Pair by 3-bytes\n this.surrogateSize = 3;\n break;\n case 'ucs2':\n case 'utf16le':\n // UTF-16 represents each of Surrogate Pair by 2-bytes\n this.surrogateSize = 2;\n this.detectIncompleteChar = utf16DetectIncompleteChar;\n break;\n case 'base64':\n // Base-64 stores 3 bytes in 4 chars, and pads the remainder.\n this.surrogateSize = 3;\n this.detectIncompleteChar = base64DetectIncompleteChar;\n break;\n default:\n this.write = passThroughWrite;\n return;\n }\n\n // Enough space to store all bytes of a single character. UTF-8 needs 4\n // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate).\n this.charBuffer = new Buffer(6);\n // Number of bytes received for the current incomplete multi-byte character.\n this.charReceived = 0;\n // Number of bytes expected for the current incomplete multi-byte character.\n this.charLength = 0;\n};\n\n\n// write decodes the given buffer and returns it as JS string that is\n// guaranteed to not contain any partial multi-byte characters. Any partial\n// character found at the end of the buffer is buffered up, and will be\n// returned when calling write again with the remaining bytes.\n//\n// Note: Converting a Buffer containing an orphan surrogate to a String\n// currently works, but converting a String to a Buffer (via `new Buffer`, or\n// Buffer#write) will replace incomplete surrogates with the unicode\n// replacement character. See https://codereview.chromium.org/121173009/ .\nStringDecoder.prototype.write = function(buffer) {\n var charStr = '';\n // if our last write ended with an incomplete multibyte character\n while (this.charLength) {\n // determine how many remaining bytes this buffer has to offer for this char\n var available = (buffer.length >= this.charLength - this.charReceived) ?\n this.charLength - this.charReceived :\n buffer.length;\n\n // add the new bytes to the char buffer\n buffer.copy(this.charBuffer, this.charReceived, 0, available);\n this.charReceived += available;\n\n if (this.charReceived < this.charLength) {\n // still not enough chars in this buffer? wait for more ...\n return '';\n }\n\n // remove bytes belonging to the current character from the buffer\n buffer = buffer.slice(available, buffer.length);\n\n // get the character that was split\n charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);\n\n // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character\n var charCode = charStr.charCodeAt(charStr.length - 1);\n if (charCode >= 0xD800 && charCode <= 0xDBFF) {\n this.charLength += this.surrogateSize;\n charStr = '';\n continue;\n }\n this.charReceived = this.charLength = 0;\n\n // if there are no more bytes in this buffer, just emit our char\n if (buffer.length === 0) {\n return charStr;\n }\n break;\n }\n\n // determine and set charLength / charReceived\n this.detectIncompleteChar(buffer);\n\n var end = buffer.length;\n if (this.charLength) {\n // buffer the incomplete character bytes we got\n buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end);\n end -= this.charReceived;\n }\n\n charStr += buffer.toString(this.encoding, 0, end);\n\n var end = charStr.length - 1;\n var charCode = charStr.charCodeAt(end);\n // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character\n if (charCode >= 0xD800 && charCode <= 0xDBFF) {\n var size = this.surrogateSize;\n this.charLength += size;\n this.charReceived += size;\n this.charBuffer.copy(this.charBuffer, size, 0, size);\n buffer.copy(this.charBuffer, 0, 0, size);\n return charStr.substring(0, end);\n }\n\n // or just emit the charStr\n return charStr;\n};\n\n// detectIncompleteChar determines if there is an incomplete UTF-8 character at\n// the end of the given buffer. If so, it sets this.charLength to the byte\n// length that character, and sets this.charReceived to the number of bytes\n// that are available for this character.\nStringDecoder.prototype.detectIncompleteChar = function(buffer) {\n // determine how many bytes we have to check at the end of this buffer\n var i = (buffer.length >= 3) ? 3 : buffer.length;\n\n // Figure out if one of the last i bytes of our buffer announces an\n // incomplete char.\n for (; i > 0; i--) {\n var c = buffer[buffer.length - i];\n\n // See http://en.wikipedia.org/wiki/UTF-8#Description\n\n // 110XXXXX\n if (i == 1 && c >> 5 == 0x06) {\n this.charLength = 2;\n break;\n }\n\n // 1110XXXX\n if (i <= 2 && c >> 4 == 0x0E) {\n this.charLength = 3;\n break;\n }\n\n // 11110XXX\n if (i <= 3 && c >> 3 == 0x1E) {\n this.charLength = 4;\n break;\n }\n }\n this.charReceived = i;\n};\n\nStringDecoder.prototype.end = function(buffer) {\n var res = '';\n if (buffer && buffer.length)\n res = this.write(buffer);\n\n if (this.charReceived) {\n var cr = this.charReceived;\n var buf = this.charBuffer;\n var enc = this.encoding;\n res += buf.slice(0, cr).toString(enc);\n }\n\n return res;\n};\n\nfunction passThroughWrite(buffer) {\n return buffer.toString(this.encoding);\n}\n\nfunction utf16DetectIncompleteChar(buffer) {\n this.charReceived = buffer.length % 2;\n this.charLength = this.charReceived ? 2 : 0;\n}\n\nfunction base64DetectIncompleteChar(buffer) {\n this.charReceived = buffer.length % 3;\n this.charLength = this.charReceived ? 3 : 0;\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/string_decoder/index.js\n// module id = 29\n// module chunks = 0","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n\n// a transform stream is a readable/writable stream where you do\n// something with the data. Sometimes it's called a \"filter\",\n// but that's not a great name for it, since that implies a thing where\n// some bits pass through, and others are simply ignored. (That would\n// be a valid example of a transform, of course.)\n//\n// While the output is causally related to the input, it's not a\n// necessarily symmetric or synchronous transformation. For example,\n// a zlib stream might take multiple plain-text writes(), and then\n// emit a single compressed chunk some time in the future.\n//\n// Here's how this works:\n//\n// The Transform stream has all the aspects of the readable and writable\n// stream classes. When you write(chunk), that calls _write(chunk,cb)\n// internally, and returns false if there's a lot of pending writes\n// buffered up. When you call read(), that calls _read(n) until\n// there's enough pending readable data buffered up.\n//\n// In a transform stream, the written data is placed in a buffer. When\n// _read(n) is called, it transforms the queued up data, calling the\n// buffered _write cb's as it consumes chunks. If consuming a single\n// written chunk would result in multiple output chunks, then the first\n// outputted bit calls the readcb, and subsequent chunks just go into\n// the read buffer, and will cause it to emit 'readable' if necessary.\n//\n// This way, back-pressure is actually determined by the reading side,\n// since _read has to be called to start processing a new chunk. However,\n// a pathological inflate type of transform can cause excessive buffering\n// here. For example, imagine a stream where every byte of input is\n// interpreted as an integer from 0-255, and then results in that many\n// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in\n// 1kb of data being output. In this case, you could write a very small\n// amount of input, and end up with a very large amount of output. In\n// such a pathological inflating mechanism, there'd be no way to tell\n// the system to stop doing the transform. A single 4MB write could\n// cause the system to run out of memory.\n//\n// However, even in such a pathological case, only a single written chunk\n// would be consumed, and then the rest would wait (un-transformed) until\n// the results of the previous transformed chunk were consumed.\n\nmodule.exports = Transform;\n\nvar Duplex = require('./_stream_duplex');\n\n/**/\nvar util = require('core-util-is');\nutil.inherits = require('inherits');\n/**/\n\nutil.inherits(Transform, Duplex);\n\n\nfunction TransformState(options, stream) {\n this.afterTransform = function(er, data) {\n return afterTransform(stream, er, data);\n };\n\n this.needTransform = false;\n this.transforming = false;\n this.writecb = null;\n this.writechunk = null;\n}\n\nfunction afterTransform(stream, er, data) {\n var ts = stream._transformState;\n ts.transforming = false;\n\n var cb = ts.writecb;\n\n if (!cb)\n return stream.emit('error', new Error('no writecb in Transform class'));\n\n ts.writechunk = null;\n ts.writecb = null;\n\n if (!util.isNullOrUndefined(data))\n stream.push(data);\n\n if (cb)\n cb(er);\n\n var rs = stream._readableState;\n rs.reading = false;\n if (rs.needReadable || rs.length < rs.highWaterMark) {\n stream._read(rs.highWaterMark);\n }\n}\n\n\nfunction Transform(options) {\n if (!(this instanceof Transform))\n return new Transform(options);\n\n Duplex.call(this, options);\n\n this._transformState = new TransformState(options, this);\n\n // when the writable side finishes, then flush out anything remaining.\n var stream = this;\n\n // start out asking for a readable event once data is transformed.\n this._readableState.needReadable = true;\n\n // we have implemented the _read method, and done the other things\n // that Readable wants before the first _read call, so unset the\n // sync guard flag.\n this._readableState.sync = false;\n\n this.once('prefinish', function() {\n if (util.isFunction(this._flush))\n this._flush(function(er) {\n done(stream, er);\n });\n else\n done(stream);\n });\n}\n\nTransform.prototype.push = function(chunk, encoding) {\n this._transformState.needTransform = false;\n return Duplex.prototype.push.call(this, chunk, encoding);\n};\n\n// This is the part where you do stuff!\n// override this function in implementation classes.\n// 'chunk' is an input chunk.\n//\n// Call `push(newChunk)` to pass along transformed output\n// to the readable side. You may call 'push' zero or more times.\n//\n// Call `cb(err)` when you are done with this chunk. If you pass\n// an error, then that'll put the hurt on the whole operation. If you\n// never call cb(), then you'll never get another chunk.\nTransform.prototype._transform = function(chunk, encoding, cb) {\n throw new Error('not implemented');\n};\n\nTransform.prototype._write = function(chunk, encoding, cb) {\n var ts = this._transformState;\n ts.writecb = cb;\n ts.writechunk = chunk;\n ts.writeencoding = encoding;\n if (!ts.transforming) {\n var rs = this._readableState;\n if (ts.needTransform ||\n rs.needReadable ||\n rs.length < rs.highWaterMark)\n this._read(rs.highWaterMark);\n }\n};\n\n// Doesn't matter what the args are here.\n// _transform does all the work.\n// That we got here means that the readable side wants more data.\nTransform.prototype._read = function(n) {\n var ts = this._transformState;\n\n if (!util.isNull(ts.writechunk) && ts.writecb && !ts.transforming) {\n ts.transforming = true;\n this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);\n } else {\n // mark that we need a transform, so that any data that comes in\n // will get processed, now that we've asked for it.\n ts.needTransform = true;\n }\n};\n\n\nfunction done(stream, er) {\n if (er)\n return stream.emit('error', er);\n\n // if there's nothing in the write buffer, then that means\n // that nothing more will ever be provided\n var ws = stream._writableState;\n var ts = stream._transformState;\n\n if (ws.length)\n throw new Error('calling transform done when ws.length != 0');\n\n if (ts.transforming)\n throw new Error('calling transform done when still transforming');\n\n return stream.push(null);\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/readable-stream/lib/_stream_transform.js\n// module id = 30\n// module chunks = 0","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a passthrough stream.\n// basically just the most minimal sort of Transform stream.\n// Every written chunk gets output as-is.\n\nmodule.exports = PassThrough;\n\nvar Transform = require('./_stream_transform');\n\n/**/\nvar util = require('core-util-is');\nutil.inherits = require('inherits');\n/**/\n\nutil.inherits(PassThrough, Transform);\n\nfunction PassThrough(options) {\n if (!(this instanceof PassThrough))\n return new PassThrough(options);\n\n Transform.call(this, options);\n}\n\nPassThrough.prototype._transform = function(chunk, encoding, cb) {\n cb(null, chunk);\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/readable-stream/lib/_stream_passthrough.js\n// module id = 31\n// module chunks = 0","module.exports = require(\"./lib/_stream_writable.js\")\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/readable-stream/writable.js\n// module id = 32\n// module chunks = 0","module.exports = require(\"./lib/_stream_duplex.js\")\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/readable-stream/duplex.js\n// module id = 33\n// module chunks = 0","module.exports = require(\"./lib/_stream_transform.js\")\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/readable-stream/transform.js\n// module id = 34\n// module chunks = 0","module.exports = require(\"./lib/_stream_passthrough.js\")\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/readable-stream/passthrough.js\n// module id = 35\n// module chunks = 0","import PouchDB from 'pouchdb'\nimport pouchdbFind from 'pouchdb-find'\nimport { DOCTYPE_FILES } from './doctypes'\n\nlet pluginLoaded = false\n\nexport function init (cozy, { options = {}, doctypes = [], timer = false }) {\n for (let doctype of doctypes) {\n createDatabase(cozy, doctype, options)\n }\n if (timer) { startAllSync(cozy, timer) }\n}\n\nexport function createDatabase (cozy, doctype, options = {}, timer = false) {\n if (!pluginLoaded) {\n PouchDB.plugin(pouchdbFind)\n pluginLoaded = true\n }\n cozy._offline = cozy._offline || []\n cozy._offline[doctype] = cozy._offline[doctype] || {}\n let offline = cozy._offline[doctype]\n if (offline && offline.database) { return offline.database }\n offline.database = new PouchDB(doctype, options)\n offline.timer = timer\n offline.autoSync = null\n if (timer) { startSync(cozy, doctype, timer) }\n createIndexes(cozy, offline.database, doctype)\n return offline.database\n}\n\nexport function hasDatabase (cozy, doctype) {\n return cozy._offline !== null &&\n doctype in cozy._offline &&\n cozy._offline[doctype].database !== undefined\n}\n\nexport function getDatabase (cozy, doctype) {\n if (hasDatabase(cozy, doctype)) {\n return cozy._offline[doctype].database\n }\n return\n}\n\nexport function destroyDatabase (cozy, doctype) {\n if (hasDatabase(cozy, doctype)) {\n stopSync(cozy, doctype)\n getDatabase(cozy, doctype).destroy()\n delete getDatabase(cozy, doctype)\n }\n}\n\nexport function getDoctypes (cozy) {\n if (cozy._offline === null) { return [] }\n return Object.keys(cozy._offline)\n}\n\n//\n// SYNC\n//\n\nexport function startAllSync (cozy, timer) {\n if (timer) {\n const doctypes = getDoctypes(cozy)\n doctypes.forEach((doctype) => {\n startSync(cozy, doctype, timer)\n })\n }\n}\n\nexport function stopAllSync (cozy) {\n const doctypes = getDoctypes(cozy)\n doctypes.forEach((doctype) => {\n stopSync(cozy, doctype)\n })\n}\n\nexport function startSync (cozy, doctype, timer) {\n // TODO: add timer limitation for not flooding Gozy\n if (hasDatabase(cozy, doctype)) {\n if (hasSync(cozy, doctype)) {\n if (timer === cozy._offline[doctype].timer) { return }\n stopSync(cozy, doctype)\n }\n let offline = cozy._offline[doctype]\n offline.timer = timer\n offline.autoSync = setInterval(() => {\n if (offline.replicate === undefined) {\n offline.replicate = replicateFromCozy(cozy, doctype)\n .on('complete', (info) => {\n delete offline.replicate\n })\n // TODO: add replicationToCozy\n }\n }, timer * 1000)\n }\n}\n\nexport function hasSync (cozy, doctype) {\n return cozy._offline !== null &&\n doctype in cozy._offline &&\n cozy._offline[doctype].autoSync !== null\n}\n\nexport function stopSync (cozy, doctype) {\n if (hasSync(cozy, doctype)) {\n let offline = cozy._offline[doctype]\n if (offline.replication) { offline.replication.cancel() }\n clearInterval(offline.autoSync)\n delete offline.autoSync\n }\n}\n\nexport function replicateFromCozy (cozy, doctype, options = {}, events = {}) {\n if (hasDatabase(cozy, doctype)) {\n if (options.live === true) {\n throw new Error('You can\\'t use `live` option with Cozy couchdb.')\n }\n const url = cozy._url + '/data/' + doctype\n let db = getDatabase(cozy, doctype)\n let replication = db.replicate.from(url, options)\n const eventNames = [\n 'change', 'paused', 'active', 'denied', 'complete', 'error'\n ]\n for (let eventName of eventNames) {\n if (typeof events[eventName] === 'function') {\n replication.on(eventName, events[eventName])\n }\n }\n return replication\n } else {\n throw new Error(`You should add this doctype: ${doctype} to offline.`)\n }\n}\n\nfunction createIndexes (cozy, db, doctype) {\n if (doctype === DOCTYPE_FILES) {\n db.createIndex({index: {fields: ['dir_id']}})\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/offline.js","module.exports = __WEBPACK_EXTERNAL_MODULE_37__;\n\n\n//////////////////\n// WEBPACK FOOTER\n// external \"pouchdb\"\n// module id = 37\n// module chunks = 0","module.exports = __WEBPACK_EXTERNAL_MODULE_38__;\n\n\n//////////////////\n// WEBPACK FOOTER\n// external \"pouchdb-find\"\n// module id = 38\n// module chunks = 0","import {cozyFetchJSON} from './fetch'\n\nexport function diskUsage (cozy) {\n return cozyFetchJSON(cozy, 'GET', `/settings/disk-usage`)\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/settings.js","import {cozyFetchJSON} from './fetch'\nimport { DOCTYPE_FILES } from './doctypes'\n\nexport function addReferencedFiles (cozy, doc, ids) {\n if (!doc) throw new Error('missing doc argument')\n if (!Array.isArray(ids)) ids = [ids]\n\n const refs = ids.map((id) => ({type: DOCTYPE_FILES, id: id}))\n\n return cozyFetchJSON(cozy, 'POST', makeReferencesPath(doc), {data: refs})\n}\n\nexport function listReferencedFiles (cozy, doc) {\n if (!doc) throw new Error('missing doc argument')\n return cozyFetchJSON(cozy, 'GET', makeReferencesPath(doc))\n .then((files) => files.map((file) => file._id))\n}\n\nfunction makeReferencesPath (doc) {\n const type = encodeURIComponent(doc._type)\n const id = encodeURIComponent(doc._id)\n return `/data/${type}/${id}/relationships/references`\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/relations.js"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/cozy-client.node.js b/dist/cozy-client.node.js index 5b1e98ff..786ffa93 100644 --- a/dist/cozy-client.node.js +++ b/dist/cozy-client.node.js @@ -90,15 +90,15 @@ var files = _interopRequireWildcard(_files); - var _offline = __webpack_require__(15); + var _offline = __webpack_require__(16); var offline = _interopRequireWildcard(_offline); - var _settings = __webpack_require__(18); + var _settings = __webpack_require__(17); var settings = _interopRequireWildcard(_settings); - var _relations = __webpack_require__(19); + var _relations = __webpack_require__(18); var relations = _interopRequireWildcard(_relations); @@ -1910,6 +1910,11 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + var Readable = void 0; + try { + Readable = __webpack_require__(15).Readable; + } catch (_) {} + var contentTypeOctetStream = 'application/octet-stream'; function doUpload(cozy, data, method, path, options) { @@ -1925,9 +1930,10 @@ var isBuffer = typeof ArrayBuffer !== 'undefined' && data instanceof ArrayBuffer; var isFile = typeof File !== 'undefined' && data instanceof File; var isBlob = typeof Blob !== 'undefined' && data instanceof Blob; + var isStream = typeof Readable !== 'undefined' && data instanceof Readable; var isString = typeof data === 'string'; - if (!isBuffer && !isFile && !isBlob && !isString) { + if (!isBuffer && !isFile && !isBlob && !isStream && !isString) { throw new Error('invalid data type'); } @@ -1945,6 +1951,8 @@ } } else if (isBlob) { contentType = contentTypeOctetStream; + } else if (isStream) { + contentType = contentTypeOctetStream; } else if (typeof data === 'string') { contentType = 'text/plain'; } @@ -1958,7 +1966,7 @@ method: method, headers: { 'Content-Type': contentType, - 'Date': lastModifiedDate ? lastModifiedDate.toISOString() : '' + 'Date': lastModifiedDate ? lastModifiedDate.toGMTString() : '' }, body: data }).then(function (res) { @@ -1997,15 +2005,24 @@ function createDirectory(cozy, options) { var _ref3 = options || {}, name = _ref3.name, - dirID = _ref3.dirID; + dirID = _ref3.dirID, + lastModifiedDate = _ref3.lastModifiedDate; if (typeof name !== 'string' || name === '') { throw new Error('missing name argument'); } + if (lastModifiedDate && typeof lastModifiedDate === 'string') { + lastModifiedDate = new Date(lastModifiedDate); + } + var path = '/files/' + encodeURIComponent(dirID || ''); var query = '?Name=' + encodeURIComponent(name) + '&Type=directory'; - return (0, _fetch.cozyFetchJSON)(cozy, 'POST', '' + path + query); + return (0, _fetch.cozyFetchJSON)(cozy, 'POST', '' + path + query, undefined, { + headers: { + 'Date': lastModifiedDate ? lastModifiedDate.toGMTString() : '' + } + }); } function updateById(cozy, id, data, options) { @@ -2133,6 +2150,12 @@ /***/ }, /* 15 */ +/***/ function(module, exports) { + + module.exports = require("stream"); + +/***/ }, +/* 16 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -2156,11 +2179,11 @@ exports.stopSync = stopSync; exports.replicateFromCozy = replicateFromCozy; - var _pouchdb = __webpack_require__(16); + var _pouchdb = __webpack_require__(!(function webpackMissingModule() { var e = new Error("Cannot find module \"pouchdb\""); e.code = 'MODULE_NOT_FOUND'; throw e; }())); var _pouchdb2 = _interopRequireDefault(_pouchdb); - var _pouchdbFind = __webpack_require__(17); + var _pouchdbFind = __webpack_require__(!(function webpackMissingModule() { var e = new Error("Cannot find module \"pouchdb-find\""); e.code = 'MODULE_NOT_FOUND'; throw e; }())); var _pouchdbFind2 = _interopRequireDefault(_pouchdbFind); @@ -2371,20 +2394,8 @@ } } -/***/ }, -/* 16 */ -/***/ function(module, exports) { - - module.exports = require("pouchdb"); - /***/ }, /* 17 */ -/***/ function(module, exports) { - - module.exports = require("pouchdb-find"); - -/***/ }, -/* 18 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -2401,7 +2412,7 @@ } /***/ }, -/* 19 */ +/* 18 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; diff --git a/dist/cozy-client.node.js.map b/dist/cozy-client.node.js.map index 9d77fa12..3e29e7b5 100644 --- a/dist/cozy-client.node.js.map +++ b/dist/cozy-client.node.js.map @@ -1 +1 @@ -{"version":3,"sources":["webpack:///webpack/bootstrap 25b8c88b0bb3357a9748","webpack:///external \"isomorphic-fetch\"","webpack:///./src/index.js","webpack:///./src/utils.js","webpack:///./src/auth_storage.js","webpack:///./src/auth_v2.js","webpack:///external \"btoa\"","webpack:///./src/auth_v3.js","webpack:///./src/fetch.js","webpack:///./src/jsonapi.js","webpack:///external \"crypto\"","webpack:///./src/crud.js","webpack:///./src/doctypes.js","webpack:///./src/mango.js","webpack:///./src/files.js","webpack:///./src/offline.js","webpack:///external \"pouchdb\"","webpack:///external \"pouchdb-find\"","webpack:///./src/settings.js","webpack:///./src/relations.js"],"names":["auth","crud","mango","files","offline","settings","relations","AppTokenV3","AppToken","AccessTokenV3","AccessToken","ClientV3","Client","AuthNone","AuthRunning","AuthError","AuthOK","defaultClientParams","softwareID","mainProto","create","find","update","delete","_delete","updateAttributes","defineIndex","query","addReferencedFiles","listReferencedFiles","destroy","authProto","registerClient","updateClient","unregisterClient","getClient","getAuthCodeURL","getAccessToken","refreshToken","filesProto","createDirectory","updateById","updateAttributesById","updateAttributesByPath","trashById","statById","statByPath","downloadById","downloadByPath","getDowloadLink","getArchiveLink","listTrash","clearTrash","restoreById","destroyById","offlineProto","init","getDoctypes","createDatabase","hasDatabase","getDatabase","destroyDatabase","replicateFromCozy","hasSync","startAllSync","startSync","stopAllSync","stopSync","settingsProto","diskUsage","Cozy","options","AppTokenV2","LocalStorage","MemoryStorage","_inited","_oauth","_token","_authstate","_authcreds","_storage","_version","_offline","token","oauth","Error","storage","_clientParams","Object","assign","clientParams","_onRegistered","onRegistered","nopOnRegistered","url","cozyURL","length","slice","_url","disablePromises","addToProto","state","isV2","then","oauthFlow","Promise","resolve","client","creds","save","CredsKey","path","pathprefix","fetch","res","ok","json","status","datasystem","undefined","protoify","context","fn","prototyped","args","ctx","obj","proto","attr","cozy","window","unpromiser","isPromise","sleep","retry","getFuzzedDelay","getBackedoffDelay","createPath","encodeQuery","decodeQuery","warn","FuzzFactor","value","apply","l","cb","err","time","setTimeout","count","delay","doTry","catch","retryDelay","fuzzingFactor","Math","random","retryCount","pow","doctype","id","route","encodeURIComponent","q","qname","queryIndex","indexOf","queries","fragIndex","queryStr","parts","split","i","pair","decodeURIComponent","hasOwnProperty","warned","text","push","console","prefix","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","data","e","removeEventListener","clearTimeout","addEventListener","opts","btoa","StateSize","StateKey","clientID","client_id","clientSecret","client_secret","registrationAccessToken","registration_access_token","redirect_uris","redirectURI","software_id","softwareVersion","software_version","clientName","client_name","clientKind","client_kind","clientURI","client_uri","logoURI","logo_uri","policyURI","policy_uri","tokenType","token_type","accessToken","access_token","refresh_token","scope","isRegistered","toRegisterJSON","disableAuth","resetSecret","createClient","manualAuthCredentials","oldClient","newClient","shouldPassRegistration","scopes","generateRandomState","join","pageURL","grantQueries","getGrantCodeFromPageURL","retrieveToken","code","tryCount","clearAndRetry","clear","registerNewClient","all","load","credentials","storedState","isUnauthorized","statePromise","t","body","headers","href","buffer","crypto","getRandomValues","Uint8Array","require","randomBytes","Array","floor","String","fromCharCode","replace","cozyFetch","cozyFetchJSON","fullpath","resp","cozyFetchWithAuth","authorize","handleResponse","toAuthHeader","newToken","saveCredentials","method","handleJSONResponse","contentType","get","FetchError","reason","response","indexKey","doc","type","findByRef","resources","ref","handleResource","rawResource","links","resource","_id","_type","_rev","meta","rev","attributes","name","rels","relationships","isArray","map","handleTopLevel","included","forEach","r","NOREV","docType","changes","tries","normalizeDoctype","DOCTYPE_FILES","KNOWN_DOCTYPES","REVERSE_KNOWN","keys","k","isQualified","known","parseSelector","normalizeSelector","makeMapReduceQuery","fields","defineIndexV2","defineIndexV3","indexRef","queryV2","queryV3","VALUEOPERATORS","LOGICOPERATORS","MAP_TEMPLATE","toLowerCase","emit","FIELDSPLACEHOLDER","toString","COUCHDB_INFINITY","COUCHDB_LOWEST","indexName","capitalize","indexDefinition","makeMapFunction","reduce","use_index","selector","limit","since","descending","sort","f","docs","charAt","toUpperCase","operator","acc","concat","filters","filter","op","field","applySelector","lower","upper","inclusiveEnd","startkey","endkey","inclusive_end","mrquery","firstFreeValueField","normalizedSelector","used","isFreeValue","contentTypeOctetStream","doUpload","ArrayBuffer","isBuffer","isFile","File","isBlob","Blob","isString","lastModifiedDate","Date","toISOString","dirID","attrs","db","children","addIsDir","toJsonApi","extractResponseLinkRelated","related","paths","archive","isDir","contents","clone","pluginLoaded","doctypes","timer","plugin","database","autoSync","createIndexes","setInterval","replicate","on","info","replication","cancel","clearInterval","events","live","from","eventNames","eventName","createIndex","index","ids","refs","makeReferencesPath","file"],"mappings":";AAAA;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,8C;;;;;;;;;;;;;sjBCAA;;;AACA;;AACA;;AACA;;AACA;;KAAYA,I;;AACZ;;KAAYC,I;;AACZ;;KAAYC,K;;AACZ;;KAAYC,K;;AACZ;;KAAYC,O;;AACZ;;KAAYC,Q;;AACZ;;KAAYC,S;;;;;;KAGAC,U,GAGRP,I,CAHFQ,Q;KACaC,a,GAEXT,I,CAFFU,W;KACQC,Q,GACNX,I,CADFY,M;;;AAGF,KAAMC,WAAW,CAAjB;AACA,KAAMC,cAAc,CAApB;AACA,KAAMC,YAAY,CAAlB;AACA,KAAMC,SAAS,CAAf;;AAEA,KAAMC,sBAAsB;AAC1BC,eAAY;AADc,EAA5B;;AAIA,KAAMC,YAAY;AAChBC,WAAQnB,KAAKmB,MADG;AAEhBC,SAAMpB,KAAKoB,IAFK;AAGhBC,WAAQrB,KAAKqB,MAHG;AAIhBC,WAAQtB,KAAKuB,OAJG;AAKhBC,qBAAkBxB,KAAKwB,gBALP;AAMhBC,gBAAaxB,MAAMwB,WANH;AAOhBC,UAAOzB,MAAMyB,KAPG;AAQhBC,uBAAoBtB,UAAUsB,kBARd;AAShBC,wBAAqBvB,UAAUuB,mBATf;AAUhBC,YAAS,mBAAmB;AAC1B,sBAAK,iDAAL;AACA,YAAO7B,KAAKuB,OAAL,uBAAP;AACD;AAbe,EA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G,IAA9B,EAAoC4K,GAApC,EAAyC;AAC9C,OAAI,CAACA,GAAL,EAAU,MAAM,IAAIxN,KAAJ,CAAU,sBAAV,CAAN;AACV,UAAO,0BAAc4C,IAAd,EAAoB,KAApB,EAA2BoT,mBAAmBxI,GAAnB,CAA3B,EACJtM,IADI,CACC,UAACpG,KAAD;AAAA,YAAWA,MAAM6T,GAAN,CAAU,UAACsH,IAAD;AAAA,cAAUA,KAAKhI,GAAf;AAAA,MAAV,CAAX;AAAA,IADD,CAAP;AAED;;AAED,UAAS+H,kBAAT,CAA6BxI,GAA7B,EAAkC;AAChC,OAAMC,OAAO5I,mBAAmB2I,IAAIU,KAAvB,CAAb;AACA,OAAMvJ,KAAKE,mBAAmB2I,IAAIS,GAAvB,CAAX;AACA,qBAAgBR,IAAhB,SAAwB9I,EAAxB;AACD,E","file":"cozy-client.node.js","sourcesContent":[" \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 25b8c88b0bb3357a9748","module.exports = require(\"isomorphic-fetch\");\n\n\n//////////////////\n// WEBPACK FOOTER\n// external \"isomorphic-fetch\"\n// module id = 1\n// module chunks = 0","/* global fetch */\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 crud from './crud'\nimport * as mango from './mango'\nimport * as files from './files'\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 mainProto = {\n create: crud.create,\n find: crud.find,\n update: crud.update,\n delete: crud._delete,\n updateAttributes: crud.updateAttributes,\n defineIndex: mango.defineIndex,\n query: mango.query,\n addReferencedFiles: relations.addReferencedFiles,\n listReferencedFiles: relations.listReferencedFiles,\n destroy: function (...args) {\n warn('destroy is deprecated, use cozy.delete instead.')\n return crud._delete(...args)\n }\n}\n\nconst authProto = {\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 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 getDowloadLink: files.getDowloadLink,\n getArchiveLink: files.getArchiveLink,\n listTrash: files.listTrash,\n clearTrash: files.clearTrash,\n restoreById: files.restoreById,\n destroyById: files.destroyById\n}\n\nconst offlineProto = {\n init: offline.init,\n getDoctypes: offline.getDoctypes,\n // database\n createDatabase: offline.createDatabase,\n hasDatabase: offline.hasDatabase,\n getDatabase: offline.getDatabase,\n destroyDatabase: offline.destroyDatabase,\n // replication\n replicateFromCozy: offline.replicateFromCozy,\n hasSync: offline.hasSync,\n startAllSync: offline.startAllSync,\n startSync: offline.startSync,\n stopAllSync: offline.stopAllSync,\n stopSync: offline.stopSync\n}\n\nconst settingsProto = {\n diskUsage: settings.diskUsage\n}\n\nclass Cozy {\n constructor (options) {\n this.files = {}\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 = null\n this._offline = null\n\n const token = options.token\n const oauth = options.oauth\n if (token && oauth) {\n throw new Error('Cannot specify an application token with a oauth activated')\n }\n\n if (token) {\n this._token = new AppTokenV3({ token })\n } else if (oauth) {\n this._oauth = true\n this._storage = oauth.storage\n this._clientParams = Object.assign({}, defaultClientParams, oauth.clientParams)\n this._onRegistered = oauth.onRegistered || nopOnRegistered\n }\n\n let url = options.cozyURL || ''\n while (url[url.length - 1] === '/') {\n url = url.slice(0, -1)\n }\n\n this._url = url\n\n const disablePromises = !!options.disablePromises\n addToProto(this, this, mainProto, disablePromises)\n addToProto(this, this.auth, authProto, disablePromises)\n addToProto(this, this.files, filesProto, 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\n authorize () {\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 return auth.oauthFlow(\n this,\n this._storage,\n this._clientParams,\n this._onRegistered\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 this._version = 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) => status.datasystem !== undefined)\n }\n return this._version\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\nconst cozy = new Cozy()\n\nexport default cozy\nexport { Cozy, LocalStorage, MemoryStorage }\n\nif ((typeof window) !== 'undefined') {\n window.cozy = cozy\n window.Cozy = Cozy\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/index.js","const 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 return\n }\n}\n\nexport function isPromise (value) {\n return !!value && typeof value.then === 'function'\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","module.exports = require(\"btoa\");\n\n\n//////////////////\n// WEBPACK FOOTER\n// external \"btoa\"\n// module id = 6\n// module chunks = 0","/* global btoa */\nimport {encodeQuery, decodeQuery} from './utils'\nimport {cozyFetchJSON, FetchError} from './fetch'\n\nconst StateSize = 16\n\nexport const CredsKey = 'creds'\nexport const StateKey = 'state'\n\nexport class Client {\n constructor (opts) {\n this.clientID = opts.clientID || opts.client_id || ''\n this.clientSecret = opts.clientSecret || opts.client_secret || ''\n this.registrationAccessToken = opts.registrationAccessToken || opts.registration_access_token || ''\n\n if (opts.redirect_uris) {\n this.redirectURI = opts.redirect_uris[0] || ''\n } else {\n this.redirectURI = opts.redirectURI || ''\n }\n\n this.softwareID = opts.softwareID || opts.software_id || ''\n this.softwareVersion = opts.softwareVersion || opts.software_version || ''\n this.clientName = opts.clientName || opts.client_name || ''\n this.clientKind = opts.clientKind || opts.client_kind || ''\n this.clientURI = opts.clientURI || opts.client_uri || ''\n\n this.logoURI = opts.logoURI || opts.logo_uri || ''\n this.policyURI = opts.policyURI || opts.policy_uri || ''\n\n if (this.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 isRegistered () {\n return this.clientID !== ''\n }\n\n toRegisterJSON () {\n return {\n redirect_uris: [this.redirectURI],\n software_id: this.softwareID,\n software_version: this.softwareVersion,\n client_name: this.clientName,\n client_kind: this.clientKind,\n client_uri: this.clientURI,\n logo_uri: this.logoURI,\n policy_uri: this.policyURI\n }\n }\n\n toAuthHeader () {\n return 'Bearer ' + this.registrationAccessToken\n }\n}\n\nexport class AccessToken {\n constructor (opts) {\n this.tokenType = opts.tokenType || opts.token_type\n this.accessToken = opts.accessToken || opts.access_token\n this.refreshToken = opts.refreshToken || opts.refresh_token\n this.scope = opts.scope\n }\n\n toAuthHeader () {\n return 'Bearer ' + this.accessToken\n }\n}\n\nexport class AppToken {\n constructor (opts) {\n this.token = opts.token || ''\n }\n\n toAuthHeader () {\n return 'Bearer ' + this.token\n }\n}\n\nexport function registerClient (cozy, client) {\n if (!(client instanceof Client)) {\n client = new Client(client)\n }\n if (client.isRegistered()) {\n return Promise.reject(new Error('Client already registered'))\n }\n return cozyFetchJSON(cozy, 'POST', '/auth/register', client.toRegisterJSON(), {\n disableAuth: true\n })\n .then((data) => new Client(data))\n}\n\nexport function updateClient (cozy, client, resetSecret = false) {\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 let data = client.toRegisterJSON()\n data.client_id = client.clientID\n if (resetSecret) data.client_secret = client.clientSecret\n\n return cozyFetchJSON(cozy, 'PUT', `/auth/register/${client.clientID}`, data)\n .then((data) => createClient(data, client))\n}\n\nexport function unregisterClient (cozy, client) {\n return cozyFetchJSON(cozy, 'DELETE', `/auth/register/${client.clientID}`)\n}\n\n// getClient will retrive the registered client informations from the server.\nexport function getClient (cozy, client) {\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 return cozyFetchJSON(cozy, 'GET', `/auth/register/${client.clientID}`, null, {\n manualAuthCredentials: {\n client: client,\n token: client\n }\n })\n .then((data) => createClient(data, client))\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 'code': 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) {\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 ])\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)) {\n throw err\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 manualAuthCredentials: { client, token },\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' }\n })\n .then((data) => new AccessToken(data))\n}\n\n// getGrantCodeFromPageURL extract the state and access_code query parameters\n// from the given url\nfunction getGrantCodeFromPageURL (pageURL = '') {\n if (pageURL === '' && typeof window !== 'undefined') {\n pageURL = window.location.href\n }\n const queries = decodeQuery(pageURL)\n if (!queries.hasOwnProperty('state')) {\n return null\n }\n return {\n state: queries['state'],\n code: queries['access_code']\n }\n}\n\n// generateRandomState will try to generate a 128bits random value from a secure\n// pseudo random generator. It will fallback on Math.random if it cannot find\n// such generator.\nfunction generateRandomState () {\n let buffer\n if (typeof window !== 'undefined' &&\n typeof window.crypto !== 'undefined' &&\n typeof window.crypto.getRandomValues === 'function') {\n buffer = new Uint8Array(StateSize)\n window.crypto.getRandomValues(buffer)\n } else {\n try {\n buffer = require('crypto').randomBytes(StateSize)\n } catch (e) {}\n }\n if (!buffer) {\n buffer = new Array(StateSize)\n for (let i = 0; i < buffer.length; i++) {\n buffer[i] = Math.floor((Math.random() * 255))\n }\n }\n return btoa(String.fromCharCode.apply(null, buffer))\n .replace(/=+$/, '')\n .replace(/\\//g, '_')\n .replace(/\\+/g, '-')\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/auth_v3.js","/* global fetch */\nimport {refreshToken, AccessToken} from './auth_v3'\nimport {retry} from './utils'\nimport jsonapi from './jsonapi'\n\nexport function cozyFetch (cozy, path, options = {}) {\n return cozy.fullpath(path).then((fullpath) => {\n let resp\n if (options.disableAuth) {\n resp = fetch(fullpath, options)\n } else if (options.manualAuthCredentials) {\n resp = cozyFetchWithAuth(cozy, fullpath, options, options.manualAuthCredentials)\n } else {\n resp = cozy.authorize().then((credentials) =>\n cozyFetchWithAuth(cozy, fullpath, options, credentials))\n }\n return resp.then(handleResponse)\n })\n}\n\nfunction cozyFetchWithAuth (cozy, fullpath, options, credentials) {\n if (credentials) {\n options.headers = options.headers || {}\n options.headers['Authorization'] = credentials.token.toAuthHeader()\n }\n\n // the option credentials:include tells fetch to include the cookies in the\n // request even for cross-origin requests\n options.credentials = 'include'\n\n return Promise.all([\n cozy.isV2(),\n fetch(fullpath, options)\n ]).then(([isV2, res]) => {\n if (res.status !== 401 || isV2 || !credentials) {\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 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 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 .then(handleJSONResponse)\n}\n\nfunction handleResponse (res) {\n if (res.ok) {\n return res\n }\n let data\n const contentType = res.headers.get('content-type')\n if (contentType && contentType.indexOf('json') >= 0) {\n data = res.json()\n } else {\n data = res.text()\n }\n return data.then(err => {\n throw new FetchError(res, err)\n })\n}\n\nfunction handleJSONResponse (res) {\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) {\n return json.then(jsonapi)\n } else {\n return json\n }\n}\n\nexport class FetchError {\n constructor (res, reason) {\n this.response = res\n this.url = res.url\n this.status = res.status\n this.reason = reason\n }\n\n isUnauthorized () {\n return this.status === 401\n }\n}\n\nFetchError.isUnauthorized = function (err) {\n return (err instanceof FetchError && err.isUnauthorized())\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\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","module.exports = require(\"crypto\");\n\n\n//////////////////\n// WEBPACK FOOTER\n// external \"crypto\"\n// module id = 10\n// module chunks = 0","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)\n return cozyFetchJSON(cozy, 'POST', 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 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/crud.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} from './utils'\nimport {normalizeDoctype} from './doctypes'\nimport {cozyFetchJSON} 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\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\n// defineIndexV2 is equivalent to defineIndex but only works for V2.\n// It transforms the index fields into a map reduce view.\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) => ({ doctype: doctype, type: 'mango', name: response.id, fields: fields }))\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 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 since: options.since\n }\n\n if (options.descending) {\n opts.sort = indexRef.fields.map(f => ({ [f]: 'desc' }))\n }\n\n let path = createPath(cozy, false, indexRef.doctype, '_find')\n return cozyFetchJSON(cozy, 'POST', path, opts)\n .then((response) => response.docs)\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\nconst contentTypeOctetStream = 'application/octet-stream'\n\nfunction doUpload (cozy, data, method, path, options) {\n if (!data) {\n throw new Error('missing data argument')\n }\n\n // transform any ArrayBufferView to ArrayBuffer\n if (data.buffer && data.buffer instanceof ArrayBuffer) {\n data = data.buffer\n }\n\n const isBuffer = (typeof ArrayBuffer !== 'undefined' && data instanceof ArrayBuffer)\n const isFile = (typeof File !== 'undefined' && data instanceof File)\n const isBlob = (typeof Blob !== 'undefined' && data instanceof Blob)\n const isString = (typeof data === 'string')\n\n if (!isBuffer && !isFile && !isBlob && !isString) {\n throw new Error('invalid data type')\n }\n\n let {contentType, lastModifiedDate} = options || {}\n if (!contentType) {\n if (isBuffer) {\n contentType = contentTypeOctetStream\n } else if (isFile) {\n contentType = data.type || contentTypeOctetStream\n if (!lastModifiedDate) {\n lastModifiedDate = data.lastModifiedDate\n }\n } else if (isBlob) {\n contentType = contentTypeOctetStream\n } else if (typeof data === 'string') {\n contentType = 'text/plain'\n }\n }\n\n if (lastModifiedDate && typeof lastModifiedDate === 'string') {\n lastModifiedDate = new Date(lastModifiedDate)\n }\n\n return cozyFetch(cozy, path, {\n method: method,\n headers: {\n 'Content-Type': contentType,\n 'Date': lastModifiedDate ? lastModifiedDate.toISOString() : ''\n },\n body: data\n })\n .then((res) => {\n const json = res.json()\n if (!res.ok) {\n return json.then(err => { throw err })\n } else {\n return json.then(jsonapi)\n }\n })\n}\n\nexport function create (cozy, data, options) {\n let {name, dirID} = options || {}\n\n // handle case where data is a file and contains the name\n if (!name && typeof data.name === 'string') {\n name = data.name\n }\n\n if (typeof name !== 'string' || name === '') {\n throw new Error('missing name argument')\n }\n\n const path = `/files/${encodeURIComponent(dirID || '')}`\n const query = `?Name=${encodeURIComponent(name)}&Type=file`\n return doUpload(cozy, data, 'POST', `${path}${query}`, options)\n}\n\nexport function createDirectory (cozy, options) {\n const {name, dirID} = options || {}\n\n if (typeof name !== 'string' || name === '') {\n throw new Error('missing name argument')\n }\n\n const path = `/files/${encodeURIComponent(dirID || '')}`\n const query = `?Name=${encodeURIComponent(name)}&Type=directory`\n return cozyFetchJSON(cozy, 'POST', `${path}${query}`)\n}\n\nexport function updateById (cozy, id, data, options) {\n return doUpload(cozy, data, 'PUT', `/files/${encodeURIComponent(id)}`, options)\n}\n\nexport function updateAttributesById (cozy, id, attrs) {\n if (!attrs || typeof attrs !== 'object') {\n throw new Error('missing attrs argument')\n }\n\n const body = { data: { attributes: attrs } }\n return cozyFetchJSON(cozy, 'PATCH',\n `/files/${encodeURIComponent(id)}`, body)\n}\n\nexport function updateAttributesByPath (cozy, path, attrs) {\n if (!attrs || typeof attrs !== 'object') {\n throw new Error('missing attrs argument')\n }\n\n const body = { data: { attributes: attrs } }\n return cozyFetchJSON(cozy, 'PATCH',\n `/files/metadata?Path=${encodeURIComponent(path)}`, body)\n}\n\nexport function trashById (cozy, id) {\n if (typeof id !== 'string' || id === '') {\n throw new Error('missing id argument')\n }\n return cozyFetchJSON(cozy, 'DELETE', `/files/${encodeURIComponent(id)}`)\n}\n\nexport function statById (cozy, id, offline = true) {\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({selector: {'dir_id': id}})\n ]).then(([doc, children]) => {\n children = children.docs.map(doc => {\n return addIsDir(toJsonApi(cozy, doc))\n })\n return addIsDir(toJsonApi(cozy, doc, children))\n })\n }\n return cozyFetchJSON(cozy, 'GET', `/files/${encodeURIComponent(id)}`)\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 getDowloadLink (cozy, path) {\n return cozyFetchJSON(cozy, 'POST', `/files/downloads?Path=${encodeURIComponent(path)}`)\n .then(extractResponseLinkRelated)\n}\n\nexport function getArchiveLink (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 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) {\n return cozyFetchJSON(cozy, 'DELETE', `/files/trash/${encodeURIComponent(id)}`)\n}\n\nfunction addIsDir (obj) {\n obj.isDir = obj.attributes.type === 'directory'\n return obj\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 relations: (name) => {\n if (name === 'contents') {\n return contents\n }\n }\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/files.js","import PouchDB from 'pouchdb'\nimport pouchdbFind from 'pouchdb-find'\nimport { DOCTYPE_FILES } from './doctypes'\n\nlet pluginLoaded = false\n\nexport function init (cozy, { options = {}, doctypes = [], timer = false }) {\n for (let doctype of doctypes) {\n createDatabase(cozy, doctype, options)\n }\n if (timer) { startAllSync(cozy, timer) }\n}\n\nexport function createDatabase (cozy, doctype, options = {}, timer = false) {\n if (!pluginLoaded) {\n PouchDB.plugin(pouchdbFind)\n pluginLoaded = true\n }\n cozy._offline = cozy._offline || []\n cozy._offline[doctype] = cozy._offline[doctype] || {}\n let offline = cozy._offline[doctype]\n if (offline && offline.database) { return offline.database }\n offline.database = new PouchDB(doctype, options)\n offline.timer = timer\n offline.autoSync = null\n if (timer) { startSync(cozy, doctype, timer) }\n createIndexes(cozy, offline.database, doctype)\n return offline.database\n}\n\nexport function hasDatabase (cozy, doctype) {\n return cozy._offline !== null &&\n doctype in cozy._offline &&\n cozy._offline[doctype].database !== undefined\n}\n\nexport function getDatabase (cozy, doctype) {\n if (hasDatabase(cozy, doctype)) {\n return cozy._offline[doctype].database\n }\n return\n}\n\nexport function destroyDatabase (cozy, doctype) {\n if (hasDatabase(cozy, doctype)) {\n stopSync(cozy, doctype)\n getDatabase(cozy, doctype).destroy()\n delete getDatabase(cozy, doctype)\n }\n}\n\nexport function getDoctypes (cozy) {\n if (cozy._offline === null) { return [] }\n return Object.keys(cozy._offline)\n}\n\n//\n// SYNC\n//\n\nexport function startAllSync (cozy, timer) {\n if (timer) {\n const doctypes = getDoctypes(cozy)\n doctypes.forEach((doctype) => {\n startSync(cozy, doctype, timer)\n })\n }\n}\n\nexport function stopAllSync (cozy) {\n const doctypes = getDoctypes(cozy)\n doctypes.forEach((doctype) => {\n stopSync(cozy, doctype)\n })\n}\n\nexport function startSync (cozy, doctype, timer) {\n // TODO: add timer limitation for not flooding Gozy\n if (hasDatabase(cozy, doctype)) {\n if (hasSync(cozy, doctype)) {\n if (timer === cozy._offline[doctype].timer) { return }\n stopSync(cozy, doctype)\n }\n let offline = cozy._offline[doctype]\n offline.timer = timer\n offline.autoSync = setInterval(() => {\n if (offline.replicate === undefined) {\n offline.replicate = replicateFromCozy(cozy, doctype)\n .on('complete', (info) => {\n delete offline.replicate\n })\n // TODO: add replicationToCozy\n }\n }, timer * 1000)\n }\n}\n\nexport function hasSync (cozy, doctype) {\n return cozy._offline !== null &&\n doctype in cozy._offline &&\n cozy._offline[doctype].autoSync !== null\n}\n\nexport function stopSync (cozy, doctype) {\n if (hasSync(cozy, doctype)) {\n let offline = cozy._offline[doctype]\n if (offline.replication) { offline.replication.cancel() }\n clearInterval(offline.autoSync)\n delete offline.autoSync\n }\n}\n\nexport function replicateFromCozy (cozy, doctype, options = {}, events = {}) {\n if (hasDatabase(cozy, doctype)) {\n if (options.live === true) {\n throw new Error('You can\\'t use `live` option with Cozy couchdb.')\n }\n const url = cozy._url + '/data/' + doctype\n let db = getDatabase(cozy, doctype)\n let replication = db.replicate.from(url, options)\n const eventNames = [\n 'change', 'paused', 'active', 'denied', 'complete', 'error'\n ]\n for (let eventName of eventNames) {\n if (typeof events[eventName] === 'function') {\n replication.on(eventName, events[eventName])\n }\n }\n return replication\n } else {\n throw new Error(`You should add this doctype: ${doctype} to offline.`)\n }\n}\n\nfunction createIndexes (cozy, db, doctype) {\n if (doctype === DOCTYPE_FILES) {\n db.createIndex({index: {fields: ['dir_id']}})\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/offline.js","module.exports = require(\"pouchdb\");\n\n\n//////////////////\n// WEBPACK FOOTER\n// external \"pouchdb\"\n// module id = 16\n// module chunks = 0","module.exports = require(\"pouchdb-find\");\n\n\n//////////////////\n// WEBPACK FOOTER\n// external \"pouchdb-find\"\n// module id = 17\n// module chunks = 0","import {cozyFetchJSON} from './fetch'\n\nexport function diskUsage (cozy) {\n return cozyFetchJSON(cozy, 'GET', `/settings/disk-usage`)\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/settings.js","import {cozyFetchJSON} from './fetch'\nimport { DOCTYPE_FILES } from './doctypes'\n\nexport function addReferencedFiles (cozy, doc, ids) {\n if (!doc) throw new Error('missing doc argument')\n if (!Array.isArray(ids)) ids = [ids]\n\n const refs = ids.map((id) => ({type: DOCTYPE_FILES, id: id}))\n\n return cozyFetchJSON(cozy, 'POST', makeReferencesPath(doc), {data: refs})\n}\n\nexport function listReferencedFiles (cozy, doc) {\n if (!doc) throw new Error('missing doc argument')\n return cozyFetchJSON(cozy, 'GET', makeReferencesPath(doc))\n .then((files) => files.map((file) => file._id))\n}\n\nfunction makeReferencesPath (doc) {\n const type = encodeURIComponent(doc._type)\n const id = encodeURIComponent(doc._id)\n return `/data/${type}/${id}/relationships/references`\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/relations.js"],"sourceRoot":""} \ No newline at end of file +{"version":3,"sources":["webpack:///webpack/bootstrap c0fe0ac8a75059f58355","webpack:///external \"isomorphic-fetch\"","webpack:///./src/index.js","webpack:///./src/utils.js","webpack:///./src/auth_storage.js","webpack:///./src/auth_v2.js","webpack:///external \"btoa\"","webpack:///./src/auth_v3.js","webpack:///./src/fetch.js","webpack:///./src/jsonapi.js","webpack:///external \"crypto\"","webpack:///./src/crud.js","webpack:///./src/doctypes.js","webpack:///./src/mango.js","webpack:///./src/files.js","webpack:///external \"stream\"","webpack:///./src/offline.js","webpack:///./src/settings.js","webpack:///./src/relations.js"],"names":["auth","crud","mango","files","offline","settings","relations","AppTokenV3","AppToken","AccessTokenV3","AccessToken","ClientV3","Client","AuthNone","AuthRunning","AuthError","AuthOK","defaultClientParams","softwareID","mainProto","create","find","update","delete","_delete","updateAttributes","defineIndex","query","addReferencedFiles","listReferencedFiles","destroy","authProto","registerClient","updateClient","unregisterClient","getClient","getAuthCodeURL","getAccessToken","refreshToken","filesProto","createDirectory","updateById","updateAttributesById","updateAttributesByPath","trashById","statById","statByPath","downloadById","downloadByPath","getDowloadLink","getArchiveLink","listTrash","clearTrash","restoreById","destroyById","offlineProto","init","getDoctypes","createDatabase","hasDatabase","getDatabase","destroyDatabase","replicateFromCozy","hasSync","startAllSync","startSync","stopAllSync","stopSync","settingsProto","diskUsage","Cozy","options","AppTokenV2","LocalStorage","MemoryStorage","_inited","_oauth","_token","_authstate","_authcreds","_storage","_version","_offline","token","oauth","Error","storage","_clientParams","Object","assign","clientParams","_onRegistered","onRegistered","nopOnRegistered","url","cozyURL","length","slice","_url","disablePromises","addToProto","state","isV2","then","oauthFlow","Promise","resolve","client","creds","save","CredsKey","path","pathprefix","fetch","res","ok","json","status","datasystem","undefined","protoify","context","fn","prototyped","args","ctx","obj","proto","attr","cozy","window","unpromiser","isPromise","sleep","retry","getFuzzedDelay","getBackedoffDelay","createPath","encodeQuery","decodeQuery","warn","FuzzFactor","value","apply","l","cb","err","time","setTimeout","count","delay","doTry","catch","retryDelay","fuzzingFactor","Math","random","retryCount","pow","doctype","id","route","encodeURIComponent","q","qname","queryIndex","indexOf","queries","fragIndex","queryStr","parts","split","i","pair","decodeURIComponent","hasOwnProperty","warned","text","push","console","prefix","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","data","e","removeEventListener","clearTimeout","addEventListener","opts","btoa","StateSize","StateKey","clientID","client_id","clientSecret","client_secret","registrationAccessToken","registration_access_token","redirect_uris","redirectURI","software_id","softwareVersion","software_version","clientName","client_name","clientKind","client_kind","clientURI","client_uri","logoURI","logo_uri","policyURI","policy_uri","tokenType","token_type","accessToken","access_token","refresh_token","scope","isRegistered","toRegisterJSON","disableAuth","resetSecret","createClient","manualAuthCredentials","oldClient","newClient","shouldPassRegistration","scopes","generateRandomState","join","pageURL","grantQueries","getGrantCodeFromPageURL","retrieveToken","code","tryCount","clearAndRetry","clear","registerNewClient","all","load","credentials","storedState","isUnauthorized","statePromise","t","body","headers","href","buffer","crypto","getRandomValues","Uint8Array","require","randomBytes","Array","floor","String","fromCharCode","replace","cozyFetch","cozyFetchJSON","fullpath","resp","cozyFetchWithAuth","authorize","handleResponse","toAuthHeader","newToken","saveCredentials","method","handleJSONResponse","contentType","get","FetchError","reason","response","indexKey","doc","type","findByRef","resources","ref","handleResource","rawResource","links","resource","_id","_type","_rev","meta","rev","attributes","name","rels","relationships","isArray","map","handleTopLevel","included","forEach","r","NOREV","docType","changes","tries","normalizeDoctype","DOCTYPE_FILES","KNOWN_DOCTYPES","REVERSE_KNOWN","keys","k","isQualified","known","parseSelector","normalizeSelector","makeMapReduceQuery","fields","defineIndexV2","defineIndexV3","indexRef","queryV2","queryV3","VALUEOPERATORS","LOGICOPERATORS","MAP_TEMPLATE","toLowerCase","emit","FIELDSPLACEHOLDER","toString","COUCHDB_INFINITY","COUCHDB_LOWEST","indexName","capitalize","indexDefinition","makeMapFunction","reduce","use_index","selector","limit","since","descending","sort","f","docs","charAt","toUpperCase","operator","acc","concat","filters","filter","op","field","applySelector","lower","upper","inclusiveEnd","startkey","endkey","inclusive_end","mrquery","firstFreeValueField","normalizedSelector","used","isFreeValue","Readable","_","contentTypeOctetStream","doUpload","ArrayBuffer","isBuffer","isFile","File","isBlob","Blob","isStream","isString","lastModifiedDate","Date","toGMTString","dirID","attrs","db","children","addIsDir","toJsonApi","extractResponseLinkRelated","related","paths","archive","isDir","contents","clone","pluginLoaded","doctypes","timer","plugin","database","autoSync","createIndexes","setInterval","replicate","on","info","replication","cancel","clearInterval","events","live","from","eventNames","eventName","createIndex","index","ids","refs","makeReferencesPath","file"],"mappings":";AAAA;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,8C;;;;;;;;;;;;;sjBCAA;;;AACA;;AACA;;AACA;;AACA;;KAAYA,I;;AACZ;;KAAYC,I;;AACZ;;KAAYC,K;;AACZ;;KAAYC,K;;AACZ;;KAAYC,O;;AACZ;;KAAYC,Q;;AACZ;;KAAYC,S;;;;;;KAGAC,U,GAGRP,I,CAHFQ,Q;KACaC,a,GAEXT,I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AA2BuT,mBAAmB3I,GAAnB,CAA3B,EACJtM,IADI,CACC,UAACpG,KAAD;AAAA,YAAWA,MAAM6T,GAAN,CAAU,UAACyH,IAAD;AAAA,cAAUA,KAAKnI,GAAf;AAAA,MAAV,CAAX;AAAA,IADD,CAAP;AAED;;AAED,UAASkI,kBAAT,CAA6B3I,GAA7B,EAAkC;AAChC,OAAMC,OAAO5I,mBAAmB2I,IAAIU,KAAvB,CAAb;AACA,OAAMvJ,KAAKE,mBAAmB2I,IAAIS,GAAvB,CAAX;AACA,qBAAgBR,IAAhB,SAAwB9I,EAAxB;AACD,E","file":"cozy-client.node.js","sourcesContent":[" \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 c0fe0ac8a75059f58355","module.exports = require(\"isomorphic-fetch\");\n\n\n//////////////////\n// WEBPACK FOOTER\n// external \"isomorphic-fetch\"\n// module id = 1\n// module chunks = 0","/* global fetch */\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 crud from './crud'\nimport * as mango from './mango'\nimport * as files from './files'\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 mainProto = {\n create: crud.create,\n find: crud.find,\n update: crud.update,\n delete: crud._delete,\n updateAttributes: crud.updateAttributes,\n defineIndex: mango.defineIndex,\n query: mango.query,\n addReferencedFiles: relations.addReferencedFiles,\n listReferencedFiles: relations.listReferencedFiles,\n destroy: function (...args) {\n warn('destroy is deprecated, use cozy.delete instead.')\n return crud._delete(...args)\n }\n}\n\nconst authProto = {\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 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 getDowloadLink: files.getDowloadLink,\n getArchiveLink: files.getArchiveLink,\n listTrash: files.listTrash,\n clearTrash: files.clearTrash,\n restoreById: files.restoreById,\n destroyById: files.destroyById\n}\n\nconst offlineProto = {\n init: offline.init,\n getDoctypes: offline.getDoctypes,\n // database\n createDatabase: offline.createDatabase,\n hasDatabase: offline.hasDatabase,\n getDatabase: offline.getDatabase,\n destroyDatabase: offline.destroyDatabase,\n // replication\n replicateFromCozy: offline.replicateFromCozy,\n hasSync: offline.hasSync,\n startAllSync: offline.startAllSync,\n startSync: offline.startSync,\n stopAllSync: offline.stopAllSync,\n stopSync: offline.stopSync\n}\n\nconst settingsProto = {\n diskUsage: settings.diskUsage\n}\n\nclass Cozy {\n constructor (options) {\n this.files = {}\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 = null\n this._offline = null\n\n const token = options.token\n const oauth = options.oauth\n if (token && oauth) {\n throw new Error('Cannot specify an application token with a oauth activated')\n }\n\n if (token) {\n this._token = new AppTokenV3({ token })\n } else if (oauth) {\n this._oauth = true\n this._storage = oauth.storage\n this._clientParams = Object.assign({}, defaultClientParams, oauth.clientParams)\n this._onRegistered = oauth.onRegistered || nopOnRegistered\n }\n\n let url = options.cozyURL || ''\n while (url[url.length - 1] === '/') {\n url = url.slice(0, -1)\n }\n\n this._url = url\n\n const disablePromises = !!options.disablePromises\n addToProto(this, this, mainProto, disablePromises)\n addToProto(this, this.auth, authProto, disablePromises)\n addToProto(this, this.files, filesProto, 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\n authorize () {\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 return auth.oauthFlow(\n this,\n this._storage,\n this._clientParams,\n this._onRegistered\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 this._version = 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) => status.datasystem !== undefined)\n }\n return this._version\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\nconst cozy = new Cozy()\n\nexport default cozy\nexport { Cozy, LocalStorage, MemoryStorage }\n\nif ((typeof window) !== 'undefined') {\n window.cozy = cozy\n window.Cozy = Cozy\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/index.js","const 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 return\n }\n}\n\nexport function isPromise (value) {\n return !!value && typeof value.then === 'function'\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","module.exports = require(\"btoa\");\n\n\n//////////////////\n// WEBPACK FOOTER\n// external \"btoa\"\n// module id = 6\n// module chunks = 0","/* global btoa */\nimport {encodeQuery, decodeQuery} from './utils'\nimport {cozyFetchJSON, FetchError} from './fetch'\n\nconst StateSize = 16\n\nexport const CredsKey = 'creds'\nexport const StateKey = 'state'\n\nexport class Client {\n constructor (opts) {\n this.clientID = opts.clientID || opts.client_id || ''\n this.clientSecret = opts.clientSecret || opts.client_secret || ''\n this.registrationAccessToken = opts.registrationAccessToken || opts.registration_access_token || ''\n\n if (opts.redirect_uris) {\n this.redirectURI = opts.redirect_uris[0] || ''\n } else {\n this.redirectURI = opts.redirectURI || ''\n }\n\n this.softwareID = opts.softwareID || opts.software_id || ''\n this.softwareVersion = opts.softwareVersion || opts.software_version || ''\n this.clientName = opts.clientName || opts.client_name || ''\n this.clientKind = opts.clientKind || opts.client_kind || ''\n this.clientURI = opts.clientURI || opts.client_uri || ''\n\n this.logoURI = opts.logoURI || opts.logo_uri || ''\n this.policyURI = opts.policyURI || opts.policy_uri || ''\n\n if (this.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 isRegistered () {\n return this.clientID !== ''\n }\n\n toRegisterJSON () {\n return {\n redirect_uris: [this.redirectURI],\n software_id: this.softwareID,\n software_version: this.softwareVersion,\n client_name: this.clientName,\n client_kind: this.clientKind,\n client_uri: this.clientURI,\n logo_uri: this.logoURI,\n policy_uri: this.policyURI\n }\n }\n\n toAuthHeader () {\n return 'Bearer ' + this.registrationAccessToken\n }\n}\n\nexport class AccessToken {\n constructor (opts) {\n this.tokenType = opts.tokenType || opts.token_type\n this.accessToken = opts.accessToken || opts.access_token\n this.refreshToken = opts.refreshToken || opts.refresh_token\n this.scope = opts.scope\n }\n\n toAuthHeader () {\n return 'Bearer ' + this.accessToken\n }\n}\n\nexport class AppToken {\n constructor (opts) {\n this.token = opts.token || ''\n }\n\n toAuthHeader () {\n return 'Bearer ' + this.token\n }\n}\n\nexport function registerClient (cozy, client) {\n if (!(client instanceof Client)) {\n client = new Client(client)\n }\n if (client.isRegistered()) {\n return Promise.reject(new Error('Client already registered'))\n }\n return cozyFetchJSON(cozy, 'POST', '/auth/register', client.toRegisterJSON(), {\n disableAuth: true\n })\n .then((data) => new Client(data))\n}\n\nexport function updateClient (cozy, client, resetSecret = false) {\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 let data = client.toRegisterJSON()\n data.client_id = client.clientID\n if (resetSecret) data.client_secret = client.clientSecret\n\n return cozyFetchJSON(cozy, 'PUT', `/auth/register/${client.clientID}`, data)\n .then((data) => createClient(data, client))\n}\n\nexport function unregisterClient (cozy, client) {\n return cozyFetchJSON(cozy, 'DELETE', `/auth/register/${client.clientID}`)\n}\n\n// getClient will retrive the registered client informations from the server.\nexport function getClient (cozy, client) {\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 return cozyFetchJSON(cozy, 'GET', `/auth/register/${client.clientID}`, null, {\n manualAuthCredentials: {\n client: client,\n token: client\n }\n })\n .then((data) => createClient(data, client))\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 'code': 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) {\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 ])\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)) {\n throw err\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 manualAuthCredentials: { client, token },\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' }\n })\n .then((data) => new AccessToken(data))\n}\n\n// getGrantCodeFromPageURL extract the state and access_code query parameters\n// from the given url\nfunction getGrantCodeFromPageURL (pageURL = '') {\n if (pageURL === '' && typeof window !== 'undefined') {\n pageURL = window.location.href\n }\n const queries = decodeQuery(pageURL)\n if (!queries.hasOwnProperty('state')) {\n return null\n }\n return {\n state: queries['state'],\n code: queries['access_code']\n }\n}\n\n// generateRandomState will try to generate a 128bits random value from a secure\n// pseudo random generator. It will fallback on Math.random if it cannot find\n// such generator.\nfunction generateRandomState () {\n let buffer\n if (typeof window !== 'undefined' &&\n typeof window.crypto !== 'undefined' &&\n typeof window.crypto.getRandomValues === 'function') {\n buffer = new Uint8Array(StateSize)\n window.crypto.getRandomValues(buffer)\n } else {\n try {\n buffer = require('crypto').randomBytes(StateSize)\n } catch (e) {}\n }\n if (!buffer) {\n buffer = new Array(StateSize)\n for (let i = 0; i < buffer.length; i++) {\n buffer[i] = Math.floor((Math.random() * 255))\n }\n }\n return btoa(String.fromCharCode.apply(null, buffer))\n .replace(/=+$/, '')\n .replace(/\\//g, '_')\n .replace(/\\+/g, '-')\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/auth_v3.js","/* global fetch */\nimport {refreshToken, AccessToken} from './auth_v3'\nimport {retry} from './utils'\nimport jsonapi from './jsonapi'\n\nexport function cozyFetch (cozy, path, options = {}) {\n return cozy.fullpath(path).then((fullpath) => {\n let resp\n if (options.disableAuth) {\n resp = fetch(fullpath, options)\n } else if (options.manualAuthCredentials) {\n resp = cozyFetchWithAuth(cozy, fullpath, options, options.manualAuthCredentials)\n } else {\n resp = cozy.authorize().then((credentials) =>\n cozyFetchWithAuth(cozy, fullpath, options, credentials))\n }\n return resp.then(handleResponse)\n })\n}\n\nfunction cozyFetchWithAuth (cozy, fullpath, options, credentials) {\n if (credentials) {\n options.headers = options.headers || {}\n options.headers['Authorization'] = credentials.token.toAuthHeader()\n }\n\n // the option credentials:include tells fetch to include the cookies in the\n // request even for cross-origin requests\n options.credentials = 'include'\n\n return Promise.all([\n cozy.isV2(),\n fetch(fullpath, options)\n ]).then(([isV2, res]) => {\n if (res.status !== 401 || isV2 || !credentials) {\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 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 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 .then(handleJSONResponse)\n}\n\nfunction handleResponse (res) {\n if (res.ok) {\n return res\n }\n let data\n const contentType = res.headers.get('content-type')\n if (contentType && contentType.indexOf('json') >= 0) {\n data = res.json()\n } else {\n data = res.text()\n }\n return data.then(err => {\n throw new FetchError(res, err)\n })\n}\n\nfunction handleJSONResponse (res) {\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) {\n return json.then(jsonapi)\n } else {\n return json\n }\n}\n\nexport class FetchError {\n constructor (res, reason) {\n this.response = res\n this.url = res.url\n this.status = res.status\n this.reason = reason\n }\n\n isUnauthorized () {\n return this.status === 401\n }\n}\n\nFetchError.isUnauthorized = function (err) {\n return (err instanceof FetchError && err.isUnauthorized())\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\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","module.exports = require(\"crypto\");\n\n\n//////////////////\n// WEBPACK FOOTER\n// external \"crypto\"\n// module id = 10\n// module chunks = 0","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)\n return cozyFetchJSON(cozy, 'POST', 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 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/crud.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} from './utils'\nimport {normalizeDoctype} from './doctypes'\nimport {cozyFetchJSON} 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\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\n// defineIndexV2 is equivalent to defineIndex but only works for V2.\n// It transforms the index fields into a map reduce view.\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) => ({ doctype: doctype, type: 'mango', name: response.id, fields: fields }))\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 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 since: options.since\n }\n\n if (options.descending) {\n opts.sort = indexRef.fields.map(f => ({ [f]: 'desc' }))\n }\n\n let path = createPath(cozy, false, indexRef.doctype, '_find')\n return cozyFetchJSON(cozy, 'POST', path, opts)\n .then((response) => response.docs)\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\nlet Readable\ntry {\n Readable = require('stream').Readable\n} catch (_) {}\n\nconst contentTypeOctetStream = 'application/octet-stream'\n\nfunction doUpload (cozy, data, method, path, options) {\n if (!data) {\n throw new Error('missing data argument')\n }\n\n // transform any ArrayBufferView to ArrayBuffer\n if (data.buffer && data.buffer instanceof ArrayBuffer) {\n data = data.buffer\n }\n\n const isBuffer = (typeof ArrayBuffer !== 'undefined' && data instanceof ArrayBuffer)\n const isFile = (typeof File !== 'undefined' && data instanceof File)\n const isBlob = (typeof Blob !== 'undefined' && data instanceof Blob)\n const isStream = (typeof Readable !== 'undefined' && data instanceof Readable)\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, lastModifiedDate} = options || {}\n if (!contentType) {\n if (isBuffer) {\n contentType = contentTypeOctetStream\n } else if (isFile) {\n contentType = data.type || contentTypeOctetStream\n if (!lastModifiedDate) {\n lastModifiedDate = data.lastModifiedDate\n }\n } else if (isBlob) {\n contentType = contentTypeOctetStream\n } else if (isStream) {\n contentType = contentTypeOctetStream\n } else if (typeof data === 'string') {\n contentType = 'text/plain'\n }\n }\n\n if (lastModifiedDate && typeof lastModifiedDate === 'string') {\n lastModifiedDate = new Date(lastModifiedDate)\n }\n\n return cozyFetch(cozy, path, {\n method: method,\n headers: {\n 'Content-Type': contentType,\n 'Date': lastModifiedDate ? lastModifiedDate.toGMTString() : ''\n },\n body: data\n })\n .then((res) => {\n const json = res.json()\n if (!res.ok) {\n return json.then(err => { throw err })\n } else {\n return json.then(jsonapi)\n }\n })\n}\n\nexport function create (cozy, data, options) {\n let {name, dirID} = options || {}\n\n // handle case where data is a file and contains the name\n if (!name && typeof data.name === 'string') {\n name = data.name\n }\n\n if (typeof name !== 'string' || name === '') {\n throw new Error('missing name argument')\n }\n\n const path = `/files/${encodeURIComponent(dirID || '')}`\n const query = `?Name=${encodeURIComponent(name)}&Type=file`\n return doUpload(cozy, data, 'POST', `${path}${query}`, options)\n}\n\nexport function createDirectory (cozy, options) {\n let {name, dirID, lastModifiedDate} = options || {}\n\n if (typeof name !== 'string' || name === '') {\n throw new Error('missing name argument')\n }\n\n if (lastModifiedDate && typeof lastModifiedDate === 'string') {\n lastModifiedDate = new Date(lastModifiedDate)\n }\n\n const path = `/files/${encodeURIComponent(dirID || '')}`\n const query = `?Name=${encodeURIComponent(name)}&Type=directory`\n return cozyFetchJSON(cozy, 'POST', `${path}${query}`, undefined, {\n headers: {\n 'Date': lastModifiedDate ? lastModifiedDate.toGMTString() : ''\n }\n })\n}\n\nexport function updateById (cozy, id, data, options) {\n return doUpload(cozy, data, 'PUT', `/files/${encodeURIComponent(id)}`, options)\n}\n\nexport function updateAttributesById (cozy, id, attrs) {\n if (!attrs || typeof attrs !== 'object') {\n throw new Error('missing attrs argument')\n }\n\n const body = { data: { attributes: attrs } }\n return cozyFetchJSON(cozy, 'PATCH',\n `/files/${encodeURIComponent(id)}`, body)\n}\n\nexport function updateAttributesByPath (cozy, path, attrs) {\n if (!attrs || typeof attrs !== 'object') {\n throw new Error('missing attrs argument')\n }\n\n const body = { data: { attributes: attrs } }\n return cozyFetchJSON(cozy, 'PATCH',\n `/files/metadata?Path=${encodeURIComponent(path)}`, body)\n}\n\nexport function trashById (cozy, id) {\n if (typeof id !== 'string' || id === '') {\n throw new Error('missing id argument')\n }\n return cozyFetchJSON(cozy, 'DELETE', `/files/${encodeURIComponent(id)}`)\n}\n\nexport function statById (cozy, id, offline = true) {\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({selector: {'dir_id': id}})\n ]).then(([doc, children]) => {\n children = children.docs.map(doc => {\n return addIsDir(toJsonApi(cozy, doc))\n })\n return addIsDir(toJsonApi(cozy, doc, children))\n })\n }\n return cozyFetchJSON(cozy, 'GET', `/files/${encodeURIComponent(id)}`)\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 getDowloadLink (cozy, path) {\n return cozyFetchJSON(cozy, 'POST', `/files/downloads?Path=${encodeURIComponent(path)}`)\n .then(extractResponseLinkRelated)\n}\n\nexport function getArchiveLink (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 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) {\n return cozyFetchJSON(cozy, 'DELETE', `/files/trash/${encodeURIComponent(id)}`)\n}\n\nfunction addIsDir (obj) {\n obj.isDir = obj.attributes.type === 'directory'\n return obj\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 relations: (name) => {\n if (name === 'contents') {\n return contents\n }\n }\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/files.js","module.exports = require(\"stream\");\n\n\n//////////////////\n// WEBPACK FOOTER\n// external \"stream\"\n// module id = 15\n// module chunks = 0","import PouchDB from 'pouchdb'\nimport pouchdbFind from 'pouchdb-find'\nimport { DOCTYPE_FILES } from './doctypes'\n\nlet pluginLoaded = false\n\nexport function init (cozy, { options = {}, doctypes = [], timer = false }) {\n for (let doctype of doctypes) {\n createDatabase(cozy, doctype, options)\n }\n if (timer) { startAllSync(cozy, timer) }\n}\n\nexport function createDatabase (cozy, doctype, options = {}, timer = false) {\n if (!pluginLoaded) {\n PouchDB.plugin(pouchdbFind)\n pluginLoaded = true\n }\n cozy._offline = cozy._offline || []\n cozy._offline[doctype] = cozy._offline[doctype] || {}\n let offline = cozy._offline[doctype]\n if (offline && offline.database) { return offline.database }\n offline.database = new PouchDB(doctype, options)\n offline.timer = timer\n offline.autoSync = null\n if (timer) { startSync(cozy, doctype, timer) }\n createIndexes(cozy, offline.database, doctype)\n return offline.database\n}\n\nexport function hasDatabase (cozy, doctype) {\n return cozy._offline !== null &&\n doctype in cozy._offline &&\n cozy._offline[doctype].database !== undefined\n}\n\nexport function getDatabase (cozy, doctype) {\n if (hasDatabase(cozy, doctype)) {\n return cozy._offline[doctype].database\n }\n return\n}\n\nexport function destroyDatabase (cozy, doctype) {\n if (hasDatabase(cozy, doctype)) {\n stopSync(cozy, doctype)\n getDatabase(cozy, doctype).destroy()\n delete getDatabase(cozy, doctype)\n }\n}\n\nexport function getDoctypes (cozy) {\n if (cozy._offline === null) { return [] }\n return Object.keys(cozy._offline)\n}\n\n//\n// SYNC\n//\n\nexport function startAllSync (cozy, timer) {\n if (timer) {\n const doctypes = getDoctypes(cozy)\n doctypes.forEach((doctype) => {\n startSync(cozy, doctype, timer)\n })\n }\n}\n\nexport function stopAllSync (cozy) {\n const doctypes = getDoctypes(cozy)\n doctypes.forEach((doctype) => {\n stopSync(cozy, doctype)\n })\n}\n\nexport function startSync (cozy, doctype, timer) {\n // TODO: add timer limitation for not flooding Gozy\n if (hasDatabase(cozy, doctype)) {\n if (hasSync(cozy, doctype)) {\n if (timer === cozy._offline[doctype].timer) { return }\n stopSync(cozy, doctype)\n }\n let offline = cozy._offline[doctype]\n offline.timer = timer\n offline.autoSync = setInterval(() => {\n if (offline.replicate === undefined) {\n offline.replicate = replicateFromCozy(cozy, doctype)\n .on('complete', (info) => {\n delete offline.replicate\n })\n // TODO: add replicationToCozy\n }\n }, timer * 1000)\n }\n}\n\nexport function hasSync (cozy, doctype) {\n return cozy._offline !== null &&\n doctype in cozy._offline &&\n cozy._offline[doctype].autoSync !== null\n}\n\nexport function stopSync (cozy, doctype) {\n if (hasSync(cozy, doctype)) {\n let offline = cozy._offline[doctype]\n if (offline.replication) { offline.replication.cancel() }\n clearInterval(offline.autoSync)\n delete offline.autoSync\n }\n}\n\nexport function replicateFromCozy (cozy, doctype, options = {}, events = {}) {\n if (hasDatabase(cozy, doctype)) {\n if (options.live === true) {\n throw new Error('You can\\'t use `live` option with Cozy couchdb.')\n }\n const url = cozy._url + '/data/' + doctype\n let db = getDatabase(cozy, doctype)\n let replication = db.replicate.from(url, options)\n const eventNames = [\n 'change', 'paused', 'active', 'denied', 'complete', 'error'\n ]\n for (let eventName of eventNames) {\n if (typeof events[eventName] === 'function') {\n replication.on(eventName, events[eventName])\n }\n }\n return replication\n } else {\n throw new Error(`You should add this doctype: ${doctype} to offline.`)\n }\n}\n\nfunction createIndexes (cozy, db, doctype) {\n if (doctype === DOCTYPE_FILES) {\n db.createIndex({index: {fields: ['dir_id']}})\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/offline.js","import {cozyFetchJSON} from './fetch'\n\nexport function diskUsage (cozy) {\n return cozyFetchJSON(cozy, 'GET', `/settings/disk-usage`)\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/settings.js","import {cozyFetchJSON} from './fetch'\nimport { DOCTYPE_FILES } from './doctypes'\n\nexport function addReferencedFiles (cozy, doc, ids) {\n if (!doc) throw new Error('missing doc argument')\n if (!Array.isArray(ids)) ids = [ids]\n\n const refs = ids.map((id) => ({type: DOCTYPE_FILES, id: id}))\n\n return cozyFetchJSON(cozy, 'POST', makeReferencesPath(doc), {data: refs})\n}\n\nexport function listReferencedFiles (cozy, doc) {\n if (!doc) throw new Error('missing doc argument')\n return cozyFetchJSON(cozy, 'GET', makeReferencesPath(doc))\n .then((files) => files.map((file) => file._id))\n}\n\nfunction makeReferencesPath (doc) {\n const type = encodeURIComponent(doc._type)\n const id = encodeURIComponent(doc._id)\n return `/data/${type}/${id}/relationships/references`\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/relations.js"],"sourceRoot":""} \ No newline at end of file