dexie-cloud-addon 1.0.0-beta.10 → 1.0.0-beta.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/dist/modern/dexie-cloud-addon.js +189 -158
  2. package/dist/modern/dexie-cloud-addon.js.map +1 -1
  3. package/dist/modern/dexie-cloud-addon.min.js +1 -1
  4. package/dist/modern/dexie-cloud-addon.min.js.map +1 -1
  5. package/dist/modern/service-worker.js +1208 -1176
  6. package/dist/modern/service-worker.js.map +1 -1
  7. package/dist/modern/service-worker.min.js +1 -1
  8. package/dist/modern/service-worker.min.js.map +1 -1
  9. package/dist/module-es5/dexie-cloud-addon.js +259 -207
  10. package/dist/module-es5/dexie-cloud-addon.js.map +1 -1
  11. package/dist/module-es5/dexie-cloud-addon.min.js +1 -1
  12. package/dist/module-es5/dexie-cloud-addon.min.js.map +1 -1
  13. package/dist/types/WSObservable.d.ts +11 -6
  14. package/dist/types/WebSocketStatus.d.ts +1 -0
  15. package/dist/types/helpers/BroadcastedLocalEvent.d.ts +8 -0
  16. package/dist/types/helpers/visibleState.d.ts +1 -0
  17. package/dist/types/sync/syncServerToClientOnly.d.ts +3 -0
  18. package/dist/types/types/CloudConnectionStatus.d.ts +0 -0
  19. package/dist/types/types/ConnectionStatus.d.ts +0 -0
  20. package/dist/types/types/LoginState.d.ts +41 -0
  21. package/dist/types/types/SyncConnectionStatus.d.ts +1 -0
  22. package/dist/types/types/SyncFlowStatus.d.ts +6 -0
  23. package/dist/types/types/SyncStatus.d.ts +6 -0
  24. package/dist/umd/dexie-cloud-addon.js +259 -207
  25. package/dist/umd/dexie-cloud-addon.js.map +1 -1
  26. package/dist/umd/dexie-cloud-addon.min.js +1 -1
  27. package/dist/umd/dexie-cloud-addon.min.js.map +1 -1
  28. package/dist/umd/service-worker.js +1208 -1176
  29. package/dist/umd/service-worker.js.map +1 -1
  30. package/dist/umd/service-worker.min.js +1 -1
  31. package/dist/umd/service-worker.min.js.map +1 -1
  32. package/dist/umd-modern/dexie-cloud-addon.js +188 -157
  33. package/dist/umd-modern/dexie-cloud-addon.js.map +1 -1
  34. package/package.json +2 -2
@@ -1 +1 @@
1
- import e,{liveQuery as t}from"dexie";import{Observable as n,BehaviorSubject as r,Subject as o,from as i,fromEvent as s,of as a,merge as c,Subscription as u,throwError as l,combineLatest as d}from"rxjs";const h=crypto.getRandomValues;function f(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,o=t.length;r<o;++r)f(e,t[r],n[r])}else{var i=t.indexOf(".");if(-1!==i){var s=t.substr(0,i),a=t.substr(i+1);if(""===a)void 0===n?Array.isArray(e)?isNaN(parseInt(s))||e.splice(parseInt(s),1):delete e[s]:e[s]=n;else{var c=e[s];c||(c=e[s]={}),f(c,a,n)}}else void 0===n?Array.isArray(e)&&!isNaN(parseInt(t))?e.splice(t,1):delete e[t]:e[t]=n}}const p="undefined"==typeof self?e=>{const t=Buffer.alloc(e);return h(t),t.toString("base64")}:e=>{const t=new Uint8Array(e);return crypto.getRandomValues(t),btoa(String.fromCharCode.apply(null,t))};function y(e){return"string"==typeof e||!!(Array.isArray(e)&&e.some((e=>y(e)))&&e.every(b))}function b(e){return"string"==typeof e||"number"==typeof e||Array.isArray(e)&&e.every(b)}function v(e,t,n){const r=e[t]||(e[t]={});switch(n.type){case"insert":case"upsert":n.keys.forEach(((e,t)=>{r[e]={type:"ups",val:n.values[t]}}));break;case"update":case"modify":n.keys.forEach(((e,t)=>{const o="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(o))f(i.val,e,t);break;case"del":break;case"upd":Object.assign(i.mod,o)}else r[e]={type:"upd",mod:o}}));break;case"delete":n.keys.forEach((e=>{r[e]={type:"del"}}))}return e}function m(e,t){for(const{table:n,muts:r}of t)for(const t of r)v(e,n,t)}var g=function(e,t){return(g=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)};function _(e,t){function n(){this.constructor=e}g(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}function w(e){return"function"==typeof e}var S=!1,k={Promise:void 0,set useDeprecatedSynchronousErrorHandling(e){e&&(new Error).stack;S=e},get useDeprecatedSynchronousErrorHandling(){return S}};function x(e){setTimeout((function(){throw e}),0)}var E={closed:!0,next:function(e){},error:function(e){if(k.useDeprecatedSynchronousErrorHandling)throw e;x(e)},complete:function(){}},I=function(){return Array.isArray||function(e){return e&&"number"==typeof e.length}}();function T(e){return null!==e&&"object"==typeof e}var C=function(){function e(e){return Error.call(this),this.message=e?e.length+" errors occurred during unsubscription:\n"+e.map((function(e,t){return t+1+") "+e.toString()})).join("\n "):"",this.name="UnsubscriptionError",this.errors=e,this}return e.prototype=Object.create(Error.prototype),e}(),A=function(){function e(e){this.closed=!1,this._parentOrParents=null,this._subscriptions=null,e&&(this._ctorUnsubscribe=!0,this._unsubscribe=e)}return e.prototype.unsubscribe=function(){var t;if(!this.closed){var n=this,r=n._parentOrParents,o=n._ctorUnsubscribe,i=n._unsubscribe,s=n._subscriptions;if(this.closed=!0,this._parentOrParents=null,this._subscriptions=null,r instanceof e)r.remove(this);else if(null!==r)for(var a=0;a<r.length;++a){r[a].remove(this)}if(w(i)){o&&(this._unsubscribe=void 0);try{i.call(this)}catch(e){t=e instanceof C?P(e.errors):[e]}}if(I(s)){a=-1;for(var c=s.length;++a<c;){var u=s[a];if(T(u))try{u.unsubscribe()}catch(e){t=t||[],e instanceof C?t=t.concat(P(e.errors)):t.push(e)}}}if(t)throw new C(t)}},e.prototype.add=function(t){var n=t;if(!t)return e.EMPTY;switch(typeof t){case"function":n=new e(t);case"object":if(n===this||n.closed||"function"!=typeof n.unsubscribe)return n;if(this.closed)return n.unsubscribe(),n;if(!(n instanceof e)){var r=n;(n=new e)._subscriptions=[r]}break;default:throw new Error("unrecognized teardown "+t+" added to Subscription.")}var o=n._parentOrParents;if(null===o)n._parentOrParents=this;else if(o instanceof e){if(o===this)return n;n._parentOrParents=[o,this]}else{if(-1!==o.indexOf(this))return n;o.push(this)}var i=this._subscriptions;return null===i?this._subscriptions=[n]:i.push(n),n},e.prototype.remove=function(e){var t=this._subscriptions;if(t){var n=t.indexOf(e);-1!==n&&t.splice(n,1)}},e.EMPTY=function(e){return e.closed=!0,e}(new e),e}();function P(e){return e.reduce((function(e,t){return e.concat(t instanceof C?t.errors:t)}),[])}var O=function(){return"function"==typeof Symbol?Symbol("rxSubscriber"):"@@rxSubscriber_"+Math.random()}(),U=function(e){function t(n,r,o){var i=e.call(this)||this;switch(i.syncErrorValue=null,i.syncErrorThrown=!1,i.syncErrorThrowable=!1,i.isStopped=!1,arguments.length){case 0:i.destination=E;break;case 1:if(!n){i.destination=E;break}if("object"==typeof n){n instanceof t?(i.syncErrorThrowable=n.syncErrorThrowable,i.destination=n,n.add(i)):(i.syncErrorThrowable=!0,i.destination=new $(i,n));break}default:i.syncErrorThrowable=!0,i.destination=new $(i,n,r,o)}return i}return _(t,e),t.prototype[O]=function(){return this},t.create=function(e,n,r){var o=new t(e,n,r);return o.syncErrorThrowable=!1,o},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))},t.prototype._next=function(e){this.destination.next(e)},t.prototype._error=function(e){this.destination.error(e),this.unsubscribe()},t.prototype._complete=function(){this.destination.complete(),this.unsubscribe()},t.prototype._unsubscribeAndRecycle=function(){var e=this._parentOrParents;return this._parentOrParents=null,this.unsubscribe(),this.closed=!1,this.isStopped=!1,this._parentOrParents=e,this},t}(A),$=function(e){function t(t,n,r,o){var i,s=e.call(this)||this;s._parentSubscriber=t;var a=s;return w(n)?i=n:n&&(i=n.next,r=n.error,o=n.complete,n!==E&&(w((a=Object.create(n)).unsubscribe)&&s.add(a.unsubscribe.bind(a)),a.unsubscribe=s.unsubscribe.bind(s))),s._context=a,s._next=i,s._error=r,s._complete=o,s}return _(t,e),t.prototype.next=function(e){if(!this.isStopped&&this._next){var t=this._parentSubscriber;k.useDeprecatedSynchronousErrorHandling&&t.syncErrorThrowable?this.__tryOrSetError(t,this._next,e)&&this.unsubscribe():this.__tryOrUnsub(this._next,e)}},t.prototype.error=function(e){if(!this.isStopped){var t=this._parentSubscriber,n=k.useDeprecatedSynchronousErrorHandling;if(this._error)n&&t.syncErrorThrowable?(this.__tryOrSetError(t,this._error,e),this.unsubscribe()):(this.__tryOrUnsub(this._error,e),this.unsubscribe());else if(t.syncErrorThrowable)n?(t.syncErrorValue=e,t.syncErrorThrown=!0):x(e),this.unsubscribe();else{if(this.unsubscribe(),n)throw e;x(e)}}},t.prototype.complete=function(){var e=this;if(!this.isStopped){var t=this._parentSubscriber;if(this._complete){var n=function(){return e._complete.call(e._context)};k.useDeprecatedSynchronousErrorHandling&&t.syncErrorThrowable?(this.__tryOrSetError(t,n),this.unsubscribe()):(this.__tryOrUnsub(n),this.unsubscribe())}else this.unsubscribe()}},t.prototype.__tryOrUnsub=function(e,t){try{e.call(this._context,t)}catch(e){if(this.unsubscribe(),k.useDeprecatedSynchronousErrorHandling)throw e;x(e)}},t.prototype.__tryOrSetError=function(e,t,n){if(!k.useDeprecatedSynchronousErrorHandling)throw new Error("bad call");try{t.call(this._context,n)}catch(t){return k.useDeprecatedSynchronousErrorHandling?(e.syncErrorValue=t,e.syncErrorThrown=!0,!0):(x(t),!0)}return!1},t.prototype._unsubscribe=function(){var e=this._parentSubscriber;this._context=null,this._parentSubscriber=null,e.unsubscribe()},t}(U);var N=function(){return"function"==typeof Symbol&&Symbol.observable||"@@observable"}();function D(e){return e}function R(e){return 0===e.length?D:1===e.length?e[0]:function(t){return e.reduce((function(e,t){return t(e)}),t)}}var j=function(){function e(e){this._isScalar=!1,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=this.operator,o=function(e,t,n){if(e){if(e instanceof U)return e;if(e[O])return e[O]()}return e||t||n?new U(e,t,n):new U(E)}(e,t,n);if(r?o.add(r.call(o,this.source)):o.add(this.source||k.useDeprecatedSynchronousErrorHandling&&!o.syncErrorThrowable?this._subscribe(o):this._trySubscribe(o)),k.useDeprecatedSynchronousErrorHandling&&o.syncErrorThrowable&&(o.syncErrorThrowable=!1,o.syncErrorThrown))throw o.syncErrorValue;return o},e.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){k.useDeprecatedSynchronousErrorHandling&&(e.syncErrorThrown=!0,e.syncErrorValue=t),!function(e){for(;e;){var t=e,n=t.closed,r=t.destination,o=t.isStopped;if(n||o)return!1;e=r&&r instanceof U?r:null}return!0}(e)?console.warn(t):e.error(t)}},e.prototype.forEach=function(e,t){var n=this;return new(t=L(t))((function(t,r){var o;o=n.subscribe((function(t){try{e(t)}catch(e){r(e),o&&o.unsubscribe()}}),r,t)}))},e.prototype._subscribe=function(e){var t=this.source;return t&&t.subscribe(e)},e.prototype[N]=function(){return this},e.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return 0===e.length?this:R(e)(this)},e.prototype.toPromise=function(e){var t=this;return new(e=L(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 L(e){if(e||(e=Promise),!e)throw new Error("no Promise impl found");return e}var B=function(e){return function(t){for(var n=0,r=e.length;n<r&&!t.closed;n++)t.next(e[n]);t.complete()}};function W(){return"function"==typeof Symbol&&Symbol.iterator?Symbol.iterator:"@@iterator"}var F=W(),M=function(e){return e&&"number"==typeof e.length&&"function"!=typeof e};function H(e){return!!e&&"function"!=typeof e.subscribe&&"function"==typeof e.then}var V=function(e){if(e&&"function"==typeof e[N])return r=e,function(e){var t=r[N]();if("function"!=typeof t.subscribe)throw new TypeError("Provided object does not correctly implement Symbol.observable");return t.subscribe(e)};if(M(e))return B(e);if(H(e))return n=e,function(e){return n.then((function(t){e.closed||(e.next(t),e.complete())}),(function(t){return e.error(t)})).then(null,x),e};if(e&&"function"==typeof e[F])return t=e,function(e){for(var n=t[F]();;){var r=void 0;try{r=n.next()}catch(t){return e.error(t),e}if(r.done){e.complete();break}if(e.next(r.value),e.closed)break}return"function"==typeof n.return&&e.add((function(){n.return&&n.return()})),e};var t,n,r,o=T(e)?"an invalid object":"'"+e+"'";throw new TypeError("You provided "+o+" where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.")},K=function(e){function t(t){var n=e.call(this)||this;return n.parent=t,n}return _(t,e),t.prototype._next=function(e){this.parent.notifyNext(e)},t.prototype._error=function(e){this.parent.notifyError(e),this.unsubscribe()},t.prototype._complete=function(){this.parent.notifyComplete(),this.unsubscribe()},t}(U),q=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return _(t,e),t.prototype.notifyNext=function(e){this.destination.next(e)},t.prototype.notifyError=function(e){this.destination.error(e)},t.prototype.notifyComplete=function(){this.destination.complete()},t}(U);function z(e,t){if(!t.closed){if(e instanceof j)return e.subscribe(t);var n;try{n=V(e)(t)}catch(e){t.error(e)}return n}}var G=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 _(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),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;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=!1,r=void 0;try{this.work(e)}catch(e){n=!0,r=!!e&&e||new Error(e)}if(n)return this.unsubscribe(),r},t.prototype._unsubscribe=function(){var e=this.id,t=this.scheduler,n=t.actions,r=n.indexOf(this);this.work=null,this.state=null,this.pending=!1,this.scheduler=null,-1!==r&&n.splice(r,1),null!=e&&(this.id=this.recycleAsyncId(t,e,null)),this.delay=null},t}(function(e){function t(t,n){return e.call(this)||this}return _(t,e),t.prototype.schedule=function(e,t){return this},t}(A)),J=function(){function e(t,n){void 0===n&&(n=e.now),this.SchedulerAction=t,this.now=n}return e.prototype.schedule=function(e,t,n){return void 0===t&&(t=0),new this.SchedulerAction(this,e).schedule(n,t)},e.now=function(){return Date.now()},e}(),Y=new(function(e){function t(n,r){void 0===r&&(r=J.now);var o=e.call(this,n,(function(){return t.delegate&&t.delegate!==o?t.delegate.now():r()}))||this;return o.actions=[],o.active=!1,o.scheduled=void 0,o}return _(t,e),t.prototype.schedule=function(n,r,o){return void 0===r&&(r=0),t.delegate&&t.delegate!==this?t.delegate.schedule(n,r,o):e.prototype.schedule.call(this,n,r,o)},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}(J))(G);function X(e){return e&&"function"==typeof e.schedule}function Z(e){return function(t){var n=new Q(e),r=t.lift(n);return n.caught=r}}var Q=function(){function e(e){this.selector=e}return e.prototype.call=function(e,t){return t.subscribe(new ee(e,this.selector,this.caught))},e}(),ee=function(e){function t(t,n,r){var o=e.call(this,t)||this;return o.selector=n,o.caught=r,o}return _(t,e),t.prototype.error=function(t){if(!this.isStopped){var n=void 0;try{n=this.selector(t,this.caught)}catch(t){return void e.prototype.error.call(this,t)}this._unsubscribeAndRecycle();var r=new K(this);this.add(r);var o=z(n,r);o!==r&&this.add(o)}},t}(q);function te(e,t){return new j((function(n){var r=new A,o=0;return r.add(t.schedule((function(){o!==e.length?(n.next(e[o++]),n.closed||r.add(this.schedule())):n.complete()}))),r}))}function ne(e,t){return t?te(e,t):new j(B(e))}function re(e,t){if(null!=e){if(function(e){return e&&"function"==typeof e[N]}(e))return function(e,t){return new j((function(n){var r=new A;return r.add(t.schedule((function(){var o=e[N]();r.add(o.subscribe({next:function(e){r.add(t.schedule((function(){return n.next(e)})))},error:function(e){r.add(t.schedule((function(){return n.error(e)})))},complete:function(){r.add(t.schedule((function(){return n.complete()})))}}))}))),r}))}(e,t);if(H(e))return function(e,t){return new j((function(n){var r=new A;return r.add(t.schedule((function(){return e.then((function(e){r.add(t.schedule((function(){n.next(e),r.add(t.schedule((function(){return n.complete()})))})))}),(function(e){r.add(t.schedule((function(){return n.error(e)})))}))}))),r}))}(e,t);if(M(e))return te(e,t);if(function(e){return e&&"function"==typeof e[F]}(e)||"string"==typeof e)return function(e,t){if(!e)throw new Error("Iterable cannot be null");return new j((function(n){var r,o=new A;return o.add((function(){r&&"function"==typeof r.return&&r.return()})),o.add(t.schedule((function(){r=e[F](),o.add(t.schedule((function(){if(!n.closed){var e,t;try{var o=r.next();e=o.value,t=o.done}catch(e){return void n.error(e)}t?n.complete():(n.next(e),this.schedule())}})))}))),o}))}(e,t)}throw new TypeError((null!==e&&typeof e||e)+" is not observable")}function oe(e,t){return t?re(e,t):e instanceof j?e:new j(V(e))}function ie(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=e[e.length-1];return X(n)?(e.pop(),te(e,n)):ne(e)}function se(e,t){return function(n){if("function"!=typeof e)throw new TypeError("argument is not a function. Are you looking for `mapTo()`?");return n.lift(new ae(e,t))}}var ae=function(){function e(e,t){this.project=e,this.thisArg=t}return e.prototype.call=function(e,t){return t.subscribe(new ce(e,this.project,this.thisArg))},e}(),ce=function(e){function t(t,n,r){var o=e.call(this,t)||this;return o.project=n,o.count=0,o.thisArg=r||o,o}return _(t,e),t.prototype._next=function(e){var t;try{t=this.project.call(this.thisArg,e,this.count++)}catch(e){return void this.destination.error(e)}this.destination.next(t)},t}(U);function ue(e,t,n){return void 0===n&&(n=Number.POSITIVE_INFINITY),"function"==typeof t?function(r){return r.pipe(ue((function(n,r){return oe(e(n,r)).pipe(se((function(e,o){return t(n,e,r,o)})))}),n))}:("number"==typeof t&&(n=t),function(t){return t.lift(new le(e,n))})}var le=function(){function e(e,t){void 0===t&&(t=Number.POSITIVE_INFINITY),this.project=e,this.concurrent=t}return e.prototype.call=function(e,t){return t.subscribe(new de(e,this.project,this.concurrent))},e}(),de=function(e){function t(t,n,r){void 0===r&&(r=Number.POSITIVE_INFINITY);var o=e.call(this,t)||this;return o.project=n,o.concurrent=r,o.hasCompleted=!1,o.buffer=[],o.active=0,o.index=0,o}return _(t,e),t.prototype._next=function(e){this.active<this.concurrent?this._tryNext(e):this.buffer.push(e)},t.prototype._tryNext=function(e){var t,n=this.index++;try{t=this.project(e,n)}catch(e){return void this.destination.error(e)}this.active++,this._innerSub(t)},t.prototype._innerSub=function(e){var t=new K(this),n=this.destination;n.add(t);var r=z(e,t);r!==t&&n.add(r)},t.prototype._complete=function(){this.hasCompleted=!0,0===this.active&&0===this.buffer.length&&this.destination.complete(),this.unsubscribe()},t.prototype.notifyNext=function(e){this.destination.next(e)},t.prototype.notifyComplete=function(){var e=this.buffer;this.active--,e.length>0?this._next(e.shift()):0===this.active&&this.hasCompleted&&this.destination.complete()},t}(q);function he(e){return void 0===e&&(e=Number.POSITIVE_INFINITY),ue(D,e)}function fe(){return he(1)}function pe(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return fe()(ie.apply(void 0,e))}function ye(e,t){return void 0===t&&(t=Y),function(n){return n.lift(new be(e,t))}}var be=function(){function e(e,t){this.dueTime=e,this.scheduler=t}return e.prototype.call=function(e,t){return t.subscribe(new ve(e,this.dueTime,this.scheduler))},e}(),ve=function(e){function t(t,n,r){var o=e.call(this,t)||this;return o.dueTime=n,o.scheduler=r,o.debouncedSubscription=null,o.lastValue=null,o.hasValue=!1,o}return _(t,e),t.prototype._next=function(e){this.clearDebounce(),this.lastValue=e,this.hasValue=!0,this.add(this.debouncedSubscription=this.scheduler.schedule(me,this.dueTime,this))},t.prototype._complete=function(){this.debouncedNext(),this.destination.complete()},t.prototype.debouncedNext=function(){if(this.clearDebounce(),this.hasValue){var e=this.lastValue;this.lastValue=null,this.hasValue=!1,this.destination.next(e)}},t.prototype.clearDebounce=function(){var e=this.debouncedSubscription;null!==e&&(this.remove(e),e.unsubscribe(),this.debouncedSubscription=null)},t}(U);function me(e){e.debouncedNext()}function ge(e){return e instanceof Date&&!isNaN(+e)}var _e=new j((function(e){return e.complete()}));function we(e){return e?function(e){return new j((function(t){return e.schedule((function(){return t.complete()}))}))}(e):_e}function Se(e,t){return new j(t?function(n){return t.schedule(ke,0,{error:e,subscriber:n})}:function(t){return t.error(e)})}function ke(e){var t=e.error;e.subscriber.error(t)}var xe=function(){function e(e,t,n){this.kind=e,this.value=t,this.error=n,this.hasValue="N"===e}return e.prototype.observe=function(e){switch(this.kind){case"N":return e.next&&e.next(this.value);case"E":return e.error&&e.error(this.error);case"C":return e.complete&&e.complete()}},e.prototype.do=function(e,t,n){switch(this.kind){case"N":return e&&e(this.value);case"E":return t&&t(this.error);case"C":return n&&n()}},e.prototype.accept=function(e,t,n){return e&&"function"==typeof e.next?this.observe(e):this.do(e,t,n)},e.prototype.toObservable=function(){switch(this.kind){case"N":return ie(this.value);case"E":return Se(this.error);case"C":return we()}throw new Error("unexpected notification kind value")},e.createNext=function(t){return void 0!==t?new e("N",t):e.undefinedValueNotification},e.createError=function(t){return new e("E",void 0,t)},e.createComplete=function(){return e.completeNotification},e.completeNotification=new e("C"),e.undefinedValueNotification=new e("N",void 0),e}();function Ee(e,t){void 0===t&&(t=Y);var n=ge(e)?+e-t.now():Math.abs(e);return function(e){return e.lift(new Ie(n,t))}}var Ie=function(){function e(e,t){this.delay=e,this.scheduler=t}return e.prototype.call=function(e,t){return t.subscribe(new Te(e,this.delay,this.scheduler))},e}(),Te=function(e){function t(t,n,r){var o=e.call(this,t)||this;return o.delay=n,o.scheduler=r,o.queue=[],o.active=!1,o.errored=!1,o}return _(t,e),t.dispatch=function(e){for(var t=e.source,n=t.queue,r=e.scheduler,o=e.destination;n.length>0&&n[0].time-r.now()<=0;)n.shift().notification.observe(o);if(n.length>0){var i=Math.max(0,n[0].time-r.now());this.schedule(e,i)}else this.unsubscribe(),t.active=!1},t.prototype._schedule=function(e){this.active=!0,this.destination.add(e.schedule(t.dispatch,this.delay,{source:this,destination:this.destination,scheduler:e}))},t.prototype.scheduleNotification=function(e){if(!0!==this.errored){var t=this.scheduler,n=new Ce(t.now()+this.delay,e);this.queue.push(n),!1===this.active&&this._schedule(t)}},t.prototype._next=function(e){this.scheduleNotification(xe.createNext(e))},t.prototype._error=function(e){this.errored=!0,this.queue=[],this.destination.error(e),this.unsubscribe()},t.prototype._complete=function(){this.scheduleNotification(xe.createComplete()),this.unsubscribe()},t}(U),Ce=function(){return function(e,t){this.time=e,this.notification=t}}();var Ae=function(){function e(e,t){this.compare=e,this.keySelector=t}return e.prototype.call=function(e,t){return t.subscribe(new Pe(e,this.compare,this.keySelector))},e}(),Pe=function(e){function t(t,n,r){var o=e.call(this,t)||this;return o.keySelector=r,o.hasKey=!1,"function"==typeof n&&(o.compare=n),o}return _(t,e),t.prototype.compare=function(e,t){return e===t},t.prototype._next=function(e){var t;try{var n=this.keySelector;t=n?n(e):e}catch(e){return this.destination.error(e)}var r=!1;if(this.hasKey)try{r=(0,this.compare)(this.key,t)}catch(e){return this.destination.error(e)}else this.hasKey=!0;r||(this.key=t,this.destination.next(e))},t}(U),Oe=function(){function e(){return Error.call(this),this.message="argument out of range",this.name="ArgumentOutOfRangeError",this}return e.prototype=Object.create(Error.prototype),e}();function Ue(e,t){return function(n){return n.lift(new $e(e,t))}}var $e=function(){function e(e,t){this.predicate=e,this.thisArg=t}return e.prototype.call=function(e,t){return t.subscribe(new Ne(e,this.predicate,this.thisArg))},e}(),Ne=function(e){function t(t,n,r){var o=e.call(this,t)||this;return o.predicate=n,o.thisArg=r,o.count=0,o}return _(t,e),t.prototype._next=function(e){var t;try{t=this.predicate.call(this.thisArg,e,this.count++)}catch(e){return void this.destination.error(e)}t&&this.destination.next(e)},t}(U);function De(e){return function(t){return 0===e?we():t.lift(new Re(e))}}var Re=function(){function e(e){if(this.total=e,this.total<0)throw new Oe}return e.prototype.call=function(e,t){return t.subscribe(new je(e,this.total))},e}(),je=function(e){function t(t,n){var r=e.call(this,t)||this;return r.total=n,r.count=0,r}return _(t,e),t.prototype._next=function(e){var t=this.total,n=++this.count;n<=t&&(this.destination.next(e),n===t&&(this.destination.complete(),this.unsubscribe()))},t}(U);function Le(e){return function(t){return t.lift(new Be(e))}}var Be=function(){function e(e){this.total=e}return e.prototype.call=function(e,t){return t.subscribe(new We(e,this.total))},e}(),We=function(e){function t(t,n){var r=e.call(this,t)||this;return r.total=n,r.count=0,r}return _(t,e),t.prototype._next=function(e){++this.count>this.total&&this.destination.next(e)},t}(U);function Fe(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=e[e.length-1];return X(n)?(e.pop(),function(t){return pe(e,t,n)}):function(t){return pe(e,t)}}function Me(e,t){return"function"==typeof t?function(n){return n.pipe(Me((function(n,r){return oe(e(n,r)).pipe(se((function(e,o){return t(n,e,r,o)})))})))}:function(t){return t.lift(new He(e))}}var He=function(){function e(e){this.project=e}return e.prototype.call=function(e,t){return t.subscribe(new Ve(e,this.project))},e}(),Ve=function(e){function t(t,n){var r=e.call(this,t)||this;return r.project=n,r.index=0,r}return _(t,e),t.prototype._next=function(e){var t,n=this.index++;try{t=this.project(e,n)}catch(e){return void this.destination.error(e)}this._innerSub(t)},t.prototype._innerSub=function(e){var t=this.innerSubscription;t&&t.unsubscribe();var n=new K(this),r=this.destination;r.add(n),this.innerSubscription=z(e,n),this.innerSubscription!==n&&r.add(this.innerSubscription)},t.prototype._complete=function(){var t=this.innerSubscription;t&&!t.closed||e.prototype._complete.call(this),this.unsubscribe()},t.prototype._unsubscribe=function(){this.innerSubscription=void 0},t.prototype.notifyComplete=function(){this.innerSubscription=void 0,this.isStopped&&e.prototype._complete.call(this)},t.prototype.notifyNext=function(e){this.destination.next(e)},t}(q);function Ke(){}function qe(e,t,n){return function(r){return r.lift(new ze(e,t,n))}}var ze=function(){function e(e,t,n){this.nextOrObserver=e,this.error=t,this.complete=n}return e.prototype.call=function(e,t){return t.subscribe(new Ge(e,this.nextOrObserver,this.error,this.complete))},e}(),Ge=function(e){function t(t,n,r,o){var i=e.call(this,t)||this;return i._tapNext=Ke,i._tapError=Ke,i._tapComplete=Ke,i._tapError=r||Ke,i._tapComplete=o||Ke,w(n)?(i._context=i,i._tapNext=n):n&&(i._context=n,i._tapNext=n.next||Ke,i._tapError=n.error||Ke,i._tapComplete=n.complete||Ke),i}return _(t,e),t.prototype._next=function(e){try{this._tapNext.call(this._context,e)}catch(e){return void this.destination.error(e)}this.destination.next(e)},t.prototype._error=function(e){try{this._tapError.call(this._context,e)}catch(e){return void this.destination.error(e)}this.destination.error(e)},t.prototype._complete=function(){try{this._tapComplete.call(this._context)}catch(e){return void this.destination.error(e)}return this.destination.complete()},t}(U),Je=function(){function e(){return Error.call(this),this.message="Timeout has occurred",this.name="TimeoutError",this}return e.prototype=Object.create(Error.prototype),e}();var Ye=function(){function e(e,t,n,r){this.waitFor=e,this.absoluteTimeout=t,this.withObservable=n,this.scheduler=r}return e.prototype.call=function(e,t){return t.subscribe(new Xe(e,this.absoluteTimeout,this.waitFor,this.withObservable,this.scheduler))},e}(),Xe=function(e){function t(t,n,r,o,i){var s=e.call(this,t)||this;return s.absoluteTimeout=n,s.waitFor=r,s.withObservable=o,s.scheduler=i,s.scheduleTimeout(),s}return _(t,e),t.dispatchTimeout=function(e){var t=e.withObservable;e._unsubscribeAndRecycle(),e.add(z(t,new K(e)))},t.prototype.scheduleTimeout=function(){var e=this.action;e?this.action=e.schedule(this,this.waitFor):this.add(this.action=this.scheduler.schedule(t.dispatchTimeout,this.waitFor,this))},t.prototype._next=function(t){this.absoluteTimeout||this.scheduleTimeout(),e.prototype._next.call(this,t)},t.prototype._unsubscribe=function(){this.action=void 0,this.scheduler=null,this.withObservable=null},t}(q);function Ze(e,t){return void 0===t&&(t=Y),function(e,t,n){return void 0===n&&(n=Y),function(r){var o=ge(e),i=o?+e-n.now():Math.abs(e);return r.lift(new Ye(i,o,t,n))}}(e,Se(new Je),t)}let Qe=!1;async function et(e,t){try{const n=await navigator.serviceWorker.ready;return"push"===t&&n.sync&&await n.sync.register(`dexie-cloud:${e.name}`),void(n.active?n.active.postMessage({type:"dexie-cloud-sync",dbName:e.name,purpose:t}):console.error("Dexie Cloud: There's no active service worker. Can this ever happen??"))}catch(e){Qe||(console.debug("Dexie Cloud: Could not register sync event",e),Qe=!0)}}function tt(e,t){e.cloud.usingServiceWorker?et(e,t):e.localSyncEvent.next({purpose:t})}const nt="undefined"!=typeof Buffer?e=>Buffer.from(e,"base64"):e=>{const t=atob(e),n=t.length,r=new Uint8Array(n);for(var o=0;o<n;o++)r[o]=t.charCodeAt(o);return r},rt="undefined"!=typeof Buffer?e=>ArrayBuffer.isView(e)?Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"):Buffer.from(e).toString("base64"):e=>btoa(String.fromCharCode.apply(null,e));function ot(t,n){return new Promise(((r,o)=>{const i={...n,onSubmit:e=>{t.next(void 0),r(e)},onCancel:()=>{t.next(void 0),o(new e.AbortError("User cancelled"))}};t.next(i)}))}function it(e,t,...n){return ot(e,{type:"message-alert",title:t,alerts:n,fields:{}})}async function st(e,t,n){let r=n||"";for(;!r||!/^[\w-\.]+@([\w-]+\.)+[\w-]{2,10}$/.test(r);)r=(await ot(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}async function at(e,t,n){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:o}=await ot(e,{type:"otp",title:"Enter OTP",alerts:r,fields:{otp:{type:"otp",label:"OTP",placeholder:"Paste OTP here"}}});return o}async function ct(e,t,n,r,o){return t.accessToken&&t.accessTokenExpiration.getTime()>Date.now()?t:t.refreshToken&&(!t.refreshTokenExpiration||t.refreshTokenExpiration.getTime()>Date.now())?await ut(e,t):await async function(e,t,n,r){const{privateKey:o,publicKey:i}=await crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:2048,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!1,["sign","verify"]);e.nonExportablePrivateKey=o;const s=function(e){const t=rt(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)}(await crypto.subtle.exportKey("spki",i));e.publicKey=i;try{const o=await t({public_key:s,hints:r});if("tokens"!==o.type)throw new Error(`Unexpected response type from token endpoint: ${o.type}`);return e.accessToken=o.accessToken,e.accessTokenExpiration=new Date(o.accessTokenExpiration),e.refreshToken=o.refreshToken,o.refreshTokenExpiration&&(e.refreshTokenExpiration=new Date(o.refreshTokenExpiration)),e.userId=o.claims.sub,e.email=o.claims.email,e.name=o.claims.name,e.claims=o.claims,o.alerts&&o.alerts.length>0&&await ot(n,{type:"message-alert",title:"Authentication Alert",fields:{},alerts:o.alerts}),e}catch(e){throw await it(n,"Authentication Failed",{type:"error",messageCode:"GENERIC_ERROR",message:"We're having a problem to authenticate rigth now.",messageParams:{}}).catch((()=>{})),e}}(t,n,r,o)}async function ut(e,t){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",o=(new TextEncoder).encode(t.refreshToken+n),i=await crypto.subtle.sign(r,t.nonExportablePrivateKey,o),s=rt(i),a={grant_type:"refresh_token",refresh_token:t.refreshToken,scopes:["ACCESS_DB"],signature:s,signing_algorithm:r,time_stamp:n},c=await fetch(`${e}/token`,{body:JSON.stringify(a),method:"post",headers:{"Content-Type":"application/json"},mode:"cors"});if(200!==c.status)throw new Error(`RefreshToken: Status ${c.status} from ${e}/token`);const u=await c.json();return t.accessToken=u.accessToken,t.accessTokenExpiration=u.accessTokenExpiration?new Date(u.accessTokenExpiration):void 0,t}const lt=new WeakMap;class dt{constructor(e,t){lt.set(this,e),Object.assign(this,t)}static load(e,t){return e.table("$logins").get(t).then((n=>new dt(e,n||{userId:t,claims:{sub:t},lastLogin:new Date(0)})))}async save(){lt.get(this).table("$logins").put(this)}}class ht extends Error{constructor(e,t){super(t||`${e.status} ${e.statusText}`),this.httpStatus=e.status}get name(){return"HttpError"}}async function ft(e,t){if((await e.getCurrentUser()).isLoggedIn){if(t){if(t.email&&e.cloud.currentUser.value.email!==t.email)throw new Error("Must logout before changing user");if(t.userId&&e.cloud.currentUserId!==t.userId)throw new Error("Must logout before changing user")}return}const n=new dt(e,{claims:{},lastLogin:new Date(0)});await ct(e.cloud.options.databaseUrl,n,e.cloud.options.fetchTokens||function(e){const{userInteraction:t}=e.cloud;return async function({public_key:n,hints:r}){var o;let i;const s=null===(o=e.cloud.options)||void 0===o?void 0:o.databaseUrl;if(!s)throw new Error("No database URL given.");i="demo"===(null==r?void 0:r.grant_type)?{demo_user:await st(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}:{email:await st(t,"Enter email address",null==r?void 0:r.email),grant_type:"otp",scopes:["ACCESS_DB"],public_key:n};const a=await fetch(`${s}/token`,{body:JSON.stringify(i),method:"post",headers:{"Content-Type":"application/json",mode:"cors"}});if(200!==a.status){const e=await a.text();throw await it(t,"Token request failed",{type:"error",messageCode:"GENERIC_ERROR",message:e,messageParams:{}}).catch((()=>{})),new ht(a,e)}const c=await a.json();if("tokens"===c.type)return c;if("otp"===i.grant_type){if("otp-sent"!==c.type)throw new Error(`Unexpected response from ${s}/token`);const e=await at(t,i.email);i.otp=e||"",i.otp_id=c.otp_id;let n=await fetch(`${s}/token`,{body:JSON.stringify(i),method:"post",headers:{"Content-Type":"application/json"},mode:"cors"});for(;401===n.status;){const e=await n.text();i.otp=await at(t,i.email,{type:"error",messageCode:"INVALID_OTP",message:e,messageParams:{}}),n=await fetch(`${s}/token`,{body:JSON.stringify(i),method:"post",headers:{"Content-Type":"application/json"},mode:"cors"})}if(200!==n.status){const e=await n.text();throw await it(t,"OTP Authentication Failed",{type:"error",messageCode:"GENERIC_ERROR",message:e,messageParams:{}}).catch((()=>{})),new ht(n,e)}return await n.json()}throw new Error(`Unexpected response from ${s}/token`)}}(e),e.cloud.userInteraction,t),await n.save(),await async function(e,t){if(t.userId===e.cloud.currentUserId)return;const n=e.table("$logins");await e.transaction("rw",n,(async e=>{const r=await n.toArray();await Promise.all(r.filter((e=>e.userId!==t.userId&&e.isLoggedIn)).map((e=>(e.isLoggedIn=!1,n.put(e))))),t.isLoggedIn=!0,t.lastLogin=new Date,await t.save(),console.debug("Saved new user",t.email)})),await new Promise((n=>{if(e.cloud.currentUserId===t.userId)n(null);else{const r=e.cloud.currentUser.subscribe((e=>{e.userId===t.userId&&(r.unsubscribe(),n(null))}))}}))}(e,n),tt(e,"pull")}const pt={userId:"unauthorized",name:"Unauthorized",claims:{sub:"unauthorized"},lastLogin:new Date(0)};try{Object.freeze(pt),Object.freeze(pt.claims)}catch(e){}const yt={},bt=self.document&&navigator.serviceWorker;bt&&bt.ready.then((e=>yt.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 vt{constructor(e){this.name=e}subscribe(e){if(!bt)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 bt.addEventListener("message",t),()=>bt.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}))):yt.registration&&(null===(t=yt.registration.active)||void 0===t||t.postMessage({type:`sw-broadcast-${this.name}`,message:e}))}}class mt extends n{constructor(e){const t="undefined"==typeof BroadcastChannel?new vt(e):new BroadcastChannel(e);super((n=>{function r(e){n.next(e.detail)}function o(e){console.debug("BroadcastedAndLocalEvent: onMessageEvent",e),n.next(e.data)}let i;return self.addEventListener(`lbc-${e}`,r),t instanceof vt?i=t.subscribe((e=>n.next(e))):(console.debug("BroadcastedAndLocalEvent: bc.addEventListener()",e,"bc is a",t),t.addEventListener("message",o)),()=>{self.removeEventListener(`lbc-${e}`,r),t instanceof vt?i():t.removeEventListener("message",o)}})),this.name=e,this.bc=t}next(e){console.debug("BroadcastedAndLocalEvent: bc.postMessage()",{...e},"bc is a",this.bc),this.bc.postMessage(e);const t=new CustomEvent(`lbc-${this.name}`,{detail:e});self.dispatchEvent(t)}}const{toString:gt}={};const _t={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 t of n)delete r[t],r["$"+t]=e[t];return r}};function wt(...e){const t=e.reduce(((e,t)=>({...e,...t})),e.reduce(((e,t)=>({...t,...e})),{})),n=new WeakMap;return{stringify:(e,r,o)=>JSON.stringify(e,(function(e){const o=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 _t;let i=n.get(r);if(void 0!==i)return i;const s=(o=e,gt.call(o).slice(8,-1)),a=Object.entries(t).find((([t,n])=>{var r,o;return null!==(o=null===(r=null==n?void 0:n.test)||void 0===r?void 0:r.call(n,e,s))&&void 0!==o?o:t===s}));return i=null==a?void 0:a[1],i||(i=Array.isArray(e)?null:"function"==typeof e?t.function||null:_t),n.set(r,i),i}default:return t[r]}var o}(o);return i?i.replace(o,r,t):o}),o),parse(e,n){let r=null,o=[];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}if(i===r){if(o.length>0){i={...i};for(const e of o)i[e.substr(1)]=i[e],delete i[e]}return o=[],i}return"$"===e[0]&&"$t"!==e&&(r=this,o.push(e)),i}))}}}const St={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 kt={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 xt={bigint:{replace:e=>({$t:"bigint",v:""+e}),revive:e=>BigInt(e.v)}};var Et={Date:{replace:e=>({$t:"Date",v:isNaN(e.getTime())?"NaN":e.toISOString()}),revive:({v:e})=>new Date("NaN"===e?NaN:Date.parse(e))}},It={Set:{replace:e=>({$t:"Set",v:Array.from(e.entries())}),revive:({v:e})=>new Set(e)}},Tt={Map:{replace:e=>({$t:"Map",v:Array.from(e.entries())}),revive:({v:e})=>new Map(e)}};const Ct="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"==typeof global?global:void 0;var At=["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 o=Ct[t];return o&&new o(r.ArrayBuffer.revive({v:e},n,r))}}})),{});function Pt(e){return function(e){for(var t="",n=0,r=e.length;n<r;n++)t+=$t[e[n]];return t}(rt(e))}function Ot(e){return nt(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+=Ut[e[n]];return t}(e))}const Ut={"-":"=",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:"+","|":"/"},$t={};for(const e of Object.keys(Ut))$t[Ut[e]]=e;var Nt={ArrayBuffer:{replace:e=>({$t:"ArrayBuffer",v:Pt(e)}),revive:({v:e})=>{const t=Ot(e);return t.buffer.byteLength===t.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}}};class Dt{constructor(e,t){this.buf=e,this.type=t}}function Rt(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 jt(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t[n]=e.charCodeAt(n);return t.buffer}const Lt={...kt,...xt,...Et,...It,...Tt,...At,...Nt,...{Blob:{test:(e,t)=>"Blob"===t||e instanceof Dt,replace:e=>({$t:"Blob",v:rt(e instanceof Dt?e.buf:jt(Rt(e))),type:e.type}),revive:({type:e,v:t})=>{const n=nt(t);return void 0!==typeof Blob?new Blob([n]):new Dt(n.buffer,e)}}}};function Bt(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 Wt={undefined:{replace:()=>{},revive:()=>{}}};const Ft="bigint"==typeof BigInt(0);function Mt(e){return"bigint"==typeof e?e:Ft?"string"==typeof e?BigInt(e):BigInt(e.v):Number("string"==typeof e?e:e.v)}function Ht(e,t){const n=Mt(e),r=Mt(t);return n<r?-1:n>r?1:0}class Vt{constructor(e){this.v=e}toString(){return this.v}}const Kt={...Wt,...Ft?{}:{bigint:{test:e=>e instanceof Vt,replace:e=>({$t:"bigint",...e}),revive:({v:e})=>new Vt(e)}}},qt=wt(Lt,Kt),zt=function(...e){const t=wt(Lt,St,...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);return[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])}))),r]},async parse(e,n){let r=0;const o=[],i=await Bt(n),s=new DataView(i);for(;r<i.byteLength;){const e=s.getUint32(r);r+=4;const t=i.slice(r,r+e);r+=e,o.push(t)}return t.parse(e,o)},async fromBinary(e){const t=new DataView(await Bt(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)}}}(Kt);async function Gt({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),o=await crypto.subtle.digest("SHA-1",r);return rt(o)}function Jt(e){return Object.entries(e.cloud.schema||{}).filter((([,{markedForSync:e}])=>e)).map((([t])=>e.table(t)))}function Yt(e){return`$${e}_mutations`}function Xt(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}async function Zt(e,t,{since:n={},limit:r=1/0}={}){return(await Promise.all(e.map((async e=>{const t=Xt(e.name),o=n[t];let i=o?e.where("rev").above(o):e;r<1/0&&(i=i.limit(r));return{table:t,muts:await i.toArray()}})))).filter((({muts:e})=>e.length>0))}async function Qt(e,t,n,r,o,i,s){const a={Accept:"application/json, application/x-bison, application/x-bison-stream","Content-Type":"application/tson"},c=await async function(e){var t,n;const r=await e.getCurrentUser(),{accessToken:o,accessTokenExpiration:i,refreshToken:s,refreshTokenExpiration:a,claims:c}=r;if(!o)return;if((null!==(t=null==i?void 0:i.getTime())&&void 0!==t?t:1/0)>Date.now())return o;if(!s)throw new Error("Refresh token missing");if((null!==(n=null==a?void 0:a.getTime())&&void 0!==n?n:1/0)<=Date.now())throw new Error("Refresh token has expired");const u=await ut(e.cloud.options.databaseUrl,r);return await e.table("$logins").update(c.sub,{accessToken:u.accessToken,accessTokenExpiration:u.accessTokenExpiration}),u.accessToken}(r);c&&(a.Authorization=`Bearer ${c}`);const u={dbID:null==t?void 0:t.remoteDbId,clientIdentity:s,schema:i||{},lastPull:t?{serverRevision:t.serverRevision,realms:t.realms,inviteRealms:t.inviteRealms}:void 0,baseRevs:n,changes:e};console.debug("Sync request",u),r.syncStateChangedEvent.next({phase:"pushing"});const l=await fetch(`${o}/sync`,{method:"post",headers:a,body:qt.stringify(u)});if(r.syncStateChangedEvent.next({phase:"pulling"}),!l.ok)throw new ht(l);switch(l.headers.get("content-type")){case"application/x-bison":return zt.fromBinary(await l.blob());case"application/x-bison-stream":default:case"application/json":{const e=await l.text();return qt.parse(e)}}}async function en(t,n,r){const o=await t.bulkGet(n),i=[],s=[];n.forEach(((n,a)=>{const c=o[a];if(c){for(const[n,o]of Object.entries(r[a])){if(n===t.schema.primKey.keyPath)throw new Error("Cannot change primary key");e.setByKeyPath(c,n,o)}i.push(n),s.push(c)}})),await(null==t.schema.primKey.keyPath?t.bulkPut(s,i):t.bulkPut(s))}function tn(t){if(null==t?void 0:t.cancelled)throw new e.AbortError("Operation was cancelled")}let nn=navigator.onLine;async function rn(e,t,n,r){await e.$baseRevs.bulkPut(Object.keys(t).filter((e=>t[e].markedForSync)).map((e=>({tableName:e,clientRev:(n[e]||0)+1,serverRev:r}))))}function on(e,t={}){for(const{table:n,muts:r}of e){const e=r.length>0&&r[r.length-1].rev||0;t[n]=e}return t}self.addEventListener("online",(()=>nn=!0)),self.addEventListener("offline",(()=>nn=!1));function sn(e,t,n,r){return an.apply(this,arguments).then((()=>{(null==r?void 0:r.justCheckIfNeeded)||e.syncStateChangedEvent.next({phase:"in-sync"})})).catch((async o=>(null==r?void 0:r.justCheckIfNeeded)?Promise.reject(o):(console.debug("Error from _sync",{isOnline:nn,syncOptions:r,error:o}),nn&&(null==r?void 0:r.retryImmediatelyOnFetchError)&&"TypeError"===(null==o?void 0:o.name)&&/fetch/.test(null==o?void 0:o.message)?(e.syncStateChangedEvent.next({phase:"error",error:o}),await new Promise((e=>setTimeout(e,500))),await sn(e,t,n,{...r,retryImmediatelyOnFetchError:!1})):(await e.$syncState.update("syncState",{timestamp:new Date,error:""+o}),e.syncStateChangedEvent.next({phase:nn?"error":"offline",error:o}),Promise.reject(o)))))}async function an(e,t,n,{isInitialSync:r,cancelToken:o,justCheckIfNeeded:i,purpose:s}={isInitialSync:!1}){var a;if(i||console.debug("SYNC STARTED",{isInitialSync:r,purpose:s}),!(null===(a=e.cloud.options)||void 0===a?void 0:a.databaseUrl))throw new Error("Internal error: sync must not be called when no databaseUrl is configured");const{databaseUrl:c}=t,u=await e.getCurrentUser(),l=u.isLoggedIn?Jt(e):[],d=l.map((t=>e.table(Yt(t.name)))),h=await e.getPersistedSyncState(),f=!r&&u.isLoggedIn?function(e,t){const n=(null==t?void 0:t.syncedTables)||[];return Jt(e).filter((e=>!n.includes(e.name)))}(e,h):[];tn(o);const b=f.length>0;if(b){if(i)return!0;console.debug("sync doSyncify is true"),await e.transaction("rw",f,(async e=>{e.idbtrans.disableChangeTracking=!0,e.idbtrans.disableAccessControl=!0,await async function(e,t,n){const r=new Set(n||[]);for(const n of e)"members"===n.name?await n.toCollection().modify((e=>{r.has(e.realmId)||e.userId!==pt.userId||(e.userId=t.userId)})):"roles"===n.name||("realms"===n.name?await n.toCollection().modify((e=>{(r.has(e.realmId)||e.owner)&&e.owner!==pt.userId||(e.owner=t.userId)})):await n.toCollection().modify((e=>{e.realmId&&r.has(e.realmId)||(e.owner&&e.owner!==pt.userId||(e.owner=t.userId),e.realmId&&e.realmId!==pt.userId||(e.realmId=t.userId))})))}(f,u,null==h?void 0:h.realms)})),tn(o)}const[v,m,g]=await e.transaction("r",e.tables,(async()=>{const t=await e.getPersistedSyncState(),r=await e.$baseRevs.toArray();let i=await Zt(d);if(tn(o),b){const e=await async function(e,t,n,r){if(t.isLoggedIn&&e.length>0){const o=new Set(r||[]);return(await Promise.all(e.map((async e=>{const{extractKey:r}=e.core.schema.primaryKey;if(!r)return{table:e.name,muts:[]};const i=n[e.name],s=(null==i?void 0:i.generatedGlobalId)?e.filter((e=>!o.has(e.realmId||"")&&y(r(e)))):e.filter((e=>{return!o.has(e.realmId||"")&&(t=r(e),!(n=null==i?void 0:i.idPrefix)||"string"==typeof t&&t.startsWith(n));var t,n})),a=await s.toArray();if(a.length>0){const n={type:"insert",values:a,keys:a.map(r),userId:t.userId};return{table:e.name,muts:[n]}}return{table:e.name,muts:[]}})))).filter((e=>e.muts.length>0))}return[]}(f,u,n,null==h?void 0:h.realms);return tn(o),i=i.concat(e),[i,t,r]}return[i,t,r]})),_=v.some((e=>e.muts.some((e=>e.keys.length>0))));if(i)return console.debug("Sync is needed:",_),_;if("push"===s&&!_)return!1;const w=on(v,null==m?void 0:m.latestRevisions),S=(null==m?void 0:m.clientIdentity)||p(16);tn(o);const k=await Qt(v,m,g,e,c,n,S);console.debug("Sync response",k);return await e.transaction("rw",e.tables,(async t=>{t.idbtrans.disableChangeTracking=!0,t.idbtrans.disableAccessControl=!0;for(const e of Object.keys(n))k.schema[e]&&(n[e]=k.schema[e]);await e.$syncState.put(n,"schema");const r=await Zt(d,0,{since:w});for(const t of d){const n=Xt(t.name);if(r.some((e=>e.table===n&&e.muts.length>0))){if(w[t.name]){const r=w[t.name]||0;await 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 await Promise.all([t.clear(),e.$baseRevs.where({tableName:n}).delete()])}on(r,w),await rn(e,n,w,k.serverRevision);const o=await e.getPersistedSyncState();await async function(e,t,n){const r=[],o=n?n.realms.concat(n.inviteRealms):[],i=new Set([...t.realms,...t.inviteRealms]);for(const e of o)i.has(e)||r.push(e);if(r.length>0){const t=new Set(r),n=Jt(e);for(const e of n)e.schema.indexes.some((e=>"realmId"===e.keyPath||Array.isArray(e.keyPath)&&"realmId"===e.keyPath[0]))?await e.where("realmId").anyOf(r).delete():await e.filter((e=>!!(null==e?void 0:e.realmId)&&t.has(e.realmId))).delete()}}(e,k,o);const i=o||{syncedTables:[],latestRevisions:{},realms:[],inviteRealms:[],clientIdentity:S};i.syncedTables=l.map((e=>e.name)).concat(f.map((e=>e.name))),i.latestRevisions=w,i.remoteDbId=k.dbId,i.initiallySynced=!0,i.realms=k.realms,i.inviteRealms=k.inviteRealms,i.serverRevision=k.serverRevision,i.timestamp=new Date,delete i.error;const s=un(k.changes,r);return await cn(s,e),e.$syncState.put(i,"syncState"),0===r.length}))?(console.debug("SYNC DONE",{isInitialSync:r}),!1):(console.debug("MORE SYNC NEEDED. Go for it again!"),await an(e,t,n,{isInitialSync:r,cancelToken:o}))}async function cn(t,n){console.debug("Applying server changes",t,e.currentTransaction);for(const{table:r,muts:o}of t){const t=n.table(r);if(!t)continue;const{primaryKey:i}=t.core.schema;for(const n of o)switch(n.type){case"insert":i.outbound?await t.bulkAdd(n.values,n.keys):(n.keys.forEach(((t,r)=>{e.setByKeyPath(n.values[r],i.keyPath,t)})),await t.bulkAdd(n.values));break;case"upsert":i.outbound?await t.bulkPut(n.values,n.keys):(n.keys.forEach(((t,r)=>{e.setByKeyPath(n.values[r],i.keyPath,t)})),await t.bulkPut(n.values));break;case"modify":1===n.keys.length?await t.update(n.keys[0],n.changeSpec):await t.where(":id").anyOf(n.keys).modify(n.changeSpec);break;case"update":await en(t,n.keys,n.changeSpecs);break;case"delete":await t.bulkDelete(n.keys)}}}function un(e,t){const n={};m(n,e);const r={};return m(r,t),function(e,t){var n,r,o;for(const[i,s]of Object.entries(t))for(const[t,a]of Object.entries(s))switch(a.type){case"ups":{const r=null===(n=e[i])||void 0===n?void 0:n[t];if(r)switch(r.type){case"ups":delete e[i][t];break;case"del":break;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===(o=e[i])||void 0===o?void 0:o[t];if(n)switch(n.type){case"ups":for(const[e,t]of Object.entries(a.mod))f(n.val,e,t);break;case"del":break;case"upd":for(const e of Object.keys(a.mod))delete n.mod[e]}break}}}(n,r),function(e){const t=p(16),n={};for(const[t,r]of Object.entries(e))for(const[e,o]of Object.entries(r)){const r=n[t]||(n[t]={});(r[o.type]||(r[o.type]=[])).push(Object.assign({key:e},o))}const r=[];for(const[e,o]of Object.entries(n)){const n={table:e,muts:[]};for(const[e,r]of Object.entries(o))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)}function ln(t){const n=[],o=new r(!0),i=new r(null);let s=!1;return i.subscribe((async()=>{if(!s&&n.length>0){s=!0,o.next(!1);try{await async function(){var r,o,i;for(;n.length>0;){const s=n.shift();try{console.debug("processing msg",s),await t.cloud.syncState.pipe(Ue((({phase:e})=>"in-sync"===e||"error"===e)),De(1)).toPromise(),console.debug("processing msg",s);const n=t.cloud.persistedSyncState.value;if(!s)continue;switch(s.type){case"token-expired":console.debug("WebSocket observable: Token expired. Refreshing token...");const a=t.cloud.currentUser.value,c=await ut(t.cloud.options.databaseUrl,a);await t.table("$logins").update(a.userId,{accessToken:c.accessToken,accessTokenExpiration:c.accessTokenExpiration});break;case"rev":(!(null==n?void 0:n.serverRevision)||Ht(n.serverRevision,s.rev)<0)&&tt(t,"pull");break;case"realm-added":(null===(r=null==n?void 0:n.realms)||void 0===r?void 0:r.includes(s.realm))||tt(t,"pull");break;case"realm-removed":(null===(o=null==n?void 0:n.realms)||void 0===o?void 0:o.includes(s.realm))&&tt(t,"pull");break;case"changes":if(console.debug("changes"),"error"===(null===(i=t.cloud.syncState.value)||void 0===i?void 0:i.phase)){tt(t,"pull");break}await t.transaction("rw",t.dx.tables,(async n=>{n.idbtrans.disableChangeTracking=!0,n.idbtrans.disableAccessControl=!0;const[r,o,i]=await Promise.all([t.getSchema(),t.getPersistedSyncState(),t.getCurrentUser()]);if(console.debug("ws message queue: in transaction"),!o||!r||!i)return void console.debug("required vars not present",{syncState:o,schema:r,currentUser:i});if(0!==Ht(s.baseRev,o.serverRevision))return void console.debug(`baseRev (${s.baseRev}) differs from our serverRevision in syncState (${o.serverRevision})`);const a=await e.waitFor(Gt(o));if(console.debug("ourRealmSetHash",a),a!==s.realmSetHash)return console.debug("not same realmSetHash",s.realmSetHash),void tt(t,"pull");let c=[];if(i.isLoggedIn){const e=Jt(t).map((e=>t.table(Yt(e.name))));c=await Zt(e),console.debug("msg queue: client changes",c)}const u=un(s.changes,c);console.debug("applying filtered server changes",u),await cn(u,t),o.latestRevisions=on(c,o.latestRevisions),o.serverRevision=s.newRev,console.debug("Updating baseRefs",o.latestRevisions),await rn(t,r,o.latestRevisions,s.newRev),console.debug("Updating syncState",o),await t.$syncState.put(o,"syncState")})),console.debug("msg queue: done with rw transaction")}}catch(e){console.error("Error in msg queue",e)}}}()}finally{s=!1,o.next(!0)}}})),{enqueue:function(e){n.push(e),i.next(null)},readyToServe:o}}const dn=new WeakMap,hn={realms:"@realmId",members:"@id",roles:"[realmId+name]",$jobs:"",$syncState:"",$baseRevs:"[tableName+clientRev]",$logins:"claims.sub, lastLogin"};let fn=0;function pn(e){"vip"in e&&(e=e.vip);let t=dn.get(e.cloud);if(!t){const n=new o;let r=new mt(`syncstatechanged-${e.name}`);n.id=++fn;let i=!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 i},localSyncEvent:n,get syncStateChangedEvent(){return r},dx:e};const s={getCurrentUser:()=>t.$logins.toArray().then((e=>e.find((e=>e.isLoggedIn))||pt)),getPersistedSyncState:()=>t.$syncState.get("syncState"),getSchema:()=>t.$syncState.get("schema"),getOptions:()=>t.$syncState.get("options"),setInitiallySynced(e){i=e},reconfigure(){r=new mt(`syncstatechanged-${e.name}`)}};Object.assign(t,s),t.messageConsumer=ln(t),dn.set(e.cloud,t)}return t}const yn="undefined"!=typeof InstallTrigger,bn="undefined"!=typeof navigator&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\/|Edge\//.test(navigator.userAgent),vn=bn?[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]:NaN,mn=bn&&vn<=605||yn;const gn="undefined"!=typeof self&&"clients"in self&&!self.document;function _n(){throw new e.SchemaError("Version increment needed to allow dexie-cloud change tracking")}const{toString:wn}={};function Sn(e){return wn.call(e).slice(8,-1)}function kn(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 xn=/b|c|d|f|g|h|j|k|l|m|n|p|q|r|s|t|v|x|y|z/i;let En=0;function In(t){return{stack:"dbcore",name:"idGenerationMiddleware",level:1,create:n=>({...n,table:r=>{const o=n.table(r);function i(n,i){let s=null;const a=kn(o.schema.primaryKey,n);return a.forEach(((c,u)=>{if(void 0===c){const r=n.values[u].realmId||t.cloud.currentUserId,c=r.substr(r.length-3);a[u]=function(e,t){const n=new Uint8Array(18),r=new Uint8Array(n.buffer,0,6),o=Date.now();En>=o?++En:En=o,r[0]=En/1099511627776,r[1]=En/4294967296,r[2]=En/16777216,r[3]=En/65536,r[4]=En/256,r[5]=En;const i=new Uint8Array(n.buffer,6);return crypto.getRandomValues(i),e+Pt(new Uint8Array(n.buffer))+(t||"")}(i,c),o.schema.primaryKey.outbound||(s||(s=n.values.slice()),s[u]=e.deepClone(s[u]),e.setByKeyPath(s[u],o.schema.primaryKey.keyPath,a[u]))}else if("string"!=typeof c||!c.startsWith(i))throw new e.ConstraintError(`The ID "${c}" is not valid for table "${r}". Primary '@' keys requires the key to be prefixed with "${i}.\n"If 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.`)})),o.mutate({...n,keys:a,values:s||n.values})}return{...o,mutate:n=>{var s,a;if(n.trans.disableChangeTracking)return o.mutate(n);if("add"===n.type||"put"===n.type){const c=null===(s=t.cloud.schema)||void 0===s?void 0:s[r];if(null==c?void 0:c.generatedGlobalId){if((null===(a=t.cloud.options)||void 0===a?void 0:a.databaseUrl)&&!t.initiallySynced){const e=kn(o.schema.primaryKey,n);return o.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 o.mutate(n)}))}return i(n,c.idPrefix)}if(null==c?void 0:c.markedForSync){kn(o.schema.primaryKey,n).forEach(((t,n)=>{if(!y(t)){const n=Array.isArray(t)?t.map(Sn).join(","):Sn(t);throw new e.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 o.mutate(n)}}}})}}function Tn(e){const t=new Uint8Array(e);return crypto.getRandomValues(t),btoa(String.fromCharCode.apply(null,t))}let Cn=0;function An(e,t){return function(n){const{readers:r,writers:o}=n.trans[t]||(n.trans[t]={writers:[],readers:[]}),i=o.length,s=(i>0?o[i-1].then((()=>e(n)),(()=>e(n))):e(n)).finally((()=>r.splice(r.indexOf(s))));return r.push(s),s}}function Pn(e,t){return function(n){const{readers:r,writers:o}=n.trans[t]||(n.trans[t]={writers:[],readers:[]});let i=(o.length>0?o[o.length-1].then((()=>e(n)),(()=>e(n))):r.length>0?(s=r,new Promise((e=>{0===s.length&&e([]);let t=s.length;const n=new Array(t);s.forEach(((r,o)=>Promise.resolve(r).then((e=>n[o]={status:"fulfilled",value:e}),(e=>n[o]={status:"rejected",reason:e})).then((()=>--t||e(n)))))}))).then((()=>e(n))):e(n)).finally((()=>o.shift()));var s;return o.push(i),i}}const On=new r(new Set);function Un({currentUserObservable:e,db:t}){return{stack:"dbcore",name:"MutationTrackingMiddleware",level:1,create:n=>{const r=n.schema.tables.filter((e=>!/^\$/.test(e.name)));let o;try{o=new Map(r.map((e=>[e.name,n.table(`$${e.name}_mutations`)])))}catch(e){_n()}return{...n,transaction:(r,o)=>{let i;if("readwrite"===o){const e=r.filter((e=>{var n,r;return null===(r=null===(n=t.cloud.schema)||void 0===n?void 0:n[e])||void 0===r?void 0:r.markedForSync})).map((e=>Yt(e)));i=n.transaction([...r,...e],o)}else i=n.transaction(r,o);if("readwrite"===o){i.txid=Tn(16),i.currentUser=e.value,On.value.add(i),On.next(On.value);const n=()=>{i.removeEventListener("complete",r),i.removeEventListener("error",n),i.removeEventListener("abort",n),On.value.delete(i),On.next(On.value)},r=()=>{var e;i.mutationsAdded&&(null===(e=t.cloud.options)||void 0===e?void 0:e.databaseUrl)&&(t.cloud.usingServiceWorker?(console.debug("registering sync event"),et(t,"push")):t.localSyncEvent.next({purpose:"push"})),n()};i.addEventListener("complete",r),i.addEventListener("error",n),i.addEventListener("abort",n)}return i},table:e=>{const t=n.table(e);if(/^\$/.test(e))return e.endsWith("_mutations")?{...t,mutate:e=>("add"!==e.type&&"put"!==e.type||(e.trans.mutationsAdded=!0),t.mutate(e))}:"$logins"===e?{...t,mutate:e=>(console.debug("Mutating $logins table",e),t.mutate(e).then((t=>(console.debug("Mutating $logins"),e.trans.mutationsAdded=!0,console.debug("$logins mutated"),t))).catch((e=>(console.debug("Failed mutation $logins",e),Promise.reject(e)))))}:t;const{schema:r}=t,i=o.get(e);return function(e){const t="$lock"+ ++Cn;return{...e,count:An(e.count,t),get:An(e.get,t),getMany:An(e.getMany,t),openCursor:An(e.openCursor,t),query:An(e.query,t),mutate:Pn(e.mutate,t)}}({...t,mutate:e=>{var n;const o=e.trans;return o.txid?o.disableChangeTracking?t.mutate(e):(null===(n=o.currentUser)||void 0===n?void 0:n.isLoggedIn)?"deleteRange"===e.type?t.query({query:{range:e.range,index:r.primaryKey},trans:e.trans,values:!1}).then((t=>s({type:"delete",keys:t.result,trans:e.trans,criteria:{index:null,range:e.range}}))):s(e):t.mutate(e):t.mutate(e)}});function s(e){const n=e.trans;n.mutationsAdded=!0;const{txid:r,currentUser:{userId:o}}=n,{type:s}=e;return t.mutate(e).then((t=>{const{numFailures:a,failures:c}=t;let u="delete"===s?e.keys:t.results,l="values"in e?e.values:[],d="changeSpecs"in e?e.changeSpecs:[];a&&(u=u.filter(((e,t)=>!c[t])),l=l.filter(((e,t)=>!c[t])),d=d.filter(((e,t)=>!c[t])));const h=Date.now(),f="delete"===e.type?{type:"delete",ts:h,keys:u,criteria:e.criteria,txid:r,userId:o}:"add"===e.type?{type:"insert",ts:h,keys:u,txid:r,userId:o,values:l}:e.criteria&&e.changeSpec?{type:"modify",ts:h,keys:u,criteria:e.criteria,changeSpec:e.changeSpec,txid:r,userId:o}:e.changeSpecs?{type:"update",ts:h,keys:u,changeSpecs:d,txid:r,userId:o}:{type:"upsert",ts:h,keys:u,values:l,txid:r,userId:o};return u.length>0||"criteria"in e&&e.criteria?i.mutate({type:"add",trans:n,values:[f]}).then((()=>t)):t}))}}}}}}function $n(e,t){return function(n,r){const o={...hn,...n},i=t.cloud.schema||(t.cloud.schema={}),s=new Set;Object.keys(o).forEach((e=>{const t=o[e],n=i[e]||(i[e]={});null!=t?(/^\@/.test(t)&&(o[e]=o[e].substr(1),n.generatedGlobalId=!0,n.idPrefix=function(e,t){let n=e[0].toLocaleLowerCase();for(let t=1,o=e.length;t<o&&n.length<3;++t)(xn.test(e[t])||(r=e[t])>="A"&&r<="Z")&&(n+=e[t].toLowerCase());for(var r,o,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;)o=n,r=(1&(i=e)?o[0].toUpperCase():o[0].toLowerCase())+(2&i?o[1].toUpperCase():o[1].toLowerCase())+(4&i?o[2].toUpperCase():o[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,s),s.add(n.idPrefix)),/^\$/.test(e)||(o[`$${e}_mutations`]="++rev",n.markedForSync=!0),n.deleted&&(n.deleted=!1)):(n.deleted=!0,n.markedForSync=!1,o[`$${e}_mutations`]=null)}));return e.call(this,o,r)}}const Nn=Tn(16);async function Dn(e,n,r,o,{awaitRemoteJob:s}={}){const a=e.table(r);if(await async function o(){if(await e.transaction("rw!",r,(async()=>{const e=await a.get(n);return e?e.heartbeat.getTime()<Date.now()-6e4&&(console.warn(`Latest ${n} worker seem to have died.\n`,"The dead job started:",e.started,"\n","Last heart beat was:",e.heartbeat,"\n","We're now taking over!"),await a.put({nodeId:Nn,started:new Date,heartbeat:new Date},n),!0):(await a.add({nodeId:Nn,started:new Date,heartbeat:new Date},n),!0)})))return!0;if(s)try{const e=i(t((()=>a.get(n)))).pipe(Ze(6e4),Ue((e=>!e)));return await e.toPromise(),!1}catch(e){if("TimeoutError"!==e.name)throw e;return await o()}return!1}()){const t=setInterval((()=>{a.update(n,(e=>e.nodeId===Nn&&(e.heartbeat=new Date)))}),1e3);try{return await o()}finally{clearInterval(t),await e.transaction("rw!",r,(async()=>{const e=await a.get(n);e&&e.nodeId===Nn&&a.delete(n)}))}}}const Rn=new r(!0),jn=new r(!0);var Ln,Bn;Rn.pipe(Me((e=>e?a(!0):a(!1).pipe(Ee(2e4)))),(function(e){return e.lift(new Ae(Ln,Bn))})).subscribe(jn);const Wn="undefined"!=typeof document?s(document,"visibilitychange"):a({}),Fn=Wn.pipe(Ue((()=>"hidden"===document.visibilityState))),Mn=Wn.pipe(Ue((()=>"visible"===document.visibilityState))),Hn="undefined"!=typeof window?c(Mn,s(window,"mousemove"),s(window,"keydown"),s(window,"wheel"),s(window,"touchmove")):a({});"undefined"!=typeof document&&c(a(!0),Fn,Hn).pipe(se((()=>"visible"===document.visibilityState)),qe((e=>{Rn.value!==e&&Rn.next(e)})),Me((e=>e?a(0).pipe(Ee(28e4),qe((()=>Rn.next(!1)))):a(0)))).subscribe((()=>{}));class Vn extends Error{constructor(){super(...arguments),this.name="TokenExpiredError"}}class Kn extends n{constructor(e,t,n,r,o,i,s){super((a=>new zn(e,t,n,i,s,a,r,o)))}}let qn=0;class zn extends u{constructor(e,t,n,r,o,i,s,a){super((()=>this.teardown())),this.id=++qn,console.debug("New WebSocket Connection",this.id,r?"authorized":"unauthorized"),this.databaseUrl=e,this.rev=t,this.clientIdentity=n,this.token=r,this.tokenExpiration=o,this.subscriber=i,this.lastUserActivity=new Date,this.messageProducer=s,this.messageProducerSubscription=null,this.webSocketStatus=a,this.connect()}teardown(){console.debug("Teardown WebSocket Connection",this.id),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,this.messageProducerSubscription&&(this.messageProducerSubscription.unsubscribe(),this.messageProducerSubscription=null)}reconnect(){this.disconnect(),this.connect()}async connect(){if(this.webSocketStatus.next("connecting"),this.lastServerActivity=new Date,this.pauseUntil&&this.pauseUntil>new Date)return void console.debug("WS not reconnecting just yet",{id:this.id,pauseUntil:this.pauseUntil});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;if(this.tokenExpiration&&this.tokenExpiration<new Date)return void this.subscriber.error(new Vn);this.pinger=setInterval((async()=>{if(this.closed)return console.debug("pinger check",this.id,"CLOSED."),void this.teardown();if(this.ws)try{this.ws.send(JSON.stringify({type:"ping"})),setTimeout((()=>{if(console.debug("pinger setTimeout",this.id,this.pinger?"alive":"dead"),this.pinger)return this.closed?(console.debug("pinger setTimeout",this.id,"subscription is closed"),void this.teardown()):void(this.lastServerActivity<new Date(Date.now()-2e4)?(console.debug("pinger: server is inactive"),console.debug("pinger reconnecting"),this.reconnect()):console.debug("pinger: server still active"))}),2e4)}catch(e){console.debug("pinger catch error",this.id,"reconnecting"),this.reconnect()}else console.debug("pinger",this.id,"reconnecting"),this.reconnect()}),3e4);const e=new URL(this.databaseUrl);e.protocol="http:"===e.protocol?"ws":"wss";const t=new URLSearchParams;if(this.subscriber.closed)return;t.set("rev",this.rev),t.set("clientId",this.clientIdentity),this.token&&t.set("token",this.token),console.debug("dexie-cloud WebSocket create");const n=this.ws=new WebSocket(`${e}/changes?${t}`);n.onclose=e=>{this.pinger&&(console.debug("dexie-cloud WebSocket onclosed",this.id),this.reconnect())},n.onmessage=e=>{if(this.pinger){console.debug("dexie-cloud WebSocket onmessage",e.data),this.lastServerActivity=new Date;try{const t=qt.parse(e.data);if("error"===t.type)throw new Error(`Error message from dexie-cloud: ${t.error}`);"rev"===t.type&&(this.rev=t.rev),"pong"!==t.type&&this.subscriber.next(t)}catch(e){this.subscriber.error(e)}}};try{await new Promise(((e,t)=>{n.onopen=t=>{console.debug("dexie-cloud WebSocket onopen"),e(null)},n.onerror=e=>{const n=e.error||new Error("WebSocket Error");this.disconnect(),this.subscriber.error(n),this.webSocketStatus.next("error"),t(n)}})),this.messageProducerSubscription=this.messageProducer.subscribe((e=>{var t;this.closed||("ready"===e.type&&"connected"!==this.webSocketStatus.value&&this.webSocketStatus.next("connected"),null===(t=this.ws)||void 0===t||t.send(qt.stringify(e)))}))}catch(e){this.pauseUntil=new Date(Date.now()+6e4)}}}async function Gn(e){var t;console.error("WebSocket observable: error but revive when user does some active thing...",e),await(t=3e3,new Promise((e=>setTimeout(e,t)))),console.debug("waiting for someone to do something"),await Hn.pipe(De(1)).toPromise(),console.debug("someone did something!")}async function Jn(e){var t;return!(!(null===(t=e.cloud.options)||void 0===t?void 0:t.databaseUrl)||!e.cloud.schema)&&await sn(e,e.cloud.options,e.cloud.schema,{justCheckIfNeeded:!0})}const Yn=new WeakMap;function Xn(e,t,n,r){const o=Yn.get(e);if(o){if(o.pull||"push"===(null==r?void 0:r.purpose))return console.debug("syncIfPossible(): returning the ongoing sync promise."),o.promise;{let i=!1;const s=e.cloud.syncState.subscribe((e=>{"pulling"===e.phase&&(i=!0)}));return o.promise.then((()=>{s.unsubscribe()})).catch((e=>(s.unsubscribe(),Promise.reject(e)))).then((()=>{if(!i)return Xn(e,t,n,r)}))}}const i=async function(){try{e.cloud.usingServiceWorker?gn&&await sn(e,t,n,r):await Dn(e,"currentSyncWorker","$jobs",(()=>sn(e,t,n,r))),Yn.delete(e),console.debug("Done sync")}catch(t){throw Yn.delete(e),console.error("Failed to sync client changes",t),t}}();return Yn.set(e,{promise:i,pull:"push"!==(null==r?void 0:r.purpose)}),i}function Zn(e,t,n){let r=null,o={cancelled:!1};function i(r,a=1){Xn(e,t,n,{cancelToken:o,retryImmediatelyOnFetchError:!0,purpose:r}).catch((e=>{console.error("error in syncIfPossible()",e),o.cancelled?s():a<3&&setTimeout((()=>i(r,a+1)),6e4*[0,5,15][a])}))}const s=()=>{console.debug("Stopping LocalSyncWorker"),o.cancelled=!0,r&&r.unsubscribe()};return{start:()=>{console.debug("Starting LocalSyncWorker",e.localSyncEvent.id),r=e.localSyncEvent.subscribe((({purpose:e})=>{try{i(e||"pull")}catch(e){console.error("What-the....",e)}}))},stop:s}}function Qn(e,t){if(e&&t&&t.unsyncedTables)for(const n of t.unsyncedTables)e[n]&&(e[n].markedForSync=!1)}var er,tr,nr,rr,or={},ir=[],sr=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i;function ar(e,t){for(var n in t)e[n]=t[n];return e}function cr(e){var t=e.parentNode;t&&t.removeChild(e)}function ur(e,t,n){var r,o,i,s=arguments,a={};for(i in t)"key"==i?r=t[i]:"ref"==i?o=t[i]:a[i]=t[i];if(arguments.length>3)for(n=[n],i=3;i<arguments.length;i++)n.push(s[i]);if(null!=n&&(a.children=n),"function"==typeof e&&null!=e.defaultProps)for(i in e.defaultProps)void 0===a[i]&&(a[i]=e.defaultProps[i]);return lr(e,a,r,o,null)}function lr(e,t,n,r,o){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==o?++er.__v:o};return null!=er.vnode&&er.vnode(i),i}function dr(e){return e.children}function hr(e,t){this.props=e,this.context=t}function fr(e,t){if(null==t)return e.__?fr(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?fr(e):null}function pr(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 pr(e)}}function yr(e){(!e.__d&&(e.__d=!0)&&tr.push(e)&&!br.__r++||rr!==er.debounceRendering)&&((rr=er.debounceRendering)||nr)(br)}function br(){for(var e;br.__r=tr.length;)e=tr.sort((function(e,t){return e.__v.__b-t.__v.__b})),tr=[],e.some((function(e){var t,n,r,o,i,s;e.__d&&(i=(o=(t=e).__v).__e,(s=t.__P)&&(n=[],(r=ar({},o)).__v=o.__v+1,xr(s,o,r,t.__n,void 0!==s.ownerSVGElement,null!=o.__h?[i]:null,n,null==i?fr(o):i,o.__h),Er(n,o),o.__e!=i&&pr(o)))}))}function vr(e,t,n,r,o,i,s,a,c,u){var l,d,h,f,p,y,b,v=r&&r.__k||ir,m=v.length;for(n.__k=[],l=0;l<t.length;l++)if(null!=(f=n.__k[l]=null==(f=t[l])||"boolean"==typeof f?null:"string"==typeof f||"number"==typeof f||"bigint"==typeof f?lr(null,f,null,null,f):Array.isArray(f)?lr(dr,{children:f},null,null,null):f.__b>0?lr(f.type,f.props,f.key,null,f.__v):f)){if(f.__=n,f.__b=n.__b+1,null===(h=v[l])||h&&f.key==h.key&&f.type===h.type)v[l]=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}xr(e,f,h=h||or,o,i,s,a,c,u),p=f.__e,(d=f.ref)&&h.ref!=d&&(b||(b=[]),h.ref&&b.push(h.ref,null,f),b.push(d,f.__c||p,f)),null!=p?(null==y&&(y=p),"function"==typeof f.type&&null!=f.__k&&f.__k===h.__k?f.__d=c=mr(f,c,e):c=gr(e,f,h,v,p,c),u||"option"!==n.type?"function"==typeof n.type&&(n.__d=c):e.value=""):c&&h.__e==c&&c.parentNode!=e&&(c=fr(h))}for(n.__e=y,l=m;l--;)null!=v[l]&&("function"==typeof n.type&&null!=v[l].__e&&v[l].__e==n.__d&&(n.__d=fr(r,l+1)),Cr(v[l],v[l]));if(b)for(l=0;l<b.length;l++)Tr(b[l],b[++l],b[++l])}function mr(e,t,n){var r,o;for(r=0;r<e.__k.length;r++)(o=e.__k[r])&&(o.__=e,t="function"==typeof o.type?mr(o,t,n):gr(n,o,o,e.__k,o.__e,t));return t}function gr(e,t,n,r,o,i){var s,a,c;if(void 0!==t.__d)s=t.__d,t.__d=void 0;else if(null==n||o!=i||null==o.parentNode)e:if(null==i||i.parentNode!==e)e.appendChild(o),s=null;else{for(a=i,c=0;(a=a.nextSibling)&&c<r.length;c+=2)if(a==o)break e;e.insertBefore(o,i),s=i}return void 0!==s?s:o.nextSibling}function _r(e,t,n){"-"===t[0]?e.setProperty(t,n):e[t]=null==n?"":"number"!=typeof n||sr.test(t)?n:n+"px"}function wr(e,t,n,r,o){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||_r(e.style,t,"");if(n)for(t in n)r&&n[t]===r[t]||_r(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?kr:Sr,i):e.removeEventListener(t,i?kr:Sr,i);else if("dangerouslySetInnerHTML"!==t){if(o)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 Sr(e){this.l[e.type+!1](er.event?er.event(e):e)}function kr(e){this.l[e.type+!0](er.event?er.event(e):e)}function xr(e,t,n,r,o,i,s,a,c){var u,l,d,h,f,p,y,b,v,m,g,_=t.type;if(void 0!==t.constructor)return null;null!=n.__h&&(c=n.__h,a=t.__e=n.__e,t.__h=null,i=[a]),(u=er.__b)&&u(t);try{e:if("function"==typeof _){if(b=t.props,v=(u=_.contextType)&&r[u.__c],m=u?v?v.props.value:u.__:r,n.__c?y=(l=t.__c=n.__c).__=l.__E:("prototype"in _&&_.prototype.render?t.__c=l=new _(b,m):(t.__c=l=new hr(b,m),l.constructor=_,l.render=Ar),v&&v.sub(l),l.props=b,l.state||(l.state={}),l.context=m,l.__n=r,d=l.__d=!0,l.__h=[]),null==l.__s&&(l.__s=l.state),null!=_.getDerivedStateFromProps&&(l.__s==l.state&&(l.__s=ar({},l.__s)),ar(l.__s,_.getDerivedStateFromProps(b,l.__s))),h=l.props,f=l.state,d)null==_.getDerivedStateFromProps&&null!=l.componentWillMount&&l.componentWillMount(),null!=l.componentDidMount&&l.__h.push(l.componentDidMount);else{if(null==_.getDerivedStateFromProps&&b!==h&&null!=l.componentWillReceiveProps&&l.componentWillReceiveProps(b,m),!l.__e&&null!=l.shouldComponentUpdate&&!1===l.shouldComponentUpdate(b,l.__s,m)||t.__v===n.__v){l.props=b,l.state=l.__s,t.__v!==n.__v&&(l.__d=!1),l.__v=t,t.__e=n.__e,t.__k=n.__k,t.__k.forEach((function(e){e&&(e.__=t)})),l.__h.length&&s.push(l);break e}null!=l.componentWillUpdate&&l.componentWillUpdate(b,l.__s,m),null!=l.componentDidUpdate&&l.__h.push((function(){l.componentDidUpdate(h,f,p)}))}l.context=m,l.props=b,l.state=l.__s,(u=er.__r)&&u(t),l.__d=!1,l.__v=t,l.__P=e,u=l.render(l.props,l.state,l.context),l.state=l.__s,null!=l.getChildContext&&(r=ar(ar({},r),l.getChildContext())),d||null==l.getSnapshotBeforeUpdate||(p=l.getSnapshotBeforeUpdate(h,f)),g=null!=u&&u.type===dr&&null==u.key?u.props.children:u,vr(e,Array.isArray(g)?g:[g],t,n,r,o,i,s,a,c),l.base=t.__e,t.__h=null,l.__h.length&&s.push(l),y&&(l.__E=l.__=null),l.__e=!1}else null==i&&t.__v===n.__v?(t.__k=n.__k,t.__e=n.__e):t.__e=Ir(n.__e,t,n,r,o,i,s,c);(u=er.diffed)&&u(t)}catch(e){t.__v=null,(c||null!=i)&&(t.__e=a,t.__h=!!c,i[i.indexOf(a)]=null),er.__e(e,t,n)}}function Er(e,t){er.__c&&er.__c(t,e),e.some((function(t){try{e=t.__h,t.__h=[],e.some((function(e){e.call(t)}))}catch(e){er.__e(e,t.__v)}}))}function Ir(e,t,n,r,o,i,s,a){var c,u,l,d,h=n.props,f=t.props,p=t.type,y=0;if("svg"===p&&(o=!0),null!=i)for(;y<i.length;y++)if((c=i[y])&&(c===e||(p?c.localName==p:3==c.nodeType))){e=c,i[y]=null;break}if(null==e){if(null===p)return document.createTextNode(f);e=o?document.createElementNS("http://www.w3.org/2000/svg",p):document.createElement(p,f.is&&f),i=null,a=!1}if(null===p)h===f||a&&e.data===f||(e.data=f);else{if(i=i&&ir.slice.call(e.childNodes),u=(h=n.props||or).dangerouslySetInnerHTML,l=f.dangerouslySetInnerHTML,!a){if(null!=i)for(h={},d=0;d<e.attributes.length;d++)h[e.attributes[d].name]=e.attributes[d].value;(l||u)&&(l&&(u&&l.__html==u.__html||l.__html===e.innerHTML)||(e.innerHTML=l&&l.__html||""))}if(function(e,t,n,r,o){var i;for(i in n)"children"===i||"key"===i||i in t||wr(e,i,null,n[i],r);for(i in t)o&&"function"!=typeof t[i]||"children"===i||"key"===i||"value"===i||"checked"===i||n[i]===t[i]||wr(e,i,t[i],n[i],r)}(e,f,h,o,a),l)t.__k=[];else if(y=t.props.children,vr(e,Array.isArray(y)?y:[y],t,n,r,o&&"foreignObject"!==p,i,s,e.firstChild,a),null!=i)for(y=i.length;y--;)null!=i[y]&&cr(i[y]);a||("value"in f&&void 0!==(y=f.value)&&(y!==e.value||"progress"===p&&!y)&&wr(e,"value",y,h.value,!1),"checked"in f&&void 0!==(y=f.checked)&&y!==e.checked&&wr(e,"checked",y,h.checked,!1))}return e}function Tr(e,t,n){try{"function"==typeof e?e(t):e.current=t}catch(e){er.__e(e,n)}}function Cr(e,t,n){var r,o,i;if(er.unmount&&er.unmount(e),(r=e.ref)&&(r.current&&r.current!==e.__e||Tr(r,null,t)),n||"function"==typeof e.type||(n=null!=(o=e.__e)),e.__e=e.__d=void 0,null!=(r=e.__c)){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(e){er.__e(e,t)}r.base=r.__P=null}if(r=e.__k)for(i=0;i<r.length;i++)r[i]&&Cr(r[i],t,n);null!=o&&cr(o)}function Ar(e,t,n){return this.constructor(e,n)}er={__e:function(e,t){for(var n,r,o;t=t.__;)if((n=t.__c)&&!n.__)try{if((r=n.constructor)&&null!=r.getDerivedStateFromError&&(n.setState(r.getDerivedStateFromError(e)),o=n.__d),null!=n.componentDidCatch&&(n.componentDidCatch(e),o=n.__d),o)return n.__E=n}catch(t){e=t}throw e},__v:0},hr.prototype.setState=function(e,t){var n;n=null!=this.__s&&this.__s!==this.state?this.__s:this.__s=ar({},this.state),"function"==typeof e&&(e=e(ar({},n),this.props)),e&&ar(n,e),null!=e&&this.__v&&(t&&this.__h.push(t),yr(this))},hr.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),yr(this))},hr.prototype.render=dr,tr=[],nr="function"==typeof Promise?Promise.prototype.then.bind(Promise.resolve()):setTimeout,br.__r=0;const Pr={Error:{color:"red"},Alert:{error:{color:"red"},warning:{color:"yellow"},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"},Input:{height:"35px",width:"17em",borderColor:"#ccf4",outline:"none",fontSize:"17pt",padding:"8px"}};function Or({children:e}){return ur("div",null,ur("div",{style:Pr.Darken}),ur("div",{style:Pr.DialogOuter},ur("div",{style:Pr.DialogInner},e)))}var Ur,$r,Nr,Dr=0,Rr=[],jr=er.__b,Lr=er.__r,Br=er.diffed,Wr=er.__c,Fr=er.unmount;function Mr(e,t){er.__h&&er.__h($r,e,Dr||t),Dr=0;var n=$r.__H||($r.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function Hr(e){return Dr=1,function(e,t,n){var r=Mr(Ur++,2);return r.t=e,r.__c||(r.__=[n?n(t):Yr(void 0,t),function(e){var t=r.t(r.__[0],e);r.__[0]!==t&&(r.__=[t,r.__[1]],r.__c.setState({}))}],r.__c=$r),r.__}(Yr,e)}function Vr(e){return Dr=5,function(e,t){var n=Mr(Ur++,7);return Jr(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}((function(){return{current:e}}),[])}function Kr(){Rr.forEach((function(e){if(e.__P)try{e.__H.__h.forEach(zr),e.__H.__h.forEach(Gr),e.__H.__h=[]}catch(t){e.__H.__h=[],er.__e(t,e.__v)}})),Rr=[]}er.__b=function(e){$r=null,jr&&jr(e)},er.__r=function(e){Lr&&Lr(e),Ur=0;var t=($r=e.__c).__H;t&&(t.__h.forEach(zr),t.__h.forEach(Gr),t.__h=[])},er.diffed=function(e){Br&&Br(e);var t=e.__c;t&&t.__H&&t.__H.__h.length&&(1!==Rr.push(t)&&Nr===er.requestAnimationFrame||((Nr=er.requestAnimationFrame)||function(e){var t,n=function(){clearTimeout(r),qr&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,100);qr&&(t=requestAnimationFrame(n))})(Kr)),$r=void 0},er.__c=function(e,t){t.some((function(e){try{e.__h.forEach(zr),e.__h=e.__h.filter((function(e){return!e.__||Gr(e)}))}catch(n){t.some((function(e){e.__h&&(e.__h=[])})),t=[],er.__e(n,e.__v)}})),Wr&&Wr(e,t)},er.unmount=function(e){Fr&&Fr(e);var t=e.__c;if(t&&t.__H)try{t.__H.__.forEach(zr)}catch(e){er.__e(e,t.__v)}};var qr="function"==typeof requestAnimationFrame;function zr(e){var t=$r;"function"==typeof e.__c&&e.__c(),$r=t}function Gr(e){var t=$r;e.__c=e.__(),$r=t}function Jr(e,t){return!e||e.length!==t.length||t.some((function(t,n){return t!==e[n]}))}function Yr(e,t){return"function"==typeof t?t(e):t}function Xr({title:e,alerts:t,fields:n,onCancel:r,onSubmit:o}){const[i,s]=Hr({}),a=Vr();return function(e,t){var n=Mr(Ur++,4);!er.__s&&Jr(n.__H,t)&&(n.__=e,n.__H=t,$r.__h.push(n))}((()=>{var e;return null===(e=a.current)||void 0===e?void 0:e.focus()}),[]),ur(Or,null,ur(dr,null,ur("h3",{style:Pr.WindowHeader},e),t.map((e=>ur("p",{style:Pr.Alert[e.type]},function({message:e,messageCode:t,messageParams:n}){return e.replace(/\{\w+\}/gi,(e=>n[e.substr(1,e.length-2)]))}(e)))),ur("form",{onSubmit:e=>{e.preventDefault(),o(i)}},Object.entries(n).map((([e,{type:t,label:n,placeholder:r}],o)=>ur("label",{style:Pr.Label},n?`${n}: `:"",ur("input",{ref:0===o?a:void 0,type:t,name:e,autoComplete:"on",style:Pr.Input,autoFocus:!0,placeholder:r,value:i[e]||"",onInput:n=>{var r;return s({...i,[e]:Zr(t,null===(r=n.target)||void 0===r?void 0:r.value)})}})))))),ur("div",{style:Pr.ButtonsDiv},ur("button",{type:"submit",style:Pr.Button,onClick:()=>o(i)},"Submit"),ur("button",{style:Pr.Button,onClick:r},"Cancel")))}function Zr(e,t){switch(e){case"email":return t.toLowerCase();case"otp":return t.toUpperCase();default:return t}}class Qr extends hr{constructor(e){super(e),this.observer=e=>this.setState({userInteraction:e}),this.state={userInteraction:void 0}}componentDidMount(){this.subscription=i(this.props.db.cloud.userInteraction).subscribe(this.observer)}componentWillUnmount(){this.subscription&&(this.subscription.unsubscribe(),delete this.subscription)}render(e,{userInteraction:t}){return t?ur(Xr,Object.assign({},t)):null}}function eo(e){const t=document.createElement("div");document.body.appendChild(t),function(e,t,n){var r,o,i;er.__&&er.__(e,t),o=(r="function"==typeof n)?null:n&&n.__k||t.__k,i=[],xr(t,e=(!r&&n||t).__k=ur(dr,null,[e]),o||or,or,void 0!==t.ownerSVGElement,!r&&n?[n]:o?null:t.firstChild?ir.slice.call(t.childNodes):null,i,!r&&n?n:o?o.__e:t.firstChild,r),Er(i,e)}(ur(Qr,{db:e.vip}),t);let n=!1;return{unsubscribe(){t.remove(),n=!0},get closed(){return n}}}function to(n){const o=n.name,c=new r(pt),u=[];let h=null;n.on("ready",(async n=>{try{await async function(n){var r,o,y,b,v,m;f=!1;const g=pn(n);gn||((null===(r=g.cloud.options)||void 0===r?void 0:r.customLoginGui)||u.push(eo(n)),u.push(function(e){let t=e.cloud.webSocketStatus.value;const n=e.cloud.webSocketStatus.pipe(Me((e=>{const n=t;t=e;const r=a(e);switch(e){case"disconnected":return Rn.value?r.pipe(ye(500)):r;case"connecting":return"not-started"===n||"error"===n?r:r.pipe(ye(4e3));default:return r}})));return d([n,e.syncStateChangedEvent.pipe(Fe({phase:"initial"})),jn]).pipe(se((([t,n,r])=>{let{phase:o,error:i,progress:s}=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"),r||(a="disconnected"),{phase:o,error:i,progress:s,status:nn?a:"offline"}})))}(g).subscribe(n.cloud.syncState)));g.tables.every((e=>e.core))||_n();const _="serviceWorker"in navigator?await navigator.serviceWorker.getRegistrations():[],w=await g.transaction("rw",g.$syncState,(async()=>{var e,t;const{options:n,schema:r}=g.cloud,[o,i,s]=await Promise.all([g.getOptions(),g.getSchema(),g.getPersistedSyncState()]);if(n?o&&JSON.stringify(o)===JSON.stringify(n)||await g.$syncState.put(n,"options"):g.cloud.options=o||null,(null===(e=g.cloud.options)||void 0===e?void 0:e.tryUseServiceWorker)&&"serviceWorker"in navigator&&_.length>0&&!mn?(console.debug("Dexie Cloud Addon: Using service worker"),g.cloud.usingServiceWorker=!0):((null===(t=g.cloud.options)||void 0===t?void 0:t.tryUseServiceWorker)&&!gn&&console.debug("dexie-cloud-addon: Not using service worker.",0===_.length?"No SW registrations found.":"serviceWorker"in navigator&&mn?"Avoiding SW background sync and SW periodic bg sync for this browser due to browser bugs.":"navigator.serviceWorker not present"),g.cloud.usingServiceWorker=!1),Qn(r,g.cloud.options),Qn(i,g.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]={...n}}await g.$syncState.put(e,"schema"),Object.assign(r,e)}}else g.cloud.schema=i||null;return null==s?void 0:s.initiallySynced}));w&&g.setInitiallySynced(!0);(function(t){var n,r;for(const o of t.tables)if(null===(r=null===(n=t.cloud.schema)||void 0===n?void 0:n[o.name])||void 0===r?void 0:r.markedForSync){if(o.schema.primKey.auto)throw new e.SchemaError(`Table ${o.name} is both autoIncremented and synced. Use db.cloud.configure({unsyncedTables: [${JSON.stringify(o.name)}]}) to blacklist it from sync`);if(!o.schema.primKey.keyPath)throw new e.SchemaError(`Table ${o.name} cannot be both synced and outbound. Use db.cloud.configure({unsyncedTables: [${JSON.stringify(o.name)}]}) to blacklist it from sync`)}})(g),(null===(o=g.cloud.options)||void 0===o?void 0:o.databaseUrl)&&!w&&(await async function(e,t,n){console.debug("Performing initial sync"),await Dn(e,"initialSync","$jobs",(async()=>{const r=await e.getPersistedSyncState();(null==r?void 0:r.initiallySynced)||await sn(e,t,n,{isInitialSync:!0})}),{awaitRemoteJob:!0}),console.debug("Done initial sync")}(g,g.cloud.options,g.cloud.schema),g.setInitiallySynced(!0));p(),gn||(u.push(t((()=>g.getCurrentUser())).subscribe(c)),u.push(t((()=>g.getPersistedSyncState())).subscribe(g.cloud.persistedSyncState)),await d([c.pipe(Le(1),De(1)),g.cloud.persistedSyncState.pipe(Le(1),De(1))]).toPromise());(null===(y=g.cloud.options)||void 0===y?void 0:y.requireAuth)&&await ft(g);h&&h.stop();h=null,p(),g.cloud.usingServiceWorker&&(null===(b=g.cloud.options)||void 0===b?void 0:b.databaseUrl)?(et(g,"push").catch((()=>{})),async function(e){var t;try{const{periodicSync:n}=await navigator.serviceWorker.ready;if(n)try{await n.register(`dexie-cloud:${e.name}`,null===(t=e.cloud.options)||void 0===t?void 0:t.periodicSync),console.debug(`Dexie Cloud: Successfully registered periodicsync event for ${e.name}`)}catch(e){console.debug("Dexie Cloud: Failed to register periodic sync. Your PWA must be installed to allow background sync.",e)}else console.debug("Dexie Cloud: periodicSync not supported.")}catch(t){console.debug(`Dexie Cloud: Could not register periodicSync for ${e.name}`,t)}}(g).catch((()=>{}))):(null===(v=g.cloud.options)||void 0===v?void 0:v.databaseUrl)&&g.cloud.schema&&!gn&&(h=Zn(g,g.cloud.options,g.cloud.schema),h.start(),tt(g,"push"));p(),gn||u.push(s(self,"online").subscribe((()=>{console.debug("online!"),g.syncStateChangedEvent.next({phase:"not-in-sync"}),tt(g,"push")})),s(self,"offline").subscribe((()=>{console.debug("offline!"),g.syncStateChangedEvent.next({phase:"offline"})})));"undefined"!=typeof window&&!gn&&(null===(m=g.cloud.options)||void 0===m?void 0:m.databaseUrl)&&u.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 n=e.messageConsumer.readyToServe.pipe(Ue((e=>e)),Me((()=>e.getPersistedSyncState())),Ue((e=>e&&e.serverRevision)),se((e=>({type:"ready",rev:e.serverRevision}))));return function t(){return e.cloud.persistedSyncState.pipe(Ue((e=>null==e?void 0:e.serverRevision)),De(1),Me((()=>e.cloud.currentUser)),Me((e=>jn.pipe(se((t=>t?e:null))))),Me((t=>t?new Kn(e.cloud.options.databaseUrl,e.cloud.persistedSyncState.value.serverRevision,e.cloud.persistedSyncState.value.clientIdentity,n,e.cloud.webSocketStatus,t.accessToken,t.accessTokenExpiration):i([]))),Z((n=>"TokenExpiredError"===(null==n?void 0:n.name)?(console.debug("WebSocket observable: Token expired. Refreshing token..."),a(!0).pipe(Me((async()=>{const t=await e.getCurrentUser(),n=await ut(e.cloud.options.databaseUrl,t);await e.table("$logins").update(t.userId,{accessToken:n.accessToken,accessTokenExpiration:n.accessTokenExpiration})})),Me((()=>t())))):l(n))),Z((e=>i(Gn(e)).pipe(Me((()=>t()))))))}().subscribe((t=>{t&&(console.debug("WS got message",t),e.messageConsumer.enqueue(t))}),(e=>{console.error("Oops! The main observable errored!",e)}),(()=>{console.error("Oops! The main observable completed!")}))}(g))}(n)}catch(e){console.error(e)}}),!0);let f=!1;function p(){if(f)throw new e.DatabaseClosedError}var y;!function(e,t){e.on.close.subscribe(t);const n=e.close;e.close=function(){n.call(this),t()}}(n,(()=>{u.forEach((e=>e.unsubscribe())),f=!0,h&&h.stop(),h=null,c.next(pt)})),n.cloud={version:"1.0.0-beta.10",options:null,schema:null,serverState:null,get currentUserId(){return c.value.userId||pt.userId},currentUser:c,syncState:new r({phase:"initial",status:"not-started"}),persistedSyncState:new r(void 0),userInteraction:new r(void 0),webSocketStatus:new r("not-started"),async login(e){const t=pn(n);await t.cloud.sync(),await ft(t,e)},configure(e){n.cloud.options=e,e.databaseUrl&&(n.name=`${o}-${function(e){const t=new URL(e);return"/"===t.pathname?t.hostname.split(".")[0]:t.pathname.split("/")[1]}(e.databaseUrl)}`,pn(n).reconfigure()),Qn(n.cloud.schema,n.cloud.options)},async sync({wait:e,purpose:r}={wait:!0,purpose:"push"}){void 0===e&&(e=!0);const o=pn(n);if("pull"===r){const t=o.cloud.persistedSyncState.value;if(tt(o,r),e){const e=await o.cloud.persistedSyncState.pipe(Ue((e=>null!=(null==e?void 0:e.timestamp)&&(!t||e.timestamp>t.timestamp))),De(1)).toPromise();if(null==e?void 0:e.error)throw new Error("Sync error: "+e.error)}}else if(await Jn(o)){const n=o.cloud.persistedSyncState.value;tt(o,r),e&&(console.debug("db.cloud.login() is waiting for sync completion..."),await i(t((async()=>{const e=await Jn(o),t=await o.getPersistedSyncState();if((null==t?void 0:t.timestamp)!==(null==n?void 0:n.timestamp)&&(null==t?void 0:t.error))throw new Error("Sync error: "+t.error);return e}))).pipe(Ue((e=>!e)),De(1)).toPromise(),console.debug("Done waiting for sync completion because we have nothing to push anymore"))}}},n.Version.prototype._parseStoresSpec=e.override(n.Version.prototype._parseStoresSpec,(e=>$n(e,n))),n.use(Un({currentUserObservable:n.cloud.currentUser,db:pn(n)})),n.use((y=pn(n),{stack:"dbcore",name:"implicitPropSetterMiddleware",level:1,create:e=>({...e,table:t=>{const n=e.table(t);return{...n,mutate:e=>{var r,o,i;const s=e.trans;if((null===(o=null===(r=y.cloud.schema)||void 0===r?void 0:r[t])||void 0===o?void 0:o.markedForSync)&&(null===(i=s.currentUser)||void 0===i?void 0:i.isLoggedIn)&&("add"===e.type||"put"===e.type))for(const t of e.values)"owner"in t||(t.owner=s.currentUser.userId),"realmId"in t||(t.realmId=s.currentUser.userId);return n.mutate(e)}}}})})),n.use(In(pn(n)))}to.version="1.0.0-beta.10",e.Cloud=to;export default to;export{to as dexieCloud};
1
+ import e,{liveQuery as t}from"dexie";import{Observable as n,BehaviorSubject as r,Subject as o,from as i,fromEvent as s,of as a,merge as c,Subscription as u,throwError as l,combineLatest as d}from"rxjs";const h=crypto.getRandomValues;function f(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,o=t.length;r<o;++r)f(e,t[r],n[r])}else{var i=t.indexOf(".");if(-1!==i){var s=t.substr(0,i),a=t.substr(i+1);if(""===a)void 0===n?Array.isArray(e)?isNaN(parseInt(s))||e.splice(parseInt(s),1):delete e[s]:e[s]=n;else{var c=e[s];c||(c=e[s]={}),f(c,a,n)}}else void 0===n?Array.isArray(e)&&!isNaN(parseInt(t))?e.splice(t,1):delete e[t]:e[t]=n}}const p="undefined"==typeof self?e=>{const t=Buffer.alloc(e);return h(t),t.toString("base64")}:e=>{const t=new Uint8Array(e);return crypto.getRandomValues(t),btoa(String.fromCharCode.apply(null,t))};function y(e){return"string"==typeof e||!!(Array.isArray(e)&&e.some((e=>y(e)))&&e.every(b))}function b(e){return"string"==typeof e||"number"==typeof e||Array.isArray(e)&&e.every(b)}function v(e,t,n){const r=e[t]||(e[t]={});switch(n.type){case"insert":case"upsert":n.keys.forEach(((e,t)=>{r[e]={type:"ups",val:n.values[t]}}));break;case"update":case"modify":n.keys.forEach(((e,t)=>{const o="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(o))f(i.val,e,t);break;case"del":break;case"upd":Object.assign(i.mod,o)}else r[e]={type:"upd",mod:o}}));break;case"delete":n.keys.forEach((e=>{r[e]={type:"del"}}))}return e}function m(e,t){for(const{table:n,muts:r}of t)for(const t of r)v(e,n,t)}var g=function(e,t){return(g=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)};function _(e,t){function n(){this.constructor=e}g(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}function w(e){return"function"==typeof e}var S=!1,k={Promise:void 0,set useDeprecatedSynchronousErrorHandling(e){e&&(new Error).stack;S=e},get useDeprecatedSynchronousErrorHandling(){return S}};function x(e){setTimeout((function(){throw e}),0)}var E={closed:!0,next:function(e){},error:function(e){if(k.useDeprecatedSynchronousErrorHandling)throw e;x(e)},complete:function(){}},I=function(){return Array.isArray||function(e){return e&&"number"==typeof e.length}}();function T(e){return null!==e&&"object"==typeof e}var C=function(){function e(e){return Error.call(this),this.message=e?e.length+" errors occurred during unsubscription:\n"+e.map((function(e,t){return t+1+") "+e.toString()})).join("\n "):"",this.name="UnsubscriptionError",this.errors=e,this}return e.prototype=Object.create(Error.prototype),e}(),A=function(){function e(e){this.closed=!1,this._parentOrParents=null,this._subscriptions=null,e&&(this._ctorUnsubscribe=!0,this._unsubscribe=e)}return e.prototype.unsubscribe=function(){var t;if(!this.closed){var n=this,r=n._parentOrParents,o=n._ctorUnsubscribe,i=n._unsubscribe,s=n._subscriptions;if(this.closed=!0,this._parentOrParents=null,this._subscriptions=null,r instanceof e)r.remove(this);else if(null!==r)for(var a=0;a<r.length;++a){r[a].remove(this)}if(w(i)){o&&(this._unsubscribe=void 0);try{i.call(this)}catch(e){t=e instanceof C?P(e.errors):[e]}}if(I(s)){a=-1;for(var c=s.length;++a<c;){var u=s[a];if(T(u))try{u.unsubscribe()}catch(e){t=t||[],e instanceof C?t=t.concat(P(e.errors)):t.push(e)}}}if(t)throw new C(t)}},e.prototype.add=function(t){var n=t;if(!t)return e.EMPTY;switch(typeof t){case"function":n=new e(t);case"object":if(n===this||n.closed||"function"!=typeof n.unsubscribe)return n;if(this.closed)return n.unsubscribe(),n;if(!(n instanceof e)){var r=n;(n=new e)._subscriptions=[r]}break;default:throw new Error("unrecognized teardown "+t+" added to Subscription.")}var o=n._parentOrParents;if(null===o)n._parentOrParents=this;else if(o instanceof e){if(o===this)return n;n._parentOrParents=[o,this]}else{if(-1!==o.indexOf(this))return n;o.push(this)}var i=this._subscriptions;return null===i?this._subscriptions=[n]:i.push(n),n},e.prototype.remove=function(e){var t=this._subscriptions;if(t){var n=t.indexOf(e);-1!==n&&t.splice(n,1)}},e.EMPTY=function(e){return e.closed=!0,e}(new e),e}();function P(e){return e.reduce((function(e,t){return e.concat(t instanceof C?t.errors:t)}),[])}var O=function(){return"function"==typeof Symbol?Symbol("rxSubscriber"):"@@rxSubscriber_"+Math.random()}(),U=function(e){function t(n,r,o){var i=e.call(this)||this;switch(i.syncErrorValue=null,i.syncErrorThrown=!1,i.syncErrorThrowable=!1,i.isStopped=!1,arguments.length){case 0:i.destination=E;break;case 1:if(!n){i.destination=E;break}if("object"==typeof n){n instanceof t?(i.syncErrorThrowable=n.syncErrorThrowable,i.destination=n,n.add(i)):(i.syncErrorThrowable=!0,i.destination=new $(i,n));break}default:i.syncErrorThrowable=!0,i.destination=new $(i,n,r,o)}return i}return _(t,e),t.prototype[O]=function(){return this},t.create=function(e,n,r){var o=new t(e,n,r);return o.syncErrorThrowable=!1,o},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))},t.prototype._next=function(e){this.destination.next(e)},t.prototype._error=function(e){this.destination.error(e),this.unsubscribe()},t.prototype._complete=function(){this.destination.complete(),this.unsubscribe()},t.prototype._unsubscribeAndRecycle=function(){var e=this._parentOrParents;return this._parentOrParents=null,this.unsubscribe(),this.closed=!1,this.isStopped=!1,this._parentOrParents=e,this},t}(A),$=function(e){function t(t,n,r,o){var i,s=e.call(this)||this;s._parentSubscriber=t;var a=s;return w(n)?i=n:n&&(i=n.next,r=n.error,o=n.complete,n!==E&&(w((a=Object.create(n)).unsubscribe)&&s.add(a.unsubscribe.bind(a)),a.unsubscribe=s.unsubscribe.bind(s))),s._context=a,s._next=i,s._error=r,s._complete=o,s}return _(t,e),t.prototype.next=function(e){if(!this.isStopped&&this._next){var t=this._parentSubscriber;k.useDeprecatedSynchronousErrorHandling&&t.syncErrorThrowable?this.__tryOrSetError(t,this._next,e)&&this.unsubscribe():this.__tryOrUnsub(this._next,e)}},t.prototype.error=function(e){if(!this.isStopped){var t=this._parentSubscriber,n=k.useDeprecatedSynchronousErrorHandling;if(this._error)n&&t.syncErrorThrowable?(this.__tryOrSetError(t,this._error,e),this.unsubscribe()):(this.__tryOrUnsub(this._error,e),this.unsubscribe());else if(t.syncErrorThrowable)n?(t.syncErrorValue=e,t.syncErrorThrown=!0):x(e),this.unsubscribe();else{if(this.unsubscribe(),n)throw e;x(e)}}},t.prototype.complete=function(){var e=this;if(!this.isStopped){var t=this._parentSubscriber;if(this._complete){var n=function(){return e._complete.call(e._context)};k.useDeprecatedSynchronousErrorHandling&&t.syncErrorThrowable?(this.__tryOrSetError(t,n),this.unsubscribe()):(this.__tryOrUnsub(n),this.unsubscribe())}else this.unsubscribe()}},t.prototype.__tryOrUnsub=function(e,t){try{e.call(this._context,t)}catch(e){if(this.unsubscribe(),k.useDeprecatedSynchronousErrorHandling)throw e;x(e)}},t.prototype.__tryOrSetError=function(e,t,n){if(!k.useDeprecatedSynchronousErrorHandling)throw new Error("bad call");try{t.call(this._context,n)}catch(t){return k.useDeprecatedSynchronousErrorHandling?(e.syncErrorValue=t,e.syncErrorThrown=!0,!0):(x(t),!0)}return!1},t.prototype._unsubscribe=function(){var e=this._parentSubscriber;this._context=null,this._parentSubscriber=null,e.unsubscribe()},t}(U);var D=function(){return"function"==typeof Symbol&&Symbol.observable||"@@observable"}();function N(e){return e}function R(e){return 0===e.length?N:1===e.length?e[0]:function(t){return e.reduce((function(e,t){return t(e)}),t)}}var j=function(){function e(e){this._isScalar=!1,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=this.operator,o=function(e,t,n){if(e){if(e instanceof U)return e;if(e[O])return e[O]()}return e||t||n?new U(e,t,n):new U(E)}(e,t,n);if(r?o.add(r.call(o,this.source)):o.add(this.source||k.useDeprecatedSynchronousErrorHandling&&!o.syncErrorThrowable?this._subscribe(o):this._trySubscribe(o)),k.useDeprecatedSynchronousErrorHandling&&o.syncErrorThrowable&&(o.syncErrorThrowable=!1,o.syncErrorThrown))throw o.syncErrorValue;return o},e.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){k.useDeprecatedSynchronousErrorHandling&&(e.syncErrorThrown=!0,e.syncErrorValue=t),!function(e){for(;e;){var t=e,n=t.closed,r=t.destination,o=t.isStopped;if(n||o)return!1;e=r&&r instanceof U?r:null}return!0}(e)?console.warn(t):e.error(t)}},e.prototype.forEach=function(e,t){var n=this;return new(t=L(t))((function(t,r){var o;o=n.subscribe((function(t){try{e(t)}catch(e){r(e),o&&o.unsubscribe()}}),r,t)}))},e.prototype._subscribe=function(e){var t=this.source;return t&&t.subscribe(e)},e.prototype[D]=function(){return this},e.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return 0===e.length?this:R(e)(this)},e.prototype.toPromise=function(e){var t=this;return new(e=L(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 L(e){if(e||(e=Promise),!e)throw new Error("no Promise impl found");return e}var B=function(e){return function(t){for(var n=0,r=e.length;n<r&&!t.closed;n++)t.next(e[n]);t.complete()}};function W(){return"function"==typeof Symbol&&Symbol.iterator?Symbol.iterator:"@@iterator"}var F=W(),M=function(e){return e&&"number"==typeof e.length&&"function"!=typeof e};function H(e){return!!e&&"function"!=typeof e.subscribe&&"function"==typeof e.then}var V=function(e){if(e&&"function"==typeof e[D])return r=e,function(e){var t=r[D]();if("function"!=typeof t.subscribe)throw new TypeError("Provided object does not correctly implement Symbol.observable");return t.subscribe(e)};if(M(e))return B(e);if(H(e))return n=e,function(e){return n.then((function(t){e.closed||(e.next(t),e.complete())}),(function(t){return e.error(t)})).then(null,x),e};if(e&&"function"==typeof e[F])return t=e,function(e){for(var n=t[F]();;){var r=void 0;try{r=n.next()}catch(t){return e.error(t),e}if(r.done){e.complete();break}if(e.next(r.value),e.closed)break}return"function"==typeof n.return&&e.add((function(){n.return&&n.return()})),e};var t,n,r,o=T(e)?"an invalid object":"'"+e+"'";throw new TypeError("You provided "+o+" where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.")},K=function(e){function t(t){var n=e.call(this)||this;return n.parent=t,n}return _(t,e),t.prototype._next=function(e){this.parent.notifyNext(e)},t.prototype._error=function(e){this.parent.notifyError(e),this.unsubscribe()},t.prototype._complete=function(){this.parent.notifyComplete(),this.unsubscribe()},t}(U),q=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return _(t,e),t.prototype.notifyNext=function(e){this.destination.next(e)},t.prototype.notifyError=function(e){this.destination.error(e)},t.prototype.notifyComplete=function(){this.destination.complete()},t}(U);function z(e,t){if(!t.closed){if(e instanceof j)return e.subscribe(t);var n;try{n=V(e)(t)}catch(e){t.error(e)}return n}}var G=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 _(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),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;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=!1,r=void 0;try{this.work(e)}catch(e){n=!0,r=!!e&&e||new Error(e)}if(n)return this.unsubscribe(),r},t.prototype._unsubscribe=function(){var e=this.id,t=this.scheduler,n=t.actions,r=n.indexOf(this);this.work=null,this.state=null,this.pending=!1,this.scheduler=null,-1!==r&&n.splice(r,1),null!=e&&(this.id=this.recycleAsyncId(t,e,null)),this.delay=null},t}(function(e){function t(t,n){return e.call(this)||this}return _(t,e),t.prototype.schedule=function(e,t){return this},t}(A)),J=function(){function e(t,n){void 0===n&&(n=e.now),this.SchedulerAction=t,this.now=n}return e.prototype.schedule=function(e,t,n){return void 0===t&&(t=0),new this.SchedulerAction(this,e).schedule(n,t)},e.now=function(){return Date.now()},e}(),Y=new(function(e){function t(n,r){void 0===r&&(r=J.now);var o=e.call(this,n,(function(){return t.delegate&&t.delegate!==o?t.delegate.now():r()}))||this;return o.actions=[],o.active=!1,o.scheduled=void 0,o}return _(t,e),t.prototype.schedule=function(n,r,o){return void 0===r&&(r=0),t.delegate&&t.delegate!==this?t.delegate.schedule(n,r,o):e.prototype.schedule.call(this,n,r,o)},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}(J))(G);function X(e){return e&&"function"==typeof e.schedule}function Z(e){return function(t){var n=new Q(e),r=t.lift(n);return n.caught=r}}var Q=function(){function e(e){this.selector=e}return e.prototype.call=function(e,t){return t.subscribe(new ee(e,this.selector,this.caught))},e}(),ee=function(e){function t(t,n,r){var o=e.call(this,t)||this;return o.selector=n,o.caught=r,o}return _(t,e),t.prototype.error=function(t){if(!this.isStopped){var n=void 0;try{n=this.selector(t,this.caught)}catch(t){return void e.prototype.error.call(this,t)}this._unsubscribeAndRecycle();var r=new K(this);this.add(r);var o=z(n,r);o!==r&&this.add(o)}},t}(q);function te(e,t){return new j((function(n){var r=new A,o=0;return r.add(t.schedule((function(){o!==e.length?(n.next(e[o++]),n.closed||r.add(this.schedule())):n.complete()}))),r}))}function ne(e,t){return t?te(e,t):new j(B(e))}function re(e,t){if(null!=e){if(function(e){return e&&"function"==typeof e[D]}(e))return function(e,t){return new j((function(n){var r=new A;return r.add(t.schedule((function(){var o=e[D]();r.add(o.subscribe({next:function(e){r.add(t.schedule((function(){return n.next(e)})))},error:function(e){r.add(t.schedule((function(){return n.error(e)})))},complete:function(){r.add(t.schedule((function(){return n.complete()})))}}))}))),r}))}(e,t);if(H(e))return function(e,t){return new j((function(n){var r=new A;return r.add(t.schedule((function(){return e.then((function(e){r.add(t.schedule((function(){n.next(e),r.add(t.schedule((function(){return n.complete()})))})))}),(function(e){r.add(t.schedule((function(){return n.error(e)})))}))}))),r}))}(e,t);if(M(e))return te(e,t);if(function(e){return e&&"function"==typeof e[F]}(e)||"string"==typeof e)return function(e,t){if(!e)throw new Error("Iterable cannot be null");return new j((function(n){var r,o=new A;return o.add((function(){r&&"function"==typeof r.return&&r.return()})),o.add(t.schedule((function(){r=e[F](),o.add(t.schedule((function(){if(!n.closed){var e,t;try{var o=r.next();e=o.value,t=o.done}catch(e){return void n.error(e)}t?n.complete():(n.next(e),this.schedule())}})))}))),o}))}(e,t)}throw new TypeError((null!==e&&typeof e||e)+" is not observable")}function oe(e,t){return t?re(e,t):e instanceof j?e:new j(V(e))}function ie(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=e[e.length-1];return X(n)?(e.pop(),te(e,n)):ne(e)}function se(e,t){return function(n){if("function"!=typeof e)throw new TypeError("argument is not a function. Are you looking for `mapTo()`?");return n.lift(new ae(e,t))}}var ae=function(){function e(e,t){this.project=e,this.thisArg=t}return e.prototype.call=function(e,t){return t.subscribe(new ce(e,this.project,this.thisArg))},e}(),ce=function(e){function t(t,n,r){var o=e.call(this,t)||this;return o.project=n,o.count=0,o.thisArg=r||o,o}return _(t,e),t.prototype._next=function(e){var t;try{t=this.project.call(this.thisArg,e,this.count++)}catch(e){return void this.destination.error(e)}this.destination.next(t)},t}(U);function ue(e,t,n){return void 0===n&&(n=Number.POSITIVE_INFINITY),"function"==typeof t?function(r){return r.pipe(ue((function(n,r){return oe(e(n,r)).pipe(se((function(e,o){return t(n,e,r,o)})))}),n))}:("number"==typeof t&&(n=t),function(t){return t.lift(new le(e,n))})}var le=function(){function e(e,t){void 0===t&&(t=Number.POSITIVE_INFINITY),this.project=e,this.concurrent=t}return e.prototype.call=function(e,t){return t.subscribe(new de(e,this.project,this.concurrent))},e}(),de=function(e){function t(t,n,r){void 0===r&&(r=Number.POSITIVE_INFINITY);var o=e.call(this,t)||this;return o.project=n,o.concurrent=r,o.hasCompleted=!1,o.buffer=[],o.active=0,o.index=0,o}return _(t,e),t.prototype._next=function(e){this.active<this.concurrent?this._tryNext(e):this.buffer.push(e)},t.prototype._tryNext=function(e){var t,n=this.index++;try{t=this.project(e,n)}catch(e){return void this.destination.error(e)}this.active++,this._innerSub(t)},t.prototype._innerSub=function(e){var t=new K(this),n=this.destination;n.add(t);var r=z(e,t);r!==t&&n.add(r)},t.prototype._complete=function(){this.hasCompleted=!0,0===this.active&&0===this.buffer.length&&this.destination.complete(),this.unsubscribe()},t.prototype.notifyNext=function(e){this.destination.next(e)},t.prototype.notifyComplete=function(){var e=this.buffer;this.active--,e.length>0?this._next(e.shift()):0===this.active&&this.hasCompleted&&this.destination.complete()},t}(q);function he(e){return void 0===e&&(e=Number.POSITIVE_INFINITY),ue(N,e)}function fe(){return he(1)}function pe(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return fe()(ie.apply(void 0,e))}function ye(e,t){return void 0===t&&(t=Y),function(n){return n.lift(new be(e,t))}}var be=function(){function e(e,t){this.dueTime=e,this.scheduler=t}return e.prototype.call=function(e,t){return t.subscribe(new ve(e,this.dueTime,this.scheduler))},e}(),ve=function(e){function t(t,n,r){var o=e.call(this,t)||this;return o.dueTime=n,o.scheduler=r,o.debouncedSubscription=null,o.lastValue=null,o.hasValue=!1,o}return _(t,e),t.prototype._next=function(e){this.clearDebounce(),this.lastValue=e,this.hasValue=!0,this.add(this.debouncedSubscription=this.scheduler.schedule(me,this.dueTime,this))},t.prototype._complete=function(){this.debouncedNext(),this.destination.complete()},t.prototype.debouncedNext=function(){if(this.clearDebounce(),this.hasValue){var e=this.lastValue;this.lastValue=null,this.hasValue=!1,this.destination.next(e)}},t.prototype.clearDebounce=function(){var e=this.debouncedSubscription;null!==e&&(this.remove(e),e.unsubscribe(),this.debouncedSubscription=null)},t}(U);function me(e){e.debouncedNext()}function ge(e){return e instanceof Date&&!isNaN(+e)}var _e=new j((function(e){return e.complete()}));function we(e){return e?function(e){return new j((function(t){return e.schedule((function(){return t.complete()}))}))}(e):_e}function Se(e,t){return new j(t?function(n){return t.schedule(ke,0,{error:e,subscriber:n})}:function(t){return t.error(e)})}function ke(e){var t=e.error;e.subscriber.error(t)}var xe=function(){function e(e,t,n){this.kind=e,this.value=t,this.error=n,this.hasValue="N"===e}return e.prototype.observe=function(e){switch(this.kind){case"N":return e.next&&e.next(this.value);case"E":return e.error&&e.error(this.error);case"C":return e.complete&&e.complete()}},e.prototype.do=function(e,t,n){switch(this.kind){case"N":return e&&e(this.value);case"E":return t&&t(this.error);case"C":return n&&n()}},e.prototype.accept=function(e,t,n){return e&&"function"==typeof e.next?this.observe(e):this.do(e,t,n)},e.prototype.toObservable=function(){switch(this.kind){case"N":return ie(this.value);case"E":return Se(this.error);case"C":return we()}throw new Error("unexpected notification kind value")},e.createNext=function(t){return void 0!==t?new e("N",t):e.undefinedValueNotification},e.createError=function(t){return new e("E",void 0,t)},e.createComplete=function(){return e.completeNotification},e.completeNotification=new e("C"),e.undefinedValueNotification=new e("N",void 0),e}();function Ee(e,t){void 0===t&&(t=Y);var n=ge(e)?+e-t.now():Math.abs(e);return function(e){return e.lift(new Ie(n,t))}}var Ie=function(){function e(e,t){this.delay=e,this.scheduler=t}return e.prototype.call=function(e,t){return t.subscribe(new Te(e,this.delay,this.scheduler))},e}(),Te=function(e){function t(t,n,r){var o=e.call(this,t)||this;return o.delay=n,o.scheduler=r,o.queue=[],o.active=!1,o.errored=!1,o}return _(t,e),t.dispatch=function(e){for(var t=e.source,n=t.queue,r=e.scheduler,o=e.destination;n.length>0&&n[0].time-r.now()<=0;)n.shift().notification.observe(o);if(n.length>0){var i=Math.max(0,n[0].time-r.now());this.schedule(e,i)}else this.unsubscribe(),t.active=!1},t.prototype._schedule=function(e){this.active=!0,this.destination.add(e.schedule(t.dispatch,this.delay,{source:this,destination:this.destination,scheduler:e}))},t.prototype.scheduleNotification=function(e){if(!0!==this.errored){var t=this.scheduler,n=new Ce(t.now()+this.delay,e);this.queue.push(n),!1===this.active&&this._schedule(t)}},t.prototype._next=function(e){this.scheduleNotification(xe.createNext(e))},t.prototype._error=function(e){this.errored=!0,this.queue=[],this.destination.error(e),this.unsubscribe()},t.prototype._complete=function(){this.scheduleNotification(xe.createComplete()),this.unsubscribe()},t}(U),Ce=function(){return function(e,t){this.time=e,this.notification=t}}();var Ae=function(){function e(e,t){this.compare=e,this.keySelector=t}return e.prototype.call=function(e,t){return t.subscribe(new Pe(e,this.compare,this.keySelector))},e}(),Pe=function(e){function t(t,n,r){var o=e.call(this,t)||this;return o.keySelector=r,o.hasKey=!1,"function"==typeof n&&(o.compare=n),o}return _(t,e),t.prototype.compare=function(e,t){return e===t},t.prototype._next=function(e){var t;try{var n=this.keySelector;t=n?n(e):e}catch(e){return this.destination.error(e)}var r=!1;if(this.hasKey)try{r=(0,this.compare)(this.key,t)}catch(e){return this.destination.error(e)}else this.hasKey=!0;r||(this.key=t,this.destination.next(e))},t}(U),Oe=function(){function e(){return Error.call(this),this.message="argument out of range",this.name="ArgumentOutOfRangeError",this}return e.prototype=Object.create(Error.prototype),e}();function Ue(e,t){return function(n){return n.lift(new $e(e,t))}}var $e=function(){function e(e,t){this.predicate=e,this.thisArg=t}return e.prototype.call=function(e,t){return t.subscribe(new De(e,this.predicate,this.thisArg))},e}(),De=function(e){function t(t,n,r){var o=e.call(this,t)||this;return o.predicate=n,o.thisArg=r,o.count=0,o}return _(t,e),t.prototype._next=function(e){var t;try{t=this.predicate.call(this.thisArg,e,this.count++)}catch(e){return void this.destination.error(e)}t&&this.destination.next(e)},t}(U);function Ne(e){return function(t){return 0===e?we():t.lift(new Re(e))}}var Re=function(){function e(e){if(this.total=e,this.total<0)throw new Oe}return e.prototype.call=function(e,t){return t.subscribe(new je(e,this.total))},e}(),je=function(e){function t(t,n){var r=e.call(this,t)||this;return r.total=n,r.count=0,r}return _(t,e),t.prototype._next=function(e){var t=this.total,n=++this.count;n<=t&&(this.destination.next(e),n===t&&(this.destination.complete(),this.unsubscribe()))},t}(U);function Le(e){return function(t){return t.lift(new Be(e))}}var Be=function(){function e(e){this.total=e}return e.prototype.call=function(e,t){return t.subscribe(new We(e,this.total))},e}(),We=function(e){function t(t,n){var r=e.call(this,t)||this;return r.total=n,r.count=0,r}return _(t,e),t.prototype._next=function(e){++this.count>this.total&&this.destination.next(e)},t}(U);function Fe(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=e[e.length-1];return X(n)?(e.pop(),function(t){return pe(e,t,n)}):function(t){return pe(e,t)}}function Me(e,t){return"function"==typeof t?function(n){return n.pipe(Me((function(n,r){return oe(e(n,r)).pipe(se((function(e,o){return t(n,e,r,o)})))})))}:function(t){return t.lift(new He(e))}}var He=function(){function e(e){this.project=e}return e.prototype.call=function(e,t){return t.subscribe(new Ve(e,this.project))},e}(),Ve=function(e){function t(t,n){var r=e.call(this,t)||this;return r.project=n,r.index=0,r}return _(t,e),t.prototype._next=function(e){var t,n=this.index++;try{t=this.project(e,n)}catch(e){return void this.destination.error(e)}this._innerSub(t)},t.prototype._innerSub=function(e){var t=this.innerSubscription;t&&t.unsubscribe();var n=new K(this),r=this.destination;r.add(n),this.innerSubscription=z(e,n),this.innerSubscription!==n&&r.add(this.innerSubscription)},t.prototype._complete=function(){var t=this.innerSubscription;t&&!t.closed||e.prototype._complete.call(this),this.unsubscribe()},t.prototype._unsubscribe=function(){this.innerSubscription=void 0},t.prototype.notifyComplete=function(){this.innerSubscription=void 0,this.isStopped&&e.prototype._complete.call(this)},t.prototype.notifyNext=function(e){this.destination.next(e)},t}(q);function Ke(){}function qe(e,t,n){return function(r){return r.lift(new ze(e,t,n))}}var ze=function(){function e(e,t,n){this.nextOrObserver=e,this.error=t,this.complete=n}return e.prototype.call=function(e,t){return t.subscribe(new Ge(e,this.nextOrObserver,this.error,this.complete))},e}(),Ge=function(e){function t(t,n,r,o){var i=e.call(this,t)||this;return i._tapNext=Ke,i._tapError=Ke,i._tapComplete=Ke,i._tapError=r||Ke,i._tapComplete=o||Ke,w(n)?(i._context=i,i._tapNext=n):n&&(i._context=n,i._tapNext=n.next||Ke,i._tapError=n.error||Ke,i._tapComplete=n.complete||Ke),i}return _(t,e),t.prototype._next=function(e){try{this._tapNext.call(this._context,e)}catch(e){return void this.destination.error(e)}this.destination.next(e)},t.prototype._error=function(e){try{this._tapError.call(this._context,e)}catch(e){return void this.destination.error(e)}this.destination.error(e)},t.prototype._complete=function(){try{this._tapComplete.call(this._context)}catch(e){return void this.destination.error(e)}return this.destination.complete()},t}(U),Je=function(){function e(){return Error.call(this),this.message="Timeout has occurred",this.name="TimeoutError",this}return e.prototype=Object.create(Error.prototype),e}();var Ye=function(){function e(e,t,n,r){this.waitFor=e,this.absoluteTimeout=t,this.withObservable=n,this.scheduler=r}return e.prototype.call=function(e,t){return t.subscribe(new Xe(e,this.absoluteTimeout,this.waitFor,this.withObservable,this.scheduler))},e}(),Xe=function(e){function t(t,n,r,o,i){var s=e.call(this,t)||this;return s.absoluteTimeout=n,s.waitFor=r,s.withObservable=o,s.scheduler=i,s.scheduleTimeout(),s}return _(t,e),t.dispatchTimeout=function(e){var t=e.withObservable;e._unsubscribeAndRecycle(),e.add(z(t,new K(e)))},t.prototype.scheduleTimeout=function(){var e=this.action;e?this.action=e.schedule(this,this.waitFor):this.add(this.action=this.scheduler.schedule(t.dispatchTimeout,this.waitFor,this))},t.prototype._next=function(t){this.absoluteTimeout||this.scheduleTimeout(),e.prototype._next.call(this,t)},t.prototype._unsubscribe=function(){this.action=void 0,this.scheduler=null,this.withObservable=null},t}(q);function Ze(e,t){return void 0===t&&(t=Y),function(e,t,n){return void 0===n&&(n=Y),function(r){var o=ge(e),i=o?+e-n.now():Math.abs(e);return r.lift(new Ye(i,o,t,n))}}(e,Se(new Je),t)}let Qe=!1;async function et(e,t){try{const n=await navigator.serviceWorker.ready;return"push"===t&&n.sync&&await n.sync.register(`dexie-cloud:${e.name}`),void(n.active?n.active.postMessage({type:"dexie-cloud-sync",dbName:e.name,purpose:t}):console.error("Dexie Cloud: There's no active service worker. Can this ever happen??"))}catch(e){Qe||(console.debug("Dexie Cloud: Could not register sync event",e),Qe=!0)}}function tt(e,t){e.cloud.usingServiceWorker?et(e,t):e.localSyncEvent.next({purpose:t})}const nt="undefined"!=typeof Buffer?e=>Buffer.from(e,"base64"):e=>{const t=atob(e),n=t.length,r=new Uint8Array(n);for(var o=0;o<n;o++)r[o]=t.charCodeAt(o);return r},rt="undefined"!=typeof Buffer?e=>ArrayBuffer.isView(e)?Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"):Buffer.from(e).toString("base64"):e=>btoa(String.fromCharCode.apply(null,e));function ot(t,n){return new Promise(((r,o)=>{const i={...n,onSubmit:e=>{t.next(void 0),r(e)},onCancel:()=>{t.next(void 0),o(new e.AbortError("User cancelled"))}};t.next(i)}))}function it(e,t,...n){return ot(e,{type:"message-alert",title:t,alerts:n,fields:{}})}async function st(e,t,n){let r=n||"";for(;!r||!/^[\w-\.]+@([\w-]+\.)+[\w-]{2,10}$/.test(r);)r=(await ot(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}async function at(e,t,n){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:o}=await ot(e,{type:"otp",title:"Enter OTP",alerts:r,fields:{otp:{type:"otp",label:"OTP",placeholder:"Paste OTP here"}}});return o}async function ct(e,t,n,r,o){return t.accessToken&&t.accessTokenExpiration.getTime()>Date.now()?t:t.refreshToken&&(!t.refreshTokenExpiration||t.refreshTokenExpiration.getTime()>Date.now())?await ut(e,t):await async function(e,t,n,r){const{privateKey:o,publicKey:i}=await crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:2048,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!1,["sign","verify"]);e.nonExportablePrivateKey=o;const s=function(e){const t=rt(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)}(await crypto.subtle.exportKey("spki",i));e.publicKey=i;try{const o=await t({public_key:s,hints:r});if("tokens"!==o.type)throw new Error(`Unexpected response type from token endpoint: ${o.type}`);return e.accessToken=o.accessToken,e.accessTokenExpiration=new Date(o.accessTokenExpiration),e.refreshToken=o.refreshToken,o.refreshTokenExpiration&&(e.refreshTokenExpiration=new Date(o.refreshTokenExpiration)),e.userId=o.claims.sub,e.email=o.claims.email,e.name=o.claims.name,e.claims=o.claims,o.alerts&&o.alerts.length>0&&await ot(n,{type:"message-alert",title:"Authentication Alert",fields:{},alerts:o.alerts}),e}catch(e){throw await it(n,"Authentication Failed",{type:"error",messageCode:"GENERIC_ERROR",message:"We're having a problem to authenticate rigth now.",messageParams:{}}).catch((()=>{})),e}}(t,n,r,o)}async function ut(e,t){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",o=(new TextEncoder).encode(t.refreshToken+n),i=await crypto.subtle.sign(r,t.nonExportablePrivateKey,o),s=rt(i),a={grant_type:"refresh_token",refresh_token:t.refreshToken,scopes:["ACCESS_DB"],signature:s,signing_algorithm:r,time_stamp:n},c=await fetch(`${e}/token`,{body:JSON.stringify(a),method:"post",headers:{"Content-Type":"application/json"},mode:"cors"});if(200!==c.status)throw new Error(`RefreshToken: Status ${c.status} from ${e}/token`);const u=await c.json();return t.accessToken=u.accessToken,t.accessTokenExpiration=u.accessTokenExpiration?new Date(u.accessTokenExpiration):void 0,t}const lt=new WeakMap;class dt{constructor(e,t){lt.set(this,e),Object.assign(this,t)}static load(e,t){return e.table("$logins").get(t).then((n=>new dt(e,n||{userId:t,claims:{sub:t},lastLogin:new Date(0)})))}async save(){lt.get(this).table("$logins").put(this)}}class ht extends Error{constructor(e,t){super(t||`${e.status} ${e.statusText}`),this.httpStatus=e.status}get name(){return"HttpError"}}async function ft(e,t){if((await e.getCurrentUser()).isLoggedIn){if(t){if(t.email&&e.cloud.currentUser.value.email!==t.email)throw new Error("Must logout before changing user");if(t.userId&&e.cloud.currentUserId!==t.userId)throw new Error("Must logout before changing user")}return}const n=new dt(e,{claims:{},lastLogin:new Date(0)});await ct(e.cloud.options.databaseUrl,n,e.cloud.options.fetchTokens||function(e){const{userInteraction:t}=e.cloud;return async function({public_key:n,hints:r}){var o;let i;const s=null===(o=e.cloud.options)||void 0===o?void 0:o.databaseUrl;if(!s)throw new Error("No database URL given.");i="demo"===(null==r?void 0:r.grant_type)?{demo_user:await st(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}:{email:await st(t,"Enter email address",null==r?void 0:r.email),grant_type:"otp",scopes:["ACCESS_DB"],public_key:n};const a=await fetch(`${s}/token`,{body:JSON.stringify(i),method:"post",headers:{"Content-Type":"application/json",mode:"cors"}});if(200!==a.status){const e=await a.text();throw await it(t,"Token request failed",{type:"error",messageCode:"GENERIC_ERROR",message:e,messageParams:{}}).catch((()=>{})),new ht(a,e)}const c=await a.json();if("tokens"===c.type)return c;if("otp"===i.grant_type){if("otp-sent"!==c.type)throw new Error(`Unexpected response from ${s}/token`);const e=await at(t,i.email);i.otp=e||"",i.otp_id=c.otp_id;let n=await fetch(`${s}/token`,{body:JSON.stringify(i),method:"post",headers:{"Content-Type":"application/json"},mode:"cors"});for(;401===n.status;){const e=await n.text();i.otp=await at(t,i.email,{type:"error",messageCode:"INVALID_OTP",message:e,messageParams:{}}),n=await fetch(`${s}/token`,{body:JSON.stringify(i),method:"post",headers:{"Content-Type":"application/json"},mode:"cors"})}if(200!==n.status){const e=await n.text();throw await it(t,"OTP Authentication Failed",{type:"error",messageCode:"GENERIC_ERROR",message:e,messageParams:{}}).catch((()=>{})),new ht(n,e)}return await n.json()}throw new Error(`Unexpected response from ${s}/token`)}}(e),e.cloud.userInteraction,t),await n.save(),await async function(e,t){if(t.userId===e.cloud.currentUserId)return;const n=e.table("$logins");await e.transaction("rw",n,(async e=>{const r=await n.toArray();await Promise.all(r.filter((e=>e.userId!==t.userId&&e.isLoggedIn)).map((e=>(e.isLoggedIn=!1,n.put(e))))),t.isLoggedIn=!0,t.lastLogin=new Date,await t.save(),console.debug("Saved new user",t.email)})),await new Promise((n=>{if(e.cloud.currentUserId===t.userId)n(null);else{const r=e.cloud.currentUser.subscribe((e=>{e.userId===t.userId&&(r.unsubscribe(),n(null))}))}}))}(e,n),tt(e,"pull")}const pt={userId:"unauthorized",name:"Unauthorized",claims:{sub:"unauthorized"},lastLogin:new Date(0)};try{Object.freeze(pt),Object.freeze(pt.claims)}catch(e){}const yt={},bt=self.document&&navigator.serviceWorker;bt&&bt.ready.then((e=>yt.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 vt{constructor(e){this.name=e}subscribe(e){if(!bt)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 bt.addEventListener("message",t),()=>bt.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}))):yt.registration&&(null===(t=yt.registration.active)||void 0===t||t.postMessage({type:`sw-broadcast-${this.name}`,message:e}))}}class mt extends n{constructor(e){const t="undefined"==typeof BroadcastChannel?new vt(e):new BroadcastChannel(e);super((n=>{function r(e){n.next(e.detail)}function o(e){console.debug("BroadcastedAndLocalEvent: onMessageEvent",e),n.next(e.data)}let i;return self.addEventListener(`lbc-${e}`,r),t instanceof vt?i=t.subscribe((e=>n.next(e))):(console.debug("BroadcastedAndLocalEvent: bc.addEventListener()",e,"bc is a",t),t.addEventListener("message",o)),()=>{self.removeEventListener(`lbc-${e}`,r),t instanceof vt?i():t.removeEventListener("message",o)}})),this.name=e,this.bc=t}next(e){console.debug("BroadcastedAndLocalEvent: bc.postMessage()",{...e},"bc is a",this.bc),this.bc.postMessage(e);const t=new CustomEvent(`lbc-${this.name}`,{detail:e});self.dispatchEvent(t)}}async function gt({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),o=await crypto.subtle.digest("SHA-1",r);return rt(o)}function _t(e){return Object.entries(e.cloud.schema||{}).filter((([,{markedForSync:e}])=>e)).map((([t])=>e.table(t)))}function wt(e){return`$${e}_mutations`}function St(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}async function kt(e,t,{since:n={},limit:r=1/0}={}){return(await Promise.all(e.map((async e=>{const t=St(e.name),o=n[t];let i=o?e.where("rev").above(o):e;r<1/0&&(i=i.limit(r));return{table:t,muts:await i.toArray()}})))).filter((({muts:e})=>e.length>0))}const{toString:xt}={};const Et={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 t of n)delete r[t],r["$"+t]=e[t];return r}};function It(...e){const t=e.reduce(((e,t)=>({...e,...t})),e.reduce(((e,t)=>({...t,...e})),{})),n=new WeakMap;return{stringify:(e,r,o)=>JSON.stringify(e,(function(e){const o=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 Et;let i=n.get(r);if(void 0!==i)return i;const s=(o=e,xt.call(o).slice(8,-1)),a=Object.entries(t).find((([t,n])=>{var r,o;return null!==(o=null===(r=null==n?void 0:n.test)||void 0===r?void 0:r.call(n,e,s))&&void 0!==o?o:t===s}));return i=null==a?void 0:a[1],i||(i=Array.isArray(e)?null:"function"==typeof e?t.function||null:Et),n.set(r,i),i}default:return t[r]}var o}(o);return i?i.replace(o,r,t):o}),o),parse(e,n){let r=null,o=[];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}if(i===r){if(o.length>0){i={...i};for(const e of o)i[e.substr(1)]=i[e],delete i[e]}return o=[],i}return"$"===e[0]&&"$t"!==e&&(r=this,o.push(e)),i}))}}}const Tt={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 Ct={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 At={bigint:{replace:e=>({$t:"bigint",v:""+e}),revive:e=>BigInt(e.v)}};var Pt={Date:{replace:e=>({$t:"Date",v:isNaN(e.getTime())?"NaN":e.toISOString()}),revive:({v:e})=>new Date("NaN"===e?NaN:Date.parse(e))}},Ot={Set:{replace:e=>({$t:"Set",v:Array.from(e.entries())}),revive:({v:e})=>new Set(e)}},Ut={Map:{replace:e=>({$t:"Map",v:Array.from(e.entries())}),revive:({v:e})=>new Map(e)}};const $t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"==typeof global?global:void 0;var Dt=["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 o=$t[t];return o&&new o(r.ArrayBuffer.revive({v:e},n,r))}}})),{});function Nt(e){return function(e){for(var t="",n=0,r=e.length;n<r;n++)t+=Lt[e[n]];return t}(rt(e))}function Rt(e){return nt(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+=jt[e[n]];return t}(e))}const jt={"-":"=",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:"+","|":"/"},Lt={};for(const e of Object.keys(jt))Lt[jt[e]]=e;var Bt={ArrayBuffer:{replace:e=>({$t:"ArrayBuffer",v:Nt(e)}),revive:({v:e})=>{const t=Rt(e);return t.buffer.byteLength===t.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}}};class Wt{constructor(e,t){this.buf=e,this.type=t}}function Ft(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 Mt(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t[n]=e.charCodeAt(n);return t.buffer}const Ht={...Ct,...At,...Pt,...Ot,...Ut,...Dt,...Bt,...{Blob:{test:(e,t)=>"Blob"===t||e instanceof Wt,replace:e=>({$t:"Blob",v:rt(e instanceof Wt?e.buf:Mt(Ft(e))),type:e.type}),revive:({type:e,v:t})=>{const n=nt(t);return void 0!==typeof Blob?new Blob([n]):new Wt(n.buffer,e)}}}};function Vt(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 Kt={undefined:{replace:()=>{},revive:()=>{}}};const qt="bigint"==typeof BigInt(0);class zt{constructor(e){this.v=e}toString(){return this.v}}const Gt={...Kt,...qt?{}:{bigint:{test:e=>e instanceof zt,replace:e=>({$t:"bigint",...e}),revive:({v:e})=>new zt(e)}}},Jt=It(Ht,Gt),Yt=function(...e){const t=It(Ht,Tt,...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);return[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])}))),r]},async parse(e,n){let r=0;const o=[],i=await Vt(n),s=new DataView(i);for(;r<i.byteLength;){const e=s.getUint32(r);r+=4;const t=i.slice(r,r+e);r+=e,o.push(t)}return t.parse(e,o)},async fromBinary(e){const t=new DataView(await Vt(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)}}}(Gt);async function Xt(e,t,n,r,o,i,s){const a={Accept:"application/json, application/x-bison, application/x-bison-stream","Content-Type":"application/tson"},c=await async function(e){var t,n;const r=await e.getCurrentUser(),{accessToken:o,accessTokenExpiration:i,refreshToken:s,refreshTokenExpiration:a,claims:c}=r;if(!o)return;if((null!==(t=null==i?void 0:i.getTime())&&void 0!==t?t:1/0)>Date.now())return o;if(!s)throw new Error("Refresh token missing");if((null!==(n=null==a?void 0:a.getTime())&&void 0!==n?n:1/0)<=Date.now())throw new Error("Refresh token has expired");const u=await ut(e.cloud.options.databaseUrl,r);return await e.table("$logins").update(c.sub,{accessToken:u.accessToken,accessTokenExpiration:u.accessTokenExpiration}),u.accessToken}(r);c&&(a.Authorization=`Bearer ${c}`);const u={v:2,dbID:null==t?void 0:t.remoteDbId,clientIdentity:s,schema:i||{},lastPull:t?{serverRevision:t.serverRevision,realms:t.realms,inviteRealms:t.inviteRealms}:void 0,baseRevs:n,changes:e};console.debug("Sync request",u),r.syncStateChangedEvent.next({phase:"pushing"});const l=await fetch(`${o}/sync`,{method:"post",headers:a,body:Jt.stringify(u)});if(r.syncStateChangedEvent.next({phase:"pulling"}),!l.ok)throw new ht(l);switch(l.headers.get("content-type")){case"application/x-bison":return Yt.fromBinary(await l.blob());case"application/x-bison-stream":default:case"application/json":{const e=await l.text();return Jt.parse(e)}}}async function Zt(t,n,r){const o=await t.bulkGet(n),i=[],s=[];n.forEach(((n,a)=>{const c=o[a];if(c){for(const[n,o]of Object.entries(r[a])){if(n===t.schema.primKey.keyPath)throw new Error("Cannot change primary key");e.setByKeyPath(c,n,o)}i.push(n),s.push(c)}})),await(null==t.schema.primKey.keyPath?t.bulkPut(s,i):t.bulkPut(s))}function Qt(t){if(null==t?void 0:t.cancelled)throw new e.AbortError("Operation was cancelled")}let en=navigator.onLine;async function tn(e,t,n,r){await e.$baseRevs.bulkPut(Object.keys(t).filter((e=>t[e].markedForSync)).map((e=>({tableName:e,clientRev:(n[e]||0)+1,serverRev:r}))))}function nn(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}self.addEventListener("online",(()=>en=!0)),self.addEventListener("offline",(()=>en=!1));function rn(e,t,n,r){return on.apply(this,arguments).then((()=>{(null==r?void 0:r.justCheckIfNeeded)||e.syncStateChangedEvent.next({phase:"in-sync"})})).catch((async o=>(null==r?void 0:r.justCheckIfNeeded)?Promise.reject(o):(console.debug("Error from _sync",{isOnline:en,syncOptions:r,error:o}),en&&(null==r?void 0:r.retryImmediatelyOnFetchError)&&"TypeError"===(null==o?void 0:o.name)&&/fetch/.test(null==o?void 0:o.message)?(e.syncStateChangedEvent.next({phase:"error",error:o}),await new Promise((e=>setTimeout(e,500))),await rn(e,t,n,{...r,retryImmediatelyOnFetchError:!1})):(await e.$syncState.update("syncState",{timestamp:new Date,error:""+o}),e.syncStateChangedEvent.next({phase:en?"error":"offline",error:o}),Promise.reject(o)))))}async function on(e,t,n,{isInitialSync:r,cancelToken:o,justCheckIfNeeded:i,purpose:s}={isInitialSync:!1}){var a;if(i||console.debug("SYNC STARTED",{isInitialSync:r,purpose:s}),!(null===(a=e.cloud.options)||void 0===a?void 0:a.databaseUrl))throw new Error("Internal error: sync must not be called when no databaseUrl is configured");const{databaseUrl:c}=t,u=await e.getCurrentUser(),l=u.isLoggedIn?_t(e):[],d=l.map((t=>e.table(wt(t.name)))),h=await e.getPersistedSyncState(),f=!r&&u.isLoggedIn?function(e,t){const n=(null==t?void 0:t.syncedTables)||[];return _t(e).filter((e=>!n.includes(e.name)))}(e,h):[];Qt(o);const b=f.length>0;if(b){if(i)return!0;console.debug("sync doSyncify is true"),await e.transaction("rw",f,(async e=>{e.idbtrans.disableChangeTracking=!0,e.idbtrans.disableAccessControl=!0,await async function(e,t,n){const r=new Set(n||[]);for(const n of e)"members"===n.name?await n.toCollection().modify((e=>{r.has(e.realmId)||e.userId!==pt.userId||(e.userId=t.userId)})):"roles"===n.name||("realms"===n.name?await n.toCollection().modify((e=>{(r.has(e.realmId)||e.owner)&&e.owner!==pt.userId||(e.owner=t.userId)})):await n.toCollection().modify((e=>{e.realmId&&r.has(e.realmId)||(e.owner&&e.owner!==pt.userId||(e.owner=t.userId),e.realmId&&e.realmId!==pt.userId||(e.realmId=t.userId))})))}(f,u,null==h?void 0:h.realms)})),Qt(o)}const[v,m,g]=await e.transaction("r",e.tables,(async()=>{const t=await e.getPersistedSyncState(),r=await e.$baseRevs.toArray();let i=await kt(d);if(Qt(o),b){const e=await async function(e,t,n,r){if(t.isLoggedIn&&e.length>0){const o=new Set(r||[]);return(await Promise.all(e.map((async e=>{const{extractKey:r}=e.core.schema.primaryKey;if(!r)return{table:e.name,muts:[]};const i=n[e.name],s=(null==i?void 0:i.generatedGlobalId)?e.filter((e=>!o.has(e.realmId||"")&&y(r(e)))):e.filter((e=>{return!o.has(e.realmId||"")&&(t=r(e),!(n=null==i?void 0:i.idPrefix)||"string"==typeof t&&t.startsWith(n));var t,n})),a=await s.toArray();if(a.length>0){const n={type:"insert",values:a,keys:a.map(r),userId:t.userId};return{table:e.name,muts:[n]}}return{table:e.name,muts:[]}})))).filter((e=>e.muts.length>0))}return[]}(f,u,n,null==h?void 0:h.realms);return Qt(o),i=i.concat(e),[i,t,r]}return[i,t,r]})),_=v.some((e=>e.muts.some((e=>e.keys.length>0))));if(i)return console.debug("Sync is needed:",_),_;if("push"===s&&!_)return!1;const w=nn(v,null==m?void 0:m.latestRevisions),S=(null==m?void 0:m.clientIdentity)||p(16);Qt(o);const k=await Xt(v,m,g,e,c,n,S);console.debug("Sync response",k);return await e.transaction("rw",e.tables,(async t=>{t.idbtrans.disableChangeTracking=!0,t.idbtrans.disableAccessControl=!0;for(const e of Object.keys(n))k.schema[e]&&(n[e]=k.schema[e]);await e.$syncState.put(n,"schema");const r=await kt(d,0,{since:w});for(const t of d){const n=St(t.name);if(r.some((e=>e.table===n&&e.muts.length>0))){if(w[t.name]){const r=w[t.name]||0;await 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 await Promise.all([t.clear(),e.$baseRevs.where({tableName:n}).delete()])}nn(r,w),await tn(e,n,w,k.serverRevision);const o=await e.getPersistedSyncState();await async function(e,t,n){const r=[],o=n?n.realms.concat(n.inviteRealms):[],i=new Set([...t.realms,...t.inviteRealms]);for(const e of o)i.has(e)||r.push(e);if(r.length>0){const t=new Set(r),n=_t(e);for(const e of n)e.schema.indexes.some((e=>"realmId"===e.keyPath||Array.isArray(e.keyPath)&&"realmId"===e.keyPath[0]))?await e.where("realmId").anyOf(r).delete():await e.filter((e=>!!(null==e?void 0:e.realmId)&&t.has(e.realmId))).delete()}}(e,k,o);const i=o||{syncedTables:[],latestRevisions:{},realms:[],inviteRealms:[],clientIdentity:S};i.syncedTables=l.map((e=>e.name)).concat(f.map((e=>e.name))),i.latestRevisions=w,i.remoteDbId=k.dbId,i.initiallySynced=!0,i.realms=k.realms,i.inviteRealms=k.inviteRealms,i.serverRevision=k.serverRevision,i.timestamp=new Date,delete i.error;const s=an(k.changes,r);return await sn(s,e),e.$syncState.put(i,"syncState"),0===r.length}))?(console.debug("SYNC DONE",{isInitialSync:r}),!1):(console.debug("MORE SYNC NEEDED. Go for it again!"),await on(e,t,n,{isInitialSync:r,cancelToken:o}))}async function sn(t,n){console.debug("Applying server changes",t,e.currentTransaction);for(const{table:r,muts:o}of t){const t=n.table(r);if(!t)continue;const{primaryKey:i}=t.core.schema;for(const n of o)switch(n.type){case"insert":i.outbound?await t.bulkAdd(n.values,n.keys):(n.keys.forEach(((t,r)=>{e.setByKeyPath(n.values[r],i.keyPath,t)})),await t.bulkAdd(n.values));break;case"upsert":i.outbound?await t.bulkPut(n.values,n.keys):(n.keys.forEach(((t,r)=>{e.setByKeyPath(n.values[r],i.keyPath,t)})),await t.bulkPut(n.values));break;case"modify":1===n.keys.length?await t.update(n.keys[0],n.changeSpec):await t.where(":id").anyOf(n.keys).modify(n.changeSpec);break;case"update":await Zt(t,n.keys,n.changeSpecs);break;case"delete":await t.bulkDelete(n.keys)}}}function an(e,t){const n={};m(n,e);const r={};return m(r,t),function(e,t){var n,r,o;for(const[i,s]of Object.entries(t))for(const[t,a]of Object.entries(s))switch(a.type){case"ups":{const r=null===(n=e[i])||void 0===n?void 0:n[t];if(r)switch(r.type){case"ups":delete e[i][t];break;case"del":break;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===(o=e[i])||void 0===o?void 0:o[t];if(n)switch(n.type){case"ups":for(const[e,t]of Object.entries(a.mod))f(n.val,e,t);break;case"del":break;case"upd":for(const e of Object.keys(a.mod))delete n.mod[e]}break}}}(n,r),function(e){const t=p(16),n={};for(const[t,r]of Object.entries(e))for(const[e,o]of Object.entries(r)){const r=n[t]||(n[t]={});(r[o.type]||(r[o.type]=[])).push(Object.assign({key:e},o))}const r=[];for(const[e,o]of Object.entries(n)){const n={table:e,muts:[]};for(const[e,r]of Object.entries(o))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)}function cn(t){const n=[],o=new r(!0),i=new r(null);let s=!1,a=0,c=[0,0,0,0,0,0,0,0,0,Date.now()];return i.subscribe((async()=>{if(!s&&n.length>0){s=!0,c.shift(),c.push(Date.now()),o.next(!1);try{await async function(){var r,o,i;for(;n.length>0;){const s=n.shift();try{console.debug("processing msg",s),await t.cloud.syncState.pipe(Ue((({phase:e})=>"in-sync"===e||"error"===e)),Ne(1)).toPromise(),console.debug("processing msg",s);const n=t.cloud.persistedSyncState.value;if(!s)continue;switch(s.type){case"token-expired":console.debug("WebSocket observable: Token expired. Refreshing token...");const a=t.cloud.currentUser.value,c=await ut(t.cloud.options.databaseUrl,a);await t.table("$logins").update(a.userId,{accessToken:c.accessToken,accessTokenExpiration:c.accessTokenExpiration});break;case"realm-added":(null===(r=null==n?void 0:n.realms)||void 0===r?void 0:r.includes(s.realm))||tt(t,"pull");break;case"realm-removed":(null===(o=null==n?void 0:n.realms)||void 0===o?void 0:o.includes(s.realm))&&tt(t,"pull");break;case"realms-changed":tt(t,"pull");break;case"changes":if(console.debug("changes"),"error"===(null===(i=t.cloud.syncState.value)||void 0===i?void 0:i.phase)){tt(t,"pull");break}await t.transaction("rw",t.dx.tables,(async n=>{n.idbtrans.disableChangeTracking=!0,n.idbtrans.disableAccessControl=!0;const[r,o,i]=await Promise.all([t.getSchema(),t.getPersistedSyncState(),t.getCurrentUser()]);if(console.debug("ws message queue: in transaction"),!o||!r||!i)return void console.debug("required vars not present",{syncState:o,schema:r,currentUser:i});if(s.baseRev!==o.serverRevision)return console.debug(`baseRev (${s.baseRev}) differs from our serverRevision in syncState (${o.serverRevision})`),void("string"!=typeof s.baseRev||"bigint"!=typeof o.serverRevision&&"object"!=typeof o.serverRevision||tt(t,"pull"));const a=await e.waitFor(gt(o));if(console.debug("ourRealmSetHash",a),a!==s.realmSetHash)return console.debug("not same realmSetHash",s.realmSetHash),void tt(t,"pull");let c=[];if(i.isLoggedIn){const e=_t(t).map((e=>t.table(wt(e.name))));c=await kt(e),console.debug("msg queue: client changes",c)}if(s.changes.length>0){const e=an(s.changes,c);console.debug("applying filtered server changes",e),await sn(e,t)}o.latestRevisions=nn(c,o.latestRevisions),o.serverRevision=s.newRev,console.debug("Updating baseRefs",o.latestRevisions),await tn(t,r,o.latestRevisions,s.newRev),console.debug("Updating syncState",o),await t.$syncState.put(o,"syncState")})),console.debug("msg queue: done with rw transaction")}}catch(e){console.error("Error in msg queue",e)}}}()}finally{c[c.length-1]-c[0]<1e4&&(Date.now()-a<5e3?(console.warn("Slowing down websocket loop for one minute"),a=Date.now()+6e4,await new Promise((e=>setTimeout(e,6e4)))):(console.warn("Slowing down websocket loop for 10 seconds"),a=Date.now()+1e4,await new Promise((e=>setTimeout(e,1e4))))),s=!1,o.next(!0)}}})),{enqueue:function(e){n.push(e),i.next(null)},readyToServe:o}}const un=new WeakMap,ln={realms:"@realmId",members:"@id",roles:"[realmId+name]",$jobs:"",$syncState:"",$baseRevs:"[tableName+clientRev]",$logins:"claims.sub, lastLogin"};let dn=0;function hn(e){"vip"in e&&(e=e.vip);let t=un.get(e.cloud);if(!t){const n=new o;let r=new mt(`syncstatechanged-${e.name}`);n.id=++dn;let i=!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 i},localSyncEvent:n,get syncStateChangedEvent(){return r},dx:e};const s={getCurrentUser:()=>t.$logins.toArray().then((e=>e.find((e=>e.isLoggedIn))||pt)),getPersistedSyncState:()=>t.$syncState.get("syncState"),getSchema:()=>t.$syncState.get("schema"),getOptions:()=>t.$syncState.get("options"),setInitiallySynced(e){i=e},reconfigure(){r=new mt(`syncstatechanged-${e.name}`)}};Object.assign(t,s),t.messageConsumer=cn(t),un.set(e.cloud,t)}return t}const fn="undefined"!=typeof InstallTrigger,pn="undefined"!=typeof navigator&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\/|Edge\//.test(navigator.userAgent),yn=pn?[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]:NaN,bn=pn&&yn<=605||fn;const vn="undefined"!=typeof self&&"clients"in self&&!self.document;function mn(){throw new e.SchemaError("Version increment needed to allow dexie-cloud change tracking")}const{toString:gn}={};function _n(e){return gn.call(e).slice(8,-1)}function wn(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 Sn=/b|c|d|f|g|h|j|k|l|m|n|p|q|r|s|t|v|x|y|z/i;let kn=0;function xn(t){return{stack:"dbcore",name:"idGenerationMiddleware",level:1,create:n=>({...n,table:r=>{const o=n.table(r);function i(n,i){let s=null;const a=wn(o.schema.primaryKey,n);return a.forEach(((c,u)=>{if(void 0===c){const r=n.values[u].realmId||t.cloud.currentUserId,c=r.substr(r.length-3);a[u]=function(e,t){const n=new Uint8Array(18),r=new Uint8Array(n.buffer,0,6),o=Date.now();kn>=o?++kn:kn=o,r[0]=kn/1099511627776,r[1]=kn/4294967296,r[2]=kn/16777216,r[3]=kn/65536,r[4]=kn/256,r[5]=kn;const i=new Uint8Array(n.buffer,6);return crypto.getRandomValues(i),e+Nt(new Uint8Array(n.buffer))+(t||"")}(i,c),o.schema.primaryKey.outbound||(s||(s=n.values.slice()),s[u]=e.deepClone(s[u]),e.setByKeyPath(s[u],o.schema.primaryKey.keyPath,a[u]))}else if("string"!=typeof c||!c.startsWith(i))throw new e.ConstraintError(`The ID "${c}" is not valid for table "${r}". Primary '@' keys requires the key to be prefixed with "${i}.\n"If 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.`)})),o.mutate({...n,keys:a,values:s||n.values})}return{...o,mutate:n=>{var s,a;if(n.trans.disableChangeTracking)return o.mutate(n);if("add"===n.type||"put"===n.type){const c=null===(s=t.cloud.schema)||void 0===s?void 0:s[r];if(null==c?void 0:c.generatedGlobalId){if((null===(a=t.cloud.options)||void 0===a?void 0:a.databaseUrl)&&!t.initiallySynced){const e=wn(o.schema.primaryKey,n);return o.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 o.mutate(n)}))}return i(n,c.idPrefix)}if(null==c?void 0:c.markedForSync){wn(o.schema.primaryKey,n).forEach(((t,n)=>{if(!y(t)){const n=Array.isArray(t)?t.map(_n).join(","):_n(t);throw new e.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 o.mutate(n)}}}})}}function En(e){const t=new Uint8Array(e);return crypto.getRandomValues(t),btoa(String.fromCharCode.apply(null,t))}let In=0;function Tn(e,t){return function(n){const{readers:r,writers:o}=n.trans[t]||(n.trans[t]={writers:[],readers:[]}),i=o.length,s=(i>0?o[i-1].then((()=>e(n)),(()=>e(n))):e(n)).finally((()=>r.splice(r.indexOf(s))));return r.push(s),s}}function Cn(e,t){return function(n){const{readers:r,writers:o}=n.trans[t]||(n.trans[t]={writers:[],readers:[]});let i=(o.length>0?o[o.length-1].then((()=>e(n)),(()=>e(n))):r.length>0?(s=r,new Promise((e=>{0===s.length&&e([]);let t=s.length;const n=new Array(t);s.forEach(((r,o)=>Promise.resolve(r).then((e=>n[o]={status:"fulfilled",value:e}),(e=>n[o]={status:"rejected",reason:e})).then((()=>--t||e(n)))))}))).then((()=>e(n))):e(n)).finally((()=>o.shift()));var s;return o.push(i),i}}const An=new r(new Set);function Pn({currentUserObservable:e,db:t}){return{stack:"dbcore",name:"MutationTrackingMiddleware",level:1,create:n=>{const r=n.schema.tables.filter((e=>!/^\$/.test(e.name)));let o;try{o=new Map(r.map((e=>[e.name,n.table(`$${e.name}_mutations`)])))}catch(e){mn()}return{...n,transaction:(r,o)=>{let i;if("readwrite"===o){const e=r.filter((e=>{var n,r;return null===(r=null===(n=t.cloud.schema)||void 0===n?void 0:n[e])||void 0===r?void 0:r.markedForSync})).map((e=>wt(e)));i=n.transaction([...r,...e],o)}else i=n.transaction(r,o);if("readwrite"===o){i.txid=En(16),i.currentUser=e.value,An.value.add(i),An.next(An.value);const n=()=>{i.removeEventListener("complete",r),i.removeEventListener("error",n),i.removeEventListener("abort",n),An.value.delete(i),An.next(An.value)},r=()=>{var e;i.mutationsAdded&&(null===(e=t.cloud.options)||void 0===e?void 0:e.databaseUrl)&&(t.cloud.usingServiceWorker?(console.debug("registering sync event"),et(t,"push")):t.localSyncEvent.next({purpose:"push"})),n()};i.addEventListener("complete",r),i.addEventListener("error",n),i.addEventListener("abort",n)}return i},table:e=>{const t=n.table(e);if(/^\$/.test(e))return e.endsWith("_mutations")?{...t,mutate:e=>("add"!==e.type&&"put"!==e.type||(e.trans.mutationsAdded=!0),t.mutate(e))}:"$logins"===e?{...t,mutate:e=>(console.debug("Mutating $logins table",e),t.mutate(e).then((t=>(console.debug("Mutating $logins"),e.trans.mutationsAdded=!0,console.debug("$logins mutated"),t))).catch((e=>(console.debug("Failed mutation $logins",e),Promise.reject(e)))))}:t;const{schema:r}=t,i=o.get(e);return function(e){const t="$lock"+ ++In;return{...e,count:Tn(e.count,t),get:Tn(e.get,t),getMany:Tn(e.getMany,t),openCursor:Tn(e.openCursor,t),query:Tn(e.query,t),mutate:Cn(e.mutate,t)}}({...t,mutate:e=>{var n;const o=e.trans;return o.txid?o.disableChangeTracking?t.mutate(e):(null===(n=o.currentUser)||void 0===n?void 0:n.isLoggedIn)?"deleteRange"===e.type?t.query({query:{range:e.range,index:r.primaryKey},trans:e.trans,values:!1}).then((t=>s({type:"delete",keys:t.result,trans:e.trans,criteria:{index:null,range:e.range}}))):s(e):t.mutate(e):t.mutate(e)}});function s(e){const n=e.trans;n.mutationsAdded=!0;const{txid:r,currentUser:{userId:o}}=n,{type:s}=e;return t.mutate(e).then((t=>{const{numFailures:a,failures:c}=t;let u="delete"===s?e.keys:t.results,l="values"in e?e.values:[],d="changeSpecs"in e?e.changeSpecs:[];a&&(u=u.filter(((e,t)=>!c[t])),l=l.filter(((e,t)=>!c[t])),d=d.filter(((e,t)=>!c[t])));const h=Date.now(),f="delete"===e.type?{type:"delete",ts:h,keys:u,criteria:e.criteria,txid:r,userId:o}:"add"===e.type?{type:"insert",ts:h,keys:u,txid:r,userId:o,values:l}:e.criteria&&e.changeSpec?{type:"modify",ts:h,keys:u,criteria:e.criteria,changeSpec:e.changeSpec,txid:r,userId:o}:e.changeSpecs?{type:"update",ts:h,keys:u,changeSpecs:d,txid:r,userId:o}:{type:"upsert",ts:h,keys:u,values:l,txid:r,userId:o};return u.length>0||"criteria"in e&&e.criteria?i.mutate({type:"add",trans:n,values:[f]}).then((()=>t)):t}))}}}}}}function On(e,t){return function(n,r){const o={...ln,...n},i=t.cloud.schema||(t.cloud.schema={}),s=new Set;Object.keys(o).forEach((e=>{const t=o[e],n=i[e]||(i[e]={});null!=t?(/^\@/.test(t)&&(o[e]=o[e].substr(1),n.generatedGlobalId=!0,n.idPrefix=function(e,t){let n=e[0].toLocaleLowerCase();for(let t=1,o=e.length;t<o&&n.length<3;++t)(Sn.test(e[t])||(r=e[t])>="A"&&r<="Z")&&(n+=e[t].toLowerCase());for(var r,o,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;)o=n,r=(1&(i=e)?o[0].toUpperCase():o[0].toLowerCase())+(2&i?o[1].toUpperCase():o[1].toLowerCase())+(4&i?o[2].toUpperCase():o[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,s),s.add(n.idPrefix)),/^\$/.test(e)||(o[`$${e}_mutations`]="++rev",n.markedForSync=!0),n.deleted&&(n.deleted=!1)):(n.deleted=!0,n.markedForSync=!1,o[`$${e}_mutations`]=null)}));return e.call(this,o,r)}}const Un=En(16);async function $n(e,n,r,o,{awaitRemoteJob:s}={}){const a=e.table(r);if(await async function o(){if(await e.transaction("rw!",r,(async()=>{const e=await a.get(n);return e?e.heartbeat.getTime()<Date.now()-6e4&&(console.warn(`Latest ${n} worker seem to have died.\n`,"The dead job started:",e.started,"\n","Last heart beat was:",e.heartbeat,"\n","We're now taking over!"),await a.put({nodeId:Un,started:new Date,heartbeat:new Date},n),!0):(await a.add({nodeId:Un,started:new Date,heartbeat:new Date},n),!0)})))return!0;if(s)try{const e=i(t((()=>a.get(n)))).pipe(Ze(6e4),Ue((e=>!e)));return await e.toPromise(),!1}catch(e){if("TimeoutError"!==e.name)throw e;return await o()}return!1}()){const t=setInterval((()=>{a.update(n,(e=>e.nodeId===Un&&(e.heartbeat=new Date)))}),1e3);try{return await o()}finally{clearInterval(t),await e.transaction("rw!",r,(async()=>{const e=await a.get(n);e&&e.nodeId===Un&&a.delete(n)}))}}}const Dn=new r(!0),Nn=new r(!0);var Rn,jn;Dn.pipe(Me((e=>e?a(!0):a(!1).pipe(Ee(2e4)))),(function(e){return e.lift(new Ae(Rn,jn))})).subscribe(Nn);const Ln="undefined"!=typeof document?s(document,"visibilitychange"):a({}),Bn=Ln.pipe(Ue((()=>"hidden"===document.visibilityState))),Wn=Ln.pipe(Ue((()=>"visible"===document.visibilityState))),Fn="undefined"!=typeof window?c(Wn,s(window,"mousemove"),s(window,"keydown"),s(window,"wheel"),s(window,"touchmove")):a({});"undefined"!=typeof document&&c(a(!0),Bn,Fn).pipe(se((()=>"visible"===document.visibilityState)),qe((e=>{Dn.value!==e&&Dn.next(e)})),Me((e=>e?a(0).pipe(Ee(28e4),qe((()=>Dn.next(!1)))):a(0)))).subscribe((()=>{}));class Mn extends Error{constructor(){super(...arguments),this.name="TokenExpiredError"}}class Hn extends n{constructor(e,t,n,r,o,i,s,a){super((c=>new Kn(e,t,n,r,s,a,c,o,i)))}}let Vn=0;class Kn extends u{constructor(e,t,n,r,o,i,s,a,c){super((()=>this.teardown())),this.id=++Vn,console.debug("New WebSocket Connection",this.id,o?"authorized":"unauthorized"),this.databaseUrl=e,this.rev=t,this.realmSetHash=n,this.clientIdentity=r,this.token=o,this.tokenExpiration=i,this.subscriber=s,this.lastUserActivity=new Date,this.messageProducer=a,this.messageProducerSubscription=null,this.webSocketStatus=c,this.connect()}teardown(){console.debug("Teardown WebSocket Connection",this.id),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,this.messageProducerSubscription&&(this.messageProducerSubscription.unsubscribe(),this.messageProducerSubscription=null)}reconnect(){this.disconnect(),this.connect()}async connect(){if(this.webSocketStatus.next("connecting"),this.lastServerActivity=new Date,this.pauseUntil&&this.pauseUntil>new Date)return void console.debug("WS not reconnecting just yet",{id:this.id,pauseUntil:this.pauseUntil});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;if(this.tokenExpiration&&this.tokenExpiration<new Date)return void this.subscriber.error(new Mn);this.pinger=setInterval((async()=>{if(this.closed)return console.debug("pinger check",this.id,"CLOSED."),void this.teardown();if(this.ws)try{this.ws.send(JSON.stringify({type:"ping"})),setTimeout((()=>{if(console.debug("pinger setTimeout",this.id,this.pinger?"alive":"dead"),this.pinger)return this.closed?(console.debug("pinger setTimeout",this.id,"subscription is closed"),void this.teardown()):void(this.lastServerActivity<new Date(Date.now()-2e4)?(console.debug("pinger: server is inactive"),console.debug("pinger reconnecting"),this.reconnect()):console.debug("pinger: server still active"))}),2e4)}catch(e){console.debug("pinger catch error",this.id,"reconnecting"),this.reconnect()}else console.debug("pinger",this.id,"reconnecting"),this.reconnect()}),3e4);const e=new URL(this.databaseUrl);e.protocol="http:"===e.protocol?"ws":"wss";const t=new URLSearchParams;if(this.subscriber.closed)return;t.set("v","2"),t.set("rev",this.rev),t.set("realmsHash",this.realmSetHash),t.set("clientId",this.clientIdentity),this.token&&t.set("token",this.token),console.debug("dexie-cloud WebSocket create");const n=this.ws=new WebSocket(`${e}/changes?${t}`);n.onclose=e=>{this.pinger&&(console.debug("dexie-cloud WebSocket onclosed",this.id),this.reconnect())},n.onmessage=e=>{if(this.pinger){console.debug("dexie-cloud WebSocket onmessage",e.data),this.lastServerActivity=new Date;try{const t=Jt.parse(e.data);if("error"===t.type)throw new Error(`Error message from dexie-cloud: ${t.error}`);"rev"===t.type&&(this.rev=t.rev),"pong"!==t.type&&this.subscriber.next(t)}catch(e){this.subscriber.error(e)}}};try{await new Promise(((e,t)=>{n.onopen=t=>{console.debug("dexie-cloud WebSocket onopen"),e(null)},n.onerror=e=>{const n=e.error||new Error("WebSocket Error");this.disconnect(),this.subscriber.error(n),this.webSocketStatus.next("error"),t(n)}})),this.messageProducerSubscription=this.messageProducer.subscribe((e=>{var t;this.closed||("ready"===e.type&&"connected"!==this.webSocketStatus.value&&this.webSocketStatus.next("connected"),null===(t=this.ws)||void 0===t||t.send(Jt.stringify(e)))}))}catch(e){this.pauseUntil=new Date(Date.now()+6e4)}}}async function qn(e){var t;console.error("WebSocket observable: error but revive when user does some active thing...",e),await(t=3e3,new Promise((e=>setTimeout(e,t)))),console.debug("waiting for someone to do something"),await Fn.pipe(Ne(1)).toPromise(),console.debug("someone did something!")}async function zn(e){var t;return!(!(null===(t=e.cloud.options)||void 0===t?void 0:t.databaseUrl)||!e.cloud.schema)&&await rn(e,e.cloud.options,e.cloud.schema,{justCheckIfNeeded:!0})}const Gn=new WeakMap;function Jn(e,t,n,r){const o=Gn.get(e);if(o){if(o.pull||"push"===(null==r?void 0:r.purpose))return console.debug("syncIfPossible(): returning the ongoing sync promise."),o.promise;{let i=!1;const s=e.cloud.syncState.subscribe((e=>{"pulling"===e.phase&&(i=!0)}));return o.promise.then((()=>{s.unsubscribe()})).catch((e=>(s.unsubscribe(),Promise.reject(e)))).then((()=>{if(!i)return Jn(e,t,n,r)}))}}const i=async function(){try{e.cloud.usingServiceWorker?vn&&await rn(e,t,n,r):await $n(e,"currentSyncWorker","$jobs",(()=>rn(e,t,n,r))),Gn.delete(e),console.debug("Done sync")}catch(t){throw Gn.delete(e),console.error("Failed to sync client changes",t),t}}();return Gn.set(e,{promise:i,pull:"push"!==(null==r?void 0:r.purpose)}),i}function Yn(e,t,n){let r=null,o={cancelled:!1};function i(r,a=1){setTimeout((()=>{Jn(e,t,n,{cancelToken:o,retryImmediatelyOnFetchError:!0,purpose:r}).catch((e=>{console.error("error in syncIfPossible()",e),o.cancelled?s():a<3&&setTimeout((()=>i(r,a+1)),6e4*[0,5,15][a])}))}),0)}const s=()=>{console.debug("Stopping LocalSyncWorker"),o.cancelled=!0,r&&r.unsubscribe()};return{start:()=>{console.debug("Starting LocalSyncWorker",e.localSyncEvent.id),r=e.localSyncEvent.subscribe((({purpose:e})=>{try{i(e||"pull")}catch(e){console.error("What-the....",e)}}))},stop:s}}function Xn(e,t){if(e&&t&&t.unsyncedTables)for(const n of t.unsyncedTables)e[n]&&(e[n].markedForSync=!1)}var Zn,Qn,er,tr,nr={},rr=[],or=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i;function ir(e,t){for(var n in t)e[n]=t[n];return e}function sr(e){var t=e.parentNode;t&&t.removeChild(e)}function ar(e,t,n){var r,o,i,s=arguments,a={};for(i in t)"key"==i?r=t[i]:"ref"==i?o=t[i]:a[i]=t[i];if(arguments.length>3)for(n=[n],i=3;i<arguments.length;i++)n.push(s[i]);if(null!=n&&(a.children=n),"function"==typeof e&&null!=e.defaultProps)for(i in e.defaultProps)void 0===a[i]&&(a[i]=e.defaultProps[i]);return cr(e,a,r,o,null)}function cr(e,t,n,r,o){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==o?++Zn.__v:o};return null!=Zn.vnode&&Zn.vnode(i),i}function ur(e){return e.children}function lr(e,t){this.props=e,this.context=t}function dr(e,t){if(null==t)return e.__?dr(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?dr(e):null}function hr(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 hr(e)}}function fr(e){(!e.__d&&(e.__d=!0)&&Qn.push(e)&&!pr.__r++||tr!==Zn.debounceRendering)&&((tr=Zn.debounceRendering)||er)(pr)}function pr(){for(var e;pr.__r=Qn.length;)e=Qn.sort((function(e,t){return e.__v.__b-t.__v.__b})),Qn=[],e.some((function(e){var t,n,r,o,i,s;e.__d&&(i=(o=(t=e).__v).__e,(s=t.__P)&&(n=[],(r=ir({},o)).__v=o.__v+1,Sr(s,o,r,t.__n,void 0!==s.ownerSVGElement,null!=o.__h?[i]:null,n,null==i?dr(o):i,o.__h),kr(n,o),o.__e!=i&&hr(o)))}))}function yr(e,t,n,r,o,i,s,a,c,u){var l,d,h,f,p,y,b,v=r&&r.__k||rr,m=v.length;for(n.__k=[],l=0;l<t.length;l++)if(null!=(f=n.__k[l]=null==(f=t[l])||"boolean"==typeof f?null:"string"==typeof f||"number"==typeof f||"bigint"==typeof f?cr(null,f,null,null,f):Array.isArray(f)?cr(ur,{children:f},null,null,null):f.__b>0?cr(f.type,f.props,f.key,null,f.__v):f)){if(f.__=n,f.__b=n.__b+1,null===(h=v[l])||h&&f.key==h.key&&f.type===h.type)v[l]=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}Sr(e,f,h=h||nr,o,i,s,a,c,u),p=f.__e,(d=f.ref)&&h.ref!=d&&(b||(b=[]),h.ref&&b.push(h.ref,null,f),b.push(d,f.__c||p,f)),null!=p?(null==y&&(y=p),"function"==typeof f.type&&null!=f.__k&&f.__k===h.__k?f.__d=c=br(f,c,e):c=vr(e,f,h,v,p,c),u||"option"!==n.type?"function"==typeof n.type&&(n.__d=c):e.value=""):c&&h.__e==c&&c.parentNode!=e&&(c=dr(h))}for(n.__e=y,l=m;l--;)null!=v[l]&&("function"==typeof n.type&&null!=v[l].__e&&v[l].__e==n.__d&&(n.__d=dr(r,l+1)),Ir(v[l],v[l]));if(b)for(l=0;l<b.length;l++)Er(b[l],b[++l],b[++l])}function br(e,t,n){var r,o;for(r=0;r<e.__k.length;r++)(o=e.__k[r])&&(o.__=e,t="function"==typeof o.type?br(o,t,n):vr(n,o,o,e.__k,o.__e,t));return t}function vr(e,t,n,r,o,i){var s,a,c;if(void 0!==t.__d)s=t.__d,t.__d=void 0;else if(null==n||o!=i||null==o.parentNode)e:if(null==i||i.parentNode!==e)e.appendChild(o),s=null;else{for(a=i,c=0;(a=a.nextSibling)&&c<r.length;c+=2)if(a==o)break e;e.insertBefore(o,i),s=i}return void 0!==s?s:o.nextSibling}function mr(e,t,n){"-"===t[0]?e.setProperty(t,n):e[t]=null==n?"":"number"!=typeof n||or.test(t)?n:n+"px"}function gr(e,t,n,r,o){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||mr(e.style,t,"");if(n)for(t in n)r&&n[t]===r[t]||mr(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?wr:_r,i):e.removeEventListener(t,i?wr:_r,i);else if("dangerouslySetInnerHTML"!==t){if(o)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 _r(e){this.l[e.type+!1](Zn.event?Zn.event(e):e)}function wr(e){this.l[e.type+!0](Zn.event?Zn.event(e):e)}function Sr(e,t,n,r,o,i,s,a,c){var u,l,d,h,f,p,y,b,v,m,g,_=t.type;if(void 0!==t.constructor)return null;null!=n.__h&&(c=n.__h,a=t.__e=n.__e,t.__h=null,i=[a]),(u=Zn.__b)&&u(t);try{e:if("function"==typeof _){if(b=t.props,v=(u=_.contextType)&&r[u.__c],m=u?v?v.props.value:u.__:r,n.__c?y=(l=t.__c=n.__c).__=l.__E:("prototype"in _&&_.prototype.render?t.__c=l=new _(b,m):(t.__c=l=new lr(b,m),l.constructor=_,l.render=Tr),v&&v.sub(l),l.props=b,l.state||(l.state={}),l.context=m,l.__n=r,d=l.__d=!0,l.__h=[]),null==l.__s&&(l.__s=l.state),null!=_.getDerivedStateFromProps&&(l.__s==l.state&&(l.__s=ir({},l.__s)),ir(l.__s,_.getDerivedStateFromProps(b,l.__s))),h=l.props,f=l.state,d)null==_.getDerivedStateFromProps&&null!=l.componentWillMount&&l.componentWillMount(),null!=l.componentDidMount&&l.__h.push(l.componentDidMount);else{if(null==_.getDerivedStateFromProps&&b!==h&&null!=l.componentWillReceiveProps&&l.componentWillReceiveProps(b,m),!l.__e&&null!=l.shouldComponentUpdate&&!1===l.shouldComponentUpdate(b,l.__s,m)||t.__v===n.__v){l.props=b,l.state=l.__s,t.__v!==n.__v&&(l.__d=!1),l.__v=t,t.__e=n.__e,t.__k=n.__k,t.__k.forEach((function(e){e&&(e.__=t)})),l.__h.length&&s.push(l);break e}null!=l.componentWillUpdate&&l.componentWillUpdate(b,l.__s,m),null!=l.componentDidUpdate&&l.__h.push((function(){l.componentDidUpdate(h,f,p)}))}l.context=m,l.props=b,l.state=l.__s,(u=Zn.__r)&&u(t),l.__d=!1,l.__v=t,l.__P=e,u=l.render(l.props,l.state,l.context),l.state=l.__s,null!=l.getChildContext&&(r=ir(ir({},r),l.getChildContext())),d||null==l.getSnapshotBeforeUpdate||(p=l.getSnapshotBeforeUpdate(h,f)),g=null!=u&&u.type===ur&&null==u.key?u.props.children:u,yr(e,Array.isArray(g)?g:[g],t,n,r,o,i,s,a,c),l.base=t.__e,t.__h=null,l.__h.length&&s.push(l),y&&(l.__E=l.__=null),l.__e=!1}else null==i&&t.__v===n.__v?(t.__k=n.__k,t.__e=n.__e):t.__e=xr(n.__e,t,n,r,o,i,s,c);(u=Zn.diffed)&&u(t)}catch(e){t.__v=null,(c||null!=i)&&(t.__e=a,t.__h=!!c,i[i.indexOf(a)]=null),Zn.__e(e,t,n)}}function kr(e,t){Zn.__c&&Zn.__c(t,e),e.some((function(t){try{e=t.__h,t.__h=[],e.some((function(e){e.call(t)}))}catch(e){Zn.__e(e,t.__v)}}))}function xr(e,t,n,r,o,i,s,a){var c,u,l,d,h=n.props,f=t.props,p=t.type,y=0;if("svg"===p&&(o=!0),null!=i)for(;y<i.length;y++)if((c=i[y])&&(c===e||(p?c.localName==p:3==c.nodeType))){e=c,i[y]=null;break}if(null==e){if(null===p)return document.createTextNode(f);e=o?document.createElementNS("http://www.w3.org/2000/svg",p):document.createElement(p,f.is&&f),i=null,a=!1}if(null===p)h===f||a&&e.data===f||(e.data=f);else{if(i=i&&rr.slice.call(e.childNodes),u=(h=n.props||nr).dangerouslySetInnerHTML,l=f.dangerouslySetInnerHTML,!a){if(null!=i)for(h={},d=0;d<e.attributes.length;d++)h[e.attributes[d].name]=e.attributes[d].value;(l||u)&&(l&&(u&&l.__html==u.__html||l.__html===e.innerHTML)||(e.innerHTML=l&&l.__html||""))}if(function(e,t,n,r,o){var i;for(i in n)"children"===i||"key"===i||i in t||gr(e,i,null,n[i],r);for(i in t)o&&"function"!=typeof t[i]||"children"===i||"key"===i||"value"===i||"checked"===i||n[i]===t[i]||gr(e,i,t[i],n[i],r)}(e,f,h,o,a),l)t.__k=[];else if(y=t.props.children,yr(e,Array.isArray(y)?y:[y],t,n,r,o&&"foreignObject"!==p,i,s,e.firstChild,a),null!=i)for(y=i.length;y--;)null!=i[y]&&sr(i[y]);a||("value"in f&&void 0!==(y=f.value)&&(y!==e.value||"progress"===p&&!y)&&gr(e,"value",y,h.value,!1),"checked"in f&&void 0!==(y=f.checked)&&y!==e.checked&&gr(e,"checked",y,h.checked,!1))}return e}function Er(e,t,n){try{"function"==typeof e?e(t):e.current=t}catch(e){Zn.__e(e,n)}}function Ir(e,t,n){var r,o,i;if(Zn.unmount&&Zn.unmount(e),(r=e.ref)&&(r.current&&r.current!==e.__e||Er(r,null,t)),n||"function"==typeof e.type||(n=null!=(o=e.__e)),e.__e=e.__d=void 0,null!=(r=e.__c)){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(e){Zn.__e(e,t)}r.base=r.__P=null}if(r=e.__k)for(i=0;i<r.length;i++)r[i]&&Ir(r[i],t,n);null!=o&&sr(o)}function Tr(e,t,n){return this.constructor(e,n)}Zn={__e:function(e,t){for(var n,r,o;t=t.__;)if((n=t.__c)&&!n.__)try{if((r=n.constructor)&&null!=r.getDerivedStateFromError&&(n.setState(r.getDerivedStateFromError(e)),o=n.__d),null!=n.componentDidCatch&&(n.componentDidCatch(e),o=n.__d),o)return n.__E=n}catch(t){e=t}throw e},__v:0},lr.prototype.setState=function(e,t){var n;n=null!=this.__s&&this.__s!==this.state?this.__s:this.__s=ir({},this.state),"function"==typeof e&&(e=e(ir({},n),this.props)),e&&ir(n,e),null!=e&&this.__v&&(t&&this.__h.push(t),fr(this))},lr.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),fr(this))},lr.prototype.render=ur,Qn=[],er="function"==typeof Promise?Promise.prototype.then.bind(Promise.resolve()):setTimeout,pr.__r=0;const Cr={Error:{color:"red"},Alert:{error:{color:"red"},warning:{color:"yellow"},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"},Input:{height:"35px",width:"17em",borderColor:"#ccf4",outline:"none",fontSize:"17pt",padding:"8px"}};function Ar({children:e}){return ar("div",null,ar("div",{style:Cr.Darken}),ar("div",{style:Cr.DialogOuter},ar("div",{style:Cr.DialogInner},e)))}var Pr,Or,Ur,$r=0,Dr=[],Nr=Zn.__b,Rr=Zn.__r,jr=Zn.diffed,Lr=Zn.__c,Br=Zn.unmount;function Wr(e,t){Zn.__h&&Zn.__h(Or,e,$r||t),$r=0;var n=Or.__H||(Or.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function Fr(e){return $r=1,function(e,t,n){var r=Wr(Pr++,2);return r.t=e,r.__c||(r.__=[n?n(t):Gr(void 0,t),function(e){var t=r.t(r.__[0],e);r.__[0]!==t&&(r.__=[t,r.__[1]],r.__c.setState({}))}],r.__c=Or),r.__}(Gr,e)}function Mr(e){return $r=5,function(e,t){var n=Wr(Pr++,7);return zr(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}((function(){return{current:e}}),[])}function Hr(){Dr.forEach((function(e){if(e.__P)try{e.__H.__h.forEach(Kr),e.__H.__h.forEach(qr),e.__H.__h=[]}catch(t){e.__H.__h=[],Zn.__e(t,e.__v)}})),Dr=[]}Zn.__b=function(e){Or=null,Nr&&Nr(e)},Zn.__r=function(e){Rr&&Rr(e),Pr=0;var t=(Or=e.__c).__H;t&&(t.__h.forEach(Kr),t.__h.forEach(qr),t.__h=[])},Zn.diffed=function(e){jr&&jr(e);var t=e.__c;t&&t.__H&&t.__H.__h.length&&(1!==Dr.push(t)&&Ur===Zn.requestAnimationFrame||((Ur=Zn.requestAnimationFrame)||function(e){var t,n=function(){clearTimeout(r),Vr&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,100);Vr&&(t=requestAnimationFrame(n))})(Hr)),Or=void 0},Zn.__c=function(e,t){t.some((function(e){try{e.__h.forEach(Kr),e.__h=e.__h.filter((function(e){return!e.__||qr(e)}))}catch(n){t.some((function(e){e.__h&&(e.__h=[])})),t=[],Zn.__e(n,e.__v)}})),Lr&&Lr(e,t)},Zn.unmount=function(e){Br&&Br(e);var t=e.__c;if(t&&t.__H)try{t.__H.__.forEach(Kr)}catch(e){Zn.__e(e,t.__v)}};var Vr="function"==typeof requestAnimationFrame;function Kr(e){var t=Or;"function"==typeof e.__c&&e.__c(),Or=t}function qr(e){var t=Or;e.__c=e.__(),Or=t}function zr(e,t){return!e||e.length!==t.length||t.some((function(t,n){return t!==e[n]}))}function Gr(e,t){return"function"==typeof t?t(e):t}function Jr({title:e,alerts:t,fields:n,onCancel:r,onSubmit:o}){const[i,s]=Fr({}),a=Mr();return function(e,t){var n=Wr(Pr++,4);!Zn.__s&&zr(n.__H,t)&&(n.__=e,n.__H=t,Or.__h.push(n))}((()=>{var e;return null===(e=a.current)||void 0===e?void 0:e.focus()}),[]),ar(Ar,null,ar(ur,null,ar("h3",{style:Cr.WindowHeader},e),t.map((e=>ar("p",{style:Cr.Alert[e.type]},function({message:e,messageCode:t,messageParams:n}){return e.replace(/\{\w+\}/gi,(e=>n[e.substr(1,e.length-2)]))}(e)))),ar("form",{onSubmit:e=>{e.preventDefault(),o(i)}},Object.entries(n).map((([e,{type:t,label:n,placeholder:r}],o)=>ar("label",{style:Cr.Label},n?`${n}: `:"",ar("input",{ref:0===o?a:void 0,type:t,name:e,autoComplete:"on",style:Cr.Input,autoFocus:!0,placeholder:r,value:i[e]||"",onInput:n=>{var r;return s({...i,[e]:Yr(t,null===(r=n.target)||void 0===r?void 0:r.value)})}})))))),ar("div",{style:Cr.ButtonsDiv},ar("button",{type:"submit",style:Cr.Button,onClick:()=>o(i)},"Submit"),ar("button",{style:Cr.Button,onClick:r},"Cancel")))}function Yr(e,t){switch(e){case"email":return t.toLowerCase();case"otp":return t.toUpperCase();default:return t}}class Xr extends lr{constructor(e){super(e),this.observer=e=>this.setState({userInteraction:e}),this.state={userInteraction:void 0}}componentDidMount(){this.subscription=i(this.props.db.cloud.userInteraction).subscribe(this.observer)}componentWillUnmount(){this.subscription&&(this.subscription.unsubscribe(),delete this.subscription)}render(e,{userInteraction:t}){return t?ar(Jr,Object.assign({},t)):null}}function Zr(e){const t=document.createElement("div");document.body.appendChild(t),function(e,t,n){var r,o,i;Zn.__&&Zn.__(e,t),o=(r="function"==typeof n)?null:n&&n.__k||t.__k,i=[],Sr(t,e=(!r&&n||t).__k=ar(ur,null,[e]),o||nr,nr,void 0!==t.ownerSVGElement,!r&&n?[n]:o?null:t.firstChild?rr.slice.call(t.childNodes):null,i,!r&&n?n:o?o.__e:t.firstChild,r),kr(i,e)}(ar(Xr,{db:e.vip}),t);let n=!1;return{unsubscribe(){t.remove(),n=!0},get closed(){return n}}}function Qr(n){const o=n.name,c=new r(pt),u=[];let h=null;n.on("ready",(async n=>{try{await async function(n){var r,o,y,b,v,m;f=!1;const g=hn(n);vn||((null===(r=g.cloud.options)||void 0===r?void 0:r.customLoginGui)||u.push(Zr(n)),u.push(function(e){let t=e.cloud.webSocketStatus.value;const n=e.cloud.webSocketStatus.pipe(Me((e=>{const n=t;t=e;const r=a(e);switch(e){case"disconnected":return Dn.value?r.pipe(ye(500)):r;case"connecting":return"not-started"===n||"error"===n?r:r.pipe(ye(4e3));default:return r}})));return d([n,e.syncStateChangedEvent.pipe(Fe({phase:"initial"})),Nn]).pipe(se((([t,n,r])=>{let{phase:o,error:i,progress:s}=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"),r||(a="disconnected"),{phase:o,error:i,progress:s,status:en?a:"offline"}})))}(g).subscribe(n.cloud.syncState)));g.tables.every((e=>e.core))||mn();const _="serviceWorker"in navigator?await navigator.serviceWorker.getRegistrations():[],w=await g.transaction("rw",g.$syncState,(async()=>{var e,t;const{options:n,schema:r}=g.cloud,[o,i,s]=await Promise.all([g.getOptions(),g.getSchema(),g.getPersistedSyncState()]);if(n?o&&JSON.stringify(o)===JSON.stringify(n)||await g.$syncState.put(n,"options"):g.cloud.options=o||null,(null===(e=g.cloud.options)||void 0===e?void 0:e.tryUseServiceWorker)&&"serviceWorker"in navigator&&_.length>0&&!bn?(console.debug("Dexie Cloud Addon: Using service worker"),g.cloud.usingServiceWorker=!0):((null===(t=g.cloud.options)||void 0===t?void 0:t.tryUseServiceWorker)&&!vn&&console.debug("dexie-cloud-addon: Not using service worker.",0===_.length?"No SW registrations found.":"serviceWorker"in navigator&&bn?"Avoiding SW background sync and SW periodic bg sync for this browser due to browser bugs.":"navigator.serviceWorker not present"),g.cloud.usingServiceWorker=!1),Xn(r,g.cloud.options),Xn(i,g.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]={...n}}await g.$syncState.put(e,"schema"),Object.assign(r,e)}}else g.cloud.schema=i||null;return null==s?void 0:s.initiallySynced}));w&&g.setInitiallySynced(!0);(function(t){var n,r;for(const o of t.tables)if(null===(r=null===(n=t.cloud.schema)||void 0===n?void 0:n[o.name])||void 0===r?void 0:r.markedForSync){if(o.schema.primKey.auto)throw new e.SchemaError(`Table ${o.name} is both autoIncremented and synced. Use db.cloud.configure({unsyncedTables: [${JSON.stringify(o.name)}]}) to blacklist it from sync`);if(!o.schema.primKey.keyPath)throw new e.SchemaError(`Table ${o.name} cannot be both synced and outbound. Use db.cloud.configure({unsyncedTables: [${JSON.stringify(o.name)}]}) to blacklist it from sync`)}})(g),(null===(o=g.cloud.options)||void 0===o?void 0:o.databaseUrl)&&!w&&(await async function(e,t,n){console.debug("Performing initial sync"),await $n(e,"initialSync","$jobs",(async()=>{const r=await e.getPersistedSyncState();(null==r?void 0:r.initiallySynced)||await rn(e,t,n,{isInitialSync:!0})}),{awaitRemoteJob:!0}),console.debug("Done initial sync")}(g,g.cloud.options,g.cloud.schema),g.setInitiallySynced(!0));p(),vn||(u.push(t((()=>g.getCurrentUser())).subscribe(c)),u.push(t((()=>g.getPersistedSyncState())).subscribe(g.cloud.persistedSyncState)),await d([c.pipe(Le(1),Ne(1)),g.cloud.persistedSyncState.pipe(Le(1),Ne(1))]).toPromise());(null===(y=g.cloud.options)||void 0===y?void 0:y.requireAuth)&&await ft(g);h&&h.stop();h=null,p(),g.cloud.usingServiceWorker&&(null===(b=g.cloud.options)||void 0===b?void 0:b.databaseUrl)?(et(g,"push").catch((()=>{})),async function(e){var t;try{const{periodicSync:n}=await navigator.serviceWorker.ready;if(n)try{await n.register(`dexie-cloud:${e.name}`,null===(t=e.cloud.options)||void 0===t?void 0:t.periodicSync),console.debug(`Dexie Cloud: Successfully registered periodicsync event for ${e.name}`)}catch(e){console.debug("Dexie Cloud: Failed to register periodic sync. Your PWA must be installed to allow background sync.",e)}else console.debug("Dexie Cloud: periodicSync not supported.")}catch(t){console.debug(`Dexie Cloud: Could not register periodicSync for ${e.name}`,t)}}(g).catch((()=>{}))):(null===(v=g.cloud.options)||void 0===v?void 0:v.databaseUrl)&&g.cloud.schema&&!vn&&(h=Yn(g,g.cloud.options,g.cloud.schema),h.start(),tt(g,"push"));p(),vn||u.push(s(self,"online").subscribe((()=>{console.debug("online!"),g.syncStateChangedEvent.next({phase:"not-in-sync"}),tt(g,"push")})),s(self,"offline").subscribe((()=>{console.debug("offline!"),g.syncStateChangedEvent.next({phase:"offline"})})));"undefined"!=typeof window&&!vn&&(null===(m=g.cloud.options)||void 0===m?void 0:m.databaseUrl)&&u.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 n=e.messageConsumer.readyToServe.pipe(Ue((e=>e)),Me((()=>e.getPersistedSyncState())),Ue((e=>e&&e.serverRevision)),se((e=>({type:"ready",rev:e.serverRevision}))));return function t(){return e.cloud.persistedSyncState.pipe(Ue((e=>null==e?void 0:e.serverRevision)),Ne(1),Me((t=>e.cloud.currentUser.pipe(se((e=>[e,t]))))),Me((([e,t])=>Nn.pipe(se((n=>[n?e:null,t]))))),Me((async([e,t])=>[e,await gt(t)])),Me((([t,r])=>t?new Hn(e.cloud.options.databaseUrl,e.cloud.persistedSyncState.value.serverRevision,r,e.cloud.persistedSyncState.value.clientIdentity,n,e.cloud.webSocketStatus,t.accessToken,t.accessTokenExpiration):i([]))),Z((n=>"TokenExpiredError"===(null==n?void 0:n.name)?(console.debug("WebSocket observable: Token expired. Refreshing token..."),a(!0).pipe(Me((async()=>{const t=await e.getCurrentUser(),n=await ut(e.cloud.options.databaseUrl,t);await e.table("$logins").update(t.userId,{accessToken:n.accessToken,accessTokenExpiration:n.accessTokenExpiration})})),Me((()=>t())))):l(n))),Z((e=>i(qn(e)).pipe(Me((()=>t()))))))}().subscribe((t=>{t&&(console.debug("WS got message",t),e.messageConsumer.enqueue(t))}),(e=>{console.error("Oops! The main observable errored!",e)}),(()=>{console.error("Oops! The main observable completed!")}))}(g))}(n)}catch(e){console.error(e)}}),!0);let f=!1;function p(){if(f)throw new e.DatabaseClosedError}var y;!function(e,t){e.on.close.subscribe(t);const n=e.close;e.close=function(){n.call(this),t()}}(n,(()=>{u.forEach((e=>e.unsubscribe())),f=!0,h&&h.stop(),h=null,c.next(pt)})),n.cloud={version:"1.0.0-beta.10",options:null,schema:null,serverState:null,get currentUserId(){return c.value.userId||pt.userId},currentUser:c,syncState:new r({phase:"initial",status:"not-started"}),persistedSyncState:new r(void 0),userInteraction:new r(void 0),webSocketStatus:new r("not-started"),async login(e){const t=hn(n);await t.cloud.sync(),await ft(t,e)},configure(e){n.cloud.options=e,e.databaseUrl&&(n.name=`${o}-${function(e){const t=new URL(e);return"/"===t.pathname?t.hostname.split(".")[0]:t.pathname.split("/")[1]}(e.databaseUrl)}`,hn(n).reconfigure()),Xn(n.cloud.schema,n.cloud.options)},async sync({wait:e,purpose:r}={wait:!0,purpose:"push"}){void 0===e&&(e=!0);const o=hn(n);if("pull"===r){const t=o.cloud.persistedSyncState.value;if(tt(o,r),e){const e=await o.cloud.persistedSyncState.pipe(Ue((e=>null!=(null==e?void 0:e.timestamp)&&(!t||e.timestamp>t.timestamp))),Ne(1)).toPromise();if(null==e?void 0:e.error)throw new Error("Sync error: "+e.error)}}else if(await zn(o)){const n=o.cloud.persistedSyncState.value;tt(o,r),e&&(console.debug("db.cloud.login() is waiting for sync completion..."),await i(t((async()=>{const e=await zn(o),t=await o.getPersistedSyncState();if((null==t?void 0:t.timestamp)!==(null==n?void 0:n.timestamp)&&(null==t?void 0:t.error))throw new Error("Sync error: "+t.error);return e}))).pipe(Ue((e=>!e)),Ne(1)).toPromise(),console.debug("Done waiting for sync completion because we have nothing to push anymore"))}}},n.Version.prototype._parseStoresSpec=e.override(n.Version.prototype._parseStoresSpec,(e=>On(e,n))),n.use(Pn({currentUserObservable:n.cloud.currentUser,db:hn(n)})),n.use((y=hn(n),{stack:"dbcore",name:"implicitPropSetterMiddleware",level:1,create:e=>({...e,table:t=>{const n=e.table(t);return{...n,mutate:e=>{var r,o,i;const s=e.trans;if((null===(o=null===(r=y.cloud.schema)||void 0===r?void 0:r[t])||void 0===o?void 0:o.markedForSync)&&(null===(i=s.currentUser)||void 0===i?void 0:i.isLoggedIn)&&("add"===e.type||"put"===e.type))for(const t of e.values)"owner"in t||(t.owner=s.currentUser.userId),"realmId"in t||(t.realmId=s.currentUser.userId);return n.mutate(e)}}}})})),n.use(xn(hn(n)))}Qr.version="1.0.0-beta.10",e.Cloud=Qr;export default Qr;export{Qr as dexieCloud};