dexie-cloud-addon 1.0.0-beta.9 → 4.0.0-beta.12

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