diff --git a/docs/settings.md b/docs/settings.md index 5501ad9..3271037 100644 --- a/docs/settings.md +++ b/docs/settings.md @@ -1,3 +1,5 @@ +NOTE: This document surely became outdated. I'll improve this doc in a while. but your contributions are always welcome. + # Settings of this plugin ## Remote Database Configurations @@ -19,14 +21,51 @@ The Database name to synchronize. ⚠️If not exist, created automatically. + ### Use the old connecting method -Since v0.8.0, Self-hosted LiveSync uses Obsidian's API to connect to the CouchDB instead of the browser API. -This method will increase the performance and avoid troubles with the CORS. -But it doesn't been well tested yet. If you are troubled, please disable this option once. +This option has been removed at v0.10.0 + + + +### End to End Encryption +Encrypt your database. It affects only the database, your files are left as plain. + +The encryption algorithm is AES-GCM. + +Note: If you want to use "Plugins and their settings", you have to enable this. + +### Passphrase +The passphrase to used as the key of encryption. Please use the long text. + +### Apply +To enable End-to-End encryption, there must be no items of the same content encrypted with different passphrases to avoid attackers guessing passphrases. Self-hosted LiveSync uses crc32 of the chunks, It is really a must. + +So, this plugin completely deletes everything from both local and remote databases before enabling it and then synchronizing again. + +To enable, "Apply and send" from the most powerful device. +If you want to synchronize an existing database, set passphrase and press "Just apply". + +- Apply and send +1. Initialize the Local Database and set (or clear) passphrase, put all files into the database again. +2. Initialize the Remote Database. +3. Lock the Remote Database. +4. Send it all. + +This process is simply heavy. Using a PC or Mac is preferred. +- Apply and receive +1. Initialize the Local Database and set (or clear) the passphrase. +2. Unlock the Remote Database. +3. Retrieve all and decrypt to file. + +When running these operations, every synchronization settings is disabled. ### Test Database connection You can check the connection by clicking this button. +### Check database configuration +You can check and modify your CouchDB's configuration from here directly. + + ## Local Database Configurations "Local Database" is created inside your obsidian. @@ -56,39 +95,6 @@ Note: If you want to use "Use history", this vault must be set to 0. ### Manual Garbage Collect Run "Garbage Collection" manually. -### End to End Encryption -Encrypt your database. It affects only the database, your files are left as plain. - -The encryption algorithm is AES-GCM. - -Note: If you want to use "Plugins and their settings", you have to enable this. - -### Passphrase -The passphrase to used as the key of encryption. Please use the long text. - -### Apply -To enable End-to-End encryption, there must be no items of the same content encrypted with different passphrases to avoid attackers guessing passphrases. Self-hosted LiveSync uses crc32 of the chunks, It is really a must. - -So, this plugin completely deletes everything from both local and remote databases before enabling it and then synchronizing again. - -To enable, "Apply and send" from the most powerful device, and "Apply and receive" from every other device. - -- Apply and send -1. Initialize the Local Database and set (or clear) passphrase, put all files into the database again. -2. Initialize the Remote Database. -3. Lock the Remote Database. -4. Send it all. - -This process is simply heavy. Using a PC or Mac is preferred. -- Apply and receive -1. Initialize the Local Database and set (or clear) the passphrase. -2. Unlock the Remote Database. -3. Retrieve all and decrypt to file. - -When running these operations, every synchronization settings is disabled. - -**And even your passphrase is wrong, It doesn't be checked before the plugin really decrypts. So If you set the wrong passphrase and run "Apply and Receive", you will get an amount of decryption error. But, this is the specification.** - ### minimum chunk size and LongLine threshold The configuration of chunk splitting. diff --git a/docs/settings_ja.md b/docs/settings_ja.md index 7a2b011..b73b778 100644 --- a/docs/settings_ja.md +++ b/docs/settings_ja.md @@ -1,3 +1,5 @@ +注意:少し内容が古くなっています。 + # このプラグインの設定項目 ## Remote Database Configurations @@ -19,9 +21,44 @@ CouchDBのURIを入力します。Cloudantの場合は「External Endpoint(prefe ⚠️存在しない場合は、テストや接続を行った際、自動的に作成されます[^1]。 [^1]:権限がない場合は自動作成には失敗します。 + + +### End to End Encryption +データベースを暗号化します。この効果はデータベースに格納されるデータに限られ、ディスク上のファイルは平文のままです。 +暗号化はAES-GCMを使用して行っています。 + +### Passphrase +暗号化を行う際に使用するパスフレーズです。充分に長いものを使用してください。 + +### Apply +End to End 暗号化を行うに当たって、異なるパスフレーズで暗号化された同一の内容を入手されることは避けるべきです。また、Self-hosted LiveSyncはコンテンツのcrc32を重複回避に使用しているため、その点でも攻撃が有効になってしまいます。 + +そのため、End to End 暗号化を有効にする際には、ローカル、リモートすべてのデータベースをいったん破棄し、新しいパスフレーズで暗号化された内容のみを、改めて同期し直します。 + +有効化するには、一番体力のある端末からApply and sendを行います。 +既に存在するリモートと同期する場合は、設定してJust applyを行ってください。 + +- Apply and send +1. ローカルのデータベースを初期化しパスフレーズを設定(またはクリア)します。その後、すべてのファイルをもう一度データベースに登録します。 +2. リモートのデータベースを初期化します。 +3. リモートのデータベースをロックし、他の端末を締め出します。 +4. すべて再送信します。 + +負荷と時間がかかるため、デスクトップから行う方が好ましいです。 +- Apply and receive +1. ローカルのデータベースを初期化し、パスフレーズを設定(またはクリア)します。 +2. リモートのデータベースにかかっているロックを解除します。 +3. すべて受信して、復号します。 + +どちらのオペレーションも、実行するとすべての同期設定が無効化されます。 + + ### Test Database connection 上記の設定でデータベースに接続できるか確認します。 +### Check database configuration +ここから直接CouchDBの設定を確認・変更できます。 + ## Local Database Configurations 端末内に作成されるデータベースの設定です。 @@ -49,35 +86,6 @@ Obsidianでのファイル操作が終わってから指定秒数が経過した ### Manual Garbage Collect 上記のGarbage Collectionを手動で行います。 -### End to End Encryption -データベースを暗号化します。この効果はデータベースに格納されるデータに限られ、ディスク上のファイルは平文のままです。 -暗号化はAES-GCMを使用して行っています。 - -### Passphrase -暗号化を行う際に使用するパスフレーズです。充分に長いものを使用してください。 - -### Apply -End to End 暗号化を行うに当たって、異なるパスフレーズで暗号化された同一の内容を入手されることは避けるべきです。また、Self-hosted LiveSyncはコンテンツのcrc32を重複回避に使用しているため、その点でも攻撃が有効になってしまいます。 - -そのため、End to End 暗号化を有効にする際には、ローカル、リモートすべてのデータベースをいったん破棄し、新しいパスフレーズで暗号化された内容のみを、改めて同期し直します。 - -有効化するには、一番体力のある端末からApply and sendを行い、他の端末でApply and receiveを行います。 - -- Apply and send -1. ローカルのデータベースを初期化しパスフレーズを設定(またはクリア)します。その後、すべてのファイルをもう一度データベースに登録します。 -2. リモートのデータベースを初期化します。 -3. リモートのデータベースをロックし、他の端末を締め出します。 -4. すべて再送信します。 - -負荷と時間がかかるため、デスクトップから行う方が好ましいです。 -- Apply and receive -1. ローカルのデータベースを初期化し、パスフレーズを設定(またはクリア)します。 -2. リモートのデータベースにかかっているロックを解除します。 -3. すべて受信して、復号します。 - -どちらのオペレーションも、実行するとすべての同期設定が無効化されます。 -**また、パスフレーズのチェックは、実際に復号するまで行いません。そのため、パスフレーズを間違えて設定し、Apply and receiveで同期を行うと、大量のエラーが発生します。これは仕様です。** - ### minimum chunk size と LongLine threshold チャンクの分割についての設定です。 Self-hosted LiveSyncは一つのチャンクのサイズを最低minimum chunk size文字確保した上で、できるだけ効率的に同期できるよう、ノートを分割してチャンクを作成します。 diff --git a/package-lock.json b/package-lock.json index ceb4189..ad75e95 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12,6 +12,7 @@ "diff-match-patch": "^1.0.5", "esbuild": "0.13.12", "esbuild-svelte": "^0.6.0", + "idb": "^7.0.1", "svelte-preprocess": "^4.10.2", "xxhash-wasm": "^0.4.2" }, @@ -2125,6 +2126,11 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/idb": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/idb/-/idb-7.0.1.tgz", + "integrity": "sha512-UUxlE7vGWK5RfB/fDwEGgRf84DY/ieqNha6msMV99UsEMQhJ1RwbCd8AYBj3QMgnE3VZnfQvm4oKVCJTYlqIgg==" + }, "node_modules/ignore": { "version": "5.1.9", "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.1.9.tgz", @@ -5077,6 +5083,11 @@ "has-symbols": "^1.0.2" } }, + "idb": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/idb/-/idb-7.0.1.tgz", + "integrity": "sha512-UUxlE7vGWK5RfB/fDwEGgRf84DY/ieqNha6msMV99UsEMQhJ1RwbCd8AYBj3QMgnE3VZnfQvm4oKVCJTYlqIgg==" + }, "ignore": { "version": "5.1.9", "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.1.9.tgz", diff --git a/package.json b/package.json index b852621..9d52cf5 100644 --- a/package.json +++ b/package.json @@ -37,6 +37,7 @@ "diff-match-patch": "^1.0.5", "esbuild": "0.13.12", "esbuild-svelte": "^0.6.0", + "idb": "^7.0.1", "svelte-preprocess": "^4.10.2", "xxhash-wasm": "^0.4.2" } diff --git a/pouchdb-browser-webpack/dist/pouchdb-browser.js b/pouchdb-browser-webpack/dist/pouchdb-browser.js index 85dd975..6c116f2 100644 --- a/pouchdb-browser-webpack/dist/pouchdb-browser.js +++ b/pouchdb-browser-webpack/dist/pouchdb-browser.js @@ -1 +1 @@ -var e={105:e=>{e.exports=function(e){return function(){var t=arguments.length;if(t){for(var n=[],r=-1;++r{var t,n="object"==typeof Reflect?Reflect:null,r=n&&"function"==typeof n.apply?n.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)};t=n&&"function"==typeof n.ownKeys?n.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var o=Number.isNaN||function(e){return e!=e};function i(){i.init.call(this)}e.exports=i,e.exports.once=function(e,t){return new Promise((function(n,r){function o(n){e.removeListener(t,i),r(n)}function i(){"function"==typeof e.removeListener&&e.removeListener("error",o),n([].slice.call(arguments))}v(e,t,i,{once:!0}),"error"!==t&&function(e,t,n){"function"==typeof e.on&&v(e,"error",t,{once:!0})}(e,o)}))},i.EventEmitter=i,i.prototype._events=void 0,i.prototype._eventsCount=0,i.prototype._maxListeners=void 0;var s=10;function a(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function c(e){return void 0===e._maxListeners?i.defaultMaxListeners:e._maxListeners}function u(e,t,n,r){var o,i,s,u;if(a(n),void 0===(i=e._events)?(i=e._events=Object.create(null),e._eventsCount=0):(void 0!==i.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),i=e._events),s=i[t]),void 0===s)s=i[t]=n,++e._eventsCount;else if("function"==typeof s?s=i[t]=r?[n,s]:[s,n]:r?s.unshift(n):s.push(n),(o=c(e))>0&&s.length>o&&!s.warned){s.warned=!0;var f=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");f.name="MaxListenersExceededWarning",f.emitter=e,f.type=t,f.count=s.length,u=f,console&&console.warn&&console.warn(u)}return e}function f(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function l(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},o=f.bind(r);return o.listener=n,r.wrapFn=o,o}function d(e,t,n){var r=e._events;if(void 0===r)return[];var o=r[t];return void 0===o?[]:"function"==typeof o?n?[o.listener||o]:[o]:n?function(e){for(var t=new Array(e.length),n=0;n0&&(s=t[0]),s instanceof Error)throw s;var a=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw a.context=s,a}var c=i[e];if(void 0===c)return!1;if("function"==typeof c)r(c,this,t);else{var u=c.length,f=p(c,u);for(n=0;n=0;i--)if(n[i]===t||n[i].listener===t){s=n[i].listener,o=i;break}if(o<0)return this;0===o?n.shift():function(e,t){for(;t+1=0;r--)this.removeListener(e,t[r]);return this},i.prototype.listeners=function(e){return d(this,e,!0)},i.prototype.rawListeners=function(e){return d(this,e,!1)},i.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):h.call(e,t)},i.prototype.listenerCount=h,i.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]}},624:(e,t,n)=>{var r,o,i,s=[n(525),n(785),n(291),n(709),n(506),n(444)],a=-1,c=[],u=!1;function f(){r&&o&&(r=!1,o.length?c=o.concat(c):a=-1,c.length&&l())}function l(){if(!r){u=!1,r=!0;for(var e=c.length,t=setTimeout(f);e;){for(o=c,c=[];o&&++a1)for(var n=1;n{t.test=function(){return!n.g.setImmediate&&void 0!==n.g.MessageChannel},t.install=function(e){var t=new n.g.MessageChannel;return t.port1.onmessage=e,function(){t.port2.postMessage(0)}}},291:(e,t,n)=>{var r=n.g.MutationObserver||n.g.WebKitMutationObserver;t.test=function(){return r},t.install=function(e){var t=0,o=new r(e),i=n.g.document.createTextNode("");return o.observe(i,{characterData:!0}),function(){i.data=t=++t%2}}},785:(e,t,n)=>{t.test=function(){return"function"==typeof n.g.queueMicrotask},t.install=function(e){return function(){n.g.queueMicrotask(e)}}},506:(e,t,n)=>{t.test=function(){return"document"in n.g&&"onreadystatechange"in n.g.document.createElement("script")},t.install=function(e){return function(){var t=n.g.document.createElement("script");return t.onreadystatechange=function(){e(),t.onreadystatechange=null,t.parentNode.removeChild(t),t=null},n.g.document.documentElement.appendChild(t),e}}},444:(e,t)=>{t.test=function(){return!0},t.install=function(e){return function(){setTimeout(e,0)}}},717:e=>{"function"==typeof Object.create?e.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:e.exports=function(e,t){if(t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}}},322:e=>{e.exports=function(e){var t=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];function n(e,t){var n=e[0],r=e[1],o=e[2],i=e[3];r=((r+=((o=((o+=((i=((i+=((n=((n+=(r&o|~r&i)+t[0]-680876936|0)<<7|n>>>25)+r|0)&r|~n&o)+t[1]-389564586|0)<<12|i>>>20)+n|0)&n|~i&r)+t[2]+606105819|0)<<17|o>>>15)+i|0)&i|~o&n)+t[3]-1044525330|0)<<22|r>>>10)+o|0,r=((r+=((o=((o+=((i=((i+=((n=((n+=(r&o|~r&i)+t[4]-176418897|0)<<7|n>>>25)+r|0)&r|~n&o)+t[5]+1200080426|0)<<12|i>>>20)+n|0)&n|~i&r)+t[6]-1473231341|0)<<17|o>>>15)+i|0)&i|~o&n)+t[7]-45705983|0)<<22|r>>>10)+o|0,r=((r+=((o=((o+=((i=((i+=((n=((n+=(r&o|~r&i)+t[8]+1770035416|0)<<7|n>>>25)+r|0)&r|~n&o)+t[9]-1958414417|0)<<12|i>>>20)+n|0)&n|~i&r)+t[10]-42063|0)<<17|o>>>15)+i|0)&i|~o&n)+t[11]-1990404162|0)<<22|r>>>10)+o|0,r=((r+=((o=((o+=((i=((i+=((n=((n+=(r&o|~r&i)+t[12]+1804603682|0)<<7|n>>>25)+r|0)&r|~n&o)+t[13]-40341101|0)<<12|i>>>20)+n|0)&n|~i&r)+t[14]-1502002290|0)<<17|o>>>15)+i|0)&i|~o&n)+t[15]+1236535329|0)<<22|r>>>10)+o|0,r=((r+=((o=((o+=((i=((i+=((n=((n+=(r&i|o&~i)+t[1]-165796510|0)<<5|n>>>27)+r|0)&o|r&~o)+t[6]-1069501632|0)<<9|i>>>23)+n|0)&r|n&~r)+t[11]+643717713|0)<<14|o>>>18)+i|0)&n|i&~n)+t[0]-373897302|0)<<20|r>>>12)+o|0,r=((r+=((o=((o+=((i=((i+=((n=((n+=(r&i|o&~i)+t[5]-701558691|0)<<5|n>>>27)+r|0)&o|r&~o)+t[10]+38016083|0)<<9|i>>>23)+n|0)&r|n&~r)+t[15]-660478335|0)<<14|o>>>18)+i|0)&n|i&~n)+t[4]-405537848|0)<<20|r>>>12)+o|0,r=((r+=((o=((o+=((i=((i+=((n=((n+=(r&i|o&~i)+t[9]+568446438|0)<<5|n>>>27)+r|0)&o|r&~o)+t[14]-1019803690|0)<<9|i>>>23)+n|0)&r|n&~r)+t[3]-187363961|0)<<14|o>>>18)+i|0)&n|i&~n)+t[8]+1163531501|0)<<20|r>>>12)+o|0,r=((r+=((o=((o+=((i=((i+=((n=((n+=(r&i|o&~i)+t[13]-1444681467|0)<<5|n>>>27)+r|0)&o|r&~o)+t[2]-51403784|0)<<9|i>>>23)+n|0)&r|n&~r)+t[7]+1735328473|0)<<14|o>>>18)+i|0)&n|i&~n)+t[12]-1926607734|0)<<20|r>>>12)+o|0,r=((r+=((o=((o+=((i=((i+=((n=((n+=(r^o^i)+t[5]-378558|0)<<4|n>>>28)+r|0)^r^o)+t[8]-2022574463|0)<<11|i>>>21)+n|0)^n^r)+t[11]+1839030562|0)<<16|o>>>16)+i|0)^i^n)+t[14]-35309556|0)<<23|r>>>9)+o|0,r=((r+=((o=((o+=((i=((i+=((n=((n+=(r^o^i)+t[1]-1530992060|0)<<4|n>>>28)+r|0)^r^o)+t[4]+1272893353|0)<<11|i>>>21)+n|0)^n^r)+t[7]-155497632|0)<<16|o>>>16)+i|0)^i^n)+t[10]-1094730640|0)<<23|r>>>9)+o|0,r=((r+=((o=((o+=((i=((i+=((n=((n+=(r^o^i)+t[13]+681279174|0)<<4|n>>>28)+r|0)^r^o)+t[0]-358537222|0)<<11|i>>>21)+n|0)^n^r)+t[3]-722521979|0)<<16|o>>>16)+i|0)^i^n)+t[6]+76029189|0)<<23|r>>>9)+o|0,r=((r+=((o=((o+=((i=((i+=((n=((n+=(r^o^i)+t[9]-640364487|0)<<4|n>>>28)+r|0)^r^o)+t[12]-421815835|0)<<11|i>>>21)+n|0)^n^r)+t[15]+530742520|0)<<16|o>>>16)+i|0)^i^n)+t[2]-995338651|0)<<23|r>>>9)+o|0,r=((r+=((i=((i+=(r^((n=((n+=(o^(r|~i))+t[0]-198630844|0)<<6|n>>>26)+r|0)|~o))+t[7]+1126891415|0)<<10|i>>>22)+n|0)^((o=((o+=(n^(i|~r))+t[14]-1416354905|0)<<15|o>>>17)+i|0)|~n))+t[5]-57434055|0)<<21|r>>>11)+o|0,r=((r+=((i=((i+=(r^((n=((n+=(o^(r|~i))+t[12]+1700485571|0)<<6|n>>>26)+r|0)|~o))+t[3]-1894986606|0)<<10|i>>>22)+n|0)^((o=((o+=(n^(i|~r))+t[10]-1051523|0)<<15|o>>>17)+i|0)|~n))+t[1]-2054922799|0)<<21|r>>>11)+o|0,r=((r+=((i=((i+=(r^((n=((n+=(o^(r|~i))+t[8]+1873313359|0)<<6|n>>>26)+r|0)|~o))+t[15]-30611744|0)<<10|i>>>22)+n|0)^((o=((o+=(n^(i|~r))+t[6]-1560198380|0)<<15|o>>>17)+i|0)|~n))+t[13]+1309151649|0)<<21|r>>>11)+o|0,r=((r+=((i=((i+=(r^((n=((n+=(o^(r|~i))+t[4]-145523070|0)<<6|n>>>26)+r|0)|~o))+t[11]-1120210379|0)<<10|i>>>22)+n|0)^((o=((o+=(n^(i|~r))+t[2]+718787259|0)<<15|o>>>17)+i|0)|~n))+t[9]-343485551|0)<<21|r>>>11)+o|0,e[0]=n+e[0]|0,e[1]=r+e[1]|0,e[2]=o+e[2]|0,e[3]=i+e[3]|0}function r(e){var t,n=[];for(t=0;t<64;t+=4)n[t>>2]=e.charCodeAt(t)+(e.charCodeAt(t+1)<<8)+(e.charCodeAt(t+2)<<16)+(e.charCodeAt(t+3)<<24);return n}function o(e){var t,n=[];for(t=0;t<64;t+=4)n[t>>2]=e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24);return n}function i(e){var t,o,i,s,a,c,u=e.length,f=[1732584193,-271733879,-1732584194,271733878];for(t=64;t<=u;t+=64)n(f,r(e.substring(t-64,t)));for(o=(e=e.substring(t-64)).length,i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],t=0;t>2]|=e.charCodeAt(t)<<(t%4<<3);if(i[t>>2]|=128<<(t%4<<3),t>55)for(n(f,i),t=0;t<16;t+=1)i[t]=0;return s=(s=8*u).toString(16).match(/(.*?)(.{0,8})$/),a=parseInt(s[2],16),c=parseInt(s[1],16)||0,i[14]=a,i[15]=c,n(f,i),f}function s(e){var n,r="";for(n=0;n<4;n+=1)r+=t[e>>8*n+4&15]+t[e>>8*n&15];return r}function a(e){var t;for(t=0;tu?new ArrayBuffer(0):(r=u-c,o=new ArrayBuffer(r),i=new Uint8Array(o),s=new Uint8Array(this,c,r),i.set(s),o)}}(),f.prototype.append=function(e){return this.appendBinary(c(e)),this},f.prototype.appendBinary=function(e){this._buff+=e,this._length+=e.length;var t,o=this._buff.length;for(t=64;t<=o;t+=64)n(this._hash,r(this._buff.substring(t-64,t)));return this._buff=this._buff.substring(t-64),this},f.prototype.end=function(e){var t,n,r=this._buff,o=r.length,i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(t=0;t>2]|=r.charCodeAt(t)<<(t%4<<3);return this._finish(i,o),n=a(this._hash),e&&(n=u(n)),this.reset(),n},f.prototype.reset=function(){return this._buff="",this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},f.prototype.getState=function(){return{buff:this._buff,length:this._length,hash:this._hash.slice()}},f.prototype.setState=function(e){return this._buff=e.buff,this._length=e.length,this._hash=e.hash,this},f.prototype.destroy=function(){delete this._hash,delete this._buff,delete this._length},f.prototype._finish=function(e,t){var r,o,i,s=t;if(e[s>>2]|=128<<(s%4<<3),s>55)for(n(this._hash,e),s=0;s<16;s+=1)e[s]=0;r=(r=8*this._length).toString(16).match(/(.*?)(.{0,8})$/),o=parseInt(r[2],16),i=parseInt(r[1],16)||0,e[14]=o,e[15]=i,n(this._hash,e)},f.hash=function(e,t){return f.hashBinary(c(e),t)},f.hashBinary=function(e,t){var n=a(i(e));return t?u(n):n},f.ArrayBuffer=function(){this.reset()},f.ArrayBuffer.prototype.append=function(e){var t,r,i,s,a,c=(r=this._buff.buffer,i=e,s=!0,(a=new Uint8Array(r.byteLength+i.byteLength)).set(new Uint8Array(r)),a.set(new Uint8Array(i),r.byteLength),s?a:a.buffer),u=c.length;for(this._length+=e.byteLength,t=64;t<=u;t+=64)n(this._hash,o(c.subarray(t-64,t)));return this._buff=t-64>2]|=r[t]<<(t%4<<3);return this._finish(i,o),n=a(this._hash),e&&(n=u(n)),this.reset(),n},f.ArrayBuffer.prototype.reset=function(){return this._buff=new Uint8Array(0),this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},f.ArrayBuffer.prototype.getState=function(){var e,t=f.prototype.getState.call(this);return t.buff=(e=t.buff,String.fromCharCode.apply(null,new Uint8Array(e))),t},f.ArrayBuffer.prototype.setState=function(e){return e.buff=function(e,t){var n,r=e.length,o=new ArrayBuffer(r),i=new Uint8Array(o);for(n=0;n>2]|=e[t]<<(t%4<<3);if(i[t>>2]|=128<<(t%4<<3),t>55)for(n(f,i),t=0;t<16;t+=1)i[t]=0;return s=(s=8*u).toString(16).match(/(.*?)(.{0,8})$/),a=parseInt(s[2],16),c=parseInt(s[1],16)||0,i[14]=a,i[15]=c,n(f,i),f}(new Uint8Array(e)));return t?u(r):r},f}()},684:(e,t)=>{function n(e,t,n){var r=n[n.length-1];e===r.element&&(n.pop(),r=n[n.length-1]);var o=r.element,i=r.index;Array.isArray(o)?o.push(e):i===t.length-2?o[t.pop()]=e:t.push(e)}t.stringify=function(e){var t=[];t.push({obj:e});for(var n,r,o,i,s,a,c,u,f,l,d="";n=t.pop();)if(r=n.obj,d+=n.prefix||"",o=n.val||"")d+=o;else if("object"!=typeof r)d+=void 0===r?null:JSON.stringify(r);else if(null===r)d+="null";else if(Array.isArray(r)){for(t.push({val:"]"}),i=r.length-1;i>=0;i--)s=0===i?"":",",t.push({obj:r[i],prefix:s});t.push({val:"["})}else{for(c in a=[],r)r.hasOwnProperty(c)&&a.push(c);for(t.push({val:"}"}),i=a.length-1;i>=0;i--)f=r[u=a[i]],l=i>0?",":"",l+=JSON.stringify(u)+":",t.push({obj:f,prefix:l});t.push({val:"{"})}return d},t.parse=function(e){for(var t,r,o,i,s,a,c,u,f,l=[],d=[],h=0;;)if("}"!==(t=e[h++])&&"]"!==t&&void 0!==t)switch(t){case" ":case"\t":case"\n":case":":case",":break;case"n":h+=3,n(null,l,d);break;case"t":h+=3,n(!0,l,d);break;case"f":h+=4,n(!1,l,d);break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":case"-":for(r="",h--;;){if(o=e[h++],!/[\d\.\-e\+]/.test(o)){h--;break}r+=o}n(parseFloat(r),l,d);break;case'"':for(i="",s=void 0,a=0;'"'!==(c=e[h++])||"\\"===s&&a%2==1;)i+=c,"\\"===(s=c)?a++:a=0;n(JSON.parse('"'+i+'"'),l,d);break;case"[":u={element:[],index:l.length},l.push(u.element),d.push(u);break;case"{":f={element:{},index:l.length},l.push(f.element),d.push(f);break;default:throw new Error("unexpectedly reached end of input: "+t)}else{if(1===l.length)return l.pop();n(l.pop(),l,d)}}},525:()=>{}},t={};function n(r){var o=t[r];if(void 0!==o)return o.exports;var i=t[r]={exports:{}};return e[r](i,i.exports,n),i.exports}n.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return n.d(t,{a:t}),t},n.d=(e,t)=>{for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var r={};(()=>{n.d(r,{o:()=>yr});var e,t=n(624),o=n.n(t),i=new Uint8Array(16);function s(){if(!e&&!(e="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return e(i)}const a=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i,c=function(e){return"string"==typeof e&&a.test(e)};for(var u=[],f=0;f<256;++f)u.push((f+256).toString(16).substr(1));const l=function(e,t,n){var r=(e=e||{}).random||(e.rng||s)();if(r[6]=15&r[6]|64,r[8]=63&r[8]|128,t){n=n||0;for(var o=0;o<16;++o)t[n+o]=r[o];return t}return function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=(u[e[t+0]]+u[e[t+1]]+u[e[t+2]]+u[e[t+3]]+"-"+u[e[t+4]]+u[e[t+5]]+"-"+u[e[t+6]]+u[e[t+7]]+"-"+u[e[t+8]]+u[e[t+9]]+"-"+u[e[t+10]]+u[e[t+11]]+u[e[t+12]]+u[e[t+13]]+u[e[t+14]]+u[e[t+15]]).toLowerCase();if(!c(n))throw TypeError("Stringified UUID is invalid");return n}(r)};var d,h,p=n(322),v=n.n(p),y=n(684),_=n(105),g=n.n(_),m=n(717),b=n.n(m),w=n(187),k=n.n(w);function j(e){return"$"+e}function O(e){return e.substring(1)}function q(){this._store={}}function A(e){if(this._store=new q,e&&Array.isArray(e))for(var t=0,n=e.length;tO(e)))},q.prototype.delete=function(e){var t=j(e),n=t in this._store;return delete this._store[t],n},q.prototype.forEach=function(e){for(var t=Object.keys(this._store),n=0,r=t.length;n=c.length)){var f=Math.min(u+6,c.length),l=c.slice(u,f);!function(c,u){c.forEach((function(c,f){var l=u+f,d=o.get(c),h=D(d[0],["atts_since","attachments"]);h.open_revs=d.map((function(e){return e.rev})),h.open_revs=h.open_revs.filter(I);var p=I;0===h.open_revs.length&&(delete h.open_revs,p=B),["revs","attachments","binary","ajax","latest"].forEach((function(e){e in t&&(h[e]=t[e])})),e.get(c,h,(function(e,t){var o,u,f,d;o=e?[{error:e}]:p(t),u=c,f=o,a[l]={id:u,docs:f},++s===i&&(d=[],a.forEach((function(e){e.docs.forEach((function(t){d.push({id:e.id,docs:[t]})}))})),n(null,{results:d})),r()}))}))}(l,u),u+=l.length}}()}try{localStorage.setItem("_pouch_check_localstorage",1),S=!!localStorage.getItem("_pouch_check_localstorage")}catch(e){S=!1}function T(){return S}function N(){k().call(this),this._listeners={},function(e){T()&&addEventListener("storage",(function(t){e.emit(t.key)}))}(this)}function M(e){if("undefined"!=typeof console&&"function"==typeof console[e]){var t=Array.prototype.slice.call(arguments,1);console[e].apply(console,t)}}function F(e){var t=0;return e||(t=2e3),function(e,t){var n=6e5;return e=parseInt(e,10)||0,(t=parseInt(t,10))!=t||t<=e?t=(e||1)<<1:t+=1,t>n&&(e=3e5,t=n),~~((t-e)*Math.random()+e)}(e,t)}function U(e,t){M("info","The above "+e+" is totally normal. "+t)}b()(N,k()),N.prototype.addListener=function(e,t,n,r){if(!this._listeners[t]){var i=this,s=!1;this._listeners[t]=a,this.on(e,a)}function a(){if(i._listeners[t])if(s)s="waiting";else{s=!0;var e=D(r,["style","include_docs","attachments","conflicts","filter","doc_ids","view","since","query_params","binary","return_docs"]);n.changes(e).on("change",(function(e){e.seq>r.since&&!r.cancelled&&(r.since=e.seq,r.onChange(e))})).on("complete",(function(){"waiting"===s&&o()(a),s=!1})).on("error",(function(){s=!1}))}}},N.prototype.removeListener=function(e,t){t in this._listeners&&(k().prototype.removeListener.call(this,e,this._listeners[t]),delete this._listeners[t])},N.prototype.notifyLocalWindows=function(e){T()&&(localStorage[e]="a"===localStorage[e]?"b":"a")},N.prototype.notify=function(e){this.emit(e),this.notifyLocalWindows(e)};var K="function"==typeof Object.assign?Object.assign:function(e){for(var t=Object(e),n=1;n0||r0||r>>1],t)<0?o=r+1:i=r;return o}(e,t,n);e.splice(r,0,t)}function ze(e,t){for(var n,r,o=t,i=e.length;o0;){var o=n.pop(),i=o.tree1,s=o.tree2;(i[1].status||s[1].status)&&(i[1].status="available"===i[1].status||"available"===s[1].status?"available":"missing");for(var a=0;a0;){var v=p.pop();if(0!==v.diff)for(var y=v.ids[2],_=0,g=y.length;_t){n||(n={});var f=u.length-t;a={pos:c.pos+f,ids:ze(u,f)};for(var l=0;l0&&r.emit("error",t)):r.emit("complete",n),r.removeAllListeners(),e.removeListener("destroyed",i)}));function i(){r.cancel()}n&&(r.on("complete",(function(e){n(null,e)})),r.on("error",n)),e.once("destroyed",i),t.onChange=function(e,t,n){r.isCancelled||function(e,t,n,r){try{e.emit("change",t,n,r)}catch(e){M("error",'Error in .on("change", function):',e)}}(r,e,t,n)};var s=new Promise((function(e,n){t.complete=function(t,r){t?n(t):e(r)}}));r.once("cancel",(function(){e.removeListener("destroyed",i),t.complete(null,{status:"cancelled"})})),this.then=s.then.bind(s),this.catch=s.catch.bind(s),this.then((function(e){o(null,e)}),o),e.taskqueue.isReady?r.validateChanges(t):e.taskqueue.addTask((function(e){e?t.complete(e):r.isCancelled?r.emit("cancel"):r.validateChanges(t)}))}function et(e,t,n){var r=[{rev:e._rev}];"all_docs"===n.style&&(r=Me(t.rev_tree).map((function(e){return{rev:e.rev}})));var o={id:t.id,changes:r,doc:e};return He(t,e._rev)&&(o.deleted=!0),n.conflicts&&(o.doc._conflicts=Fe(t),o.doc._conflicts.length||delete o.doc._conflicts),o}function tt(e,t){return et?1:0}function nt(e,t){return function(n,r){n||r[0]&&r[0].error?((n=n||r[0]).docId=t,e(n)):e(null,r.length?r[0]:r)}}function rt(e,t){var n=tt(e._id,t._id);return 0!==n?n:tt(e._revisions?e._revisions.start:0,t._revisions?t._revisions.start:0)}function ot(e){var t=e._compactionQueue[0],n=t.opts,r=t.callback;e.get("_local/compaction").catch((function(){return!1})).then((function(t){t&&t.last_seq&&(n.last_seq=t.last_seq),e._compact(n,(function(t,n){t?r(t):r(null,n),o()((function(){e._compactionQueue.shift(),e._compactionQueue.length&&ot(e)}))}))}))}function it(){for(var e in k().call(this),it.prototype)"function"==typeof this[e]&&(this[e]=this[e].bind(this))}function st(){this.isReady=!1,this.failed=!1,this.queue=[]}function at(e,t){if(!(this instanceof at))return new at(e,t);var n=this;if(t=t||{},e&&"object"==typeof e&&(e=(t=e).name,delete t.name),void 0===t.deterministic_revs&&(t.deterministic_revs=!0),this.__opts=t=C(t),n.auto_compaction=t.auto_compaction,n.prefix=at.prefix,"string"!=typeof e)throw new Error("Missing/invalid DB name");var r=function(e,t){var n=e.match(/([a-z-]*):\/\/(.*)/);if(n)return{name:/https?/.test(n[1])?n[1]+"://"+n[2]:n[2],adapter:n[1]};var r=at.adapters,o=at.preferredAdapters,i=at.prefix,s=t.adapter;if(!s)for(var a=0;at&&a.push(e)})),Te(i,(function(e,t,n,r,o){var i=t+"-"+n;"available"===o.status&&-1!==a.indexOf(i)&&c.push(i)})),r._doCompaction(e,c,n)}))})),it.prototype.compact=$("compact",(function(e,t){"function"==typeof e&&(t=e,e={});var n=this;e=e||{},n._compactionQueue=n._compactionQueue||[],n._compactionQueue.push({opts:e,callback:t}),1===n._compactionQueue.length&&ot(n)})),it.prototype._compact=function(e,t){var n=this,r={return_docs:!1,last_seq:e.last_seq||0},o=[];n.changes(r).on("change",(function(e){o.push(n.compactDocument(e.id,0))})).on("complete",(function(e){var r=e.last_seq;Promise.all(o).then((function(){return be(n,"_local/compaction",(function(e){return(!e.last_seq||e.last_seq0?e.keys.slice(e.skip):e.keys;e.keys=t,e.skip=0,delete e.limit,e.descending&&(t.reverse(),e.descending=!1)}(e),0===e.keys.length))return this._allDocs({limit:0},t)}return this._allDocs(e,t)})),it.prototype.changes=function(e,t){return"function"==typeof e&&(t=e,e={}),(e=e||{}).return_docs="return_docs"in e?e.return_docs:!e.live,new Ze(this,e,t)},it.prototype.close=$("close",(function(e){return this._closed=!0,this.emit("closed"),this._close(e)})),it.prototype.info=$("info",(function(e){var t=this;this._info((function(n,r){if(n)return e(n);r.db_name=r.db_name||t.name,r.auto_compaction=!(!t.auto_compaction||le(t)),r.adapter=t.adapter,e(null,r)}))})),it.prototype.id=$("id",(function(e){return this._id(e)})),it.prototype.type=function(){return"function"==typeof this._type?this._type():this.adapter},it.prototype.bulkDocs=$("bulkDocs",(function(e,t,n){if("function"==typeof t&&(n=t,t={}),t=t||{},Array.isArray(e)&&(e={docs:e}),!e||!e.docs||!Array.isArray(e.docs))return n(se(z));for(var r=0;r0&&"\\"===e[r-1]&&("$"===i||"."===i)?n=n.substring(0,n.length-1)+i:"."===i?(t.push(n),n=""):n+=i}return t.push(n),t}!function(e){Object.keys(k().prototype).forEach((function(t){"function"==typeof k().prototype[t]&&(e[t]=lt[t].bind(lt))}));var t=e._destructionListeners=new h;e.on("ref",(function(e){t.has(e.name)||t.set(e.name,[]),t.get(e.name).push(e)})),e.on("unref",(function(e){if(t.has(e.name)){var n=t.get(e.name),r=n.indexOf(e);r<0||(n.splice(r,1),n.length>1?t.set(e.name,n):t.delete(e.name))}})),e.on("destroyed",(function(e){if(t.has(e)){var n=t.get(e);t.delete(e),n.forEach((function(e){e.emit("destroyed",!0)}))}}))}(at),at.adapter=function(e,t,n){t.valid()&&(at.adapters[e]=t,n&&at.preferredAdapters.push(e))},at.plugin=function(e){if("function"==typeof e)e(at);else{if("object"!=typeof e||0===Object.keys(e).length)throw new Error('Invalid plugin: got "'+e+'", expected an object or a function');Object.keys(e).forEach((function(t){at.prototype[t]=e[t]}))}return this.__defaults&&(at.__defaults=K({},this.__defaults)),at},at.defaults=function(e){function t(e,n){if(!(this instanceof t))return new t(e,n);n=n||{},e&&"object"==typeof e&&(e=(n=e).name,delete n.name),n=K({},t.__defaults,n),at.call(this,e,n)}return b()(t,at),t.preferredAdapters=at.preferredAdapters.slice(),Object.keys(at).forEach((function(e){e in t||(t[e]=at[e])})),t.__defaults=K({},this.__defaults,e),t},at.fetch=function(e,t){return ut(e,t)};var pt=["$or","$nor","$not"];function vt(e){return pt.indexOf(e)>-1}function yt(e){return Object.keys(e)[0]}function _t(e){var t={},n={$or:!0,$nor:!0};return e.forEach((function(e){Object.keys(e).forEach((function(r){var o=e[r];if("object"!=typeof o&&(o={$eq:o}),vt(r))if(o instanceof Array){if(n[r])return n[r]=!1,void(t[r]=o);var i=[];t[r].forEach((function(e){Object.keys(o).forEach((function(t){var n=o[t],r=Math.max(Object.keys(e).length,Object.keys(n).length),s=_t([e,n]);Object.keys(s).length<=r||i.push(s)}))})),t[r]=i}else t[r]=_t([o]);else{var s=t[r]=t[r]||{};Object.keys(o).forEach((function(e){var t=o[e];return"$gt"===e||"$gte"===e?function(e,t,n){void 0===n.$eq&&(void 0!==n.$gte?"$gte"===e?t>n.$gte&&(n.$gte=t):t>=n.$gte&&(delete n.$gte,n.$gt=t):void 0!==n.$gt?"$gte"===e?t>n.$gt&&(delete n.$gt,n.$gte=t):t>n.$gt&&(n.$gt=t):n[e]=t)}(e,t,s):"$lt"===e||"$lte"===e?function(e,t,n){void 0===n.$eq&&(void 0!==n.$lte?"$lte"===e?tt?1:-1}(e,t)}return Array.isArray(e)?function(e,t){for(var n=Math.min(e.length,t.length),r=0;rt.length?1:-1}(e,t):function(e,t){for(var n=Object.keys(e),r=Object.keys(t),o=Math.min(n.length,r.length),i=0;ir.length?1:-1}(e,t)}function kt(e){switch(typeof e){case"undefined":return null;case"number":return e===1/0||e===-1/0||isNaN(e)?null:e;case"object":var t=e;if(Array.isArray(e)){var n=e.length;e=new Array(n);for(var r=0;r0)return!1;var a=dt(r,s);return"object"==typeof i?xt(i,t,n,a):Et("$eq",t,i,s,a)})):e===r)}function Et(e,t,n,r,o){if(!$t[e])throw new Error('unknown operator "'+e+'" - should be one of $eq, $lte, $lt, $gt, $gte, $exists, $ne, $in, $nin, $size, $mod, $regex, $elemMatch, $type, $allMatch or $all');return $t[e](t,n,r,o)}function Ct(e){return null!=e}function Pt(e){return void 0!==e}function Lt(e,t){return t.some((function(t){return e instanceof Array?e.some((function(e){return 0===wt(t,e)})):0===wt(t,e)}))}var $t={$elemMatch:function(e,t,n,r){return!!Array.isArray(r)&&0!==r.length&&("object"==typeof r[0]?r.some((function(e){return St(e,t,Object.keys(t))})):r.some((function(r){return xt(t,e,n,r)})))},$allMatch:function(e,t,n,r){return!!Array.isArray(r)&&0!==r.length&&("object"==typeof r[0]?r.every((function(e){return St(e,t,Object.keys(t))})):r.every((function(r){return xt(t,e,n,r)})))},$eq:function(e,t,n,r){return Pt(r)&&0===wt(r,t)},$gte:function(e,t,n,r){return Pt(r)&&wt(r,t)>=0},$gt:function(e,t,n,r){return Pt(r)&&wt(r,t)>0},$lte:function(e,t,n,r){return Pt(r)&&wt(r,t)<=0},$lt:function(e,t,n,r){return Pt(r)&&wt(r,t)<0},$exists:function(e,t,n,r){return t?Pt(r):!Pt(r)},$mod:function(e,t,n,r){return Ct(r)&&function(e,t){return"number"==typeof e&&parseInt(e,10)===e&&e%t[0]===t[1]}(r,t)},$ne:function(e,t,n,r){return t.every((function(e){return 0!==wt(r,e)}))},$in:function(e,t,n,r){return Ct(r)&&Lt(r,t)},$nin:function(e,t,n,r){return Ct(r)&&!Lt(r,t)},$size:function(e,t,n,r){return Ct(r)&&Array.isArray(r)&&function(e,t){return e.length===t}(r,t)},$all:function(e,t,n,r){return Array.isArray(r)&&function(e,t){return t.every((function(t){return e.some((function(e){return 0===wt(t,e)}))}))}(r,t)},$regex:function(e,t,n,r){return Ct(r)&&"string"==typeof r&&t.every((function(e){return function(e,t){return new RegExp(t).test(e)}(r,e)}))},$type:function(e,t,n,r){return function(e,t){switch(t){case"null":return null===e;case"boolean":return"boolean"==typeof e;case"number":return"number"==typeof e;case"string":return"string"==typeof e;case"array":return e instanceof Array;case"object":return"[object Object]"==={}.toString.call(e)}}(r,t)}};function Dt(e,t){if(e.selector&&e.filter&&"_selector"!==e.filter){var n="string"==typeof e.filter?e.filter:"function";return t(new Error('selector invalid for filter "'+n+'"'))}t()}function It(e){e.view&&!e.filter&&(e.filter="_view"),e.selector&&!e.filter&&(e.filter="_selector"),e.filter&&"string"==typeof e.filter&&("_view"===e.filter?e.view=he(e.view):e.filter=he(e.filter))}function Bt(e,t){return t.filter&&"string"==typeof t.filter&&!t.doc_ids&&!le(e.db)}function Rt(e,t){var n=t.complete;if("_view"===t.filter){if(!t.view||"string"!=typeof t.view){var r=se(te,"`view` filter parameter not found or invalid.");return n(r)}var o=de(t.view);e.db.get("_design/"+o[0],(function(r,i){if(e.isCancelled)return n(null,{status:"cancelled"});if(r)return n(ae(r));var s=i&&i.views&&i.views[o[1]]&&i.views[o[1]].map;if(!s)return n(se(V,i.views?"missing json key: "+o[1]:"missing json key: views"));t.filter=me(["return function(doc) {",' "use strict";'," var emitted = false;"," var emit = function (a, b) {"," emitted = true;"," };"," var view = "+s+";"," view(doc);"," if (emitted) {"," return true;"," }","};"].join("\n"),{}),e.doChanges(t)}))}else if(t.selector)t.filter=function(e){return function(e,t){if("object"!=typeof t)throw new Error("Selector error: expected a JSON object");var n=function(e,t,n){if(e=e.filter((function(e){return St(e.doc,t.selector,n)})),t.sort){var r=function(e){function t(t){return e.map((function(e){var n=ht(yt(e));return dt(t,n)}))}return function(e,n){var r,o,i=wt(t(e.doc),t(n.doc));return 0!==i?i:(r=e.doc._id)<(o=n.doc._id)?-1:r>o?1:0}}(t.sort);e=e.sort(r),"string"!=typeof t.sort[0]&&"desc"===(o=t.sort[0])[yt(o)]&&(e=e.reverse())}var o;if("limit"in t||"skip"in t){var i=t.skip||0,s=("limit"in t?t.limit:e.length)+i;e=e.slice(i,s)}return e}([{doc:e}],{selector:t=bt(t)},Object.keys(t));return n&&1===n.length}(e,t.selector)},e.doChanges(t);else{var i=de(t.filter);e.db.get("_design/"+i[0],(function(r,o){if(e.isCancelled)return n(null,{status:"cancelled"});if(r)return n(ae(r));var s=o&&o.filters&&o.filters[i[1]];if(!s)return n(se(V,o&&o.filters?"missing json key: "+i[1]:"missing json key: filters"));t.filter=me('"use strict";\nreturn '+s+";",{}),e.doChanges(t)}))}}function Tt(e){return e.reduce((function(e,t){return e[t]=!0,e}),{})}at.plugin((function(e){e._changesFilterPlugin={validate:Dt,normalize:It,shouldFilter:Bt,filter:Rt}})),at.version="7.3.0";var Nt=Tt(["_id","_rev","_access","_attachments","_deleted","_revisions","_revs_info","_conflicts","_deleted_conflicts","_local_seq","_rev_tree","_replication_id","_replication_state","_replication_state_time","_replication_state_reason","_replication_stats","_removed"]),Mt=Tt(["_access","_attachments","_replication_id","_replication_state","_replication_state_time","_replication_state_reason","_replication_stats"]);function Ft(e){if(!/^\d+-/.test(e))return se(oe);var t=e.indexOf("-"),n=e.substring(0,t),r=e.substring(t+1);return{prefix:parseInt(n,10),id:r}}function Ut(e,t,n){var r,o,i;n||(n={deterministic_revs:!0});var s={status:"available"};if(e._deleted&&(s.deleted=!0),t)if(e._id||(e._id=Be()),o=Ie(e,n.deterministic_revs),e._rev){if((i=Ft(e._rev)).error)return i;e._rev_tree=[{pos:i.prefix,ids:[i.id,{status:"missing"},[[o,s,[]]]]}],r=i.prefix+1}else e._rev_tree=[{pos:1,ids:[o,s,[]]}],r=1;else if(e._revisions&&(e._rev_tree=function(e,t){for(var n=e.start-e.ids.length+1,r=e.ids,o=[r[0],t,[]],i=1,s=r.length;i1&&!n?(a={continue:function(){if(!i.length)return o();var n,a=i[i.length-1];if(t&&t.upper)try{n=IDBKeyRange.bound(a,t.upper,!0,t.upperOpen)}catch(e){if("DataError"===e.name&&0===e.code)return o()}else n=IDBKeyRange.lowerBound(a,!0);t=n,i=null,s=null,e.getAll(t,r).onsuccess=c,e.getAllKeys(t,r).onsuccess=u}},e.getAll(t,r).onsuccess=c,e.getAllKeys(t,r).onsuccess=u):n?e.openCursor(t,"prev").onsuccess=f:e.openCursor(t).onsuccess=f}function dn(e,t,n){var r,o,i="startkey"in e&&e.startkey,s="endkey"in e&&e.endkey,a="key"in e&&e.key,c="keys"in e&&e.keys,u=e.skip||0,f="number"==typeof e.limit?e.limit:-1,l=!1!==e.inclusive_end;if(!c&&(r=function(e,t,n,r,o){try{if(e&&t)return o?IDBKeyRange.bound(t,e,!n,!1):IDBKeyRange.bound(e,t,!1,!n);if(e)return o?IDBKeyRange.upperBound(e):IDBKeyRange.lowerBound(e);if(t)return o?IDBKeyRange.lowerBound(t,!n):IDBKeyRange.upperBound(t,!n);if(r)return IDBKeyRange.only(r)}catch(e){return{error:e}}return null}(i,s,l,a,e.descending),(o=r&&r.error)&&("DataError"!==o.name||0!==o.code)))return n(se(re,o.name,o.message));var d=[zt,Vt,Wt];e.attachments&&d.push(Gt);var h=cn(t,d,"readonly");if(h.error)return n(h.error);var p=h.txn;p.oncomplete=function(){e.attachments?sn(w,e.binary).then(q):q()},p.onabort=Zt(n);var v,y,_=p.objectStore(zt),g=p.objectStore(Vt),m=p.objectStore(Wt),b=g.index("_doc_id_rev"),w=[];function k(t,n){var r={id:n.id,key:n.id,value:{rev:t}};n.deleted?c&&(w.push(r),r.value.deleted=!0,r.doc=null):u--<=0&&(w.push(r),e.include_docs&&function(t,n,r){var o=t.id+"::"+r;b.get(o).onsuccess=function(r){if(n.doc=nn(r.target.result)||{},e.conflicts){var o=Fe(t);o.length&&(n.doc._conflicts=o)}on(n.doc,e,p)}}(n,r,t))}function j(e){for(var t=0,n=e.length;t0&&(y=e.target.result[0])}({target:{result:[n]}})}),o||0===f?void 0:c?function(e,t,n){var r=new Array(e.length),o=0;e.forEach((function(i,s){t.get(i).onsuccess=function(t){t.target.result?r[s]=t.target.result:r[s]={key:i,error:"not_found"},++o===e.length&&n(e,r,{})}}))}(e.keys,_,O):-1===f?function(e,t,n){if("function"!=typeof e.getAll){var r=[];e.openCursor(t).onsuccess=function(e){var t=e.target.result;t?(r.push(t.value),t.continue()):n({target:{result:r}})}}else e.getAll(t).onsuccess=n}(_,r,(function(t){var n=t.target.result;e.descending&&(n=n.reverse()),j(n)})):void ln(_,r,e.descending,f+u,O)}var hn=!1,pn=[];function vn(){!hn&&pn.length&&(hn=!0,pn.shift()())}var yn,_n=new h,gn=new h;function mn(e,t){var n=this;!function(t,r,i){pn.push((function(){var t;t=function(e,t){!function(e,t,n,r){try{e(t,n)}catch(t){r.emit("error",t)}}(r,e,t,i),hn=!1,o()((function(){vn()}))},function(e,t,n){var r=t.name,i=null,s=null;function a(e){return function(t,n){t&&t instanceof Error&&!t.reason&&s&&(t.reason=s),e(t,n)}}function c(e){var t=e.createObjectStore(zt,{keyPath:"id"});e.createObjectStore(Vt,{autoIncrement:!0}).createIndex("_doc_id_rev","_doc_id_rev",{unique:!0}),e.createObjectStore(Gt,{keyPath:"digest"}),e.createObjectStore(Wt,{keyPath:"id",autoIncrement:!1}),e.createObjectStore(Ht),t.createIndex("deletedOrLocal","deletedOrLocal",{unique:!1}),e.createObjectStore(Yt,{keyPath:"_id"});var n=e.createObjectStore(Qt,{autoIncrement:!0});n.createIndex("seq","seq"),n.createIndex("digestSeq","digestSeq",{unique:!0})}function u(e,t){var n=e.objectStore(zt);n.createIndex("deletedOrLocal","deletedOrLocal",{unique:!1}),n.openCursor().onsuccess=function(e){var r=e.target.result;if(r){var o=r.value,i=He(o);o.deletedOrLocal=i?"1":"0",n.put(o),r.continue()}else t()}}function f(e){e.createObjectStore(Yt,{keyPath:"_id"}).createIndex("_doc_id_rev","_doc_id_rev",{unique:!0})}function l(e,t){var n=e.objectStore(Yt),r=e.objectStore(zt),o=e.objectStore(Vt);r.openCursor().onsuccess=function(e){var i=e.target.result;if(i){var s=i.value,a=s.id,c=Xe(a),u=Re(s);if(c){var f=a+"::"+u,l=a+"::",d=a+"::~",h=o.index("_doc_id_rev"),p=IDBKeyRange.bound(l,d,!1,!1),v=h.openCursor(p);v.onsuccess=function(e){if(v=e.target.result){var t=v.value;t._doc_id_rev===f&&n.put(t),o.delete(v.primaryKey),v.continue()}else r.delete(i.primaryKey),i.continue()}}else i.continue()}else t&&t()}}function p(e){var t=e.createObjectStore(Qt,{autoIncrement:!0});t.createIndex("seq","seq"),t.createIndex("digestSeq","digestSeq",{unique:!0})}function v(e,t){var n=e.objectStore(Vt),r=e.objectStore(Gt),o=e.objectStore(Qt);r.count().onsuccess=function(e){if(!e.target.result)return t();n.openCursor().onsuccess=function(e){var n=e.target.result;if(!n)return t();for(var r=n.value,i=n.primaryKey,s=Object.keys(r._attachments||{}),a={},c=0;co&&(o=n),t.continue()}}function a(){var e=en(i,i.winningRev,i.deleted);r.put(e).onsuccess=function(){o.continue()}}}}e._meta=null,e._remote=!1,e.type=function(){return"idb"},e._id=L((function(t){t(null,e._meta.instanceId)})),e._bulkDocs=function(n,r,o){fn(t,n,r,e,i,a(o))},e._get=function(e,t,n){var r,o,s,a=t.ctx;if(!a){var c=cn(i,[zt,Vt,Gt],"readonly");if(c.error)return n(c.error);a=c.txn}function u(){n(s,{doc:r,metadata:o,ctx:a})}a.objectStore(zt).get(e).onsuccess=function(e){if(!(o=tn(e.target.result)))return s=se(V,"missing"),u();var n;if(t.rev)n=t.latest?function(e,t){for(var n,r=t.rev_tree.slice();n=r.pop();){var o=n.pos,i=n.ids,s=i[0],a=i[1],c=i[2],u=0===c.length,f=n.history?n.history.slice():[];if(f.push({id:s,pos:o,opts:a}),u)for(var l=0,d=f.length;l=43)},r.onerror=e.onabort=function(e){e.preventDefault(),e.stopPropagation(),t(!1)}})).catch((function(){return!1}))}(f)),yn.then((function(e){c=e,d()})),f.oncomplete=function(){l=!0,d()},f.onabort=Zt(n)},g.onerror=function(e){var t=e.target.error&&e.target.error.message;t?-1!==t.indexOf("stored database is a higher version")&&(t=new Error('This DB was created with the newer "indexeddb" adapter, but you are trying to open it with the older "idb" adapter')):t="Failed to open indexedDB, are you in private browsing mode?",M("error",t),n(se(re,t))}}(n,e,t)})),vn()}(0,t,n.constructor)}mn.valid=function(){try{return"undefined"!=typeof indexedDB&&"undefined"!=typeof IDBKeyRange}catch(e){return!1}};var bn=5e3,wn={};function kn(e){var t=e.doc||e.ok,n=t&&t._attachments;n&&Object.keys(n).forEach((function(e){var t=n[e];t.data=Ae(t.data,t.content_type)}))}function jn(e){return/^_design/.test(e)?"_design/"+encodeURIComponent(e.slice(8)):/^_local/.test(e)?"_local/"+encodeURIComponent(e.slice(7)):encodeURIComponent(e)}function On(e){return e._attachments&&Object.keys(e._attachments)?Promise.all(Object.keys(e._attachments).map((function(t){var n=e._attachments[t];if(n.data&&"string"!=typeof n.data)return new Promise((function(e){Ee(n.data,e)})).then((function(e){n.data=e}))}))):Promise.resolve()}function qn(e,t){return An(e,e.db+"/"+t)}function An(e,t){var n=e.path?"/":"";return e.protocol+"://"+e.host+(e.port?":"+e.port:"")+"/"+e.path+n+t}function Sn(e){return"?"+Object.keys(e).map((function(t){return t+"="+encodeURIComponent(e[t])})).join("&")}function xn(e,t){var n=this,r=function(e,t){if(function(e){if(!e.prefix)return!1;var t=ge(e.prefix).protocol;return"http"===t||"https"===t}(t)){var n=t.name.substr(t.prefix.length);e=t.prefix.replace(/\/?$/,"/")+encodeURIComponent(n)}var r=ge(e);(r.user||r.password)&&(r.auth={username:r.user,password:r.password});var o=r.path.replace(/(^\/|\/$)/g,"").split("/");return r.db=o.pop(),-1===r.db.indexOf("%")&&(r.db=encodeURIComponent(r.db)),r.path=o.join("/"),r}(e.name,e),i=qn(r,"");e=C(e);var s,a=function(t,n){if((n=n||{}).headers=n.headers||new ft,n.credentials="include",e.auth||r.auth){var o=e.auth||r.auth,i=o.username+":"+o.password,s=ke(unescape(encodeURIComponent(i)));n.headers.set("Authorization","Basic "+s)}var a=e.headers||{};return Object.keys(a).forEach((function(e){n.headers.append(e,a[e])})),function(e){var t="undefined"!=typeof navigator&&navigator.userAgent?navigator.userAgent.toLowerCase():"",n=-1!==t.indexOf("msie"),r=-1!==t.indexOf("trident"),o=-1!==t.indexOf("edge"),i=!("method"in e)||"GET"===e.method;return(n||r||o)&&i}(n)&&(t+=(-1===t.indexOf("?")?"?":"&")+"_nonce="+Date.now()),(e.fetch||ut)(t,n)};function c(e,t){return $(e,g()((function(e){f().then((function(){return t.apply(this,e)})).catch((function(t){e.pop()(t)}))}))).bind(n)}function u(e,t,n){var r={};return(t=t||{}).headers=t.headers||new ft,t.headers.get("Content-Type")||t.headers.set("Content-Type","application/json"),t.headers.get("Accept")||t.headers.set("Accept","application/json"),a(e,t).then((function(e){return r.ok=e.ok,r.status=e.status,e.json()})).then((function(e){if(r.data=e,!r.ok){r.data.status=r.status;var t=ae(r.data);if(n)return n(t);throw t}if(Array.isArray(r.data)&&(r.data=r.data.map((function(e){return e.error||e.missing?ae(e):e}))),!n)return r;n(null,r.data)}))}function f(){return e.skip_setup?Promise.resolve():s||((s=u(i).catch((function(e){return e&&e.status&&404===e.status?(U(404,"PouchDB is just detecting if the remote exists."),u(i,{method:"PUT"})):Promise.reject(e)})).catch((function(e){return!(!e||!e.status||412!==e.status)||Promise.reject(e)}))).catch((function(){s=null})),s)}function l(e){return e.split("/").map(encodeURIComponent).join("/")}o()((function(){t(null,n)})),n._remote=!0,n.type=function(){return"http"},n.id=c("id",(function(e){a(An(r,"")).then((function(e){return e.json()})).catch((function(){return{}})).then((function(t){var n=t&&t.uuid?t.uuid+r.db:qn(r,"");e(null,n)}))})),n.compact=c("compact",(function(e,t){"function"==typeof e&&(t=e,e={}),e=C(e),u(qn(r,"_compact"),{method:"POST"}).then((function(){!function r(){n.info((function(n,o){o&&!o.compact_running?t(null,{ok:!0}):setTimeout(r,e.interval||200)}))}()}))})),n.bulkGet=$("bulkGet",(function(e,t){var n=this;function o(t){var n={};e.revs&&(n.revs=!0),e.attachments&&(n.attachments=!0),e.latest&&(n.latest=!0),u(qn(r,"_bulk_get"+Sn(n)),{method:"POST",body:JSON.stringify({docs:e.docs})}).then((function(n){e.attachments&&e.binary&&n.data.results.forEach((function(e){e.docs.forEach(kn)})),t(null,n.data)})).catch(t)}function i(){var r=Math.ceil(e.docs.length/50),o=0,i=new Array(r);function s(e){return function(n,s){i[e]=s.results,++o===r&&t(null,{results:ue(i)})}}for(var a=0;at?t:a;var c=qn(r,"_changes"+Sn(i)),v={signal:p.signal,method:d,body:JSON.stringify(l)};h=n,e.aborted||f().then((function(){return u(c,v,o)})).catch(o)}},y={results:[]},_=function(n,r){if(!e.aborted){var i=0;if(r&&r.results){i=r.results.length,y.last_seq=r.last_seq;var c=null,u=null;"number"==typeof r.pending&&(c=r.pending),"string"!=typeof y.last_seq&&"number"!=typeof y.last_seq||(u=y.last_seq),e.query_params,r.results=r.results.filter((function(t){a--;var n=ce(e)(t);return n&&(e.include_docs&&e.attachments&&e.binary&&kn(t),e.return_docs&&y.results.push(t),e.onChange(t,c,u)),n}))}else if(n)return e.aborted=!0,void e.complete(n);r&&r.last_seq&&(h=r.last_seq);var f=s&&a<=0||r&&i0?e.slice(n):e}function u(e){var t=e.value;return t&&"object"==typeof t&&t._id||e.id}function f(e){return function(t){return e.include_docs&&e.attachments&&e.binary&&function(e){e.rows.forEach((function(e){var t=e.doc&&e.doc._attachments;t&&Object.keys(t).forEach((function(e){var n=t[e];t[e].data=Ae(n.data,n.content_type)}))}))}(t),t}}function l(e,t,n,r){var o=t[e];void 0!==o&&(r&&(o=encodeURIComponent(JSON.stringify(o))),n.push(e+"="+o))}function p(e){if(void 0!==e){var t=Number(e);return isNaN(t)||t!==parseInt(e,10)?e:t}}function v(e,t){var n=e.descending?"endkey":"startkey",r=e.descending?"startkey":"endkey";if(void 0!==e[n]&&void 0!==e[r]&&wt(e[n],e[r])>0)throw new En("No rows can match your key range, reverse your start_key and end_key or set {descending : true}");if(t.reduce&&!1!==e.reduce){if(e.include_docs)throw new En("{include_docs:true} is invalid for reduce");if(e.keys&&e.keys.length>1&&!e.group&&!e.group_level)throw new En("Multi-key fetches for reduce views must use {group: true}")}["group_level","limit","skip"].forEach((function(t){var n=function(e){if(e){if("number"!=typeof e)return new En('Invalid value for integer: "'+e+'"');if(e<0)return new En('Invalid value for positive integer: "'+e+'"')}}(e[t]);if(n)throw n}))}function y(e){return function(t){if(404===t.status)return e;throw t}}function _(e){var t="string"==typeof e?e:e.name,n=zn[t];return n||(n=zn[t]=new Un),n}function m(e,t){return $n(_(e),(function(){return function(e,t){var n,r;var o=function(e,t){if("function"==typeof e&&2===e.length){var n=e;return function(e){return n(e,t)}}return Fn(e.toString(),t)}(e.mapFun,(function(e,t){var o={id:r._id,key:kt(e)};null!=t&&(o.value=kt(t)),n.push(o)})),s=e.seq||0;function c(t,n){return function(){return function(e,t,n){var r="_local/lastSeq";return e.db.get(r).catch(y({_id:r,seq:0})).then((function(r){var o=In(t);return Promise.all(o.map((function(n){return function(e,t,n){var r="_local/doc_"+e,o={_id:r,keys:[]},i=n.get(e),s=i[0];return(function(e){return 1===e.length&&/^1-/.test(e[0].rev)}(i[1])?Promise.resolve(o):t.db.get(r).catch(y(o))).then((function(e){return function(e){return e.keys.length?t.db.allDocs({keys:e.keys,include_docs:!0}):Promise.resolve({rows:[]})}(e).then((function(t){return function(e,t){for(var n=[],r=new d,o=0,i=t.rows.length;o0&&0===wt(i.key,t)&&s.push(r),n.set(jt(s),i),t=i.key}return n}return p().then((function(){return l.finish()})).then((function(){e.seq=s}))}(e,t)}))()}function b(e,t){return $n(_(e),(function(){return function(e,t){var n,r=e.reduceFun&&!1!==t.reduce,o=t.skip||0;function i(t){return t.include_docs=!0,e.db.allDocs(t).then((function(e){return n=e.total_rows,e.rows.map((function(e){if("value"in e.doc&&"object"==typeof e.doc.value&&null!==e.doc.value){var t=Object.keys(e.doc.value).sort(),n=["id","key","value"];if(!(tn))return e.doc.value}var r=function(e){for(var t=[],n=[],r=0;;){var o=e[r++];if("\0"!==o)switch(o){case"1":t.push(null);break;case"2":t.push("1"===e[r]),r++;break;case"3":var i=Ot(e,r);t.push(i.num),r+=i.length;break;case"4":for(var s="";;){var a=e[r];if("\0"===a)break;s+=a,r++}s=s.replace(/\u0001\u0001/g,"\0").replace(/\u0001\u0002/g,"").replace(/\u0002\u0002/g,""),t.push(s);break;case"5":var c={element:[],index:t.length};t.push(c.element),n.push(c);break;case"6":var u={element:{},index:t.length};t.push(u.element),n.push(u);break;default:throw new Error("bad collationIndex or unexpectedly reached end of input: "+o)}else{if(1===t.length)return t.pop();qt(t,n)}}}(e.doc._id);return{key:r[0],id:r[1],value:"value"in e.doc?e.doc.value:null}}))}))}function a(i){var a;if(a=r?function(e,t,n){0===n.group_level&&delete n.group_level;var r=n.group||n.group_level,o=function(e){var t=e.toString(),n=function(e){if(/^_sum/.test(e))return Wn;if(/^_count/.test(e))return Yn;if(/^_stats/.test(e))return Hn;if(/^_/.test(e))throw new Error(e+" is not a supported reduce function.")}(t);return n||Fn(t)}(e.reduceFun),i=[],a=isNaN(n.group_level)?Number.POSITIVE_INFINITY:n.group_level;t.forEach((function(e){var t=i[i.length-1],n=r?e.key:null;if(r&&Array.isArray(n)&&(n=n.slice(0,a)),t&&0===wt(t.groupKey,n))return t.keys.push([e.key,e.id]),void t.values.push(e.value);i.push({keys:[[e.key,e.id]],values:[e.value],groupKey:n})})),t=[];for(var u=0,f=i.length;u0)return function(t){return e.allDocs({keys:t,include_docs:!0,conflicts:!0}).then((function(e){if(r.cancelled)throw new Error("cancelled");e.rows.forEach((function(e){var t;e.deleted||!e.doc||!er(e.value.rev)||(t=e.doc)._attachments&&Object.keys(t._attachments).length>0||function(e){return e._conflicts&&e._conflicts.length>0}(e.doc)||(e.doc._conflicts&&delete e.doc._conflicts,o.push(e.doc),delete n[e.id])}))}))}(t)})).then((function(){var s=function(e){var t=[];return Object.keys(e).forEach((function(n){e[n].missing.forEach((function(e){t.push({id:n,rev:e})}))})),{docs:t,revs:!0,latest:!0}}(n);if(s.docs.length)return e.bulkGet(s).then((function(n){if(r.cancelled)throw new Error("cancelled");return Promise.all(n.results.map((function(n){return Promise.all(n.docs.map((function(n){var r=n.ok;return n.error&&(i=!1),r&&r._attachments?function(e,t,n){var r=le(t)&&!le(e),o=Object.keys(n._attachments);return r?e.get(n._id).then((function(r){return Promise.all(o.map((function(o){return function(e,t,n){return!e._attachments||!e._attachments[n]||e._attachments[n].digest!==t._attachments[n].digest}(r,n,o)?t.getAttachment(n._id,o):e.getAttachment(r._id,o)})))})).catch((function(e){if(404!==e.status)throw e;return tr(t,n)})):tr(t,n)}(t,e,r).then((function(e){var t=Object.keys(r._attachments);return e.forEach((function(e,n){var o=r._attachments[t[n]];delete o.stub,delete o.length,o.data=e})),r})):r})))}))).then((function(e){o=o.concat(ue(e).filter(Boolean))}))}))})).then((function(){return{ok:i,docs:o}}))}var rr="pouchdb";function or(e,t,n,r,o){return e.get(t).catch((function(n){if(404===n.status)return"http"!==e.adapter&&"https"!==e.adapter||U(404,"PouchDB is just checking if a remote checkpoint exists."),{session_id:r,_id:t,history:[],replicator:rr,version:1};throw n})).then((function(i){if(!o.cancelled&&i.last_seq!==n)return i.history=(i.history||[]).filter((function(e){return e.session_id!==r})),i.history.unshift({last_seq:n,session_id:r}),i.history=i.history.slice(0,5),i.version=1,i.replicator=rr,i.session_id=r,i.last_seq=n,e.put(i).catch((function(i){if(409===i.status)return or(e,t,n,r,o);throw i}))}))}function ir(e,t,n,r,o){this.src=e,this.target=t,this.id=n,this.returnValue=r,this.opts=o||{}}ir.prototype.writeCheckpoint=function(e,t){var n=this;return this.updateTarget(e,t).then((function(){return n.updateSource(e,t)}))},ir.prototype.updateTarget=function(e,t){return this.opts.writeTargetCheckpoint?or(this.target,this.id,e,t,this.returnValue):Promise.resolve(!0)},ir.prototype.updateSource=function(e,t){if(this.opts.writeSourceCheckpoint){var n=this;return or(this.src,this.id,e,t,this.returnValue).catch((function(e){if(ur(e))return n.opts.writeSourceCheckpoint=!1,!0;throw e}))}return Promise.resolve(!0)};var sr={undefined:function(e,t){return 0===wt(e.last_seq,t.last_seq)?t.last_seq:0},1:function(e,t){return(n=t,r=e,n.session_id===r.session_id?{last_seq:n.last_seq,history:n.history}:ar(n.history,r.history)).last_seq;var n,r}};function ar(e,t){var n=e[0],r=e.slice(1),o=t[0],i=t.slice(1);return n&&0!==t.length?cr(n.session_id,t)?{last_seq:n.last_seq,history:e}:cr(o.session_id,r)?{last_seq:o.last_seq,history:i}:ar(r,i):{last_seq:0,history:[]}}function cr(e,t){var n=t[0],r=t.slice(1);return!(!e||0===t.length)&&(e===n.session_id||cr(e,r))}function ur(e){return"number"==typeof e.status&&4===Math.floor(e.status/100)}function fr(e,t,n,r,i){var s,a,c,u=[],f={seq:0,changes:[],docs:[]},l=!1,d=!1,h=!1,p=0,v=n.continuous||n.live||!1,y=n.batch_size||100,_=n.batches_limit||10,g=n.style||"all_docs",m=!1,b=n.doc_ids,w=n.selector,k=[],j=Be();i=i||{ok:!0,start_time:(new Date).toISOString(),docs_read:0,docs_written:0,doc_write_failures:0,errors:[]};var O={};function q(){return c?Promise.resolve():function(e,t,n){var r=n.doc_ids?n.doc_ids.sort(wt):"",o=n.filter?n.filter.toString():"",i="",s="",a="";return n.selector&&(a=JSON.stringify(n.selector)),n.filter&&n.query_params&&(i=JSON.stringify(function(e){return Object.keys(e).sort(wt).reduce((function(t,n){return t[n]=e[n],t}),{})}(n.query_params))),n.filter&&"_view"===n.filter&&(s=n.view.toString()),Promise.all([e.id(),t.id()]).then((function(e){var t=e[0]+e[1]+o+s+i+r+a;return new Promise((function(e){$e(t,e)}))})).then((function(e){return"_local/"+e.replace(/\//g,".").replace(/\+/g,"_")}))}(e,t,n).then((function(o){a=o;var i;i=!1===n.checkpoint?{writeSourceCheckpoint:!1,writeTargetCheckpoint:!1}:"source"===n.checkpoint?{writeSourceCheckpoint:!0,writeTargetCheckpoint:!1}:"target"===n.checkpoint?{writeSourceCheckpoint:!1,writeTargetCheckpoint:!0}:{writeSourceCheckpoint:!0,writeTargetCheckpoint:!0},c=new ir(e,t,a,r,i)}))}function A(){if(k=[],0!==s.docs.length){var e=s.docs,o={timeout:n.timeout};return t.bulkDocs({docs:e,new_edits:!1},o).then((function(t){if(r.cancelled)throw $(),new Error("cancelled");var n=Object.create(null);t.forEach((function(e){e.error&&(n[e.id]=e)}));var o=Object.keys(n).length;i.doc_write_failures+=o,i.docs_written+=e.length-o,e.forEach((function(e){var t=n[e._id];if(t){i.errors.push(t);var o=(t.name||"").toLowerCase();if("unauthorized"!==o&&"forbidden"!==o)throw t;r.emit("denied",C(t))}else k.push(e)}))}),(function(t){throw i.doc_write_failures+=e.length,t}))}}function S(){if(s.error)throw new Error("There was a problem getting docs.");i.last_seq=p=s.seq;var e=C(i);return k.length&&(e.docs=k,"number"==typeof s.pending&&(e.pending=s.pending,delete s.pending),r.emit("change",e)),l=!0,c.writeCheckpoint(s.seq,j).then((function(){if(r.emit("checkpoint",{checkpoint:s.seq}),l=!1,r.cancelled)throw $(),new Error("cancelled");s=void 0,R()})).catch((function(e){throw N(e),e}))}function x(){return nr(e,t,s.diffs,r).then((function(e){s.error=!e.ok,e.docs.forEach((function(e){delete s.diffs[e._id],i.docs_read++,s.docs.push(e)}))}))}function E(){var e;r.cancelled||s||(0!==u.length?(s=u.shift(),r.emit("checkpoint",{start_next_batch:s.seq}),(e={},s.changes.forEach((function(t){r.emit("checkpoint",{revs_diff:t}),"_user/"!==t.id&&(e[t.id]=t.changes.map((function(e){return e.rev})))})),t.revsDiff(e).then((function(e){if(r.cancelled)throw $(),new Error("cancelled");s.diffs=e}))).then(x).then(A).then(S).then(E).catch((function(e){L("batch processing terminated with error",e)}))):P(!0))}function P(e){0!==f.changes.length?(e||d||f.changes.length>=y)&&(u.push(f),f={seq:0,changes:[],docs:[]},"pending"!==r.state&&"stopped"!==r.state||(r.state="active",r.emit("active")),E()):0!==u.length||s||((v&&O.live||d)&&(r.state="pending",r.emit("paused")),d&&$())}function L(e,t){h||(t.message||(t.message=e),i.ok=!1,i.status="aborting",u=[],f={seq:0,changes:[],docs:[]},$(t))}function $(o){if(!(h||r.cancelled&&(i.status="cancelled",l)))if(i.status=i.status||"complete",i.end_time=(new Date).toISOString(),i.last_seq=p,h=!0,o){(o=se(o)).result=i;var s=(o.name||"").toLowerCase();"unauthorized"===s||"forbidden"===s?(r.emit("error",o),r.removeAllListeners()):function(e,t,n,r){if(!1===e.retry)return t.emit("error",n),void t.removeAllListeners();if("function"!=typeof e.back_off_function&&(e.back_off_function=F),t.emit("requestError",n),"active"===t.state||"pending"===t.state){t.emit("paused",n),t.state="stopped";var o=function(){e.current_back_off=0};t.once("paused",(function(){t.removeListener("active",o)})),t.once("active",o)}e.current_back_off=e.current_back_off||0,e.current_back_off=e.back_off_function(e.current_back_off),setTimeout(r,e.current_back_off)}(n,r,o,(function(){fr(e,t,n,r)}))}else r.emit("complete",i),r.removeAllListeners()}function D(e,t,i){if(r.cancelled)return $();"number"==typeof t&&(f.pending=t),ce(n)(e)&&(f.seq=e.seq||i,f.changes.push(e),r.emit("checkpoint",{pending_batch:f.seq}),o()((function(){P(0===u.length&&O.live)})))}function I(e){if(m=!1,r.cancelled)return $();if(e.results.length>0)O.since=e.results[e.results.length-1].seq,R(),P(!0);else{var t=function(){v?(O.live=!0,R()):d=!0,P(!0)};s||0!==e.results.length?t():(l=!0,c.writeCheckpoint(e.last_seq,j).then((function(){l=!1,i.last_seq=p=e.last_seq,t()})).catch(N))}}function B(e){if(m=!1,r.cancelled)return $();L("changes rejected",e)}function R(){if(!m&&!d&&u.length<_){m=!0,r._changes&&(r.removeListener("cancel",r._abortChanges),r._changes.cancel()),r.once("cancel",o);var t=e.changes(O).on("change",D);t.then(i,i),t.then(I).catch(B),n.retry&&(r._changes=t,r._abortChanges=o)}function o(){t.cancel()}function i(){r.removeListener("cancel",o)}}function T(){q().then((function(){if(!r.cancelled)return c.getCheckpoint().then((function(e){O={since:p=e,limit:y,batch_size:y,style:g,doc_ids:b,selector:w,return_docs:!0},n.filter&&("string"!=typeof n.filter?O.include_docs=!0:O.filter=n.filter),"heartbeat"in n&&(O.heartbeat=n.heartbeat),"timeout"in n&&(O.timeout=n.timeout),n.query_params&&(O.query_params=n.query_params),n.view&&(O.view=n.view),R()}));$()})).catch((function(e){L("getCheckpoint rejected with ",e)}))}function N(e){l=!1,L("writeCheckpoint completed with error",e)}r.ready(e,t),r.cancelled?$():(r._addedListeners||(r.once("cancel",$),"function"==typeof n.complete&&(r.once("error",n.complete),r.once("complete",(function(e){n.complete(null,e)}))),r._addedListeners=!0),void 0===n.since?T():q().then((function(){return l=!0,c.writeCheckpoint(n.since,j)})).then((function(){l=!1,r.cancelled?$():(p=n.since,T())})).catch(N))}function lr(){k().call(this),this.cancelled=!1,this.state="pending";var e=this,t=new Promise((function(t,n){e.once("complete",t),e.once("error",n)}));e.then=function(e,n){return t.then(e,n)},e.catch=function(e){return t.catch(e)},e.catch((function(){}))}function dr(e,t){var n=t.PouchConstructor;return"string"==typeof e?new n(e,t):e}function hr(e,t,n,r){if("function"==typeof n&&(r=n,n={}),void 0===n&&(n={}),n.doc_ids&&!Array.isArray(n.doc_ids))throw se(te,"`doc_ids` filter parameter is not a list.");n.complete=r,(n=C(n)).continuous=n.continuous||n.live,n.retry="retry"in n&&n.retry,n.PouchConstructor=n.PouchConstructor||this;var o=new lr(n);return fr(dr(e,n),dr(t,n),n,o),o}function pr(e,t,n,r){return"function"==typeof n&&(r=n,n={}),void 0===n&&(n={}),(n=C(n)).PouchConstructor=n.PouchConstructor||this,new vr(e=dr(e,n),t=dr(t,n),n,r)}function vr(e,t,n,r){var o=this;this.canceled=!1;var i=n.push?K({},n,n.push):n,s=n.pull?K({},n,n.pull):n;function a(e){o.emit("change",{direction:"pull",change:e})}function c(e){o.emit("change",{direction:"push",change:e})}function u(e){o.emit("denied",{direction:"push",doc:e})}function f(e){o.emit("denied",{direction:"pull",doc:e})}function l(){o.pushPaused=!0,o.pullPaused&&o.emit("paused")}function d(){o.pullPaused=!0,o.pushPaused&&o.emit("paused")}function h(){o.pushPaused=!1,o.pullPaused&&o.emit("active",{direction:"push"})}function p(){o.pullPaused=!1,o.pushPaused&&o.emit("active",{direction:"pull"})}this.push=hr(e,t,i),this.pull=hr(t,e,s),this.pushPaused=!0,this.pullPaused=!0;var v={};function y(e){return function(t,n){("change"===t&&(n===a||n===c)||"denied"===t&&(n===f||n===u)||"paused"===t&&(n===d||n===l)||"active"===t&&(n===p||n===h))&&(t in v||(v[t]={}),v[t][e]=!0,2===Object.keys(v[t]).length&&o.removeAllListeners(t))}}function _(e,t,n){-1==e.listeners(t).indexOf(n)&&e.on(t,n)}n.live&&(this.push.on("complete",o.pull.cancel.bind(o.pull)),this.pull.on("complete",o.push.cancel.bind(o.push))),this.on("newListener",(function(e){"change"===e?(_(o.pull,"change",a),_(o.push,"change",c)):"denied"===e?(_(o.pull,"denied",f),_(o.push,"denied",u)):"active"===e?(_(o.pull,"active",p),_(o.push,"active",h)):"paused"===e&&(_(o.pull,"paused",d),_(o.push,"paused",l))})),this.on("removeListener",(function(e){"change"===e?(o.pull.removeListener("change",a),o.push.removeListener("change",c)):"denied"===e?(o.pull.removeListener("denied",f),o.push.removeListener("denied",u)):"active"===e?(o.pull.removeListener("active",p),o.push.removeListener("active",h)):"paused"===e&&(o.pull.removeListener("paused",d),o.push.removeListener("paused",l))})),this.pull.on("removeListener",y("pull")),this.push.on("removeListener",y("push"));var g=Promise.all([this.push,this.pull]).then((function(e){var t={push:e[0],pull:e[1]};return o.emit("complete",t),r&&r(null,t),o.removeAllListeners(),t}),(function(e){if(o.cancel(),r?r(e):o.emit("error",e),o.removeAllListeners(),r)throw e}));this.then=function(e,t){return g.then(e,t)},this.catch=function(e){return g.catch(e)}}ir.prototype.getCheckpoint=function(){var e=this;return e.opts&&e.opts.writeSourceCheckpoint&&!e.opts.writeTargetCheckpoint?e.src.get(e.id).then((function(e){return e.last_seq||0})).catch((function(e){if(404!==e.status)throw e;return 0})):e.target.get(e.id).then((function(t){return e.opts&&e.opts.writeTargetCheckpoint&&!e.opts.writeSourceCheckpoint?t.last_seq||0:e.src.get(e.id).then((function(e){return t.version!==e.version?0:(n=t.version?t.version.toString():"undefined")in sr?sr[n](t,e):0;var n}),(function(n){if(404===n.status&&t.last_seq)return e.src.put({_id:e.id,last_seq:0}).then((function(){return 0}),(function(n){return ur(n)?(e.opts.writeSourceCheckpoint=!1,t.last_seq):0}));throw n}))})).catch((function(e){if(404!==e.status)throw e;return 0}))},b()(lr,k()),lr.prototype.cancel=function(){this.cancelled=!0,this.state="cancelled",this.emit("cancel")},lr.prototype.ready=function(e,t){var n=this;function r(){n.cancel()}function o(){e.removeListener("destroyed",r),t.removeListener("destroyed",r)}n._readyCalled||(n._readyCalled=!0,e.once("destroyed",r),t.once("destroyed",r),n.once("complete",o),n.once("error",o))},b()(vr,k()),vr.prototype.cancel=function(){this.canceled||(this.canceled=!0,this.push.cancel(),this.pull.cancel())},at.plugin((function(e){e.adapter("idb",mn,!0)})).plugin((function(e){e.adapter("http",xn,!1),e.adapter("https",xn,!1)})).plugin(Zn).plugin((function(e){e.replicate=hr,e.sync=pr,Object.defineProperty(e.prototype,"replicate",{get:function(){var e=this;return void 0===this.replicateMethods&&(this.replicateMethods={from:function(t,n,r){return e.constructor.replicate(t,e,n,r)},to:function(t,n,r){return e.constructor.replicate(e,t,n,r)}}),this.replicateMethods}}),e.prototype.sync=function(e,t,n){return this.constructor.sync(this,e,t,n)}}));const yr=at})();var o=r.o;export{o as PouchDB}; \ No newline at end of file +var e={105:e=>{e.exports=function(e){return function(){var t=arguments.length;if(t){for(var n=[],r=-1;++r{var t,n="object"==typeof Reflect?Reflect:null,r=n&&"function"==typeof n.apply?n.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)};t=n&&"function"==typeof n.ownKeys?n.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var i=Number.isNaN||function(e){return e!=e};function o(){o.init.call(this)}e.exports=o,e.exports.once=function(e,t){return new Promise((function(n,r){function i(n){e.removeListener(t,o),r(n)}function o(){"function"==typeof e.removeListener&&e.removeListener("error",i),n([].slice.call(arguments))}v(e,t,o,{once:!0}),"error"!==t&&function(e,t,n){"function"==typeof e.on&&v(e,"error",t,{once:!0})}(e,i)}))},o.EventEmitter=o,o.prototype._events=void 0,o.prototype._eventsCount=0,o.prototype._maxListeners=void 0;var s=10;function a(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function u(e){return void 0===e._maxListeners?o.defaultMaxListeners:e._maxListeners}function c(e,t,n,r){var i,o,s,c;if(a(n),void 0===(o=e._events)?(o=e._events=Object.create(null),e._eventsCount=0):(void 0!==o.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),o=e._events),s=o[t]),void 0===s)s=o[t]=n,++e._eventsCount;else if("function"==typeof s?s=o[t]=r?[n,s]:[s,n]:r?s.unshift(n):s.push(n),(i=u(e))>0&&s.length>i&&!s.warned){s.warned=!0;var f=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");f.name="MaxListenersExceededWarning",f.emitter=e,f.type=t,f.count=s.length,c=f,console&&console.warn&&console.warn(c)}return e}function f(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function l(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},i=f.bind(r);return i.listener=n,r.wrapFn=i,i}function d(e,t,n){var r=e._events;if(void 0===r)return[];var i=r[t];return void 0===i?[]:"function"==typeof i?n?[i.listener||i]:[i]:n?function(e){for(var t=new Array(e.length),n=0;n0&&(s=t[0]),s instanceof Error)throw s;var a=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw a.context=s,a}var u=o[e];if(void 0===u)return!1;if("function"==typeof u)r(u,this,t);else{var c=u.length,f=p(u,c);for(n=0;n=0;o--)if(n[o]===t||n[o].listener===t){s=n[o].listener,i=o;break}if(i<0)return this;0===i?n.shift():function(e,t){for(;t+1=0;r--)this.removeListener(e,t[r]);return this},o.prototype.listeners=function(e){return d(this,e,!0)},o.prototype.rawListeners=function(e){return d(this,e,!1)},o.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):h.call(e,t)},o.prototype.listenerCount=h,o.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]}},624:(e,t,n)=>{var r,i,o,s=[n(525),n(785),n(291),n(709),n(506),n(176)],a=-1,u=[],c=!1;function f(){r&&i&&(r=!1,i.length?u=i.concat(u):a=-1,u.length&&l())}function l(){if(!r){c=!1,r=!0;for(var e=u.length,t=setTimeout(f);e;){for(i=u,u=[];i&&++a1)for(var n=1;n{t.test=function(){return!n.g.setImmediate&&void 0!==n.g.MessageChannel},t.install=function(e){var t=new n.g.MessageChannel;return t.port1.onmessage=e,function(){t.port2.postMessage(0)}}},291:(e,t,n)=>{var r=n.g.MutationObserver||n.g.WebKitMutationObserver;t.test=function(){return r},t.install=function(e){var t=0,i=new r(e),o=n.g.document.createTextNode("");return i.observe(o,{characterData:!0}),function(){o.data=t=++t%2}}},785:(e,t,n)=>{t.test=function(){return"function"==typeof n.g.queueMicrotask},t.install=function(e){return function(){n.g.queueMicrotask(e)}}},506:(e,t,n)=>{t.test=function(){return"document"in n.g&&"onreadystatechange"in n.g.document.createElement("script")},t.install=function(e){return function(){var t=n.g.document.createElement("script");return t.onreadystatechange=function(){e(),t.onreadystatechange=null,t.parentNode.removeChild(t),t=null},n.g.document.documentElement.appendChild(t),e}}},176:(e,t)=>{t.test=function(){return!0},t.install=function(e){return function(){setTimeout(e,0)}}},717:e=>{"function"==typeof Object.create?e.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:e.exports=function(e,t){if(t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}}},198:(e,t,n)=>{n.d(t,{Z:()=>fr});var r,i,o=n(624),s=n.n(o),a=n(586),u=n(322),c=n.n(u),f=n(684),l=n(105),d=n.n(l),h=n(717),p=n.n(h),v=n(187),y=n.n(v);function g(e){return"$"+e}function _(e){return e.substring(1)}function m(){this._store={}}function b(e){if(this._store=new m,e&&Array.isArray(e))for(var t=0,n=e.length;t_(e)))},m.prototype.delete=function(e){var t=g(e),n=t in this._store;return delete this._store[t],n},m.prototype.forEach=function(e){for(var t=Object.keys(this._store),n=0,r=t.length;n=c.length)){var i=Math.min(f+6,c.length),l=c.slice(f,i);!function(i,c){i.forEach((function(i,f){var l=c+f,d=o.get(i),h=A(d[0],["atts_since","attachments"]);h.open_revs=d.map((function(e){return e.rev})),h.open_revs=h.open_revs.filter(S);var p=S;0===h.open_revs.length&&(delete h.open_revs,p=E),["revs","attachments","binary","ajax","latest"].forEach((function(e){e in t&&(h[e]=t[e])})),e.get(i,h,(function(e,t){var o,c,f,d;o=e?[{error:e}]:p(t),c=i,f=o,u[l]={id:c,docs:f},++a===s&&(d=[],u.forEach((function(e){e.docs.forEach((function(t){d.push({id:e.id,docs:[t]})}))})),n(null,{results:d})),r()}))}))}(l,f),f+=l.length}}()}try{localStorage.setItem("_pouch_check_localstorage",1),w=!!localStorage.getItem("_pouch_check_localstorage")}catch(e){w=!1}function C(){return w}function D(){y().call(this),this._listeners={},function(e){C()&&addEventListener("storage",(function(t){e.emit(t.key)}))}(this)}function L(e){if("undefined"!=typeof console&&"function"==typeof console[e]){var t=Array.prototype.slice.call(arguments,1);console[e].apply(console,t)}}function B(e){var t=0;return e||(t=2e3),function(e,t){var n=6e5;return e=parseInt(e,10)||0,(t=parseInt(t,10))!=t||t<=e?t=(e||1)<<1:t+=1,t>n&&(e=3e5,t=n),~~((t-e)*Math.random()+e)}(e,t)}function I(e,t){L("info","The above "+e+" is totally normal. "+t)}p()(D,y()),D.prototype.addListener=function(e,t,n,r){if(!this._listeners[t]){var i=this,o=!1;this._listeners[t]=a,this.on(e,a)}function a(){if(i._listeners[t])if(o)o="waiting";else{o=!0;var e=A(r,["style","include_docs","attachments","conflicts","filter","doc_ids","view","since","query_params","binary","return_docs"]);n.changes(e).on("change",(function(e){e.seq>r.since&&!r.cancelled&&(r.since=e.seq,r.onChange(e))})).on("complete",(function(){"waiting"===o&&s()(a),o=!1})).on("error",(function(){o=!1}))}}},D.prototype.removeListener=function(e,t){t in this._listeners&&(y().prototype.removeListener.call(this,e,this._listeners[t]),delete this._listeners[t])},D.prototype.notifyLocalWindows=function(e){C()&&(localStorage[e]="a"===localStorage[e]?"b":"a")},D.prototype.notify=function(e){this.emit(e),this.notifyLocalWindows(e)};var T="function"==typeof Object.assign?Object.assign:function(e){for(var t=Object(e),n=1;n0||r0||r>>1],t)<0?i=r+1:o=r;return i}(e,t,n);e.splice(r,0,t)}function Ne(e,t){for(var n,r,i=t,o=e.length;i0;){var i=n.pop(),o=i.tree1,s=i.tree2;(o[1].status||s[1].status)&&(o[1].status="available"===o[1].status||"available"===s[1].status?"available":"missing");for(var a=0;a0;){var v=p.pop();if(0!==v.diff)for(var y=v.ids[2],g=0,_=y.length;g<_;g++)p.push({ids:y[g],diff:v.diff-1,parent:v.ids,parentIdx:g});else v.ids[0]===l.ids[0]&&h.push(v)}var m=h[0];m?(r=Fe(m.ids,l.ids),m.parent[2][m.parentIdx]=r.tree,i.push({pos:f.pos,ids:f.ids}),o=o||r.conflicts,s=!0):i.push(c)}else i.push(c)}return s||i.push(t),i.sort(Te),{tree:i,conflicts:o||"internal_node"}}function ze(e,t,n){var r=Ue(e,t),i=function(e,t){for(var n,r,i=Ie(e),o=0,s=i.length;ot){n||(n={});var f=c.length-t;a={pos:u.pos+f,ids:Ne(c,f)};for(var l=0;l0&&r.emit("error",t)):r.emit("complete",n),r.removeAllListeners(),e.removeListener("destroyed",o)}));function o(){r.cancel()}n&&(r.on("complete",(function(e){n(null,e)})),r.on("error",n)),e.once("destroyed",o),t.onChange=function(e,t,n){r.isCancelled||function(e,t,n,r){try{e.emit("change",t,n,r)}catch(e){L("error",'Error in .on("change", function):',e)}}(r,e,t,n)};var s=new Promise((function(e,n){t.complete=function(t,r){t?n(t):e(r)}}));r.once("cancel",(function(){e.removeListener("destroyed",o),t.complete(null,{status:"cancelled"})})),this.then=s.then.bind(s),this.catch=s.catch.bind(s),this.then((function(e){i(null,e)}),i),e.taskqueue.isReady?r.validateChanges(t):e.taskqueue.addTask((function(e){e?t.complete(e):r.isCancelled?r.emit("cancel"):r.validateChanges(t)}))}function Ge(e,t,n){var r=[{rev:e._rev}];"all_docs"===n.style&&(r=Le(t.rev_tree).map((function(e){return{rev:e.rev}})));var i={id:t.id,changes:r,doc:e};return Ke(t,e._rev)&&(i.deleted=!0),n.conflicts&&(i.doc._conflicts=Be(t),i.doc._conflicts.length||delete i.doc._conflicts),i}function We(e,t){return et?1:0}function Ze(e,t){return function(n,r){n||r[0]&&r[0].error?((n=n||r[0]).docId=t,e(n)):e(null,r.length?r[0]:r)}}function Xe(e,t){var n=We(e._id,t._id);return 0!==n?n:We(e._revisions?e._revisions.start:0,t._revisions?t._revisions.start:0)}function Ye(e){var t=e._compactionQueue[0],n=t.opts,r=t.callback;e.get("_local/compaction").catch((function(){return!1})).then((function(t){t&&t.last_seq&&(n.last_seq=t.last_seq),e._compact(n,(function(t,n){t?r(t):r(null,n),s()((function(){e._compactionQueue.shift(),e._compactionQueue.length&&Ye(e)}))}))}))}function He(){for(var e in y().call(this),He.prototype)"function"==typeof this[e]&&(this[e]=this[e].bind(this))}function et(){this.isReady=!1,this.failed=!1,this.queue=[]}function tt(e,t){if(!(this instanceof tt))return new tt(e,t);var n=this;if(t=t||{},e&&"object"==typeof e&&(e=(t=e).name,delete t.name),void 0===t.deterministic_revs&&(t.deterministic_revs=!0),this.__opts=t=O(t),n.auto_compaction=t.auto_compaction,n.prefix=tt.prefix,"string"!=typeof e)throw new Error("Missing/invalid DB name");var r=function(e,t){var n=e.match(/([a-z-]*):\/\/(.*)/);if(n)return{name:/https?/.test(n[1])?n[1]+"://"+n[2]:n[2],adapter:n[1]};var r=tt.adapters,i=tt.preferredAdapters,o=tt.prefix,s=t.adapter;if(!s)for(var a=0;at&&a.push(e)})),Ce(o,(function(e,t,n,r,i){var o=t+"-"+n;"available"===i.status&&-1!==a.indexOf(o)&&u.push(o)})),r._doCompaction(e,u,n)}))})),He.prototype.compact=q("compact",(function(e,t){"function"==typeof e&&(t=e,e={});var n=this;e=e||{},n._compactionQueue=n._compactionQueue||[],n._compactionQueue.push({opts:e,callback:t}),1===n._compactionQueue.length&&Ye(n)})),He.prototype._compact=function(e,t){var n=this,r={return_docs:!1,last_seq:e.last_seq||0},i=[];n.changes(r).on("change",(function(e){i.push(n.compactDocument(e.id,0))})).on("complete",(function(e){var r=e.last_seq;Promise.all(i).then((function(){return pe(n,"_local/compaction",(function(e){return(!e.last_seq||e.last_seq0?e.keys.slice(e.skip):e.keys;e.keys=t,e.skip=0,delete e.limit,e.descending&&(t.reverse(),e.descending=!1)}(e),0===e.keys.length))return this._allDocs({limit:0},t)}return this._allDocs(e,t)})),He.prototype.changes=function(e,t){return"function"==typeof e&&(t=e,e={}),(e=e||{}).return_docs="return_docs"in e?e.return_docs:!e.live,new Qe(this,e,t)},He.prototype.close=q("close",(function(e){return this._closed=!0,this.emit("closed"),this._close(e)})),He.prototype.info=q("info",(function(e){var t=this;this._info((function(n,r){if(n)return e(n);r.db_name=r.db_name||t.name,r.auto_compaction=!(!t.auto_compaction||oe(t)),r.adapter=t.adapter,e(null,r)}))})),He.prototype.id=q("id",(function(e){return this._id(e)})),He.prototype.type=function(){return"function"==typeof this._type?this._type():this.adapter},He.prototype.bulkDocs=q("bulkDocs",(function(e,t,n){if("function"==typeof t&&(n=t,t={}),t=t||{},Array.isArray(e)&&(e={docs:e}),!e||!e.docs||!Array.isArray(e.docs))return n(ee(N));for(var r=0;r0&&"\\"===e[r-1]&&("$"===o||"."===o)?n=n.substring(0,n.length-1)+o:"."===o?(t.push(n),n=""):n+=o}return t.push(n),t}!function(e){Object.keys(y().prototype).forEach((function(t){"function"==typeof y().prototype[t]&&(e[t]=ot[t].bind(ot))}));var t=e._destructionListeners=new i;e.on("ref",(function(e){t.has(e.name)||t.set(e.name,[]),t.get(e.name).push(e)})),e.on("unref",(function(e){if(t.has(e.name)){var n=t.get(e.name),r=n.indexOf(e);r<0||(n.splice(r,1),n.length>1?t.set(e.name,n):t.delete(e.name))}})),e.on("destroyed",(function(e){if(t.has(e)){var n=t.get(e);t.delete(e),n.forEach((function(e){e.emit("destroyed",!0)}))}}))}(tt),tt.adapter=function(e,t,n){t.valid()&&(tt.adapters[e]=t,n&&tt.preferredAdapters.push(e))},tt.plugin=function(e){if("function"==typeof e)e(tt);else{if("object"!=typeof e||0===Object.keys(e).length)throw new Error('Invalid plugin: got "'+e+'", expected an object or a function');Object.keys(e).forEach((function(t){tt.prototype[t]=e[t]}))}return this.__defaults&&(tt.__defaults=T({},this.__defaults)),tt},tt.defaults=function(e){function t(e,n){if(!(this instanceof t))return new t(e,n);n=n||{},e&&"object"==typeof e&&(e=(n=e).name,delete n.name),n=T({},t.__defaults,n),tt.call(this,e,n)}return p()(t,tt),t.preferredAdapters=tt.preferredAdapters.slice(),Object.keys(tt).forEach((function(e){e in t||(t[e]=tt[e])})),t.__defaults=T({},this.__defaults,e),t},tt.fetch=function(e,t){return rt(e,t)};var ut=["$or","$nor","$not"];function ct(e){return ut.indexOf(e)>-1}function ft(e){return Object.keys(e)[0]}function lt(e){var t={},n={$or:!0,$nor:!0};return e.forEach((function(e){Object.keys(e).forEach((function(r){var i=e[r];if("object"!=typeof i&&(i={$eq:i}),ct(r))if(i instanceof Array){if(n[r])return n[r]=!1,void(t[r]=i);var o=[];t[r].forEach((function(e){Object.keys(i).forEach((function(t){var n=i[t],r=Math.max(Object.keys(e).length,Object.keys(n).length),s=lt([e,n]);Object.keys(s).length<=r||o.push(s)}))})),t[r]=o}else t[r]=lt([i]);else{var s=t[r]=t[r]||{};Object.keys(i).forEach((function(e){var t=i[e];return"$gt"===e||"$gte"===e?function(e,t,n){void 0===n.$eq&&(void 0!==n.$gte?"$gte"===e?t>n.$gte&&(n.$gte=t):t>=n.$gte&&(delete n.$gte,n.$gt=t):void 0!==n.$gt?"$gte"===e?t>n.$gt&&(delete n.$gt,n.$gte=t):t>n.$gt&&(n.$gt=t):n[e]=t)}(e,t,s):"$lt"===e||"$lte"===e?function(e,t,n){void 0===n.$eq&&(void 0!==n.$lte?"$lte"===e?tt?1:-1}(e,t)}return Array.isArray(e)?function(e,t){for(var n=Math.min(e.length,t.length),r=0;rt.length?1:-1}(e,t):function(e,t){for(var n=Object.keys(e),r=Object.keys(t),i=Math.min(n.length,r.length),o=0;or.length?1:-1}(e,t)}function yt(e){switch(typeof e){case"undefined":return null;case"number":return e===1/0||e===-1/0||isNaN(e)?null:e;case"object":var t=e;if(Array.isArray(e)){var n=e.length;e=new Array(n);for(var r=0;r0)return!1;var a=st(r,s);return"object"==typeof o?kt(o,t,n,a):jt("$eq",t,o,s,a)})):e===r)}function jt(e,t,n,r,i){if(!qt[e])throw new Error('unknown operator "'+e+'" - should be one of $eq, $lte, $lt, $gt, $gte, $exists, $ne, $in, $nin, $size, $mod, $regex, $elemMatch, $type, $allMatch or $all');return qt[e](t,n,r,i)}function Ot(e){return null!=e}function $t(e){return void 0!==e}function xt(e,t){return t.some((function(t){return e instanceof Array?e.some((function(e){return 0===vt(t,e)})):0===vt(t,e)}))}var qt={$elemMatch:function(e,t,n,r){return!!Array.isArray(r)&&0!==r.length&&("object"==typeof r[0]?r.some((function(e){return wt(e,t,Object.keys(t))})):r.some((function(r){return kt(t,e,n,r)})))},$allMatch:function(e,t,n,r){return!!Array.isArray(r)&&0!==r.length&&("object"==typeof r[0]?r.every((function(e){return wt(e,t,Object.keys(t))})):r.every((function(r){return kt(t,e,n,r)})))},$eq:function(e,t,n,r){return $t(r)&&0===vt(r,t)},$gte:function(e,t,n,r){return $t(r)&&vt(r,t)>=0},$gt:function(e,t,n,r){return $t(r)&&vt(r,t)>0},$lte:function(e,t,n,r){return $t(r)&&vt(r,t)<=0},$lt:function(e,t,n,r){return $t(r)&&vt(r,t)<0},$exists:function(e,t,n,r){return t?$t(r):!$t(r)},$mod:function(e,t,n,r){return Ot(r)&&function(e,t){return"number"==typeof e&&parseInt(e,10)===e&&e%t[0]===t[1]}(r,t)},$ne:function(e,t,n,r){return t.every((function(e){return 0!==vt(r,e)}))},$in:function(e,t,n,r){return Ot(r)&&xt(r,t)},$nin:function(e,t,n,r){return Ot(r)&&!xt(r,t)},$size:function(e,t,n,r){return Ot(r)&&Array.isArray(r)&&function(e,t){return e.length===t}(r,t)},$all:function(e,t,n,r){return Array.isArray(r)&&function(e,t){return t.every((function(t){return e.some((function(e){return 0===vt(t,e)}))}))}(r,t)},$regex:function(e,t,n,r){return Ot(r)&&"string"==typeof r&&t.every((function(e){return function(e,t){return new RegExp(t).test(e)}(r,e)}))},$type:function(e,t,n,r){return function(e,t){switch(t){case"null":return null===e;case"boolean":return"boolean"==typeof e;case"number":return"number"==typeof e;case"string":return"string"==typeof e;case"array":return e instanceof Array;case"object":return"[object Object]"==={}.toString.call(e)}}(r,t)}};function At(e,t){if(e.selector&&e.filter&&"_selector"!==e.filter){var n="string"==typeof e.filter?e.filter:"function";return t(new Error('selector invalid for filter "'+n+'"'))}t()}function St(e){e.view&&!e.filter&&(e.filter="_view"),e.selector&&!e.filter&&(e.filter="_selector"),e.filter&&"string"==typeof e.filter&&("_view"===e.filter?e.view=ae(e.view):e.filter=ae(e.filter))}function Et(e,t){return t.filter&&"string"==typeof t.filter&&!t.doc_ids&&!oe(e.db)}function Pt(e,t){var n=t.complete;if("_view"===t.filter){if(!t.view||"string"!=typeof t.view){var r=ee(W,"`view` filter parameter not found or invalid.");return n(r)}var i=se(t.view);e.db.get("_design/"+i[0],(function(r,o){if(e.isCancelled)return n(null,{status:"cancelled"});if(r)return n(te(r));var s=o&&o.views&&o.views[i[1]]&&o.views[i[1]].map;if(!s)return n(ee(R,o.views?"missing json key: "+i[1]:"missing json key: views"));t.filter=he(["return function(doc) {",' "use strict";'," var emitted = false;"," var emit = function (a, b) {"," emitted = true;"," };"," var view = "+s+";"," view(doc);"," if (emitted) {"," return true;"," }","};"].join("\n"),{}),e.doChanges(t)}))}else if(t.selector)t.filter=function(e){return function(e,t){if("object"!=typeof t)throw new Error("Selector error: expected a JSON object");var n=function(e,t,n){if(e=e.filter((function(e){return wt(e.doc,t.selector,n)})),t.sort){var r=function(e){function t(t){return e.map((function(e){var n=at(ft(e));return st(t,n)}))}return function(e,n){var r,i,o=vt(t(e.doc),t(n.doc));return 0!==o?o:(r=e.doc._id)<(i=n.doc._id)?-1:r>i?1:0}}(t.sort);e=e.sort(r),"string"!=typeof t.sort[0]&&"desc"===(i=t.sort[0])[ft(i)]&&(e=e.reverse())}var i;if("limit"in t||"skip"in t){var o=t.skip||0,s=("limit"in t?t.limit:e.length)+o;e=e.slice(o,s)}return e}([{doc:e}],{selector:t=pt(t)},Object.keys(t));return n&&1===n.length}(e,t.selector)},e.doChanges(t);else{var o=se(t.filter);e.db.get("_design/"+o[0],(function(r,i){if(e.isCancelled)return n(null,{status:"cancelled"});if(r)return n(te(r));var s=i&&i.filters&&i.filters[o[1]];if(!s)return n(ee(R,i&&i.filters?"missing json key: "+o[1]:"missing json key: filters"));t.filter=he('"use strict";\nreturn '+s+";",{}),e.doChanges(t)}))}}function Ct(e){return e.reduce((function(e,t){return e[t]=!0,e}),{})}tt.plugin((function(e){e._changesFilterPlugin={validate:At,normalize:St,shouldFilter:Et,filter:Pt}})),tt.version="7.3.0";var Dt=Ct(["_id","_rev","_access","_attachments","_deleted","_revisions","_revs_info","_conflicts","_deleted_conflicts","_local_seq","_rev_tree","_replication_id","_replication_state","_replication_state_time","_replication_state_reason","_replication_stats","_removed"]),Lt=Ct(["_access","_attachments","_replication_id","_replication_state","_replication_state_time","_replication_state_reason","_replication_stats"]);function Bt(e){if(!/^\d+-/.test(e))return ee(Y);var t=e.indexOf("-"),n=e.substring(0,t),r=e.substring(t+1);return{prefix:parseInt(n,10),id:r}}function It(e,t,n){var r,i,o;n||(n={deterministic_revs:!0});var s={status:"available"};if(e._deleted&&(s.deleted=!0),t)if(e._id||(e._id=Ee()),i=Se(e,n.deterministic_revs),e._rev){if((o=Bt(e._rev)).error)return o;e._rev_tree=[{pos:o.prefix,ids:[o.id,{status:"missing"},[[i,s,[]]]]}],r=o.prefix+1}else e._rev_tree=[{pos:1,ids:[i,s,[]]}],r=1;else if(e._revisions&&(e._rev_tree=function(e,t){for(var n=e.start-e.ids.length+1,r=e.ids,i=[r[0],t,[]],o=1,s=r.length;o1&&!n?(a={continue:function(){if(!o.length)return i();var n,a=o[o.length-1];if(t&&t.upper)try{n=IDBKeyRange.bound(a,t.upper,!0,t.upperOpen)}catch(e){if("DataError"===e.name&&0===e.code)return i()}else n=IDBKeyRange.lowerBound(a,!0);t=n,o=null,s=null,e.getAll(t,r).onsuccess=u,e.getAllKeys(t,r).onsuccess=c}},e.getAll(t,r).onsuccess=u,e.getAllKeys(t,r).onsuccess=c):n?e.openCursor(t,"prev").onsuccess=f:e.openCursor(t).onsuccess=f}function sn(e,t,n){var r,i,o="startkey"in e&&e.startkey,s="endkey"in e&&e.endkey,a="key"in e&&e.key,u="keys"in e&&e.keys,c=e.skip||0,f="number"==typeof e.limit?e.limit:-1,l=!1!==e.inclusive_end;if(!u&&(r=function(e,t,n,r,i){try{if(e&&t)return i?IDBKeyRange.bound(t,e,!n,!1):IDBKeyRange.bound(e,t,!1,!n);if(e)return i?IDBKeyRange.upperBound(e):IDBKeyRange.lowerBound(e);if(t)return i?IDBKeyRange.lowerBound(t,!n):IDBKeyRange.upperBound(t,!n);if(r)return IDBKeyRange.only(r)}catch(e){return{error:e}}return null}(o,s,l,a,e.descending),(i=r&&r.error)&&("DataError"!==i.name||0!==i.code)))return n(ee(X,i.name,i.message));var d=[Nt,Rt,zt];e.attachments&&d.push(Ft);var h=tn(t,d,"readonly");if(h.error)return n(h.error);var p=h.txn;p.oncomplete=function(){e.attachments?Ht(w,e.binary).then($):$()},p.onabort=Qt(n);var v,y,g=p.objectStore(Nt),_=p.objectStore(Rt),m=p.objectStore(zt),b=_.index("_doc_id_rev"),w=[];function k(t,n){var r={id:n.id,key:n.id,value:{rev:t}};n.deleted?u&&(w.push(r),r.value.deleted=!0,r.doc=null):c--<=0&&(w.push(r),e.include_docs&&function(t,n,r){var i=t.id+"::"+r;b.get(i).onsuccess=function(r){if(n.doc=Zt(r.target.result)||{},e.conflicts){var i=Be(t);i.length&&(n.doc._conflicts=i)}Yt(n.doc,e,p)}}(n,r,t))}function j(e){for(var t=0,n=e.length;t0&&(y=e.target.result[0])}({target:{result:[n]}})}),i||0===f?void 0:u?function(e,t,n){var r=new Array(e.length),i=0;e.forEach((function(o,s){t.get(o).onsuccess=function(t){t.target.result?r[s]=t.target.result:r[s]={key:o,error:"not_found"},++i===e.length&&n(e,r,{})}}))}(e.keys,g,O):-1===f?function(e,t,n){if("function"!=typeof e.getAll){var r=[];e.openCursor(t).onsuccess=function(e){var t=e.target.result;t?(r.push(t.value),t.continue()):n({target:{result:r}})}}else e.getAll(t).onsuccess=n}(g,r,(function(t){var n=t.target.result;e.descending&&(n=n.reverse()),j(n)})):void on(g,r,e.descending,f+c,O)}var an=!1,un=[];function cn(){!an&&un.length&&(an=!0,un.shift()())}var fn,ln=new i,dn=new i;function hn(e,t){var n=this;!function(t,o,a){un.push((function(){var t;t=function(e,t){!function(e,t,n,r){try{e(t,n)}catch(t){r.emit("error",t)}}(o,e,t,a),an=!1,s()((function(){cn()}))},function(e,t,n){var o=t.name,a=null,u=null;function c(e){return function(t,n){t&&t instanceof Error&&!t.reason&&u&&(t.reason=u),e(t,n)}}function f(e){var t=e.createObjectStore(Nt,{keyPath:"id"});e.createObjectStore(Rt,{autoIncrement:!0}).createIndex("_doc_id_rev","_doc_id_rev",{unique:!0}),e.createObjectStore(Ft,{keyPath:"digest"}),e.createObjectStore(zt,{keyPath:"id",autoIncrement:!1}),e.createObjectStore(Kt),t.createIndex("deletedOrLocal","deletedOrLocal",{unique:!1}),e.createObjectStore(Jt,{keyPath:"_id"});var n=e.createObjectStore(Ut,{autoIncrement:!0});n.createIndex("seq","seq"),n.createIndex("digestSeq","digestSeq",{unique:!0})}function l(e,t){var n=e.objectStore(Nt);n.createIndex("deletedOrLocal","deletedOrLocal",{unique:!1}),n.openCursor().onsuccess=function(e){var r=e.target.result;if(r){var i=r.value,o=Ke(i);i.deletedOrLocal=o?"1":"0",n.put(i),r.continue()}else t()}}function d(e){e.createObjectStore(Jt,{keyPath:"_id"}).createIndex("_doc_id_rev","_doc_id_rev",{unique:!0})}function h(e,t){var n=e.objectStore(Jt),r=e.objectStore(Nt),i=e.objectStore(Rt);r.openCursor().onsuccess=function(e){var o=e.target.result;if(o){var s=o.value,a=s.id,u=Ve(a),c=Pe(s);if(u){var f=a+"::"+c,l=a+"::",d=a+"::~",h=i.index("_doc_id_rev"),p=IDBKeyRange.bound(l,d,!1,!1),v=h.openCursor(p);v.onsuccess=function(e){if(v=e.target.result){var t=v.value;t._doc_id_rev===f&&n.put(t),i.delete(v.primaryKey),v.continue()}else r.delete(o.primaryKey),o.continue()}}else o.continue()}else t&&t()}}function p(e){var t=e.createObjectStore(Ut,{autoIncrement:!0});t.createIndex("seq","seq"),t.createIndex("digestSeq","digestSeq",{unique:!0})}function v(e,t){var n=e.objectStore(Rt),r=e.objectStore(Ft),i=e.objectStore(Ut);r.count().onsuccess=function(e){if(!e.target.result)return t();n.openCursor().onsuccess=function(e){var n=e.target.result;if(!n)return t();for(var r=n.value,o=n.primaryKey,s=Object.keys(r._attachments||{}),a={},u=0;ui&&(i=n),t.continue()}}function a(){var e=Gt(o,o.winningRev,o.deleted);r.put(e).onsuccess=function(){i.continue()}}}}e._meta=null,e._remote=!1,e.type=function(){return"idb"},e._id=x((function(t){t(null,e._meta.instanceId)})),e._bulkDocs=function(n,r,i){rn(t,n,r,e,a,c(i))},e._get=function(e,t,n){var r,i,o,s=t.ctx;if(!s){var u=tn(a,[Nt,Rt,Ft],"readonly");if(u.error)return n(u.error);s=u.txn}function c(){n(o,{doc:r,metadata:i,ctx:s})}s.objectStore(Nt).get(e).onsuccess=function(e){if(!(i=Wt(e.target.result)))return o=ee(R,"missing"),c();var n;if(t.rev)n=t.latest?function(e,t){for(var n,r=t.rev_tree.slice();n=r.pop();){var i=n.pos,o=n.ids,s=o[0],a=o[1],u=o[2],c=0===u.length,f=n.history?n.history.slice():[];if(f.push({id:s,pos:i,opts:a}),c)for(var l=0,d=f.length;l=43)},r.onerror=e.onabort=function(e){e.preventDefault(),e.stopPropagation(),t(!1)}})).catch((function(){return!1}))}(f)),fn.then((function(e){s=e,d()})),f.oncomplete=function(){l=!0,d()},f.onabort=Qt(n)},_.onerror=function(e){var t=e.target.error&&e.target.error.message;t?-1!==t.indexOf("stored database is a higher version")&&(t=new Error('This DB was created with the newer "indexeddb" adapter, but you are trying to open it with the older "idb" adapter')):t="Failed to open indexedDB, are you in private browsing mode?",L("error",t),n(ee(X,t))}}(n,e,t)})),cn()}(0,t,n.constructor)}hn.valid=function(){try{return"undefined"!=typeof indexedDB&&"undefined"!=typeof IDBKeyRange}catch(e){return!1}};var pn=5e3,vn={};function yn(e){var t=e.doc||e.ok,n=t&&t._attachments;n&&Object.keys(n).forEach((function(e){var t=n[e];t.data=be(t.data,t.content_type)}))}function gn(e){return/^_design/.test(e)?"_design/"+encodeURIComponent(e.slice(8)):/^_local/.test(e)?"_local/"+encodeURIComponent(e.slice(7)):encodeURIComponent(e)}function _n(e){return e._attachments&&Object.keys(e._attachments)?Promise.all(Object.keys(e._attachments).map((function(t){var n=e._attachments[t];if(n.data&&"string"!=typeof n.data)return new Promise((function(e){je(n.data,e)})).then((function(e){n.data=e}))}))):Promise.resolve()}function mn(e,t){return bn(e,e.db+"/"+t)}function bn(e,t){var n=e.path?"/":"";return e.protocol+"://"+e.host+(e.port?":"+e.port:"")+"/"+e.path+n+t}function wn(e){return"?"+Object.keys(e).map((function(t){return t+"="+encodeURIComponent(e[t])})).join("&")}function kn(e,t){var n=this,r=function(e,t){if(function(e){if(!e.prefix)return!1;var t=de(e.prefix).protocol;return"http"===t||"https"===t}(t)){var n=t.name.substr(t.prefix.length);e=t.prefix.replace(/\/?$/,"/")+encodeURIComponent(n)}var r=de(e);(r.user||r.password)&&(r.auth={username:r.user,password:r.password});var i=r.path.replace(/(^\/|\/$)/g,"").split("/");return r.db=i.pop(),-1===r.db.indexOf("%")&&(r.db=encodeURIComponent(r.db)),r.path=i.join("/"),r}(e.name,e),i=mn(r,"");e=O(e);var o,a=function(t,n){if((n=n||{}).headers=n.headers||new it,n.credentials="include",e.auth||r.auth){var i=e.auth||r.auth,o=i.username+":"+i.password,s=ye(unescape(encodeURIComponent(o)));n.headers.set("Authorization","Basic "+s)}var a=e.headers||{};return Object.keys(a).forEach((function(e){n.headers.append(e,a[e])})),function(e){var t="undefined"!=typeof navigator&&navigator.userAgent?navigator.userAgent.toLowerCase():"",n=-1!==t.indexOf("msie"),r=-1!==t.indexOf("trident"),i=-1!==t.indexOf("edge"),o=!("method"in e)||"GET"===e.method;return(n||r||i)&&o}(n)&&(t+=(-1===t.indexOf("?")?"?":"&")+"_nonce="+Date.now()),(e.fetch||rt)(t,n)};function u(e,t){return q(e,d()((function(e){f().then((function(){return t.apply(this,e)})).catch((function(t){e.pop()(t)}))}))).bind(n)}function c(e,t,n){var r={};return(t=t||{}).headers=t.headers||new it,t.headers.get("Content-Type")||t.headers.set("Content-Type","application/json"),t.headers.get("Accept")||t.headers.set("Accept","application/json"),a(e,t).then((function(e){return r.ok=e.ok,r.status=e.status,e.json()})).then((function(e){if(r.data=e,!r.ok){r.data.status=r.status;var t=te(r.data);if(n)return n(t);throw t}if(Array.isArray(r.data)&&(r.data=r.data.map((function(e){return e.error||e.missing?te(e):e}))),!n)return r;n(null,r.data)}))}function f(){return e.skip_setup?Promise.resolve():o||((o=c(i).catch((function(e){return e&&e.status&&404===e.status?(I(404,"PouchDB is just detecting if the remote exists."),c(i,{method:"PUT"})):Promise.reject(e)})).catch((function(e){return!(!e||!e.status||412!==e.status)||Promise.reject(e)}))).catch((function(){o=null})),o)}function l(e){return e.split("/").map(encodeURIComponent).join("/")}s()((function(){t(null,n)})),n._remote=!0,n.type=function(){return"http"},n.id=u("id",(function(e){a(bn(r,"")).then((function(e){return e.json()})).catch((function(){return{}})).then((function(t){var n=t&&t.uuid?t.uuid+r.db:mn(r,"");e(null,n)}))})),n.compact=u("compact",(function(e,t){"function"==typeof e&&(t=e,e={}),e=O(e),c(mn(r,"_compact"),{method:"POST"}).then((function(){!function r(){n.info((function(n,i){i&&!i.compact_running?t(null,{ok:!0}):setTimeout(r,e.interval||200)}))}()}))})),n.bulkGet=q("bulkGet",(function(e,t){var n=this;function i(t){var n={};e.revs&&(n.revs=!0),e.attachments&&(n.attachments=!0),e.latest&&(n.latest=!0),c(mn(r,"_bulk_get"+wn(n)),{method:"POST",body:JSON.stringify({docs:e.docs})}).then((function(n){e.attachments&&e.binary&&n.data.results.forEach((function(e){e.docs.forEach(yn)})),t(null,n.data)})).catch(t)}function o(){var r=Math.ceil(e.docs.length/50),i=0,o=new Array(r);function s(e){return function(n,s){o[e]=s.results,++i===r&&t(null,{results:re(o)})}}for(var a=0;at?t:a;var u=mn(r,"_changes"+wn(i)),v={signal:p.signal,method:d,body:JSON.stringify(l)};h=n,e.aborted||f().then((function(){return c(u,v,s)})).catch(s)}},y={results:[]},g=function(n,r){if(!e.aborted){var i=0;if(r&&r.results){i=r.results.length,y.last_seq=r.last_seq;var u=null,c=null;"number"==typeof r.pending&&(u=r.pending),"string"!=typeof y.last_seq&&"number"!=typeof y.last_seq||(c=y.last_seq),e.query_params,r.results=r.results.filter((function(t){a--;var n=ne(e)(t);return n&&(e.include_docs&&e.attachments&&e.binary&&yn(t),e.return_docs&&y.results.push(t),e.onChange(t,u,c)),n}))}else if(n)return e.aborted=!0,void e.complete(n);r&&r.last_seq&&(h=r.last_seq);var f=o&&a<=0||r&&i0?e.slice(n):e}function l(e){var t=e.value;return t&&"object"==typeof t&&t._id||e.id}function h(e){return function(t){return e.include_docs&&e.attachments&&e.binary&&function(e){e.rows.forEach((function(e){var t=e.doc&&e.doc._attachments;t&&Object.keys(t).forEach((function(e){var n=t[e];t[e].data=be(n.data,n.content_type)}))}))}(t),t}}function p(e,t,n,r){var i=t[e];void 0!==i&&(r&&(i=encodeURIComponent(JSON.stringify(i))),n.push(e+"="+i))}function v(e){if(void 0!==e){var t=Number(e);return isNaN(t)||t!==parseInt(e,10)?e:t}}function y(e,t){var n=e.descending?"endkey":"startkey",r=e.descending?"startkey":"endkey";if(void 0!==e[n]&&void 0!==e[r]&&vt(e[n],e[r])>0)throw new jn("No rows can match your key range, reverse your start_key and end_key or set {descending : true}");if(t.reduce&&!1!==e.reduce){if(e.include_docs)throw new jn("{include_docs:true} is invalid for reduce");if(e.keys&&e.keys.length>1&&!e.group&&!e.group_level)throw new jn("Multi-key fetches for reduce views must use {group: true}")}["group_level","limit","skip"].forEach((function(t){var n=function(e){if(e){if("number"!=typeof e)return new jn('Invalid value for integer: "'+e+'"');if(e<0)return new jn('Invalid value for positive integer: "'+e+'"')}}(e[t]);if(n)throw n}))}function g(e){return function(t){if(404===t.status)return e;throw t}}function _(e){var t="string"==typeof e?e:e.name,n=Nn[t];return n||(n=Nn[t]=new In),n}function m(e,t){return qn(_(e),(function(){return function(e,t){var n,o;var s=function(e,t){if("function"==typeof e&&2===e.length){var n=e;return function(e){return n(e,t)}}return Bn(e.toString(),t)}(e.mapFun,(function(e,t){var r={id:o._id,key:yt(e)};null!=t&&(r.value=yt(t)),n.push(r)})),u=e.seq||0;function f(t,n){return function(){return function(e,t,n){var i="_local/lastSeq";return e.db.get(i).catch(g({_id:i,seq:0})).then((function(i){var o=Sn(t);return Promise.all(o.map((function(n){return function(e,t,n){var i="_local/doc_"+e,o={_id:i,keys:[]},s=n.get(e),a=s[0];return(function(e){return 1===e.length&&/^1-/.test(e[0].rev)}(s[1])?Promise.resolve(o):t.db.get(i).catch(g(o))).then((function(e){return function(e){return e.keys.length?t.db.allDocs({keys:e.keys,include_docs:!0}):Promise.resolve({rows:[]})}(e).then((function(t){return function(e,t){for(var n=[],i=new r,o=0,s=t.rows.length;o0&&0===vt(s.key,t)&&a.push(r),n.set(gt(a),s),t=s.key}return n}return p().then((function(){return h.finish()})).then((function(){e.seq=u}))}(e,t)}))()}function b(e,t){return qn(_(e),(function(){return function(e,t){var n,r=e.reduceFun&&!1!==t.reduce,o=t.skip||0;function s(t){return t.include_docs=!0,e.db.allDocs(t).then((function(e){return n=e.total_rows,e.rows.map((function(e){if("value"in e.doc&&"object"==typeof e.doc.value&&null!==e.doc.value){var t=Object.keys(e.doc.value).sort(),n=["id","key","value"];if(!(tn))return e.doc.value}var r=function(e){for(var t=[],n=[],r=0;;){var i=e[r++];if("\0"!==i)switch(i){case"1":t.push(null);break;case"2":t.push("1"===e[r]),r++;break;case"3":var o=_t(e,r);t.push(o.num),r+=o.length;break;case"4":for(var s="";;){var a=e[r];if("\0"===a)break;s+=a,r++}s=s.replace(/\u0001\u0001/g,"\0").replace(/\u0001\u0002/g,"").replace(/\u0002\u0002/g,""),t.push(s);break;case"5":var u={element:[],index:t.length};t.push(u.element),n.push(u);break;case"6":var c={element:{},index:t.length};t.push(c.element),n.push(c);break;default:throw new Error("bad collationIndex or unexpectedly reached end of input: "+i)}else{if(1===t.length)return t.pop();mt(t,n)}}}(e.doc._id);return{key:r[0],id:r[1],value:"value"in e.doc?e.doc.value:null}}))}))}function a(s){var a;if(a=r?function(e,t,n){0===n.group_level&&delete n.group_level;var r=n.group||n.group_level,i=function(e){var t=e.toString(),n=function(e){if(/^_sum/.test(e))return zn;if(/^_count/.test(e))return Jn;if(/^_stats/.test(e))return Kn;if(/^_/.test(e))throw new Error(e+" is not a supported reduce function.")}(t);return n||Bn(t)}(e.reduceFun),o=[],s=isNaN(n.group_level)?Number.POSITIVE_INFINITY:n.group_level;t.forEach((function(e){var t=o[o.length-1],n=r?e.key:null;if(r&&Array.isArray(n)&&(n=n.slice(0,s)),t&&0===vt(t.groupKey,n))return t.keys.push([e.key,e.id]),void t.values.push(e.value);o.push({keys:[[e.key,e.id]],values:[e.value],groupKey:n})})),t=[];for(var a=0,c=o.length;a0)return function(t){return e.allDocs({keys:t,include_docs:!0,conflicts:!0}).then((function(e){if(r.cancelled)throw new Error("cancelled");e.rows.forEach((function(e){var t;e.deleted||!e.doc||!Gn(e.value.rev)||(t=e.doc)._attachments&&Object.keys(t._attachments).length>0||function(e){return e._conflicts&&e._conflicts.length>0}(e.doc)||(e.doc._conflicts&&delete e.doc._conflicts,i.push(e.doc),delete n[e.id])}))}))}(t)})).then((function(){var s=function(e){var t=[];return Object.keys(e).forEach((function(n){e[n].missing.forEach((function(e){t.push({id:n,rev:e})}))})),{docs:t,revs:!0,latest:!0}}(n);if(s.docs.length)return e.bulkGet(s).then((function(n){if(r.cancelled)throw new Error("cancelled");return Promise.all(n.results.map((function(n){return Promise.all(n.docs.map((function(n){var r=n.ok;return n.error&&(o=!1),r&&r._attachments?function(e,t,n){var r=oe(t)&&!oe(e),i=Object.keys(n._attachments);return r?e.get(n._id).then((function(r){return Promise.all(i.map((function(i){return function(e,t,n){return!e._attachments||!e._attachments[n]||e._attachments[n].digest!==t._attachments[n].digest}(r,n,i)?t.getAttachment(n._id,i):e.getAttachment(r._id,i)})))})).catch((function(e){if(404!==e.status)throw e;return Wn(t,n)})):Wn(t,n)}(t,e,r).then((function(e){var t=Object.keys(r._attachments);return e.forEach((function(e,n){var i=r._attachments[t[n]];delete i.stub,delete i.length,i.data=e})),r})):r})))}))).then((function(e){i=i.concat(re(e).filter(Boolean))}))}))})).then((function(){return{ok:o,docs:i}}))}var Xn="pouchdb";function Yn(e,t,n,r,i){return e.get(t).catch((function(n){if(404===n.status)return"http"!==e.adapter&&"https"!==e.adapter||I(404,"PouchDB is just checking if a remote checkpoint exists."),{session_id:r,_id:t,history:[],replicator:Xn,version:1};throw n})).then((function(o){if(!i.cancelled&&o.last_seq!==n)return o.history=(o.history||[]).filter((function(e){return e.session_id!==r})),o.history.unshift({last_seq:n,session_id:r}),o.history=o.history.slice(0,5),o.version=1,o.replicator=Xn,o.session_id=r,o.last_seq=n,e.put(o).catch((function(o){if(409===o.status)return Yn(e,t,n,r,i);throw o}))}))}function Hn(e,t,n,r,i){this.src=e,this.target=t,this.id=n,this.returnValue=r,this.opts=i||{}}Hn.prototype.writeCheckpoint=function(e,t){var n=this;return this.updateTarget(e,t).then((function(){return n.updateSource(e,t)}))},Hn.prototype.updateTarget=function(e,t){return this.opts.writeTargetCheckpoint?Yn(this.target,this.id,e,t,this.returnValue):Promise.resolve(!0)},Hn.prototype.updateSource=function(e,t){if(this.opts.writeSourceCheckpoint){var n=this;return Yn(this.src,this.id,e,t,this.returnValue).catch((function(e){if(rr(e))return n.opts.writeSourceCheckpoint=!1,!0;throw e}))}return Promise.resolve(!0)};var er={undefined:function(e,t){return 0===vt(e.last_seq,t.last_seq)?t.last_seq:0},1:function(e,t){return(n=t,r=e,n.session_id===r.session_id?{last_seq:n.last_seq,history:n.history}:tr(n.history,r.history)).last_seq;var n,r}};function tr(e,t){var n=e[0],r=e.slice(1),i=t[0],o=t.slice(1);return n&&0!==t.length?nr(n.session_id,t)?{last_seq:n.last_seq,history:e}:nr(i.session_id,r)?{last_seq:i.last_seq,history:o}:tr(r,o):{last_seq:0,history:[]}}function nr(e,t){var n=t[0],r=t.slice(1);return!(!e||0===t.length)&&(e===n.session_id||nr(e,r))}function rr(e){return"number"==typeof e.status&&4===Math.floor(e.status/100)}function ir(e,t,n,r,i){var o,a,u,c=[],f={seq:0,changes:[],docs:[]},l=!1,d=!1,h=!1,p=0,v=n.continuous||n.live||!1,y=n.batch_size||100,g=n.batches_limit||10,_=n.style||"all_docs",m=!1,b=n.doc_ids,w=n.selector,k=[],j=Ee();i=i||{ok:!0,start_time:(new Date).toISOString(),docs_read:0,docs_written:0,doc_write_failures:0,errors:[]};var $={};function x(){return u?Promise.resolve():function(e,t,n){var r=n.doc_ids?n.doc_ids.sort(vt):"",i=n.filter?n.filter.toString():"",o="",s="",a="";return n.selector&&(a=JSON.stringify(n.selector)),n.filter&&n.query_params&&(o=JSON.stringify(function(e){return Object.keys(e).sort(vt).reduce((function(t,n){return t[n]=e[n],t}),{})}(n.query_params))),n.filter&&"_view"===n.filter&&(s=n.view.toString()),Promise.all([e.id(),t.id()]).then((function(e){var t=e[0]+e[1]+i+s+o+r+a;return new Promise((function(e){qe(t,e)}))})).then((function(e){return"_local/"+e.replace(/\//g,".").replace(/\+/g,"_")}))}(e,t,n).then((function(i){a=i;var o;o=!1===n.checkpoint?{writeSourceCheckpoint:!1,writeTargetCheckpoint:!1}:"source"===n.checkpoint?{writeSourceCheckpoint:!0,writeTargetCheckpoint:!1}:"target"===n.checkpoint?{writeSourceCheckpoint:!1,writeTargetCheckpoint:!0}:{writeSourceCheckpoint:!0,writeTargetCheckpoint:!0},u=new Hn(e,t,a,r,o)}))}function q(){if(k=[],0!==o.docs.length){var e=o.docs,s={timeout:n.timeout};return t.bulkDocs({docs:e,new_edits:!1},s).then((function(t){if(r.cancelled)throw D(),new Error("cancelled");var n=Object.create(null);t.forEach((function(e){e.error&&(n[e.id]=e)}));var o=Object.keys(n).length;i.doc_write_failures+=o,i.docs_written+=e.length-o,e.forEach((function(e){var t=n[e._id];if(t){i.errors.push(t);var o=(t.name||"").toLowerCase();if("unauthorized"!==o&&"forbidden"!==o)throw t;r.emit("denied",O(t))}else k.push(e)}))}),(function(t){throw i.doc_write_failures+=e.length,t}))}}function A(){if(o.error)throw new Error("There was a problem getting docs.");i.last_seq=p=o.seq;var e=O(i);return k.length&&(e.docs=k,"number"==typeof o.pending&&(e.pending=o.pending,delete o.pending),r.emit("change",e)),l=!0,u.writeCheckpoint(o.seq,j).then((function(){if(r.emit("checkpoint",{checkpoint:o.seq}),l=!1,r.cancelled)throw D(),new Error("cancelled");o=void 0,M()})).catch((function(e){throw R(e),e}))}function S(){return Zn(e,t,o.diffs,r).then((function(e){o.error=!e.ok,e.docs.forEach((function(e){delete o.diffs[e._id],i.docs_read++,o.docs.push(e)}))}))}function E(){var e;r.cancelled||o||(0!==c.length?(o=c.shift(),r.emit("checkpoint",{start_next_batch:o.seq}),(e={},o.changes.forEach((function(t){r.emit("checkpoint",{revs_diff:t}),"_user/"!==t.id&&(e[t.id]=t.changes.map((function(e){return e.rev})))})),t.revsDiff(e).then((function(e){if(r.cancelled)throw D(),new Error("cancelled");o.diffs=e}))).then(S).then(q).then(A).then(E).catch((function(e){C("batch processing terminated with error",e)}))):P(!0))}function P(e){0!==f.changes.length?(e||d||f.changes.length>=y)&&(c.push(f),f={seq:0,changes:[],docs:[]},"pending"!==r.state&&"stopped"!==r.state||(r.state="active",r.emit("active")),E()):0!==c.length||o||((v&&$.live||d)&&(r.state="pending",r.emit("paused")),d&&D())}function C(e,t){h||(t.message||(t.message=e),i.ok=!1,i.status="aborting",c=[],f={seq:0,changes:[],docs:[]},D(t))}function D(o){if(!(h||r.cancelled&&(i.status="cancelled",l)))if(i.status=i.status||"complete",i.end_time=(new Date).toISOString(),i.last_seq=p,h=!0,o){(o=ee(o)).result=i;var s=(o.name||"").toLowerCase();"unauthorized"===s||"forbidden"===s?(r.emit("error",o),r.removeAllListeners()):function(e,t,n,r){if(!1===e.retry)return t.emit("error",n),void t.removeAllListeners();if("function"!=typeof e.back_off_function&&(e.back_off_function=B),t.emit("requestError",n),"active"===t.state||"pending"===t.state){t.emit("paused",n),t.state="stopped";var i=function(){e.current_back_off=0};t.once("paused",(function(){t.removeListener("active",i)})),t.once("active",i)}e.current_back_off=e.current_back_off||0,e.current_back_off=e.back_off_function(e.current_back_off),setTimeout(r,e.current_back_off)}(n,r,o,(function(){ir(e,t,n,r)}))}else r.emit("complete",i),r.removeAllListeners()}function L(e,t,i){if(r.cancelled)return D();"number"==typeof t&&(f.pending=t),ne(n)(e)&&(f.seq=e.seq||i,f.changes.push(e),r.emit("checkpoint",{pending_batch:f.seq}),s()((function(){P(0===c.length&&$.live)})))}function I(e){if(m=!1,r.cancelled)return D();if(e.results.length>0)$.since=e.results[e.results.length-1].seq,M(),P(!0);else{var t=function(){v?($.live=!0,M()):d=!0,P(!0)};o||0!==e.results.length?t():(l=!0,u.writeCheckpoint(e.last_seq,j).then((function(){l=!1,i.last_seq=p=e.last_seq,t()})).catch(R))}}function T(e){if(m=!1,r.cancelled)return D();C("changes rejected",e)}function M(){if(!m&&!d&&c.length{n.d(t,{Z:()=>vt});var r=n(717),i=n.n(r);function o(e,t,n){Error.call(this,n),this.status=e,this.name=t,this.message=n,this.error=!0}i()(o,Error),o.prototype.toString=function(){return JSON.stringify({status:this.status,name:this.name,message:this.message,reason:this.reason})},new o(401,"unauthorized","Name or password is incorrect."),new o(400,"bad_request","Missing JSON list of 'docs'"),new o(404,"not_found","missing"),new o(409,"conflict","Document update conflict"),new o(400,"bad_request","_id field must contain a string"),new o(412,"missing_id","_id is required for puts"),new o(400,"bad_request","Only reserved document ids may start with underscore."),new o(412,"precondition_failed","Database not open");var s=new o(500,"unknown_error","Database encountered an unknown error");function a(e){if("object"!=typeof e){var t=e;(e=s).data=t}return"error"in e&&"conflict"===e.error&&(e.name="conflict",e.status=409),"name"in e||(e.name=e.error||"unknown"),"status"in e||(e.status=500),"message"in e||(e.message=e.message||e.reason),"stack"in e||(e.stack=(new Error).stack),e}new o(500,"badarg","Some query argument is invalid"),new o(400,"invalid_request","Request was invalid"),new o(400,"query_parse_error","Some query parameter is invalid"),new o(500,"doc_validation","Bad special document member"),new o(400,"bad_request","Something wrong with the request"),new o(400,"bad_request","Document must be a JSON object"),new o(404,"not_found","Database not found"),new o(500,"indexed_db_went_bad","unknown"),new o(500,"web_sql_went_bad","unknown"),new o(500,"levelDB_went_went_bad","unknown"),new o(403,"forbidden","Forbidden by design doc validate_doc_update function"),new o(400,"bad_request","Invalid rev format"),new o(412,"file_exists","The database could not be created, the file already exists."),new o(412,"missing_stub","A pre-existing attachment stub wasn't found"),new o(413,"invalid_url","Provided URL is invalid"),"undefined"!=typeof AbortController&&AbortController,fetch;var u,c,f=Headers;function l(e){return"$"+e}function d(e){return e.substring(1)}function h(){this._store={}}function p(e){if(this._store=new h,e&&Array.isArray(e))for(var t=0,n=e.length;td(e)))},h.prototype.delete=function(e){var t=l(e),n=t in this._store;return delete this._store[t],n},h.prototype.forEach=function(e){for(var t=Object.keys(this._store),n=0,r=t.length;nt?1:-1}(e,t)}return Array.isArray(e)?function(e,t){for(var n=Math.min(e.length,t.length),r=0;rt.length?1:-1}(e,t):function(e,t){for(var n=Object.keys(e),r=Object.keys(t),i=Math.min(n.length,r.length),o=0;or.length?1:-1}(e,t)}function _(e){switch(typeof e){case"undefined":return null;case"number":return e===1/0||e===-1/0||isNaN(e)?null:e;case"object":var t=e;if(Array.isArray(e)){var n=e.length;e=new Array(n);for(var r=0;rr.since&&!r.cancelled&&(r.since=e.seq,r.onChange(e))})).on("complete",(function(){"waiting"===o&&x()(s),o=!1})).on("error",(function(){o=!1}))}}},N.prototype.removeListener=function(e,t){t in this._listeners&&(A().prototype.removeListener.call(this,e,this._listeners[t]),delete this._listeners[t])},N.prototype.notifyLocalWindows=function(e){M()&&(localStorage[e]="a"===localStorage[e]?"b":"a")},N.prototype.notify=function(e){this.emit(e),this.notifyLocalWindows(e)};var F="function"==typeof Object.assign?Object.assign:function(e){for(var t=Object(e),n=1;nt?1:0}function ue(e){for(var t=[],n="",r=0,i=e.length;r0&&"\\"===e[r-1]&&("$"===o||"."===o)?n=n.substring(0,n.length-1)+o:"."===o?(t.push(n),n=""):n+=o}return t.push(n),t}var ce=["$or","$nor","$not"];function fe(e){return ce.indexOf(e)>-1}function le(e){return Object.keys(e)[0]}function de(e){return e[le(e)]}function he(e){var t={},n={$or:!0,$nor:!0};return e.forEach((function(e){Object.keys(e).forEach((function(r){var i=e[r];if("object"!=typeof i&&(i={$eq:i}),fe(r))if(i instanceof Array){if(n[r])return n[r]=!1,void(t[r]=i);var o=[];t[r].forEach((function(e){Object.keys(i).forEach((function(t){var n=i[t],r=Math.max(Object.keys(e).length,Object.keys(n).length),s=he([e,n]);Object.keys(s).length<=r||o.push(s)}))})),t[r]=o}else t[r]=he([i]);else{var s=t[r]=t[r]||{};Object.keys(i).forEach((function(e){var t=i[e];return"$gt"===e||"$gte"===e?function(e,t,n){void 0===n.$eq&&(void 0!==n.$gte?"$gte"===e?t>n.$gte&&(n.$gte=t):t>=n.$gte&&(delete n.$gte,n.$gt=t):void 0!==n.$gt?"$gte"===e?t>n.$gt&&(delete n.$gt,n.$gte=t):t>n.$gt&&(n.$gt=t):n[e]=t)}(e,t,s):"$lt"===e||"$lte"===e?function(e,t,n){void 0===n.$eq&&(void 0!==n.$lte?"$lte"===e?t0)return!1;var a=oe(r,s);return"object"==typeof o?me(o,t,n,a):be("$eq",t,o,s,a)})):e===r)}function be(e,t,n,r,i){if(!Oe[e])throw new Error('unknown operator "'+e+'" - should be one of $eq, $lte, $lt, $gt, $gte, $exists, $ne, $in, $nin, $size, $mod, $regex, $elemMatch, $type, $allMatch or $all');return Oe[e](t,n,r,i)}function we(e){return null!=e}function ke(e){return void 0!==e}function je(e,t){return t.some((function(t){return e instanceof Array?e.some((function(e){return 0===g(t,e)})):0===g(t,e)}))}var Oe={$elemMatch:function(e,t,n,r){return!!Array.isArray(r)&&0!==r.length&&("object"==typeof r[0]?r.some((function(e){return _e(e,t,Object.keys(t))})):r.some((function(r){return me(t,e,n,r)})))},$allMatch:function(e,t,n,r){return!!Array.isArray(r)&&0!==r.length&&("object"==typeof r[0]?r.every((function(e){return _e(e,t,Object.keys(t))})):r.every((function(r){return me(t,e,n,r)})))},$eq:function(e,t,n,r){return ke(r)&&0===g(r,t)},$gte:function(e,t,n,r){return ke(r)&&g(r,t)>=0},$gt:function(e,t,n,r){return ke(r)&&g(r,t)>0},$lte:function(e,t,n,r){return ke(r)&&g(r,t)<=0},$lt:function(e,t,n,r){return ke(r)&&g(r,t)<0},$exists:function(e,t,n,r){return t?ke(r):!ke(r)},$mod:function(e,t,n,r){return we(r)&&function(e,t){return"number"==typeof e&&parseInt(e,10)===e&&e%t[0]===t[1]}(r,t)},$ne:function(e,t,n,r){return t.every((function(e){return 0!==g(r,e)}))},$in:function(e,t,n,r){return we(r)&&je(r,t)},$nin:function(e,t,n,r){return we(r)&&!je(r,t)},$size:function(e,t,n,r){return we(r)&&Array.isArray(r)&&function(e,t){return e.length===t}(r,t)},$all:function(e,t,n,r){return Array.isArray(r)&&function(e,t){return t.every((function(t){return e.some((function(e){return 0===g(t,e)}))}))}(r,t)},$regex:function(e,t,n,r){return we(r)&&"string"==typeof r&&t.every((function(e){return function(e,t){return new RegExp(t).test(e)}(r,e)}))},$type:function(e,t,n,r){return function(e,t){switch(t){case"null":return null===e;case"boolean":return"boolean"==typeof e;case"number":return"number"==typeof e;case"string":return"string"==typeof e;case"array":return e instanceof Array;case"object":return"[object Object]"==={}.toString.call(e)}}(r,t)}};function $e(e,t){if("object"!=typeof t)throw new Error("Selector error: expected a JSON object");var n=ge([{doc:e}],{selector:t=ye(t)},Object.keys(t));return n&&1===n.length}function xe(e){return(e=I(e)).index||(e.index={}),["type","name","ddoc"].forEach((function(t){e.index[t]&&(e[t]=e.index[t],delete e.index[t])})),e.fields&&(e.index.fields=e.fields,delete e.fields),e.type||(e.type="json"),e}function qe(e,t,n){var r="",i=t,o=!0;if(-1!==["$in","$nin","$or","$and","$mod","$nor","$all"].indexOf(e)&&(Array.isArray(t)||(r="Query operator "+e+" must be an array.")),-1!==["$not","$elemMatch","$allMatch"].indexOf(e)&&(Array.isArray(t)||"object"!=typeof t||null===t)&&(r="Query operator "+e+" must be an object."),"$mod"===e&&Array.isArray(t))if(2!==t.length)r="Query operator $mod must be in the format [divisor, remainder], where divisor and remainder are both integers.";else{var s=t[0],a=t[1];0===s&&(r="Query operator $mod's divisor cannot be 0, cannot divide by zero.",o=!1),"number"==typeof s&&parseInt(s,10)===s||(r="Query operator $mod's divisor is not an integer.",i=s),parseInt(a,10)!==a&&(r="Query operator $mod's remainder is not an integer.",i=a)}if("$exists"===e&&"boolean"!=typeof t&&(r="Query operator $exists must be a boolean."),"$type"===e){var u=["null","boolean","number","string","array","object"],c='"'+u.slice(0,u.length-1).join('", "')+'", or "'+u[u.length-1]+'"';("string"!=typeof t||-1==u.indexOf(t))&&(r="Query operator $type must be a string. Supported values: "+c+".")}if("$size"===e&&parseInt(t,10)!==t&&(r="Query operator $size must be a integer."),"$regex"===e&&"string"!=typeof t&&(console.log("here",n),n?r="Query operator $regex must be a string.":t instanceof RegExp||(r="Query operator $regex must be a string or an instance of a javascript regular expression.")),r)throw o&&(r+=" Received"+(null===i?" ":Array.isArray(i)?" array":" "+typeof i)+": "+("object"==typeof i&&null!==i?JSON.stringify(i,null,"\t"):i)),new Error(r)}var Ae=["$all","$allMatch","$and","$elemMatch","$exists","$in","$mod","$nin","$nor","$not","$or","$regex","$size","$type"],Se=["$in","$nin","$mod","$all"],Ee=["$eq","$gt","$gte","$lt","$lte"];function Pe(e,t){if(Array.isArray(e))for(var n of e)"object"==typeof n&&null!==s&&Pe(n,t);else for(var r=Object.keys(e),i=0;i0?e.slice(n):e}function d(e){var t=e.value;return t&&"object"==typeof t&&t._id||e.id}function h(e){return function(t){return e.include_docs&&e.attachments&&e.binary&&function(e){e.rows.forEach((function(e){var t=e.doc&&e.doc._attachments;t&&Object.keys(t).forEach((function(e){var n=t[e];t[e].data=y(n.data,n.content_type)}))}))}(t),t}}function p(e,t,n,r){var i=t[e];void 0!==i&&(r&&(i=encodeURIComponent(JSON.stringify(i))),n.push(e+"="+i))}function v(e){if(void 0!==e){var t=Number(e);return isNaN(t)||t!==parseInt(e,10)?e:t}}function k(e,t){var n=e.descending?"endkey":"startkey",r=e.descending?"startkey":"endkey";if(void 0!==e[n]&&void 0!==e[r]&&g(e[n],e[r])>0)throw new K("No rows can match your key range, reverse your start_key and end_key or set {descending : true}");if(t.reduce&&!1!==e.reduce){if(e.include_docs)throw new K("{include_docs:true} is invalid for reduce");if(e.keys&&e.keys.length>1&&!e.group&&!e.group_level)throw new K("Multi-key fetches for reduce views must use {group: true}")}["group_level","limit","skip"].forEach((function(t){var n=function(e){if(e){if("number"!=typeof e)return new K('Invalid value for integer: "'+e+'"');if(e<0)return new K('Invalid value for positive integer: "'+e+'"')}}(e[t]);if(n)throw n}))}function j(e){return function(t){if(404===t.status)return e;throw t}}function $(e){var t="string"==typeof e?e:e.name,n=te[t];return n||(n=te[t]=new Y),n}function q(e,n){return W($(e),(function(){return function(e,n){var r,o;var a=t(e.mapFun,(function(e,t){var n={id:o._id,key:_(e)};null!=t&&(n.value=_(t)),r.push(n)})),f=e.seq||0;function l(t,n){return function(){return function(e,t,n){var r="_local/lastSeq";return e.db.get(r).catch(j({_id:r,seq:0})).then((function(r){var i=X(t);return Promise.all(i.map((function(n){return function(e,t,n){var r,i="_local/doc_"+e,o={_id:i,keys:[]},s=n.get(e),a=s[0];return(r=s[1],1===r.length&&/^1-/.test(r[0].rev)?Promise.resolve(o):t.db.get(i).catch(j(o))).then((function(e){return function(e){return e.keys.length?t.db.allDocs({keys:e.keys,include_docs:!0}):Promise.resolve({rows:[]})}(e).then((function(t){return function(e,t){for(var n=[],r=new u,i=0,o=t.rows.length;i0&&0===g(o.key,t)&&s.push(r),n.set(m(s),o),t=o.key}return n}return v().then((function(){return p.finish()})).then((function(){e.seq=f}))}(e,n)}))()}function A(e,t){return W($(e),(function(){return function(e,t){var r,i=e.reduceFun&&!1!==t.reduce,s=t.skip||0;function a(t){return t.include_docs=!0,e.db.allDocs(t).then((function(e){return r=e.total_rows,e.rows.map((function(e){if("value"in e.doc&&"object"==typeof e.doc.value&&null!==e.doc.value){var t=Object.keys(e.doc.value).sort(),n=["id","key","value"];if(!(tn))return e.doc.value}var r=function(e){for(var t=[],n=[],r=0;;){var i=e[r++];if("\0"!==i)switch(i){case"1":t.push(null);break;case"2":t.push("1"===e[r]),r++;break;case"3":var o=b(e,r);t.push(o.num),r+=o.length;break;case"4":for(var s="";;){var a=e[r];if("\0"===a)break;s+=a,r++}s=s.replace(/\u0001\u0001/g,"\0").replace(/\u0001\u0002/g,"").replace(/\u0002\u0002/g,""),t.push(s);break;case"5":var u={element:[],index:t.length};t.push(u.element),n.push(u);break;case"6":var c={element:{},index:t.length};t.push(c.element),n.push(c);break;default:throw new Error("bad collationIndex or unexpectedly reached end of input: "+i)}else{if(1===t.length)return t.pop();w(t,n)}}}(e.doc._id);return{key:r[0],id:r[1],value:"value"in e.doc?e.doc.value:null}}))}))}function u(a){var u;if(u=i?function(e,t,r){0===r.group_level&&delete r.group_level;var i=r.group||r.group_level,s=n(e.reduceFun),a=[],u=isNaN(r.group_level)?Number.POSITIVE_INFINITY:r.group_level;t.forEach((function(e){var t=a[a.length-1],n=i?e.key:null;if(i&&Array.isArray(n)&&(n=n.slice(0,u)),t&&0===g(t.groupKey,n))return t.keys.push([e.key,e.id]),void t.values.push(e.value);a.push({keys:[[e.key,e.id]],values:[e.value],groupKey:n})})),t=[];for(var c=0,f=a.length;cs.length)&&Ue(o,s)),i=Ue(n,e);return r&&i}var o,s;return function(e,t){e=e.slice();for(var n=0,r=t.length;n0){var d="$gt"in l||"$gte"in l||"$lt"in l||"$lte"in l,h=Object.keys(e[i[c-1]]),p=ze(h,["$eq"]),v=ze(h,Object.keys(l));if(d&&!p&&!v){u(c);break}}for(var y=Object.keys(l),g=null,_=0;_=i.length?r:i,0===i.length?{fields:n}:{fields:n=n.sort((function(e,t){var n=i.indexOf(e);-1===n&&(n=Number.MAX_VALUE);var r=i.indexOf(t);return-1===r&&(r=Number.MAX_VALUE),nr?1:0})),sortOrder:t.map(le)}}(n,r),o=i.fields,s=function(e,t,n,r,i){var o=function(e,t,n,r){return r.filter((function(r){return it(r,n,t,e)}))}(e,t,n,r);if(0===o.length){if(i)throw{error:"no_usable_index",message:"There is no index available for this selector."};var s=r[0];return s.defaultUsed=!0,s}if(1===o.length&&!i)return o[0];var a=function(e){for(var t={},n=0,r=e.length;nr&&(r=a,n=s)}return n}(o,(function(e){for(var t=e.def.fields.map(le),n=0,r=0,i=t.length;r0)throw new Error('Cannot sort on field(s) "'+n.join(",")+'" when using the default index')}t.defaultUsed}(t,o);var s=F({include_docs:!0,reduce:!1,indexes_count:r.total_rows},i.queryOpts);return"startkey"in s&&"endkey"in s&&g(s.startkey,s.endkey)>0?{docs:[]}:(t.sort&&"string"!=typeof t.sort[0]&&"desc"===de(t.sort[0])&&(s.descending=!0,s=function(e){var t=I(e);return delete t.startkey,delete t.endkey,delete t.inclusive_start,delete t.inclusive_end,"endkey"in e&&(t.startkey=e.endkey),"startkey"in e&&(t.endkey=e.startkey),"inclusive_start"in e&&(t.inclusive_end=e.inclusive_start),"inclusive_end"in e&&(t.inclusive_start=e.inclusive_end),t}(s)),i.inMemoryFields.length||("limit"in t&&(s.limit=t.limit),"skip"in t&&(s.skip=t.skip)),n?Promise.resolve(i,s):Promise.resolve().then((function(){if("_all_docs"===o.name)return function(e,t){var n=I(t);return n.descending?("endkey"in n&&"string"!=typeof n.endkey&&(n.endkey=""),"startkey"in n&&"string"!=typeof n.startkey&&(n.limit=0)):("startkey"in n&&"string"!=typeof n.startkey&&(n.startkey=""),"endkey"in n&&"string"!=typeof n.endkey&&(n.limit=0)),"key"in n&&"string"!=typeof n.key&&(n.limit=0),n.limit>0&&n.indexes_count&&(n.original_limit=n.limit,n.limit+=n.indexes_count),e.allDocs(n).then((function(e){return e.rows=e.rows.filter((function(e){return!/^_design\//.test(e.id)})),n.original_limit&&(n.limit=n.original_limit),e.rows=e.rows.slice(0,n.limit),e}))}(e,s);var t,n=(t=o).ddoc.substring(8)+"/"+t.name;return Ke(e).query.call(e,n,s)})).then((function(e){!1===s.inclusive_start&&(e.rows=function(e,t,n){for(var r=n.def.fields,i=0,o=e.length;it.length;)s.pop();if(Math.abs(g(s,t))>0)break}return i>0?e.slice(i):e}(e.rows,s.startkey,o)),i.inMemoryFields.length&&(e.rows=ge(e.rows,t,i.inMemoryFields));var n={docs:e.rows.map((function(e){var n=e.doc;return t.fields?function(e,t){for(var n={},r=0,i=t.length;r{function t(e,t){return function(...n){function r(){let r=null;const i="query"===t?1:0;n.length>i&&"function"==typeof n[n.length-1]&&(r=n.pop());let o=e._originals[t].bind(e);for(const n of e._handlers[t])o=n.bind(e,o);const s=o(...n);return s.then&&r&&function(e,t){e.then(((...e)=>{t(null,...e)})).catch((e=>{t(e)}))}(s,r),s}return"changes"!==t&&e.taskqueue&&!e.taskqueue.isReady?new Promise(((t,n)=>{e.taskqueue.addTask((e=>{e?n(e):t()}))})).then(r):r()}}const n={install:function(e,n={}){e._originals&&e._handlers||(e._originals={},e._handlers={});for(const[r,i]of Object.entries(n)){if(!(r in e))throw new Error(`Method '${r}' does not exist on given base, so it cannot be wrapped.`);r in e._originals||(e._originals[r]=e[r]),r in e._handlers?e._handlers[r].unshift(i):(e._handlers[r]=[i],e[r]=t(e,r))}},uninstall:function(e,t){if(!e._originals||!e._handlers)throw new Error("No wrapper methods installed, so no methods can be uninstalled.");for(const[n,r]of Object.entries(t)){const t=`Wrapper method for '${n}' not installed: ${r.toString()}`;if(!(n in e._handlers))throw new Error(t);const i=e._handlers[n].indexOf(r);if(-1===i)throw new Error(t);e._handlers[n].splice(i,1)}}};try{e.exports=n}catch{}try{window.PouchDBWrappers=n}catch{}},322:e=>{e.exports=function(e){var t=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];function n(e,t){var n=e[0],r=e[1],i=e[2],o=e[3];r=((r+=((i=((i+=((o=((o+=((n=((n+=(r&i|~r&o)+t[0]-680876936|0)<<7|n>>>25)+r|0)&r|~n&i)+t[1]-389564586|0)<<12|o>>>20)+n|0)&n|~o&r)+t[2]+606105819|0)<<17|i>>>15)+o|0)&o|~i&n)+t[3]-1044525330|0)<<22|r>>>10)+i|0,r=((r+=((i=((i+=((o=((o+=((n=((n+=(r&i|~r&o)+t[4]-176418897|0)<<7|n>>>25)+r|0)&r|~n&i)+t[5]+1200080426|0)<<12|o>>>20)+n|0)&n|~o&r)+t[6]-1473231341|0)<<17|i>>>15)+o|0)&o|~i&n)+t[7]-45705983|0)<<22|r>>>10)+i|0,r=((r+=((i=((i+=((o=((o+=((n=((n+=(r&i|~r&o)+t[8]+1770035416|0)<<7|n>>>25)+r|0)&r|~n&i)+t[9]-1958414417|0)<<12|o>>>20)+n|0)&n|~o&r)+t[10]-42063|0)<<17|i>>>15)+o|0)&o|~i&n)+t[11]-1990404162|0)<<22|r>>>10)+i|0,r=((r+=((i=((i+=((o=((o+=((n=((n+=(r&i|~r&o)+t[12]+1804603682|0)<<7|n>>>25)+r|0)&r|~n&i)+t[13]-40341101|0)<<12|o>>>20)+n|0)&n|~o&r)+t[14]-1502002290|0)<<17|i>>>15)+o|0)&o|~i&n)+t[15]+1236535329|0)<<22|r>>>10)+i|0,r=((r+=((i=((i+=((o=((o+=((n=((n+=(r&o|i&~o)+t[1]-165796510|0)<<5|n>>>27)+r|0)&i|r&~i)+t[6]-1069501632|0)<<9|o>>>23)+n|0)&r|n&~r)+t[11]+643717713|0)<<14|i>>>18)+o|0)&n|o&~n)+t[0]-373897302|0)<<20|r>>>12)+i|0,r=((r+=((i=((i+=((o=((o+=((n=((n+=(r&o|i&~o)+t[5]-701558691|0)<<5|n>>>27)+r|0)&i|r&~i)+t[10]+38016083|0)<<9|o>>>23)+n|0)&r|n&~r)+t[15]-660478335|0)<<14|i>>>18)+o|0)&n|o&~n)+t[4]-405537848|0)<<20|r>>>12)+i|0,r=((r+=((i=((i+=((o=((o+=((n=((n+=(r&o|i&~o)+t[9]+568446438|0)<<5|n>>>27)+r|0)&i|r&~i)+t[14]-1019803690|0)<<9|o>>>23)+n|0)&r|n&~r)+t[3]-187363961|0)<<14|i>>>18)+o|0)&n|o&~n)+t[8]+1163531501|0)<<20|r>>>12)+i|0,r=((r+=((i=((i+=((o=((o+=((n=((n+=(r&o|i&~o)+t[13]-1444681467|0)<<5|n>>>27)+r|0)&i|r&~i)+t[2]-51403784|0)<<9|o>>>23)+n|0)&r|n&~r)+t[7]+1735328473|0)<<14|i>>>18)+o|0)&n|o&~n)+t[12]-1926607734|0)<<20|r>>>12)+i|0,r=((r+=((i=((i+=((o=((o+=((n=((n+=(r^i^o)+t[5]-378558|0)<<4|n>>>28)+r|0)^r^i)+t[8]-2022574463|0)<<11|o>>>21)+n|0)^n^r)+t[11]+1839030562|0)<<16|i>>>16)+o|0)^o^n)+t[14]-35309556|0)<<23|r>>>9)+i|0,r=((r+=((i=((i+=((o=((o+=((n=((n+=(r^i^o)+t[1]-1530992060|0)<<4|n>>>28)+r|0)^r^i)+t[4]+1272893353|0)<<11|o>>>21)+n|0)^n^r)+t[7]-155497632|0)<<16|i>>>16)+o|0)^o^n)+t[10]-1094730640|0)<<23|r>>>9)+i|0,r=((r+=((i=((i+=((o=((o+=((n=((n+=(r^i^o)+t[13]+681279174|0)<<4|n>>>28)+r|0)^r^i)+t[0]-358537222|0)<<11|o>>>21)+n|0)^n^r)+t[3]-722521979|0)<<16|i>>>16)+o|0)^o^n)+t[6]+76029189|0)<<23|r>>>9)+i|0,r=((r+=((i=((i+=((o=((o+=((n=((n+=(r^i^o)+t[9]-640364487|0)<<4|n>>>28)+r|0)^r^i)+t[12]-421815835|0)<<11|o>>>21)+n|0)^n^r)+t[15]+530742520|0)<<16|i>>>16)+o|0)^o^n)+t[2]-995338651|0)<<23|r>>>9)+i|0,r=((r+=((o=((o+=(r^((n=((n+=(i^(r|~o))+t[0]-198630844|0)<<6|n>>>26)+r|0)|~i))+t[7]+1126891415|0)<<10|o>>>22)+n|0)^((i=((i+=(n^(o|~r))+t[14]-1416354905|0)<<15|i>>>17)+o|0)|~n))+t[5]-57434055|0)<<21|r>>>11)+i|0,r=((r+=((o=((o+=(r^((n=((n+=(i^(r|~o))+t[12]+1700485571|0)<<6|n>>>26)+r|0)|~i))+t[3]-1894986606|0)<<10|o>>>22)+n|0)^((i=((i+=(n^(o|~r))+t[10]-1051523|0)<<15|i>>>17)+o|0)|~n))+t[1]-2054922799|0)<<21|r>>>11)+i|0,r=((r+=((o=((o+=(r^((n=((n+=(i^(r|~o))+t[8]+1873313359|0)<<6|n>>>26)+r|0)|~i))+t[15]-30611744|0)<<10|o>>>22)+n|0)^((i=((i+=(n^(o|~r))+t[6]-1560198380|0)<<15|i>>>17)+o|0)|~n))+t[13]+1309151649|0)<<21|r>>>11)+i|0,r=((r+=((o=((o+=(r^((n=((n+=(i^(r|~o))+t[4]-145523070|0)<<6|n>>>26)+r|0)|~i))+t[11]-1120210379|0)<<10|o>>>22)+n|0)^((i=((i+=(n^(o|~r))+t[2]+718787259|0)<<15|i>>>17)+o|0)|~n))+t[9]-343485551|0)<<21|r>>>11)+i|0,e[0]=n+e[0]|0,e[1]=r+e[1]|0,e[2]=i+e[2]|0,e[3]=o+e[3]|0}function r(e){var t,n=[];for(t=0;t<64;t+=4)n[t>>2]=e.charCodeAt(t)+(e.charCodeAt(t+1)<<8)+(e.charCodeAt(t+2)<<16)+(e.charCodeAt(t+3)<<24);return n}function i(e){var t,n=[];for(t=0;t<64;t+=4)n[t>>2]=e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24);return n}function o(e){var t,i,o,s,a,u,c=e.length,f=[1732584193,-271733879,-1732584194,271733878];for(t=64;t<=c;t+=64)n(f,r(e.substring(t-64,t)));for(i=(e=e.substring(t-64)).length,o=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],t=0;t>2]|=e.charCodeAt(t)<<(t%4<<3);if(o[t>>2]|=128<<(t%4<<3),t>55)for(n(f,o),t=0;t<16;t+=1)o[t]=0;return s=(s=8*c).toString(16).match(/(.*?)(.{0,8})$/),a=parseInt(s[2],16),u=parseInt(s[1],16)||0,o[14]=a,o[15]=u,n(f,o),f}function s(e){var n,r="";for(n=0;n<4;n+=1)r+=t[e>>8*n+4&15]+t[e>>8*n&15];return r}function a(e){var t;for(t=0;tc?new ArrayBuffer(0):(r=c-u,i=new ArrayBuffer(r),o=new Uint8Array(i),s=new Uint8Array(this,u,r),o.set(s),i)}}(),f.prototype.append=function(e){return this.appendBinary(u(e)),this},f.prototype.appendBinary=function(e){this._buff+=e,this._length+=e.length;var t,i=this._buff.length;for(t=64;t<=i;t+=64)n(this._hash,r(this._buff.substring(t-64,t)));return this._buff=this._buff.substring(t-64),this},f.prototype.end=function(e){var t,n,r=this._buff,i=r.length,o=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(t=0;t>2]|=r.charCodeAt(t)<<(t%4<<3);return this._finish(o,i),n=a(this._hash),e&&(n=c(n)),this.reset(),n},f.prototype.reset=function(){return this._buff="",this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},f.prototype.getState=function(){return{buff:this._buff,length:this._length,hash:this._hash.slice()}},f.prototype.setState=function(e){return this._buff=e.buff,this._length=e.length,this._hash=e.hash,this},f.prototype.destroy=function(){delete this._hash,delete this._buff,delete this._length},f.prototype._finish=function(e,t){var r,i,o,s=t;if(e[s>>2]|=128<<(s%4<<3),s>55)for(n(this._hash,e),s=0;s<16;s+=1)e[s]=0;r=(r=8*this._length).toString(16).match(/(.*?)(.{0,8})$/),i=parseInt(r[2],16),o=parseInt(r[1],16)||0,e[14]=i,e[15]=o,n(this._hash,e)},f.hash=function(e,t){return f.hashBinary(u(e),t)},f.hashBinary=function(e,t){var n=a(o(e));return t?c(n):n},f.ArrayBuffer=function(){this.reset()},f.ArrayBuffer.prototype.append=function(e){var t,r,o,s,a,u=(r=this._buff.buffer,o=e,s=!0,(a=new Uint8Array(r.byteLength+o.byteLength)).set(new Uint8Array(r)),a.set(new Uint8Array(o),r.byteLength),s?a:a.buffer),c=u.length;for(this._length+=e.byteLength,t=64;t<=c;t+=64)n(this._hash,i(u.subarray(t-64,t)));return this._buff=t-64>2]|=r[t]<<(t%4<<3);return this._finish(o,i),n=a(this._hash),e&&(n=c(n)),this.reset(),n},f.ArrayBuffer.prototype.reset=function(){return this._buff=new Uint8Array(0),this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},f.ArrayBuffer.prototype.getState=function(){var e,t=f.prototype.getState.call(this);return t.buff=(e=t.buff,String.fromCharCode.apply(null,new Uint8Array(e))),t},f.ArrayBuffer.prototype.setState=function(e){return e.buff=function(e,t){var n,r=e.length,i=new ArrayBuffer(r),o=new Uint8Array(i);for(n=0;n>2]|=e[t]<<(t%4<<3);if(o[t>>2]|=128<<(t%4<<3),t>55)for(n(f,o),t=0;t<16;t+=1)o[t]=0;return s=(s=8*c).toString(16).match(/(.*?)(.{0,8})$/),a=parseInt(s[2],16),u=parseInt(s[1],16)||0,o[14]=a,o[15]=u,n(f,o),f}(new Uint8Array(e)));return t?c(r):r},f}()},380:(e,t,n)=>{const r=n(552);function i(e){return"_"!==e[0]}function o(e){return!("string"!=typeof e._id||!/^_local/.test(e._id))||!!e._deleted&&0===Object.keys(e).filter(i).length}function s(e){const t=function(t){return!o(t)&&e.incoming?e.incoming(t):t},n=function(t){return!o(t)&&e.outgoing?e.outgoing(t):t},i={async get(e,...t){const r=await e(...t);return Array.isArray(r)?(await Promise.all(r.map((async e=>{e.ok&&(e.ok=await n(e.ok))}))),r):n(r)},bulkDocs:async(e,n,...r)=>(n.docs?n.docs=await Promise.all(n.docs.map(t)):n=await Promise.all(n.map(t)),e(n,...r)),async allDocs(e,...t){const r=await e(...t);return await Promise.all(r.rows.map((async e=>{e.doc&&(e.doc=await n(e.doc))}))),r},async bulkGet(e,...t){const r=async e=>e.ok?{ok:await n(e.ok)}:e;let{results:i,...o}=await e(...t);return i=await Promise.all(i.map((async e=>{const{id:t,docs:n}=e;return t&&n&&Array.isArray(n)?{id:t,docs:await Promise.all(n.map(r))}:e}))),{results:i,...o}},changes(e,...t){async function r(e){return e.doc?(e.doc=await n(e.doc),e):e}async function i(e){return e.results?(e.results=await Promise.all(e.results.map(r)),e):e}const o=e(...t),{on:s,then:a}=o;return Object.assign(o,{on(e,t){const n=t;return"change"===e?t=async e=>{n(await r(e))}:"complete"===e&&(t=async e=>{n(await i(e))}),s.call(o,e,t)},then:(e,t)=>a.call(o,i).then(e,t)})}};"http"===this.type()&&(i.put=async function(e,n,...r){return e(n=await t(n),...r)},i.query=async function(e,...t){const r=await e(...t);return await Promise.all(r.rows.map((async e=>{e.doc&&(e.doc=await n(e.doc))}))),r}),r.install(this,i)}e.exports={transform:s,filter:s},"undefined"!=typeof window&&window.PouchDB&&window.PouchDB.plugin(t)},586:(e,t,n)=>{var r;n.d(t,{Z:()=>f});var i=new Uint8Array(16);function o(){if(!r&&!(r="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return r(i)}const s=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i,a=function(e){return"string"==typeof e&&s.test(e)};for(var u=[],c=0;c<256;++c)u.push((c+256).toString(16).substr(1));const f=function(e,t,n){var r=(e=e||{}).random||(e.rng||o)();if(r[6]=15&r[6]|64,r[8]=63&r[8]|128,t){n=n||0;for(var i=0;i<16;++i)t[n+i]=r[i];return t}return function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=(u[e[t+0]]+u[e[t+1]]+u[e[t+2]]+u[e[t+3]]+"-"+u[e[t+4]]+u[e[t+5]]+"-"+u[e[t+6]]+u[e[t+7]]+"-"+u[e[t+8]]+u[e[t+9]]+"-"+u[e[t+10]]+u[e[t+11]]+u[e[t+12]]+u[e[t+13]]+u[e[t+14]]+u[e[t+15]]).toLowerCase();if(!a(n))throw TypeError("Stringified UUID is invalid");return n}(r)}},684:(e,t)=>{function n(e,t,n){var r=n[n.length-1];e===r.element&&(n.pop(),r=n[n.length-1]);var i=r.element,o=r.index;Array.isArray(i)?i.push(e):o===t.length-2?i[t.pop()]=e:t.push(e)}t.stringify=function(e){var t=[];t.push({obj:e});for(var n,r,i,o,s,a,u,c,f,l,d="";n=t.pop();)if(r=n.obj,d+=n.prefix||"",i=n.val||"")d+=i;else if("object"!=typeof r)d+=void 0===r?null:JSON.stringify(r);else if(null===r)d+="null";else if(Array.isArray(r)){for(t.push({val:"]"}),o=r.length-1;o>=0;o--)s=0===o?"":",",t.push({obj:r[o],prefix:s});t.push({val:"["})}else{for(u in a=[],r)r.hasOwnProperty(u)&&a.push(u);for(t.push({val:"}"}),o=a.length-1;o>=0;o--)f=r[c=a[o]],l=o>0?",":"",l+=JSON.stringify(c)+":",t.push({obj:f,prefix:l});t.push({val:"{"})}return d},t.parse=function(e){for(var t,r,i,o,s,a,u,c,f,l=[],d=[],h=0;;)if("}"!==(t=e[h++])&&"]"!==t&&void 0!==t)switch(t){case" ":case"\t":case"\n":case":":case",":break;case"n":h+=3,n(null,l,d);break;case"t":h+=3,n(!0,l,d);break;case"f":h+=4,n(!1,l,d);break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":case"-":for(r="",h--;;){if(i=e[h++],!/[\d\.\-e\+]/.test(i)){h--;break}r+=i}n(parseFloat(r),l,d);break;case'"':for(o="",s=void 0,a=0;'"'!==(u=e[h++])||"\\"===s&&a%2==1;)o+=u,"\\"===(s=u)?a++:a=0;n(JSON.parse('"'+o+'"'),l,d);break;case"[":c={element:[],index:l.length},l.push(c.element),d.push(c);break;case"{":f={element:{},index:l.length},l.push(f.element),d.push(f);break;default:throw new Error("unexpectedly reached end of input: "+t)}else{if(1===l.length)return l.pop();n(l.pop(),l,d)}}},525:()=>{}},t={};function n(r){var i=t[r];if(void 0!==i)return i.exports;var o=t[r]={exports:{}};return e[r](o,o.exports,n),o.exports}n.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return n.d(t,{a:t}),t},n.d=(e,t)=>{for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var r={};(()=>{n.d(r,{o:()=>o});const e=n(198).Z,t=n(614).Z,i=n(380),o=e.plugin(t).plugin(i)})();var i=r.o;export{i as PouchDB}; \ No newline at end of file diff --git a/pouchdb-browser-webpack/package.json b/pouchdb-browser-webpack/package.json index 93361bb..26d2932 100644 --- a/pouchdb-browser-webpack/package.json +++ b/pouchdb-browser-webpack/package.json @@ -1,23 +1,25 @@ { - "name": "pouchdb-browser-webpack", - "version": "1.0.0", - "description": "pouchdb-browser webpack", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1", - "build": "webpack --mode=production --node-env=production", - "build:dev": "webpack --mode=development", - "build:prod": "webpack --mode=production --node-env=production", - "watch": "webpack --watch" - }, - "keywords": [], - "author": "", - "license": "ISC", - "dependencies": { - "pouchdb-browser": "^7.3.0" - }, - "devDependencies": { - "webpack": "^5.58.1", - "webpack-cli": "^4.9.0" - } + "name": "pouchdb-browser-webpack", + "version": "1.0.0", + "description": "pouchdb-browser webpack", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1", + "build": "webpack --mode=production --node-env=production", + "build:dev": "webpack --mode=development", + "build:prod": "webpack --mode=production --node-env=production", + "watch": "webpack --watch" + }, + "keywords": [], + "author": "", + "license": "ISC", + "dependencies": { + "pouchdb-browser": "^7.3.0", + "transform-pouch": "^2.0.0", + "pouchdb-find": "^7.3.0" + }, + "devDependencies": { + "webpack": "^5.58.1", + "webpack-cli": "^4.9.0" + } } diff --git a/pouchdb-browser-webpack/src/index.js b/pouchdb-browser-webpack/src/index.js index 95924ce..32c51e5 100644 --- a/pouchdb-browser-webpack/src/index.js +++ b/pouchdb-browser-webpack/src/index.js @@ -1,4 +1,10 @@ +/* eslint-disable no-undef */ +/* eslint-disable @typescript-eslint/no-var-requires */ // This module just webpacks pouchdb-browser -import * as PouchDB_src from "pouchdb-browser"; -const PouchDB = PouchDB_src.default; +// import * as PouchDB_src from "pouchdb-browser"; +const pouch = require("pouchdb-browser").default; +const find = require("pouchdb-find").default; +const transform = require("transform-pouch"); +const PouchDB = pouch.plugin(find).plugin(transform); + export { PouchDB }; diff --git a/src/LocalPouchDB.ts b/src/LocalPouchDB.ts index b0c7725..604055f 100644 --- a/src/LocalPouchDB.ts +++ b/src/LocalPouchDB.ts @@ -21,15 +21,56 @@ import { MILSTONE_DOCID, DatabaseConnectingStatus, } from "./lib/src/types"; -import { decrypt, encrypt } from "./lib/src/e2ee"; import { RemoteDBSettings } from "./lib/src/types"; -import { resolveWithIgnoreKnownError, delay, runWithLock, isPlainText, splitPieces, NewNotice, WrappedNotice } from "./lib/src/utils"; +import { resolveWithIgnoreKnownError, delay, runWithLock, NewNotice, WrappedNotice, shouldSplitAsPlainText, splitPieces2, enableEncryption } from "./lib/src/utils"; import { path2id } from "./utils"; import { Logger } from "./lib/src/logger"; -import { checkRemoteVersion, connectRemoteCouchDB, getLastPostFailedBySize } from "./utils_couchdb"; +import { checkRemoteVersion, connectRemoteCouchDBWithSetting, getLastPostFailedBySize } from "./utils_couchdb"; +import { openDB, deleteDB, IDBPDatabase } from "idb"; type ReplicationCallback = (e: PouchDB.Core.ExistingDocument[]) => Promise; +class LRUCache { + cache = new Map([]); + revCache = new Map([]); + maxCache = 100; + constructor() {} + get(key: string) { + // debugger + const v = this.cache.get(key); + if (v) { + // update the key to recently used. + this.cache.delete(key); + this.revCache.delete(v); + this.cache.set(key, v); + this.revCache.set(v, key); + } + return v; + } + revGet(value: string) { + // debugger + const key = this.revCache.get(value); + if (value) { + // update the key to recently used. + this.cache.delete(key); + this.revCache.delete(value); + this.cache.set(key, value); + this.revCache.set(value, key); + } + return key; + } + set(key: string, value: string) { + this.cache.set(key, value); + this.revCache.set(value, key); + if (this.cache.size > this.maxCache) { + for (const kv of this.cache) { + this.revCache.delete(kv[1]); + this.cache.delete(kv[0]); + if (this.cache.size <= this.maxCache) break; + } + } + } +} export class LocalPouchDB { auth: Credential; dbname: string; @@ -42,12 +83,13 @@ export class LocalPouchDB { h32: (input: string, seed?: number) => string; h64: (input: string, seedHigh?: number, seedLow?: number) => string; h32Raw: (input: Uint8Array, seed?: number) => number; - hashCache: { - [key: string]: string; - } = {}; - hashCacheRev: { - [key: string]: string; - } = {}; + // hashCache: { + // [key: string]: string; + // } = {}; + // hashCacheRev: { + // [key: string]: string; + // } = {}; + hashCaches = new LRUCache(); corruptedEntries: { [key: string]: EntryDoc } = {}; remoteLocked = false; @@ -90,8 +132,6 @@ export class LocalPouchDB { this.settings = settings; this.cancelHandler = this.cancelHandler.bind(this); this.isMobile = isMobile; - - // this.initializeDatabase(); } close() { Logger("Database closed (by close)"); @@ -101,10 +141,6 @@ export class LocalPouchDB { this.localDatabase.close(); } } - disposeHashCache() { - this.hashCache = {}; - this.hashCacheRev = {}; - } updateRecentModifiedDocs(id: string, rev: string, deleted: boolean) { const idrev = id + rev; @@ -119,52 +155,132 @@ export class LocalPouchDB { const idrev = id + rev; return this.recentModifiedDocs.indexOf(idrev) !== -1; } - - async initializeDatabase() { + async isOldDatabaseExists() { + const db = new PouchDB(this.dbname + "-livesync", { + auto_compaction: this.settings.useHistory ? false : true, + revs_limit: 100, + deterministic_revs: true, + skip_setup: true, + }); + try { + const info = await db.info(); + Logger(info, LOG_LEVEL.VERBOSE); + return db; + } catch (ex) { + return false; + } + } + async initializeDatabase(): Promise { await this.prepareHashFunctions(); if (this.localDatabase != null) this.localDatabase.close(); this.changeHandler = this.cancelHandler(this.changeHandler); this.localDatabase = null; - this.localDatabase = new PouchDB(this.dbname + "-livesync", { + + this.localDatabase = new PouchDB(this.dbname + "-livesync-v2", { auto_compaction: this.settings.useHistory ? false : true, revs_limit: 100, deterministic_revs: true, }); - - Logger("Database Info"); + Logger("Database info", LOG_LEVEL.VERBOSE); Logger(await this.localDatabase.info(), LOG_LEVEL.VERBOSE); - // initialize local node information. - const nodeinfo: EntryNodeInfo = await resolveWithIgnoreKnownError(this.localDatabase.get(NODEINFO_DOCID), { - _id: NODEINFO_DOCID, - type: "nodeinfo", - nodeid: "", - }); - if (nodeinfo.nodeid == "") { - nodeinfo.nodeid = Math.random().toString(36).slice(-10); - await this.localDatabase.put(nodeinfo); - } - this.localDatabase.on("close", () => { - Logger("Database closed."); - this.isReady = false; - this.localDatabase.removeAllListeners(); - }); - this.nodeid = nodeinfo.nodeid; - - // Traceing the leaf id - const changes = this.localDatabase - .changes({ - since: "now", - live: true, - filter: (doc) => doc.type == "leaf", - }) - .on("change", (e) => { - if (e.deleted) return; - this.leafArrived(e.id); - this.docSeq = `${e.seq}`; + Logger("Open Database..."); + // The sequence after migration. + const nextSeq = async (): Promise => { + Logger("Database Info"); + Logger(await this.localDatabase.info(), LOG_LEVEL.VERBOSE); + // initialize local node information. + const nodeinfo: EntryNodeInfo = await resolveWithIgnoreKnownError(this.localDatabase.get(NODEINFO_DOCID), { + _id: NODEINFO_DOCID, + type: "nodeinfo", + nodeid: "", + v20220607: true, }); - this.changeHandler = changes; - this.isReady = true; - Logger("Database is now ready."); + if (nodeinfo.nodeid == "") { + nodeinfo.nodeid = Math.random().toString(36).slice(-10); + await this.localDatabase.put(nodeinfo); + } + this.localDatabase.on("close", () => { + Logger("Database closed."); + this.isReady = false; + this.localDatabase.removeAllListeners(); + }); + this.nodeid = nodeinfo.nodeid; + + // Traceing the leaf id + const changes = this.localDatabase + .changes({ + since: "now", + live: true, + filter: (doc) => doc.type == "leaf", + }) + .on("change", (e) => { + if (e.deleted) return; + this.leafArrived(e.id); + this.docSeq = `${e.seq}`; + }); + this.changeHandler = changes; + this.isReady = true; + Logger("Database is now ready."); + return true; + }; + Logger("Checking old database", LOG_LEVEL.VERBOSE); + const old = await this.isOldDatabaseExists(); + + //Migrate. + if (old) { + const oi = await old.info(); + if (oi.doc_count == 0) { + Logger("Old database is empty, proceed to next step", LOG_LEVEL.VERBOSE); + // aleady converted. + return nextSeq(); + } + // + const progress = NewNotice("Converting..", 0); + try { + Logger("We have to upgrade database..", LOG_LEVEL.NOTICE); + + // To debug , uncomment below. + + // this.localDatabase.destroy(); + // await delay(100); + // this.localDatabase = new PouchDB(this.dbname + "-livesync-v2", { + // auto_compaction: this.settings.useHistory ? false : true, + // revs_limit: 100, + // deterministic_revs: true, + // }); + const newDbStatus = await this.localDatabase.info(); + Logger("New database is initialized"); + Logger(newDbStatus); + + if (this.settings.encrypt) { + enableEncryption(old, this.settings.passphrase); + } + const rep = old.replicate.to(this.localDatabase); + rep.on("change", (e) => { + progress.setMessage(`Converting ${e.docs_written} docs...`); + Logger(`Converting ${e.docs_written} docs...`, LOG_LEVEL.VERBOSE); + }); + const w = await rep; + progress.hide(); + + if (w.ok) { + Logger("Conversion completed!", LOG_LEVEL.NOTICE); + old.destroy(); // delete the old database. + this.isReady = true; + return nextSeq(); + } else { + throw new Error("Conversion failed!"); + } + } catch (ex) { + progress.hide(); + Logger("Conversion failed!, If you are fully synchronized, please drop the old database in the Hatch pane in setting dialog. or please make an issue on Github.", LOG_LEVEL.NOTICE); + Logger(ex); + this.isReady = false; + return false; + } + } else { + return nextSeq(); + } } async prepareHashFunctions() { @@ -203,55 +319,28 @@ export class LocalPouchDB { async getDBLeaf(id: string, waitForReady: boolean): Promise { await this.waitForGCComplete(); // when in cache, use that. - if (this.hashCacheRev[id]) { - return this.hashCacheRev[id]; + const leaf = this.hashCaches.revGet(id); + if (leaf) { + return leaf; } try { const w = await this.localDatabase.get(id); if (w.type == "leaf") { - if (id.startsWith("h:+")) { - try { - w.data = await decrypt(w.data, this.settings.passphrase); - } catch (e) { - Logger("The element of the document has been encrypted, but decryption failed.", LOG_LEVEL.NOTICE); - throw e; - } - } - this.hashCache[w.data] = id; - this.hashCacheRev[id] = w.data; + this.hashCaches.set(id, w.data); return w.data; } throw new Error(`retrive leaf, but it was not leaf.`); } catch (ex) { - if (ex.status && ex.status == 404 && waitForReady) { - // just leaf is not ready. - // wait for on - if ((await this.waitForLeafReady(id)) === false) { - throw new Error(`time out (waiting leaf)`); - } - try { - // retrive again. - const w = await this.localDatabase.get(id); - if (w.type == "leaf") { - if (id.startsWith("h:+")) { - try { - w.data = await decrypt(w.data, this.settings.passphrase); - } catch (e) { - Logger("The element of the document has been encrypted, but decryption failed.", LOG_LEVEL.NOTICE); - throw e; - } - } - this.hashCache[w.data] = id; - this.hashCacheRev[id] = w.data; - return w.data; + if (ex.status && ex.status == 404) { + if (waitForReady) { + // just leaf is not ready. + // wait for on + if ((await this.waitForLeafReady(id)) === false) { + throw new Error(`time out (waiting leaf)`); } - throw new Error(`retrive leaf, but it was not leaf.`); - } catch (ex) { - if (ex.status && ex.status == 404) { - throw new Error("leaf is not found"); - } - Logger(`Something went wrong on retriving leaf`); - throw ex; + return this.getDBLeaf(id, false); + } else { + throw new Error("Leaf was not found"); } } else { Logger(`Something went wrong on retriving leaf`); @@ -517,7 +606,7 @@ export class LocalPouchDB { let plainSplit = false; let cacheUsed = 0; const userpasswordHash = this.h32Raw(new TextEncoder().encode(this.settings.passphrase)); - if (isPlainText(note._id)) { + if (shouldSplitAsPlainText(note._id)) { pieceSize = MAX_DOC_SIZE; plainSplit = true; } @@ -535,7 +624,7 @@ export class LocalPouchDB { let longLineThreshold = this.settings.longLineThreshold; if (longLineThreshold < 100) longLineThreshold = 100; - const pieces = splitPieces(note.data, pieceSize, plainSplit, minimumChunkSize, longLineThreshold); + const pieces = splitPieces2(note.data, pieceSize, plainSplit, minimumChunkSize, longLineThreshold); for (const piece of pieces()) { processed++; let leafid = ""; @@ -544,9 +633,10 @@ export class LocalPouchDB { let hashQ = 0; // if hash collided, **IF**, count it up. let tryNextHash = false; let needMake = true; - if (typeof this.hashCache[piece] !== "undefined") { + const cache = this.hashCaches.get(piece); + if (cache) { hashedPiece = ""; - leafid = this.hashCache[piece]; + leafid = cache; needMake = false; skiped++; cacheUsed++; @@ -563,21 +653,11 @@ export class LocalPouchDB { try { nleafid = `${leafid}${hashQ}`; const pieceData = await this.localDatabase.get(nleafid); - //try decode - if (pieceData._id.startsWith("h:+")) { - try { - pieceData.data = await decrypt(pieceData.data, this.settings.passphrase); - } catch (e) { - Logger("Decode failed!"); - throw e; - } - } if (pieceData.type == "leaf" && pieceData.data == piece) { leafid = nleafid; needMake = false; tryNextHash = false; - this.hashCache[piece] = leafid; - this.hashCacheRev[leafid] = piece; + this.hashCaches.set(piece, leafid); } else if (pieceData.type == "leaf") { Logger("hash:collision!!"); hashQ++; @@ -601,19 +681,15 @@ export class LocalPouchDB { } while (tryNextHash); if (needMake) { //have to make - let savePiece = piece; - if (this.settings.encrypt) { - const passphrase = this.settings.passphrase; - savePiece = await encrypt(piece, passphrase); - } + const savePiece = piece; + const d: EntryLeaf = { _id: leafid, data: savePiece, type: "leaf", }; newLeafs.push(d); - this.hashCache[piece] = leafid; - this.hashCacheRev[leafid] = piece; + this.hashCaches.set(piece, leafid); made++; } else { skiped++; @@ -635,7 +711,6 @@ export class LocalPouchDB { } else { Logger(`save failed:id:${item.id} rev:${item.rev}`, LOG_LEVEL.NOTICE); Logger(item); - // this.disposeHashCache(); saved = false; } } @@ -707,7 +782,7 @@ export class LocalPouchDB { this.openOneshotReplication( setting, showingNotice, - async (e) => { }, + async (e) => {}, false, (e) => { if (e === true) res(e); @@ -731,16 +806,12 @@ export class LocalPouchDB { return false; } const uri = setting.couchDB_URI + (setting.couchDB_DBNAME == "" ? "" : "/" + setting.couchDB_DBNAME); - const auth: Credential = { - username: setting.couchDB_USER, - password: setting.couchDB_PASSWORD, - }; if (this.syncHandler != null) { Logger("Another replication running."); return false; } - const dbret = await connectRemoteCouchDB(uri, auth, setting.disableRequestURI || this.isMobile); + const dbret = await connectRemoteCouchDBWithSetting(setting, this.isMobile); if (typeof dbret === "string") { Logger(`could not connect to ${uri}: ${dbret}`, showResult ? LOG_LEVEL.NOTICE : LOG_LEVEL.INFO); return false; @@ -1038,6 +1109,15 @@ export class LocalPouchDB { Logger("Replication closed"); } + async resetLocalOldDatabase() { + const oldDB = await this.isOldDatabaseExists(); + if (oldDB) { + oldDB.destroy(); + NewNotice("Deleted! Please re-launch obsidian.", LOG_LEVEL.NOTICE); + } else { + NewNotice("Old database is not exist.", LOG_LEVEL.NOTICE); + } + } async resetDatabase() { await this.waitForGCComplete(); this.changeHandler = this.cancelHandler(this.changeHandler); @@ -1047,17 +1127,11 @@ export class LocalPouchDB { await this.localDatabase.destroy(); this.localDatabase = null; await this.initializeDatabase(); - this.disposeHashCache(); Logger("Local Database Reset", LOG_LEVEL.NOTICE); } async tryResetRemoteDatabase(setting: RemoteDBSettings) { await this.closeReplication(); - const uri = setting.couchDB_URI + (setting.couchDB_DBNAME == "" ? "" : "/" + setting.couchDB_DBNAME); - const auth: Credential = { - username: setting.couchDB_USER, - password: setting.couchDB_PASSWORD, - }; - const con = await connectRemoteCouchDB(uri, auth, setting.disableRequestURI || this.isMobile); + const con = await connectRemoteCouchDBWithSetting(setting, this.isMobile); if (typeof con == "string") return; try { await con.db.destroy(); @@ -1070,22 +1144,14 @@ export class LocalPouchDB { } async tryCreateRemoteDatabase(setting: RemoteDBSettings) { await this.closeReplication(); - const uri = setting.couchDB_URI + (setting.couchDB_DBNAME == "" ? "" : "/" + setting.couchDB_DBNAME); - const auth: Credential = { - username: setting.couchDB_USER, - password: setting.couchDB_PASSWORD, - }; - const con2 = await connectRemoteCouchDB(uri, auth, setting.disableRequestURI || this.isMobile); + const con2 = await connectRemoteCouchDBWithSetting(setting, this.isMobile); + if (typeof con2 === "string") return; Logger("Remote Database Created or Connected", LOG_LEVEL.NOTICE); } async markRemoteLocked(setting: RemoteDBSettings, locked: boolean) { const uri = setting.couchDB_URI + (setting.couchDB_DBNAME == "" ? "" : "/" + setting.couchDB_DBNAME); - const auth: Credential = { - username: setting.couchDB_USER, - password: setting.couchDB_PASSWORD, - }; - const dbret = await connectRemoteCouchDB(uri, auth, setting.disableRequestURI || this.isMobile); + const dbret = await connectRemoteCouchDBWithSetting(setting, this.isMobile); if (typeof dbret === "string") { Logger(`could not connect to ${uri}:${dbret}`, LOG_LEVEL.NOTICE); return; @@ -1115,11 +1181,7 @@ export class LocalPouchDB { } async markRemoteResolved(setting: RemoteDBSettings) { const uri = setting.couchDB_URI + (setting.couchDB_DBNAME == "" ? "" : "/" + setting.couchDB_DBNAME); - const auth: Credential = { - username: setting.couchDB_USER, - password: setting.couchDB_PASSWORD, - }; - const dbret = await connectRemoteCouchDB(uri, auth, setting.disableRequestURI || this.isMobile); + const dbret = await connectRemoteCouchDBWithSetting(setting, this.isMobile); if (typeof dbret === "string") { Logger(`could not connect to ${uri}:${dbret}`, LOG_LEVEL.NOTICE); return; @@ -1159,7 +1221,6 @@ export class LocalPouchDB { const dc = await this.localDatabase.allDocs({ keys: [...children] }); if (dc.rows.some((e) => "error" in e)) { this.corruptedEntries[entry._id] = entry; - this.disposeHashCache(); Logger(`sancheck:corrupted:${entry._id} : ${children.length}`, LOG_LEVEL.VERBOSE); return false; } @@ -1180,84 +1241,150 @@ export class LocalPouchDB { await runWithLock("replicate", true, async () => { if (this.gcRunning) return; this.gcRunning = true; + let idbGC: IDBPDatabase<{ id: string }> = null; + const storeIDB = "gc"; + const idbname = "idb-" + this.dbname + "-idb-gcx"; try { - // get all documents of NewEntry2 - // we don't use queries , just use allDocs(); - this.disposeHashCache(); - let c = 0; - let readCount = 0; - let hashPieces: string[] = []; - let usedPieces: string[] = []; - Logger("Collecting Garbage"); - do { - const result = await this.localDatabase.allDocs({ include_docs: false, skip: c, limit: 2000, conflicts: true }); - readCount = result.rows.length; - Logger("checked:" + readCount); - if (readCount > 0) { - //there are some result - for (const v of result.rows) { - if (v.id.startsWith("h:")) { - hashPieces = Array.from(new Set([...hashPieces, v.id])); - } else { - const docT = await this.localDatabase.get(v.id, { revs_info: true }); - const revs = docT._revs_info; - // console.log(`revs:${revs.length}`) - for (const rev of revs) { - if (rev.status != "available") continue; - // console.log(`id:${docT._id},rev:${rev.rev}`); - const doc = await this.localDatabase.get(v.id, { rev: rev.rev }); - if ("children" in doc) { - // used pieces memo. - usedPieces = Array.from(new Set([...usedPieces, ...doc.children])); - if (doc._conflicts) { - for (const cid of doc._conflicts) { - const p = await this.localDatabase.get(doc._id, { rev: cid }); - if (p.type == "newnote" || p.type == "plain") { - usedPieces = Array.from(new Set([...usedPieces, ...p.children])); - } - } - } - } + const procAllDocs = async (getLeaf: boolean, startkey: string, endkey: string, callback: (idordoc: string[]) => Promise) => { + let c = 0; + let readCount = 0; + do { + const result = await this.localDatabase.allDocs({ include_docs: false, skip: c, limit: 2000, conflicts: !getLeaf, startkey: startkey, endkey: endkey }); + readCount = result.rows.length; + if (readCount > 0) { + await callback(result.rows.map((e) => e.id)); + } + c += readCount; + } while (readCount != 0); + }; + + // Delete working indexedDB once. + + await deleteDB(idbname); + idbGC = await openDB(idbname, 1, { + upgrade(db) { + db.createObjectStore(storeIDB, { keyPath: "id" }); + }, + }); + + // Mark all chunks once. + await procAllDocs(true, "h:", "h_", async (docs) => { + Logger(`Chunks marked - :${docs.length}`); + const tx = idbGC.transaction(storeIDB, "readwrite"); + const store = tx.objectStore(storeIDB); + + for (const docId of docs) { + await store.put({ id: docId }); + } + await tx.done; + }); + + Logger("All chunks are marked once"); + + const unmarkUsedByHashId = async (doc: EntryDoc) => { + if ("children" in doc) { + const tx = idbGC.transaction(storeIDB, "readwrite"); + const store = tx.objectStore(storeIDB); + + for (const hashId of doc.children) { + await store.delete(hashId); + } + await tx.done; + } + }; + Logger("Processing existen docs"); + let procDocs = 0; + await procAllDocs(false, null, null, async (doc) => { + const docIds = (doc as string[]).filter((e) => !e.startsWith("h:") && !e.startsWith("ps:")); + for (const docId of docIds) { + procDocs++; + if (procDocs % 25 == 0) Logger(`${procDocs} Processed`); + const docT = await this.localDatabase.get(docId, { revs_info: true }); + if (docT._deleted) continue; + // Unmark about latest doc. + unmarkUsedByHashId(docT); + const revs = docT._revs_info; + + // Unmark old revisions + for (const rev of revs) { + if (rev.status != "available") continue; + const docRev = await this.localDatabase.get(docId, { rev: rev.rev }); + unmarkUsedByHashId(docRev); + if (docRev._conflicts) { + // Unmark the conflicted chunks of old revisions. + for (const cid of docRev._conflicts) { + const docConflict = await this.localDatabase.get(docId, { rev: cid }); + unmarkUsedByHashId(docConflict); } } } - } - c += readCount; - } while (readCount != 0); - // items collected. - Logger("Finding unused pieces"); - this.disposeHashCache(); - const garbages = hashPieces.filter((e) => usedPieces.indexOf(e) == -1); - let deleteCount = 0; - Logger("we have to delete:" + garbages.length); - let deleteDoc: EntryDoc[] = []; - for (const v of garbages) { - try { - const item = await this.localDatabase.get(v); - item._deleted = true; - deleteDoc.push(item); - if (deleteDoc.length > 50) { - await this.localDatabase.bulkDocs(deleteDoc); - deleteDoc = []; - Logger("delete:" + deleteCount); + // Unmark the conflicted chunk. + if (docT._conflicts) { + for (const cid of docT._conflicts) { + const docConflict = await this.localDatabase.get(docId, { rev: cid }); + unmarkUsedByHashId(docConflict); + } } - deleteCount++; - } catch (ex) { - if (ex.status && ex.status == 404) { - // NO OP. It should be timing problem. + } + }); + // All marked chunks could be deleted. + Logger("Delete non-used chunks"); + let dataLeft = false; + let chunkKeys: string[] = []; + let totalDelCount = 0; + do { + const tx = idbGC.transaction(storeIDB, "readonly"); + const store = tx.objectStore(storeIDB); + let cursor = await store.openCursor(); + if (cursor == null) break; + const maxconcurrentDocs = 10; + let delChunkCount = 0; + do { + // console.log(cursor.key, cursor.value); + if (cursor) { + chunkKeys.push(cursor.key as string); + delChunkCount++; + dataLeft = true; } else { - throw ex; + dataLeft = false; } + cursor = await cursor.continue(); + } while (cursor && dataLeft && delChunkCount < maxconcurrentDocs); + // if (chunkKeys.length > 0) { + totalDelCount += delChunkCount; + const delDocResult = await this.localDatabase.allDocs({ keys: chunkKeys, include_docs: true }); + const delDocs = delDocResult.rows.map((e) => ({ ...e.doc, _deleted: true })); + await this.localDatabase.bulkDocs(delDocs); + Logger(`deleted from pouchdb:${delDocs.length}`); + const tx2 = idbGC.transaction(storeIDB, "readwrite"); + const store2 = tx2.objectStore(storeIDB); + for (const doc of chunkKeys) { + await store2.delete(doc); } + Logger(`deleted from workspace:${chunkKeys.length}`); + await tx2.done; + // } + chunkKeys = []; + } while (dataLeft); + Logger(`Deleted ${totalDelCount} chunks`); + Logger("Teardown the database"); + if (idbGC != null) { + idbGC.close(); + idbGC = null; } - if (deleteDoc.length > 0) { - await this.localDatabase.bulkDocs(deleteDoc); - } - Logger(`GC:deleted ${deleteCount} items.`); + await deleteDB(idbname); + this.gcRunning = false; + Logger("Done"); + } catch (ex) { + Logger("Error on garbage collection"); + Logger(ex); } finally { + if (idbGC != null) { + idbGC.close(); + } + await deleteDB(idbname); this.gcRunning = false; } }); - this.disposeHashCache(); } } diff --git a/src/ObsidianLiveSyncSettingTab.ts b/src/ObsidianLiveSyncSettingTab.ts index dbb6478..9774568 100644 --- a/src/ObsidianLiveSyncSettingTab.ts +++ b/src/ObsidianLiveSyncSettingTab.ts @@ -1,9 +1,9 @@ import { App, PluginSettingTab, Setting, sanitizeHTMLToDom, RequestUrlParam, requestUrl } from "obsidian"; -import { EntryDoc, LOG_LEVEL } from "./lib/src/types"; +import { EntryDoc, LOG_LEVEL, RemoteDBSettings } from "./lib/src/types"; import { path2id, id2path } from "./utils"; import { NewNotice, runWithLock } from "./lib/src/utils"; import { Logger } from "./lib/src/logger"; -import { connectRemoteCouchDB } from "./utils_couchdb"; +import { checkSyncInfo, connectRemoteCouchDBWithSetting } from "./utils_couchdb"; import { testCrypt } from "./lib/src/e2ee"; import ObsidianLiveSyncPlugin from "./main"; @@ -15,14 +15,16 @@ export class ObsidianLiveSyncSettingTab extends PluginSettingTab { this.plugin = plugin; } async testConnection(): Promise { - const db = await connectRemoteCouchDB( - this.plugin.settings.couchDB_URI + (this.plugin.settings.couchDB_DBNAME == "" ? "" : "/" + this.plugin.settings.couchDB_DBNAME), - { - username: this.plugin.settings.couchDB_USER, - password: this.plugin.settings.couchDB_PASSWORD, - }, - this.plugin.settings.disableRequestURI - ); + // const db = await connectRemoteCouchDB( + // this.plugin.settings.couchDB_URI + (this.plugin.settings.couchDB_DBNAME == "" ? "" : "/" + this.plugin.settings.couchDB_DBNAME), + // { + // username: this.plugin.settings.couchDB_USER, + // password: this.plugin.settings.couchDB_PASSWORD, + // }, + // this.plugin.settings.disableRequestURI, + // this.plugin.settings.encrypt ? this.plugin.settings.passphrase : this.plugin.settings.encrypt + // ); + const db = await connectRemoteCouchDBWithSetting(this.plugin.settings, this.plugin.localDatabase.isMobile); if (typeof db === "string") { this.plugin.addLog(`could not connect to ${this.plugin.settings.couchDB_URI} : ${this.plugin.settings.couchDB_DBNAME} \n(${db})`, LOG_LEVEL.NOTICE); return; @@ -78,7 +80,7 @@ export class ObsidianLiveSyncSettingTab extends PluginSettingTab { const containerRemoteDatabaseEl = containerEl.createDiv(); containerRemoteDatabaseEl.createEl("h3", { text: "Remote Database configuration" }); const syncWarn = containerRemoteDatabaseEl.createEl("div", { text: `These settings are kept locked while automatic synchronization options are enabled. Disable these options in the "Sync Settings" tab to unlock.` }); - syncWarn.addClass("op-warn"); + syncWarn.addClass("op-warn-info"); syncWarn.addClass("sls-hidden"); const isAnySyncEnabled = (): boolean => { @@ -170,20 +172,126 @@ export class ObsidianLiveSyncSettingTab extends PluginSettingTab { this.plugin.settings.couchDB_DBNAME = value; await this.plugin.saveSettings(); }) - ), + ) - new Setting(containerRemoteDatabaseEl) - .setDesc("This feature is locked in mobile") - .setName("Use the old connecting method") - .addToggle((toggle) => { - toggle.setValue(this.plugin.settings.disableRequestURI).onChange(async (value) => { - this.plugin.settings.disableRequestURI = value; + // new Setting(containerRemoteDatabaseEl) + // .setDesc("This feature is locked in mobile") + // .setName("Use the old connecting method") + // .addToggle((toggle) => { + // toggle.setValue(this.plugin.settings.disableRequestURI).onChange(async (value) => { + // this.plugin.settings.disableRequestURI = value; + // await this.plugin.saveSettings(); + // }); + // toggle.setDisabled(this.plugin.isMobile); + // return toggle; + // }) + ); + new Setting(containerRemoteDatabaseEl) + .setName("End to End Encryption") + .setDesc("Encrypting contents on the database.") + .addToggle((toggle) => + toggle.setValue(this.plugin.settings.workingEncrypt).onChange(async (value) => { + this.plugin.settings.workingEncrypt = value; + phasspharase.setDisabled(!value); + await this.plugin.saveSettings(); + }) + ); + const phasspharase = new Setting(containerRemoteDatabaseEl) + .setName("Passphrase") + .setDesc("Encrypting passphrase") + .addText((text) => { + text.setPlaceholder("") + .setValue(this.plugin.settings.workingPassphrase) + .onChange(async (value) => { + this.plugin.settings.workingPassphrase = value; await this.plugin.saveSettings(); }); - toggle.setDisabled(this.plugin.isMobile); - return toggle; - }) - ); + text.inputEl.setAttribute("type", "password"); + }); + phasspharase.setDisabled(!this.plugin.settings.workingEncrypt); + containerRemoteDatabaseEl.createEl("div", { + text: "If you change the passphrase, rebuilding the remote database is required. Please press 'Apply and send'. Or, If you have configured it to connect to an existing database, click 'Just apply'.", + }); + const checkWorkingPassphrase = async (): Promise => { + const settingForCheck: RemoteDBSettings = { + ...this.plugin.settings, + encrypt: this.plugin.settings.workingEncrypt, + passphrase: this.plugin.settings.workingPassphrase, + }; + console.dir(settingForCheck); + const db = await connectRemoteCouchDBWithSetting(settingForCheck, this.plugin.localDatabase.isMobile); + if (typeof db === "string") { + Logger("Could not connect to the database.", LOG_LEVEL.NOTICE); + return false; + } else { + if (await checkSyncInfo(db.db)) { + // Logger("Database connected", LOG_LEVEL.NOTICE); + return true; + } else { + Logger("Failed to read remote database", LOG_LEVEL.NOTICE); + return false; + } + } + }; + const applyEncryption = async (sendToServer: boolean) => { + if (this.plugin.settings.workingEncrypt && this.plugin.settings.workingPassphrase == "") { + Logger("If you enable encryption, you have to set the passphrase", LOG_LEVEL.NOTICE); + return; + } + if (this.plugin.settings.workingEncrypt && !(await testCrypt())) { + Logger("WARNING! Your device would not support encryption.", LOG_LEVEL.NOTICE); + return; + } + if (!(await checkWorkingPassphrase())) { + return; + } + if (!this.plugin.settings.workingEncrypt) { + this.plugin.settings.workingPassphrase = ""; + } + this.plugin.settings.liveSync = false; + this.plugin.settings.periodicReplication = false; + this.plugin.settings.syncOnSave = false; + this.plugin.settings.syncOnStart = false; + this.plugin.settings.syncOnFileOpen = false; + this.plugin.settings.encrypt = this.plugin.settings.workingEncrypt; + this.plugin.settings.passphrase = this.plugin.settings.workingPassphrase; + + await this.plugin.saveSettings(); + // await this.plugin.resetLocalDatabase(); + if (sendToServer) { + await this.plugin.initializeDatabase(true); + await this.plugin.markRemoteLocked(); + await this.plugin.tryResetRemoteDatabase(); + await this.plugin.markRemoteLocked(); + await this.plugin.replicateAllToServer(true); + } else { + await this.plugin.markRemoteResolved(); + await this.plugin.replicate(true); + } + }; + new Setting(containerRemoteDatabaseEl) + .setName("Apply") + .setDesc("apply encryption settinngs, and re-initialize remote database") + .addButton((button) => + button + .setButtonText("Apply and send") + .setWarning() + .setDisabled(false) + .setClass("sls-btn-left") + .onClick(async () => { + await applyEncryption(true); + }) + ) + .addButton((button) => + button + .setButtonText("Just apply") + .setWarning() + .setDisabled(false) + .setClass("sls-btn-right") + .onClick(async () => { + await applyEncryption(false); + }) + ); new Setting(containerRemoteDatabaseEl) .setName("Test Database Connection") @@ -408,88 +516,6 @@ export class ObsidianLiveSyncSettingTab extends PluginSettingTab { await this.plugin.garbageCollect(); }) ); - new Setting(containerLocalDatabaseEl) - .setName("End to End Encryption") - .setDesc("Encrypting contents on the database.") - .addToggle((toggle) => - toggle.setValue(this.plugin.settings.workingEncrypt).onChange(async (value) => { - this.plugin.settings.workingEncrypt = value; - phasspharase.setDisabled(!value); - await this.plugin.saveSettings(); - }) - ); - const phasspharase = new Setting(containerLocalDatabaseEl) - .setName("Passphrase") - .setDesc("Encrypting passphrase") - .addText((text) => { - text.setPlaceholder("") - .setValue(this.plugin.settings.workingPassphrase) - .onChange(async (value) => { - this.plugin.settings.workingPassphrase = value; - await this.plugin.saveSettings(); - }); - text.inputEl.setAttribute("type", "password"); - }); - phasspharase.setDisabled(!this.plugin.settings.workingEncrypt); - containerLocalDatabaseEl.createEl("div", { - text: "When you change any encryption enabled or passphrase, you have to reset all databases to make sure that the last password is unused and erase encrypted data from anywhere. This operation will not lost your vault if you are fully synced.", - }); - const applyEncryption = async (sendToServer: boolean) => { - if (this.plugin.settings.workingEncrypt && this.plugin.settings.workingPassphrase == "") { - Logger("If you enable encryption, you have to set the passphrase", LOG_LEVEL.NOTICE); - return; - } - if (this.plugin.settings.workingEncrypt && !(await testCrypt())) { - Logger("WARNING! Your device would not support encryption.", LOG_LEVEL.NOTICE); - return; - } - if (!this.plugin.settings.workingEncrypt) { - this.plugin.settings.workingPassphrase = ""; - } - this.plugin.settings.liveSync = false; - this.plugin.settings.periodicReplication = false; - this.plugin.settings.syncOnSave = false; - this.plugin.settings.syncOnStart = false; - this.plugin.settings.syncOnFileOpen = false; - this.plugin.settings.encrypt = this.plugin.settings.workingEncrypt; - this.plugin.settings.passphrase = this.plugin.settings.workingPassphrase; - - await this.plugin.saveSettings(); - await this.plugin.resetLocalDatabase(); - if (sendToServer) { - await this.plugin.initializeDatabase(true); - await this.plugin.markRemoteLocked(); - await this.plugin.tryResetRemoteDatabase(); - await this.plugin.markRemoteLocked(); - await this.plugin.replicateAllToServer(true); - } else { - await this.plugin.markRemoteResolved(); - await this.plugin.replicate(true); - } - }; - new Setting(containerLocalDatabaseEl) - .setName("Apply") - .setDesc("apply encryption settinngs, and re-initialize database") - .addButton((button) => - button - .setButtonText("Apply and send") - .setWarning() - .setDisabled(false) - .setClass("sls-btn-left") - .onClick(async () => { - await applyEncryption(true); - }) - ) - .addButton((button) => - button - .setButtonText("Apply and receive") - .setWarning() - .setDisabled(false) - .setClass("sls-btn-right") - .onClick(async () => { - await applyEncryption(false); - }) - ); containerLocalDatabaseEl.createEl("div", { text: sanitizeHTMLToDom(`Advanced settings
@@ -830,7 +856,7 @@ export class ObsidianLiveSyncSettingTab extends PluginSettingTab { } } const hatchWarn = containerHatchEl.createEl("div", { text: `To stop the bootup sequence for fixing problems on databases, you can put redflag.md on top of your vault (Rebooting obsidian is required).` }); - hatchWarn.addClass("op-warn"); + hatchWarn.addClass("op-warn-info"); const dropHistory = async (sendToServer: boolean) => { this.plugin.settings.liveSync = false; this.plugin.settings.periodicReplication = false; @@ -1001,6 +1027,20 @@ export class ObsidianLiveSyncSettingTab extends PluginSettingTab { }) ); + new Setting(containerHatchEl) + .setName("Drop old encrypted database") + .setDesc("WARNING: Please use this button only when you have failed on converting old-style localdatabase at v0.10.0.") + .addButton((button) => + button + .setButtonText("Drop") + .setWarning() + .setDisabled(false) + .onClick(async () => { + await this.plugin.resetLocalOldDatabase(); + await this.plugin.initializeDatabase(); + }) + ); + addScreenElement("50", containerHatchEl); // With great respect, thank you TfTHacker! // refered: https://github.com/TfTHacker/obsidian42-brat/blob/main/src/features/BetaPlugins.ts diff --git a/src/lib b/src/lib index d495f45..92c1bbc 160000 --- a/src/lib +++ b/src/lib @@ -1 +1 @@ -Subproject commit d495f4577ab2a90f3471d21336b3dcf38b861d40 +Subproject commit 92c1bbc45dc7961d3af65dd151a9b3d3b48b18ec diff --git a/src/main.ts b/src/main.ts index 7d6978b..eb78517 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,7 +1,7 @@ import { debounce, Notice, Plugin, TFile, addIcon, TFolder, normalizePath, TAbstractFile, Editor, MarkdownView, PluginManifest, Modal, App } from "obsidian"; import { diff_match_patch } from "diff-match-patch"; -import { EntryDoc, LoadedEntry, ObsidianLiveSyncSettings, diff_check_result, diff_result_leaf, EntryBody, LOG_LEVEL, VER, DEFAULT_SETTINGS, diff_result, FLAGMD_REDFLAG } from "./lib/src/types"; +import { EntryDoc, LoadedEntry, ObsidianLiveSyncSettings, diff_check_result, diff_result_leaf, EntryBody, LOG_LEVEL, VER, DEFAULT_SETTINGS, diff_result, FLAGMD_REDFLAG, SYNCINFO_ID } from "./lib/src/types"; import { PluginDataEntry, PERIODIC_PLUGIN_SWEEP, PluginList, DevicePluginList } from "./types"; import { base64ToString, @@ -17,6 +17,7 @@ import { setNoticeClass, NewNotice, allSettledWithConcurrencyLimit, + getLocks, } from "./lib/src/utils"; import { Logger, setLogger } from "./lib/src/logger"; import { LocalPouchDB } from "./LocalPouchDB"; @@ -27,6 +28,7 @@ import { DocumentHistoryModal } from "./DocumentHistoryModal"; import PluginPane from "./PluginPane.svelte"; import { id2path, path2id } from "./utils"; +const isDebug = false; setNoticeClass(Notice); class PluginDialogModal extends Modal { plugin: ObsidianLiveSyncPlugin; @@ -161,37 +163,42 @@ export default class ObsidianLiveSyncPlugin extends Plugin { this.addSettingTab(new ObsidianLiveSyncSettingTab(this.app, this)); this.app.workspace.onLayoutReady(async () => { - try { - if (this.isRedFlagRaised()) { - this.settings.batchSave = false; - this.settings.liveSync = false; - this.settings.periodicReplication = false; - this.settings.syncOnSave = false; - this.settings.syncOnStart = false; - this.settings.syncOnFileOpen = false; - this.settings.autoSweepPlugins = false; - this.settings.usePluginSync = false; - this.settings.suspendFileWatching = true; - await this.saveSettings(); - await this.openDatabase(); - const warningMessage = "The red flag is raised! The whole initialize steps are skipped, and any file changes are not captured."; - Logger(warningMessage, LOG_LEVEL.NOTICE); - this.setStatusBarText(warningMessage); - } else { - if (this.settings.suspendFileWatching) { - Logger("'Suspend file watching' turned on. Are you sure this is what you intended? Every modification on the vault will be ignored.", LOG_LEVEL.NOTICE); + if (this.localDatabase.isReady) + try { + if (this.isRedFlagRaised()) { + this.settings.batchSave = false; + this.settings.liveSync = false; + this.settings.periodicReplication = false; + this.settings.syncOnSave = false; + this.settings.syncOnStart = false; + this.settings.syncOnFileOpen = false; + this.settings.autoSweepPlugins = false; + this.settings.usePluginSync = false; + this.settings.suspendFileWatching = true; + await this.saveSettings(); + await this.openDatabase(); + const warningMessage = "The red flag is raised! The whole initialize steps are skipped, and any file changes are not captured."; + Logger(warningMessage, LOG_LEVEL.NOTICE); + this.setStatusBarText(warningMessage); + } else { + if (this.settings.suspendFileWatching) { + Logger("'Suspend file watching' turned on. Are you sure this is what you intended? Every modification on the vault will be ignored.", LOG_LEVEL.NOTICE); + } + const isInitalized = await this.initializeDatabase(); + if (!isInitalized) { + //TODO:stop all sync. + return false; + } } - await this.initializeDatabase(); + await this.realizeSettingSyncMode(); + this.registerWatchEvents(); + if (this.settings.syncOnStart) { + this.localDatabase.openReplication(this.settings, false, false, this.parseReplicationResult); + } + } catch (ex) { + Logger("Error while loading Self-hosted LiveSync", LOG_LEVEL.NOTICE); + Logger(ex, LOG_LEVEL.VERBOSE); } - await this.realizeSettingSyncMode(); - this.registerWatchEvents(); - if (this.settings.syncOnStart) { - this.localDatabase.openReplication(this.settings, false, false, this.parseReplicationResult); - } - } catch (ex) { - Logger("Error while loading Self-hosted LiveSync", LOG_LEVEL.NOTICE); - Logger(ex, LOG_LEVEL.VERBOSE); - } }); this.addCommand({ id: "livesync-replicate", @@ -204,7 +211,6 @@ export default class ObsidianLiveSyncPlugin extends Plugin { id: "livesync-dump", name: "Dump informations of this doc ", editorCallback: (editor: Editor, view: MarkdownView) => { - this.localDatabase.disposeHashCache(); this.localDatabase.getDBEntry(view.file.path, {}, true, false); }, }); @@ -318,7 +324,7 @@ export default class ObsidianLiveSyncPlugin extends Plugin { this.localDatabase.updateInfo = () => { this.refreshStatusText(); }; - await this.localDatabase.initializeDatabase(); + return await this.localDatabase.initializeDatabase(); } async garbageCollect() { @@ -329,6 +335,8 @@ export default class ObsidianLiveSyncPlugin extends Plugin { this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData()); this.settings.workingEncrypt = this.settings.encrypt; this.settings.workingPassphrase = this.settings.passphrase; + // Delete this feature to avoid problems on mobile. + this.settings.disableRequestURI = true; const lsname = "obsidian-live-sync-vaultanddevicename-" + this.app.vault.getName(); if (this.settings.deviceAndVaultName != "") { if (!localStorage.getItem(lsname)) { @@ -422,7 +430,6 @@ export default class ObsidianLiveSyncPlugin extends Plugin { if (this.settings.syncOnFileOpen && !this.suspended) { await this.replicate(); } - this.localDatabase.disposeHashCache(); await this.showIfConflicted(file); this.gcHook(); } @@ -581,7 +588,11 @@ export default class ObsidianLiveSyncPlugin extends Plugin { notifies: { [key: string]: { notice: Notice; timer: NodeJS.Timeout; count: number } } = {}; // eslint-disable-next-line require-await + lastLog = ""; async addLog(message: any, level: LOG_LEVEL = LOG_LEVEL.INFO) { + if (level == LOG_LEVEL.DEBUG && !isDebug) { + return; + } if (level < LOG_LEVEL.INFO && this.settings && this.settings.lessInformationInLog) { return; } @@ -595,6 +606,10 @@ export default class ObsidianLiveSyncPlugin extends Plugin { this.logMessage = [].concat(this.logMessage).concat([newmessage]).slice(-100); console.log(valutName + ":" + newmessage); + this.setStatusBarText(null, messagecontent.substring(0, 30)); + if (message instanceof Error) { + console.trace(message); + } if (level >= LOG_LEVEL.NOTICE) { if (messagecontent in this.notifies) { @@ -814,6 +829,9 @@ export default class ObsidianLiveSyncPlugin extends Plugin { if (change._id.startsWith("h:")) { continue; } + if (change._id == SYNCINFO_ID) { + continue; + } if (change.type != "leaf" && change.type != "versioninfo" && change.type != "milestoneinfo" && change.type != "nodeinfo") { Logger("replication change arrived", LOG_LEVEL.VERBOSE); await this.handleDBChanged(change); @@ -956,22 +974,36 @@ export default class ObsidianLiveSyncPlugin extends Plugin { const procs = getProcessingCounts(); const procsDisp = procs == 0 ? "" : ` ⏳${procs}`; const message = `Sync:${w} ↑${sent} ↓${arrived}${waiting}${procsDisp}`; - this.setStatusBarText(message); + const locks = getLocks(); + const pendingTask = locks.pending.length ? `\nPending:${locks.pending.join(", ")}` : ""; + const runningTask = locks.running.length ? `\nRunning:${locks.running.join(", ")}` : ""; + this.setStatusBarText(message + pendingTask + runningTask); } - setStatusBarText(message: string) { - if (this.lastMessage != message) { - this.statusBar.setText(message); + logHideTimer: NodeJS.Timeout = null; + setStatusBarText(message: string = null, log: string = null) { + if (!this.statusBar) return; + const newMsg = typeof message == "string" ? message : this.lastMessage; + const newLog = typeof log == "string" ? log : this.lastLog; + if (`${this.lastMessage}-${this.lastLog}` != `${newMsg}-${newLog}`) { + this.statusBar.setText(newMsg.split("\n")[0]); + if (this.settings.showStatusOnEditor) { const root = document.documentElement; - root.style.setProperty("--slsmessage", '"' + message + '"'); + root.style.setProperty("--slsmessage", '"' + (newMsg + "\n" + newLog).split("\n").join("\\a ") + '"'); } else { const root = document.documentElement; root.style.setProperty("--slsmessage", '""'); } - this.lastMessage = message; + if (this.logHideTimer != null) { + clearTimeout(this.logHideTimer); + } + this.logHideTimer = setTimeout(() => this.setStatusBarText(null, ""), 3000); + this.lastMessage = newMsg; + this.lastLog = newLog; } } + updateStatusBarText() {} async replicate(showMessage?: boolean) { if (this.settings.versionUpFlash != "") { @@ -986,8 +1018,14 @@ export default class ObsidianLiveSyncPlugin extends Plugin { } async initializeDatabase(showingNotice?: boolean) { - await this.openDatabase(); - await this.syncAllFiles(showingNotice); + if (await this.openDatabase()) { + if (this.localDatabase.isReady) { + await this.syncAllFiles(showingNotice); + } + return true; + } else { + return false; + } } async replicateAllToServer(showingNotice?: boolean) { @@ -1428,6 +1466,9 @@ export default class ObsidianLiveSyncPlugin extends Plugin { async resetLocalDatabase() { await this.localDatabase.resetDatabase(); } + async resetLocalOldDatabase() { + await this.localDatabase.resetLocalOldDatabase(); + } async tryResetRemoteDatabase() { await this.localDatabase.tryResetRemoteDatabase(this.settings); diff --git a/src/utils_couchdb.ts b/src/utils_couchdb.ts index 8b093b0..9a73b08 100644 --- a/src/utils_couchdb.ts +++ b/src/utils_couchdb.ts @@ -1,6 +1,6 @@ import { Logger } from "./lib/src/logger"; -import { LOG_LEVEL, VER, VERSIONINFO_DOCID, EntryVersionInfo, EntryDoc } from "./lib/src/types"; -import { resolveWithIgnoreKnownError } from "./lib/src/utils"; +import { LOG_LEVEL, VER, VERSIONINFO_DOCID, EntryVersionInfo, EntryDoc, RemoteDBSettings, SYNCINFO_ID, SyncInfo } from "./lib/src/types"; +import { enableEncryption, resolveWithIgnoreKnownError } from "./lib/src/utils"; import { PouchDB } from "./pouchdb-browser"; import { requestUrl, RequestUrlParam, RequestUrlResponse } from "obsidian"; @@ -27,7 +27,18 @@ const fetchByAPI = async (request: RequestUrlParam): Promise return ret; }; -export const connectRemoteCouchDB = async (uri: string, auth: { username: string; password: string }, disableRequestURI: boolean): Promise; info: PouchDB.Core.DatabaseInfo }> => { +export const connectRemoteCouchDBWithSetting = (settings: RemoteDBSettings, isMobile: boolean) => + connectRemoteCouchDB( + settings.couchDB_URI + (settings.couchDB_DBNAME == "" ? "" : "/" + settings.couchDB_DBNAME), + { + username: settings.couchDB_USER, + password: settings.couchDB_PASSWORD, + }, + settings.disableRequestURI || isMobile, + settings.encrypt ? settings.passphrase : settings.encrypt + ); + +const connectRemoteCouchDB = async (uri: string, auth: { username: string; password: string }, disableRequestURI: boolean, passphrase: string | boolean): Promise; info: PouchDB.Core.DatabaseInfo }> => { if (!isValidRemoteCouchDBURI(uri)) return "Remote URI is not valid"; let authHeader = ""; if (auth.username && auth.password) { @@ -82,7 +93,7 @@ export const connectRemoteCouchDB = async (uri: string, auth: { username: string } else { last_post_successed = true; } - Logger(`HTTP:${method}${size} to:${localURL} -> ${r.status}`, LOG_LEVEL.VERBOSE); + Logger(`HTTP:${method}${size} to:${localURL} -> ${r.status}`, LOG_LEVEL.DEBUG); return new Response(r.arrayBuffer, { headers: r.headers, @@ -109,7 +120,7 @@ export const connectRemoteCouchDB = async (uri: string, auth: { username: string } else { last_post_successed = true; } - Logger(`HTTP:${method}${size} to:${localURL} -> ${responce.status}`, LOG_LEVEL.VERBOSE); + Logger(`HTTP:${method}${size} to:${localURL} -> ${responce.status}`, LOG_LEVEL.DEBUG); return responce; } catch (ex) { Logger(`HTTP:${method}${size} to:${localURL} -> failed`, LOG_LEVEL.VERBOSE); @@ -124,6 +135,9 @@ export const connectRemoteCouchDB = async (uri: string, auth: { username: string }, }; const db: PouchDB.Database = new PouchDB(uri, conf); + if (passphrase && typeof passphrase === "string") { + enableEncryption(db, passphrase); + } try { const info = await db.info(); return { db: db, info: info }; @@ -179,3 +193,32 @@ export const bumpRemoteVersion = async (db: PouchDB.Database, barrier: number = await db.put(vi); return true; }; + +export const checkSyncInfo = async (db: PouchDB.Database): Promise => { + try { + const syncinfo = (await db.get(SYNCINFO_ID)) as SyncInfo; + console.log(syncinfo); + // if we could decrypt the doc, it must be ok. + return true; + } catch (ex) { + if (ex.status && ex.status == 404) { + const randomStrSrc = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; + const temp = [...Array(30)] + .map((e) => Math.floor(Math.random() * randomStrSrc.length)) + .map((e) => randomStrSrc[e]) + .join(""); + const newSyncInfo: SyncInfo = { + _id: SYNCINFO_ID, + type: "syncinfo", + data: temp, + }; + if (await db.put(newSyncInfo)) { + return true; + } + return false; + } else { + console.dir(ex); + return false; + } + } +}; diff --git a/styles.css b/styles.css index 363b28d..005e065 100644 --- a/styles.css +++ b/styles.css @@ -1,14 +1,14 @@ .added { - color: black; - background-color: white; + color: var(--text-on-accent); + background-color: var(--text-accent); } .normal { - color: lightgray; + color: var(--text-normal); } .deleted { - color: white; - background-color: black; - /* text-decoration: line-through; */ + color: var(--text-on-accent); + background-color: var(--text-muted); + text-decoration: line-through; } .op-scrollable { overflow-y: scroll; @@ -24,6 +24,25 @@ padding: 2px; border-radius: 4px; } +.op-warn::before { + content: "Warning"; + font-weight: bold; + color: salmon; + position: relative; + display: block; +} +.op-warn-info { + border: 1px solid rgb(255, 209, 81); + padding: 2px; + border-radius: 4px; +} +.op-warn-info::before { + content: "Notice"; + font-weight: bold; + color: rgb(255, 209, 81); + position: relative; + display: block; +} .syncstatusbar { -webkit-filter: grayscale(100%); filter: grayscale(100%); @@ -69,6 +88,8 @@ .CodeMirror-wrap::before, .cm-s-obsidian > .cm-editor::before { content: var(--slsmessage); + text-align: right; + white-space: pre-wrap; position: absolute; border-radius: 4px; /* border:1px solid --background-modifier-border; */