/*! remotestorage.js 1.2.3, https://remotestorage.io, MIT licensed */ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define("RemoteStorage",[],t):"object"==typeof exports?exports.RemoteStorage=t():e.RemoteStorage=t()}(this,(function(){return function(e){var t={};function r(n){if(t[n])return t[n].exports;var o=t[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}return r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)r.d(n,o,function(t){return e[t]}.bind(null,o));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=17)}([function(e,t,r){(function(t,r){function n(e){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}var o={logError:function(e){"string"==typeof e?console.error(e):console.error(e.message,e.stack)},globalContext:"undefined"!=typeof window?window:"object"===("undefined"==typeof self?"undefined":n(self))?self:t,getGlobalContext:function(){return"undefined"!=typeof window?window:"object"===("undefined"==typeof self?"undefined":n(self))?self:t},extend:function(e){var t=Array.prototype.slice.call(arguments,1);return t.forEach((function(t){for(var r in t)e[r]=t[r]})),e},containingFolder:function(e){if(""===e)return"/";if(!e)throw"Path not given!";return e.replace(/\/+/g,"/").replace(/[^\/]+\/?$/,"")},isFolder:function(e){return"/"===e.substr(-1)},isDocument:function(e){return!o.isFolder(e)},baseName:function(e){var t=e.split("/");return o.isFolder(e)?t[t.length-2]+"/":t[t.length-1]},cleanPath:function(e){return e.replace(/\/+/g,"/").split("/").map(encodeURIComponent).join("/").replace(/'/g,"%27")},bindAll:function(e){for(var t in this)"function"==typeof e[t]&&(e[t]=e[t].bind(e))},equal:function(e,t,r){var i;if(r=r||[],n(e)!==n(t))return!1;if("number"==typeof e||"boolean"==typeof e||"string"==typeof e)return e===t;if("function"==typeof e)return e.toString()===t.toString();if(e instanceof ArrayBuffer&&t instanceof ArrayBuffer&&(e=new Uint8Array(e),t=new Uint8Array(t)),e instanceof Array){if(e.length!==t.length)return!1;for(var s=0,a=e.length;s=0)continue;(u=r.slice()).push(t[i])}if(!o.equal(e[i],t[i],u))return!1}}return!0},deepClone:function(e){var t;return void 0===e?void 0:(function e(t,r){var o,i;if("object"===n(t)&&!Array.isArray(t)&&null!==t)for(o in t)"object"===n(t[o])&&null!==t[o]&&("[object ArrayBuffer]"===t[o].toString()?(r[o]=new ArrayBuffer(t[o].byteLength),i=new Int8Array(t[o]),new Int8Array(r[o]).set(i)):e(t[o],r[o]))}(e,t=JSON.parse(JSON.stringify(e))),t)},pathsFromRoot:function(e){for(var t=[e],r=e.replace(/\/$/,"").split("/");r.length>1;)r.pop(),t.push(r.join("/")+"/");return t},localStorageAvailable:function(){var e=o.getGlobalContext();if(!("localStorage"in e))return!1;try{return e.localStorage.setItem("rs-check",1),e.localStorage.removeItem("rs-check"),!0}catch(e){return!1}},getJSONFromLocalStorage:function(e){var t=o.getGlobalContext();try{return JSON.parse(t.localStorage.getItem(e))}catch(e){}},shouldBeTreatedAsBinary:function(e,t){return t&&t.match(/charset=binary/)||/[\x00-\x08\x0E-\x1F\uFFFD]/.test(e)},getTextFromArrayBuffer:function(e,n){return new Promise((function(i){if("undefined"==typeof Blob){var s=new r(new Uint8Array(e));i(s.toString(n))}else{var a;if(o.globalContext.BlobBuilder=o.globalContext.BlobBuilder||o.globalContext.WebKitBlobBuilder,void 0!==o.globalContext.BlobBuilder){var u=new t.BlobBuilder;u.append(e),a=u.getBlob()}else a=new Blob([e]);var c=new FileReader;"function"==typeof c.addEventListener?c.addEventListener("loadend",(function(e){i(e.target.result)})):c.onloadend=function(e){i(e.target.result)},c.readAsText(a,n)}}))}};e.exports=o}).call(this,r(10),r(18).Buffer)},function(e,t,r){var n=r(3);e.exports=function(){n.logging&&console.log.apply(console,arguments)}},function(e,t,r){var n=r(1),o={addEventListener:function(e,t){if("string"!=typeof e)throw new Error("Argument eventName should be a string");if("function"!=typeof t)throw new Error("Argument handler should be a function");n("[Eventhandling] Adding event listener",e),this._validateEvent(e),this._handlers[e].push(t)},removeEventListener:function(e,t){this._validateEvent(e);for(var r=this._handlers[e].length,n=0;n0&&(e.state=n)}else e[decodeURIComponent(r[0])]=decodeURIComponent(r[1]);return e}),{})}var a,u=function e(t,r){var n=r.authURL,s=r.scope,a=r.redirectUri,u=r.clientId;if(o("[Authorize] authURL = ",n,"scope = ",s,"redirectUri = ",a,"clientId = ",u),!i.localStorageAvailable()&&"remotestorage"===t.backend){a+=a.indexOf("#")>0?"&":"#";var c={userAddress:t.remote.userAddress,href:t.remote.href,storageApi:t.remote.storageApi,properties:t.remote.properties};a+="rsDiscovery="+btoa(JSON.stringify(c))}var l=function(e,t,r,n){var o=t.indexOf("#"),i=e;return i+=e.indexOf("?")>0?"&":"?",i+="redirect_uri="+encodeURIComponent(t.replace(/#.*$/,"")),i+="&scope="+encodeURIComponent(r),i+="&client_id="+encodeURIComponent(n),-1!==o&&o+1!==t.length&&(i+="&state="+encodeURIComponent(t.substring(o+1))),i+="&response_type=token"}(n,a,s,u);if(i.globalContext.cordova)return e.openWindow(l,a,"location=yes,clearsessioncache=yes,clearcache=yes").then((function(e){t.remote.configure({token:e.access_token})}));e.setLocation(l)};u.IMPLIED_FAKE_TOKEN=!1,u.Unauthorized=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.name="Unauthorized",this.message=void 0===e?"App authorization expired or revoked.":e,void 0!==t.code&&(this.code=t.code),this.stack=(new Error).stack},u.Unauthorized.prototype=Object.create(Error.prototype),u.Unauthorized.prototype.constructor=u.Unauthorized,u.getLocation=function(){return document.location},u.setLocation=function(e){if("string"==typeof e)document.location.href=e;else{if("object"!==n(e))throw"Invalid location "+e;document.location=e}},u.openWindow=function(e,t,r){return new Promise((function(n,o){var i=open(e,"_blank",r);if(!i||i.closed)return o("Authorization popup was blocked");var a=function(){return o("Authorization was canceled")};i.addEventListener("loadstart",(function(e){if(0===e.url.indexOf(t)){i.removeEventListener("exit",a),i.close();var r=s(e.url);return r?n(r):o("Authorization error")}})),i.addEventListener("exit",a)}))},u._rs_supported=function(){return"undefined"!=typeof document},u._rs_init=function(e){a=function(){var n=!1;if(r){if(r.error)throw"access_denied"===r.error?new u.Unauthorized("Authorization failed: access denied",{code:"access_denied"}):new u.Unauthorized("Authorization failed: ".concat(r.error));r.rsDiscovery&&e.remote.configure(r.rsDiscovery),r.access_token&&(e.remote.configure({token:r.access_token}),n=!0),r.remotestorage&&(e.connect(r.remotestorage),n=!0),r.state&&(t=u.getLocation(),u.setLocation(t.href.split("#")[0]+"#"+r.state))}n||e.remote.stopWaitingForToken()};var t,r=s();r&&((t=u.getLocation()).hash=""),e.on("features-loaded",a)},u._rs_cleanup=function(e){e.removeEventListener("features-loaded",a)},e.exports=u},function(e,t,r){function n(e){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}var o=r(2),i=r(0),s=r(3),a=r(22),u=r(23),c=u.SchemaNotFound,l=function(e,t){if("/"!==t[t.length-1])throw"Not a folder: "+t;"/"===t&&(this.makePath=function(e){return("/"===e[0]?"":"/")+e}),this.storage=e,this.base=t;var r=this.base.split("/");r.length>2?this.moduleName=r[1]:this.moduleName="root",o(this,"change"),this.on=this.on.bind(this),e.onChange(this.base,this._fireChange.bind(this))};l.Types=u,l.prototype={scope:function(e){return new l(this.storage,this.makePath(e))},getListing:function(e,t){if("string"!=typeof e)e="";else if(e.length>0&&"/"!==e[e.length-1])return Promise.reject("Not a folder: "+e);return this.storage.get(this.makePath(e),t).then((function(e){return 404===e.statusCode?{}:e.body}))},getAll:function(e,t){if("string"!=typeof e)e="";else if(e.length>0&&"/"!==e[e.length-1])return Promise.reject("Not a folder: "+e);return this.storage.get(this.makePath(e),t).then(function(r){if(404===r.statusCode)return{};if("object"===n(r.body)){var o=Object.keys(r.body);if(0===o.length)return{};var i=o.map(function(o){return this.storage.get(this.makePath(e+o),t).then((function(e){if("string"==typeof e.body)try{e.body=JSON.parse(e.body)}catch(e){}"object"===n(e.body)&&(r.body[o]=e.body)}))}.bind(this));return Promise.all(i).then((function(){return r.body}))}}.bind(this))},getFile:function(e,t){return"string"!=typeof e?Promise.reject("Argument 'path' of baseClient.getFile must be a string"):this.storage.get(this.makePath(e),t).then((function(e){return{data:e.body,contentType:e.contentType,revision:e.revision}}))},storeFile:function(e,t,r){return"string"!=typeof e?Promise.reject("Argument 'mimeType' of baseClient.storeFile must be a string"):"string"!=typeof t?Promise.reject("Argument 'path' of baseClient.storeFile must be a string"):"string"!=typeof r&&"object"!==n(r)?Promise.reject("Argument 'body' of baseClient.storeFile must be a string, ArrayBuffer, or ArrayBufferView"):(this.storage.access.checkPathPermission(this.makePath(t),"rw")||console.warn("WARNING: Editing a document to which only read access ('r') was claimed"),this.storage.put(this.makePath(t),r,e).then(function(e){return 200===e.statusCode||201===e.statusCode?e.revision:Promise.reject("Request (PUT "+this.makePath(t)+") failed with status: "+e.statusCode)}.bind(this)))},getObject:function(e,t){return"string"!=typeof e?Promise.reject("Argument 'path' of baseClient.getObject must be a string"):this.storage.get(this.makePath(e),t).then(function(t){if("object"===n(t.body))return t.body;if("string"==typeof t.body)try{return JSON.parse(t.body)}catch(t){throw"Not valid JSON: "+this.makePath(e)}else if(void 0!==t.body&&200===t.statusCode)return Promise.reject("Not an object: "+this.makePath(e))}.bind(this))},storeObject:function(e,t,r){if("string"!=typeof e)return Promise.reject("Argument 'typeAlias' of baseClient.storeObject must be a string");if("string"!=typeof t)return Promise.reject("Argument 'path' of baseClient.storeObject must be a string");if("object"!==n(r))return Promise.reject("Argument 'object' of baseClient.storeObject must be an object");this._attachType(r,e);try{var o=this.validate(r);if(!o.valid)return Promise.reject(o)}catch(e){return Promise.reject(e)}return this.storage.put(this.makePath(t),JSON.stringify(r),"application/json; charset=UTF-8").then(function(e){return 200===e.statusCode||201===e.statusCode?e.revision:Promise.reject("Request (PUT "+this.makePath(t)+") failed with status: "+e.statusCode)}.bind(this))},remove:function(e){return"string"!=typeof e?Promise.reject("Argument 'path' of baseClient.remove must be a string"):(this.storage.access.checkPathPermission(this.makePath(e),"rw")||console.warn("WARNING: Removing a document to which only read access ('r') was claimed"),this.storage.delete(this.makePath(e)))},getItemURL:function(e){if("string"!=typeof e)throw"Argument 'path' of baseClient.getItemURL must be a string";return this.storage.connected?(e=this._cleanPath(this.makePath(e)),this.storage.remote.href+e):void 0},cache:function(e,t){if("string"!=typeof e)throw"Argument 'path' of baseClient.cache must be a string";if(void 0===t)t="ALL";else if("string"!=typeof t)throw"Argument 'strategy' of baseClient.cache must be a string or undefined";if("FLUSH"!==t&&"SEEN"!==t&&"ALL"!==t)throw'Argument \'strategy\' of baseclient.cache must be one of ["FLUSH", "SEEN", "ALL"]';return this.storage.caching.set(this.makePath(e),t),this},flush:function(e){return this.storage.local.flush(e)},declareType:function(e,t,r){r||(r=t,t=this._defaultTypeURI(e)),l.Types.declare(this.moduleName,e,t,r)},validate:function(e){var t=l.Types.getSchema(e["@context"]);if(t)return a.validateResult(e,t);throw new c(e["@context"])},schemas:{configurable:!0,get:function(){return l.Types.inScope(this.moduleName)}},_defaultTypeURI:function(e){return"http://remotestorage.io/spec/modules/"+encodeURIComponent(this.moduleName)+"/"+encodeURIComponent(e)},_attachType:function(e,t){e["@context"]=l.Types.resolveAlias(this.moduleName+"/"+t)||this._defaultTypeURI(t)},makePath:function(e){return this.base+(e||"")},_fireChange:function(e){s.changeEvents[e.origin]&&(["new","old","lastCommon"].forEach((function(t){if((!e[t+"ContentType"]||/^application\/(.*)json(.*)/.exec(e[t+"ContentType"]))&&"string"==typeof e[t+"Value"])try{e[t+"Value"]=JSON.parse(e[t+"Value"])}catch(e){}})),this._emit("change",e))},_cleanPath:i.cleanPath},l._rs_init=function(){},e.exports=l},function(e,t,r){"use strict";function n(e){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}var o,i,s=r(1),a=r(0),u=r(2),c=r(4),l=r(3),h="remotestorage:wireclient",f={"draft-dejong-remotestorage-00":2,"draft-dejong-remotestorage-01":3,"draft-dejong-remotestorage-02":4,"https://www.w3.org/community/rww/wiki/read-write-web-00#simple":1};if("function"==typeof ArrayBufferView)i=function(e){return e&&e instanceof ArrayBufferView};else{var d=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array];i=function(e){for(var t=0;t<8;t++)if(e instanceof d[t])return!0;return!1}}var p=a.isFolder,m=a.cleanPath,y=a.shouldBeTreatedAsBinary,g=a.getJSONFromLocalStorage,v=a.getTextFromArrayBuffer;function b(e){return"string"!=typeof e?e:"*"===e?"*":'"'+e+'"'}function _(e){return"string"!=typeof e?e:e.replace(/^["']|["']$/g,"")}var w=function(e){if(this.rs=e,this.connected=!1,u(this,"connected","not-connected"),o){var t=g(h);t&&setTimeout(function(){this.configure(t)}.bind(this),0)}this._revisionCache={},this.connected&&setTimeout(this._emit.bind(this),0,"connected")};w.prototype={_request:function(e,t,r,n,o,i,a){if(("PUT"===e||"DELETE"===e)&&"/"===t[t.length-1])return Promise.reject("Don't "+e+" on directories!");var u,l=this;return r!==c.IMPLIED_FAKE_TOKEN&&(n.Authorization="Bearer "+r),this.rs._emit("wire-busy",{method:e,isFolder:p(t)}),w.request(e,t,{body:o,headers:n,responseType:"arraybuffer"}).then((function(r){if(l.online||(l.online=!0,l.rs._emit("network-online")),l.rs._emit("wire-done",{method:e,isFolder:p(t),success:!0}),o=r.status,[401,403,404,412].indexOf(o)>=0)return s("[WireClient] Error response status",r.status),u=i?_(r.getResponseHeader("ETag")):void 0,401===r.status&&l.rs._emit("error",new c.Unauthorized),Promise.resolve({statusCode:r.status,revision:u});if(function(e){return[201,204,304].indexOf(e)>=0}(r.status)||200===r.status&&"GET"!==e)return u=_(r.getResponseHeader("ETag")),s("[WireClient] Successful request",u),Promise.resolve({statusCode:r.status,revision:u});var n=r.getResponseHeader("Content-Type");u=i?_(r.getResponseHeader("ETag")):200===r.status?a:void 0;var o,h=function(e){var t,r="UTF-8";return e&&(t=e.match(/charset=(.+)$/))&&(r=t[1]),r}(n);return y(r.response,n)?(s("[WireClient] Successful request with unknown or binary mime-type",u),Promise.resolve({statusCode:r.status,body:r.response,contentType:n,revision:u})):v(r.response,h).then((function(e){return s("[WireClient] Successful request",u),Promise.resolve({statusCode:r.status,body:e,contentType:n,revision:u})}))}),(function(r){return l.online&&(l.online=!1,l.rs._emit("network-offline")),l.rs._emit("wire-done",{method:e,isFolder:p(t),success:!1}),Promise.reject(r)}))},configure:function(e){if("object"!==n(e))throw new Error("WireClient configure settings parameter should be an object");void 0!==e.userAddress&&(this.userAddress=e.userAddress),void 0!==e.href&&(this.href=e.href),void 0!==e.storageApi&&(this.storageApi=e.storageApi),void 0!==e.token&&(this.token=e.token),void 0!==e.properties&&(this.properties=e.properties),void 0!==this.storageApi&&(this._storageApi=f[this.storageApi]||5,this.supportsRevs=this._storageApi>=2),this.href&&this.token?(this.connected=!0,this.online=!0,this._emit("connected")):this.connected=!1,o&&(localStorage[h]=JSON.stringify({userAddress:this.userAddress,href:this.href,storageApi:this.storageApi,token:this.token,properties:this.properties}))},stopWaitingForToken:function(){this.connected||this._emit("not-connected")},get:function(e,t){var r=this;if(!this.connected)return Promise.reject("not connected (path: "+e+")");t||(t={});var o={};return this.supportsRevs&&t.ifNoneMatch&&(o["If-None-Match"]=b(t.ifNoneMatch)),this._request("GET",this.href+m(e),this.token,o,void 0,this.supportsRevs,this._revisionCache[e]).then((function(t){if(!p(e))return Promise.resolve(t);var o,i={};if(void 0!==t.body)try{t.body=JSON.parse(t.body)}catch(t){return Promise.reject("Folder description at "+r.href+m(e)+" is not JSON")}if(200===t.statusCode&&"object"===n(t.body)){if(0===Object.keys(t.body).length)t.statusCode=404;else if("http://remotestorage.io/spec/folder-description"===(o=t.body)["@context"]&&"object"===n(o.items)){for(var s in t.body.items)r._revisionCache[e+s]=t.body.items[s].ETag;i=t.body.items}else Object.keys(t.body).forEach((function(n){r._revisionCache[e+n]=t.body[n],i[n]={ETag:t.body[n]}}));return t.body=i,Promise.resolve(t)}return Promise.resolve(t)}))},put:function(e,t,r,n){if(!this.connected)return Promise.reject("not connected (path: "+e+")");n||(n={}),!r.match(/charset=/)&&(t instanceof ArrayBuffer||i(t))&&(r+="; charset=binary");var o={"Content-Type":r};return this.supportsRevs&&(n.ifMatch&&(o["If-Match"]=b(n.ifMatch)),n.ifNoneMatch&&(o["If-None-Match"]=b(n.ifNoneMatch))),this._request("PUT",this.href+m(e),this.token,o,t,this.supportsRevs)},delete:function(e,t){if(!this.connected)throw new Error("not connected (path: "+e+")");t||(t={});var r={};return this.supportsRevs&&t.ifMatch&&(r["If-Match"]=b(t.ifMatch)),this._request("DELETE",this.href+m(e),this.token,r,void 0,this.supportsRevs)}},w.isArrayBufferView=i,w.request=function(e,t,r){return"function"==typeof fetch?w._fetchRequest(e,t,r):"function"==typeof XMLHttpRequest?w._xhrRequest(e,t,r):(s("[WireClient] add a polyfill for fetch or XMLHttpRequest"),Promise.reject("[WireClient] add a polyfill for fetch or XMLHttpRequest"))},w._fetchRequest=function(e,t,r){var n,o,i={};"function"==typeof AbortController&&(o=new AbortController);var a=fetch(t,{method:e,headers:r.headers,body:r.body,signal:o?o.signal:void 0}).then((function(e){switch(s("[WireClient fetch]",e),e.headers.forEach((function(e,t){i[t.toUpperCase()]=e})),n={readyState:4,status:e.status,statusText:e.statusText,response:void 0,getResponseHeader:function(e){return i[e.toUpperCase()]||null},responseType:r.responseType,responseURL:t},r.responseType){case"arraybuffer":return e.arrayBuffer();case"blob":return e.blob();case"json":return e.json();case void 0:case"":case"text":return e.text();default:throw new Error("responseType 'document' is not currently supported using fetch")}})).then((function(e){return n.response=e,r.responseType&&"text"!==r.responseType||(n.responseText=e),n})),u=new Promise((function(e,t){setTimeout((function(){t("timeout"),o&&o.abort()}),l.requestTimeout)}));return Promise.race([a,u])},w._xhrRequest=function(e,t,r){return new Promise((function(o,a){s("[WireClient]",e,t);var u=!1,c=setTimeout((function(){u=!0,a("timeout")}),l.requestTimeout),h=new XMLHttpRequest;if(h.open(e,t,!0),r.responseType&&(h.responseType=r.responseType),r.headers)for(var f in r.headers)h.setRequestHeader(f,r.headers[f]);h.onload=function(){u||(clearTimeout(c),o(h))},h.onerror=function(e){u||(clearTimeout(c),a(e))};var d=r.body;"object"===n(d)&&!i(d)&&d instanceof ArrayBuffer&&(d=new Uint8Array(d)),h.send(d)}))},Object.defineProperty(w.prototype,"storageType",{get:function(){if(this.storageApi){var e=this.storageApi.match(/draft-dejong-(remotestorage-\d\d)/);return e?e[1]:"2012.04"}}}),w._rs_init=function(e){o=a.localStorageAvailable(),e.remote=new w(e),this.online=!0},w._rs_supported=function(){return"function"==typeof fetch||"function"==typeof XMLHttpRequest},w._rs_cleanup=function(){o&&delete localStorage[h]},e.exports=w},function(e,t,r){function n(e,t){return!t||"object"!==c(t)&&"function"!=typeof t?function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e):t}function o(e){var t="function"==typeof Map?new Map:void 0;return(o=function(e){if(null===e||(r=e,-1===Function.toString.call(r).indexOf("[native code]")))return e;var r;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return s(e,arguments,u(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),a(n,e)})(e)}function i(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(e){return!1}}function s(e,t,r){return(s=i()?Reflect.construct:function(e,t,r){var n=[null];n.push.apply(n,t);var o=new(Function.bind.apply(e,n));return r&&a(o,r.prototype),o}).apply(null,arguments)}function a(e,t){return(a=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function u(e){return(u=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function c(e){return(c="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function l(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function h(e,t){for(var r=0;r0}},{key:"collectDiffTasks",value:function(){var e=this,t=0;return this.rs.local.forAllNodes((function(r){t>100||(e.isCorrupt(r)?(P("[Sync] WARNING: corrupt node in local cache",r),"object"===c(r)&&r.path&&(e.addTask(r.path),t++)):e.needsFetch(r)&&e.rs.access.checkPathPermission(r.path,"r")?(e.addTask(r.path),t++):y(r.path)&&e.needsPush(r)&&e.rs.access.checkPathPermission(r.path,"rw")&&(e.addTask(r.path),t++))})).then((function(){return t}),(function(e){throw e}))}},{key:"inConflict",value:function(e){return e.local&&e.remote&&(void 0!==e.remote.body||e.remote.itemsMap)}},{key:"needsRefresh",value:function(e){return!!e.common&&(!e.common.timestamp||this.now()-e.common.timestamp>S.syncInterval)}},{key:"needsFetch",value:function(e){return!!this.inConflict(e)||!(!e.common||void 0!==e.common.itemsMap||void 0!==e.common.body)||!(!e.remote||void 0!==e.remote.itemsMap||void 0!==e.remote.body)}},{key:"needsPush",value:function(e){return!this.inConflict(e)&&(!(!e.local||e.push)||void 0)}},{key:"needsRemotePut",value:function(e){return e.local&&e.local.body}},{key:"needsRemoteDelete",value:function(e){return e.local&&!1===e.local.body}},{key:"getParentPath",value:function(e){var t=e.match(/^(.*\/)([^\/]+\/?)$/);if(t)return t[1];throw new Error('Not a valid path: "'+e+'"')}},{key:"deleteChildPathsFromTasks",value:function(){for(var e in this._tasks)for(var t=b(e),r=1;r=e))return!0;return r>=e}},{key:"collectTasks",value:function(e){var t=this;return this.hasTasks()||this.stopped?Promise.resolve():this.collectDiffTasks().then((function(r){return r||!1===e?Promise.resolve():t.collectRefreshTasks()}),(function(e){throw e}))}},{key:"addTask",value:function(e,t){this._tasks[e]||(this._tasks[e]=[]),"function"==typeof t&&this._tasks[e].push(t)}},{key:"sync",value:function(){var e=this;return this.done=!1,this.doTasks()?Promise.resolve():this.collectTasks().then((function(){try{e.doTasks()}catch(e){P("[Sync] doTasks error",e)}}),(function(e){throw P("[Sync] Sync error",e),new Error("Local cache unavailable")}))}}])&&h(t.prototype,r),n&&h(t,n),e}();k.SyncError=function(e){function t(e){var r;l(this,t),(r=n(this,u(t).call(this))).name="SyncError";var o="Sync failed: ";return"object"===c(e)&&"message"in e?(o+=e.message,r.stack=e.stack,r.originalError=e):o+=e,r.message=o,r}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&a(e,t)}(t,e),t}(o(Error)),e.exports=k},function(e,t,r){function n(e){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}var o=r(0),i=r(3),s=r(1),a=o.isFolder,u=o.isDocument,c=o.deepClone;function l(e){if("object"===n(e)&&"string"==typeof e.path)if(a(e.path)){if(e.local&&e.local.itemsMap)return e.local;if(e.common&&e.common.itemsMap)return e.common}else{if(e.local){if(e.local.body&&e.local.contentType)return e.local;if(!1===e.local.body)return}if(e.common&&e.common.body&&e.common.contentType)return e.common;if(e.body&&e.contentType)return{body:e.body,contentType:e.contentType}}}function h(e,t){var r;for(r in e){if(e[r]&&e[r].remote)return!0;var n=l(e[r]);if(n&&n.timestamp&&(new Date).getTime()-n.timestamp<=t)return!1;if(!n)return!0}return!0}var f=o.pathsFromRoot;function d(e){var t={path:e,common:{}};return a(e)&&(t.common.itemsMap={}),t}function p(e,t){return e.common||(e.common={itemsMap:{}}),e.common.itemsMap||(e.common.itemsMap={}),e.local||(e.local=c(e.common)),e.local.itemsMap||(e.local.itemsMap=e.common.itemsMap),e.local.itemsMap[t]=!0,e}var m={get:function(e,t,r){return"number"==typeof t?this.getNodes(f(e)).then((function(n){var o=l(n[e]);return h(n,t)?r(e):o?{statusCode:200,body:o.body||o.itemsMap,contentType:o.contentType}:{statusCode:404}})):this.getNodes([e]).then((function(t){var r=l(t[e]);if(r){if(a(e))for(var n in r.itemsMap)r.itemsMap.hasOwnProperty(n)&&!1===r.itemsMap[n]&&delete r.itemsMap[n];return{statusCode:200,body:r.body||r.itemsMap,contentType:r.contentType}}return{statusCode:404}}))},put:function(e,t,r){var n=f(e);return this._updateNodes(n,(function(e,n){try{for(var o=0,i=e.length;o0)break}else console.error("Cannot delete non-existing node "+o)}return t}))},flush:function(e){var t=this;return t._getAllDescendentPaths(e).then((function(e){return t.getNodes(e)})).then((function(e){for(var r in e){var n=e[r];n&&n.common&&n.local&&t._emitChange({path:n.path,origin:"local",oldValue:!1===n.local.body?void 0:n.local.body,newValue:!1===n.common.body?void 0:n.common.body}),e[r]=void 0}return t.setNodes(e)}))},_emitChange:function(e){i.changeEvents[e.origin]&&this._emit("change",e)},fireInitial:function(){if(i.changeEvents.local){var e=this;e.forAllNodes((function(t){var r;u(t.path)&&(r=l(t))&&e._emitChange({path:t.path,origin:"local",oldValue:void 0,oldContentType:void 0,newValue:r.body,newContentType:r.contentType})})).then((function(){e._emit("local-events-done")}))}},onDiff:function(e){this.diffHandler=e},migrate:function(e){return"object"!==n(e)||e.common||(e.common={},"string"==typeof e.path?"/"===e.path.substr(-1)&&"object"===n(e.body)&&(e.common.itemsMap=e.body):(e.local||(e.local={}),e.local.body=e.body,e.local.contentType=e.contentType)),e},_updateNodesRunning:!1,_updateNodesQueued:[],_updateNodes:function(e,t){return new Promise(function(r,n){this._doUpdateNodes(e,t,{resolve:r,reject:n})}.bind(this))},_doUpdateNodes:function(e,t,r){var n=this;n._updateNodesRunning?n._updateNodesQueued.push({paths:e,cb:t,promise:r}):(n._updateNodesRunning=!0,n.getNodes(e).then((function(i){var s,a=c(i),l=[],h=o.equal;for(var f in i=t(e,i))h(s=i[f],a[f])?delete i[f]:u(f)&&(h(s.local.body,s.local.previousBody)&&s.local.contentType===s.local.previousContentType||l.push({path:f,origin:"window",oldValue:s.local.previousBody,newValue:!1===s.local.body?void 0:s.local.body,oldContentType:s.local.previousContentType,newContentType:s.local.contentType}),delete s.local.previousBody,delete s.local.previousContentType);n.setNodes(i).then((function(){n._emitChangeEvents(l),r.resolve({statusCode:200})}))})).then((function(){return Promise.resolve()}),(function(e){r.reject(e)})).then((function(){n._updateNodesRunning=!1;var e=n._updateNodesQueued.shift();e&&n._doUpdateNodes(e.paths,e.cb,e.promise)})))},_emitChangeEvents:function(e){for(var t=0,r=e.length;t1e3&&e<36e5}b.Authorize=h,b.SyncError=f.SyncError,b.Unauthorized=h.Unauthorized,b.DiscoveryError=u.DiscoveryError,b.prototype={loadModules:function(){l.modules.forEach(this.addModule.bind(this))},authorize:function(e){this.access.setStorageType(this.remote.storageApi),void 0===e.scope&&(e.scope=this.access.scopeParameter),e.redirectUri=m.cordova?l.cordovaRedirectUri:String(h.getLocation()),void 0===e.clientId&&(e.clientId=e.redirectUri.match(/^(https?:\/\/[^/]+)/)[0]),h(this,e)},impliedauth:function(e,t){e=this.remote.storageApi,t=String(document.location),d("ImpliedAuth proceeding due to absent authURL; storageApi = "+e+" redirectUri = "+t),this.remote.configure({token:h.IMPLIED_FAKE_TOKEN}),document.location=t},connect:function(e,t){var r=this;if(this.setBackend("remotestorage"),e.indexOf("@")<0)this._emit("error",new b.DiscoveryError("User address doesn't contain an @."));else{if(m.cordova){if("string"!=typeof l.cordovaRedirectUri)return void this._emit("error",new b.DiscoveryError("Please supply a custom HTTPS redirect URI for your Cordova app"));if(!m.cordova.InAppBrowser)return void this._emit("error",new b.DiscoveryError("Please include the InAppBrowser Cordova plugin to enable OAuth"))}this.remote.configure({userAddress:e}),this._emit("connecting");var n=setTimeout(function(){this._emit("error",new b.DiscoveryError("No storage information found for this user address."))}.bind(this),l.discoveryTimeout);u(e).then((function(o){if(clearTimeout(n),r._emit("authing"),o.userAddress=e,r.remote.configure(o),!r.remote.connected)if(o.authURL)if(void 0===t)r.authorize({authURL:o.authURL});else{if("string"!=typeof t)throw new Error("Supplied bearer token must be a string");d("Skipping authorization sequence and connecting with known token"),r.remote.configure({token:t})}else r.impliedauth()}),(function(){clearTimeout(n),r._emit("error",new b.DiscoveryError("No storage information found for this user address."))}))}},reconnect:function(){this.remote.configure({token:null}),"remotestorage"===this.backend?this.connect(this.remote.userAddress):this.remote.connect()},disconnect:function(){this.remote&&this.remote.configure({userAddress:null,href:null,storageApi:null,token:null,properties:null}),this._setGPD({get:this._pendingGPD("get"),put:this._pendingGPD("put"),delete:this._pendingGPD("delete")});var e=this._cleanups.length,t=0,r=function(){++t>=e&&(this._init(),d("Done cleaning up, emitting disconnected and disconnect events"),this._emit("disconnected"))}.bind(this);e>0?this._cleanups.forEach(function(e){var t=e(this);"object"===n(t)&&"function"==typeof t.then?t.then(r):r()}.bind(this)):r()},setBackend:function(e){this.backend=e,o&&(e?localStorage.setItem("remotestorage:backend",e):localStorage.removeItem("remotestorage:backend"))},onChange:function(e,t){this._pathHandlers.change[e]||(this._pathHandlers.change[e]=[]),this._pathHandlers.change[e].push(t)},enableLog:function(){l.logging=!0},disableLog:function(){l.logging=!1},log:function(){d.apply(b,arguments)},setApiKeys:function(e){var t=this,r=["googledrive","dropbox"];if("object"!==n(e)||!Object.keys(e).every((function(e){return r.includes(e)})))return console.error("setApiKeys() was called with invalid arguments"),!1;Object.keys(e).forEach((function(r){var n=e[r];if(n){switch(r){case"dropbox":t.apiKeys.dropbox={appKey:n},void 0!==t.dropbox&&t.dropbox.clientId===n||s._rs_init(t);break;case"googledrive":t.apiKeys.googledrive={clientId:n},void 0!==t.googledrive&&t.googledrive.clientId===n||a._rs_init(t)}return!0}delete t.apiKeys[r]})),o&&localStorage.setItem("remotestorage:api-keys",JSON.stringify(this.apiKeys))},setCordovaRedirectUri:function(e){if("string"!=typeof e||!e.match(/http(s)?:\/\//))throw new Error("Cordova redirect URI must be a URI string");l.cordovaRedirectUri=e},_init:p.loadFeatures,features:p.features,loadFeature:p.loadFeature,featureSupported:p.featureSupported,featureDone:p.featureDone,featuresDone:p.featuresDone,featuresLoaded:p.featuresLoaded,featureInitialized:p.featureInitialized,featureFailed:p.featureFailed,hasFeature:p.hasFeature,_setCachingModule:p._setCachingModule,_collectCleanupFunctions:p._collectCleanupFunctions,_fireReady:p._fireReady,initFeature:p.initFeature,_setGPD:function(e,t){function r(e){return function(){return e.apply(t,arguments).then(v.bind(this))}}this.get=r(e.get),this.put=r(e.put),this.delete=r(e.delete)},_pendingGPD:function(e){return function(){var t=Array.prototype.slice.call(arguments);return new Promise(function(r,n){this._pending.push({method:e,args:t,promise:{resolve:r,reject:n}})}.bind(this))}.bind(this)},_processPending:function(){this._pending.forEach(function(e){try{this[e.method].apply(this,e.args).then(e.promise.resolve,e.promise.reject)}catch(t){e.promise.reject(t)}}.bind(this)),this._pending=[]},_bindChange:function(e){e.on("change",this._dispatchEvent.bind(this,"change"))},_dispatchEvent:function(e,t){var r=this;Object.keys(this._pathHandlers[e]).forEach((function(n){var o=n.length;t.path.substr(0,o)===n&&r._pathHandlers[e][n].forEach((function(e){var o={};for(var i in t)o[i]=t[i];o.relativePath=t.path.replace(new RegExp("^"+n),"");try{e(o)}catch(e){console.error("'change' handler failed: ",e,e.stack),r._emit("error",e)}}))}))},scope:function(e){if("string"!=typeof e)throw"Argument 'path' of baseClient.scope must be a string";if(!this.access.checkPathPermission(e,"r")){var t=e.replace(/(['\\])/g,"\\$1");console.warn("WARNING: please call remoteStorage.access.claim('"+t+"', 'r') (read only) or remoteStorage.access.claim('"+t+"', 'rw') (read/write) first")}return new c(this,e)},getSyncInterval:function(){return l.syncInterval},setSyncInterval:function(e){if(!_(e))throw e+" is not a valid sync interval";var t=l.syncInterval;l.syncInterval=parseInt(e,10),this._emit("sync-interval-change",{oldValue:t,newValue:e})},getBackgroundSyncInterval:function(){return l.backgroundSyncInterval},setBackgroundSyncInterval:function(e){if(!_(e))throw e+" is not a valid sync interval";var t=l.backgroundSyncInterval;l.backgroundSyncInterval=parseInt(e,10),this._emit("sync-interval-change",{oldValue:t,newValue:e})},getCurrentSyncInterval:function(){return l.isBackground?l.backgroundSyncInterval:l.syncInterval},getRequestTimeout:function(){return l.requestTimeout},setRequestTimeout:function(e){l.requestTimeout=parseInt(e,10)},syncCycle:function(){this.sync&&!this.sync.stopped&&(this.on("sync-done",function(){d("[Sync] Sync done. Setting timer to",this.getCurrentSyncInterval()),this.sync&&!this.sync.stopped&&(this._syncTimer&&(clearTimeout(this._syncTimer),this._syncTimer=void 0),this._syncTimer=setTimeout(this.sync.sync.bind(this.sync),this.getCurrentSyncInterval()))}.bind(this)),this.sync.sync())},startSync:function(){return l.cache?(this.sync.stopped=!1,this.syncStopped=!1,this.sync.sync()):(console.warn("Nothing to sync, because caching is disabled."),Promise.resolve())},stopSync:function(){clearTimeout(this._syncTimer),this._syncTimer=void 0,this.sync?(d("[Sync] Stopping sync"),this.sync.stopped=!0):(d("[Sync] Will instantiate sync stopped"),this.syncStopped=!0)}},b.util=i,Object.defineProperty(b.prototype,"connected",{get:function(){return this.remote.connected}});var w=r(15);Object.defineProperty(b.prototype,"access",{get:function(){var e=new w;return Object.defineProperty(this,"access",{value:e}),e},configurable:!0});var P=r(16);Object.defineProperty(b.prototype,"caching",{configurable:!0,get:function(){var e=new P;return Object.defineProperty(this,"caching",{value:e}),e}}),e.exports=b,r(32)},function(e,t){var r;r=function(){return this}();try{r=r||new Function("return this")()}catch(e){"object"==typeof window&&(r=window)}e.exports=r},function(e,t,r){function n(e){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}var o,i=r(4),s=r(5),a=r(6),u=r(0),c=r(2),l=r(24),h=r(7),f="remotestorage:dropbox",d=u.isFolder,p=u.cleanPath,m=u.shouldBeTreatedAsBinary,y=u.getJSONFromLocalStorage,g=u.getTextFromArrayBuffer,v=function(e){return p("/remotestorage/"+e).replace(/\/$/,"")},b=function(e,t){return new RegExp("^"+t.join("\\/")+"(\\/|$)").test(e.error_summary)},_=function(e){return e instanceof ArrayBuffer||a.isArrayBufferView(e)},w=function(e){if(this.rs=e,this.connected=!1,this.rs=e,this._initialFetchDone=!1,c(this,"connected","not-connected"),this.clientId=e.apiKeys.dropbox.appKey,this._revCache=new l("rev"),this._fetchDeltaCursor=null,this._fetchDeltaPromise=null,this._itemRefs={},o=u.localStorageAvailable()){var t=y(f);t&&this.configure(t),this._itemRefs=y("".concat(f,":shares"))||{}}this.connected&&setTimeout(this._emit.bind(this),0,"connected")};function P(e){e._dropboxOrigSync||(e._dropboxOrigSync=e.sync.sync.bind(e.sync),e.sync.sync=function(){return this.dropbox.fetchDelta.apply(this.dropbox,arguments).then(e._dropboxOrigSync,(function(t){e._emit("error",new h.SyncError(t)),e._emit("sync-done")}))}.bind(e))}function E(e){e._dropboxOrigSyncCycle&&(e.syncCycle=e._dropboxOrigSyncCycle,delete e._dropboxOrigSyncCycle)}function S(e){!function(e){e._origRemote||(e._origRemote=e.remote,e.remote=e.dropbox)}(e),e.sync?P(e):function(e){var t=arguments;e._dropboxOrigSyncCycle||(e._dropboxOrigSyncCycle=e.syncCycle,e.syncCycle=function(){if(!e.sync)throw new Error("expected sync to be initialized by now");P(e),e._dropboxOrigSyncCycle(t),E(e)})}(e),function(e){e._origBaseClientGetItemURL||(e._origBaseClientGetItemURL=s.prototype.getItemURL,s.prototype.getItemURL=function(){throw new Error("getItemURL is not implemented for Dropbox yet")})}(e)}function T(e){!function(e){e._origRemote&&(e.remote=e._origRemote,delete e._origRemote)}(e),function(e){e._dropboxOrigSync&&(e.sync.sync=e._dropboxOrigSync,delete e._dropboxOrigSync)}(e),function(e){e._origBaseClientGetItemURL&&(s.prototype.getItemURL=e._origBaseClientGetItemURL,delete e._origBaseClientGetItemURL)}(e),E(e)}w.prototype={online:!0,connect:function(){this.rs.setBackend("dropbox"),this.token?S(this.rs):this.rs.authorize({authURL:"https://www.dropbox.com/oauth2/authorize",scope:"",clientId:this.clientId})},configure:function(e){void 0!==e.userAddress&&(this.userAddress=e.userAddress),void 0!==e.token&&(this.token=e.token);var t=function(){o&&localStorage.setItem(f,JSON.stringify({userAddress:this.userAddress,token:this.token}))},r=function(){this.connected=!1,o&&localStorage.removeItem(f)};this.token?(this.connected=!0,this.userAddress?(this._emit("connected"),t.apply(this)):this.info().then(function(e){this.userAddress=e.email,this._emit("connected"),t.apply(this)}.bind(this)).catch(function(){r.apply(this),this.rs._emit("error",new Error("Could not fetch user info."))}.bind(this))):r.apply(this)},stopWaitingForToken:function(){this.connected||this._emit("not-connected")},_getFolder:function(e){var t=this._revCache,r=this,n=function(n){var i,s;if(200!==n.status&&409!==n.status)return Promise.reject("Unexpected response status: "+n.status);try{i=JSON.parse(n.responseText)}catch(e){return Promise.reject(e)}return 409===n.status?b(i,["path","not_found"])?Promise.resolve({}):Promise.reject(new Error("API returned an error: "+i.error_summary)):(s=i.entries.reduce((function(n,o){var i="folder"===o[".tag"],s=o.path_lower.split("/").slice(-1)[0]+(i?"/":"");return i?n[s]={ETag:t.get(e+s)}:(n[s]={ETag:o.rev},r._revCache.set(e+s,o.rev)),n}),{}),i.has_more?o(i.cursor).then((function(e){return Object.assign(s,e)})):Promise.resolve(s))},o=function(e){var t={body:{cursor:e}};return r._request("POST","https://api.dropboxapi.com/2/files/list_folder/continue",t).then(n)};return this._request("POST","https://api.dropboxapi.com/2/files/list_folder",{body:{path:v(e)}}).then(n).then((function(r){return Promise.resolve({statusCode:200,body:r,contentType:"application/json; charset=UTF-8",revision:t.get(e)})}))},get:function(e,t){var r=this;if(!this.connected)return Promise.reject("not connected (path: "+e+")");var n=this,o=this._revCache.get(e);if(null===o)return Promise.resolve({statusCode:404});if(t&&t.ifNoneMatch){if(!this._initialFetchDone)return this.fetchDelta().then((function(){return r.get(e,t)}));if(o&&o===t.ifNoneMatch)return Promise.resolve({statusCode:304})}if("/"===e.substr(-1))return this._getFolder(e,t);var i={headers:{"Dropbox-API-Arg":JSON.stringify({path:v(e)})},responseType:"arraybuffer"};return t&&t.ifNoneMatch&&(i.headers["If-None-Match"]=t.ifNoneMatch),this._request("GET","https://content.dropboxapi.com/2/files/download",i).then((function(t){var r,o,i,s,a=t.status;return 200!==a&&409!==a?Promise.resolve({statusCode:a}):(r=t.getResponseHeader("Dropbox-API-Result"),g(t.response,"UTF-8").then((function(u){o=u,409===a&&(r=o);try{r=JSON.parse(r)}catch(e){return Promise.reject(e)}if(409===a)return b(r,["path","not_found"])?{statusCode:404}:Promise.reject(new Error('API error while downloading file ("'+e+'"): '+r.error_summary));if(i=t.getResponseHeader("Content-Type"),s=r.rev,n._revCache.set(e,s),n._shareIfNeeded(e),m(u,i))o=t.response;else try{o=JSON.parse(o),i="application/json; charset=UTF-8"}catch(e){}return{statusCode:a,body:o,contentType:i,revision:s}})))}))},put:function(e,t,r,n){var o=this;if(!this.connected)throw new Error("not connected (path: "+e+")");var i=this._revCache.get(e);if(n&&n.ifMatch&&i&&i!==n.ifMatch)return Promise.resolve({statusCode:412,revision:i});if(n&&"*"===n.ifNoneMatch&&i&&"rev"!==i)return Promise.resolve({statusCode:412,revision:i});if(!r.match(/charset=/)&&_(t)&&(r+="; charset=binary"),t.length>157286400)return Promise.reject(new Error("Cannot upload file larger than 150MB"));var s=n&&(n.ifMatch||"*"===n.ifNoneMatch),a={body:t,contentType:r,path:e};return(s?this._getMetadata(e).then((function(e){return n&&"*"===n.ifNoneMatch&&e?Promise.resolve({statusCode:412,revision:e.rev}):n&&n.ifMatch&&e&&e.rev!==n.ifMatch?Promise.resolve({statusCode:412,revision:e.rev}):o._uploadSimple(a)})):o._uploadSimple(a)).then((function(t){return o._shareIfNeeded(e),t}))},delete:function(e,t){var r=this;if(!this.connected)throw new Error("not connected (path: "+e+")");var n=this._revCache.get(e);return t&&t.ifMatch&&n&&t.ifMatch!==n?Promise.resolve({statusCode:412,revision:n}):t&&t.ifMatch?this._getMetadata(e).then((function(n){return t&&t.ifMatch&&n&&n.rev!==t.ifMatch?Promise.resolve({statusCode:412,revision:n.rev}):r._deleteSimple(e)})):this._deleteSimple(e)},_shareIfNeeded:function(e){e.match(/^\/public\/.*[^/]$/)&&void 0===this._itemRefs[e]&&this.share(e)},share:function(e){var t=this,r={body:{path:v(e)}};return this._request("POST","https://api.dropboxapi.com/2/sharing/create_shared_link_with_settings",r).then((function(r){if(200!==r.status&&409!==r.status)return Promise.reject(new Error("Invalid response status:"+r.status));var n;try{n=JSON.parse(r.responseText)}catch(e){return Promise.reject(new Error("Invalid response body: "+r.responseText))}return 409===r.status?b(n,["shared_link_already_exists"])?t._getSharedLink(e):Promise.reject(new Error("API error: "+n.error_summary)):Promise.resolve(n.url)})).then((function(r){return t._itemRefs[e]=r,o&&localStorage.setItem(f+":shares",JSON.stringify(t._itemRefs)),Promise.resolve(r)}),(function(t){return t.message='Sharing Dropbox file or folder ("'+e+'") failed: '+t.message,Promise.reject(t)}))},info:function(){return this._request("POST","https://api.dropboxapi.com/2/users/get_current_account",{}).then((function(e){var t=e.responseText;try{t=JSON.parse(t)}catch(e){return Promise.reject(new Error("Could not query current account info: Invalid API response: "+t))}return Promise.resolve({email:t.email})}))},_request:function(e,t,r){var o=this;return r.headers||(r.headers={}),r.headers.Authorization="Bearer "+this.token,"object"!==n(r.body)||_(r.body)||(r.body=JSON.stringify(r.body),r.headers["Content-Type"]="application/json; charset=UTF-8"),this.rs._emit("wire-busy",{method:e,isFolder:d(t)}),a.request.call(this,e,t,r).then((function(n){return n&&503===n.status?(o.online&&(o.online=!1,o.rs._emit("network-offline")),setTimeout(o._request(e,t,r),3210)):(o.online||(o.online=!0,o.rs._emit("network-online")),o.rs._emit("wire-done",{method:e,isFolder:d(t),success:!0}),Promise.resolve(n))}),(function(r){return o.online&&(o.online=!1,o.rs._emit("network-offline")),o.rs._emit("wire-done",{method:e,isFolder:d(t),success:!1}),Promise.reject(r)}))},fetchDelta:function(){var e=this;if(this._fetchDeltaPromise)return this._fetchDeltaPromise;var t=Array.prototype.slice.call(arguments),r=this,o=function e(n){var o,s="https://api.dropboxapi.com/2/files/list_folder";return"string"==typeof n?(s+="/continue",o={cursor:n}):o={path:"/remotestorage",recursive:!0,include_deleted:!0},r._request("POST",s,{body:o}).then((function(o){if(401===o.status)return r.rs._emit("error",new i.Unauthorized),Promise.resolve(t);if(200!==o.status&&409!==o.status)return Promise.reject(new Error("Invalid response status: "+o.status));var s;try{s=JSON.parse(o.responseText)}catch(e){return Promise.reject(new Error("Invalid response body: "+o.responseText))}if(409===o.status){if(!b(s,["path","not_found"]))return Promise.reject(new Error("API returned an error: "+s.error_summary));s={cursor:null,entries:[],has_more:!1}}if(n||r._revCache.deactivatePropagation(),s.entries.forEach((function(e){var t=e.path_lower.substr("/remotestorage".length);"deleted"===e[".tag"]?(r._revCache.delete(t),r._revCache.delete(t+"/")):"file"===e[".tag"]&&r._revCache.set(t,e.rev)})),r._fetchDeltaCursor=s.cursor,s.has_more)return e(s.cursor);r._revCache.activatePropagation(),r._initialFetchDone=!0})).catch((function(e){return"timeout"===e||e instanceof ProgressEvent?Promise.resolve():Promise.reject(e)}))};return this._fetchDeltaPromise=o(r._fetchDeltaCursor).catch((function(t){return"object"===n(t)&&"message"in t?t.message="Dropbox: fetchDelta: "+t.message:t="Dropbox: fetchDelta: ".concat(t),e._fetchDeltaPromise=null,Promise.reject(t)})).then((function(){return e._fetchDeltaPromise=null,Promise.resolve(t)})),this._fetchDeltaPromise},_getMetadata:function(e){var t={path:v(e)};return this._request("POST","https://api.dropboxapi.com/2/files/get_metadata",{body:t}).then((function(e){if(200!==e.status&&409!==e.status)return Promise.reject(new Error("Invalid response status:"+e.status));var t;try{t=JSON.parse(e.responseText)}catch(t){return Promise.reject(new Error("Invalid response body: "+e.responseText))}return 409===e.status?b(t,["path","not_found"])?Promise.resolve():Promise.reject(new Error("API error: "+t.error_summary)):Promise.resolve(t)})).then(void 0,(function(t){return t.message='Could not load metadata for file or folder ("'+e+'"): '+t.message,Promise.reject(t)}))},_uploadSimple:function(e){var t=this,r={path:v(e.path),mode:{".tag":"overwrite"},mute:!0};return e.ifMatch&&(r.mode={".tag":"update",update:e.ifMatch}),this._request("POST","https://content.dropboxapi.com/2/files/upload",{body:e.body,headers:{"Content-Type":"application/octet-stream","Dropbox-API-Arg":JSON.stringify(r)}}).then((function(r){if(200!==r.status&&409!==r.status)return Promise.resolve({statusCode:r.status});var n=r.responseText;try{n=JSON.parse(n)}catch(e){return Promise.reject(new Error("Invalid API result: "+n))}return 409===r.status?b(n,["path","conflict"])?t._getMetadata(e.path).then((function(e){return Promise.resolve({statusCode:412,revision:e.rev})})):Promise.reject(new Error("API error: "+n.error_summary)):(t._revCache.set(e.path,n.rev),Promise.resolve({statusCode:r.status,revision:n.rev}))}))},_deleteSimple:function(e){var t=this,r={path:v(e)};return this._request("POST","https://api.dropboxapi.com/2/files/delete",{body:r}).then((function(e){if(200!==e.status&&409!==e.status)return Promise.resolve({statusCode:e.status});var t=e.responseText;try{t=JSON.parse(t)}catch(e){return Promise.reject(new Error("Invalid response body: "+t))}return 409===e.status?b(t,["path_lookup","not_found"])?Promise.resolve({statusCode:404}):Promise.reject(new Error("API error: "+t.error_summary)):Promise.resolve({statusCode:200})})).then((function(r){return 200!==r.statusCode&&404!==r.statusCode||(t._revCache.delete(e),delete t._itemRefs[e]),Promise.resolve(r)}),(function(t){return t.message='Could not delete Dropbox file or folder ("'+e+'"): '+t.message,Promise.reject(t)}))},_getSharedLink:function(e){var t={body:{path:v(e),direct_only:!0}};return this._request("POST","https://api.dropbox.com/2/sharing/list_shared_links",t).then((function(e){if(200!==e.status&&409!==e.status)return Promise.reject(new Error("Invalid response status: "+e.status));var t;try{t=JSON.parse(e.responseText)}catch(t){return Promise.reject(new Error("Invalid response body: "+e.responseText))}return 409===e.status?Promise.reject(new Error("API error: "+e.error_summary)):t.links.length?Promise.resolve(t.links[0].url):Promise.reject(new Error("No links returned"))}),(function(t){return t.message='Could not get link to a shared file or folder ("'+e+'"): '+t.message,Promise.reject(t)}))}},w._rs_init=function(e){o=u.localStorageAvailable(),e.apiKeys.dropbox&&(e.dropbox=new w(e)),"dropbox"===e.backend&&S(e)},w._rs_supported=function(){return!0},w._rs_cleanup=function(e){T(e),o&&localStorage.removeItem(f),e.setBackend(void 0)},e.exports=w},function(e,t,r){var n=r(2),o="undefined"!=typeof window?"browser":"node",i={},s=function(){return i};s.isBrowser=function(){return"browser"===o},s.isNode=function(){return"node"===o},s.goBackground=function(){s._emit("background")},s.goForeground=function(){s._emit("foreground")},s._rs_init=function(){function e(){document[i.hiddenProperty]?s.goBackground():s.goForeground()}n(s,"background","foreground"),"browser"===o&&(void 0!==document.hidden?(i.hiddenProperty="hidden",i.visibilityChangeEvent="visibilitychange"):void 0!==document.mozHidden?(i.hiddenProperty="mozHidden",i.visibilityChangeEvent="mozvisibilitychange"):void 0!==document.msHidden?(i.hiddenProperty="msHidden",i.visibilityChangeEvent="msvisibilitychange"):void 0!==document.webkitHidden&&(i.hiddenProperty="webkitHidden",i.visibilityChangeEvent="webkitvisibilitychange"),document.addEventListener(i.visibilityChangeEvent,e,!1),e())},s._rs_cleanup=function(){},e.exports=s},function(e,t,r){function n(e){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}var o,i=r(5),s=r(6),a=r(2),u=r(0),c="https://www.googleapis.com",l="remotestorage:googledrive",h=u.isFolder,f=u.cleanPath,d=u.shouldBeTreatedAsBinary,p=u.getJSONFromLocalStorage,m=u.getTextFromArrayBuffer;function y(e){return"/"===e.substr(-1)&&(e=e.substr(0,e.length-1)),decodeURIComponent(e)}function g(e){return e.replace(/[^\/]+\/?$/,"")}function v(e){var t=e.split("/");return"/"===e.substr(-1)?t[t.length-2]+"/":t[t.length-1]}function b(e){return f("".concat("/remotestorage","/").concat(e))}function _(e){return e.replace(/^["'](.*)["']$/,"$1")}var w=function(e){this.maxAge=e,this._items={}};w.prototype={get:function(e){var t=this._items[e],r=(new Date).getTime();return t&&t.t>=r-this.maxAge?t.v:void 0},set:function(e,t){this._items[e]={v:t,t:(new Date).getTime()}}};var P=function(e,t){if(a(this,"connected","not-connected"),this.rs=e,this.clientId=t,this._fileIdCache=new w(300),o=u.localStorageAvailable()){var r=p(l);r&&this.configure(r)}};P.prototype={connected:!1,online:!0,configure:function(e){var t=this;void 0!==e.userAddress&&(this.userAddress=e.userAddress),void 0!==e.token&&(this.token=e.token);var r=function(){o&&localStorage.setItem(l,JSON.stringify({userAddress:this.userAddress,token:this.token}))},n=function(){this.connected=!1,delete this.token,o&&localStorage.removeItem(l)};this.token?(this.connected=!0,this.userAddress?(this._emit("connected"),r.apply(this)):this.info().then((function(e){t.userAddress=e.user.emailAddress,t._emit("connected"),r.apply(t)})).catch((function(){n.apply(t),t.rs._emit("error",new Error("Could not fetch user info."))}))):n.apply(this)},connect:function(){this.rs.setBackend("googledrive"),this.rs.authorize({authURL:"https://accounts.google.com/o/oauth2/auth",scope:"https://www.googleapis.com/auth/drive",clientId:this.clientId})},stopWaitingForToken:function(){this.connected||this._emit("not-connected")},get:function(e,t){return"/"===e.substr(-1)?this._getFolder(b(e),t):this._getFile(b(e),t)},put:function(e,t,r,n){var o=this,i=b(e);function s(e){if(e.status>=200&&e.status<300){var t=JSON.parse(e.responseText),r=_(t.etag);return Promise.resolve({statusCode:200,contentType:t.mimeType,revision:r})}return 412===e.status?Promise.resolve({statusCode:412,revision:"conflict"}):Promise.reject("PUT failed with status "+e.status+" ("+e.responseText+")")}return this._getFileId(i).then((function(e){return e?n&&"*"===n.ifNoneMatch?s({status:412}):o._updateFile(e,i,t,r,n).then(s):o._createFile(i,t,r,n).then(s)}))},delete:function(e,t){var r=this,o=b(e);return this._getFileId(o).then((function(e){return e?r._getMeta(e).then((function(o){var i;return"object"===n(o)&&"string"==typeof o.etag&&(i=_(o.etag)),t&&t.ifMatch&&t.ifMatch!==i?{statusCode:412,revision:i}:r._request("DELETE",c+"/drive/v2/files/"+e,{}).then((function(e){return 200===e.status||204===e.status?{statusCode:200}:Promise.reject("Delete failed: "+e.status+" ("+e.responseText+")")}))})):Promise.resolve({statusCode:200})}))},info:function(){return this._request("GET","https://www.googleapis.com/drive/v2/about?fields=user",{}).then((function(e){try{var t=JSON.parse(e.responseText);return Promise.resolve(t)}catch(e){return Promise.reject(e)}}))},_updateFile:function(e,t,r,n,o){var i=this,s={mimeType:n},a={"Content-Type":"application/json; charset=UTF-8"};return o&&o.ifMatch&&(a["If-Match"]='"'+o.ifMatch+'"'),this._request("PUT",c+"/upload/drive/v2/files/"+e+"?uploadType=resumable",{body:JSON.stringify(s),headers:a}).then((function(e){return 412===e.status?e:i._request("PUT",e.getResponseHeader("Location"),{body:n.match(/^application\/json/)?JSON.stringify(r):r})}))},_createFile:function(e,t,r){var n=this;return this._getParentId(e).then((function(o){var i={title:y(v(e)),mimeType:r,parents:[{kind:"drive#fileLink",id:o}]};return n._request("POST",c+"/upload/drive/v2/files?uploadType=resumable",{body:JSON.stringify(i),headers:{"Content-Type":"application/json; charset=UTF-8"}}).then((function(e){return n._request("POST",e.getResponseHeader("Location"),{body:r.match(/^application\/json/)?JSON.stringify(t):t})}))}))},_getFile:function(e,t){var r=this;return this._getFileId(e).then((function(e){return r._getMeta(e).then((function(e){var o;if("object"===n(e)&&"string"==typeof e.etag&&(o=_(e.etag)),t&&t.ifNoneMatch&&o===t.ifNoneMatch)return Promise.resolve({statusCode:304});if(!e.downloadUrl){if(!e.exportLinks||!e.exportLinks["text/html"])return Promise.resolve({statusCode:200,body:"",contentType:e.mimeType,revision:o});e.mimeType+=";export=text/html",e.downloadUrl=e.exportLinks["text/html"]}return r._request("GET",e.downloadUrl,{responseType:"arraybuffer"}).then((function(t){return m(t.response,"UTF-8").then((function(r){var n=r;if(e.mimeType.match(/^application\/json/))try{n=JSON.parse(n)}catch(e){}else d(r,e.mimeType)&&(n=t.response);return{statusCode:200,body:n,contentType:e.mimeType,revision:o}}))}))}))}))},_getFolder:function(e){var t=this;return this._getFileId(e).then((function(r){var n,o,i,s;return r?(n="'"+r+"' in parents","items(downloadUrl,etag,fileSize,id,mimeType,title)",t._request("GET",c+"/drive/v2/files?q="+encodeURIComponent(n)+"&fields="+encodeURIComponent("items(downloadUrl,etag,fileSize,id,mimeType,title)")+"&maxResults=1000",{}).then((function(r){if(200!==r.status)return Promise.reject("request failed or something: "+r.status);try{o=JSON.parse(r.responseText)}catch(e){return Promise.reject("non-JSON response from GoogleDrive")}s={};var n=!0,a=!1,u=void 0;try{for(var c,l=o.items[Symbol.iterator]();!(n=(c=l.next()).done);n=!0){var h=c.value;i=_(h.etag),"application/vnd.google-apps.folder"===h.mimeType?(t._fileIdCache.set(e+h.title+"/",h.id),s[h.title+"/"]={ETag:i}):(t._fileIdCache.set(e+h.title,h.id),s[h.title]={ETag:i,"Content-Type":h.mimeType,"Content-Length":h.fileSize})}}catch(e){a=!0,u=e}finally{try{n||null==l.return||l.return()}finally{if(a)throw u}}return Promise.resolve({statusCode:200,body:s,contentType:"application/json; charset=UTF-8",revision:void 0})}))):Promise.resolve({statusCode:404})}))},_getParentId:function(e){var t=this,r=g(e);return this._getFileId(r).then((function(e){return e?Promise.resolve(e):t._createFolder(r)}))},_createFolder:function(e){var t=this;return this._getParentId(e).then((function(r){return t._request("POST",c+"/drive/v2/files",{body:JSON.stringify({title:y(v(e)),mimeType:"application/vnd.google-apps.folder",parents:[{id:r}]}),headers:{"Content-Type":"application/json; charset=UTF-8"}}).then((function(e){var t=JSON.parse(e.responseText);return Promise.resolve(t.id)}))}))},_getFileId:function(e){var t,r=this;return"/"===e?Promise.resolve("root"):(t=this._fileIdCache.get(e))?Promise.resolve(t):this._getFolder(g(e)).then((function(){return(t=r._fileIdCache.get(e))?Promise.resolve(t):"/"===e.substr(-1)?r._createFolder(e).then((function(){return r._getFileId(e)})):Promise.resolve()}))},_getMeta:function(e){return this._request("GET",c+"/drive/v2/files/"+e,{}).then((function(t){return 200===t.status?Promise.resolve(JSON.parse(t.responseText)):Promise.reject("request (getting metadata for "+e+") failed with status: "+t.status)}))},_request:function(e,t,r){var n=this;return r.headers||(r.headers={}),r.headers.Authorization="Bearer "+this.token,this.rs._emit("wire-busy",{method:e,isFolder:h(t)}),s.request.call(this,e,t,r).then((function(r){return r&&401===r.status?void n.connect():(n.online||(n.online=!0,n.rs._emit("network-online")),n.rs._emit("wire-done",{method:e,isFolder:h(t),success:!0}),Promise.resolve(r))}),(function(r){return n.online&&(n.online=!1,n.rs._emit("network-offline")),n.rs._emit("wire-done",{method:e,isFolder:h(t),success:!1}),Promise.reject(r)}))}},P._rs_init=function(e){var t,r=e.apiKeys.googledrive;r&&(e.googledrive=new P(e,r.clientId),"googledrive"===e.backend&&(e._origRemote=e.remote,e.remote=e.googledrive,(t=e)._origBaseClientGetItemURL||(t._origBaseClientGetItemURL=i.prototype.getItemURL,i.prototype.getItemURL=function(){throw new Error("getItemURL is not implemented for Google Drive yet")})))},P._rs_supported=function(){return!0},P._rs_cleanup=function(e){var t;e.setBackend(void 0),e._origRemote&&(e.remote=e._origRemote,delete e._origRemote),(t=e)._origBaseClientGetItemURL&&(i.prototype.getItemURL=t._origBaseClientGetItemURL,delete t._origBaseClientGetItemURL)},e.exports=P},function(e,t,r){"use strict";function n(e){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}var o,i=r(1),s=r(0),a=r(25),u={},c=function(e){return new Promise((function(t,r){return e in u?t(u[e]):new a({tls_only:!1,uri_fallback:!0,request_timeout:5e3}).lookup(e,(function(s,a){if(s)return r(s);if("object"!==n(a.idx.links.remotestorage)||"number"!=typeof a.idx.links.remotestorage.length||a.idx.links.remotestorage.length<=0)return i("[Discover] WebFinger record for "+e+" does not have remotestorage defined in the links section ",JSON.stringify(a.json)),r("WebFinger record for "+e+" does not have remotestorage defined in the links section.");var c=a.idx.links.remotestorage[0],l=c.properties["http://tools.ietf.org/html/rfc6749#section-4.2"]||c.properties["auth-endpoint"],h=c.properties["http://remotestorage.io/spec/version"]||c.type;return u[e]={href:c.href,storageApi:h,authURL:l,properties:c.properties},o&&(localStorage["remotestorage:discover"]=JSON.stringify({cache:u})),t(u[e])}))}))};(c.DiscoveryError=function(e){this.name="DiscoveryError",this.message=e,this.stack=(new Error).stack}).prototype=Object.create(Error.prototype),c.DiscoveryError.prototype.constructor=c.DiscoveryError,c._rs_init=function(){if(o=s.localStorageAvailable()){var e;try{e=JSON.parse(localStorage["remotestorage:discover"])}catch(e){}e&&(u=e.cache)}},c._rs_supported=function(){return!!s.globalContext.XMLHttpRequest},c._rs_cleanup=function(){o&&delete localStorage["remotestorage:discover"]},e.exports=c},function(e,t){var r=function(){this.reset()};r.prototype={claim:function(e,t){if("string"!=typeof e||-1!==e.indexOf("/")||0===e.length)throw new Error("Scope should be a non-empty string without forward slashes");if(!t.match(/^rw?$/))throw new Error("Mode should be either 'r' or 'rw'");this._adjustRootPaths(e),this.scopeModeMap[e]=t},get:function(e){return this.scopeModeMap[e]},remove:function(e){var t,r={};for(t in this.scopeModeMap)r[t]=this.scopeModeMap[t];for(t in this.reset(),delete r[e],r)this.set(t,r[t])},checkPermission:function(e,t){var r=this.get(e);return r&&("r"===t||"rw"===r)},checkPathPermission:function(e,t){return!!this.checkPermission("*",t)||!!this.checkPermission(this._getModuleName(e),t)},reset:function(){this.rootPaths=[],this.scopeModeMap={}},_getModuleName:function(e){if("/"!==e[0])throw new Error("Path should start with a slash");var t=e.replace(/^\/public/,"").match(/^\/([^/]*)\//);return t?t[1]:"*"},_adjustRootPaths:function(e){"*"in this.scopeModeMap||"*"===e?this.rootPaths=["/"]:e in this.scopeModeMap||(this.rootPaths.push("/"+e+"/"),this.rootPaths.push("/public/"+e+"/"))},_scopeNameForParameter:function(e){if("*"===e.name&&this.storageType){if("2012.04"===this.storageType)return"";if(this.storageType.match(/remotestorage-0[01]/))return"root"}return e.name},setStorageType:function(e){this.storageType=e}},Object.defineProperty(r.prototype,"scopes",{get:function(){return Object.keys(this.scopeModeMap).map(function(e){return{name:e,mode:this.scopeModeMap[e]}}.bind(this))}}),Object.defineProperty(r.prototype,"scopeParameter",{get:function(){return this.scopes.map(function(e){return this._scopeNameForParameter(e)+":"+e.mode}.bind(this)).join(" ")}}),r._rs_init=function(){},e.exports=r},function(e,t,r){var n=r(0),o=r(1),i=n.containingFolder,s=function(){this.reset()};s.prototype={pendingActivations:[],set:function(e,t){if("string"!=typeof e)throw new Error("path should be a string");if(!n.isFolder(e))throw new Error("path should be a folder");if(this._remoteStorage&&this._remoteStorage.access&&!this._remoteStorage.access.checkPathPermission(e,"r"))throw new Error('No access to path "'+e+'". You have to claim access to it first.');if(!t.match(/^(FLUSH|SEEN|ALL)$/))throw new Error("strategy should be 'FLUSH', 'SEEN', or 'ALL'");this._rootPaths[e]=t,"ALL"===t&&(this.activateHandler?this.activateHandler(e):this.pendingActivations.push(e))},enable:function(e){this.set(e,"ALL")},disable:function(e){this.set(e,"FLUSH")},onActivate:function(e){var t;for(o("[Caching] Setting activate handler",e,this.pendingActivations),this.activateHandler=e,t=0;t * @license MIT */ var n=r(19),o=r(20),i=r(21);function s(){return u.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function a(e,t){if(s()=s())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s().toString(16)+" bytes");return 0|e}function p(e,t){if(u.isBuffer(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var r=e.length;if(0===r)return 0;for(var n=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return B(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return q(e).length;default:if(n)return B(e).length;t=(""+t).toLowerCase(),n=!0}}function m(e,t,r){var n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return O(this,t,r);case"utf8":case"utf-8":return A(this,t,r);case"ascii":return R(this,t,r);case"latin1":case"binary":return k(this,t,r);case"base64":return T(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return I(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function y(e,t,r){var n=e[t];e[t]=e[r],e[r]=n}function g(e,t,r,n,o){if(0===e.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(r)&&(r=o?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(o)return-1;r=e.length-1}else if(r<0){if(!o)return-1;r=0}if("string"==typeof t&&(t=u.from(t,n)),u.isBuffer(t))return 0===t.length?-1:v(e,t,r,n,o);if("number"==typeof t)return t&=255,u.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):v(e,[t],r,n,o);throw new TypeError("val must be string, number or Buffer")}function v(e,t,r,n,o){var i,s=1,a=e.length,u=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;s=2,a/=2,u/=2,r/=2}function c(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(o){var l=-1;for(i=r;ia&&(r=a-u),i=r;i>=0;i--){for(var h=!0,f=0;fo&&(n=o):n=o;var i=t.length;if(i%2!=0)throw new TypeError("Invalid hex string");n>i/2&&(n=i/2);for(var s=0;s>8,o=r%256,i.push(o),i.push(n);return i}(t,e.length-r),e,r,n)}function T(e,t,r){return 0===t&&r===e.length?n.fromByteArray(e):n.fromByteArray(e.slice(t,r))}function A(e,t,r){r=Math.min(e.length,r);for(var n=[],o=t;o239?4:c>223?3:c>191?2:1;if(o+h<=r)switch(h){case 1:c<128&&(l=c);break;case 2:128==(192&(i=e[o+1]))&&(u=(31&c)<<6|63&i)>127&&(l=u);break;case 3:i=e[o+1],s=e[o+2],128==(192&i)&&128==(192&s)&&(u=(15&c)<<12|(63&i)<<6|63&s)>2047&&(u<55296||u>57343)&&(l=u);break;case 4:i=e[o+1],s=e[o+2],a=e[o+3],128==(192&i)&&128==(192&s)&&128==(192&a)&&(u=(15&c)<<18|(63&i)<<12|(63&s)<<6|63&a)>65535&&u<1114112&&(l=u)}null===l?(l=65533,h=1):l>65535&&(l-=65536,n.push(l>>>10&1023|55296),l=56320|1023&l),n.push(l),o+=h}return function(e){var t=e.length;if(t<=4096)return String.fromCharCode.apply(String,e);var r="",n=0;for(;n0&&(e=this.toString("hex",0,r).match(/.{2}/g).join(" "),this.length>r&&(e+=" ... ")),""},u.prototype.compare=function(e,t,r,n,o){if(!u.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===o&&(o=this.length),t<0||r>e.length||n<0||o>this.length)throw new RangeError("out of range index");if(n>=o&&t>=r)return 0;if(n>=o)return-1;if(t>=r)return 1;if(this===e)return 0;for(var i=(o>>>=0)-(n>>>=0),s=(r>>>=0)-(t>>>=0),a=Math.min(i,s),c=this.slice(n,o),l=e.slice(t,r),h=0;ho)&&(r=o),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var i=!1;;)switch(n){case"hex":return b(this,e,t,r);case"utf8":case"utf-8":return _(this,e,t,r);case"ascii":return w(this,e,t,r);case"latin1":case"binary":return P(this,e,t,r);case"base64":return E(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return S(this,e,t,r);default:if(i)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),i=!0}},u.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function R(e,t,r){var n="";r=Math.min(e.length,r);for(var o=t;on)&&(r=n);for(var o="",i=t;ir)throw new RangeError("Trying to access beyond buffer length")}function M(e,t,r,n,o,i){if(!u.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>o||te.length)throw new RangeError("Index out of range")}function N(e,t,r,n){t<0&&(t=65535+t+1);for(var o=0,i=Math.min(e.length-r,2);o>>8*(n?o:1-o)}function x(e,t,r,n){t<0&&(t=4294967295+t+1);for(var o=0,i=Math.min(e.length-r,4);o>>8*(n?o:3-o)&255}function U(e,t,r,n,o,i){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function j(e,t,r,n,i){return i||U(e,0,r,4),o.write(e,t,r,n,23,4),r+4}function L(e,t,r,n,i){return i||U(e,0,r,8),o.write(e,t,r,n,52,8),r+8}u.prototype.slice=function(e,t){var r,n=this.length;if((e=~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),(t=void 0===t?n:~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),t0&&(o*=256);)n+=this[e+--t]*o;return n},u.prototype.readUInt8=function(e,t){return t||C(e,1,this.length),this[e]},u.prototype.readUInt16LE=function(e,t){return t||C(e,2,this.length),this[e]|this[e+1]<<8},u.prototype.readUInt16BE=function(e,t){return t||C(e,2,this.length),this[e]<<8|this[e+1]},u.prototype.readUInt32LE=function(e,t){return t||C(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},u.prototype.readUInt32BE=function(e,t){return t||C(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},u.prototype.readIntLE=function(e,t,r){e|=0,t|=0,r||C(e,t,this.length);for(var n=this[e],o=1,i=0;++i=(o*=128)&&(n-=Math.pow(2,8*t)),n},u.prototype.readIntBE=function(e,t,r){e|=0,t|=0,r||C(e,t,this.length);for(var n=t,o=1,i=this[e+--n];n>0&&(o*=256);)i+=this[e+--n]*o;return i>=(o*=128)&&(i-=Math.pow(2,8*t)),i},u.prototype.readInt8=function(e,t){return t||C(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},u.prototype.readInt16LE=function(e,t){t||C(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},u.prototype.readInt16BE=function(e,t){t||C(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},u.prototype.readInt32LE=function(e,t){return t||C(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},u.prototype.readInt32BE=function(e,t){return t||C(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},u.prototype.readFloatLE=function(e,t){return t||C(e,4,this.length),o.read(this,e,!0,23,4)},u.prototype.readFloatBE=function(e,t){return t||C(e,4,this.length),o.read(this,e,!1,23,4)},u.prototype.readDoubleLE=function(e,t){return t||C(e,8,this.length),o.read(this,e,!0,52,8)},u.prototype.readDoubleBE=function(e,t){return t||C(e,8,this.length),o.read(this,e,!1,52,8)},u.prototype.writeUIntLE=function(e,t,r,n){(e=+e,t|=0,r|=0,n)||M(this,e,t,r,Math.pow(2,8*r)-1,0);var o=1,i=0;for(this[t]=255&e;++i=0&&(i*=256);)this[t+o]=e/i&255;return t+r},u.prototype.writeUInt8=function(e,t,r){return e=+e,t|=0,r||M(this,e,t,1,255,0),u.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},u.prototype.writeUInt16LE=function(e,t,r){return e=+e,t|=0,r||M(this,e,t,2,65535,0),u.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):N(this,e,t,!0),t+2},u.prototype.writeUInt16BE=function(e,t,r){return e=+e,t|=0,r||M(this,e,t,2,65535,0),u.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):N(this,e,t,!1),t+2},u.prototype.writeUInt32LE=function(e,t,r){return e=+e,t|=0,r||M(this,e,t,4,4294967295,0),u.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):x(this,e,t,!0),t+4},u.prototype.writeUInt32BE=function(e,t,r){return e=+e,t|=0,r||M(this,e,t,4,4294967295,0),u.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):x(this,e,t,!1),t+4},u.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t|=0,!n){var o=Math.pow(2,8*r-1);M(this,e,t,r,o-1,-o)}var i=0,s=1,a=0;for(this[t]=255&e;++i>0)-a&255;return t+r},u.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t|=0,!n){var o=Math.pow(2,8*r-1);M(this,e,t,r,o-1,-o)}var i=r-1,s=1,a=0;for(this[t+i]=255&e;--i>=0&&(s*=256);)e<0&&0===a&&0!==this[t+i+1]&&(a=1),this[t+i]=(e/s>>0)-a&255;return t+r},u.prototype.writeInt8=function(e,t,r){return e=+e,t|=0,r||M(this,e,t,1,127,-128),u.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},u.prototype.writeInt16LE=function(e,t,r){return e=+e,t|=0,r||M(this,e,t,2,32767,-32768),u.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):N(this,e,t,!0),t+2},u.prototype.writeInt16BE=function(e,t,r){return e=+e,t|=0,r||M(this,e,t,2,32767,-32768),u.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):N(this,e,t,!1),t+2},u.prototype.writeInt32LE=function(e,t,r){return e=+e,t|=0,r||M(this,e,t,4,2147483647,-2147483648),u.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):x(this,e,t,!0),t+4},u.prototype.writeInt32BE=function(e,t,r){return e=+e,t|=0,r||M(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),u.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):x(this,e,t,!1),t+4},u.prototype.writeFloatLE=function(e,t,r){return j(this,e,t,!0,r)},u.prototype.writeFloatBE=function(e,t,r){return j(this,e,t,!1,r)},u.prototype.writeDoubleLE=function(e,t,r){return L(this,e,t,!0,r)},u.prototype.writeDoubleBE=function(e,t,r){return L(this,e,t,!1,r)},u.prototype.copy=function(e,t,r,n){if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t=0;--o)e[o+t]=this[o+r];else if(i<1e3||!u.TYPED_ARRAY_SUPPORT)for(o=0;o>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(i=t;i55295&&r<57344){if(!o){if(r>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(s+1===n){(t-=3)>-1&&i.push(239,191,189);continue}o=r;continue}if(r<56320){(t-=3)>-1&&i.push(239,191,189),o=r;continue}r=65536+(o-55296<<10|r-56320)}else o&&(t-=3)>-1&&i.push(239,191,189);if(o=null,r<128){if((t-=1)<0)break;i.push(r)}else if(r<2048){if((t-=2)<0)break;i.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;i.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;i.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return i}function q(e){return n.toByteArray(function(e){if((e=function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}(e).replace(D,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function J(e,t,r,n){for(var o=0;o=t.length||o>=e.length);++o)t[o+r]=e[o];return o}}).call(this,r(10))},function(e,t,r){"use strict";t.byteLength=function(e){var t=c(e),r=t[0],n=t[1];return 3*(r+n)/4-n},t.toByteArray=function(e){var t,r,n=c(e),s=n[0],a=n[1],u=new i(function(e,t,r){return 3*(t+r)/4-r}(0,s,a)),l=0,h=a>0?s-4:s;for(r=0;r>16&255,u[l++]=t>>8&255,u[l++]=255&t;2===a&&(t=o[e.charCodeAt(r)]<<2|o[e.charCodeAt(r+1)]>>4,u[l++]=255&t);1===a&&(t=o[e.charCodeAt(r)]<<10|o[e.charCodeAt(r+1)]<<4|o[e.charCodeAt(r+2)]>>2,u[l++]=t>>8&255,u[l++]=255&t);return u},t.fromByteArray=function(e){for(var t,r=e.length,o=r%3,i=[],s=0,a=r-o;sa?a:s+16383));1===o?(t=e[r-1],i.push(n[t>>2]+n[t<<4&63]+"==")):2===o&&(t=(e[r-2]<<8)+e[r-1],i.push(n[t>>10]+n[t>>4&63]+n[t<<2&63]+"="));return i.join("")};for(var n=[],o=[],i="undefined"!=typeof Uint8Array?Uint8Array:Array,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0,u=s.length;a0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function l(e,t,r){for(var o,i,s=[],a=t;a>18&63]+n[i>>12&63]+n[i>>6&63]+n[63&i]);return s.join("")}o["-".charCodeAt(0)]=62,o["_".charCodeAt(0)]=63},function(e,t){t.read=function(e,t,r,n,o){var i,s,a=8*o-n-1,u=(1<>1,l=-7,h=r?o-1:0,f=r?-1:1,d=e[t+h];for(h+=f,i=d&(1<<-l)-1,d>>=-l,l+=a;l>0;i=256*i+e[t+h],h+=f,l-=8);for(s=i&(1<<-l)-1,i>>=-l,l+=n;l>0;s=256*s+e[t+h],h+=f,l-=8);if(0===i)i=1-c;else{if(i===u)return s?NaN:1/0*(d?-1:1);s+=Math.pow(2,n),i-=c}return(d?-1:1)*s*Math.pow(2,i-n)},t.write=function(e,t,r,n,o,i){var s,a,u,c=8*i-o-1,l=(1<>1,f=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,d=n?0:i-1,p=n?1:-1,m=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,s=l):(s=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-s))<1&&(s--,u*=2),(t+=s+h>=1?f/u:f*Math.pow(2,1-h))*u>=2&&(s++,u/=2),s+h>=l?(a=0,s=l):s+h>=1?(a=(t*u-1)*Math.pow(2,o),s+=h):(a=t*Math.pow(2,h-1)*Math.pow(2,o),s=0));o>=8;e[r+d]=255&a,d+=p,a/=256,o-=8);for(s=s<0;e[r+d]=255&s,d+=p,s/=256,c-=8);e[r+d-p]|=128*m}},function(e,t){var r={}.toString;e.exports=Array.isArray||function(e){return"[object Array]"==r.call(e)}},function(e,t,r){var n,o,i;o=[],void 0===(i="function"==typeof(n=function(){var e,t,r,n;Object.keys||(Object.keys=(e=Object.prototype.hasOwnProperty,t=!{toString:null}.propertyIsEnumerable("toString"),n=(r=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"]).length,function(o){if("object"!=typeof o&&"function"!=typeof o||null===o)throw new TypeError("Object.keys called on non-object");var i=[];for(var s in o)e.call(o,s)&&i.push(s);if(t)for(var a=0;a>>0;if(0===r)return-1;var n=0;if(arguments.length>1&&((n=Number(arguments[1]))!=n?n=0:0!==n&&n!==1/0&&n!==-1/0&&(n=(n>0||-1)*Math.floor(Math.abs(n)))),n>=r)return-1;for(var o=n>=0?n:Math.max(r-Math.abs(n),0);o0&&(t+=l.suffices["*"]&&r||",",l.suffices["*"]&&u&&(t+=l.name+"=")),t+=a?encodeURIComponent(h[d]).replace(/!/g,"%21"):s(h[d])}else if("object"==typeof h){u&&!l.suffices["*"]&&(t+=l.name+"=");var p=!0;for(var m in h)p||(t+=l.suffices["*"]&&r||","),p=!1,t+=a?encodeURIComponent(m).replace(/!/g,"%21"):s(m),t+=l.suffices["*"]?"=":",",t+=a?encodeURIComponent(h[m]).replace(/!/g,"%21"):s(h[m])}else u&&(t+=l.name,c&&""===h||(t+="=")),null!=l.truncate&&(h=h.substring(0,l.truncate)),t+=a?encodeURIComponent(h).replace(/!/g,"%21"):s(h)}return t};return _.varNames=l,{prefix:n,substitution:_}}function u(e){if(!(this instanceof u))return new u(e);for(var t=e.split("{"),r=[t.shift()],n=[],o=[],i=[];t.length>0;){var s=t.shift(),c=s.split("}")[0],l=s.substring(c.length+1),h=a(c);o.push(h.substitution),n.push(h.prefix),r.push(l),i=i.concat(h.substitution.varNames)}this.fill=function(e){for(var t=r[0],n=0;n0&&"/"===t.charAt(e.length-1)||"#"===r.charAt(0)||"?"===r.charAt(0))return!0}return!1}(t,e.id)&&void 0===this.schemas[e.id]&&(this.schemas[e.id]=e),e)if("enum"!==n)if("object"==typeof e[n])this.searchSchemas(e[n],t);else if("$ref"===n){var o=m(e[n]);o&&void 0===this.schemas[o]&&void 0===this.missingMap[o]&&(this.missingMap[o]=o)}},c.prototype.addSchema=function(e,t){if("string"!=typeof e||void 0===t){if("object"!=typeof e||"string"!=typeof e.id)return;e=(t=e).id}e===m(e)+"#"&&(e=m(e)),this.schemas[e]=t,delete this.missingMap[e],y(t,e),this.searchSchemas(t,e)},c.prototype.getSchemaMap=function(){var e={};for(var t in this.schemas)e[t]=this.schemas[t];return e},c.prototype.getSchemaUris=function(e){var t=[];for(var r in this.schemas)e&&!e.test(r)||t.push(r);return t},c.prototype.getMissingUris=function(e){var t=[];for(var r in this.missingMap)e&&!e.test(r)||t.push(r);return t},c.prototype.dropSchemas=function(){this.schemas={},this.reset()},c.prototype.reset=function(){this.missing=[],this.missingMap={},this.errors=[]},c.prototype.validateAll=function(e,t,r,n,o){var i;if(!(t=this.resolveRefs(t)))return null;if(t instanceof P)return this.errors.push(t),t;var s,a=this.errors.length,u=null,c=null;if(this.checkRecursive&&e&&"object"==typeof e){if(i=!this.scanned.length,e[this.validatedSchemasKey]){var l=e[this.validatedSchemasKey].indexOf(t);if(-1!==l)return this.errors=this.errors.concat(e[this.validationErrorsKey][l]),null}if(Object.isFrozen(e)&&-1!==(s=this.scannedFrozen.indexOf(e))){var h=this.scannedFrozenSchemas[s].indexOf(t);if(-1!==h)return this.errors=this.errors.concat(this.scannedFrozenValidationErrors[s][h]),null}if(this.scanned.push(e),Object.isFrozen(e))-1===s&&(s=this.scannedFrozen.length,this.scannedFrozen.push(e),this.scannedFrozenSchemas.push([])),u=this.scannedFrozenSchemas[s].length,this.scannedFrozenSchemas[s][u]=t,this.scannedFrozenValidationErrors[s][u]=[];else{if(!e[this.validatedSchemasKey])try{Object.defineProperty(e,this.validatedSchemasKey,{value:[],configurable:!0}),Object.defineProperty(e,this.validationErrorsKey,{value:[],configurable:!0})}catch(t){e[this.validatedSchemasKey]=[],e[this.validationErrorsKey]=[]}c=e[this.validatedSchemasKey].length,e[this.validatedSchemasKey][c]=t,e[this.validationErrorsKey][c]=[]}}var f=this.errors.length,d=this.validateBasic(e,t,o)||this.validateNumeric(e,t,o)||this.validateString(e,t,o)||this.validateArray(e,t,o)||this.validateObject(e,t,o)||this.validateCombinations(e,t,o)||this.validateHypermedia(e,t,o)||this.validateFormat(e,t,o)||this.validateDefinedKeywords(e,t,o)||null;if(i){for(;this.scanned.length;)delete this.scanned.pop()[this.validatedSchemasKey];this.scannedFrozen=[],this.scannedFrozenSchemas=[]}if(d||f!==this.errors.length)for(;r&&r.length||n&&n.length;){var p=r&&r.length?""+r.pop():null,m=n&&n.length?""+n.pop():null;d&&(d=d.prefixWith(p,m)),this.prefixErrors(f,p,m)}return null!==u?this.scannedFrozenValidationErrors[s][u]=this.errors.slice(a):null!==c&&(e[this.validationErrorsKey][c]=this.errors.slice(a)),this.handleError(d)},c.prototype.validateFormat=function(e,t){if("string"!=typeof t.format||!this.formatValidators[t.format])return null;var r=this.formatValidators[t.format].call(null,e,t);return"string"==typeof r||"number"==typeof r?this.createError(v.FORMAT_CUSTOM,{message:r},"","/format",null,e,t):r&&"object"==typeof r?this.createError(v.FORMAT_CUSTOM,{message:r.message||"?"},r.dataPath||"",r.schemaPath||"/format",null,e,t):null},c.prototype.validateDefinedKeywords=function(e,t,r){for(var n in this.definedKeywords)if(void 0!==t[n])for(var o=this.definedKeywords[n],i=0;i=h&&nt.maximum)return this.createError(v.NUMBER_MAXIMUM,{value:e,maximum:t.maximum},"","/maximum",null,e,t);if(t.exclusiveMaximum&&e===t.maximum)return this.createError(v.NUMBER_MAXIMUM_EXCLUSIVE,{value:e,maximum:t.maximum},"","/exclusiveMaximum",null,e,t)}return null},c.prototype.validateNaN=function(e,t){return"number"!=typeof e?null:!0===isNaN(e)||e===1/0||e===-1/0?this.createError(v.NUMBER_NOT_A_NUMBER,{value:e},"","/type",null,e,t):null},c.prototype.validateString=function(e,t,r){return this.validateStringLength(e,t,r)||this.validateStringPattern(e,t,r)||null},c.prototype.validateStringLength=function(e,t){return"string"!=typeof e?null:void 0!==t.minLength&&e.lengtht.maxLength?this.createError(v.STRING_LENGTH_LONG,{length:e.length,maximum:t.maxLength},"","/maxLength",null,e,t):null},c.prototype.validateStringPattern=function(e,t){if("string"!=typeof e||"string"!=typeof t.pattern&&!(t.pattern instanceof RegExp))return null;var r;if(t.pattern instanceof RegExp)r=t.pattern;else{var n,o="",i=t.pattern.match(/^\/(.+)\/([img]*)$/);i?(n=i[1],o=i[2]):n=t.pattern,r=new RegExp(n,o)}return r.test(e)?null:this.createError(v.STRING_PATTERN,{pattern:t.pattern},"","/pattern",null,e,t)},c.prototype.validateArray=function(e,t,r){return Array.isArray(e)&&(this.validateArrayLength(e,t,r)||this.validateArrayUniqueItems(e,t,r)||this.validateArrayItems(e,t,r))||null},c.prototype.validateArrayLength=function(e,t){var r;return void 0!==t.minItems&&e.lengtht.maxItems&&(r=this.createError(v.ARRAY_LENGTH_LONG,{length:e.length,maximum:t.maxItems},"","/maxItems",null,e,t),this.handleError(r))?r:null},c.prototype.validateArrayUniqueItems=function(e,t){if(t.uniqueItems)for(var r=0;rt.maxProperties&&(r=this.createError(v.OBJECT_PROPERTIES_MAXIMUM,{propertyCount:n.length,maximum:t.maxProperties},"","/maxProperties",null,e,t),this.handleError(r))?r:null},c.prototype.validateObjectRequiredProperties=function(e,t){if(void 0!==t.required)for(var r=0;r 10000");if(void 0!==v[e])throw new Error("Error already defined: "+e+" as "+v[e]);if(void 0!==b[t])throw new Error("Error code already used: "+b[t]+" as "+t);for(var n in v[e]=t,b[t]=e,w[e]=w[t]=r,E){var o=E[n];o[e]&&(o[t]=o[t]||o[e])}},reset:function(){o.reset(),this.error=null,this.missing=[],this.valid=!0},missing:[],error:null,valid:!0,normSchema:y,resolveUrl:p,getDocumentUri:m,errorCodes:v};return i.language(t||"en"),i}();return S.addLanguage("en-gb",w),S.tv4=S,S})?n.apply(t,o):n)||(e.exports=i)},function(e,t){var r={uris:{},schemas:{},aliases:{},declare:function(e,t,r,n){var o=e+"/"+t;if(n.extends){var i,s=n.extends.split("/");i=1===s.length?e+"/"+s.shift():s.join("/");var a=this.uris[i];if(!a)throw"Type '"+o+"' tries to extend unknown schema '"+i+"'";n.extends=this.schemas[a]}this.uris[o]=r,this.aliases[r]=o,this.schemas[r]=n},resolveAlias:function(e){return this.uris[e]},getSchema:function(e){return this.schemas[e]},inScope:function(e){var t=e.length,r={};for(var n in this.uris)if(n.substr(0,t+1)===e+"/"){var o=this.uris[n];r[o]=this.schemas[o]}return r}},n=function(e){var t=new Error("Schema not found: "+e);return t.name="SchemaNotFound",t};n.prototype=Error.prototype,r.SchemaNotFound=n,e.exports=r},function(e,t){function r(e){this.defaultValue=e,this._canPropagate=!1,this._storage={},this._itemsRev={},this.activatePropagation()}r.prototype={get:function(e){e=e.toLowerCase();var t=this._storage[e];return void 0===t&&(t=this.defaultValue,this._storage[e]=t),t},set:function(e,t){return e=e.toLowerCase(),this._storage[e]===t?t:(this._storage[e]=t,t||delete this._itemsRev[e],this._updateParentFolderItemRev(e,t),this._canPropagate&&this._propagate(e),t)},delete:function(e){return this.set(e,null)},deactivatePropagation:function(){return this._canPropagate=!1,!0},activatePropagation:function(){return!!this._canPropagate||(this._generateFolderRev("/"),this._canPropagate=!0,!0)},_hashCode:function(e){var t,r=0;if(0===e.length)return r;for(t=0;t0&&(r=this._generateHash(n))}return this.set(e,r),r}},e.exports=r},function(e,t,r){var n; /*! * webfinger.js * version 2.7.0 * http://github.com/silverbucket/webfinger.js * * Developed and Maintained by: * Nick Jennings 2012 * * webfinger.js is released under the AGPL (see LICENSE). * * You don't have to do anything special to choose one license or the other and you don't * have to notify anyone which license you are using. * Please see the corresponding license file for details of these licenses. * You are free to use, modify and distribute this software, but all copyright * information must remain. * */"function"!=typeof fetch&&"function"!=typeof XMLHttpRequest&&(XMLHttpRequest=r(26)),function(r){var o={"http://webfist.org/spec/rel":"webfist","http://webfinger.net/rel/avatar":"avatar",remotestorage:"remotestorage","http://tools.ietf.org/id/draft-dejong-remotestorage":"remotestorage",remoteStorage:"remotestorage","http://www.packetizer.com/rel/share":"share","http://webfinger.net/rel/profile-page":"profile",me:"profile",vcard:"vcard",blog:"blog","http://packetizer.com/rel/blog":"blog","http://schemas.google.com/g/2010#updates-from":"updates","https://camlistore.org/rel/server":"camilstore"},i={avatar:[],remotestorage:[],blog:[],vcard:[],updates:[],share:[],profile:[],webfist:[],camlistore:[]},s=["webfinger","host-meta","host-meta.json"];function a(e){return e.toString=function(){return this.message},e}function u(e){"object"!=typeof e&&(e={}),this.config={tls_only:void 0===e.tls_only||e.tls_only,webfist_fallback:void 0!==e.webfist_fallback&&e.webfist_fallback,uri_fallback:void 0!==e.uri_fallback&&e.uri_fallback,request_timeout:void 0!==e.request_timeout?e.request_timeout:1e4}}u.prototype.__fetchJRD=function(e,t,r){if("function"==typeof fetch)return this.__fetchJRD_fetch(e,t,r);if("function"==typeof XMLHttpRequest)return this.__fetchJRD_XHR(e,t,r);throw new Error("add a polyfill for fetch or XMLHttpRequest")},u.prototype.__fetchJRD_fetch=function(e,t,r){var n,o=this;"function"==typeof AbortController&&(n=new AbortController);var i=fetch(e,{headers:{Accept:"application/jrd+json, application/json"},signal:n?n.signal:void 0}).then((function(t){if(t.ok)return t.text();throw 404===t.status?a({message:"resource not found",url:e,status:t.status}):a({message:"error during request",url:e,status:t.status})}),(function(t){throw a({message:"error during request",url:e,status:void 0,err:t})})).then((function(t){if(o.__isValidJSON(t))return t;throw a({message:"invalid json",url:e,status:void 0})})),s=new Promise((function(t,r){setTimeout((function(){r(a({message:"request timed out",url:e,status:void 0})),n&&n.abort()}),o.config.request_timeout)}));Promise.race([i,s]).then((function(e){r(e)})).catch((function(e){t(e)}))},u.prototype.__fetchJRD_XHR=function(e,t,r){var n=this,o=!1,i=new XMLHttpRequest;function s(){if(!o){if(o=!0,200===i.status)return n.__isValidJSON(i.responseText)?r(i.responseText):t(a({message:"invalid json",url:e,status:i.status}));if(404===i.status)return t(a({message:"resource not found",url:e,status:i.status}));if(i.status>=301&&i.status<=302){var s=i.getResponseHeader("Location");return function(e){return"string"==typeof e&&"https"===e.split("://")[0]}(s)?u():t(a({message:"no redirect URL found",url:e,status:i.status}))}return t(a({message:"error during request",url:e,status:i.status}))}}function u(){i.onreadystatechange=function(){4===i.readyState&&s()},i.onload=function(){s()},i.ontimeout=function(){return t(a({message:"request timed out",url:e,status:i.status}))},i.open("GET",e,!0),i.timeout=n.config.request_timeout,i.setRequestHeader("Accept","application/jrd+json, application/json"),i.send()}return u()},u.prototype.__isValidJSON=function(e){try{JSON.parse(e)}catch(e){return!1}return!0},u.prototype.__isLocalhost=function(e){return/^localhost(\.localdomain)?(\:[0-9]+)?$/.test(e)},u.prototype.__processJRD=function(e,t,r,n){var s=JSON.parse(t);if("object"!=typeof s||"object"!=typeof s.links)return void 0!==s.error?r(a({message:s.error,request:e})):r(a({message:"unknown response from server",request:e}));var u=s.links;Array.isArray(u)||(u=[]);var c={object:s,json:t,idx:{}};c.idx.properties={name:void 0},c.idx.links=JSON.parse(JSON.stringify(i)),u.map((function(e,t){if(o.hasOwnProperty(e.rel)&&c.idx.links[o[e.rel]]){var r={};Object.keys(e).map((function(t,n){r[t]=e[t]})),c.idx.links[o[e.rel]].push(r)}}));var l=JSON.parse(t).properties;for(var h in l)l.hasOwnProperty(h)&&"http://packetizer.com/ns/name"===h&&(c.idx.properties.name=l[h]);return n(c)},u.prototype.lookup=function(e,t){if("string"!=typeof e)throw new Error("first parameter must be a user address");if("function"!=typeof t)throw new Error("second parameter must be a callback");var r=this,n="";n=e.indexOf("://")>-1?e.replace(/ /g,"").split("/")[2]:e.replace(/ /g,"").split("@")[1];var o=0,i="https";function a(){var t="";return e.split("://")[1]||(t="acct:"),i+"://"+n+"/.well-known/"+s[o]+"?resource="+t+e}function u(e){if(r.config.uri_fallback&&"webfist.org"!==n&&o!==s.length-1)return o+=1,c();if(!r.config.tls_only&&"https"===i)return o=0,i="http",c();if(!r.config.webfist_fallback||"webfist.org"===n)return t(e);o=0,i="http",n="webfist.org";var u=a();r.__fetchJRD(u,t,(function(e){r.__processJRD(u,e,t,(function(e){"object"==typeof e.idx.links.webfist&&"string"==typeof e.idx.links.webfist[0].href&&r.__fetchJRD(e.idx.links.webfist[0].href,t,(function(e){r.__processJRD(u,e,t,(function(e){return t(null,t)}))}))}))}))}function c(){var e=a();r.__fetchJRD(e,u,(function(n){r.__processJRD(e,n,t,(function(e){t(null,e)}))}))}return(r.__isLocalhost(n)&&(i="http"),setTimeout(c,0))},u.prototype.lookupLink=function(e,t,r){if(!i.hasOwnProperty(t))return r("unsupported rel "+t);this.lookup(e,(function(e,n){var o=n.idx.links[t];return e?r(e):0===o.length?r('no links found with rel="'+t+'"'):r(null,o[0])}))},void 0===(n=function(){return u}.apply(t,[]))||(e.exports=n)}()},function(e,t){e.exports=XMLHttpRequest},function(e,t,r){"use strict";function n(e){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}var o=r(0),i=r(1),s=r(28),a=r(3),u={features:[],featuresDone:0,readyFired:!1,loadFeatures:function(){var e=this;for(var t in this.features=[],this.featuresDone=0,this.readyFired=!1,this.featureModules={WireClient:r(6),Dropbox:r(11),GoogleDrive:r(13),Access:r(15),Discover:r(14),Authorize:r(4),BaseClient:r(5),Env:r(12)},a.cache&&o.extend(this.featureModules,{Caching:r(16),IndexedDB:r(29),LocalStorage:r(30),InMemoryStorage:r(31),Sync:r(7)}),a.disableFeatures.forEach((function(t){e.featureModules[t]&&delete e.featureModules[t]})),this._allLoaded=!1,this.featureModules)this.loadFeature(t)},hasFeature:function(e){for(var t=this.features.length-1;t>=0;t--)if(this.features[t].name===e)return this.features[t].supported;return!1},loadFeature:function(e){var t=this,r=this.featureModules[e],o=!r._rs_supported||r._rs_supported();i("[RemoteStorage] [FEATURE ".concat(e,"] initializing ...")),"object"===n(o)?o.then((function(){t.featureSupported(e,!0),t.initFeature(e)}),(function(){t.featureSupported(e,!1)})):"boolean"==typeof o?(this.featureSupported(e,o),o&&this.initFeature(e)):this.featureSupported(e,!1)},initFeature:function(e){var t,r=this,o=this.featureModules[e];try{t=o._rs_init(this)}catch(t){return void this.featureFailed(e,t)}"object"===n(t)&&"function"==typeof t.then?t.then((function(){r.featureInitialized(e)}),(function(t){r.featureFailed(e,t)})):this.featureInitialized(e)},featureFailed:function(e,t){i("[RemoteStorage] [FEATURE ".concat(e,"] initialization failed (").concat(t,")")),this.featureDone()},featureSupported:function(e,t){i("[RemoteStorage] [FEATURE ".concat(e,"] ").concat(t?"":" not"," supported")),t||this.featureDone()},featureInitialized:function(e){i("[RemoteStorage] [FEATURE ".concat(e,"] initialized.")),this.features.push({name:e,init:this.featureModules[e]._rs_init,supported:!0,cleanup:this.featureModules[e]._rs_cleanup}),this.featureDone()},featureDone:function(){this.featuresDone++,this.featuresDone===Object.keys(this.featureModules).length&&setTimeout(this.featuresLoaded.bind(this),0)},_setCachingModule:function(){var e=this;["IndexedDB","LocalStorage","InMemoryStorage"].some((function(t){if(e.features.some((function(e){return e.name===t})))return e.features.local=e.featureModules[t],!0}))},_fireReady:function(){try{this.readyFired||(this._emit("ready"),this.readyFired=!0)}catch(e){console.error("'ready' failed: ",e,e.stack),this._emit("error",e)}},featuresLoaded:function(){var e=this;i("[REMOTESTORAGE] All features loaded !"),this._setCachingModule(),this.local=a.cache&&this.features.local&&new this.features.local,this.local&&this.remote?(this._setGPD(s,this),this._bindChange(this.local)):this.remote&&this._setGPD(this.remote,this.remote),this.remote&&(this.remote.on("connected",(function(){e._fireReady(),e._emit("connected")})),this.remote.on("not-connected",(function(){e._fireReady(),e._emit("not-connected")})),this.remote.connected&&(this._fireReady(),this._emit("connected")),this.hasFeature("Authorize")||this.remote.stopWaitingForToken()),this._collectCleanupFunctions();try{this._allLoaded=!0,this._emit("features-loaded")}catch(e){o.logError(e),this._emit("error",e)}this._processPending()},_collectCleanupFunctions:function(){this._cleanups=[];for(var e=0;e0?this.getNodesFromDb(t).then((function(e){for(var t in r)e[t]=r[t];return e})):Promise.resolve(r)},setNodes:function(e){for(var t in e)this.changesQueued[t]=e[t]||!1;return this.maybeFlush(),Promise.resolve()},maybeFlush:function(){0===this.putsRunning?this.flushChangesQueued():this.commitSlownessWarning||(this.commitSlownessWarning=setInterval((function(){console.warn("WARNING: waited more than 10 seconds for previous commit to finish")}),1e4))},flushChangesQueued:function(){this.commitSlownessWarning&&(clearInterval(this.commitSlownessWarning),this.commitSlownessWarning=null),Object.keys(this.changesQueued).length>0&&(this.changesRunning=this.changesQueued,this.changesQueued={},this.setNodesInDb(this.changesRunning).then(this.flushChangesQueued.bind(this)))},getNodesFromDb:function(e){var t=this;return new Promise((function(r,n){var o=t.db.transaction(["nodes"],"readonly"),i=o.objectStore("nodes"),s={};t.getsRunning++,e.map((function(e){i.get(e).onsuccess=function(t){s[e]=t.target.result}})),o.oncomplete=function(){r(s),this.getsRunning--}.bind(t),o.onerror=o.onabort=function(){n("get transaction error/abort"),this.getsRunning--}.bind(t)}))},setNodesInDb:function(e){var t=this;return new Promise((function(r,o){var s=t.db.transaction(["nodes"],"readwrite"),a=s.objectStore("nodes"),u=(new Date).getTime();for(var c in t.putsRunning++,i("[IndexedDB] Starting put",e,t.putsRunning),e){var l=e[c];if("object"===n(l))try{a.put(l)}catch(e){throw i("[IndexedDB] Error while putting",l,e),e}else try{a.delete(c)}catch(e){throw i("[IndexedDB] Error while removing",a,l,e),e}}s.oncomplete=function(){this.putsRunning--,i("[IndexedDB] Finished put",e,this.putsRunning,(new Date).getTime()-u+"ms"),r()}.bind(t),s.onerror=function(){this.putsRunning--,o("transaction error")}.bind(t),s.onabort=function(){o("transaction abort"),this.putsRunning--}.bind(t)}))},reset:function(e){var t=this,r=this.db.name;this.db.close(),c.clean(this.db.name,(function(){c.open(r,(function(r,n){r?i("[IndexedDB] Error while resetting local storage",r):t.db=n,"function"==typeof e&&e(self)}))}))},forAllNodes:function(e){var t=this;return new Promise((function(r){t.db.transaction(["nodes"],"readonly").objectStore("nodes").openCursor().onsuccess=function(n){var o=n.target.result;o?(e(t.migrate(o.value)),o.continue()):r()}}))},closeDB:function(){0===this.putsRunning?this.db.close():setTimeout(this.closeDB.bind(this),100)}},c.open=function(e,t){var r=setTimeout((function(){t("timeout trying to open db")}),1e4);try{var n=indexedDB.open(e,2);n.onerror=function(){i("[IndexedDB] Opening DB failed",n),clearTimeout(r),t(n.error)},n.onupgradeneeded=function(e){var t=n.result;i("[IndexedDB] Upgrade: from ",e.oldVersion," to ",e.newVersion),1!==e.oldVersion&&(i("[IndexedDB] Creating object store: nodes"),t.createObjectStore("nodes",{keyPath:"path"})),i("[IndexedDB] Creating object store: changes"),t.createObjectStore("changes",{keyPath:"path"})},n.onsuccess=function(){clearTimeout(r);var o=n.result;if(!o.objectStoreNames.contains("nodes")||!o.objectStoreNames.contains("changes"))return i("[IndexedDB] Missing object store. Resetting the database."),void c.clean(e,(function(){c.open(e,t)}));t(null,n.result)}}catch(n){i("[IndexedDB] Failed to open database: "+n),i("[IndexedDB] Resetting database and trying again."),clearTimeout(r),c.clean(e,(function(){c.open(e,t)}))}},c.clean=function(e,t){var r=indexedDB.deleteDatabase(e);r.onsuccess=function(){i("[IndexedDB] Done removing DB"),t()},r.onerror=r.onabort=function(t){console.error('Failed to remove database "'+e+'"',t)}},c._rs_init=function(e){return new Promise((function(t,r){c.open("remotestorage",(function(n,i){n?r(n):(o=i,i.onerror=function(){e._emit("error",n)},t())}))}))},c._rs_supported=function(){return new Promise((function(e,t){var r=u.getGlobalContext(),n=!1;if("undefined"!=typeof navigator&&navigator.userAgent.match(/Android (2|3|4\.[0-3])/)&&(navigator.userAgent.match(/Chrome|Firefox/)||(n=!0)),"indexedDB"in r&&!n)try{var o=indexedDB.open("rs-check");o.onerror=function(){t()},o.onsuccess=function(){o.result.close(),indexedDB.deleteDatabase("rs-check"),e()}}catch(e){t()}else t()}))},c._rs_cleanup=function(e){return new Promise((function(t){e.local&&e.local.closeDB(),c.clean("remotestorage",t)}))},e.exports=c},function(e,t,r){var n=r(8),o=r(1),i=r(2),s=r(0),a="remotestorage:cache:nodes:",u=function(){n(this),o("[LocalStorage] Registering events"),i(this,"change","local-events-done")};function c(e){return e.substr(0,a.length)===a||"remotestorage:cache:changes:"===e.substr(0,"remotestorage:cache:changes:".length)}u.prototype={getNodes:function(e){for(var t={},r=0,n=e.length;r