@graffiti-garden/implementation-local 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +78 -0
  2. package/dist/database.browser.js +27 -0
  3. package/dist/database.browser.js.map +1 -0
  4. package/dist/database.cjs.js +2 -0
  5. package/dist/database.cjs.js.map +1 -0
  6. package/dist/database.js +2 -0
  7. package/dist/database.js.map +1 -0
  8. package/dist/index.browser.js +32 -0
  9. package/dist/index.browser.js.map +1 -0
  10. package/dist/index.cjs.js +2 -0
  11. package/dist/index.cjs.js.map +1 -0
  12. package/dist/index.js +2 -0
  13. package/dist/index.js.map +1 -0
  14. package/dist/session-manager.browser.js +2 -0
  15. package/dist/session-manager.browser.js.map +1 -0
  16. package/dist/session-manager.cjs.js +2 -0
  17. package/dist/session-manager.cjs.js.map +1 -0
  18. package/dist/session-manager.js +2 -0
  19. package/dist/session-manager.js.map +1 -0
  20. package/dist/src/database.d.ts +57 -0
  21. package/dist/src/database.d.ts.map +1 -0
  22. package/dist/src/index.d.ts +26 -0
  23. package/dist/src/index.d.ts.map +1 -0
  24. package/dist/src/session-manager.d.ts +22 -0
  25. package/dist/src/session-manager.d.ts.map +1 -0
  26. package/dist/src/synchronize.d.ts +25 -0
  27. package/dist/src/synchronize.d.ts.map +1 -0
  28. package/dist/src/tests.spec.d.ts +2 -0
  29. package/dist/src/tests.spec.d.ts.map +1 -0
  30. package/dist/src/utilities.d.ts +15 -0
  31. package/dist/src/utilities.d.ts.map +1 -0
  32. package/dist/synchronize.browser.js +18 -0
  33. package/dist/synchronize.browser.js.map +1 -0
  34. package/dist/synchronize.cjs.js +2 -0
  35. package/dist/synchronize.cjs.js.map +1 -0
  36. package/dist/synchronize.js +2 -0
  37. package/dist/synchronize.js.map +1 -0
  38. package/dist/utilities.browser.js +2 -0
  39. package/dist/utilities.browser.js.map +1 -0
  40. package/dist/utilities.cjs.js +2 -0
  41. package/dist/utilities.cjs.js.map +1 -0
  42. package/dist/utilities.js +2 -0
  43. package/dist/utilities.js.map +1 -0
  44. package/package.json +110 -0
  45. package/src/database.ts +450 -0
  46. package/src/index.ts +58 -0
  47. package/src/session-manager.ts +122 -0
  48. package/src/synchronize.ts +154 -0
  49. package/src/tests.spec.ts +16 -0
  50. package/src/utilities.ts +128 -0
@@ -0,0 +1,2 @@
1
+ "use strict";var t=require("@graffiti-garden/api"),e=require("ajv-draft-04"),n=require("pouchdb"),o=require("@repeaterjs/repeater"),i=require("fast-json-patch");class s{sessionEvents=new EventTarget;constructor(){(async()=>{await Promise.resolve();for(const t of this.getLoggedInActors()){const e=new CustomEvent("login",{detail:{session:{actor:t}}});this.sessionEvents.dispatchEvent(e)}const t=new CustomEvent("initialized");this.sessionEvents.dispatchEvent(t)})()}loggedInActors=[];getLoggedInActors(){if("undefined"!=typeof window){const t=window.localStorage.getItem("graffiti-actor");return t?t.split(",").map(decodeURIComponent):[]}return this.loggedInActors}setLoggedInActors(t){"undefined"!=typeof window?window.localStorage.setItem("graffiti-actor",t.map(encodeURIComponent).join(",")):this.loggedInActors=t}login=async t=>{let e,n=t?.actor;if(!n&&"undefined"!=typeof window){const t=window.prompt("This is an insecure implementation of the Graffiti API for *demo purposes only*. Do not store any sensitive information here. \n\n Simply choose a username to log in.");t&&(n=t)}if(n){const t=this.getLoggedInActors();t.includes(n)||this.setLoggedInActors([...t,n]),e={session:{actor:n}}}else e={error:new Error("No actor ID provided to login")};const o=new CustomEvent("login",{detail:e});this.sessionEvents.dispatchEvent(o)};logout=async t=>{const e=this.getLoggedInActors(),n=e.includes(t.actor);n&&this.setLoggedInActors(e.filter((e=>e!==t.actor)));const o=n?{actor:t.actor}:{actor:t.actor,error:new Error("Not logged in with that actor")},i=new CustomEvent("logout",{detail:o});this.sessionEvents.dispatchEvent(i)}}const r=t=>`${t.source}/${encodeURIComponent(t.actor)}/${encodeURIComponent(t.name)}`,a=e=>{const n=e.split("/"),o=n.pop(),i=n.pop();if(!o||!i||!n.length)throw new t.GraffitiErrorInvalidUri;return{name:decodeURIComponent(o),actor:decodeURIComponent(i),source:n.join("/")}};function c(t=16){const e=new Uint8Array(t);crypto.getRandomValues(e);return btoa(String.fromCodePoint(...e)).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=+$/,"")}function d(t){return"string"==typeof t?{location:a(t),uri:t}:{location:{name:t.name,actor:t.actor,source:t.source},uri:r(t)}}function l(e,n,o,i){const s=o[n];if(s&&s.length)try{i[n]=e(i[n],s,!0,!1).newDocument}catch(e){throw"object"==typeof e&&e&&"name"in e&&"string"==typeof e.name&&"message"in e&&"string"==typeof e.message?"TEST_OPERATION_FAILED"===e.name?new t.GraffitiErrorPatchTestFailed(e.message):new t.GraffitiErrorPatchError(e.name+": "+e.message):e}}function h(e,n){try{return e.compile(n)}catch(e){throw new t.GraffitiErrorInvalidSchema(e instanceof Error?e.message:void 0)}}function f(t,e,n){t.actor!==n?.actor&&(t.allowed=t.allowed&&n?[n.actor]:void 0,t.channels=t.channels.filter((t=>e.includes(t))))}function u(t,e){return void 0===t.allowed||!!e?.actor&&(t.actor===e.actor||t.allowed.includes(e.actor))}class w{db;source="local";tombstoneRetention=864e5;ajv;constructor(t,o){this.ajv=o??new e({strict:!1}),this.source=t?.sourceName??this.source,this.tombstoneRetention=t?.tombstoneRetention??this.tombstoneRetention;const i={name:"graffitiDb",...t?.pouchDBOptions};this.db=new n(i.name,i),this.db.put({_id:"_design/index3",views:{byChannelAndLastModified:{map:function(t){const e=t.lastModified.toString().padStart(15,"0");t.channels.forEach((function(t){const n=encodeURIComponent(t)+"/"+e;emit(n)}))}.toString()}}}).catch((t=>{if(!t||"object"!=typeof t||!("name"in t)||"conflict"!==t.name)throw t}))}async queryByLocation(t){const e=r(t)+"/";return(await this.db.allDocs({startkey:e,endkey:e+"￿",include_docs:!0})).rows.map((t=>t.doc)).reduce(((t,e)=>(e&&t.push(e),t)),[]).filter((t=>!t.tombstone))}docId(t){return r(t)+"/"+c()}get=async(...e)=>{const[n,o,i]=e,{location:s}=d(n),r=await this.queryByLocation(s);if(!r.length)throw new t.GraffitiErrorNotFound;const a=r.reduce(((t,e)=>t.lastModified>e.lastModified?t:e)),{_id:c,_rev:l,...w}=a;if(!u(a,i))throw new t.GraffitiErrorNotFound;f(w,[],i);if(!h(this.ajv,o)(w))throw new t.GraffitiErrorSchemaMismatch;return w};async deleteAtLocation(t,e=!1){const n=await this.queryByLocation(t);if(!n.length)return;const o=n.map((t=>t.lastModified)).reduce(((t,e)=>t>e?t:e)),i=n.filter((t=>!e||t.lastModified<o)),s=n.filter((t=>e&&t.lastModified===o));if(s.length){const t=s.map((t=>t._id)).reduce(((t,e)=>t>e?t:e)),e=s.filter((e=>e._id!==t));i.push(...e)}const r=e?o:(new Date).getTime();let a;for(const t of i.sort(((t,e)=>t.lastModified-e.lastModified))){const e={...t,tombstone:!0,lastModified:r};try{await this.db.put(e)}catch(t){if(t&&"object"==typeof t&&"name"in t&&"conflict"===t.name)continue}const{_id:n,_rev:o,...i}=e;a=i}return a}delete=async(...e)=>{const[n,o]=e,{location:i}=d(n);if(i.actor!==o.actor)throw new t.GraffitiErrorForbidden;const s=await this.deleteAtLocation(i);if(!s)throw new t.GraffitiErrorNotFound;return s};put=async(...e)=>{const[n,o]=e;if(n.actor&&n.actor!==o.actor)throw new t.GraffitiErrorForbidden;const i={value:n.value,channels:n.channels,allowed:n.allowed,name:n.name??c(),source:n.source??this.source,actor:o.actor,tombstone:!1,lastModified:(new Date).getTime()};await this.db.put({_id:this.docId(i),...i});const s=await this.deleteAtLocation(i,!0);return s||{...i,value:{},channels:[],allowed:void 0,tombstone:!0}};patch=async(...e)=>{const[n,o,s]=e,{location:r}=d(o);if(r.actor!==s.actor)throw new t.GraffitiErrorForbidden;const a=await this.get(o,{},s),c={...a};for(const t of["value","channels","allowed"])l(i.applyPatch,t,n,c);if("object"!=typeof c.value||Array.isArray(c.value)||!c.value)throw new t.GraffitiErrorPatchError("value is no longer an object");if(!Array.isArray(c.channels)||!c.channels.every((t=>"string"==typeof t)))throw new t.GraffitiErrorPatchError("channels are no longer an array of strings");if(c.allowed&&(!Array.isArray(c.allowed)||!c.allowed.every((t=>"string"==typeof t))))throw new t.GraffitiErrorPatchError("allowed list is not an array of strings");return c.lastModified=(new Date).getTime(),await this.db.put({...c,_id:this.docId(c)}),await this.deleteAtLocation(c,!0),{...a,tombstone:!0,lastModified:c.lastModified}};discover=(...t)=>{const[e,n,i]=t,s=h(this.ajv,n);let r="",a="￿";const c=n.properties?.lastModified;if(c?.minimum){let t=Math.ceil(c.minimum);t===c.minimum&&c.exclusiveMinimum&&t++,r=t.toString().padStart(15,"0")}if(c?.maximum){let t=Math.floor(c.maximum);t===c.maximum&&c.exclusiveMaximum&&t--,a=t.toString().padStart(15,"0")}return new o.Repeater((async(t,n)=>{const o=new Set;for(const n of e){const c=encodeURIComponent(n),d=c+"/"+r,l=c+"/"+a,h=await this.db.query("index3/byChannelAndLastModified",{startkey:d,endkey:l,include_docs:!0});for(const n of h.rows){const r=n.doc;if(!r)continue;const{_id:a,_rev:c,...d}=r;o.has(a)||(o.add(a),u(r,i)&&(f(d,e,i),s(d)&&t({value:d})))}}return n(),{tombstoneRetention:this.tombstoneRetention}}))};listChannels=(...t)=>async function*(){}();listOrphans=(...t)=>async function*(){}()}class m{synchronizeEvents=new EventTarget;ajv;graffiti;constructor(t,n){this.ajv=n??new e({strict:!1}),this.graffiti=t}synchronizeDispatch(t,e){const n=new CustomEvent("change",{detail:{oldObject:t,newObject:e}});this.synchronizeEvents.dispatchEvent(n)}get=async(...t)=>{const e=await this.graffiti.get(...t);return this.synchronizeDispatch(e),e};put=async(...t)=>{const e=await this.graffiti.put(...t),n=t[0],o={...e,value:n.value,channels:n.channels,allowed:n.allowed,tombstone:!1};return this.synchronizeDispatch(e,o),e};patch=async(...t)=>{const e=await this.graffiti.patch(...t),n={...e};n.tombstone=!1;for(const e of["value","channels","allowed"])l(i.applyPatch,e,t[0],n);return this.synchronizeDispatch(e,n),e};delete=async(...t)=>{const e=await this.graffiti.delete(...t);return this.synchronizeDispatch(e),e};discover=(...t)=>{const e=this.graffiti.discover(...t),n=this.synchronizeDispatch.bind(this);return async function*(){let t=await e.next();for(;!t.done;)t.value.error||n(t.value.value),yield t.value,t=await e.next();return t.value}()};synchronize=(...t)=>{const[e,n,i]=t,s=h(this.ajv,n);return new o.Repeater((async(t,n)=>{const o=n=>{const{oldObject:o,newObject:r}=n.detail;for(const n of[r,o])if(n&&n.channels.some((t=>e.includes(t)))&&u(n,i)){const o={...n};if(f(o,e,i),s(o)){t({value:o});break}}};this.synchronizeEvents.addEventListener("change",o),await n,this.synchronizeEvents.removeEventListener("change",o)}))}}class g extends t.Graffiti{locationToUri=r;uriToLocation=a;login;logout;sessionEvents;put;get;patch;delete;discover;synchronize;listChannels;listOrphans;constructor(t){super();const n=new s;this.login=n.login.bind(n),this.logout=n.logout.bind(n),this.sessionEvents=n.sessionEvents;const o=new e({strict:!1}),i=new w(t,o),r=new m(i,o);this.put=r.put.bind(r),this.get=r.get.bind(r),this.patch=r.patch.bind(r),this.delete=r.delete.bind(r),this.discover=r.discover.bind(r),this.synchronize=r.synchronize.bind(r),this.listChannels=i.listChannels.bind(i),this.listOrphans=i.listOrphans.bind(i)}}exports.GraffitiLocal=g;
2
+ //# sourceMappingURL=index.cjs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs.js","sources":[],"sourcesContent":[],"names":[],"mappings":""}
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ import{GraffitiErrorInvalidUri as e,GraffitiErrorPatchTestFailed as t,GraffitiErrorPatchError as n,GraffitiErrorInvalidSchema as r,GraffitiErrorNotFound as i,GraffitiErrorSchemaMismatch as o,GraffitiErrorForbidden as s,Graffiti as a}from"@graffiti-garden/api";import c from"ajv-draft-04";import{Repeater as u}from"@repeaterjs/repeater";import{applyPatch as f}from"fast-json-patch";class l{sessionEvents=new EventTarget;constructor(){(async()=>{await Promise.resolve();for(const e of this.getLoggedInActors()){const t=new CustomEvent("login",{detail:{session:{actor:e}}});this.sessionEvents.dispatchEvent(t)}const e=new CustomEvent("initialized");this.sessionEvents.dispatchEvent(e)})()}loggedInActors=[];getLoggedInActors(){if("undefined"!=typeof window){const e=window.localStorage.getItem("graffiti-actor");return e?e.split(",").map(decodeURIComponent):[]}return this.loggedInActors}setLoggedInActors(e){"undefined"!=typeof window?window.localStorage.setItem("graffiti-actor",e.map(encodeURIComponent).join(",")):this.loggedInActors=e}login=async e=>{let t,n=e?.actor;if(!n&&"undefined"!=typeof window){const e=window.prompt("This is an insecure implementation of the Graffiti API for *demo purposes only*. Do not store any sensitive information here. \n\n Simply choose a username to log in.");e&&(n=e)}if(n){const e=this.getLoggedInActors();e.includes(n)||this.setLoggedInActors([...e,n]),t={session:{actor:n}}}else t={error:new Error("No actor ID provided to login")};const r=new CustomEvent("login",{detail:t});this.sessionEvents.dispatchEvent(r)};logout=async e=>{const t=this.getLoggedInActors(),n=t.includes(e.actor);n&&this.setLoggedInActors(t.filter((t=>t!==e.actor)));const r=n?{actor:e.actor}:{actor:e.actor,error:new Error("Not logged in with that actor")},i=new CustomEvent("logout",{detail:r});this.sessionEvents.dispatchEvent(i)}}var d="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{};function h(){throw new Error("setTimeout has not been defined")}function p(){throw new Error("clearTimeout has not been defined")}var v=h,g=p;function _(e){if(v===setTimeout)return setTimeout(e,0);if((v===h||!v)&&setTimeout)return v=setTimeout,setTimeout(e,0);try{return v(e,0)}catch(t){try{return v.call(null,e,0)}catch(t){return v.call(this,e,0)}}}"function"==typeof d.setTimeout&&(v=setTimeout),"function"==typeof d.clearTimeout&&(g=clearTimeout);var m,y=[],w=!1,b=-1;function k(){w&&m&&(w=!1,m.length?y=m.concat(y):b=-1,y.length&&j())}function j(){if(!w){var e=_(k);w=!0;for(var t=y.length;t;){for(m=y,y=[];++b<t;)m&&m[b].run();b=-1,t=y.length}m=null,w=!1,function(e){if(g===clearTimeout)return clearTimeout(e);if((g===p||!g)&&clearTimeout)return g=clearTimeout,clearTimeout(e);try{return g(e)}catch(t){try{return g.call(null,e)}catch(t){return g.call(this,e)}}}(e)}}function q(e,t){this.fun=e,this.array=t}q.prototype.run=function(){this.fun.apply(null,this.array)};function A(){}var O=A,S=A,x=A,E=A,C=A,I=A,L=A;var D=d.performance||{},$=D.now||D.mozNow||D.msNow||D.oNow||D.webkitNow||function(){return(new Date).getTime()};var P=new Date;var T={nextTick:function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];y.push(new q(e,t)),1!==y.length||w||_(j)},title:"browser",browser:!0,env:{},argv:[],version:"",versions:{},on:O,addListener:S,once:x,off:E,removeListener:C,removeAllListeners:I,emit:L,binding:function(e){throw new Error("process.binding is not supported")},cwd:function(){return"/"},chdir:function(e){throw new Error("process.chdir is not supported")},umask:function(){return 0},hrtime:function(e){var t=.001*$.call(D),n=Math.floor(t),r=Math.floor(t%1*1e9);return e&&(n-=e[0],(r-=e[1])<0&&(n--,r+=1e9)),[n,r]},platform:"browser",release:{},config:{},uptime:function(){return(new Date-P)/1e3}};function B(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var R,M={exports:{}};var N,U=(R||(R=1,M.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,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(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<i;t+=1)o[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*u).toString(16).match(/(.*?)(.{0,8})$/),a=parseInt(s[2],16),c=parseInt(s[1],16)||0,o[14]=a,o[15]=c,n(f,o),f}function s(e){var t,r,o,s,a,c,u=e.length,f=[1732584193,-271733879,-1732584194,271733878];for(t=64;t<=u;t+=64)n(f,i(e.subarray(t-64,t)));for(r=(e=t-64<u?e.subarray(t-64):new Uint8Array(0)).length,o=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],t=0;t<r;t+=1)o[t>>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*u).toString(16).match(/(.*?)(.{0,8})$/),a=parseInt(s[2],16),c=parseInt(s[1],16)||0,o[14]=a,o[15]=c,n(f,o),f}function a(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 c(e){var t;for(t=0;t<e.length;t+=1)e[t]=a(e[t]);return e.join("")}function u(e){return/[\u0080-\uFFFF]/.test(e)&&(e=unescape(encodeURIComponent(e))),e}function f(e,t){var n,r=e.length,i=new ArrayBuffer(r),o=new Uint8Array(i);for(n=0;n<r;n+=1)o[n]=e.charCodeAt(n);return t?o:i}function l(e){return String.fromCharCode.apply(null,new Uint8Array(e))}function d(e,t,n){var r=new Uint8Array(e.byteLength+t.byteLength);return r.set(new Uint8Array(e)),r.set(new Uint8Array(t),e.byteLength),r}function h(e){var t,n=[],r=e.length;for(t=0;t<r-1;t+=2)n.push(parseInt(e.substr(t,2),16));return String.fromCharCode.apply(String,n)}function p(){this.reset()}return c(o("hello")),"undefined"==typeof ArrayBuffer||ArrayBuffer.prototype.slice||function(){function t(e,t){return(e=0|e||0)<0?Math.max(e+t,0):Math.min(e,t)}ArrayBuffer.prototype.slice=function(n,r){var i,o,s,a,c=this.byteLength,u=t(n,c),f=c;return r!==e&&(f=t(r,c)),u>f?new ArrayBuffer(0):(i=f-u,o=new ArrayBuffer(i),s=new Uint8Array(o),a=new Uint8Array(this,u,i),s.set(a),o)}}(),p.prototype.append=function(e){return this.appendBinary(u(e)),this},p.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},p.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<i;t+=1)o[t>>2]|=r.charCodeAt(t)<<(t%4<<3);return this._finish(o,i),n=c(this._hash),e&&(n=h(n)),this.reset(),n},p.prototype.reset=function(){return this._buff="",this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},p.prototype.getState=function(){return{buff:this._buff,length:this._length,hash:this._hash.slice()}},p.prototype.setState=function(e){return this._buff=e.buff,this._length=e.length,this._hash=e.hash,this},p.prototype.destroy=function(){delete this._hash,delete this._buff,delete this._length},p.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)},p.hash=function(e,t){return p.hashBinary(u(e),t)},p.hashBinary=function(e,t){var n=c(o(e));return t?h(n):n},p.ArrayBuffer=function(){this.reset()},p.ArrayBuffer.prototype.append=function(e){var t,r=d(this._buff.buffer,e),o=r.length;for(this._length+=e.byteLength,t=64;t<=o;t+=64)n(this._hash,i(r.subarray(t-64,t)));return this._buff=t-64<o?new Uint8Array(r.buffer.slice(t-64)):new Uint8Array(0),this},p.ArrayBuffer.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<i;t+=1)o[t>>2]|=r[t]<<(t%4<<3);return this._finish(o,i),n=c(this._hash),e&&(n=h(n)),this.reset(),n},p.ArrayBuffer.prototype.reset=function(){return this._buff=new Uint8Array(0),this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},p.ArrayBuffer.prototype.getState=function(){var e=p.prototype.getState.call(this);return e.buff=l(e.buff),e},p.ArrayBuffer.prototype.setState=function(e){return e.buff=f(e.buff,!0),p.prototype.setState.call(this,e)},p.ArrayBuffer.prototype.destroy=p.prototype.destroy,p.ArrayBuffer.prototype._finish=p.prototype._finish,p.ArrayBuffer.hash=function(e,t){var n=c(s(new Uint8Array(e)));return t?h(n):n},p}()),M.exports),z=B(U),F=new Uint8Array(16);function K(){if(!N&&!(N="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 N(F)}var J=/^(?:[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;for(var V=[],G=0;G<256;++G)V.push((G+256).toString(16).substr(1));function Q(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=(V[e[t+0]]+V[e[t+1]]+V[e[t+2]]+V[e[t+3]]+"-"+V[e[t+4]]+V[e[t+5]]+"-"+V[e[t+6]]+V[e[t+7]]+"-"+V[e[t+8]]+V[e[t+9]]+"-"+V[e[t+10]]+V[e[t+11]]+V[e[t+12]]+V[e[t+13]]+V[e[t+14]]+V[e[t+15]]).toLowerCase();if(!function(e){return"string"==typeof e&&J.test(e)}(n))throw TypeError("Stringified UUID is invalid");return n}function W(e,t,n){var r=(e=e||{}).random||(e.rng||K)();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 Q(r)}var Y,H={};var X=function(){if(Y)return H;function e(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;if(Array.isArray(i))i.push(e);else if(o===t.length-2){i[t.pop()]=e}else t.push(e)}return Y=1,H.stringify=function(e){var t=[];t.push({obj:e});for(var n,r,i,o,s,a,c,u,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(c in a=[],r)r.hasOwnProperty(c)&&a.push(c);for(t.push({val:"}"}),o=a.length-1;o>=0;o--)f=r[u=a[o]],l=o>0?",":"",l+=JSON.stringify(u)+":",t.push({obj:f,prefix:l});t.push({val:"{"})}return d},H.parse=function(t){for(var n,r,i,o,s,a,c,u,f,l=[],d=[],h=0;;)if("}"!==(n=t[h++])&&"]"!==n&&void 0!==n)switch(n){case" ":case"\t":case"\n":case":":case",":break;case"n":h+=3,e(null,l,d);break;case"t":h+=3,e(!0,l,d);break;case"f":h+=4,e(!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=t[h++],!/[\d\.\-e\+]/.test(i)){h--;break}r+=i}e(parseFloat(r),l,d);break;case'"':for(o="",s=void 0,a=0;'"'!==(c=t[h++])||"\\"===s&&a%2==1;)o+=c,"\\"===(s=c)?a++:a=0;e(JSON.parse('"'+o+'"'),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: "+n)}else{if(1===l.length)return l.pop();e(l.pop(),l,d)}},H}(),Z=B(X);function ee(){}function te(){te.init.call(this)}function ne(e){return void 0===e._maxListeners?te.defaultMaxListeners:e._maxListeners}function re(e,t,n,r){var i,o,s,a;if("function"!=typeof n)throw new TypeError('"listener" argument must be a function');if((o=e._events)?(o.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),o=e._events),s=o[t]):(o=e._events=new ee,e._eventsCount=0),s){if("function"==typeof s?s=o[t]=r?[n,s]:[s,n]:r?s.unshift(n):s.push(n),!s.warned&&(i=ne(e))&&i>0&&s.length>i){s.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+t+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=s.length,a=c,"function"==typeof console.warn?console.warn(a):console.log(a)}}else s=o[t]=n,++e._eventsCount;return e}function ie(e,t,n){var r=!1;function i(){e.removeListener(t,i),r||(r=!0,n.apply(e,arguments))}return i.listener=n,i}function oe(e){var t=this._events;if(t){var n=t[e];if("function"==typeof n)return 1;if(n)return n.length}return 0}function se(e,t){for(var n=new Array(t);t--;)n[t]=e[t];return n}ee.prototype=Object.create(null),te.EventEmitter=te,te.usingDomains=!1,te.prototype.domain=void 0,te.prototype._events=void 0,te.prototype._maxListeners=void 0,te.defaultMaxListeners=10,te.init=function(){this.domain=null,te.usingDomains&&undefined.active,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new ee,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},te.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},te.prototype.getMaxListeners=function(){return ne(this)},te.prototype.emit=function(e){var t,n,r,i,o,s,a,c="error"===e;if(s=this._events)c=c&&null==s.error;else if(!c)return!1;if(a=this.domain,c){if(t=arguments[1],!a){if(t instanceof Error)throw t;var u=new Error('Uncaught, unspecified "error" event. ('+t+")");throw u.context=t,u}return t||(t=new Error('Uncaught, unspecified "error" event')),t.domainEmitter=this,t.domain=a,t.domainThrown=!1,a.emit("error",t),!1}if(!(n=s[e]))return!1;var f="function"==typeof n;switch(r=arguments.length){case 1:!function(e,t,n){if(t)e.call(n);else for(var r=e.length,i=se(e,r),o=0;o<r;++o)i[o].call(n)}(n,f,this);break;case 2:!function(e,t,n,r){if(t)e.call(n,r);else for(var i=e.length,o=se(e,i),s=0;s<i;++s)o[s].call(n,r)}(n,f,this,arguments[1]);break;case 3:!function(e,t,n,r,i){if(t)e.call(n,r,i);else for(var o=e.length,s=se(e,o),a=0;a<o;++a)s[a].call(n,r,i)}(n,f,this,arguments[1],arguments[2]);break;case 4:!function(e,t,n,r,i,o){if(t)e.call(n,r,i,o);else for(var s=e.length,a=se(e,s),c=0;c<s;++c)a[c].call(n,r,i,o)}(n,f,this,arguments[1],arguments[2],arguments[3]);break;default:for(i=new Array(r-1),o=1;o<r;o++)i[o-1]=arguments[o];!function(e,t,n,r){if(t)e.apply(n,r);else for(var i=e.length,o=se(e,i),s=0;s<i;++s)o[s].apply(n,r)}(n,f,this,i)}return!0},te.prototype.addListener=function(e,t){return re(this,e,t,!1)},te.prototype.on=te.prototype.addListener,te.prototype.prependListener=function(e,t){return re(this,e,t,!0)},te.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,ie(this,e,t)),this},te.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,ie(this,e,t)),this},te.prototype.removeListener=function(e,t){var n,r,i,o,s;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(r=this._events))return this;if(!(n=r[e]))return this;if(n===t||n.listener&&n.listener===t)0==--this._eventsCount?this._events=new ee:(delete r[e],r.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(i=-1,o=n.length;o-- >0;)if(n[o]===t||n[o].listener&&n[o].listener===t){s=n[o].listener,i=o;break}if(i<0)return this;if(1===n.length){if(n[0]=void 0,0==--this._eventsCount)return this._events=new ee,this;delete r[e]}else!function(e,t){for(var n=t,r=n+1,i=e.length;r<i;n+=1,r+=1)e[n]=e[r];e.pop()}(n,i);r.removeListener&&this.emit("removeListener",e,s||t)}return this},te.prototype.removeAllListeners=function(e){var t,n;if(!(n=this._events))return this;if(!n.removeListener)return 0===arguments.length?(this._events=new ee,this._eventsCount=0):n[e]&&(0==--this._eventsCount?this._events=new ee:delete n[e]),this;if(0===arguments.length){for(var r,i=Object.keys(n),o=0;o<i.length;++o)"removeListener"!==(r=i[o])&&this.removeAllListeners(r);return this.removeAllListeners("removeListener"),this._events=new ee,this._eventsCount=0,this}if("function"==typeof(t=n[e]))this.removeListener(e,t);else if(t)do{this.removeListener(e,t[t.length-1])}while(t[0]);return this},te.prototype.listeners=function(e){var t,n,r=this._events;return n=r&&(t=r[e])?"function"==typeof t?[t.listener||t]:function(e){for(var t=new Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}(t):[],n},te.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):oe.call(e,t)},te.prototype.listenerCount=oe,te.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};var ae=Function.prototype.toString,ce=ae.call(Object);function ue(e){var t,n,r;if(!e||"object"!=typeof e)return e;if(Array.isArray(e)){for(t=[],n=0,r=e.length;n<r;n++)t[n]=ue(e[n]);return t}if(e instanceof Date&&isFinite(e))return e.toISOString();if(function(e){return"undefined"!=typeof ArrayBuffer&&e instanceof ArrayBuffer||"undefined"!=typeof Blob&&e instanceof Blob}(e))return function(e){return e instanceof ArrayBuffer?e.slice(0):e.slice(0,e.size,e.type)}(e);if(!function(e){var t=Object.getPrototypeOf(e);if(null===t)return!0;var n=t.constructor;return"function"==typeof n&&n instanceof n&&ae.call(n)==ce}(e))return e;for(n in t={},e)if(Object.prototype.hasOwnProperty.call(e,n)){var i=ue(e[n]);void 0!==i&&(t[n]=i)}return t}function fe(e){var t=!1;return function(...n){if(t)throw new Error("once called more than once");t=!0,e.apply(this,n)}}function le(e){return function(...t){t=ue(t);var n=this,r="function"==typeof t[t.length-1]&&t.pop(),i=new Promise((function(r,i){var o;try{var s=fe((function(e,t){e?i(e):r(t)}));t.push(s),(o=e.apply(n,t))&&"function"==typeof o.then&&r(o)}catch(e){i(e)}}));return r&&i.then((function(e){r(null,e)}),r),i}}function de(e,t){return le((function(...n){if(this._closed)return Promise.reject(new Error("database is closed"));if(this._destroyed)return Promise.reject(new Error("database is destroyed"));var r=this;return function(e,t,n){if(e.constructor.listeners("debug").length){for(var r=["api",e.name,t],i=0;i<n.length-1;i++)r.push(n[i]);e.constructor.emit("debug",r);var o=n[n.length-1];n[n.length-1]=function(n,r){var i=["api",e.name,t];i=i.concat(n?["error",n]:["success",r]),e.constructor.emit("debug",i),o(n,r)}}}(r,e,n),this.taskqueue.isReady?t.apply(this,n):new Promise((function(t,i){r.taskqueue.addTask((function(o){o?i(o):t(r[e].apply(r,n))}))}))}))}function he(e,t){for(var n={},r=0,i=t.length;r<i;r++){var o=t[r];o in e&&(n[o]=e[o])}return n}var pe;function ve(e){return e}function ge(e){return[{ok:e}]}function _e(e,t,n){var r=t.docs,i=new Map;r.forEach((function(e){i.has(e.id)?i.get(e.id).push(e):i.set(e.id,[e])}));var o=i.size,s=0,a=new Array(o);function c(){var e;++s===o&&(e=[],a.forEach((function(t){t.docs.forEach((function(n){e.push({id:t.id,docs:[n]})}))})),n(null,{results:e}))}var u=[];i.forEach((function(e,t){u.push(t)}));var f=0;function l(){if(!(f>=u.length)){var n=Math.min(f+6,u.length),r=u.slice(f,n);!function(n,r){n.forEach((function(n,o){var s=r+o,u=i.get(n),f=he(u[0],["atts_since","attachments"]);f.open_revs=u.map((function(e){return e.rev})),f.open_revs=f.open_revs.filter(ve);var d=ve;0===f.open_revs.length&&(delete f.open_revs,d=ge),["revs","attachments","binary","ajax","latest"].forEach((function(e){e in t&&(f[e]=t[e])})),e.get(n,f,(function(e,t){var r,i,o;r=e?[{error:e}]:d(t),i=n,o=r,a[s]={id:i,docs:o},c(),l()}))}))}(r,f),f+=r.length}}l()}try{localStorage.setItem("_pouch_check_localstorage",1),pe=!!localStorage.getItem("_pouch_check_localstorage")}catch(e){pe=!1}function me(){return pe}const ye="function"==typeof queueMicrotask?queueMicrotask:function(e){Promise.resolve().then(e)};function we(e){if("undefined"!=typeof console&&"function"==typeof console[e]){var t=Array.prototype.slice.call(arguments,1);console[e].apply(console,t)}}function be(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 ke(e,t){we("info","The above "+e+" is totally normal. "+t)}class je extends Error{constructor(e,t,n){super(),this.status=e,this.name=t,this.message=n,this.error=!0}toString(){return JSON.stringify({status:this.status,name:this.name,message:this.message,reason:this.reason})}}new je(401,"unauthorized","Name or password is incorrect.");var qe=new je(400,"bad_request","Missing JSON list of 'docs'"),Ae=new je(404,"not_found","missing"),Oe=new je(409,"conflict","Document update conflict"),Se=new je(400,"bad_request","_id field must contain a string"),xe=new je(412,"missing_id","_id is required for puts"),Ee=new je(400,"bad_request","Only reserved document ids may start with underscore.");new je(412,"precondition_failed","Database not open");var Ce=new je(500,"unknown_error","Database encountered an unknown error"),Ie=new je(500,"badarg","Some query argument is invalid");new je(400,"invalid_request","Request was invalid");var Le=new je(400,"query_parse_error","Some query parameter is invalid"),De=new je(500,"doc_validation","Bad special document member"),$e=new je(400,"bad_request","Something wrong with the request"),Pe=new je(400,"bad_request","Document must be a JSON object");new je(404,"not_found","Database not found");var Te=new je(500,"indexed_db_went_bad","unknown");new je(500,"web_sql_went_bad","unknown"),new je(500,"levelDB_went_went_bad","unknown"),new je(403,"forbidden","Forbidden by design doc validate_doc_update function");var Be=new je(400,"bad_request","Invalid rev format");new je(412,"file_exists","The database could not be created, the file already exists.");var Re=new je(412,"missing_stub","A pre-existing attachment stub wasn't found");function Me(e,t){function n(t){for(var n=Object.getOwnPropertyNames(e),r=0,i=n.length;r<i;r++)"function"!=typeof e[n[r]]&&(this[n[r]]=e[n[r]]);void 0===this.stack&&(this.stack=(new Error).stack),void 0!==t&&(this.reason=t)}return n.prototype=je.prototype,new n(t)}function Ne(e){if("object"!=typeof e){var t=e;(e=Ce).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}function Ue(e){var t={},n=e.filter&&"function"==typeof e.filter;return t.query=e.query_params,function(r){r.doc||(r.doc={});var i=n&&function(e,t,n){try{return!e(t,n)}catch(e){var r="Filter function threw: "+e.toString();return Me($e,r)}}(e.filter,r.doc,t);if("object"==typeof i)return i;if(i)return!1;if(e.include_docs){if(!e.attachments)for(var o in r.doc._attachments)Object.prototype.hasOwnProperty.call(r.doc._attachments,o)&&(r.doc._attachments[o].stub=!0)}else delete r.doc;return!0}}function ze(e){var t;if(e?"string"!=typeof e?t=Me(Se):/^_/.test(e)&&!/^_(design|local)/.test(e)&&(t=Me(Ee)):t=Me(xe),t)throw t}function Fe(e){return"boolean"==typeof e._remote?e._remote:"function"==typeof e.type&&(we("warn","db.type() is deprecated and will be removed in a future version of PouchDB"),"http"===e.type())}function Ke(e){if(!e)return null;var t=e.split("/");return 2===t.length?t:1===t.length?[e,e]:null}function Je(e){var t=Ke(e);return t?t.join("/"):null}new je(413,"invalid_url","Provided URL is invalid");var Ve=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],Ge="queryKey",Qe=/(?:^|&)([^&=]*)=?([^&]*)/g,We=/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;function Ye(e){for(var t=We.exec(e),n={},r=14;r--;){var i=Ve[r],o=t[r]||"",s=-1!==["user","password"].indexOf(i);n[i]=s?decodeURIComponent(o):o}return n[Ge]={},n[Ve[12]].replace(Qe,(function(e,t,r){t&&(n[Ge][t]=r)})),n}function He(e,t){var n=[],r=[];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(n.push(i),r.push(t[i]));return n.push(e),Function.apply(null,n).apply(null,r)}function Xe(e,t,n){return e.get(t).catch((function(e){if(404!==e.status)throw e;return{}})).then((function(r){var i=r._rev,o=n(r);return o?(o._id=t,o._rev=i,function(e,t,n){return e.put(t).then((function(e){return{updated:!0,rev:e.rev}}),(function(r){if(409!==r.status)throw r;return Xe(e,t._id,n)}))}(e,o,n)):{updated:!1,rev:i}}))}var Ze=function(e){return atob(e)},et=function(e){return btoa(e)};function tt(e,t){e=e||[],t=t||{};try{return new Blob(e,t)}catch(i){if("TypeError"!==i.name)throw i;for(var n=new("undefined"!=typeof BlobBuilder?BlobBuilder:"undefined"!=typeof MSBlobBuilder?MSBlobBuilder:"undefined"!=typeof MozBlobBuilder?MozBlobBuilder:WebKitBlobBuilder),r=0;r<e.length;r+=1)n.append(e[r]);return n.getBlob(t.type)}}function nt(e){for(var t=e.length,n=new ArrayBuffer(t),r=new Uint8Array(n),i=0;i<t;i++)r[i]=e.charCodeAt(i);return n}function rt(e,t){return tt([nt(e)],{type:t})}function it(e,t){return rt(Ze(e),t)}function ot(e,t){var n=new FileReader,r="function"==typeof n.readAsBinaryString;n.onloadend=function(e){var n=e.target.result||"";if(r)return t(n);t(function(e){for(var t="",n=new Uint8Array(e),r=n.byteLength,i=0;i<r;i++)t+=String.fromCharCode(n[i]);return t}(n))},r?n.readAsBinaryString(e):n.readAsArrayBuffer(e)}function st(e,t){ot(e,(function(e){t(e)}))}function at(e,t){st(e,(function(e){t(et(e))}))}var ct=self.setImmediate||self.setTimeout;function ut(e,t,n,r,i){(n>0||r<t.size)&&(t=t.slice(n,r)),function(e,t){var n=new FileReader;n.onloadend=function(e){var n=e.target.result||new ArrayBuffer(0);t(n)},n.readAsArrayBuffer(e)}(t,(function(t){e.append(t),i()}))}function ft(e,t,n,r,i){(n>0||r<t.length)&&(t=t.substring(n,r)),e.appendBinary(t),i()}function lt(e,t){var n="string"==typeof e,r=n?e.length:e.size,i=Math.min(32768,r),o=Math.ceil(r/i),s=0,a=n?new z:new z.ArrayBuffer,c=n?ft:ut;function u(){ct(l)}function f(){var e=function(e){return et(e)}(a.end(!0));t(e),a.destroy()}function l(){var t=s*i,n=t+i;s++,c(a,e,t,n,s<o?u:f)}l()}function dt(e){return z.hash(e)}function ht(e,t){if(!t)return W().replace(/-/g,"").toLowerCase();var n=Object.assign({},e);return delete n._rev_tree,dt(JSON.stringify(n))}var pt=W;function vt(e){for(var t,n,r,i,o=e.rev_tree.slice();i=o.pop();){var s=i.ids,a=s[2],c=i.pos;if(a.length)for(var u=0,f=a.length;u<f;u++)o.push({pos:c+1,ids:a[u]});else{var l=!!s[1].deleted,d=s[0];t&&!(r!==l?r:n!==c?n<c:t<d)||(t=d,n=c,r=l)}}return n+"-"+t}function gt(e,t){for(var n,r=e.slice();n=r.pop();)for(var i=n.pos,o=n.ids,s=o[2],a=t(0===s.length,i,o[0],n.ctx,o[1]),c=0,u=s.length;c<u;c++)r.push({pos:i+1,ids:s[c],ctx:a})}function _t(e,t){return e.pos-t.pos}function mt(e){var t=[];gt(e,(function(e,n,r,i,o){e&&t.push({rev:n+"-"+r,pos:n,opts:o})})),t.sort(_t).reverse();for(var n=0,r=t.length;n<r;n++)delete t[n].pos;return t}function yt(e){for(var t=vt(e),n=mt(e.rev_tree),r=[],i=0,o=n.length;i<o;i++){var s=n[i];s.rev===t||s.opts.deleted||r.push(s.rev)}return r}function wt(e){for(var t,n=[],r=e.slice();t=r.pop();){var i=t.pos,o=t.ids,s=o[0],a=o[1],c=o[2],u=0===c.length,f=t.history?t.history.slice():[];f.push({id:s,opts:a}),u&&n.push({pos:i+1-f.length,ids:f});for(var l=0,d=c.length;l<d;l++)r.push({pos:i+1,ids:c[l],history:f})}return n.reverse()}function bt(e,t){return e.pos-t.pos}function kt(e,t,n){var r=function(e,t,n){for(var r,i=0,o=e.length;i<o;)n(e[r=i+o>>>1],t)<0?i=r+1:o=r;return i}(e,t,n);e.splice(r,0,t)}function jt(e,t){for(var n,r,i=t,o=e.length;i<o;i++){var s=e[i],a=[s.id,s.opts,[]];r?(r[2].push(a),r=a):n=r=a}return n}function qt(e,t){return e[0]<t[0]?-1:1}function At(e,t){for(var n=[{tree1:e,tree2:t}],r=!1;n.length>0;){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;a<s[2].length;a++)if(o[2][0]){for(var c=!1,u=0;u<o[2].length;u++)o[2][u][0]===s[2][a][0]&&(n.push({tree1:o[2][u],tree2:s[2][a]}),c=!0);c||(r="new_branch",kt(o[2],s[2][a],qt))}else r="new_leaf",o[2][0]=s[2][a]}return{conflicts:r,tree:e}}function Ot(e,t,n){var r,i=[],o=!1,s=!1;if(!e.length)return{tree:[t],conflicts:"new_leaf"};for(var a=0,c=e.length;a<c;a++){var u=e[a];if(u.pos===t.pos&&u.ids[0]===t.ids[0])r=At(u.ids,t.ids),i.push({pos:u.pos,ids:r.tree}),o=o||r.conflicts,s=!0;else if(!0!==n){var f=u.pos<t.pos?u:t,l=u.pos<t.pos?t:u,d=l.pos-f.pos,h=[],p=[];for(p.push({ids:f.ids,diff:d,parent:null,parentIdx:null});p.length>0;){var v=p.pop();if(0!==v.diff)for(var g=v.ids[2],_=0,m=g.length;_<m;_++)p.push({ids:g[_],diff:v.diff-1,parent:v.ids,parentIdx:_});else v.ids[0]===l.ids[0]&&h.push(v)}var y=h[0];y?(r=At(y.ids,l.ids),y.parent[2][y.parentIdx]=r.tree,i.push({pos:f.pos,ids:f.ids}),o=o||r.conflicts,s=!0):i.push(u)}else i.push(u)}return s||i.push(t),i.sort(bt),{tree:i,conflicts:o||"internal_node"}}function St(e,t,n){var r=Ot(e,t),i=function(e,t){for(var n,r,i=wt(e),o=0,s=i.length;o<s;o++){var a,c=i[o],u=c.ids;if(u.length>t){n||(n={});var f=u.length-t;a={pos:c.pos+f,ids:jt(u,f)};for(var l=0;l<f;l++){var d=c.pos+l+"-"+u[l].id;n[d]=!0}}else a={pos:c.pos,ids:jt(u,0)};r=r?Ot(r,a,!0).tree:[a]}return n&&gt(r,(function(e,t,r){delete n[t+"-"+r]})),{tree:r,revs:n?Object.keys(n):[]}}(r.tree,n);return{tree:i.tree,stemmedRevs:i.revs,conflicts:r.conflicts}}function xt(e){return e.ids}function Et(e,t){t||(t=vt(e));for(var n,r=t.substring(t.indexOf("-")+1),i=e.rev_tree.map(xt);n=i.pop();){if(n[0]===r)return!!n[1].deleted;i=i.concat(n[2])}}function Ct(e){return"string"==typeof e&&e.startsWith("_local/")}function It(e,t,n){var r=[{rev:e._rev}];"all_docs"===n.style&&(r=mt(t.rev_tree).map((function(e){return{rev:e.rev}})));var i={id:t.id,changes:r,doc:e};return Et(t,e._rev)&&(i.deleted=!0),n.conflicts&&(i.doc._conflicts=yt(t),i.doc._conflicts.length||delete i.doc._conflicts),i}class Lt extends te{constructor(e,t,n){super(),this.db=e;var r=(t=t?ue(t):{}).complete=fe(((t,n)=>{var r,o;t?(o="error",("listenerCount"in(r=this)?r.listenerCount(o):te.listenerCount(r,o))>0&&this.emit("error",t)):this.emit("complete",n),this.removeAllListeners(),e.removeListener("destroyed",i)}));n&&(this.on("complete",(function(e){n(null,e)})),this.on("error",n));const i=()=>{this.cancel()};e.once("destroyed",i),t.onChange=(e,t,n)=>{this.isCancelled||function(e,t,n,r){try{e.emit("change",t,n,r)}catch(e){we("error",'Error in .on("change", function):',e)}}(this,e,t,n)};var o=new Promise((function(e,n){t.complete=function(t,r){t?n(t):e(r)}}));this.once("cancel",(function(){e.removeListener("destroyed",i),t.complete(null,{status:"cancelled"})})),this.then=o.then.bind(o),this.catch=o.catch.bind(o),this.then((function(e){r(null,e)}),r),e.taskqueue.isReady?this.validateChanges(t):e.taskqueue.addTask((e=>{e?t.complete(e):this.isCancelled?this.emit("cancel"):this.validateChanges(t)}))}cancel(){this.isCancelled=!0,this.db.taskqueue.isReady&&this.emit("cancel")}validateChanges(e){var t=e.complete;Kt._changesFilterPlugin?Kt._changesFilterPlugin.validate(e,(n=>{if(n)return t(n);this.doChanges(e)})):this.doChanges(e)}doChanges(e){var t=e.complete;if("live"in(e=ue(e))&&!("continuous"in e)&&(e.continuous=e.live),e.processChange=It,"latest"===e.since&&(e.since="now"),e.since||(e.since=0),"now"!==e.since){if(Kt._changesFilterPlugin){if(Kt._changesFilterPlugin.normalize(e),Kt._changesFilterPlugin.shouldFilter(this,e))return Kt._changesFilterPlugin.filter(this,e)}else["doc_ids","filter","selector","view"].forEach((function(t){t in e&&we("warn",'The "'+t+'" option was passed in to changes/replicate, but pouchdb-changes-filter plugin is not installed, so it was ignored. Please install the plugin to enable filtering.')}));"descending"in e||(e.descending=!1),e.limit=0===e.limit?1:e.limit,e.complete=t;var n=this.db._changes(e);if(n&&"function"==typeof n.cancel){const e=this.cancel;this.cancel=(...t)=>{n.cancel(),e.apply(this,t)}}}else this.db.info().then((n=>{this.isCancelled?t(null,{status:"cancelled"}):(e.since=n.update_seq,this.doChanges(e))}),t)}}function Dt(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 $t(e,t){if(e._id===t._id){return(e._revisions?e._revisions.start:0)-(t._revisions?t._revisions.start:0)}return e._id<t._id?-1:1}function Pt(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),ye((function(){e._compactionQueue.shift(),e._compactionQueue.length&&Pt(e)}))}))}))}function Tt(e,t,n){return e.get("_local/purges").then((function(e){const r=e.purgeSeq+1;return e.purges.push({docId:t,rev:n,purgeSeq:r}),e.purges.length>self.purged_infos_limit&&e.purges.splice(0,e.purges.length-self.purged_infos_limit),e.purgeSeq=r,e})).catch((function(e){if(404!==e.status)throw e;return{_id:"_local/purges",purges:[{docId:t,rev:n,purgeSeq:0}],purgeSeq:0}})).then((function(t){return e.put(t)}))}function Bt(e){return null===e||"object"!=typeof e||Array.isArray(e)}const Rt=/^\d+-[^-]*$/;function Mt(e){return"string"==typeof e&&Rt.test(e)}class Nt extends te{_setup(){this.post=de("post",(function(e,t,n){if("function"==typeof t&&(n=t,t={}),Bt(e))return n(Me(Pe));this.bulkDocs({docs:[e]},t,Dt(n,e._id))})).bind(this),this.put=de("put",(function(e,t,n){if("function"==typeof t&&(n=t,t={}),Bt(e))return n(Me(Pe));if(ze(e._id),"_rev"in e&&!Mt(e._rev))return n(Me(Be));if(Ct(e._id)&&"function"==typeof this._putLocal)return e._deleted?this._removeLocal(e,n):this._putLocal(e,n);const r=n=>{"function"==typeof this._put&&!1!==t.new_edits?this._put(e,t,n):this.bulkDocs({docs:[e]},t,Dt(n,e._id))};var i,o,s,a;t.force&&e._rev?(i=e._rev.split("-"),o=i[1],s=parseInt(i[0],10)+1,a=ht(),e._revisions={start:s,ids:[a,o]},e._rev=s+"-"+a,t.new_edits=!1,r((function(t){var r=t?null:{ok:!0,id:e._id,rev:e._rev};n(t,r)}))):r(n)})).bind(this),this.putAttachment=de("putAttachment",(function(e,t,n,r,i){var o=this;function s(e){var n="_rev"in e?parseInt(e._rev,10):0;return e._attachments=e._attachments||{},e._attachments[t]={content_type:i,data:r,revpos:++n},o.put(e)}return"function"==typeof i&&(i=r,r=n,n=null),void 0===i&&(i=r,r=n,n=null),i||we("warn","Attachment",t,"on document",e,"is missing content_type"),o.get(e).then((function(e){if(e._rev!==n)throw Me(Oe);return s(e)}),(function(t){if(t.reason===Ae.message)return s({_id:e});throw t}))})).bind(this),this.removeAttachment=de("removeAttachment",(function(e,t,n,r){this.get(e,((e,i)=>{if(e)r(e);else if(i._rev===n){if(!i._attachments)return r();delete i._attachments[t],0===Object.keys(i._attachments).length&&delete i._attachments,this.put(i,r)}else r(Me(Oe))}))})).bind(this),this.remove=de("remove",(function(e,t,n,r){var i;"string"==typeof t?(i={_id:e,_rev:t},"function"==typeof n&&(r=n,n={})):(i=e,"function"==typeof t?(r=t,n={}):(r=n,n=t)),(n=n||{}).was_delete=!0;var o={_id:i._id,_rev:i._rev||n.rev,_deleted:!0};if(Ct(o._id)&&"function"==typeof this._removeLocal)return this._removeLocal(i,r);this.bulkDocs({docs:[o]},n,Dt(r,o._id))})).bind(this),this.revsDiff=de("revsDiff",(function(e,t,n){"function"==typeof t&&(n=t,t={});var r=Object.keys(e);if(!r.length)return n(null,{});var i=0,o=new Map;function s(e,t){o.has(e)||o.set(e,{missing:[]}),o.get(e).missing.push(t)}r.forEach((function(t){this._getRevisionTree(t,(function(a,c){if(a&&404===a.status&&"missing"===a.message)o.set(t,{missing:e[t]});else{if(a)return n(a);!function(t,n){var r=e[t].slice(0);gt(n,(function(e,n,i,o,a){var c=n+"-"+i,u=r.indexOf(c);-1!==u&&(r.splice(u,1),"available"!==a.status&&s(t,c))})),r.forEach((function(e){s(t,e)}))}(t,c)}if(++i===r.length){var u={};return o.forEach((function(e,t){u[t]=e})),n(null,u)}}))}),this)})).bind(this),this.bulkGet=de("bulkGet",(function(e,t){_e(this,e,t)})).bind(this),this.compactDocument=de("compactDocument",(function(e,t,n){this._getRevisionTree(e,((r,i)=>{if(r)return n(r);var o=function(e){var t={},n=[];return gt(e,(function(e,r,i,o){var s=r+"-"+i;return e&&(t[s]=0),void 0!==o&&n.push({from:o,to:s}),s})),n.reverse(),n.forEach((function(e){void 0===t[e.from]?t[e.from]=1+t[e.to]:t[e.from]=Math.min(t[e.from],1+t[e.to])})),t}(i),s=[],a=[];Object.keys(o).forEach((function(e){o[e]>t&&s.push(e)})),gt(i,(function(e,t,n,r,i){var o=t+"-"+n;"available"===i.status&&-1!==s.indexOf(o)&&a.push(o)})),this._doCompaction(e,a,n)}))})).bind(this),this.compact=de("compact",(function(e,t){"function"==typeof e&&(t=e,e={}),e=e||{},this._compactionQueue=this._compactionQueue||[],this._compactionQueue.push({opts:e,callback:t}),1===this._compactionQueue.length&&Pt(this)})).bind(this),this.get=de("get",(function(e,t,n){if("function"==typeof t&&(n=t,t={}),t=t||{},"string"!=typeof e)return n(Me(Se));if(Ct(e)&&"function"==typeof this._getLocal)return this._getLocal(e,n);var r=[];const i=()=>{var i=[],o=r.length;if(!o)return n(null,i);r.forEach((r=>{this.get(e,{rev:r,revs:t.revs,latest:t.latest,attachments:t.attachments,binary:t.binary},(function(e,t){if(e)i.push({missing:r});else{for(var s,a=0,c=i.length;a<c;a++)if(i[a].ok&&i[a].ok._rev===t._rev){s=!0;break}s||i.push({ok:t})}--o||n(null,i)}))}))};if(!t.open_revs)return this._get(e,t,((r,i)=>{if(r)return r.docId=e,n(r);var o=i.doc,s=i.metadata,a=i.ctx;if(t.conflicts){var c=yt(s);c.length&&(o._conflicts=c)}if(Et(s,o._rev)&&(o._deleted=!0),t.revs||t.revs_info){for(var u=o._rev.split("-"),f=parseInt(u[0],10),l=u[1],d=wt(s.rev_tree),h=null,p=0;p<d.length;p++){var v=d[p];const e=v.ids.findIndex((e=>e.id===l));(e===f-1||!h&&-1!==e)&&(h=v)}if(!h)return(r=new Error("invalid rev tree")).docId=e,n(r);const i=o._rev.split("-")[1],a=h.ids.findIndex((e=>e.id===i))+1;var g=h.ids.length-a;if(h.ids.splice(a,g),h.ids.reverse(),t.revs&&(o._revisions={start:h.pos+h.ids.length-1,ids:h.ids.map((function(e){return e.id}))}),t.revs_info){var _=h.pos+h.ids.length;o._revs_info=h.ids.map((function(e){return{rev:--_+"-"+e.id,status:e.opts.status}}))}}if(t.attachments&&o._attachments){var m=o._attachments,y=Object.keys(m).length;if(0===y)return n(null,o);Object.keys(m).forEach((e=>{this._getAttachment(o._id,e,m[e],{binary:t.binary,metadata:s,ctx:a},(function(t,r){var i=o._attachments[e];i.data=r,delete i.stub,delete i.length,--y||n(null,o)}))}))}else{if(o._attachments)for(var w in o._attachments)Object.prototype.hasOwnProperty.call(o._attachments,w)&&(o._attachments[w].stub=!0);n(null,o)}}));if("all"===t.open_revs)this._getRevisionTree(e,(function(e,t){if(e)return n(e);r=mt(t).map((function(e){return e.rev})),i()}));else{if(!Array.isArray(t.open_revs))return n(Me(Ce,"function_clause"));r=t.open_revs;for(var o=0;o<r.length;o++){if(!Mt(r[o]))return n(Me(Be))}i()}})).bind(this),this.getAttachment=de("getAttachment",(function(e,t,n,r){n instanceof Function&&(r=n,n={}),this._get(e,n,((i,o)=>i?r(i):o.doc._attachments&&o.doc._attachments[t]?(n.ctx=o.ctx,n.binary=!0,n.metadata=o.metadata,void this._getAttachment(e,t,o.doc._attachments[t],n,r)):r(Me(Ae))))})).bind(this),this.allDocs=de("allDocs",(function(e,t){if("function"==typeof e&&(t=e,e={}),e.skip=void 0!==e.skip?e.skip:0,e.start_key&&(e.startkey=e.start_key),e.end_key&&(e.endkey=e.end_key),"keys"in e){if(!Array.isArray(e.keys))return t(new TypeError("options.keys must be an array"));var n=["startkey","endkey","key"].filter((function(t){return t in e}))[0];if(n)return void t(Me(Le,"Query parameter `"+n+"` is not compatible with multi-get"));if(!Fe(this)&&(function(e){var t="limit"in e?e.keys.slice(e.skip,e.limit+e.skip):e.skip>0?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)})).bind(this),this.close=de("close",(function(e){return this._closed=!0,this.emit("closed"),this._close(e)})).bind(this),this.info=de("info",(function(e){this._info(((t,n)=>{if(t)return e(t);n.db_name=n.db_name||this.name,n.auto_compaction=!(!this.auto_compaction||Fe(this)),n.adapter=this.adapter,e(null,n)}))})).bind(this),this.id=de("id",(function(e){return this._id(e)})).bind(this),this.bulkDocs=de("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(Me(qe));for(var r=0;r<e.docs.length;++r){const t=e.docs[r];if(Bt(t))return n(Me(Pe));if("_rev"in t&&!Mt(t._rev))return n(Me(Be))}var i;if(e.docs.forEach((function(e){e._attachments&&Object.keys(e._attachments).forEach((function(t){i=i||function(e){return"_"===e.charAt(0)&&e+" is not a valid attachment name, attachment names cannot start with '_'"}(t),e._attachments[t].content_type||we("warn","Attachment",t,"on document",e._id,"is missing content_type")}))})),i)return n(Me($e,i));"new_edits"in t||(t.new_edits=!("new_edits"in e)||e.new_edits);var o=this;t.new_edits||Fe(o)||e.docs.sort($t),function(e){for(var t=0;t<e.length;t++){var n=e[t];if(n._deleted)delete n._attachments;else if(n._attachments)for(var r=Object.keys(n._attachments),i=0;i<r.length;i++){var o=r[i];n._attachments[o]=he(n._attachments[o],["data","digest","content_type","length","revpos","stub"])}}}(e.docs);var s=e.docs.map((function(e){return e._id}));this._bulkDocs(e,t,(function(e,r){if(e)return n(e);if(t.new_edits||(r=r.filter((function(e){return e.error}))),!Fe(o))for(var i=0,a=r.length;i<a;i++)r[i].id=r[i].id||s[i];n(null,r)}))})).bind(this),this.registerDependentDatabase=de("registerDependentDatabase",(function(e,t){var n=ue(this.__opts);this.__opts.view_adapter&&(n.adapter=this.__opts.view_adapter);var r=new this.constructor(e,n);Xe(this,"_local/_pouch_dependentDbs",(function(t){return t.dependentDbs=t.dependentDbs||{},!t.dependentDbs[e]&&(t.dependentDbs[e]=!0,t)})).then((function(){t(null,{db:r})})).catch(t)})).bind(this),this.destroy=de("destroy",(function(e,t){"function"==typeof e&&(t=e,e={});var n=!("use_prefix"in this)||this.use_prefix;const r=()=>{this._destroy(e,((e,n)=>{if(e)return t(e);this._destroyed=!0,this.emit("destroyed"),t(null,n||{ok:!0})}))};if(Fe(this))return r();this.get("_local/_pouch_dependentDbs",((e,i)=>{if(e)return 404!==e.status?t(e):r();var o=i.dependentDbs,s=this.constructor,a=Object.keys(o).map((e=>{var t=n?e.replace(new RegExp("^"+s.prefix),""):e;return new s(t,this.__opts).destroy()}));Promise.all(a).then(r,t)}))})).bind(this)}_compact(e,t){var n,r={return_docs:!1,last_seq:e.last_seq||0,since:e.last_seq||0},i=[],o=0;const s=e=>{this.activeTasks.update(n,{completed_items:++o}),i.push(this.compactDocument(e.id,0))},a=e=>{this.activeTasks.remove(n,e),t(e)},c=e=>{var r=e.last_seq;Promise.all(i).then((()=>Xe(this,"_local/compaction",(e=>(!e.last_seq||e.last_seq<r)&&(e.last_seq=r,e))))).then((()=>{this.activeTasks.remove(n),t(null,{ok:!0})})).catch(a)};this.info().then((e=>{n=this.activeTasks.add({name:"database_compaction",total_items:e.update_seq-r.last_seq}),this.changes(r).on("change",s).on("complete",c).on("error",a)}))}changes(e,t){return"function"==typeof e&&(t=e,e={}),(e=e||{}).return_docs="return_docs"in e?e.return_docs:!e.live,new Lt(this,e,t)}type(){return"function"==typeof this._type?this._type():this.adapter}}Nt.prototype.purge=de("_purge",(function(e,t,n){if(void 0===this._purge)return n(Me(Ce,"Purge is not implemented in the "+this.adapter+" adapter."));var r=this;r._getRevisionTree(e,((i,o)=>{if(i)return n(i);if(!o)return n(Me(Ae));let s;try{s=function(e,t){let n=[];const r=e.slice();let i;for(;i=r.pop();){const{pos:e,ids:o}=i,s=`${e}-${o[0]}`,a=o[2];if(n.push(s),s===t){if(0!==a.length)throw new Error("The requested revision is not a leaf");return n.reverse()}(0===a.length||a.length>1)&&(n=[]);for(let t=0,n=a.length;t<n;t++)r.push({pos:e+1,ids:a[t]})}if(0===n.length)throw new Error("The requested revision does not exist");return n.reverse()}(o,t)}catch(i){return n(i.message||i)}r._purge(e,s,((i,o)=>{if(i)return n(i);Tt(r,e,t).then((function(){return n(null,o)}))}))}))}));class Ut{constructor(){this.isReady=!1,this.failed=!1,this.queue=[]}execute(){var e;if(this.failed)for(;e=this.queue.shift();)e(this.failed);else for(;e=this.queue.shift();)e()}fail(e){this.failed=e,this.execute()}ready(e){this.isReady=!0,this.db=e,this.execute()}addTask(e){this.queue.push(e),this.failed&&this.execute()}}function zt(e,t){let n=function(...e){if(!(this instanceof n))return new n(...e);t.apply(this,e)};var r,i;return i=e,(r=n).prototype=Object.create(i.prototype,{constructor:{value:r}}),n}class Ft extends Nt{constructor(e,t){super(),this._setup(e,t)}_setup(e,t){if(super._setup(),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=ue(t),this.auto_compaction=t.auto_compaction,this.purged_infos_limit=t.purged_infos_limit||1e3,this.prefix=Kt.prefix,"string"!=typeof e)throw new Error("Missing/invalid DB name");var n=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=Kt.adapters,i=Kt.preferredAdapters,o=Kt.prefix,s=t.adapter;if(!s)for(var a=0;a<i.length&&"idb"===(s=i[a])&&"websql"in r&&me()&&localStorage["_pouch__websqldb_"+o+e];++a)we("log",'PouchDB is downgrading "'+e+'" to WebSQL to avoid data loss, because it was already opened with WebSQL.');var c=r[s];return{name:c&&"use_prefix"in c&&!c.use_prefix?e:o+e,adapter:s}}((t.prefix||"")+e,t);if(t.name=n.name,t.adapter=t.adapter||n.adapter,this.name=e,this._adapter=t.adapter,Kt.emit("debug",["adapter","Picked adapter: ",t.adapter]),!Kt.adapters[t.adapter]||!Kt.adapters[t.adapter].valid())throw new Error("Invalid Adapter: "+t.adapter);if(t.view_adapter&&(!Kt.adapters[t.view_adapter]||!Kt.adapters[t.view_adapter].valid()))throw new Error("Invalid View Adapter: "+t.view_adapter);this.taskqueue=new Ut,this.adapter=t.adapter,Kt.adapters[t.adapter].call(this,t,(e=>{if(e)return this.taskqueue.fail(e);!function(e){function t(t){e.removeListener("closed",n),t||e.constructor.emit("destroyed",e.name)}function n(){e.removeListener("destroyed",t),e.constructor.emit("unref",e)}e.once("destroyed",t),e.once("closed",n),e.constructor.emit("ref",e)}(this),this.emit("created",this),Kt.emit("created",this.name),this.taskqueue.ready(this)}))}}const Kt=zt(Ft,(function(e,t){Ft.prototype._setup.call(this,e,t)}));var Jt=fetch,Vt=Headers;Kt.adapters={},Kt.preferredAdapters=[],Kt.prefix="_pouch_";var Gt=new te;!function(e){Object.keys(te.prototype).forEach((function(t){"function"==typeof te.prototype[t]&&(e[t]=Gt[t].bind(Gt))}));var t=e._destructionListeners=new Map;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)}))}}))}(Kt),Kt.adapter=function(e,t,n){t.valid()&&(Kt.adapters[e]=t,n&&Kt.preferredAdapters.push(e))},Kt.plugin=function(e){if("function"==typeof e)e(Kt);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){Kt.prototype[t]=e[t]}))}return this.__defaults&&(Kt.__defaults=Object.assign({},this.__defaults)),Kt},Kt.defaults=function(e){let t=zt(Kt,(function(e,n){n=n||{},e&&"object"==typeof e&&(e=(n=e).name,delete n.name),n=Object.assign({},t.__defaults,n),Kt.call(this,e,n)}));return t.preferredAdapters=Kt.preferredAdapters.slice(),Object.keys(Kt).forEach((function(e){e in t||(t[e]=Kt[e])})),t.__defaults=Object.assign({},this.__defaults,e),t},Kt.fetch=function(e,t){return Jt(e,t)},Kt.prototype.activeTasks=Kt.activeTasks=new class{constructor(){this.tasks={}}list(){return Object.values(this.tasks)}add(e){const t=W();return this.tasks[t]={id:t,name:e.name,total_items:e.total_items,created_at:(new Date).toJSON()},t}get(e){return this.tasks[e]}remove(e,t){return delete this.tasks[e],this.tasks}update(e,t){const n=this.tasks[e];if(void 0!==n){const r={id:n.id,name:n.name,created_at:n.created_at,total_items:t.total_items||n.total_items,completed_items:t.completed_items||n.completed_items,updated_at:(new Date).toJSON()};this.tasks[e]=r}return this.tasks}};function Qt(e,t){for(var n=e,r=0,i=t.length;r<i;r++){if(!(n=n[t[r]]))break}return n}function Wt(e){for(var t=[],n="",r=0,i=e.length;r<i;r++){var o=e[r];r>0&&"\\"===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 Yt=["$or","$nor","$not"];function Ht(e){return Yt.indexOf(e)>-1}function Xt(e){return Object.keys(e)[0]}function Zt(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}),Ht(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=Zt([e,n]);Object.keys(s).length<=r||o.push(s)}))})),t[r]=o}else t[r]=Zt([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){if(void 0!==n.$eq)return;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){if(void 0!==n.$eq)return;void 0!==n.$lte?"$lte"===e?t<n.$lte&&(n.$lte=t):t<=n.$lte&&(delete n.$lte,n.$lt=t):void 0!==n.$lt?"$lte"===e?t<n.$lt&&(delete n.$lt,n.$lte=t):t<n.$lt&&(n.$lt=t):n[e]=t}(e,t,s):"$ne"===e?function(e,t){"$ne"in t?t.$ne.push(e):t.$ne=[e]}(t,s):"$eq"===e?function(e,t){delete t.$gt,delete t.$gte,delete t.$lt,delete t.$lte,delete t.$ne,t.$eq=e}(t,s):"$regex"===e?function(e,t){"$regex"in t?t.$regex.push(e):t.$regex=[e]}(t,s):void(s[e]=t)}))}}))})),t}function en(e){for(var t in e){if(Array.isArray(e))for(var n in e)e[n].$and&&(e[n]=Zt(e[n].$and));var r=e[t];"object"==typeof r&&en(r)}return e}function tn(e,t){for(var n in e){"$and"===n&&(t=!0);var r=e[n];"object"==typeof r&&(t=tn(r,t))}return t}function nn(e){var t=ue(e);tn(t,!1)&&"$and"in(t=en(t))&&(t=Zt(t.$and)),["$or","$nor"].forEach((function(e){e in t&&t[e].forEach((function(e){for(var t=Object.keys(e),n=0;n<t.length;n++){var r=t[n],i=e[r];"object"==typeof i&&null!==i||(e[r]={$eq:i})}}))})),"$not"in t&&(t.$not=Zt([t.$not]));for(var n=Object.keys(t),r=0;r<n.length;r++){var i=n[r],o=t[i];"object"==typeof o&&null!==o||(o={$eq:o}),t[i]=o}return rn(t),t}function rn(e){Object.keys(e).forEach((function(t){var n=e[t];Array.isArray(n)?n.forEach((function(e){e&&"object"==typeof e&&rn(e)})):"$ne"===t?e.$ne=[n]:"$regex"===t?e.$regex=[n]:n&&"object"==typeof n&&rn(n)}))}var on=-324;function sn(e,t){if(e===t)return 0;e=an(e),t=an(t);var n=dn(e),r=dn(t);if(n-r!=0)return n-r;switch(typeof e){case"number":return e-t;case"boolean":return e<t?-1:1;case"string":return function(e,t){return e===t?0:e>t?1:-1}(e,t)}return Array.isArray(e)?function(e,t){for(var n=Math.min(e.length,t.length),r=0;r<n;r++){var i=sn(e[r],t[r]);if(0!==i)return i}return e.length===t.length?0:e.length>t.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;o<i;o++){var s=sn(n[o],r[o]);if(0!==s)return s;if(0!==(s=sn(e[n[o]],t[r[o]])))return s}return n.length===r.length?0:n.length>r.length?1:-1}(e,t)}function an(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;r<n;r++)e[r]=an(t[r])}else{if(e instanceof Date)return e.toJSON();if(null!==e)for(var i in e={},t)if(Object.prototype.hasOwnProperty.call(t,i)){var o=t[i];void 0!==o&&(e[i]=an(o))}}}return e}function cn(e){if(null!==e)switch(typeof e){case"boolean":return e?1:0;case"number":return function(e){if(0===e)return"1";var t=e.toExponential().split(/e\+?/),n=parseInt(t[1],10),r=e<0,i=r?"0":"2",o=(s=((r?-n:n)-on).toString(),a="0",c=3,function(e,t,n){for(var r="",i=n-e.length;r.length<i;)r+=t;return r}(s,a,c)+s);var s,a,c;i+=""+o;var u=Math.abs(parseFloat(t[0]));r&&(u=10-u);var f=u.toFixed(20);return f=f.replace(/\.?0+$/,""),i+=""+f,i}(e);case"string":return e.replace(/\u0002/g,"").replace(/\u0001/g,"").replace(/\u0000/g,"");case"object":var t=Array.isArray(e),n=t?e:Object.keys(e),r=-1,i=n.length,o="";if(t)for(;++r<i;)o+=un(n[r]);else for(;++r<i;){var s=n[r];o+=un(s)+un(e[s])}return o}return""}function un(e){return dn(e=an(e))+""+cn(e)+"\0"}function fn(e,t){var n,r=t;if("1"===e[t])n=0,t++;else{var i="0"===e[t];t++;var o="",s=e.substring(t,t+3),a=parseInt(s,10)+on;for(i&&(a=-a),t+=3;;){var c=e[t];if("\0"===c)break;o+=c,t++}n=1===(o=o.split(".")).length?parseInt(o,10):parseFloat(o[0]+"."+o[1]),i&&(n-=10),0!==a&&(n=parseFloat(n+"e"+a))}return{num:n,length:t-r}}function ln(e,t){var n=e.pop();if(t.length){var r=t[t.length-1];n===r.element&&(t.pop(),r=t[t.length-1]);var i=r.element,o=r.index;if(Array.isArray(i))i.push(n);else if(o===e.length-2){i[e.pop()]=n}else e.push(n)}}function dn(e){var t=["boolean","number","string","object"].indexOf(typeof e);return~t?null===e?1:Array.isArray(e)?5:t<3?t+2:t+3:Array.isArray(e)?5:void 0}function hn(e,t,n){if(e=e.filter((function(e){return pn(e.doc,t.selector,n)})),t.sort){var r=function(e){function t(t){return e.map((function(e){var n=Wt(Xt(e));return Qt(t,n)}))}return function(e,n){var r,i,o=sn(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])[Xt(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}function pn(e,t,n){return n.every((function(n){var r=t[n],i=Wt(n),o=Qt(e,i);return Ht(n)?function(e,t,n){if("$or"===e)return t.some((function(e){return pn(n,e,Object.keys(e))}));if("$not"===e)return!pn(n,t,Object.keys(t));return!t.find((function(e){return pn(n,e,Object.keys(e))}))}(n,r,e):vn(r,e,i,o)}))}function vn(e,t,n,r){return!e||("object"==typeof e?Object.keys(e).every((function(i){var o=e[i];if(0===i.indexOf("$"))return gn(i,t,o,n,r);var s=Wt(i);if(void 0===r&&"object"!=typeof o&&s.length>0)return!1;var a=Qt(r,s);return"object"==typeof o?vn(o,t,n,a):gn("$eq",t,o,s,a)})):e===r)}function gn(e,t,n,r,i){if(!wn[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 wn[e](t,n,r,i)}function _n(e){return null!=e}function mn(e){return void 0!==e}function yn(e,t){return t.some((function(t){return e instanceof Array?e.some((function(e){return 0===sn(t,e)})):0===sn(t,e)}))}var wn={$elemMatch:function(e,t,n,r){return!!Array.isArray(r)&&(0!==r.length&&("object"==typeof r[0]&&null!==r[0]?r.some((function(e){return pn(e,t,Object.keys(t))})):r.some((function(r){return vn(t,e,n,r)}))))},$allMatch:function(e,t,n,r){return!!Array.isArray(r)&&(0!==r.length&&("object"==typeof r[0]&&null!==r[0]?r.every((function(e){return pn(e,t,Object.keys(t))})):r.every((function(r){return vn(t,e,n,r)}))))},$eq:function(e,t,n,r){return mn(r)&&0===sn(r,t)},$gte:function(e,t,n,r){return mn(r)&&sn(r,t)>=0},$gt:function(e,t,n,r){return mn(r)&&sn(r,t)>0},$lte:function(e,t,n,r){return mn(r)&&sn(r,t)<=0},$lt:function(e,t,n,r){return mn(r)&&sn(r,t)<0},$exists:function(e,t,n,r){return t?mn(r):!mn(r)},$mod:function(e,t,n,r){return _n(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!==sn(r,e)}))},$in:function(e,t,n,r){return _n(r)&&yn(r,t)},$nin:function(e,t,n,r){return _n(r)&&!yn(r,t)},$size:function(e,t,n,r){return _n(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===sn(t,e)}))}))}(r,t)},$regex:function(e,t,n,r){return _n(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 bn(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 kn(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=Je(e.view):e.filter=Je(e.filter))}function jn(e,t){return t.filter&&"string"==typeof t.filter&&!t.doc_ids&&!Fe(e.db)}function qn(e,t){var n=t.complete;if("_view"===t.filter){if(!t.view||"string"!=typeof t.view){var r=Me($e,"`view` filter parameter not found or invalid.");return n(r)}var i=Ke(t.view);e.db.get("_design/"+i[0],(function(r,o){if(e.isCancelled)return n(null,{status:"cancelled"});if(r)return n(Ne(r));var s=o&&o.views&&o.views[i[1]]&&o.views[i[1]].map;if(!s)return n(Me(Ae,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=hn([{doc:e}],{selector:t=nn(t)},Object.keys(t));return n&&1===n.length}(e,t.selector)},e.doChanges(t);else{var o=Ke(t.filter);e.db.get("_design/"+o[0],(function(r,i){if(e.isCancelled)return n(null,{status:"cancelled"});if(r)return n(Ne(r));var s=i&&i.filters&&i.filters[o[1]];if(!s)return n(Me(Ae,i&&i.filters?"missing json key: "+o[1]:"missing json key: filters"));t.filter=He('"use strict";\nreturn '+s+";",{}),e.doChanges(t)}))}}function An(e){return e.reduce((function(e,t){return e[t]=!0,e}),{})}Kt.plugin((function(e){e._changesFilterPlugin={validate:bn,normalize:kn,shouldFilter:jn,filter:qn}})),Kt.version="9.0.0";var On=An(["_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"]),Sn=An(["_access","_attachments","_replication_id","_replication_state","_replication_state_time","_replication_state_reason","_replication_stats"]);function xn(e){if(!/^\d+-/.test(e))return Me(Be);var t=e.indexOf("-"),n=e.substring(0,t),r=e.substring(t+1);return{prefix:parseInt(n,10),id:r}}function En(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=pt()),i=ht(e,n.deterministic_revs),e._rev){if((o=xn(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;o<s;o++)i=[r[o],{status:"missing"},[i]];return[{pos:n,ids:i}]}(e._revisions,s),r=e._revisions.start,i=e._revisions.ids[0]),!e._rev_tree){if((o=xn(e._rev)).error)return o;r=o.prefix,i=o.id,e._rev_tree=[{pos:r,ids:[i,s,[]]}]}ze(e._id),e._rev=r+"-"+i;var a={metadata:{},data:{}};for(var c in e)if(Object.prototype.hasOwnProperty.call(e,c)){var u="_"===c[0];if(u&&!On[c]){var f=Me(De,c);throw f.message=De.message+": "+c,f}u&&!Sn[c]?a.metadata[c.slice(1)]=e[c]:a.data[c]=e[c]}return a}function Cn(e,t,n){var r=function(e){try{return Ze(e)}catch(e){return{error:Me(Ie,"Attachment is not a valid base64 string")}}}(e.data);if(r.error)return n(r.error);e.length=r.length,e.data="blob"===t?rt(r,e.content_type):"base64"===t?et(r):r,lt(r,(function(t){e.digest="md5-"+t,n()}))}function In(e,t,n){if(e.stub)return n();"string"==typeof e.data?Cn(e,t,n):function(e,t,n){lt(e.data,(function(r){e.digest="md5-"+r,e.length=e.data.size||e.data.length||0,"binary"===t?st(e.data,(function(t){e.data=t,n()})):"base64"===t?at(e.data,(function(t){e.data=t,n()})):n()}))}(e,t,n)}function Ln(e,t,n,r,i,o,s,a){if(function(e,t){for(var n,r=e.slice(),i=t.split("-"),o=parseInt(i[0],10),s=i[1];n=r.pop();){if(n.pos===o&&n.ids[0]===s)return!0;for(var a=n.ids[2],c=0,u=a.length;c<u;c++)r.push({pos:n.pos+1,ids:a[c]})}return!1}(t.rev_tree,n.metadata.rev)&&!a)return r[i]=n,o();var c=t.winningRev||vt(t),u="deleted"in t?t.deleted:Et(t,c),f="deleted"in n.metadata?n.metadata.deleted:Et(n.metadata),l=/^1-/.test(n.metadata.rev);if(u&&!f&&a&&l){var d=n.data;d._rev=c,d._id=n.metadata.id,n=En(d,a)}var h=St(t.rev_tree,n.metadata.rev_tree[0],e);if(a&&(u&&f&&"new_leaf"!==h.conflicts||!u&&"new_leaf"!==h.conflicts||u&&!f&&"new_branch"===h.conflicts)){var p=Me(Oe);return r[i]=p,o()}var v=n.metadata.rev;n.metadata.rev_tree=h.tree,n.stemmedRevs=h.stemmedRevs||[],t.rev_map&&(n.metadata.rev_map=t.rev_map);var g=vt(n.metadata),_=Et(n.metadata,g),m=u===_?0:u<_?-1:1;s(n,g,_,v===g?_:Et(n.metadata,v),!0,m,i,o)}function Dn(e,t,n,r,i,o,s,a,c){e=e||1e3;var u=a.new_edits,f=new Map,l=0,d=t.length;function h(){++l===d&&c&&c()}t.forEach((function(e,t){if(e._id&&Ct(e._id)){var r=e._deleted?"_removeLocal":"_putLocal";n[r](e,{ctx:i},(function(e,n){o[t]=e||n,h()}))}else{var s=e.metadata.id;f.has(s)?(d--,f.get(s).push([e,t])):f.set(s,[[e,t]])}})),f.forEach((function(t,n){var i=0;function c(){++i<t.length?f():h()}function f(){var f=t[i],l=f[0],d=f[1];if(r.has(n))Ln(e,r.get(n),l,o,d,c,s,u);else{var h=St([],l.metadata.rev_tree[0],e);l.metadata.rev_tree=h.tree,l.stemmedRevs=h.stemmedRevs||[],function(e,t,n){var r=vt(e.metadata),i=Et(e.metadata,r);if("was_delete"in a&&i)return o[t]=Me(Ae,"deleted"),n();if(u&&function(e){return"missing"===e.metadata.rev_tree[0].ids[1].status}(e)){var c=Me(Oe);return o[t]=c,n()}s(e,r,i,i,!1,i?0:1,t,n)}(l,d,c)}}f()}))}var $n="document-store",Pn="by-sequence",Tn="attach-store",Bn="attach-seq-store",Rn="meta-store",Mn="local-store",Nn="detect-blob-support";function Un(e){try{return JSON.stringify(e)}catch(t){return Z.stringify(e)}}function zn(e){return function(t){var n="unknown_error";t.target&&t.target.error&&(n=t.target.error.name||t.target.error.message),e(Me(Te,n,t.type))}}function Fn(e,t,n){return{data:Un(e),winningRev:t,deletedOrLocal:n?"1":"0",seq:e.seq,id:e.id}}function Kn(e){if(!e)return null;var t=function(e){try{return JSON.parse(e)}catch(t){return Z.parse(e)}}(e.data);return t.winningRev=e.winningRev,t.deleted="1"===e.deletedOrLocal,t.seq=e.seq,t}function Jn(e){if(!e)return e;var t=e._doc_id_rev.lastIndexOf(":");return e._id=e._doc_id_rev.substring(0,t-1),e._rev=e._doc_id_rev.substring(t+1),delete e._doc_id_rev,e}function Vn(e,t,n,r){n?r(e?"string"!=typeof e?e:it(e,t):tt([""],{type:t})):e?"string"!=typeof e?ot(e,(function(e){r(et(e))})):r(e):r("")}function Gn(e,t,n,r){var i=Object.keys(e._attachments||{});if(!i.length)return r&&r();var o=0;function s(){++o===i.length&&r&&r()}i.forEach((function(r){t.attachments&&t.include_docs?function(e,t){var r=e._attachments[t],i=r.digest;n.objectStore(Tn).get(i).onsuccess=function(e){r.body=e.target.result.body,s()}}(e,r):(e._attachments[r].stub=!0,s())}))}function Qn(e,t){return Promise.all(e.map((function(e){if(e.doc&&e.doc._attachments){var n=Object.keys(e.doc._attachments);return Promise.all(n.map((function(n){var r=e.doc._attachments[n];if("body"in r){var i=r.body,o=r.content_type;return new Promise((function(s){Vn(i,o,t,(function(t){e.doc._attachments[n]=Object.assign(he(r,["digest","content_type"]),{data:t}),s()}))}))}})))}})))}function Wn(e,t,n){var r=[],i=n.objectStore(Pn),o=n.objectStore(Tn),s=n.objectStore(Bn),a=e.length;function c(){--a||function(){if(!r.length)return;r.forEach((function(e){s.index("digestSeq").count(IDBKeyRange.bound(e+"::",e+"::￿",!1,!1)).onsuccess=function(t){t.target.result||o.delete(e)}}))}()}e.forEach((function(e){var n=i.index("_doc_id_rev"),o=t+"::"+e;n.getKey(o).onsuccess=function(e){var t=e.target.result;if("number"!=typeof t)return c();i.delete(t),s.index("seq").openCursor(IDBKeyRange.only(t)).onsuccess=function(e){var t=e.target.result;if(t){var n=t.value.digestSeq.split("::")[0];r.push(n),s.delete(t.primaryKey),t.continue()}else c()}}}))}function Yn(e,t,n){try{return{txn:e.transaction(t,n)}}catch(e){return{error:e}}}var Hn=new class extends te{constructor(){super(),this._listeners={},me()&&addEventListener("storage",(e=>{this.emit(e.key)}))}addListener(e,t,n,r){if(!this._listeners[t]){var i=!1,o=this;this._listeners[t]=s,this.on(e,s)}function s(){if(o._listeners[t])if(i)i="waiting";else{i=!0;var e=he(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"===i&&ye(s),i=!1})).on("error",(function(){i=!1}))}}}removeListener(e,t){t in this._listeners&&(super.removeListener(e,this._listeners[t]),delete this._listeners[t])}notifyLocalWindows(e){me()&&(localStorage[e]="a"===localStorage[e]?"b":"a")}notify(e){this.emit(e),this.notifyLocalWindows(e)}};function Xn(e,t,n,r,i,o){for(var s,a,c,u,f,l,d,h,p=t.docs,v=0,g=p.length;v<g;v++){var _=p[v];_._id&&Ct(_._id)||(_=p[v]=En(_,n.new_edits,e)).error&&!d&&(d=_)}if(d)return o(d);var m=!1,y=0,w=new Array(p.length),b=new Map,k=!1,j=r._meta.blobSupport?"blob":"base64";function q(){m=!0,A()}function A(){h&&m&&(h.docCount+=y,l.put(h))}function O(){k||(Hn.notify(r._meta.name),o(null,w))}function S(e,t,n,r,i,o,s,a){e.metadata.winningRev=t,e.metadata.deleted=n;var c=e.data;if(c._id=e.metadata.id,c._rev=e.metadata.rev,r&&(c._deleted=!0),c._attachments&&Object.keys(c._attachments).length)return function(e,t,n,r,i,o){var s=e.data,a=0,c=Object.keys(s._attachments);function f(){a===c.length&&x(e,t,n,r,i,o)}function l(){a++,f()}c.forEach((function(n){var r=e.data._attachments[n];if(r.stub)a++,f();else{var i=r.data;delete r.data,r.revpos=parseInt(t,10),function(e,t,n){var r=u.count(e);r.onsuccess=function(r){if(r.target.result)return n();var i={digest:e,body:t};u.put(i).onsuccess=n}}(r.digest,i,l)}}))}(e,t,n,i,s,a);y+=o,A(),x(e,t,n,i,s,a)}function x(e,t,n,i,o,u){var l=e.data,d=e.metadata;function h(o){var c=e.stemmedRevs||[];i&&r.auto_compaction&&(c=c.concat(function(e){var t=[];return gt(e.rev_tree,(function(e,n,r,i,o){"available"!==o.status||e||(t.push(n+"-"+r),o.status="missing")})),t}(e.metadata))),c&&c.length&&Wn(c,e.metadata.id,s),d.seq=o.target.result;var u=Fn(d,t,n);a.put(u).onsuccess=p}function p(){w[o]={ok:!0,id:d.id,rev:d.rev},b.set(e.metadata.id,e.metadata),function(e,t,n){var r=0,i=Object.keys(e.data._attachments||{});if(!i.length)return n();function o(){++r===i.length&&n()}function s(n){var r=e.data._attachments[n].digest,i=f.put({seq:t,digestSeq:r+"::"+t});i.onsuccess=o,i.onerror=function(e){e.preventDefault(),e.stopPropagation(),o()}}for(var a=0;a<i.length;a++)s(i[a])}(e,d.seq,u)}l._doc_id_rev=d.id+"::"+d.rev,delete l._id,delete l._rev;var v=c.put(l);v.onsuccess=h,v.onerror=function(e){e.preventDefault(),e.stopPropagation(),c.index("_doc_id_rev").getKey(l._doc_id_rev).onsuccess=function(e){c.put(l,e.target.result).onsuccess=h}}}!function(e,t,n){if(!e.length)return n();var r,i=0;function o(){i++,e.length===i&&(r?n(r):n())}e.forEach((function(e){var n=e.data&&e.data._attachments?Object.keys(e.data._attachments):[],i=0;if(!n.length)return o();function s(e){r=e,++i===n.length&&o()}for(var a in e.data._attachments)Object.prototype.hasOwnProperty.call(e.data._attachments,a)&&In(e.data._attachments[a],t,s)}))}(p,j,(function(t){if(t)return o(t);!function(){var t=Yn(i,[$n,Pn,Tn,Mn,Bn,Rn],"readwrite");if(t.error)return o(t.error);(s=t.txn).onabort=zn(o),s.ontimeout=zn(o),s.oncomplete=O,a=s.objectStore($n),c=s.objectStore(Pn),u=s.objectStore(Tn),f=s.objectStore(Bn),(l=s.objectStore(Rn)).get(Rn).onsuccess=function(e){h=e.target.result,A()},function(e){var t=[];if(p.forEach((function(e){e.data&&e.data._attachments&&Object.keys(e.data._attachments).forEach((function(n){var r=e.data._attachments[n];r.stub&&t.push(r.digest)}))})),!t.length)return e();var n,r=0;function i(){++r===t.length&&e(n)}t.forEach((function(e){!function(e,t){var n=u.get(e);n.onsuccess=function(n){if(n.target.result)t();else{var r=Me(Re,"unknown stub attachment with digest "+e);r.status=412,t(r)}}}(e,(function(e){e&&!n&&(n=e),i()}))}))}((function(t){if(t)return k=!0,o(t);!function(){if(!p.length)return;var t=0;function i(){++t===p.length&&Dn(e.revs_limit,p,r,b,s,w,S,n,q)}function o(e){var t=Kn(e.target.result);t&&b.set(t.id,t),i()}for(var c=0,u=p.length;c<u;c++){var f=p[c];if(f._id&&Ct(f._id))i();else a.get(f.metadata.id).onsuccess=o}}()}))}()}))}function Zn(e,t,n,r,i){var o,s,a;function c(e){s=e.target.result,o&&i(o,s,a)}function u(e){o=e.target.result,s&&i(o,s,a)}function f(e){var t=e.target.result;if(!t)return i();i([t.key],[t.value],t)}-1===r&&(r=1e3),"function"==typeof e.getAll&&"function"==typeof e.getAllKeys&&r>1&&!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=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 er(e,t,n){var r,i,o="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,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(Me(Te,i.name,i.message));var d=[$n,Pn,Rn];e.attachments&&d.push(Tn);var h=Yn(t,d,"readonly");if(h.error)return n(h.error);var p=h.txn;p.oncomplete=function(){e.attachments?Qn(b,e.binary).then(A):A()},p.onabort=zn(n);var v,g,_=p.objectStore($n),m=p.objectStore(Pn),y=p.objectStore(Rn),w=m.index("_doc_id_rev"),b=[];function k(t,n){var r={id:n.id,key:n.id,value:{rev:t}};n.deleted?c&&(b.push(r),r.value.deleted=!0,r.doc=null):u--<=0&&(b.push(r),e.include_docs&&function(t,n,r){var i=t.id+"::"+r;w.get(i).onsuccess=function(r){if(n.doc=Jn(r.target.result)||{},e.conflicts){var i=yt(t);i.length&&(n.doc._conflicts=i)}Gn(n.doc,e,p)}}(n,r,t))}function j(e){for(var t=0,n=e.length;t<n&&b.length!==f;t++){var r=e[t];if(r.error&&c)b.push(r);else{var i=Kn(r);k(i.winningRev,i)}}}function q(e,t,n){n&&(j(t),b.length<f&&n.continue())}function A(){var t={total_rows:v,offset:e.skip,rows:b};e.update_seq&&void 0!==g&&(t.update_seq=g),n(null,t)}return y.get(Rn).onsuccess=function(e){v=e.target.result.docCount},e.update_seq&&(m.openKeyCursor(null,"prev").onsuccess=e=>{var t=e.target.result;t&&t.key&&(g=t.key)}),i||0===f?void 0:c?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,{})}}))}(c,_,q):-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 Zn(_,r,e.descending,f+u,q)}var tr=!1,nr=[];function rr(){!tr&&nr.length&&(tr=!0,nr.shift()())}function ir(e,t,n,r){if((e=ue(e)).continuous){var i=n+":"+pt();return Hn.addListener(n,i,t,e),Hn.notify(n),{cancel:function(){Hn.removeListener(n,i)}}}var o=e.doc_ids&&new Set(e.doc_ids);e.since=e.since||0;var s=e.since,a="limit"in e?e.limit:-1;0===a&&(a=1);var c,u,f,l,d=[],h=0,p=Ue(e),v=new Map;function g(e,t,n,r){if(n.seq!==t)return r();if(n.winningRev===e._rev)return r(n,e);var i=e._id+"::"+n.winningRev;l.get(i).onsuccess=function(e){r(n,Jn(e.target.result))}}function _(){e.complete(null,{results:d,last_seq:s})}var m=[$n,Pn];e.attachments&&m.push(Tn);var y=Yn(r,m,"readonly");if(y.error)return e.complete(y.error);(c=y.txn).onabort=zn(e.complete),c.oncomplete=function(){!e.continuous&&e.attachments?Qn(d).then(_):_()},u=c.objectStore(Pn),f=c.objectStore($n),l=u.index("_doc_id_rev"),Zn(u,e.since&&!e.descending?IDBKeyRange.lowerBound(e.since,!0):null,e.descending,a,(function(t,n,r){if(r&&t.length){var i=new Array(t.length),u=new Array(t.length),l=0;n.forEach((function(n,s){!function(e,t,n){if(o&&!o.has(e._id))return n();var r=v.get(e._id);if(r)return g(e,t,r,n);f.get(e._id).onsuccess=function(i){r=Kn(i.target.result),v.set(e._id,r),g(e,t,r,n)}}(Jn(n),t[s],(function(n,o){u[s]=n,i[s]=o,++l===t.length&&function(){for(var t=[],n=0,o=i.length;n<o&&h!==a;n++){var s=i[n];if(s){var c=u[n];t.push(_(c,s))}}Promise.all(t).then((function(t){for(var n=0,r=t.length;n<r;n++)t[n]&&e.onChange(t[n])})).catch(e.complete),h!==a&&r.continue()}()}))}))}function _(t,n){var r=e.processChange(n,t,e);s=r.seq=t.seq;var i=p(r);return"object"==typeof i?Promise.reject(i):i?(h++,e.return_docs&&d.push(r),e.attachments&&e.include_docs?new Promise((function(t){Gn(n,e,c,(function(){Qn([r],e.binary).then((function(){t(r)}))}))})):Promise.resolve(r)):Promise.resolve()}}))}var or,sr=new Map,ar=new Map;function cr(e,t){var n=this;!function(e,t,n){nr.push((function(){e((function(e,r){!function(e,t,n,r){try{e(t,n)}catch(t){r.emit("error",t)}}(t,e,r,n),tr=!1,ye((function(){rr()}))}))})),rr()}((function(t){!function(e,t,n){var r=t.name,i=null,o=null;function s(e){return function(t,n){t&&t instanceof Error&&!t.reason&&o&&(t.reason=o),e(t,n)}}function a(e){var t=e.createObjectStore($n,{keyPath:"id"});e.createObjectStore(Pn,{autoIncrement:!0}).createIndex("_doc_id_rev","_doc_id_rev",{unique:!0}),e.createObjectStore(Tn,{keyPath:"digest"}),e.createObjectStore(Rn,{keyPath:"id",autoIncrement:!1}),e.createObjectStore(Nn),t.createIndex("deletedOrLocal","deletedOrLocal",{unique:!1}),e.createObjectStore(Mn,{keyPath:"_id"});var n=e.createObjectStore(Bn,{autoIncrement:!0});n.createIndex("seq","seq"),n.createIndex("digestSeq","digestSeq",{unique:!0})}function c(e,t){var n=e.objectStore($n);n.createIndex("deletedOrLocal","deletedOrLocal",{unique:!1}),n.openCursor().onsuccess=function(e){var r=e.target.result;if(r){var i=r.value,o=Et(i);i.deletedOrLocal=o?"1":"0",n.put(i),r.continue()}else t()}}function u(e){e.createObjectStore(Mn,{keyPath:"_id"}).createIndex("_doc_id_rev","_doc_id_rev",{unique:!0})}function f(e,t){var n=e.objectStore(Mn),r=e.objectStore($n),i=e.objectStore(Pn);r.openCursor().onsuccess=function(e){var o=e.target.result;if(o){var s=o.value,a=s.id,c=Ct(a),u=vt(s);if(c){var f=a+"::"+u,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 l(e){var t=e.createObjectStore(Bn,{autoIncrement:!0});t.createIndex("seq","seq"),t.createIndex("digestSeq","digestSeq",{unique:!0})}function d(e,t){var n=e.objectStore(Pn),r=e.objectStore(Tn),i=e.objectStore(Bn);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={},c=0;c<s.length;c++){a[r._attachments[s[c]].digest]=!0}var u=Object.keys(a);for(c=0;c<u.length;c++){var f=u[c];i.put({seq:o,digestSeq:f+"::"+o})}n.continue()}}}function h(e){function t(e){return e.data?Kn(e):(e.deleted="1"===e.deletedOrLocal,e)}var n=e.objectStore(Pn),r=e.objectStore($n);r.openCursor().onsuccess=function(e){var i=e.target.result;if(i){var o=t(i.value);if(o.winningRev=o.winningRev||vt(o),o.seq)return a();s()}function s(){var e=o.id+"::",t=o.id+"::￿",r=n.index("_doc_id_rev").openCursor(IDBKeyRange.bound(e,t)),i=0;r.onsuccess=function(e){var t=e.target.result;if(!t)return o.seq=i,a();var n=t.primaryKey;n>i&&(i=n),t.continue()}}function a(){var e=Fn(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=le((function(t){t(null,e._meta.instanceId)})),e._bulkDocs=function(n,r,o){Xn(t,n,r,e,i,s(o))},e._get=function(e,t,n){var r,o,s,a=t.ctx;if(!a){var c=Yn(i,[$n,Pn,Tn],"readonly");if(c.error)return n(c.error);a=c.txn}function u(){n(s,{doc:r,metadata:o,ctx:a})}a.objectStore($n).get(e).onsuccess=function(e){if(!(o=Kn(e.target.result)))return s=Me(Ae,"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 i=n.pos,o=n.ids,s=o[0],a=o[1],c=o[2],u=0===c.length,f=n.history?n.history.slice():[];if(f.push({id:s,pos:i,opts:a}),u)for(var l=0,d=f.length;l<d;l++){var h=f[l];if(h.pos+"-"+h.id===e)return i+"-"+s}for(var p=0,v=c.length;p<v;p++)r.push({pos:i+1,ids:c[p],history:f})}throw new Error("Unable to resolve latest revision for id "+t.id+", rev "+e)}(t.rev,o):t.rev;else if(n=o.winningRev,Et(o))return s=Me(Ae,"deleted"),u();var i=a.objectStore(Pn),c=o.id+"::"+n;i.index("_doc_id_rev").get(c).onsuccess=function(e){if((r=e.target.result)&&(r=Jn(r)),!r)return s=Me(Ae,"missing"),u();u()}}},e._getAttachment=function(e,t,n,r,o){var s;if(r.ctx)s=r.ctx;else{var a=Yn(i,[$n,Pn,Tn],"readonly");if(a.error)return o(a.error);s=a.txn}var c=n.digest,u=n.content_type;s.objectStore(Tn).get(c).onsuccess=function(e){Vn(e.target.result.body,u,r.binary,(function(e){o(null,e)}))}},e._info=function(t){var n,r,o=Yn(i,[Rn,Pn],"readonly");if(o.error)return t(o.error);var s=o.txn;s.objectStore(Rn).get(Rn).onsuccess=function(e){r=e.target.result.docCount},s.objectStore(Pn).openKeyCursor(null,"prev").onsuccess=function(e){var t=e.target.result;n=t?t.key:0},s.oncomplete=function(){t(null,{doc_count:r,update_seq:n,idb_attachment_format:e._meta.blobSupport?"binary":"base64"})}},e._allDocs=function(e,t){er(e,i,s(t))},e._changes=function(t){return ir(t,e,r,i)},e._close=function(e){i.close(),sr.delete(r),e()},e._getRevisionTree=function(e,t){var n=Yn(i,[$n],"readonly");if(n.error)return t(n.error);n.txn.objectStore($n).get(e).onsuccess=function(e){var n=Kn(e.target.result);n?t(null,n.rev_tree):t(Me(Ae))}},e._doCompaction=function(e,t,n){var r=Yn(i,[$n,Pn,Tn,Bn],"readwrite");if(r.error)return n(r.error);var o=r.txn;o.objectStore($n).get(e).onsuccess=function(n){var r=Kn(n.target.result);gt(r.rev_tree,(function(e,n,r,i,o){var s=n+"-"+r;-1!==t.indexOf(s)&&(o.status="missing")})),Wn(t,e,o);var i=r.winningRev,s=r.deleted;o.objectStore($n).put(Fn(r,i,s))},o.onabort=zn(n),o.oncomplete=function(){n()}},e._getLocal=function(e,t){var n=Yn(i,[Mn],"readonly");if(n.error)return t(n.error);var r=n.txn.objectStore(Mn).get(e);r.onerror=zn(t),r.onsuccess=function(e){var n=e.target.result;n?(delete n._doc_id_rev,t(null,n)):t(Me(Ae))}},e._putLocal=function(e,t,n){"function"==typeof t&&(n=t,t={}),delete e._revisions;var r=e._rev,o=e._id;e._rev=r?"0-"+(parseInt(r.split("-")[1],10)+1):"0-1";var s,a=t.ctx;if(!a){var c=Yn(i,[Mn],"readwrite");if(c.error)return n(c.error);(a=c.txn).onerror=zn(n),a.oncomplete=function(){s&&n(null,s)}}var u,f=a.objectStore(Mn);r?(u=f.get(o)).onsuccess=function(i){var o=i.target.result;o&&o._rev===r?f.put(e).onsuccess=function(){s={ok:!0,id:e._id,rev:e._rev},t.ctx&&n(null,s)}:n(Me(Oe))}:((u=f.add(e)).onerror=function(e){n(Me(Oe)),e.preventDefault(),e.stopPropagation()},u.onsuccess=function(){s={ok:!0,id:e._id,rev:e._rev},t.ctx&&n(null,s)})},e._removeLocal=function(e,t,n){"function"==typeof t&&(n=t,t={});var r,o=t.ctx;if(!o){var s=Yn(i,[Mn],"readwrite");if(s.error)return n(s.error);(o=s.txn).oncomplete=function(){r&&n(null,r)}}var a=e._id,c=o.objectStore(Mn),u=c.get(a);u.onerror=zn(n),u.onsuccess=function(i){var o=i.target.result;o&&o._rev===e._rev?(c.delete(a),r={ok:!0,id:a,rev:"0-0"},t.ctx&&n(null,r)):n(Me(Ae))}},e._destroy=function(e,t){Hn.removeAllListeners(r);var n=ar.get(r);n&&n.result&&(n.result.close(),sr.delete(r));var i=indexedDB.deleteDatabase(r);i.onsuccess=function(){ar.delete(r),me()&&r in localStorage&&delete localStorage[r],t(null,{ok:!0})},i.onerror=zn(t)};var p=sr.get(r);if(p)return i=p.idb,e._meta=p.global,ye((function(){n(null,e)}));var v=indexedDB.open(r,5);ar.set(r,v),v.onupgradeneeded=function(e){var t=e.target.result;if(e.oldVersion<1)return a(t);var n=e.currentTarget.transaction;e.oldVersion<3&&u(t),e.oldVersion<4&&l(t);var r=[c,f,d,h],i=e.oldVersion;function o(){var e=r[i-1];i++,e&&e(n,o)}o()},v.onsuccess=function(t){(i=t.target.result).onversionchange=function(){i.close(),sr.delete(r)},i.onabort=function(e){we("error","Database has a global failure",e.target.error),o=e.target.error,i.close(),sr.delete(r)};var s,a,c,u,f=i.transaction([Rn,Nn,$n],"readwrite"),l=!1;function d(){void 0!==c&&l&&(e._meta={name:r,instanceId:u,blobSupport:c},sr.set(r,{idb:i,global:e._meta}),n(null,e))}function h(){if(void 0!==a&&void 0!==s){var e=r+"_id";e in s?u=s[e]:s[e]=u=pt(),s.docCount=a,f.objectStore(Rn).put(s)}}f.objectStore(Rn).get(Rn).onsuccess=function(e){s=e.target.result||{id:Rn},h()},function(e,t){e.objectStore($n).index("deletedOrLocal").count(IDBKeyRange.only("0")).onsuccess=function(e){t(e.target.result)}}(f,(function(e){a=e,h()})),or||(or=function(e,t,n){return new Promise((function(r){var i=tt([""]);let o;{const r=n;o=e.objectStore(t).put(i,r)}o.onsuccess=function(){var e=navigator.userAgent.match(/Chrome\/(\d+)/),t=navigator.userAgent.match(/Edge\//);r(t||!e||parseInt(e[1],10)>=43)},o.onerror=e.onabort=function(e){e.preventDefault(),e.stopPropagation(),r(!1)}})).catch((function(){return!1}))}(f,Nn,"key")),or.then((function(e){c=e,d()})),f.oncomplete=function(){l=!0,d()},f.onabort=zn(n)},v.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?",we("error",t),n(Me(Te,t))}}(n,e,t)}),t,n.constructor)}cr.valid=function(){try{return"undefined"!=typeof indexedDB&&"undefined"!=typeof IDBKeyRange}catch(e){return!1}};const ur=5e3,fr={};function lr(e){const t=e.doc||e.ok,n=t&&t._attachments;n&&Object.keys(n).forEach((function(e){const t=n[e];t.data=it(t.data,t.content_type)}))}function dr(e){return/^_design/.test(e)?"_design/"+encodeURIComponent(e.slice(8)):e.startsWith("_local/")?"_local/"+encodeURIComponent(e.slice(7)):encodeURIComponent(e)}function hr(e){return e._attachments&&Object.keys(e._attachments)?Promise.all(Object.keys(e._attachments).map((function(t){const n=e._attachments[t];if(n.data&&"string"!=typeof n.data)return new Promise((function(e){at(n.data,e)})).then((function(e){n.data=e}))}))):Promise.resolve()}function pr(e,t){if(function(e){if(!e.prefix)return!1;const t=Ye(e.prefix).protocol;return"http"===t||"https"===t}(t)){const n=t.name.substr(t.prefix.length);e=t.prefix.replace(/\/?$/,"/")+encodeURIComponent(n)}const n=Ye(e);(n.user||n.password)&&(n.auth={username:n.user,password:n.password});const r=n.path.replace(/(^\/|\/$)/g,"").split("/");return n.db=r.pop(),-1===n.db.indexOf("%")&&(n.db=encodeURIComponent(n.db)),n.path=r.join("/"),n}function vr(e,t){return gr(e,e.db+"/"+t)}function gr(e,t){const n=e.path?"/":"";return e.protocol+"://"+e.host+(e.port?":"+e.port:"")+"/"+e.path+n+t}function _r(e){const t=Object.keys(e);return 0===t.length?"":"?"+t.map((t=>t+"="+encodeURIComponent(e[t]))).join("&")}function mr(e,t){const n=this,r=pr(e.name,e),i=vr(r,"");e=ue(e);const o=async function(t,n){if((n=n||{}).headers=n.headers||new Vt,n.credentials="include",e.auth||r.auth){const t=e.auth||r.auth,i=t.username+":"+t.password,o=et(unescape(encodeURIComponent(i)));n.headers.set("Authorization","Basic "+o)}const i=e.headers||{};Object.keys(i).forEach((function(e){n.headers.append(e,i[e])})),function(e){const 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());const o=e.fetch||Jt;return await o(t,n)};function s(e,t){return de(e,(function(...e){u().then((function(){return t.apply(this,e)})).catch((function(t){e.pop()(t)}))})).bind(n)}async function a(e,t){const n={};(t=t||{}).headers=t.headers||new Vt,t.headers.get("Content-Type")||t.headers.set("Content-Type","application/json"),t.headers.get("Accept")||t.headers.set("Accept","application/json");const r=await o(e,t);n.ok=r.ok,n.status=r.status;const i=await r.json();if(n.data=i,!n.ok){n.data.status=n.status;throw Ne(n.data)}return Array.isArray(n.data)&&(n.data=n.data.map((function(e){return e.error||e.missing?Ne(e):e}))),n}let c;async function u(){return e.skip_setup?Promise.resolve():c||(c=a(i).catch((function(e){return e&&e.status&&404===e.status?(ke(404,"PouchDB is just detecting if the remote exists."),a(i,{method:"PUT"})):Promise.reject(e)})).catch((function(e){return!(!e||!e.status||412!==e.status)||Promise.reject(e)})),c.catch((function(){c=null})),c)}function f(e){return e.split("/").map(encodeURIComponent).join("/")}ye((function(){t(null,n)})),n._remote=!0,n.type=function(){return"http"},n.id=s("id",(async function(e){let t;try{const e=await o(gr(r,""));t=await e.json()}catch(e){t={}}e(null,t&&t.uuid?t.uuid+r.db:vr(r,""))})),n.compact=s("compact",(async function(e,t){"function"==typeof e&&(t=e,e={}),e=ue(e),await a(vr(r,"_compact"),{method:"POST"}),function r(){n.info((function(n,i){i&&!i.compact_running?t(null,{ok:!0}):setTimeout(r,e.interval||200)}))}()})),n.bulkGet=de("bulkGet",(function(e,t){const n=this;async function i(t){const n={};e.revs&&(n.revs=!0),e.attachments&&(n.attachments=!0),e.latest&&(n.latest=!0);try{const i=await a(vr(r,"_bulk_get"+_r(n)),{method:"POST",body:JSON.stringify({docs:e.docs})});e.attachments&&e.binary&&i.data.results.forEach((function(e){e.docs.forEach(lr)})),t(null,i.data)}catch(e){t(e)}}function o(){const r=Math.ceil(e.docs.length/50);let i=0;const o=new Array(r);function s(e){return function(n,s){o[e]=s.results,++i===r&&t(null,{results:o.flat()})}}for(let t=0;t<r;t++){const r=he(e,["revs","attachments","binary","latest"]);r.docs=e.docs.slice(50*t,Math.min(e.docs.length,50*(t+1))),_e(n,r,s(t))}}const s=gr(r,""),c=fr[s];"boolean"!=typeof c?i((function(e,n){e?(fr[s]=!1,ke(e.status,"PouchDB is just detecting if the remote supports the _bulk_get API."),o()):(fr[s]=!0,t(null,n))})):c?i(t):o()})),n._info=async function(e){try{await u();const t=await o(vr(r,"")),n=await t.json();n.host=vr(r,""),e(null,n)}catch(t){e(t)}},n.fetch=async function(e,t){await u();const n="/"===e.substring(0,1)?gr(r,e.substring(1)):vr(r,e);return o(n,t)},n.get=s("get",(async function(e,t,n){"function"==typeof t&&(n=t,t={});const i={};function s(e){const n=e._attachments,i=n&&Object.keys(n);if(!n||!i.length)return;return function(e,t){return new Promise((function(n,r){var i,o=0,s=0,a=0,c=e.length;function u(){++a===c?i?r(i):n():d()}function f(){o--,u()}function l(e){o--,i=i||e,u()}function d(){for(;o<t&&s<c;)o++,e[s++]().then(f,l)}d()}))}(i.map((function(i){return function(){return async function(i){const s=n[i],a=dr(e._id)+"/"+f(i)+"?rev="+e._rev,c=await o(vr(r,a));let u,l;if(u="buffer"in c?await c.buffer():await c.blob(),t.binary){const e=Object.getOwnPropertyDescriptor(u.__proto__,"type");e&&!e.set||(u.type=s.content_type),l=u}else l=await new Promise((function(e){at(u,e)}));delete s.stub,delete s.length,s.data=l}(i)}})),5)}(t=ue(t)).revs&&(i.revs=!0),t.revs_info&&(i.revs_info=!0),t.latest&&(i.latest=!0),t.open_revs&&("all"!==t.open_revs&&(t.open_revs=JSON.stringify(t.open_revs)),i.open_revs=t.open_revs),t.rev&&(i.rev=t.rev),t.conflicts&&(i.conflicts=t.conflicts),t.update_seq&&(i.update_seq=t.update_seq),e=dr(e);const c=vr(r,e+_r(i));try{const e=await a(c);t.attachments&&await(u=e.data,Array.isArray(u)?Promise.all(u.map((function(e){if(e.ok)return s(e.ok)}))):s(u)),n(null,e.data)}catch(t){t.docId=e,n(t)}var u})),n.remove=s("remove",(async function(e,t,n,i){let o;"string"==typeof t?(o={_id:e,_rev:t},"function"==typeof n&&(i=n,n={})):(o=e,"function"==typeof t?(i=t,n={}):(i=n,n=t));const s=o._rev||n.rev,c=vr(r,dr(o._id))+"?rev="+s;try{i(null,(await a(c,{method:"DELETE"})).data)}catch(e){i(e)}})),n.getAttachment=s("getAttachment",(async function(e,t,n,i){"function"==typeof n&&(i=n,n={});const s=n.rev?"?rev="+n.rev:"",a=vr(r,dr(e))+"/"+f(t)+s;let c;try{const e=await o(a,{method:"GET"});if(!e.ok)throw e;let t;c=e.headers.get("content-type"),(T.browser||"function"!=typeof e.buffer)&&(t=await e.blob()),i(null,t)}catch(e){i(e)}})),n.removeAttachment=s("removeAttachment",(async function(e,t,n,i){const o=vr(r,dr(e)+"/"+f(t))+"?rev="+n;try{i(null,(await a(o,{method:"DELETE"})).data)}catch(e){i(e)}})),n.putAttachment=s("putAttachment",(async function(e,t,n,i,o,s){"function"==typeof o&&(s=o,o=i,i=n,n=null);const c=dr(e)+"/"+f(t);let u=vr(r,c);if(n&&(u+="?rev="+n),"string"==typeof i){let e;try{e=Ze(i)}catch(e){return s(Me(Ie,"Attachment is not a valid base64 string"))}i=e?rt(e,o):""}try{s(null,(await a(u,{headers:new Vt({"Content-Type":o}),method:"PUT",body:i})).data)}catch(e){s(e)}})),n._bulkDocs=async function(e,t,n){e.new_edits=t.new_edits;try{await u(),await Promise.all(e.docs.map(hr));n(null,(await a(vr(r,"_bulk_docs"),{method:"POST",body:JSON.stringify(e)})).data)}catch(e){n(e)}},n._put=async function(e,t,n){try{await u(),await hr(e);n(null,(await a(vr(r,dr(e._id)),{method:"PUT",body:JSON.stringify(e)})).data)}catch(t){t.docId=e&&e._id,n(t)}},n.allDocs=s("allDocs",(async function(e,t){"function"==typeof e&&(t=e,e={});const n={};let i,o="GET";(e=ue(e)).conflicts&&(n.conflicts=!0),e.update_seq&&(n.update_seq=!0),e.descending&&(n.descending=!0),e.include_docs&&(n.include_docs=!0),e.attachments&&(n.attachments=!0),e.key&&(n.key=JSON.stringify(e.key)),e.start_key&&(e.startkey=e.start_key),e.startkey&&(n.startkey=JSON.stringify(e.startkey)),e.end_key&&(e.endkey=e.end_key),e.endkey&&(n.endkey=JSON.stringify(e.endkey)),void 0!==e.inclusive_end&&(n.inclusive_end=!!e.inclusive_end),void 0!==e.limit&&(n.limit=e.limit),void 0!==e.skip&&(n.skip=e.skip);const s=_r(n);void 0!==e.keys&&(o="POST",i={keys:e.keys});try{const n=await a(vr(r,"_all_docs"+s),{method:o,body:JSON.stringify(i)});e.include_docs&&e.attachments&&e.binary&&n.data.rows.forEach(lr),t(null,n.data)}catch(e){t(e)}})),n._changes=function(e){const t="batch_size"in e?e.batch_size:25;(e=ue(e)).continuous&&!("heartbeat"in e)&&(e.heartbeat=1e4);let n="timeout"in e?e.timeout:3e4;"timeout"in e&&e.timeout&&n-e.timeout<ur&&(n=e.timeout+ur),"heartbeat"in e&&e.heartbeat&&n-e.heartbeat<ur&&(n=e.heartbeat+ur);const i={};"timeout"in e&&e.timeout&&(i.timeout=e.timeout);const o=void 0!==e.limit&&e.limit;let s=o;if(e.style&&(i.style=e.style),(e.include_docs||e.filter&&"function"==typeof e.filter)&&(i.include_docs=!0),e.attachments&&(i.attachments=!0),e.continuous&&(i.feed="longpoll"),e.seq_interval&&(i.seq_interval=e.seq_interval),e.conflicts&&(i.conflicts=!0),e.descending&&(i.descending=!0),e.update_seq&&(i.update_seq=!0),"heartbeat"in e&&e.heartbeat&&(i.heartbeat=e.heartbeat),e.filter&&"string"==typeof e.filter&&(i.filter=e.filter),e.view&&"string"==typeof e.view&&(i.filter="_view",i.view=e.view),e.query_params&&"object"==typeof e.query_params)for(const t in e.query_params)Object.prototype.hasOwnProperty.call(e.query_params,t)&&(i[t]=e.query_params[t]);let c,f="GET";e.doc_ids?(i.filter="_doc_ids",f="POST",c={doc_ids:e.doc_ids}):e.selector&&(i.filter="_selector",f="POST",c={selector:e.selector});const l=new AbortController;let d;const h=async function(n,h){if(e.aborted)return;i.since=n,"object"==typeof i.since&&(i.since=JSON.stringify(i.since)),e.descending?o&&(i.limit=s):i.limit=!o||s>t?t:s;const p=vr(r,"_changes"+_r(i)),v={signal:l.signal,method:f,body:JSON.stringify(c)};if(d=n,!e.aborted)try{await u();h(null,(await a(p,v)).data)}catch(e){h(e)}},p={results:[]},v=function(n,r){if(e.aborted)return;let i=0;if(r&&r.results){i=r.results.length,p.last_seq=r.last_seq;let t=null,n=null;"number"==typeof r.pending&&(t=r.pending),"string"!=typeof p.last_seq&&"number"!=typeof p.last_seq||(n=p.last_seq),e.query_params,r.results=r.results.filter((function(r){s--;const i=Ue(e)(r);return i&&(e.include_docs&&e.attachments&&e.binary&&lr(r),e.return_docs&&p.results.push(r),e.onChange(r,t,n)),i}))}else if(n)return e.aborted=!0,void e.complete(n);r&&r.last_seq&&(d=r.last_seq);const a=o&&s<=0||r&&i<t||e.descending;(!e.continuous||o&&s<=0)&&a?e.complete(null,p):ye((function(){h(d,v)}))};return h(e.since||0,v),{cancel:function(){e.aborted=!0,l.abort()}}},n.revsDiff=s("revsDiff",(async function(e,t,n){"function"==typeof t&&(n=t,t={});try{n(null,(await a(vr(r,"_revs_diff"),{method:"POST",body:JSON.stringify(e)})).data)}catch(e){n(e)}})),n._close=function(e){e()},n._destroy=async function(e,t){try{t(null,await a(vr(r,""),{method:"DELETE"}))}catch(e){404===e.status?t(null,{ok:!0}):t(e)}}}mr.valid=function(){return!0};class yr extends Error{constructor(e){super(),this.status=400,this.name="query_parse_error",this.message=e,this.error=!0;try{Error.captureStackTrace(this,yr)}catch(e){}}}class wr extends Error{constructor(e){super(),this.status=404,this.name="not_found",this.message=e,this.error=!0;try{Error.captureStackTrace(this,wr)}catch(e){}}}class br extends Error{constructor(e){super(),this.status=500,this.name="invalid_value",this.message=e,this.error=!0;try{Error.captureStackTrace(this,br)}catch(e){}}}function kr(e,t){return t&&e.then((function(e){ye((function(){t(null,e)}))}),(function(e){ye((function(){t(e)}))})),e}function jr(e,t){return function(){var n=arguments,r=this;return e.add((function(){return t.apply(r,n)}))}}function qr(e){var t=new Set(e),n=new Array(t.size),r=-1;return t.forEach((function(e){n[++r]=e})),n}function Ar(e){var t=new Array(e.size),n=-1;return e.forEach((function(e,r){t[++n]=r})),t}function Or(e){return new br("builtin "+e+" function requires map values to be numbers or number arrays")}function Sr(e){for(var t=0,n=0,r=e.length;n<r;n++){var i=e[n];if("number"!=typeof i){if(!Array.isArray(i))throw Or("_sum");t="number"==typeof t?[t]:t;for(var o=0,s=i.length;o<s;o++){var a=i[o];if("number"!=typeof a)throw Or("_sum");void 0===t[o]?t.push(a):t[o]+=a}}else"number"==typeof t?t+=i:t[0]+=i}return t}var xr=we.bind(null,"log"),Er=Array.isArray,Cr=JSON.parse;function Ir(e,t){return He("return ("+e.replace(/;\s*$/,"")+");",{emit:t,sum:Sr,log:xr,isArray:Er,toJSON:Cr})}class Lr{constructor(){this.promise=Promise.resolve()}add(e){return this.promise=this.promise.catch((()=>{})).then((()=>e())),this.promise}finish(){return this.promise}}function Dr(e){if(!e)return"undefined";switch(typeof e){case"function":case"string":return e.toString();default:return JSON.stringify(e)}}async function $r(e,t,n,r,i,o){const s=function(e,t){return Dr(e)+Dr(t)+"undefined"}(n,r);let a;if(!i&&(a=e._cachedViews=e._cachedViews||{},a[s]))return a[s];const c=e.info().then((async function(c){const u=c.db_name+"-mrview-"+(i?"temp":dt(s));await Xe(e,"_local/"+o,(function(e){e.views=e.views||{};let n=t;-1===n.indexOf("/")&&(n=t+"/"+t);const r=e.views[n]=e.views[n]||{};if(!r[u])return r[u]=!0,e}));const f=(await e.registerDependentDatabase(u)).db;f.auto_compaction=!0;const l={name:u,db:f,sourceDB:e,adapter:e.adapter,mapFun:n,reduceFun:r};let d;try{d=await l.db.get("_local/lastSeq")}catch(e){if(404!==e.status)throw e}return l.seq=d?d.seq:0,a&&l.db.once("destroyed",(function(){delete a[s]})),l}));return a&&(a[s]=c),c}const Pr={},Tr=new Lr;function Br(e){return-1===e.indexOf("/")?[e,e]:e.split("/")}function Rr(e,t,n){try{e.emit("error",t)}catch(e){we("error","The user's map/reduce function threw an uncaught error.\nYou can debug this error by doing:\nmyDatabase.on('error', function (err) { debugger; });\nPlease double-check your map/reduce function."),we("error",t,n)}}var Mr=function(e,t){return Sr(t)},Nr=function(e,t){return t.length},Ur=function(e,t){return{sum:Sr(t),min:Math.min.apply(null,t),max:Math.max.apply(null,t),count:t.length,sumsqr:function(e){for(var t=0,n=0,r=e.length;n<r;n++){var i=e[n];t+=i*i}return t}(t)}};var zr=function(e,t,n,r){function i(e,t,n){try{t(n)}catch(r){Rr(e,r,{fun:t,doc:n})}}function o(e,t,n,r,i){try{return{output:t(n,r,i)}}catch(o){return Rr(e,o,{fun:t,keys:n,values:r,rereduce:i}),{error:o}}}function s(e,t){const n=sn(e.key,t.key);return 0!==n?n:sn(e.value,t.value)}function a(e,t,n){return n=n||0,"number"==typeof t?e.slice(n,t+n):n>0?e.slice(n):e}function c(e){const t=e.value;return t&&"object"==typeof t&&t._id||e.id}function u(e){return function(t){return e.include_docs&&e.attachments&&e.binary&&function(e){for(const t of e.rows){const e=t.doc&&t.doc._attachments;if(e)for(const t of Object.keys(e)){const n=e[t];e[t].data=it(n.data,n.content_type)}}}(t),t}}function f(e,t,n,r){let i=t[e];void 0!==i&&(r&&(i=encodeURIComponent(JSON.stringify(i))),n.push(e+"="+i))}function l(e){if(void 0!==e){const t=Number(e);return isNaN(t)||t!==parseInt(e,10)?e:t}}function d(e){if(e){if("number"!=typeof e)return new yr(`Invalid value for integer: "${e}"`);if(e<0)return new yr(`Invalid value for positive integer: "${e}"`)}}function h(e,t){const n=e.descending?"endkey":"startkey",r=e.descending?"startkey":"endkey";if(void 0!==e[n]&&void 0!==e[r]&&sn(e[n],e[r])>0)throw new yr("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 yr("{include_docs:true} is invalid for reduce");if(e.keys&&e.keys.length>1&&!e.group&&!e.group_level)throw new yr("Multi-key fetches for reduce views must use {group: true}")}for(const t of["group_level","limit","skip"]){const n=d(e[t]);if(n)throw n}}function p(e){return function(t){if(404===t.status)return e;throw t}}function v(e,t,n){var r="_local/lastSeq";return e.db.get(r).catch(p({_id:r,seq:0})).then((function(r){var i=Ar(t);return Promise.all(i.map((function(n){return async function(e,t,n){const r="_local/doc_"+e,i={_id:r,keys:[]},o=n.get(e),s=o[0],a=o[1],c=await(function(e){return 1===e.length&&/^1-/.test(e[0].rev)}(a)?Promise.resolve(i):t.db.get(r).catch(p(i))),u=await function(e){return e.keys.length?t.db.allDocs({keys:e.keys,include_docs:!0}):Promise.resolve({rows:[]})}(c);return function(e,t){const n=[],r=new Set;for(const e of t.rows){const t=e.doc;if(t&&(n.push(t),r.add(t._id),t._deleted=!s.has(t._id),!t._deleted)){const e=s.get(t._id);"value"in e&&(t.value=e.value)}}const i=Ar(s);for(const e of i)if(!r.has(e)){const t={_id:e},r=s.get(e);"value"in r&&(t.value=r.value),n.push(t)}return e.keys=qr(i.concat(e.keys)),n.push(e),n}(c,u)}(n,e,t)}))).then((function(t){var i=t.flat();return r.seq=n,i.push(r),e.db.bulkDocs({docs:i})})).then((()=>function(e){return e.sourceDB.get("_local/purges").then((function(t){const n=t.purgeSeq;return e.db.get("_local/purgeSeq").then((function(e){return e._rev})).catch(p(void 0)).then((function(t){return e.db.put({_id:"_local/purgeSeq",_rev:t,purgeSeq:n})}))})).catch((function(e){if(404!==e.status)throw e}))}(e)))}))}function g(e){const t="string"==typeof e?e:e.name;let n=Pr[t];return n||(n=Pr[t]=new Lr),n}async function _(e,n){return jr(g(e),(function(){return async function(e,n){let r,o,a;function c(e,t){const n={id:o._id,key:an(e)};null!=t&&(n.value=an(t)),r.push(n)}const u=t(e.mapFun,c);let f=e.seq||0;function l(){return e.sourceDB.info().then((function(t){a=e.sourceDB.activeTasks.add({name:"view_indexing",total_items:t.update_seq-f})}))}function d(t,n){return function(){return v(e,t,n)}}let h=0;const g={view:e.name,indexed_docs:h};e.sourceDB.emit("indexing",g);const _=new Lr;async function m(){return w(await e.sourceDB.changes({return_docs:!0,conflicts:!0,include_docs:!0,style:"all_docs",since:f,limit:n.changes_batch_size}),await y())}function y(){return e.db.get("_local/purgeSeq").then((function(e){return e.purgeSeq})).catch(p(-1)).then((function(t){return e.sourceDB.get("_local/purges").then((function(n){const r=n.purges.filter((function(e,n){return n>t})).map((e=>e.docId)),i=r.filter((function(e,t){return r.indexOf(e)===t}));return Promise.all(i.map((function(t){return e.sourceDB.get(t).then((function(e){return{docId:t,doc:e}})).catch(p({docId:t}))})))})).catch(p([]))}))}function w(t,r){const i=t.results;if(!i.length&&!r.length)return;for(const e of r){if(i.findIndex((function(t){return t.id===e.docId}))<0){const t={_id:e.docId,doc:{_id:e.docId,_deleted:1},changes:[]};e.doc&&(t.doc=e.doc,t.changes.push({rev:e.doc._rev})),i.push(t)}}const o=b(i);_.add(d(o,f)),h+=i.length;const s={view:e.name,last_seq:t.last_seq,results_count:i.length,indexed_docs:h};return e.sourceDB.emit("indexing",s),e.sourceDB.activeTasks.update(a,{completed_items:h}),i.length<n.changes_batch_size?void 0:m()}function b(t){const n=new Map;for(const a of t){if("_"!==a.doc._id[0]){r=[],o=a.doc,o._deleted||i(e.sourceDB,u,o),r.sort(s);const t=k(r);n.set(a.doc._id,[t,a.changes])}f=a.seq}return n}function k(e){const t=new Map;let n;for(let r=0,i=e.length;r<i;r++){const i=e[r],o=[i.key,i.id];r>0&&0===sn(i.key,n)&&o.push(r),t.set(un(o),i),n=i.key}return t}try{await l(),await m(),await _.finish(),e.seq=f,e.sourceDB.activeTasks.remove(a)}catch(t){e.sourceDB.activeTasks.remove(a,t)}}(e,n)}))()}function m(e,t){return jr(g(e),(function(){return async function(e,t){let r;const i=e.reduceFun&&!1!==t.reduce,s=t.skip||0;void 0===t.keys||t.keys.length||(t.limit=0,delete t.keys);async function u(t){t.include_docs=!0;const n=await e.db.allDocs(t);return r=n.total_rows,n.rows.map((function(e){if("value"in e.doc&&"object"==typeof e.doc.value&&null!==e.doc.value){const t=Object.keys(e.doc.value).sort(),n=["id","key","value"];if(!(t<n||t>n))return e.doc.value}const t=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=fn(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 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: "+i)}else{if(1===t.length)return t.pop();ln(t,n)}}}(e.doc._id);return{key:t[0],id:t[1],value:"value"in e.doc?e.doc.value:null}}))}async function f(u){let f;if(f=i?function(e,t,r){0===r.group_level&&delete r.group_level;const i=r.group||r.group_level,s=n(e.reduceFun),c=[],u=isNaN(r.group_level)?Number.POSITIVE_INFINITY:r.group_level;for(const e of t){const t=c[c.length-1];let n=i?e.key:null;i&&Array.isArray(n)&&(n=n.slice(0,u)),t&&0===sn(t.groupKey,n)?(t.keys.push([e.key,e.id]),t.values.push(e.value)):c.push({keys:[[e.key,e.id]],values:[e.value],groupKey:n})}t=[];for(const n of c){const r=o(e.sourceDB,s,n.keys,n.values,!1);if(r.error&&r.error instanceof br)throw r.error;t.push({value:r.error?null:r.output,key:n.groupKey})}return{rows:a(t,r.limit,r.skip)}}(e,u,t):void 0===t.keys?{total_rows:r,offset:s,rows:u}:{total_rows:r,offset:s,rows:a(u,t.limit,t.skip)},t.update_seq&&(f.update_seq=e.seq),t.include_docs){const n=qr(u.map(c)),r=await e.sourceDB.allDocs({keys:n,include_docs:!0,conflicts:t.conflicts,attachments:t.attachments,binary:t.binary}),i=new Map;for(const e of r.rows)i.set(e.id,e.doc);for(const e of u){const t=c(e),n=i.get(t);n&&(e.doc=n)}}return f}if(void 0!==t.keys){const e=t.keys.map((function(e){const n={startkey:un([e]),endkey:un([e,{}])};return t.update_seq&&(n.update_seq=!0),u(n)}));return f((await Promise.all(e)).flat())}{const e={descending:t.descending};let n,r;if(t.update_seq&&(e.update_seq=!0),"start_key"in t&&(n=t.start_key),"startkey"in t&&(n=t.startkey),"end_key"in t&&(r=t.end_key),"endkey"in t&&(r=t.endkey),void 0!==n&&(e.startkey=t.descending?un([n,{}]):un([n])),void 0!==r){let n=!1!==t.inclusive_end;t.descending&&(n=!n),e.endkey=un(n?[r,{}]:[r])}if(void 0!==t.key){const n=un([t.key]),r=un([t.key,{}]);e.descending?(e.endkey=n,e.startkey=r):(e.startkey=n,e.endkey=r)}i||("number"==typeof t.limit&&(e.limit=t.limit),e.skip=s);return f(await u(e))}}(e,t)}))()}async function y(t,n,i){if("function"==typeof t._query)return function(e,t,n){return new Promise((function(r,i){e._query(t,n,(function(e,t){if(e)return i(e);r(t)}))}))}(t,n,i);if(Fe(t))return async function(e,t,n){let r,i,o=[],s="GET";if(f("reduce",n,o),f("include_docs",n,o),f("attachments",n,o),f("limit",n,o),f("descending",n,o),f("group",n,o),f("group_level",n,o),f("skip",n,o),f("stale",n,o),f("conflicts",n,o),f("startkey",n,o,!0),f("start_key",n,o,!0),f("endkey",n,o,!0),f("end_key",n,o,!0),f("inclusive_end",n,o),f("key",n,o,!0),f("update_seq",n,o),o=o.join("&"),o=""===o?"":"?"+o,void 0!==n.keys){const e=2e3,i=`keys=${encodeURIComponent(JSON.stringify(n.keys))}`;i.length+o.length+1<=e?o+=("?"===o[0]?"&":"?")+i:(s="POST","string"==typeof t?r={keys:n.keys}:t.keys=n.keys)}if("string"==typeof t){const a=Br(t),c=await e.fetch("_design/"+a[0]+"/_view/"+a[1]+o,{headers:new Vt({"Content-Type":"application/json"}),method:s,body:JSON.stringify(r)});i=c.ok;const f=await c.json();if(!i)throw f.status=c.status,Ne(f);for(const e of f.rows)if(e.value&&e.value.error&&"builtin_reduce_error"===e.value.error)throw new Error(e.reason);return new Promise((function(e){e(f)})).then(u(n))}r=r||{};for(const e of Object.keys(t))Array.isArray(t[e])?r[e]=t[e]:r[e]=t[e].toString();const a=await e.fetch("_temp_view"+o,{headers:new Vt({"Content-Type":"application/json"}),method:"POST",body:JSON.stringify(r)});i=a.ok;const c=await a.json();if(!i)throw c.status=a.status,Ne(c);return new Promise((function(e){e(c)})).then(u(n))}(t,n,i);const o={changes_batch_size:t.__opts.view_update_changes_batch_size||50};if("string"!=typeof n)return h(i,n),Tr.add((async function(){const r=await $r(t,"temp_view/temp_view",n.map,n.reduce,!0,e);return s=_(r,o).then((function(){return m(r,i)})),a=function(){return r.db.destroy()},s.then((function(e){return a().then((function(){return e}))}),(function(e){return a().then((function(){throw e}))}));var s,a})),Tr.finish();{const s=n,a=Br(s),c=a[0],u=a[1],f=await t.get("_design/"+c);if(!(n=f.views&&f.views[u]))throw new wr(`ddoc ${f._id} has no view named ${u}`);r(f,u),h(i,n);const l=await $r(t,s,n.map,n.reduce,!1,e);return"ok"===i.stale||"update_after"===i.stale?("update_after"===i.stale&&ye((function(){_(l,o)})),m(l,i)):(await _(l,o),m(l,i))}}var w;return{query:function(e,t,n){const r=this;"function"==typeof t&&(n=t,t={}),t=t?function(e){return e.group_level=l(e.group_level),e.limit=l(e.limit),e.skip=l(e.skip),e}(t):{},"function"==typeof e&&(e={map:e});const i=Promise.resolve().then((function(){return y(r,e,t)}));return kr(i,n),i},viewCleanup:(w=function(){const t=this;return"function"==typeof t._viewCleanup?function(e){return new Promise((function(t,n){e._viewCleanup((function(e,r){if(e)return n(e);t(r)}))}))}(t):Fe(t)?async function(e){return(await e.fetch("_view_cleanup",{headers:new Vt({"Content-Type":"application/json"}),method:"POST"})).json()}(t):async function(t){try{const n=await t.get("_local/"+e),r=new Map;for(const e of Object.keys(n.views)){const t=Br(e),n="_design/"+t[0],i=t[1];let o=r.get(n);o||(o=new Set,r.set(n,o)),o.add(i)}const i={keys:Ar(r),include_docs:!0},o=await t.allDocs(i),s={};for(const e of o.rows){const t=e.key.substring(8);for(const i of r.get(e.key)){let r=t+"/"+i;n.views[r]||(r=i);const o=Object.keys(n.views[r]),a=e.doc&&e.doc.views&&e.doc.views[i];for(const e of o)s[e]=s[e]||a}}const a=Object.keys(s).filter((function(e){return!s[e]})).map((function(e){return jr(g(e),(function(){return new t.constructor(e,t.__opts).destroy()}))()}));return Promise.all(a).then((function(){return{ok:!0}}))}catch(e){if(404===e.status)return{ok:!0};throw e}}(t)},function(...e){var t=e.pop(),n=w.apply(this,e);return"function"==typeof t&&kr(n,t),n})}}("mrviews",(function(e,t){if("function"==typeof e&&2===e.length){var n=e;return function(e){return n(e,t)}}return Ir(e.toString(),t)}),(function(e){var t=e.toString(),n=function(e){if(/^_sum/.test(e))return Mr;if(/^_count/.test(e))return Nr;if(/^_stats/.test(e))return Ur;if(/^_/.test(e))throw new Error(e+" is not a supported reduce function.")}(t);return n||Ir(t)}),(function(e,t){var n=e.views&&e.views[t];if("string"!=typeof n.map)throw new wr("ddoc "+e._id+" has no string view named "+t+", instead found object of type: "+typeof n.map)}));var Fr={query:function(e,t,n){return zr.query.call(this,e,t,n)},viewCleanup:function(e){return zr.viewCleanup.call(this,e)}};function Kr(e,t){var n=Object.keys(t._attachments);return Promise.all(n.map((function(n){return e.getAttachment(t._id,n,{rev:t._rev})})))}function Jr(e,t,n,r){n=ue(n);var i=[],o=!0;return Promise.resolve().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=Fe(t)&&!Fe(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 Kr(t,n)})):Kr(t,n)}(t,e,r).then((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(e.flat().filter(Boolean))}))}))})).then((function(){return{ok:o,docs:i}}))}var Vr="pouchdb";function Gr(e,t,n,r,i){return e.get(t).catch((function(n){if(404===n.status)return"http"!==e.adapter&&"https"!==e.adapter||ke(404,"PouchDB is just checking if a remote checkpoint exists."),{session_id:r,_id:t,history:[],replicator:Vr,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=Vr,o.session_id=r,o.last_seq=n,e.put(o).catch((function(o){if(409===o.status)return Gr(e,t,n,r,i);throw o}))}))}class Qr{constructor(e,t,n,r,i={writeSourceCheckpoint:!0,writeTargetCheckpoint:!0}){this.src=e,this.target=t,this.id=n,this.returnValue=r,this.opts=i,void 0===i.writeSourceCheckpoint&&(i.writeSourceCheckpoint=!0),void 0===i.writeTargetCheckpoint&&(i.writeTargetCheckpoint=!0)}writeCheckpoint(e,t){var n=this;return this.updateTarget(e,t).then((function(){return n.updateSource(e,t)}))}updateTarget(e,t){return this.opts.writeTargetCheckpoint?Gr(this.target,this.id,e,t,this.returnValue):Promise.resolve(!0)}updateSource(e,t){if(this.opts.writeSourceCheckpoint){var n=this;return Gr(this.src,this.id,e,t,this.returnValue).catch((function(e){if(Xr(e))return n.opts.writeSourceCheckpoint=!1,!0;throw e}))}return Promise.resolve(!0)}getCheckpoint(){var e=this;return e.opts.writeSourceCheckpoint||e.opts.writeTargetCheckpoint?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 Wr?Wr[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 Xr(n)?(e.opts.writeSourceCheckpoint=!1,t.last_seq):0}));throw n}))})).catch((function(e){if(404!==e.status)throw e;return 0})):Promise.resolve(0)}}var Wr={undefined:function(e,t){return 0===sn(e.last_seq,t.last_seq)?t.last_seq:0},1:function(e,t){return function(e,t){if(e.session_id===t.session_id)return{last_seq:e.last_seq,history:e.history};return Yr(e.history,t.history)}(t,e).last_seq}};function Yr(e,t){var n=e[0],r=e.slice(1),i=t[0],o=t.slice(1);return n&&0!==t.length?Hr(n.session_id,t)?{last_seq:n.last_seq,history:e}:Hr(i.session_id,r)?{last_seq:i.last_seq,history:o}:Yr(r,o):{last_seq:0,history:[]}}function Hr(e,t){var n=t[0],r=t.slice(1);return!(!e||0===t.length)&&(e===n.session_id||Hr(e,r))}function Xr(e){return"number"==typeof e.status&&4===Math.floor(e.status/100)}function Zr(e,t,n,r,i){return this instanceof Qr?Zr:new Qr(e,t,n,r,i)}function ei(e,t,n){var r=n.doc_ids?n.doc_ids.sort(sn):"",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(sn).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){lt(t,e)}))})).then((function(e){return"_local/"+(e=e.replace(/\//g,".").replace(/\+/g,"_"))}))}function ti(e,t,n,r,i){var o,s,a,c,u=[],f={seq:0,changes:[],docs:[]},l=!1,d=!1,h=!1,p=0,v=0,g=n.continuous||n.live||!1,_=n.batch_size||100,m=n.batches_limit||10,y=n.style||"all_docs",w=!1,b=n.doc_ids,k=n.selector,j=[],q=pt();i=i||{ok:!0,start_time:(new Date).toISOString(),docs_read:0,docs_written:0,doc_write_failures:0,errors:[]};var A={};function O(){return a?Promise.resolve():ei(e,t,n).then((function(i){s=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},a=new Zr(e,t,s,r,o)}))}function S(){if(j=[],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",ue(t))}else j.push(e)}))}),(function(t){throw i.doc_write_failures+=e.length,t}))}}function x(){if(o.error)throw new Error("There was a problem getting docs.");i.last_seq=v=o.seq;var t=ue(i);return j.length&&(t.docs=j,"number"==typeof o.pending&&(t.pending=o.pending,delete o.pending),r.emit("change",t)),l=!0,e.info().then((function(t){var n=e.activeTasks.get(c);if(o&&n){var r=n.completed_items||0,i=parseInt(t.update_seq,10)-parseInt(p,10);e.activeTasks.update(c,{completed_items:r+o.changes.length,total_items:i})}})),a.writeCheckpoint(o.seq,q).then((function(){if(r.emit("checkpoint",{checkpoint:o.seq}),l=!1,r.cancelled)throw D(),new Error("cancelled");o=void 0,B()})).catch((function(e){throw N(e),e}))}function E(){return Jr(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 C(){var e;r.cancelled||o||(0!==u.length?(o=u.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(E).then(S).then(x).then(C).catch((function(e){L("batch processing terminated with error",e)}))):I(!0))}function I(e){0!==f.changes.length?(e||d||f.changes.length>=_)&&(u.push(f),f={seq:0,changes:[],docs:[]},"pending"!==r.state&&"stopped"!==r.state||(r.state="active",r.emit("active")),C()):0!==u.length||o||((g&&A.live||d)&&(r.state="pending",r.emit("paused")),d&&D())}function L(e,t){h||(t.message||(t.message=e),i.ok=!1,i.status="aborting",u=[],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=v,h=!0,e.activeTasks.remove(c,o),o){(o=Me(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=be),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(){ti(e,t,n,r)}))}else r.emit("complete",i),r.removeAllListeners()}function $(t,i,o){if(r.cancelled)return D();if("number"==typeof i&&(f.pending=i),Ue(n)(t))f.seq=t.seq||o,f.changes.push(t),r.emit("checkpoint",{pending_batch:f.seq}),ye((function(){I(0===u.length&&A.live)}));else{var s=e.activeTasks.get(c);if(s){var a=s.completed_items||0;e.activeTasks.update(c,{completed_items:++a})}}}function P(e){if(w=!1,r.cancelled)return D();if(e.results.length>0)A.since=e.results[e.results.length-1].seq,B(),I(!0);else{var t=function(){g?(A.live=!0,B()):d=!0,I(!0)};o||0!==e.results.length?t():(l=!0,a.writeCheckpoint(e.last_seq,q).then((function(){if(l=!1,i.last_seq=v=e.last_seq,r.cancelled)throw D(),new Error("cancelled");t()})).catch(N))}}function T(e){if(w=!1,r.cancelled)return D();L("changes rejected",e)}function B(){if(!w&&!d&&u.length<m){w=!0,r._changes&&(r.removeListener("cancel",r._abortChanges),r._changes.cancel()),r.once("cancel",i);var t=e.changes(A).on("change",$);t.then(o,o),t.then(P).catch(T),n.retry&&(r._changes=t,r._abortChanges=i)}function i(){t.cancel()}function o(){r.removeListener("cancel",i)}}function R(t){return e.info().then((function(r){var i=void 0===n.since?parseInt(r.update_seq,10)-parseInt(t,10):parseInt(r.update_seq,10);return c=e.activeTasks.add({name:`${g?"continuous ":""}replication from ${r.db_name}`,total_items:i}),t}))}function M(){O().then((function(){if(!r.cancelled)return a.getCheckpoint().then(R).then((function(e){p=e,A={since:v=e,limit:_,batch_size:_,style:y,doc_ids:b,selector:k,return_docs:!0},n.filter&&("string"!=typeof n.filter?A.include_docs=!0:A.filter=n.filter),"heartbeat"in n&&(A.heartbeat=n.heartbeat),"timeout"in n&&(A.timeout=n.timeout),n.query_params&&(A.query_params=n.query_params),n.view&&(A.view=n.view),B()}));D()})).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?D():(r._addedListeners||(r.once("cancel",D),"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?M():O().then((function(){return l=!0,a.writeCheckpoint(n.since,q)})).then((function(){l=!1,r.cancelled?D():(v=n.since,M())})).catch(N))}class ni extends te{constructor(){super(),this.cancelled=!1,this.state="pending";const e=new Promise(((e,t)=>{this.once("complete",e),this.once("error",t)}));this.then=function(t,n){return e.then(t,n)},this.catch=function(t){return e.catch(t)},this.catch((function(){}))}cancel(){this.cancelled=!0,this.state="cancelled",this.emit("cancel")}ready(e,t){if(this._readyCalled)return;this._readyCalled=!0;const n=()=>{this.cancel()};function r(){e.removeListener("destroyed",n),t.removeListener("destroyed",n)}e.once("destroyed",n),t.once("destroyed",n),this.once("complete",r),this.once("error",r)}}function ri(e,t){var n=t.PouchConstructor;return"string"==typeof e?new n(e,t):e}function ii(e,t,n,r){if("function"==typeof n&&(r=n,n={}),void 0===n&&(n={}),n.doc_ids&&!Array.isArray(n.doc_ids))throw Me($e,"`doc_ids` filter parameter is not a list.");n.complete=r,(n=ue(n)).continuous=n.continuous||n.live,n.retry="retry"in n&&n.retry,n.PouchConstructor=n.PouchConstructor||this;var i=new ni(n);return ti(ri(e,n),ri(t,n),n,i),i}function oi(e,t,n,r){return"function"==typeof n&&(r=n,n={}),void 0===n&&(n={}),(n=ue(n)).PouchConstructor=n.PouchConstructor||this,e=ri(e,n),t=ri(t,n),new si(e,t,n,r)}class si extends te{constructor(e,t,n,r){super(),this.canceled=!1;const i=n.push?Object.assign({},n,n.push):n,o=n.pull?Object.assign({},n,n.pull):n;this.push=ii(e,t,i),this.pull=ii(t,e,o),this.pushPaused=!0,this.pullPaused=!0;const s=e=>{this.emit("change",{direction:"pull",change:e})},a=e=>{this.emit("change",{direction:"push",change:e})},c=e=>{this.emit("denied",{direction:"push",doc:e})},u=e=>{this.emit("denied",{direction:"pull",doc:e})},f=()=>{this.pushPaused=!0,this.pullPaused&&this.emit("paused")},l=()=>{this.pullPaused=!0,this.pushPaused&&this.emit("paused")},d=()=>{this.pushPaused=!1,this.pullPaused&&this.emit("active",{direction:"push"})},h=()=>{this.pullPaused=!1,this.pushPaused&&this.emit("active",{direction:"pull"})};let p={};const v=e=>(t,n)=>{("change"===t&&(n===s||n===a)||"denied"===t&&(n===u||n===c)||"paused"===t&&(n===l||n===f)||"active"===t&&(n===h||n===d))&&(t in p||(p[t]={}),p[t][e]=!0,2===Object.keys(p[t]).length&&this.removeAllListeners(t))};function g(e,t,n){-1==e.listeners(t).indexOf(n)&&e.on(t,n)}n.live&&(this.push.on("complete",this.pull.cancel.bind(this.pull)),this.pull.on("complete",this.push.cancel.bind(this.push))),this.on("newListener",(function(e){"change"===e?(g(this.pull,"change",s),g(this.push,"change",a)):"denied"===e?(g(this.pull,"denied",u),g(this.push,"denied",c)):"active"===e?(g(this.pull,"active",h),g(this.push,"active",d)):"paused"===e&&(g(this.pull,"paused",l),g(this.push,"paused",f))})),this.on("removeListener",(function(e){"change"===e?(this.pull.removeListener("change",s),this.push.removeListener("change",a)):"denied"===e?(this.pull.removeListener("denied",u),this.push.removeListener("denied",c)):"active"===e?(this.pull.removeListener("active",h),this.push.removeListener("active",d)):"paused"===e&&(this.pull.removeListener("paused",l),this.push.removeListener("paused",f))})),this.pull.on("removeListener",v("pull")),this.push.on("removeListener",v("push"));const _=Promise.all([this.push,this.pull]).then((e=>{const t={push:e[0],pull:e[1]};return this.emit("complete",t),r&&r(null,t),this.removeAllListeners(),t}),(e=>{if(this.cancel(),r?r(e):this.emit("error",e),this.removeAllListeners(),r)throw e}));this.then=function(e,t){return _.then(e,t)},this.catch=function(e){return _.catch(e)}}cancel(){this.canceled||(this.canceled=!0,this.push.cancel(),this.pull.cancel())}}Kt.plugin((function(e){e.adapter("idb",cr,!0)})).plugin((function(e){e.adapter("http",mr,!1),e.adapter("https",mr,!1)})).plugin(Fr).plugin((function(e){e.replicate=ii,e.sync=oi,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 ai=e=>`${e.source}/${encodeURIComponent(e.actor)}/${encodeURIComponent(e.name)}`,ci=t=>{const n=t.split("/"),r=n.pop(),i=n.pop();if(!r||!i||!n.length)throw new e;return{name:decodeURIComponent(r),actor:decodeURIComponent(i),source:n.join("/")}};function ui(e=16){const t=new Uint8Array(e);crypto.getRandomValues(t);return btoa(String.fromCodePoint(...t)).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=+$/,"")}function fi(e){return"string"==typeof e?{location:ci(e),uri:e}:{location:{name:e.name,actor:e.actor,source:e.source},uri:ai(e)}}function li(e,r,i,o){const s=i[r];if(s&&s.length)try{o[r]=e(o[r],s,!0,!1).newDocument}catch(e){throw"object"==typeof e&&e&&"name"in e&&"string"==typeof e.name&&"message"in e&&"string"==typeof e.message?"TEST_OPERATION_FAILED"===e.name?new t(e.message):new n(e.name+": "+e.message):e}}function di(e,t){try{return e.compile(t)}catch(e){throw new r(e instanceof Error?e.message:void 0)}}function hi(e,t,n){e.actor!==n?.actor&&(e.allowed=e.allowed&&n?[n.actor]:void 0,e.channels=e.channels.filter((e=>t.includes(e))))}function pi(e,t){return void 0===e.allowed||!!t?.actor&&(e.actor===t.actor||e.allowed.includes(t.actor))}class vi{db;source="local";tombstoneRetention=864e5;ajv;constructor(e,t){this.ajv=t??new c({strict:!1}),this.source=e?.sourceName??this.source,this.tombstoneRetention=e?.tombstoneRetention??this.tombstoneRetention;const n={name:"graffitiDb",...e?.pouchDBOptions};this.db=new Kt(n.name,n),this.db.put({_id:"_design/index3",views:{byChannelAndLastModified:{map:function(e){const t=e.lastModified.toString().padStart(15,"0");e.channels.forEach((function(e){const n=encodeURIComponent(e)+"/"+t;emit(n)}))}.toString()}}}).catch((e=>{if(!e||"object"!=typeof e||!("name"in e)||"conflict"!==e.name)throw e}))}async queryByLocation(e){const t=ai(e)+"/";return(await this.db.allDocs({startkey:t,endkey:t+"￿",include_docs:!0})).rows.map((e=>e.doc)).reduce(((e,t)=>(t&&e.push(t),e)),[]).filter((e=>!e.tombstone))}docId(e){return ai(e)+"/"+ui()}get=async(...e)=>{const[t,n,r]=e,{location:s}=fi(t),a=await this.queryByLocation(s);if(!a.length)throw new i;const c=a.reduce(((e,t)=>e.lastModified>t.lastModified?e:t)),{_id:u,_rev:f,...l}=c;if(!pi(c,r))throw new i;hi(l,[],r);if(!di(this.ajv,n)(l))throw new o;return l};async deleteAtLocation(e,t=!1){const n=await this.queryByLocation(e);if(!n.length)return;const r=n.map((e=>e.lastModified)).reduce(((e,t)=>e>t?e:t)),i=n.filter((e=>!t||e.lastModified<r)),o=n.filter((e=>t&&e.lastModified===r));if(o.length){const e=o.map((e=>e._id)).reduce(((e,t)=>e>t?e:t)),t=o.filter((t=>t._id!==e));i.push(...t)}const s=t?r:(new Date).getTime();let a;for(const e of i.sort(((e,t)=>e.lastModified-t.lastModified))){const t={...e,tombstone:!0,lastModified:s};try{await this.db.put(t)}catch(e){if(e&&"object"==typeof e&&"name"in e&&"conflict"===e.name)continue}const{_id:n,_rev:r,...i}=t;a=i}return a}delete=async(...e)=>{const[t,n]=e,{location:r}=fi(t);if(r.actor!==n.actor)throw new s;const o=await this.deleteAtLocation(r);if(!o)throw new i;return o};put=async(...e)=>{const[t,n]=e;if(t.actor&&t.actor!==n.actor)throw new s;const r={value:t.value,channels:t.channels,allowed:t.allowed,name:t.name??ui(),source:t.source??this.source,actor:n.actor,tombstone:!1,lastModified:(new Date).getTime()};await this.db.put({_id:this.docId(r),...r});const i=await this.deleteAtLocation(r,!0);return i||{...r,value:{},channels:[],allowed:void 0,tombstone:!0}};patch=async(...e)=>{const[t,r,i]=e,{location:o}=fi(r);if(o.actor!==i.actor)throw new s;const a=await this.get(r,{},i),c={...a};for(const e of["value","channels","allowed"])li(f,e,t,c);if("object"!=typeof c.value||Array.isArray(c.value)||!c.value)throw new n("value is no longer an object");if(!Array.isArray(c.channels)||!c.channels.every((e=>"string"==typeof e)))throw new n("channels are no longer an array of strings");if(c.allowed&&(!Array.isArray(c.allowed)||!c.allowed.every((e=>"string"==typeof e))))throw new n("allowed list is not an array of strings");return c.lastModified=(new Date).getTime(),await this.db.put({...c,_id:this.docId(c)}),await this.deleteAtLocation(c,!0),{...a,tombstone:!0,lastModified:c.lastModified}};discover=(...e)=>{const[t,n,r]=e,i=di(this.ajv,n);let o="",s="￿";const a=n.properties?.lastModified;if(a?.minimum){let e=Math.ceil(a.minimum);e===a.minimum&&a.exclusiveMinimum&&e++,o=e.toString().padStart(15,"0")}if(a?.maximum){let e=Math.floor(a.maximum);e===a.maximum&&a.exclusiveMaximum&&e--,s=e.toString().padStart(15,"0")}return new u((async(e,n)=>{const a=new Set;for(const n of t){const c=encodeURIComponent(n),u=c+"/"+o,f=c+"/"+s,l=await this.db.query("index3/byChannelAndLastModified",{startkey:u,endkey:f,include_docs:!0});for(const n of l.rows){const o=n.doc;if(!o)continue;const{_id:s,_rev:c,...u}=o;a.has(s)||(a.add(s),pi(o,r)&&(hi(u,t,r),i(u)&&e({value:u})))}}return n(),{tombstoneRetention:this.tombstoneRetention}}))};listChannels=(...e)=>async function*(){}();listOrphans=(...e)=>async function*(){}()}class gi{synchronizeEvents=new EventTarget;ajv;graffiti;constructor(e,t){this.ajv=t??new c({strict:!1}),this.graffiti=e}synchronizeDispatch(e,t){const n=new CustomEvent("change",{detail:{oldObject:e,newObject:t}});this.synchronizeEvents.dispatchEvent(n)}get=async(...e)=>{const t=await this.graffiti.get(...e);return this.synchronizeDispatch(t),t};put=async(...e)=>{const t=await this.graffiti.put(...e),n=e[0],r={...t,value:n.value,channels:n.channels,allowed:n.allowed,tombstone:!1};return this.synchronizeDispatch(t,r),t};patch=async(...e)=>{const t=await this.graffiti.patch(...e),n={...t};n.tombstone=!1;for(const t of["value","channels","allowed"])li(f,t,e[0],n);return this.synchronizeDispatch(t,n),t};delete=async(...e)=>{const t=await this.graffiti.delete(...e);return this.synchronizeDispatch(t),t};discover=(...e)=>{const t=this.graffiti.discover(...e),n=this.synchronizeDispatch.bind(this);return async function*(){let e=await t.next();for(;!e.done;)e.value.error||n(e.value.value),yield e.value,e=await t.next();return e.value}()};synchronize=(...e)=>{const[t,n,r]=e,i=di(this.ajv,n);return new u((async(e,n)=>{const o=n=>{const{oldObject:o,newObject:s}=n.detail;for(const n of[s,o])if(n&&n.channels.some((e=>t.includes(e)))&&pi(n,r)){const o={...n};if(hi(o,t,r),i(o)){e({value:o});break}}};this.synchronizeEvents.addEventListener("change",o),await n,this.synchronizeEvents.removeEventListener("change",o)}))}}class _i extends a{locationToUri=ai;uriToLocation=ci;login;logout;sessionEvents;put;get;patch;delete;discover;synchronize;listChannels;listOrphans;constructor(e){super();const t=new l;this.login=t.login.bind(t),this.logout=t.logout.bind(t),this.sessionEvents=t.sessionEvents;const n=new c({strict:!1}),r=new vi(e,n),i=new gi(r,n);this.put=i.put.bind(i),this.get=i.get.bind(i),this.patch=i.patch.bind(i),this.delete=i.delete.bind(i),this.discover=i.discover.bind(i),this.synchronize=i.synchronize.bind(i),this.listChannels=r.listChannels.bind(r),this.listOrphans=r.listOrphans.bind(r)}}export{_i as GraffitiLocal};
2
+ //# sourceMappingURL=index.js.map