diff --git a/com/isoterminal/feat/remoteStorage.js b/com/isoterminal/feat/remoteStorage.js new file mode 100644 index 0000000..b09a13b --- /dev/null +++ b/com/isoterminal/feat/remoteStorage.js @@ -0,0 +1,36 @@ +if( typeof emulator != 'undefined' ){ + // inside worker-thread + +}else{ + // inside browser-thread + // + ISOTerminal.prototype.remoteStorageInit = async function(opts){ + await AFRAME.utils.require({"remoteStorageWidget": "com/lib/aframe-remotestorage.min.js"}) + let el = document.querySelector("[remotestorage]") + if( el ){ + let value = el.getAttribute("remotestorage") + el.removeAttribute("remotestorage") + el.setAttribute("remotestorage", value) // (re)activate aframe component + this.remoteStorageMount() + } + } + + ISOTerminal.prototype.remoteStorageGet = function(){ + return document.querySelector('[remotestorage]')?.components.remotestorage.remoteStorage + } + + ISOTerminal.prototype.remoteStorageMount = function(){ + const rs = this.remoteStorageGet() + rs.addEventListener('connected', function(){ + + }) + + rs.addEventListener('not-connected', function(){ + + }) + } + + ISOTerminal.addEventListener('init', function(){ + this.addEventListener('term_init', (opts) => this.remoteStorageInit(opts.detail) ) + }) +} diff --git a/com/lib/aframe-remotestorage.min.js b/com/lib/aframe-remotestorage.min.js new file mode 100644 index 0000000..81ca790 --- /dev/null +++ b/com/lib/aframe-remotestorage.min.js @@ -0,0 +1,416 @@ +/*! For license information please see remotestorage.js.LICENSE.txt */!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(){var n,s={548:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Access=void 0;class n{static _rs_init(){}constructor(){this.reset()}get scopes(){return Object.keys(this.scopeModeMap).map(e=>({name:e,mode:this.scopeModeMap[e]}))}get scopeParameter(){return this.scopes.map(e=>`${this._scopeNameForParameter(e)}:${e.mode}`).join(" ")}claim(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(e){return this.scopeModeMap[e]}remove(e){const t={};for(const e in this.scopeModeMap)t[e]=this.scopeModeMap[e];this.reset(),delete t[e];for(const e in t)this.claim(e,t[e])}checkPermission(e,t){const n=this.get(e);return n&&("r"===t||"rw"===n)}checkPathPermission(e,t){if(this.checkPermission("*",t))return!0;const n=this._getModuleName(e);return!!this.checkPermission(n,t)}reset(){this.rootPaths=[],this.scopeModeMap={}}_getModuleName(e){if("/"!==e[0])throw new Error("Path should start with a slash");const t=e.replace(/^\/public/,"").match(/^\/([^/]*)\//);return t?t[1]:"*"}_adjustRootPaths(e){"*"in this.scopeModeMap||"*"===e?this.rootPaths=["/"]:e in this.scopeModeMap||(this.rootPaths.push("/"+e+"/"),this.rootPaths.push("/public/"+e+"/"))}_scopeNameForParameter(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(e){this.storageType=e}}t.Access=n,t.default=n},275:function(e,t,n){"use strict";var c=this&&this.__awaiter||function(e,t,n,s){return new(n||(n=Promise))(function(o,i){function r(e){try{a(s.next(e))}catch(e){i(e)}}function c(e){try{a(s.throw(e))}catch(e){i(e)}}function a(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(r,c)}a((s=s.apply(e,t||[])).next())})},l=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Authorize=void 0;const o=l(n(334)),i=n(746),a=l(n(503)),d=n(368);let r;function u(e){const n=e||s.getLocation().href,t={};for(const[e,s]of new URL(n).searchParams)t[e]=s;const o=n.indexOf("#");if(-1===o)return t;const i=n.substring(o+1);return i.includes("=")?i.split("&").reduce(function(e,t){const n=t.split("=");if("state"===n[0]&&n[1].match(/rsDiscovery/)){let t=decodeURIComponent(n[1]);const s=t.substr(t.indexOf("rsDiscovery=")).split("&")[0].split("=")[1];e.rsDiscovery=JSON.parse(atob(s)),t=t.replace(new RegExp("&?rsDiscovery="+s),""),t.length>0&&(e.state=t)}else e[decodeURIComponent(n[0])]=decodeURIComponent(n[1]);return e},t):t}class s{static authorize(e,t){if((0,o.default)("[Authorize] authURL = ",t.authURL,"scope = ",t.scope,"redirectUri = ",t.redirectUri,"clientId = ",t.clientId,"response_type =",t.response_type),!t.scope)throw new Error("Cannot authorize due to undefined or empty scope; did you forget to access.claim()?");if(!(0,i.localStorageAvailable)()&&"remotestorage"===e.backend){t.redirectUri+=t.redirectUri.indexOf("#")>0?"&":"#";const n={userAddress:e.remote.userAddress,href:e.remote.href,storageApi:e.remote.storageApi,properties:e.remote.properties};t.redirectUri+="rsDiscovery="+(0,i.toBase64)(JSON.stringify(n))}const n=function(e){const n=new URL(e.redirectUri);e.state||(e.state=n.hash?n.hash.substring(1):""),e.response_type||(e.response_type="token");const t=new URL(e.authURL);t.searchParams.set("redirect_uri",e.redirectUri.replace(/#.*$/,"")),t.searchParams.set("scope",e.scope),t.searchParams.set("client_id",e.clientId);for(const n of["state","response_type","code_challenge","code_challenge_method","token_access_type"]){const s=e[n];s&&t.searchParams.set(n,s)}return t.href}(t);i.globalContext.cordova?s.openWindow(n,t.redirectUri,"location=yes,clearsessioncache=yes,clearcache=yes").then(t=>{e.remote.configure({token:t.access_token})}):s.setLocation(n)}static refreshAccessToken(e,t,n){return c(this,void 0,void 0,function*(){var s,i,r;yield t.configure({token:null,tokenType:null});const c=new URLSearchParams({grant_type:"refresh_token",client_id:t.clientId,refresh_token:n}),e=yield(0,d.requestWithTimeout)("POST",t.TOKEN_URL,{headers:{"Content-Type":"application/x-www-form-urlencoded"},body:c.toString(),responseType:"json"});if(200!==e?.status)throw yield t.configure({refreshToken:null}),new a.default("refresh token rejected:"+JSON.stringify(e.response));{(0,o.default)(`[Authorize] access token good for ${null===(s=e?.response)||void 0===s?void 0:s.expires_in} seconds`);const n={token:null===(i=e?.response)||void 0===i?void 0:i.access_token,tokenType:null===(r=e?.response)||void 0===r?void 0:r.token_type};if(!n.token)throw new Error(`no access_token in "successful" refresh: ${e.response}`);yield t.configure(n)}})}static setLocation(e){if("string"==typeof e)document.location.href=e;else{if("object"!=typeof e)throw"Invalid location "+e;document.location=e}}static _rs_supported(){return"undefined"!=typeof document}static _rs_cleanup(e){e.removeEventListener("features-loaded",r)}}t.Authorize=s,s.IMPLIED_FAKE_TOKEN=!1,s.getLocation=function(){return document.location},s.openWindow=function(e,t,n){return new Promise((s,o)=>{const i=open(e,"_blank",n);function a(){o("Authorization was canceled")}i&&!i.closed?(i.addEventListener("loadstart",function(e){if(0!==e.url.indexOf(t))return;i.removeEventListener("exit",a),i.close();const n=u(e.url);n?s(n):o("Authorization error")}),i.addEventListener("exit",a)):o("Authorization popup was blocked")})},s._rs_init=function(e){const t=u();let n;t&&(n=s.getLocation(),n.hash=""),r=function(){let i=!1;if(t){if(t.error)throw"access_denied"===t.error?new a.default("Authorization failed: access denied",{code:"access_denied"}):new a.default(`Authorization failed: ${t.error}`);t.rsDiscovery&&e.remote.configure(t.rsDiscovery),t.access_token&&(e.remote.configure({token:t.access_token}),i=!0),t.remotestorage&&(e.connect(t.remotestorage),i=!0),t.state&&(n=s.getLocation(),s.setLocation(n.href.split("#")[0]+"#"+t.state)),t.code&&(function(t){c(this,void 0,void 0,function*(){var a,r,c,l;const u=sessionStorage.getItem("remotestorage:codeVerifier");if(!u)return void(0,o.default)("[Authorize] Ignoring OAuth code parameter, because no PKCE code verifier found in sessionStorage");n=s.getLocation();let h=n.origin;"/"!==n.pathname&&(h+=n.pathname);const m=new URLSearchParams({code:t,grant_type:"authorization_code",client_id:e.remote.clientId,redirect_uri:h,code_verifier:u}),i=yield(0,d.requestWithTimeout)("POST",e.remote.TOKEN_URL,{headers:{"Content-Type":"application/x-www-form-urlencoded"},body:m.toString(),responseType:"json"});if(200===i.status){(0,o.default)(`[Authorize] access token good for ${null===(a=i?.response)||void 0===a?void 0:a.expires_in} seconds`);const t={token:null===(r=i?.response)||void 0===r?void 0:r.access_token,refreshToken:null===(c=i?.response)||void 0===c?void 0:c.refresh_token,tokenType:null===(l=i?.response)||void 0===l?void 0:l.token_type};t.token?e.remote.configure(t):e._emit("error",new Error(`no access_token in "successful" response: ${i.response}`)),sessionStorage.removeItem("remotestorage:codeVerifier")}else e._emit("error",new Error(`${i.statusText}: ${i.response}`))})}(t.code),i=!0),i||e.remote.stopWaitingForToken()}else e.remote.stopWaitingForToken()},e.on("features-loaded",r)},t.default=s},424:function(e,t,n){"use strict";var o=this&&this.__awaiter||function(e,t,n,s){return new(n||(n=Promise))(function(o,i){function r(e){try{a(s.next(e))}catch(e){i(e)}}function c(e){try{a(s.throw(e))}catch(e){i(e)}}function a(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(r,c)}a((s=s.apply(e,t||[])).next())})},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.BaseClient=void 0;const r=i(n(439)),c=i(n(613)),l=i(n(491)),d=i(n(93)),u=i(n(28)),a=n(746);class s{constructor(e,t){if(this.schemas={configurable:!0,get(){return s.Types.inScope(this.moduleName)}},"/"!==t[t.length-1])throw"Not a folder: "+t;"/"===t&&(this.makePath=e=>("/"===e[0]?"":"/")+e),this.storage=e,this.base=t,this.moduleName=function(e){const t=e.split("/");return e.length>2?t[1]:"root"}(this.base),this.addEvents(["change"]),this.on=this.on.bind(this),e.onChange(this.base,this._fireChange.bind(this))}scope(e){return new s(this.storage,this.makePath(e))}getListing(e,t){return o(this,void 0,void 0,function*(){if("string"!=typeof e)e="";else if(e.length>0&&!(0,a.isFolder)(e))return Promise.reject("Not a folder: "+e);return this.storage.get(this.makePath(e),t).then(e=>404===e.statusCode?{}:e.body)})}getAll(e,t){return o(this,void 0,void 0,function*(){if("string"!=typeof e)e="";else if(e.length>0&&!(0,a.isFolder)(e))return Promise.reject("Not a folder: "+e);return this.storage.get(this.makePath(e),t).then(n=>{if(404===n.statusCode)return{};if("object"==typeof n.body){const s=Object.keys(n.body);if(0===s.length)return{};const o=s.map(s=>this.storage.get(this.makePath(e+s),t).then(e=>{if("string"==typeof e.body)try{e.body=JSON.parse(e.body)}catch{}"object"==typeof e.body&&(n.body[s]=e.body)}));return Promise.all(o).then(()=>n.body)}})})}getFile(e,t){return o(this,void 0,void 0,function*(){return"string"!=typeof e?Promise.reject("Argument 'path' of baseClient.getFile must be a string"):this.storage.get(this.makePath(e),t).then(e=>({data:e.body,contentType:e.contentType,revision:e.revision}))})}storeFile(e,t,n){return o(this,void 0,void 0,function*(){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 n&&"object"!=typeof n?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),n,e).then(e=>200===e.statusCode||201===e.statusCode?e.revision:Promise.reject("Request (PUT "+this.makePath(t)+") failed with status: "+e.statusCode)))})}getObject(e,t){return o(this,void 0,void 0,function*(){return"string"!=typeof e?Promise.reject("Argument 'path' of baseClient.getObject must be a string"):this.storage.get(this.makePath(e),t).then(t=>{if("object"==typeof t.body)return t.body;if("string"==typeof t.body)try{return JSON.parse(t.body)}catch{throw new Error("Not valid JSON: "+this.makePath(e))}else if(void 0!==t.body&&200===t.statusCode)return Promise.reject("Not an object: "+this.makePath(e))})})}storeObject(e,t,n){return o(this,void 0,void 0,function*(){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"!=typeof n)return Promise.reject("Argument 'object' of baseClient.storeObject must be an object");this._attachType(n,e);try{const e=this.validate(n);if(!e.valid)return Promise.reject(e)}catch(e){return Promise.reject(e)}return this.storage.put(this.makePath(t),JSON.stringify(n),"application/json; charset=UTF-8").then(e=>200===e.statusCode||201===e.statusCode?e.revision:Promise.reject("Request (PUT "+this.makePath(t)+") failed with status: "+e.statusCode))})}remove(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(e){if("string"!=typeof e)throw"Argument 'path' of baseClient.getItemURL must be a string";return this.storage.connected?(e=(0,a.cleanPath)(this.makePath(e)),this.storage.remote.href+e):void 0}cache(e,t="ALL"){if("string"!=typeof e)throw"Argument 'path' of baseClient.cache must be a string";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}declareType(e,t,n){let o;if(n&&"string"==typeof t)o=t;else if(n||"string"==typeof t){if(!n&&"string"==typeof t)throw new Error("declareType() requires a JSON Schema object to be passed, in order to validate object types/formats")}else n=t,o=this._defaultTypeURI(e);s.Types.declare(this.moduleName,e,o,n)}validate(e){const t=s.Types.getSchema(e["@context"]);if(t)return r.default.validateResult(e,t);throw new l.default(e["@context"])}_defaultTypeURI(e){return"http://remotestorage.io/spec/modules/"+encodeURIComponent(this.moduleName)+"/"+encodeURIComponent(e)}_attachType(e,t){e["@context"]=s.Types.resolveAlias(this.moduleName+"/"+t)||this._defaultTypeURI(t)}makePath(e){return this.base+(e||"")}_fireChange(e){u.default.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{}}),this._emit("change",e))}static _rs_init(){}}t.BaseClient=s,s.Types=c.default,(0,a.applyMixins)(s,[d.default]),t.default=s},285:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Caching=void 0;const s=n(746),a=i(n(334));class o{constructor(){this.pendingActivations=[],this.reset()}set(e,t){if("string"!=typeof e)throw new Error("path should be a string");if(!(0,s.isFolder)(e))throw new Error("path should be a folder");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(e){this.set(e,"ALL")}disable(e){this.set(e,"FLUSH")}onActivate(e){(0,a.default)("[Caching] Setting activate handler",e,this.pendingActivations),this.activateHandler=e;for(let t=0;t{const i=o(s[e]);return c(s,t)?n(e):i?{statusCode:200,body:i.body||i.itemsMap,contentType:i.contentType}:{statusCode:404}}):this.getNodes([e]).then(t=>{const n=o(t[e]);if(n){if((0,s.isFolder)(e))for(const e in n.itemsMap)n.itemsMap.hasOwnProperty(e)&&!1===n.itemsMap[e]&&delete n.itemsMap[e];return{statusCode:200,body:n.body||n.itemsMap,contentType:n.contentType}}return{statusCode:404}})})}put(e,t,n){return a(this,void 0,void 0,function*(){const i=(0,s.pathsFromRoot)(e);return this._updateNodes(i,function(e,s){try{for(let a=0,d=e.length;a0)break}}else console.error("Cannot delete non-existing node "+r)}return t})}flush(e){return this._getAllDescendentPaths(e).then(e=>this.getNodes(e)).then(e=>{for(const n in e){const t=e[n];t&&t.common&&t.local&&this._emitChange({path:t.path,origin:"local",oldValue:!1===t.local.body?void 0:t.local.body,newValue:!1===t.common.body?void 0:t.common.body}),e[n]=void 0}return this.setNodes(e)})}_emitChange(e){r.default.changeEvents[e.origin]&&this._emit("change",e)}fireInitial(){r.default.changeEvents.local&&this.forAllNodes(e=>{if((0,s.isDocument)(e.path)){const t=o(e);t&&this._emitChange({path:e.path,origin:"local",oldValue:void 0,oldContentType:void 0,newValue:t.body,newContentType:t.contentType})}}).then(()=>{this._emit("local-events-done")})}onDiff(e){this.diffHandler=e}migrate(e){return"object"!=typeof e||e.common||(e.common={},"string"==typeof e.path?"/"===e.path.substr(-1)&&"object"==typeof e.body&&(e.common.itemsMap=e.body):(e.local||(e.local={}),e.local.body=e.body,e.local.contentType=e.contentType)),e}_updateNodes(e,t){return new Promise((n,s)=>{this._doUpdateNodes(e,t,{resolve:n,reject:s})})}_doUpdateNodes(e,t,n){this._updateNodesRunning?this._updateNodesQueued.push({paths:e,cb:t,promise:n}):(this._updateNodesRunning=!0,this.getNodes(e).then(o=>{const a=(0,s.deepClone)(o),i=[];o=t(e,o);for(const t in o){const e=o[t];(0,s.equal)(e,a[t])?delete o[t]:(0,s.isDocument)(t)&&((0,s.equal)(e.local.body,e.local.previousBody)&&e.local.contentType===e.local.previousContentType||i.push({path:t,origin:"window",oldValue:e.local.previousBody,newValue:!1===e.local.body?void 0:e.local.body,oldContentType:e.local.previousContentType,newContentType:e.local.contentType}),delete e.local.previousBody,delete e.local.previousContentType)}this.setNodes(o).then(()=>{this._emitChangeEvents(i),n.resolve({statusCode:200})})}).then(()=>Promise.resolve(),e=>{n.reject(e)}).then(()=>{this._updateNodesRunning=!1;const e=this._updateNodesQueued.shift();e&&this._doUpdateNodes(e.paths,e.cb,e.promise)}))}_emitChangeEvents(e){for(let t=0,n=e.length;t{const n=[e],s=o(t[e]),i=Object.keys(s.itemsMap).map(t=>this._getAllDescendentPaths(e+t).then(e=>{for(let t=0,s=e.length;tn)}):Promise.resolve([e])}_getInternals(){return{getLatest:o,makeNode:l,isOutdated:c}}}(0,s.applyMixins)(d,[u.default]),e.exports=d},28:function(e){"use strict";e.exports={cache:!0,changeEvents:{local:!0,window:!1,remote:!0,conflict:!0},cordovaRedirectUri:void 0,logging:!1,modules:[],backgroundSyncInterval:6e4,disableFeatures:[],discoveryTimeout:5e3,isBackground:!1,requestTimeout:3e4,syncInterval:1e4}},373:function(e,t,n){"use strict";var a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const d=a(n(199)),l=a(n(28)),u=a(n(334)),r=n(746);let i;const c="remotestorage:discover";let o={};const s=function(e){return new Promise((t,n)=>{if(e in o)return t(o[e]);const s=new d.default({tls_only:!1,uri_fallback:!0,request_timeout:l.default.discoveryTimeout});return setTimeout(()=>n(new Error("timed out")),l.default.discoveryTimeout),s.lookup(e,function(s,a){if(s)return n(s);if("object"!=typeof a.idx.links.remotestorage||"number"!=typeof a.idx.links.remotestorage.length||a.idx.links.remotestorage.length<=0)return(0,u.default)("[Discover] WebFinger record for "+e+" does not have remotestorage defined in the links section ",JSON.stringify(a.json)),n("WebFinger record for "+e+" does not have remotestorage defined in the links section.");const r=a.idx.links.remotestorage[0],l=r.properties["http://tools.ietf.org/html/rfc6749#section-4.2"]||r.properties["auth-endpoint"],d=r.properties["http://remotestorage.io/spec/version"]||r.type;return o[e]={href:r.href,storageApi:d,authURL:l,properties:r.properties},i&&localStorage.setItem(c,JSON.stringify({cache:o})),t(o[e])})})};(s.DiscoveryError=function(e){this.name="DiscoveryError",this.message=e,this.stack=(new Error).stack}).prototype=Object.create(Error.prototype),s.DiscoveryError.prototype.constructor=s.DiscoveryError,s._rs_init=function(){if(i=(0,r.localStorageAvailable)(),i)try{const e=JSON.parse(localStorage[c]);o=e.cache}catch{}},s._rs_supported=function(){return Object.prototype.hasOwnProperty.call(r.globalContext,"fetch")||Object.prototype.hasOwnProperty.call(r.globalContext,"XMLHttpRequest")},s._rs_cleanup=function(){i&&delete localStorage[c]},e.exports=s},706:function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,s){return new(n||(n=Promise))(function(o,i){function r(e){try{a(s.next(e))}catch(e){i(e)}}function c(e){try{a(s.throw(e))}catch(e){i(e)}}function a(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(r,c)}a((s=s.apply(e,t||[])).next())})},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const x=c(n(93)),u=c(n(424)),w=c(n(941)),E=c(n(982)),m=c(n(503)),s=n(746),h=n(368),k=n(684),O=c(n(275));let o;const l="remotestorage:dropbox",g="https://api.dropboxapi.com/2/files/list_folder",v="https://api.dropboxapi.com/2/files/list_folder/continue",b="/remotestorage";function a(e){return(b+"/"+e).replace(/\/+$/,"").replace(/\/+/g,"/")}const C=/[\u007f-\uffff]/g;function _(e){return JSON.stringify(e).replace(C,function(e){return"\\u"+("000"+e.charCodeAt(0).toString(16)).slice(-4)})}function i(e,t){return new RegExp("^"+t.join("\\/")+"(\\/|$)").test(e.error_summary)}function f(e){return e instanceof ArrayBuffer||(0,h.isArrayBufferView)(e)}class d extends k.RemoteBase{constructor(e){if(super(e),this.online=!0,this.storageApi="draft-dejong-remotestorage-19",this._initialFetchDone=!1,this.addEvents(["connected","not-connected"]),this.clientId=e.apiKeys.dropbox.appKey,this.TOKEN_URL="https://api.dropboxapi.com/oauth2/token",this._revCache=new w.default("rev"),this._fetchDeltaCursor=null,this._fetchDeltaPromise=null,this._itemRefs={},o=(0,s.localStorageAvailable)(),o){const e=(0,s.getJSONFromLocalStorage)(l);e&&this.configure(e),this._itemRefs=(0,s.getJSONFromLocalStorage)(`${l}:shares`)||{}}this.connected&&setTimeout(this._emit.bind(this),0,"connected")}connect(){return r(this,void 0,void 0,function*(){try{if(this.rs.setBackend("dropbox"),this.token)p(this.rs);else{const{codeVerifier:t,codeChallenge:n,state:e}=yield(0,s.generateCodeVerifier)();sessionStorage.setItem("remotestorage:codeVerifier",t),sessionStorage.setItem("remotestorage:state",e),this.rs.authorize({authURL:"https://www.dropbox.com/oauth2/authorize",scope:"account_info.read files.content.read files.content.write files.metadata.read files.metadata.write",clientId:this.clientId,response_type:"code",state:e,code_challenge:n,code_challenge_method:"S256",token_access_type:"offline"})}}catch(e){throw this.rs._emit("error",e),this.rs.setBackend(void 0),e}})}configure(e){return r(this,void 0,void 0,function*(){void 0!==e.userAddress&&(this.userAddress=e.userAddress),void 0!==e.token&&(this.token=e.token),void 0!==e.refreshToken&&(this.refreshToken=e.refreshToken),void 0!==e.tokenType&&(this.tokenType=e.tokenType);const t=()=>{o&&localStorage.setItem(l,JSON.stringify({userAddress:this.userAddress,token:this.token,refreshToken:this.refreshToken,tokenType:this.tokenType}))};if(this.refreshToken||this.token)if(this.connected=!0,this.userAddress)this._emit("connected"),t();else try{const e=yield this.info();this.userAddress=e.email,this._emit("connected"),t()}catch{this.connected=!1,this.rs._emit("error",new Error("Could not fetch user info.")),t.apply(this)}else(()=>{this.connected=!1,o&&localStorage.removeItem(l),this.rs.setBackend(void 0)})()})}_getFolder(e){const t=this._revCache,n=n=>{let o;if(200!==n.status&&409!==n.status)return Promise.reject("Unexpected response status: "+n.status);try{o=JSON.parse(n.responseText)}catch(e){return Promise.reject(e)}if(409===n.status)return i(o,["path","not_found"])?Promise.resolve({}):Promise.reject(new Error("API returned an error: "+o.error_summary));const a=o.entries.reduce((n,s)=>{try{const i="folder"===s[".tag"],o=s.path_display.split("/").slice(-1)[0]+(i?"/":"");if(i)n[o]={ETag:t.get(e+o)};else{const t=new Date(s.server_modified);n[o]={ETag:s.rev,"Content-Length":s.size,"Last-Modified":t.toUTCString()},this._revCache.set(e+o,s.rev)}}catch(t){console.error(`[Dropbox] folder “${e}” has entry ${JSON.stringify(s)}:`,t)}return n},{});return o.has_more?s(o.cursor).then(function(e){return Object.assign(a,e)}):Promise.resolve(a)},s=e=>{const t={body:{cursor:e}};return this._request("POST",v,t).then(n)};return this._request("POST",g,{body:{path:a(e)}}).then(n).then(function(n){return Promise.resolve({statusCode:200,body:n,contentType:"application/json; charset=UTF-8",revision:t.get(e)})})}get(e,t={}){if(!this.connected)return Promise.reject("not connected (path: "+e+")");const n=this._revCache.get(e);if(null===n)return Promise.resolve({statusCode:404});if(t&&t.ifNoneMatch){if(!this._initialFetchDone)return this.fetchDelta().then(()=>this.get(e,t));if(n&&n===t.ifNoneMatch)return Promise.resolve({statusCode:304})}if("/"===e.slice(-1))return this._getFolder(e);const o={headers:{"Dropbox-API-Arg":_({path:a(e)})},responseType:"arraybuffer"};return t&&t.ifNoneMatch&&(o.headers["If-None-Match"]=t.ifNoneMatch),this._request("GET","https://content.dropboxapi.com/2/files/download",o).then(t=>{const o=t.status;let n,a,r,c;return 200!==o&&409!==o?Promise.resolve({statusCode:o}):(n=t.getResponseHeader("Dropbox-API-Result"),(0,s.getTextFromArrayBuffer)(t.response,"UTF-8").then(l=>{a=l,409===o&&(n=a);try{n=JSON.parse(n)}catch(e){return Promise.reject(e)}if(409===o)return i(n,["path","not_found"])?{statusCode:404}:Promise.reject(new Error('API error while downloading file ("'+e+'"): '+n.error_summary));if(r=t.getResponseHeader("Content-Type"),c=n.rev,this._revCache.set(e,c),this._shareIfNeeded(e),(0,s.shouldBeTreatedAsBinary)(l,r))a=t.response;else try{a=JSON.parse(a),r="application/json; charset=UTF-8"}catch{}return{statusCode:o,body:a,contentType:r,revision:c}}))})}put(){return r(this,arguments,void 0,function*(e,t,n,s={}){if(!this.connected)throw new Error("not connected (path: "+e+")");const o=this._revCache.get(e);if(s&&s.ifMatch&&o&&o!==s.ifMatch)return{statusCode:412,revision:o};if(s&&"*"===s.ifNoneMatch&&o&&"rev"!==o)return{statusCode:412,revision:o};if(!n.match(/charset=/)&&f(t)&&(n+="; charset=binary"),t.length>157286400)throw new Error("Cannot upload file larger than 150MB");const i={body:t,contentType:n,path:e};if(s&&(s.ifMatch||"*"===s.ifNoneMatch)){const t=yield this._getMetadata(e);if(s&&"*"===s.ifNoneMatch&&t)return{statusCode:412,revision:t.rev};if(s&&s.ifMatch&&t&&t.rev!==s.ifMatch)return{statusCode:412,revision:t.rev}}const a=yield this._uploadSimple(i);return this._shareIfNeeded(e),a})}delete(){return r(this,arguments,void 0,function*(e,t={}){if(!this.connected)throw new Error("not connected (path: "+e+")");const n=this._revCache.get(e);if(t?.ifMatch&&n&&t.ifMatch!==n)return{statusCode:412,revision:n};if(t?.ifMatch){const n=yield this._getMetadata(e);if(t?.ifMatch&&n&&n.rev!==t.ifMatch)return{statusCode:412,revision:n.rev}}return this._deleteSimple(e)})}_shareIfNeeded(e){if(e.match(/^\/public\/.*[^/]$/)&&void 0===this._itemRefs[e])return this.share(e)}share(e){const t={body:{path:a(e)}};return this._request("POST","https://api.dropboxapi.com/2/sharing/create_shared_link_with_settings",t).then(t=>{if(200!==t.status&&409!==t.status)return Promise.reject(new Error("Invalid response status:"+t.status));let n;try{n=JSON.parse(t.responseText)}catch{return Promise.reject(new Error("Invalid response body: "+t.responseText))}return 409===t.status?i(n,["shared_link_already_exists"])?this._getSharedLink(e):Promise.reject(new Error("API error: "+n.error_summary)):Promise.resolve(n.url)}).then(t=>(this._itemRefs[e]=t,o&&localStorage.setItem(l+":shares",JSON.stringify(this._itemRefs)),Promise.resolve(t)),t=>(t.message='Sharing Dropbox file or folder ("'+e+'") failed: '+t.message,Promise.reject(t)))}info(){return this._request("POST","https://api.dropboxapi.com/2/users/get_current_account",{}).then(function(e){let t;try{const n=JSON.parse(e.responseText);t=n?.email}catch{return Promise.reject(new Error("Could not query current account info: Invalid API response: "+e.responseText))}return Promise.resolve({email:t})})}_request(){return r(this,arguments,void 0,function*(e,t,n,o=1){if(this.isForbiddenRequestMethod(e,t))throw`Don't use ${e} on directories!`;if(!this.token)throw new m.default("No access token");n.headers||(n.headers={}),n.headers.Authorization="Bearer "+this.token,"object"!=typeof n.body||f(n.body)||(n.body=JSON.stringify(n.body),n.headers["Content-Type"]="application/json; charset=UTF-8"),this.rs._emit("wire-busy",{method:e,isFolder:(0,s.isFolder)(t)});try{const i=yield(0,h.requestWithTimeout)(e,t,n);return this.online||(this.online=!0,this.rs._emit("network-online")),this.rs._emit("wire-done",{method:e,isFolder:(0,s.isFolder)(t),success:!0}),401===i?.status&&this.refreshToken?o>=3?(console.error(`Abandoned after ${o} attempts: ${e} ${t}`),i):(this.rs._emit("wire-busy",{method:e,isFolder:(0,s.isFolder)(t)}),yield O.default.refreshAccessToken(this.rs,this,this.refreshToken),this.rs._emit("wire-done",{method:e,isFolder:(0,s.isFolder)(t),success:!0}),this._request(e,t,n,o+1)):[503,429].includes(i?.status)?(this.online&&(this.online=!1,this.rs._emit("network-offline")),o>=3?(console.warn(`Abandoned after ${o} attempts: ${e} ${t}`),i):(yield new Promise(e=>setTimeout(e,(0,h.retryAfterMs)(i))),this._request(e,t,n,o+1))):i}catch(n){throw this.online&&(this.online=!1,this.rs._emit("network-offline")),this.rs._emit("wire-done",{method:e,isFolder:(0,s.isFolder)(t),success:!1}),n}})}fetchDelta(...t){if(this._fetchDeltaPromise)return this._fetchDeltaPromise;const e=t=>r(this,void 0,void 0,function*(){let n,s;"string"==typeof t?(n=v,s={cursor:t}):(n=g,s={path:b,recursive:!0,include_deleted:!0});try{const a=yield this._request("POST",n,{body:s});if(401===a.status)throw new m.default;if(200!==a.status&&409!==a.status)throw new Error("Invalid response status: "+a.status);let o;try{o=JSON.parse(a.responseText)}catch{throw new Error("Invalid response body: "+a.responseText)}if(409===a.status){if(!i(o,["path","not_found"]))throw new Error("API returned an error: "+o.error_summary);o={cursor:null,entries:[],has_more:!1}}if(t||this._revCache.deactivatePropagation(),o.entries.forEach(e=>{const t=e.path_display.slice(14);"deleted"===e[".tag"]?(this._revCache.delete(t),this._revCache.delete(t+"/")):"file"===e[".tag"]&&this._revCache.set(t,e.rev)}),this._fetchDeltaCursor=o.cursor,o.has_more)return e(o.cursor);this._revCache.activatePropagation(),this._initialFetchDone=!0}catch(e){if("timeout"===e)return;throw e}});return this._fetchDeltaPromise=e(this._fetchDeltaCursor).catch(e=>("object"==typeof e&&"message"in e?e.message="Dropbox: fetchDelta: "+e.message:e=`Dropbox: fetchDelta: ${e}`,this.rs._emit("error",e),this._fetchDeltaPromise=null,Promise.reject(e))).then(()=>(this._fetchDeltaPromise=null,Promise.resolve(t))),this._fetchDeltaPromise}_getMetadata(e){const t={path:a(e)};return this._request("POST","https://api.dropboxapi.com/2/files/get_metadata",{body:t}).then(e=>{if(200!==e.status&&409!==e.status)return Promise.reject(new Error("Invalid response status:"+e.status));let t;try{t=JSON.parse(e.responseText)}catch{return Promise.reject(new Error("Invalid response body: "+e.responseText))}return 409===e.status?i(t,["path","not_found"])?Promise.resolve():Promise.reject(new Error("API error: "+t.error_summary)):Promise.resolve(t)}).then(void 0,t=>(t.message='Could not load metadata for file or folder ("'+e+'"): '+t.message,Promise.reject(t)))}_uploadSimple(e){const t={path:a(e.path),mode:{".tag":"overwrite",update:void 0},mute:!0};return e.ifMatch&&(t.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":_(t)}}).then(t=>{if(200!==t.status&&409!==t.status)return Promise.resolve({statusCode:t.status});let n;try{n=JSON.parse(t.responseText)}catch{return Promise.reject(new Error("Invalid API result: "+t.responseText))}return 409===t.status?i(n,["path","conflict"])?this._getMetadata(e.path).then(function(e){return Promise.resolve({statusCode:412,revision:e.rev})}):(this.rs._emit("error",new Error(n.error_summary)),Promise.resolve({statusCode:t.status})):(this._revCache.set(e.path,n.rev),Promise.resolve({statusCode:t.status,revision:n.rev}))})}_deleteSimple(e){const t={path:a(e)};return this._request("POST","https://api.dropboxapi.com/2/files/delete",{body:t}).then(e=>{if(200!==e.status&&409!==e.status)return Promise.resolve({statusCode:e.status});let t;try{t=JSON.parse(e.responseText)}catch{return Promise.reject(new Error("Invalid response body: "+e.responseText))}if(409===e.status){if(i(t,["path_lookup","not_found"]))return Promise.resolve({statusCode:404});this.rs._emit("error",new Error(t.error_summary))}return Promise.resolve({statusCode:e.status})}).then(t=>(200!==t.statusCode&&404!==t.statusCode||(this._revCache.delete(e),delete this._itemRefs[e]),Promise.resolve(t)),t=>(t.message='Could not delete Dropbox file or folder ("'+e+'"): '+t.message,Promise.reject(t)))}_getSharedLink(e){return r(this,void 0,void 0,function*(){const t={body:{path:a(e),direct_only:!0}};return this._request("POST","https://api.dropbox.com/2/sharing/list_shared_links",t).then(e=>{if(200!==e.status&&409!==e.status)return Promise.reject(new Error("Invalid response status: "+e.status));let t;try{t=JSON.parse(e.responseText)}catch{return Promise.reject(new Error("Invalid response body: "+e.responseText))}return 409===e.status?Promise.reject(new Error("API error: "+t?.error_summary||0)):t.links.length?Promise.resolve(t.links[0].url):Promise.reject(new Error("No links returned"))},t=>(t.message='Could not get link to a shared file or folder ("'+e+'"): '+t.message,Promise.reject(t)))})}static _rs_init(e){o=(0,s.localStorageAvailable)(),e.apiKeys.dropbox&&(e.dropbox=new d(e)),"dropbox"===e.backend&&p(e)}static _rs_supported(){return!0}static _rs_cleanup(e){!function(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&&(u.default.prototype.getItemURL=e._origBaseClientGetItemURL,delete e._origBaseClientGetItemURL)}(e),j(e)}(e),o&&localStorage.removeItem(l),e.setBackend(void 0)}}function y(e,...t){e._dropboxOrigSync||(e._dropboxOrigSync=e.sync.sync.bind(e.sync),e.sync.sync=function(){return this.dropbox.fetchDelta(e,...t).then(e._dropboxOrigSync,function(t){e._emit("error",new E.default(t)),e._emit("sync-done")})}.bind(e))}function j(e){e._dropboxOrigSyncCycle&&(e.syncCycle=e._dropboxOrigSyncCycle,delete e._dropboxOrigSyncCycle)}function p(e){!function(e){e._origRemote||(e._origRemote=e.remote,e.remote=e.dropbox)}(e),e.sync?y(e):function(e,...t){e._dropboxOrigSyncCycle||(e._dropboxOrigSyncCycle=e.syncCycle,e.syncCycle=()=>{if(!e.sync)throw new Error("expected sync to be initialized by now");y(e),e._dropboxOrigSyncCycle(e,...t),j(e)})}(e),function(e){e._origBaseClientGetItemURL||(e._origBaseClientGetItemURL=u.default.prototype.getItemURL,u.default.prototype.getItemURL=function(){throw new Error("getItemURL is not implemented for Dropbox yet")})}(e)}(0,s.applyMixins)(d,[x.default]),e.exports=d},451:function(e,t,n){"use strict";const o=(this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}})(n(93)),i=n(746);class s{constructor(){this.addEvents(["background","foreground"]),this.mode="undefined"!=typeof window?"browser":"node","browser"===this.mode&&(this.setBrowserPrefixedNames(),document.addEventListener(this.visibilityChangeEvent,this.setVisibility.bind(this),!1),this.setVisibility())}setBrowserPrefixedNames(){"browser"===this.mode&&(void 0!==document.hidden?(this.hiddenProperty="hidden",this.visibilityChangeEvent="visibilitychange"):void 0!==document.mozHidden?(this.hiddenProperty="mozHidden",this.visibilityChangeEvent="mozvisibilitychange"):void 0!==document.msHidden?(this.hiddenProperty="msHidden",this.visibilityChangeEvent="msvisibilitychange"):void 0!==document.webkitHidden&&(this.hiddenProperty="webkitHidden",this.visibilityChangeEvent="webkitvisibilitychange"))}setVisibility(){document[this.hiddenProperty]?this.goBackground():this.goForeground()}isBrowser(){return"browser"===this.mode}isNode(){return"node"===this.mode}goBackground(){this._emit("background")}goForeground(){this._emit("foreground")}static _rs_init(){}static _rs_cleanup(){}}(0,i.applyMixins)(s,[o.default]),e.exports=s},93:function(e,t,n){"use strict";var o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.EventHandling=void 0;const i=o(n(334));class s{addEvents(e){e.forEach(e=>this._addEvent(e))}addEventListener(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");(0,i.default)("[EventHandling] Adding event listener",e),this._validateEvent(e),this._handlers[e].push(t)}on(e,t){return this.addEventListener(e,t)}removeEventListener(e,t){this._validateEvent(e);const n=this._handlers[e].length;for(let s=0;s{e.apply(this,t)})}_validateEvent(e){if(!(e in this._handlers))throw new Error("Unknown event: "+e)}_delegateEvent(e,t){t.on(e,t=>{this._emit(e,t)})}_addEvent(e){void 0===this._handlers&&(this._handlers={}),this._handlers[e]=[]}}t.EventHandling=s,t.default=s},545:function(e,t,n){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const i=s(n(28)),u=s(n(451)),o=s(n(334)),a=n(746),f=s(n(370)),l=s(n(548)),d=s(n(275)),r=s(n(373)),h=s(n(424)),m=s(n(801)),c=s(n(706)),p=s(n(600)),g=s(n(313)),v=s(n(285)),b=s(n(567)),j=s(n(794)),y=s(n(365)),_={features:[],featuresDone:0,readyFired:!1,loadFeatures(){this.features=[],this.featuresDone=0,this.readyFired=!1,this.featureModules={WireClient:p.default,Dropbox:c.default,GoogleDrive:m.default,Access:l.default,Discover:r.default,Authorize:d.default,BaseClient:h.default,Env:u.default},i.default.cache&&(0,a.extend)(this.featureModules,{Caching:v.default,IndexedDB:b.default,LocalStorage:j.default,InMemoryStorage:y.default,Sync:g.default}),i.default.disableFeatures.forEach(e=>{this.featureModules[e]&&delete this.featureModules[e]}),this._allLoaded=!1;for(const e in this.featureModules)this.loadFeature(e)},hasFeature(e){for(let t=this.features.length-1;t>=0;t--)if(this.features[t].name===e)return this.features[t].supported;return!1},loadFeature(e){const n=this.featureModules[e],t=!n._rs_supported||n._rs_supported();(0,o.default)(`[RemoteStorage] [FEATURE ${e}] initializing ...`),"object"==typeof t?t.then(()=>{this.featureSupported(e,!0),this.initFeature(e)},()=>{this.featureSupported(e,!1)}):"boolean"==typeof t?(this.featureSupported(e,t),t&&this.initFeature(e)):this.featureSupported(e,!1)},initFeature(e){const n=this.featureModules[e];let t;try{t=n._rs_init(this)}catch(t){return void this.featureFailed(e,t)}"object"==typeof t&&"function"==typeof t.then?t.then(()=>{this.featureInitialized(e)},t=>{this.featureFailed(e,t)}):this.featureInitialized(e)},featureFailed(e,t){(0,o.default)(`[RemoteStorage] [FEATURE ${e}] initialization failed (${t})`),this.featureDone()},featureSupported(e,t){(0,o.default)(`[RemoteStorage] [FEATURE ${e}]${t?"":"not "} supported`),t||this.featureDone()},featureInitialized(e){(0,o.default)(`[RemoteStorage] [FEATURE ${e}] initialized`),this.features.push({name:e,init:this.featureModules[e]._rs_init,supported:!0,cleanup:this.featureModules[e]._rs_cleanup}),this.featureDone()},featureDone(){this.featuresDone++,this.featuresDone===Object.keys(this.featureModules).length&&setTimeout(this.featuresLoaded.bind(this),0)},_setCachingModule(){["IndexedDB","LocalStorage","InMemoryStorage"].some(e=>{if(this.features.some(t=>t.name===e))return this.features.local=this.featureModules[e],!0})},_fireReady(){try{this.readyFired||(this._emit("ready"),this.readyFired=!0)}catch(e){console.error("'ready' failed: ",e,e.stack),this._emit("error",e)}},featuresLoaded(){(0,o.default)("[RemoteStorage] All features loaded"),this._setCachingModule(),this.local=i.default.cache&&this.features.local&&new this.features.local,this.local&&this.remote?(this._setGPD(f.default,this),this._bindChange(this.local)):this.remote&&this._setGPD(this.remote,this.remote),this.remote&&(this.remote.on("connected",()=>{this._fireReady(),this._emit("connected")}),this.remote.on("not-connected",()=>{this._fireReady(),this._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){(0,a.logError)(e),this._emit("error",e)}this._processPending()},_collectCleanupFunctions(){this._cleanups=[];for(let e=0;e=n-this.maxAge?t.v:void 0}set(e,t){this._items[e]={v:t,t:(new Date).getTime()}}}class l extends p.RemoteBase{constructor(e,t){if(super(e),this.online=!0,this.storageApi="draft-dejong-remotestorage-19",this.addEvents(["connected","not-connected"]),this.clientId=t,this._fileIdCache=new v(300),a=(0,s.localStorageAvailable)(),a){const e=(0,s.getJSONFromLocalStorage)(r);e&&this.configure(e)}}configure(e){void 0!==e.userAddress&&(this.userAddress=e.userAddress),void 0!==e.token&&(this.token=e.token);const t=function(){a&&localStorage.setItem(r,JSON.stringify({userAddress:this.userAddress,token:this.token}))},n=function(){this.connected=!1,delete this.token,a&&localStorage.removeItem(r)};this.token?(this.connected=!0,this.userAddress?(this._emit("connected"),t.apply(this)):this.info().then(e=>{this.userAddress=e.user.emailAddress,this._emit("connected"),t.apply(this)}).catch(()=>{n.apply(this),this.rs._emit("error",new Error("Could not fetch user info."))})):n.apply(this)}connect(){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})}get(e,t={}){return(0,s.isFolder)(e)?this._getFolder(i(e)):this._getFile(i(e),t)}put(e,t,n,s={}){const o=i(e);function a(e){if(e.status>=200&&e.status<300){const t=JSON.parse(e.responseText),n=this.stripQuotes(t.etag);return Promise.resolve({statusCode:200,contentType:t.mimeType,revision:n})}return 412===e.status?Promise.resolve({statusCode:412,revision:"conflict"}):Promise.reject("PUT failed with status "+e.status+" ("+e.responseText+")")}return this._getFileId(o).then(e=>e?s&&"*"===s.ifNoneMatch?a({status:412}):this._updateFile(e,o,t,n,s).then(a):this._createFile(o,t,n).then(a))}delete(e,t={}){const n=i(e);return this._getFileId(n).then(e=>e?this._getMeta(e).then(n=>{let s;return"object"==typeof n&&"string"==typeof n.etag&&(s=this.stripQuotes(n.etag)),t&&t.ifMatch&&t.ifMatch!==s?{statusCode:412,revision:s}:this._request("DELETE",o+"/drive/v2/files/"+e,{}).then(e=>200===e.status||204===e.status?{statusCode:200}:Promise.reject("Delete failed: "+e.status+" ("+e.responseText+")"))}):Promise.resolve({statusCode:200}))}info(){const e=o+"/drive/v2/about?fields=user";return this._request("GET",e,{}).then(function(e){try{const t=JSON.parse(e.responseText);return Promise.resolve(t)}catch(e){return Promise.reject(e)}})}_updateFile(e,t,n,s,i){const r={mimeType:s},a={"Content-Type":"application/json; charset=UTF-8"};return i&&i.ifMatch&&(a["If-Match"]=this.addQuotes(i.ifMatch)),this._request("PUT",o+"/upload/drive/v2/files/"+e+"?uploadType=resumable",{body:JSON.stringify(r),headers:a}).then(e=>412===e.status?e:this._request("PUT",e.getResponseHeader("Location"),{body:s.match(/^application\/json/)?JSON.stringify(n):n}))}_createFile(e,t,n){return this._getParentId(e).then(s=>{const i={title:h(d(e)),mimeType:n,parents:[{kind:"drive#fileLink",id:s}]};return this._request("POST",o+"/upload/drive/v2/files?uploadType=resumable",{body:JSON.stringify(i),headers:{"Content-Type":"application/json; charset=UTF-8"}}).then(e=>this._request("POST",e.getResponseHeader("Location"),{body:n.match(/^application\/json/)?JSON.stringify(t):t}))})}_getFile(e,t){return this._getFileId(e).then(e=>this._getMeta(e).then(e=>{let n;if("object"==typeof e&&"string"==typeof e.etag&&(n=this.stripQuotes(e.etag)),t&&t.ifNoneMatch&&n===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:n});e.mimeType+=";export=text/html",e.downloadUrl=e.exportLinks["text/html"]}return this._request("GET",e.downloadUrl,{responseType:"arraybuffer"}).then(t=>(0,s.getTextFromArrayBuffer)(t.response,"UTF-8").then(function(o){let i=o;if(e.mimeType.match(/^application\/json/))try{i=JSON.parse(i)}catch{}else(0,s.shouldBeTreatedAsBinary)(o,e.mimeType)&&(i=t.response);return{statusCode:200,body:i,contentType:e.mimeType,revision:n}}))}))}_getFolder(e){return this._getFileId(e).then(t=>{let a,i,n;if(!t)return Promise.resolve({statusCode:404});const r="'"+t+"' in parents";return this._request("GET",o+"/drive/v2/files?q="+encodeURIComponent(r)+"&fields="+encodeURIComponent("items(downloadUrl,etag,fileSize,id,mimeType,title,labels)")+"&maxResults=1000&trashed=false",{}).then(t=>{var o;if(200!==t.status)return Promise.reject("request failed or something: "+t.status);try{a=JSON.parse(t.responseText)}catch{return Promise.reject("non-JSON response from GoogleDrive")}n={};for(const t of a.items)(null===(o=t.labels)||void 0===o?void 0:o.trashed)||(i=this.stripQuotes(t.etag),t.mimeType===u?(this._fileIdCache.set(e+(0,s.cleanPath)(t.title)+"/",t.id),n[t.title+"/"]={ETag:i}):(this._fileIdCache.set(e+(0,s.cleanPath)(t.title),t.id),n[t.title]={ETag:i,"Content-Type":t.mimeType,"Content-Length":t.fileSize}));return Promise.resolve({statusCode:200,body:n,contentType:"application/json; charset=UTF-8",revision:void 0})})})}_getParentId(e){const t=m(e);return this._getFileId(t).then(e=>e?Promise.resolve(e):this._createFolder(t))}_createFolder(e){return this._getParentId(e).then(t=>this._request("POST",o+"/drive/v2/files",{body:JSON.stringify({title:h(d(e)),mimeType:u,parents:[{id:t}]}),headers:{"Content-Type":"application/json; charset=UTF-8"}}).then(e=>{const t=JSON.parse(e.responseText);return Promise.resolve(t.id)}))}_getFileId(e){let t;return"/"===e?Promise.resolve("root"):(t=this._fileIdCache.get(e))?Promise.resolve(t):this._getFolder(m(e)).then(()=>(t=this._fileIdCache.get(e),t?Promise.resolve(t):"/"===e.substr(-1)?this._createFolder(e).then(()=>this._getFileId(e)):Promise.resolve()))}_getMeta(e){return this._request("GET",o+"/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(e,t,n){return this.isForbiddenRequestMethod(e,t)?Promise.reject(`Don't use ${e} on directories!`):(n.headers||(n.headers={}),n.headers.Authorization="Bearer "+this.token,this.rs._emit("wire-busy",{method:e,isFolder:(0,s.isFolder)(t)}),(0,g.requestWithTimeout)(e,t,n).then(n=>n&&401===n.status?void this.connect():(this.online||(this.online=!0,this.rs._emit("network-online")),this.rs._emit("wire-done",{method:e,isFolder:(0,s.isFolder)(t),success:!0}),Promise.resolve(n)),n=>(this.online&&(this.online=!1,this.rs._emit("network-offline")),this.rs._emit("wire-done",{method:e,isFolder:(0,s.isFolder)(t),success:!1}),Promise.reject(n))))}static _rs_init(e){const t=e.apiKeys.googledrive;var n;t&&(e.googledrive=new l(e,t.clientId),"googledrive"===e.backend&&(e._origRemote=e.remote,e.remote=e.googledrive,(n=e)._origBaseClientGetItemURL||(n._origBaseClientGetItemURL=c.default.prototype.getItemURL,c.default.prototype.getItemURL=function(){throw new Error("getItemURL is not implemented for Google Drive yet")})))}static _rs_supported(){return!0}static _rs_cleanup(e){var t;e.setBackend(void 0),e._origRemote&&(e.remote=e._origRemote,delete e._origRemote),(t=e)._origBaseClientGetItemURL&&(c.default.prototype.getItemURL=t._origBaseClientGetItemURL,delete t._origBaseClientGetItemURL)}}(0,s.applyMixins)(l,[b.default]),e.exports=l},567:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,s){return new(n||(n=Promise))(function(o,i){function r(e){try{a(s.next(e))}catch(e){i(e)}}function c(e){try{a(s.throw(e))}catch(e){i(e)}}function a(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(r,c)}a((s=s.apply(e,t||[])).next())})},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const d=r(n(93)),u=r(n(496)),s=r(n(334)),a=n(746),c="remotestorage";let l;class o extends u.default{constructor(e){super(),this.addEvents(["change","local-events-done"]),this.db=e||l,this.db?(this.getsRunning=0,this.putsRunning=0,this.changesQueued={},this.changesRunning={},this.commitSlownessWarning=null):(0,s.default)("[IndexedDB] Failed to open DB")}getNodes(e){return i(this,void 0,void 0,function*(){const n=[],t={};for(let s=0,o=e.length;s0?this.getNodesFromDb(n).then(function(e){for(const n in t)e[n]=t[n];return e}):Promise.resolve(t)})}setNodes(e){return i(this,void 0,void 0,function*(){for(const t in e)this.changesQueued[t]=e[t]||!1;return this.maybeFlush(),Promise.resolve()})}maybeFlush(){0===this.putsRunning?this.flushChangesQueued():this.commitSlownessWarning||(this.commitSlownessWarning=n.g.setInterval(function(){console.warn("WARNING: waited more than 10 seconds for previous commit to finish")},1e4))}flushChangesQueued(){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(e){return new Promise((t,n)=>{const s=this.db.transaction(["nodes"],"readonly"),i=s.objectStore("nodes"),o={};this.getsRunning++,e.map(e=>{i.get(e).onsuccess=t=>{o[e]=t.target.result}}),s.oncomplete=()=>{t(o),this.getsRunning--},s.onerror=s.onabort=()=>{n("get transaction error/abort"),this.getsRunning--}})}setNodesInDb(e){return i(this,void 0,void 0,function*(){return new Promise((t,n)=>{const o=this.db.transaction(["nodes"],"readwrite"),i=o.objectStore("nodes"),a=(new Date).getTime();this.putsRunning++,(0,s.default)("[IndexedDB] Starting put",e,this.putsRunning);for(const n in e){const t=e[n];if("object"==typeof t)try{i.put(t)}catch(e){throw(0,s.default)("[IndexedDB] Error while putting",t,e),e}else try{i.delete(n)}catch(e){throw(0,s.default)("[IndexedDB] Error while removing",i,t,e),e}}o.oncomplete=()=>{this.putsRunning--,(0,s.default)("[IndexedDB] Finished put",e,this.putsRunning,(new Date).getTime()-a+"ms"),t()},o.onerror=()=>{this.putsRunning--,n("transaction error")},o.onabort=()=>{n("transaction abort"),this.putsRunning--}})})}reset(e){const t=this.db.name;this.db.close(),o.clean(this.db.name,()=>{o.open(t,(t,n)=>{t?(0,s.default)("[IndexedDB] Error while resetting local storage",t):this.db=n,"function"==typeof e&&e(self)})})}forAllNodes(e){return i(this,void 0,void 0,function*(){return new Promise(t=>{this.db.transaction(["nodes"],"readonly").objectStore("nodes").openCursor().onsuccess=n=>{const s=n.target.result;s?(e(this.migrate(s.value)),s.continue()):t()}})})}closeDB(){0===this.putsRunning?this.db.close():setTimeout(this.closeDB.bind(this),100)}static open(e,t){const n=setTimeout(function(){t("timeout trying to open db")},1e4);try{const i=indexedDB.open(e,2);i.onerror=function(){(0,s.default)("[IndexedDB] Opening DB failed",i),clearTimeout(n),t(i.error)},i.onupgradeneeded=function(e){const t=i.result;(0,s.default)("[IndexedDB] Upgrade: from ",e.oldVersion," to ",e.newVersion),1!==e.oldVersion&&((0,s.default)("[IndexedDB] Creating object store: nodes"),t.createObjectStore("nodes",{keyPath:"path"})),(0,s.default)("[IndexedDB] Creating object store: changes"),t.createObjectStore("changes",{keyPath:"path"})},i.onsuccess=function(){clearTimeout(n);const a=i.result;if(!a.objectStoreNames.contains("nodes")||!a.objectStoreNames.contains("changes"))return(0,s.default)("[IndexedDB] Missing object store. Resetting the database."),void o.clean(e,function(){o.open(e,t)});t(null,i.result)}}catch(i){(0,s.default)("[IndexedDB] Failed to open database: "+i),(0,s.default)("[IndexedDB] Resetting database and trying again."),clearTimeout(n),o.clean(e,function(){o.open(e,t)})}}static clean(e,t){const n=indexedDB.deleteDatabase(e);n.onsuccess=function(){(0,s.default)("[IndexedDB] Done removing DB"),t()},n.onerror=n.onabort=function(t){console.error('Failed to remove database "'+e+'"',t)}}static _rs_init(e){return new Promise((t,n)=>{o.open(c,function(s,o){s?n(s):(l=o,o.onerror=()=>{e._emit("error",s)},t())})})}static _rs_supported(){return new Promise((e,t)=>{const s=(0,a.getGlobalContext)();let n=!1;if("undefined"!=typeof navigator&&navigator.userAgent.match(/Android (2|3|4\.[0-3])/)&&(navigator.userAgent.match(/Chrome|Firefox/)||(n=!0)),"indexedDB"in s&&!n)try{const n=indexedDB.open("rs-check");n.onerror=function(){t()},n.onsuccess=function(){n.result.close(),indexedDB.deleteDatabase("rs-check"),e()}}catch{t()}else t()})}static _rs_cleanup(e){return new Promise(t=>{e.local&&e.local.closeDB(),o.clean(c,t)})}diffHandler(){}}(0,a.applyMixins)(o,[d.default]),e.exports=o},365:function(e,t,n){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const a=s(n(93)),r=s(n(496)),o=n(746);class i extends r.default{constructor(){super(),this._storage={},this.addEvents(["change","local-events-done"])}getNodes(e){const t={};for(let n=0,s=e.length;n{(0,l.default)("[LocalStorage] Removing",e),delete localStorage[e]})}}(0,i.applyMixins)(a,[c.default]),e.exports=a},334:function(e,t,n){"use strict";const s=(this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}})(n(28));e.exports=function(...e){s.default.logging&&console.log(...e)}},684:function(e,t,n){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.RemoteBase=void 0;const o=s(n(93)),i=n(746);class a extends o.default{constructor(e){super(),this.rs=e,this.connected=!1}stopWaitingForToken(){this.connected||this._emit("not-connected")}addQuotes(e){return"string"!=typeof e?e:"*"===e?"*":'"'+e+'"'}stripQuotes(e){return"string"!=typeof e?e:e.replace(/^["']|["']$/g,"")}isForbiddenRequestMethod(e,t){return("PUT"===e||"DELETE"===e)&&(0,i.isFolder)(t)}}t.RemoteBase=a},423:function(e,t,n){"use strict";var r,y=this&&this.__createBinding||(Object.create?function(e,t,n,s){void 0===s&&(s=n);var o=Object.getOwnPropertyDescriptor(t,n);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,s,o)}:function(e,t,n,s){void 0===s&&(s=n),e[s]=t[n]}),k=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),E=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var n,t={};if(e!=null)for(n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&y(t,e,n);return k(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.RemoteStorage=void 0;const s=a(n(28)),m=a(n(334)),c=n(746),C=a(n(548)),l=a(n(275)),u=a(n(424)),O=a(n(285)),w=n(93),v=a(n(801)),j=a(n(706)),f=a(n(373)),b=a(n(982)),g=a(n(503)),i=a(n(545)),_=E(n(746)),h=(0,c.getGlobalContext)();let d;function x(e){return 403!==e.statusCode&&401!==e.statusCode||this._emit("error",new g.default),Promise.resolve(e)}function p(e){return"number"==typeof e&&e>=2e3&&e<=36e5}!function(e){e.GOOGLE="googledrive",e.DROPBOX="dropbox"}(r||(r={}));class o{constructor(e){if(this._pending=[],this._cleanups=[],this._pathHandlers={change:{}},this.apiKeys={},this._init=i.default.loadFeatures,this.features=i.default.features,this.loadFeature=i.default.loadFeature,this.featureSupported=i.default.featureSupported,this.featureDone=i.default.featureDone,this.featuresDone=i.default.featuresDone,this.featuresLoaded=i.default.featuresLoaded,this.featureInitialized=i.default.featureInitialized,this.featureFailed=i.default.featureFailed,this.hasFeature=i.default.hasFeature,this._setCachingModule=i.default._setCachingModule,this._collectCleanupFunctions=i.default._collectCleanupFunctions,this._fireReady=i.default._fireReady,this.initFeature=i.default.initFeature,"object"==typeof e&&(0,c.extend)(s.default,e),this.addEvents(["ready","authing","connecting","connected","disconnected","not-connected","conflict","error","features-loaded","sync-interval-change","sync-req-done","sync-done","wire-busy","wire-done","network-offline","network-online"]),this._setGPD({get:this._pendingGPD("get"),put:this._pendingGPD("put"),delete:this._pendingGPD("delete")}),d=(0,c.localStorageAvailable)(),d){this.apiKeys=(0,c.getJSONFromLocalStorage)("remotestorage:api-keys")||{};const e=localStorage.getItem("remotestorage:backend");"dropbox"===e||"googledrive"===e?this.setBackend(e):this.setBackend("remotestorage")}const t=this.on;this.on=function(e,n){if(this._allLoaded)switch(e){case"features-loaded":setTimeout(n,0);break;case"ready":this.remote&&setTimeout(n,0);break;case"connected":this.remote&&this.remote.connected&&setTimeout(n,0);break;case"not-connected":this.remote&&!this.remote.connected&&setTimeout(n,0)}return t.call(this,e,n)},this._init(),this.fireInitial=function(){this.local&&setTimeout(this.local.fireInitial.bind(this.local),0)}.bind(this),this.on("ready",this.fireInitial.bind(this)),this.loadModules()}get connected(){return this.remote.connected}loadModules(){s.default.modules.forEach(this.addModule.bind(this))}authorize(e){if(this.access.setStorageType(this.remote.storageApi),void 0===e.scope&&(e.scope=this.access.scopeParameter),h.cordova)e.redirectUri=s.default.cordovaRedirectUri;else{const t=l.default.getLocation();let n=t.origin;"/"!==t.pathname&&(n+=t.pathname),e.redirectUri=n}void 0===e.clientId&&(e.clientId=e.redirectUri.match(/^(https?:\/\/[^/]+)/)[0]),l.default.authorize(this,e)}impliedauth(e,t){e=e||this.remote.storageApi,t=t||String(document.location),(0,m.default)("ImpliedAuth proceeding due to absent authURL; storageApi = "+e+" redirectUri = "+t),this.remote.configure({token:l.default.IMPLIED_FAKE_TOKEN}),document.location.href=t}connect(e,t){if(this.setBackend("remotestorage"),e.indexOf("@")<0&&!e.match(/^(https?:\/\/)?[^\s/$.?#]+\.[^\s]*$/))this._emit("error",new o.DiscoveryError("Not a valid user address or URL."));else{if(e.indexOf("@")<0&&!e.match(/^https?:\/\//)&&(e=`https://${e}`),h.cordova){if("string"!=typeof s.default.cordovaRedirectUri)return void this._emit("error",new o.DiscoveryError("Please supply a custom HTTPS redirect URI for your Cordova app"));if(!h.cordova.InAppBrowser)return void this._emit("error",new o.DiscoveryError("Please include the InAppBrowser Cordova plugin to enable OAuth"))}this.remote.configure({userAddress:e}),this._emit("connecting"),(0,f.default)(e).then(n=>{if(this._emit("authing"),n.userAddress=e,this.remote.configure(n),!this.remote.connected)if(n.authURL)if(void 0===t)this.authorize({authURL:n.authURL});else{if("string"!=typeof t)throw new Error("Supplied bearer token must be a string");(0,m.default)("Skipping authorization sequence and connecting with known token"),this.remote.configure({token:t})}else this.impliedauth()},()=>{this._emit("error",new o.DiscoveryError("No storage information found for this user address."))})}}reconnect(){this.remote.configure({token:null}),"remotestorage"===this.backend?this.connect(this.remote.userAddress):this.remote.connect()}disconnect(){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")});const t=this._cleanups.length;let n=0;const e=()=>{n++,n>=t&&(this._init(),this._emit("disconnected"))};t>0?this._cleanups.forEach(t=>{const n=t(this);"object"==typeof n&&"function"==typeof n.then?n.then(e):e()}):e()}setBackend(e){this.backend=e,d&&(void 0!==e?localStorage.setItem("remotestorage:backend",e):localStorage.removeItem("remotestorage:backend"))}onChange(e,t){this._pathHandlers.change[e]||(this._pathHandlers.change[e]=[]),this._pathHandlers.change[e].push(t)}enableLog(){s.default.logging=!0}disableLog(){s.default.logging=!1}log(...e){m.default.apply(o,e)}setApiKeys(e){const t=[r.GOOGLE,r.DROPBOX];if("object"!=typeof e||!Object.keys(e).every(e=>t.includes(e)))return console.error("setApiKeys() was called with invalid arguments"),!1;Object.keys(e).forEach(t=>{const n=e[t];if(n){switch(t){case r.DROPBOX:this.apiKeys[r.DROPBOX]={appKey:n},void 0!==this.dropbox&&this.dropbox.clientId===n||j.default._rs_init(this);break;case r.GOOGLE:this.apiKeys[r.GOOGLE]={clientId:n},void 0!==this.googledrive&&this.googledrive.clientId===n||v.default._rs_init(this)}return!0}delete this.apiKeys[t]}),d&&localStorage.setItem("remotestorage:api-keys",JSON.stringify(this.apiKeys))}setCordovaRedirectUri(e){if("string"!=typeof e||!e.match(/http(s)?:\/\//))throw new Error("Cordova redirect URI must be a URI string");s.default.cordovaRedirectUri=e}_setGPD(e,t){function n(e){return function(...n){return e.apply(t,n).then(x.bind(this))}}this.get=n(e.get),this.put=n(e.put),this.delete=n(e.delete)}_pendingGPD(e){return(...t)=>{const n=Array.prototype.slice.call(t);return new Promise((t,s)=>{this._pending.push({method:e,args:n,promise:{resolve:t,reject:s}})})}}_processPending(){this._pending.forEach(e=>{try{this[e.method](...e.args).then(e.promise.resolve,e.promise.reject)}catch(t){e.promise.reject(t)}}),this._pending=[]}_bindChange(e){e.on("change",this._dispatchEvent.bind(this,"change"))}_dispatchEvent(e,t){Object.keys(this._pathHandlers[e]).forEach(n=>{const s=n.length;t.path.substr(0,s)===n&&this._pathHandlers[e][n].forEach(e=>{const s={};for(const e in t)s[e]=t[e];s.relativePath=t.path.replace(new RegExp("^"+n),"");try{e(s)}catch(e){console.error("'change' handler failed: ",e,e.stack),this._emit("error",e)}})})}scope(e){if("string"!=typeof e)throw"Argument 'path' of baseClient.scope must be a string";return this.access.checkPathPermission(e,"r")||console.warn("WARNING: Please use remoteStorage.access.claim() to ask for access permissions first: https://remotestoragejs.readthedocs.io/en/latest/js-api/access.html#claim"),new u.default(this,e)}getSyncInterval(){return s.default.syncInterval}setSyncInterval(e){if(!p(e))throw e+" is not a valid sync interval";const t=s.default.syncInterval;s.default.syncInterval=e,this._emit("sync-interval-change",{oldValue:t,newValue:e})}getBackgroundSyncInterval(){return s.default.backgroundSyncInterval}setBackgroundSyncInterval(e){if(!p(e))throw e+" is not a valid sync interval";const t=s.default.backgroundSyncInterval;s.default.backgroundSyncInterval=e,this._emit("sync-interval-change",{oldValue:t,newValue:e})}getCurrentSyncInterval(){return s.default.isBackground?s.default.backgroundSyncInterval:s.default.syncInterval}getRequestTimeout(){return s.default.requestTimeout}setRequestTimeout(e){if("number"!=typeof e)throw e+" is not a valid request timeout";s.default.requestTimeout=e}syncCycle(){this.sync&&!this.sync.stopped&&(this.on("sync-done",()=>{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()))}),this.sync.sync())}startSync(){return s.default.cache?(this.sync.stopped=!1,this.syncStopped=!1,this.sync.sync()):(console.warn("Nothing to sync, because caching is disabled."),Promise.resolve())}stopSync(){clearTimeout(this._syncTimer),this._syncTimer=void 0,this.sync?this.sync.stopped=!0:this.syncStopped=!0}addModule(e){const t=e.name,n=e.builder;if(Object.defineProperty(this,t,{configurable:!0,get:function(){const e=this._loadModule(t,n);return Object.defineProperty(this,t,{value:e}),e}}),-1!==t.indexOf("-")){const e=t.replace(/-[a-z]/g,function(e){return e[1].toUpperCase()});Object.defineProperty(this,e,{get:function(){return this[t]}})}}_loadModule(e,t){if(t)return t(new u.default(this,"/"+e+"/"),new u.default(this,"/public/"+e+"/")).exports;throw"Unknown module: "+e}}t.RemoteStorage=o,o.Authorize=l.default,o.SyncError=b.default,o.Unauthorized=g.default,o.DiscoveryError=f.default.DiscoveryError,o.util=_,Object.defineProperty(o.prototype,"access",{get:function(){const e=new C.default;return Object.defineProperty(this,"access",{value:e}),e},configurable:!0}),Object.defineProperty(o.prototype,"caching",{configurable:!0,get:function(){const e=new O.default;return Object.defineProperty(this,"caching",{value:e}),e}}),(0,c.applyMixins)(o,[w.EventHandling]),t.default=o},368:function(e,t,n){"use strict";var s=this&&this.__awaiter||function(e,t,n,s){return new(n||(n=Promise))(function(o,i){function r(e){try{a(s.next(e))}catch(e){i(e)}}function c(e){try{a(s.throw(e))}catch(e){i(e)}}function a(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(r,c)}a((s=s.apply(e,t||[])).next())})},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isArrayBufferView=void 0,t.retryAfterMs=function(e){const t=1e3*parseInt(e.getResponseHeader("Retry-After"));return t>=1e3?t:Math.max(1500,Math.min(6e4,Math.round(o.default.syncInterval/(2.9+.2*Math.random()))))},t.requestWithTimeout=function(e,n,i){return s(this,void 0,void 0,function*(){return"function"==typeof fetch?function(e,t,n){return s(this,void 0,void 0,function*(){const s="function"==typeof AbortController?new AbortController:null;let r;const l=new Promise((e,t)=>{r=setTimeout(()=>{s&&s.abort(),t("timeout")},o.default.requestTimeout)});let i;const c={},d=fetch(t,{method:e,headers:n.headers,body:n.body,signal:s?s.signal:void 0}).then(e=>{switch((0,a.default)("[requests fetch]",e),e.headers.forEach((e,t)=>{c[t.toUpperCase()]=e}),i={readyState:4,status:e.status,statusText:e.statusText,response:void 0,getResponseHeader:e=>c[e.toUpperCase()]||null,responseType:n.responseType,responseURL:t},n.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(e=>(i.response=e,n.responseType&&"text"!==n.responseType||(i.responseText=e),i)).finally(()=>{clearTimeout(r)});return Promise.race([d,l])})}(e,n,i):"function"==typeof XMLHttpRequest?function(e,n,i){return s(this,void 0,void 0,function*(){return new Promise((s,r)=>{(0,a.default)("[requests XHR]",e,n);let d=!1;const u=setTimeout(()=>{d=!0,r("timeout")},o.default.requestTimeout),c=new XMLHttpRequest;if(c.open(e,n,!0),i.responseType&&(c.responseType=i.responseType),i.headers)for(const e in i.headers)c.setRequestHeader(e,i.headers[e]);c.onload=()=>{d||(clearTimeout(u),s(c))},c.onerror=e=>{d||(clearTimeout(u),r(e))};let l=i.body;"object"==typeof l&&!(0,t.isArrayBufferView)(l)&&l instanceof ArrayBuffer&&(l=new Uint8Array(l)),c.send(l)})})}(e,n,i):Promise.reject("[Requests] You need to add a polyfill for fetch or XMLHttpRequest")})};const a=i(n(334)),o=i(n(28));if("function"==typeof(n.g||window).ArrayBufferView)t.isArrayBufferView=function(e){return e&&e instanceof(n.g||window).ArrayBufferView};else{const e=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array];t.isArrayBufferView=function(t){for(let n=0;n<8;n++)if(t instanceof e[n])return!0;return!1}}},941:function(e){"use strict";e.exports=class{constructor(e){this._itemsRev={},this._storage={},this._canPropagate=!1,this.defaultValue=e,this.activatePropagation()}get(e){e=e.toLowerCase();let t=this._storage[e];return void 0===t&&(t=this.defaultValue,this._storage[e]=t),t}set(e,t){return e=e.toLowerCase(),this._storage[e]===t||(this._storage[e]=t,t||delete this._itemsRev[e],this._updateParentFolderItemRev(e,t),this._canPropagate&&this._propagate(e)),t}delete(e){return this.set(e,null)}deactivatePropagation(){return this._canPropagate=!1,!0}activatePropagation(){return this._canPropagate||(this._generateFolderRev("/"),this._canPropagate=!0),!0}_hashCode(e){let t=0;if(0===e.length)return t;for(let n=0;n0&&(n=this._generateHash(e))}return this.set(e,n),n}}},491:function(e){"use strict";class t extends Error{constructor(e){super();const t=new Error("Schema not found: "+e);return t.name="SchemaNotFound",t}}e.exports=t},982:function(e){"use strict";class t extends Error{constructor(e){super(),this.name="SyncError",this.message="Sync failed: ","string"==typeof e?this.message+=e:(this.message+=e.message,this.stack=e.stack,this.originalError=e)}}e.exports=t},313:function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,s){return new(n||(n=Promise))(function(o,i){function r(e){try{a(s.next(e))}catch(e){i(e)}}function c(e){try{a(s.throw(e))}catch(e){i(e)}}function a(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(r,c)}a((s=s.apply(e,t||[])).next())})},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Sync=void 0;const h=a(n(28)),b=a(n(451)),m=a(n(93)),o=a(n(334)),v=a(n(275)),p=a(n(982)),f=a(n(503)),s=n(746);let d,l;function r(e,t,n){return{action:e,path:t,promise:n}}function g(e,t){return e.common.revision!==t&&(!e.remote||e.remote.revision!==t)}function u(e){return e.common&&e.common.revision}class c{constructor(e){this._finishedTasks=[],this.rs=e,this._tasks={},this._running={},this._timeStarted={},this.numThreads=10,this.rs.local.onDiff(e=>{this.addTask(e),this.doTasks()}),this.rs.caching.onActivate(e=>{this.addTask(e),this.doTasks()}),this.addEvents(["done","req-done"])}now(){return(new Date).getTime()}queueGetRequest(e){return new Promise((t,n)=>{this.rs.remote.connected?this.rs.remote.online?(this.addTask(e,function(){this.rs.local.get(e).then(e=>t(e))}.bind(this)),this.doTasks()):n("cannot fulfill maxAge requirement - remote is not online"):n("cannot fulfill maxAge requirement - remote is not connected")})}corruptServerItemsMap(e,t){if("object"!=typeof e||Array.isArray(e))return!0;for(const n in e){const o=e[n];if("object"!=typeof o)return!0;if("string"!=typeof o.ETag)return!0;if((0,s.isFolder)(n)){if(-1!==n.substring(0,n.length-1).indexOf("/"))return!0}else{if(-1!==n.indexOf("/"))return!0;if(t){if("string"!=typeof o["Content-Type"])return!0;if("number"!=typeof o["Content-Length"])return!0}}}return!1}corruptItemsMap(e){if("object"!=typeof e||Array.isArray(e))return!0;for(const t in e)if("boolean"!=typeof e[t])return!0;return!1}corruptRevision(e){return"object"!=typeof e||Array.isArray(e)||e.revision&&"string"!=typeof e.revision||e.body&&"string"!=typeof e.body&&"object"!=typeof e.body||e.contentType&&"string"!=typeof e.contentType||e.contentLength&&"number"!=typeof e.contentLength||e.timestamp&&"number"!=typeof e.timestamp||e.itemsMap&&this.corruptItemsMap(e.itemsMap)}isCorrupt(e){return"object"!=typeof e||Array.isArray(e)||"string"!=typeof e.path||this.corruptRevision(e.common)||e.local&&this.corruptRevision(e.local)||e.remote&&this.corruptRevision(e.remote)||e.push&&this.corruptRevision(e.push)}hasTasks(){return Object.getOwnPropertyNames(this._tasks).length>0}collectDiffTasks(){return i(this,void 0,void 0,function*(){let e=0;return this.rs.local.forAllNodes(t=>{e>100||(this.isCorrupt(t)?((0,o.default)("[Sync] WARNING: corrupt node in local cache",t),"object"==typeof t&&t.path&&(this.addTask(t.path),e++)):(this.needsFetch(t)&&this.rs.access.checkPathPermission(t.path,"r")||(0,s.isDocument)(t.path)&&this.needsPush(t)&&this.rs.access.checkPathPermission(t.path,"rw"))&&(this.addTask(t.path),e++))}).then(()=>e).catch(e=>{throw e})})}inConflict(e){return e.local&&e.remote&&(void 0!==e.remote.body||e.remote.itemsMap)}needsRefresh(e){return!!e.common&&(!e.common.timestamp||this.now()-e.common.timestamp>h.default.syncInterval)}needsFetch(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)}needsPush(e){return!this.inConflict(e)&&(!!e.local&&!e.push||void 0)}needsRemotePut(e){return e.local&&e.local.body}needsRemoteDelete(e){return e.local&&!1===e.local.body}getParentPath(e){const t=e.match(/^(.*\/)([^/]+\/?)$/);if(t)return t[1];throw new Error('Not a valid path: "'+e+'"')}deleteChildPathsFromTasks(){for(const e in this._tasks){const t=(0,s.pathsFromRoot)(e);for(let n=1;n{let t;if(this.needsRefresh(e)){try{t=this.getParentPath(e.path)}catch{}t&&this.rs.access.checkPathPermission(t,"r")?this.addTask(t):this.rs.access.checkPathPermission(e.path,"r")&&this.addTask(e.path)}}).then(()=>this.deleteChildPathsFromTasks()).catch(e=>{throw e})})}flush(e){for(const t in e)"FLUSH"===this.rs.caching.checkPath(t)&&e[t]&&!e[t].local&&((0,o.default)("[Sync] Flushing",t),e[t]=void 0);return e}doTask(e){return this.rs.local.getNodes([e]).then(t=>{const n=t[e];return void 0===n||function(e){return e.remote&&e.remote.revision&&!e.remote.itemsMap&&!e.remote.body}(n)?r("get",e,this.rs.remote.get(e)):this.needsRemotePut(n)?(n.push=(0,s.deepClone)(n.local),n.push.timestamp=this.now(),this.rs.local.setNodes(this.flush(t)).then(()=>{let t;return t=u(n)?{ifMatch:n.common.revision}:{ifNoneMatch:"*"},r("put",e,this.rs.remote.put(e,n.push.body,n.push.contentType,t))})):this.needsRemoteDelete(n)?(n.push={body:!1,timestamp:this.now()},this.rs.local.setNodes(this.flush(t)).then(()=>u(n)?r("delete",e,this.rs.remote.delete(e,{ifMatch:n.common.revision})):r("get",e,this.rs.remote.get(e)))):u(n)?r("get",e,this.rs.remote.get(e,{ifNoneMatch:n.common.revision})):r("get",e,this.rs.remote.get(e))})}autoMergeFolder(e){if(e.remote.itemsMap&&(e.common=e.remote,delete e.remote,e.common.itemsMap)){for(const t in e.common.itemsMap)e.local.itemsMap[t]||(e.local.itemsMap[t]=!1);(0,s.equal)(e.local.itemsMap,e.common.itemsMap)&&delete e.local}return e}autoMergeDocument(e){return function(e){return(!e.remote||!e.remote.revision||e.remote.revision===e.common.revision)&&(void 0===e.common.body&&!1===e.remote.body||e.remote.body===e.common.body&&e.remote.contentType===e.common.contentType)}(e)?delete(e=function(e){return e.remote&&!1===e.remote.body&&e.local&&!1===e.local.body&&delete e.local,e}(e)).remote:void 0!==e.remote.body&&((0,o.default)("[Sync] Emitting keep/revert"),this.rs.local._emitChange({origin:"conflict",path:e.path,oldValue:e.local.body,newValue:e.remote.body,lastCommonValue:e.common.body,oldContentType:e.local.contentType,newContentType:e.remote.contentType,lastCommonContentType:e.common.contentType}),e.remote.body?e.common=e.remote:e.common={},delete e.remote,delete e.local),e}autoMerge(e){if(e.remote){if(e.local)return(0,s.isFolder)(e.path)?this.autoMergeFolder(e):this.autoMergeDocument(e);if((0,s.isFolder)(e.path))void 0!==e.remote.itemsMap&&(e.common=e.remote,delete e.remote);else if(void 0!==e.remote.body){const t={origin:"remote",path:e.path,oldValue:!1===e.common.body?void 0:e.common.body,newValue:!1===e.remote.body?void 0:e.remote.body,oldContentType:e.common.contentType,newContentType:e.remote.contentType};if((t.oldValue||t.newValue)&&this.rs.local._emitChange(t),!e.remote.body)return;e.common=e.remote,delete e.remote}return e}e.common.body&&this.rs.local._emitChange({origin:"remote",path:e.path,oldValue:e.common.body,newValue:void 0,oldContentType:e.common.contentType,newContentType:void 0})}updateCommonTimestamp(e,t){return i(this,void 0,void 0,function*(){return this.rs.local.getNodes([e]).then(n=>(n[e]&&n[e].common&&n[e].common.revision===t&&(n[e].common.timestamp=this.now()),this.rs.local.setNodes(this.flush(n))))})}markChildren(e,t,n,o){return i(this,void 0,void 0,function*(){const a=[],i={},r={};for(const n in t)a.push(e+n),i[e+n]=t[n];for(const t in o)a.push(e+t);return this.rs.local.getNodes(a).then(t=>{let c,a;for(const l in t)if(a=t[l],i[l])a&&a.common?g(a,i[l].ETag)&&(n[l]=(0,s.deepClone)(a),n[l].remote={revision:i[l].ETag,timestamp:this.now()},n[l]=this.autoMerge(n[l])):(c=this.rs.caching.checkPath(l),"ALL"===c&&(n[l]={path:l,common:{timestamp:this.now()},remote:{revision:i[l].ETag,timestamp:this.now()}})),n[l]&&i[l]["Content-Type"]&&(n[l].remote.contentType=i[l]["Content-Type"]),n[l]&&i[l]["Content-Length"]&&(n[l].remote.contentLength=i[l]["Content-Length"]);else if(o[l.substring(e.length)]&&a&&a.common){if(a.common.itemsMap)for(const e in a.common.itemsMap)r[l+e]=!0;if(a.local&&a.local.itemsMap)for(const e in a.local.itemsMap)r[l+e]=!0;if(a.remote||(0,s.isFolder)(l))n[l]=void 0;else if(n[l]=this.autoMerge(a),void 0===n[l]){const o=this.getParentPath(l),t=n[o],i=l.substring(e.length);t&&t.local&&(delete t.local.itemsMap[i],(0,s.equal)(t.local.itemsMap,t.common.itemsMap)&&delete t.local)}}return this.deleteRemoteTrees(Object.keys(r),n).then(e=>this.rs.local.setNodes(this.flush(e)))})})}deleteRemoteTrees(e,t){return i(this,void 0,void 0,function*(){return 0===e.length?Promise.resolve(t):this.rs.local.getNodes(e).then(e=>i(this,void 0,void 0,function*(){const n={};function o(e,t){if(e&&e.itemsMap)for(const s in e.itemsMap)n[t+s]=!0}for(const n in e){const i=e[n];i&&((0,s.isFolder)(n)?(o(i.common,n),o(i.local,n)):i.common&&void 0!==typeof i.common.body&&(t[n]=(0,s.deepClone)(i),t[n].remote={body:!1,timestamp:this.now()},t[n]=this.autoMerge(t[n])))}return this.deleteRemoteTrees(Object.keys(n),t).then(e=>this.rs.local.setNodes(this.flush(e)))}))})}completeFetch(e,t,n,o){return i(this,void 0,void 0,function*(){let a,i;const r=(0,s.pathsFromRoot)(e);return(0,s.isFolder)(e)?a=[e]:(i=r[1],a=[e,i]),this.rs.local.getNodes(a).then(a=>{let l,c,r=a[e];const d={};function u(e){if(e&&e.itemsMap)for(l in e.itemsMap)t[l]||(d[l]=!0)}if("object"==typeof r&&r.path===e&&"object"==typeof r.common||(r={path:e,common:{}},a[e]=r),r.remote={revision:o,timestamp:this.now()},(0,s.isFolder)(e))for(l in u(r.common),u(r.remote),r.remote.itemsMap={},t)r.remote.itemsMap[l]=!0;else r.remote.body=t,r.remote.contentType=n,c=a[i],c&&c.local&&c.local.itemsMap&&(l=e.substring(i.length),c.local.itemsMap[l]=!0,(0,s.equal)(c.local.itemsMap,c.common.itemsMap)&&delete c.local);return a[e]=this.autoMerge(r),{toBeSaved:a,missingChildren:d}})})}completePush(e,t,n,a){return i(this,void 0,void 0,function*(){return this.rs.local.getNodes([e]).then(i=>{const r=i[e];if(!r.push)throw this.stopped=!0,new Error("completePush called but no push version!");return n?((0,o.default)("[Sync] We have a conflict"),r.remote&&r.remote.revision===a||(r.remote={revision:a||"conflict",timestamp:this.now()},delete r.push),i[e]=this.autoMerge(r)):(r.common={revision:a,timestamp:this.now()},"put"===t?(r.common.body=r.push.body,r.common.contentType=r.push.contentType,(0,s.equal)(r.local.body,r.push.body)&&r.local.contentType===r.push.contentType&&delete r.local,delete r.push):"delete"===t&&(!1===r.local.body?i[e]=void 0:delete r.push)),this.rs.local.setNodes(this.flush(i))})})}dealWithFailure(e){return i(this,void 0,void 0,function*(){return this.rs.local.getNodes([e]).then(t=>{if(t[e])return delete t[e].push,this.rs.local.setNodes(this.flush(t))})})}interpretStatus(e){const t={statusCode:e,successful:void 0,conflict:void 0,unAuth:void 0,notFound:void 0,changed:void 0,networkProblems:void 0};if("string"==typeof e&&("offline"===e||"timeout"===e))return t.successful=!1,t.networkProblems=!0,t;if("number"==typeof e){const n=Math.floor(e/100);return t.successful=2===n||304===e||412===e||404===e,t.conflict=412===e,t.unAuth=401===e&&this.rs.remote.token!==v.default.IMPLIED_FAKE_TOKEN||402===e||403===e,t.notFound=404===e,t.changed=304!==e,t}}handleGetResponse(e,t,n,a,r){return i(this,void 0,void 0,function*(){return t.notFound&&(n=!!(0,s.isFolder)(e)&&{}),t.changed?this.completeFetch(e,n,a,r).then(t=>(0,s.isFolder)(e)?this.corruptServerItemsMap(n)?((0,o.default)("[Sync] WARNING: Discarding corrupt folder description from server for "+e),!1):this.markChildren(e,n,t.toBeSaved,t.missingChildren).then(()=>!0):this.rs.local.setNodes(this.flush(t.toBeSaved)).then(()=>!0)):this.updateCommonTimestamp(e,r).then(()=>!0)})}handleResponse(e,t,n){const s=this.interpretStatus(n.statusCode);if(s.successful){if("get"===t)return this.handleGetResponse(e,s,n.body,n.contentType,n.revision);if("put"===t||"delete"===t)return this.completePush(e,t,s.conflict,n.revision).then(function(){return!0});throw new Error(`cannot handle response for unknown action ${t}`)}{let t;return t=s.unAuth?new f.default:s.networkProblems?new p.default("Network request failed."):new Error("HTTP response code "+s.statusCode+" received."),this.dealWithFailure(e).then(()=>{throw this.rs._emit("error",t),t})}}finishTask(e,t=!0){if(void 0!==e.action){if(!t||!((0,o.default)("[Sync] queue finished task:",e.path),this._finishedTasks.push(e),this._finishedTasks.length>1))return(0,o.default)("[Sync] run task:",e.path),e.promise.then(t=>this.handleResponse(e.path,e.action,t),t=>((0,o.default)("[Sync] wireclient rejects its promise!",e.path,e.action,t),this.handleResponse(e.path,e.action,{statusCode:"offline"}))).then(t=>i(this,void 0,void 0,function*(){if(this._finishedTasks.shift(),delete this._timeStarted[e.path],delete this._running[e.path],t&&this._tasks[e.path]){for(let t=0;t0?this.finishTask(this._finishedTasks[0],!1):yield this.collectTasks(!1).then(()=>{!this.hasTasks()||this.stopped?((0,o.default)("[Sync] Sync is done! Reschedule?",Object.getOwnPropertyNames(this._tasks).length,this.stopped),this.done||(this.done=!0,this.rs._emit("sync-done",{completed:!0}))):setTimeout(()=>{this.doTasks()},10)})}),t=>{(0,o.default)("[Sync] Error",t),this._finishedTasks.shift(),delete this._timeStarted[e.path],delete this._running[e.path],this.rs._emit("sync-req-done",{tasksRemaining:Object.keys(this._tasks).length}),this._finishedTasks.length>0?this.finishTask(this._finishedTasks[0],!1):this.done||(this.done=!0,this.rs._emit("sync-done",{completed:!1}))});(0,o.default)("[Sync] delaying finished task:",e.path)}else delete this._running[e.path]}doTasks(){let s,e,t=0;s=this.rs.remote.connected?this.rs.remote.online?this.numThreads:1:0;const n=s-Object.getOwnPropertyNames(this._running).length;if(n<=0)return!0;for(e in this._tasks)if(!this._running[e]&&(this._timeStarted[e]=this.now(),this._running[e]=this.doTask(e),this._running[e].then(this.finishTask.bind(this)),t++,t>=n))return!0;return t>=n}collectTasks(e){return i(this,void 0,void 0,function*(){return this.hasTasks()||this.stopped?Promise.resolve():this.collectDiffTasks().then(t=>t||!1===e?Promise.resolve():this.collectRefreshTasks(),function(e){throw e})})}addTask(e,t){this._tasks[e]||(this._tasks[e]=[]),"function"==typeof t&&this._tasks[e].push(t)}sync(){return this.done=!1,this.doTasks()?Promise.resolve():this.collectTasks().then(()=>{try{this.doTasks()}catch(e){(0,o.default)("[Sync] doTasks error",e)}},function(e){throw(0,o.default)("[Sync] Sync error",e),new Error("Local cache unavailable")})}static _rs_init(e){d=function(){(0,o.default)("[Sync] syncCycleCb calling syncCycle");const t=new b.default;t.isBrowser()&&function(e,t){function n(e){const n=t.getCurrentSyncInterval();h.default.isBackground=!e;const s=t.getCurrentSyncInterval();t._emit("sync-interval-change",{oldValue:n,newValue:s})}e.on("background",()=>n(!1)),e.on("foreground",()=>n(!0))}(t,e),e.sync||(e.sync=new c(e),e.syncStopped&&((0,o.default)("[Sync] Instantiating sync stopped"),e.sync.stopped=!0,delete e.syncStopped)),(0,o.default)("[Sync] syncCycleCb calling syncCycle"),e.syncCycle()},l=function(){e.removeEventListener("connected",l),e.startSync()},e.on("ready",d),e.on("connected",l)}static _rs_cleanup(e){e.stopSync(),e.removeEventListener("ready",d),e.removeEventListener("connected",l),e.sync=void 0,delete e.sync}}t.Sync=c,(0,s.applyMixins)(c,[m.default]),t.default=c},370:function(e,t,n){"use strict";var o=this&&this.__awaiter||function(e,t,n,s){return new(n||(n=Promise))(function(o,i){function r(e){try{a(s.next(e))}catch(e){i(e)}}function c(e){try{a(s.throw(e))}catch(e){i(e)}}function a(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(r,c)}a((s=s.apply(e,t||[])).next())})};const i=(this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}})(n(334));function a(e){return"dropbox"===this.backend&&!!e.match(/^\/public\/.*[^/]$/)}const s={get:function(e,t){if(this.local){if(void 0===t)t="object"==typeof(n=this).remote&&n.remote.connected&&n.remote.online?2*n.getSyncInterval():((0,i.default)("Not setting default maxAge, because remote is offline or not connected"),!1);else if("number"!=typeof t&&!1!==t)return Promise.reject("Argument 'maxAge' must be 'false' or a number");return this.local.get(e,t,this.sync.queueGetRequest.bind(this.sync))}return this.remote.get(e);var n},put:function(e,t,n){return a.bind(this)(e)?s._wrapBusyDone.call(this,this.remote.put(e,t,n)):this.local?this.local.put(e,t,n):s._wrapBusyDone.call(this,this.remote.put(e,t,n))},delete:function(e){return this.local?this.local.delete(e):s._wrapBusyDone.call(this,this.remote.delete(e))},_wrapBusyDone:function(e){return o(this,void 0,void 0,function*(){return this._emit("wire-busy"),e.then(e=>(this._emit("wire-done",{success:!0}),Promise.resolve(e)),e=>(this._emit("wire-done",{success:!1}),Promise.reject(e)))})}};e.exports=s},613:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BaseClientTypes=void 0;class n{constructor(){this.uris={},this.schemas={},this.aliases={}}declare(e,t,n,s){const o=e+"/"+t;if(s.extends){const t=s.extends.split("/"),n=1===t.length?e+"/"+t.shift():t.join("/"),i=this.uris[n];if(!i)throw"Type '"+o+"' tries to extend unknown schema '"+n+"'";s.extends=this.schemas[i]}this.uris[o]=n,this.aliases[n]=o,this.schemas[n]=s}resolveAlias(e){return this.uris[e]}getSchema(e){return this.schemas[e]}inScope(e){const n=e.length,t={};for(const s in this.uris)if(s.substr(0,n+1)===e+"/"){const e=this.uris[s];t[e]=this.schemas[e]}return t}}t.BaseClientTypes=n;const s=new n;t.default=s},503:function(e){"use strict";class t extends Error{constructor(e,t={}){super(),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}}e.exports=t},746:function(e,t,n){"use strict";var o=this&&this.__awaiter||function(e,t,n,s){return new(n||(n=Promise))(function(o,i){function r(e){try{a(s.next(e))}catch(e){i(e)}}function c(e){try{a(s.throw(e))}catch(e){i(e)}}function a(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(r,c)}a((s=s.apply(e,t||[])).next())})};function s(e,t){if("object"==typeof e&&!Array.isArray(e)&&null!==e)for(const n in e)if("object"==typeof e[n]&&null!==e[n])if("[object ArrayBuffer]"===e[n].toString()){t[n]=new ArrayBuffer(e[n].byteLength);const s=new Int8Array(e[n]);new Int8Array(t[n]).set(s)}else s(e[n],t[n])}Object.defineProperty(t,"__esModule",{value:!0}),t.toBase64=t.getTextFromArrayBuffer=t.shouldBeTreatedAsBinary=t.getJSONFromLocalStorage=t.localStorageAvailable=t.pathsFromRoot=t.deepClone=t.equal=t.bindAll=t.cleanPath=t.baseName=t.isDocument=t.isFolder=t.containingFolder=t.extend=t.getGlobalContext=t.globalContext=t.logError=void 0,t.generateCodeVerifier=function(){return o(this,arguments,void 0,function*(e=128){const t=new Uint8Array(e);crypto.getRandomValues(t);const n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",s=Array.from(t).map(e=>n[e%66]),i=s.join(""),a=Uint8Array.from(s.map(e=>e.charCodeAt(0))),r=(o=yield crypto.subtle.digest("SHA-256",a),btoa(String.fromCharCode.apply(null,new Uint8Array(o))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""));var o;return crypto.getRandomValues(t),{codeVerifier:i,codeChallenge:r,state:Array.from(t).map(e=>n[e%66]).join("")}})},t.applyMixins=function(e,t){t.forEach(t=>{Object.getOwnPropertyNames(t.prototype).forEach(n=>{Object.defineProperty(e.prototype,n,Object.getOwnPropertyDescriptor(t.prototype,n))})})},t.logError=e=>{"string"==typeof e?console.error(e):console.error(e.message,e.stack)},t.globalContext="undefined"!=typeof window?window:"object"==typeof self?self:n.g,t.getGlobalContext=()=>"undefined"!=typeof window?window:"object"==typeof self?self:n.g,t.extend=(...e)=>{const t=e[0];return Array.prototype.slice.call(e,1).forEach(function(e){for(const n in e)t[n]=e[n]}),t},t.containingFolder=e=>{if(""===e)return"/";if(!e)throw"Path not given!";return e.replace(/\/+/g,"/").replace(/[^/]+\/?$/,"")},t.isFolder=e=>"/"===e.slice(-1),t.isDocument=e=>!(0,t.isFolder)(e),t.baseName=e=>{const n=e.split("/");return(0,t.isFolder)(e)?n[n.length-2]+"/":n[n.length-1]},t.cleanPath=e=>e.replace(/\/+/g,"/").split("/").map(encodeURIComponent).join("/").replace(/'/g,"%27"),t.bindAll=e=>{for(const t in this)"function"==typeof e[t]&&(e[t]=e[t].bind(e))},t.equal=(e,n,s=[])=>{let o;if(typeof e!=typeof n)return!1;if("number"==typeof e||"boolean"==typeof e||"string"==typeof e)return e===n;if("function"==typeof e)return e.toString()===n.toString();if(e instanceof ArrayBuffer&&n instanceof ArrayBuffer&&(e=new Uint8Array(e),n=new Uint8Array(n)),e instanceof Array){{if(e.length!==n.length)return!1;for(let o=0,i=e.length;o=0)continue;i=s.slice(),i.push(n[o])}if(!(0,t.equal)(e[o],n[o],i))return!1}}return!0},t.deepClone=e=>{if(void 0!==e){const t=JSON.parse(JSON.stringify(e));return s(e,t),t}},t.pathsFromRoot=e=>{const n=[e],t=e.replace(/\/$/,"").split("/");for(;t.length>1;)t.pop(),n.push(t.join("/")+"/");return n},t.localStorageAvailable=()=>{const e=(0,t.getGlobalContext)();if(!("localStorage"in e))return!1;try{return e.localStorage.setItem("rs-check","1"),e.localStorage.removeItem("rs-check"),!0}catch{return!1}},t.getJSONFromLocalStorage=e=>{const n=(0,t.getGlobalContext)();try{return JSON.parse(n.localStorage.getItem(e))}catch{}},t.shouldBeTreatedAsBinary=(e,t)=>!!(t&&t.match(/charset=binary/)||/[\x00-\x08\x0E-\x1F\uFFFD]/.test(e)),t.getTextFromArrayBuffer=(e,n)=>new Promise(s=>{if("undefined"==typeof Blob||"undefined"==typeof FileReader){const t=Buffer.from(e);s(t.toString(n))}else{let a;const o=t.globalContext;if(o.BlobBuilder=o.BlobBuilder||o.WebKitBlobBuilder,void 0!==o.BlobBuilder){const t=new o.BlobBuilder;t.append(e),a=t.getBlob()}else a=new Blob([e]);const i=new FileReader;"function"==typeof i.addEventListener?i.addEventListener("loadend",function(e){s(e.target.result)}):i.onloadend=function(e){s(e.target.result)},i.readAsText(a,n)}}),t.toBase64=e=>{const n=(0,t.getGlobalContext)();return"btoa"in n?n.btoa(e):Buffer.from(e).toString("base64")}},600:function(e,t,n){"use strict";var f=this&&this.__awaiter||function(e,t,n,s){return new(n||(n=Promise))(function(o,i){function r(e){try{a(s.next(e))}catch(e){i(e)}}function c(e){try{a(s.throw(e))}catch(e){i(e)}}function a(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(r,c)}a((s=s.apply(e,t||[])).next())})},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const d=a(n(275)),u=a(n(93)),h=a(n(503)),i=a(n(334)),s=n(746),l=n(368),m=n(684);let o;const r="remotestorage:wireclient",p={"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};class c extends m.RemoteBase{constructor(e){if(super(e),this._revisionCache={},o=(0,s.localStorageAvailable)(),this.addEvents(["connected","not-connected"]),o){const e=function(){const e=(0,s.getJSONFromLocalStorage)(r)||{},{userAddress:t,href:n,storageApi:o,token:i,properties:a}=e;return{userAddress:t,href:n,storageApi:o,token:i,properties:a}}();e&&setTimeout(()=>{this.configure(e)},0)}this.connected&&setTimeout(this._emit.bind(this),0,"connected")}get storageType(){if(this.storageApi){const e=this.storageApi.match(/draft-dejong-(remotestorage-\d\d)/);return e?e[1]:"2012.04"}}_request(e,t,n,o,a,r,c){return f(this,void 0,void 0,function*(){if(this.isForbiddenRequestMethod(e,t))return Promise.reject(`Don't use ${e} on directories!`);let u;return n!==d.default.IMPLIED_FAKE_TOKEN&&(o.Authorization="Bearer "+n),this.rs._emit("wire-busy",{method:e,isFolder:(0,s.isFolder)(t)}),(0,l.requestWithTimeout)(e,t,{body:a,headers:o,responseType:"arraybuffer"}).then(n=>{if(this.online||(this.online=!0,this.rs._emit("network-online")),this.rs._emit("wire-done",{method:e,isFolder:(0,s.isFolder)(t),success:!0}),o=n.status,[401,403,404,412].indexOf(o)>=0)return(0,i.default)("[WireClient] Error response status",n.status),u=r?this.stripQuotes(n.getResponseHeader("ETag")):void 0,401===n.status&&this.rs._emit("error",new h.default),Promise.resolve({statusCode:n.status,revision:u});if(function(e){return[201,204,304].indexOf(e)>=0}(n.status)||200===n.status&&"GET"!==e)return u=this.stripQuotes(n.getResponseHeader("ETag")),(0,i.default)("[WireClient] Successful request",u),Promise.resolve({statusCode:n.status,revision:u});{const e=n.getResponseHeader("Content-Type");u=r?this.stripQuotes(n.getResponseHeader("ETag")):200===n.status?c:void 0;const t=function(e){let t,n="utf-8";return e&&(t=e.match(/charset=(.+)$/),t&&(n=t[1])),n}(e);return(0,s.shouldBeTreatedAsBinary)(n.response,e)?((0,i.default)("[WireClient] Successful request with unknown or binary mime-type",u),Promise.resolve({statusCode:n.status,body:n.response,contentType:e,revision:u})):(0,s.getTextFromArrayBuffer)(n.response,t).then(t=>((0,i.default)("[WireClient] Successful request",u),Promise.resolve({statusCode:n.status,body:t,contentType:e,revision:u})))}var o},n=>(this.online&&(this.online=!1,this.rs._emit("network-offline")),this.rs._emit("wire-done",{method:e,isFolder:(0,s.isFolder)(t),success:!1}),Promise.reject(n)))})}configure(e){if("object"!=typeof e)throw new Error("WireClient configure settings parameter should be an object");if(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),"string"==typeof this.storageApi){const e=p[this.storageApi]||5;this.supportsRevs=e>=2}this.href&&this.token?(this.connected=!0,this.online=!0,this._emit("connected")):this.connected=!1,o&&(localStorage[r]=JSON.stringify({userAddress:this.userAddress,href:this.href,storageApi:this.storageApi,token:this.token,properties:this.properties}))}get(e,t={}){if(!this.connected)return Promise.reject("not connected (path: "+e+")");const n={};return this.supportsRevs&&t.ifNoneMatch&&(n["If-None-Match"]=this.addQuotes(t.ifNoneMatch)),this._request("GET",this.href+(0,s.cleanPath)(e),this.token,n,void 0,this.supportsRevs,this._revisionCache[e]).then(t=>{if(!(0,s.isFolder)(e))return Promise.resolve(t);let n={};if(void 0!==t.body)try{t.body=JSON.parse(t.body)}catch{return Promise.reject("Folder description at "+this.href+(0,s.cleanPath)(e)+" is not JSON")}if(200===t.statusCode&&"object"==typeof 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"==typeof o.items){for(const n in t.body.items)this._revisionCache[e+n]=t.body.items[n].ETag;n=t.body.items}else Object.keys(t.body).forEach(s=>{this._revisionCache[e+s]=t.body[s],n[s]={ETag:t.body[s]}});return t.body=n,Promise.resolve(t)}return Promise.resolve(t);var o})}put(e,t,n,o={}){if(!this.connected)return Promise.reject("not connected (path: "+e+")");!n.match(/charset=/)&&(t instanceof ArrayBuffer||(0,l.isArrayBufferView)(t))&&(n+="; charset=binary");const i={"Content-Type":n};return this.supportsRevs&&(o.ifMatch&&(i["If-Match"]=this.addQuotes(o.ifMatch)),o.ifNoneMatch&&(i["If-None-Match"]=this.addQuotes(o.ifNoneMatch))),this._request("PUT",this.href+(0,s.cleanPath)(e),this.token,i,t,this.supportsRevs)}delete(e,t={}){if(!this.connected)throw new Error("not connected (path: "+e+")");t||(t={});const n={};return this.supportsRevs&&t.ifMatch&&(n["If-Match"]=this.addQuotes(t.ifMatch)),this._request("DELETE",this.href+(0,s.cleanPath)(e),this.token,n,void 0,this.supportsRevs)}static _rs_init(e){e.remote=new c(e),e.remote.online=!0}static _rs_supported(){return"function"==typeof fetch||"function"==typeof XMLHttpRequest}static _rs_cleanup(){o&&delete localStorage[r]}}(0,s.applyMixins)(c,[u.default]),e.exports=c},439:function(e,t){var n,s=function(){Object.keys||(Object.keys=(p=Object.prototype.hasOwnProperty,_=!{toString:null}.propertyIsEnumerable("toString"),y=(m=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"]).length,function(e){if("object"!=typeof e&&"function"!=typeof e||null===e)throw new TypeError("Object.keys called on non-object");var t,s,n=[];for(s in e)p.call(e,s)&&n.push(s);if(_)for(t=0;t>>0;if(0===s)return-1;if(t=0,arguments.length>1&&((t=Number(arguments[1]))!=t?t=0:0!==t&&t!==1/0&&t!==-1/0&&(t=(t>0||-1)*Math.floor(Math.abs(t)))),t>=s)return-1;for(n=t>=0?t:Math.max(s-Math.abs(t),0);n0&&(n+=l.suffices["*"]&&s||",",l.suffices["*"]&&i&&(n+=l.name+"=")),n+=a?encodeURIComponent(t[d]).replace(/!/g,"%21"):r(t[d])}else if("object"==typeof t){i&&!l.suffices["*"]&&(n+=l.name+"="),m=!0;for(h in t)m||(n+=l.suffices["*"]&&s||","),m=!1,n+=a?encodeURIComponent(h).replace(/!/g,"%21"):r(h),n+=l.suffices["*"]?"=":",",n+=a?encodeURIComponent(t[h]).replace(/!/g,"%21"):r(t[h])}else i&&(n+=l.name,v&&""===t||(n+="=")),null!=l.truncate&&(t=t.substring(0,l.truncate)),n+=a?encodeURIComponent(t).replace(/!/g,"%21"):r(t);return n},f.varNames=g,{prefix:o,substitution:f}}function l(e){if(!(this instanceof l))return new l(e);for(var t=e.split("{"),n=[t.shift()],c=[],s=[],o=[];t.length>0;){var a=t.shift(),r=a.split("}")[0],d=a.substring(r.length+1),i=x(r);s.push(i.substitution),c.push(i.prefix),n.push(d),o=o.concat(i.substitution.varNames)}this.fill=function(e){for(var o=n[0],t=0;t0&&"/"===t.charAt(e.length-1)||"#"===n.charAt(0)||"?"===n.charAt(0))return!0}return!1}(t,e.id)&&void 0===this.schemas[e.id]&&(this.schemas[e.id]=e),e)"enum"!==s&&("object"==typeof e[s]?this.searchSchemas(e[s],t):"$ref"===s&&(n=d(e[s]),n&&void 0===this.schemas[n]&&void 0===this.missingMap[n]&&(this.missingMap[n]=n)))},e.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===d(e)+"#"&&(e=d(e)),this.schemas[e]=t,delete this.missingMap[e],u(t,e),this.searchSchemas(t,e)},e.prototype.getSchemaMap=function(){var t,e={};for(t in this.schemas)e[t]=this.schemas[t];return e},e.prototype.getSchemaUris=function(e){var n,t=[];for(n in this.schemas)e&&!e.test(n)||t.push(n);return t},e.prototype.getMissingUris=function(e){var n,t=[];for(n in this.missingMap)e&&!e.test(n)||t.push(n);return t},e.prototype.dropSchemas=function(){this.schemas={},this.reset()},e.prototype.reset=function(){this.missing=[],this.missingMap={},this.errors=[]},e.prototype.validateAll=function(e,t,n,o,i){if(!(t=this.resolveRefs(t)))return null;if(t instanceof s)return this.errors.push(t),t;var a,r,d,u,h,m,f,p,g=this.errors.length,c=null,l=null;if(this.checkRecursive&&e&&"object"==typeof e){if(p=!this.scanned.length,e[this.validatedSchemasKey]&&(d=e[this.validatedSchemasKey].indexOf(t),-1!==d))return this.errors=this.errors.concat(e[this.validationErrorsKey][d]),null;if(Object.isFrozen(e)&&-1!==(a=this.scannedFrozen.indexOf(e))&&(u=this.scannedFrozenSchemas[a].indexOf(t),-1!==u))return this.errors=this.errors.concat(this.scannedFrozenValidationErrors[a][u]),null;if(this.scanned.push(e),Object.isFrozen(e))-1===a&&(a=this.scannedFrozen.length,this.scannedFrozen.push(e),this.scannedFrozenSchemas.push([])),c=this.scannedFrozenSchemas[a].length,this.scannedFrozenSchemas[a][c]=t,this.scannedFrozenValidationErrors[a][c]=[];else{if(!e[this.validatedSchemasKey])try{Object.defineProperty(e,this.validatedSchemasKey,{value:[],configurable:!0}),Object.defineProperty(e,this.validationErrorsKey,{value:[],configurable:!0})}catch{e[this.validatedSchemasKey]=[],e[this.validationErrorsKey]=[]}l=e[this.validatedSchemasKey].length,e[this.validatedSchemasKey][l]=t,e[this.validationErrorsKey][l]=[]}}if(h=this.errors.length,r=this.validateBasic(e,t,i)||this.validateNumeric(e,t,i)||this.validateString(e,t,i)||this.validateArray(e,t,i)||this.validateObject(e,t,i)||this.validateCombinations(e,t,i)||this.validateHypermedia(e,t,i)||this.validateFormat(e,t,i)||this.validateDefinedKeywords(e,t,i)||null,p){for(;this.scanned.length;)delete this.scanned.pop()[this.validatedSchemasKey];this.scannedFrozen=[],this.scannedFrozenSchemas=[]}if(r||h!==this.errors.length)for(;n&&n.length||o&&o.length;)m=n&&n.length?""+n.pop():null,f=o&&o.length?""+o.pop():null,r&&(r=r.prefixWith(m,f)),this.prefixErrors(h,m,f);return null!==c?this.scannedFrozenValidationErrors[a][c]=this.errors.slice(g):null!==l&&(e[this.validationErrorsKey][l]=this.errors.slice(g)),this.handleError(r)},e.prototype.validateFormat=function(e,n){if("string"!=typeof n.format||!this.formatValidators[n.format])return null;var s=this.formatValidators[n.format].call(null,e,n);return"string"==typeof s||"number"==typeof s?this.createError(t.FORMAT_CUSTOM,{message:s},"","/format",null,e,n):s&&"object"==typeof s?this.createError(t.FORMAT_CUSTOM,{message:s.message||"?"},s.dataPath||"",s.schemaPath||"/format",null,e,n):null},e.prototype.validateDefinedKeywords=function(e,n,s){for(a in this.definedKeywords)if(void 0!==n[a])for(var o,i,a,l,d,c=this.definedKeywords[a],r=0;r=f&&on.maximum)return this.createError(t.NUMBER_MAXIMUM,{value:e,maximum:n.maximum},"","/maximum",null,e,n);if(n.exclusiveMaximum&&e===n.maximum)return this.createError(t.NUMBER_MAXIMUM_EXCLUSIVE,{value:e,maximum:n.maximum},"","/exclusiveMaximum",null,e,n)}return null},e.prototype.validateNaN=function(e,n){return"number"!=typeof e?null:!0===isNaN(e)||e===1/0||e===-1/0?this.createError(t.NUMBER_NOT_A_NUMBER,{value:e},"","/type",null,e,n):null},e.prototype.validateString=function(e,t,n){return this.validateStringLength(e,t,n)||this.validateStringPattern(e,t,n)||null},e.prototype.validateStringLength=function(e,n){return"string"!=typeof e?null:void 0!==n.minLength&&e.lengthn.maxLength?this.createError(t.STRING_LENGTH_LONG,{length:e.length,maximum:n.maxLength},"","/maxLength",null,e,n):null},e.prototype.validateStringPattern=function(e,n){if("string"!=typeof e||"string"!=typeof n.pattern&&!(n.pattern instanceof RegExp))return null;if(n.pattern instanceof RegExp)s=n.pattern;else{var s,o,a="",i=n.pattern.match(/^\/(.+)\/([img]*)$/);i?(o=i[1],a=i[2]):o=n.pattern,s=new RegExp(o,a)}return s.test(e)?null:this.createError(t.STRING_PATTERN,{pattern:n.pattern},"","/pattern",null,e,n)},e.prototype.validateArray=function(e,t,n){return Array.isArray(e)&&(this.validateArrayLength(e,t,n)||this.validateArrayUniqueItems(e,t,n)||this.validateArrayItems(e,t,n))||null},e.prototype.validateArrayLength=function(e,n){var s;return void 0!==n.minItems&&e.lengthn.maxItems&&(s=this.createError(t.ARRAY_LENGTH_LONG,{length:e.length,maximum:n.maxItems},"","/maxItems",null,e,n),this.handleError(s))?s:null},e.prototype.validateArrayUniqueItems=function(e,n){if(n.uniqueItems)for(var o,i,s=0;sn.maxProperties&&(s=this.createError(t.OBJECT_PROPERTIES_MAXIMUM,{propertyCount:o.length,maximum:n.maxProperties},"","/maxProperties",null,e,n),this.handleError(s))?s:null},e.prototype.validateObjectRequiredProperties=function(e,n){if(void 0!==n.required)for(var o,i,s=0;s 10000");if(void 0!==t[e])throw new Error("Error already defined: "+e+" as "+t[e]);if(void 0!==a[s])throw new Error("Error code already used: "+a[s]+" as "+s);for(c in t[e]=s,a[s]=e,i[e]=i[s]=o,n){var c,r=n[c];r[e]&&(r[s]=r[s]||r[e])}},reset:function(){r.reset(),this.error=null,this.missing=[],this.valid=!0},missing:[],error:null,valid:!0,normSchema:u,resolveUrl:g,getDocumentUri:d,errorCodes:t};return m.language(o||"en"),m}(),o.addLanguage("en-gb",i),o.tv4=o,o};void 0===(n=s.apply(t,[]))||(e.exports=n)},199:function(e,t,n){var s;"function"!=typeof fetch&&"function"!=typeof XMLHttpRequest&&(XMLHttpRequest=n(317)),function(){var a={"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"},r={avatar:[],remotestorage:[],blog:[],vcard:[],updates:[],share:[],profile:[],webfist:[],camlistore:[]},c=["webfinger","host-meta","host-meta.json"];function o(e){return e.toString=function(){return this.message},e}function i(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}}i.prototype.__fetchJRD=function(e,t,n){if("function"==typeof fetch)return this.__fetchJRD_fetch(e,t,n);if("function"==typeof XMLHttpRequest)return this.__fetchJRD_XHR(e,t,n);throw new Error("add a polyfill for fetch or XMLHttpRequest")},i.prototype.__fetchJRD_fetch=function(e,t,n){i=this,"function"==typeof AbortController&&(s=new AbortController);var s,i,a=fetch(e,{headers:{Accept:"application/jrd+json, application/json"},signal:s?s.signal:void 0}).then(function(t){if(t.ok)return t.text();throw o(404===t.status?{message:"resource not found",url:e,status:t.status}:{message:"error during request",url:e,status:t.status})},function(t){throw o({message:"error during request",url:e,status:void 0,err:t})}).then(function(t){if(i.__isValidJSON(t))return t;throw o({message:"invalid json",url:e,status:void 0})}),r=new Promise(function(t,n){setTimeout(function(){n(o({message:"request timed out",url:e,status:void 0})),s&&s.abort()},i.config.request_timeout)});Promise.race([a,r]).then(function(e){n(e)}).catch(function(e){t(e)})},i.prototype.__fetchJRD_XHR=function(e,t,n){var i=this,a=!1,s=new XMLHttpRequest;function r(){if(!a)return a=!0,200===s.status?i.__isValidJSON(s.responseText)?n(s.responseText):t(o({message:"invalid json",url:e,status:s.status})):404===s.status?t(o({message:"resource not found",url:e,status:s.status})):s.status>=301&&s.status<=302?function(e){return"string"==typeof e&&"https"===e.split("://")[0]}(s.getResponseHeader("Location"))?c():t(o({message:"no redirect URL found",url:e,status:s.status})):t(o({message:"error during request",url:e,status:s.status}))}function c(){s.onreadystatechange=function(){4===s.readyState&&r()},s.onload=function(){r()},s.ontimeout=function(){return t(o({message:"request timed out",url:e,status:s.status}))},s.open("GET",e,!0),s.timeout=i.config.request_timeout,s.setRequestHeader("Accept","application/jrd+json, application/json"),s.send()}return c()},i.prototype.__isValidJSON=function(e){try{JSON.parse(e)}catch{return!1}return!0},i.prototype.__isLocalhost=function(e){return/^localhost(\.localdomain)?(:[0-9]+)?$/.test(e)},i.prototype.__processJRD=function(e,t,n,s){var i,l,d,u,c=JSON.parse(t);if("object"!=typeof c||"object"!=typeof c.links)return n(o(void 0!==c.error?{message:c.error,request:e}:{message:"unknown response from server",request:e}));l=c.links,Array.isArray(l)||(l=[]),i={object:c,json:t,idx:{}},i.idx.properties={name:void 0},i.idx.links=JSON.parse(JSON.stringify(r)),l.map(function(e){if(a.hasOwnProperty(e.rel)&&i.idx.links[a[e.rel]]){var n={};Object.keys(e).map(function(t){n[t]=e[t]}),i.idx.links[a[e.rel]].push(n)}}),d=JSON.parse(t).properties;for(u in d)d.hasOwnProperty(u)&&"http://packetizer.com/ns/name"===u&&(i.idx.properties.name=d[u]);return s(i)},i.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 n=this,s="",s=e.indexOf("://")>-1?e.replace(/ /g,"").split("/")[2]:e.replace(/ /g,"").split("@")[1],o=0,i="https";function r(){var t="";return e.split("://")[1]||(t="acct:"),i+"://"+s+"/.well-known/"+c[o]+"?resource="+t+e}function l(e){if(n.config.uri_fallback&&"webfist.org"!==s&&o!==c.length-1)return o+=1,a();if(!n.config.tls_only&&"https"===i)return o=0,i="http",a();if(!n.config.webfist_fallback||"webfist.org"===s)return t(e);o=0,i="http",s="webfist.org";var l=r();n.__fetchJRD(l,t,function(e){n.__processJRD(l,e,t,function(e){"object"==typeof e.idx.links.webfist&&"string"==typeof e.idx.links.webfist[0].href&&n.__fetchJRD(e.idx.links.webfist[0].href,t,function(e){n.__processJRD(l,e,t,function(){return t(null,t)})})})})}function a(){var e=r();n.__fetchJRD(e,l,function(s){n.__processJRD(e,s,t,function(e){t(null,e)})})}return n.__isLocalhost(s)&&(i="http"),setTimeout(a,0)},i.prototype.lookupLink=function(e,t,n){if(!r.hasOwnProperty(t))return n("unsupported rel "+t);this.lookup(e,function(e,s){var o=s.idx.links[t];return e?n(e):0===o.length?n('no links found with rel="'+t+'"'):n(null,o[0])})},void 0===(s=function(){return i}.apply(t,[]))||(e.exports=s)}()},317:function(e){e.exports=XMLHttpRequest}},t={};function e(n){var o,i=t[n];return void 0!==i?i.exports:(o=t[n]={exports:{}},s[n].call(o.exports,o,o.exports,e),o.exports)}return e.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch{if("object"==typeof window)return window}}(),n=e(423),n.default}()}),!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.Widget=t():e.Widget=t()}(self,function(){return(()=>{"use strict";var n,e={d:(t,n)=>{for(var s in n)e.o(n,s)&&!e.o(t,s)&&Object.defineProperty(t,s,{enumerable:!0,get:n[s]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)},t={};function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){for(var n,s=0;si}),n=function(){function e(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(s(this,e),this.rs=t,this.leaveOpen=!!n.leaveOpen&&n.leaveOpen,this.autoCloseAfter=n.autoCloseAfter?n.autoCloseAfter:1500,this.skipInitial=!!n.skipInitial&&n.skipInitial,this.logging=!!n.logging&&n.logging,n.hasOwnProperty("modalBackdrop")){if("boolean"!=typeof n.modalBackdrop&&"onlySmallScreens"!==n.modalBackdrop)throw'options.modalBackdrop has to be true/false or "onlySmallScreens"';this.modalBackdrop=n.modalBackdrop}else this.modalBackdrop="onlySmallScreens";this.active=!1,this.online=!1,this.closed=!1,this.lastSynced=null,this.lastSyncedUpdateLoop=null}var t,n;return t=e,n=[{key:"log",value:function(){if(this.logging){for(var t,n=arguments.length,s=new Array(n),e=0;e div { + font-size: 1.125em; + padding: 10px 0; +} +.rs-button-big:hover { + box-shadow: 0 1px 2px 0 rgba(0,0,0,0.1), 0 3px 8px 0 rgba(0,0,0,0.2); +} +.rs-button-big:active { + background-color: #eee; + box-shadow: 0 1px 2px 0 rgba(0,0,0,0.1), 0 3px 8px 0 rgba(0,0,0,0.2); +} +.rs-button-big:last-child { + margin-bottom: 0; +} + +.rs-content { + padding: 0 10px 10px 10px; +} + + +.rs-state-choose .rs-main-logo, +.rs-state-sign-in .rs-main-logo { + margin-left: 45%; + float: none; +} + +.rs-sign-in-form input[type=text] { + padding: 15px 10px; + display: block; + width: 100%; + font: inherit; + height: 52px; + border: 1px solid #aaa; + border-radius: 0; + box-shadow: none; +} +.rs-sign-in-form button.rs-connect { + padding: 15px 10px; + margin-top: 20px; + margin-bottom: 15px; + display: block; + width: 100%; + border: none; + border-radius: 3px; + background-color: #3fb34f; + font: inherit; + color: #fff; + transition: box-shadow 200ms, background-color 200ms; +} + +.rs-sign-in-form button.rs-connect:hover { + cursor: pointer; + background-color: #4BCB5D; + box-shadow: 0 1px 2px 0 rgba(0,0,0,0.1), 0 3px 8px 0 rgba(0,0,0,0.2); +} + +.rs-sign-in-form button.rs-connect:active { + background-color: #3fb34f; +} + +.rs-sign-in-form button.rs-connect:disabled, +.rs-sign-in-form button.rs-connect:disabled:hover { + background-color: #aaa; +} + +.rs-sign-in-form button.rs-connecting svg { + height: 1em; + width: auto; + vertical-align: middle; + margin-left: 0.5em; + animation: rs-spin 1s linear infinite; +} + +.rs-sign-in-error.rs-hidden, +.rs-box-error.rs-hidden { + height: 0; +} + +.rs-sign-in-error.rs-visible, +.rs-box-error.rs-visible { + height: auto; + border-radius: 3px; + padding: 0.5em 0.5em; + margin-top: 0.5em; + text-align: center; + background-color: rgba(255,0,0,0.1); + color: darkred; +} + +.rs-box-error { + display: flex; + flex-direction: row; +} + +.rs-box-error .rs-error-message { + flex: auto; +} + + /*Choose provider box */ +.rs-box-choose { + text-align: center; + overflow: hidden; +} + +.rs-box-choose p { + margin-top: 0; + margin-bottom: 20px; + line-height: 1.4em; +} + +/*Connected box */ +.rs-box-connected { + display: flex; + flex-direction: row; + height: 40px; + transition: height 0s; +} +.rs-connected-text { + flex: auto; + min-width: 0; +} +.rs-box-connected .rs-user { + font-weight: bold; + text-overflow: ellipsis; + overflow: hidden; + word-break: keep-all; +} +.rs-connected-buttons, .rs-error-buttons { + flex: none; +} +.rs-disconnect:hover { + border-color: #FF2D2D; +} +.rs-disconnect:hover .rs-icon{ + fill: #FF2D2D; +} +.rs-sync:hover { + border-color: #FFBB0C; +} +.rs-sync:hover .rs-icon { + fill: #FFBB0C; +} +.rs-sync.rs-rotate { + border-color: #FFBB0C; +} +.rs-sync.rs-rotate .rs-icon { + fill: #FFBB0C; + animation: rs-spin 1s linear infinite; +} + +/* Floating widget styles (top right corner) */ +.rs-floating { + position: fixed; + top: 0; + right: 0; +} + +@keyframes rs-spin { + 100% { + transform: rotate(360deg); + transform: rotate(360deg); + } +} + +/* Small/mobile screens */ +@media screen and (max-width: 420px) { + .rs-widget { + font-size: 100%; + transition: all 300ms ease-out; + max-width: 400px; + } + .rs-floating { + position: relative; + top: auto; + right: auto + } + .rs-closed { + max-width: 56px; + } + .rs-state-choose, + .rs-state-sign-in { + position: fixed; + top: 0; + left: 0; + right: 0; + max-width: 100%; + } +} + +/* remove dotted outline border on Firefox */ +.rs-widget a:focus, +.rs-widget a:active, +.rs-widget button:focus, +.rs-widget input:focus { + outline:none; +} +.rs-widget button::-moz-focus-inner, +.rs-widget input[type="button"]::-moz-focus-inner { + border:0; +} + +/* prevent rounded buttons on mobile Safari */ +.rs-widget button, +.rs-widget input[type="button"] { + -webkit-appearance: none; +} + +.remotestorage-widget-modal-backdrop { + display: none; + position: fixed; + top: 0; + bottom: 0; + left: 0; + right: 0; + background-color: rgba(0, 0, 0, 0.5); + opacity: 0; + transition: opacity 0.3s linear; +} + +.remotestorage-widget-modal-backdrop.visible { + opacity: 1; + transition: opacity 0.3s linear; +} +`,e.appendChild(t),e}},{key:"setModalClass",value:function(){if(this.modalBackdrop){if("onlySmallScreens"===this.modalBackdrop&&!this.isSmallScreen())return;this.rsWidget.classList.add("rs-modal")}}},{key:"setupElements",value:function(){this.rsWidget=document.querySelector(".rs-widget"),this.rsBackdrop=document.querySelector(".remotestorage-widget-modal-backdrop"),this.rsInitial=document.querySelector(".rs-box-initial"),this.rsChoose=document.querySelector(".rs-box-choose"),this.rsConnected=document.querySelector(".rs-box-connected"),this.rsSignIn=document.querySelector(".rs-box-sign-in"),this.rsConnectedLabel=document.querySelector(".rs-box-connected .rs-sub-headline"),this.rsChooseRemoteStorageButton=document.querySelector("button.rs-choose-rs"),this.rsChooseDropboxButton=document.querySelector("button.rs-choose-dropbox"),this.rsChooseGoogleDriveButton=document.querySelector("button.rs-choose-googledrive"),this.rsErrorBox=document.querySelector(".rs-box-error .rs-error-message"),this.rs.apiKeys.hasOwnProperty("googledrive")||this.rsChooseGoogleDriveButton.parentNode.removeChild(this.rsChooseGoogleDriveButton),this.rs.apiKeys.hasOwnProperty("dropbox")||this.rsChooseDropboxButton.parentNode.removeChild(this.rsChooseDropboxButton),this.rsSignInForm=document.querySelector(".rs-sign-in-form"),this.rsAddressInput=this.rsSignInForm.querySelector("input[name=rs-user-address]"),this.rsConnectButton=document.querySelector(".rs-connect"),this.rsDisconnectButton=document.querySelector(".rs-disconnect"),this.rsSyncButton=document.querySelector(".rs-sync"),this.rsLogo=document.querySelector(".rs-widget-icon"),this.rsErrorReconnectLink=document.querySelector(".rs-box-error a.rs-reconnect"),this.rsErrorDisconnectButton=document.querySelector(".rs-box-error button.rs-disconnect"),this.rsConnectedUser=document.querySelector(".rs-connected-text h1.rs-user")}},{key:"setupHandlers",value:function(){var e=this;this.rs.on("connected",function(){return e.eventHandler("connected")}),this.rs.on("ready",function(){return e.eventHandler("ready")}),this.rs.on("disconnected",function(){return e.eventHandler("disconnected")}),this.rs.on("network-online",function(){return e.eventHandler("network-online")}),this.rs.on("network-offline",function(){return e.eventHandler("network-offline")}),this.rs.on("error",function(t){return e.eventHandler("error",t)}),this.setEventListeners(),this.setClickHandlers()}},{key:"attach",value:function(e){var t,n=this.createHtmlTemplate();if(e){if(t=document.getElementById(e),!parent)throw'Failed to find target DOM element with id="'+e+'"'}else t=document.body;t.appendChild(n),this.setupElements(),this.setupHandlers(),this.setInitialState(),this.setModalClass()}},{key:"setEventListeners",value:function(){var e=this;this.rsSignInForm.addEventListener("submit",function(t){t.preventDefault();var n=document.querySelector("input[name=rs-user-address]").value;e.disableConnectButton(),e.rs.connect(n)})}},{key:"showChooseOrSignIn",value:function(){this.rsWidget.classList.contains("rs-modal")&&(this.rsBackdrop.style.display="block",this.rsBackdrop.classList.add("visible")),this.rs.apiKeys&&Object.keys(this.rs.apiKeys).length>0?this.setState("choose"):this.setState("sign-in")}},{key:"setClickHandlers",value:function(){var e=this;this.rsInitial.addEventListener("click",function(){return e.showChooseOrSignIn()}),this.rsChooseRemoteStorageButton.addEventListener("click",function(){e.setState("sign-in"),e.rsAddressInput.focus()}),this.rsChooseDropboxButton.addEventListener("click",function(){return e.rs.dropbox.connect()}),this.rsChooseGoogleDriveButton.addEventListener("click",function(){return e.rs.googledrive.connect()}),this.rsDisconnectButton.addEventListener("click",function(){return e.rs.disconnect()}),this.rsErrorReconnectLink.addEventListener("click",function(){return e.rs.reconnect()}),this.rsErrorDisconnectButton.addEventListener("click",function(){return e.rs.disconnect()}),this.rs.hasFeature("Sync")&&this.rsSyncButton.addEventListener("click",function(){e.rsSyncButton.classList.contains("rs-rotate")?(e.rs.stopSync(),e.rsSyncButton.classList.remove("rs-rotate")):(e.rsConnectedLabel.textContent="Synchronizing",e.rs.startSync(),e.rsSyncButton.classList.add("rs-rotate"))}),document.addEventListener("click",function(){return e.close()}),this.rsWidget.addEventListener("click",function(e){return e.stopPropagation()}),this.rsLogo.addEventListener("click",function(){return e.toggle()})}},{key:"toggle",value:function(){this.closed?this.open():"initial"===this.state?this.showChooseOrSignIn():this.close()}},{key:"open",value:function(){this.closed=!1,this.rsWidget.classList.remove("rs-closed"),this.shouldCloseWhenSyncDone=!1;var e=document.querySelector(".rs-box.rs-selected");e&&e.setAttribute("aria-hidden","false")}},{key:"close",value:function(){var e,t=this;"error"!==this.state&&(!this.leaveOpen&&this.active?(this.closed=!0,this.rsWidget.classList.add("rs-closed"),e=document.querySelector(".rs-box.rs-selected"),e&&e.setAttribute("aria-hidden","true")):this.active?this.setState("connected"):this.setInitialState(),this.rsWidget.classList.contains("rs-modal")&&(this.rsBackdrop.classList.remove("visible"),setTimeout(function(){t.rsBackdrop.style.display="none"},300)))}},{key:"disableConnectButton",value:function(){this.rsConnectButton.disabled=!0,this.rsConnectButton.classList.add("rs-connecting"),this.rsConnectButton.innerHTML="Connecting ".concat(` + + + + + + + +`)}},{key:"enableConnectButton",value:function(){this.rsConnectButton.disabled=!1,this.rsConnectButton.textContent="Connect",this.rsConnectButton.classList.remove("rs-connecting")}},{key:"setOffline",value:function(){this.online&&(this.rsWidget.classList.add("rs-offline"),this.rsConnectedLabel.textContent="Offline",this.online=!1)}},{key:"setOnline",value:function(){this.online||(this.rsWidget.classList.remove("rs-offline"),this.active&&(this.rsConnectedLabel.textContent="Connected")),this.online=!0}},{key:"setBackendClass",value:function(e){this.rsWidget.classList.remove("rs-backend-remotestorage"),this.rsWidget.classList.remove("rs-backend-dropbox"),this.rsWidget.classList.remove("rs-backend-googledrive"),e&&this.rsWidget.classList.add("rs-backend-".concat(e))}},{key:"showErrorBox",value:function(e){this.rsErrorBox.innerHTML=e,this.setState("error")}},{key:"hideErrorBox",value:function(){this.rsErrorBox.innerHTML="",this.close()}},{key:"handleDiscoveryError",value:function(e){var t=document.querySelector(".rs-sign-in-error");t.innerHTML=e.message,t.classList.remove("rs-hidden"),t.classList.add("rs-visible"),this.enableConnectButton()}},{key:"handleSyncError",value:function(e){console.debug('Encountered SyncError: "'.concat(e.message,'"')),this.setOffline()}},{key:"handleUnauthorized",value:function(e){e.code&&"access_denied"===e.code?this.rs.disconnect():(this.open(),this.showErrorBox(e.message+" "),this.rsErrorBox.appendChild(this.rsErrorReconnectLink),this.rsErrorReconnectLink.classList.remove("rs-hidden"))}},{key:"updateLastSyncedStatus",value:function(){var t,e=new Date;if(this.online)return this.lastSynced=e,void(this.rsConnectedLabel.textContent="Synced just now");this.lastSynced?(t=Math.round((e.getTime()-this.lastSynced.getTime())/1e3),this.rsConnectedLabel.textContent="Synced ".concat(t," seconds ago")):this.rsWidget.classList.contains("rs-state-unauthorized")||(this.rsConnectedLabel.textContent="Offline")}},{key:"isSmallScreen",value:function(){return window.innerWidth<421}}],n&&o(t.prototype,n),Object.defineProperty(t,"prototype",{writable:!1}),e}();const i=n;return t.default})()}),AFRAME.registerComponent("remotestorage",{schema:{dropbox:{type:"string",default:""},googledrive:{type:"string",default:""},leaveOpen:{type:"bool",default:!1},autoCloseAfter:{type:"number",default:1500},skipInitial:{type:"bool",default:!1},logging:{type:"bool",default:!1},modalBackdrop:{type:"string",default:"onlySmallScreens"},folder:{type:"string"},domid:{type:"string"}},init:function(){let t={};remoteStorage=this.remoteStorage=new RemoteStorage({logging:this.data.logging}),this.data.dropbox&&(t.dropbox=this.data.dropbox),this.data.googledrive&&(t.googledrive=this.data.googledrive),Object.keys(t).length&&remoteStorage.setApiKeys(t),remoteStorage.on("connected",e=>this.el.sceneEl.emit("remoteStorage.connected",e)),remoteStorage.on("network-offline",e=>this.el.sceneEl.emit("remoteStorage.network-offline",e)),remoteStorage.on("network-online",e=>this.el.sceneEl.emit("remoteStorage.network-online",e)),remoteStorage.on("error",e=>this.el.sceneEl.emit("remoteStorage.error",e)),remoteStorage.on("ready",e=>this.el.sceneEl.emit("remoteStorage.ready",e)),remoteStorage.access.claim(this.data.folder,"rw"),remoteStorage.caching.enable(`/${this.data.folder}/`);let e={...this.data};e.modalBackdrop=="false"&&(e.modalBackdrop=!1),e.modalBackdrop=="true"&&(e.modalBackdrop=!0),widget=this.widget=new Widget(remoteStorage,e),widget.attach(this.data.domid)}}) +