dexie-cloud-addon 4.2.0-alpha.1 → 4.2.0-alpha.3
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.
- package/dist/modern/dexie-cloud-addon.js +1893 -14966
- package/dist/modern/dexie-cloud-addon.js.map +1 -1
- package/dist/modern/dexie-cloud-addon.min.js +1 -1
- package/dist/modern/dexie-cloud-addon.min.js.gz +0 -0
- package/dist/modern/dexie-cloud-addon.min.js.map +1 -1
- package/dist/modern/service-worker.js +1969 -15042
- package/dist/modern/service-worker.js.map +1 -1
- package/dist/modern/service-worker.min.js +1 -1
- package/dist/modern/service-worker.min.js.map +1 -1
- package/dist/modern/yjs/reopenDocSignal.d.ts +2 -2
- package/dist/umd/dexie-cloud-addon.js +200 -1677
- package/dist/umd/dexie-cloud-addon.js.gz +0 -0
- package/dist/umd/dexie-cloud-addon.js.map +1 -1
- package/dist/umd/dexie-cloud-addon.min.js +1 -1
- package/dist/umd/dexie-cloud-addon.min.js.gz +0 -0
- package/dist/umd/dexie-cloud-addon.min.js.map +1 -1
- package/dist/umd/service-worker.js +61 -1538
- package/dist/umd/service-worker.js.map +1 -1
- package/dist/umd/service-worker.min.js +1 -1
- package/dist/umd/service-worker.min.js.map +1 -1
- package/dist/umd/yjs/reopenDocSignal.d.ts +2 -2
- package/package.json +3 -3
- package/dist/modern/helpers/dbOnClosed.d.ts +0 -2
- package/dist/modern/yjs/Y.d.ts +0 -3
- package/dist/modern/yjs/importDexieYProvider.d.ts +0 -1
- package/dist/umd/helpers/dbOnClosed.d.ts +0 -2
- package/dist/umd/yjs/Y.d.ts +0 -3
- package/dist/umd/yjs/importDexieYProvider.d.ts +0 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("dexie"),require("rxjs")):"function"==typeof define&&define.amd?define(["exports","dexie","rxjs"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).DexieCloud={},e.Dexie,e.rxjs)}(this,(function(e,t,n){"use strict";var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},r(e,t)};function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}r(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}function s(e,t,n,r){return new(n||(n=Promise))((function(i,s){function o(e){try{l(r.next(e))}catch(e){s(e)}}function c(e){try{l(r.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,c)}l((r=r.apply(e,t||[])).next())}))}function o(e,t){var n,r,i,s,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return s={next:c(0),throw:c(1),return:c(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function c(s){return function(c){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,r&&(i=2&s[0]?r.return:s[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,s[1])).done)return i;switch(r=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,r=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!(i=o.trys,(i=i.length>0&&i[i.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!i||s[1]>i[0]&&s[1]<i[3])){o.label=s[1];break}if(6===s[0]&&o.label<i[1]){o.label=i[1],i=s;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(s);break}i[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],r=0}finally{n=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}}function c(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function l(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,i,s=n.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(r=s.next()).done;)o.push(r.value)}catch(e){i={error:e}}finally{try{r&&!r.done&&(n=s.return)&&n.call(s)}finally{if(i)throw i.error}}return o}function a(e,t,n){if(n||2===arguments.length)for(var r,i=0,s=t.length;i<s;i++)!r&&i in t||(r||(r=Array.prototype.slice.call(t,0,i)),r[i]=t[i]);return e.concat(r||Array.prototype.slice.call(t))}function u(e){return this instanceof u?(this.v=e,this):new u(e)}function d(e,t,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r,i=n.apply(e,t||[]),s=[];return r={},o("next"),o("throw"),o("return"),r[Symbol.asyncIterator]=function(){return this},r;function o(e){i[e]&&(r[e]=function(t){return new Promise((function(n,r){s.push([e,t,n,r])>1||c(e,t)}))})}function c(e,t){try{!function(e){e.value instanceof u?Promise.resolve(e.value.v).then(l,a):d(s[0][2],e)}(i[e](t))}catch(e){d(s[0][3],e)}}function l(e){c("next",e)}function a(e){c("throw",e)}function d(e,t){e(t),s.shift(),s.length&&c(s[0][0],s[0][1])}}function h(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,n=e[Symbol.asyncIterator];return n?n.call(e):(e=c(e),t={},r("next"),r("throw"),r("return"),t[Symbol.asyncIterator]=function(){return this},t);function r(n){t[n]=e[n]&&function(t){return new Promise((function(r,i){(function(e,t,n,r){Promise.resolve(r).then((function(t){e({value:t,done:n})}),t)})(r,i,(t=e[n](t)).done,t.value)}))}}}const f={}.hasOwnProperty;function p(e,t,n){if(e&&void 0!==t&&(!("isFrozen"in Object)||!Object.isFrozen(e)))if("string"!=typeof t&&"length"in t){!function(e){if(!e)throw new Error("Assertion Failed")}("string"!=typeof n&&"length"in n);for(var r=0,i=t.length;r<i;++r)p(e,t[r],n[r])}else{var s=t.indexOf(".");if(-1!==s){var o=t.substr(0,s),c=t.substr(s+1);if(""===c)void 0===n?Array.isArray(e)?isNaN(parseInt(o))||e.splice(parseInt(o),1):delete e[o]:e[o]=n;else{var l=e[o];l&&function(e,t){return f.call(e,t)}(e,o)||(l=e[o]={}),p(l,c,n)}}else void 0===n?Array.isArray(e)&&!isNaN(parseInt(t))?e.splice(t,1):delete e[t]:e[t]=n}}const g="undefined"!=typeof self&&"undefined"!=typeof crypto?(e,t=crypto.getRandomValues.bind(crypto))=>{const n=new Uint8Array(e);return t(n),self.btoa(String.fromCharCode.apply(null,n))}:"undefined"!=typeof Buffer?(e,t=y)=>{const n=Buffer.alloc(e);return t(n),n.toString("base64")}:()=>{throw new Error("No implementation of randomString was found")};function y(e){for(let t=0;t<e.length;++t)e[t]=Math.floor(256*Math.random())}function v(e){return"string"==typeof e||!!(Array.isArray(e)&&e.some((e=>v(e)))&&e.every(m))}function m(e){return"string"==typeof e||"number"==typeof e||Array.isArray(e)&&e.every(m)}function b(e,t,n){const r=e[t]||(e[t]={}),i=n.keys.map((e=>"string"==typeof e?e:JSON.stringify(e)));switch(n.type){case"insert":case"upsert":i.forEach(((e,t)=>{r[e]={type:"ups",val:n.values[t]}}));break;case"update":case"modify":i.forEach(((e,t)=>{const i="update"===n.type?n.changeSpecs[t]:n.changeSpec,s=r[e];if(s)switch(s.type){case"ups":for(const[e,t]of Object.entries(i))p(s.val,e,t);break;case"del":break;case"upd":Object.assign(s.mod,i)}else r[e]={type:"upd",mod:i}}));break;case"delete":i.forEach((e=>{r[e]={type:"del"}}))}return e}function w(e,t){for(const{table:n,muts:r}of t)for(const t of r)b(e,n,t)}const _=Math.floor,k=Math.abs,S=(e,t)=>e>t?e:t,E=128,x=127,I=Number.MAX_SAFE_INTEGER,C=Number.isInteger||(e=>"number"==typeof e&&isFinite(e)&&_(e)===e),A=Array.isArray,O="undefined"!=typeof TextEncoder?new TextEncoder:null,D=O?e=>O.encode(e):e=>{const t=unescape(encodeURIComponent(e)),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.codePointAt(e);return r};let T="undefined"==typeof TextDecoder?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});T&&1===T.decode(new Uint8Array).length&&(T=null);let U=class{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}};const j=(e,t)=>{const n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(2*n),e.cpos=0),e.cbuf[e.cpos++]=t},P=(e,t)=>{for(;t>x;)j(e,E|x&t),t=_(t/128);j(e,x&t)},L=new Uint8Array(3e4),R=L.length/3,N=O&&O.encodeInto?(e,t)=>{if(t.length<R){const n=O.encodeInto(t,L).written||0;P(e,n);for(let t=0;t<n;t++)j(e,L[t])}else $(e,D(t))}:(e,t)=>{const n=unescape(encodeURIComponent(t)),r=n.length;P(e,r);for(let t=0;t<r;t++)j(e,n.codePointAt(t))},$=(e,t)=>{P(e,t.byteLength),((e,t)=>{const n=e.cbuf.length,r=e.cpos,i=((e,t)=>e<t?e:t)(n-r,t.length),s=t.length-i;e.cbuf.set(t.subarray(0,i),r),e.cpos+=i,s>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(S(2*n,s)),e.cbuf.set(t.subarray(i)),e.cpos=s)})(e,t)},M=(e,t)=>{((e,t)=>{const n=e.cbuf.length;n-e.cpos<t&&(e.bufs.push(new Uint8Array(e.cbuf.buffer,0,e.cpos)),e.cbuf=new Uint8Array(2*S(n,t)),e.cpos=0)})(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},B=(e,t)=>M(e,8).setBigUint64(0,t,!1),F=new DataView(new ArrayBuffer(4)),W=(e,t)=>{switch(typeof t){case"string":j(e,119),N(e,t);break;case"number":C(t)&&k(t)<=2147483647?(j(e,125),((e,t)=>{const n=(e=>0!==e?e<0:1/e<0)(t);for(n&&(t=-t),j(e,(t>63?E:0)|(n?64:0)|63&t),t=_(t/64);t>0;)j(e,(t>x?E:0)|x&t),t=_(t/128)})(e,t)):(n=t,F.setFloat32(0,n),F.getFloat32(0)===n?(j(e,124),((e,t)=>{M(e,4).setFloat32(0,t,!1)})(e,t)):(j(e,123),((e,t)=>{M(e,8).setFloat64(0,t,!1)})(e,t)));break;case"bigint":j(e,122),((e,t)=>{M(e,8).setBigInt64(0,t,!1)})(e,t);break;case"object":if(null===t)j(e,126);else if(A(t)){j(e,117),P(e,t.length);for(let n=0;n<t.length;n++)W(e,t[n])}else if(t instanceof Uint8Array)j(e,116),$(e,t);else{j(e,118);const n=Object.keys(t);P(e,n.length);for(let r=0;r<n.length;r++){const i=n[r];N(e,i),W(e,t[i])}}break;case"boolean":j(e,t?120:121);break;default:j(e,127)}var n};function V(e){const t=new U;switch(N(t,e.type),"table"in e&&N(t,e.table),"prop"in e&&N(t,e.prop),e.type){case"u-ack":case"u-reject":B(t,BigInt(e.i));break;case"outdated-server-rev":break;case"y-complete-sync-done":N(t,e.yServerRev);break;default:switch(W(t,e.k),e.type){case"aware":$(t,e.u);break;case"doc-open":W(t,e.serverRev),W(t,e.sv);break;case"doc-close":break;case"sv":$(t,e.sv);break;case"u-c":$(t,e.u),B(t,BigInt(e.i));break;case"u-s":$(t,e.u),N(t,e.r||"")}}return(e=>{const t=new Uint8Array((e=>{let t=e.cpos;for(let n=0;n<e.bufs.length;n++)t+=e.bufs[n].length;return t})(e));let n=0;for(let r=0;r<e.bufs.length;r++){const i=e.bufs[r];t.set(i,n),n+=i.length}return t.set(new Uint8Array(e.cbuf.buffer,0,e.cpos),n),t})(t)}const K=e=>new Error(e),H=K("Unexpected end of array"),z=K("Integer out of Range");let J=class{constructor(e){this.arr=e,this.pos=0}};const q=e=>e.pos!==e.arr.length,Y=e=>((e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n})(e,Q(e)),G=e=>e.arr[e.pos++],Q=e=>{let t=0,n=1;const r=e.arr.length;for(;e.pos<r;){const r=e.arr[e.pos++];if(t+=(r&x)*n,n*=128,r<E)return t;if(t>I)throw z}throw H},X=T?e=>T.decode(Y(e)):e=>{let t=Q(e);if(0===t)return"";{let n=String.fromCodePoint(G(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(G(e));else for(;t>0;){const r=t<1e4?t:1e4,i=e.arr.subarray(e.pos,e.pos+r);e.pos+=r,n+=String.fromCodePoint.apply(null,i),t-=r}return decodeURIComponent(escape(n))}},Z=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},ee=e=>Z(e,8).getBigUint64(0,!1),te=[e=>{},e=>null,e=>{let t=e.arr[e.pos++],n=63&t,r=64;const i=(64&t)>0?-1:1;if(0==(t&E))return i*n;const s=e.arr.length;for(;e.pos<s;){if(t=e.arr[e.pos++],n+=(t&x)*r,r*=128,t<E)return i*n;if(n>I)throw z}throw H},e=>Z(e,4).getFloat32(0,!1),e=>Z(e,8).getFloat64(0,!1),e=>Z(e,8).getBigInt64(0,!1),e=>!1,e=>!0,X,e=>{const t=Q(e),n={};for(let r=0;r<t;r++){n[X(e)]=ne(e)}return n},e=>{const t=Q(e),n=[];for(let r=0;r<t;r++)n.push(ne(e));return n},Y],ne=e=>te[127-G(e)](e);function re(e){return d(this,arguments,(function*(){var t,n,r,i;let s=0,o=new Uint8Array(4),c=0,l=[],a=0;try{for(var d,f=!0,p=h(e);!(t=(d=yield u(p.next())).done);f=!0){i=d.value,f=!1;const e=i,t=new DataView(e.buffer,e.byteOffset,e.byteLength);let n=0;for(;n<e.byteLength;)switch(s){case 0:if(n+4>e.byteLength){for(const t of e.slice(n)){if(4===c)break;o[c++]=t,++n}if(c<4)break}else if(c>0&&c<4)for(const t of e.slice(n,n+4-c))o[c++]=t,++n;case 1:a=4===c?new DataView(o.buffer,0,4).getUint32(0,!1):t.getUint32(n,!1),c?c=0:n+=4;case 2:if(n>=e.byteLength){s=2;break}if(n+a>e.byteLength)l.push(e.slice(n)),a-=e.byteLength-n,s=2,n=e.byteLength;else{if(l.length>0){const t=new Uint8Array(l.reduce(((e,t)=>e+t.byteLength),a));let r=0;for(const e of l)t.set(e,r),r+=e.byteLength;t.set(e.slice(n,n+a),r),l=[],yield yield u(t)}else yield yield u(e.slice(n,n+a));n+=a,s=0}}}}catch(e){n={error:e}}finally{try{f||t||!(r=p.return)||(yield u(r.call(p)))}finally{if(n)throw n.error}}}))}function ie(e){return"function"==typeof e}function se(e){return function(t){if(function(e){return ie(null==e?void 0:e.lift)}(t))return t.lift((function(t){try{return e(t,this)}catch(e){this.error(e)}}));throw new TypeError("Unable to lift unknown Observable type")}}var oe=function(e){return e&&"number"==typeof e.length&&"function"!=typeof e};function ce(e){return ie(null==e?void 0:e.then)}var le,ae,ue=(le=function(e){return function(t){e(this),this.message=t?t.length+" errors occurred during unsubscription:\n"+t.map((function(e,t){return t+1+") "+e.toString()})).join("\n "):"",this.name="UnsubscriptionError",this.errors=t}},(ae=le((function(e){Error.call(e),e.stack=(new Error).stack}))).prototype=Object.create(Error.prototype),ae.prototype.constructor=ae,ae);function de(e,t){if(e){var n=e.indexOf(t);0<=n&&e.splice(n,1)}}var he=function(){function e(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}var t;return e.prototype.unsubscribe=function(){var e,t,n,r,i;if(!this.closed){this.closed=!0;var s=this._parentage;if(s)if(this._parentage=null,Array.isArray(s))try{for(var o=c(s),u=o.next();!u.done;u=o.next()){u.value.remove(this)}}catch(t){e={error:t}}finally{try{u&&!u.done&&(t=o.return)&&t.call(o)}finally{if(e)throw e.error}}else s.remove(this);var d=this.initialTeardown;if(ie(d))try{d()}catch(e){i=e instanceof ue?e.errors:[e]}var h=this._finalizers;if(h){this._finalizers=null;try{for(var f=c(h),p=f.next();!p.done;p=f.next()){var g=p.value;try{pe(g)}catch(e){i=null!=i?i:[],e instanceof ue?i=a(a([],l(i)),l(e.errors)):i.push(e)}}}catch(e){n={error:e}}finally{try{p&&!p.done&&(r=f.return)&&r.call(f)}finally{if(n)throw n.error}}}if(i)throw new ue(i)}},e.prototype.add=function(t){var n;if(t&&t!==this)if(this.closed)pe(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=null!==(n=this._finalizers)&&void 0!==n?n:[]).push(t)}},e.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},e.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},e.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&de(t,e)},e.prototype.remove=function(t){var n=this._finalizers;n&&de(n,t),t instanceof e&&t._removeParent(this)},e.EMPTY=((t=new e).closed=!0,t),e}();function fe(e){return e instanceof he||e&&"closed"in e&&ie(e.remove)&&ie(e.add)&&ie(e.unsubscribe)}function pe(e){ie(e)?e():e.unsubscribe()}he.EMPTY;var ge={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},ye={setTimeout:function(e,t){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];var i=ye.delegate;return(null==i?void 0:i.setTimeout)?i.setTimeout.apply(i,a([e,t],l(n))):setTimeout.apply(void 0,a([e,t],l(n)))},clearTimeout:function(e){var t=ye.delegate;return((null==t?void 0:t.clearTimeout)||clearTimeout)(e)},delegate:void 0};function ve(e){ye.setTimeout((function(){throw e}))}function me(){}var be=function(e){function t(t){var n=e.call(this)||this;return n.isStopped=!1,t?(n.destination=t,fe(t)&&t.add(n)):n.destination=xe,n}return i(t,e),t.create=function(e,t,n){return new Se(e,t,n)},t.prototype.next=function(e){this.isStopped||this._next(e)},t.prototype.error=function(e){this.isStopped||(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,e.prototype.unsubscribe.call(this),this.destination=null)},t.prototype._next=function(e){this.destination.next(e)},t.prototype._error=function(e){try{this.destination.error(e)}finally{this.unsubscribe()}},t.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},t}(he),we=Function.prototype.bind;function _e(e,t){return we.call(e,t)}var ke=function(){function e(e){this.partialObserver=e}return e.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(e){Ee(e)}},e.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(e){Ee(e)}else Ee(e)},e.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(e){Ee(e)}},e}(),Se=function(e){function t(t,n,r){var i,s,o=e.call(this)||this;ie(t)||!t?i={next:null!=t?t:void 0,error:null!=n?n:void 0,complete:null!=r?r:void 0}:o&&ge.useDeprecatedNextContext?((s=Object.create(t)).unsubscribe=function(){return o.unsubscribe()},i={next:t.next&&_e(t.next,s),error:t.error&&_e(t.error,s),complete:t.complete&&_e(t.complete,s)}):i=t;return o.destination=new ke(i),o}return i(t,e),t}(be);function Ee(e){ve(e)}var xe={closed:!0,next:me,error:function(e){throw e},complete:me},Ie="function"==typeof Symbol&&Symbol.observable||"@@observable";function Ce(e){return e}var Ae=function(){function e(e){e&&(this._subscribe=e)}return e.prototype.lift=function(t){var n=new e;return n.source=this,n.operator=t,n},e.prototype.subscribe=function(e,t,n){var r,i=this,s=(r=e)&&r instanceof be||function(e){return e&&ie(e.next)&&ie(e.error)&&ie(e.complete)}(r)&&fe(r)?e:new Se(e,t,n);return function(){var e=i,t=e.operator,n=e.source;s.add(t?t.call(s,n):n?i._subscribe(s):i._trySubscribe(s))}(),s},e.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},e.prototype.forEach=function(e,t){var n=this;return new(t=Oe(t))((function(t,r){var i=new Se({next:function(t){try{e(t)}catch(e){r(e),i.unsubscribe()}},error:r,complete:t});n.subscribe(i)}))},e.prototype._subscribe=function(e){var t;return null===(t=this.source)||void 0===t?void 0:t.subscribe(e)},e.prototype[Ie]=function(){return this},e.prototype.pipe=function(){for(var e,t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return(0===(e=t).length?Ce:1===e.length?e[0]:function(t){return e.reduce((function(e,t){return t(e)}),t)})(this)},e.prototype.toPromise=function(e){var t=this;return new(e=Oe(e))((function(e,n){var r;t.subscribe((function(e){return r=e}),(function(e){return n(e)}),(function(){return e(r)}))}))},e.create=function(t){return new e(t)},e}();function Oe(e){var t;return null!==(t=null!=e?e:ge.Promise)&&void 0!==t?t:Promise}function De(e){return ie(e[Ie])}function Te(e){return Symbol.asyncIterator&&ie(null==e?void 0:e[Symbol.asyncIterator])}function Ue(e){return new TypeError("You provided "+(null!==e&&"object"==typeof e?"an invalid object":"'"+e+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}var je="function"==typeof Symbol&&Symbol.iterator?Symbol.iterator:"@@iterator";function Pe(e){return ie(null==e?void 0:e[je])}function Le(e){return d(this,arguments,(function(){var t,n,r;return o(this,(function(i){switch(i.label){case 0:t=e.getReader(),i.label=1;case 1:i.trys.push([1,,9,10]),i.label=2;case 2:return[4,u(t.read())];case 3:return n=i.sent(),r=n.value,n.done?[4,u(void 0)]:[3,5];case 4:return[2,i.sent()];case 5:return[4,u(r)];case 6:return[4,i.sent()];case 7:return i.sent(),[3,2];case 8:return[3,10];case 9:return t.releaseLock(),[7];case 10:return[2]}}))}))}function Re(e){return ie(null==e?void 0:e.getReader)}function Ne(e){if(e instanceof Ae)return e;if(null!=e){if(De(e))return i=e,new Ae((function(e){var t=i[Ie]();if(ie(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")}));if(oe(e))return r=e,new Ae((function(e){for(var t=0;t<r.length&&!e.closed;t++)e.next(r[t]);e.complete()}));if(ce(e))return n=e,new Ae((function(e){n.then((function(t){e.closed||(e.next(t),e.complete())}),(function(t){return e.error(t)})).then(null,ve)}));if(Te(e))return $e(e);if(Pe(e))return t=e,new Ae((function(e){var n,r;try{for(var i=c(t),s=i.next();!s.done;s=i.next()){var o=s.value;if(e.next(o),e.closed)return}}catch(e){n={error:e}}finally{try{s&&!s.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}e.complete()}));if(Re(e))return $e(Le(e))}var t,n,r,i;throw Ue(e)}function $e(e){return new Ae((function(t){(function(e,t){var n,r,i,c;return s(this,void 0,void 0,(function(){var s,l;return o(this,(function(o){switch(o.label){case 0:o.trys.push([0,5,6,11]),n=h(e),o.label=1;case 1:return[4,n.next()];case 2:if((r=o.sent()).done)return[3,4];if(s=r.value,t.next(s),t.closed)return[2];o.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return l=o.sent(),i={error:l},[3,11];case 6:return o.trys.push([6,,9,10]),r&&!r.done&&(c=n.return)?[4,c.call(n)]:[3,8];case 7:o.sent(),o.label=8;case 8:return[3,10];case 9:if(i)throw i.error;return[7];case 10:return[7];case 11:return t.complete(),[2]}}))}))})(e,t).catch((function(e){return t.error(e)}))}))}function Me(e,t,n,r,i){return new Be(e,t,n,r,i)}var Be=function(e){function t(t,n,r,i,s,o){var c=e.call(this,t)||this;return c.onFinalize=s,c.shouldUnsubscribe=o,c._next=n?function(e){try{n(e)}catch(e){t.error(e)}}:e.prototype._next,c._error=i?function(e){try{i(e)}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._error,c._complete=r?function(){try{r()}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._complete,c}return i(t,e),t.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var n=this.closed;e.prototype.unsubscribe.call(this),!n&&(null===(t=this.onFinalize)||void 0===t||t.call(this))}},t}(be),Fe=function(e){function t(t,n){return e.call(this)||this}return i(t,e),t.prototype.schedule=function(e,t){return this},t}(he),We={setInterval:function(e,t){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];var i=We.delegate;return(null==i?void 0:i.setInterval)?i.setInterval.apply(i,a([e,t],l(n))):setInterval.apply(void 0,a([e,t],l(n)))},clearInterval:function(e){var t=We.delegate;return((null==t?void 0:t.clearInterval)||clearInterval)(e)},delegate:void 0},Ve=function(e){function t(t,n){var r=e.call(this,t,n)||this;return r.scheduler=t,r.work=n,r.pending=!1,r}return i(t,e),t.prototype.schedule=function(e,t){if(void 0===t&&(t=0),this.closed)return this;this.state=e;var n=this.id,r=this.scheduler;return null!=n&&(this.id=this.recycleAsyncId(r,n,t)),this.pending=!0,this.delay=t,this.id=this.id||this.requestAsyncId(r,this.id,t),this},t.prototype.requestAsyncId=function(e,t,n){return void 0===n&&(n=0),We.setInterval(e.flush.bind(e,this),n)},t.prototype.recycleAsyncId=function(e,t,n){if(void 0===n&&(n=0),null!=n&&this.delay===n&&!1===this.pending)return t;We.clearInterval(t)},t.prototype.execute=function(e,t){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var n=this._execute(e,t);if(n)return n;!1===this.pending&&null!=this.id&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},t.prototype._execute=function(e,t){var n,r=!1;try{this.work(e)}catch(e){r=!0,n=e||new Error("Scheduled action threw falsy error")}if(r)return this.unsubscribe(),n},t.prototype.unsubscribe=function(){if(!this.closed){var t=this.id,n=this.scheduler,r=n.actions;this.work=this.state=this.scheduler=null,this.pending=!1,de(r,this),null!=t&&(this.id=this.recycleAsyncId(n,t,null)),this.delay=null,e.prototype.unsubscribe.call(this)}},t}(Fe),Ke={now:function(){return(Ke.delegate||Date).now()},delegate:void 0},He=function(){function e(t,n){void 0===n&&(n=e.now),this.schedulerActionCtor=t,this.now=n}return e.prototype.schedule=function(e,t,n){return void 0===t&&(t=0),new this.schedulerActionCtor(this,e).schedule(n,t)},e.now=Ke.now,e}(),ze=new(function(e){function t(t,n){void 0===n&&(n=He.now);var r=e.call(this,t,n)||this;return r.actions=[],r._active=!1,r._scheduled=void 0,r}return i(t,e),t.prototype.flush=function(e){var t=this.actions;if(this._active)t.push(e);else{var n;this._active=!0;do{if(n=e.execute(e.state,e.delay))break}while(e=t.shift());if(this._active=!1,n){for(;e=t.shift();)e.unsubscribe();throw n}}},t}(He))(Ve),Je=ze;function qe(e){return e&&ie(e.schedule)}function Ye(e,t,n){void 0===e&&(e=0),void 0===n&&(n=Je);var r=-1;return null!=t&&(qe(t)?n=t:r=t),new Ae((function(t){var i,s=(i=e)instanceof Date&&!isNaN(i)?+e-n.now():e;s<0&&(s=0);var o=0;return n.schedule((function(){t.closed||(t.next(o++),0<=r?this.schedule(void 0,r):t.complete())}),s)}))}function Ge(e){return qe((t=e)[t.length-1])?e.pop():void 0;var t}function Qe(e,t,n,r,i){void 0===r&&(r=0),void 0===i&&(i=!1);var s=t.schedule((function(){n(),i?e.add(this.schedule(null,r)):this.unsubscribe()}),r);if(e.add(s),!i)return s}function Xe(e){return se((function(t,n){var r,i=null,s=!1;i=t.subscribe(Me(n,void 0,void 0,(function(o){r=Ne(e(o,Xe(e)(t))),i?(i.unsubscribe(),i=null,r.subscribe(n)):s=!0}))),s&&(i.unsubscribe(),i=null,r.subscribe(n))}))}function Ze(e,t){return void 0===t&&(t=0),se((function(n,r){n.subscribe(Me(r,(function(n){return Qe(r,e,(function(){return r.next(n)}),t)}),(function(){return Qe(r,e,(function(){return r.complete()}),t)}),(function(n){return Qe(r,e,(function(){return r.error(n)}),t)})))}))}function et(e,t){return void 0===t&&(t=0),se((function(n,r){r.add(e.schedule((function(){return n.subscribe(r)}),t))}))}function tt(e,t){if(!e)throw new Error("Iterable cannot be null");return new Ae((function(n){Qe(n,t,(function(){var r=e[Symbol.asyncIterator]();Qe(n,t,(function(){r.next().then((function(e){e.done?n.complete():n.next(e.value)}))}),0,!0)}))}))}function nt(e,t){if(null!=e){if(De(e))return function(e,t){return Ne(e).pipe(et(t),Ze(t))}(e,t);if(oe(e))return function(e,t){return new Ae((function(n){var r=0;return t.schedule((function(){r===e.length?n.complete():(n.next(e[r++]),n.closed||this.schedule())}))}))}(e,t);if(ce(e))return function(e,t){return Ne(e).pipe(et(t),Ze(t))}(e,t);if(Te(e))return tt(e,t);if(Pe(e))return function(e,t){return new Ae((function(n){var r;return Qe(n,t,(function(){r=e[je](),Qe(n,t,(function(){var e,t,i;try{t=(e=r.next()).value,i=e.done}catch(e){return void n.error(e)}i?n.complete():n.next(t)}),0,!0)})),function(){return ie(null==r?void 0:r.return)&&r.return()}}))}(e,t);if(Re(e))return function(e,t){return tt(Le(e),t)}(e,t)}throw Ue(e)}function rt(e,t){return se((function(n,r){var i=0;n.subscribe(Me(r,(function(n){r.next(e.call(t,n,i++))})))}))}function it(e,t,n){return void 0===n&&(n=1/0),ie(t)?it((function(n,r){return rt((function(e,i){return t(n,e,r,i)}))(Ne(e(n,r)))}),n):("number"==typeof t&&(n=t),se((function(t,r){return function(e,t,n,r,i,s,o,c){var l=[],a=0,u=0,d=!1,h=function(){!d||l.length||a||t.complete()},f=function(e){return a<r?p(e):l.push(e)},p=function(e){s&&t.next(e),a++;var c=!1;Ne(n(e,u++)).subscribe(Me(t,(function(e){null==i||i(e),s?f(e):t.next(e)}),(function(){c=!0}),void 0,(function(){if(c)try{a--;for(var e=function(){var e=l.shift();o?Qe(t,o,(function(){return p(e)})):p(e)};l.length&&a<r;)e();h()}catch(e){t.error(e)}})))};return e.subscribe(Me(t,f,(function(){d=!0,h()}))),function(){null==c||c()}}(t,r,e,n)})))}function st(){return void 0===(e=1)&&(e=1/0),it(Ce,e);var e}function ot(e,t){return void 0===t&&(t=ze),se((function(n,r){var i=null,s=null,o=null,c=function(){if(i){i.unsubscribe(),i=null;var e=s;s=null,r.next(e)}};function l(){var n=o+e,s=t.now();if(s<n)return i=this.schedule(void 0,n-s),void r.add(i);c()}n.subscribe(Me(r,(function(n){s=n,o=t.now(),i||(i=t.schedule(l,e),r.add(i))}),(function(){c(),r.complete()}),void 0,(function(){s=i=null})))}))}function ct(){for(var e,t,n=[],r=0;r<arguments.length;r++)n[r]=arguments[r];return st()((e=n,(t=Ge(n))?nt(e,t):Ne(e)))}var lt=new Ae((function(e){return e.complete()}));function at(e){return e<=0?function(){return lt}:se((function(t,n){var r=0;t.subscribe(Me(n,(function(t){++r<=e&&(n.next(t),e<=r&&n.complete())})))}))}function ut(e,t){return t?function(n){return ct(t.pipe(at(1),se((function(e,t){e.subscribe(Me(t,me))}))),n.pipe(ut(e)))}:it((function(t,n){return e(t,n).pipe(at(1),function(e){return rt((function(){return e}))}(t))}))}function dt(e,t){void 0===t&&(t=ze);var n=Ye(e,t);return ut((function(){return n}))}function ht(e,t){return void 0===t&&(t=Ce),e=null!=e?e:ft,se((function(n,r){var i,s=!0;n.subscribe(Me(r,(function(n){var o=t(n);!s&&e(i,o)||(s=!1,i=o,r.next(n))})))}))}function ft(e,t){return e===t}function pt(e,t){return se((function(n,r){var i=0;n.subscribe(Me(r,(function(n){return e.call(t,n,i++)&&r.next(n)})))}))}function gt(e){return pt((function(t,n){return e<=n}))}function yt(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=Ge(e);return se((function(t,r){(n?ct(e,t,n):ct(e,t)).subscribe(r)}))}function vt(e,t){return se((function(n,r){var i=null,s=0,o=!1,c=function(){return o&&!i&&r.complete()};n.subscribe(Me(r,(function(n){null==i||i.unsubscribe();var o=0,l=s++;Ne(e(n,l)).subscribe(i=Me(r,(function(e){return r.next(t?t(n,e,l,o++):e)}),(function(){i=null,c()})))}),(function(){o=!0,c()})))}))}function mt(e,t,n){var r=ie(e)||t||n?{next:e,error:t,complete:n}:e;return r?se((function(e,t){var n;null===(n=r.subscribe)||void 0===n||n.call(r);var i=!0;e.subscribe(Me(t,(function(e){var n;null===(n=r.next)||void 0===n||n.call(r,e),t.next(e)}),(function(){var e;i=!1,null===(e=r.complete)||void 0===e||e.call(r),t.complete()}),(function(e){var n;i=!1,null===(n=r.error)||void 0===n||n.call(r,e),t.error(e)}),(function(){var e,t;i&&(null===(e=r.unsubscribe)||void 0===e||e.call(r)),null===(t=r.finalize)||void 0===t||t.call(r)})))})):Ce}let bt=!1;function wt(e,t){return s(this,void 0,void 0,(function*(){try{const n=yield navigator.serviceWorker.ready;if("push"===t&&n.sync&&(yield n.sync.register(`dexie-cloud:${e.name}`)),!n.active)throw new Error("Failed to trigger sync - there's no active service worker");return void n.active.postMessage({type:"dexie-cloud-sync",dbName:e.name,purpose:t})}catch(e){bt||(bt=!0)}}))}function _t(e,t){e.cloud.usingServiceWorker?wt(e,t):e.localSyncEvent.next({purpose:t})}const kt="fromBase64"in Uint8Array,St="toBase64"in Uint8Array.prototype,Et="undefined"!=typeof Buffer?e=>Buffer.from(e,"base64"):kt?e=>Uint8Array.fromBase64(e):e=>{const t=atob(e),n=t.length,r=new Uint8Array(n);for(var i=0;i<n;i++)r[i]=t.charCodeAt(i);return r},xt="undefined"!=typeof Buffer?e=>ArrayBuffer.isView(e)?Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"):Buffer.from(e).toString("base64"):St?e=>(ArrayBuffer.isView(e)?e:new Uint8Array(e)).toBase64():e=>{const t=ArrayBuffer.isView(e)?e:new Uint8Array(e),n=[];for(let e=0,r=t.length;e<r;e+=4096){const r=t.subarray(e,e+4096);n.push(String.fromCharCode.apply(null,r))}return btoa(n.join(""))};class It extends Error{constructor({title:e,message:t,messageCode:n,messageParams:r}){super(t),this.name="TokenErrorResponseError",this.title=e,this.messageCode=n,this.messageParams=r}}function Ct(e,n){return new Promise(((r,i)=>{const s=Object.assign(Object.assign({submitLabel:"Submit",cancelLabel:"Cancel"},n),{onSubmit:t=>{e.next(void 0),r(t)},onCancel:()=>{e.next(void 0),i(new t.AbortError("User cancelled"))}});e.next(s)}))}function At(e,t,...n){return Ct(e,{type:"message-alert",title:t,alerts:n,fields:{},submitLabel:"OK",cancelLabel:null})}function Ot(e,t,n){return s(this,void 0,void 0,(function*(){let r=n||"";for(;!r||!/^[\w-+.]+@([\w-]+\.)+[\w-]{2,10}(\sas\s[\w-+.]+@([\w-]+\.)+[\w-]{2,10})?$/.test(r);)r=(yield Ct(e,{type:"email",title:t,alerts:r?[{type:"error",messageCode:"INVALID_EMAIL",message:"Please enter a valid email address",messageParams:{}}]:[],fields:{email:{type:"email",placeholder:"you@somedomain.com"}}})).email;return r}))}function Dt(e,t,n){return s(this,void 0,void 0,(function*(){const r=[{type:"info",messageCode:"OTP_SENT",message:"A One-Time password has been sent to {email}",messageParams:{email:t}}];n&&r.push(n);const{otp:i}=yield Ct(e,{type:"otp",title:"Enter OTP",alerts:r,fields:{otp:{type:"otp",label:"OTP",placeholder:"Paste OTP here"}}});return i}))}function Tt(e){return s(this,void 0,void 0,(function*(){var t,n,r;const i=yield e.getCurrentUser(),{accessToken:s,accessTokenExpiration:o,refreshToken:c,refreshTokenExpiration:l,claims:a}=i;if(!s)return null;if((null!==(t=null==o?void 0:o.getTime())&&void 0!==t?t:1/0)>Date.now()&&"ok"===((null===(n=i.license)||void 0===n?void 0:n.status)||"ok"))return i;if(!c)throw new Error("Refresh token missing");if((null!==(r=null==l?void 0:l.getTime())&&void 0!==r?r:1/0)<=Date.now())throw new Error("Refresh token has expired");const u=yield jt(e.cloud.options.databaseUrl,i);return yield e.table("$logins").update(a.sub,{accessToken:u.accessToken,accessTokenExpiration:u.accessTokenExpiration,claims:u.claims,license:u.license,data:u.data}),u}))}function Ut(e,n,r,i,o){return s(this,void 0,void 0,(function*(){return n.accessToken&&n.accessTokenExpiration.getTime()>Date.now()?n:n.refreshToken&&(!n.refreshTokenExpiration||n.refreshTokenExpiration.getTime()>Date.now())?yield jt(e,n):yield function(e,n,r,i){return s(this,void 0,void 0,(function*(){if(!crypto.subtle)throw"undefined"!=typeof location&&"http:"===location.protocol?new Error("Dexie Cloud Addon needs to use WebCrypto, but your browser has disabled it due to being served from an insecure location. Please serve it from https or http://localhost:<port> (See https://stackoverflow.com/questions/46670556/how-to-enable-crypto-subtle-for-unsecure-origins-in-chrome/46671627#46671627)"):new Error("This browser does not support WebCrypto.");const{privateKey:s,publicKey:o}=yield crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:2048,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!1,["sign","verify"]);if(!s||!o)throw new Error("Could not generate RSA keypair");e.nonExportablePrivateKey=s;const c=function(e){const t=xt(e);return function(e){let t="-----BEGIN PUBLIC KEY-----\n";for(;e.length>0;)t+=e.substring(0,64)+"\n",e=e.substring(64);return t+="-----END PUBLIC KEY-----",t}(t)}(yield crypto.subtle.exportKey("spki",o));e.publicKey=o;try{const t=yield n({public_key:c,hints:i});if("error"===t.type)throw new It(t);if("tokens"!==t.type)throw new Error(`Unexpected response type from token endpoint: ${t.type}`);return e.accessToken=t.accessToken,e.accessTokenExpiration=new Date(t.accessTokenExpiration),e.refreshToken=t.refreshToken,t.refreshTokenExpiration&&(e.refreshTokenExpiration=new Date(t.refreshTokenExpiration)),e.userId=t.claims.sub,e.email=t.claims.email,e.name=t.claims.name,e.claims=t.claims,e.license={type:t.userType,status:t.claims.license||"ok"},e.data=t.data,null!=t.evalDaysLeft&&(e.license.evalDaysLeft=t.evalDaysLeft),null!=t.userValidUntil&&(e.license.validUntil=new Date(t.userValidUntil)),t.alerts&&t.alerts.length>0&&(yield Ct(r,{type:"message-alert",title:"Authentication Alert",fields:{},alerts:t.alerts})),e}catch(e){if(e instanceof It)throw yield At(r,e.title,{type:"error",messageCode:e.messageCode,message:e.message,messageParams:{}}),e;let n="We're having a problem authenticating right now.";if(e instanceof TypeError){n=void 0!==typeof navigator&&!navigator.onLine?"You seem to be offline. Please connect to the internet and try again.":t.debug||"undefined"!=typeof location&&("localhost"===location.hostname||"127.0.0.1"===location.hostname)?`Could not connect to server. Please verify that your origin '${location.origin}' is whitelisted using \`npx dexie-cloud whitelist\``:"Could not connect to server. Please verify the connection.",yield At(r,"Authentication Failed",{type:"error",messageCode:"GENERIC_ERROR",message:n,messageParams:{}}).catch((()=>{}))}throw e}}))}(n,r,i,o)}))}function jt(e,t){return s(this,void 0,void 0,(function*(){if(!t.refreshToken)throw new Error("Cannot refresh token - refresh token is missing.");if(!t.nonExportablePrivateKey)throw new Error("login.nonExportablePrivateKey is missing - cannot sign refresh token without a private key.");const n=Date.now(),r="RSASSA-PKCS1-v1_5",i=(new TextEncoder).encode(t.refreshToken+n),s=yield crypto.subtle.sign(r,t.nonExportablePrivateKey,i),o=xt(s),c={grant_type:"refresh_token",refresh_token:t.refreshToken,scopes:["ACCESS_DB"],signature:o,signing_algorithm:r,time_stamp:n},l=yield fetch(`${e}/token`,{body:JSON.stringify(c),method:"post",headers:{"Content-Type":"application/json"},mode:"cors"});if(200!==l.status)throw new Error(`RefreshToken: Status ${l.status} from ${e}/token`);const a=yield l.json();if("error"===a.type)throw new It(a);return t.accessToken=a.accessToken,t.accessTokenExpiration=a.accessTokenExpiration?new Date(a.accessTokenExpiration):void 0,t.claims=a.claims,t.license={type:a.userType,status:a.claims.license||"ok"},null!=a.evalDaysLeft&&(t.license.evalDaysLeft=a.evalDaysLeft),null!=a.userValidUntil&&(t.license.validUntil=new Date(a.userValidUntil)),a.data&&(t.data=a.data),t}))}const Pt=new WeakMap;class Lt{constructor(e,t){Pt.set(this,e),Object.assign(this,t)}static load(e,t){return e.table("$logins").get(t).then((n=>new Lt(e,n||{userId:t,claims:{sub:t},lastLogin:new Date(0)})))}save(){return s(this,void 0,void 0,(function*(){Pt.get(this).table("$logins").put(this)}))}}const Rt={userId:"unauthorized",name:"Unauthorized",claims:{sub:"unauthorized"},lastLogin:new Date(0)};try{Object.freeze(Rt),Object.freeze(Rt.claims)}catch(e){}function Nt(e,t){return n.firstValueFrom(n.from(e).pipe(n.filter(t)))}function $t(e){return s(this,void 0,void 0,(function*(){const t=yield Mt(e);if(t){if(!(yield function(e,t,n){return s(this,void 0,void 0,(function*(){const r=[{type:"warning",messageCode:"LOGOUT_CONFIRMATION",message:"{numUnsyncedChanges} unsynced changes will get lost!\n Logout anyway?",messageParams:{currentUserId:t,numUnsyncedChanges:n.toString()}}];return yield Ct(e,{type:"logout-confirmation",title:"Confirm Logout",alerts:r,fields:{},submitLabel:"Confirm logout",cancelLabel:"Cancel"}).then((()=>!0)).catch((()=>!1))}))}(e.cloud.userInteraction,e.cloud.currentUserId,t)))throw new Error("User cancelled logout due to unsynced changes");yield Mt(e,{deleteUnsyncedData:!0})}}))}function Mt(e){return s(this,arguments,void 0,(function*(e,{deleteUnsyncedData:t=!1}={}){const[n,r]=yield e.dx.transaction("rw",e.dx.tables,(n=>s(this,void 0,void 0,(function*(){const r=n.idbtrans;r.disableChangeTracking=!0,r.disableAccessControl=!0;const i=n.storeNames.filter((e=>e.endsWith("_mutations"))),s=(yield Promise.all(i.map((e=>n.table(e).count())))).reduce(((e,t)=>e+t),0);if(s>0&&!t)return[s,!1];e.$syncState.delete("syncState");for(const t of e.dx.tables)"$jobs"!==t.name&&"$syncState"!==t.name&&t.clear();return[s,!0]}))));return r&&(yield Nt(e.cloud.currentUser,(e=>e.userId===Rt.userId)),yield e.cloud.sync({purpose:"pull",wait:!0})),n}))}class Bt extends Error{constructor(e,t){super(t||`${e.status} ${e.statusText}`),this.httpStatus=e.status}get name(){return"HttpError"}}function Ft(e,...t){globalThis.console[e](...t)}function Wt(e,t){return s(this,void 0,void 0,(function*(){var n;const r=yield e.getCurrentUser(),i=r.userId;if(r.isLoggedIn&&(!t||!t.email&&!t.userId)){if("ok"===((null===(n=r.license)||void 0===n?void 0:n.status)||"ok")&&r.accessToken&&(!r.accessTokenExpiration||r.accessTokenExpiration.getTime()>Date.now()))return!1;if(r.refreshToken&&(!r.refreshTokenExpiration||r.refreshTokenExpiration.getTime()>Date.now()))return yield Tt(e),!1}const o=new Lt(e,{claims:{},lastLogin:new Date(0)});return yield Ut(e.cloud.options.databaseUrl,o,e.cloud.options.fetchTokens||function(e){const{userInteraction:t}=e.cloud;return function(n){return s(this,arguments,void 0,(function*({public_key:n,hints:r}){var i;let s;const o=null===(i=e.cloud.options)||void 0===i?void 0:i.databaseUrl;if(!o)throw new Error("No database URL given.");if("demo"===(null==r?void 0:r.grant_type))s={demo_user:yield Ot(t,"Enter a demo user email",(null==r?void 0:r.email)||(null==r?void 0:r.userId)),grant_type:"demo",scopes:["ACCESS_DB"],public_key:n};else if((null==r?void 0:r.otpId)&&r.otp)s={grant_type:"otp",otp_id:r.otpId,otp:r.otp,scopes:["ACCESS_DB"],public_key:n};else{const e=yield Ot(t,"Enter email address",null==r?void 0:r.email);s=/@demo.local$/.test(e)?{demo_user:e,grant_type:"demo",scopes:["ACCESS_DB"],public_key:n}:{email:e,grant_type:"otp",scopes:["ACCESS_DB"]}}const c=yield fetch(`${o}/token`,{body:JSON.stringify(s),method:"post",headers:{"Content-Type":"application/json",mode:"cors"}});if(200!==c.status){const e=yield c.text();throw yield At(t,"Token request failed",{type:"error",messageCode:"GENERIC_ERROR",message:e,messageParams:{}}).catch((()=>{})),new Bt(c,e)}const l=yield c.json();if("tokens"===l.type||"error"===l.type)return l;if("otp"===s.grant_type&&"email"in s){if("otp-sent"!==l.type)throw new Error(`Unexpected response from ${o}/token`);const e=yield Dt(t,s.email),r=Object.assign(Object.assign({},s),{otp:e||"",otp_id:l.otp_id,public_key:n});let i=yield fetch(`${o}/token`,{body:JSON.stringify(r),method:"post",headers:{"Content-Type":"application/json"},mode:"cors"});for(;401===i.status;){const e=yield i.text();r.otp=yield Dt(t,s.email,{type:"error",messageCode:"INVALID_OTP",message:e,messageParams:{}}),i=yield fetch(`${o}/token`,{body:JSON.stringify(r),method:"post",headers:{"Content-Type":"application/json"},mode:"cors"})}if(200!==i.status){const e=yield i.text();throw new Bt(i,e)}return yield i.json()}throw new Error(`Unexpected response from ${o}/token`)}))}}(e),e.cloud.userInteraction,t),i!==Rt.userId&&o.userId!==i&&(yield $t(e)),yield function(e,t){return s(this,void 0,void 0,(function*(){const n=e.table("$logins");yield e.transaction("rw",n,(e=>s(this,void 0,void 0,(function*(){const e=yield n.toArray();yield Promise.all(e.filter((e=>e.userId!==t.userId&&e.isLoggedIn)).map((e=>(e.isLoggedIn=!1,n.put(e))))),t.isLoggedIn=!0,t.lastLogin=new Date;try{yield t.save()}catch(e){try{"DataCloneError"===e.name&&(Ft("debug","Login context property names:",Object.keys(t)),Ft("debug","Login context property names:",Object.keys(t)),Ft("debug","Login context:",t),Ft("debug","Login context JSON:",JSON.stringify(t)))}catch(e){}throw e}})))),yield Nt(e.cloud.currentUser,(e=>e.userId===t.userId))}))}(e,o),_t(e,"pull"),o.userId!==i}))}const Vt={},Kt="undefined"!=typeof self&&self.document&&"undefined"!=typeof navigator&&navigator.serviceWorker;Kt&&Kt.ready.then((e=>Vt.registration=e)),"undefined"!=typeof self&&"clients"in self&&!self.document&&addEventListener("message",(e=>{var t,n;(null===(n=null===(t=e.data)||void 0===t?void 0:t.type)||void 0===n?void 0:n.startsWith("sw-broadcast-"))&&[...self.clients.matchAll({includeUncontrolled:!0})].forEach((t=>{var n;return t.id!==(null===(n=e.source)||void 0===n?void 0:n.id)&&t.postMessage(e.data)}))}));class Ht{constructor(e){this.name=e}subscribe(e){if(!Kt)return()=>{};const t=t=>{var n;(null===(n=t.data)||void 0===n?void 0:n.type)===`sw-broadcast-${this.name}`&&e(t.data.message)};return Kt.addEventListener("message",t),()=>Kt.removeEventListener("message",t)}postMessage(e){var t;"object"==typeof self.clients?[...self.clients.matchAll({includeUncontrolled:!0})].forEach((t=>t.postMessage({type:`sw-broadcast-${this.name}`,message:e}))):Vt.registration&&(null===(t=Vt.registration.active)||void 0===t||t.postMessage({type:`sw-broadcast-${this.name}`,message:e}))}}const zt=globalThis["lbc-events"]||(globalThis["lbc-events"]=new Map);class Jt extends n.Observable{constructor(e){const t="undefined"==typeof BroadcastChannel?new Ht(e):new BroadcastChannel(e);super((n=>{function r(e){n.next(e.detail)}function i(e){n.next(e.data)}let s;!function(e,t){zt.has(e)?zt.get(e).push(t):zt.set(e,[t])}(`lbc-${e}`,r);try{t instanceof Ht?s=t.subscribe((e=>n.next(e))):t.addEventListener("message",i)}catch(e){}return()=>{!function(e,t){const n=zt.get(e);if(n){const e=n.indexOf(t);-1!==e&&n.splice(e,1)}}(`lbc-${e}`,r),t instanceof Ht?s():t.removeEventListener("message",i)}})),this.name=e,this.bc=t}next(e){this.bc.postMessage(e);!function(e){const t=zt.get(e.type);t&&t.forEach((t=>{try{t(e)}catch(e){}}))}(new CustomEvent(`lbc-${this.name}`,{detail:e}))}}function qt(e){return s(this,arguments,void 0,(function*({realms:e,inviteRealms:t}){const n=JSON.stringify([...e.map((e=>({realmId:e,accepted:!0}))),...t.map((e=>({realmId:e,accepted:!1})))].sort(((e,t)=>e.realmId<t.realmId?-1:e.realmId>t.realmId?1:0))),r=(new TextEncoder).encode(n),i=yield crypto.subtle.digest("SHA-1",r);return xt(i)}))}function Yt(e){return Object.entries(e.cloud.schema||{}).filter((([,{markedForSync:e}])=>e)).map((([t])=>e.tables.filter((({name:e})=>e===t))[0])).filter((e=>e))}function Gt(e){return`$${e}_mutations`}function Qt(e){var t;const n=null===(t=/^\$(.*)_mutations$/.exec(e))||void 0===t?void 0:t[1];if(!n)throw new Error(`Given mutationTable ${e} is not correct`);return n}const Xt=[].concat;function Zt(e){return Xt.apply([],e)}function en(e,t){return s(this,arguments,void 0,(function*(e,t,{since:n={},limit:r=1/0}={}){const i=Zt(yield Promise.all(e.map((e=>s(this,void 0,void 0,(function*(){const t=Qt(e.name),i=n[t];let s=i?e.where("rev").above(i):e;r<1/0&&(s=s.limit(r));return(yield s.toArray()).map((e=>({table:t,mut:e})))})))))).sort(((e,t)=>e.mut.txid===t.mut.txid?e.mut.opNo-t.mut.opNo:e.mut.ts-t.mut.ts)),o=[];let c=null,l=null;for(const{table:e,mut:t}of i)c&&c.table===e&&l===t.txid?c.muts.push(t):(c={table:e,muts:[t]},l=t.txid,o.push(c));return o}))}function tn(e){const t=new Uint8Array(e);if("undefined"!=typeof crypto)crypto.getRandomValues(t);else for(let n=0;n<e;n++)t[n]=Math.floor(256*Math.random());if("undefined"!=typeof Buffer&&Buffer.from)return Buffer.from(t).toString("base64");if("undefined"!=typeof btoa)return btoa(String.fromCharCode.apply(null,t));throw new Error("No btoa or Buffer available")}const{toString:nn}={};const rn={replace:function(e){const t=Object.keys(e);let n=null;for(let e=0,r=t.length;e<r;++e)"$"===t[e][0]&&(n=n||[],n.push(t[e]));if(!n)return e;const r={...e};for(const e of n)delete r[e];for(const t of n)r["$"+t]=e[t];return r}};function sn(...e){const t=e.reduce(((e,t)=>({...e,...t})),e.reduce(((e,t)=>({...t,...e})),{})),n=new WeakMap;return{stringify(e,r,i){const s=JSON.stringify(e,(function(e){const i=this[e],s=function(e){const r=typeof e;switch(typeof e){case"object":case"function":{if(null===e)return null;const r=Object.getPrototypeOf(e);if(!r)return rn;let s=n.get(r);if(void 0!==s)return s;const o=(i=e,nn.call(i).slice(8,-1)),c=Object.entries(t).find((([t,n])=>{var r,i;return null!==(i=null===(r=null==n?void 0:n.test)||void 0===r?void 0:r.call(n,e,o))&&void 0!==i?i:t===o}));return s=null==c?void 0:c[1],s||(s=Array.isArray(e)?null:"function"==typeof e?t.function||null:rn),n.set(r,s),s}default:return t[r]}var i}(i);return s?s.replace(i,r,t):i}),i);return s},parse(e,n){const r=[];return JSON.parse(e,(function(e,i){const s=null==i?void 0:i.$t;if(s){const e=t[s];i=e?e.revive(i,n,t):i}let o=r[r.length-1];if(o&&o[0]===i){i={...i};for(const e of o[1])delete i[e];for(const[e,t]of Object.entries(o[2]))i[e]=t;r.pop()}if(void 0===i||"$"===e[0]&&"$t"!==e){let t,n;o=r[r.length-1],o&&o[0]===this?(t=o[1],n=o[2]):r.push([this,t=[],n={}]),"$"===e[0]&&"$t"!==e?(t.push(e),n[e.substr(1)]=i):n[e]=void 0}return i}))}}}const on={Blob:{test:(e,t)=>"Blob"===t,replace:(e,t)=>{const n=t.length;return t.push(e),{$t:"Blob",mimeType:e.type,i:n}},revive:({i:e,mimeType:t},n)=>new Blob([n[e]],{type:t})}};var cn={number:{replace:e=>{switch(!0){case isNaN(e):return{$t:"number",v:"NaN"};case e===1/0:return{$t:"number",v:"Infinity"};case e===-1/0:return{$t:"number",v:"-Infinity"};default:return e}},revive:({v:e})=>Number(e)}};const ln={bigint:{replace:e=>({$t:"bigint",v:""+e}),revive:e=>BigInt(e.v)}};var an={Date:{replace:e=>({$t:"Date",v:isNaN(e.getTime())?"NaN":e.toISOString()}),revive:({v:e})=>new Date("NaN"===e?NaN:Date.parse(e))}},un={Set:{replace:e=>({$t:"Set",v:Array.from(e.entries())}),revive:({v:e})=>new Set(e)}},dn={Map:{replace:e=>({$t:"Map",v:Array.from(e.entries())}),revive:({v:e})=>new Map(e)}};const hn="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof global?global:void 0;var fn=["Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","DataView","BigInt64Array","BigUint64Array"].reduce(((e,t)=>({...e,[t]:{replace:(e,n,r)=>({$t:t,v:r.ArrayBuffer.replace(0===e.byteOffset&&e.byteLength===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),n,r).v}),revive:({v:e},n,r)=>{const i=hn[t];return i&&new i(r.ArrayBuffer.revive({v:e},n,r))}}})),{});function pn(e){return function(e){for(var t="",n=0,r=e.length;n<r;n++)t+=vn[e[n]];return t}(xt(e))}function gn(e){return Et(function(e){if("string"!=typeof e)throw new Error("invalid decoder input: "+e);for(var t="",n=0,r=e.length;n<r;n++)t+=yn[e[n]];return t}(e))}const yn={"-":"=",0:"A",1:"B",2:"C",3:"D",4:"E",5:"F",6:"G",7:"H",8:"I",9:"J",A:"K",B:"L",C:"M",D:"N",E:"O",F:"P",G:"Q",H:"R",I:"S",J:"T",K:"U",L:"V",M:"W",N:"X",O:"Y",P:"Z",Q:"a",R:"b",S:"c",T:"d",U:"e",V:"f",W:"g",X:"h",Y:"i",Z:"j",_:"k",a:"l",b:"m",c:"n",d:"o",e:"p",f:"q",g:"r",h:"s",i:"t",j:"u",k:"v",l:"w",m:"x",n:"y",o:"z",p:"0",q:"1",r:"2",s:"3",t:"4",u:"5",v:"6",w:"7",x:"8",y:"9",z:"+","|":"/"},vn={};for(const e of Object.keys(yn))vn[yn[e]]=e;var mn={ArrayBuffer:{replace:e=>({$t:"ArrayBuffer",v:pn(e)}),revive:({v:e})=>{const t=gn(e);return t.buffer.byteLength===t.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}}};class bn{constructor(e,t){this.buf=e,this.type=t}}function wn(e){const t=new XMLHttpRequest;if(t.overrideMimeType("text/plain; charset=x-user-defined"),t.open("GET",URL.createObjectURL(e),!1),t.send(),200!==t.status&&0!==t.status)throw new Error("Bad Blob access: "+t.status);return t.responseText}function _n(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t[n]=e.charCodeAt(n);return t.buffer}var kn={Blob:{test:(e,t)=>"Blob"===t||e instanceof bn,replace:e=>({$t:"Blob",v:xt(e instanceof bn?e.buf:_n(wn(e))),type:e.type}),revive:({type:e,v:t})=>{const n=Et(t);return void 0!==typeof Blob?new Blob([n]):new bn(n.buffer,e)}}};const Sn={...cn,...ln,...an,...un,...dn,...fn,...mn,...kn};function En(e){return new Promise(((t,n)=>{const r=new FileReader;r.onabort=e=>n(new Error("file read aborted")),r.onerror=e=>n(e.target.error),r.onload=e=>t(e.target.result),r.readAsArrayBuffer(e)}))}var xn={undefined:{replace:()=>({$t:"undefined"}),revive:()=>{}}},In={File:{test:(e,t)=>"File"===t,replace:e=>({$t:"File",v:xt(_n(wn(e))),type:e.type,name:e.name,lastModified:new Date(e.lastModified).toISOString()}),revive:({type:e,v:t,name:n,lastModified:r})=>{const i=Et(t);return new File([i],n,{type:e,lastModified:new Date(r).getTime()})}}};const Cn="function"==typeof BigInt&&"bigint"==typeof BigInt(0);class An{toString(){return this.v}constructor(e){this.v=e}}const On=Cn?{}:{bigint:{test:e=>e instanceof An,replace:e=>Object.assign({$t:"bigint"},e),revive:({v:e})=>new An(e)}},Dn=Object.assign(Object.assign(Object.assign(Object.assign({},xn),On),In),{PropModification:{test:e=>e instanceof t.PropModification,replace:e=>Object.assign({$t:"PropModification"},e["@@propmod"]),revive:e=>{var n=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]])}return n}(e,["$t"]);return new t.PropModification(n)}}}),Tn=sn(Sn,Dn),Un=function(...e){const t=sn(Sn,on,...e);return{toBinary(e){const[t,n]=this.stringify(e),r=new ArrayBuffer(4);return new DataView(r).setUint32(0,t.size),new Blob([r,t,n])},stringify(e){const n=[],r=t.stringify(e,n),i=new Blob(n.map((e=>{const t=new ArrayBuffer(4);return new DataView(t).setUint32(0,"byteLength"in e?e.byteLength:e.size),new Blob([t,e])})));return[i,r]},async parse(e,n){let r=0;const i=[],s=await En(n),o=new DataView(s);for(;r<s.byteLength;){const e=o.getUint32(r);r+=4;const t=s.slice(r,r+e);r+=e,i.push(t)}return t.parse(e,i)},async fromBinary(e){const t=new DataView(await En(e.slice(0,4))).getUint32(0),n=e.slice(4,t+4),r=await function(e){return new Promise(((t,n)=>{const r=new FileReader;r.onabort=e=>n(new Error("file read aborted")),r.onerror=e=>n(e.target.error),r.onload=e=>t(e.target.result),r.readAsText(e)}))}(e.slice(t+4));return await this.parse(r,n)}}}(Dn);function jn(e,n,r){const i=[];for(let s of r){const{table:r,muts:o}=s,c=e.tables.find((e=>e.name===r));if(!c)throw new Error(`Internal error: table ${r} not found in DBCore schema`);const{primaryKey:l}=c;let a=s;o.forEach(((e,r)=>{const i=!l.outbound&&("upsert"===e.type||"insert"===e.type);e.keys.forEach(((e,o)=>{if(Array.isArray(e)){a===s&&(a=Pn(s,i));const t=a.muts[r],n=JSON.stringify(e);t.keys[o]=n}else if("#"===e[0]){a===s&&(a=Pn(s,i));const c=a.muts[r];if(!n.isLoggedIn)throw new Error("Internal error: Cannot sync private IDs before authenticated");const u=`${e}:${n.userId}`;c.keys[o]=u,i&&t.setByKeyPath(c.values[o],l.keyPath,u)}}))})),i.push(a)}return i}function Pn(e,t){return Object.assign(Object.assign({},e),{muts:t?e.muts.map((e=>"insert"!==e.type&&"upsert"!==e.type||!e.values?Object.assign(Object.assign({},e),{keys:e.keys.slice()}):Object.assign(Object.assign({},e),{keys:e.keys.slice(),values:e.values.slice()}))):e.muts.map((e=>Object.assign(Object.assign({},e),{keys:e.keys.slice()})))})}let Ln=new WeakMap;function Rn(e){return s(this,void 0,void 0,(function*(){var t,n;const r=(null!==(n=null===(t=Ln.get(e))||void 0===t?void 0:t.getTime())&&void 0!==n?n:0)-Date.now();r>0&&(yield new Promise((e=>setTimeout(e,r))))}))}function Nn(e,t,n,r,i,o,c,l,a){return s(this,void 0,void 0,(function*(){const s={Accept:"application/json, application/x-bison, application/x-bison-stream","Content-Type":"application/tson"},u=yield Tt(i),d=null==u?void 0:u.accessToken;d&&(s.Authorization=`Bearer ${d}`);const h={v:2,dbID:null==n?void 0:n.remoteDbId,clientIdentity:l,schema:c||{},lastPull:n?{serverRevision:n.serverRevision,yServerRevision:n.yServerRevision,realms:n.realms,inviteRealms:n.inviteRealms}:void 0,baseRevs:r,changes:jn(i.dx.core.schema,a,e),y:t,dxcv:i.cloud.version};i.syncStateChangedEvent.next({phase:"pushing"});const f=Tn.stringify(h),p=yield fetch(`${o}/sync`,{method:"post",headers:s,credentials:"include",body:f});if(i.syncStateChangedEvent.next({phase:"pulling"}),function(e,t){const n=t.headers.get("Ratelimit-Limit"),r=t.headers.get("Ratelimit-Remaining"),i=t.headers.get("Ratelimit-Reset");if(n&&r&&i){const t=Number(n),s=Math.max(0,Number(r)),o=Number(i);if(s<t/2){const t=Math.ceil(o/(s+1));Ln.set(e,new Date(Date.now()+1e3*t))}else Ln.delete(e)}}(i,p),!p.ok)throw new Bt(p);if("application/x-bison"===p.headers.get("content-type"))return Un.fromBinary(yield p.blob());{const e=yield p.text();return Tn.parse(e)}}))}function $n(e){if(null==e?void 0:e.cancelled)throw new t.AbortError("Operation was cancelled")}let Mn=!1;function Bn(e,t,n,r){return s(this,void 0,void 0,(function*(){yield e.$baseRevs.bulkPut(Object.keys(t).filter((e=>t[e].markedForSync)).map((e=>({tableName:e,clientRev:(n[e]||0)+1,serverRev:r})))),yield e.$baseRevs.where("tableName").noneOf(Object.keys(t).filter((e=>t[e].markedForSync))).delete()}))}function Fn(e,t={}){for(const{table:n,muts:r}of e){const e=r.length>0?r[r.length-1].rev:null;t[n]=e||t[n]||0}return t}function Wn(e,n,r){return s(this,void 0,void 0,(function*(){const i=yield e.bulkGet(n),s=[],o=[];n.forEach(((n,c)=>{const l=i[c];if(l){for(const[i,s]of Object.entries(r[c]))if(i===e.schema.primKey.keyPath){if(0!==t.cmp(s,n))throw new Error("Cannot change primary key")}else t.setByKeyPath(l,i,s);s.push(n),o.push(l)}})),yield null==e.schema.primKey.keyPath?e.bulkPut(o,s):e.bulkPut(o)}))}function Vn(e,n){return s(this,void 0,void 0,(function*(){for(const{table:r,muts:i}of e){if(!n.dx._allTables[r])continue;const e=n.table(r),{primaryKey:s}=e.core.schema,o=e=>{switch(e[0]){case"[":if(e.endsWith("]"))try{return JSON.parse(e)}catch(e){}return e;case"#":return e.endsWith(":"+n.cloud.currentUserId)?e.substr(0,e.length-n.cloud.currentUserId.length-1):e;default:return e}};for(const n of i){const r=n.keys.map(o);switch(n.type){case"insert":s.outbound?yield e.bulkAdd(n.values,r):(r.forEach(((e,r)=>{t.setByKeyPath(n.values[r],s.keyPath,e)})),yield e.bulkAdd(n.values));break;case"upsert":s.outbound?yield e.bulkPut(n.values,r):(r.forEach(((e,r)=>{t.setByKeyPath(n.values[r],s.keyPath,e)})),yield e.bulkPut(n.values));break;case"modify":1===r.length?yield e.update(r[0],n.changeSpec):yield e.where(":id").anyOf(r).modify(n.changeSpec);break;case"update":yield Wn(e,r,n.changeSpecs);break;case"delete":yield e.bulkDelete(r)}}}}))}"undefined"!=typeof self&&"undefined"!=typeof navigator&&(Mn=navigator.onLine,self.addEventListener("online",(()=>Mn=!0)),self.addEventListener("offline",(()=>Mn=!1)));const Kn="dexie-cloud-syncer";function Hn(e,t){return e.where("i").between(t,1/0,!0).toArray()}const zn=()=>new Map,Jn=e=>{const t=zn();return e.forEach(((e,n)=>{t.set(n,e)})),t},qn=(e,t,n)=>{let r=e.get(t);return void 0===r&&e.set(t,r=n()),r},Yn=()=>new Set,Gn=e=>e[e.length-1],Qn=(e,t)=>{for(let n=0;n<t.length;n++)e.push(t[n])},Xn=Array.from,Zn=Array.isArray;class er{constructor(){this._observers=zn()}on(e,t){return qn(this._observers,e,Yn).add(t),t}once(e,t){const n=(...r)=>{this.off(e,n),t(...r)};this.on(e,n)}off(e,t){const n=this._observers.get(e);void 0!==n&&(n.delete(t),0===n.size&&this._observers.delete(e))}emit(e,t){return Xn((this._observers.get(e)||zn()).values()).forEach((e=>e(...t)))}destroy(){this._observers=zn()}}const tr=Math.floor,nr=Math.abs,rr=(e,t)=>e<t?e:t,ir=(e,t)=>e>t?e:t,sr=e=>0!==e?e<0:1/e<0,or=64,cr=128,lr=127,ar=Number.MAX_SAFE_INTEGER,ur=Number.isInteger||(e=>"number"==typeof e&&isFinite(e)&&tr(e)===e),dr=/^\s*/g,hr=/([A-Z])/g,fr=(e,t)=>(e=>e.replace(dr,""))(e.replace(hr,(e=>`${t}${(e=>e.toLowerCase())(e)}`))),pr="undefined"!=typeof TextEncoder?new TextEncoder:null,gr=pr?e=>pr.encode(e):e=>{const t=unescape(encodeURIComponent(e)),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.codePointAt(e);return r};let yr="undefined"==typeof TextDecoder?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});yr&&1===yr.decode(new Uint8Array).length&&(yr=null);class vr{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const mr=()=>new vr,br=e=>{const t=new Uint8Array((e=>{let t=e.cpos;for(let n=0;n<e.bufs.length;n++)t+=e.bufs[n].length;return t})(e));let n=0;for(let r=0;r<e.bufs.length;r++){const i=e.bufs[r];t.set(i,n),n+=i.length}return t.set(new Uint8Array(e.cbuf.buffer,0,e.cpos),n),t},wr=(e,t)=>{const n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(2*n),e.cpos=0),e.cbuf[e.cpos++]=t},_r=wr,kr=(e,t)=>{for(;t>lr;)wr(e,cr|lr&t),t=tr(t/128);wr(e,lr&t)},Sr=(e,t)=>{const n=sr(t);for(n&&(t=-t),wr(e,(t>63?cr:0)|(n?or:0)|63&t),t=tr(t/64);t>0;)wr(e,(t>lr?cr:0)|lr&t),t=tr(t/128)},Er=new Uint8Array(3e4),xr=Er.length/3,Ir=pr&&pr.encodeInto?(e,t)=>{if(t.length<xr){const n=pr.encodeInto(t,Er).written||0;kr(e,n);for(let t=0;t<n;t++)wr(e,Er[t])}else Ar(e,gr(t))}:(e,t)=>{const n=unescape(encodeURIComponent(t)),r=n.length;kr(e,r);for(let t=0;t<r;t++)wr(e,n.codePointAt(t))},Cr=(e,t)=>{const n=e.cbuf.length,r=e.cpos,i=rr(n-r,t.length),s=t.length-i;e.cbuf.set(t.subarray(0,i),r),e.cpos+=i,s>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(ir(2*n,s)),e.cbuf.set(t.subarray(i)),e.cpos=s)},Ar=(e,t)=>{kr(e,t.byteLength),Cr(e,t)},Or=(e,t)=>{((e,t)=>{const n=e.cbuf.length;n-e.cpos<t&&(e.bufs.push(new Uint8Array(e.cbuf.buffer,0,e.cpos)),e.cbuf=new Uint8Array(2*ir(n,t)),e.cpos=0)})(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},Dr=new DataView(new ArrayBuffer(4)),Tr=(e,t)=>{switch(typeof t){case"string":wr(e,119),Ir(e,t);break;case"number":ur(t)&&nr(t)<=2147483647?(wr(e,125),Sr(e,t)):(n=t,Dr.setFloat32(0,n),Dr.getFloat32(0)===n?(wr(e,124),((e,t)=>{Or(e,4).setFloat32(0,t,!1)})(e,t)):(wr(e,123),((e,t)=>{Or(e,8).setFloat64(0,t,!1)})(e,t)));break;case"bigint":wr(e,122),((e,t)=>{Or(e,8).setBigInt64(0,t,!1)})(e,t);break;case"object":if(null===t)wr(e,126);else if(Zn(t)){wr(e,117),kr(e,t.length);for(let n=0;n<t.length;n++)Tr(e,t[n])}else if(t instanceof Uint8Array)wr(e,116),Ar(e,t);else{wr(e,118);const n=Object.keys(t);kr(e,n.length);for(let r=0;r<n.length;r++){const i=n[r];Ir(e,i),Tr(e,t[i])}}break;case"boolean":wr(e,t?120:121);break;default:wr(e,127)}var n};class Ur extends vr{constructor(e){super(),this.w=e,this.s=null,this.count=0}write(e){this.s===e?this.count++:(this.count>0&&kr(this,this.count-1),this.count=1,this.w(this,e),this.s=e)}}const jr=e=>{e.count>0&&(Sr(e.encoder,1===e.count?e.s:-e.s),e.count>1&&kr(e.encoder,e.count-2))};class Pr{constructor(){this.encoder=new vr,this.s=0,this.count=0}write(e){this.s===e?this.count++:(jr(this),this.count=1,this.s=e)}toUint8Array(){return jr(this),br(this.encoder)}}const Lr=e=>{if(e.count>0){const t=2*e.diff+(1===e.count?0:1);Sr(e.encoder,t),e.count>1&&kr(e.encoder,e.count-2)}};class Rr{constructor(){this.encoder=new vr,this.s=0,this.count=0,this.diff=0}write(e){this.diff===e-this.s?(this.s=e,this.count++):(Lr(this),this.count=1,this.diff=e-this.s,this.s=e)}toUint8Array(){return Lr(this),br(this.encoder)}}class Nr{constructor(){this.sarr=[],this.s="",this.lensE=new Pr}write(e){this.s+=e,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(e.length)}toUint8Array(){const e=new vr;return this.sarr.push(this.s),this.s="",Ir(e,this.sarr.join("")),Cr(e,this.lensE.toUint8Array()),br(e)}}const $r=e=>new Error(e),Mr=()=>{throw $r("Method unimplemented")},Br=()=>{throw $r("Unexpected case")},Fr=$r("Unexpected end of array"),Wr=$r("Integer out of Range");class Vr{constructor(e){this.arr=e,this.pos=0}}const Kr=e=>new Vr(e),Hr=e=>((e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n})(e,Jr(e)),zr=e=>e.arr[e.pos++],Jr=e=>{let t=0,n=1;const r=e.arr.length;for(;e.pos<r;){const r=e.arr[e.pos++];if(t+=(r&lr)*n,n*=128,r<cr)return t;if(t>ar)throw Wr}throw Fr},qr=e=>{let t=e.arr[e.pos++],n=63&t,r=64;const i=(t&or)>0?-1:1;if(0==(t&cr))return i*n;const s=e.arr.length;for(;e.pos<s;){if(t=e.arr[e.pos++],n+=(t&lr)*r,r*=128,t<cr)return i*n;if(n>ar)throw Wr}throw Fr},Yr=yr?e=>yr.decode(Hr(e)):e=>{let t=Jr(e);if(0===t)return"";{let n=String.fromCodePoint(zr(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(zr(e));else for(;t>0;){const r=t<1e4?t:1e4,i=e.arr.subarray(e.pos,e.pos+r);e.pos+=r,n+=String.fromCodePoint.apply(null,i),t-=r}return decodeURIComponent(escape(n))}},Gr=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},Qr=[e=>{},e=>null,qr,e=>Gr(e,4).getFloat32(0,!1),e=>Gr(e,8).getFloat64(0,!1),e=>Gr(e,8).getBigInt64(0,!1),e=>!1,e=>!0,Yr,e=>{const t=Jr(e),n={};for(let r=0;r<t;r++){n[Yr(e)]=Xr(e)}return n},e=>{const t=Jr(e),n=[];for(let r=0;r<t;r++)n.push(Xr(e));return n},Hr],Xr=e=>Qr[127-zr(e)](e);class Zr extends Vr{constructor(e,t){super(e),this.reader=t,this.s=null,this.count=0}read(){var e;return 0===this.count&&(this.s=this.reader(this),(e=this).pos!==e.arr.length?this.count=Jr(this)+1:this.count=-1),this.count--,this.s}}class ei extends Vr{constructor(e){super(e),this.s=0,this.count=0}read(){if(0===this.count){this.s=qr(this);const e=sr(this.s);this.count=1,e&&(this.s=-this.s,this.count=Jr(this)+2)}return this.count--,this.s}}class ti extends Vr{constructor(e){super(e),this.s=0,this.count=0,this.diff=0}read(){if(0===this.count){const e=qr(this),t=1&e;this.diff=tr(e/2),this.count=1,t&&(this.count=Jr(this)+2)}return this.s+=this.diff,this.count--,this.s}}class ni{constructor(e){this.decoder=new ei(e),this.str=Yr(this.decoder),this.spos=0}read(){const e=this.spos+this.decoder.read(),t=this.str.slice(this.spos,e);return this.spos=e,t}}const ri=crypto.getRandomValues.bind(crypto),ii=()=>ri(new Uint32Array(1))[0],si=[1e7]+-1e3+-4e3+-8e3+-1e11,oi=()=>si.replace(/[018]/g,(e=>(e^ii()&15>>e/4).toString(16))),ci=e=>new Promise(e);Promise.all.bind(Promise);const li=e=>void 0===e?null:e;let ai=new class{constructor(){this.map=new Map}setItem(e,t){this.map.set(e,t)}getItem(e){return this.map.get(e)}},ui=!0;try{"undefined"!=typeof localStorage&&localStorage&&(ai=localStorage,ui=!1)}catch(va){}const di=ai,hi=Object.assign,fi=Object.keys,pi=e=>fi(e).length,gi=(e,t)=>e===t||pi(e)===pi(t)&&((e,t)=>{for(const n in e)if(!t(e[n],n))return!1;return!0})(e,((e,n)=>(void 0!==e||((e,t)=>Object.prototype.hasOwnProperty.call(e,t))(t,n))&&t[n]===e)),yi=Object.freeze,vi=e=>{for(const t in e){const n=e[t];"object"!=typeof n&&"function"!=typeof n||vi(e[t])}return yi(e)},mi=(e,t,n=0)=>{try{for(;n<e.length;n++)e[n](...t)}finally{n<e.length&&mi(e,t,n+1)}},bi="undefined"!=typeof process&&process.release&&/node|io\.js/.test(process.release.name)&&"[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0);let wi;const _i=e=>(()=>{if(void 0===wi)if(bi){wi=zn();const e=process.argv;let t=null;for(let n=0;n<e.length;n++){const r=e[n];"-"===r[0]?(null!==t&&wi.set(t,""),t=r):null!==t&&(wi.set(t,r),t=null)}null!==t&&wi.set(t,"")}else"object"==typeof location?(wi=zn(),(location.search||"?").slice(1).split("&").forEach((e=>{if(0!==e.length){const[t,n]=e.split("=");wi.set(`--${fr(t,"-")}`,n),wi.set(`-${fr(t,"-")}`,n)}}))):wi=zn();return wi})().has(e),ki=e=>li(bi?process.env[e.toUpperCase().replaceAll("-","_")]:di.getItem(e)),Si=e=>_i("--"+e)||null!==ki(e);Si("production");var Ei;bi&&(Ei=process.env.FORCE_COLOR,["true","1","2"].includes(Ei))||!_i("--no-colors")&&!Si("no-color")&&(!bi||process.stdout.isTTY)&&(!bi||_i("--color")||null!==ki("COLORTERM")||(ki("TERM")||"").includes("color"));class xi{constructor(e,t){this.left=e,this.right=t}}const Ii=(e,t)=>new xi(e,t);"undefined"!=typeof DOMParser&&new DOMParser;const Ci=Symbol,Ai=Ci(),Oi=Ci(),Di=Ci(),Ti=Ci(),Ui=Ci(),ji=Ci(),Pi=Ci(),Li=Ci(),Ri=Ci(),Ni=(Ii("font-weight","bold"),Ii("font-weight","normal"),Ii("color","blue"),Ii("color","green"),Ii("color","grey"),Ii("color","red"),Ii("color","purple"),Ii("color","orange"),Ii("color","black"),Yn()),$i=e=>({[Symbol.iterator](){return this},next:e}),Mi=(e,t)=>$i((()=>{const{done:n,value:r}=e.next();return{done:n,value:n?void 0:t(r)}}));class Bi{constructor(e,t){this.clock=e,this.len=t}}class Fi{constructor(){this.clients=new Map}}const Wi=(e,t,n)=>t.clients.forEach(((t,r)=>{const i=e.doc.store.clients.get(r);if(null!=i){const r=i[i.length-1],s=r.id.clock+r.length;for(let r=0,o=t[r];r<t.length&&o.clock<s;o=t[++r])Es(e,i,o.clock,o.len,n)}})),Vi=(e,t)=>{const n=e.clients.get(t.client);return void 0!==n&&null!==((e,t)=>{let n=0,r=e.length-1;for(;n<=r;){const i=tr((n+r)/2),s=e[i],o=s.clock;if(o<=t){if(t<o+s.len)return i;n=i+1}else r=i-1}return null})(n,t.clock)},Ki=e=>{e.clients.forEach((e=>{let t,n;for(e.sort(((e,t)=>e.clock-t.clock)),t=1,n=1;t<e.length;t++){const r=e[n-1],i=e[t];r.clock+r.len>=i.clock?r.len=ir(r.len,i.clock+i.len-r.clock):(n<t&&(e[n]=i),n++)}e.length=n}))},Hi=(e,t,n,r)=>{qn(e.clients,t,(()=>[])).push(new Bi(n,r))},zi=(e,t)=>{kr(e.restEncoder,t.clients.size),Xn(t.clients.entries()).sort(((e,t)=>t[0]-e[0])).forEach((([t,n])=>{e.resetDsCurVal(),kr(e.restEncoder,t);const r=n.length;kr(e.restEncoder,r);for(let t=0;t<r;t++){const r=n[t];e.writeDsClock(r.clock),e.writeDsLen(r.len)}}))},Ji=(e,t,n)=>{const r=new Fi,i=Jr(e.restDecoder);for(let s=0;s<i;s++){e.resetDsCurVal();const i=Jr(e.restDecoder),s=Jr(e.restDecoder),o=n.clients.get(i)||[],c=vs(n,i);for(let n=0;n<s;n++){const n=e.readDsClock(),s=n+e.readDsLen();if(n<c){c<s&&Hi(r,i,c,s-c);let e=bs(o,n),l=o[e];for(!l.deleted&&l.id.clock<n&&(o.splice(e+1,0,oc(t,l,n-l.id.clock)),e++);e<o.length&&(l=o[e++],l.id.clock<s);)l.deleted||(s<l.id.clock+l.length&&o.splice(e,0,oc(t,l,s-l.id.clock)),l.delete(t))}else Hi(r,i,n,s-n)}}if(r.clients.size>0){const e=new ts;return kr(e.restEncoder,0),zi(e,r),e.toUint8Array()}return null},qi=ii;class Yi extends er{constructor({guid:e=oi(),collectionid:t=null,gc:n=!0,gcFilter:r=(()=>!0),meta:i=null,autoLoad:s=!1,shouldLoad:o=!0}={}){super(),this.gc=n,this.gcFilter=r,this.clientID=qi(),this.guid=e,this.collectionid=t,this.share=new Map,this.store=new gs,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=o,this.autoLoad=s,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=ci((e=>{this.on("load",(()=>{this.isLoaded=!0,e(this)}))}));const c=()=>ci((e=>{const t=n=>{void 0!==n&&!0!==n||(this.off("sync",t),e())};this.on("sync",t)}));this.on("sync",(e=>{!1===e&&this.isSynced&&(this.whenSynced=c()),this.isSynced=void 0===e||!0===e,this.isSynced&&!this.isLoaded&&this.emit("load",[this])})),this.whenSynced=c()}load(){const e=this._item;null===e||this.shouldLoad||Ds(e.parent.doc,(e=>{e.subdocsLoaded.add(this)}),null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(Xn(this.subdocs).map((e=>e.guid)))}transact(e,t=null){return Ds(this,e,t)}get(e,t=Ys){const n=qn(this.share,e,(()=>{const e=new t;return e._integrate(this,null),e})),r=n.constructor;if(t!==Ys&&r!==t){if(r===Ys){const r=new t;r._map=n._map,n._map.forEach((e=>{for(;null!==e;e=e.left)e.parent=r})),r._start=n._start;for(let e=r._start;null!==e;e=e.right)e.parent=r;return r._length=n._length,this.share.set(e,r),r._integrate(this,null),r}throw new Error(`Type with the name ${e} has already been defined with a different constructor`)}return n}getArray(e=""){return this.get(e,po)}getText(e=""){return this.get(e,Uo)}getMap(e=""){return this.get(e,yo)}getXmlElement(e=""){return this.get(e,Lo)}getXmlFragment(e=""){return this.get(e,Po)}toJSON(){const e={};return this.share.forEach(((t,n)=>{e[n]=t.toJSON()})),e}destroy(){this.isDestroyed=!0,Xn(this.subdocs).forEach((e=>e.destroy()));const e=this._item;if(null!==e){this._item=null;const t=e.content;t.doc=new Yi({guid:this.guid,...t.opts,shouldLoad:!1}),t.doc._item=e,Ds(e.parent.doc,(n=>{const r=t.doc;e.deleted||n.subdocsAdded.add(r),n.subdocsRemoved.add(this)}),null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class Gi{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=Jr(this.restDecoder),this.dsCurrVal}readDsLen(){const e=Jr(this.restDecoder)+1;return this.dsCurrVal+=e,e}}class Qi extends Gi{constructor(e){super(e),this.keys=[],Jr(e),this.keyClockDecoder=new ti(Hr(e)),this.clientDecoder=new ei(Hr(e)),this.leftClockDecoder=new ti(Hr(e)),this.rightClockDecoder=new ti(Hr(e)),this.infoDecoder=new Zr(Hr(e),zr),this.stringDecoder=new ni(Hr(e)),this.parentInfoDecoder=new Zr(Hr(e),zr),this.typeRefDecoder=new ei(Hr(e)),this.lenDecoder=new ei(Hr(e))}readLeftID(){return new us(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new us(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return 1===this.parentInfoDecoder.read()}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return Xr(this.restDecoder)}readBuf(){return Hr(this.restDecoder)}readJSON(){return Xr(this.restDecoder)}readKey(){const e=this.keyClockDecoder.read();if(e<this.keys.length)return this.keys[e];{const e=this.stringDecoder.read();return this.keys.push(e),e}}}class Xi{constructor(){this.restEncoder=mr()}toUint8Array(){return br(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){kr(this.restEncoder,e)}writeDsLen(e){kr(this.restEncoder,e)}}class Zi extends Xi{writeLeftID(e){kr(this.restEncoder,e.client),kr(this.restEncoder,e.clock)}writeRightID(e){kr(this.restEncoder,e.client),kr(this.restEncoder,e.clock)}writeClient(e){kr(this.restEncoder,e)}writeInfo(e){_r(this.restEncoder,e)}writeString(e){Ir(this.restEncoder,e)}writeParentInfo(e){kr(this.restEncoder,e?1:0)}writeTypeRef(e){kr(this.restEncoder,e)}writeLen(e){kr(this.restEncoder,e)}writeAny(e){Tr(this.restEncoder,e)}writeBuf(e){Ar(this.restEncoder,e)}writeJSON(e){Ir(this.restEncoder,JSON.stringify(e))}writeKey(e){Ir(this.restEncoder,e)}}class es{constructor(){this.restEncoder=mr(),this.dsCurrVal=0}toUint8Array(){return br(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(e){const t=e-this.dsCurrVal;this.dsCurrVal=e,kr(this.restEncoder,t)}writeDsLen(e){0===e&&Br(),kr(this.restEncoder,e-1),this.dsCurrVal+=e}}class ts extends es{constructor(){super(),this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new Rr,this.clientEncoder=new Pr,this.leftClockEncoder=new Rr,this.rightClockEncoder=new Rr,this.infoEncoder=new Ur(_r),this.stringEncoder=new Nr,this.parentInfoEncoder=new Ur(_r),this.typeRefEncoder=new Pr,this.lenEncoder=new Pr}toUint8Array(){const e=mr();return kr(e,0),Ar(e,this.keyClockEncoder.toUint8Array()),Ar(e,this.clientEncoder.toUint8Array()),Ar(e,this.leftClockEncoder.toUint8Array()),Ar(e,this.rightClockEncoder.toUint8Array()),Ar(e,br(this.infoEncoder)),Ar(e,this.stringEncoder.toUint8Array()),Ar(e,br(this.parentInfoEncoder)),Ar(e,this.typeRefEncoder.toUint8Array()),Ar(e,this.lenEncoder.toUint8Array()),Cr(e,br(this.restEncoder)),br(e)}writeLeftID(e){this.clientEncoder.write(e.client),this.leftClockEncoder.write(e.clock)}writeRightID(e){this.clientEncoder.write(e.client),this.rightClockEncoder.write(e.clock)}writeClient(e){this.clientEncoder.write(e)}writeInfo(e){this.infoEncoder.write(e)}writeString(e){this.stringEncoder.write(e)}writeParentInfo(e){this.parentInfoEncoder.write(e?1:0)}writeTypeRef(e){this.typeRefEncoder.write(e)}writeLen(e){this.lenEncoder.write(e)}writeAny(e){Tr(this.restEncoder,e)}writeBuf(e){Ar(this.restEncoder,e)}writeJSON(e){Tr(this.restEncoder,e)}writeKey(e){const t=this.keyMap.get(e);void 0===t?(this.keyClockEncoder.write(this.keyClock++),this.stringEncoder.write(e)):this.keyClockEncoder.write(t)}}const ns=(e,t,n)=>{const r=new Map;n.forEach(((e,n)=>{vs(t,n)>e&&r.set(n,e)})),ys(t).forEach(((e,t)=>{n.has(t)||r.set(t,0)})),kr(e.restEncoder,r.size),Xn(r.entries()).sort(((e,t)=>t[0]-e[0])).forEach((([n,r])=>{((e,t,n,r)=>{r=ir(r,t[0].id.clock);const i=bs(t,r);kr(e.restEncoder,t.length-i),e.writeClient(n),kr(e.restEncoder,r);const s=t[i];s.write(e,r-s.id.clock);for(let n=i+1;n<t.length;n++)t[n].write(e,0)})(e,t.clients.get(n),n,r)}))},rs=(e,t,n,r=new Qi(e))=>Ds(t,(e=>{e.local=!1;let t=!1;const n=e.doc,i=n.store,s=((e,t)=>{const n=zn(),r=Jr(e.restDecoder);for(let i=0;i<r;i++){const r=Jr(e.restDecoder),i=new Array(r),s=e.readClient();let o=Jr(e.restDecoder);n.set(s,{i:0,refs:i});for(let n=0;n<r;n++){const r=e.readInfo();switch(31&r){case 0:{const t=e.readLen();i[n]=new Bo(hs(s,o),t),o+=t;break}case 10:{const t=Jr(e.restDecoder);i[n]=new uc(hs(s,o),t),o+=t;break}default:{const c=0==(192&r),l=new cc(hs(s,o),null,(r&cr)===cr?e.readLeftID():null,null,(r&or)===or?e.readRightID():null,c?e.readParentInfo()?t.get(e.readString()):e.readLeftID():null,c&&32==(32&r)?e.readString():null,lc(e,r));i[n]=l,o+=l.length}}}}return n})(r,n),o=((e,t,n)=>{const r=[];let i=Xn(n.keys()).sort(((e,t)=>e-t));if(0===i.length)return null;const s=()=>{if(0===i.length)return null;let e=n.get(i[i.length-1]);for(;e.refs.length===e.i;){if(i.pop(),!(i.length>0))return null;e=n.get(i[i.length-1])}return e};let o=s();if(null===o)return null;const c=new gs,l=new Map,a=(e,t)=>{const n=l.get(e);(null==n||n>t)&&l.set(e,t)};let u=o.refs[o.i++];const d=new Map,h=()=>{for(const e of r){const t=e.id.client,r=n.get(t);r?(r.i--,c.clients.set(t,r.refs.slice(r.i)),n.delete(t),r.i=0,r.refs=[]):c.clients.set(t,[e]),i=i.filter((e=>e!==t))}r.length=0};for(;;){if(u.constructor!==uc){const i=qn(d,u.id.client,(()=>vs(t,u.id.client)))-u.id.clock;if(i<0)r.push(u),a(u.id.client,u.id.clock-1),h();else{const s=u.getMissing(e,t);if(null!==s){r.push(u);const e=n.get(s)||{refs:[],i:0};if(e.refs.length!==e.i){u=e.refs[e.i++];continue}a(s,vs(t,s)),h()}else(0===i||i<u.length)&&(u.integrate(e,i),d.set(u.id.client,u.id.clock+u.length))}}if(r.length>0)u=r.pop();else if(null!==o&&o.i<o.refs.length)u=o.refs[o.i++];else{if(o=s(),null===o)break;u=o.refs[o.i++]}}if(c.clients.size>0){const e=new ts;return ns(e,c,new Map),kr(e.restEncoder,0),{missing:l,update:e.toUint8Array()}}return null})(e,i,s),c=i.pendingStructs;if(c){for(const[e,n]of c.missing)if(n<vs(i,e)){t=!0;break}if(o){for(const[e,t]of o.missing){const n=c.missing.get(e);(null==n||n>t)&&c.missing.set(e,t)}c.update=Ls([c.update,o.update])}}else i.pendingStructs=o;const l=Ji(r,e,i);if(i.pendingDs){const t=new Qi(Kr(i.pendingDs));Jr(t.restDecoder);const n=Ji(t,e,i);i.pendingDs=l&&n?Ls([l,n]):l||n}else i.pendingDs=l;if(t){const t=i.pendingStructs.update;i.pendingStructs=null,is(e.doc,t)}}),n,!1),is=(e,t,n,r=Qi)=>{const i=Kr(t);rs(i,e,n,new r(i))};class ss{constructor(){this.l=[]}}const os=()=>new ss,cs=(e,t)=>e.l.push(t),ls=(e,t)=>{const n=e.l;n.length;e.l=n.filter((e=>t!==e)),e.l.length},as=(e,t,n)=>mi(e.l,[t,n]);class us{constructor(e,t){this.client=e,this.clock=t}}const ds=(e,t)=>e===t||null!==e&&null!==t&&e.client===t.client&&e.clock===t.clock,hs=(e,t)=>new us(e,t),fs=(e,t)=>void 0===t?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!Vi(t.ds,e.id),ps=(e,t)=>{const n=qn(e.meta,ps,Yn),r=e.doc.store;n.has(t)||(t.sv.forEach(((t,n)=>{t<vs(r,n)&&ks(e,hs(n,t))})),Wi(e,t.ds,(e=>{})),n.add(t))};class gs{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const ys=e=>{const t=new Map;return e.clients.forEach(((e,n)=>{const r=e[e.length-1];t.set(n,r.id.clock+r.length)})),t},vs=(e,t)=>{const n=e.clients.get(t);if(void 0===n)return 0;const r=n[n.length-1];return r.id.clock+r.length},ms=(e,t)=>{let n=e.clients.get(t.id.client);if(void 0===n)n=[],e.clients.set(t.id.client,n);else{const e=n[n.length-1];if(e.id.clock+e.length!==t.id.clock)throw Br()}n.push(t)},bs=(e,t)=>{let n=0,r=e.length-1,i=e[r],s=i.id.clock;if(s===t)return r;let o=tr(t/(s+i.length-1)*r);for(;n<=r;){if(i=e[o],s=i.id.clock,s<=t){if(t<s+i.length)return o;n=o+1}else r=o-1;o=tr((n+r)/2)}throw Br()},ws=(e,t)=>{const n=e.clients.get(t.client);return n[bs(n,t.clock)]},_s=(e,t,n)=>{const r=bs(t,n),i=t[r];return i.id.clock<n&&i instanceof cc?(t.splice(r+1,0,oc(e,i,n-i.id.clock)),r+1):r},ks=(e,t)=>{const n=e.doc.store.clients.get(t.client);return n[_s(e,n,t.clock)]},Ss=(e,t,n)=>{const r=t.clients.get(n.client),i=bs(r,n.clock),s=r[i];return n.clock!==s.id.clock+s.length-1&&s.constructor!==Bo&&r.splice(i+1,0,oc(e,s,n.clock-s.id.clock+1)),s},Es=(e,t,n,r,i)=>{if(0===r)return;const s=n+r;let o,c=_s(e,t,n);do{o=t[c++],s<o.id.clock+o.length&&_s(e,t,s),i(o)}while(c<t.length&&t[c].id.clock<s)};class xs{constructor(e,t,n){this.doc=e,this.deleteSet=new Fi,this.beforeState=ys(e.store),this.afterState=new Map,this.changed=new Map,this.changedParentTypes=new Map,this._mergeStructs=[],this.origin=t,this.meta=new Map,this.local=n,this.subdocsAdded=new Set,this.subdocsRemoved=new Set,this.subdocsLoaded=new Set,this._needFormattingCleanup=!1}}const Is=(e,t)=>!(0===t.deleteSet.clients.size&&!((e,t)=>{for(const[n,r]of e)if(t(r,n))return!0;return!1})(t.afterState,((e,n)=>t.beforeState.get(n)!==e)))&&(Ki(t.deleteSet),((e,t)=>{ns(e,t.doc.store,t.beforeState)})(e,t),zi(e,t.deleteSet),!0),Cs=(e,t,n)=>{const r=t._item;(null===r||r.id.clock<(e.beforeState.get(r.id.client)||0)&&!r.deleted)&&qn(e.changed,t,Yn).add(n)},As=(e,t)=>{let n=e[t],r=e[t-1],i=t;for(;i>0&&(r.deleted===n.deleted&&r.constructor===n.constructor&&r.mergeWith(n));n=r,r=e[--i-1])n instanceof cc&&null!==n.parentSub&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,r);const s=t-i;return s&&e.splice(t+1-s,s),s},Os=(e,t)=>{if(t<e.length){const n=e[t],r=n.doc,i=r.store,s=n.deleteSet,o=n._mergeStructs;try{Ki(s),n.afterState=ys(n.doc.store),r.emit("beforeObserverCalls",[n,r]);const e=[];n.changed.forEach(((t,r)=>e.push((()=>{null!==r._item&&r._item.deleted||r._callObserver(n,t)})))),e.push((()=>{n.changedParentTypes.forEach(((e,t)=>{t._dEH.l.length>0&&(null===t._item||!t._item.deleted)&&((e=e.filter((e=>null===e.target._item||!e.target._item.deleted))).forEach((e=>{e.currentTarget=t,e._path=null})),e.sort(((e,t)=>e.path.length-t.path.length)),as(t._dEH,e,n))}))})),e.push((()=>r.emit("afterTransaction",[n,r]))),mi(e,[]),n._needFormattingCleanup&&Oo(n)}finally{r.gc&&((e,t,n)=>{for(const[r,i]of e.clients.entries()){const e=t.clients.get(r);for(let r=i.length-1;r>=0;r--){const s=i[r],o=s.clock+s.len;for(let r=bs(e,s.clock),i=e[r];r<e.length&&i.id.clock<o;i=e[++r]){const i=e[r];if(s.clock+s.len<=i.id.clock)break;i instanceof cc&&i.deleted&&!i.keep&&n(i)&&i.gc(t,!1)}}}})(s,i,r.gcFilter),((e,t)=>{e.clients.forEach(((e,n)=>{const r=t.clients.get(n);for(let t=e.length-1;t>=0;t--){const n=e[t];for(let e=rr(r.length-1,1+bs(r,n.clock+n.len-1)),t=r[e];e>0&&t.id.clock>=n.clock;t=r[e])e-=1+As(r,e)}}))})(s,i),n.afterState.forEach(((e,t)=>{const r=n.beforeState.get(t)||0;if(r!==e){const e=i.clients.get(t),n=ir(bs(e,r),1);for(let t=e.length-1;t>=n;)t-=1+As(e,t)}}));for(let e=o.length-1;e>=0;e--){const{client:t,clock:n}=o[e].id,r=i.clients.get(t),s=bs(r,n);s+1<r.length&&As(r,s+1)>1||s>0&&As(r,s)}if(n.local||n.afterState.get(r.clientID)===n.beforeState.get(r.clientID)||(((...e)=>{Ni.forEach((t=>t.print(e)))})(Li,Ai,"[yjs] ",Oi,ji,"Changed the client-id because another client seems to be using it."),r.clientID=qi()),r.emit("afterTransactionCleanup",[n,r]),r._observers.has("update")){const e=new Zi;Is(e,n)&&r.emit("update",[e.toUint8Array(),n.origin,r,n])}if(r._observers.has("updateV2")){const e=new ts;Is(e,n)&&r.emit("updateV2",[e.toUint8Array(),n.origin,r,n])}const{subdocsAdded:c,subdocsLoaded:l,subdocsRemoved:a}=n;(c.size>0||a.size>0||l.size>0)&&(c.forEach((e=>{e.clientID=r.clientID,null==e.collectionid&&(e.collectionid=r.collectionid),r.subdocs.add(e)})),a.forEach((e=>r.subdocs.delete(e))),r.emit("subdocs",[{loaded:l,added:c,removed:a},r,n]),a.forEach((e=>e.destroy()))),e.length<=t+1?(r._transactionCleanups=[],r.emit("afterAllTransactions",[r,e])):Os(e,t+1)}}},Ds=(e,t,n=null,r=!0)=>{const i=e._transactionCleanups;let s=!1,o=null;null===e._transaction&&(s=!0,e._transaction=new xs(e,n,r),i.push(e._transaction),1===i.length&&e.emit("beforeAllTransactions",[e]),e.emit("beforeTransaction",[e._transaction,e]));try{o=t(e._transaction)}finally{if(s){const t=e._transaction===i[0];e._transaction=null,t&&Os(i,0)}}return o};class Ts{constructor(e,t){this.gen=function*(e){const t=Jr(e.restDecoder);for(let n=0;n<t;n++){const t=Jr(e.restDecoder),n=e.readClient();let r=Jr(e.restDecoder);for(let i=0;i<t;i++){const t=e.readInfo();if(10===t){const t=Jr(e.restDecoder);yield new uc(hs(n,r),t),r+=t}else if(0!=(31&t)){const i=0==(192&t),s=new cc(hs(n,r),null,(t&cr)===cr?e.readLeftID():null,null,(t&or)===or?e.readRightID():null,i?e.readParentInfo()?e.readString():e.readLeftID():null,i&&32==(32&t)?e.readString():null,lc(e,t));yield s,r+=s.length}else{const t=e.readLen();yield new Bo(hs(n,r),t),r+=t}}}}(e),this.curr=null,this.done=!1,this.filterSkips=t,this.next()}next(){do{this.curr=this.gen.next().value||null}while(this.filterSkips&&null!==this.curr&&this.curr.constructor===uc);return this.curr}}class Us{constructor(e){this.currClient=0,this.startClock=0,this.written=0,this.encoder=e,this.clientStructs=[]}}const js=(e,t=es,n=Qi)=>{const r=new t,i=new Ts(new n(Kr(e)),!1);let s=i.curr;if(null!==s){let e=0,t=s.id.client,n=0!==s.id.clock,o=n?0:s.id.clock+s.length;for(;null!==s;s=i.next())t!==s.id.client&&(0!==o&&(e++,kr(r.restEncoder,t),kr(r.restEncoder,o)),t=s.id.client,o=0,n=0!==s.id.clock),s.constructor===uc&&(n=!0),n||(o=s.id.clock+s.length);0!==o&&(e++,kr(r.restEncoder,t),kr(r.restEncoder,o));const c=mr();return kr(c,e),((e,t)=>{Cr(e,br(t))})(c,r.restEncoder),r.restEncoder=c,r.toUint8Array()}return kr(r.restEncoder,0),r.toUint8Array()},Ps=(e,t)=>{if(e.constructor===Bo){const{client:n,clock:r}=e.id;return new Bo(hs(n,r+t),e.length-t)}if(e.constructor===uc){const{client:n,clock:r}=e.id;return new uc(hs(n,r+t),e.length-t)}{const n=e,{client:r,clock:i}=n.id;return new cc(hs(r,i+t),null,hs(r,i+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},Ls=(e,t=Qi,n=ts)=>{if(1===e.length)return e[0];const r=e.map((e=>new t(Kr(e))));let i=r.map((e=>new Ts(e,!0))),s=null;const o=new n,c=new Us(o);for(;i=i.filter((e=>null!==e.curr)),i.sort(((e,t)=>{if(e.curr.id.client===t.curr.id.client){const n=e.curr.id.clock-t.curr.id.clock;return 0===n?e.curr.constructor===t.curr.constructor?0:e.curr.constructor===uc?1:-1:n}return t.curr.id.client-e.curr.id.client})),0!==i.length;){const e=i[0],t=e.curr.id.client;if(null!==s){let n=e.curr,r=!1;for(;null!==n&&n.id.clock+n.length<=s.struct.id.clock+s.struct.length&&n.id.client>=s.struct.id.client;)n=e.next(),r=!0;if(null===n||n.id.client!==t||r&&n.id.clock>s.struct.id.clock+s.struct.length)continue;if(t!==s.struct.id.client)Ns(c,s.struct,s.offset),s={struct:n,offset:0},e.next();else if(s.struct.id.clock+s.struct.length<n.id.clock)if(s.struct.constructor===uc)s.struct.length=n.id.clock+n.length-s.struct.id.clock;else{Ns(c,s.struct,s.offset);const e=n.id.clock-s.struct.id.clock-s.struct.length;s={struct:new uc(hs(t,s.struct.id.clock+s.struct.length),e),offset:0}}else{const t=s.struct.id.clock+s.struct.length-n.id.clock;t>0&&(s.struct.constructor===uc?s.struct.length-=t:n=Ps(n,t)),s.struct.mergeWith(n)||(Ns(c,s.struct,s.offset),s={struct:n,offset:0},e.next())}}else s={struct:e.curr,offset:0},e.next();for(let n=e.curr;null!==n&&n.id.client===t&&n.id.clock===s.struct.id.clock+s.struct.length&&n.constructor!==uc;n=e.next())Ns(c,s.struct,s.offset),s={struct:n,offset:0}}null!==s&&(Ns(c,s.struct,s.offset),s=null),$s(c);const l=r.map((e=>(e=>{const t=new Fi,n=Jr(e.restDecoder);for(let r=0;r<n;r++){e.resetDsCurVal();const n=Jr(e.restDecoder),r=Jr(e.restDecoder);if(r>0){const i=qn(t.clients,n,(()=>[]));for(let t=0;t<r;t++)i.push(new Bi(e.readDsClock(),e.readDsLen()))}}return t})(e))),a=(e=>{const t=new Fi;for(let n=0;n<e.length;n++)e[n].clients.forEach(((r,i)=>{if(!t.clients.has(i)){const s=r.slice();for(let t=n+1;t<e.length;t++)Qn(s,e[t].clients.get(i)||[]);t.clients.set(i,s)}}));return Ki(t),t})(l);return zi(o,a),o.toUint8Array()},Rs=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:br(e.encoder.restEncoder)}),e.encoder.restEncoder=mr(),e.written=0)},Ns=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&Rs(e),0===e.written&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),kr(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},$s=e=>{Rs(e);const t=e.encoder.restEncoder;kr(t,e.clientStructs.length);for(let n=0;n<e.clientStructs.length;n++){const r=e.clientStructs[n];kr(t,r.written),Cr(t,r.restEncoder)}},Ms="You must not compute changes after the event-handler fired.";class Bs{constructor(e,t){this.target=e,this.currentTarget=e,this.transaction=t,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=Fs(this.currentTarget,this.target))}deletes(e){return Vi(this.transaction.deleteSet,e.id)}get keys(){if(null===this._keys){if(0===this.transaction.doc._transactionCleanups.length)throw $r(Ms);const e=new Map,t=this.target;this.transaction.changed.get(t).forEach((n=>{if(null!==n){const r=t._map.get(n);let i,s;if(this.adds(r)){let e=r.left;for(;null!==e&&this.adds(e);)e=e.left;if(this.deletes(r)){if(null===e||!this.deletes(e))return;i="delete",s=Gn(e.content.getContent())}else null!==e&&this.deletes(e)?(i="update",s=Gn(e.content.getContent())):(i="add",s=void 0)}else{if(!this.deletes(r))return;i="delete",s=Gn(r.content.getContent())}e.set(n,{action:i,oldValue:s})}})),this._keys=e}return this._keys}get delta(){return this.changes.delta}adds(e){return e.id.clock>=(this.transaction.beforeState.get(e.id.client)||0)}get changes(){let e=this._changes;if(null===e){if(0===this.transaction.doc._transactionCleanups.length)throw $r(Ms);const t=this.target,n=Yn(),r=Yn(),i=[];e={added:n,deleted:r,delta:i,keys:this.keys};if(this.transaction.changed.get(t).has(null)){let e=null;const s=()=>{e&&i.push(e)};for(let i=t._start;null!==i;i=i.right)i.deleted?this.deletes(i)&&!this.adds(i)&&(null!==e&&void 0!==e.delete||(s(),e={delete:0}),e.delete+=i.length,r.add(i)):this.adds(i)?(null!==e&&void 0!==e.insert||(s(),e={insert:[]}),e.insert=e.insert.concat(i.content.getContent()),n.add(i)):(null!==e&&void 0!==e.retain||(s(),e={retain:0}),e.retain+=i.length);null!==e&&void 0===e.retain&&s()}this._changes=e}return e}}const Fs=(e,t)=>{const n=[];for(;null!==t._item&&t!==e;){if(null!==t._item.parentSub)n.unshift(t._item.parentSub);else{let e=0,r=t._item.parent._start;for(;r!==t._item&&null!==r;)!r.deleted&&r.countable&&(e+=r.length),r=r.right;n.unshift(e)}t=t._item.parent}return n},Ws=()=>{((...e)=>{e.unshift(Li),Ni.forEach((t=>t.print(e)))})("Invalid access: Add Yjs type to a document before reading data.")};let Vs=0;class Ks{constructor(e,t){e.marker=!0,this.p=e,this.index=t,this.timestamp=Vs++}}const Hs=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=Vs++},zs=(e,t)=>{if(null===e._start||0===t||null===e._searchMarker)return null;const n=0===e._searchMarker.length?null:e._searchMarker.reduce(((e,n)=>nr(t-e.index)<nr(t-n.index)?e:n));let r=e._start,i=0;for(null!==n&&(r=n.p,i=n.index,(e=>{e.timestamp=Vs++})(n));null!==r.right&&i<t;){if(!r.deleted&&r.countable){if(t<i+r.length)break;i+=r.length}r=r.right}for(;null!==r.left&&i>t;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);for(;null!==r.left&&r.left.id.client===r.id.client&&r.left.id.clock+r.left.length===r.id.clock;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);return null!==n&&nr(n.index-i)<r.parent.length/80?(Hs(n,r,i),n):((e,t,n)=>{if(e.length>=80){const r=e.reduce(((e,t)=>e.timestamp<t.timestamp?e:t));return Hs(r,t,n),r}{const r=new Ks(t,n);return e.push(r),r}})(e._searchMarker,r,i)},Js=(e,t,n)=>{for(let r=e.length-1;r>=0;r--){const i=e[r];if(n>0){let t=i.p;for(t.marker=!1;t&&(t.deleted||!t.countable);)t=t.left,t&&!t.deleted&&t.countable&&(i.index-=t.length);if(null===t||!0===t.marker){e.splice(r,1);continue}i.p=t,t.marker=!0}(t<i.index||n>0&&t===i.index)&&(i.index=ir(t,i.index+n))}},qs=(e,t,n)=>{const r=e,i=t.changedParentTypes;for(;qn(i,e,(()=>[])).push(n),null!==e._item;)e=e._item.parent;as(r._eH,n,t)};class Ys{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=os(),this._dEH=os(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,t){this.doc=e,this._item=t}_copy(){throw Mr()}clone(){throw Mr()}_write(e){}get _first(){let e=this._start;for(;null!==e&&e.deleted;)e=e.right;return e}_callObserver(e,t){!e.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(e){cs(this._eH,e)}observeDeep(e){cs(this._dEH,e)}unobserve(e){ls(this._eH,e)}unobserveDeep(e){ls(this._dEH,e)}toJSON(){}}const Gs=(e,t,n)=>{e.doc??Ws(),t<0&&(t=e._length+t),n<0&&(n=e._length+n);let r=n-t;const i=[];let s=e._start;for(;null!==s&&r>0;){if(s.countable&&!s.deleted){const e=s.content.getContent();if(e.length<=t)t-=e.length;else{for(let n=t;n<e.length&&r>0;n++)i.push(e[n]),r--;t=0}}s=s.right}return i},Qs=e=>{e.doc??Ws();const t=[];let n=e._start;for(;null!==n;){if(n.countable&&!n.deleted){const e=n.content.getContent();for(let n=0;n<e.length;n++)t.push(e[n])}n=n.right}return t},Xs=(e,t)=>{let n=0,r=e._start;for(e.doc??Ws();null!==r;){if(r.countable&&!r.deleted){const i=r.content.getContent();for(let r=0;r<i.length;r++)t(i[r],n++,e)}r=r.right}},Zs=(e,t)=>{const n=[];return Xs(e,((r,i)=>{n.push(t(r,i,e))})),n},eo=e=>{let t=e._start,n=null,r=0;return{[Symbol.iterator](){return this},next:()=>{if(null===n){for(;null!==t&&t.deleted;)t=t.right;if(null===t)return{done:!0,value:void 0};n=t.content.getContent(),r=0,t=t.right}const e=n[r++];return n.length<=r&&(n=null),{done:!1,value:e}}}},to=(e,t)=>{e.doc??Ws();const n=zs(e,t);let r=e._start;for(null!==n&&(r=n.p,t-=n.index);null!==r;r=r.right)if(!r.deleted&&r.countable){if(t<r.length)return r.content.getContent()[t];t-=r.length}},no=(e,t,n,r)=>{let i=n;const s=e.doc,o=s.clientID,c=s.store,l=null===n?t._start:n.right;let a=[];const u=()=>{a.length>0&&(i=new cc(hs(o,vs(c,o)),i,i&&i.lastId,l,l&&l.id,t,null,new Yo(a)),i.integrate(e,0),a=[])};r.forEach((n=>{if(null===n)a.push(n);else switch(n.constructor){case Number:case Object:case Boolean:case Array:case String:a.push(n);break;default:switch(u(),n.constructor){case Uint8Array:case ArrayBuffer:i=new cc(hs(o,vs(c,o)),i,i&&i.lastId,l,l&&l.id,t,null,new Fo(new Uint8Array(n))),i.integrate(e,0);break;case Yi:i=new cc(hs(o,vs(c,o)),i,i&&i.lastId,l,l&&l.id,t,null,new Ko(n)),i.integrate(e,0);break;default:if(!(n instanceof Ys))throw new Error("Unexpected content type in insert operation");i=new cc(hs(o,vs(c,o)),i,i&&i.lastId,l,l&&l.id,t,null,new sc(n)),i.integrate(e,0)}}})),u()},ro=()=>$r("Length exceeded!"),io=(e,t,n,r)=>{if(n>t._length)throw ro();if(0===n)return t._searchMarker&&Js(t._searchMarker,n,r.length),no(e,t,null,r);const i=n,s=zs(t,n);let o=t._start;for(null!==s&&(o=s.p,0===(n-=s.index)&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));null!==o;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n<o.length&&ks(e,hs(o.id.client,o.id.clock+n));break}n-=o.length}return t._searchMarker&&Js(t._searchMarker,i,r.length),no(e,t,o,r)},so=(e,t,n,r)=>{if(0===r)return;const i=n,s=r,o=zs(t,n);let c=t._start;for(null!==o&&(c=o.p,n-=o.index);null!==c&&n>0;c=c.right)!c.deleted&&c.countable&&(n<c.length&&ks(e,hs(c.id.client,c.id.clock+n)),n-=c.length);for(;r>0&&null!==c;)c.deleted||(r<c.length&&ks(e,hs(c.id.client,c.id.clock+r)),c.delete(e),r-=c.length),c=c.right;if(r>0)throw ro();t._searchMarker&&Js(t._searchMarker,i,-s+r)},oo=(e,t,n)=>{const r=t._map.get(n);void 0!==r&&r.delete(e)},co=(e,t,n,r)=>{const i=t._map.get(n)||null,s=e.doc,o=s.clientID;let c;if(null==r)c=new Yo([r]);else switch(r.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:c=new Yo([r]);break;case Uint8Array:c=new Fo(r);break;case Yi:c=new Ko(r);break;default:if(!(r instanceof Ys))throw new Error("Unexpected content type");c=new sc(r)}new cc(hs(o,vs(s.store,o)),i,i&&i.lastId,null,null,t,n,c).integrate(e,0)},lo=(e,t)=>{e.doc??Ws();const n=e._map.get(t);return void 0===n||n.deleted?void 0:n.content.getContent()[n.length-1]},ao=e=>{const t={};return e.doc??Ws(),e._map.forEach(((e,n)=>{e.deleted||(t[n]=e.content.getContent()[e.length-1])})),t},uo=(e,t)=>{e.doc??Ws();const n=e._map.get(t);return void 0!==n&&!n.deleted},ho=e=>(e.doc??Ws(),((e,t)=>$i((()=>{let n;do{n=e.next()}while(!n.done&&!t(n.value));return n})))(e._map.entries(),(e=>!e[1].deleted)));class fo extends Bs{}class po extends Ys{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(e){const t=new po;return t.push(e),t}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new po}clone(){const e=new po;return e.insert(0,this.toArray().map((e=>e instanceof Ys?e.clone():e))),e}get length(){return this.doc??Ws(),this._length}_callObserver(e,t){super._callObserver(e,t),qs(this,e,new fo(this,e))}insert(e,t){null!==this.doc?Ds(this.doc,(n=>{io(n,this,e,t)})):this._prelimContent.splice(e,0,...t)}push(e){null!==this.doc?Ds(this.doc,(t=>{((e,t,n)=>{let r=(t._searchMarker||[]).reduce(((e,t)=>t.index>e.index?t:e),{index:0,p:t._start}).p;if(r)for(;r.right;)r=r.right;no(e,t,r,n)})(t,this,e)})):this._prelimContent.push(...e)}unshift(e){this.insert(0,e)}delete(e,t=1){null!==this.doc?Ds(this.doc,(n=>{so(n,this,e,t)})):this._prelimContent.splice(e,t)}get(e){return to(this,e)}toArray(){return Qs(this)}slice(e=0,t=this.length){return Gs(this,e,t)}toJSON(){return this.map((e=>e instanceof Ys?e.toJSON():e))}map(e){return Zs(this,e)}forEach(e){Xs(this,e)}[Symbol.iterator](){return eo(this)}_write(e){e.writeTypeRef(Xo)}}class go extends Bs{constructor(e,t,n){super(e,t),this.keysChanged=n}}class yo extends Ys{constructor(e){super(),this._prelimContent=null,this._prelimContent=void 0===e?new Map:new Map(e)}_integrate(e,t){super._integrate(e,t),this._prelimContent.forEach(((e,t)=>{this.set(t,e)})),this._prelimContent=null}_copy(){return new yo}clone(){const e=new yo;return this.forEach(((t,n)=>{e.set(n,t instanceof Ys?t.clone():t)})),e}_callObserver(e,t){qs(this,e,new go(this,e,t))}toJSON(){this.doc??Ws();const e={};return this._map.forEach(((t,n)=>{if(!t.deleted){const r=t.content.getContent()[t.length-1];e[n]=r instanceof Ys?r.toJSON():r}})),e}get size(){return[...ho(this)].length}keys(){return Mi(ho(this),(e=>e[0]))}values(){return Mi(ho(this),(e=>e[1].content.getContent()[e[1].length-1]))}entries(){return Mi(ho(this),(e=>[e[0],e[1].content.getContent()[e[1].length-1]]))}forEach(e){this.doc??Ws(),this._map.forEach(((t,n)=>{t.deleted||e(t.content.getContent()[t.length-1],n,this)}))}[Symbol.iterator](){return this.entries()}delete(e){null!==this.doc?Ds(this.doc,(t=>{oo(t,this,e)})):this._prelimContent.delete(e)}set(e,t){return null!==this.doc?Ds(this.doc,(n=>{co(n,this,e,t)})):this._prelimContent.set(e,t),t}get(e){return lo(this,e)}has(e){return uo(this,e)}clear(){null!==this.doc?Ds(this.doc,(e=>{this.forEach((function(t,n,r){oo(e,r,n)}))})):this._prelimContent.clear()}_write(e){e.writeTypeRef(Zo)}}const vo=(e,t)=>e===t||"object"==typeof e&&"object"==typeof t&&e&&t&&gi(e,t);class mo{constructor(e,t,n,r){this.left=e,this.right=t,this.index=n,this.currentAttributes=r}forward(){if(null===this.right&&Br(),this.right.content.constructor===zo)this.right.deleted||ko(this.currentAttributes,this.right.content);else this.right.deleted||(this.index+=this.right.length);this.left=this.right,this.right=this.right.right}}const bo=(e,t,n)=>{for(;null!==t.right&&n>0;){if(t.right.content.constructor===zo)t.right.deleted||ko(t.currentAttributes,t.right.content);else t.right.deleted||(n<t.right.length&&ks(e,hs(t.right.id.client,t.right.id.clock+n)),t.index+=t.right.length,n-=t.right.length);t.left=t.right,t.right=t.right.right}return t},wo=(e,t,n,r)=>{const i=new Map,s=r?zs(t,n):null;if(s){const t=new mo(s.p.left,s.p,s.index,i);return bo(e,t,n-s.index)}{const r=new mo(null,t._start,0,i);return bo(e,r,n)}},_o=(e,t,n,r)=>{for(;null!==n.right&&(!0===n.right.deleted||n.right.content.constructor===zo&&vo(r.get(n.right.content.key),n.right.content.value));)n.right.deleted||r.delete(n.right.content.key),n.forward();const i=e.doc,s=i.clientID;r.forEach(((r,o)=>{const c=n.left,l=n.right,a=new cc(hs(s,vs(i.store,s)),c,c&&c.lastId,l,l&&l.id,t,null,new zo(o,r));a.integrate(e,0),n.right=a,n.forward()}))},ko=(e,t)=>{const{key:n,value:r}=t;null===r?e.delete(n):e.set(n,r)},So=(e,t)=>{for(;null!==e.right&&(e.right.deleted||e.right.content.constructor===zo&&vo(t[e.right.content.key]??null,e.right.content.value));)e.forward()},Eo=(e,t,n,r)=>{const i=e.doc,s=i.clientID,o=new Map;for(const c in r){const l=r[c],a=n.currentAttributes.get(c)??null;if(!vo(a,l)){o.set(c,a);const{left:r,right:u}=n;n.right=new cc(hs(s,vs(i.store,s)),r,r&&r.lastId,u,u&&u.id,t,null,new zo(c,l)),n.right.integrate(e,0),n.forward()}}return o},xo=(e,t,n,r,i)=>{n.currentAttributes.forEach(((e,t)=>{void 0===i[t]&&(i[t]=null)}));const s=e.doc,o=s.clientID;So(n,i);const c=Eo(e,t,n,i),l=r.constructor===String?new Go(r):r instanceof Ys?new sc(r):new Ho(r);let{left:a,right:u,index:d}=n;t._searchMarker&&Js(t._searchMarker,n.index,l.getLength()),u=new cc(hs(o,vs(s.store,o)),a,a&&a.lastId,u,u&&u.id,t,null,l),u.integrate(e,0),n.right=u,n.index=d,n.forward(),_o(e,t,n,c)},Io=(e,t,n,r,i)=>{const s=e.doc,o=s.clientID;So(n,i);const c=Eo(e,t,n,i);e:for(;null!==n.right&&(r>0||c.size>0&&(n.right.deleted||n.right.content.constructor===zo));){if(!n.right.deleted)switch(n.right.content.constructor){case zo:{const{key:t,value:s}=n.right.content,o=i[t];if(void 0!==o){if(vo(o,s))c.delete(t);else{if(0===r)break e;c.set(t,s)}n.right.delete(e)}else n.currentAttributes.set(t,s);break}default:r<n.right.length&&ks(e,hs(n.right.id.client,n.right.id.clock+r)),r-=n.right.length}n.forward()}if(r>0){let i="";for(;r>0;r--)i+="\n";n.right=new cc(hs(o,vs(s.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new Go(i)),n.right.integrate(e,0),n.forward()}_o(e,t,n,c)},Co=(e,t,n,r,i)=>{let s=t;const o=zn();for(;s&&(!s.countable||s.deleted);){if(!s.deleted&&s.content.constructor===zo){const e=s.content;o.set(e.key,e)}s=s.right}let c=0,l=!1;for(;t!==s;){if(n===t&&(l=!0),!t.deleted){const n=t.content;switch(n.constructor){case zo:{const{key:s,value:a}=n,u=r.get(s)??null;o.get(s)===n&&u!==a||(t.delete(e),c++,l||(i.get(s)??null)!==a||u===a||(null===u?i.delete(s):i.set(s,u))),l||t.deleted||ko(i,n);break}}}t=t.right}return c},Ao=e=>{let t=0;return Ds(e.doc,(n=>{let r=e._start,i=e._start,s=zn();const o=Jn(s);for(;i;){if(!1===i.deleted)if(i.content.constructor===zo)ko(o,i.content);else t+=Co(n,r,i,s,o),s=Jn(o),r=i;i=i.right}})),t},Oo=e=>{const t=new Set,n=e.doc;for(const[r,i]of e.afterState.entries()){const s=e.beforeState.get(r)||0;i!==s&&Es(e,n.store.clients.get(r),s,i,(e=>{e.deleted||e.content.constructor!==zo||e.constructor===Bo||t.add(e.parent)}))}Ds(n,(n=>{Wi(e,e.deleteSet,(e=>{if(e instanceof Bo||!e.parent._hasFormatting||t.has(e.parent))return;const r=e.parent;e.content.constructor===zo?t.add(r):((e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;const n=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===zo){const r=t.content.key;n.has(r)?t.delete(e):n.add(r)}t=t.left}})(n,e)}));for(const e of t)Ao(e)}))},Do=(e,t,n)=>{const r=n,i=Jn(t.currentAttributes),s=t.right;for(;n>0&&null!==t.right;){if(!1===t.right.deleted)switch(t.right.content.constructor){case sc:case Ho:case Go:n<t.right.length&&ks(e,hs(t.right.id.client,t.right.id.clock+n)),n-=t.right.length,t.right.delete(e)}t.forward()}s&&Co(e,s,t.right,i,t.currentAttributes);const o=(t.left||t.right).parent;return o._searchMarker&&Js(o._searchMarker,t.index,-r+n),t};class To extends Bs{constructor(e,t,n){super(e,t),this.childListChanged=!1,this.keysChanged=new Set,n.forEach((e=>{null===e?this.childListChanged=!0:this.keysChanged.add(e)}))}get changes(){if(null===this._changes){const e={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=e}return this._changes}get delta(){if(null===this._delta){const e=this.target.doc,t=[];Ds(e,(e=>{const n=new Map,r=new Map;let i=this.target._start,s=null;const o={};let c="",l=0,a=0;const u=()=>{if(null!==s){let e=null;switch(s){case"delete":a>0&&(e={delete:a}),a=0;break;case"insert":("object"==typeof c||c.length>0)&&(e={insert:c},n.size>0&&(e.attributes={},n.forEach(((t,n)=>{null!==t&&(e.attributes[n]=t)})))),c="";break;case"retain":l>0&&(e={retain:l},(e=>{for(const t in e)return!1;return!0})(o)||(e.attributes=hi({},o))),l=0}e&&t.push(e),s=null}};for(;null!==i;){switch(i.content.constructor){case sc:case Ho:this.adds(i)?this.deletes(i)||(u(),s="insert",c=i.content.getContent()[0],u()):this.deletes(i)?("delete"!==s&&(u(),s="delete"),a+=1):i.deleted||("retain"!==s&&(u(),s="retain"),l+=1);break;case Go:this.adds(i)?this.deletes(i)||("insert"!==s&&(u(),s="insert"),c+=i.content.str):this.deletes(i)?("delete"!==s&&(u(),s="delete"),a+=i.length):i.deleted||("retain"!==s&&(u(),s="retain"),l+=i.length);break;case zo:{const{key:t,value:c}=i.content;if(this.adds(i)){if(!this.deletes(i)){const l=n.get(t)??null;vo(l,c)?null!==c&&i.delete(e):("retain"===s&&u(),vo(c,r.get(t)??null)?delete o[t]:o[t]=c)}}else if(this.deletes(i)){r.set(t,c);const e=n.get(t)??null;vo(e,c)||("retain"===s&&u(),o[t]=e)}else if(!i.deleted){r.set(t,c);const n=o[t];void 0!==n&&(vo(n,c)?null!==n&&i.delete(e):("retain"===s&&u(),null===c?delete o[t]:o[t]=c))}i.deleted||("insert"===s&&u(),ko(n,i.content));break}}i=i.right}for(u();t.length>0;){const e=t[t.length-1];if(void 0===e.retain||void 0!==e.attributes)break;t.pop()}})),this._delta=t}return this._delta}}class Uo extends Ys{constructor(e){super(),this._pending=void 0!==e?[()=>this.insert(0,e)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Ws(),this._length}_integrate(e,t){super._integrate(e,t);try{this._pending.forEach((e=>e()))}catch(e){}this._pending=null}_copy(){return new Uo}clone(){const e=new Uo;return e.applyDelta(this.toDelta()),e}_callObserver(e,t){super._callObserver(e,t);const n=new To(this,e,t);qs(this,e,n),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??Ws();let e="",t=this._start;for(;null!==t;)!t.deleted&&t.countable&&t.content.constructor===Go&&(e+=t.content.str),t=t.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:t=!0}={}){null!==this.doc?Ds(this.doc,(n=>{const r=new mo(null,this._start,0,new Map);for(let i=0;i<e.length;i++){const s=e[i];if(void 0!==s.insert){const o=t||"string"!=typeof s.insert||i!==e.length-1||null!==r.right||"\n"!==s.insert.slice(-1)?s.insert:s.insert.slice(0,-1);("string"!=typeof o||o.length>0)&&xo(n,this,r,o,s.attributes||{})}else void 0!==s.retain?Io(n,this,r,s.retain,s.attributes||{}):void 0!==s.delete&&Do(n,r,s.delete)}})):this._pending.push((()=>this.applyDelta(e)))}toDelta(e,t,n){this.doc??Ws();const r=[],i=new Map,s=this.doc;let o="",c=this._start;function l(){if(o.length>0){const e={};let t=!1;i.forEach(((n,r)=>{t=!0,e[r]=n}));const n={insert:o};t&&(n.attributes=e),r.push(n),o=""}}const a=()=>{for(;null!==c;){if(fs(c,e)||void 0!==t&&fs(c,t))switch(c.content.constructor){case Go:{const r=i.get("ychange");void 0===e||fs(c,e)?void 0===t||fs(c,t)?void 0!==r&&(l(),i.delete("ychange")):void 0!==r&&r.user===c.id.client&&"added"===r.type||(l(),i.set("ychange",n?n("added",c.id):{type:"added"})):void 0!==r&&r.user===c.id.client&&"removed"===r.type||(l(),i.set("ychange",n?n("removed",c.id):{type:"removed"})),o+=c.content.str;break}case sc:case Ho:{l();const e={insert:c.content.getContent()[0]};if(i.size>0){const t={};e.attributes=t,i.forEach(((e,n)=>{t[n]=e}))}r.push(e);break}case zo:fs(c,e)&&(l(),ko(i,c.content))}c=c.right}l()};return e||t?Ds(s,(n=>{e&&ps(n,e),t&&ps(n,t),a()}),"cleanup"):a(),r}insert(e,t,n){if(t.length<=0)return;const r=this.doc;null!==r?Ds(r,(r=>{const i=wo(r,this,e,!n);n||(n={},i.currentAttributes.forEach(((e,t)=>{n[t]=e}))),xo(r,this,i,t,n)})):this._pending.push((()=>this.insert(e,t,n)))}insertEmbed(e,t,n){const r=this.doc;null!==r?Ds(r,(r=>{const i=wo(r,this,e,!n);xo(r,this,i,t,n||{})})):this._pending.push((()=>this.insertEmbed(e,t,n||{})))}delete(e,t){if(0===t)return;const n=this.doc;null!==n?Ds(n,(n=>{Do(n,wo(n,this,e,!0),t)})):this._pending.push((()=>this.delete(e,t)))}format(e,t,n){if(0===t)return;const r=this.doc;null!==r?Ds(r,(r=>{const i=wo(r,this,e,!1);null!==i.right&&Io(r,this,i,t,n)})):this._pending.push((()=>this.format(e,t,n)))}removeAttribute(e){null!==this.doc?Ds(this.doc,(t=>{oo(t,this,e)})):this._pending.push((()=>this.removeAttribute(e)))}setAttribute(e,t){null!==this.doc?Ds(this.doc,(n=>{co(n,this,e,t)})):this._pending.push((()=>this.setAttribute(e,t)))}getAttribute(e){return lo(this,e)}getAttributes(){return ao(this)}_write(e){e.writeTypeRef(ec)}}class jo{constructor(e,t=(()=>!0)){this._filter=t,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??Ws()}[Symbol.iterator](){return this}next(){let e=this._currentNode,t=e&&e.content&&e.content.type;if(null!==e&&(!this._firstCall||e.deleted||!this._filter(t)))do{if(t=e.content.type,e.deleted||t.constructor!==Lo&&t.constructor!==Po||null===t._start)for(;null!==e;){const t=e.next;if(null!==t){e=t;break}e=e.parent===this._root?null:e.parent._item}else e=t._start}while(null!==e&&(e.deleted||!this._filter(e.content.type)));return this._firstCall=!1,null===e?{value:void 0,done:!0}:(this._currentNode=e,{value:e.content.type,done:!1})}}class Po extends Ys{constructor(){super(),this._prelimContent=[]}get firstChild(){const e=this._first;return e?e.content.getContent()[0]:null}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Po}clone(){const e=new Po;return e.insert(0,this.toArray().map((e=>e instanceof Ys?e.clone():e))),e}get length(){return this.doc??Ws(),null===this._prelimContent?this._length:this._prelimContent.length}createTreeWalker(e){return new jo(this,e)}querySelector(e){e=e.toUpperCase();const t=new jo(this,(t=>t.nodeName&&t.nodeName.toUpperCase()===e)).next();return t.done?null:t.value}querySelectorAll(e){return e=e.toUpperCase(),Xn(new jo(this,(t=>t.nodeName&&t.nodeName.toUpperCase()===e)))}_callObserver(e,t){qs(this,e,new Ro(this,t,e))}toString(){return Zs(this,(e=>e.toString())).join("")}toJSON(){return this.toString()}toDOM(e=document,t={},n){const r=e.createDocumentFragment();return void 0!==n&&n._createAssociation(r,this),Xs(this,(i=>{r.insertBefore(i.toDOM(e,t,n),null)})),r}insert(e,t){null!==this.doc?Ds(this.doc,(n=>{io(n,this,e,t)})):this._prelimContent.splice(e,0,...t)}insertAfter(e,t){if(null!==this.doc)Ds(this.doc,(n=>{const r=e&&e instanceof Ys?e._item:e;no(n,this,r,t)}));else{const n=this._prelimContent,r=null===e?0:n.findIndex((t=>t===e))+1;if(0===r&&null!==e)throw $r("Reference item not found");n.splice(r,0,...t)}}delete(e,t=1){null!==this.doc?Ds(this.doc,(n=>{so(n,this,e,t)})):this._prelimContent.splice(e,t)}toArray(){return Qs(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return to(this,e)}slice(e=0,t=this.length){return Gs(this,e,t)}forEach(e){Xs(this,e)}_write(e){e.writeTypeRef(nc)}}class Lo extends Po{constructor(e="UNDEFINED"){super(),this.nodeName=e,this._prelimAttrs=new Map}get nextSibling(){const e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){const e=this._item?this._item.prev:null;return e?e.content.type:null}_integrate(e,t){super._integrate(e,t),this._prelimAttrs.forEach(((e,t)=>{this.setAttribute(t,e)})),this._prelimAttrs=null}_copy(){return new Lo(this.nodeName)}clone(){const e=new Lo(this.nodeName);return((e,t)=>{for(const n in e)t(e[n],n)})(this.getAttributes(),((t,n)=>{"string"==typeof t&&e.setAttribute(n,t)})),e.insert(0,this.toArray().map((e=>e instanceof Ys?e.clone():e))),e}toString(){const e=this.getAttributes(),t=[],n=[];for(const t in e)n.push(t);n.sort();const r=n.length;for(let i=0;i<r;i++){const r=n[i];t.push(r+'="'+e[r]+'"')}const i=this.nodeName.toLocaleLowerCase();return`<${i}${t.length>0?" "+t.join(" "):""}>${super.toString()}</${i}>`}removeAttribute(e){null!==this.doc?Ds(this.doc,(t=>{oo(t,this,e)})):this._prelimAttrs.delete(e)}setAttribute(e,t){null!==this.doc?Ds(this.doc,(n=>{co(n,this,e,t)})):this._prelimAttrs.set(e,t)}getAttribute(e){return lo(this,e)}hasAttribute(e){return uo(this,e)}getAttributes(e){return e?((e,t)=>{const n={};return e._map.forEach(((e,r)=>{let i=e;for(;null!==i&&(!t.sv.has(i.id.client)||i.id.clock>=(t.sv.get(i.id.client)||0));)i=i.left;null!==i&&fs(i,t)&&(n[r]=i.content.getContent()[i.length-1])})),n})(this,e):ao(this)}toDOM(e=document,t={},n){const r=e.createElement(this.nodeName),i=this.getAttributes();for(const e in i){const t=i[e];"string"==typeof t&&r.setAttribute(e,t)}return Xs(this,(i=>{r.appendChild(i.toDOM(e,t,n))})),void 0!==n&&n._createAssociation(r,this),r}_write(e){e.writeTypeRef(tc),e.writeKey(this.nodeName)}}class Ro extends Bs{constructor(e,t,n){super(e,n),this.childListChanged=!1,this.attributesChanged=new Set,t.forEach((e=>{null===e?this.childListChanged=!0:this.attributesChanged.add(e)}))}}class No extends yo{constructor(e){super(),this.hookName=e}_copy(){return new No(this.hookName)}clone(){const e=new No(this.hookName);return this.forEach(((t,n)=>{e.set(n,t)})),e}toDOM(e=document,t={},n){const r=t[this.hookName];let i;return i=void 0!==r?r.createDom(this):document.createElement(this.hookName),i.setAttribute("data-yjs-hook",this.hookName),void 0!==n&&n._createAssociation(i,this),i}_write(e){e.writeTypeRef(rc),e.writeKey(this.hookName)}}class $o extends Uo{get nextSibling(){const e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){const e=this._item?this._item.prev:null;return e?e.content.type:null}_copy(){return new $o}clone(){const e=new $o;return e.applyDelta(this.toDelta()),e}toDOM(e=document,t,n){const r=e.createTextNode(this.toString());return void 0!==n&&n._createAssociation(r,this),r}toString(){return this.toDelta().map((e=>{const t=[];for(const n in e.attributes){const r=[];for(const t in e.attributes[n])r.push({key:t,value:e.attributes[n][t]});r.sort(((e,t)=>e.key<t.key?-1:1)),t.push({nodeName:n,attrs:r})}t.sort(((e,t)=>e.nodeName<t.nodeName?-1:1));let n="";for(let e=0;e<t.length;e++){const r=t[e];n+=`<${r.nodeName}`;for(let e=0;e<r.attrs.length;e++){const t=r.attrs[e];n+=` ${t.key}="${t.value}"`}n+=">"}n+=e.insert;for(let e=t.length-1;e>=0;e--)n+=`</${t[e].nodeName}>`;return n})).join("")}toJSON(){return this.toString()}_write(e){e.writeTypeRef(ic)}}class Mo{constructor(e,t){this.id=e,this.length=t}get deleted(){throw Mr()}mergeWith(e){return!1}write(e,t,n){throw Mr()}integrate(e,t){throw Mr()}}class Bo extends Mo{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor===e.constructor&&(this.length+=e.length,!0)}integrate(e,t){t>0&&(this.id.clock+=t,this.length-=t),ms(e.doc.store,this)}write(e,t){e.writeInfo(0),e.writeLen(this.length-t)}getMissing(e,t){return null}}class Fo{constructor(e){this.content=e}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new Fo(this.content)}splice(e){throw Mr()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeBuf(this.content)}getRef(){return 3}}class Wo{constructor(e){this.len=e}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new Wo(this.len)}splice(e){const t=new Wo(this.len-e);return this.len=e,t}mergeWith(e){return this.len+=e.len,!0}integrate(e,t){Hi(e.deleteSet,t.id.client,t.id.clock,this.len),t.markDeleted()}delete(e){}gc(e){}write(e,t){e.writeLen(this.len-t)}getRef(){return 1}}const Vo=(e,t)=>new Yi({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1});class Ko{constructor(e){e._item,this.doc=e;const t={};this.opts=t,e.gc||(t.gc=!1),e.autoLoad&&(t.autoLoad=!0),null!==e.meta&&(t.meta=e.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new Ko(Vo(this.doc.guid,this.opts))}splice(e){throw Mr()}mergeWith(e){return!1}integrate(e,t){this.doc._item=t,e.subdocsAdded.add(this.doc),this.doc.shouldLoad&&e.subdocsLoaded.add(this.doc)}delete(e){e.subdocsAdded.has(this.doc)?e.subdocsAdded.delete(this.doc):e.subdocsRemoved.add(this.doc)}gc(e){}write(e,t){e.writeString(this.doc.guid),e.writeAny(this.opts)}getRef(){return 9}}class Ho{constructor(e){this.embed=e}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new Ho(this.embed)}splice(e){throw Mr()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeJSON(this.embed)}getRef(){return 5}}class zo{constructor(e,t){this.key=e,this.value=t}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new zo(this.key,this.value)}splice(e){throw Mr()}mergeWith(e){return!1}integrate(e,t){const n=t.parent;n._searchMarker=null,n._hasFormatting=!0}delete(e){}gc(e){}write(e,t){e.writeKey(this.key),e.writeJSON(this.value)}getRef(){return 6}}class Jo{constructor(e){this.arr=e}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new Jo(this.arr)}splice(e){const t=new Jo(this.arr.slice(e));return this.arr=this.arr.slice(0,e),t}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){const n=this.arr.length;e.writeLen(n-t);for(let r=t;r<n;r++){const t=this.arr[r];e.writeString(void 0===t?"undefined":JSON.stringify(t))}}getRef(){return 2}}const qo="development"===ki("node_env");class Yo{constructor(e){this.arr=e,qo&&vi(e)}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new Yo(this.arr)}splice(e){const t=new Yo(this.arr.slice(e));return this.arr=this.arr.slice(0,e),t}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){const n=this.arr.length;e.writeLen(n-t);for(let r=t;r<n;r++){const t=this.arr[r];e.writeAny(t)}}getRef(){return 8}}class Go{constructor(e){this.str=e}getLength(){return this.str.length}getContent(){return this.str.split("")}isCountable(){return!0}copy(){return new Go(this.str)}splice(e){const t=new Go(this.str.slice(e));this.str=this.str.slice(0,e);const n=this.str.charCodeAt(e-1);return n>=55296&&n<=56319&&(this.str=this.str.slice(0,e-1)+"�",t.str="�"+t.str.slice(1)),t}mergeWith(e){return this.str+=e.str,!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeString(0===t?this.str:this.str.slice(t))}getRef(){return 4}}const Qo=[e=>new po,e=>new yo,e=>new Uo,e=>new Lo(e.readKey()),e=>new Po,e=>new No(e.readKey()),e=>new $o],Xo=0,Zo=1,ec=2,tc=3,nc=4,rc=5,ic=6;class sc{constructor(e){this.type=e}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new sc(this.type._copy())}splice(e){throw Mr()}mergeWith(e){return!1}integrate(e,t){this.type._integrate(e.doc,t)}delete(e){let t=this.type._start;for(;null!==t;)t.deleted?t.id.clock<(e.beforeState.get(t.id.client)||0)&&e._mergeStructs.push(t):t.delete(e),t=t.right;this.type._map.forEach((t=>{t.deleted?t.id.clock<(e.beforeState.get(t.id.client)||0)&&e._mergeStructs.push(t):t.delete(e)})),e.changed.delete(this.type)}gc(e){let t=this.type._start;for(;null!==t;)t.gc(e,!0),t=t.right;this.type._start=null,this.type._map.forEach((t=>{for(;null!==t;)t.gc(e,!0),t=t.left})),this.type._map=new Map}write(e,t){this.type._write(e)}getRef(){return 7}}const oc=(e,t,n)=>{const{client:r,clock:i}=t.id,s=new cc(hs(r,i+n),t,hs(r,i+n-1),t.right,t.rightOrigin,t.parent,t.parentSub,t.content.splice(n));return t.deleted&&s.markDeleted(),t.keep&&(s.keep=!0),null!==t.redone&&(s.redone=hs(t.redone.client,t.redone.clock+n)),t.right=s,null!==s.right&&(s.right.left=s),e._mergeStructs.push(s),null!==s.parentSub&&null===s.right&&s.parent._map.set(s.parentSub,s),t.length=n,s};class cc extends Mo{constructor(e,t,n,r,i,s,o,c){super(e,c.getLength()),this.origin=n,this.left=t,this.right=r,this.rightOrigin=i,this.parent=s,this.parentSub=o,this.redone=null,this.content=c,this.info=this.content.isCountable()?2:0}set marker(e){(8&this.info)>0!==e&&(this.info^=8)}get marker(){return(8&this.info)>0}get keep(){return(1&this.info)>0}set keep(e){this.keep!==e&&(this.info^=1)}get countable(){return(2&this.info)>0}get deleted(){return(4&this.info)>0}set deleted(e){this.deleted!==e&&(this.info^=4)}markDeleted(){this.info|=4}getMissing(e,t){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=vs(t,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=vs(t,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===us&&this.id.client!==this.parent.client&&this.parent.clock>=vs(t,this.parent.client))return this.parent.client;if(this.origin&&(this.left=Ss(e,t,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=ks(e,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===Bo||this.right&&this.right.constructor===Bo)this.parent=null;else if(this.parent){if(this.parent.constructor===us){const e=ws(t,this.parent);e.constructor===Bo?this.parent=null:this.parent=e.content.type}}else this.left&&this.left.constructor===cc?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===cc&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);return null}integrate(e,t){if(t>0&&(this.id.clock+=t,this.left=Ss(e,e.doc.store,hs(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(t),this.length-=t),this.parent){if(!this.left&&(!this.right||null!==this.right.left)||this.left&&this.left.right!==this.right){let t,n=this.left;if(null!==n)t=n.right;else if(null!==this.parentSub)for(t=this.parent._map.get(this.parentSub)||null;null!==t&&null!==t.left;)t=t.left;else t=this.parent._start;const r=new Set,i=new Set;for(;null!==t&&t!==this.right;){if(i.add(t),r.add(t),ds(this.origin,t.origin)){if(t.id.client<this.id.client)n=t,r.clear();else if(ds(this.rightOrigin,t.rightOrigin))break}else{if(null===t.origin||!i.has(ws(e.doc.store,t.origin)))break;r.has(ws(e.doc.store,t.origin))||(n=t,r.clear())}t=t.right}this.left=n}if(null!==this.left){const e=this.left.right;this.right=e,this.left.right=this}else{let e;if(null!==this.parentSub)for(e=this.parent._map.get(this.parentSub)||null;null!==e&&null!==e.left;)e=e.left;else e=this.parent._start,this.parent._start=this;this.right=e}null!==this.right?this.right.left=this:null!==this.parentSub&&(this.parent._map.set(this.parentSub,this),null!==this.left&&this.left.delete(e)),null===this.parentSub&&this.countable&&!this.deleted&&(this.parent._length+=this.length),ms(e.doc.store,this),this.content.integrate(e,this),Cs(e,this.parent,this.parentSub),(null!==this.parent._item&&this.parent._item.deleted||null!==this.parentSub&&null!==this.right)&&this.delete(e)}else new Bo(this.id,this.length).integrate(e,0)}get next(){let e=this.right;for(;null!==e&&e.deleted;)e=e.right;return e}get prev(){let e=this.left;for(;null!==e&&e.deleted;)e=e.left;return e}get lastId(){return 1===this.length?this.id:hs(this.id.client,this.id.clock+this.length-1)}mergeWith(e){if(this.constructor===e.constructor&&ds(e.origin,this.lastId)&&this.right===e&&ds(this.rightOrigin,e.rightOrigin)&&this.id.client===e.id.client&&this.id.clock+this.length===e.id.clock&&this.deleted===e.deleted&&null===this.redone&&null===e.redone&&this.content.constructor===e.content.constructor&&this.content.mergeWith(e.content)){const t=this.parent._searchMarker;return t&&t.forEach((t=>{t.p===e&&(t.p=this,!this.deleted&&this.countable&&(t.index-=this.length))})),e.keep&&(this.keep=!0),this.right=e.right,null!==this.right&&(this.right.left=this),this.length+=e.length,!0}return!1}delete(e){if(!this.deleted){const t=this.parent;this.countable&&null===this.parentSub&&(t._length-=this.length),this.markDeleted(),Hi(e.deleteSet,this.id.client,this.id.clock,this.length),Cs(e,t,this.parentSub),this.content.delete(e)}}gc(e,t){if(!this.deleted)throw Br();this.content.gc(e),t?((e,t,n)=>{const r=e.clients.get(t.id.client);r[bs(r,t.id.clock)]=n})(e,this,new Bo(this.id,this.length)):this.content=new Wo(this.length)}write(e,t){const n=t>0?hs(this.id.client,this.id.clock+t-1):this.origin,r=this.rightOrigin,i=this.parentSub,s=31&this.content.getRef()|(null===n?0:cr)|(null===r?0:or)|(null===i?0:32);if(e.writeInfo(s),null!==n&&e.writeLeftID(n),null!==r&&e.writeRightID(r),null===n&&null===r){const t=this.parent;if(void 0!==t._item){const n=t._item;if(null===n){const n=(e=>{for(const[t,n]of e.doc.share.entries())if(n===e)return t;throw Br()})(t);e.writeParentInfo(!0),e.writeString(n)}else e.writeParentInfo(!1),e.writeLeftID(n.id)}else t.constructor===String?(e.writeParentInfo(!0),e.writeString(t)):t.constructor===us?(e.writeParentInfo(!1),e.writeLeftID(t)):Br();null!==i&&e.writeString(i)}this.content.write(e,t)}}const lc=(e,t)=>ac[31&t](e),ac=[()=>{Br()},e=>new Wo(e.readLen()),e=>{const t=e.readLen(),n=[];for(let r=0;r<t;r++){const t=e.readString();"undefined"===t?n.push(void 0):n.push(JSON.parse(t))}return new Jo(n)},e=>new Fo(e.readBuf()),e=>new Go(e.readString()),e=>new Ho(e.readJSON()),e=>new zo(e.readKey(),e.readJSON()),e=>new sc(Qo[e.readTypeRef()](e)),e=>{const t=e.readLen(),n=[];for(let r=0;r<t;r++)n.push(e.readAny());return new Yo(n)},e=>new Ko(Vo(e.readString(),e.readAny())),()=>{Br()}];class uc extends Mo{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor===e.constructor&&(this.length+=e.length,!0)}integrate(e,t){Br()}write(e,t){e.writeInfo(10),kr(e.restEncoder,this.length-t)}getMissing(e,t){return null}}const dc="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{},hc="__ $YJS$ __";function fc(e,t,n){var r,i,s;if(!e.dx._allTables[t])return;const o=null===(s=null===(i=null===(r=e.table(t))||void 0===r?void 0:r.schema.yProps)||void 0===i?void 0:i.find((e=>e.prop===n)))||void 0===s?void 0:s.updatesTable;return o&&e.dx._allTables[o]?e.table(o):void 0}dc[hc],dc[hc]=!0;const pc=new FinalizationRegistry((({cache:e,key:t})=>{delete e[t]}));function gc(e){var t,n;return null!==(t=(n=e._novip)._docCache)&&void 0!==t?t:n._docCache={cache:{},get size(){return Object.keys(this.cache).length},find(e,t,n){const r=mc(e,t,n),i=this.cache[r];return i?i.deref():void 0},add(e){var t;const{parentTable:n,parentId:r,parentProp:i}=e.meta;if(!n||!i||null==r)throw new Error("Missing Dexie-related metadata in Y.Doc");const s=mc(n,r,i),o=null===(t=this.cache[s])||void 0===t?void 0:t.deref();o&&pc.unregister(o),this.cache[s]=new WeakRef(e),pc.register(e,{cache:this.cache,key:s},e)},delete(e){pc.unregister(e);const t=mc(e.meta.parentTable,e.meta.parentId,e.meta.parentProp),n=this.cache[t];(null==n?void 0:n.deref())===e&&delete this.cache[t]}}}const yc=new WeakSet;function vc(e){if(yc.has(e))throw new Error(`Y.Doc ${e.meta.parentId} has been destroyed`)}function mc(e,t,n){return`${e}[${t}].${n}`}let bc=null;function wc(e){bc=e}function _c(){}const kc=new WeakMap;function Sc(){return t.Dexie.Events(null,"load","sync","error")}class Ec{static getOrCreateDocument(e,t,n,r){var i,s;const o=gc(e),c=null===(s=null===(i=e.table(t).schema.yProps)||void 0===i?void 0:i.find((e=>e.prop===n)))||void 0===s?void 0:s.updatesTable;if(!c)throw new Error(`Updates table for ${t}.${n} not found`);return function(e,t,n,r,i,s){let o=t.find(n,s,r);return o||(o=new Yi({meta:{db:e,updatesTable:i,parentProp:r,parentTable:n,parentId:s}}),t.add(o),o.on("destroy",(()=>{yc.add(o),t.delete(o)})),o)}(e,o,t,n,c,r)}static load(e,t){var n;let r=kc.get(e);return r?(++r.refCount,null!=(null==t?void 0:t.gracePeriod)&&r.graceTimeout<t.gracePeriod&&(r.graceTimeout=t.gracePeriod),r.graceTimer&&(clearTimeout(r.graceTimer),r.graceTimer=null)):(r=new Ec(e),r.graceTimeout=null!==(n=null==t?void 0:t.gracePeriod)&&void 0!==n?n:-1,kc.set(e,r)),r}static release(e){if(!e||yc.has(e))return;const t=kc.get(e);t?--t.refCount<=0&&(t.graceTimeout<0?t._release():t.graceTimer||(t.graceTimer=setTimeout((()=>{t.graceTimer=null,0===t.refCount&&t._release()}),t.graceTimeout))):e.destroy()}_release(){this.doc&&Promise.resolve(Ec.on("beforeunload").fire(this)).finally((()=>{var e;0===this.refCount&&(null===(e=this.doc)||void 0===e||e.destroy())}))}static for(e){return kc.get(e)}static get currentUpdateRow(){return bc}get whenLoaded(){return this._whenLoaded||(this._whenLoaded=new Promise(((e,n)=>{this.doc?this.doc.isLoaded?e():this._error?n(this._error):yc.has(this.doc)?n(new t.Dexie.AbortError("Document was destroyed before loaded")):(this.on("load",e),this.on("error",n),this.doc.on("destroy",(()=>n(new t.Dexie.AbortError("Document was destroyed before loaded"))))):n(new Error("No Y.Doc associated with this provider"))}))),this._whenLoaded}get whenSynced(){return this._whenSynced||(this._whenSynced=new Promise(((e,n)=>{this.doc?this.doc.isSynced?e():this._error?n(this._error):yc.has(this.doc)?n(new t.Dexie.AbortError("Document was destroyed before synced")):(this.on("sync",e),this.on("error",n),this.doc.on("destroy",(()=>n(new t.Dexie.AbortError("Document was destroyed before synced"))))):n(new Error("No Y.Doc associated with this provider"))}))),this._whenSynced}constructor(e){this.refCount=1,this.cleanupHandlers=[],this.graceTimeout=-1,this.doc=null,this.destroyed=!1,this.on=Sc(),this.doc=e,this.off=(e,t)=>{var n;return null===(n=this.on[e])||void 0===n?void 0:n.unsubscribe(t)},"dispose"in Symbol&&(this[Symbol.dispose]=()=>Ec.release(e)),e.on("load",(()=>this.on("load").fire())),e.on("sync",(e=>!1!==e&&this.on("sync").fire())),e.on("destroy",this.destroy.bind(this)),this.on("error",(e=>{this._error=e}));const{db:n,parentTable:r,parentId:i,updatesTable:s}=e.meta||{};if(!n||!r||!s)throw new Error("Missing Dexie-related metadata in Y.Doc. Documents need to be obtained through Y.Doc properties from dexie queries.");if(!n.table(r)||!n.table(s))throw new Error(`Table ${r} or ${s} not found in db`);vc(e),this.stopObserving=function(e,n,r,i,s,o){let c=0,l=!0;const a=t.liveQuery((()=>{vc(n);const e=r.table(s);return Promise.all([(c>0?e.where("i").between(c,1/0,!1).toArray().then((e=>e.filter((e=>0===t.cmp(e.k,o))))):e.where({k:o}).toArray()).then((e=>e)),r.table(i).where(":id").equals(o).toArray()])})).subscribe((([t,r])=>{t.length>0&&(c=t[t.length-1].i),0!==r.length?(vc(n),t.length>0&&Ds(n,(()=>{t.forEach((e=>{try{wc(e),is(n,e.u)}finally{wc(null)}}))}),e,!1),l&&(l=!1,n.emit("load",[n]))):n.destroy()}),(t=>{e.on("error").fire(t)})),u=(t,n)=>{n!==e&&r.table(s).add({k:o,u:t,f:1}).then((e=>{e===c-1&&++c})).catch((t=>{e.on("error").fire(t)}))},d=()=>{a.unsubscribe(),n.off("updateV2",u),n.off("destroy",d)};return n.on("updateV2",u),n.on("destroy",d),d}(this,e,n,r,s,i),Ec.on("new").fire(this)}destroy(){var e;kc.delete(this.doc),this.doc=null,this.destroyed=!0,this.refCount=0,null===(e=this.stopObserving)||void 0===e||e.call(this),this.on=Sc(),this.cleanupHandlers.forEach((e=>e()))}addCleanupHandler(e){this.cleanupHandlers.push("function"==typeof e?e:()=>e.unsubscribe())}}function xc(e,n){return s(this,void 0,void 0,(function*(){var r;const i={};let o,c=!1;for(const l of e)try{switch(l.type){case"u-s":{const e=fc(n,l.table,l.prop);if(e){const t={k:l.k,u:l.u};l.r&&(t.r=l.r,o=l.r),i[e.name]=yield e.add(t)}break}case"u-ack":{const e=fc(n,l.table,l.prop);e&&(yield n.transaction("rw",e,(t=>s(this,void 0,void 0,(function*(){let n=yield t.table(e.name).get(Kn);yield t.table(e.name).put(Object.assign(Object.assign({},n||{i:Kn}),{unsentFrom:Math.max((null==n?void 0:n.unsentFrom)||1,l.i+1)}))})))));break}case"u-reject":{const e=fc(n,l.table,l.prop);if(!e)break;const i=null===(r=yield e.get(l.i))||void 0===r?void 0:r.k;if(null!=i){yield n.transaction("rw",e,(n=>(n.idbtrans._rejecting_y_ypdate=!0,e.where("i").aboveOrEqual(l.i).filter((e=>0===t.cmp(e.k,i)&&1==(1&(e.f||0)))).delete())));const r=Ec.getDocCache(n.dx).find(l.table,i,l.prop);r&&r.destroy()}break}case"in-sync":{const e=Ec.getDocCache(n.dx).find(l.table,l.k,l.prop);e&&!e.isSynced&&e.emit("sync",[!0,e]);break}case"y-complete-sync-done":o=l.yServerRev;break;case"outdated-server-rev":c=!0}}catch(e){}return{receivedUntils:i,resyncNeeded:c,yServerRevision:o}}))}Ec.on=t.Dexie.Events(null,{new:[function(e,t){return e===_c?t:function(){e.apply(this,arguments),t.apply(this,arguments)}}],beforeunload:[function(e,t){return e===_c?t:function(){var n=e.apply(this,arguments);if(n&&"function"==typeof n.then){for(var r=this,i=arguments.length,s=new Array(i);i--;)s[i]=arguments[i];return n.then((function(){return t.apply(r,s)}))}return t.apply(this,arguments)}}]}),Ec.getDocCache=gc,t.Dexie.DexieYProvider=Ec;const Ic=1,Cc=2,Ac=3;function Oc(e,n,r){return s(this,arguments,void 0,(function*(e,n,{yDownloadedRealms:r,realms:i}){if(r&&i&&i.every((e=>"*"===r[e])))return;const o=yield Tt(e),c={"Content-Type":"application/json",Accept:"application/octet-stream"};o&&(c.Authorization=`Bearer ${o.accessToken}`);const l=yield fetch(`${n}/y/download`,{body:Tn.stringify({downloadedRealms:r||{}}),method:"POST",headers:c,credentials:"include"});if(!l.ok)throw new Error(`Failed to download Yjs documents from server. Status: ${l.status}`);yield async function(e,...t){var n,r,i;let s=e();for(let e=0;e<t.length;e++)s=t[e](s);try{for(var o,c=!0,l=h(s);!(n=(o=await l.next()).done);c=!0)o.value,c=!1}catch(e){r={error:e}}finally{try{c||n||!(i=l.return)||await i.call(l)}finally{if(r)throw r.error}}}(function(e){return function(){return d(this,arguments,(function*(){if(!e.body)throw new Error("Response body is not readable");const t=e.body.getReader();try{for(;;){const{done:e,value:n}=yield u(t.read());if(e)return yield u(void 0);yield yield u(n)}}finally{t.releaseLock()}}))}}(l),re,(function(r){return d(this,arguments,(function*(){var i,o,c,l;let a=null,d=null,f=null,p=[];function g(t){return s(this,void 0,void 0,(function*(){const r=p[p.length-1];if(p.length>0){if(!a||!d||!f)throw new Error(`Protocol error from ${n}/y/download`);const t=fc(e,d,f);t&&(yield t.bulkAdd(p)),p=[]}a&&(d&&f&&r||t)&&(yield e.$syncState.update("syncState",(e=>{const n=e.yDownloadedRealms||{};n[a]=t?"*":{tbl:d,prop:f,key:r.k},e.yDownloadedRealms=n})))}))}try{try{for(var y,v=!0,m=h(r);!(i=(y=yield u(m.next())).done);v=!0){l=y.value,v=!1;const e=new J(l);for(;q(e);)switch(G(e)){case Ic:yield u(g(!0)),a=X(e);break;case Cc:yield u(g(!1)),d=X(e),f=X(e);break;case Ac:{const t=ne(e),n=Y(e);p.push({k:t,u:n});break}}yield u(g(!1))}}catch(e){o={error:e}}finally{try{v||i||!(c=m.return)||(yield u(c.call(m)))}finally{if(o)throw o.error}}yield u(g(!0))}catch(e){throw e instanceof t.DexieError||(yield u(g(!1))),e}}))}))}))}const Dc="currentSyncWorker";function Tc(e,t,n,r){return Uc(e,t,n,r).then((t=>((null==r?void 0:r.justCheckIfNeeded)||e.syncStateChangedEvent.next({phase:"in-sync"}),t))).catch((i=>s(this,void 0,void 0,(function*(){return(null==r?void 0:r.justCheckIfNeeded)?Promise.reject(i):Mn&&(null==r?void 0:r.retryImmediatelyOnFetchError)&&"TypeError"===(null==i?void 0:i.name)&&/fetch/.test(null==i?void 0:i.message)?(e.syncStateChangedEvent.next({phase:"error",error:i}),yield new Promise((e=>setTimeout(e,500))),yield Tc(e,t,n,Object.assign(Object.assign({},r),{retryImmediatelyOnFetchError:!1}))):(yield e.$syncState.update("syncState",{timestamp:new Date,error:""+i}),e.syncStateChangedEvent.next({phase:Mn?"error":"offline",error:new Error(""+(null==i?void 0:i.message)||i)}),Promise.reject(i))}))))}function Uc(e,t,n){return s(this,arguments,void 0,(function*(e,t,n,{isInitialSync:r,cancelToken:i,justCheckIfNeeded:o,purpose:c}={isInitialSync:!1}){var l;if(!(null===(l=e.cloud.options)||void 0===l?void 0:l.databaseUrl))throw new Error("Internal error: sync must not be called when no databaseUrl is configured");const{databaseUrl:a}=t,u=yield e.getCurrentUser(),d=u.isLoggedIn?Yt(e):[],h=d.map((t=>e.table(Gt(t.name)))),f=yield e.getPersistedSyncState(),p=u.isLoggedIn,y=p?function(e,t){const n=(null==t?void 0:t.syncedTables)||[];return Yt(e).filter((e=>!n.includes(e.name)))}(e,f):[];$n(i);const m=y.length>0;if(m){if(o)return!0;yield e.transaction("rw",y,(e=>s(this,void 0,void 0,(function*(){e.idbtrans.disableChangeTracking=!0,e.idbtrans.disableAccessControl=!0,yield function(e,t,n){return s(this,void 0,void 0,(function*(){const r=new Set(n||[]);for(const n of e)"members"===n.name?yield n.toCollection().modify((e=>{r.has(e.realmId)||e.userId&&e.userId!==Rt.userId||(e.userId=t.userId)})):"roles"===n.name||("realms"===n.name?yield n.toCollection().modify((e=>{r.has(e.realmId)||void 0!==e.owner&&e.owner!==Rt.userId||(e.owner=t.userId)})):yield n.toCollection().modify((e=>{e.realmId&&r.has(e.realmId)||(e.owner&&e.owner!==Rt.userId||(e.owner=t.userId),e.realmId&&e.realmId!==Rt.userId||(e.realmId=t.userId))})))}))}(y,u,null==f?void 0:f.realms)})))),$n(i)}const[b,w,_,{yMessages:k,lastUpdateIds:S}]=yield e.transaction("r",e.tables,(()=>s(this,void 0,void 0,(function*(){const t=yield e.getPersistedSyncState();let r=yield e.$baseRevs.toArray();r=r.filter((e=>d.some((t=>t.name===e.tableName))));let o=yield en(h,e);const c=yield function(e,t){return s(this,void 0,void 0,(function*(){const n=[],r={};for(const i of t)if(i.schema.yProps)for(const t of i.schema.yProps){const s=e.table(t.updatesTable),o=yield s.get(Kn),c=(null==o?void 0:o.unsentFrom)||1,l=(null==o?void 0:o.receivedUntil)||0,a=Math.min(c,l+1),u=yield Hn(s,a);u.length>0&&(r[s.name]=u[u.length-1].i);const d={};for(const e of u){const t=1==(1&(e.f||0));if(t&&e.i<c)continue;const n=JSON.stringify(e.k)+"/"+t;let r=d[n];r?(r.u.push(e.u),r.i=Math.max(e.i,r.i)):(d[n]=r={i:e.i,k:e.k,isLocal:t,u:[]},r.u.push(e.u))}for(const{k:e,isLocal:r,u:s,i:o}of Object.values(d)){const c=1===s.length?s[0]:Ls(s);if(r)n.push({type:"u-c",table:i.name,prop:t.prop,k:e,u:c,i:o});else{const r=js(c);n.push({type:"sv",table:i.name,prop:t.prop,k:e,sv:r})}}}return{yMessages:n,lastUpdateIds:r}}))}(e,d);if($n(i),m){const e=[...(null==f?void 0:f.realms)||[],...(null==f?void 0:f.inviteRealms)||[]],l=yield function(e,t,n,r){return s(this,void 0,void 0,(function*(){const i=`upload-${tn(8)}`;if(t.isLoggedIn&&e.length>0){const o=new Set(r||[]);return(yield Promise.all(e.map((e=>s(this,void 0,void 0,(function*(){const{extractKey:r}=e.core.schema.primaryKey;if(!r)return{table:e.name,muts:[]};const s=n[e.name],c=(null==s?void 0:s.generatedGlobalId)?e.filter((e=>{return r(e),!o.has(e.realmId||"")&&(t=r(e),!(n=null==s?void 0:s.idPrefix)||"string"==typeof t&&t.startsWith(n));var t,n})):e.filter((e=>{const t=r(e);return!o.has(e.realmId||"")&&v(t)})),l=yield c.toArray();if(l.length>0){const n={type:"upsert",values:l,keys:l.map(r),userId:t.userId,txid:i};return{table:e.name,muts:[n]}}return{table:e.name,muts:[]}})))))).filter((e=>e.muts.length>0))}return[]}))}(y,u,n,e);return $n(i),o=o.concat(l),[o,t,r,c]}return[o,t,r,c]})))),E=b.some((e=>e.muts.some((e=>e.keys.length>0))))||k.some((e=>"u-c"===e.type));if(o)return E;if("push"===c&&!E)return!1;const x=Fn(b,null==w?void 0:w.latestRevisions),I=(null==w?void 0:w.clientIdentity)||g(16);$n(i);const C=yield Nn(b,k,w,_,e,a,n,I,u),{done:A,newSyncState:O}=yield e.transaction("rw",e.tables,(t=>s(this,void 0,void 0,(function*(){t.idbtrans.disableChangeTracking=!0,t.idbtrans.disableAccessControl=!0;for(const e of Object.keys(n))C.schema[e]&&(n[e]=C.schema[e]);yield e.$syncState.put(n,"schema");const r=yield en(h,e,{since:x});for(const t of h){const n=Qt(t.name);if(r.some((e=>e.table===n&&e.muts.length>0))){if(x[n]){const r=x[n]||0;yield Promise.all([t.where("rev").belowOrEqual(r).delete(),e.$baseRevs.where(":id").between([n,-1/0],[n,r+1],!0,!0).reverse().offset(1).delete()])}}else yield Promise.all([t.clear(),e.$baseRevs.where({tableName:n}).delete()])}Fn(r,x),yield Bn(e,n,x,C.serverRevision);const i=yield e.getPersistedSyncState();yield function(e,t,n){return s(this,void 0,void 0,(function*(){const r=new Set,i=new Set,s=n?n.realms:[],o=n?n.inviteRealms:[],c=new Set(t.realms),l=new Set(t.realms.concat(t.inviteRealms));for(const e of s)c.has(e)||(i.add(e),l.has(e)||r.add(e));for(const e of o.concat(s))l.has(e)||r.add(e);if(r.size>0||i.size>0){const t=Yt(e);for(const e of t){let t=["realms","members","roles"].includes(e.name)?r:i;0!==t.size&&(e.schema.indexes.some((e=>"realmId"===e.keyPath||Array.isArray(e.keyPath)&&"realmId"===e.keyPath[0]))?yield e.where("realmId").anyOf([...t]).delete():yield e.filter((e=>!!(null==e?void 0:e.realmId)&&t.has(e.realmId))).delete())}}if(i.size>0&&(null==n?void 0:n.yDownloadedRealms))for(const e of i)delete n.yDownloadedRealms[e]}))}(e,C,i);const o=i||{syncedTables:[],latestRevisions:{},realms:[],inviteRealms:[],clientIdentity:I};p&&(o.syncedTables=d.map((e=>e.name)).concat(y.map((e=>e.name)))),o.latestRevisions=x,o.remoteDbId=C.dbId,o.initiallySynced=!0,o.realms=C.realms,o.inviteRealms=C.inviteRealms,o.serverRevision=C.serverRevision,o.yServerRevision=C.serverRevision,o.timestamp=new Date,delete o.error;const c=jc(C.changes,r);if(yield Vn(c,e),C.yMessages){const{receivedUntils:t,resyncNeeded:n,yServerRevision:r}=yield xc(C.yMessages,e);r&&(o.yServerRevision=r),yield function(e,t,n){return s(this,void 0,void 0,(function*(){var r,i,o,c,l;const a={};for(const[t,n]of Object.entries(e))null!==(r=a[t])&&void 0!==r||(a[t]={}),a[t].unsentFrom=n+1;for(const[e,n]of Object.entries(t))null!==(i=a[e])&&void 0!==i||(a[e]={}),a[e].receivedUntil=n;const u=Object.values(n.dx._dbSchema).filter((e=>e.yProps)).map((e=>e.yProps.map((e=>e.updatesTable)))).flat();for(const e of u){const t=a[e],r=null!==(o=null==t?void 0:t.unsentFrom)&&void 0!==o?o:1,i=null!==(l=null!==(c=null==t?void 0:t.receivedUntil)&&void 0!==c?c:(yield n.table(e).where("i").between(1,1/0).reverse().limit(1).primaryKeys())[0])&&void 0!==l?l:0;yield n.transaction("rw",e,(()=>s(this,void 0,void 0,(function*(){const t=yield n.table(e).get(Kn);t?(t.unsentFrom=Math.max(r,t.unsentFrom||1),t.receivedUntil=Math.max(i,t.receivedUntil||0),yield n.table(e).put(t)):yield n.table(e).add({i:Kn,unsentFrom:r,receivedUntil:i})}))))}}))}(S,t,e),n&&(o.yDownloadedRealms={})}return e.$syncState.put(o,"syncState"),{done:0===r.length,newSyncState:o}}))));if(!A)return yield Rn(e),yield Uc(e,t,n,{isInitialSync:r,cancelToken:i});const D=Object.values(n).some((e=>{var t;return null===(t=e.yProps)||void 0===t?void 0:t.length})),T=!!C.yMessages;if(D&&T)try{yield Oc(e,a,O)}catch(e){}return e.syncCompleteEvent.next(),!1}))}function jc(e,t){const n={};w(n,e);const r={};return w(r,t),function(e,t){var n,r,i;for(const[s,o]of Object.entries(t))for(const[t,c]of Object.entries(o))switch(c.type){case"ups":{const r=null===(n=e[s])||void 0===n?void 0:n[t];if(r)switch(r.type){case"ups":case"upd":delete e[s][t]}}break;case"del":null===(r=e[s])||void 0===r||delete r[t];break;case"upd":{const n=null===(i=e[s])||void 0===i?void 0:i[t];if(n)switch(n.type){case"ups":for(const[e,t]of Object.entries(c.mod))p(n.val,e,t);break;case"del":break;case"upd":for(const e of Object.keys(c.mod))delete n.mod[e]}break}}}(n,r),function(e,t=""){t||(t=g(16));const n={};for(const[t,r]of Object.entries(e))for(const[e,i]of Object.entries(r)){const r=n[t]||(n[t]={});(r[i.type]||(r[i.type]=[])).push(Object.assign({key:e},i))}const r=[];for(const[e,i]of Object.entries(n)){const n={table:e,muts:[]};for(const[e,r]of Object.entries(i))switch(e){case"ups":{const e={type:"upsert",keys:r.map((e=>e.key)),values:r.map((e=>e.val)),txid:t};n.muts.push(e);break}case"upd":{const e={type:"update",keys:r.map((e=>e.key)),changeSpecs:r.map((e=>e.mod)),txid:t};n.muts.push(e);break}case"del":{const e={type:"delete",keys:r.map((e=>e.key)),txid:t};n.muts.push(e);break}}r.push(n)}return r}(n)}const Pc=10,Lc=1e4,Rc=1e3;function Nc(e){const r=[],i=new n.BehaviorSubject(!0),o=new n.BehaviorSubject(null);let c=!1,l=new Array(Pc).fill(0);return o.subscribe((()=>s(this,void 0,void 0,(function*(){if(!c&&r.length>0){c=!0,l.shift(),l.push(Date.now()),i.next(!1);try{yield function(){return s(this,void 0,void 0,(function*(){for(var i,o,c,l,a,u;r.length>0;){const d=r.shift();try{yield n.firstValueFrom(e.cloud.syncState.pipe(pt((({phase:e})=>"in-sync"===e||"error"===e))));const r=e.cloud.persistedSyncState.value;if(!d)continue;switch(d.type){case"token-expired":const n=e.cloud.currentUser.value,h=yield jt(e.cloud.options.databaseUrl,n);yield e.table("$logins").update(n.userId,{accessToken:h.accessToken,accessTokenExpiration:h.accessTokenExpiration,claims:h.claims,license:h.license,data:h.data});break;case"realm-added":(null===(i=null==r?void 0:r.realms)||void 0===i?void 0:i.includes(d.realm))||(null===(o=null==r?void 0:r.inviteRealms)||void 0===o?void 0:o.includes(d.realm))||(yield e.cloud.sync({purpose:"pull",wait:!0}));break;case"realm-accepted":(null===(c=null==r?void 0:r.realms)||void 0===c?void 0:c.includes(d.realm))||(yield e.cloud.sync({purpose:"pull",wait:!0}));break;case"realm-removed":((null===(l=null==r?void 0:r.realms)||void 0===l?void 0:l.includes(d.realm))||(null===(a=null==r?void 0:r.inviteRealms)||void 0===a?void 0:a.includes(d.realm)))&&(yield e.cloud.sync({purpose:"pull",wait:!0}));break;case"realms-changed":yield e.cloud.sync({purpose:"pull",wait:!0});break;case"changes":if("error"===(null===(u=e.cloud.syncState.value)||void 0===u?void 0:u.phase)){_t(e,"pull");break}yield e.transaction("rw",e.dx.tables,(n=>s(this,void 0,void 0,(function*(){n.idbtrans.disableChangeTracking=!0,n.idbtrans.disableAccessControl=!0;const[r,i,s]=yield Promise.all([e.getSchema(),e.getPersistedSyncState(),e.getCurrentUser()]);if(!i||!r||!s)return;if(d.baseRev!==i.serverRevision)return void("string"!=typeof d.baseRev||"bigint"!=typeof i.serverRevision&&"object"!=typeof i.serverRevision||_t(e,"pull"));if((yield t.waitFor(qt(i)))!==d.realmSetHash)return void _t(e,"pull");let o=[];if(s.isLoggedIn){const t=Yt(e).map((t=>e.table(Gt(t.name))));o=yield en(t,e)}if(d.changes.length>0){const t=jc(d.changes,o);yield Vn(t,e)}i.latestRevisions=Fn(o,i.latestRevisions),i.serverRevision=d.newRev,yield Bn(e,r,i.latestRevisions,d.newRev),yield e.$syncState.put(i,"syncState")}))))}}catch(e){}}}))}()}finally{l[l.length-1]-l[0]<Lc&&(yield new Promise((e=>setTimeout(e,Rc)))),c=!1,i.next(!0)}}})))),{enqueue:function(e){r.push(e),o.next(null)},readyToServe:i}}const $c=new WeakMap,Mc={members:"@id, [userId+realmId], [email+realmId], realmId",roles:"[realmId+name]",realms:"@realmId",$jobs:"",$syncState:"",$baseRevs:"[tableName+clientRev]",$logins:"claims.sub, lastLogin"};let Bc=0;function Fc(e){"vip"in e&&(e=e.vip);let t=$c.get(e.cloud);if(!t){const r=new n.Subject;let i=new Jt(`syncstatechanged-${e.name}`),s=new Jt(`synccomplete-${e.name}`);r.id=++Bc;let o=!1;t={get name(){return e.name},close:()=>e.close(),transaction:e.transaction.bind(e),table:e.table.bind(e),get tables(){return e.tables},cloud:e.cloud,get $jobs(){return e.table("$jobs")},get $syncState(){return e.table("$syncState")},get $baseRevs(){return e.table("$baseRevs")},get $logins(){return e.table("$logins")},get realms(){return e.realms},get members(){return e.members},get roles(){return e.roles},get initiallySynced(){return o},localSyncEvent:r,get syncStateChangedEvent(){return i},get syncCompleteEvent(){return s},dx:e};const c={getCurrentUser:()=>t.$logins.toArray().then((e=>e.find((e=>e.isLoggedIn))||Rt)),getPersistedSyncState:()=>t.$syncState.get("syncState"),getSchema:()=>t.$syncState.get("schema").then((e=>{if(e)for(const r of t.tables)r.schema.primKey&&r.schema.primKey.keyPath&&e[r.name]&&(e[r.name].primaryKey="string"==typeof(n=r.schema.primKey.keyPath)?n:n?"["+[].join.call(n,"+")+"]":"");var n;return e})),getOptions:()=>t.$syncState.get("options"),setInitiallySynced(e){o=e},reconfigure(){i=new Jt(`syncstatechanged-${e.name}`),s=new Jt(`synccomplete-${e.name}`)}};Object.assign(t,c),t.messageConsumer=Nc(t),t.messageProducer=new n.Subject,$c.set(e.cloud,t)}return t}const Wc="undefined"!=typeof InstallTrigger,Vc="undefined"!=typeof navigator&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\/|Edge\//.test(navigator.userAgent),Kc=Vc?[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]:NaN,Hc=Vc&&Kc<=605||Wc,zc="undefined"!=typeof self&&"clients"in self&&!self.document;const{toString:Jc}={};function qc(e){return Jc.call(e).slice(8,-1)}function Yc(e,t){var n;return"delete"===t.type?t.keys:(null===(n=t.keys)||void 0===n?void 0:n.slice())||t.values.map(e.extractKey)}const Gc=/b|c|d|f|g|h|j|k|l|m|n|p|q|r|s|t|v|x|y|z/i;let Qc=0;function Xc(e,t){const n=new Uint8Array(18),r=new Uint8Array(n.buffer,0,6),i=Date.now();Qc>=i?++Qc:Qc=i,r[0]=Qc/1099511627776,r[1]=Qc/4294967296,r[2]=Qc/16777216,r[3]=Qc/65536,r[4]=Qc/256,r[5]=Qc;const s=new Uint8Array(n.buffer,6);crypto.getRandomValues(s);return e+pn(new Uint8Array(n.buffer))+(t||"")}function Zc(e){return{stack:"dbcore",name:"idGenerationMiddleware",level:1,create:n=>Object.assign(Object.assign({},n),{table:r=>{const i=n.table(r);return Object.assign(Object.assign({},i),{mutate:n=>{var s,o;const c=n.trans;if("versionchange"===c.mode&&(c.disableChangeTracking=!0,c.disableAccessControl=!0),c.disableChangeTracking)return i.mutate(n);if("add"===n.type||"put"===n.type){const c=null===(s=e.cloud.schema)||void 0===s?void 0:s[r];if(null==c?void 0:c.generatedGlobalId){if((null===(o=e.cloud.options)||void 0===o?void 0:o.databaseUrl)&&!e.initiallySynced){const e=Yc(i.schema.primaryKey,n);return i.getMany({keys:e,trans:n.trans,cache:"immutable"}).then((t=>{if(t.length<e.length)throw new Error("Unable to create new objects without an initial sync having been performed.");return i.mutate(n)}))}return function(n,s){let o=null;const c=Yc(i.schema.primaryKey,n);return c.forEach(((l,a)=>{if(void 0===l){const r=n.values[a].realmId||e.cloud.currentUserId,l=r.substr(r.length-3);c[a]=Xc(s,l),i.schema.primaryKey.outbound||(o||(o=n.values.slice()),o[a]=t.deepClone(o[a]),t.setByKeyPath(o[a],i.schema.primaryKey.keyPath,c[a]))}else if("string"!=typeof l||!l.startsWith(s)&&!l.startsWith("#"+s))throw new t.ConstraintError(`The ID "${l}" is not valid for table "${r}". Primary '@' keys requires the key to be prefixed with "${s}" (or "#${s}).\nIf you want to generate IDs programmatically, remove '@' from the schema to get rid of this constraint. Dexie Cloud supports custom IDs as long as they are random and globally unique.`)})),i.mutate(Object.assign(Object.assign({},n),{keys:c,values:o||n.values}))}(n,c.idPrefix)}if(null==c?void 0:c.markedForSync){Yc(i.schema.primaryKey,n).forEach(((e,n)=>{if(!v(e)){const n=Array.isArray(e)?e.map(qc).join(","):qc(e);throw new t.ConstraintError(`Invalid primary key type ${n} for table ${r}. Tables marked for sync has primary keys of type string or Array of string (and optional numbers)`)}}))}}return i.mutate(n)}})}})}}let el=0;function tl(e,t){return function(n){const{readers:r,writers:i}=n.trans[t]||(n.trans[t]={writers:[],readers:[]}),s=i.length,o=(s>0?i[s-1].then((()=>e(n)),(()=>e(n))):e(n)).finally((()=>{r.splice(r.indexOf(o))}));return r.push(o),o}}function nl(e,t){return function(n){const{readers:r,writers:i}=n.trans[t]||(n.trans[t]={writers:[],readers:[]});let s=(i.length>0?i[i.length-1].then((()=>e(n)),(()=>e(n))):r.length>0?(o=r,new Promise((e=>{0===o.length&&e([]);let t=o.length;const n=new Array(t);o.forEach(((r,i)=>Promise.resolve(r).then((e=>n[i]={status:"fulfilled",value:e}),(e=>n[i]={status:"rejected",reason:e})).then((()=>--t||e(n)))))}))).then((()=>e(n))):e(n)).finally((()=>{i.shift()}));var o;return i.push(s),s}}const rl=new n.BehaviorSubject(new Set);function il(e){var t,n,r,i;return(null===(t=e.cloud.options)||void 0===t?void 0:t.disableEagerSync)||"ok"!==(null===(r=null===(n=e.cloud.currentUser.value)||void 0===n?void 0:n.license)||void 0===r?void 0:r.status)||!(null===(i=e.cloud.options)||void 0===i?void 0:i.databaseUrl)}function sl({currentUserObservable:e,db:n}){return{stack:"dbcore",name:"MutationTrackingMiddleware",level:1,create:r=>{const i=new Set(r.schema.tables.map((e=>e.name))),s=r.schema.tables.filter((e=>!/^\$/.test(e.name))),o=new Map;for(const e of s){const t=`$${e.name}_mutations`;i.has(t)&&o.set(e.name,r.table(t))}return Object.assign(Object.assign({},r),{transaction:(t,i)=>{let s;if("readwrite"===i){const e=t.filter((e=>{var t,r;return null===(r=null===(t=n.cloud.schema)||void 0===t?void 0:t[e])||void 0===r?void 0:r.markedForSync})).map((e=>Gt(e)));s=r.transaction([...t,...e],i)}else s=r.transaction(t,i);if("readwrite"===i){s.txid=tn(16),s.opCount=0,s.currentUser=e.value,rl.value.add(s),rl.next(rl.value);const t=()=>{s.removeEventListener("complete",r),s.removeEventListener("error",t),s.removeEventListener("abort",t),rl.value.delete(s),rl.next(rl.value)},r=()=>{s.mutationsAdded&&!il(n)&&_t(n,"push"),t()};s.addEventListener("complete",r),s.addEventListener("error",t),s.addEventListener("abort",t)}return s},table:e=>{const i=r.table(e);if(/^\$/.test(e))return e.endsWith("_mutations")?Object.assign(Object.assign({},i),{mutate:e=>("add"!==e.type&&"put"!==e.type||(e.trans.mutationsAdded=!0),i.mutate(e))}):"$logins"===e?Object.assign(Object.assign({},i),{mutate:e=>i.mutate(e).then((t=>(e.trans.mutationsAdded=!0,t))).catch((e=>Promise.reject(e)))}):i;const{schema:s}=i,c=o.get(e);return c?function(e){const t="$lock"+ ++el;return Object.assign(Object.assign({},e),{count:tl(e.count,t),get:tl(e.get,t),getMany:tl(e.getMany,t),openCursor:tl(e.openCursor,t),query:tl(e.query,t),mutate:nl(e.mutate,t)})}(Object.assign(Object.assign({},i),{mutate:t=>{var r,o,c;const a=t.trans;return a.txid?a.disableChangeTracking?i.mutate(t):(null===(o=null===(r=n.cloud.schema)||void 0===r?void 0:r[e])||void 0===o?void 0:o.markedForSync)&&(null===(c=a.currentUser)||void 0===c?void 0:c.isLoggedIn)?"deleteRange"===t.type?i.query({query:{range:t.range,index:s.primaryKey},trans:t.trans,values:!1}).then((e=>l({type:"delete",keys:e.result,trans:t.trans,criteria:{index:null,range:t.range}}))):l(t):i.mutate(t):i.mutate(t)}})):i;function l(r){var o,l;const a=r.trans,u=null===(l=null===(o=n.cloud.options)||void 0===o?void 0:o.unsyncedProperties)||void 0===l?void 0:l[e],{txid:d,currentUser:{userId:h}}=a,{type:f}=r,p=++a.opCount;function g(e){if(!u)return e;let t=e;for(const n of Object.keys(e))u.some((e=>n===e||n.startsWith(e+".")))&&(t===e&&(t=Object.assign({},e)),delete t[n]);return t}return i.mutate(r).then((e=>{var n;const{numFailures:i,failures:o}=e;let l="delete"===f?r.keys:e.results,y="values"in r?r.values:[],v="changeSpec"in r?r.changeSpec:void 0,m="updates"in r?r.updates:void 0;if(i&&(l=l.filter(((e,t)=>!o[t])),y=y.filter(((e,t)=>!o[t]))),u){if(y=y.map((e=>{const t=Object.assign({},e);for(const e of u)delete t[e];return t})),v&&(v=g(v),0===Object.keys(v).length))return e;if(m){let e=m.changeSpecs.map(g),n={keys:[],changeSpecs:[]};const r=new t.RangeSet;let i=!1;for(let t=0,s=e.length;t<s;++t)Object.keys(e[t]).length>0?(n.keys.push(m.keys[t]),n.changeSpecs.push(e[t]),r.addKey(m.keys[t])):i=!0;if(m=n,i){let e=[],t=[];for(let n=0,i=l.length;n<i;++n)r.hasKey(l[n])&&(e.push(l[n]),t.push(y[n]));l=e,y=t}}}const b=Date.now();let w="criteria"in r&&r.criteria?Object.assign(Object.assign({},r.criteria),{index:r.criteria.index===s.primaryKey.keyPath?null:r.criteria.index}):void 0;if(u&&(null==w?void 0:w.index)){const e=null===(n=s.indexes.find((e=>e.name===w.index)))||void 0===n?void 0:n.keyPath;(e?"string"==typeof e?[e]:e:[]).some((e=>null==u?void 0:u.includes(e)))&&(w=void 0)}const _="delete"===r.type?{type:"delete",ts:b,opNo:p,keys:l,criteria:w,txid:d,userId:h}:"add"===r.type?{type:"insert",ts:b,opNo:p,keys:l,txid:d,userId:h,values:y}:w&&v?{type:"modify",ts:b,opNo:p,keys:l,criteria:w,changeSpec:v,txid:d,userId:h}:v?{type:"update",ts:b,opNo:p,keys:l,changeSpecs:l.map((()=>v)),txid:d,userId:h}:m?{type:"update",ts:b,opNo:p,keys:m.keys,changeSpecs:m.changeSpecs,txid:d,userId:h}:{type:"upsert",ts:b,opNo:p,keys:l,values:y,txid:d,userId:h};return"isAdditionalChunk"in r&&r.isAdditionalChunk&&(_.isAdditionalChunk=!0),l.length>0||w?c.mutate({type:"add",trans:a,values:[_]}).then((()=>(a.mutationsAdded=!0,e))):e}))}}})}}}function ol(e,t){return function(n,r){var i;const s=Object.assign(Object.assign({},Mc),n);Object.keys(Mc).forEach((e=>{const t=s[e];if(null==t)throw new Error(`Cannot delete table ${e} as it is needed for access control of Dexie Cloud`);if(!n[e])return;const r=t.split(",").map((e=>e.trim())),i=Mc[e].split(",").map((e=>e.trim())),o=new Set(r.map((e=>e.replace(/([&*]|\+\+)/g,""))));if(r[0]!==i[0])throw new Error(`Cannot override primary key of table ${e}. Please declare it as {${e}: ${JSON.stringify(Mc[e])}`);for(let t=1;t<i.length;++t){const n=i[t];o.has(n.replace(/([&*]|\+\+)/g,""))||(s[e]+=`,${n}`)}}));const o=t.cloud.schema||(t.cloud.schema={}),c=new Set;Object.keys(s).forEach((e=>{const t=s[e],n=o[e]||(o[e]={});null!=t?(/^\@/.test(t)&&(s[e]=s[e].substr(1),n.generatedGlobalId=!0,n.idPrefix=function(e,t){let n=e[0].toLocaleLowerCase();for(let t=1,i=e.length;t<i&&n.length<3;++t)(Gc.test(e[t])||(r=e[t])>="A"&&r<="Z")&&(n+=e[t].toLowerCase());for(var r,i,s;t.has(n);){if(/\d/g.test(n)){if(n=n.substr(0,n.length-1)+(n[n.length-1]+1),!(n.length>3))continue;n=n.substr(0,3)}else if(n.length<3){n+="2";continue}let e=1,r=n;for(;t.has(r)&&e<8;)i=n,r=(1&(s=e)?i[0].toUpperCase():i[0].toLowerCase())+(2&s?i[1].toUpperCase():i[1].toLowerCase())+(4&s?i[2].toUpperCase():i[2].toLowerCase()),++e;if(e<8)n=r;else{let e=n.charCodeAt(2)+1&127;n=n.substr(0,2)+String.fromCharCode(e)}}return n}(e,c),c.add(n.idPrefix)),/^\$/.test(e)||(s[`$${e}_mutations`]="++rev",n.markedForSync=!0),n.deleted&&(n.deleted=!1)):(n.deleted=!0,n.markedForSync=!1,s[`$${e}_mutations`]=null)}));const l=e.call(this,s,r);for(const[e,t]of Object.entries(r))if(null===(i=t.yProps)||void 0===i?void 0:i.length){const n=o[e];n&&(n.yProps=t.yProps.map((e=>e.prop)))}return l}}function cl(e,t,n){return"undefined"!=typeof navigator&&navigator.locks?navigator.locks.request(e.name+"|"+t,(()=>n())):n()}const ll=new n.BehaviorSubject(!0),al=new n.BehaviorSubject(!0);ll.pipe(vt((e=>e?n.of(!0):n.of(!1).pipe(dt(2e4)))),ht()).subscribe(al);const ul="undefined"!=typeof document?n.fromEvent(document,"visibilitychange"):n.of({}),dl=ul.pipe(pt((()=>"hidden"===document.visibilityState))),hl=ul.pipe(pt((()=>"visible"===document.visibilityState))),fl="undefined"!=typeof window?n.merge(hl,n.fromEvent(window,"mousedown"),n.fromEvent(window,"mousemove"),n.fromEvent(window,"keydown"),n.fromEvent(window,"wheel"),n.fromEvent(window,"touchmove")):n.of({});"undefined"!=typeof document&&n.merge(n.of(!0),dl,fl).pipe(rt((()=>"visible"===document.visibilityState)),mt((e=>{ll.value!==e&&ll.next(e)})),vt((e=>e?n.of(0).pipe(dt(16e4),mt((()=>ll.next(!1)))):n.of(0)))).subscribe((()=>{}));class pl extends Error{constructor(){super(...arguments),this.name="TokenExpiredError"}}function gl(e){var n,r;if(!(null===(n=e.cloud.options)||void 0===n?void 0:n.awarenessProtocol))throw new t.MissingAPIError('awarenessProtocol was not provided to db.cloud.configure(). Please import * as awarenessProtocol from "y-protocols/awareness".');return null===(r=e.cloud.options)||void 0===r?void 0:r.awarenessProtocol}const yl=new WeakMap,vl=new WeakMap;function ml(e){let t=vl.get(e);return t||(t=new n.Subject,vl.set(e,t)),t}class bl extends n.Observable{constructor(e,t,n,r,i,s,o,c){super((l=>new _l(e,t,n,r,i,c,l,s,o)))}}let wl=0;class _l extends n.Subscription{constructor(e,t,n,r,i,s,o,c,l){super((()=>this.teardown())),this.id=++wl,this.subscriptions=new Set,this.reconnecting=!1,this.db=e,this.databaseUrl=e.cloud.options.databaseUrl,this.rev=t,this.yrev=n,this.realmSetHash=r,this.clientIdentity=i,this.user=s,this.subscriber=o,this.lastUserActivity=new Date,this.messageProducer=c,this.webSocketStatus=l,this.connect()}teardown(){this.disconnect()}disconnect(){if(this.webSocketStatus.next("disconnected"),this.pinger&&(clearInterval(this.pinger),this.pinger=null),this.ws)try{this.ws.close()}catch(e){}this.ws=null;for(const e of this.subscriptions)e.unsubscribe();this.subscriptions.clear()}reconnect(){if(!this.reconnecting){this.reconnecting=!0;try{this.disconnect()}catch(e){}this.connect().catch((()=>{})).then((()=>this.reconnecting=!1))}}connect(){return s(this,void 0,void 0,(function*(){if(this.lastServerActivity=new Date,this.pauseUntil&&this.pauseUntil>new Date)return;if(this.ws)throw new Error("Called connect() when a connection is already open");if(!this.databaseUrl)throw new Error("Cannot connect without a database URL");if(this.closed)return;const e=this.user.accessTokenExpiration;if(e&&e<new Date)return void this.subscriber.error(new pl);this.webSocketStatus.next("connecting"),this.pinger=setInterval((()=>s(this,void 0,void 0,(function*(){if(this.closed)this.teardown();else if(this.ws)try{this.ws.send(JSON.stringify({type:"ping"})),setTimeout((()=>{this.pinger&&(this.closed?this.teardown():this.lastServerActivity<new Date(Date.now()-2e4)&&this.reconnect())}),2e4)}catch(e){this.reconnect()}else this.reconnect()}))),3e4);const r=new URL(this.databaseUrl);r.protocol="http:"===r.protocol?"ws":"wss";const i=new URLSearchParams;if(this.subscriber.closed)return;i.set("v","2"),this.rev&&i.set("rev",this.rev),this.yrev&&i.set("yrev",this.yrev),i.set("realmsHash",this.realmSetHash),i.set("clientId",this.clientIdentity),i.set("dxcv",this.db.cloud.version),this.user.accessToken&&i.set("token",this.user.accessToken);const o=this.ws=new WebSocket(`${r}/changes?${i}`);o.binaryType="arraybuffer",o.onclose=e=>{this.pinger&&this.reconnect()},o.onmessage=e=>{if(this.pinger){this.lastServerActivity=new Date;try{const t="string"==typeof e.data?Tn.parse(e.data):function(e){const t=new J(e),n=X(t);if("outdated-server-rev"===n)return{type:n};if("y-complete-sync-done"===n)return{type:n,yServerRev:X(t)};const r=X(t),i=X(t);switch(n){case"u-ack":case"u-reject":return{type:n,table:r,prop:i,i:Number(ee(t))};default:{const e=ne(t);switch(n){case"in-sync":case"doc-close":return{type:n,table:r,prop:i,k:e};case"aware":return{type:n,table:r,prop:i,k:e,u:Y(t)};case"doc-open":return{type:n,table:r,prop:i,k:e,serverRev:ne(t),sv:ne(t)};case"sv":return{type:n,table:r,prop:i,k:e,sv:Y(t)};case"u-c":return{type:n,table:r,prop:i,k:e,u:Y(t),i:Number(ee(t))};case"u-s":return{type:n,table:r,prop:i,k:e,u:Y(t),r:t.pos<t.arr.length&&X(t)||void 0};default:throw new TypeError(`Unknown message type: ${n}`)}}}}(new Uint8Array(e.data));if("error"===t.type)throw new Error(`Error message from dexie-cloud: ${t.error}`);if("aware"===t.type){const e=Ec.getDocCache(this.db.dx).find(t.table,t.k,t.prop);if(e){const n=(e=>yl.get(e))(e);if(n){gl(this.db).applyAwarenessUpdate(n,t.u,"server")}}}else if("pong"===t.type);else if("doc-open"===t.type){const e=Ec.getDocCache(this.db.dx).find(t.table,t.k,t.prop);e&&ml(e).next()}else"u-ack"===t.type||"u-reject"===t.type||"u-s"===t.type||"in-sync"===t.type||"outdated-server-rev"===t.type||"y-complete-sync-done"===t.type?xc([t],this.db).then((e=>s(this,[e],void 0,(function*({resyncNeeded:e,yServerRevision:n,receivedUntils:r}){if(n&&(yield this.db.$syncState.update("syncState",{yServerRevision:n})),"u-s"===t.type&&r){const e=fc(this.db,t.table,t.prop);if(e){const t=r[e.name];t&&(yield e.update(Kn,{receivedUntil:t}))}}e&&(yield this.db.cloud.sync({purpose:"pull",wait:!0}))})))):this.subscriber.next(t)}catch(e){this.subscriber.error(e)}}};try{let e=!1;yield new Promise(((t,n)=>{o.onopen=n=>{e=!0,t(null)},o.onerror=t=>{if(e)this.reconnect();else{const e=t.error||new Error("WebSocket Error");this.subscriber.error(e),this.webSocketStatus.next("error"),n(e)}}})),this.subscriptions.add(this.messageProducer.subscribe((e=>{var t,n;this.closed||("ready"===e.type&&"connected"!==this.webSocketStatus.value&&this.webSocketStatus.next("connected"),"ready"===e.type?(this.rev=e.rev,null===(t=this.ws)||void 0===t||t.send(Tn.stringify(e))):null===(n=this.ws)||void 0===n||n.send(V(e)))}))),this.user.isLoggedIn&&!il(this.db)&&this.subscriptions.add(function(e){const r=Zt(e.tables.filter((t=>{var n,r;return(null===(r=null===(n=e.cloud.schema)||void 0===n?void 0:n[t.name])||void 0===r?void 0:r.markedForSync)&&t.schema.yProps})).map((e=>e.schema.yProps.map((t=>({table:e.name,ydocProp:t.prop,updatesTable:t.updatesTable}))))));return n.merge(...r.map((({table:r,ydocProp:i,updatesTable:o})=>{const c=e.table(o);return n.from(c.get(Kn)).pipe(n.switchMap((e=>{let o=(null==e?void 0:e.unsentFrom)||1;return n.from(t.liveQuery((()=>s(this,void 0,void 0,(function*(){return(yield Hn(c,o)).filter((e=>e.f&&1&e.f)).map((e=>({type:"u-c",table:r,prop:i,k:e.k,u:e.u,i:e.i})))}))))).pipe(n.tap((e=>{e.length>0&&(o=e.at(-1).i+1)})))})))}))).pipe(n.mergeMap((e=>e)))}(this.db).subscribe(this.db.messageProducer))}catch(e){this.pauseUntil=new Date(Date.now()+6e4)}}))}}class kl extends Error{constructor(e){super("expired"===e?"License expired":"deactivated"===e?"User deactivated":"Invalid license"),this.name="InvalidLicenseError",e&&(this.license=e)}}function Sl(e){return s(this,void 0,void 0,(function*(){var e;yield(e=3e3,new Promise((t=>setTimeout(t,e)))),yield n.firstValueFrom(fl)}))}function El(e){return s(this,void 0,void 0,(function*(){var t;return!(!(null===(t=e.cloud.options)||void 0===t?void 0:t.databaseUrl)||!e.cloud.schema)&&(yield Tc(e,e.cloud.options,e.cloud.schema,{justCheckIfNeeded:!0}))}))}const xl=new WeakMap;function Il(e,t,n,r){const i=xl.get(e);if(i){if(i.pull||"push"===(null==r?void 0:r.purpose))return i.promise;{let s=!1;const o=e.cloud.syncState.subscribe((e=>{"pulling"===e.phase&&(s=!0)}));return i.promise.then((()=>{o.unsubscribe()})).catch((e=>(o.unsubscribe(),Promise.reject(e)))).then((()=>{if(!s)return Il(e,t,n,r)}))}}const o=function(){return s(this,void 0,void 0,(function*(){try{yield Rn(e),yield cl(e,Dc,(()=>Tc(e,t,n,r))),xl.delete(e)}catch(t){throw xl.delete(e),t}}))}();return xl.set(e,{promise:o,pull:"push"!==(null==r?void 0:r.purpose)}),o}const Cl=1e3;function Al(e,t,n){let r=null,i={cancelled:!1},s=0,o=0;function c(r=1){setTimeout((()=>{const h=l?"pull":"push";o=Date.now(),Il(e,t,n,{cancelToken:i,retryImmediatelyOnFetchError:!0,purpose:h}).then((()=>{if(i.cancelled)d();else if(l||a)return l=!1,a=!1,c();u=!1,s=0,o=0})).catch((e=>{if(i.cancelled)d(),u=!1,s=0,o=0;else if(r<5){const e=[0,20,40,300,900][r]*Cl;s=Date.now()+e,o=0,setTimeout((()=>c(r+1)),e)}else u=!1,s=0,o=0}))}),0)}let l=!1,a=!1,u=!1;const d=()=>{i.cancelled=!0,r&&r.unsubscribe()};return{start:()=>{r=e.localSyncEvent.subscribe((({purpose:e})=>{(e=>{i.cancelled||("pull"===e&&(l=!0),"push"===e&&(a=!0),u?s||o>0&&Date.now():(u=!0,c()))})(e||"pull")}))},stop:d}}function Ol(e,t){if(e&&t&&t.unsyncedTables)for(const n of t.unsyncedTables)e[n]&&(e[n].markedForSync=!1)}var Dl,Tl,Ul,jl,Pl,Ll={},Rl=[],Nl=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i;function $l(e,t){for(var n in t)e[n]=t[n];return e}function Ml(e){var t=e.parentNode;t&&t.removeChild(e)}function Bl(e,t,n){var r,i,s,o={};for(s in t)"key"==s?r=t[s]:"ref"==s?i=t[s]:o[s]=t[s];if(arguments.length>2&&(o.children=arguments.length>3?Dl.call(arguments,2):n),"function"==typeof e&&null!=e.defaultProps)for(s in e.defaultProps)void 0===o[s]&&(o[s]=e.defaultProps[s]);return Fl(e,o,r,i,null)}function Fl(e,t,n,r,i){var s={type:e,props:t,key:n,ref:r,__k:null,__:null,__b:0,__e:null,__d:void 0,__c:null,__h:null,constructor:void 0,__v:null==i?++Ul:i};return null==i&&null!=Tl.vnode&&Tl.vnode(s),s}function Wl(e){return e.children}function Vl(e,t){this.props=e,this.context=t}function Kl(e,t){if(null==t)return e.__?Kl(e.__,e.__.__k.indexOf(e)+1):null;for(var n;t<e.__k.length;t++)if(null!=(n=e.__k[t])&&null!=n.__e)return n.__e;return"function"==typeof e.type?Kl(e):null}function Hl(e){var t,n;if(null!=(e=e.__)&&null!=e.__c){for(e.__e=e.__c.base=null,t=0;t<e.__k.length;t++)if(null!=(n=e.__k[t])&&null!=n.__e){e.__e=e.__c.base=n.__e;break}return Hl(e)}}function zl(e){(!e.__d&&(e.__d=!0)&&jl.push(e)&&!Jl.__r++||Pl!==Tl.debounceRendering)&&((Pl=Tl.debounceRendering)||setTimeout)(Jl)}function Jl(){for(var e;Jl.__r=jl.length;)e=jl.sort((function(e,t){return e.__v.__b-t.__v.__b})),jl=[],e.some((function(e){var t,n,r,i,s,o;e.__d&&(s=(i=(t=e).__v).__e,(o=t.__P)&&(n=[],(r=$l({},i)).__v=i.__v+1,ta(o,i,r,t.__n,void 0!==o.ownerSVGElement,null!=i.__h?[s]:null,n,null==s?Kl(i):s,i.__h),na(n,i),i.__e!=s&&Hl(i)))}))}function ql(e,t,n,r,i,s,o,c,l,a){var u,d,h,f,p,g,y,v=r&&r.__k||Rl,m=v.length;for(n.__k=[],u=0;u<t.length;u++)if(null!=(f=n.__k[u]=null==(f=t[u])||"boolean"==typeof f?null:"string"==typeof f||"number"==typeof f||"bigint"==typeof f?Fl(null,f,null,null,f):Array.isArray(f)?Fl(Wl,{children:f},null,null,null):f.__b>0?Fl(f.type,f.props,f.key,null,f.__v):f)){if(f.__=n,f.__b=n.__b+1,null===(h=v[u])||h&&f.key==h.key&&f.type===h.type)v[u]=void 0;else for(d=0;d<m;d++){if((h=v[d])&&f.key==h.key&&f.type===h.type){v[d]=void 0;break}h=null}ta(e,f,h=h||Ll,i,s,o,c,l,a),p=f.__e,(d=f.ref)&&h.ref!=d&&(y||(y=[]),h.ref&&y.push(h.ref,null,f),y.push(d,f.__c||p,f)),null!=p?(null==g&&(g=p),"function"==typeof f.type&&f.__k===h.__k?f.__d=l=Yl(f,l,e):l=Gl(e,f,h,v,p,l),"function"==typeof n.type&&(n.__d=l)):l&&h.__e==l&&l.parentNode!=e&&(l=Kl(h))}for(n.__e=g,u=m;u--;)null!=v[u]&&("function"==typeof n.type&&null!=v[u].__e&&v[u].__e==n.__d&&(n.__d=Kl(r,u+1)),sa(v[u],v[u]));if(y)for(u=0;u<y.length;u++)ia(y[u],y[++u],y[++u])}function Yl(e,t,n){for(var r,i=e.__k,s=0;i&&s<i.length;s++)(r=i[s])&&(r.__=e,t="function"==typeof r.type?Yl(r,t,n):Gl(n,r,r,i,r.__e,t));return t}function Gl(e,t,n,r,i,s){var o,c,l;if(void 0!==t.__d)o=t.__d,t.__d=void 0;else if(null==n||i!=s||null==i.parentNode)e:if(null==s||s.parentNode!==e)e.appendChild(i),o=null;else{for(c=s,l=0;(c=c.nextSibling)&&l<r.length;l+=2)if(c==i)break e;e.insertBefore(i,s),o=s}return void 0!==o?o:i.nextSibling}function Ql(e,t,n){"-"===t[0]?e.setProperty(t,n):e[t]=null==n?"":"number"!=typeof n||Nl.test(t)?n:n+"px"}function Xl(e,t,n,r,i){var s;e:if("style"===t)if("string"==typeof n)e.style.cssText=n;else{if("string"==typeof r&&(e.style.cssText=r=""),r)for(t in r)n&&t in n||Ql(e.style,t,"");if(n)for(t in n)r&&n[t]===r[t]||Ql(e.style,t,n[t])}else if("o"===t[0]&&"n"===t[1])s=t!==(t=t.replace(/Capture$/,"")),t=t.toLowerCase()in e?t.toLowerCase().slice(2):t.slice(2),e.l||(e.l={}),e.l[t+s]=n,n?r||e.addEventListener(t,s?ea:Zl,s):e.removeEventListener(t,s?ea:Zl,s);else if("dangerouslySetInnerHTML"!==t){if(i)t=t.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if("href"!==t&&"list"!==t&&"form"!==t&&"tabIndex"!==t&&"download"!==t&&t in e)try{e[t]=null==n?"":n;break e}catch(e){}"function"==typeof n||(null!=n&&(!1!==n||"a"===t[0]&&"r"===t[1])?e.setAttribute(t,n):e.removeAttribute(t))}}function Zl(e){this.l[e.type+!1](Tl.event?Tl.event(e):e)}function ea(e){this.l[e.type+!0](Tl.event?Tl.event(e):e)}function ta(e,t,n,r,i,s,o,c,l){var a,u,d,h,f,p,g,y,v,m,b,w,_,k=t.type;if(void 0!==t.constructor)return null;null!=n.__h&&(l=n.__h,c=t.__e=n.__e,t.__h=null,s=[c]),(a=Tl.__b)&&a(t);try{e:if("function"==typeof k){if(y=t.props,v=(a=k.contextType)&&r[a.__c],m=a?v?v.props.value:a.__:r,n.__c?g=(u=t.__c=n.__c).__=u.__E:("prototype"in k&&k.prototype.render?t.__c=u=new k(y,m):(t.__c=u=new Vl(y,m),u.constructor=k,u.render=oa),v&&v.sub(u),u.props=y,u.state||(u.state={}),u.context=m,u.__n=r,d=u.__d=!0,u.__h=[]),null==u.__s&&(u.__s=u.state),null!=k.getDerivedStateFromProps&&(u.__s==u.state&&(u.__s=$l({},u.__s)),$l(u.__s,k.getDerivedStateFromProps(y,u.__s))),h=u.props,f=u.state,d)null==k.getDerivedStateFromProps&&null!=u.componentWillMount&&u.componentWillMount(),null!=u.componentDidMount&&u.__h.push(u.componentDidMount);else{if(null==k.getDerivedStateFromProps&&y!==h&&null!=u.componentWillReceiveProps&&u.componentWillReceiveProps(y,m),!u.__e&&null!=u.shouldComponentUpdate&&!1===u.shouldComponentUpdate(y,u.__s,m)||t.__v===n.__v){u.props=y,u.state=u.__s,t.__v!==n.__v&&(u.__d=!1),u.__v=t,t.__e=n.__e,t.__k=n.__k,t.__k.forEach((function(e){e&&(e.__=t)})),u.__h.length&&o.push(u);break e}null!=u.componentWillUpdate&&u.componentWillUpdate(y,u.__s,m),null!=u.componentDidUpdate&&u.__h.push((function(){u.componentDidUpdate(h,f,p)}))}if(u.context=m,u.props=y,u.__v=t,u.__P=e,b=Tl.__r,w=0,"prototype"in k&&k.prototype.render)u.state=u.__s,u.__d=!1,b&&b(t),a=u.render(u.props,u.state,u.context);else do{u.__d=!1,b&&b(t),a=u.render(u.props,u.state,u.context),u.state=u.__s}while(u.__d&&++w<25);u.state=u.__s,null!=u.getChildContext&&(r=$l($l({},r),u.getChildContext())),d||null==u.getSnapshotBeforeUpdate||(p=u.getSnapshotBeforeUpdate(h,f)),_=null!=a&&a.type===Wl&&null==a.key?a.props.children:a,ql(e,Array.isArray(_)?_:[_],t,n,r,i,s,o,c,l),u.base=t.__e,t.__h=null,u.__h.length&&o.push(u),g&&(u.__E=u.__=null),u.__e=!1}else null==s&&t.__v===n.__v?(t.__k=n.__k,t.__e=n.__e):t.__e=ra(n.__e,t,n,r,i,s,o,l);(a=Tl.diffed)&&a(t)}catch(e){t.__v=null,(l||null!=s)&&(t.__e=c,t.__h=!!l,s[s.indexOf(c)]=null),Tl.__e(e,t,n)}}function na(e,t){Tl.__c&&Tl.__c(t,e),e.some((function(t){try{e=t.__h,t.__h=[],e.some((function(e){e.call(t)}))}catch(e){Tl.__e(e,t.__v)}}))}function ra(e,t,n,r,i,s,o,c){var l,a,u,d=n.props,h=t.props,f=t.type,p=0;if("svg"===f&&(i=!0),null!=s)for(;p<s.length;p++)if((l=s[p])&&"setAttribute"in l==!!f&&(f?l.localName===f:3===l.nodeType)){e=l,s[p]=null;break}if(null==e){if(null===f)return document.createTextNode(h);e=i?document.createElementNS("http://www.w3.org/2000/svg",f):document.createElement(f,h.is&&h),s=null,c=!1}if(null===f)d===h||c&&e.data===h||(e.data=h);else{if(s=s&&Dl.call(e.childNodes),a=(d=n.props||Ll).dangerouslySetInnerHTML,u=h.dangerouslySetInnerHTML,!c){if(null!=s)for(d={},p=0;p<e.attributes.length;p++)d[e.attributes[p].name]=e.attributes[p].value;(u||a)&&(u&&(a&&u.__html==a.__html||u.__html===e.innerHTML)||(e.innerHTML=u&&u.__html||""))}if(function(e,t,n,r,i){var s;for(s in n)"children"===s||"key"===s||s in t||Xl(e,s,null,n[s],r);for(s in t)i&&"function"!=typeof t[s]||"children"===s||"key"===s||"value"===s||"checked"===s||n[s]===t[s]||Xl(e,s,t[s],n[s],r)}(e,h,d,i,c),u)t.__k=[];else if(p=t.props.children,ql(e,Array.isArray(p)?p:[p],t,n,r,i&&"foreignObject"!==f,s,o,s?s[0]:n.__k&&Kl(n,0),c),null!=s)for(p=s.length;p--;)null!=s[p]&&Ml(s[p]);c||("value"in h&&void 0!==(p=h.value)&&(p!==e.value||"progress"===f&&!p||"option"===f&&p!==d.value)&&Xl(e,"value",p,d.value,!1),"checked"in h&&void 0!==(p=h.checked)&&p!==e.checked&&Xl(e,"checked",p,d.checked,!1))}return e}function ia(e,t,n){try{"function"==typeof e?e(t):e.current=t}catch(e){Tl.__e(e,n)}}function sa(e,t,n){var r,i;if(Tl.unmount&&Tl.unmount(e),(r=e.ref)&&(r.current&&r.current!==e.__e||ia(r,null,t)),null!=(r=e.__c)){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(e){Tl.__e(e,t)}r.base=r.__P=null}if(r=e.__k)for(i=0;i<r.length;i++)r[i]&&sa(r[i],t,"function"!=typeof e.type);n||null==e.__e||Ml(e.__e),e.__e=e.__d=void 0}function oa(e,t,n){return this.constructor(e,n)}function ca(e,t,n){var r,i,s;Tl.__&&Tl.__(e,t),i=(r="function"==typeof n)?null:n&&n.__k||t.__k,s=[],ta(t,e=(!r&&n||t).__k=Bl(Wl,null,[e]),i||Ll,Ll,void 0!==t.ownerSVGElement,!r&&n?[n]:i?null:t.firstChild?Dl.call(t.childNodes):null,s,!r&&n?n:i?i.__e:t.firstChild,r),na(s,e)}Dl=Rl.slice,Tl={__e:function(e,t,n,r){for(var i,s,o;t=t.__;)if((i=t.__c)&&!i.__)try{if((s=i.constructor)&&null!=s.getDerivedStateFromError&&(i.setState(s.getDerivedStateFromError(e)),o=i.__d),null!=i.componentDidCatch&&(i.componentDidCatch(e,r||{}),o=i.__d),o)return i.__E=i}catch(t){e=t}throw e}},Ul=0,Vl.prototype.setState=function(e,t){var n;n=null!=this.__s&&this.__s!==this.state?this.__s:this.__s=$l({},this.state),"function"==typeof e&&(e=e($l({},n),this.props)),e&&$l(n,e),null!=e&&this.__v&&(t&&this.__h.push(t),zl(this))},Vl.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),zl(this))},Vl.prototype.render=Wl,jl=[],Jl.__r=0;const la={Error:{color:"red"},Alert:{error:{color:"red",fontWeight:"bold"},warning:{color:"#f80",fontWeight:"bold"},info:{color:"black"}},Darken:{position:"fixed",top:0,left:0,opacity:.5,backgroundColor:"#000",width:"100vw",height:"100vh",zIndex:150,webkitBackdropFilter:"blur(2px)",backdropFilter:"blur(2px)"},DialogOuter:{position:"fixed",top:0,left:0,width:"100vw",height:"100vh",zIndex:150,alignItems:"center",display:"flex",justifyContent:"center"},DialogInner:{position:"relative",color:"#222",backgroundColor:"#fff",padding:"30px",marginBottom:"2em",maxWidth:"90%",maxHeight:"90%",overflowY:"auto",border:"3px solid #3d3d5d",borderRadius:"8px",boxShadow:"0 0 80px 10px #666",width:"auto",fontFamily:"sans-serif"},Input:{height:"35px",width:"17em",borderColor:"#ccf4",outline:"none",fontSize:"17pt",padding:"8px"}};function aa({children:e,className:t}){return Bl("div",{className:t},Bl("div",{style:la.Darken}),Bl("div",{style:la.DialogOuter},Bl("div",{style:la.DialogInner},e)))}var ua,da,ha,fa,pa=0,ga=[],ya=[],va=Tl.__b,ma=Tl.__r,ba=Tl.diffed,wa=Tl.__c,_a=Tl.unmount;function ka(e,t){Tl.__h&&Tl.__h(da,e,pa||t),pa=0;var n=da.__H||(da.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({__V:ya}),n.__[e]}function Sa(e){return pa=1,function(e,t,n){var r=ka(ua++,2);if(r.t=e,!r.__c&&(r.__=[n?n(t):Da(void 0,t),function(e){var t=r.__N?r.__N[0]:r.__[0],n=r.t(t,e);t!==n&&(r.__N=[n,r.__[1]],r.__c.setState({}))}],r.__c=da,!da.u)){da.u=!0;var i=da.shouldComponentUpdate;da.shouldComponentUpdate=function(e,t,n){if(!r.__c.__H)return!0;var s=r.__c.__H.__.filter((function(e){return e.__c}));if(s.every((function(e){return!e.__N})))return!i||i.call(this,e,t,n);var o=!1;return s.forEach((function(e){if(e.__N){var t=e.__[0];e.__=e.__N,e.__N=void 0,t!==e.__[0]&&(o=!0)}})),!!o&&(!i||i.call(this,e,t,n))}}return r.__N||r.__}(Da,e)}function Ea(e){return pa=5,function(e,t){var n=ka(ua++,7);return Oa(n.__H,t)?(n.__V=e(),n.i=t,n.__h=e,n.__V):n.__}((function(){return{current:e}}),[])}function xa(){for(var e;e=ga.shift();)if(e.__P&&e.__H)try{e.__H.__h.forEach(Ca),e.__H.__h.forEach(Aa),e.__H.__h=[]}catch(t){e.__H.__h=[],Tl.__e(t,e.__v)}}Tl.__b=function(e){da=null,va&&va(e)},Tl.__r=function(e){ma&&ma(e),ua=0;var t=(da=e.__c).__H;t&&(ha===da?(t.__h=[],da.__h=[],t.__.forEach((function(e){e.__N&&(e.__=e.__N),e.__V=ya,e.__N=e.i=void 0}))):(t.__h.forEach(Ca),t.__h.forEach(Aa),t.__h=[])),ha=da},Tl.diffed=function(e){ba&&ba(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(1!==ga.push(t)&&fa===Tl.requestAnimationFrame||((fa=Tl.requestAnimationFrame)||function(e){var t,n=function(){clearTimeout(r),Ia&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,100);Ia&&(t=requestAnimationFrame(n))})(xa)),t.__H.__.forEach((function(e){e.i&&(e.__H=e.i),e.__V!==ya&&(e.__=e.__V),e.i=void 0,e.__V=ya}))),ha=da=null},Tl.__c=function(e,t){t.some((function(e){try{e.__h.forEach(Ca),e.__h=e.__h.filter((function(e){return!e.__||Aa(e)}))}catch(n){t.some((function(e){e.__h&&(e.__h=[])})),t=[],Tl.__e(n,e.__v)}})),wa&&wa(e,t)},Tl.unmount=function(e){_a&&_a(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.forEach((function(e){try{Ca(e)}catch(e){t=e}})),t&&Tl.__e(t,n.__v))};var Ia="function"==typeof requestAnimationFrame;function Ca(e){var t=da,n=e.__c;"function"==typeof n&&(e.__c=void 0,n()),da=t}function Aa(e){var t=da;e.__c=e.__(),da=t}function Oa(e,t){return!e||e.length!==t.length||t.some((function(t,n){return t!==e[n]}))}function Da(e,t){return"function"==typeof t?t(e):t}function Ta({message:e,messageCode:t,messageParams:n}){return e.replace(/\{\w+\}/gi,(e=>n[e.substring(1,e.length-1)]))}function Ua({title:e,type:t,alerts:n,fields:r,submitLabel:i,cancelLabel:s,onCancel:o,onSubmit:c}){const[l,a]=Sa({}),u=Ea(null);return function(e,t){var n=ka(ua++,4);!Tl.__s&&Oa(n.__H,t)&&(n.__=e,n.i=t,da.__h.push(n))}((()=>{var e;return null===(e=u.current)||void 0===e?void 0:e.focus()}),[]),Bl(aa,{className:"dxc-login-dlg"},Bl(Wl,null,Bl("h3",{style:la.WindowHeader},e),n.map((e=>Bl("p",{style:la.Alert[e.type]},Ta(e)))),Bl("form",{onSubmit:e=>{e.preventDefault(),c(l)}},Object.entries(r).map((([e,{type:t,label:n,placeholder:r}],i)=>Bl("label",{style:la.Label,key:i},n?`${n}: `:"",Bl("input",{ref:0===i?u:void 0,type:t,name:e,autoComplete:"on",style:la.Input,autoFocus:!0,placeholder:r,value:l[e]||"",onInput:n=>{var r;const i=function(e,t){switch(e){case"email":return t.toLowerCase();case"otp":return t.toUpperCase();default:return t}}(t,null===(r=n.target)||void 0===r?void 0:r.value);let s=Object.assign(Object.assign({},l),{[e]:i});a(s),"otp"===t&&8===(null==i?void 0:i.trim().length)&&c(s)}})))))),Bl("div",{style:la.ButtonsDiv},Bl(Wl,null,Bl("button",{type:"submit",style:la.Button,onClick:()=>c(l)},i),s&&Bl("button",{style:la.Button,onClick:o},s))))}class ja extends Vl{constructor(e){super(e),this.observer=e=>this.setState({userInteraction:e}),this.state={userInteraction:void 0}}componentDidMount(){this.subscription=n.from(this.props.db.cloud.userInteraction).subscribe(this.observer)}componentWillUnmount(){this.subscription&&(this.subscription.unsubscribe(),delete this.subscription)}render(e,{userInteraction:t}){return t?Bl(Ua,Object.assign({},t)):null}}function Pa(e){const t=new WeakMap;return n=>{let r=t.get(n);return r||(r=e(n),t.set(n,r)),r}}const La=Pa((e=>new n.BehaviorSubject(Rt)));function Ra(e,t){let r=t,i=n.from(e).pipe(n.map((e=>r=e)),n.share({resetOnRefCountZero:()=>n.timer(1e3)}));const s=new n.Observable((e=>{let t=!1;const n=i.subscribe({next(n){t=!0,e.next(n)},error(t){e.error(t)},complete(){e.complete()}});return t||n.closed||e.next(r),n}));return s.getValue=()=>r,s}const Na=Pa((e=>Ra(t.liveQuery((()=>e.roles.where({realmId:"rlm-public"}).toArray().then((e=>{const t={};for(const n of e.slice().sort(((e,t)=>(e.sortOrder||0)-(t.sortOrder||0))))t[n.name]=n;return t})))),{}))),$a=Pa((e=>Ra(La(e._novip).pipe(vt((n=>t.liveQuery((()=>e.transaction("r","realms","members",(()=>Promise.all([e.members.where({userId:n.userId}).toArray(),e.realms.toArray(),n.userId]).then((([e,t,n])=>({selfMembers:e,realms:t,userId:n})))))))))),{selfMembers:[],realms:[],get userId(){return e.cloud.currentUserId}})));function Ma(...e){if(0===e.length)return{};const t=e.reduce(((e,t)=>{const n=Object.assign({},e);for(const[e,r]of Object.entries(t))if(e in n&&n[e]){if("*"===n[e])continue;if("*"===r)n[e]="*";else if(Array.isArray(r)&&Array.isArray(n[e])){const t=n,i=t[e];t[e]=[...new Set([...i,...r])]}else if("object"==typeof r&&r&&"object"==typeof n[e]){const t=n[e];for(const[e,n]of Object.entries(r))"*"!==t[e]&&("*"===n?t[e]="*":Array.isArray(t[e])&&Array.isArray(n)&&(t[e]=[...new Set([...t[e],...n])]))}}else n[e]=t[e];return n}));return t}const Ba=Pa((e=>function(e,t){let r;const i=e.pipe(n.map((e=>r=t(e))));return i.getValue=()=>void 0!==r?r:r=t(e.getValue()),i}(Ra(n.combineLatest([$a(e._novip),Na(e._novip)]).pipe(rt((([{selfMembers:e,realms:t,userId:n},r])=>({selfMembers:e,realms:t,userId:n,globalRoles:r})))),{selfMembers:[],realms:[],userId:Rt.userId,globalRoles:{}}),(({selfMembers:e,realms:t,userId:n,globalRoles:r})=>{const i=t.map((t=>{const i=e.filter((e=>e.realmId===t.realmId)),s=i.map((e=>e.permissions)).filter((e=>e)),o=Zt(i.map((e=>e.roles)).filter((e=>e))).map((e=>r[e])).filter((e=>e)).map((e=>e.permissions));return Object.assign(Object.assign({},t),{permissions:t.owner===n?{manage:"*"}:Ma(...s,...o)})})).reduce(((e,t)=>Object.assign(Object.assign({},e),{[t.realmId]:t})),{[n]:{realmId:n,owner:n,name:n,permissions:{manage:"*"}}});return i}))));class Fa{constructor(e,t,n){this.permissions=e||{},this.tableName=t,this.isOwner=n}add(...e){var t;return"*"===this.permissions.manage||(!!(null===(t=this.permissions.manage)||void 0===t?void 0:t.includes(this.tableName))||("*"===this.permissions.add||!!e.every((e=>{var t;return null===(t=this.permissions.add)||void 0===t?void 0:t.includes(e)}))))}update(...e){var t,n;if(this.isOwner||"*"===this.permissions.manage)return!0;if(null===(t=this.permissions.manage)||void 0===t?void 0:t.includes(this.tableName))return!0;if("*"===this.permissions.update)return e.every((e=>"owner"!==e));const r=null===(n=this.permissions.update)||void 0===n?void 0:n[this.tableName];return"*"===r?e.every((e=>"owner"!==e)):e.every((e=>null==r?void 0:r.some((t=>t===e||"*"===t&&"owner"!==e))))}delete(){var e;return!(!this.isOwner&&"*"!==this.permissions.manage)||!!(null===(e=this.permissions.manage)||void 0===e?void 0:e.includes(this.tableName))}}const Wa=Pa((e=>{const r=La(e._novip).pipe(vt((n=>t.liveQuery((()=>e.members.where({email:n.email||""}).toArray()))))),i=Ba(e._novip),o=$a(e._novip);return Ra(n.combineLatest([r,o,i]).pipe(rt((([t,n,r])=>{const i=(e,t)=>Object.assign(Object.assign({},e),{[t.id]:Object.assign(Object.assign({},t),{realm:r[t.realmId]})}),o=t.reduce(i,{}),c=n.selfMembers.reduce(i,o);return Object.values(c).filter((e=>!e.accepted)).map((t=>Object.assign(Object.assign({},t),{accept(){return s(this,void 0,void 0,(function*(){yield e.members.update(t.id,{accepted:new Date})}))},reject(){return s(this,void 0,void 0,(function*(){yield e.members.update(t.id,{rejected:new Date})}))}})))}))),[])}));function Va(e){return r=>{var i;const o=r.doc;if(!o)throw new Error("Internal error: DexieYProvider.createYHandler called without a doc. This is unexpected.");const{parentTable:c}=o.meta||{};if(!(null===(i=e.cloud.schema)||void 0===i?void 0:i[c].markedForSync))return;let l;Object.defineProperty(r,"awareness",{get:()=>l||(l=function(e,r,i){const{parentTable:o,parentId:c,parentProp:l,updatesTable:a}=r.meta,u=gl(e),d=new u.Awareness(r),h=ml(r);return d.on("update",(({added:t,updated:n,removed:s},c)=>{const a=t.concat(n).concat(s),h=e.cloud.currentUser.value;if("server"!==c&&h.isLoggedIn&&!il(e)){const t=u.encodeAwarenessUpdate(d,a);e.messageProducer.next({type:"aware",table:o,prop:l,k:r.meta.parentId,u:t}),i.destroyed&&e.messageProducer.next({type:"doc-close",table:o,prop:l,k:r.meta.parentId})}})),d.on("destroy",(()=>{u.removeAwarenessStates(d,[r.clientID],"provider destroyed")})),(()=>{s(this,void 0,void 0,(function*(){if(i.destroyed)return;let r=!1,u=1;const d=n.combineLatest([e.cloud.webSocketStatus,h.pipe(n.startWith(null))]).subscribe((([t])=>{if(i.destroyed)return;r="connected"===t;const n=e.cloud.currentUser.value;"connected"===t&&n.isLoggedIn&&!il(e)&&(++u,f().catch((e=>{})))}));function f(){return s(this,void 0,void 0,(function*(){const n=u,d=e.table(a),h=e.$syncState,[f,p]=yield e.transaction("r",h,d,(()=>s(this,void 0,void 0,(function*(){const e=yield d.get(Kn),t=yield h.get("syncState");return[(null==e?void 0:e.receivedUntil)||0,(null==t?void 0:t.yServerRevision)||(null==t?void 0:t.serverRevision)]}))));if(i.destroyed||u!==n||!r)return;const g={type:"doc-open",table:o,prop:l,k:c,serverRev:p},y=yield d.where("i").between(f,1/0,!1).filter((e=>0===t.cmp(e.k,c)&&0==(1&(e.f||0)))).toArray();if(!i.destroyed&&u===n&&r){if(y.length>0){const e=Ls(y.map((e=>e.u))),t=js(e);g.sv=t}e.messageProducer.next(g)}}))}i.addCleanupHandler(d)}))})(),d}(e,o,r),yl.set(o,l),l)})}}const Ka={},Ha=new WeakMap,za=qa("tx"),Ja=qa("unload");function qa(e){let t=null,n=!1,r=new Map;return{name:e,run(){return s(this,void 0,void 0,(function*(){!n&&r.size>0&&(n=!0,t&&(yield t.catch((()=>{}))),setTimeout((()=>{n=!1;const e=r;r=new Map,t=function(e){return s(this,void 0,void 0,(function*(){for(const{db:t,parentId:n,triggers:r,parentTable:i,prop:s}of e.values()){const e=Ec.getOrCreateDocument(t,i,s,n);try{const t=Ec.load(e);yield t.whenLoaded;for(const t of r)yield t(e,n)}catch(e){null==e||e.name}finally{Ec.release(e)}}}))}(e).finally((()=>{t=null}))}),0))}))},enqueue(e,t,n,i,s){const o=`${e.name}:${t}:${n}:${i}`;let c=r.get(o);c||(c={db:e,parentTable:t,parentId:n,prop:i,triggers:new Set},r.set(o,c)),c.triggers.add(s)}}}function Ya(){za.run()}function Ga(){Ja.run()}const Qa={nameSuffix:!0};function Xa(e){const r=e.name,i=La(e),o=[];let c=!1,l=null;e.on("ready",(e=>s(this,void 0,void 0,(function*(){try{yield function(e){return s(this,void 0,void 0,(function*(){var r,h,f,p,g,y,v;a=!1;const m=Fc(e);"undefined"!=typeof window&&"undefined"!=typeof document&&((null===(r=m.cloud.options)||void 0===r?void 0:r.customLoginGui)||o.push(function(e){let t=!1;const n=document.createElement("div");return document.body?(document.body.appendChild(n),ca(Bl(ja,{db:e.vip}),n)):addEventListener("DOMContentLoaded",(()=>{t||(document.body.appendChild(n),ca(Bl(ja,{db:e.vip}),n))})),{unsubscribe(){try{n.remove()}catch(e){}t=!0},get closed(){return t}}}(e))),m.cloud.isServiceWorkerDB||o.push(function(e){let t=e.cloud.webSocketStatus.value;const r=e.cloud.webSocketStatus.pipe(vt((e=>{const r=t;t=e;const i=n.of(e);switch(e){case"disconnected":return ll.value?i.pipe(ot(500)):i;case"connecting":return"not-started"===r||"error"===r?i:i.pipe(ot(4e3));default:return i}})));return n.combineLatest([r,e.syncStateChangedEvent.pipe(yt({phase:"initial"})),La(e.dx._novip),al]).pipe(rt((([t,n,r,i])=>{var s;if((null===(s=r.license)||void 0===s?void 0:s.status)&&"ok"!==r.license.status)return{phase:"offline",status:"offline",license:r.license.status};let{phase:o,error:c,progress:l}=n,a=t;return"error"===o&&(a="error"),"not-started"===t&&("pushing"!==o&&"pulling"!==o||(a="connecting")),"error"!==e.cloud.syncState.value.phase||"pushing"!==n.phase&&"pulling"!==n.phase||(a="connecting"),i||(a="disconnected"),{phase:o,error:c,progress:l,status:Mn?a:"offline",license:"ok"}})))}(m).subscribe(e.cloud.syncState)),o.push(m.syncCompleteEvent.subscribe(d)),m.tables.every((e=>e.core))||function(){throw new t.SchemaError("Version increment needed to allow dexie-cloud change tracking")}();const b="serviceWorker"in navigator?yield navigator.serviceWorker.getRegistrations():[],[w,_]=yield m.transaction("rw",m.$syncState,(()=>s(this,void 0,void 0,(function*(){var e,t;const{options:n,schema:r}=m.cloud,[i,s,o]=yield Promise.all([m.getOptions(),m.getSchema(),m.getPersistedSyncState()]);if(c){if(!i||JSON.stringify(i)!==JSON.stringify(n)){if(!n)throw new Error("Internal error");const e=Object.assign({},n);delete e.fetchTokens,delete e.awarenessProtocol,yield m.$syncState.put(e,"options")}}else m.cloud.options=i||null;if((null===(e=m.cloud.options)||void 0===e?void 0:e.tryUseServiceWorker)&&"serviceWorker"in navigator&&b.length>0&&!Hc?m.cloud.usingServiceWorker=!0:((null===(t=m.cloud.options)||void 0===t?void 0:t.tryUseServiceWorker)&&m.cloud.isServiceWorkerDB,m.cloud.usingServiceWorker=!1),Ol(r,m.cloud.options),Ol(s,m.cloud.options),r){if(!s||JSON.stringify(s)!==JSON.stringify(r)){const e=s||{};for(const[t,n]of Object.entries(r)){const r=e[t];r?(r.markedForSync=n.markedForSync,n.deleted=r.deleted,r.generatedGlobalId=n.generatedGlobalId):e[t]=Object.assign({},n)}yield m.$syncState.put(e,"schema"),Object.assign(r,e)}}else m.cloud.schema=s||null;return[null==o?void 0:o.initiallySynced,null==o?void 0:o.realms]}))));if(w&&m.setInitiallySynced(!0),function(e){var n,r;for(const i of e.tables)if(null===(r=null===(n=e.cloud.schema)||void 0===n?void 0:n[i.name])||void 0===r?void 0:r.markedForSync){if(i.schema.primKey.auto)throw new t.SchemaError(`Table ${i.name} is both autoIncremented and synced. Use db.cloud.configure({unsyncedTables: [${JSON.stringify(i.name)}]}) to blacklist it from sync`);if(!i.schema.primKey.keyPath)throw new t.SchemaError(`Table ${i.name} cannot be both synced and outbound. Use db.cloud.configure({unsyncedTables: [${JSON.stringify(i.name)}]}) to blacklist it from sync`)}}(m),u(),!m.cloud.isServiceWorkerDB){o.push(t.liveQuery((()=>m.getCurrentUser())).subscribe(i)),o.push(t.liveQuery((()=>m.getPersistedSyncState())).subscribe(m.cloud.persistedSyncState)),yield n.firstValueFrom(n.combineLatest([i.pipe(gt(1),at(1)),m.cloud.persistedSyncState.pipe(gt(1),at(1))]));const e=Va(m);Ec.on.new.subscribe(e),m.dx.once("close",(()=>{Ec.on.new.unsubscribe(e)}))}let k=!1;const S=yield m.getCurrentUser(),E=null===(h=m.cloud.options)||void 0===h?void 0:h.requireAuth;E&&(m.cloud.isServiceWorkerDB?yield n.firstValueFrom(i.pipe(pt((e=>!!e.isLoggedIn)),at(1))):"object"==typeof E?(!S.isLoggedIn||E.userId&&S.userId!==E.userId||E.email&&S.email!==E.email)&&(k=yield Wt(m,E)):S.isLoggedIn||(k=yield Wt(m))),!S.isLoggedIn||_&&_.includes(S.userId)||(k=!0),l&&l.stop(),l=null,u();const x=(null===(f=m.cloud.options)||void 0===f?void 0:f.databaseUrl)&&(!w||k);x&&(yield function(e,t,n){return s(this,void 0,void 0,(function*(){yield cl(e,Dc,(()=>Tc(e,t,n,{isInitialSync:!0})))}))}(m,m.cloud.options,m.cloud.schema),m.setInitiallySynced(!0)),u(),m.cloud.usingServiceWorker&&(null===(p=m.cloud.options)||void 0===p?void 0:p.databaseUrl)?(x||wt(m,"push").catch((()=>{})),function(e){return s(this,void 0,void 0,(function*(){var t;try{const{periodicSync:n}=yield navigator.serviceWorker.ready;if(n)try{yield n.register(`dexie-cloud:${e.name}`,null===(t=e.cloud.options)||void 0===t?void 0:t.periodicSync)}catch(e){}}catch(e){}}))}(m).catch((()=>{}))):(null===(g=m.cloud.options)||void 0===g?void 0:g.databaseUrl)&&m.cloud.schema&&!m.cloud.isServiceWorkerDB&&(l=Al(m,m.cloud.options,m.cloud.schema),l.start(),x||_t(m,"push")),u(),m.cloud.isServiceWorkerDB||o.push(n.fromEvent(self,"online").subscribe((()=>{m.syncStateChangedEvent.next({phase:"not-in-sync"}),il(m)||_t(m,"push")})),n.fromEvent(self,"offline").subscribe((()=>{m.syncStateChangedEvent.next({phase:"offline"})}))),!(null===(y=m.cloud.options)||void 0===y?void 0:y.databaseUrl)||(null===(v=m.cloud.options)||void 0===v?void 0:v.disableWebSocket)||zc||o.push(function(e){var t;if(!(null===(t=e.cloud.options)||void 0===t?void 0:t.databaseUrl))throw new Error("No database URL to connect WebSocket to");const r=e.messageConsumer.readyToServe.pipe(pt((e=>e)),vt((()=>e.getPersistedSyncState())),pt((e=>e&&e.serverRevision)),vt((e=>s(this,void 0,void 0,(function*(){return{type:"ready",rev:e.serverRevision,realmSetHash:yield qt(e)}}))))),i=n.merge(r,e.messageProducer);return function t(){return e.cloud.persistedSyncState.pipe(pt((e=>null==e?void 0:e.serverRevision)),at(1),vt((t=>e.cloud.currentUser.pipe(rt((e=>[e,t]))))),vt((([e,t])=>al.pipe(rt((n=>[n?e:null,t]))))),vt((([t,r])=>(null==t?void 0:t.isLoggedIn)&&!(null==r?void 0:r.realms.includes(t.userId))?e.cloud.persistedSyncState.pipe(pt((e=>(null==e?void 0:e.realms.includes(t.userId))||!1)),at(1),rt((e=>[t,e]))):new n.BehaviorSubject([t,r]))),vt((e=>s(this,[e],void 0,(function*([e,t]){return[e,yield qt(t)]})))),ht((([e,t],[n,r])=>e===n&&t===r)),vt((([r,s])=>{var o;return(null===(o=e.cloud.persistedSyncState)||void 0===o?void 0:o.value)?r?new bl(e,e.cloud.persistedSyncState.value.serverRevision,e.cloud.persistedSyncState.value.yServerRevision,s,e.cloud.persistedSyncState.value.clientIdentity,i,e.cloud.webSocketStatus,r):n.from([]):t()})),Xe((r=>"TokenExpiredError"===(null==r?void 0:r.name)?n.of(!0).pipe(vt((()=>s(this,void 0,void 0,(function*(){const t=yield e.getCurrentUser(),n=yield jt(e.cloud.options.databaseUrl,t);yield e.table("$logins").update(t.userId,{accessToken:n.accessToken,accessTokenExpiration:n.accessTokenExpiration,claims:n.claims,license:n.license,data:n.data})})))),vt((()=>t()))):n.throwError((()=>r)))),Xe((r=>(e.cloud.webSocketStatus.next("error"),r instanceof kl?n.throwError((()=>r)):n.from(Sl()).pipe(vt((()=>t())))))))}().subscribe({next:t=>{t&&e.messageConsumer.enqueue(t)},error:e=>{},complete:()=>{}})}(m))}))}(e)}catch(e){}}))),!0);let a=!1;function u(){if(a)throw new t.DatabaseClosedError}e.once("close",(()=>{o.forEach((e=>e.unsubscribe())),o.splice(0,o.length),a=!0,l&&l.stop(),l=null,i.next(Rt)}));const d=new n.Subject;var h;e.cloud={version:"4.2.0-alpha.1",options:Object.assign({},Qa),schema:null,get currentUserId(){return i.value.userId||Rt.userId},currentUser:i,syncState:new n.BehaviorSubject({phase:"initial",status:"not-started"}),events:{syncComplete:d},persistedSyncState:new n.BehaviorSubject(void 0),userInteraction:new n.BehaviorSubject(void 0),webSocketStatus:new n.BehaviorSubject("not-started"),login(t){return s(this,void 0,void 0,(function*(){const n=Fc(e);yield n.cloud.sync(),yield Wt(n,t)}))},invites:Wa(e),roles:Na(e),configure(t){t=e.cloud.options=Object.assign(Object.assign({},e.cloud.options),t),c=!0,t.databaseUrl&&t.nameSuffix&&(e.name=`${r}-${function(e){const t=new URL(e);return"/"===t.pathname?t.hostname.split(".")[0]:t.pathname.split("/")[1]}(t.databaseUrl)}`,Fc(e).reconfigure()),Ol(e.cloud.schema,e.cloud.options)},logout(){return s(this,arguments,void 0,(function*({force:t}={}){t?yield Mt(Fc(e),{deleteUnsyncedData:!0}):yield $t(Fc(e))}))},sync(){return s(this,arguments,void 0,(function*({wait:r,purpose:i}={wait:!0,purpose:"push"}){var o;void 0===r&&(r=!0);const c=Fc(e);if("ok"!==((null===(o=c.cloud.currentUser.value.license)||void 0===o?void 0:o.status)||"ok")&&(yield Tt(c)),"pull"===i){const e=c.cloud.persistedSyncState.value;if(_t(c,i),r){const t=yield n.firstValueFrom(c.cloud.persistedSyncState.pipe(pt((t=>null!=(null==t?void 0:t.timestamp)&&(!e||t.timestamp>e.timestamp)))));if(null==t?void 0:t.error)throw new Error("Sync error: "+t.error)}}else if(yield El(c)){const e=c.cloud.persistedSyncState.value;_t(c,i),r&&(yield n.firstValueFrom(n.from(t.liveQuery((()=>s(this,void 0,void 0,(function*(){const t=yield El(c),n=yield c.getPersistedSyncState();if((null==n?void 0:n.timestamp)!==(null==e?void 0:e.timestamp)&&(null==n?void 0:n.error))throw new Error("Sync error: "+n.error);return t}))))).pipe(pt((e=>!e)))))}}))},permissions:(t,n)=>function(e,t,n){if(!t)throw new TypeError("Cannot check permissions of undefined or null. A Dexie Cloud object with realmId and owner expected.");const{owner:r,realmId:i}=t;if(!n){if("function"!=typeof t.table)throw new TypeError("Missing 'table' argument to permissions and table could not be extracted from entity");n=t.table()}const s=Ba(e),o=t=>{const s=t[i||e.cloud.currentUserId];return s?new Fa(s.permissions,n,void 0===i||i===e.cloud.currentUserId||r===e.cloud.currentUserId):new Fa({},n,!r||r===e.cloud.currentUserId)},c=s.pipe(rt(o));return c.getValue=()=>o(s.getValue()),c}(e._novip,t,n)},e.Version.prototype._parseStoresSpec=t.override(e.Version.prototype._parseStoresSpec,(t=>ol(t,e))),e.Table.prototype.newId=function({colocateWith:t}={}){const n=t&&t.substr(t.length-3);return Xc(e.cloud.schema[this.name].idPrefix||"",n)},e.Table.prototype.idPrefix=function(){var e,t;return(null===(t=null===(e=this.db.cloud.schema)||void 0===e?void 0:e[this.name])||void 0===t?void 0:t.idPrefix)||""},e.use(sl({currentUserObservable:e.cloud.currentUser,db:Fc(e)})),e.use((h=Fc(e),{stack:"dbcore",name:"implicitPropSetterMiddleware",level:1,create:e=>Object.assign(Object.assign({},e),{table:t=>{const n=e.table(t);return Object.assign(Object.assign({},n),{mutate:e=>{var r,i,s,o,c,l;const a=e.trans;if(a.disableChangeTracking)return n.mutate(e);const u=null!==(i=null===(r=a.currentUser)||void 0===r?void 0:r.userId)&&void 0!==i?i:Rt.userId;if((null===(o=null===(s=h.cloud.schema)||void 0===s?void 0:s[t])||void 0===o?void 0:o.markedForSync)&&("add"===e.type||"put"===e.type)){if("members"===t)for(const t of e.values)"string"==typeof t.email&&(t.email=t.email.trim().toLowerCase());for(const t of e.values){t.owner||(t.owner=u),t.realmId||(t.realmId=u);const r=null===(l=(c=n.schema.primaryKey).extractKey)||void 0===l?void 0:l.call(c,t);"string"==typeof r&&"#"===r[0]&&"put"===e.type&&(delete e.criteria,delete e.changeSpec,delete e.updates,t.$ts=Date.now())}}return n.mutate(e)}})}})})),e.use(Zc(Fc(e)))}Xa.version="4.2.0-alpha.1",t.Cloud=Xa,e.default=Xa,e.defineYDocTrigger=function(e,n,r){var i,s;const o=null===(s=null===(i=e.schema.yProps)||void 0===i?void 0:i.find((e=>e.prop===n)))||void 0===s?void 0:s.updatesTable;if(!o)throw new Error(`Table ${e.name} does not have a Yjs property named ${n}`);Ka[o]={trigger:r,parentTable:e.name,prop:n};const c=e.db._novip;let l=Ha.get(c);l||(l=(e=>({stack:"dbcore",level:10,name:"yTriggerMiddleware",create:n=>Object.assign(Object.assign({},n),{transaction:(e,t,r)=>{const i=n.transaction(e,t,r);return"readonly"===t?i:e.some((e=>Ka[e]))?(i.addEventListener("complete",Ya),i):i},table:r=>{const i=n.table(r),s=Ka[r];if(!s)return i;const{trigger:o,parentTable:c,prop:l}=s;return Object.assign(Object.assign({},i),{mutate(n){var r;switch(n.type){case"add":for(const t of n.values){if(null==t.k)continue;const n=t.k,i=Ec.getDocCache(e).find(c,n,l);(i&&(null===(r=Ec.for(i))||void 0===r?void 0:r.refCount)?Ja:za).enqueue(e,c,n,l,o)}break;case"delete":n.trans._rejecting_y_ypdate&&i.getMany({keys:n.keys,trans:n.trans,cache:"immutable"}).then((n=>{const r=new t.RangeSet;for(const{k:e}of n)null!=e&&r.addKey(e);for(const t of r)za.enqueue(e,c,t.from,l,o)}))}return i.mutate(n)}})}})}))(c),Ha.set(c,l)),c.use(l),Ec.on("beforeunload",Ga)},e.dexieCloud=Xa,e.getTiedObjectId=function(e){return e.startsWith("rlm~")?e.substr(4):null},e.getTiedRealmId=function(e){return"rlm~"+e},e.resolveText=Ta,Object.defineProperty(e,"__esModule",{value:!0})}));
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("dexie"),require("rxjs"),require("rxjs/operators")):"function"==typeof define&&define.amd?define(["exports","dexie","rxjs","rxjs/operators"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).DexieCloud={},e.Dexie,e.rxjs,e.rxjs.operators)}(this,(function(e,t,n,r){"use strict";function s(e,t,n,r){return new(n||(n=Promise))((function(s,i){function o(e){try{c(r.next(e))}catch(e){i(e)}}function l(e){try{c(r.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,l)}c((r=r.apply(e,t||[])).next())}))}function i(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function o(e){return this instanceof o?(this.v=e,this):new o(e)}function l(e,t,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r,s=n.apply(e,t||[]),i=[];return r={},l("next"),l("throw"),l("return"),r[Symbol.asyncIterator]=function(){return this},r;function l(e){s[e]&&(r[e]=function(t){return new Promise((function(n,r){i.push([e,t,n,r])>1||c(e,t)}))})}function c(e,t){try{!function(e){e.value instanceof o?Promise.resolve(e.value.v).then(a,u):d(i[0][2],e)}(s[e](t))}catch(e){d(i[0][3],e)}}function a(e){c("next",e)}function u(e){c("throw",e)}function d(e,t){e(t),i.shift(),i.length&&c(i[0][0],i[0][1])}}function c(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,n=e[Symbol.asyncIterator];return n?n.call(e):(e=i(e),t={},r("next"),r("throw"),r("return"),t[Symbol.asyncIterator]=function(){return this},t);function r(n){t[n]=e[n]&&function(t){return new Promise((function(r,s){(function(e,t,n,r){Promise.resolve(r).then((function(t){e({value:t,done:n})}),t)})(r,s,(t=e[n](t)).done,t.value)}))}}}const a={}.hasOwnProperty;function u(e,t,n){if(e&&void 0!==t&&(!("isFrozen"in Object)||!Object.isFrozen(e)))if("string"!=typeof t&&"length"in t){!function(e){if(!e)throw new Error("Assertion Failed")}("string"!=typeof n&&"length"in n);for(var r=0,s=t.length;r<s;++r)u(e,t[r],n[r])}else{var i=t.indexOf(".");if(-1!==i){var o=t.substr(0,i),l=t.substr(i+1);if(""===l)void 0===n?Array.isArray(e)?isNaN(parseInt(o))||e.splice(parseInt(o),1):delete e[o]:e[o]=n;else{var c=e[o];c&&function(e,t){return a.call(e,t)}(e,o)||(c=e[o]={}),u(c,l,n)}}else void 0===n?Array.isArray(e)&&!isNaN(parseInt(t))?e.splice(t,1):delete e[t]:e[t]=n}}const d="undefined"!=typeof self&&"undefined"!=typeof crypto?(e,t=crypto.getRandomValues.bind(crypto))=>{const n=new Uint8Array(e);return t(n),self.btoa(String.fromCharCode.apply(null,n))}:"undefined"!=typeof Buffer?(e,t=h)=>{const n=Buffer.alloc(e);return t(n),n.toString("base64")}:()=>{throw new Error("No implementation of randomString was found")};function h(e){for(let t=0;t<e.length;++t)e[t]=Math.floor(256*Math.random())}function f(e){return"string"==typeof e||!!(Array.isArray(e)&&e.some((e=>f(e)))&&e.every(p))}function p(e){return"string"==typeof e||"number"==typeof e||Array.isArray(e)&&e.every(p)}function g(e,t,n){const r=e[t]||(e[t]={}),s=n.keys.map((e=>"string"==typeof e?e:JSON.stringify(e)));switch(n.type){case"insert":case"upsert":s.forEach(((e,t)=>{r[e]={type:"ups",val:n.values[t]}}));break;case"update":case"modify":s.forEach(((e,t)=>{const s="update"===n.type?n.changeSpecs[t]:n.changeSpec,i=r[e];if(i)switch(i.type){case"ups":for(const[e,t]of Object.entries(s))u(i.val,e,t);break;case"del":break;case"upd":Object.assign(i.mod,s)}else r[e]={type:"upd",mod:s}}));break;case"delete":s.forEach((e=>{r[e]={type:"del"}}))}return e}function y(e,t){for(const{table:n,muts:r}of t)for(const t of r)g(e,n,t)}const m=Math.floor,v=Math.abs,b=(e,t)=>e>t?e:t,w=128,_=127,k=Number.MAX_SAFE_INTEGER,S=Number.isInteger||(e=>"number"==typeof e&&isFinite(e)&&m(e)===e),E=Array.isArray,x="undefined"!=typeof TextEncoder?new TextEncoder:null,C=x?e=>x.encode(e):e=>{const t=unescape(encodeURIComponent(e)),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.codePointAt(e);return r};let I="undefined"==typeof TextDecoder?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});I&&1===I.decode(new Uint8Array).length&&(I=null);let A=class{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}};const D=(e,t)=>{const n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(2*n),e.cpos=0),e.cbuf[e.cpos++]=t},O=(e,t)=>{for(;t>_;)D(e,w|_&t),t=m(t/128);D(e,_&t)},T=new Uint8Array(3e4),U=T.length/3,j=x&&x.encodeInto?(e,t)=>{if(t.length<U){const n=x.encodeInto(t,T).written||0;O(e,n);for(let t=0;t<n;t++)D(e,T[t])}else L(e,C(t))}:(e,t)=>{const n=unescape(encodeURIComponent(t)),r=n.length;O(e,r);for(let t=0;t<r;t++)D(e,n.codePointAt(t))},L=(e,t)=>{O(e,t.byteLength),((e,t)=>{const n=e.cbuf.length,r=e.cpos,s=((e,t)=>e<t?e:t)(n-r,t.length),i=t.length-s;e.cbuf.set(t.subarray(0,s),r),e.cpos+=s,i>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(b(2*n,i)),e.cbuf.set(t.subarray(s)),e.cpos=i)})(e,t)},P=(e,t)=>{((e,t)=>{const n=e.cbuf.length;n-e.cpos<t&&(e.bufs.push(new Uint8Array(e.cbuf.buffer,0,e.cpos)),e.cbuf=new Uint8Array(2*b(n,t)),e.cpos=0)})(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},R=(e,t)=>P(e,8).setBigUint64(0,t,!1),M=new DataView(new ArrayBuffer(4)),$=(e,t)=>{switch(typeof t){case"string":D(e,119),j(e,t);break;case"number":S(t)&&v(t)<=2147483647?(D(e,125),((e,t)=>{const n=(e=>0!==e?e<0:1/e<0)(t);for(n&&(t=-t),D(e,(t>63?w:0)|(n?64:0)|63&t),t=m(t/64);t>0;)D(e,(t>_?w:0)|_&t),t=m(t/128)})(e,t)):(n=t,M.setFloat32(0,n),M.getFloat32(0)===n?(D(e,124),((e,t)=>{P(e,4).setFloat32(0,t,!1)})(e,t)):(D(e,123),((e,t)=>{P(e,8).setFloat64(0,t,!1)})(e,t)));break;case"bigint":D(e,122),((e,t)=>{P(e,8).setBigInt64(0,t,!1)})(e,t);break;case"object":if(null===t)D(e,126);else if(E(t)){D(e,117),O(e,t.length);for(let n=0;n<t.length;n++)$(e,t[n])}else if(t instanceof Uint8Array)D(e,116),L(e,t);else{D(e,118);const n=Object.keys(t);O(e,n.length);for(let r=0;r<n.length;r++){const s=n[r];j(e,s),$(e,t[s])}}break;case"boolean":D(e,t?120:121);break;default:D(e,127)}var n};function N(e){const t=new A;switch(j(t,e.type),"table"in e&&j(t,e.table),"prop"in e&&j(t,e.prop),e.type){case"u-ack":case"u-reject":R(t,BigInt(e.i));break;case"outdated-server-rev":break;case"y-complete-sync-done":j(t,e.yServerRev);break;default:switch($(t,e.k),e.type){case"aware":L(t,e.u);break;case"doc-open":$(t,e.serverRev),$(t,e.sv);break;case"doc-close":break;case"sv":L(t,e.sv);break;case"u-c":L(t,e.u),R(t,BigInt(e.i));break;case"u-s":L(t,e.u),j(t,e.r||"")}}return(e=>{const t=new Uint8Array((e=>{let t=e.cpos;for(let n=0;n<e.bufs.length;n++)t+=e.bufs[n].length;return t})(e));let n=0;for(let r=0;r<e.bufs.length;r++){const s=e.bufs[r];t.set(s,n),n+=s.length}return t.set(new Uint8Array(e.cbuf.buffer,0,e.cpos),n),t})(t)}const B=e=>new Error(e),F=B("Unexpected end of array"),W=B("Integer out of Range");let V=class{constructor(e){this.arr=e,this.pos=0}};const K=e=>e.pos!==e.arr.length,H=e=>((e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n})(e,z(e)),J=e=>e.arr[e.pos++],z=e=>{let t=0,n=1;const r=e.arr.length;for(;e.pos<r;){const r=e.arr[e.pos++];if(t+=(r&_)*n,n*=128,r<w)return t;if(t>k)throw W}throw F},q=I?e=>I.decode(H(e)):e=>{let t=z(e);if(0===t)return"";{let n=String.fromCodePoint(J(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(J(e));else for(;t>0;){const r=t<1e4?t:1e4,s=e.arr.subarray(e.pos,e.pos+r);e.pos+=r,n+=String.fromCodePoint.apply(null,s),t-=r}return decodeURIComponent(escape(n))}},Y=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},G=e=>Y(e,8).getBigUint64(0,!1),Q=[e=>{},e=>null,e=>{let t=e.arr[e.pos++],n=63&t,r=64;const s=(64&t)>0?-1:1;if(0==(t&w))return s*n;const i=e.arr.length;for(;e.pos<i;){if(t=e.arr[e.pos++],n+=(t&_)*r,r*=128,t<w)return s*n;if(n>k)throw W}throw F},e=>Y(e,4).getFloat32(0,!1),e=>Y(e,8).getFloat64(0,!1),e=>Y(e,8).getBigInt64(0,!1),e=>!1,e=>!0,q,e=>{const t=z(e),n={};for(let r=0;r<t;r++){n[q(e)]=X(e)}return n},e=>{const t=z(e),n=[];for(let r=0;r<t;r++)n.push(X(e));return n},H],X=e=>Q[127-J(e)](e);function Z(e){return l(this,arguments,(function*(){var t,n,r,s;let i=0,l=new Uint8Array(4),a=0,u=[],d=0;try{for(var h,f=!0,p=c(e);!(t=(h=yield o(p.next())).done);f=!0){s=h.value,f=!1;const e=s,t=new DataView(e.buffer,e.byteOffset,e.byteLength);let n=0;for(;n<e.byteLength;)switch(i){case 0:if(n+4>e.byteLength){for(const t of e.slice(n)){if(4===a)break;l[a++]=t,++n}if(a<4)break}else if(a>0&&a<4)for(const t of e.slice(n,n+4-a))l[a++]=t,++n;case 1:d=4===a?new DataView(l.buffer,0,4).getUint32(0,!1):t.getUint32(n,!1),a?a=0:n+=4;case 2:if(n>=e.byteLength){i=2;break}if(n+d>e.byteLength)u.push(e.slice(n)),d-=e.byteLength-n,i=2,n=e.byteLength;else{if(u.length>0){const t=new Uint8Array(u.reduce(((e,t)=>e+t.byteLength),d));let r=0;for(const e of u)t.set(e,r),r+=e.byteLength;t.set(e.slice(n,n+d),r),u=[],yield yield o(t)}else yield yield o(e.slice(n,n+d));n+=d,i=0}}}}catch(e){n={error:e}}finally{try{f||t||!(r=p.return)||(yield o(r.call(p)))}finally{if(n)throw n.error}}}))}let ee=!1;function te(e,t){return s(this,void 0,void 0,(function*(){try{const n=yield navigator.serviceWorker.ready;if("push"===t&&n.sync&&(yield n.sync.register(`dexie-cloud:${e.name}`)),!n.active)throw new Error("Failed to trigger sync - there's no active service worker");return void n.active.postMessage({type:"dexie-cloud-sync",dbName:e.name,purpose:t})}catch(e){ee||(ee=!0)}}))}function ne(e,t){e.cloud.usingServiceWorker?te(e,t):e.localSyncEvent.next({purpose:t})}const re="fromBase64"in Uint8Array,se="toBase64"in Uint8Array.prototype,ie="undefined"!=typeof Buffer?e=>Buffer.from(e,"base64"):re?e=>Uint8Array.fromBase64(e):e=>{const t=atob(e),n=t.length,r=new Uint8Array(n);for(var s=0;s<n;s++)r[s]=t.charCodeAt(s);return r},oe="undefined"!=typeof Buffer?e=>ArrayBuffer.isView(e)?Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"):Buffer.from(e).toString("base64"):se?e=>(ArrayBuffer.isView(e)?e:new Uint8Array(e)).toBase64():e=>{const t=ArrayBuffer.isView(e)?e:new Uint8Array(e),n=[];for(let e=0,r=t.length;e<r;e+=4096){const r=t.subarray(e,e+4096);n.push(String.fromCharCode.apply(null,r))}return btoa(n.join(""))};class le extends Error{constructor({title:e,message:t,messageCode:n,messageParams:r}){super(t),this.name="TokenErrorResponseError",this.title=e,this.messageCode=n,this.messageParams=r}}function ce(e,n){return new Promise(((r,s)=>{const i=Object.assign(Object.assign({submitLabel:"Submit",cancelLabel:"Cancel"},n),{onSubmit:t=>{e.next(void 0),r(t)},onCancel:()=>{e.next(void 0),s(new t.AbortError("User cancelled"))}});e.next(i)}))}function ae(e,t,...n){return ce(e,{type:"message-alert",title:t,alerts:n,fields:{},submitLabel:"OK",cancelLabel:null})}function ue(e,t,n){return s(this,void 0,void 0,(function*(){let r=n||"";for(;!r||!/^[\w-+.]+@([\w-]+\.)+[\w-]{2,10}(\sas\s[\w-+.]+@([\w-]+\.)+[\w-]{2,10})?$/.test(r);)r=(yield ce(e,{type:"email",title:t,alerts:r?[{type:"error",messageCode:"INVALID_EMAIL",message:"Please enter a valid email address",messageParams:{}}]:[],fields:{email:{type:"email",placeholder:"you@somedomain.com"}}})).email;return r}))}function de(e,t,n){return s(this,void 0,void 0,(function*(){const r=[{type:"info",messageCode:"OTP_SENT",message:"A One-Time password has been sent to {email}",messageParams:{email:t}}];n&&r.push(n);const{otp:s}=yield ce(e,{type:"otp",title:"Enter OTP",alerts:r,fields:{otp:{type:"otp",label:"OTP",placeholder:"Paste OTP here"}}});return s}))}function he(e){return s(this,void 0,void 0,(function*(){var t,n,r;const s=yield e.getCurrentUser(),{accessToken:i,accessTokenExpiration:o,refreshToken:l,refreshTokenExpiration:c,claims:a}=s;if(!i)return null;if((null!==(t=null==o?void 0:o.getTime())&&void 0!==t?t:1/0)>Date.now()&&"ok"===((null===(n=s.license)||void 0===n?void 0:n.status)||"ok"))return s;if(!l)throw new Error("Refresh token missing");if((null!==(r=null==c?void 0:c.getTime())&&void 0!==r?r:1/0)<=Date.now())throw new Error("Refresh token has expired");const u=yield pe(e.cloud.options.databaseUrl,s);return yield e.table("$logins").update(a.sub,{accessToken:u.accessToken,accessTokenExpiration:u.accessTokenExpiration,claims:u.claims,license:u.license,data:u.data}),u}))}function fe(e,n,r,i,o){return s(this,void 0,void 0,(function*(){return n.accessToken&&n.accessTokenExpiration.getTime()>Date.now()?n:n.refreshToken&&(!n.refreshTokenExpiration||n.refreshTokenExpiration.getTime()>Date.now())?yield pe(e,n):yield function(e,n,r,i){return s(this,void 0,void 0,(function*(){if(!crypto.subtle)throw"undefined"!=typeof location&&"http:"===location.protocol?new Error("Dexie Cloud Addon needs to use WebCrypto, but your browser has disabled it due to being served from an insecure location. Please serve it from https or http://localhost:<port> (See https://stackoverflow.com/questions/46670556/how-to-enable-crypto-subtle-for-unsecure-origins-in-chrome/46671627#46671627)"):new Error("This browser does not support WebCrypto.");const{privateKey:s,publicKey:o}=yield crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:2048,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!1,["sign","verify"]);if(!s||!o)throw new Error("Could not generate RSA keypair");e.nonExportablePrivateKey=s;const l=function(e){const t=oe(e);return function(e){let t="-----BEGIN PUBLIC KEY-----\n";for(;e.length>0;)t+=e.substring(0,64)+"\n",e=e.substring(64);return t+="-----END PUBLIC KEY-----",t}(t)}(yield crypto.subtle.exportKey("spki",o));e.publicKey=o;try{const t=yield n({public_key:l,hints:i});if("error"===t.type)throw new le(t);if("tokens"!==t.type)throw new Error(`Unexpected response type from token endpoint: ${t.type}`);return e.accessToken=t.accessToken,e.accessTokenExpiration=new Date(t.accessTokenExpiration),e.refreshToken=t.refreshToken,t.refreshTokenExpiration&&(e.refreshTokenExpiration=new Date(t.refreshTokenExpiration)),e.userId=t.claims.sub,e.email=t.claims.email,e.name=t.claims.name,e.claims=t.claims,e.license={type:t.userType,status:t.claims.license||"ok"},e.data=t.data,null!=t.evalDaysLeft&&(e.license.evalDaysLeft=t.evalDaysLeft),null!=t.userValidUntil&&(e.license.validUntil=new Date(t.userValidUntil)),t.alerts&&t.alerts.length>0&&(yield ce(r,{type:"message-alert",title:"Authentication Alert",fields:{},alerts:t.alerts})),e}catch(e){if(e instanceof le)throw yield ae(r,e.title,{type:"error",messageCode:e.messageCode,message:e.message,messageParams:{}}),e;let n="We're having a problem authenticating right now.";if(e instanceof TypeError){n=void 0!==typeof navigator&&!navigator.onLine?"You seem to be offline. Please connect to the internet and try again.":t.debug||"undefined"!=typeof location&&("localhost"===location.hostname||"127.0.0.1"===location.hostname)?`Could not connect to server. Please verify that your origin '${location.origin}' is whitelisted using \`npx dexie-cloud whitelist\``:"Could not connect to server. Please verify the connection.",yield ae(r,"Authentication Failed",{type:"error",messageCode:"GENERIC_ERROR",message:n,messageParams:{}}).catch((()=>{}))}throw e}}))}(n,r,i,o)}))}function pe(e,t){return s(this,void 0,void 0,(function*(){if(!t.refreshToken)throw new Error("Cannot refresh token - refresh token is missing.");if(!t.nonExportablePrivateKey)throw new Error("login.nonExportablePrivateKey is missing - cannot sign refresh token without a private key.");const n=Date.now(),r="RSASSA-PKCS1-v1_5",s=(new TextEncoder).encode(t.refreshToken+n),i=yield crypto.subtle.sign(r,t.nonExportablePrivateKey,s),o=oe(i),l={grant_type:"refresh_token",refresh_token:t.refreshToken,scopes:["ACCESS_DB"],signature:o,signing_algorithm:r,time_stamp:n},c=yield fetch(`${e}/token`,{body:JSON.stringify(l),method:"post",headers:{"Content-Type":"application/json"},mode:"cors"});if(200!==c.status)throw new Error(`RefreshToken: Status ${c.status} from ${e}/token`);const a=yield c.json();if("error"===a.type)throw new le(a);return t.accessToken=a.accessToken,t.accessTokenExpiration=a.accessTokenExpiration?new Date(a.accessTokenExpiration):void 0,t.claims=a.claims,t.license={type:a.userType,status:a.claims.license||"ok"},null!=a.evalDaysLeft&&(t.license.evalDaysLeft=a.evalDaysLeft),null!=a.userValidUntil&&(t.license.validUntil=new Date(a.userValidUntil)),a.data&&(t.data=a.data),t}))}const ge=new WeakMap;class ye{constructor(e,t){ge.set(this,e),Object.assign(this,t)}static load(e,t){return e.table("$logins").get(t).then((n=>new ye(e,n||{userId:t,claims:{sub:t},lastLogin:new Date(0)})))}save(){return s(this,void 0,void 0,(function*(){ge.get(this).table("$logins").put(this)}))}}const me={userId:"unauthorized",name:"Unauthorized",claims:{sub:"unauthorized"},lastLogin:new Date(0)};try{Object.freeze(me),Object.freeze(me.claims)}catch(e){}function ve(e,t){return n.firstValueFrom(n.from(e).pipe(n.filter(t)))}function be(e){return s(this,void 0,void 0,(function*(){const t=yield we(e);if(t){if(!(yield function(e,t,n){return s(this,void 0,void 0,(function*(){const r=[{type:"warning",messageCode:"LOGOUT_CONFIRMATION",message:"{numUnsyncedChanges} unsynced changes will get lost!\n Logout anyway?",messageParams:{currentUserId:t,numUnsyncedChanges:n.toString()}}];return yield ce(e,{type:"logout-confirmation",title:"Confirm Logout",alerts:r,fields:{},submitLabel:"Confirm logout",cancelLabel:"Cancel"}).then((()=>!0)).catch((()=>!1))}))}(e.cloud.userInteraction,e.cloud.currentUserId,t)))throw new Error("User cancelled logout due to unsynced changes");yield we(e,{deleteUnsyncedData:!0})}}))}function we(e){return s(this,arguments,void 0,(function*(e,{deleteUnsyncedData:t=!1}={}){const[n,r]=yield e.dx.transaction("rw",e.dx.tables,(n=>s(this,void 0,void 0,(function*(){const r=n.idbtrans;r.disableChangeTracking=!0,r.disableAccessControl=!0;const s=n.storeNames.filter((e=>e.endsWith("_mutations"))),i=(yield Promise.all(s.map((e=>n.table(e).count())))).reduce(((e,t)=>e+t),0);if(i>0&&!t)return[i,!1];e.$syncState.delete("syncState");for(const t of e.dx.tables)"$jobs"!==t.name&&"$syncState"!==t.name&&t.clear();return[i,!0]}))));return r&&(yield ve(e.cloud.currentUser,(e=>e.userId===me.userId)),yield e.cloud.sync({purpose:"pull",wait:!0})),n}))}class _e extends Error{constructor(e,t){super(t||`${e.status} ${e.statusText}`),this.httpStatus=e.status}get name(){return"HttpError"}}function ke(e,...t){globalThis.console[e](...t)}function Se(e,t){return s(this,void 0,void 0,(function*(){var n;const r=yield e.getCurrentUser(),i=r.userId;if(r.isLoggedIn&&(!t||!t.email&&!t.userId)){if("ok"===((null===(n=r.license)||void 0===n?void 0:n.status)||"ok")&&r.accessToken&&(!r.accessTokenExpiration||r.accessTokenExpiration.getTime()>Date.now()))return!1;if(r.refreshToken&&(!r.refreshTokenExpiration||r.refreshTokenExpiration.getTime()>Date.now()))return yield he(e),!1}const o=new ye(e,{claims:{},lastLogin:new Date(0)});return yield fe(e.cloud.options.databaseUrl,o,e.cloud.options.fetchTokens||function(e){const{userInteraction:t}=e.cloud;return function(n){return s(this,arguments,void 0,(function*({public_key:n,hints:r}){var s;let i;const o=null===(s=e.cloud.options)||void 0===s?void 0:s.databaseUrl;if(!o)throw new Error("No database URL given.");if("demo"===(null==r?void 0:r.grant_type))i={demo_user:yield ue(t,"Enter a demo user email",(null==r?void 0:r.email)||(null==r?void 0:r.userId)),grant_type:"demo",scopes:["ACCESS_DB"],public_key:n};else if((null==r?void 0:r.otpId)&&r.otp)i={grant_type:"otp",otp_id:r.otpId,otp:r.otp,scopes:["ACCESS_DB"],public_key:n};else{const e=yield ue(t,"Enter email address",null==r?void 0:r.email);i=/@demo.local$/.test(e)?{demo_user:e,grant_type:"demo",scopes:["ACCESS_DB"],public_key:n}:{email:e,grant_type:"otp",scopes:["ACCESS_DB"]}}const l=yield fetch(`${o}/token`,{body:JSON.stringify(i),method:"post",headers:{"Content-Type":"application/json",mode:"cors"}});if(200!==l.status){const e=yield l.text();throw yield ae(t,"Token request failed",{type:"error",messageCode:"GENERIC_ERROR",message:e,messageParams:{}}).catch((()=>{})),new _e(l,e)}const c=yield l.json();if("tokens"===c.type||"error"===c.type)return c;if("otp"===i.grant_type&&"email"in i){if("otp-sent"!==c.type)throw new Error(`Unexpected response from ${o}/token`);const e=yield de(t,i.email),r=Object.assign(Object.assign({},i),{otp:e||"",otp_id:c.otp_id,public_key:n});let s=yield fetch(`${o}/token`,{body:JSON.stringify(r),method:"post",headers:{"Content-Type":"application/json"},mode:"cors"});for(;401===s.status;){const e=yield s.text();r.otp=yield de(t,i.email,{type:"error",messageCode:"INVALID_OTP",message:e,messageParams:{}}),s=yield fetch(`${o}/token`,{body:JSON.stringify(r),method:"post",headers:{"Content-Type":"application/json"},mode:"cors"})}if(200!==s.status){const e=yield s.text();throw new _e(s,e)}return yield s.json()}throw new Error(`Unexpected response from ${o}/token`)}))}}(e),e.cloud.userInteraction,t),i!==me.userId&&o.userId!==i&&(yield be(e)),yield function(e,t){return s(this,void 0,void 0,(function*(){const n=e.table("$logins");yield e.transaction("rw",n,(e=>s(this,void 0,void 0,(function*(){const e=yield n.toArray();yield Promise.all(e.filter((e=>e.userId!==t.userId&&e.isLoggedIn)).map((e=>(e.isLoggedIn=!1,n.put(e))))),t.isLoggedIn=!0,t.lastLogin=new Date;try{yield t.save()}catch(e){try{"DataCloneError"===e.name&&(ke("debug","Login context property names:",Object.keys(t)),ke("debug","Login context property names:",Object.keys(t)),ke("debug","Login context:",t),ke("debug","Login context JSON:",JSON.stringify(t)))}catch(e){}throw e}})))),yield ve(e.cloud.currentUser,(e=>e.userId===t.userId))}))}(e,o),ne(e,"pull"),o.userId!==i}))}const Ee={},xe="undefined"!=typeof self&&self.document&&"undefined"!=typeof navigator&&navigator.serviceWorker;xe&&xe.ready.then((e=>Ee.registration=e)),"undefined"!=typeof self&&"clients"in self&&!self.document&&addEventListener("message",(e=>{var t,n;(null===(n=null===(t=e.data)||void 0===t?void 0:t.type)||void 0===n?void 0:n.startsWith("sw-broadcast-"))&&[...self.clients.matchAll({includeUncontrolled:!0})].forEach((t=>{var n;return t.id!==(null===(n=e.source)||void 0===n?void 0:n.id)&&t.postMessage(e.data)}))}));class Ce{constructor(e){this.name=e}subscribe(e){if(!xe)return()=>{};const t=t=>{var n;(null===(n=t.data)||void 0===n?void 0:n.type)===`sw-broadcast-${this.name}`&&e(t.data.message)};return xe.addEventListener("message",t),()=>xe.removeEventListener("message",t)}postMessage(e){var t;"object"==typeof self.clients?[...self.clients.matchAll({includeUncontrolled:!0})].forEach((t=>t.postMessage({type:`sw-broadcast-${this.name}`,message:e}))):Ee.registration&&(null===(t=Ee.registration.active)||void 0===t||t.postMessage({type:`sw-broadcast-${this.name}`,message:e}))}}const Ie=globalThis["lbc-events"]||(globalThis["lbc-events"]=new Map);class Ae extends n.Observable{constructor(e){const t="undefined"==typeof BroadcastChannel?new Ce(e):new BroadcastChannel(e);super((n=>{function r(e){n.next(e.detail)}function s(e){n.next(e.data)}let i;!function(e,t){Ie.has(e)?Ie.get(e).push(t):Ie.set(e,[t])}(`lbc-${e}`,r);try{t instanceof Ce?i=t.subscribe((e=>n.next(e))):t.addEventListener("message",s)}catch(e){}return()=>{!function(e,t){const n=Ie.get(e);if(n){const e=n.indexOf(t);-1!==e&&n.splice(e,1)}}(`lbc-${e}`,r),t instanceof Ce?i():t.removeEventListener("message",s)}})),this.name=e,this.bc=t}next(e){this.bc.postMessage(e);!function(e){const t=Ie.get(e.type);t&&t.forEach((t=>{try{t(e)}catch(e){}}))}(new CustomEvent(`lbc-${this.name}`,{detail:e}))}}function De(e){return s(this,arguments,void 0,(function*({realms:e,inviteRealms:t}){const n=JSON.stringify([...e.map((e=>({realmId:e,accepted:!0}))),...t.map((e=>({realmId:e,accepted:!1})))].sort(((e,t)=>e.realmId<t.realmId?-1:e.realmId>t.realmId?1:0))),r=(new TextEncoder).encode(n),s=yield crypto.subtle.digest("SHA-1",r);return oe(s)}))}function Oe(e){return Object.entries(e.cloud.schema||{}).filter((([,{markedForSync:e}])=>e)).map((([t])=>e.tables.filter((({name:e})=>e===t))[0])).filter((e=>e))}function Te(e){return`$${e}_mutations`}function Ue(e){var t;const n=null===(t=/^\$(.*)_mutations$/.exec(e))||void 0===t?void 0:t[1];if(!n)throw new Error(`Given mutationTable ${e} is not correct`);return n}const je=[].concat;function Le(e){return je.apply([],e)}function Pe(e,t){return s(this,arguments,void 0,(function*(e,t,{since:n={},limit:r=1/0}={}){const i=Le(yield Promise.all(e.map((e=>s(this,void 0,void 0,(function*(){const t=Ue(e.name),s=n[t];let i=s?e.where("rev").above(s):e;r<1/0&&(i=i.limit(r));return(yield i.toArray()).map((e=>({table:t,mut:e})))})))))).sort(((e,t)=>e.mut.txid===t.mut.txid?e.mut.opNo-t.mut.opNo:e.mut.ts-t.mut.ts)),o=[];let l=null,c=null;for(const{table:e,mut:t}of i)l&&l.table===e&&c===t.txid?l.muts.push(t):(l={table:e,muts:[t]},c=t.txid,o.push(l));return o}))}function Re(e){const t=new Uint8Array(e);if("undefined"!=typeof crypto)crypto.getRandomValues(t);else for(let n=0;n<e;n++)t[n]=Math.floor(256*Math.random());if("undefined"!=typeof Buffer&&Buffer.from)return Buffer.from(t).toString("base64");if("undefined"!=typeof btoa)return btoa(String.fromCharCode.apply(null,t));throw new Error("No btoa or Buffer available")}const{toString:Me}={};const $e={replace:function(e){const t=Object.keys(e);let n=null;for(let e=0,r=t.length;e<r;++e)"$"===t[e][0]&&(n=n||[],n.push(t[e]));if(!n)return e;const r={...e};for(const e of n)delete r[e];for(const t of n)r["$"+t]=e[t];return r}};function Ne(...e){const t=e.reduce(((e,t)=>({...e,...t})),e.reduce(((e,t)=>({...t,...e})),{})),n=new WeakMap;return{stringify(e,r,s){const i=JSON.stringify(e,(function(e){const s=this[e],i=function(e){const r=typeof e;switch(typeof e){case"object":case"function":{if(null===e)return null;const r=Object.getPrototypeOf(e);if(!r)return $e;let i=n.get(r);if(void 0!==i)return i;const o=(s=e,Me.call(s).slice(8,-1)),l=Object.entries(t).find((([t,n])=>{var r,s;return null!==(s=null===(r=null==n?void 0:n.test)||void 0===r?void 0:r.call(n,e,o))&&void 0!==s?s:t===o}));return i=null==l?void 0:l[1],i||(i=Array.isArray(e)?null:"function"==typeof e?t.function||null:$e),n.set(r,i),i}default:return t[r]}var s}(s);return i?i.replace(s,r,t):s}),s);return i},parse(e,n){const r=[];return JSON.parse(e,(function(e,s){const i=null==s?void 0:s.$t;if(i){const e=t[i];s=e?e.revive(s,n,t):s}let o=r[r.length-1];if(o&&o[0]===s){s={...s};for(const e of o[1])delete s[e];for(const[e,t]of Object.entries(o[2]))s[e]=t;r.pop()}if(void 0===s||"$"===e[0]&&"$t"!==e){let t,n;o=r[r.length-1],o&&o[0]===this?(t=o[1],n=o[2]):r.push([this,t=[],n={}]),"$"===e[0]&&"$t"!==e?(t.push(e),n[e.substr(1)]=s):n[e]=void 0}return s}))}}}const Be={Blob:{test:(e,t)=>"Blob"===t,replace:(e,t)=>{const n=t.length;return t.push(e),{$t:"Blob",mimeType:e.type,i:n}},revive:({i:e,mimeType:t},n)=>new Blob([n[e]],{type:t})}};var Fe={number:{replace:e=>{switch(!0){case isNaN(e):return{$t:"number",v:"NaN"};case e===1/0:return{$t:"number",v:"Infinity"};case e===-1/0:return{$t:"number",v:"-Infinity"};default:return e}},revive:({v:e})=>Number(e)}};const We={bigint:{replace:e=>({$t:"bigint",v:""+e}),revive:e=>BigInt(e.v)}};var Ve={Date:{replace:e=>({$t:"Date",v:isNaN(e.getTime())?"NaN":e.toISOString()}),revive:({v:e})=>new Date("NaN"===e?NaN:Date.parse(e))}},Ke={Set:{replace:e=>({$t:"Set",v:Array.from(e.entries())}),revive:({v:e})=>new Set(e)}},He={Map:{replace:e=>({$t:"Map",v:Array.from(e.entries())}),revive:({v:e})=>new Map(e)}};const Je="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof global?global:void 0;var ze=["Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","DataView","BigInt64Array","BigUint64Array"].reduce(((e,t)=>({...e,[t]:{replace:(e,n,r)=>({$t:t,v:r.ArrayBuffer.replace(0===e.byteOffset&&e.byteLength===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),n,r).v}),revive:({v:e},n,r)=>{const s=Je[t];return s&&new s(r.ArrayBuffer.revive({v:e},n,r))}}})),{});function qe(e){return function(e){for(var t="",n=0,r=e.length;n<r;n++)t+=Qe[e[n]];return t}(oe(e))}function Ye(e){return ie(function(e){if("string"!=typeof e)throw new Error("invalid decoder input: "+e);for(var t="",n=0,r=e.length;n<r;n++)t+=Ge[e[n]];return t}(e))}const Ge={"-":"=",0:"A",1:"B",2:"C",3:"D",4:"E",5:"F",6:"G",7:"H",8:"I",9:"J",A:"K",B:"L",C:"M",D:"N",E:"O",F:"P",G:"Q",H:"R",I:"S",J:"T",K:"U",L:"V",M:"W",N:"X",O:"Y",P:"Z",Q:"a",R:"b",S:"c",T:"d",U:"e",V:"f",W:"g",X:"h",Y:"i",Z:"j",_:"k",a:"l",b:"m",c:"n",d:"o",e:"p",f:"q",g:"r",h:"s",i:"t",j:"u",k:"v",l:"w",m:"x",n:"y",o:"z",p:"0",q:"1",r:"2",s:"3",t:"4",u:"5",v:"6",w:"7",x:"8",y:"9",z:"+","|":"/"},Qe={};for(const e of Object.keys(Ge))Qe[Ge[e]]=e;var Xe={ArrayBuffer:{replace:e=>({$t:"ArrayBuffer",v:qe(e)}),revive:({v:e})=>{const t=Ye(e);return t.buffer.byteLength===t.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}}};class Ze{constructor(e,t){this.buf=e,this.type=t}}function et(e){const t=new XMLHttpRequest;if(t.overrideMimeType("text/plain; charset=x-user-defined"),t.open("GET",URL.createObjectURL(e),!1),t.send(),200!==t.status&&0!==t.status)throw new Error("Bad Blob access: "+t.status);return t.responseText}function tt(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t[n]=e.charCodeAt(n);return t.buffer}var nt={Blob:{test:(e,t)=>"Blob"===t||e instanceof Ze,replace:e=>({$t:"Blob",v:oe(e instanceof Ze?e.buf:tt(et(e))),type:e.type}),revive:({type:e,v:t})=>{const n=ie(t);return void 0!==typeof Blob?new Blob([n]):new Ze(n.buffer,e)}}};const rt={...Fe,...We,...Ve,...Ke,...He,...ze,...Xe,...nt};function st(e){return new Promise(((t,n)=>{const r=new FileReader;r.onabort=e=>n(new Error("file read aborted")),r.onerror=e=>n(e.target.error),r.onload=e=>t(e.target.result),r.readAsArrayBuffer(e)}))}var it={undefined:{replace:()=>({$t:"undefined"}),revive:()=>{}}},ot={File:{test:(e,t)=>"File"===t,replace:e=>({$t:"File",v:oe(tt(et(e))),type:e.type,name:e.name,lastModified:new Date(e.lastModified).toISOString()}),revive:({type:e,v:t,name:n,lastModified:r})=>{const s=ie(t);return new File([s],n,{type:e,lastModified:new Date(r).getTime()})}}};const lt="function"==typeof BigInt&&"bigint"==typeof BigInt(0);class ct{toString(){return this.v}constructor(e){this.v=e}}const at=lt?{}:{bigint:{test:e=>e instanceof ct,replace:e=>Object.assign({$t:"bigint"},e),revive:({v:e})=>new ct(e)}},ut=Object.assign(Object.assign(Object.assign(Object.assign({},it),at),ot),{PropModification:{test:e=>e instanceof t.PropModification,replace:e=>Object.assign({$t:"PropModification"},e["@@propmod"]),revive:e=>{var n=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(r=Object.getOwnPropertySymbols(e);s<r.length;s++)t.indexOf(r[s])<0&&Object.prototype.propertyIsEnumerable.call(e,r[s])&&(n[r[s]]=e[r[s]])}return n}(e,["$t"]);return new t.PropModification(n)}}}),dt=Ne(rt,ut),ht=function(...e){const t=Ne(rt,Be,...e);return{toBinary(e){const[t,n]=this.stringify(e),r=new ArrayBuffer(4);return new DataView(r).setUint32(0,t.size),new Blob([r,t,n])},stringify(e){const n=[],r=t.stringify(e,n),s=new Blob(n.map((e=>{const t=new ArrayBuffer(4);return new DataView(t).setUint32(0,"byteLength"in e?e.byteLength:e.size),new Blob([t,e])})));return[s,r]},async parse(e,n){let r=0;const s=[],i=await st(n),o=new DataView(i);for(;r<i.byteLength;){const e=o.getUint32(r);r+=4;const t=i.slice(r,r+e);r+=e,s.push(t)}return t.parse(e,s)},async fromBinary(e){const t=new DataView(await st(e.slice(0,4))).getUint32(0),n=e.slice(4,t+4),r=await function(e){return new Promise(((t,n)=>{const r=new FileReader;r.onabort=e=>n(new Error("file read aborted")),r.onerror=e=>n(e.target.error),r.onload=e=>t(e.target.result),r.readAsText(e)}))}(e.slice(t+4));return await this.parse(r,n)}}}(ut);function ft(e,n,r){const s=[];for(let i of r){const{table:r,muts:o}=i,l=e.tables.find((e=>e.name===r));if(!l)throw new Error(`Internal error: table ${r} not found in DBCore schema`);const{primaryKey:c}=l;let a=i;o.forEach(((e,r)=>{const s=!c.outbound&&("upsert"===e.type||"insert"===e.type);e.keys.forEach(((e,o)=>{if(Array.isArray(e)){a===i&&(a=pt(i,s));const t=a.muts[r],n=JSON.stringify(e);t.keys[o]=n}else if("#"===e[0]){a===i&&(a=pt(i,s));const l=a.muts[r];if(!n.isLoggedIn)throw new Error("Internal error: Cannot sync private IDs before authenticated");const u=`${e}:${n.userId}`;l.keys[o]=u,s&&t.setByKeyPath(l.values[o],c.keyPath,u)}}))})),s.push(a)}return s}function pt(e,t){return Object.assign(Object.assign({},e),{muts:t?e.muts.map((e=>"insert"!==e.type&&"upsert"!==e.type||!e.values?Object.assign(Object.assign({},e),{keys:e.keys.slice()}):Object.assign(Object.assign({},e),{keys:e.keys.slice(),values:e.values.slice()}))):e.muts.map((e=>Object.assign(Object.assign({},e),{keys:e.keys.slice()})))})}let gt=new WeakMap;function yt(e){return s(this,void 0,void 0,(function*(){var t,n;const r=(null!==(n=null===(t=gt.get(e))||void 0===t?void 0:t.getTime())&&void 0!==n?n:0)-Date.now();r>0&&(yield new Promise((e=>setTimeout(e,r))))}))}function mt(e,t,n,r,i,o,l,c,a){return s(this,void 0,void 0,(function*(){const s={Accept:"application/json, application/x-bison, application/x-bison-stream","Content-Type":"application/tson"},u=yield he(i),d=null==u?void 0:u.accessToken;d&&(s.Authorization=`Bearer ${d}`);const h={v:2,dbID:null==n?void 0:n.remoteDbId,clientIdentity:c,schema:l||{},lastPull:n?{serverRevision:n.serverRevision,yServerRevision:n.yServerRevision,realms:n.realms,inviteRealms:n.inviteRealms}:void 0,baseRevs:r,changes:ft(i.dx.core.schema,a,e),y:t,dxcv:i.cloud.version};i.syncStateChangedEvent.next({phase:"pushing"});const f=dt.stringify(h),p=yield fetch(`${o}/sync`,{method:"post",headers:s,credentials:"include",body:f});if(i.syncStateChangedEvent.next({phase:"pulling"}),function(e,t){const n=t.headers.get("Ratelimit-Limit"),r=t.headers.get("Ratelimit-Remaining"),s=t.headers.get("Ratelimit-Reset");if(n&&r&&s){const t=Number(n),i=Math.max(0,Number(r)),o=Number(s);if(i<t/2){const t=Math.ceil(o/(i+1));gt.set(e,new Date(Date.now()+1e3*t))}else gt.delete(e)}}(i,p),!p.ok)throw new _e(p);if("application/x-bison"===p.headers.get("content-type"))return ht.fromBinary(yield p.blob());{const e=yield p.text();return dt.parse(e)}}))}function vt(e){if(null==e?void 0:e.cancelled)throw new t.AbortError("Operation was cancelled")}let bt=!1;function wt(e,t,n,r){return s(this,void 0,void 0,(function*(){yield e.$baseRevs.bulkPut(Object.keys(t).filter((e=>t[e].markedForSync)).map((e=>({tableName:e,clientRev:(n[e]||0)+1,serverRev:r})))),yield e.$baseRevs.where("tableName").noneOf(Object.keys(t).filter((e=>t[e].markedForSync))).delete()}))}function _t(e,t={}){for(const{table:n,muts:r}of e){const e=r.length>0?r[r.length-1].rev:null;t[n]=e||t[n]||0}return t}function kt(e,n,r){return s(this,void 0,void 0,(function*(){const s=yield e.bulkGet(n),i=[],o=[];n.forEach(((n,l)=>{const c=s[l];if(c){for(const[s,i]of Object.entries(r[l]))if(s===e.schema.primKey.keyPath){if(0!==t.cmp(i,n))throw new Error("Cannot change primary key")}else t.setByKeyPath(c,s,i);i.push(n),o.push(c)}})),yield null==e.schema.primKey.keyPath?e.bulkPut(o,i):e.bulkPut(o)}))}function St(e,n){return s(this,void 0,void 0,(function*(){for(const{table:r,muts:s}of e){if(!n.dx._allTables[r])continue;const e=n.table(r),{primaryKey:i}=e.core.schema,o=e=>{switch(e[0]){case"[":if(e.endsWith("]"))try{return JSON.parse(e)}catch(e){}return e;case"#":return e.endsWith(":"+n.cloud.currentUserId)?e.substr(0,e.length-n.cloud.currentUserId.length-1):e;default:return e}};for(const n of s){const r=n.keys.map(o);switch(n.type){case"insert":i.outbound?yield e.bulkAdd(n.values,r):(r.forEach(((e,r)=>{t.setByKeyPath(n.values[r],i.keyPath,e)})),yield e.bulkAdd(n.values));break;case"upsert":i.outbound?yield e.bulkPut(n.values,r):(r.forEach(((e,r)=>{t.setByKeyPath(n.values[r],i.keyPath,e)})),yield e.bulkPut(n.values));break;case"modify":1===r.length?yield e.update(r[0],n.changeSpec):yield e.where(":id").anyOf(r).modify(n.changeSpec);break;case"update":yield kt(e,r,n.changeSpecs);break;case"delete":yield e.bulkDelete(r)}}}}))}"undefined"!=typeof self&&"undefined"!=typeof navigator&&(bt=navigator.onLine,self.addEventListener("online",(()=>bt=!0)),self.addEventListener("offline",(()=>bt=!1)));const Et="dexie-cloud-syncer";function xt(e,t){return e.where("i").between(t,1/0,!0).toArray()}const Ct=()=>new Map,It=e=>{const t=Ct();return e.forEach(((e,n)=>{t.set(n,e)})),t},At=(e,t,n)=>{let r=e.get(t);return void 0===r&&e.set(t,r=n()),r},Dt=()=>new Set,Ot=e=>e[e.length-1],Tt=(e,t)=>{for(let n=0;n<t.length;n++)e.push(t[n])},Ut=Array.from,jt=Array.isArray;class Lt{constructor(){this._observers=Ct()}on(e,t){return At(this._observers,e,Dt).add(t),t}once(e,t){const n=(...r)=>{this.off(e,n),t(...r)};this.on(e,n)}off(e,t){const n=this._observers.get(e);void 0!==n&&(n.delete(t),0===n.size&&this._observers.delete(e))}emit(e,t){return Ut((this._observers.get(e)||Ct()).values()).forEach((e=>e(...t)))}destroy(){this._observers=Ct()}}const Pt=Math.floor,Rt=Math.abs,Mt=(e,t)=>e<t?e:t,$t=(e,t)=>e>t?e:t,Nt=e=>0!==e?e<0:1/e<0,Bt=64,Ft=128,Wt=127,Vt=Number.MAX_SAFE_INTEGER,Kt=Number.isInteger||(e=>"number"==typeof e&&isFinite(e)&&Pt(e)===e),Ht=/^\s*/g,Jt=/([A-Z])/g,zt=(e,t)=>(e=>e.replace(Ht,""))(e.replace(Jt,(e=>`${t}${(e=>e.toLowerCase())(e)}`))),qt="undefined"!=typeof TextEncoder?new TextEncoder:null,Yt=qt?e=>qt.encode(e):e=>{const t=unescape(encodeURIComponent(e)),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.codePointAt(e);return r};let Gt="undefined"==typeof TextDecoder?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});Gt&&1===Gt.decode(new Uint8Array).length&&(Gt=null);class Qt{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const Xt=()=>new Qt,Zt=e=>{const t=new Uint8Array((e=>{let t=e.cpos;for(let n=0;n<e.bufs.length;n++)t+=e.bufs[n].length;return t})(e));let n=0;for(let r=0;r<e.bufs.length;r++){const s=e.bufs[r];t.set(s,n),n+=s.length}return t.set(new Uint8Array(e.cbuf.buffer,0,e.cpos),n),t},en=(e,t)=>{const n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(2*n),e.cpos=0),e.cbuf[e.cpos++]=t},tn=en,nn=(e,t)=>{for(;t>Wt;)en(e,Ft|Wt&t),t=Pt(t/128);en(e,Wt&t)},rn=(e,t)=>{const n=Nt(t);for(n&&(t=-t),en(e,(t>63?Ft:0)|(n?Bt:0)|63&t),t=Pt(t/64);t>0;)en(e,(t>Wt?Ft:0)|Wt&t),t=Pt(t/128)},sn=new Uint8Array(3e4),on=sn.length/3,ln=qt&&qt.encodeInto?(e,t)=>{if(t.length<on){const n=qt.encodeInto(t,sn).written||0;nn(e,n);for(let t=0;t<n;t++)en(e,sn[t])}else an(e,Yt(t))}:(e,t)=>{const n=unescape(encodeURIComponent(t)),r=n.length;nn(e,r);for(let t=0;t<r;t++)en(e,n.codePointAt(t))},cn=(e,t)=>{const n=e.cbuf.length,r=e.cpos,s=Mt(n-r,t.length),i=t.length-s;e.cbuf.set(t.subarray(0,s),r),e.cpos+=s,i>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array($t(2*n,i)),e.cbuf.set(t.subarray(s)),e.cpos=i)},an=(e,t)=>{nn(e,t.byteLength),cn(e,t)},un=(e,t)=>{((e,t)=>{const n=e.cbuf.length;n-e.cpos<t&&(e.bufs.push(new Uint8Array(e.cbuf.buffer,0,e.cpos)),e.cbuf=new Uint8Array(2*$t(n,t)),e.cpos=0)})(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},dn=new DataView(new ArrayBuffer(4)),hn=(e,t)=>{switch(typeof t){case"string":en(e,119),ln(e,t);break;case"number":Kt(t)&&Rt(t)<=2147483647?(en(e,125),rn(e,t)):(n=t,dn.setFloat32(0,n),dn.getFloat32(0)===n?(en(e,124),((e,t)=>{un(e,4).setFloat32(0,t,!1)})(e,t)):(en(e,123),((e,t)=>{un(e,8).setFloat64(0,t,!1)})(e,t)));break;case"bigint":en(e,122),((e,t)=>{un(e,8).setBigInt64(0,t,!1)})(e,t);break;case"object":if(null===t)en(e,126);else if(jt(t)){en(e,117),nn(e,t.length);for(let n=0;n<t.length;n++)hn(e,t[n])}else if(t instanceof Uint8Array)en(e,116),an(e,t);else{en(e,118);const n=Object.keys(t);nn(e,n.length);for(let r=0;r<n.length;r++){const s=n[r];ln(e,s),hn(e,t[s])}}break;case"boolean":en(e,t?120:121);break;default:en(e,127)}var n};class fn extends Qt{constructor(e){super(),this.w=e,this.s=null,this.count=0}write(e){this.s===e?this.count++:(this.count>0&&nn(this,this.count-1),this.count=1,this.w(this,e),this.s=e)}}const pn=e=>{e.count>0&&(rn(e.encoder,1===e.count?e.s:-e.s),e.count>1&&nn(e.encoder,e.count-2))};class gn{constructor(){this.encoder=new Qt,this.s=0,this.count=0}write(e){this.s===e?this.count++:(pn(this),this.count=1,this.s=e)}toUint8Array(){return pn(this),Zt(this.encoder)}}const yn=e=>{if(e.count>0){const t=2*e.diff+(1===e.count?0:1);rn(e.encoder,t),e.count>1&&nn(e.encoder,e.count-2)}};class mn{constructor(){this.encoder=new Qt,this.s=0,this.count=0,this.diff=0}write(e){this.diff===e-this.s?(this.s=e,this.count++):(yn(this),this.count=1,this.diff=e-this.s,this.s=e)}toUint8Array(){return yn(this),Zt(this.encoder)}}class vn{constructor(){this.sarr=[],this.s="",this.lensE=new gn}write(e){this.s+=e,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(e.length)}toUint8Array(){const e=new Qt;return this.sarr.push(this.s),this.s="",ln(e,this.sarr.join("")),cn(e,this.lensE.toUint8Array()),Zt(e)}}const bn=e=>new Error(e),wn=()=>{throw bn("Method unimplemented")},_n=()=>{throw bn("Unexpected case")},kn=bn("Unexpected end of array"),Sn=bn("Integer out of Range");class En{constructor(e){this.arr=e,this.pos=0}}const xn=e=>new En(e),Cn=e=>((e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n})(e,An(e)),In=e=>e.arr[e.pos++],An=e=>{let t=0,n=1;const r=e.arr.length;for(;e.pos<r;){const r=e.arr[e.pos++];if(t+=(r&Wt)*n,n*=128,r<Ft)return t;if(t>Vt)throw Sn}throw kn},Dn=e=>{let t=e.arr[e.pos++],n=63&t,r=64;const s=(t&Bt)>0?-1:1;if(0==(t&Ft))return s*n;const i=e.arr.length;for(;e.pos<i;){if(t=e.arr[e.pos++],n+=(t&Wt)*r,r*=128,t<Ft)return s*n;if(n>Vt)throw Sn}throw kn},On=Gt?e=>Gt.decode(Cn(e)):e=>{let t=An(e);if(0===t)return"";{let n=String.fromCodePoint(In(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(In(e));else for(;t>0;){const r=t<1e4?t:1e4,s=e.arr.subarray(e.pos,e.pos+r);e.pos+=r,n+=String.fromCodePoint.apply(null,s),t-=r}return decodeURIComponent(escape(n))}},Tn=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},Un=[e=>{},e=>null,Dn,e=>Tn(e,4).getFloat32(0,!1),e=>Tn(e,8).getFloat64(0,!1),e=>Tn(e,8).getBigInt64(0,!1),e=>!1,e=>!0,On,e=>{const t=An(e),n={};for(let r=0;r<t;r++){n[On(e)]=jn(e)}return n},e=>{const t=An(e),n=[];for(let r=0;r<t;r++)n.push(jn(e));return n},Cn],jn=e=>Un[127-In(e)](e);class Ln extends En{constructor(e,t){super(e),this.reader=t,this.s=null,this.count=0}read(){var e;return 0===this.count&&(this.s=this.reader(this),(e=this).pos!==e.arr.length?this.count=An(this)+1:this.count=-1),this.count--,this.s}}class Pn extends En{constructor(e){super(e),this.s=0,this.count=0}read(){if(0===this.count){this.s=Dn(this);const e=Nt(this.s);this.count=1,e&&(this.s=-this.s,this.count=An(this)+2)}return this.count--,this.s}}class Rn extends En{constructor(e){super(e),this.s=0,this.count=0,this.diff=0}read(){if(0===this.count){const e=Dn(this),t=1&e;this.diff=Pt(e/2),this.count=1,t&&(this.count=An(this)+2)}return this.s+=this.diff,this.count--,this.s}}class Mn{constructor(e){this.decoder=new Pn(e),this.str=On(this.decoder),this.spos=0}read(){const e=this.spos+this.decoder.read(),t=this.str.slice(this.spos,e);return this.spos=e,t}}const $n=crypto.getRandomValues.bind(crypto),Nn=()=>$n(new Uint32Array(1))[0],Bn=[1e7]+-1e3+-4e3+-8e3+-1e11,Fn=()=>Bn.replace(/[018]/g,(e=>(e^Nn()&15>>e/4).toString(16))),Wn=e=>new Promise(e);Promise.all.bind(Promise);const Vn=e=>void 0===e?null:e;let Kn=new class{constructor(){this.map=new Map}setItem(e,t){this.map.set(e,t)}getItem(e){return this.map.get(e)}},Hn=!0;try{"undefined"!=typeof localStorage&&localStorage&&(Kn=localStorage,Hn=!1)}catch(Xl){}const Jn=Kn,zn=Object.assign,qn=Object.keys,Yn=e=>qn(e).length,Gn=(e,t)=>e===t||Yn(e)===Yn(t)&&((e,t)=>{for(const n in e)if(!t(e[n],n))return!1;return!0})(e,((e,n)=>(void 0!==e||((e,t)=>Object.prototype.hasOwnProperty.call(e,t))(t,n))&&t[n]===e)),Qn=Object.freeze,Xn=e=>{for(const t in e){const n=e[t];"object"!=typeof n&&"function"!=typeof n||Xn(e[t])}return Qn(e)},Zn=(e,t,n=0)=>{try{for(;n<e.length;n++)e[n](...t)}finally{n<e.length&&Zn(e,t,n+1)}},er="undefined"!=typeof process&&process.release&&/node|io\.js/.test(process.release.name)&&"[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0);let tr;const nr=e=>(()=>{if(void 0===tr)if(er){tr=Ct();const e=process.argv;let t=null;for(let n=0;n<e.length;n++){const r=e[n];"-"===r[0]?(null!==t&&tr.set(t,""),t=r):null!==t&&(tr.set(t,r),t=null)}null!==t&&tr.set(t,"")}else"object"==typeof location?(tr=Ct(),(location.search||"?").slice(1).split("&").forEach((e=>{if(0!==e.length){const[t,n]=e.split("=");tr.set(`--${zt(t,"-")}`,n),tr.set(`-${zt(t,"-")}`,n)}}))):tr=Ct();return tr})().has(e),rr=e=>Vn(er?process.env[e.toUpperCase().replaceAll("-","_")]:Jn.getItem(e)),sr=e=>nr("--"+e)||null!==rr(e);sr("production");var ir;er&&(ir=process.env.FORCE_COLOR,["true","1","2"].includes(ir))||!nr("--no-colors")&&!sr("no-color")&&(!er||process.stdout.isTTY)&&(!er||nr("--color")||null!==rr("COLORTERM")||(rr("TERM")||"").includes("color"));class or{constructor(e,t){this.left=e,this.right=t}}const lr=(e,t)=>new or(e,t);"undefined"!=typeof DOMParser&&new DOMParser;const cr=Symbol,ar=cr(),ur=cr(),dr=cr(),hr=cr(),fr=cr(),pr=cr(),gr=cr(),yr=cr(),mr=cr(),vr=(lr("font-weight","bold"),lr("font-weight","normal"),lr("color","blue"),lr("color","green"),lr("color","grey"),lr("color","red"),lr("color","purple"),lr("color","orange"),lr("color","black"),Dt()),br=e=>({[Symbol.iterator](){return this},next:e}),wr=(e,t)=>br((()=>{const{done:n,value:r}=e.next();return{done:n,value:n?void 0:t(r)}}));class _r{constructor(e,t){this.clock=e,this.len=t}}class kr{constructor(){this.clients=new Map}}const Sr=(e,t,n)=>t.clients.forEach(((t,r)=>{const s=e.doc.store.clients.get(r);if(null!=s){const r=s[s.length-1],i=r.id.clock+r.length;for(let r=0,o=t[r];r<t.length&&o.clock<i;o=t[++r])is(e,s,o.clock,o.len,n)}})),Er=(e,t)=>{const n=e.clients.get(t.client);return void 0!==n&&null!==((e,t)=>{let n=0,r=e.length-1;for(;n<=r;){const s=Pt((n+r)/2),i=e[s],o=i.clock;if(o<=t){if(t<o+i.len)return s;n=s+1}else r=s-1}return null})(n,t.clock)},xr=e=>{e.clients.forEach((e=>{let t,n;for(e.sort(((e,t)=>e.clock-t.clock)),t=1,n=1;t<e.length;t++){const r=e[n-1],s=e[t];r.clock+r.len>=s.clock?r.len=$t(r.len,s.clock+s.len-r.clock):(n<t&&(e[n]=s),n++)}e.length=n}))},Cr=(e,t,n,r)=>{At(e.clients,t,(()=>[])).push(new _r(n,r))},Ir=(e,t)=>{nn(e.restEncoder,t.clients.size),Ut(t.clients.entries()).sort(((e,t)=>t[0]-e[0])).forEach((([t,n])=>{e.resetDsCurVal(),nn(e.restEncoder,t);const r=n.length;nn(e.restEncoder,r);for(let t=0;t<r;t++){const r=n[t];e.writeDsClock(r.clock),e.writeDsLen(r.len)}}))},Ar=(e,t,n)=>{const r=new kr,s=An(e.restDecoder);for(let i=0;i<s;i++){e.resetDsCurVal();const s=An(e.restDecoder),i=An(e.restDecoder),o=n.clients.get(s)||[],l=Xr(n,s);for(let n=0;n<i;n++){const n=e.readDsClock(),i=n+e.readDsLen();if(n<l){l<i&&Cr(r,s,l,i-l);let e=es(o,n),c=o[e];for(!c.deleted&&c.id.clock<n&&(o.splice(e+1,0,Bi(t,c,n-c.id.clock)),e++);e<o.length&&(c=o[e++],c.id.clock<i);)c.deleted||(i<c.id.clock+c.length&&o.splice(e,0,Bi(t,c,i-c.id.clock)),c.delete(t))}else Cr(r,s,n,i-n)}}if(r.clients.size>0){const e=new Rr;return nn(e.restEncoder,0),Ir(e,r),e.toUint8Array()}return null},Dr=Nn;class Or extends Lt{constructor({guid:e=Fn(),collectionid:t=null,gc:n=!0,gcFilter:r=(()=>!0),meta:s=null,autoLoad:i=!1,shouldLoad:o=!0}={}){super(),this.gc=n,this.gcFilter=r,this.clientID=Dr(),this.guid=e,this.collectionid=t,this.share=new Map,this.store=new Gr,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=o,this.autoLoad=i,this.meta=s,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=Wn((e=>{this.on("load",(()=>{this.isLoaded=!0,e(this)}))}));const l=()=>Wn((e=>{const t=n=>{void 0!==n&&!0!==n||(this.off("sync",t),e())};this.on("sync",t)}));this.on("sync",(e=>{!1===e&&this.isSynced&&(this.whenSynced=l()),this.isSynced=void 0===e||!0===e,this.isSynced&&!this.isLoaded&&this.emit("load",[this])})),this.whenSynced=l()}load(){const e=this._item;null===e||this.shouldLoad||ds(e.parent.doc,(e=>{e.subdocsLoaded.add(this)}),null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(Ut(this.subdocs).map((e=>e.guid)))}transact(e,t=null){return ds(this,e,t)}get(e,t=Os){const n=At(this.share,e,(()=>{const e=new t;return e._integrate(this,null),e})),r=n.constructor;if(t!==Os&&r!==t){if(r===Os){const r=new t;r._map=n._map,n._map.forEach((e=>{for(;null!==e;e=e.left)e.parent=r})),r._start=n._start;for(let e=r._start;null!==e;e=e.right)e.parent=r;return r._length=n._length,this.share.set(e,r),r._integrate(this,null),r}throw new Error(`Type with the name ${e} has already been defined with a different constructor`)}return n}getArray(e=""){return this.get(e,qs)}getText(e=""){return this.get(e,hi)}getMap(e=""){return this.get(e,Gs)}getXmlElement(e=""){return this.get(e,gi)}getXmlFragment(e=""){return this.get(e,pi)}toJSON(){const e={};return this.share.forEach(((t,n)=>{e[n]=t.toJSON()})),e}destroy(){this.isDestroyed=!0,Ut(this.subdocs).forEach((e=>e.destroy()));const e=this._item;if(null!==e){this._item=null;const t=e.content;t.doc=new Or({guid:this.guid,...t.opts,shouldLoad:!1}),t.doc._item=e,ds(e.parent.doc,(n=>{const r=t.doc;e.deleted||n.subdocsAdded.add(r),n.subdocsRemoved.add(this)}),null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class Tr{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=An(this.restDecoder),this.dsCurrVal}readDsLen(){const e=An(this.restDecoder)+1;return this.dsCurrVal+=e,e}}class Ur extends Tr{constructor(e){super(e),this.keys=[],An(e),this.keyClockDecoder=new Rn(Cn(e)),this.clientDecoder=new Pn(Cn(e)),this.leftClockDecoder=new Rn(Cn(e)),this.rightClockDecoder=new Rn(Cn(e)),this.infoDecoder=new Ln(Cn(e),In),this.stringDecoder=new Mn(Cn(e)),this.parentInfoDecoder=new Ln(Cn(e),In),this.typeRefDecoder=new Pn(Cn(e)),this.lenDecoder=new Pn(Cn(e))}readLeftID(){return new Hr(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new Hr(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return 1===this.parentInfoDecoder.read()}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return jn(this.restDecoder)}readBuf(){return Cn(this.restDecoder)}readJSON(){return jn(this.restDecoder)}readKey(){const e=this.keyClockDecoder.read();if(e<this.keys.length)return this.keys[e];{const e=this.stringDecoder.read();return this.keys.push(e),e}}}class jr{constructor(){this.restEncoder=Xt()}toUint8Array(){return Zt(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){nn(this.restEncoder,e)}writeDsLen(e){nn(this.restEncoder,e)}}class Lr extends jr{writeLeftID(e){nn(this.restEncoder,e.client),nn(this.restEncoder,e.clock)}writeRightID(e){nn(this.restEncoder,e.client),nn(this.restEncoder,e.clock)}writeClient(e){nn(this.restEncoder,e)}writeInfo(e){tn(this.restEncoder,e)}writeString(e){ln(this.restEncoder,e)}writeParentInfo(e){nn(this.restEncoder,e?1:0)}writeTypeRef(e){nn(this.restEncoder,e)}writeLen(e){nn(this.restEncoder,e)}writeAny(e){hn(this.restEncoder,e)}writeBuf(e){an(this.restEncoder,e)}writeJSON(e){ln(this.restEncoder,JSON.stringify(e))}writeKey(e){ln(this.restEncoder,e)}}class Pr{constructor(){this.restEncoder=Xt(),this.dsCurrVal=0}toUint8Array(){return Zt(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(e){const t=e-this.dsCurrVal;this.dsCurrVal=e,nn(this.restEncoder,t)}writeDsLen(e){0===e&&_n(),nn(this.restEncoder,e-1),this.dsCurrVal+=e}}class Rr extends Pr{constructor(){super(),this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new mn,this.clientEncoder=new gn,this.leftClockEncoder=new mn,this.rightClockEncoder=new mn,this.infoEncoder=new fn(tn),this.stringEncoder=new vn,this.parentInfoEncoder=new fn(tn),this.typeRefEncoder=new gn,this.lenEncoder=new gn}toUint8Array(){const e=Xt();return nn(e,0),an(e,this.keyClockEncoder.toUint8Array()),an(e,this.clientEncoder.toUint8Array()),an(e,this.leftClockEncoder.toUint8Array()),an(e,this.rightClockEncoder.toUint8Array()),an(e,Zt(this.infoEncoder)),an(e,this.stringEncoder.toUint8Array()),an(e,Zt(this.parentInfoEncoder)),an(e,this.typeRefEncoder.toUint8Array()),an(e,this.lenEncoder.toUint8Array()),cn(e,Zt(this.restEncoder)),Zt(e)}writeLeftID(e){this.clientEncoder.write(e.client),this.leftClockEncoder.write(e.clock)}writeRightID(e){this.clientEncoder.write(e.client),this.rightClockEncoder.write(e.clock)}writeClient(e){this.clientEncoder.write(e)}writeInfo(e){this.infoEncoder.write(e)}writeString(e){this.stringEncoder.write(e)}writeParentInfo(e){this.parentInfoEncoder.write(e?1:0)}writeTypeRef(e){this.typeRefEncoder.write(e)}writeLen(e){this.lenEncoder.write(e)}writeAny(e){hn(this.restEncoder,e)}writeBuf(e){an(this.restEncoder,e)}writeJSON(e){hn(this.restEncoder,e)}writeKey(e){const t=this.keyMap.get(e);void 0===t?(this.keyClockEncoder.write(this.keyClock++),this.stringEncoder.write(e)):this.keyClockEncoder.write(t)}}const Mr=(e,t,n)=>{const r=new Map;n.forEach(((e,n)=>{Xr(t,n)>e&&r.set(n,e)})),Qr(t).forEach(((e,t)=>{n.has(t)||r.set(t,0)})),nn(e.restEncoder,r.size),Ut(r.entries()).sort(((e,t)=>t[0]-e[0])).forEach((([n,r])=>{((e,t,n,r)=>{r=$t(r,t[0].id.clock);const s=es(t,r);nn(e.restEncoder,t.length-s),e.writeClient(n),nn(e.restEncoder,r);const i=t[s];i.write(e,r-i.id.clock);for(let n=s+1;n<t.length;n++)t[n].write(e,0)})(e,t.clients.get(n),n,r)}))},$r=(e,t,n,r=new Ur(e))=>ds(t,(e=>{e.local=!1;let t=!1;const n=e.doc,s=n.store,i=((e,t)=>{const n=Ct(),r=An(e.restDecoder);for(let s=0;s<r;s++){const r=An(e.restDecoder),s=new Array(r),i=e.readClient();let o=An(e.restDecoder);n.set(i,{i:0,refs:s});for(let n=0;n<r;n++){const r=e.readInfo();switch(31&r){case 0:{const t=e.readLen();s[n]=new wi(zr(i,o),t),o+=t;break}case 10:{const t=An(e.restDecoder);s[n]=new Ki(zr(i,o),t),o+=t;break}default:{const l=0==(192&r),c=new Fi(zr(i,o),null,(r&Ft)===Ft?e.readLeftID():null,null,(r&Bt)===Bt?e.readRightID():null,l?e.readParentInfo()?t.get(e.readString()):e.readLeftID():null,l&&32==(32&r)?e.readString():null,Wi(e,r));s[n]=c,o+=c.length}}}}return n})(r,n),o=((e,t,n)=>{const r=[];let s=Ut(n.keys()).sort(((e,t)=>e-t));if(0===s.length)return null;const i=()=>{if(0===s.length)return null;let e=n.get(s[s.length-1]);for(;e.refs.length===e.i;){if(s.pop(),!(s.length>0))return null;e=n.get(s[s.length-1])}return e};let o=i();if(null===o)return null;const l=new Gr,c=new Map,a=(e,t)=>{const n=c.get(e);(null==n||n>t)&&c.set(e,t)};let u=o.refs[o.i++];const d=new Map,h=()=>{for(const e of r){const t=e.id.client,r=n.get(t);r?(r.i--,l.clients.set(t,r.refs.slice(r.i)),n.delete(t),r.i=0,r.refs=[]):l.clients.set(t,[e]),s=s.filter((e=>e!==t))}r.length=0};for(;;){if(u.constructor!==Ki){const s=At(d,u.id.client,(()=>Xr(t,u.id.client)))-u.id.clock;if(s<0)r.push(u),a(u.id.client,u.id.clock-1),h();else{const i=u.getMissing(e,t);if(null!==i){r.push(u);const e=n.get(i)||{refs:[],i:0};if(e.refs.length!==e.i){u=e.refs[e.i++];continue}a(i,Xr(t,i)),h()}else(0===s||s<u.length)&&(u.integrate(e,s),d.set(u.id.client,u.id.clock+u.length))}}if(r.length>0)u=r.pop();else if(null!==o&&o.i<o.refs.length)u=o.refs[o.i++];else{if(o=i(),null===o)break;u=o.refs[o.i++]}}if(l.clients.size>0){const e=new Rr;return Mr(e,l,new Map),nn(e.restEncoder,0),{missing:c,update:e.toUint8Array()}}return null})(e,s,i),l=s.pendingStructs;if(l){for(const[e,n]of l.missing)if(n<Xr(s,e)){t=!0;break}if(o){for(const[e,t]of o.missing){const n=l.missing.get(e);(null==n||n>t)&&l.missing.set(e,t)}l.update=ys([l.update,o.update])}}else s.pendingStructs=o;const c=Ar(r,e,s);if(s.pendingDs){const t=new Ur(xn(s.pendingDs));An(t.restDecoder);const n=Ar(t,e,s);s.pendingDs=c&&n?ys([c,n]):c||n}else s.pendingDs=c;if(t){const t=s.pendingStructs.update;s.pendingStructs=null,Nr(e.doc,t)}}),n,!1),Nr=(e,t,n,r=Ur)=>{const s=xn(t);$r(s,e,n,new r(s))};class Br{constructor(){this.l=[]}}const Fr=()=>new Br,Wr=(e,t)=>e.l.push(t),Vr=(e,t)=>{const n=e.l;n.length;e.l=n.filter((e=>t!==e)),e.l.length},Kr=(e,t,n)=>Zn(e.l,[t,n]);class Hr{constructor(e,t){this.client=e,this.clock=t}}const Jr=(e,t)=>e===t||null!==e&&null!==t&&e.client===t.client&&e.clock===t.clock,zr=(e,t)=>new Hr(e,t),qr=(e,t)=>void 0===t?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!Er(t.ds,e.id),Yr=(e,t)=>{const n=At(e.meta,Yr,Dt),r=e.doc.store;n.has(t)||(t.sv.forEach(((t,n)=>{t<Xr(r,n)&&rs(e,zr(n,t))})),Sr(e,t.ds,(e=>{})),n.add(t))};class Gr{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const Qr=e=>{const t=new Map;return e.clients.forEach(((e,n)=>{const r=e[e.length-1];t.set(n,r.id.clock+r.length)})),t},Xr=(e,t)=>{const n=e.clients.get(t);if(void 0===n)return 0;const r=n[n.length-1];return r.id.clock+r.length},Zr=(e,t)=>{let n=e.clients.get(t.id.client);if(void 0===n)n=[],e.clients.set(t.id.client,n);else{const e=n[n.length-1];if(e.id.clock+e.length!==t.id.clock)throw _n()}n.push(t)},es=(e,t)=>{let n=0,r=e.length-1,s=e[r],i=s.id.clock;if(i===t)return r;let o=Pt(t/(i+s.length-1)*r);for(;n<=r;){if(s=e[o],i=s.id.clock,i<=t){if(t<i+s.length)return o;n=o+1}else r=o-1;o=Pt((n+r)/2)}throw _n()},ts=(e,t)=>{const n=e.clients.get(t.client);return n[es(n,t.clock)]},ns=(e,t,n)=>{const r=es(t,n),s=t[r];return s.id.clock<n&&s instanceof Fi?(t.splice(r+1,0,Bi(e,s,n-s.id.clock)),r+1):r},rs=(e,t)=>{const n=e.doc.store.clients.get(t.client);return n[ns(e,n,t.clock)]},ss=(e,t,n)=>{const r=t.clients.get(n.client),s=es(r,n.clock),i=r[s];return n.clock!==i.id.clock+i.length-1&&i.constructor!==wi&&r.splice(s+1,0,Bi(e,i,n.clock-i.id.clock+1)),i},is=(e,t,n,r,s)=>{if(0===r)return;const i=n+r;let o,l=ns(e,t,n);do{o=t[l++],i<o.id.clock+o.length&&ns(e,t,i),s(o)}while(l<t.length&&t[l].id.clock<i)};class os{constructor(e,t,n){this.doc=e,this.deleteSet=new kr,this.beforeState=Qr(e.store),this.afterState=new Map,this.changed=new Map,this.changedParentTypes=new Map,this._mergeStructs=[],this.origin=t,this.meta=new Map,this.local=n,this.subdocsAdded=new Set,this.subdocsRemoved=new Set,this.subdocsLoaded=new Set,this._needFormattingCleanup=!1}}const ls=(e,t)=>!(0===t.deleteSet.clients.size&&!((e,t)=>{for(const[n,r]of e)if(t(r,n))return!0;return!1})(t.afterState,((e,n)=>t.beforeState.get(n)!==e)))&&(xr(t.deleteSet),((e,t)=>{Mr(e,t.doc.store,t.beforeState)})(e,t),Ir(e,t.deleteSet),!0),cs=(e,t,n)=>{const r=t._item;(null===r||r.id.clock<(e.beforeState.get(r.id.client)||0)&&!r.deleted)&&At(e.changed,t,Dt).add(n)},as=(e,t)=>{let n=e[t],r=e[t-1],s=t;for(;s>0&&(r.deleted===n.deleted&&r.constructor===n.constructor&&r.mergeWith(n));n=r,r=e[--s-1])n instanceof Fi&&null!==n.parentSub&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,r);const i=t-s;return i&&e.splice(t+1-i,i),i},us=(e,t)=>{if(t<e.length){const n=e[t],r=n.doc,s=r.store,i=n.deleteSet,o=n._mergeStructs;try{xr(i),n.afterState=Qr(n.doc.store),r.emit("beforeObserverCalls",[n,r]);const e=[];n.changed.forEach(((t,r)=>e.push((()=>{null!==r._item&&r._item.deleted||r._callObserver(n,t)})))),e.push((()=>{n.changedParentTypes.forEach(((e,t)=>{t._dEH.l.length>0&&(null===t._item||!t._item.deleted)&&((e=e.filter((e=>null===e.target._item||!e.target._item.deleted))).forEach((e=>{e.currentTarget=t,e._path=null})),e.sort(((e,t)=>e.path.length-t.path.length)),Kr(t._dEH,e,n))}))})),e.push((()=>r.emit("afterTransaction",[n,r]))),Zn(e,[]),n._needFormattingCleanup&&ai(n)}finally{r.gc&&((e,t,n)=>{for(const[r,s]of e.clients.entries()){const e=t.clients.get(r);for(let r=s.length-1;r>=0;r--){const i=s[r],o=i.clock+i.len;for(let r=es(e,i.clock),s=e[r];r<e.length&&s.id.clock<o;s=e[++r]){const s=e[r];if(i.clock+i.len<=s.id.clock)break;s instanceof Fi&&s.deleted&&!s.keep&&n(s)&&s.gc(t,!1)}}}})(i,s,r.gcFilter),((e,t)=>{e.clients.forEach(((e,n)=>{const r=t.clients.get(n);for(let t=e.length-1;t>=0;t--){const n=e[t];for(let e=Mt(r.length-1,1+es(r,n.clock+n.len-1)),t=r[e];e>0&&t.id.clock>=n.clock;t=r[e])e-=1+as(r,e)}}))})(i,s),n.afterState.forEach(((e,t)=>{const r=n.beforeState.get(t)||0;if(r!==e){const e=s.clients.get(t),n=$t(es(e,r),1);for(let t=e.length-1;t>=n;)t-=1+as(e,t)}}));for(let e=o.length-1;e>=0;e--){const{client:t,clock:n}=o[e].id,r=s.clients.get(t),i=es(r,n);i+1<r.length&&as(r,i+1)>1||i>0&&as(r,i)}if(n.local||n.afterState.get(r.clientID)===n.beforeState.get(r.clientID)||(((...e)=>{vr.forEach((t=>t.print(e)))})(yr,ar,"[yjs] ",ur,pr,"Changed the client-id because another client seems to be using it."),r.clientID=Dr()),r.emit("afterTransactionCleanup",[n,r]),r._observers.has("update")){const e=new Lr;ls(e,n)&&r.emit("update",[e.toUint8Array(),n.origin,r,n])}if(r._observers.has("updateV2")){const e=new Rr;ls(e,n)&&r.emit("updateV2",[e.toUint8Array(),n.origin,r,n])}const{subdocsAdded:l,subdocsLoaded:c,subdocsRemoved:a}=n;(l.size>0||a.size>0||c.size>0)&&(l.forEach((e=>{e.clientID=r.clientID,null==e.collectionid&&(e.collectionid=r.collectionid),r.subdocs.add(e)})),a.forEach((e=>r.subdocs.delete(e))),r.emit("subdocs",[{loaded:c,added:l,removed:a},r,n]),a.forEach((e=>e.destroy()))),e.length<=t+1?(r._transactionCleanups=[],r.emit("afterAllTransactions",[r,e])):us(e,t+1)}}},ds=(e,t,n=null,r=!0)=>{const s=e._transactionCleanups;let i=!1,o=null;null===e._transaction&&(i=!0,e._transaction=new os(e,n,r),s.push(e._transaction),1===s.length&&e.emit("beforeAllTransactions",[e]),e.emit("beforeTransaction",[e._transaction,e]));try{o=t(e._transaction)}finally{if(i){const t=e._transaction===s[0];e._transaction=null,t&&us(s,0)}}return o};class hs{constructor(e,t){this.gen=function*(e){const t=An(e.restDecoder);for(let n=0;n<t;n++){const t=An(e.restDecoder),n=e.readClient();let r=An(e.restDecoder);for(let s=0;s<t;s++){const t=e.readInfo();if(10===t){const t=An(e.restDecoder);yield new Ki(zr(n,r),t),r+=t}else if(0!=(31&t)){const s=0==(192&t),i=new Fi(zr(n,r),null,(t&Ft)===Ft?e.readLeftID():null,null,(t&Bt)===Bt?e.readRightID():null,s?e.readParentInfo()?e.readString():e.readLeftID():null,s&&32==(32&t)?e.readString():null,Wi(e,t));yield i,r+=i.length}else{const t=e.readLen();yield new wi(zr(n,r),t),r+=t}}}}(e),this.curr=null,this.done=!1,this.filterSkips=t,this.next()}next(){do{this.curr=this.gen.next().value||null}while(this.filterSkips&&null!==this.curr&&this.curr.constructor===Ki);return this.curr}}class fs{constructor(e){this.currClient=0,this.startClock=0,this.written=0,this.encoder=e,this.clientStructs=[]}}const ps=(e,t=Pr,n=Ur)=>{const r=new t,s=new hs(new n(xn(e)),!1);let i=s.curr;if(null!==i){let e=0,t=i.id.client,n=0!==i.id.clock,o=n?0:i.id.clock+i.length;for(;null!==i;i=s.next())t!==i.id.client&&(0!==o&&(e++,nn(r.restEncoder,t),nn(r.restEncoder,o)),t=i.id.client,o=0,n=0!==i.id.clock),i.constructor===Ki&&(n=!0),n||(o=i.id.clock+i.length);0!==o&&(e++,nn(r.restEncoder,t),nn(r.restEncoder,o));const l=Xt();return nn(l,e),((e,t)=>{cn(e,Zt(t))})(l,r.restEncoder),r.restEncoder=l,r.toUint8Array()}return nn(r.restEncoder,0),r.toUint8Array()},gs=(e,t)=>{if(e.constructor===wi){const{client:n,clock:r}=e.id;return new wi(zr(n,r+t),e.length-t)}if(e.constructor===Ki){const{client:n,clock:r}=e.id;return new Ki(zr(n,r+t),e.length-t)}{const n=e,{client:r,clock:s}=n.id;return new Fi(zr(r,s+t),null,zr(r,s+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},ys=(e,t=Ur,n=Rr)=>{if(1===e.length)return e[0];const r=e.map((e=>new t(xn(e))));let s=r.map((e=>new hs(e,!0))),i=null;const o=new n,l=new fs(o);for(;s=s.filter((e=>null!==e.curr)),s.sort(((e,t)=>{if(e.curr.id.client===t.curr.id.client){const n=e.curr.id.clock-t.curr.id.clock;return 0===n?e.curr.constructor===t.curr.constructor?0:e.curr.constructor===Ki?1:-1:n}return t.curr.id.client-e.curr.id.client})),0!==s.length;){const e=s[0],t=e.curr.id.client;if(null!==i){let n=e.curr,r=!1;for(;null!==n&&n.id.clock+n.length<=i.struct.id.clock+i.struct.length&&n.id.client>=i.struct.id.client;)n=e.next(),r=!0;if(null===n||n.id.client!==t||r&&n.id.clock>i.struct.id.clock+i.struct.length)continue;if(t!==i.struct.id.client)vs(l,i.struct,i.offset),i={struct:n,offset:0},e.next();else if(i.struct.id.clock+i.struct.length<n.id.clock)if(i.struct.constructor===Ki)i.struct.length=n.id.clock+n.length-i.struct.id.clock;else{vs(l,i.struct,i.offset);const e=n.id.clock-i.struct.id.clock-i.struct.length;i={struct:new Ki(zr(t,i.struct.id.clock+i.struct.length),e),offset:0}}else{const t=i.struct.id.clock+i.struct.length-n.id.clock;t>0&&(i.struct.constructor===Ki?i.struct.length-=t:n=gs(n,t)),i.struct.mergeWith(n)||(vs(l,i.struct,i.offset),i={struct:n,offset:0},e.next())}}else i={struct:e.curr,offset:0},e.next();for(let n=e.curr;null!==n&&n.id.client===t&&n.id.clock===i.struct.id.clock+i.struct.length&&n.constructor!==Ki;n=e.next())vs(l,i.struct,i.offset),i={struct:n,offset:0}}null!==i&&(vs(l,i.struct,i.offset),i=null),bs(l);const c=r.map((e=>(e=>{const t=new kr,n=An(e.restDecoder);for(let r=0;r<n;r++){e.resetDsCurVal();const n=An(e.restDecoder),r=An(e.restDecoder);if(r>0){const s=At(t.clients,n,(()=>[]));for(let t=0;t<r;t++)s.push(new _r(e.readDsClock(),e.readDsLen()))}}return t})(e))),a=(e=>{const t=new kr;for(let n=0;n<e.length;n++)e[n].clients.forEach(((r,s)=>{if(!t.clients.has(s)){const i=r.slice();for(let t=n+1;t<e.length;t++)Tt(i,e[t].clients.get(s)||[]);t.clients.set(s,i)}}));return xr(t),t})(c);return Ir(o,a),o.toUint8Array()},ms=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:Zt(e.encoder.restEncoder)}),e.encoder.restEncoder=Xt(),e.written=0)},vs=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&ms(e),0===e.written&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),nn(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},bs=e=>{ms(e);const t=e.encoder.restEncoder;nn(t,e.clientStructs.length);for(let n=0;n<e.clientStructs.length;n++){const r=e.clientStructs[n];nn(t,r.written),cn(t,r.restEncoder)}},ws="You must not compute changes after the event-handler fired.";class _s{constructor(e,t){this.target=e,this.currentTarget=e,this.transaction=t,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=ks(this.currentTarget,this.target))}deletes(e){return Er(this.transaction.deleteSet,e.id)}get keys(){if(null===this._keys){if(0===this.transaction.doc._transactionCleanups.length)throw bn(ws);const e=new Map,t=this.target;this.transaction.changed.get(t).forEach((n=>{if(null!==n){const r=t._map.get(n);let s,i;if(this.adds(r)){let e=r.left;for(;null!==e&&this.adds(e);)e=e.left;if(this.deletes(r)){if(null===e||!this.deletes(e))return;s="delete",i=Ot(e.content.getContent())}else null!==e&&this.deletes(e)?(s="update",i=Ot(e.content.getContent())):(s="add",i=void 0)}else{if(!this.deletes(r))return;s="delete",i=Ot(r.content.getContent())}e.set(n,{action:s,oldValue:i})}})),this._keys=e}return this._keys}get delta(){return this.changes.delta}adds(e){return e.id.clock>=(this.transaction.beforeState.get(e.id.client)||0)}get changes(){let e=this._changes;if(null===e){if(0===this.transaction.doc._transactionCleanups.length)throw bn(ws);const t=this.target,n=Dt(),r=Dt(),s=[];e={added:n,deleted:r,delta:s,keys:this.keys};if(this.transaction.changed.get(t).has(null)){let e=null;const i=()=>{e&&s.push(e)};for(let s=t._start;null!==s;s=s.right)s.deleted?this.deletes(s)&&!this.adds(s)&&(null!==e&&void 0!==e.delete||(i(),e={delete:0}),e.delete+=s.length,r.add(s)):this.adds(s)?(null!==e&&void 0!==e.insert||(i(),e={insert:[]}),e.insert=e.insert.concat(s.content.getContent()),n.add(s)):(null!==e&&void 0!==e.retain||(i(),e={retain:0}),e.retain+=s.length);null!==e&&void 0===e.retain&&i()}this._changes=e}return e}}const ks=(e,t)=>{const n=[];for(;null!==t._item&&t!==e;){if(null!==t._item.parentSub)n.unshift(t._item.parentSub);else{let e=0,r=t._item.parent._start;for(;r!==t._item&&null!==r;)!r.deleted&&r.countable&&(e+=r.length),r=r.right;n.unshift(e)}t=t._item.parent}return n},Ss=()=>{((...e)=>{e.unshift(yr),vr.forEach((t=>t.print(e)))})("Invalid access: Add Yjs type to a document before reading data.")};let Es=0;class xs{constructor(e,t){e.marker=!0,this.p=e,this.index=t,this.timestamp=Es++}}const Cs=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=Es++},Is=(e,t)=>{if(null===e._start||0===t||null===e._searchMarker)return null;const n=0===e._searchMarker.length?null:e._searchMarker.reduce(((e,n)=>Rt(t-e.index)<Rt(t-n.index)?e:n));let r=e._start,s=0;for(null!==n&&(r=n.p,s=n.index,(e=>{e.timestamp=Es++})(n));null!==r.right&&s<t;){if(!r.deleted&&r.countable){if(t<s+r.length)break;s+=r.length}r=r.right}for(;null!==r.left&&s>t;)r=r.left,!r.deleted&&r.countable&&(s-=r.length);for(;null!==r.left&&r.left.id.client===r.id.client&&r.left.id.clock+r.left.length===r.id.clock;)r=r.left,!r.deleted&&r.countable&&(s-=r.length);return null!==n&&Rt(n.index-s)<r.parent.length/80?(Cs(n,r,s),n):((e,t,n)=>{if(e.length>=80){const r=e.reduce(((e,t)=>e.timestamp<t.timestamp?e:t));return Cs(r,t,n),r}{const r=new xs(t,n);return e.push(r),r}})(e._searchMarker,r,s)},As=(e,t,n)=>{for(let r=e.length-1;r>=0;r--){const s=e[r];if(n>0){let t=s.p;for(t.marker=!1;t&&(t.deleted||!t.countable);)t=t.left,t&&!t.deleted&&t.countable&&(s.index-=t.length);if(null===t||!0===t.marker){e.splice(r,1);continue}s.p=t,t.marker=!0}(t<s.index||n>0&&t===s.index)&&(s.index=$t(t,s.index+n))}},Ds=(e,t,n)=>{const r=e,s=t.changedParentTypes;for(;At(s,e,(()=>[])).push(n),null!==e._item;)e=e._item.parent;Kr(r._eH,n,t)};class Os{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=Fr(),this._dEH=Fr(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,t){this.doc=e,this._item=t}_copy(){throw wn()}clone(){throw wn()}_write(e){}get _first(){let e=this._start;for(;null!==e&&e.deleted;)e=e.right;return e}_callObserver(e,t){!e.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(e){Wr(this._eH,e)}observeDeep(e){Wr(this._dEH,e)}unobserve(e){Vr(this._eH,e)}unobserveDeep(e){Vr(this._dEH,e)}toJSON(){}}const Ts=(e,t,n)=>{e.doc??Ss(),t<0&&(t=e._length+t),n<0&&(n=e._length+n);let r=n-t;const s=[];let i=e._start;for(;null!==i&&r>0;){if(i.countable&&!i.deleted){const e=i.content.getContent();if(e.length<=t)t-=e.length;else{for(let n=t;n<e.length&&r>0;n++)s.push(e[n]),r--;t=0}}i=i.right}return s},Us=e=>{e.doc??Ss();const t=[];let n=e._start;for(;null!==n;){if(n.countable&&!n.deleted){const e=n.content.getContent();for(let n=0;n<e.length;n++)t.push(e[n])}n=n.right}return t},js=(e,t)=>{let n=0,r=e._start;for(e.doc??Ss();null!==r;){if(r.countable&&!r.deleted){const s=r.content.getContent();for(let r=0;r<s.length;r++)t(s[r],n++,e)}r=r.right}},Ls=(e,t)=>{const n=[];return js(e,((r,s)=>{n.push(t(r,s,e))})),n},Ps=e=>{let t=e._start,n=null,r=0;return{[Symbol.iterator](){return this},next:()=>{if(null===n){for(;null!==t&&t.deleted;)t=t.right;if(null===t)return{done:!0,value:void 0};n=t.content.getContent(),r=0,t=t.right}const e=n[r++];return n.length<=r&&(n=null),{done:!1,value:e}}}},Rs=(e,t)=>{e.doc??Ss();const n=Is(e,t);let r=e._start;for(null!==n&&(r=n.p,t-=n.index);null!==r;r=r.right)if(!r.deleted&&r.countable){if(t<r.length)return r.content.getContent()[t];t-=r.length}},Ms=(e,t,n,r)=>{let s=n;const i=e.doc,o=i.clientID,l=i.store,c=null===n?t._start:n.right;let a=[];const u=()=>{a.length>0&&(s=new Fi(zr(o,Xr(l,o)),s,s&&s.lastId,c,c&&c.id,t,null,new Di(a)),s.integrate(e,0),a=[])};r.forEach((n=>{if(null===n)a.push(n);else switch(n.constructor){case Number:case Object:case Boolean:case Array:case String:a.push(n);break;default:switch(u(),n.constructor){case Uint8Array:case ArrayBuffer:s=new Fi(zr(o,Xr(l,o)),s,s&&s.lastId,c,c&&c.id,t,null,new _i(new Uint8Array(n))),s.integrate(e,0);break;case Or:s=new Fi(zr(o,Xr(l,o)),s,s&&s.lastId,c,c&&c.id,t,null,new Ei(n)),s.integrate(e,0);break;default:if(!(n instanceof Os))throw new Error("Unexpected content type in insert operation");s=new Fi(zr(o,Xr(l,o)),s,s&&s.lastId,c,c&&c.id,t,null,new Ni(n)),s.integrate(e,0)}}})),u()},$s=()=>bn("Length exceeded!"),Ns=(e,t,n,r)=>{if(n>t._length)throw $s();if(0===n)return t._searchMarker&&As(t._searchMarker,n,r.length),Ms(e,t,null,r);const s=n,i=Is(t,n);let o=t._start;for(null!==i&&(o=i.p,0===(n-=i.index)&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));null!==o;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n<o.length&&rs(e,zr(o.id.client,o.id.clock+n));break}n-=o.length}return t._searchMarker&&As(t._searchMarker,s,r.length),Ms(e,t,o,r)},Bs=(e,t,n,r)=>{if(0===r)return;const s=n,i=r,o=Is(t,n);let l=t._start;for(null!==o&&(l=o.p,n-=o.index);null!==l&&n>0;l=l.right)!l.deleted&&l.countable&&(n<l.length&&rs(e,zr(l.id.client,l.id.clock+n)),n-=l.length);for(;r>0&&null!==l;)l.deleted||(r<l.length&&rs(e,zr(l.id.client,l.id.clock+r)),l.delete(e),r-=l.length),l=l.right;if(r>0)throw $s();t._searchMarker&&As(t._searchMarker,s,-i+r)},Fs=(e,t,n)=>{const r=t._map.get(n);void 0!==r&&r.delete(e)},Ws=(e,t,n,r)=>{const s=t._map.get(n)||null,i=e.doc,o=i.clientID;let l;if(null==r)l=new Di([r]);else switch(r.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:l=new Di([r]);break;case Uint8Array:l=new _i(r);break;case Or:l=new Ei(r);break;default:if(!(r instanceof Os))throw new Error("Unexpected content type");l=new Ni(r)}new Fi(zr(o,Xr(i.store,o)),s,s&&s.lastId,null,null,t,n,l).integrate(e,0)},Vs=(e,t)=>{e.doc??Ss();const n=e._map.get(t);return void 0===n||n.deleted?void 0:n.content.getContent()[n.length-1]},Ks=e=>{const t={};return e.doc??Ss(),e._map.forEach(((e,n)=>{e.deleted||(t[n]=e.content.getContent()[e.length-1])})),t},Hs=(e,t)=>{e.doc??Ss();const n=e._map.get(t);return void 0!==n&&!n.deleted},Js=e=>{return e.doc??Ss(),t=e._map.entries(),n=e=>!e[1].deleted,br((()=>{let e;do{e=t.next()}while(!e.done&&!n(e.value));return e}));var t,n};class zs extends _s{}class qs extends Os{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(e){const t=new qs;return t.push(e),t}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new qs}clone(){const e=new qs;return e.insert(0,this.toArray().map((e=>e instanceof Os?e.clone():e))),e}get length(){return this.doc??Ss(),this._length}_callObserver(e,t){super._callObserver(e,t),Ds(this,e,new zs(this,e))}insert(e,t){null!==this.doc?ds(this.doc,(n=>{Ns(n,this,e,t)})):this._prelimContent.splice(e,0,...t)}push(e){null!==this.doc?ds(this.doc,(t=>{((e,t,n)=>{let r=(t._searchMarker||[]).reduce(((e,t)=>t.index>e.index?t:e),{index:0,p:t._start}).p;if(r)for(;r.right;)r=r.right;Ms(e,t,r,n)})(t,this,e)})):this._prelimContent.push(...e)}unshift(e){this.insert(0,e)}delete(e,t=1){null!==this.doc?ds(this.doc,(n=>{Bs(n,this,e,t)})):this._prelimContent.splice(e,t)}get(e){return Rs(this,e)}toArray(){return Us(this)}slice(e=0,t=this.length){return Ts(this,e,t)}toJSON(){return this.map((e=>e instanceof Os?e.toJSON():e))}map(e){return Ls(this,e)}forEach(e){js(this,e)}[Symbol.iterator](){return Ps(this)}_write(e){e.writeTypeRef(Ui)}}class Ys extends _s{constructor(e,t,n){super(e,t),this.keysChanged=n}}class Gs extends Os{constructor(e){super(),this._prelimContent=null,this._prelimContent=void 0===e?new Map:new Map(e)}_integrate(e,t){super._integrate(e,t),this._prelimContent.forEach(((e,t)=>{this.set(t,e)})),this._prelimContent=null}_copy(){return new Gs}clone(){const e=new Gs;return this.forEach(((t,n)=>{e.set(n,t instanceof Os?t.clone():t)})),e}_callObserver(e,t){Ds(this,e,new Ys(this,e,t))}toJSON(){this.doc??Ss();const e={};return this._map.forEach(((t,n)=>{if(!t.deleted){const r=t.content.getContent()[t.length-1];e[n]=r instanceof Os?r.toJSON():r}})),e}get size(){return[...Js(this)].length}keys(){return wr(Js(this),(e=>e[0]))}values(){return wr(Js(this),(e=>e[1].content.getContent()[e[1].length-1]))}entries(){return wr(Js(this),(e=>[e[0],e[1].content.getContent()[e[1].length-1]]))}forEach(e){this.doc??Ss(),this._map.forEach(((t,n)=>{t.deleted||e(t.content.getContent()[t.length-1],n,this)}))}[Symbol.iterator](){return this.entries()}delete(e){null!==this.doc?ds(this.doc,(t=>{Fs(t,this,e)})):this._prelimContent.delete(e)}set(e,t){return null!==this.doc?ds(this.doc,(n=>{Ws(n,this,e,t)})):this._prelimContent.set(e,t),t}get(e){return Vs(this,e)}has(e){return Hs(this,e)}clear(){null!==this.doc?ds(this.doc,(e=>{this.forEach((function(t,n,r){Fs(e,r,n)}))})):this._prelimContent.clear()}_write(e){e.writeTypeRef(ji)}}const Qs=(e,t)=>e===t||"object"==typeof e&&"object"==typeof t&&e&&t&&Gn(e,t);class Xs{constructor(e,t,n,r){this.left=e,this.right=t,this.index=n,this.currentAttributes=r}forward(){if(null===this.right&&_n(),this.right.content.constructor===Ci)this.right.deleted||ni(this.currentAttributes,this.right.content);else this.right.deleted||(this.index+=this.right.length);this.left=this.right,this.right=this.right.right}}const Zs=(e,t,n)=>{for(;null!==t.right&&n>0;){if(t.right.content.constructor===Ci)t.right.deleted||ni(t.currentAttributes,t.right.content);else t.right.deleted||(n<t.right.length&&rs(e,zr(t.right.id.client,t.right.id.clock+n)),t.index+=t.right.length,n-=t.right.length);t.left=t.right,t.right=t.right.right}return t},ei=(e,t,n,r)=>{const s=new Map,i=r?Is(t,n):null;if(i){const t=new Xs(i.p.left,i.p,i.index,s);return Zs(e,t,n-i.index)}{const r=new Xs(null,t._start,0,s);return Zs(e,r,n)}},ti=(e,t,n,r)=>{for(;null!==n.right&&(!0===n.right.deleted||n.right.content.constructor===Ci&&Qs(r.get(n.right.content.key),n.right.content.value));)n.right.deleted||r.delete(n.right.content.key),n.forward();const s=e.doc,i=s.clientID;r.forEach(((r,o)=>{const l=n.left,c=n.right,a=new Fi(zr(i,Xr(s.store,i)),l,l&&l.lastId,c,c&&c.id,t,null,new Ci(o,r));a.integrate(e,0),n.right=a,n.forward()}))},ni=(e,t)=>{const{key:n,value:r}=t;null===r?e.delete(n):e.set(n,r)},ri=(e,t)=>{for(;null!==e.right&&(e.right.deleted||e.right.content.constructor===Ci&&Qs(t[e.right.content.key]??null,e.right.content.value));)e.forward()},si=(e,t,n,r)=>{const s=e.doc,i=s.clientID,o=new Map;for(const l in r){const c=r[l],a=n.currentAttributes.get(l)??null;if(!Qs(a,c)){o.set(l,a);const{left:r,right:u}=n;n.right=new Fi(zr(i,Xr(s.store,i)),r,r&&r.lastId,u,u&&u.id,t,null,new Ci(l,c)),n.right.integrate(e,0),n.forward()}}return o},ii=(e,t,n,r,s)=>{n.currentAttributes.forEach(((e,t)=>{void 0===s[t]&&(s[t]=null)}));const i=e.doc,o=i.clientID;ri(n,s);const l=si(e,t,n,s),c=r.constructor===String?new Oi(r):r instanceof Os?new Ni(r):new xi(r);let{left:a,right:u,index:d}=n;t._searchMarker&&As(t._searchMarker,n.index,c.getLength()),u=new Fi(zr(o,Xr(i.store,o)),a,a&&a.lastId,u,u&&u.id,t,null,c),u.integrate(e,0),n.right=u,n.index=d,n.forward(),ti(e,t,n,l)},oi=(e,t,n,r,s)=>{const i=e.doc,o=i.clientID;ri(n,s);const l=si(e,t,n,s);e:for(;null!==n.right&&(r>0||l.size>0&&(n.right.deleted||n.right.content.constructor===Ci));){if(!n.right.deleted)switch(n.right.content.constructor){case Ci:{const{key:t,value:i}=n.right.content,o=s[t];if(void 0!==o){if(Qs(o,i))l.delete(t);else{if(0===r)break e;l.set(t,i)}n.right.delete(e)}else n.currentAttributes.set(t,i);break}default:r<n.right.length&&rs(e,zr(n.right.id.client,n.right.id.clock+r)),r-=n.right.length}n.forward()}if(r>0){let s="";for(;r>0;r--)s+="\n";n.right=new Fi(zr(o,Xr(i.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new Oi(s)),n.right.integrate(e,0),n.forward()}ti(e,t,n,l)},li=(e,t,n,r,s)=>{let i=t;const o=Ct();for(;i&&(!i.countable||i.deleted);){if(!i.deleted&&i.content.constructor===Ci){const e=i.content;o.set(e.key,e)}i=i.right}let l=0,c=!1;for(;t!==i;){if(n===t&&(c=!0),!t.deleted){const n=t.content;switch(n.constructor){case Ci:{const{key:i,value:a}=n,u=r.get(i)??null;o.get(i)===n&&u!==a||(t.delete(e),l++,c||(s.get(i)??null)!==a||u===a||(null===u?s.delete(i):s.set(i,u))),c||t.deleted||ni(s,n);break}}}t=t.right}return l},ci=e=>{let t=0;return ds(e.doc,(n=>{let r=e._start,s=e._start,i=Ct();const o=It(i);for(;s;){if(!1===s.deleted)if(s.content.constructor===Ci)ni(o,s.content);else t+=li(n,r,s,i,o),i=It(o),r=s;s=s.right}})),t},ai=e=>{const t=new Set,n=e.doc;for(const[r,s]of e.afterState.entries()){const i=e.beforeState.get(r)||0;s!==i&&is(e,n.store.clients.get(r),i,s,(e=>{e.deleted||e.content.constructor!==Ci||e.constructor===wi||t.add(e.parent)}))}ds(n,(n=>{Sr(e,e.deleteSet,(e=>{if(e instanceof wi||!e.parent._hasFormatting||t.has(e.parent))return;const r=e.parent;e.content.constructor===Ci?t.add(r):((e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;const n=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===Ci){const r=t.content.key;n.has(r)?t.delete(e):n.add(r)}t=t.left}})(n,e)}));for(const e of t)ci(e)}))},ui=(e,t,n)=>{const r=n,s=It(t.currentAttributes),i=t.right;for(;n>0&&null!==t.right;){if(!1===t.right.deleted)switch(t.right.content.constructor){case Ni:case xi:case Oi:n<t.right.length&&rs(e,zr(t.right.id.client,t.right.id.clock+n)),n-=t.right.length,t.right.delete(e)}t.forward()}i&&li(e,i,t.right,s,t.currentAttributes);const o=(t.left||t.right).parent;return o._searchMarker&&As(o._searchMarker,t.index,-r+n),t};class di extends _s{constructor(e,t,n){super(e,t),this.childListChanged=!1,this.keysChanged=new Set,n.forEach((e=>{null===e?this.childListChanged=!0:this.keysChanged.add(e)}))}get changes(){if(null===this._changes){const e={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=e}return this._changes}get delta(){if(null===this._delta){const e=this.target.doc,t=[];ds(e,(e=>{const n=new Map,r=new Map;let s=this.target._start,i=null;const o={};let l="",c=0,a=0;const u=()=>{if(null!==i){let e=null;switch(i){case"delete":a>0&&(e={delete:a}),a=0;break;case"insert":("object"==typeof l||l.length>0)&&(e={insert:l},n.size>0&&(e.attributes={},n.forEach(((t,n)=>{null!==t&&(e.attributes[n]=t)})))),l="";break;case"retain":c>0&&(e={retain:c},(e=>{for(const t in e)return!1;return!0})(o)||(e.attributes=zn({},o))),c=0}e&&t.push(e),i=null}};for(;null!==s;){switch(s.content.constructor){case Ni:case xi:this.adds(s)?this.deletes(s)||(u(),i="insert",l=s.content.getContent()[0],u()):this.deletes(s)?("delete"!==i&&(u(),i="delete"),a+=1):s.deleted||("retain"!==i&&(u(),i="retain"),c+=1);break;case Oi:this.adds(s)?this.deletes(s)||("insert"!==i&&(u(),i="insert"),l+=s.content.str):this.deletes(s)?("delete"!==i&&(u(),i="delete"),a+=s.length):s.deleted||("retain"!==i&&(u(),i="retain"),c+=s.length);break;case Ci:{const{key:t,value:l}=s.content;if(this.adds(s)){if(!this.deletes(s)){const c=n.get(t)??null;Qs(c,l)?null!==l&&s.delete(e):("retain"===i&&u(),Qs(l,r.get(t)??null)?delete o[t]:o[t]=l)}}else if(this.deletes(s)){r.set(t,l);const e=n.get(t)??null;Qs(e,l)||("retain"===i&&u(),o[t]=e)}else if(!s.deleted){r.set(t,l);const n=o[t];void 0!==n&&(Qs(n,l)?null!==n&&s.delete(e):("retain"===i&&u(),null===l?delete o[t]:o[t]=l))}s.deleted||("insert"===i&&u(),ni(n,s.content));break}}s=s.right}for(u();t.length>0;){const e=t[t.length-1];if(void 0===e.retain||void 0!==e.attributes)break;t.pop()}})),this._delta=t}return this._delta}}class hi extends Os{constructor(e){super(),this._pending=void 0!==e?[()=>this.insert(0,e)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Ss(),this._length}_integrate(e,t){super._integrate(e,t);try{this._pending.forEach((e=>e()))}catch(e){}this._pending=null}_copy(){return new hi}clone(){const e=new hi;return e.applyDelta(this.toDelta()),e}_callObserver(e,t){super._callObserver(e,t);const n=new di(this,e,t);Ds(this,e,n),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??Ss();let e="",t=this._start;for(;null!==t;)!t.deleted&&t.countable&&t.content.constructor===Oi&&(e+=t.content.str),t=t.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:t=!0}={}){null!==this.doc?ds(this.doc,(n=>{const r=new Xs(null,this._start,0,new Map);for(let s=0;s<e.length;s++){const i=e[s];if(void 0!==i.insert){const o=t||"string"!=typeof i.insert||s!==e.length-1||null!==r.right||"\n"!==i.insert.slice(-1)?i.insert:i.insert.slice(0,-1);("string"!=typeof o||o.length>0)&&ii(n,this,r,o,i.attributes||{})}else void 0!==i.retain?oi(n,this,r,i.retain,i.attributes||{}):void 0!==i.delete&&ui(n,r,i.delete)}})):this._pending.push((()=>this.applyDelta(e)))}toDelta(e,t,n){this.doc??Ss();const r=[],s=new Map,i=this.doc;let o="",l=this._start;function c(){if(o.length>0){const e={};let t=!1;s.forEach(((n,r)=>{t=!0,e[r]=n}));const n={insert:o};t&&(n.attributes=e),r.push(n),o=""}}const a=()=>{for(;null!==l;){if(qr(l,e)||void 0!==t&&qr(l,t))switch(l.content.constructor){case Oi:{const r=s.get("ychange");void 0===e||qr(l,e)?void 0===t||qr(l,t)?void 0!==r&&(c(),s.delete("ychange")):void 0!==r&&r.user===l.id.client&&"added"===r.type||(c(),s.set("ychange",n?n("added",l.id):{type:"added"})):void 0!==r&&r.user===l.id.client&&"removed"===r.type||(c(),s.set("ychange",n?n("removed",l.id):{type:"removed"})),o+=l.content.str;break}case Ni:case xi:{c();const e={insert:l.content.getContent()[0]};if(s.size>0){const t={};e.attributes=t,s.forEach(((e,n)=>{t[n]=e}))}r.push(e);break}case Ci:qr(l,e)&&(c(),ni(s,l.content))}l=l.right}c()};return e||t?ds(i,(n=>{e&&Yr(n,e),t&&Yr(n,t),a()}),"cleanup"):a(),r}insert(e,t,n){if(t.length<=0)return;const r=this.doc;null!==r?ds(r,(r=>{const s=ei(r,this,e,!n);n||(n={},s.currentAttributes.forEach(((e,t)=>{n[t]=e}))),ii(r,this,s,t,n)})):this._pending.push((()=>this.insert(e,t,n)))}insertEmbed(e,t,n){const r=this.doc;null!==r?ds(r,(r=>{const s=ei(r,this,e,!n);ii(r,this,s,t,n||{})})):this._pending.push((()=>this.insertEmbed(e,t,n||{})))}delete(e,t){if(0===t)return;const n=this.doc;null!==n?ds(n,(n=>{ui(n,ei(n,this,e,!0),t)})):this._pending.push((()=>this.delete(e,t)))}format(e,t,n){if(0===t)return;const r=this.doc;null!==r?ds(r,(r=>{const s=ei(r,this,e,!1);null!==s.right&&oi(r,this,s,t,n)})):this._pending.push((()=>this.format(e,t,n)))}removeAttribute(e){null!==this.doc?ds(this.doc,(t=>{Fs(t,this,e)})):this._pending.push((()=>this.removeAttribute(e)))}setAttribute(e,t){null!==this.doc?ds(this.doc,(n=>{Ws(n,this,e,t)})):this._pending.push((()=>this.setAttribute(e,t)))}getAttribute(e){return Vs(this,e)}getAttributes(){return Ks(this)}_write(e){e.writeTypeRef(Li)}}class fi{constructor(e,t=(()=>!0)){this._filter=t,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??Ss()}[Symbol.iterator](){return this}next(){let e=this._currentNode,t=e&&e.content&&e.content.type;if(null!==e&&(!this._firstCall||e.deleted||!this._filter(t)))do{if(t=e.content.type,e.deleted||t.constructor!==gi&&t.constructor!==pi||null===t._start)for(;null!==e;){const t=e.next;if(null!==t){e=t;break}e=e.parent===this._root?null:e.parent._item}else e=t._start}while(null!==e&&(e.deleted||!this._filter(e.content.type)));return this._firstCall=!1,null===e?{value:void 0,done:!0}:(this._currentNode=e,{value:e.content.type,done:!1})}}class pi extends Os{constructor(){super(),this._prelimContent=[]}get firstChild(){const e=this._first;return e?e.content.getContent()[0]:null}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new pi}clone(){const e=new pi;return e.insert(0,this.toArray().map((e=>e instanceof Os?e.clone():e))),e}get length(){return this.doc??Ss(),null===this._prelimContent?this._length:this._prelimContent.length}createTreeWalker(e){return new fi(this,e)}querySelector(e){e=e.toUpperCase();const t=new fi(this,(t=>t.nodeName&&t.nodeName.toUpperCase()===e)).next();return t.done?null:t.value}querySelectorAll(e){return e=e.toUpperCase(),Ut(new fi(this,(t=>t.nodeName&&t.nodeName.toUpperCase()===e)))}_callObserver(e,t){Ds(this,e,new yi(this,t,e))}toString(){return Ls(this,(e=>e.toString())).join("")}toJSON(){return this.toString()}toDOM(e=document,t={},n){const r=e.createDocumentFragment();return void 0!==n&&n._createAssociation(r,this),js(this,(s=>{r.insertBefore(s.toDOM(e,t,n),null)})),r}insert(e,t){null!==this.doc?ds(this.doc,(n=>{Ns(n,this,e,t)})):this._prelimContent.splice(e,0,...t)}insertAfter(e,t){if(null!==this.doc)ds(this.doc,(n=>{const r=e&&e instanceof Os?e._item:e;Ms(n,this,r,t)}));else{const n=this._prelimContent,r=null===e?0:n.findIndex((t=>t===e))+1;if(0===r&&null!==e)throw bn("Reference item not found");n.splice(r,0,...t)}}delete(e,t=1){null!==this.doc?ds(this.doc,(n=>{Bs(n,this,e,t)})):this._prelimContent.splice(e,t)}toArray(){return Us(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return Rs(this,e)}slice(e=0,t=this.length){return Ts(this,e,t)}forEach(e){js(this,e)}_write(e){e.writeTypeRef(Ri)}}class gi extends pi{constructor(e="UNDEFINED"){super(),this.nodeName=e,this._prelimAttrs=new Map}get nextSibling(){const e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){const e=this._item?this._item.prev:null;return e?e.content.type:null}_integrate(e,t){super._integrate(e,t),this._prelimAttrs.forEach(((e,t)=>{this.setAttribute(t,e)})),this._prelimAttrs=null}_copy(){return new gi(this.nodeName)}clone(){const e=new gi(this.nodeName);return((e,t)=>{for(const n in e)t(e[n],n)})(this.getAttributes(),((t,n)=>{"string"==typeof t&&e.setAttribute(n,t)})),e.insert(0,this.toArray().map((e=>e instanceof Os?e.clone():e))),e}toString(){const e=this.getAttributes(),t=[],n=[];for(const t in e)n.push(t);n.sort();const r=n.length;for(let s=0;s<r;s++){const r=n[s];t.push(r+'="'+e[r]+'"')}const s=this.nodeName.toLocaleLowerCase();return`<${s}${t.length>0?" "+t.join(" "):""}>${super.toString()}</${s}>`}removeAttribute(e){null!==this.doc?ds(this.doc,(t=>{Fs(t,this,e)})):this._prelimAttrs.delete(e)}setAttribute(e,t){null!==this.doc?ds(this.doc,(n=>{Ws(n,this,e,t)})):this._prelimAttrs.set(e,t)}getAttribute(e){return Vs(this,e)}hasAttribute(e){return Hs(this,e)}getAttributes(e){return e?((e,t)=>{const n={};return e._map.forEach(((e,r)=>{let s=e;for(;null!==s&&(!t.sv.has(s.id.client)||s.id.clock>=(t.sv.get(s.id.client)||0));)s=s.left;null!==s&&qr(s,t)&&(n[r]=s.content.getContent()[s.length-1])})),n})(this,e):Ks(this)}toDOM(e=document,t={},n){const r=e.createElement(this.nodeName),s=this.getAttributes();for(const e in s){const t=s[e];"string"==typeof t&&r.setAttribute(e,t)}return js(this,(s=>{r.appendChild(s.toDOM(e,t,n))})),void 0!==n&&n._createAssociation(r,this),r}_write(e){e.writeTypeRef(Pi),e.writeKey(this.nodeName)}}class yi extends _s{constructor(e,t,n){super(e,n),this.childListChanged=!1,this.attributesChanged=new Set,t.forEach((e=>{null===e?this.childListChanged=!0:this.attributesChanged.add(e)}))}}class mi extends Gs{constructor(e){super(),this.hookName=e}_copy(){return new mi(this.hookName)}clone(){const e=new mi(this.hookName);return this.forEach(((t,n)=>{e.set(n,t)})),e}toDOM(e=document,t={},n){const r=t[this.hookName];let s;return s=void 0!==r?r.createDom(this):document.createElement(this.hookName),s.setAttribute("data-yjs-hook",this.hookName),void 0!==n&&n._createAssociation(s,this),s}_write(e){e.writeTypeRef(Mi),e.writeKey(this.hookName)}}class vi extends hi{get nextSibling(){const e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){const e=this._item?this._item.prev:null;return e?e.content.type:null}_copy(){return new vi}clone(){const e=new vi;return e.applyDelta(this.toDelta()),e}toDOM(e=document,t,n){const r=e.createTextNode(this.toString());return void 0!==n&&n._createAssociation(r,this),r}toString(){return this.toDelta().map((e=>{const t=[];for(const n in e.attributes){const r=[];for(const t in e.attributes[n])r.push({key:t,value:e.attributes[n][t]});r.sort(((e,t)=>e.key<t.key?-1:1)),t.push({nodeName:n,attrs:r})}t.sort(((e,t)=>e.nodeName<t.nodeName?-1:1));let n="";for(let e=0;e<t.length;e++){const r=t[e];n+=`<${r.nodeName}`;for(let e=0;e<r.attrs.length;e++){const t=r.attrs[e];n+=` ${t.key}="${t.value}"`}n+=">"}n+=e.insert;for(let e=t.length-1;e>=0;e--)n+=`</${t[e].nodeName}>`;return n})).join("")}toJSON(){return this.toString()}_write(e){e.writeTypeRef($i)}}class bi{constructor(e,t){this.id=e,this.length=t}get deleted(){throw wn()}mergeWith(e){return!1}write(e,t,n){throw wn()}integrate(e,t){throw wn()}}class wi extends bi{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor===e.constructor&&(this.length+=e.length,!0)}integrate(e,t){t>0&&(this.id.clock+=t,this.length-=t),Zr(e.doc.store,this)}write(e,t){e.writeInfo(0),e.writeLen(this.length-t)}getMissing(e,t){return null}}class _i{constructor(e){this.content=e}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new _i(this.content)}splice(e){throw wn()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeBuf(this.content)}getRef(){return 3}}class ki{constructor(e){this.len=e}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new ki(this.len)}splice(e){const t=new ki(this.len-e);return this.len=e,t}mergeWith(e){return this.len+=e.len,!0}integrate(e,t){Cr(e.deleteSet,t.id.client,t.id.clock,this.len),t.markDeleted()}delete(e){}gc(e){}write(e,t){e.writeLen(this.len-t)}getRef(){return 1}}const Si=(e,t)=>new Or({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1});class Ei{constructor(e){e._item,this.doc=e;const t={};this.opts=t,e.gc||(t.gc=!1),e.autoLoad&&(t.autoLoad=!0),null!==e.meta&&(t.meta=e.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new Ei(Si(this.doc.guid,this.opts))}splice(e){throw wn()}mergeWith(e){return!1}integrate(e,t){this.doc._item=t,e.subdocsAdded.add(this.doc),this.doc.shouldLoad&&e.subdocsLoaded.add(this.doc)}delete(e){e.subdocsAdded.has(this.doc)?e.subdocsAdded.delete(this.doc):e.subdocsRemoved.add(this.doc)}gc(e){}write(e,t){e.writeString(this.doc.guid),e.writeAny(this.opts)}getRef(){return 9}}class xi{constructor(e){this.embed=e}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new xi(this.embed)}splice(e){throw wn()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeJSON(this.embed)}getRef(){return 5}}class Ci{constructor(e,t){this.key=e,this.value=t}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new Ci(this.key,this.value)}splice(e){throw wn()}mergeWith(e){return!1}integrate(e,t){const n=t.parent;n._searchMarker=null,n._hasFormatting=!0}delete(e){}gc(e){}write(e,t){e.writeKey(this.key),e.writeJSON(this.value)}getRef(){return 6}}class Ii{constructor(e){this.arr=e}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new Ii(this.arr)}splice(e){const t=new Ii(this.arr.slice(e));return this.arr=this.arr.slice(0,e),t}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){const n=this.arr.length;e.writeLen(n-t);for(let r=t;r<n;r++){const t=this.arr[r];e.writeString(void 0===t?"undefined":JSON.stringify(t))}}getRef(){return 2}}const Ai="development"===rr("node_env");class Di{constructor(e){this.arr=e,Ai&&Xn(e)}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new Di(this.arr)}splice(e){const t=new Di(this.arr.slice(e));return this.arr=this.arr.slice(0,e),t}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){const n=this.arr.length;e.writeLen(n-t);for(let r=t;r<n;r++){const t=this.arr[r];e.writeAny(t)}}getRef(){return 8}}class Oi{constructor(e){this.str=e}getLength(){return this.str.length}getContent(){return this.str.split("")}isCountable(){return!0}copy(){return new Oi(this.str)}splice(e){const t=new Oi(this.str.slice(e));this.str=this.str.slice(0,e);const n=this.str.charCodeAt(e-1);return n>=55296&&n<=56319&&(this.str=this.str.slice(0,e-1)+"�",t.str="�"+t.str.slice(1)),t}mergeWith(e){return this.str+=e.str,!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeString(0===t?this.str:this.str.slice(t))}getRef(){return 4}}const Ti=[e=>new qs,e=>new Gs,e=>new hi,e=>new gi(e.readKey()),e=>new pi,e=>new mi(e.readKey()),e=>new vi],Ui=0,ji=1,Li=2,Pi=3,Ri=4,Mi=5,$i=6;class Ni{constructor(e){this.type=e}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new Ni(this.type._copy())}splice(e){throw wn()}mergeWith(e){return!1}integrate(e,t){this.type._integrate(e.doc,t)}delete(e){let t=this.type._start;for(;null!==t;)t.deleted?t.id.clock<(e.beforeState.get(t.id.client)||0)&&e._mergeStructs.push(t):t.delete(e),t=t.right;this.type._map.forEach((t=>{t.deleted?t.id.clock<(e.beforeState.get(t.id.client)||0)&&e._mergeStructs.push(t):t.delete(e)})),e.changed.delete(this.type)}gc(e){let t=this.type._start;for(;null!==t;)t.gc(e,!0),t=t.right;this.type._start=null,this.type._map.forEach((t=>{for(;null!==t;)t.gc(e,!0),t=t.left})),this.type._map=new Map}write(e,t){this.type._write(e)}getRef(){return 7}}const Bi=(e,t,n)=>{const{client:r,clock:s}=t.id,i=new Fi(zr(r,s+n),t,zr(r,s+n-1),t.right,t.rightOrigin,t.parent,t.parentSub,t.content.splice(n));return t.deleted&&i.markDeleted(),t.keep&&(i.keep=!0),null!==t.redone&&(i.redone=zr(t.redone.client,t.redone.clock+n)),t.right=i,null!==i.right&&(i.right.left=i),e._mergeStructs.push(i),null!==i.parentSub&&null===i.right&&i.parent._map.set(i.parentSub,i),t.length=n,i};class Fi extends bi{constructor(e,t,n,r,s,i,o,l){super(e,l.getLength()),this.origin=n,this.left=t,this.right=r,this.rightOrigin=s,this.parent=i,this.parentSub=o,this.redone=null,this.content=l,this.info=this.content.isCountable()?2:0}set marker(e){(8&this.info)>0!==e&&(this.info^=8)}get marker(){return(8&this.info)>0}get keep(){return(1&this.info)>0}set keep(e){this.keep!==e&&(this.info^=1)}get countable(){return(2&this.info)>0}get deleted(){return(4&this.info)>0}set deleted(e){this.deleted!==e&&(this.info^=4)}markDeleted(){this.info|=4}getMissing(e,t){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=Xr(t,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=Xr(t,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===Hr&&this.id.client!==this.parent.client&&this.parent.clock>=Xr(t,this.parent.client))return this.parent.client;if(this.origin&&(this.left=ss(e,t,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=rs(e,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===wi||this.right&&this.right.constructor===wi)this.parent=null;else if(this.parent){if(this.parent.constructor===Hr){const e=ts(t,this.parent);e.constructor===wi?this.parent=null:this.parent=e.content.type}}else this.left&&this.left.constructor===Fi?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===Fi&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);return null}integrate(e,t){if(t>0&&(this.id.clock+=t,this.left=ss(e,e.doc.store,zr(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(t),this.length-=t),this.parent){if(!this.left&&(!this.right||null!==this.right.left)||this.left&&this.left.right!==this.right){let t,n=this.left;if(null!==n)t=n.right;else if(null!==this.parentSub)for(t=this.parent._map.get(this.parentSub)||null;null!==t&&null!==t.left;)t=t.left;else t=this.parent._start;const r=new Set,s=new Set;for(;null!==t&&t!==this.right;){if(s.add(t),r.add(t),Jr(this.origin,t.origin)){if(t.id.client<this.id.client)n=t,r.clear();else if(Jr(this.rightOrigin,t.rightOrigin))break}else{if(null===t.origin||!s.has(ts(e.doc.store,t.origin)))break;r.has(ts(e.doc.store,t.origin))||(n=t,r.clear())}t=t.right}this.left=n}if(null!==this.left){const e=this.left.right;this.right=e,this.left.right=this}else{let e;if(null!==this.parentSub)for(e=this.parent._map.get(this.parentSub)||null;null!==e&&null!==e.left;)e=e.left;else e=this.parent._start,this.parent._start=this;this.right=e}null!==this.right?this.right.left=this:null!==this.parentSub&&(this.parent._map.set(this.parentSub,this),null!==this.left&&this.left.delete(e)),null===this.parentSub&&this.countable&&!this.deleted&&(this.parent._length+=this.length),Zr(e.doc.store,this),this.content.integrate(e,this),cs(e,this.parent,this.parentSub),(null!==this.parent._item&&this.parent._item.deleted||null!==this.parentSub&&null!==this.right)&&this.delete(e)}else new wi(this.id,this.length).integrate(e,0)}get next(){let e=this.right;for(;null!==e&&e.deleted;)e=e.right;return e}get prev(){let e=this.left;for(;null!==e&&e.deleted;)e=e.left;return e}get lastId(){return 1===this.length?this.id:zr(this.id.client,this.id.clock+this.length-1)}mergeWith(e){if(this.constructor===e.constructor&&Jr(e.origin,this.lastId)&&this.right===e&&Jr(this.rightOrigin,e.rightOrigin)&&this.id.client===e.id.client&&this.id.clock+this.length===e.id.clock&&this.deleted===e.deleted&&null===this.redone&&null===e.redone&&this.content.constructor===e.content.constructor&&this.content.mergeWith(e.content)){const t=this.parent._searchMarker;return t&&t.forEach((t=>{t.p===e&&(t.p=this,!this.deleted&&this.countable&&(t.index-=this.length))})),e.keep&&(this.keep=!0),this.right=e.right,null!==this.right&&(this.right.left=this),this.length+=e.length,!0}return!1}delete(e){if(!this.deleted){const t=this.parent;this.countable&&null===this.parentSub&&(t._length-=this.length),this.markDeleted(),Cr(e.deleteSet,this.id.client,this.id.clock,this.length),cs(e,t,this.parentSub),this.content.delete(e)}}gc(e,t){if(!this.deleted)throw _n();this.content.gc(e),t?((e,t,n)=>{const r=e.clients.get(t.id.client);r[es(r,t.id.clock)]=n})(e,this,new wi(this.id,this.length)):this.content=new ki(this.length)}write(e,t){const n=t>0?zr(this.id.client,this.id.clock+t-1):this.origin,r=this.rightOrigin,s=this.parentSub,i=31&this.content.getRef()|(null===n?0:Ft)|(null===r?0:Bt)|(null===s?0:32);if(e.writeInfo(i),null!==n&&e.writeLeftID(n),null!==r&&e.writeRightID(r),null===n&&null===r){const t=this.parent;if(void 0!==t._item){const n=t._item;if(null===n){const n=(e=>{for(const[t,n]of e.doc.share.entries())if(n===e)return t;throw _n()})(t);e.writeParentInfo(!0),e.writeString(n)}else e.writeParentInfo(!1),e.writeLeftID(n.id)}else t.constructor===String?(e.writeParentInfo(!0),e.writeString(t)):t.constructor===Hr?(e.writeParentInfo(!1),e.writeLeftID(t)):_n();null!==s&&e.writeString(s)}this.content.write(e,t)}}const Wi=(e,t)=>Vi[31&t](e),Vi=[()=>{_n()},e=>new ki(e.readLen()),e=>{const t=e.readLen(),n=[];for(let r=0;r<t;r++){const t=e.readString();"undefined"===t?n.push(void 0):n.push(JSON.parse(t))}return new Ii(n)},e=>new _i(e.readBuf()),e=>new Oi(e.readString()),e=>new xi(e.readJSON()),e=>new Ci(e.readKey(),e.readJSON()),e=>new Ni(Ti[e.readTypeRef()](e)),e=>{const t=e.readLen(),n=[];for(let r=0;r<t;r++)n.push(e.readAny());return new Di(n)},e=>new Ei(Si(e.readString(),e.readAny())),()=>{_n()}];class Ki extends bi{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor===e.constructor&&(this.length+=e.length,!0)}integrate(e,t){_n()}write(e,t){e.writeInfo(10),nn(e.restEncoder,this.length-t)}getMissing(e,t){return null}}const Hi="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{},Ji="__ $YJS$ __";function zi(e,t,n){var r,s,i;if(!e.dx._allTables[t])return;const o=null===(i=null===(s=null===(r=e.table(t))||void 0===r?void 0:r.schema.yProps)||void 0===s?void 0:s.find((e=>e.prop===n)))||void 0===i?void 0:i.updatesTable;return o&&e.dx._allTables[o]?e.table(o):void 0}Hi[Ji],Hi[Ji]=!0;const qi=new FinalizationRegistry((({cache:e,key:t})=>{delete e[t]}));function Yi(e){var t,n;return null!==(t=(n=e._novip)._docCache)&&void 0!==t?t:n._docCache={cache:{},get size(){return Object.keys(this.cache).length},find(e,t,n){const r=Xi(e,t,n),s=this.cache[r];return s?s.deref():void 0},add(e){var t;const{parentTable:n,parentId:r,parentProp:s}=e.meta;if(!n||!s||null==r)throw new Error("Missing Dexie-related metadata in Y.Doc");const i=Xi(n,r,s),o=null===(t=this.cache[i])||void 0===t?void 0:t.deref();o&&qi.unregister(o),this.cache[i]=new WeakRef(e),qi.register(e,{cache:this.cache,key:i},e)},delete(e){qi.unregister(e);const t=Xi(e.meta.parentTable,e.meta.parentId,e.meta.parentProp),n=this.cache[t];(null==n?void 0:n.deref())===e&&delete this.cache[t]}}}const Gi=new WeakSet;function Qi(e){if(Gi.has(e))throw new Error(`Y.Doc ${e.meta.parentId} has been destroyed`)}function Xi(e,t,n){return`${e}[${t}].${n}`}let Zi=null;function eo(e){Zi=e}function to(){}const no=new WeakMap;function ro(){return t.Dexie.Events(null,"load","sync","error")}class so{static getOrCreateDocument(e,t,n,r){var s,i;const o=Yi(e),l=null===(i=null===(s=e.table(t).schema.yProps)||void 0===s?void 0:s.find((e=>e.prop===n)))||void 0===i?void 0:i.updatesTable;if(!l)throw new Error(`Updates table for ${t}.${n} not found`);return function(e,t,n,r,s,i){let o=t.find(n,i,r);return o||(o=new Or({meta:{db:e,updatesTable:s,parentProp:r,parentTable:n,parentId:i}}),t.add(o),o.on("destroy",(()=>{Gi.add(o),t.delete(o)})),o)}(e,o,t,n,l,r)}static load(e,t){var n;let r=no.get(e);return r?(++r.refCount,null!=(null==t?void 0:t.gracePeriod)&&r.graceTimeout<t.gracePeriod&&(r.graceTimeout=t.gracePeriod),r.graceTimer&&(clearTimeout(r.graceTimer),r.graceTimer=null)):(r=new so(e),r.graceTimeout=null!==(n=null==t?void 0:t.gracePeriod)&&void 0!==n?n:-1,no.set(e,r)),r}static release(e){if(!e||Gi.has(e))return;const t=no.get(e);t?--t.refCount<=0&&(t.graceTimeout<0?t._release():t.graceTimer||(t.graceTimer=setTimeout((()=>{t.graceTimer=null,0===t.refCount&&t._release()}),t.graceTimeout))):e.destroy()}_release(){this.doc&&Promise.resolve(so.on("beforeunload").fire(this)).finally((()=>{var e;0===this.refCount&&(null===(e=this.doc)||void 0===e||e.destroy())}))}static for(e){return no.get(e)}static get currentUpdateRow(){return Zi}get whenLoaded(){return this._whenLoaded||(this._whenLoaded=new Promise(((e,n)=>{this.doc?this.doc.isLoaded?e():this._error?n(this._error):Gi.has(this.doc)?n(new t.Dexie.AbortError("Document was destroyed before loaded")):(this.on("load",e),this.on("error",n),this.doc.on("destroy",(()=>n(new t.Dexie.AbortError("Document was destroyed before loaded"))))):n(new Error("No Y.Doc associated with this provider"))}))),this._whenLoaded}get whenSynced(){return this._whenSynced||(this._whenSynced=new Promise(((e,n)=>{this.doc?this.doc.isSynced?e():this._error?n(this._error):Gi.has(this.doc)?n(new t.Dexie.AbortError("Document was destroyed before synced")):(this.on("sync",e),this.on("error",n),this.doc.on("destroy",(()=>n(new t.Dexie.AbortError("Document was destroyed before synced"))))):n(new Error("No Y.Doc associated with this provider"))}))),this._whenSynced}constructor(e){this.refCount=1,this.cleanupHandlers=[],this.graceTimeout=-1,this.doc=null,this.destroyed=!1,this.on=ro(),this.doc=e,this.off=(e,t)=>{var n;return null===(n=this.on[e])||void 0===n?void 0:n.unsubscribe(t)},"dispose"in Symbol&&(this[Symbol.dispose]=()=>so.release(e)),e.on("load",(()=>this.on("load").fire())),e.on("sync",(e=>!1!==e&&this.on("sync").fire())),e.on("destroy",this.destroy.bind(this)),this.on("error",(e=>{this._error=e}));const{db:n,parentTable:r,parentId:s,updatesTable:i}=e.meta||{};if(!n||!r||!i)throw new Error("Missing Dexie-related metadata in Y.Doc. Documents need to be obtained through Y.Doc properties from dexie queries.");if(!n.table(r)||!n.table(i))throw new Error(`Table ${r} or ${i} not found in db`);Qi(e),this.stopObserving=function(e,n,r,s,i,o){let l=0,c=!0;const a=t.liveQuery((()=>{Qi(n);const e=r.table(i);return Promise.all([(l>0?e.where("i").between(l,1/0,!1).toArray().then((e=>e.filter((e=>0===t.cmp(e.k,o))))):e.where({k:o}).toArray()).then((e=>e)),r.table(s).where(":id").equals(o).toArray()])})).subscribe((([t,r])=>{t.length>0&&(l=t[t.length-1].i),0!==r.length?(Qi(n),t.length>0&&ds(n,(()=>{t.forEach((e=>{try{eo(e),Nr(n,e.u)}finally{eo(null)}}))}),e,!1),c&&(c=!1,n.emit("load",[n]))):n.destroy()}),(t=>{e.on("error").fire(t)})),u=(t,n)=>{n!==e&&r.table(i).add({k:o,u:t,f:1}).then((e=>{e===l-1&&++l})).catch((t=>{e.on("error").fire(t)}))},d=()=>{a.unsubscribe(),n.off("updateV2",u),n.off("destroy",d)};return n.on("updateV2",u),n.on("destroy",d),d}(this,e,n,r,i,s),so.on("new").fire(this)}destroy(){var e;no.delete(this.doc),this.doc=null,this.destroyed=!0,this.refCount=0,null===(e=this.stopObserving)||void 0===e||e.call(this),this.on=ro(),this.cleanupHandlers.forEach((e=>e()))}addCleanupHandler(e){this.cleanupHandlers.push("function"==typeof e?e:()=>e.unsubscribe())}}function io(e,n){return s(this,void 0,void 0,(function*(){var r;const i={};let o,l=!1;for(const c of e)try{switch(c.type){case"u-s":{const e=zi(n,c.table,c.prop);if(e){const t={k:c.k,u:c.u};c.r&&(t.r=c.r,o=c.r),i[e.name]=yield e.add(t)}break}case"u-ack":{const e=zi(n,c.table,c.prop);e&&(yield n.transaction("rw",e,(t=>s(this,void 0,void 0,(function*(){let n=yield t.table(e.name).get(Et);yield t.table(e.name).put(Object.assign(Object.assign({},n||{i:Et}),{unsentFrom:Math.max((null==n?void 0:n.unsentFrom)||1,c.i+1)}))})))));break}case"u-reject":{const e=zi(n,c.table,c.prop);if(!e)break;const s=null===(r=yield e.get(c.i))||void 0===r?void 0:r.k;if(null!=s){yield n.transaction("rw",e,(n=>(n.idbtrans._rejecting_y_ypdate=!0,e.where("i").aboveOrEqual(c.i).filter((e=>0===t.cmp(e.k,s)&&1==(1&(e.f||0)))).delete())));const r=so.getDocCache(n.dx).find(c.table,s,c.prop);r&&r.destroy()}break}case"in-sync":{const e=so.getDocCache(n.dx).find(c.table,c.k,c.prop);e&&!e.isSynced&&e.emit("sync",[!0,e]);break}case"y-complete-sync-done":o=c.yServerRev;break;case"outdated-server-rev":l=!0}}catch(e){}return{receivedUntils:i,resyncNeeded:l,yServerRevision:o}}))}so.on=t.Dexie.Events(null,{new:[function(e,t){return e===to?t:function(){e.apply(this,arguments),t.apply(this,arguments)}}],beforeunload:[function(e,t){return e===to?t:function(){var n=e.apply(this,arguments);if(n&&"function"==typeof n.then){for(var r=this,s=arguments.length,i=new Array(s);s--;)i[s]=arguments[s];return n.then((function(){return t.apply(r,i)}))}return t.apply(this,arguments)}}]}),so.getDocCache=Yi,t.Dexie.DexieYProvider?so=t.Dexie.DexieYProvider||so:t.Dexie.DexieYProvider=so;const oo=1,lo=2,co=3;function ao(e,n,r){return s(this,arguments,void 0,(function*(e,n,{yDownloadedRealms:r,realms:i}){if(r&&i&&i.every((e=>"*"===r[e])))return;const a=yield he(e),u={"Content-Type":"application/json",Accept:"application/octet-stream"};a&&(u.Authorization=`Bearer ${a.accessToken}`);const d=yield fetch(`${n}/y/download`,{body:dt.stringify({downloadedRealms:r||{}}),method:"POST",headers:u,credentials:"include"});if(!d.ok)throw new Error(`Failed to download Yjs documents from server. Status: ${d.status}`);yield async function(e,...t){var n,r,s;let i=e();for(let e=0;e<t.length;e++)i=t[e](i);try{for(var o,l=!0,a=c(i);!(n=(o=await a.next()).done);l=!0)o.value,l=!1}catch(e){r={error:e}}finally{try{l||n||!(s=a.return)||await s.call(a)}finally{if(r)throw r.error}}}(function(e){return function(){return l(this,arguments,(function*(){if(!e.body)throw new Error("Response body is not readable");const t=e.body.getReader();try{for(;;){const{done:e,value:n}=yield o(t.read());if(e)return yield o(void 0);yield yield o(n)}}finally{t.releaseLock()}}))}}(d),Z,(function(r){return l(this,arguments,(function*(){var i,l,a,u;let d=null,h=null,f=null,p=[];function g(t){return s(this,void 0,void 0,(function*(){const r=p[p.length-1];if(p.length>0){if(!d||!h||!f)throw new Error(`Protocol error from ${n}/y/download`);const t=zi(e,h,f);t&&(yield t.bulkAdd(p)),p=[]}d&&(h&&f&&r||t)&&(yield e.$syncState.update("syncState",(e=>{const n=e.yDownloadedRealms||{};n[d]=t?"*":{tbl:h,prop:f,key:r.k},e.yDownloadedRealms=n})))}))}try{try{for(var y,m=!0,v=c(r);!(i=(y=yield o(v.next())).done);m=!0){u=y.value,m=!1;const e=new V(u);for(;K(e);)switch(J(e)){case oo:yield o(g(!0)),d=q(e);break;case lo:yield o(g(!1)),h=q(e),f=q(e);break;case co:{const t=X(e),n=H(e);p.push({k:t,u:n});break}}yield o(g(!1))}}catch(e){l={error:e}}finally{try{m||i||!(a=v.return)||(yield o(a.call(v)))}finally{if(l)throw l.error}}yield o(g(!0))}catch(e){throw e instanceof t.DexieError||(yield o(g(!1))),e}}))}))}))}const uo="currentSyncWorker";function ho(e,t,n,r){return fo(e,t,n,r).then((t=>((null==r?void 0:r.justCheckIfNeeded)||e.syncStateChangedEvent.next({phase:"in-sync"}),t))).catch((i=>s(this,void 0,void 0,(function*(){return(null==r?void 0:r.justCheckIfNeeded)?Promise.reject(i):bt&&(null==r?void 0:r.retryImmediatelyOnFetchError)&&"TypeError"===(null==i?void 0:i.name)&&/fetch/.test(null==i?void 0:i.message)?(e.syncStateChangedEvent.next({phase:"error",error:i}),yield new Promise((e=>setTimeout(e,500))),yield ho(e,t,n,Object.assign(Object.assign({},r),{retryImmediatelyOnFetchError:!1}))):(yield e.$syncState.update("syncState",{timestamp:new Date,error:""+i}),e.syncStateChangedEvent.next({phase:bt?"error":"offline",error:new Error(""+(null==i?void 0:i.message)||i)}),Promise.reject(i))}))))}function fo(e,t,n){return s(this,arguments,void 0,(function*(e,t,n,{isInitialSync:r,cancelToken:i,justCheckIfNeeded:o,purpose:l}={isInitialSync:!1}){var c;if(!(null===(c=e.cloud.options)||void 0===c?void 0:c.databaseUrl))throw new Error("Internal error: sync must not be called when no databaseUrl is configured");const{databaseUrl:a}=t,u=yield e.getCurrentUser(),h=u.isLoggedIn?Oe(e):[],p=h.map((t=>e.table(Te(t.name)))),g=yield e.getPersistedSyncState(),y=u.isLoggedIn,m=y?function(e,t){const n=(null==t?void 0:t.syncedTables)||[];return Oe(e).filter((e=>!n.includes(e.name)))}(e,g):[];vt(i);const v=m.length>0;if(v){if(o)return!0;yield e.transaction("rw",m,(e=>s(this,void 0,void 0,(function*(){e.idbtrans.disableChangeTracking=!0,e.idbtrans.disableAccessControl=!0,yield function(e,t,n){return s(this,void 0,void 0,(function*(){const r=new Set(n||[]);for(const n of e)"members"===n.name?yield n.toCollection().modify((e=>{r.has(e.realmId)||e.userId&&e.userId!==me.userId||(e.userId=t.userId)})):"roles"===n.name||("realms"===n.name?yield n.toCollection().modify((e=>{r.has(e.realmId)||void 0!==e.owner&&e.owner!==me.userId||(e.owner=t.userId)})):yield n.toCollection().modify((e=>{e.realmId&&r.has(e.realmId)||(e.owner&&e.owner!==me.userId||(e.owner=t.userId),e.realmId&&e.realmId!==me.userId||(e.realmId=t.userId))})))}))}(m,u,null==g?void 0:g.realms)})))),vt(i)}const[b,w,_,{yMessages:k,lastUpdateIds:S}]=yield e.transaction("r",e.tables,(()=>s(this,void 0,void 0,(function*(){const t=yield e.getPersistedSyncState();let r=yield e.$baseRevs.toArray();r=r.filter((e=>h.some((t=>t.name===e.tableName))));let o=yield Pe(p,e);const l=yield function(e,t){return s(this,void 0,void 0,(function*(){const n=[],r={};for(const s of t)if(s.schema.yProps)for(const t of s.schema.yProps){const i=e.table(t.updatesTable),o=yield i.get(Et),l=(null==o?void 0:o.unsentFrom)||1,c=(null==o?void 0:o.receivedUntil)||0,a=Math.min(l,c+1),u=yield xt(i,a);u.length>0&&(r[i.name]=u[u.length-1].i);const d={};for(const e of u){const t=1==(1&(e.f||0));if(t&&e.i<l)continue;const n=JSON.stringify(e.k)+"/"+t;let r=d[n];r?(r.u.push(e.u),r.i=Math.max(e.i,r.i)):(d[n]=r={i:e.i,k:e.k,isLocal:t,u:[]},r.u.push(e.u))}for(const{k:e,isLocal:r,u:i,i:o}of Object.values(d)){const l=1===i.length?i[0]:ys(i);if(r)n.push({type:"u-c",table:s.name,prop:t.prop,k:e,u:l,i:o});else{const r=ps(l);n.push({type:"sv",table:s.name,prop:t.prop,k:e,sv:r})}}}return{yMessages:n,lastUpdateIds:r}}))}(e,h);if(vt(i),v){const e=[...(null==g?void 0:g.realms)||[],...(null==g?void 0:g.inviteRealms)||[]],c=yield function(e,t,n,r){return s(this,void 0,void 0,(function*(){const i=`upload-${Re(8)}`;if(t.isLoggedIn&&e.length>0){const o=new Set(r||[]);return(yield Promise.all(e.map((e=>s(this,void 0,void 0,(function*(){const{extractKey:r}=e.core.schema.primaryKey;if(!r)return{table:e.name,muts:[]};const s=n[e.name],l=(null==s?void 0:s.generatedGlobalId)?e.filter((e=>{return r(e),!o.has(e.realmId||"")&&(t=r(e),!(n=null==s?void 0:s.idPrefix)||"string"==typeof t&&t.startsWith(n));var t,n})):e.filter((e=>{const t=r(e);return!o.has(e.realmId||"")&&f(t)})),c=yield l.toArray();if(c.length>0){const n={type:"upsert",values:c,keys:c.map(r),userId:t.userId,txid:i};return{table:e.name,muts:[n]}}return{table:e.name,muts:[]}})))))).filter((e=>e.muts.length>0))}return[]}))}(m,u,n,e);return vt(i),o=o.concat(c),[o,t,r,l]}return[o,t,r,l]})))),E=b.some((e=>e.muts.some((e=>e.keys.length>0))))||k.some((e=>"u-c"===e.type));if(o)return E;if("push"===l&&!E)return!1;const x=_t(b,null==w?void 0:w.latestRevisions),C=(null==w?void 0:w.clientIdentity)||d(16);vt(i);const I=yield mt(b,k,w,_,e,a,n,C,u),{done:A,newSyncState:D}=yield e.transaction("rw",e.tables,(t=>s(this,void 0,void 0,(function*(){t.idbtrans.disableChangeTracking=!0,t.idbtrans.disableAccessControl=!0;for(const e of Object.keys(n))I.schema[e]&&(n[e]=I.schema[e]);yield e.$syncState.put(n,"schema");const r=yield Pe(p,e,{since:x});for(const t of p){const n=Ue(t.name);if(r.some((e=>e.table===n&&e.muts.length>0))){if(x[n]){const r=x[n]||0;yield Promise.all([t.where("rev").belowOrEqual(r).delete(),e.$baseRevs.where(":id").between([n,-1/0],[n,r+1],!0,!0).reverse().offset(1).delete()])}}else yield Promise.all([t.clear(),e.$baseRevs.where({tableName:n}).delete()])}_t(r,x),yield wt(e,n,x,I.serverRevision);const i=yield e.getPersistedSyncState();yield function(e,t,n){return s(this,void 0,void 0,(function*(){const r=new Set,s=new Set,i=n?n.realms:[],o=n?n.inviteRealms:[],l=new Set(t.realms),c=new Set(t.realms.concat(t.inviteRealms));for(const e of i)l.has(e)||(s.add(e),c.has(e)||r.add(e));for(const e of o.concat(i))c.has(e)||r.add(e);if(r.size>0||s.size>0){const t=Oe(e);for(const e of t){let t=["realms","members","roles"].includes(e.name)?r:s;0!==t.size&&(e.schema.indexes.some((e=>"realmId"===e.keyPath||Array.isArray(e.keyPath)&&"realmId"===e.keyPath[0]))?yield e.where("realmId").anyOf([...t]).delete():yield e.filter((e=>!!(null==e?void 0:e.realmId)&&t.has(e.realmId))).delete())}}if(s.size>0&&(null==n?void 0:n.yDownloadedRealms))for(const e of s)delete n.yDownloadedRealms[e]}))}(e,I,i);const o=i||{syncedTables:[],latestRevisions:{},realms:[],inviteRealms:[],clientIdentity:C};y&&(o.syncedTables=h.map((e=>e.name)).concat(m.map((e=>e.name)))),o.latestRevisions=x,o.remoteDbId=I.dbId,o.initiallySynced=!0,o.realms=I.realms,o.inviteRealms=I.inviteRealms,o.serverRevision=I.serverRevision,o.yServerRevision=I.serverRevision,o.timestamp=new Date,delete o.error;const l=po(I.changes,r);if(yield St(l,e),I.yMessages){const{receivedUntils:t,resyncNeeded:n,yServerRevision:r}=yield io(I.yMessages,e);r&&(o.yServerRevision=r),yield function(e,t,n){return s(this,void 0,void 0,(function*(){var r,i,o,l,c;const a={};for(const[t,n]of Object.entries(e))null!==(r=a[t])&&void 0!==r||(a[t]={}),a[t].unsentFrom=n+1;for(const[e,n]of Object.entries(t))null!==(i=a[e])&&void 0!==i||(a[e]={}),a[e].receivedUntil=n;const u=Object.values(n.dx._dbSchema).filter((e=>e.yProps)).map((e=>e.yProps.map((e=>e.updatesTable)))).flat();for(const e of u){const t=a[e],r=null!==(o=null==t?void 0:t.unsentFrom)&&void 0!==o?o:1,i=null!==(c=null!==(l=null==t?void 0:t.receivedUntil)&&void 0!==l?l:(yield n.table(e).where("i").between(1,1/0).reverse().limit(1).primaryKeys())[0])&&void 0!==c?c:0;yield n.transaction("rw",e,(()=>s(this,void 0,void 0,(function*(){const t=yield n.table(e).get(Et);t?(t.unsentFrom=Math.max(r,t.unsentFrom||1),t.receivedUntil=Math.max(i,t.receivedUntil||0),yield n.table(e).put(t)):yield n.table(e).add({i:Et,unsentFrom:r,receivedUntil:i})}))))}}))}(S,t,e),n&&(o.yDownloadedRealms={})}return e.$syncState.put(o,"syncState"),{done:0===r.length,newSyncState:o}}))));if(!A)return yield yt(e),yield fo(e,t,n,{isInitialSync:r,cancelToken:i});const O=Object.values(n).some((e=>{var t;return null===(t=e.yProps)||void 0===t?void 0:t.length})),T=!!I.yMessages;if(O&&T)try{yield ao(e,a,D)}catch(e){}return e.syncCompleteEvent.next(),!1}))}function po(e,t){const n={};y(n,e);const r={};return y(r,t),function(e,t){var n,r,s;for(const[i,o]of Object.entries(t))for(const[t,l]of Object.entries(o))switch(l.type){case"ups":{const r=null===(n=e[i])||void 0===n?void 0:n[t];if(r)switch(r.type){case"ups":case"upd":delete e[i][t]}}break;case"del":null===(r=e[i])||void 0===r||delete r[t];break;case"upd":{const n=null===(s=e[i])||void 0===s?void 0:s[t];if(n)switch(n.type){case"ups":for(const[e,t]of Object.entries(l.mod))u(n.val,e,t);break;case"del":break;case"upd":for(const e of Object.keys(l.mod))delete n.mod[e]}break}}}(n,r),function(e,t=""){t||(t=d(16));const n={};for(const[t,r]of Object.entries(e))for(const[e,s]of Object.entries(r)){const r=n[t]||(n[t]={});(r[s.type]||(r[s.type]=[])).push(Object.assign({key:e},s))}const r=[];for(const[e,s]of Object.entries(n)){const n={table:e,muts:[]};for(const[e,r]of Object.entries(s))switch(e){case"ups":{const e={type:"upsert",keys:r.map((e=>e.key)),values:r.map((e=>e.val)),txid:t};n.muts.push(e);break}case"upd":{const e={type:"update",keys:r.map((e=>e.key)),changeSpecs:r.map((e=>e.mod)),txid:t};n.muts.push(e);break}case"del":{const e={type:"delete",keys:r.map((e=>e.key)),txid:t};n.muts.push(e);break}}r.push(n)}return r}(n)}const go=10,yo=1e4,mo=1e3;function vo(e){const i=[],o=new n.BehaviorSubject(!0),l=new n.BehaviorSubject(null);let c=!1,a=new Array(go).fill(0);return l.subscribe((()=>s(this,void 0,void 0,(function*(){if(!c&&i.length>0){c=!0,a.shift(),a.push(Date.now()),o.next(!1);try{yield function(){return s(this,void 0,void 0,(function*(){for(var o,l,c,a,u,d;i.length>0;){const h=i.shift();try{yield n.firstValueFrom(e.cloud.syncState.pipe(r.filter((({phase:e})=>"in-sync"===e||"error"===e))));const i=e.cloud.persistedSyncState.value;if(!h)continue;switch(h.type){case"token-expired":const n=e.cloud.currentUser.value,r=yield pe(e.cloud.options.databaseUrl,n);yield e.table("$logins").update(n.userId,{accessToken:r.accessToken,accessTokenExpiration:r.accessTokenExpiration,claims:r.claims,license:r.license,data:r.data});break;case"realm-added":(null===(o=null==i?void 0:i.realms)||void 0===o?void 0:o.includes(h.realm))||(null===(l=null==i?void 0:i.inviteRealms)||void 0===l?void 0:l.includes(h.realm))||(yield e.cloud.sync({purpose:"pull",wait:!0}));break;case"realm-accepted":(null===(c=null==i?void 0:i.realms)||void 0===c?void 0:c.includes(h.realm))||(yield e.cloud.sync({purpose:"pull",wait:!0}));break;case"realm-removed":((null===(a=null==i?void 0:i.realms)||void 0===a?void 0:a.includes(h.realm))||(null===(u=null==i?void 0:i.inviteRealms)||void 0===u?void 0:u.includes(h.realm)))&&(yield e.cloud.sync({purpose:"pull",wait:!0}));break;case"realms-changed":yield e.cloud.sync({purpose:"pull",wait:!0});break;case"changes":if("error"===(null===(d=e.cloud.syncState.value)||void 0===d?void 0:d.phase)){ne(e,"pull");break}yield e.transaction("rw",e.dx.tables,(n=>s(this,void 0,void 0,(function*(){n.idbtrans.disableChangeTracking=!0,n.idbtrans.disableAccessControl=!0;const[r,s,i]=yield Promise.all([e.getSchema(),e.getPersistedSyncState(),e.getCurrentUser()]);if(!s||!r||!i)return;if(h.baseRev!==s.serverRevision)return void("string"!=typeof h.baseRev||"bigint"!=typeof s.serverRevision&&"object"!=typeof s.serverRevision||ne(e,"pull"));if((yield t.waitFor(De(s)))!==h.realmSetHash)return void ne(e,"pull");let o=[];if(i.isLoggedIn){const t=Oe(e).map((t=>e.table(Te(t.name))));o=yield Pe(t,e)}if(h.changes.length>0){const t=po(h.changes,o);yield St(t,e)}s.latestRevisions=_t(o,s.latestRevisions),s.serverRevision=h.newRev,yield wt(e,r,s.latestRevisions,h.newRev),yield e.$syncState.put(s,"syncState")}))))}}catch(e){}}}))}()}finally{a[a.length-1]-a[0]<yo&&(yield new Promise((e=>setTimeout(e,mo)))),c=!1,o.next(!0)}}})))),{enqueue:function(e){i.push(e),l.next(null)},readyToServe:o}}const bo=new WeakMap,wo={members:"@id, [userId+realmId], [email+realmId], realmId",roles:"[realmId+name]",realms:"@realmId",$jobs:"",$syncState:"",$baseRevs:"[tableName+clientRev]",$logins:"claims.sub, lastLogin"};let _o=0;function ko(e){"vip"in e&&(e=e.vip);let t=bo.get(e.cloud);if(!t){const r=new n.Subject;let s=new Ae(`syncstatechanged-${e.name}`),i=new Ae(`synccomplete-${e.name}`);r.id=++_o;let o=!1;t={get name(){return e.name},close:()=>e.close(),transaction:e.transaction.bind(e),table:e.table.bind(e),get tables(){return e.tables},cloud:e.cloud,get $jobs(){return e.table("$jobs")},get $syncState(){return e.table("$syncState")},get $baseRevs(){return e.table("$baseRevs")},get $logins(){return e.table("$logins")},get realms(){return e.realms},get members(){return e.members},get roles(){return e.roles},get initiallySynced(){return o},localSyncEvent:r,get syncStateChangedEvent(){return s},get syncCompleteEvent(){return i},dx:e};const l={getCurrentUser:()=>t.$logins.toArray().then((e=>e.find((e=>e.isLoggedIn))||me)),getPersistedSyncState:()=>t.$syncState.get("syncState"),getSchema:()=>t.$syncState.get("schema").then((e=>{if(e)for(const r of t.tables)r.schema.primKey&&r.schema.primKey.keyPath&&e[r.name]&&(e[r.name].primaryKey="string"==typeof(n=r.schema.primKey.keyPath)?n:n?"["+[].join.call(n,"+")+"]":"");var n;return e})),getOptions:()=>t.$syncState.get("options"),setInitiallySynced(e){o=e},reconfigure(){s=new Ae(`syncstatechanged-${e.name}`),i=new Ae(`synccomplete-${e.name}`)}};Object.assign(t,l),t.messageConsumer=vo(t),t.messageProducer=new n.Subject,bo.set(e.cloud,t)}return t}const So="undefined"!=typeof InstallTrigger,Eo="undefined"!=typeof navigator&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\/|Edge\//.test(navigator.userAgent),xo=Eo?[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]:NaN,Co=Eo&&xo<=605||So,Io="undefined"!=typeof self&&"clients"in self&&!self.document;const{toString:Ao}={};function Do(e){return Ao.call(e).slice(8,-1)}function Oo(e,t){var n;return"delete"===t.type?t.keys:(null===(n=t.keys)||void 0===n?void 0:n.slice())||t.values.map(e.extractKey)}const To=/b|c|d|f|g|h|j|k|l|m|n|p|q|r|s|t|v|x|y|z/i;let Uo=0;function jo(e,t){const n=new Uint8Array(18),r=new Uint8Array(n.buffer,0,6),s=Date.now();Uo>=s?++Uo:Uo=s,r[0]=Uo/1099511627776,r[1]=Uo/4294967296,r[2]=Uo/16777216,r[3]=Uo/65536,r[4]=Uo/256,r[5]=Uo;const i=new Uint8Array(n.buffer,6);crypto.getRandomValues(i);return e+qe(new Uint8Array(n.buffer))+(t||"")}function Lo(e){return{stack:"dbcore",name:"idGenerationMiddleware",level:1,create:n=>Object.assign(Object.assign({},n),{table:r=>{const s=n.table(r);return Object.assign(Object.assign({},s),{mutate:n=>{var i,o;const l=n.trans;if("versionchange"===l.mode&&(l.disableChangeTracking=!0,l.disableAccessControl=!0),l.disableChangeTracking)return s.mutate(n);if("add"===n.type||"put"===n.type){const l=null===(i=e.cloud.schema)||void 0===i?void 0:i[r];if(null==l?void 0:l.generatedGlobalId){if((null===(o=e.cloud.options)||void 0===o?void 0:o.databaseUrl)&&!e.initiallySynced){const e=Oo(s.schema.primaryKey,n);return s.getMany({keys:e,trans:n.trans,cache:"immutable"}).then((t=>{if(t.length<e.length)throw new Error("Unable to create new objects without an initial sync having been performed.");return s.mutate(n)}))}return function(n,i){let o=null;const l=Oo(s.schema.primaryKey,n);return l.forEach(((c,a)=>{if(void 0===c){const r=n.values[a].realmId||e.cloud.currentUserId,c=r.substr(r.length-3);l[a]=jo(i,c),s.schema.primaryKey.outbound||(o||(o=n.values.slice()),o[a]=t.deepClone(o[a]),t.setByKeyPath(o[a],s.schema.primaryKey.keyPath,l[a]))}else if("string"!=typeof c||!c.startsWith(i)&&!c.startsWith("#"+i))throw new t.ConstraintError(`The ID "${c}" is not valid for table "${r}". Primary '@' keys requires the key to be prefixed with "${i}" (or "#${i}).\nIf you want to generate IDs programmatically, remove '@' from the schema to get rid of this constraint. Dexie Cloud supports custom IDs as long as they are random and globally unique.`)})),s.mutate(Object.assign(Object.assign({},n),{keys:l,values:o||n.values}))}(n,l.idPrefix)}if(null==l?void 0:l.markedForSync){Oo(s.schema.primaryKey,n).forEach(((e,n)=>{if(!f(e)){const n=Array.isArray(e)?e.map(Do).join(","):Do(e);throw new t.ConstraintError(`Invalid primary key type ${n} for table ${r}. Tables marked for sync has primary keys of type string or Array of string (and optional numbers)`)}}))}}return s.mutate(n)}})}})}}let Po=0;function Ro(e,t){return function(n){const{readers:r,writers:s}=n.trans[t]||(n.trans[t]={writers:[],readers:[]}),i=s.length,o=(i>0?s[i-1].then((()=>e(n)),(()=>e(n))):e(n)).finally((()=>{r.splice(r.indexOf(o))}));return r.push(o),o}}function Mo(e,t){return function(n){const{readers:r,writers:s}=n.trans[t]||(n.trans[t]={writers:[],readers:[]});let i=(s.length>0?s[s.length-1].then((()=>e(n)),(()=>e(n))):r.length>0?(o=r,new Promise((e=>{0===o.length&&e([]);let t=o.length;const n=new Array(t);o.forEach(((r,s)=>Promise.resolve(r).then((e=>n[s]={status:"fulfilled",value:e}),(e=>n[s]={status:"rejected",reason:e})).then((()=>--t||e(n)))))}))).then((()=>e(n))):e(n)).finally((()=>{s.shift()}));var o;return s.push(i),i}}const $o=new n.BehaviorSubject(new Set);function No(e){var t,n,r,s;return(null===(t=e.cloud.options)||void 0===t?void 0:t.disableEagerSync)||"ok"!==(null===(r=null===(n=e.cloud.currentUser.value)||void 0===n?void 0:n.license)||void 0===r?void 0:r.status)||!(null===(s=e.cloud.options)||void 0===s?void 0:s.databaseUrl)}function Bo({currentUserObservable:e,db:n}){return{stack:"dbcore",name:"MutationTrackingMiddleware",level:1,create:r=>{const s=new Set(r.schema.tables.map((e=>e.name))),i=r.schema.tables.filter((e=>!/^\$/.test(e.name))),o=new Map;for(const e of i){const t=`$${e.name}_mutations`;s.has(t)&&o.set(e.name,r.table(t))}return Object.assign(Object.assign({},r),{transaction:(t,s)=>{let i;if("readwrite"===s){const e=t.filter((e=>{var t,r;return null===(r=null===(t=n.cloud.schema)||void 0===t?void 0:t[e])||void 0===r?void 0:r.markedForSync})).map((e=>Te(e)));i=r.transaction([...t,...e],s)}else i=r.transaction(t,s);if("readwrite"===s){i.txid=Re(16),i.opCount=0,i.currentUser=e.value,$o.value.add(i),$o.next($o.value);const t=()=>{i.removeEventListener("complete",r),i.removeEventListener("error",t),i.removeEventListener("abort",t),$o.value.delete(i),$o.next($o.value)},r=()=>{i.mutationsAdded&&!No(n)&&ne(n,"push"),t()};i.addEventListener("complete",r),i.addEventListener("error",t),i.addEventListener("abort",t)}return i},table:e=>{const s=r.table(e);if(/^\$/.test(e))return e.endsWith("_mutations")?Object.assign(Object.assign({},s),{mutate:e=>("add"!==e.type&&"put"!==e.type||(e.trans.mutationsAdded=!0),s.mutate(e))}):"$logins"===e?Object.assign(Object.assign({},s),{mutate:e=>s.mutate(e).then((t=>(e.trans.mutationsAdded=!0,t))).catch((e=>Promise.reject(e)))}):s;const{schema:i}=s,l=o.get(e);return l?function(e){const t="$lock"+ ++Po;return Object.assign(Object.assign({},e),{count:Ro(e.count,t),get:Ro(e.get,t),getMany:Ro(e.getMany,t),openCursor:Ro(e.openCursor,t),query:Ro(e.query,t),mutate:Mo(e.mutate,t)})}(Object.assign(Object.assign({},s),{mutate:t=>{var r,o,l;const a=t.trans;return a.txid?a.disableChangeTracking?s.mutate(t):(null===(o=null===(r=n.cloud.schema)||void 0===r?void 0:r[e])||void 0===o?void 0:o.markedForSync)&&(null===(l=a.currentUser)||void 0===l?void 0:l.isLoggedIn)?"deleteRange"===t.type?s.query({query:{range:t.range,index:i.primaryKey},trans:t.trans,values:!1}).then((e=>c({type:"delete",keys:e.result,trans:t.trans,criteria:{index:null,range:t.range}}))):c(t):s.mutate(t):s.mutate(t)}})):s;function c(r){var o,c;const a=r.trans,u=null===(c=null===(o=n.cloud.options)||void 0===o?void 0:o.unsyncedProperties)||void 0===c?void 0:c[e],{txid:d,currentUser:{userId:h}}=a,{type:f}=r,p=++a.opCount;function g(e){if(!u)return e;let t=e;for(const n of Object.keys(e))u.some((e=>n===e||n.startsWith(e+".")))&&(t===e&&(t=Object.assign({},e)),delete t[n]);return t}return s.mutate(r).then((e=>{var n;const{numFailures:s,failures:o}=e;let c="delete"===f?r.keys:e.results,y="values"in r?r.values:[],m="changeSpec"in r?r.changeSpec:void 0,v="updates"in r?r.updates:void 0;if(s&&(c=c.filter(((e,t)=>!o[t])),y=y.filter(((e,t)=>!o[t]))),u){if(y=y.map((e=>{const t=Object.assign({},e);for(const e of u)delete t[e];return t})),m&&(m=g(m),0===Object.keys(m).length))return e;if(v){let e=v.changeSpecs.map(g),n={keys:[],changeSpecs:[]};const r=new t.RangeSet;let s=!1;for(let t=0,i=e.length;t<i;++t)Object.keys(e[t]).length>0?(n.keys.push(v.keys[t]),n.changeSpecs.push(e[t]),r.addKey(v.keys[t])):s=!0;if(v=n,s){let e=[],t=[];for(let n=0,s=c.length;n<s;++n)r.hasKey(c[n])&&(e.push(c[n]),t.push(y[n]));c=e,y=t}}}const b=Date.now();let w="criteria"in r&&r.criteria?Object.assign(Object.assign({},r.criteria),{index:r.criteria.index===i.primaryKey.keyPath?null:r.criteria.index}):void 0;if(u&&(null==w?void 0:w.index)){const e=null===(n=i.indexes.find((e=>e.name===w.index)))||void 0===n?void 0:n.keyPath;(e?"string"==typeof e?[e]:e:[]).some((e=>null==u?void 0:u.includes(e)))&&(w=void 0)}const _="delete"===r.type?{type:"delete",ts:b,opNo:p,keys:c,criteria:w,txid:d,userId:h}:"add"===r.type?{type:"insert",ts:b,opNo:p,keys:c,txid:d,userId:h,values:y}:w&&m?{type:"modify",ts:b,opNo:p,keys:c,criteria:w,changeSpec:m,txid:d,userId:h}:m?{type:"update",ts:b,opNo:p,keys:c,changeSpecs:c.map((()=>m)),txid:d,userId:h}:v?{type:"update",ts:b,opNo:p,keys:v.keys,changeSpecs:v.changeSpecs,txid:d,userId:h}:{type:"upsert",ts:b,opNo:p,keys:c,values:y,txid:d,userId:h};return"isAdditionalChunk"in r&&r.isAdditionalChunk&&(_.isAdditionalChunk=!0),c.length>0||w?l.mutate({type:"add",trans:a,values:[_]}).then((()=>(a.mutationsAdded=!0,e))):e}))}}})}}}function Fo(e,t){return function(n,r){var s;const i=Object.assign(Object.assign({},wo),n);Object.keys(wo).forEach((e=>{const t=i[e];if(null==t)throw new Error(`Cannot delete table ${e} as it is needed for access control of Dexie Cloud`);if(!n[e])return;const r=t.split(",").map((e=>e.trim())),s=wo[e].split(",").map((e=>e.trim())),o=new Set(r.map((e=>e.replace(/([&*]|\+\+)/g,""))));if(r[0]!==s[0])throw new Error(`Cannot override primary key of table ${e}. Please declare it as {${e}: ${JSON.stringify(wo[e])}`);for(let t=1;t<s.length;++t){const n=s[t];o.has(n.replace(/([&*]|\+\+)/g,""))||(i[e]+=`,${n}`)}}));const o=t.cloud.schema||(t.cloud.schema={}),l=new Set;Object.keys(i).forEach((e=>{const t=i[e],n=o[e]||(o[e]={});null!=t?(/^\@/.test(t)&&(i[e]=i[e].substr(1),n.generatedGlobalId=!0,n.idPrefix=function(e,t){let n=e[0].toLocaleLowerCase();for(let t=1,s=e.length;t<s&&n.length<3;++t)(To.test(e[t])||(r=e[t])>="A"&&r<="Z")&&(n+=e[t].toLowerCase());for(var r,s,i;t.has(n);){if(/\d/g.test(n)){if(n=n.substr(0,n.length-1)+(n[n.length-1]+1),!(n.length>3))continue;n=n.substr(0,3)}else if(n.length<3){n+="2";continue}let e=1,r=n;for(;t.has(r)&&e<8;)s=n,r=(1&(i=e)?s[0].toUpperCase():s[0].toLowerCase())+(2&i?s[1].toUpperCase():s[1].toLowerCase())+(4&i?s[2].toUpperCase():s[2].toLowerCase()),++e;if(e<8)n=r;else{let e=n.charCodeAt(2)+1&127;n=n.substr(0,2)+String.fromCharCode(e)}}return n}(e,l),l.add(n.idPrefix)),/^\$/.test(e)||(i[`$${e}_mutations`]="++rev",n.markedForSync=!0),n.deleted&&(n.deleted=!1)):(n.deleted=!0,n.markedForSync=!1,i[`$${e}_mutations`]=null)}));const c=e.call(this,i,r);for(const[e,t]of Object.entries(r))if(null===(s=t.yProps)||void 0===s?void 0:s.length){const n=o[e];n&&(n.yProps=t.yProps.map((e=>e.prop)))}return c}}function Wo(e,t,n){return"undefined"!=typeof navigator&&navigator.locks?navigator.locks.request(e.name+"|"+t,(()=>n())):n()}const Vo=new n.BehaviorSubject(!0),Ko=new n.BehaviorSubject(!0);Vo.pipe(r.switchMap((e=>e?n.of(!0):n.of(!1).pipe(r.delay(2e4)))),r.distinctUntilChanged()).subscribe(Ko);const Ho="undefined"!=typeof document?n.fromEvent(document,"visibilitychange"):n.of({}),Jo=Ho.pipe(r.filter((()=>"hidden"===document.visibilityState))),zo=Ho.pipe(r.filter((()=>"visible"===document.visibilityState))),qo="undefined"!=typeof window?n.merge(zo,n.fromEvent(window,"mousedown"),n.fromEvent(window,"mousemove"),n.fromEvent(window,"keydown"),n.fromEvent(window,"wheel"),n.fromEvent(window,"touchmove")):n.of({});"undefined"!=typeof document&&n.merge(n.of(!0),Jo,qo).pipe(r.map((()=>"visible"===document.visibilityState)),r.tap((e=>{Vo.value!==e&&Vo.next(e)})),r.switchMap((e=>e?n.of(0).pipe(r.delay(16e4),r.tap((()=>Vo.next(!1)))):n.of(0)))).subscribe((()=>{}));class Yo extends Error{constructor(){super(...arguments),this.name="TokenExpiredError"}}function Go(e){var n,r;if(!(null===(n=e.cloud.options)||void 0===n?void 0:n.awarenessProtocol))throw new t.MissingAPIError('awarenessProtocol was not provided to db.cloud.configure(). Please import * as awarenessProtocol from "y-protocols/awareness".');return null===(r=e.cloud.options)||void 0===r?void 0:r.awarenessProtocol}const Qo=new WeakMap,Xo=new WeakMap;function Zo(e){let t=Xo.get(e);return t||(t=new n.Subject,Xo.set(e,t)),t}class el extends n.Observable{constructor(e,t,n,r,s,i,o,l){super((c=>new nl(e,t,n,r,s,l,c,i,o)))}}let tl=0;class nl extends n.Subscription{constructor(e,t,n,r,s,i,o,l,c){super((()=>this.teardown())),this.id=++tl,this.subscriptions=new Set,this.reconnecting=!1,this.db=e,this.databaseUrl=e.cloud.options.databaseUrl,this.rev=t,this.yrev=n,this.realmSetHash=r,this.clientIdentity=s,this.user=i,this.subscriber=o,this.lastUserActivity=new Date,this.messageProducer=l,this.webSocketStatus=c,this.connect()}teardown(){this.disconnect()}disconnect(){if(this.webSocketStatus.next("disconnected"),this.pinger&&(clearInterval(this.pinger),this.pinger=null),this.ws)try{this.ws.close()}catch(e){}this.ws=null;for(const e of this.subscriptions)e.unsubscribe();this.subscriptions.clear()}reconnect(){if(!this.reconnecting){this.reconnecting=!0;try{this.disconnect()}catch(e){}this.connect().catch((()=>{})).then((()=>this.reconnecting=!1))}}connect(){return s(this,void 0,void 0,(function*(){if(this.lastServerActivity=new Date,this.pauseUntil&&this.pauseUntil>new Date)return;if(this.ws)throw new Error("Called connect() when a connection is already open");if(!this.databaseUrl)throw new Error("Cannot connect without a database URL");if(this.closed)return;const e=this.user.accessTokenExpiration;if(e&&e<new Date)return void this.subscriber.error(new Yo);this.webSocketStatus.next("connecting"),this.pinger=setInterval((()=>s(this,void 0,void 0,(function*(){if(this.closed)this.teardown();else if(this.ws)try{this.ws.send(JSON.stringify({type:"ping"})),setTimeout((()=>{this.pinger&&(this.closed?this.teardown():this.lastServerActivity<new Date(Date.now()-2e4)&&this.reconnect())}),2e4)}catch(e){this.reconnect()}else this.reconnect()}))),3e4);const r=new URL(this.databaseUrl);r.protocol="http:"===r.protocol?"ws":"wss";const i=new URLSearchParams;if(this.subscriber.closed)return;i.set("v","2"),this.rev&&i.set("rev",this.rev),this.yrev&&i.set("yrev",this.yrev),i.set("realmsHash",this.realmSetHash),i.set("clientId",this.clientIdentity),i.set("dxcv",this.db.cloud.version),this.user.accessToken&&i.set("token",this.user.accessToken);const o=this.ws=new WebSocket(`${r}/changes?${i}`);o.binaryType="arraybuffer",o.onclose=e=>{this.pinger&&this.reconnect()},o.onmessage=e=>{if(this.pinger){this.lastServerActivity=new Date;try{const t="string"==typeof e.data?dt.parse(e.data):function(e){const t=new V(e),n=q(t);if("outdated-server-rev"===n)return{type:n};if("y-complete-sync-done"===n)return{type:n,yServerRev:q(t)};const r=q(t),s=q(t);switch(n){case"u-ack":case"u-reject":return{type:n,table:r,prop:s,i:Number(G(t))};default:{const e=X(t);switch(n){case"in-sync":case"doc-close":return{type:n,table:r,prop:s,k:e};case"aware":return{type:n,table:r,prop:s,k:e,u:H(t)};case"doc-open":return{type:n,table:r,prop:s,k:e,serverRev:X(t),sv:X(t)};case"sv":return{type:n,table:r,prop:s,k:e,sv:H(t)};case"u-c":return{type:n,table:r,prop:s,k:e,u:H(t),i:Number(G(t))};case"u-s":return{type:n,table:r,prop:s,k:e,u:H(t),r:t.pos<t.arr.length&&q(t)||void 0};default:throw new TypeError(`Unknown message type: ${n}`)}}}}(new Uint8Array(e.data));if("error"===t.type)throw new Error(`Error message from dexie-cloud: ${t.error}`);if("aware"===t.type){const e=so.getDocCache(this.db.dx).find(t.table,t.k,t.prop);if(e){const n=(e=>Qo.get(e))(e);if(n){Go(this.db).applyAwarenessUpdate(n,t.u,"server")}}}else if("pong"===t.type);else if("doc-open"===t.type){const e=so.getDocCache(this.db.dx).find(t.table,t.k,t.prop);e&&Zo(e).next()}else"u-ack"===t.type||"u-reject"===t.type||"u-s"===t.type||"in-sync"===t.type||"outdated-server-rev"===t.type||"y-complete-sync-done"===t.type?io([t],this.db).then((e=>s(this,[e],void 0,(function*({resyncNeeded:e,yServerRevision:n,receivedUntils:r}){if(n&&(yield this.db.$syncState.update("syncState",{yServerRevision:n})),"u-s"===t.type&&r){const e=zi(this.db,t.table,t.prop);if(e){const t=r[e.name];t&&(yield e.update(Et,{receivedUntil:t}))}}e&&(yield this.db.cloud.sync({purpose:"pull",wait:!0}))})))):this.subscriber.next(t)}catch(e){this.subscriber.error(e)}}};try{let e=!1;yield new Promise(((t,n)=>{o.onopen=n=>{e=!0,t(null)},o.onerror=t=>{if(e)this.reconnect();else{const e=t.error||new Error("WebSocket Error");this.subscriber.error(e),this.webSocketStatus.next("error"),n(e)}}})),this.subscriptions.add(this.messageProducer.subscribe((e=>{var t,n;this.closed||("ready"===e.type&&"connected"!==this.webSocketStatus.value&&this.webSocketStatus.next("connected"),"ready"===e.type?(this.rev=e.rev,null===(t=this.ws)||void 0===t||t.send(dt.stringify(e))):null===(n=this.ws)||void 0===n||n.send(N(e)))}))),this.user.isLoggedIn&&!No(this.db)&&this.subscriptions.add(function(e){const r=Le(e.tables.filter((t=>{var n,r;return(null===(r=null===(n=e.cloud.schema)||void 0===n?void 0:n[t.name])||void 0===r?void 0:r.markedForSync)&&t.schema.yProps})).map((e=>e.schema.yProps.map((t=>({table:e.name,ydocProp:t.prop,updatesTable:t.updatesTable}))))));return n.merge(...r.map((({table:r,ydocProp:i,updatesTable:o})=>{const l=e.table(o);return n.from(l.get(Et)).pipe(n.switchMap((e=>{let o=(null==e?void 0:e.unsentFrom)||1;return n.from(t.liveQuery((()=>s(this,void 0,void 0,(function*(){return(yield xt(l,o)).filter((e=>e.f&&1&e.f)).map((e=>({type:"u-c",table:r,prop:i,k:e.k,u:e.u,i:e.i})))}))))).pipe(n.tap((e=>{e.length>0&&(o=e.at(-1).i+1)})))})))}))).pipe(n.mergeMap((e=>e)))}(this.db).subscribe(this.db.messageProducer))}catch(e){this.pauseUntil=new Date(Date.now()+6e4)}}))}}class rl extends Error{constructor(e){super("expired"===e?"License expired":"deactivated"===e?"User deactivated":"Invalid license"),this.name="InvalidLicenseError",e&&(this.license=e)}}function sl(e){return s(this,void 0,void 0,(function*(){var e;yield(e=3e3,new Promise((t=>setTimeout(t,e)))),yield n.firstValueFrom(qo)}))}function il(e){return s(this,void 0,void 0,(function*(){var t;return!(!(null===(t=e.cloud.options)||void 0===t?void 0:t.databaseUrl)||!e.cloud.schema)&&(yield ho(e,e.cloud.options,e.cloud.schema,{justCheckIfNeeded:!0}))}))}const ol=new WeakMap;function ll(e,t,n,r){const i=ol.get(e);if(i){if(i.pull||"push"===(null==r?void 0:r.purpose))return i.promise;{let s=!1;const o=e.cloud.syncState.subscribe((e=>{"pulling"===e.phase&&(s=!0)}));return i.promise.then((()=>{o.unsubscribe()})).catch((e=>(o.unsubscribe(),Promise.reject(e)))).then((()=>{if(!s)return ll(e,t,n,r)}))}}const o=function(){return s(this,void 0,void 0,(function*(){try{yield yt(e),yield Wo(e,uo,(()=>ho(e,t,n,r))),ol.delete(e)}catch(t){throw ol.delete(e),t}}))}();return ol.set(e,{promise:o,pull:"push"!==(null==r?void 0:r.purpose)}),o}const cl=1e3;function al(e,t,n){let r=null,s={cancelled:!1},i=0,o=0;function l(r=1){setTimeout((()=>{const h=c?"pull":"push";o=Date.now(),ll(e,t,n,{cancelToken:s,retryImmediatelyOnFetchError:!0,purpose:h}).then((()=>{if(s.cancelled)d();else if(c||a)return c=!1,a=!1,l();u=!1,i=0,o=0})).catch((e=>{if(s.cancelled)d(),u=!1,i=0,o=0;else if(r<5){const e=[0,20,40,300,900][r]*cl;i=Date.now()+e,o=0,setTimeout((()=>l(r+1)),e)}else u=!1,i=0,o=0}))}),0)}let c=!1,a=!1,u=!1;const d=()=>{s.cancelled=!0,r&&r.unsubscribe()};return{start:()=>{r=e.localSyncEvent.subscribe((({purpose:e})=>{(e=>{s.cancelled||("pull"===e&&(c=!0),"push"===e&&(a=!0),u?i||o>0&&Date.now():(u=!0,l()))})(e||"pull")}))},stop:d}}function ul(e,t){if(e&&t&&t.unsyncedTables)for(const n of t.unsyncedTables)e[n]&&(e[n].markedForSync=!1)}var dl,hl,fl,pl,gl,yl={},ml=[],vl=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i;function bl(e,t){for(var n in t)e[n]=t[n];return e}function wl(e){var t=e.parentNode;t&&t.removeChild(e)}function _l(e,t,n){var r,s,i,o={};for(i in t)"key"==i?r=t[i]:"ref"==i?s=t[i]:o[i]=t[i];if(arguments.length>2&&(o.children=arguments.length>3?dl.call(arguments,2):n),"function"==typeof e&&null!=e.defaultProps)for(i in e.defaultProps)void 0===o[i]&&(o[i]=e.defaultProps[i]);return kl(e,o,r,s,null)}function kl(e,t,n,r,s){var i={type:e,props:t,key:n,ref:r,__k:null,__:null,__b:0,__e:null,__d:void 0,__c:null,__h:null,constructor:void 0,__v:null==s?++fl:s};return null==s&&null!=hl.vnode&&hl.vnode(i),i}function Sl(e){return e.children}function El(e,t){this.props=e,this.context=t}function xl(e,t){if(null==t)return e.__?xl(e.__,e.__.__k.indexOf(e)+1):null;for(var n;t<e.__k.length;t++)if(null!=(n=e.__k[t])&&null!=n.__e)return n.__e;return"function"==typeof e.type?xl(e):null}function Cl(e){var t,n;if(null!=(e=e.__)&&null!=e.__c){for(e.__e=e.__c.base=null,t=0;t<e.__k.length;t++)if(null!=(n=e.__k[t])&&null!=n.__e){e.__e=e.__c.base=n.__e;break}return Cl(e)}}function Il(e){(!e.__d&&(e.__d=!0)&&pl.push(e)&&!Al.__r++||gl!==hl.debounceRendering)&&((gl=hl.debounceRendering)||setTimeout)(Al)}function Al(){for(var e;Al.__r=pl.length;)e=pl.sort((function(e,t){return e.__v.__b-t.__v.__b})),pl=[],e.some((function(e){var t,n,r,s,i,o;e.__d&&(i=(s=(t=e).__v).__e,(o=t.__P)&&(n=[],(r=bl({},s)).__v=s.__v+1,Rl(o,s,r,t.__n,void 0!==o.ownerSVGElement,null!=s.__h?[i]:null,n,null==i?xl(s):i,s.__h),Ml(n,s),s.__e!=i&&Cl(s)))}))}function Dl(e,t,n,r,s,i,o,l,c,a){var u,d,h,f,p,g,y,m=r&&r.__k||ml,v=m.length;for(n.__k=[],u=0;u<t.length;u++)if(null!=(f=n.__k[u]=null==(f=t[u])||"boolean"==typeof f?null:"string"==typeof f||"number"==typeof f||"bigint"==typeof f?kl(null,f,null,null,f):Array.isArray(f)?kl(Sl,{children:f},null,null,null):f.__b>0?kl(f.type,f.props,f.key,null,f.__v):f)){if(f.__=n,f.__b=n.__b+1,null===(h=m[u])||h&&f.key==h.key&&f.type===h.type)m[u]=void 0;else for(d=0;d<v;d++){if((h=m[d])&&f.key==h.key&&f.type===h.type){m[d]=void 0;break}h=null}Rl(e,f,h=h||yl,s,i,o,l,c,a),p=f.__e,(d=f.ref)&&h.ref!=d&&(y||(y=[]),h.ref&&y.push(h.ref,null,f),y.push(d,f.__c||p,f)),null!=p?(null==g&&(g=p),"function"==typeof f.type&&f.__k===h.__k?f.__d=c=Ol(f,c,e):c=Tl(e,f,h,m,p,c),"function"==typeof n.type&&(n.__d=c)):c&&h.__e==c&&c.parentNode!=e&&(c=xl(h))}for(n.__e=g,u=v;u--;)null!=m[u]&&("function"==typeof n.type&&null!=m[u].__e&&m[u].__e==n.__d&&(n.__d=xl(r,u+1)),Bl(m[u],m[u]));if(y)for(u=0;u<y.length;u++)Nl(y[u],y[++u],y[++u])}function Ol(e,t,n){for(var r,s=e.__k,i=0;s&&i<s.length;i++)(r=s[i])&&(r.__=e,t="function"==typeof r.type?Ol(r,t,n):Tl(n,r,r,s,r.__e,t));return t}function Tl(e,t,n,r,s,i){var o,l,c;if(void 0!==t.__d)o=t.__d,t.__d=void 0;else if(null==n||s!=i||null==s.parentNode)e:if(null==i||i.parentNode!==e)e.appendChild(s),o=null;else{for(l=i,c=0;(l=l.nextSibling)&&c<r.length;c+=2)if(l==s)break e;e.insertBefore(s,i),o=i}return void 0!==o?o:s.nextSibling}function Ul(e,t,n){"-"===t[0]?e.setProperty(t,n):e[t]=null==n?"":"number"!=typeof n||vl.test(t)?n:n+"px"}function jl(e,t,n,r,s){var i;e:if("style"===t)if("string"==typeof n)e.style.cssText=n;else{if("string"==typeof r&&(e.style.cssText=r=""),r)for(t in r)n&&t in n||Ul(e.style,t,"");if(n)for(t in n)r&&n[t]===r[t]||Ul(e.style,t,n[t])}else if("o"===t[0]&&"n"===t[1])i=t!==(t=t.replace(/Capture$/,"")),t=t.toLowerCase()in e?t.toLowerCase().slice(2):t.slice(2),e.l||(e.l={}),e.l[t+i]=n,n?r||e.addEventListener(t,i?Pl:Ll,i):e.removeEventListener(t,i?Pl:Ll,i);else if("dangerouslySetInnerHTML"!==t){if(s)t=t.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if("href"!==t&&"list"!==t&&"form"!==t&&"tabIndex"!==t&&"download"!==t&&t in e)try{e[t]=null==n?"":n;break e}catch(e){}"function"==typeof n||(null!=n&&(!1!==n||"a"===t[0]&&"r"===t[1])?e.setAttribute(t,n):e.removeAttribute(t))}}function Ll(e){this.l[e.type+!1](hl.event?hl.event(e):e)}function Pl(e){this.l[e.type+!0](hl.event?hl.event(e):e)}function Rl(e,t,n,r,s,i,o,l,c){var a,u,d,h,f,p,g,y,m,v,b,w,_,k=t.type;if(void 0!==t.constructor)return null;null!=n.__h&&(c=n.__h,l=t.__e=n.__e,t.__h=null,i=[l]),(a=hl.__b)&&a(t);try{e:if("function"==typeof k){if(y=t.props,m=(a=k.contextType)&&r[a.__c],v=a?m?m.props.value:a.__:r,n.__c?g=(u=t.__c=n.__c).__=u.__E:("prototype"in k&&k.prototype.render?t.__c=u=new k(y,v):(t.__c=u=new El(y,v),u.constructor=k,u.render=Fl),m&&m.sub(u),u.props=y,u.state||(u.state={}),u.context=v,u.__n=r,d=u.__d=!0,u.__h=[]),null==u.__s&&(u.__s=u.state),null!=k.getDerivedStateFromProps&&(u.__s==u.state&&(u.__s=bl({},u.__s)),bl(u.__s,k.getDerivedStateFromProps(y,u.__s))),h=u.props,f=u.state,d)null==k.getDerivedStateFromProps&&null!=u.componentWillMount&&u.componentWillMount(),null!=u.componentDidMount&&u.__h.push(u.componentDidMount);else{if(null==k.getDerivedStateFromProps&&y!==h&&null!=u.componentWillReceiveProps&&u.componentWillReceiveProps(y,v),!u.__e&&null!=u.shouldComponentUpdate&&!1===u.shouldComponentUpdate(y,u.__s,v)||t.__v===n.__v){u.props=y,u.state=u.__s,t.__v!==n.__v&&(u.__d=!1),u.__v=t,t.__e=n.__e,t.__k=n.__k,t.__k.forEach((function(e){e&&(e.__=t)})),u.__h.length&&o.push(u);break e}null!=u.componentWillUpdate&&u.componentWillUpdate(y,u.__s,v),null!=u.componentDidUpdate&&u.__h.push((function(){u.componentDidUpdate(h,f,p)}))}if(u.context=v,u.props=y,u.__v=t,u.__P=e,b=hl.__r,w=0,"prototype"in k&&k.prototype.render)u.state=u.__s,u.__d=!1,b&&b(t),a=u.render(u.props,u.state,u.context);else do{u.__d=!1,b&&b(t),a=u.render(u.props,u.state,u.context),u.state=u.__s}while(u.__d&&++w<25);u.state=u.__s,null!=u.getChildContext&&(r=bl(bl({},r),u.getChildContext())),d||null==u.getSnapshotBeforeUpdate||(p=u.getSnapshotBeforeUpdate(h,f)),_=null!=a&&a.type===Sl&&null==a.key?a.props.children:a,Dl(e,Array.isArray(_)?_:[_],t,n,r,s,i,o,l,c),u.base=t.__e,t.__h=null,u.__h.length&&o.push(u),g&&(u.__E=u.__=null),u.__e=!1}else null==i&&t.__v===n.__v?(t.__k=n.__k,t.__e=n.__e):t.__e=$l(n.__e,t,n,r,s,i,o,c);(a=hl.diffed)&&a(t)}catch(e){t.__v=null,(c||null!=i)&&(t.__e=l,t.__h=!!c,i[i.indexOf(l)]=null),hl.__e(e,t,n)}}function Ml(e,t){hl.__c&&hl.__c(t,e),e.some((function(t){try{e=t.__h,t.__h=[],e.some((function(e){e.call(t)}))}catch(e){hl.__e(e,t.__v)}}))}function $l(e,t,n,r,s,i,o,l){var c,a,u,d=n.props,h=t.props,f=t.type,p=0;if("svg"===f&&(s=!0),null!=i)for(;p<i.length;p++)if((c=i[p])&&"setAttribute"in c==!!f&&(f?c.localName===f:3===c.nodeType)){e=c,i[p]=null;break}if(null==e){if(null===f)return document.createTextNode(h);e=s?document.createElementNS("http://www.w3.org/2000/svg",f):document.createElement(f,h.is&&h),i=null,l=!1}if(null===f)d===h||l&&e.data===h||(e.data=h);else{if(i=i&&dl.call(e.childNodes),a=(d=n.props||yl).dangerouslySetInnerHTML,u=h.dangerouslySetInnerHTML,!l){if(null!=i)for(d={},p=0;p<e.attributes.length;p++)d[e.attributes[p].name]=e.attributes[p].value;(u||a)&&(u&&(a&&u.__html==a.__html||u.__html===e.innerHTML)||(e.innerHTML=u&&u.__html||""))}if(function(e,t,n,r,s){var i;for(i in n)"children"===i||"key"===i||i in t||jl(e,i,null,n[i],r);for(i in t)s&&"function"!=typeof t[i]||"children"===i||"key"===i||"value"===i||"checked"===i||n[i]===t[i]||jl(e,i,t[i],n[i],r)}(e,h,d,s,l),u)t.__k=[];else if(p=t.props.children,Dl(e,Array.isArray(p)?p:[p],t,n,r,s&&"foreignObject"!==f,i,o,i?i[0]:n.__k&&xl(n,0),l),null!=i)for(p=i.length;p--;)null!=i[p]&&wl(i[p]);l||("value"in h&&void 0!==(p=h.value)&&(p!==e.value||"progress"===f&&!p||"option"===f&&p!==d.value)&&jl(e,"value",p,d.value,!1),"checked"in h&&void 0!==(p=h.checked)&&p!==e.checked&&jl(e,"checked",p,d.checked,!1))}return e}function Nl(e,t,n){try{"function"==typeof e?e(t):e.current=t}catch(e){hl.__e(e,n)}}function Bl(e,t,n){var r,s;if(hl.unmount&&hl.unmount(e),(r=e.ref)&&(r.current&&r.current!==e.__e||Nl(r,null,t)),null!=(r=e.__c)){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(e){hl.__e(e,t)}r.base=r.__P=null}if(r=e.__k)for(s=0;s<r.length;s++)r[s]&&Bl(r[s],t,"function"!=typeof e.type);n||null==e.__e||wl(e.__e),e.__e=e.__d=void 0}function Fl(e,t,n){return this.constructor(e,n)}function Wl(e,t,n){var r,s,i;hl.__&&hl.__(e,t),s=(r="function"==typeof n)?null:n&&n.__k||t.__k,i=[],Rl(t,e=(!r&&n||t).__k=_l(Sl,null,[e]),s||yl,yl,void 0!==t.ownerSVGElement,!r&&n?[n]:s?null:t.firstChild?dl.call(t.childNodes):null,i,!r&&n?n:s?s.__e:t.firstChild,r),Ml(i,e)}dl=ml.slice,hl={__e:function(e,t,n,r){for(var s,i,o;t=t.__;)if((s=t.__c)&&!s.__)try{if((i=s.constructor)&&null!=i.getDerivedStateFromError&&(s.setState(i.getDerivedStateFromError(e)),o=s.__d),null!=s.componentDidCatch&&(s.componentDidCatch(e,r||{}),o=s.__d),o)return s.__E=s}catch(t){e=t}throw e}},fl=0,El.prototype.setState=function(e,t){var n;n=null!=this.__s&&this.__s!==this.state?this.__s:this.__s=bl({},this.state),"function"==typeof e&&(e=e(bl({},n),this.props)),e&&bl(n,e),null!=e&&this.__v&&(t&&this.__h.push(t),Il(this))},El.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),Il(this))},El.prototype.render=Sl,pl=[],Al.__r=0;const Vl={Error:{color:"red"},Alert:{error:{color:"red",fontWeight:"bold"},warning:{color:"#f80",fontWeight:"bold"},info:{color:"black"}},Darken:{position:"fixed",top:0,left:0,opacity:.5,backgroundColor:"#000",width:"100vw",height:"100vh",zIndex:150,webkitBackdropFilter:"blur(2px)",backdropFilter:"blur(2px)"},DialogOuter:{position:"fixed",top:0,left:0,width:"100vw",height:"100vh",zIndex:150,alignItems:"center",display:"flex",justifyContent:"center"},DialogInner:{position:"relative",color:"#222",backgroundColor:"#fff",padding:"30px",marginBottom:"2em",maxWidth:"90%",maxHeight:"90%",overflowY:"auto",border:"3px solid #3d3d5d",borderRadius:"8px",boxShadow:"0 0 80px 10px #666",width:"auto",fontFamily:"sans-serif"},Input:{height:"35px",width:"17em",borderColor:"#ccf4",outline:"none",fontSize:"17pt",padding:"8px"}};function Kl({children:e,className:t}){return _l("div",{className:t},_l("div",{style:Vl.Darken}),_l("div",{style:Vl.DialogOuter},_l("div",{style:Vl.DialogInner},e)))}var Hl,Jl,zl,ql,Yl=0,Gl=[],Ql=[],Xl=hl.__b,Zl=hl.__r,ec=hl.diffed,tc=hl.__c,nc=hl.unmount;function rc(e,t){hl.__h&&hl.__h(Jl,e,Yl||t),Yl=0;var n=Jl.__H||(Jl.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({__V:Ql}),n.__[e]}function sc(e){return Yl=1,function(e,t,n){var r=rc(Hl++,2);if(r.t=e,!r.__c&&(r.__=[n?n(t):dc(void 0,t),function(e){var t=r.__N?r.__N[0]:r.__[0],n=r.t(t,e);t!==n&&(r.__N=[n,r.__[1]],r.__c.setState({}))}],r.__c=Jl,!Jl.u)){Jl.u=!0;var s=Jl.shouldComponentUpdate;Jl.shouldComponentUpdate=function(e,t,n){if(!r.__c.__H)return!0;var i=r.__c.__H.__.filter((function(e){return e.__c}));if(i.every((function(e){return!e.__N})))return!s||s.call(this,e,t,n);var o=!1;return i.forEach((function(e){if(e.__N){var t=e.__[0];e.__=e.__N,e.__N=void 0,t!==e.__[0]&&(o=!0)}})),!!o&&(!s||s.call(this,e,t,n))}}return r.__N||r.__}(dc,e)}function ic(e){return Yl=5,function(e,t){var n=rc(Hl++,7);return uc(n.__H,t)?(n.__V=e(),n.i=t,n.__h=e,n.__V):n.__}((function(){return{current:e}}),[])}function oc(){for(var e;e=Gl.shift();)if(e.__P&&e.__H)try{e.__H.__h.forEach(cc),e.__H.__h.forEach(ac),e.__H.__h=[]}catch(t){e.__H.__h=[],hl.__e(t,e.__v)}}hl.__b=function(e){Jl=null,Xl&&Xl(e)},hl.__r=function(e){Zl&&Zl(e),Hl=0;var t=(Jl=e.__c).__H;t&&(zl===Jl?(t.__h=[],Jl.__h=[],t.__.forEach((function(e){e.__N&&(e.__=e.__N),e.__V=Ql,e.__N=e.i=void 0}))):(t.__h.forEach(cc),t.__h.forEach(ac),t.__h=[])),zl=Jl},hl.diffed=function(e){ec&&ec(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(1!==Gl.push(t)&&ql===hl.requestAnimationFrame||((ql=hl.requestAnimationFrame)||function(e){var t,n=function(){clearTimeout(r),lc&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,100);lc&&(t=requestAnimationFrame(n))})(oc)),t.__H.__.forEach((function(e){e.i&&(e.__H=e.i),e.__V!==Ql&&(e.__=e.__V),e.i=void 0,e.__V=Ql}))),zl=Jl=null},hl.__c=function(e,t){t.some((function(e){try{e.__h.forEach(cc),e.__h=e.__h.filter((function(e){return!e.__||ac(e)}))}catch(n){t.some((function(e){e.__h&&(e.__h=[])})),t=[],hl.__e(n,e.__v)}})),tc&&tc(e,t)},hl.unmount=function(e){nc&&nc(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.forEach((function(e){try{cc(e)}catch(e){t=e}})),t&&hl.__e(t,n.__v))};var lc="function"==typeof requestAnimationFrame;function cc(e){var t=Jl,n=e.__c;"function"==typeof n&&(e.__c=void 0,n()),Jl=t}function ac(e){var t=Jl;e.__c=e.__(),Jl=t}function uc(e,t){return!e||e.length!==t.length||t.some((function(t,n){return t!==e[n]}))}function dc(e,t){return"function"==typeof t?t(e):t}function hc({message:e,messageCode:t,messageParams:n}){return e.replace(/\{\w+\}/gi,(e=>n[e.substring(1,e.length-1)]))}function fc({title:e,type:t,alerts:n,fields:r,submitLabel:s,cancelLabel:i,onCancel:o,onSubmit:l}){const[c,a]=sc({}),u=ic(null);return function(e,t){var n=rc(Hl++,4);!hl.__s&&uc(n.__H,t)&&(n.__=e,n.i=t,Jl.__h.push(n))}((()=>{var e;return null===(e=u.current)||void 0===e?void 0:e.focus()}),[]),_l(Kl,{className:"dxc-login-dlg"},_l(Sl,null,_l("h3",{style:Vl.WindowHeader},e),n.map((e=>_l("p",{style:Vl.Alert[e.type]},hc(e)))),_l("form",{onSubmit:e=>{e.preventDefault(),l(c)}},Object.entries(r).map((([e,{type:t,label:n,placeholder:r}],s)=>_l("label",{style:Vl.Label,key:s},n?`${n}: `:"",_l("input",{ref:0===s?u:void 0,type:t,name:e,autoComplete:"on",style:Vl.Input,autoFocus:!0,placeholder:r,value:c[e]||"",onInput:n=>{var r;const s=function(e,t){switch(e){case"email":return t.toLowerCase();case"otp":return t.toUpperCase();default:return t}}(t,null===(r=n.target)||void 0===r?void 0:r.value);let i=Object.assign(Object.assign({},c),{[e]:s});a(i),"otp"===t&&8===(null==s?void 0:s.trim().length)&&l(i)}})))))),_l("div",{style:Vl.ButtonsDiv},_l(Sl,null,_l("button",{type:"submit",style:Vl.Button,onClick:()=>l(c)},s),i&&_l("button",{style:Vl.Button,onClick:o},i))))}class pc extends El{constructor(e){super(e),this.observer=e=>this.setState({userInteraction:e}),this.state={userInteraction:void 0}}componentDidMount(){this.subscription=n.from(this.props.db.cloud.userInteraction).subscribe(this.observer)}componentWillUnmount(){this.subscription&&(this.subscription.unsubscribe(),delete this.subscription)}render(e,{userInteraction:t}){return t?_l(fc,Object.assign({},t)):null}}function gc(e){const t=new WeakMap;return n=>{let r=t.get(n);return r||(r=e(n),t.set(n,r)),r}}const yc=gc((e=>new n.BehaviorSubject(me)));function mc(e,t){let r=t,s=n.from(e).pipe(n.map((e=>r=e)),n.share({resetOnRefCountZero:()=>n.timer(1e3)}));const i=new n.Observable((e=>{let t=!1;const n=s.subscribe({next(n){t=!0,e.next(n)},error(t){e.error(t)},complete(){e.complete()}});return t||n.closed||e.next(r),n}));return i.getValue=()=>r,i}const vc=gc((e=>mc(t.liveQuery((()=>e.roles.where({realmId:"rlm-public"}).toArray().then((e=>{const t={};for(const n of e.slice().sort(((e,t)=>(e.sortOrder||0)-(t.sortOrder||0))))t[n.name]=n;return t})))),{}))),bc=gc((e=>mc(yc(e._novip).pipe(r.switchMap((n=>t.liveQuery((()=>e.transaction("r","realms","members",(()=>Promise.all([e.members.where({userId:n.userId}).toArray(),e.realms.toArray(),n.userId]).then((([e,t,n])=>({selfMembers:e,realms:t,userId:n})))))))))),{selfMembers:[],realms:[],get userId(){return e.cloud.currentUserId}})));function wc(...e){if(0===e.length)return{};const t=e.reduce(((e,t)=>{const n=Object.assign({},e);for(const[e,r]of Object.entries(t))if(e in n&&n[e]){if("*"===n[e])continue;if("*"===r)n[e]="*";else if(Array.isArray(r)&&Array.isArray(n[e])){const t=n,s=t[e];t[e]=[...new Set([...s,...r])]}else if("object"==typeof r&&r&&"object"==typeof n[e]){const t=n[e];for(const[e,n]of Object.entries(r))"*"!==t[e]&&("*"===n?t[e]="*":Array.isArray(t[e])&&Array.isArray(n)&&(t[e]=[...new Set([...t[e],...n])]))}}else n[e]=t[e];return n}));return t}const _c=gc((e=>function(e,t){let r;const s=e.pipe(n.map((e=>r=t(e))));return s.getValue=()=>void 0!==r?r:r=t(e.getValue()),s}(mc(n.combineLatest([bc(e._novip),vc(e._novip)]).pipe(r.map((([{selfMembers:e,realms:t,userId:n},r])=>({selfMembers:e,realms:t,userId:n,globalRoles:r})))),{selfMembers:[],realms:[],userId:me.userId,globalRoles:{}}),(({selfMembers:e,realms:t,userId:n,globalRoles:r})=>{const s=t.map((t=>{const s=e.filter((e=>e.realmId===t.realmId)),i=s.map((e=>e.permissions)).filter((e=>e)),o=Le(s.map((e=>e.roles)).filter((e=>e))).map((e=>r[e])).filter((e=>e)).map((e=>e.permissions));return Object.assign(Object.assign({},t),{permissions:t.owner===n?{manage:"*"}:wc(...i,...o)})})).reduce(((e,t)=>Object.assign(Object.assign({},e),{[t.realmId]:t})),{[n]:{realmId:n,owner:n,name:n,permissions:{manage:"*"}}});return s}))));class kc{constructor(e,t,n){this.permissions=e||{},this.tableName=t,this.isOwner=n}add(...e){var t;return"*"===this.permissions.manage||(!!(null===(t=this.permissions.manage)||void 0===t?void 0:t.includes(this.tableName))||("*"===this.permissions.add||!!e.every((e=>{var t;return null===(t=this.permissions.add)||void 0===t?void 0:t.includes(e)}))))}update(...e){var t,n;if(this.isOwner||"*"===this.permissions.manage)return!0;if(null===(t=this.permissions.manage)||void 0===t?void 0:t.includes(this.tableName))return!0;if("*"===this.permissions.update)return e.every((e=>"owner"!==e));const r=null===(n=this.permissions.update)||void 0===n?void 0:n[this.tableName];return"*"===r?e.every((e=>"owner"!==e)):e.every((e=>null==r?void 0:r.some((t=>t===e||"*"===t&&"owner"!==e))))}delete(){var e;return!(!this.isOwner&&"*"!==this.permissions.manage)||!!(null===(e=this.permissions.manage)||void 0===e?void 0:e.includes(this.tableName))}}const Sc=gc((e=>{const i=yc(e._novip).pipe(r.switchMap((n=>t.liveQuery((()=>e.members.where({email:n.email||""}).toArray()))))),o=_c(e._novip),l=bc(e._novip);return mc(n.combineLatest([i,l,o]).pipe(r.map((([t,n,r])=>{const i=(e,t)=>Object.assign(Object.assign({},e),{[t.id]:Object.assign(Object.assign({},t),{realm:r[t.realmId]})}),o=t.reduce(i,{}),l=n.selfMembers.reduce(i,o);return Object.values(l).filter((e=>!e.accepted)).map((t=>Object.assign(Object.assign({},t),{accept(){return s(this,void 0,void 0,(function*(){yield e.members.update(t.id,{accepted:new Date})}))},reject(){return s(this,void 0,void 0,(function*(){yield e.members.update(t.id,{rejected:new Date})}))}})))}))),[])}));function Ec(e){return r=>{var i;const o=r.doc;if(!o)throw new Error("Internal error: DexieYProvider.createYHandler called without a doc. This is unexpected.");const{parentTable:l}=o.meta||{};if(!(null===(i=e.cloud.schema)||void 0===i?void 0:i[l].markedForSync))return;let c;Object.defineProperty(r,"awareness",{get:()=>c||(c=function(e,r,i){const{parentTable:o,parentId:l,parentProp:c,updatesTable:a}=r.meta,u=Go(e),d=new u.Awareness(r),h=Zo(r);return d.on("update",(({added:t,updated:n,removed:s},l)=>{const a=t.concat(n).concat(s),h=e.cloud.currentUser.value;if("server"!==l&&h.isLoggedIn&&!No(e)){const t=u.encodeAwarenessUpdate(d,a);e.messageProducer.next({type:"aware",table:o,prop:c,k:r.meta.parentId,u:t}),i.destroyed&&e.messageProducer.next({type:"doc-close",table:o,prop:c,k:r.meta.parentId})}})),d.on("destroy",(()=>{u.removeAwarenessStates(d,[r.clientID],"provider destroyed")})),(()=>{s(this,void 0,void 0,(function*(){if(i.destroyed)return;let r=!1,u=1;const d=n.combineLatest([e.cloud.webSocketStatus,h.pipe(n.startWith(null))]).subscribe((([t])=>{if(i.destroyed)return;r="connected"===t;const n=e.cloud.currentUser.value;"connected"===t&&n.isLoggedIn&&!No(e)&&(++u,f().catch((e=>{})))}));function f(){return s(this,void 0,void 0,(function*(){const n=u,d=e.table(a),h=e.$syncState,[f,p]=yield e.transaction("r",h,d,(()=>s(this,void 0,void 0,(function*(){const e=yield d.get(Et),t=yield h.get("syncState");return[(null==e?void 0:e.receivedUntil)||0,(null==t?void 0:t.yServerRevision)||(null==t?void 0:t.serverRevision)]}))));if(i.destroyed||u!==n||!r)return;const g={type:"doc-open",table:o,prop:c,k:l,serverRev:p},y=yield d.where("i").between(f,1/0,!1).filter((e=>0===t.cmp(e.k,l)&&0==(1&(e.f||0)))).toArray();if(!i.destroyed&&u===n&&r){if(y.length>0){const e=ys(y.map((e=>e.u))),t=ps(e);g.sv=t}e.messageProducer.next(g)}}))}i.addCleanupHandler(d)}))})(),d}(e,o,r),Qo.set(o,c),c)})}}const xc={},Cc=new WeakMap,Ic=Dc("tx"),Ac=Dc("unload");function Dc(e){let t=null,n=!1,r=new Map;return{name:e,run(){return s(this,void 0,void 0,(function*(){!n&&r.size>0&&(n=!0,t&&(yield t.catch((()=>{}))),setTimeout((()=>{n=!1;const e=r;r=new Map,t=function(e){return s(this,void 0,void 0,(function*(){for(const{db:t,parentId:n,triggers:r,parentTable:s,prop:i}of e.values()){const e=so.getOrCreateDocument(t,s,i,n);try{const t=so.load(e);yield t.whenLoaded;for(const t of r)yield t(e,n)}catch(e){null==e||e.name}finally{so.release(e)}}}))}(e).finally((()=>{t=null}))}),0))}))},enqueue(e,t,n,s,i){const o=`${e.name}:${t}:${n}:${s}`;let l=r.get(o);l||(l={db:e,parentTable:t,parentId:n,prop:s,triggers:new Set},r.set(o,l)),l.triggers.add(i)}}}function Oc(){Ic.run()}function Tc(){Ac.run()}const Uc={nameSuffix:!0};function jc(e){const i=e.name,o=yc(e),l=[];let c=!1,a=null;e.on("ready",(e=>s(this,void 0,void 0,(function*(){try{yield function(e){return s(this,void 0,void 0,(function*(){var i,f,p,g,y,m,v;u=!1;const b=ko(e);"undefined"!=typeof window&&"undefined"!=typeof document&&((null===(i=b.cloud.options)||void 0===i?void 0:i.customLoginGui)||l.push(function(e){let t=!1;const n=document.createElement("div");return document.body?(document.body.appendChild(n),Wl(_l(pc,{db:e.vip}),n)):addEventListener("DOMContentLoaded",(()=>{t||(document.body.appendChild(n),Wl(_l(pc,{db:e.vip}),n))})),{unsubscribe(){try{n.remove()}catch(e){}t=!0},get closed(){return t}}}(e))),b.cloud.isServiceWorkerDB||l.push(function(e){let t=e.cloud.webSocketStatus.value;const s=e.cloud.webSocketStatus.pipe(r.switchMap((e=>{const s=t;t=e;const i=n.of(e);switch(e){case"disconnected":return Vo.value?i.pipe(r.debounceTime(500)):i;case"connecting":return"not-started"===s||"error"===s?i:i.pipe(r.debounceTime(4e3));default:return i}})));return n.combineLatest([s,e.syncStateChangedEvent.pipe(r.startWith({phase:"initial"})),yc(e.dx._novip),Ko]).pipe(r.map((([t,n,r,s])=>{var i;if((null===(i=r.license)||void 0===i?void 0:i.status)&&"ok"!==r.license.status)return{phase:"offline",status:"offline",license:r.license.status};let{phase:o,error:l,progress:c}=n,a=t;return"error"===o&&(a="error"),"not-started"===t&&("pushing"!==o&&"pulling"!==o||(a="connecting")),"error"!==e.cloud.syncState.value.phase||"pushing"!==n.phase&&"pulling"!==n.phase||(a="connecting"),s||(a="disconnected"),{phase:o,error:l,progress:c,status:bt?a:"offline",license:"ok"}})))}(b).subscribe(e.cloud.syncState)),l.push(b.syncCompleteEvent.subscribe(h)),b.tables.every((e=>e.core))||function(){throw new t.SchemaError("Version increment needed to allow dexie-cloud change tracking")}();const w="serviceWorker"in navigator?yield navigator.serviceWorker.getRegistrations():[],[_,k]=yield b.transaction("rw",b.$syncState,(()=>s(this,void 0,void 0,(function*(){var e,t;const{options:n,schema:r}=b.cloud,[s,i,o]=yield Promise.all([b.getOptions(),b.getSchema(),b.getPersistedSyncState()]);if(c){if(!s||JSON.stringify(s)!==JSON.stringify(n)){if(!n)throw new Error("Internal error");const e=Object.assign({},n);delete e.fetchTokens,delete e.awarenessProtocol,yield b.$syncState.put(e,"options")}}else b.cloud.options=s||null;if((null===(e=b.cloud.options)||void 0===e?void 0:e.tryUseServiceWorker)&&"serviceWorker"in navigator&&w.length>0&&!Co?b.cloud.usingServiceWorker=!0:((null===(t=b.cloud.options)||void 0===t?void 0:t.tryUseServiceWorker)&&b.cloud.isServiceWorkerDB,b.cloud.usingServiceWorker=!1),ul(r,b.cloud.options),ul(i,b.cloud.options),r){if(!i||JSON.stringify(i)!==JSON.stringify(r)){const e=i||{};for(const[t,n]of Object.entries(r)){const r=e[t];r?(r.markedForSync=n.markedForSync,n.deleted=r.deleted,r.generatedGlobalId=n.generatedGlobalId):e[t]=Object.assign({},n)}yield b.$syncState.put(e,"schema"),Object.assign(r,e)}}else b.cloud.schema=i||null;return[null==o?void 0:o.initiallySynced,null==o?void 0:o.realms]}))));if(_&&b.setInitiallySynced(!0),function(e){var n,r;for(const s of e.tables)if(null===(r=null===(n=e.cloud.schema)||void 0===n?void 0:n[s.name])||void 0===r?void 0:r.markedForSync){if(s.schema.primKey.auto)throw new t.SchemaError(`Table ${s.name} is both autoIncremented and synced. Use db.cloud.configure({unsyncedTables: [${JSON.stringify(s.name)}]}) to blacklist it from sync`);if(!s.schema.primKey.keyPath)throw new t.SchemaError(`Table ${s.name} cannot be both synced and outbound. Use db.cloud.configure({unsyncedTables: [${JSON.stringify(s.name)}]}) to blacklist it from sync`)}}(b),d(),!b.cloud.isServiceWorkerDB){l.push(t.liveQuery((()=>b.getCurrentUser())).subscribe(o)),l.push(t.liveQuery((()=>b.getPersistedSyncState())).subscribe(b.cloud.persistedSyncState)),yield n.firstValueFrom(n.combineLatest([o.pipe(r.skip(1),r.take(1)),b.cloud.persistedSyncState.pipe(r.skip(1),r.take(1))]));const e=Ec(b);so.on.new.subscribe(e),b.dx.once("close",(()=>{so.on.new.unsubscribe(e)}))}let S=!1;const E=yield b.getCurrentUser(),x=null===(f=b.cloud.options)||void 0===f?void 0:f.requireAuth;x&&(b.cloud.isServiceWorkerDB?yield n.firstValueFrom(o.pipe(r.filter((e=>!!e.isLoggedIn)),r.take(1))):"object"==typeof x?(!E.isLoggedIn||x.userId&&E.userId!==x.userId||x.email&&E.email!==x.email)&&(S=yield Se(b,x)):E.isLoggedIn||(S=yield Se(b))),!E.isLoggedIn||k&&k.includes(E.userId)||(S=!0),a&&a.stop(),a=null,d();const C=(null===(p=b.cloud.options)||void 0===p?void 0:p.databaseUrl)&&(!_||S);C&&(yield function(e,t,n){return s(this,void 0,void 0,(function*(){yield Wo(e,uo,(()=>ho(e,t,n,{isInitialSync:!0})))}))}(b,b.cloud.options,b.cloud.schema),b.setInitiallySynced(!0)),d(),b.cloud.usingServiceWorker&&(null===(g=b.cloud.options)||void 0===g?void 0:g.databaseUrl)?(C||te(b,"push").catch((()=>{})),function(e){return s(this,void 0,void 0,(function*(){var t;try{const{periodicSync:n}=yield navigator.serviceWorker.ready;if(n)try{yield n.register(`dexie-cloud:${e.name}`,null===(t=e.cloud.options)||void 0===t?void 0:t.periodicSync)}catch(e){}}catch(e){}}))}(b).catch((()=>{}))):(null===(y=b.cloud.options)||void 0===y?void 0:y.databaseUrl)&&b.cloud.schema&&!b.cloud.isServiceWorkerDB&&(a=al(b,b.cloud.options,b.cloud.schema),a.start(),C||ne(b,"push")),d(),b.cloud.isServiceWorkerDB||l.push(n.fromEvent(self,"online").subscribe((()=>{b.syncStateChangedEvent.next({phase:"not-in-sync"}),No(b)||ne(b,"push")})),n.fromEvent(self,"offline").subscribe((()=>{b.syncStateChangedEvent.next({phase:"offline"})}))),!(null===(m=b.cloud.options)||void 0===m?void 0:m.databaseUrl)||(null===(v=b.cloud.options)||void 0===v?void 0:v.disableWebSocket)||Io||l.push(function(e){var t;if(!(null===(t=e.cloud.options)||void 0===t?void 0:t.databaseUrl))throw new Error("No database URL to connect WebSocket to");const i=e.messageConsumer.readyToServe.pipe(r.filter((e=>e)),r.switchMap((()=>e.getPersistedSyncState())),r.filter((e=>e&&e.serverRevision)),r.switchMap((e=>s(this,void 0,void 0,(function*(){return{type:"ready",rev:e.serverRevision,realmSetHash:yield De(e)}}))))),o=n.merge(i,e.messageProducer);return function t(){return e.cloud.persistedSyncState.pipe(r.filter((e=>null==e?void 0:e.serverRevision)),r.take(1),r.switchMap((t=>e.cloud.currentUser.pipe(r.map((e=>[e,t]))))),r.switchMap((([e,t])=>Ko.pipe(r.map((n=>[n?e:null,t]))))),r.switchMap((([t,s])=>(null==t?void 0:t.isLoggedIn)&&!(null==s?void 0:s.realms.includes(t.userId))?e.cloud.persistedSyncState.pipe(r.filter((e=>(null==e?void 0:e.realms.includes(t.userId))||!1)),r.take(1),r.map((e=>[t,e]))):new n.BehaviorSubject([t,s]))),r.switchMap((e=>s(this,[e],void 0,(function*([e,t]){return[e,yield De(t)]})))),r.distinctUntilChanged((([e,t],[n,r])=>e===n&&t===r)),r.switchMap((([r,s])=>{var i;return(null===(i=e.cloud.persistedSyncState)||void 0===i?void 0:i.value)?r?new el(e,e.cloud.persistedSyncState.value.serverRevision,e.cloud.persistedSyncState.value.yServerRevision,s,e.cloud.persistedSyncState.value.clientIdentity,o,e.cloud.webSocketStatus,r):n.from([]):t()})),r.catchError((i=>"TokenExpiredError"===(null==i?void 0:i.name)?n.of(!0).pipe(r.switchMap((()=>s(this,void 0,void 0,(function*(){const t=yield e.getCurrentUser(),n=yield pe(e.cloud.options.databaseUrl,t);yield e.table("$logins").update(t.userId,{accessToken:n.accessToken,accessTokenExpiration:n.accessTokenExpiration,claims:n.claims,license:n.license,data:n.data})})))),r.switchMap((()=>t()))):n.throwError((()=>i)))),r.catchError((s=>(e.cloud.webSocketStatus.next("error"),s instanceof rl?n.throwError((()=>s)):n.from(sl()).pipe(r.switchMap((()=>t())))))))}().subscribe({next:t=>{t&&e.messageConsumer.enqueue(t)},error:e=>{},complete:()=>{}})}(b))}))}(e)}catch(e){}}))),!0);let u=!1;function d(){if(u)throw new t.DatabaseClosedError}e.once("close",(()=>{l.forEach((e=>e.unsubscribe())),l.splice(0,l.length),u=!0,a&&a.stop(),a=null,o.next(me)}));const h=new n.Subject;var f;e.cloud={version:"4.2.0-alpha.3",options:Object.assign({},Uc),schema:null,get currentUserId(){return o.value.userId||me.userId},currentUser:o,syncState:new n.BehaviorSubject({phase:"initial",status:"not-started"}),events:{syncComplete:h},persistedSyncState:new n.BehaviorSubject(void 0),userInteraction:new n.BehaviorSubject(void 0),webSocketStatus:new n.BehaviorSubject("not-started"),login(t){return s(this,void 0,void 0,(function*(){const n=ko(e);yield n.cloud.sync(),yield Se(n,t)}))},invites:Sc(e),roles:vc(e),configure(t){t=e.cloud.options=Object.assign(Object.assign({},e.cloud.options),t),c=!0,t.databaseUrl&&t.nameSuffix&&(e.name=`${i}-${function(e){const t=new URL(e);return"/"===t.pathname?t.hostname.split(".")[0]:t.pathname.split("/")[1]}(t.databaseUrl)}`,ko(e).reconfigure()),ul(e.cloud.schema,e.cloud.options)},logout(){return s(this,arguments,void 0,(function*({force:t}={}){t?yield we(ko(e),{deleteUnsyncedData:!0}):yield be(ko(e))}))},sync(){return s(this,arguments,void 0,(function*({wait:i,purpose:o}={wait:!0,purpose:"push"}){var l;void 0===i&&(i=!0);const c=ko(e);if("ok"!==((null===(l=c.cloud.currentUser.value.license)||void 0===l?void 0:l.status)||"ok")&&(yield he(c)),"pull"===o){const e=c.cloud.persistedSyncState.value;if(ne(c,o),i){const t=yield n.firstValueFrom(c.cloud.persistedSyncState.pipe(r.filter((t=>null!=(null==t?void 0:t.timestamp)&&(!e||t.timestamp>e.timestamp)))));if(null==t?void 0:t.error)throw new Error("Sync error: "+t.error)}}else if(yield il(c)){const e=c.cloud.persistedSyncState.value;ne(c,o),i&&(yield n.firstValueFrom(n.from(t.liveQuery((()=>s(this,void 0,void 0,(function*(){const t=yield il(c),n=yield c.getPersistedSyncState();if((null==n?void 0:n.timestamp)!==(null==e?void 0:e.timestamp)&&(null==n?void 0:n.error))throw new Error("Sync error: "+n.error);return t}))))).pipe(r.filter((e=>!e)))))}}))},permissions:(t,n)=>function(e,t,n){if(!t)throw new TypeError("Cannot check permissions of undefined or null. A Dexie Cloud object with realmId and owner expected.");const{owner:s,realmId:i}=t;if(!n){if("function"!=typeof t.table)throw new TypeError("Missing 'table' argument to permissions and table could not be extracted from entity");n=t.table()}const o=_c(e),l=t=>{const r=t[i||e.cloud.currentUserId];return r?new kc(r.permissions,n,void 0===i||i===e.cloud.currentUserId||s===e.cloud.currentUserId):new kc({},n,!s||s===e.cloud.currentUserId)},c=o.pipe(r.map(l));return c.getValue=()=>l(o.getValue()),c}(e._novip,t,n)},e.Version.prototype._parseStoresSpec=t.override(e.Version.prototype._parseStoresSpec,(t=>Fo(t,e))),e.Table.prototype.newId=function({colocateWith:t}={}){const n=t&&t.substr(t.length-3);return jo(e.cloud.schema[this.name].idPrefix||"",n)},e.Table.prototype.idPrefix=function(){var e,t;return(null===(t=null===(e=this.db.cloud.schema)||void 0===e?void 0:e[this.name])||void 0===t?void 0:t.idPrefix)||""},e.use(Bo({currentUserObservable:e.cloud.currentUser,db:ko(e)})),e.use((f=ko(e),{stack:"dbcore",name:"implicitPropSetterMiddleware",level:1,create:e=>Object.assign(Object.assign({},e),{table:t=>{const n=e.table(t);return Object.assign(Object.assign({},n),{mutate:e=>{var r,s,i,o,l,c;const a=e.trans;if(a.disableChangeTracking)return n.mutate(e);const u=null!==(s=null===(r=a.currentUser)||void 0===r?void 0:r.userId)&&void 0!==s?s:me.userId;if((null===(o=null===(i=f.cloud.schema)||void 0===i?void 0:i[t])||void 0===o?void 0:o.markedForSync)&&("add"===e.type||"put"===e.type)){if("members"===t)for(const t of e.values)"string"==typeof t.email&&(t.email=t.email.trim().toLowerCase());for(const t of e.values){t.owner||(t.owner=u),t.realmId||(t.realmId=u);const r=null===(c=(l=n.schema.primaryKey).extractKey)||void 0===c?void 0:c.call(l,t);"string"==typeof r&&"#"===r[0]&&"put"===e.type&&(delete e.criteria,delete e.changeSpec,delete e.updates,t.$ts=Date.now())}}return n.mutate(e)}})}})})),e.use(Lo(ko(e)))}jc.version="4.2.0-alpha.3",t.Cloud=jc,e.default=jc,e.defineYDocTrigger=function(e,n,r){var s,i;const o=null===(i=null===(s=e.schema.yProps)||void 0===s?void 0:s.find((e=>e.prop===n)))||void 0===i?void 0:i.updatesTable;if(!o)throw new Error(`Table ${e.name} does not have a Yjs property named ${n}`);xc[o]={trigger:r,parentTable:e.name,prop:n};const l=e.db._novip;let c=Cc.get(l);c||(c=(e=>({stack:"dbcore",level:10,name:"yTriggerMiddleware",create:n=>Object.assign(Object.assign({},n),{transaction:(e,t,r)=>{const s=n.transaction(e,t,r);return"readonly"===t?s:e.some((e=>xc[e]))?(s.addEventListener("complete",Oc),s):s},table:r=>{const s=n.table(r),i=xc[r];if(!i)return s;const{trigger:o,parentTable:l,prop:c}=i;return Object.assign(Object.assign({},s),{mutate(n){var r;switch(n.type){case"add":for(const t of n.values){if(null==t.k)continue;const n=t.k,s=so.getDocCache(e).find(l,n,c);(s&&(null===(r=so.for(s))||void 0===r?void 0:r.refCount)?Ac:Ic).enqueue(e,l,n,c,o)}break;case"delete":n.trans._rejecting_y_ypdate&&s.getMany({keys:n.keys,trans:n.trans,cache:"immutable"}).then((n=>{const r=new t.RangeSet;for(const{k:e}of n)null!=e&&r.addKey(e);for(const t of r)Ic.enqueue(e,l,t.from,c,o)}))}return s.mutate(n)}})}})}))(l),Cc.set(l,c)),l.use(c),so.on("beforeunload",Tc)},e.dexieCloud=jc,e.getTiedObjectId=function(e){return e.startsWith("rlm~")?e.substr(4):null},e.getTiedRealmId=function(e){return"rlm~"+e},e.resolveText=hc,Object.defineProperty(e,"__esModule",{value:!0})}));
|
|
2
2
|
//# sourceMappingURL=dexie-cloud-addon.min.js.map
|