From 7e3c6f16e919e252d3329b7c0c72e9ed271af509 Mon Sep 17 00:00:00 2001 From: eight Date: Thu, 9 Dec 2021 00:00:30 +0800 Subject: [PATCH] Fix: bump db-to-cloud, show detailed LockError (#1361) * Bump db-to-cloud * Fix: bump db-to-cloud, show detailed LockError * Fix: used -> use * Change: drop our retry code --- _locales/en/messages.json | 8 ++++++++ background/sync-manager.js | 26 ++++++++++++++------------ package-lock.json | 14 +++++++------- package.json | 2 +- vendor/db-to-cloud/README.md | 2 +- vendor/db-to-cloud/db-to-cloud.min.js | 2 +- 6 files changed, 32 insertions(+), 22 deletions(-) diff --git a/_locales/en/messages.json b/_locales/en/messages.json index be2006e4..3411e44d 100644 --- a/_locales/en/messages.json +++ b/_locales/en/messages.json @@ -1669,6 +1669,14 @@ "message": "Sync failed.\nTry to re-login in Stylus options:\nclick 'disconnect' first, then 'connect'.", "description": "Tooltip for the toolbar icon" }, + "syncErrorLock": { + "message": "The database is already in use. The lock will expire at $TIME$", + "placeholders": { + "time": { + "content": "$1" + } + } + }, "syncStorageErrorSaving": { "message": "The value cannot be saved. Try reducing the amount of text.", "description": "Displayed when trying to save an excessively big value via storage.sync API" diff --git a/background/sync-manager.js b/background/sync-manager.js index 21a644c7..91a0753a 100644 --- a/background/sync-manager.js +++ b/background/sync-manager.js @@ -11,7 +11,6 @@ const syncMan = (() => { const SYNC_DELAY = 1; // minutes const SYNC_INTERVAL = 30; // minutes - const SYNC_LOCK_RETRIES = 10; // number of retries before the error is reported for scheduled sync const STATES = Object.freeze({ connected: 'connected', connecting: 'connecting', @@ -27,7 +26,6 @@ const syncMan = (() => { currentDriveName: null, errorMessage: null, login: false, - lockRetries: 0, }; let lastError = null; let ctrl; @@ -44,9 +42,7 @@ const syncMan = (() => { chrome.alarms.onAlarm.addListener(async ({name}) => { if (name === 'syncNow') { - await syncMan.syncNow({isScheduled: true}); - const retrying = status.lockRetries / SYNC_LOCK_RETRIES * Math.random(); - schedule(SYNC_DELAY + SYNC_INTERVAL * (retrying || 1)); + await syncMan.syncNow(); } }); @@ -143,7 +139,7 @@ const syncMan = (() => { emitStatusChange(); }, - async syncNow({isScheduled} = {}) { + async syncNow() { if (ready.then) await ready; if (!currentDrive || !status.login) { console.warn('cannot sync when disconnected'); @@ -154,18 +150,13 @@ const syncMan = (() => { status.errorMessage = null; lastError = null; } catch (err) { + err.message = translateErrorMessage(err); status.errorMessage = err.message; lastError = err; - if (isScheduled && - err.code === 409 && - ++status.lockRetries <= SYNC_LOCK_RETRIES) { - return; - } if (isGrantError(err)) { status.login = false; } } - status.lockRetries = 0; emitStatusChange(); }, }; @@ -208,6 +199,9 @@ const syncMan = (() => { setState(drive, state) { return chromeLocal.setValue(STORAGE_KEY + drive.name, state); }, + retryMaxAttempts: 10, + retryExp: 1.2, + retryDelay: 6, }); } @@ -257,8 +251,16 @@ const syncMan = (() => { function schedule(delay = SYNC_DELAY) { chrome.alarms.create('syncNow', { delayInMinutes: delay, // fractional values are supported + periodInMinutes: SYNC_INTERVAL, }); } + function translateErrorMessage(err) { + if (err.name === 'LockError') { + return browser.i18n.getMessage('syncErrorLock', new Date(err.expire).toLocaleString([], {timeStyle: 'short'})); + } + return err.message || String(err); + } + //#endregion })(); diff --git a/package-lock.json b/package-lock.json index 66d84cfa..08c78276 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,7 +10,7 @@ "license": "GPL-3.0-only", "dependencies": { "codemirror": "5.63.3", - "db-to-cloud": "^0.6.0", + "db-to-cloud": "^0.7.0", "jsonlint": "^1.6.3", "less-bundle": "github:openstyles/less-bundle#v0.1.0", "lz-string-unsafe": "^1.4.4-fork-1", @@ -2322,9 +2322,9 @@ } }, "node_modules/db-to-cloud": { - "version": "0.6.0", - "resolved": "https://registry.npmjs.org/db-to-cloud/-/db-to-cloud-0.6.0.tgz", - "integrity": "sha512-AbvxpU+fA3Fsdzu0OxL+cVPS9HwM6DzXFDg00WIQ3YeMkWs5saMXpiXMfISlkpBUwm5Cbr4W7cfhYszu38BzSw==", + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/db-to-cloud/-/db-to-cloud-0.7.0.tgz", + "integrity": "sha512-fs3FS6vMLk7E6gnuao9lJqTU+ohy6Pa9fqgZSVnoICMsCfqrnyYj+reA81xOmw9kfqVQNdtu+zZv67IJThrMvA==", "dependencies": { "@eight04/read-write-lock": "^0.1.0", "universal-base64": "^2.1.0" @@ -11501,9 +11501,9 @@ } }, "db-to-cloud": { - "version": "0.6.0", - "resolved": "https://registry.npmjs.org/db-to-cloud/-/db-to-cloud-0.6.0.tgz", - "integrity": "sha512-AbvxpU+fA3Fsdzu0OxL+cVPS9HwM6DzXFDg00WIQ3YeMkWs5saMXpiXMfISlkpBUwm5Cbr4W7cfhYszu38BzSw==", + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/db-to-cloud/-/db-to-cloud-0.7.0.tgz", + "integrity": "sha512-fs3FS6vMLk7E6gnuao9lJqTU+ohy6Pa9fqgZSVnoICMsCfqrnyYj+reA81xOmw9kfqVQNdtu+zZv67IJThrMvA==", "requires": { "@eight04/read-write-lock": "^0.1.0", "universal-base64": "^2.1.0" diff --git a/package.json b/package.json index a87f5efe..d794449a 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,7 @@ }, "dependencies": { "codemirror": "5.63.3", - "db-to-cloud": "^0.6.0", + "db-to-cloud": "^0.7.0", "jsonlint": "^1.6.3", "less-bundle": "github:openstyles/less-bundle#v0.1.0", "lz-string-unsafe": "^1.4.4-fork-1", diff --git a/vendor/db-to-cloud/README.md b/vendor/db-to-cloud/README.md index fed55581..ae4bf563 100644 --- a/vendor/db-to-cloud/README.md +++ b/vendor/db-to-cloud/README.md @@ -1,4 +1,4 @@ -## db-to-cloud v0.6.0 +## db-to-cloud v0.7.0 Following files are copied from npm (node_modules): diff --git a/vendor/db-to-cloud/db-to-cloud.min.js b/vendor/db-to-cloud/db-to-cloud.min.js index 6d46dcfe..a0d4226d 100644 --- a/vendor/db-to-cloud/db-to-cloud.min.js +++ b/vendor/db-to-cloud/db-to-cloud.min.js @@ -1,2 +1,2 @@ -var dbToCloud=function(t){"use strict";function e(t,e,n,o,r,i,c){try{var a=t[i](c),s=a.value}catch(t){return void n(t)}a.done?e(s):Promise.resolve(s).then(o,r)}function n(t){return function(){var n=this,o=arguments;return new Promise((function(r,i){var c=t.apply(n,o);function a(t){e(c,r,i,a,s,"next",t)}function s(t){e(c,r,i,a,s,"throw",t)}a(void 0)}))}}function o(t,e,n){return e in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function r(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);e&&(o=o.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,o)}return n}function i(t){for(var e=1;e=0||(r[n]=t[n]);return r}(t,e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(o=0;o=0||Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function a(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){if("undefined"==typeof Symbol||!(Symbol.iterator in Object(t)))return;var n=[],o=!0,r=!1,i=void 0;try{for(var c,a=t[Symbol.iterator]();!(o=(c=a.next()).done)&&(n.push(c.value),!e||n.length!==e);o=!0);}catch(t){r=!0,i=t}finally{try{o||null==a.return||a.return()}finally{if(r)throw i}}return n}(t,e)||s(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function s(t,e){if(t){if("string"==typeof t)return l(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?l(t,e):void 0}}function l(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,o=new Array(e);n=t.length?{done:!0}:{done:!1,value:t[o++]}},e:function(t){throw t},f:r}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,c=!0,a=!1;return{s:function(){n=t[Symbol.iterator]()},n:function(){var t=n.next();return c=t.done,t},e:function(t){a=!0,i=t},f:function(){try{c||null==n.return||n.return()}finally{if(a)throw i}}}}function p({maxActiveReader:t=1/0}={}){let e,n,o=0;const r={read:t=>i(t,!1),write:t=>i(t,!0),length:0};return r;function i(t,o){const i=function({fn:t,block:e=!1,prev:n,next:o,q:r=c(),q2:i=(t.length?c():null)}){return{fn:t,block:e,prev:n,next:o,q:r,q2:i}}({fn:t,block:o});return n?(n.next=i,i.prev=n,n=i,e||(e=n)):e=n=i,r.length++,a(),i.q.promise}function c(){const t={};return t.promise=new Promise(((e,n)=>{t.resolve=e,t.reject=n})),t}function a(){const i=e;if(!i||i.block&&i.prev||i.prev&&i.prev.block||o>=t)return;let c;i.block||o++,e=i.next;try{c=i.fn(i.q2&&i.q2.resolve)}catch(t){return i.q.reject(t),void s()}if(i.q2&&i.q2.promise.then(l),c&&c.then){const t=c.then(i.q.resolve,i.q.reject);i.q2||t.then(s)}else if(i.q.resolve(c),!i.q2)return void s();function s(){l()}function l(t){i.prev&&(i.prev.next=i.next),i.next&&(i.next.prev=i.prev),n===i&&(n=i.prev),i.block||o--,r.length--,t&&t(),a()}a()}}function f(t){let e,n=0;return()=>(n&&clearTimeout(n),n=setTimeout(o),e||(e=function(){const t={};return t.promise=new Promise(((e,n)=>{t.resolve=e,t.reject=n})),t}()),e.promise);function o(){Promise.resolve(t()).then(e.resolve,e.reject),n=0,e=null}}const d={};function h(t){return String.fromCharCode(parseInt(t.slice(1),16))}function y(t){return"%".concat("00".concat(t.charCodeAt(0).toString(16)).slice(-2))}Object.defineProperty(d,"__esModule",{value:!0}),d.encode=function(t){return btoa(encodeURIComponent(t).replace(/%[0-9A-F]{2}/g,h))},d.decode=function(t){return decodeURIComponent(Array.from(atob(t),y).join(""))};class g extends Error{constructor(t,e,n=e&&e.status){super(t),this.code=n,this.origin=e,Error.captureStackTrace&&Error.captureStackTrace(this,g)}}function v(t){return new Promise((e=>setTimeout(e,t)))}function m({fetch:t,cooldown:e=0,getAccessToken:o}){const r=p();return t=>r.write(function(){var o=n((function*(n){try{return yield function(t){return a.apply(this,arguments)}(t)}finally{e&&t.method&&"GET"!==t.method?setTimeout(n,e):n()}}));return function(t){return o.apply(this,arguments)}}());function a(){return(a=n((function*(e){let n=e.path,r=e.contentType,a=e.headers,s=e.format,l=c(e,["path","contentType","headers","format"]);const u={Authorization:"Bearer ".concat(yield o())};for(r&&(u["Content-Type"]=r),Object.assign(u,a);;){const e=yield t(n,i({headers:u},l));if(!e.ok){const t=e.headers.get("Retry-After");if(t){const e=Number(t);if(e){yield v(1e3*e);continue}}const n=yield e.text();throw new g("failed to fetch [".concat(e.status,"]: ").concat(n),e)}if(s)return yield e[s]();const o=e.headers.get("Content-Type");return/application\/json/.test(o)?yield e.json():yield e.text()}}))).apply(this,arguments)}}var b=Object.freeze({__proto__:null,fsDrive:()=>{},github:function({userAgent:t="db-to-cloud",owner:e,repo:o,getAccessToken:r,fetch:i=("undefined"!=typeof self?self:global).fetch}){const c=m({fetch:i,getAccessToken:r,cooldown:1e3}),a=new Map;return{name:"github",get:p,put:h,post:function(t,e){return h(t,e,!1)},delete:function(t){return g.apply(this,arguments)},list:function(t){return l.apply(this,arguments)},shaCache:a};function s(e){return e.headers||(e.headers={}),e.headers["User-Agent"]||(e.headers["User-Agent"]=t),e.headers.Accept||(e.headers.Accept="application/vnd.github.v3+json"),e.path="https://api.github.com".concat(e.path),c(e)}function l(){return(l=n((function*(t){const n=[];var r,i=u(yield s({path:"/repos/".concat(e,"/").concat(o,"/contents/").concat(t)}));try{for(i.s();!(r=i.n()).done;){const t=r.value;n.push(t.name),a.set(t.path,t.sha)}}catch(t){i.e(t)}finally{i.f()}return n}))).apply(this,arguments)}function p(t){return f.apply(this,arguments)}function f(){return(f=n((function*(t){const n=yield s({path:"/repos/".concat(e,"/").concat(o,"/contents/").concat(t)});return a.set(n.path,n.sha),d.decode(n.content)}))).apply(this,arguments)}function h(t,e){return y.apply(this,arguments)}function y(){return(y=n((function*(t,n,r=!0){const i={message:"",content:d.encode(n)};r&&a.has(t)&&(i.sha=a.get(t));const c={method:"PUT",path:"/repos/".concat(e,"/").concat(o,"/contents/").concat(t),contentType:"application/json",body:JSON.stringify(i)};let l,u=!1;for(;!l;){try{l=yield s(c)}catch(e){if(422!==e.code||!e.message.includes('\\"sha\\" wasn\'t supplied'))throw e;if(!r||u)throw e.code="EEXIST",e;yield p(t)}u=!0}a.set(t,l.content.sha)}))).apply(this,arguments)}function g(){return(g=n((function*(t){try{let n=a.get(t);n||(yield p(t),n=a.get(t)),yield s({method:"DELETE",path:"/repos/".concat(e,"/").concat(o,"/contents/").concat(t),body:JSON.stringify({message:"",sha:n})})}catch(t){if(404===t.code)return;throw t}}))).apply(this,arguments)}},dropbox:function({getAccessToken:t,fetch:e=("undefined"!=typeof self?self:global).fetch}){const o=m({fetch:e,getAccessToken:t});return{name:"dropbox",get:function(t){return l.apply(this,arguments)},put:p,post:function(t,e){return d.apply(this,arguments)},delete:function(t){return h.apply(this,arguments)},list:function(t){return a.apply(this,arguments)}};function r(t){let e=t.path,n=t.body,r=c(t,["path","body"]);return o(i({method:"POST",path:"https://api.dropboxapi.com/2/".concat(e),contentType:"application/json",body:JSON.stringify(n)},r))}function a(){return(a=n((function*(t){const e=[];let n=yield r({path:"files/list_folder",body:{path:"/".concat(t)}});var o,i=u(n.entries);try{for(i.s();!(o=i.n()).done;){const t=o.value;e.push(t.name)}}catch(t){i.e(t)}finally{i.f()}if(!n.has_more)return e;for(;n.has_more;){n=yield r({path:"files/list_folder/continue",body:{cursor:n.cursor}});var c,a=u(n.entries);try{for(a.s();!(c=a.n()).done;){const t=c.value;e.push(t.name)}}catch(t){a.e(t)}finally{a.f()}}return e}))).apply(this,arguments)}function s(t){const e=new URLSearchParams;return e.set("arg",JSON.stringify(t)),e.toString()}function l(){return(l=n((function*(t){const e={path:"/".concat(t)};try{return yield o({path:"https://content.dropboxapi.com/2/files/download?".concat(s(e)),format:"text"})}catch(t){throw 409===t.code&&t.message.includes("not_found")&&(t.code="ENOENT"),t}}))).apply(this,arguments)}function p(t,e){return f.apply(this,arguments)}function f(){return(f=n((function*(t,e,n="overwrite"){const r={path:"/".concat(t),mode:n,autorename:!1,mute:!0};yield o({path:"https://content.dropboxapi.com/2/files/upload?".concat(s(r)),method:"POST",contentType:"application/octet-stream",body:e})}))).apply(this,arguments)}function d(){return(d=n((function*(t,e){try{return yield p(t,e,"add")}catch(t){throw 409===t.code&&t.message.includes("conflict")&&(t.code="EEXIST"),t}}))).apply(this,arguments)}function h(){return(h=n((function*(t){try{yield r({path:"files/delete_v2",body:{path:"/".concat(t)}})}catch(t){if(409===t.code&&t.message.includes("not_found"))return;throw t}}))).apply(this,arguments)}},onedrive:function({getAccessToken:t,fetch:e=("undefined"!=typeof self?self:global).fetch}){const o=m({fetch:e,getAccessToken:t});return{name:"onedrive",get:function(t){return a.apply(this,arguments)},put:function(t,e){return s.apply(this,arguments)},post:function(t,e){return l.apply(this,arguments)},delete:function(t){return u.apply(this,arguments)},list:function(t){return c.apply(this,arguments)}};function r(t){return i.apply(this,arguments)}function i(){return(i=n((function*(t){return t.path="https://graph.microsoft.com/v1.0/me/drive/special/approot".concat(t.path),yield o(t)}))).apply(this,arguments)}function c(){return(c=n((function*(t){t&&(t=":/".concat(t,":"));let e=yield r({path:"".concat(t,"/children?select=name")}),n=e.value.map((t=>t.name));for(;e["@odata.nextLink"];)e=yield o({path:e["@odata.nextLink"]}),n=n.concat(e.value.map((t=>t.name)));return n}))).apply(this,arguments)}function a(){return(a=n((function*(t){return yield r({path:":/".concat(t,":/content"),format:"text"})}))).apply(this,arguments)}function s(){return(s=n((function*(t,e){yield r({method:"PUT",path:":/".concat(t,":/content"),headers:{"Content-Type":"text/plain"},body:e})}))).apply(this,arguments)}function l(){return(l=n((function*(t,e){try{yield r({method:"PUT",path:":/".concat(t,":/content?@microsoft.graph.conflictBehavior=fail"),headers:{"Content-Type":"text/plain"},body:e})}catch(t){throw 409===t.code&&t.message.includes("nameAlreadyExists")&&(t.code="EEXIST"),t}}))).apply(this,arguments)}function u(){return(u=n((function*(t){try{yield r({method:"DELETE",path:":/".concat(t,":")})}catch(t){if(404===t.code)return;throw t}}))).apply(this,arguments)}},google:function({getAccessToken:t,fetch:e=("undefined"!=typeof self?self:global).fetch,FormData:o=("undefined"!=typeof self?self:global).FormData,Blob:r=("undefined"!=typeof self?self:global).Blob}){const i=m({fetch:e,getAccessToken:t}),c=new Map;let a;return{name:"google",get:function(t){return O.apply(this,arguments)},put:function(t,e){return k.apply(this,arguments)},post:E,delete:function(t){return S.apply(this,arguments)},list:function(t){return j.apply(this,arguments)},init:function(){return T.apply(this,arguments)},acquireLock:function(t){return p.apply(this,arguments)},releaseLock:function(){return f.apply(this,arguments)},fileMetaCache:c};function s(t,e){return l.apply(this,arguments)}function l(){return(l=n((function*(t,e){yield i({method:"DELETE",path:"https://www.googleapis.com/drive/v3/files/".concat(t,"/revisions/").concat(e)})}))).apply(this,arguments)}function p(){return(p=n((function*(t){const e=c.get("lock.json"),n=(yield y(e.id,JSON.stringify({expire:Date.now()+60*t*1e3}))).headRevisionId,o=yield i({path:"https://www.googleapis.com/drive/v3/files/".concat(e.id,"/revisions?fields=revisions(id)")});for(let t=1;tDate.now())throw yield s(e.id,n),new g("failed to acquire lock",null,"EEXIST");yield s(e.id,r)}throw new Error("cannot find lock revision")}))).apply(this,arguments)}function f(){return(f=n((function*(){const t=c.get("lock.json");yield s(t.id,a),a=null}))).apply(this,arguments)}function d(t,e){return h.apply(this,arguments)}function h(){return(h=n((function*(t,e){t="https://www.googleapis.com/drive/v3/files?spaces=appDataFolder&fields=nextPageToken,files(id,name,headRevisionId)"+(t?"&"+t:"");let n=yield i({path:t});for(e(n);n.nextPageToken;)n=yield i({path:"".concat(t,"&pageToken=").concat(n.nextPageToken)}),e(n)}))).apply(this,arguments)}function y(t,e){return v.apply(this,arguments)}function v(){return(v=n((function*(t,e){return yield i({method:"PATCH",path:"https://www.googleapis.com/upload/drive/v3/files/".concat(t,"?uploadType=media&fields=headRevisionId"),headers:{"Content-Type":"text/plain"},body:e})}))).apply(this,arguments)}function b(t){return w.apply(this,arguments)}function w(){return(w=n((function*(t){t&&(t="q=".concat(encodeURIComponent(t))),yield d(t,(t=>{var e,n=u(t.files);try{for(n.s();!(e=n.n()).done;){const t=e.value;c.set(t.name,t)}}catch(t){n.e(t)}finally{n.f()}}))}))).apply(this,arguments)}function T(){return(T=n((function*(){yield b(),c.has("lock.json")||(yield E("lock.json","{}")),c.has("meta.json")||(yield E("meta.json","{}"))}))).apply(this,arguments)}function j(){return(j=n((function*(t){return[...c.values()].filter((e=>e.name.startsWith(t+"/"))).map((t=>t.name.split("/")[1]))}))).apply(this,arguments)}function O(){return(O=n((function*(t){let e=c.get(t);if(!e&&(yield b("name = '".concat(t,"'")),e=c.get(t),!e))throw new g("metaCache doesn't contain ".concat(t),null,"ENOENT");try{return yield i({path:"https://www.googleapis.com/drive/v3/files/".concat(e.id,"?alt=media")})}catch(t){throw 404===t.code&&(t.code="ENOENT"),t}}))).apply(this,arguments)}function k(){return(k=n((function*(t,e){if(!c.has(t))return yield E(t,e);const n=c.get(t),o=yield y(n.id,e);n.headRevisionId=o.headRevisionId}))).apply(this,arguments)}function E(t,e){return C.apply(this,arguments)}function C(){return(C=n((function*(t,e){const n=new o,a={name:t,parents:["appDataFolder"]};n.append("metadata",new r([JSON.stringify(a)],{type:"application/json; charset=UTF-8"})),n.append("media",new r([e],{type:"text/plain"}));const s=yield i({method:"POST",path:"https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&fields=id,name,headRevisionId",body:n});c.set(s.name,s)}))).apply(this,arguments)}function S(){return(S=n((function*(t){const e=c.get(t);if(e)try{yield i({method:"DELETE",path:"https://www.googleapis.com/drive/v3/files/".concat(e.id)})}catch(t){if(404===t.code)return;throw t}}))).apply(this,arguments)}}});return t.dbToCloud=function({onGet:t,onPut:e,onDelete:o,onFirstSync:r,onWarn:i=console.error,onProgress:c,compareRevision:s,getState:l,setState:d,lockExpire:h=60}){let y,g,v;const m=new Map,b=f((()=>d(y,g))),w=new Map,T=p();return{use:function(t){y=function(t){const e=Object.create(t);return e.get=function(){var e=n((function*(e){return JSON.parse(yield t.get(e))}));return function(t){return e.apply(this,arguments)}}(),e.put=function(){var e=n((function*(e,n){return yield t.put(e,JSON.stringify(n))}));return function(t,n){return e.apply(this,arguments)}}(),e.post=function(){var e=n((function*(e,n){return yield t.post(e,JSON.stringify(n))}));return function(t,n){return e.apply(this,arguments)}}(),e.isInit=!1,e.acquireLock||(e.acquireLock=function(t){return o.apply(this,arguments)},e.releaseLock=function(){return r.apply(this,arguments)}),e.getMeta||(e.getMeta=function(){return i.apply(this,arguments)},e.putMeta=function(t){return c.apply(this,arguments)}),e.peekChanges||(e.peekChanges=function(t){return a.apply(this,arguments)}),e;function o(){return(o=n((function*(t){try{yield this.post("lock.json",{expire:Date.now()+60*t*1e3})}catch(t){if("EEXIST"===t.code){const t=yield this.get("lock.json");Date.now()>t.expire&&(yield this.delete("lock.json"))}throw t}}))).apply(this,arguments)}function r(){return(r=n((function*(){yield this.delete("lock.json")}))).apply(this,arguments)}function i(){return(i=n((function*(){try{return yield this.get("meta.json")}catch(t){if("ENOENT"===t.code||404===t.code)return{};throw t}}))).apply(this,arguments)}function c(){return(c=n((function*(t){yield this.put("meta.json",t)}))).apply(this,arguments)}function a(){return(a=n((function*(t){return(yield this.getMeta()).lastChange!==t.lastChange}))).apply(this,arguments)}}(t)},init:function(){return T.write(n((function*(){if(!g||!g.enabled){if(!y)throw new Error("cloud drive is undefined");g=(yield l(y))||{},g.enabled=!0,g.queue||(g.queue=[])}})))},uninit:function(){return T.write(n((function*(){g&&g.enabled&&(g=v=null,m.clear(),w.clear(),y.uninit&&y.isInit&&(yield y.uninit(),y.isInit=!1),yield b())})))},put:function(t,e){if(!g||!g.enabled)return;g.queue.push({_id:t,_rev:e,action:"put"}),b()},delete:function(t,e){if(!g||!g.enabled)return;g.queue.push({_id:t,_rev:e,action:"delete"}),b()},syncNow:function(t){return T.write(n((function*(){if(!g||!g.enabled)throw new Error("Cannot sync now, the sync is not enabled");y.init&&!y.isInit&&(yield y.init(),y.isInit=!0),null==g.lastChange&&(yield r()),yield function(){return x.apply(this,arguments)}(t)})))},drive:()=>y,isInit:()=>Boolean(g&&g.enabled)};function j(){return O.apply(this,arguments)}function O(){return(O=n((function*(){if(v=yield y.getMeta(),!v.lastChange||v.lastChange===g.lastChange)return;let t=[];if(g.lastChange){const e=Math.floor((v.lastChange-1)/100);let n=Math.floor(g.lastChange/100);for(;n<=e;){const e=yield y.get("changes/".concat(n,".json"));m.set(n,e),t=t.concat(e),n++}t=t.slice(g.lastChange%100)}else t=(yield y.list("docs")).map((t=>({action:"put",_id:t.slice(0,-5)})));const n=new Map;var r,s=u(t);try{for(s.s();!(r=s.n()).done;){const t=r.value;n.set(t._id,t)}}catch(t){s.e(t)}finally{s.f()}let l=0;var p,f=u(n);try{for(f.s();!(p=f.n()).done;){const t=a(p.value,2),r=t[0],s=t[1];let u,f;if(c&&c({phase:"pull",total:n.size,loaded:l,change:s}),"delete"===s.action)yield o(r,s._rev);else if("put"===s.action){try{var d=yield y.get("docs/".concat(r,".json"));u=d.doc,f=d._rev}catch(t){if("ENOENT"===t.code||404===t.code){i("Cannot find ".concat(r,". Is it deleted without updating the history?")),l++;continue}throw t}yield e(u)}const h=s._rev||f;h&&w.set(r,h),l++}}catch(t){f.e(t)}finally{f.f()}g.lastChange=v.lastChange,yield b()}))).apply(this,arguments)}function k(){return E.apply(this,arguments)}function E(){return(E=n((function*(){if(!g.queue.length)return;const e=g.queue.slice(),n=new Map;var o,r=u(e);try{for(r.s();!(o=r.n()).done;){const t=o.value;n.set(t._id,t)}}catch(t){r.e(t)}finally{r.f()}const i=[];var a,l=u(n.values());try{for(l.s();!(a=l.n()).done;){const t=a.value,e=w.get(t._id);void 0!==e&&s(t._rev,e)<=0||i.push(t)}}catch(t){l.e(t)}finally{l.f()}let p,f,d=0;for(var h=0,T=i;h=0||(r[n]=t[n]);return r}(t,e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(o=0;o=0||Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function a(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var n=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null==n)return;var o,r,i=[],c=!0,a=!1;try{for(n=n.call(t);!(c=(o=n.next()).done)&&(i.push(o.value),!e||i.length!==e);c=!0);}catch(t){a=!0,r=t}finally{try{c||null==n.return||n.return()}finally{if(a)throw r}}return i}(t,e)||s(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function s(t,e){if(t){if("string"==typeof t)return l(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?l(t,e):void 0}}function l(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,o=new Array(e);n=t.length?{done:!0}:{done:!1,value:t[o++]}},e:function(t){throw t},f:r}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,c=!0,a=!1;return{s:function(){n=n.call(t)},n:function(){var t=n.next();return c=t.done,t},e:function(t){a=!0,i=t},f:function(){try{c||null==n.return||n.return()}finally{if(a)throw i}}}}function p({maxActiveReader:t=1/0}={}){let e,n,o=0;const r={read:t=>i(t,!1),write:t=>i(t,!0),length:0};return r;function i(t,o){const i=function({fn:t,block:e=!1,prev:n,next:o,q:r=c(),q2:i=(t.length?c():null)}){return{fn:t,block:e,prev:n,next:o,q:r,q2:i}}({fn:t,block:o});return n?(n.next=i,i.prev=n,n=i,e||(e=n)):e=n=i,r.length++,a(),i.q.promise}function c(){const t={};return t.promise=new Promise(((e,n)=>{t.resolve=e,t.reject=n})),t}function a(){const i=e;if(!i||i.block&&i.prev||i.prev&&i.prev.block||o>=t)return;let c;i.block||o++,e=i.next;try{c=i.fn(i.q2&&i.q2.resolve)}catch(t){return i.q.reject(t),void s()}if(i.q2&&i.q2.promise.then(l),c&&c.then){const t=c.then(i.q.resolve,i.q.reject);i.q2||t.then(s)}else if(i.q.resolve(c),!i.q2)return void s();function s(){l()}function l(t){i.prev&&(i.prev.next=i.next),i.next&&(i.next.prev=i.prev),n===i&&(n=i.prev),i.block||o--,r.length--,t&&t(),a()}a()}}class f extends Error{constructor(t){super("The database is locked. Will expire at ".concat(new Date(t).toLocaleString())),this.expire=t,this.name="LockError",Error.captureStackTrace&&Error.captureStackTrace(this,f)}}function h(t){let e,n=0;return()=>(n&&clearTimeout(n),n=setTimeout(o),e||(e=function(){const t={};return t.promise=new Promise(((e,n)=>{t.resolve=e,t.reject=n})),t}()),e.promise);function o(){Promise.resolve(t()).then(e.resolve,e.reject),n=0,e=null}}function d(t){return new Promise((e=>setTimeout(e,t)))}function y(t){return String.fromCharCode(parseInt(t.slice(1),16))}function g(t){return btoa(encodeURIComponent(t).replace(/%[0-9A-F]{2}/g,y))}function m(t){return"%".concat("00".concat(t.charCodeAt(0).toString(16)).slice(-2))}function v(t){return decodeURIComponent(Array.from(atob(t),m).join(""))}const w=["path","contentType","headers","format","raw"];class b extends Error{constructor(t,e,n=e&&e.status){super(t),this.code=n,this.origin=e,Error.captureStackTrace&&Error.captureStackTrace(this,b)}}function T({fetch:t,cooldown:e=0,getAccessToken:o,username:i,password:a}){const s=p(),l=i||a?"Basic ".concat(g("".concat(i,":").concat(a))):null;return t=>s.write(function(){var n=r((function*(n){try{return yield function(t){return u.apply(this,arguments)}(t)}finally{e&&t.method&&"GET"!==t.method?setTimeout(n,e):n()}}));return function(t){return n.apply(this,arguments)}}());function u(){return(u=r((function*(e){let r=e.path,i=e.contentType,a=e.headers,s=e.format,u=e.raw,p=void 0!==u&&u,f=c(e,w);const h={};for(o&&(h.Authorization="Bearer ".concat(yield o())),l&&(h.Authorization=l),i&&(h["Content-Type"]=i),Object.assign(h,a);;){const e=yield t(r,n({headers:h},f));if(!e.ok){const t=e.headers.get("Retry-After");if(t){const e=Number(t);if(e){yield d(1e3*e);continue}}const n=yield e.text();throw new b("failed to fetch [".concat(e.status,"]: ").concat(n),e)}if(p)return e;if(s)return yield e[s]();const o=e.headers.get("Content-Type");return/application\/json/.test(o)?yield e.json():yield e.text()}}))).apply(this,arguments)}}const E=["path","body"];function O(t){const e=t.replace(/[/\\][^/\\]+\/?$/,"");return e===t?".":e}const j=["path"];function k(t){return Array.isArray(t)?t:[t]}function x(t){const e=Array.prototype.filter.call(t.childNodes,(t=>1===t.nodeType));if(!e.length)return t.textContent;const n={};var o,r=u(e);try{for(r.s();!(o=r.n()).done;){const t=o.value,e=x(t);if(n[t.localName])if(Array.isArray(n[t.localName]))n[t.localName].push(e);else{const o=[n[t.localName]];o.push(e),n[t.localName]=o}else n[t.localName]=e}}catch(t){r.e(t)}finally{r.f()}return n}var C=Object.freeze({__proto__:null,fsDrive:()=>{},github:function({userAgent:t="db-to-cloud",owner:e,repo:n,getAccessToken:o,fetch:i=("undefined"!=typeof self?self:global).fetch}){const c=T({fetch:i,getAccessToken:o,cooldown:1e3}),a=new Map;return{name:"github",get:p,put:h,post:function(t,e){return h(t,e,!1)},delete:function(t){return y.apply(this,arguments)},list:function(t){return l.apply(this,arguments)},shaCache:a};function s(e){return e.headers||(e.headers={}),e.headers["User-Agent"]||(e.headers["User-Agent"]=t),e.headers.Accept||(e.headers.Accept="application/vnd.github.v3+json"),e.path="https://api.github.com".concat(e.path),c(e)}function l(){return(l=r((function*(t){const o=[];var r,i=u(yield s({path:"/repos/".concat(e,"/").concat(n,"/contents/").concat(t)}));try{for(i.s();!(r=i.n()).done;){const t=r.value;o.push(t.name),a.set(t.path,t.sha)}}catch(t){i.e(t)}finally{i.f()}return o}))).apply(this,arguments)}function p(t){return f.apply(this,arguments)}function f(){return(f=r((function*(t){const o=yield s({path:"/repos/".concat(e,"/").concat(n,"/contents/").concat(t)});return a.set(o.path,o.sha),v(o.content)}))).apply(this,arguments)}function h(t,e){return d.apply(this,arguments)}function d(){return(d=r((function*(t,o,r=!0){const i={message:"",content:g(o)};r&&a.has(t)&&(i.sha=a.get(t));const c={method:"PUT",path:"/repos/".concat(e,"/").concat(n,"/contents/").concat(t),contentType:"application/json",body:JSON.stringify(i)};let l,u=!1;for(;!l;){try{l=yield s(c)}catch(e){if(422!==e.code||!e.message.includes('\\"sha\\" wasn\'t supplied'))throw e;if(!r||u)throw e.code="EEXIST",e;yield p(t)}u=!0}a.set(t,l.content.sha)}))).apply(this,arguments)}function y(){return(y=r((function*(t){try{let o=a.get(t);o||(yield p(t),o=a.get(t)),yield s({method:"DELETE",path:"/repos/".concat(e,"/").concat(n,"/contents/").concat(t),body:JSON.stringify({message:"",sha:o})})}catch(t){if(404===t.code)return;throw t}}))).apply(this,arguments)}},dropbox:function({getAccessToken:t,fetch:e=("undefined"!=typeof self?self:global).fetch}){const o=T({fetch:e,getAccessToken:t});return{name:"dropbox",get:function(t){return l.apply(this,arguments)},put:p,post:function(t,e){return h.apply(this,arguments)},delete:function(t){return d.apply(this,arguments)},list:function(t){return a.apply(this,arguments)}};function i(t){let e=t.path,r=t.body,i=c(t,E);return o(n({method:"POST",path:"https://api.dropboxapi.com/2/".concat(e),contentType:"application/json",body:JSON.stringify(r)},i))}function a(){return(a=r((function*(t){const e=[];let n=yield i({path:"files/list_folder",body:{path:"/".concat(t)}});var o,r=u(n.entries);try{for(r.s();!(o=r.n()).done;){const t=o.value;e.push(t.name)}}catch(t){r.e(t)}finally{r.f()}if(!n.has_more)return e;for(;n.has_more;){n=yield i({path:"files/list_folder/continue",body:{cursor:n.cursor}});var c,a=u(n.entries);try{for(a.s();!(c=a.n()).done;){const t=c.value;e.push(t.name)}}catch(t){a.e(t)}finally{a.f()}}return e}))).apply(this,arguments)}function s(t){const e=new URLSearchParams;return e.set("arg",JSON.stringify(t)),e.toString()}function l(){return(l=r((function*(t){const e={path:"/".concat(t)};try{return yield o({path:"https://content.dropboxapi.com/2/files/download?".concat(s(e)),format:"text"})}catch(t){throw 409===t.code&&t.message.includes("not_found")&&(t.code="ENOENT"),t}}))).apply(this,arguments)}function p(t,e){return f.apply(this,arguments)}function f(){return(f=r((function*(t,e,n="overwrite"){const r={path:"/".concat(t),mode:n,autorename:!1,mute:!0};yield o({path:"https://content.dropboxapi.com/2/files/upload?".concat(s(r)),method:"POST",contentType:"application/octet-stream",body:e})}))).apply(this,arguments)}function h(){return(h=r((function*(t,e){try{return yield p(t,e,"add")}catch(t){throw 409===t.code&&t.message.includes("conflict")&&(t.code="EEXIST"),t}}))).apply(this,arguments)}function d(){return(d=r((function*(t){try{yield i({path:"files/delete_v2",body:{path:"/".concat(t)}})}catch(t){if(409===t.code&&t.message.includes("not_found"))return;throw t}}))).apply(this,arguments)}},onedrive:function({getAccessToken:t,fetch:e=("undefined"!=typeof self?self:global).fetch}){const n=T({fetch:e,getAccessToken:t});return{name:"onedrive",get:function(t){return a.apply(this,arguments)},put:function(t,e){return s.apply(this,arguments)},post:function(t,e){return l.apply(this,arguments)},delete:function(t){return u.apply(this,arguments)},list:function(t){return c.apply(this,arguments)}};function o(t){return i.apply(this,arguments)}function i(){return(i=r((function*(t){return t.path="https://graph.microsoft.com/v1.0/me/drive/special/approot".concat(t.path),yield n(t)}))).apply(this,arguments)}function c(){return(c=r((function*(t){t&&(t=":/".concat(t,":"));let e=yield o({path:"".concat(t,"/children?select=name")}),r=e.value.map((t=>t.name));for(;e["@odata.nextLink"];)e=yield n({path:e["@odata.nextLink"]}),r=r.concat(e.value.map((t=>t.name)));return r}))).apply(this,arguments)}function a(){return(a=r((function*(t){return yield o({path:":/".concat(t,":/content"),format:"text"})}))).apply(this,arguments)}function s(){return(s=r((function*(t,e){yield o({method:"PUT",path:":/".concat(t,":/content"),headers:{"Content-Type":"text/plain"},body:e})}))).apply(this,arguments)}function l(){return(l=r((function*(t,e){try{yield o({method:"PUT",path:":/".concat(t,":/content?@microsoft.graph.conflictBehavior=fail"),headers:{"Content-Type":"text/plain"},body:e})}catch(t){throw 409===t.code&&t.message.includes("nameAlreadyExists")&&(t.code="EEXIST"),t}}))).apply(this,arguments)}function u(){return(u=r((function*(t){try{yield o({method:"DELETE",path:":/".concat(t,":")})}catch(t){if(404===t.code)return;throw t}}))).apply(this,arguments)}},google:function({getAccessToken:t,fetch:e=("undefined"!=typeof self?self:global).fetch,FormData:n=("undefined"!=typeof self?self:global).FormData,Blob:o=("undefined"!=typeof self?self:global).Blob}){const i=T({fetch:e,getAccessToken:t}),c=new Map;let a;return{name:"google",get:function(t){return j.apply(this,arguments)},put:function(t,e){return k.apply(this,arguments)},post:x,delete:function(t){return S.apply(this,arguments)},list:function(t){return O.apply(this,arguments)},init:function(){return E.apply(this,arguments)},acquireLock:function(t){return p.apply(this,arguments)},releaseLock:function(){return h.apply(this,arguments)},fileMetaCache:c};function s(t,e){return l.apply(this,arguments)}function l(){return(l=r((function*(t,e){yield i({method:"DELETE",path:"https://www.googleapis.com/drive/v3/files/".concat(t,"/revisions/").concat(e)})}))).apply(this,arguments)}function p(){return(p=r((function*(t){const e=c.get("lock.json"),n=(yield g(e.id,JSON.stringify({expire:Date.now()+60*t*1e3}))).headRevisionId,o=yield i({path:"https://www.googleapis.com/drive/v3/files/".concat(e.id,"/revisions?fields=revisions(id)")});for(let t=1;tDate.now())throw yield s(e.id,n),new f(c.expire);yield s(e.id,r)}throw new Error("cannot find lock revision")}))).apply(this,arguments)}function h(){return(h=r((function*(){const t=c.get("lock.json");yield s(t.id,a),a=null}))).apply(this,arguments)}function d(t,e){return y.apply(this,arguments)}function y(){return(y=r((function*(t,e){t="https://www.googleapis.com/drive/v3/files?spaces=appDataFolder&fields=nextPageToken,files(id,name,headRevisionId)"+(t?"&"+t:"");let n=yield i({path:t});for(e(n);n.nextPageToken;)n=yield i({path:"".concat(t,"&pageToken=").concat(n.nextPageToken)}),e(n)}))).apply(this,arguments)}function g(t,e){return m.apply(this,arguments)}function m(){return(m=r((function*(t,e){return yield i({method:"PATCH",path:"https://www.googleapis.com/upload/drive/v3/files/".concat(t,"?uploadType=media&fields=headRevisionId"),headers:{"Content-Type":"text/plain"},body:e})}))).apply(this,arguments)}function v(t){return w.apply(this,arguments)}function w(){return(w=r((function*(t){t&&(t="q=".concat(encodeURIComponent(t))),yield d(t,(t=>{var e,n=u(t.files);try{for(n.s();!(e=n.n()).done;){const t=e.value;c.set(t.name,t)}}catch(t){n.e(t)}finally{n.f()}}))}))).apply(this,arguments)}function E(){return(E=r((function*(){yield v(),c.has("lock.json")||(yield x("lock.json","{}")),c.has("meta.json")||(yield x("meta.json","{}"))}))).apply(this,arguments)}function O(){return(O=r((function*(t){return[...c.values()].filter((e=>e.name.startsWith(t+"/"))).map((t=>t.name.split("/")[1]))}))).apply(this,arguments)}function j(){return(j=r((function*(t){let e=c.get(t);if(!e&&(yield v("name = '".concat(t,"'")),e=c.get(t),!e))throw new b("metaCache doesn't contain ".concat(t),null,"ENOENT");try{return yield i({path:"https://www.googleapis.com/drive/v3/files/".concat(e.id,"?alt=media")})}catch(t){throw 404===t.code&&(t.code="ENOENT"),t}}))).apply(this,arguments)}function k(){return(k=r((function*(t,e){if(!c.has(t))return yield x(t,e);const n=c.get(t),o=yield g(n.id,e);n.headRevisionId=o.headRevisionId}))).apply(this,arguments)}function x(t,e){return C.apply(this,arguments)}function C(){return(C=r((function*(t,e){const r=new n,a={name:t,parents:["appDataFolder"]};r.append("metadata",new o([JSON.stringify(a)],{type:"application/json; charset=UTF-8"})),r.append("media",new o([e],{type:"text/plain"}));const s=yield i({method:"POST",path:"https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&fields=id,name,headRevisionId",body:r});c.set(s.name,s)}))).apply(this,arguments)}function S(){return(S=r((function*(t){const e=c.get(t);if(e)try{yield i({method:"DELETE",path:"https://www.googleapis.com/drive/v3/files/".concat(e.id)})}catch(t){if(404===t.code)return;throw t}}))).apply(this,arguments)}},webdav:function({username:t,password:e,url:o,fetch:i=("undefined"!=typeof self?self:global).fetch,DOMParser:a=("undefined"!=typeof self?self:global).DOMParser}){o.endsWith("/")||(o+="/");const s=T({fetch:i,username:t,password:e});return{name:"webdav",get:function(t){return h.apply(this,arguments)},put:function(t,e){return d.apply(this,arguments)},post:function(t,e){return m.apply(this,arguments)},delete:function(t){return v.apply(this,arguments)},list:function(t){return f.apply(this,arguments)}};function l(t){return p.apply(this,arguments)}function p(){return(p=r((function*(t){let e=t.path,r=c(t,j);const i=yield s(n({path:"".concat(o).concat(e)},r));if(r.format||"string"!=typeof i||!i)return i;const l=x((new a).parseFromString(i,"application/xml"));if(l.error)throw new Error("Failed requesting DAV at ".concat(o).concat(e,": ").concat(JSON.stringify(l.error)));if(l.multistatus){l.multistatus.response=k(l.multistatus.response);var p,f=u(l.multistatus.response);try{for(f.s();!(p=f.n()).done;){const t=p.value;if(t.error)throw new Error("Failed requesting DAV at ".concat(o).concat(e,": ").concat(t.href," ").concat(t.error))}}catch(t){f.e(t)}finally{f.f()}}return l}))).apply(this,arguments)}function f(){return(f=r((function*(t){t.endsWith("/")||(t+="/");const e=[];var n,r=u(k((yield l({method:"PROPFIND",path:t,contentType:"application/xml",body:' \n \n \n ',headers:{Depth:"1"}})).multistatus.response));try{for(r.s();!(n=r.n()).done;){const r=n.value;if(k(r.propstat).some((t=>t.prop.resourcetype&&void 0!==t.prop.resourcetype.collection)))continue;const i="".concat(o).concat(t),c=new URL(r.href,i).href.slice(i.length);e.push(c)}}catch(t){r.e(t)}finally{r.f()}return e}))).apply(this,arguments)}function h(){return(h=r((function*(t){return yield l({method:"GET",path:t,format:"text"})}))).apply(this,arguments)}function d(){return(d=r((function*(t,e){return yield y(O(t),(()=>l({method:"PUT",path:t,contentType:"application/octet-stream",body:e})))}))).apply(this,arguments)}function y(t,e){return g.apply(this,arguments)}function g(){return(g=r((function*(t,e){try{return yield e()}catch(e){if(409!==e.code&&404!==e.code||"."===t)throw e}return yield y(O(t),(()=>l({method:"MKCOL",path:t}))),yield e()}))).apply(this,arguments)}function m(){return(m=r((function*(t,e){try{return yield y(O(t),(()=>l({method:"PUT",path:t,body:e,contentType:"octet-stream",headers:{"If-None-Match":"*"}})))}catch(t){throw 412===t.code&&(t.code="EEXIST"),t}}))).apply(this,arguments)}function v(){return(v=r((function*(t){try{yield l({method:"DELETE",path:t})}catch(t){if(404===t.code)return;throw t}}))).apply(this,arguments)}}});return t.dbToCloud=function({onGet:t,onPut:e,onDelete:n,onFirstSync:o,onWarn:i=console.error,onProgress:c,compareRevision:s,getState:l,setState:y,lockExpire:g=60,retryMaxAttempts:m=5,retryExp:v=1.5,retryDelay:w=10}){let b,T,E;const O=new Map,j=h((()=>y(b,T))),k=new Map,x=p();return{use:function(t){b=function(t){const e=Object.create(t);return e.get=function(){var e=r((function*(e){return JSON.parse(yield t.get(e))}));return function(t){return e.apply(this,arguments)}}(),e.put=function(){var e=r((function*(e,n){return yield t.put(e,JSON.stringify(n))}));return function(t,n){return e.apply(this,arguments)}}(),e.post=function(){var e=r((function*(e,n){return yield t.post(e,JSON.stringify(n))}));return function(t,n){return e.apply(this,arguments)}}(),e.isInit=!1,e.acquireLock||(e.acquireLock=function(t){return n.apply(this,arguments)},e.releaseLock=function(){return o.apply(this,arguments)}),e.getMeta||(e.getMeta=function(){return i.apply(this,arguments)},e.putMeta=function(t){return c.apply(this,arguments)}),e.peekChanges||(e.peekChanges=function(t){return a.apply(this,arguments)}),e;function n(){return(n=r((function*(t){try{yield this.post("lock.json",{expire:Date.now()+60*t*1e3})}catch(t){if("EEXIST"!==t.code)throw t;const e=yield this.get("lock.json");if(Date.now()>e.expire)throw yield this.delete("lock.json"),new Error("Found expired lock, please try again");throw new f(e.expire)}}))).apply(this,arguments)}function o(){return(o=r((function*(){yield this.delete("lock.json")}))).apply(this,arguments)}function i(){return(i=r((function*(){try{return yield this.get("meta.json")}catch(t){if("ENOENT"===t.code||404===t.code)return{};throw t}}))).apply(this,arguments)}function c(){return(c=r((function*(t){yield this.put("meta.json",t)}))).apply(this,arguments)}function a(){return(a=r((function*(t){return(yield this.getMeta()).lastChange!==t.lastChange}))).apply(this,arguments)}}(t)},init:function(){return x.write(r((function*(){if(!T||!T.enabled){if(!b)throw new Error("cloud drive is undefined");T=(yield l(b))||{},T.enabled=!0,T.queue||(T.queue=[])}})))},uninit:function(){return x.write(r((function*(){T&&T.enabled&&(T=E=null,O.clear(),k.clear(),b.uninit&&b.isInit&&(yield b.uninit(),b.isInit=!1),yield j())})))},put:function(t,e){if(!T||!T.enabled)return;T.queue.push({_id:t,_rev:e,action:"put"}),j()},delete:function(t,e){if(!T||!T.enabled)return;T.queue.push({_id:t,_rev:e,action:"delete"}),j()},syncNow:function(t){return x.write(r((function*(){if(!T||!T.enabled)throw new Error("Cannot sync now, the sync is not enabled");b.init&&!b.isInit&&(yield b.init(),b.isInit=!0),null==T.lastChange&&(yield o()),yield function(){return q.apply(this,arguments)}(t)})))},drive:()=>b,isInit:()=>Boolean(T&&T.enabled)};function C(){return S.apply(this,arguments)}function S(){return(S=r((function*(){if(E=yield b.getMeta(),!E.lastChange||E.lastChange===T.lastChange)return;let t=[];if(T.lastChange){const e=Math.floor((E.lastChange-1)/100);let n=Math.floor(T.lastChange/100);for(;n<=e;){const e=yield b.get("changes/".concat(n,".json"));O.set(n,e),t=t.concat(e),n++}t=t.slice(T.lastChange%100)}else t=(yield b.list("docs")).map((t=>({action:"put",_id:t.slice(0,-5)})));const o=new Map;var r,s=u(t);try{for(s.s();!(r=s.n()).done;){const t=r.value;o.set(t._id,t)}}catch(t){s.e(t)}finally{s.f()}let l=0;var p,f=u(o);try{for(f.s();!(p=f.n()).done;){const t=a(p.value,2),r=t[0],s=t[1];let u,f;if(c&&c({phase:"pull",total:o.size,loaded:l,change:s}),"delete"===s.action)yield n(r,s._rev);else if("put"===s.action){try{var h=yield b.get("docs/".concat(r,".json"));u=h.doc,f=h._rev}catch(t){if("ENOENT"===t.code||404===t.code){i("Cannot find ".concat(r,". Is it deleted without updating the history?")),l++;continue}throw t}yield e(u)}const d=s._rev||f;d&&k.set(r,d),l++}}catch(t){f.e(t)}finally{f.f()}T.lastChange=E.lastChange,yield j()}))).apply(this,arguments)}function A(){return P.apply(this,arguments)}function P(){return(P=r((function*(){if(!T.queue.length)return;const e=T.queue.slice(),n=new Map;var o,r=u(e);try{for(r.s();!(o=r.n()).done;){const t=o.value;n.set(t._id,t)}}catch(t){r.e(t)}finally{r.f()}const i=[];var a,l=u(n.values());try{for(l.s();!(a=l.n()).done;){const t=a.value,e=k.get(t._id);void 0!==e&&s(t._rev,e)<=0||i.push(t)}}catch(t){l.e(t)}finally{l.f()}let p,f,h=0;for(var d=0,y=i;d=m)throw t;yield d(1e3*n),n*=v}try{yield C(),yield A()}finally{yield b.releaseLock()}}))).apply(this,arguments)}function q(){return(q=r((function*(t=!0){c&&c({phase:"start"});try{if(!T.queue.length&&t&&E){if(!(yield b.peekChanges(E)))return}yield _()}finally{c&&c({phase:"end"})}}))).apply(this,arguments)}},t.drive=C,Object.defineProperty(t,"__esModule",{value:!0}),t}({}); //# sourceMappingURL=db-to-cloud.min.js.map