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