dexie-cloud-addon 1.0.0-beta.7 → 4.0.0-beta.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/modern/dexie-cloud-addon.js +2159 -2052
- package/dist/modern/dexie-cloud-addon.js.map +1 -1
- package/dist/modern/dexie-cloud-addon.min.js +1 -1
- package/dist/modern/dexie-cloud-addon.min.js.map +1 -1
- package/dist/modern/service-worker.js +3063 -2963
- package/dist/modern/service-worker.js.map +1 -1
- package/dist/modern/service-worker.min.js +1 -1
- package/dist/modern/service-worker.min.js.map +1 -1
- package/dist/module-es5/dexie-cloud-addon.js +2999 -2687
- package/dist/module-es5/dexie-cloud-addon.js.map +1 -1
- package/dist/module-es5/dexie-cloud-addon.min.js +1 -1
- package/dist/module-es5/dexie-cloud-addon.min.js.map +1 -1
- package/dist/types/DexieCloudAPI.d.ts +49 -0
- package/dist/types/DexieCloudOptions.d.ts +1 -0
- package/dist/types/DexieCloudSyncOptions.d.ts +4 -0
- package/dist/types/DexieCloudTable.d.ts +2 -0
- package/dist/types/Invite.d.ts +6 -0
- package/dist/types/PermissionChecker.d.ts +15 -0
- package/dist/types/WSObservable.d.ts +16 -7
- package/dist/types/associate.d.ts +1 -0
- package/dist/types/authentication/setCurrentUser.d.ts +2 -2
- package/dist/types/createSharedValueObservable.d.ts +3 -0
- package/dist/types/currentUserEmitter.d.ts +3 -0
- package/dist/types/db/DexieCloudDB.d.ts +2 -2
- package/dist/types/db/entities/EntityCommon.d.ts +1 -0
- package/dist/types/dexie-cloud-client.d.ts +3 -1
- package/dist/types/extend-dexie-interface.d.ts +11 -49
- package/dist/types/getInternalAccessControlObservable.d.ts +12 -0
- package/dist/types/getInvitesObservable.d.ts +25 -0
- package/dist/types/getPermissionsLookupObservable.d.ts +16 -0
- package/dist/types/getTiedRealmId.d.ts +2 -0
- package/dist/types/helpers/flatten.d.ts +1 -0
- package/dist/types/mapValueObservable.d.ts +5 -0
- package/dist/types/mergePermissions.d.ts +2 -0
- package/dist/types/middleware-helpers/idGenerationHelpers.d.ts +18 -0
- package/dist/types/middlewares/createIdGenerationMiddleware.d.ts +1 -6
- package/dist/types/permissions.d.ts +9 -0
- package/dist/types/sync/applyServerChanges.d.ts +3 -0
- package/dist/types/sync/encodeIdsForServer.d.ts +4 -0
- package/dist/types/sync/getTablesToSyncify.d.ts +1 -1
- package/dist/types/sync/listClientChanges.d.ts +3 -3
- package/dist/types/sync/listSyncifiedChanges.d.ts +4 -4
- package/dist/types/sync/sync.d.ts +2 -2
- package/dist/types/sync/syncWithServer.d.ts +2 -1
- package/dist/types/types/NewIdOptions.d.ts +3 -0
- package/dist/umd/dexie-cloud-addon.js +2989 -2675
- package/dist/umd/dexie-cloud-addon.js.map +1 -1
- package/dist/umd/dexie-cloud-addon.min.js +1 -1
- package/dist/umd/dexie-cloud-addon.min.js.map +1 -1
- package/dist/umd/service-worker.js +3051 -2951
- package/dist/umd/service-worker.js.map +1 -1
- package/dist/umd/service-worker.min.js +1 -1
- package/dist/umd/service-worker.min.js.map +1 -1
- package/dist/umd-modern/dexie-cloud-addon.js +2145 -2036
- package/dist/umd-modern/dexie-cloud-addon.js.map +1 -1
- package/package.json +6 -7
|
@@ -1 +1 @@
|
|
|
1
|
-
import e,{liveQuery as t}from"dexie";import{Observable as n,BehaviorSubject as r,from as o,fromEvent as i,of as s,merge as a,Subscription as c,throwError as u,combineLatest as l}from"rxjs";const d={userId:"unauthorized",name:"Unauthorized",claims:{sub:"unauthorized"},lastLogin:new Date(0)};try{Object.freeze(d),Object.freeze(d.claims)}catch(e){}const h={},f=self.document&&navigator.serviceWorker;f&&f.ready.then((e=>h.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 p{constructor(e){this.name=e}subscribe(e){if(!f)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 f.addEventListener("message",t),()=>f.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}))):h.registration&&(null===(t=h.registration.active)||void 0===t||t.postMessage({type:`sw-broadcast-${this.name}`,message:e}))}}class y extends n{constructor(e){const t="undefined"==typeof BroadcastChannel?new p(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 p?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 p?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 b=function(e,t){return(b=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 v(e,t){function n(){this.constructor=e}b(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}function m(e){return"function"==typeof e}var g=!1,_={Promise:void 0,set useDeprecatedSynchronousErrorHandling(e){e&&(new Error).stack;g=e},get useDeprecatedSynchronousErrorHandling(){return g}};function w(e){setTimeout((function(){throw e}),0)}var S={closed:!0,next:function(e){},error:function(e){if(_.useDeprecatedSynchronousErrorHandling)throw e;w(e)},complete:function(){}},k=function(){return Array.isArray||function(e){return e&&"number"==typeof e.length}}();function x(e){return null!==e&&"object"==typeof e}var E=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}(),I=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(m(i)){o&&(this._unsubscribe=void 0);try{i.call(this)}catch(e){t=e instanceof E?T(e.errors):[e]}}if(k(s)){a=-1;for(var c=s.length;++a<c;){var u=s[a];if(x(u))try{u.unsubscribe()}catch(e){t=t||[],e instanceof E?t=t.concat(T(e.errors)):t.push(e)}}}if(t)throw new E(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 T(e){return e.reduce((function(e,t){return e.concat(t instanceof E?t.errors:t)}),[])}var C=function(){return"function"==typeof Symbol?Symbol("rxSubscriber"):"@@rxSubscriber_"+Math.random()}(),A=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=S;break;case 1:if(!n){i.destination=S;break}if("object"==typeof n){n instanceof t?(i.syncErrorThrowable=n.syncErrorThrowable,i.destination=n,n.add(i)):(i.syncErrorThrowable=!0,i.destination=new P(i,n));break}default:i.syncErrorThrowable=!0,i.destination=new P(i,n,r,o)}return i}return v(t,e),t.prototype[C]=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}(I),P=function(e){function t(t,n,r,o){var i,s=e.call(this)||this;s._parentSubscriber=t;var a=s;return m(n)?i=n:n&&(i=n.next,r=n.error,o=n.complete,n!==S&&(m((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 v(t,e),t.prototype.next=function(e){if(!this.isStopped&&this._next){var t=this._parentSubscriber;_.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=_.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):w(e),this.unsubscribe();else{if(this.unsubscribe(),n)throw e;w(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)};_.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(),_.useDeprecatedSynchronousErrorHandling)throw e;w(e)}},t.prototype.__tryOrSetError=function(e,t,n){if(!_.useDeprecatedSynchronousErrorHandling)throw new Error("bad call");try{t.call(this._context,n)}catch(t){return _.useDeprecatedSynchronousErrorHandling?(e.syncErrorValue=t,e.syncErrorThrown=!0,!0):(w(t),!0)}return!1},t.prototype._unsubscribe=function(){var e=this._parentSubscriber;this._context=null,this._parentSubscriber=null,e.unsubscribe()},t}(A);var O=function(){return"function"==typeof Symbol&&Symbol.observable||"@@observable"}();function U(e){return e}function D(e){return 0===e.length?U:1===e.length?e[0]:function(t){return e.reduce((function(e,t){return t(e)}),t)}}var $=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 A)return e;if(e[C])return e[C]()}return e||t||n?new A(e,t,n):new A(S)}(e,t,n);if(r?o.add(r.call(o,this.source)):o.add(this.source||_.useDeprecatedSynchronousErrorHandling&&!o.syncErrorThrowable?this._subscribe(o):this._trySubscribe(o)),_.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){_.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 A?r:null}return!0}(e)?console.warn(t):e.error(t)}},e.prototype.forEach=function(e,t){var n=this;return new(t=N(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[O]=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:D(e)(this)},e.prototype.toPromise=function(e){var t=this;return new(e=N(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 N(e){if(e||(e=Promise),!e)throw new Error("no Promise impl found");return e}var R=function(e){return function(t){for(var n=0,r=e.length;n<r&&!t.closed;n++)t.next(e[n]);t.complete()}};function j(){return"function"==typeof Symbol&&Symbol.iterator?Symbol.iterator:"@@iterator"}var L=j(),W=function(e){return e&&"number"==typeof e.length&&"function"!=typeof e};function B(e){return!!e&&"function"!=typeof e.subscribe&&"function"==typeof e.then}var F=function(e){if(e&&"function"==typeof e[O])return r=e,function(e){var t=r[O]();if("function"!=typeof t.subscribe)throw new TypeError("Provided object does not correctly implement Symbol.observable");return t.subscribe(e)};if(W(e))return R(e);if(B(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,w),e};if(e&&"function"==typeof e[L])return t=e,function(e){for(var n=t[L]();;){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=x(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.")},M=function(e){function t(t){var n=e.call(this)||this;return n.parent=t,n}return v(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}(A),H=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return v(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}(A);function V(e,t){if(!t.closed){if(e instanceof $)return e.subscribe(t);var n;try{n=F(e)(t)}catch(e){t.error(e)}return n}}var K=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 v(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 v(t,e),t.prototype.schedule=function(e,t){return this},t}(I)),q=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}(),z=new(function(e){function t(n,r){void 0===r&&(r=q.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 v(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}(q))(K);function G(e){return e&&"function"==typeof e.schedule}function J(e){return function(t){var n=new Y(e),r=t.lift(n);return n.caught=r}}var Y=function(){function e(e){this.selector=e}return e.prototype.call=function(e,t){return t.subscribe(new X(e,this.selector,this.caught))},e}(),X=function(e){function t(t,n,r){var o=e.call(this,t)||this;return o.selector=n,o.caught=r,o}return v(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 M(this);this.add(r);var o=V(n,r);o!==r&&this.add(o)}},t}(H);function Z(e,t){return new $((function(n){var r=new I,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?Z(e,t):new $(R(e))}function ee(e,t){if(null!=e){if(function(e){return e&&"function"==typeof e[O]}(e))return function(e,t){return new $((function(n){var r=new I;return r.add(t.schedule((function(){var o=e[O]();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(B(e))return function(e,t){return new $((function(n){var r=new I;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(W(e))return Z(e,t);if(function(e){return e&&"function"==typeof e[L]}(e)||"string"==typeof e)return function(e,t){if(!e)throw new Error("Iterable cannot be null");return new $((function(n){var r,o=new I;return o.add((function(){r&&"function"==typeof r.return&&r.return()})),o.add(t.schedule((function(){r=e[L](),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 te(e,t){return t?ee(e,t):e instanceof $?e:new $(F(e))}function ne(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=e[e.length-1];return G(n)?(e.pop(),Z(e,n)):Q(e)}function re(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 oe(e,t))}}var oe=function(){function e(e,t){this.project=e,this.thisArg=t}return e.prototype.call=function(e,t){return t.subscribe(new ie(e,this.project,this.thisArg))},e}(),ie=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 v(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}(A);function se(e,t,n){return void 0===n&&(n=Number.POSITIVE_INFINITY),"function"==typeof t?function(r){return r.pipe(se((function(n,r){return te(e(n,r)).pipe(re((function(e,o){return t(n,e,r,o)})))}),n))}:("number"==typeof t&&(n=t),function(t){return t.lift(new ae(e,n))})}var ae=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 ce(e,this.project,this.concurrent))},e}(),ce=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 v(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 M(this),n=this.destination;n.add(t);var r=V(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}(H);function ue(e){return void 0===e&&(e=Number.POSITIVE_INFINITY),se(U,e)}function le(){return ue(1)}function de(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return le()(ne.apply(void 0,e))}function he(e,t){return void 0===t&&(t=z),function(n){return n.lift(new fe(e,t))}}var fe=function(){function e(e,t){this.dueTime=e,this.scheduler=t}return e.prototype.call=function(e,t){return t.subscribe(new pe(e,this.dueTime,this.scheduler))},e}(),pe=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 v(t,e),t.prototype._next=function(e){this.clearDebounce(),this.lastValue=e,this.hasValue=!0,this.add(this.debouncedSubscription=this.scheduler.schedule(ye,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}(A);function ye(e){e.debouncedNext()}function be(e){return e instanceof Date&&!isNaN(+e)}var ve=new $((function(e){return e.complete()}));function me(e){return e?function(e){return new $((function(t){return e.schedule((function(){return t.complete()}))}))}(e):ve}function ge(e,t){return new $(t?function(n){return t.schedule(_e,0,{error:e,subscriber:n})}:function(t){return t.error(e)})}function _e(e){var t=e.error;e.subscriber.error(t)}var we=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 ne(this.value);case"E":return ge(this.error);case"C":return me()}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 Se(e,t){void 0===t&&(t=z);var n=be(e)?+e-t.now():Math.abs(e);return function(e){return e.lift(new ke(n,t))}}var ke=function(){function e(e,t){this.delay=e,this.scheduler=t}return e.prototype.call=function(e,t){return t.subscribe(new xe(e,this.delay,this.scheduler))},e}(),xe=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 v(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 Ee(t.now()+this.delay,e);this.queue.push(n),!1===this.active&&this._schedule(t)}},t.prototype._next=function(e){this.scheduleNotification(we.createNext(e))},t.prototype._error=function(e){this.errored=!0,this.queue=[],this.destination.error(e),this.unsubscribe()},t.prototype._complete=function(){this.scheduleNotification(we.createComplete()),this.unsubscribe()},t}(A),Ee=function(){return function(e,t){this.time=e,this.notification=t}}();var Ie=function(){function e(e,t){this.compare=e,this.keySelector=t}return e.prototype.call=function(e,t){return t.subscribe(new Te(e,this.compare,this.keySelector))},e}(),Te=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 v(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}(A),Ce=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 Ae(e,t){return function(n){return n.lift(new Pe(e,t))}}var Pe=function(){function e(e,t){this.predicate=e,this.thisArg=t}return e.prototype.call=function(e,t){return t.subscribe(new Oe(e,this.predicate,this.thisArg))},e}(),Oe=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 v(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}(A);function Ue(e){return function(t){return 0===e?me():t.lift(new De(e))}}var De=function(){function e(e){if(this.total=e,this.total<0)throw new Ce}return e.prototype.call=function(e,t){return t.subscribe(new $e(e,this.total))},e}(),$e=function(e){function t(t,n){var r=e.call(this,t)||this;return r.total=n,r.count=0,r}return v(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}(A);function Ne(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=e[e.length-1];return G(n)?(e.pop(),function(t){return de(e,t,n)}):function(t){return de(e,t)}}function Re(e,t){return"function"==typeof t?function(n){return n.pipe(Re((function(n,r){return te(e(n,r)).pipe(re((function(e,o){return t(n,e,r,o)})))})))}:function(t){return t.lift(new je(e))}}var je=function(){function e(e){this.project=e}return e.prototype.call=function(e,t){return t.subscribe(new Le(e,this.project))},e}(),Le=function(e){function t(t,n){var r=e.call(this,t)||this;return r.project=n,r.index=0,r}return v(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 M(this),r=this.destination;r.add(n),this.innerSubscription=V(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}(H);function We(){}function Be(e,t,n){return function(r){return r.lift(new Fe(e,t,n))}}var Fe=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 Me(e,this.nextOrObserver,this.error,this.complete))},e}(),Me=function(e){function t(t,n,r,o){var i=e.call(this,t)||this;return i._tapNext=We,i._tapError=We,i._tapComplete=We,i._tapError=r||We,i._tapComplete=o||We,m(n)?(i._context=i,i._tapNext=n):n&&(i._context=n,i._tapNext=n.next||We,i._tapError=n.error||We,i._tapComplete=n.complete||We),i}return v(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}(A),He=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 Ve=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 Ke(e,this.absoluteTimeout,this.waitFor,this.withObservable,this.scheduler))},e}(),Ke=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 v(t,e),t.dispatchTimeout=function(e){var t=e.withObservable;e._unsubscribeAndRecycle(),e.add(V(t,new M(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}(H);function qe(e,t){return void 0===t&&(t=z),function(e,t,n){return void 0===n&&(n=z),function(r){var o=be(e),i=o?+e-n.now():Math.abs(e);return r.lift(new Ve(i,o,t,n))}}(e,ge(new He),t)}const{toString:ze}={};const Ge={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 Je(...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 Ge;let i=n.get(r);if(void 0!==i)return i;const s=(o=e,ze.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:Ge),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 Ye={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 Xe={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 Ze={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))}},et={Set:{replace:e=>({$t:"Set",v:Array.from(e.entries())}),revive:({v:e})=>new Set(e)}},tt={Map:{replace:e=>({$t:"Map",v:Array.from(e.entries())}),revive:({v:e})=>new Map(e)}};const nt="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"==typeof global?global:void 0;var rt=["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=nt[t];return o&&new o(r.ArrayBuffer.revive({v:e},n,r))}}})),{});const ot="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},it="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 st(e){return function(e){for(var t="",n=0,r=e.length;n<r;n++)t+=ut[e[n]];return t}(it(e))}function at(e){return ot(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+=ct[e[n]];return t}(e))}const ct={"-":"=",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:"+","|":"/"},ut={};for(const e of Object.keys(ct))ut[ct[e]]=e;var lt={ArrayBuffer:{replace:e=>({$t:"ArrayBuffer",v:st(e)}),revive:({v:e})=>{const t=at(e);return t.buffer.byteLength===t.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}}};class dt{constructor(e,t){this.buf=e,this.type=t}}function ht(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 ft(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t[n]=e.charCodeAt(n);return t.buffer}const pt={...Xe,...Ze,...Qe,...et,...tt,...rt,...lt,...{Blob:{test:(e,t)=>"Blob"===t||e instanceof dt,replace:e=>({$t:"Blob",v:it(e instanceof dt?e.buf:ft(ht(e))),type:e.type}),revive:({type:e,v:t})=>{const n=ot(t);return void 0!==typeof Blob?new Blob([n]):new dt(n.buffer,e)}}}};function yt(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 bt={undefined:{replace:()=>{},revive:()=>{}}};const vt="bigint"==typeof BigInt(0);function mt(e){return"bigint"==typeof e?e:vt?"string"==typeof e?BigInt(e):BigInt(e.v):Number("string"==typeof e?e:e.v)}function gt(e,t){const n=mt(e),r=mt(t);return n<r?-1:n>r?1:0}class _t{constructor(e){this.v=e}toString(){return this.v}}const wt={...bt,...vt?{}:{bigint:{test:e=>e instanceof _t,replace:e=>({$t:"bigint",...e}),revive:({v:e})=>new _t(e)}}},St=Je(pt,wt),kt=function(...e){const t=Je(pt,Ye,...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 yt(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 yt(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)}}}(wt);let xt=!1;async function Et(e,t){try{const n=await navigator.serviceWorker.ready;return"push"===t&&n.sync&&await n.sync.register(`dexie-cloud:${e.name}`),void(n.active?n.active.postMessage({type:"dexie-cloud-sync",dbName:e.name,purpose:t}):console.error("Dexie Cloud: There's no active service worker. Can this ever happen??"))}catch(e){xt||(console.debug("Dexie Cloud: Could not register sync event",e),xt=!0)}}function It(e,t){e.cloud.usingServiceWorker?Et(e,t):e.localSyncEvent.next({purpose:t})}async function Tt({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 it(o)}function Ct(e){return Object.entries(e.cloud.schema||{}).filter((([,{markedForSync:e}])=>e)).map((([t])=>e.table(t)))}function At(e){return`$${e}_mutations`}function Pt(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 Ot(e,t,{since:n={},limit:r=1/0}={}){return(await Promise.all(e.map((async e=>{const t=Pt(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 Ut=crypto.getRandomValues;function Dt(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)Dt(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]={}),Dt(c,a,n)}}else void 0===n?Array.isArray(e)&&!isNaN(parseInt(t))?e.splice(t,1):delete e[t]:e[t]=n}}const $t="undefined"==typeof self?e=>{const t=Buffer.alloc(e);return Ut(t),t.toString("base64")}:e=>{const t=new Uint8Array(e);return crypto.getRandomValues(t),btoa(String.fromCharCode.apply(null,t))};function Nt(e){return"string"==typeof e||!!(Array.isArray(e)&&e.some((e=>Nt(e)))&&e.every(Rt))}function Rt(e){return"string"==typeof e||"number"==typeof e||Array.isArray(e)&&e.every(Rt)}function jt(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))Dt(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 Lt(e,t){for(const{table:n,muts:r}of t)for(const t of r)jt(e,n,t)}function Wt(t,n){return new Promise(((r,o)=>{const i={...n,onSubmit:e=>{t.next(void 0),r(e)},onCancel:()=>{t.next(void 0),o(new e.AbortError("User cancelled"))}};t.next(i)}))}function Bt(e,t,...n){return Wt(e,{type:"message-alert",title:t,alerts:n,fields:{}})}async function Ft(e,t,n){let r=n||"";for(;!r||!/^[\w-\.]+@([\w-]+\.)+[\w-]{2,10}$/.test(r);)r=(await Wt(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 Mt(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 Wt(e,{type:"otp",title:"Enter OTP",alerts:r,fields:{otp:{type:"otp",label:"OTP",placeholder:"Paste OTP here"}}});return o}async function Ht(e,t,n,r,o){return t.accessToken&&t.accessTokenExpiration.getTime()>Date.now()?t:t.refreshToken&&(!t.refreshTokenExpiration||t.refreshTokenExpiration.getTime()>Date.now())?await Vt(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=it(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 Wt(n,{type:"message-alert",title:"Authentication Alert",fields:{},alerts:o.alerts}),e}catch(e){throw await Bt(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 Vt(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=it(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 Kt extends Error{constructor(e,t){super(t||`${e.status} ${e.statusText}`),this.httpStatus=e.status}get name(){return"HttpError"}}async function qt(e,t,n,r,o,i,s){const a={Accept:"application/json, application/x-bison, application/x-bison-stream","Content-Type":"application/tson"},c=await async function(e){var t,n;const r=await e.getCurrentUser(),{accessToken:o,accessTokenExpiration:i,refreshToken:s,refreshTokenExpiration:a,claims:c}=r;if(!o)return;if((null!==(t=null==i?void 0:i.getTime())&&void 0!==t?t:1/0)>Date.now())return o;if(!s)throw new Error("Refresh token missing");if((null!==(n=null==a?void 0:a.getTime())&&void 0!==n?n:1/0)<=Date.now())throw new Error("Refresh token has expired");const u=await Vt(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:St.stringify(u)});if(r.syncStateChangedEvent.next({phase:"pulling"}),!l.ok)throw new Kt(l);switch(l.headers.get("content-type")){case"application/x-bison":return kt.fromBinary(await l.blob());case"application/x-bison-stream":default:case"application/json":{const e=await l.text();return St.parse(e)}}}async function zt(t,n,r){const o=await t.bulkGet(n),i=[],s=[];n.forEach(((n,a)=>{const c=o[a];if(c){for(const[n,o]of Object.entries(r[a])){if(n===t.schema.primKey.keyPath)throw new Error("Cannot change primary key");e.setByKeyPath(c,n,o)}i.push(n),s.push(c)}})),await(null==t.schema.primKey.keyPath?t.bulkPut(s,i):t.bulkPut(s))}function Gt(t){if(null==t?void 0:t.cancelled)throw new e.AbortError("Operation was cancelled")}let Jt=navigator.onLine;async function Yt(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 Xt(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",(()=>Jt=!0)),self.addEventListener("offline",(()=>Jt=!1));function Zt(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:Jt,syncOptions:r,error:o}),Jt&&(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 Zt(e,t,n,{...r,retryImmediatelyOnFetchError:!1})):(await e.$syncState.update("syncState",{timestamp:new Date,error:""+o}),e.syncStateChangedEvent.next({phase:Jt?"error":"offline",error:o}),Promise.reject(o)))))}async function Qt(e,t,n,{isInitialSync:r,cancelToken:o,justCheckIfNeeded:i,purpose:s}={isInitialSync:!1}){var a;if(i||console.debug("SYNC STARTED",{isInitialSync:r,purpose:s}),!(null===(a=e.cloud.options)||void 0===a?void 0:a.databaseUrl))throw new Error("Internal error: sync must not be called when no databaseUrl is configured");const{databaseUrl:c}=t,u=await e.getCurrentUser(),l=u.isLoggedIn?Ct(e):[],h=l.map((t=>e.table(At(t.name)))),f=await e.getPersistedSyncState(),p=!r&&u.isLoggedIn?function(e,t){const n=(null==t?void 0:t.syncedTables)||[];return Ct(e).filter((e=>!n.includes(e.name)))}(e,f):[];Gt(o);const y=p.length>0;if(y){if(i)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!==d.userId||(e.userId=t.userId)})):"roles"===n.name||("realms"===n.name?await n.toCollection().modify((e=>{(r.has(e.realmId)||e.owner)&&e.owner!==d.userId||(e.owner=t.userId)})):await n.toCollection().modify((e=>{e.realmId&&r.has(e.realmId)||(e.owner&&e.owner!==d.userId||(e.owner=t.userId),e.realmId&&e.realmId!==d.userId||(e.realmId=t.userId))})))}(p,u,null==f?void 0:f.realms)})),Gt(o)}const[b,v,m]=await e.transaction("r",e.tables,(async()=>{const t=await e.getPersistedSyncState(),r=await e.$baseRevs.toArray();let i=await Ot(h);if(Gt(o),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||"")&&Nt(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,u,n,null==f?void 0:f.realms);return Gt(o),i=i.concat(e),[i,t,r]}return[i,t,r]})),g=b.some((e=>e.muts.some((e=>e.keys.length>0))));if(i)return console.debug("Sync is needed:",g),g;if("push"===s&&!g)return!1;const _=Xt(b,null==v?void 0:v.latestRevisions),w=(null==v?void 0:v.clientIdentity)||$t(16);Gt(o);const S=await qt(b,v,m,e,c,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 Ot(h,0,{since:_});for(const t of h){const n=Pt(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()])}Xt(r,_),await Yt(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=Ct(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=l.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=tn(S.changes,r);return await en(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:o}))}async function en(t,n){console.debug("Applying server changes",t,e.currentTransaction);for(const{table:r,muts:o}of t){const t=n.table(r);if(!t)continue;const{primaryKey:i}=t.core.schema;for(const n of o)switch(n.type){case"insert":i.outbound?await t.bulkAdd(n.values,n.keys):(n.keys.forEach(((t,r)=>{e.setByKeyPath(n.values[r],i.keyPath,t)})),await t.bulkAdd(n.values));break;case"upsert":i.outbound?await t.bulkPut(n.values,n.keys):(n.keys.forEach(((t,r)=>{e.setByKeyPath(n.values[r],i.keyPath,t)})),await t.bulkPut(n.values));break;case"modify":1===n.keys.length?await t.update(n.keys[0],n.changeSpec):await t.where(":id").anyOf(n.keys).modify(n.changeSpec);break;case"update":await zt(t,n.keys,n.changeSpecs);break;case"delete":await t.bulkDelete(n.keys)}}}function tn(e,t){const n={};Lt(n,e);const r={};return Lt(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))Dt(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=$t(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 nn(t){const n=[],o=new r(!0),i=new r(null);let s=!1;return i.subscribe((async()=>{if(!s&&n.length>0){s=!0,o.next(!1);try{await async function(){var r,o,i;for(;n.length>0;){const s=n.shift();try{console.debug("processing msg",s),await t.cloud.syncState.pipe(Ae((({phase:e})=>"in-sync"===e||"error"===e)),Ue(1)).toPromise(),console.debug("processing msg",s);const n=t.cloud.persistedSyncState.value;if(!s)continue;switch(s.type){case"token-expired":console.debug("WebSocket observable: Token expired. Refreshing token...");const a=t.cloud.currentUser.value,c=await Vt(t.cloud.options.databaseUrl,a);await t.table("$logins").update(a.userId,{accessToken:c.accessToken,accessTokenExpiration:c.accessTokenExpiration});break;case"rev":(!(null==n?void 0:n.serverRevision)||gt(n.serverRevision,s.rev)<0)&&It(t,"pull");break;case"realm-added":(null===(r=null==n?void 0:n.realms)||void 0===r?void 0:r.includes(s.realm))||It(t,"pull");break;case"realm-removed":(null===(o=null==n?void 0:n.realms)||void 0===o?void 0:o.includes(s.realm))&&It(t,"pull");break;case"changes":if(console.debug("changes"),"error"===(null===(i=t.cloud.syncState.value)||void 0===i?void 0:i.phase)){It(t,"pull");break}await t.transaction("rw",t.dx.tables,(async n=>{n.idbtrans.disableChangeTracking=!0,n.idbtrans.disableAccessControl=!0;const[r,o,i]=await Promise.all([t.getSchema(),t.getPersistedSyncState(),t.getCurrentUser()]);if(console.debug("ws message queue: in transaction"),!o||!r||!i)return void console.debug("required vars not present",{syncState:o,schema:r,currentUser:i});if(0!==gt(s.baseRev,o.serverRevision))return void console.debug(`baseRev (${s.baseRev}) differs from our serverRevision in syncState (${o.serverRevision})`);const a=await e.waitFor(Tt(o));if(console.debug("ourRealmSetHash",a),a!==s.realmSetHash)return console.debug("not same realmSetHash",s.realmSetHash),void It(t,"pull");let c=[];if(i.isLoggedIn){const e=Ct(t).map((e=>t.table(At(e.name))));c=await Ot(e),console.debug("msg queue: client changes",c)}const u=tn(s.changes,c);console.debug("applying filtered server changes",u),await en(u,t),o.latestRevisions=Xt(c,o.latestRevisions),o.serverRevision=s.newRev,console.debug("Updating baseRefs",o.latestRevisions),await Yt(t,r,o.latestRevisions,s.newRev),console.debug("Updating syncState",o),await t.$syncState.put(o,"syncState")})),console.debug("msg queue: done with rw transaction")}}catch(e){console.error("Error in msg queue",e)}}}()}finally{s=!1,o.next(!0)}}})),{enqueue:function(e){n.push(e),i.next(null)},readyToServe:o}}const rn=new WeakMap,on={realms:"@realmId",members:"@id",roles:"[realmId+name]",$jobs:"",$syncState:"",$baseRevs:"[tableName+clientRev]",$logins:"claims.sub, lastLogin"};let sn=0;function an(e){"vip"in e&&(e=e.vip);let t=rn.get(e.cloud);if(!t){const n=new r({purpose:"pull"});let o=new y(`syncstatechanged-${e.name}`);n.id=++sn;let i=!1;t={get name(){return e.name},close:()=>e.close(),transaction:e.transaction.bind(e),table:e.table.bind(e),get tables(){return e.tables},cloud:e.cloud,get $jobs(){return e.table("$jobs")},get $syncState(){return e.table("$syncState")},get $baseRevs(){return e.table("$baseRevs")},get $logins(){return e.table("$logins")},get realms(){return e.realms},get members(){return e.members},get roles(){return e.roles},get initiallySynced(){return i},localSyncEvent:n,get syncStateChangedEvent(){return o},dx:e};const s={getCurrentUser:()=>t.$logins.toArray().then((e=>e.find((e=>e.isLoggedIn))||d)),getPersistedSyncState:()=>t.$syncState.get("syncState"),getSchema:()=>t.$syncState.get("schema"),getOptions:()=>t.$syncState.get("options"),setInitiallySynced(e){i=e},reconfigure(){o=new y(`syncstatechanged-${e.name}`)}};Object.assign(t,s),t.messageConsumer=nn(t),rn.set(e.cloud,t)}return t}const cn=new WeakMap;class un{constructor(e,t){cn.set(this,e),Object.assign(this,t)}static load(e,t){return e.table("$logins").get(t).then((n=>new un(e,n||{userId:t,claims:{sub:t},lastLogin:new Date(0)})))}async save(){cn.get(this).table("$logins").put(this)}}async function ln(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 un(e,{claims:{},lastLogin:new Date(0)});await Ht(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 Ft(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 Ft(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 Bt(t,"Token request failed",{type:"error",messageCode:"GENERIC_ERROR",message:e,messageParams:{}}).catch((()=>{})),new Kt(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 Mt(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 Mt(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 Bt(t,"OTP Authentication Failed",{type:"error",messageCode:"GENERIC_ERROR",message:e,messageParams:{}}).catch((()=>{})),new Kt(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)}const dn="undefined"!=typeof InstallTrigger,hn="undefined"!=typeof navigator&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\/|Edge\//.test(navigator.userAgent),fn=hn?[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]:NaN,pn=hn&&fn<=605||dn;const yn="undefined"!=typeof self&&"clients"in self&&!self.document;function bn(){throw new e.SchemaError("Version increment needed to allow dexie-cloud change tracking")}const{toString:vn}={};function mn(e){return vn.call(e).slice(8,-1)}function gn(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 _n=/b|c|d|f|g|h|j|k|l|m|n|p|q|r|s|t|v|x|y|z/i;let wn=0;function Sn(t){return{stack:"dbcore",name:"idGenerationMiddleware",level:1,create:n=>({...n,table:r=>{const o=n.table(r);function i(n,i){let s=null;const a=gn(o.schema.primaryKey,n);return a.forEach(((c,u)=>{if(void 0===c){const r=n.values[u].realmId||t.cloud.currentUserId,c=r.substr(r.length-3);a[u]=function(e,t){const n=new Uint8Array(18),r=new Uint8Array(n.buffer,0,6),o=Date.now();wn>=o?++wn:wn=o,r[0]=wn/1099511627776,r[1]=wn/4294967296,r[2]=wn/16777216,r[3]=wn/65536,r[4]=wn/256,r[5]=wn;const i=new Uint8Array(n.buffer,6);return crypto.getRandomValues(i),e+st(new Uint8Array(n.buffer))+(t||"")}(i,c),o.schema.primaryKey.outbound||(s||(s=n.values.slice()),s[u]=e.deepClone(s[u]),e.setByKeyPath(s[u],o.schema.primaryKey.keyPath,a[u]))}else if("string"!=typeof c||!c.startsWith(i))throw new e.ConstraintError(`The ID "${c}" is not valid for table "${r}". Primary '@' keys requires the key to be prefixed with "${i}.\n"If you want to generate IDs programmatically, remove '@' from the schema to get rid of this constraint. Dexie Cloud supports custom IDs as long as they are random and globally unique.`)})),o.mutate({...n,keys:a,values:s||n.values})}return{...o,mutate:n=>{var s,a;if(n.trans.disableChangeTracking)return o.mutate(n);if("add"===n.type||"put"===n.type){const c=null===(s=t.cloud.schema)||void 0===s?void 0:s[r];if(null==c?void 0:c.generatedGlobalId){if((null===(a=t.cloud.options)||void 0===a?void 0:a.databaseUrl)&&!t.initiallySynced){const e=gn(o.schema.primaryKey,n);return o.getMany({keys:e,trans:n.trans,cache:"immutable"}).then((t=>{if(t.length<e.length)throw new Error("Unable to create new objects without an initial sync having been performed.");return o.mutate(n)}))}return i(n,c.idPrefix)}if(null==c?void 0:c.markedForSync){gn(o.schema.primaryKey,n).forEach(((t,n)=>{if(!Nt(t)){const n=Array.isArray(t)?t.map(mn).join(","):mn(t);throw new e.ConstraintError(`Invalid primary key type ${n} for table ${r}. Tables marked for sync has primary keys of type string or Array of string (and optional numbers)`)}}))}}return o.mutate(n)}}}})}}function kn(e){const t=new Uint8Array(e);return crypto.getRandomValues(t),btoa(String.fromCharCode.apply(null,t))}let xn=0;function En(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 In(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 Tn=new r(new Set);function Cn({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){bn()}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=>At(e)));i=n.transaction([...r,...e],o)}else i=n.transaction(r,o);if("readwrite"===o){i.txid=kn(16),i.currentUser=e.value,Tn.value.add(i),Tn.next(Tn.value);const n=()=>{i.removeEventListener("complete",r),i.removeEventListener("error",n),i.removeEventListener("abort",n),Tn.value.delete(i),Tn.next(Tn.value)},r=()=>{var e;i.mutationsAdded&&(null===(e=t.cloud.options)||void 0===e?void 0:e.databaseUrl)&&(t.cloud.usingServiceWorker?(console.debug("registering sync event"),Et(t,"push")):t.localSyncEvent.next({purpose:"push"})),n()};i.addEventListener("complete",r),i.addEventListener("error",n),i.addEventListener("abort",n)}return i},table:e=>{const t=n.table(e);if(/^\$/.test(e))return e.endsWith("_mutations")?{...t,mutate:e=>("add"!==e.type&&"put"!==e.type||(e.trans.mutationsAdded=!0),t.mutate(e))}:"$logins"===e?{...t,mutate:e=>(console.debug("Mutating $logins table",e),t.mutate(e).then((t=>(console.debug("Mutating $logins"),e.trans.mutationsAdded=!0,console.debug("$logins mutated"),t))).catch((e=>(console.debug("Failed mutation $logins",e),Promise.reject(e)))))}:t;const{schema:r}=t,i=o.get(e);return function(e){const t="$lock"+ ++xn;return{...e,count:En(e.count,t),get:En(e.get,t),getMany:En(e.getMany,t),openCursor:En(e.openCursor,t),query:En(e.query,t),mutate:In(e.mutate,t)}}({...t,mutate:e=>{var n;const o=e.trans;return o.txid?o.disableChangeTracking?t.mutate(e):(null===(n=o.currentUser)||void 0===n?void 0:n.isLoggedIn)?"deleteRange"===e.type?t.query({query:{range:e.range,index:r.primaryKey},trans:e.trans,values:!1}).then((t=>s({type:"delete",keys:t.result,trans:e.trans,criteria:{index:null,range:e.range}}))):s(e):t.mutate(e):t.mutate(e)}});function s(e){const n=e.trans;n.mutationsAdded=!0;const{txid:r,currentUser:{userId:o}}=n,{type:s}=e;return t.mutate(e).then((t=>{const{numFailures:a,failures:c}=t;let u="delete"===s?e.keys:t.results,l="values"in e?e.values:[],d="changeSpecs"in e?e.changeSpecs:[];a&&(u=u.filter(((e,t)=>!c[t])),l=l.filter(((e,t)=>!c[t])),d=d.filter(((e,t)=>!c[t])));const h=Date.now(),f="delete"===e.type?{type:"delete",ts:h,keys:u,criteria:e.criteria,txid:r,userId:o}:"add"===e.type?{type:"insert",ts:h,keys:u,txid:r,userId:o,values:l}:e.criteria&&e.changeSpec?{type:"modify",ts:h,keys:u,criteria:e.criteria,changeSpec:e.changeSpec,txid:r,userId:o}:e.changeSpecs?{type:"update",ts:h,keys:u,changeSpecs:d,txid:r,userId:o}:{type:"upsert",ts:h,keys:u,values:l,txid:r,userId:o};return u.length>0||"criteria"in e&&e.criteria?i.mutate({type:"add",trans:n,values:[f]}).then((()=>t)):t}))}}}}}}function An(e,t){return function(n,r){const o={...on,...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)(_n.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 Pn=kn(16);async function On(e,n,r,i,{awaitRemoteJob:s}={}){const a=e.table(r);if(await async function i(){if(await e.transaction("rw!",r,(async()=>{const e=await a.get(n);return e?e.heartbeat.getTime()<Date.now()-6e4&&(console.warn(`Latest ${n} worker seem to have died.\n`,"The dead job started:",e.started,"\n","Last heart beat was:",e.heartbeat,"\n","We're now taking over!"),await a.put({nodeId:Pn,started:new Date,heartbeat:new Date},n),!0):(await a.add({nodeId:Pn,started:new Date,heartbeat:new Date},n),!0)})))return!0;if(s)try{const e=o(t((()=>a.get(n)))).pipe(qe(6e4),Ae((e=>!e)));return await e.toPromise(),!1}catch(e){if("TimeoutError"!==e.name)throw e;return await i()}return!1}()){const t=setInterval((()=>{a.update(n,(e=>e.nodeId===Pn&&(e.heartbeat=new Date)))}),1e3);try{return await i()}finally{clearInterval(t),await e.transaction("rw!",r,(async()=>{const e=await a.get(n);e&&e.nodeId===Pn&&a.delete(n)}))}}}const Un=new r(!0),Dn=new r(!0);var $n,Nn;Un.pipe(Re((e=>e?s(!0):s(!1).pipe(Se(2e4)))),(function(e){return e.lift(new Ie($n,Nn))})).subscribe(Dn);const Rn="undefined"!=typeof document?i(document,"visibilitychange"):s({}),jn=Rn.pipe(Ae((()=>"hidden"===document.visibilityState))),Ln=Rn.pipe(Ae((()=>"visible"===document.visibilityState))),Wn="undefined"!=typeof window?a(Ln,i(window,"mousemove"),i(window,"keydown"),i(window,"wheel"),i(window,"touchmove")):s({});"undefined"!=typeof document&&a(s(!0),jn,Wn).pipe(re((()=>"visible"===document.visibilityState)),Be((e=>{Un.value!==e&&Un.next(e)})),Re((e=>e?s(0).pipe(Se(28e4),Be((()=>Un.next(!1)))):s(0)))).subscribe((()=>{}));class Bn extends Error{constructor(){super(...arguments),this.name="TokenExpiredError"}}class Fn extends n{constructor(e,t,n,r,o,i,s){super((a=>new Hn(e,t,n,i,s,a,r,o)))}}let Mn=0;class Hn extends c{constructor(e,t,n,r,o,i,s,a){super((()=>this.teardown())),this.id=++Mn,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 Bn);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=St.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(St.stringify(e)))}))}catch(e){this.pauseUntil=new Date(Date.now()+6e4)}}}async function Vn(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 Wn.pipe(Ue(1)).toPromise(),console.debug("someone did something!")}async function Kn(e){var t;return!(!(null===(t=e.cloud.options)||void 0===t?void 0:t.databaseUrl)||!e.cloud.schema)&&await Zt(e,e.cloud.options,e.cloud.schema,{justCheckIfNeeded:!0})}const qn=new WeakMap;function zn(e,t,n,r){let o=qn.get(e);if(o)return o.pull||"push"===(null==r?void 0:r.purpose)?(console.debug("syncIfPossible(): returning the ongoing sync promise."),o.promise):o.promise.then((()=>zn(e,t,n,r)));const i=async function(){try{e.cloud.usingServiceWorker?yn&&await Zt(e,t,n,r):await On(e,"currentSyncWorker","$jobs",(()=>Zt(e,t,n,r))),qn.delete(e),console.debug("Done sync")}catch(t){throw qn.delete(e),console.error("Failed to sync client changes",t),t}}();return qn.set(e,{promise:i,pull:"push"!==(null==r?void 0:r.purpose)}),i}function Gn(e,t,n){let r=null,o={cancelled:!1};function i(r,a=1){zn(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 Jn(e,t){if(e&&t&&t.unsyncedTables)for(const n of t.unsyncedTables)e[n]&&(e[n].markedForSync=!1)}var Yn,Xn,Zn,Qn,er={},tr=[],nr=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i;function rr(e,t){for(var n in t)e[n]=t[n];return e}function or(e){var t=e.parentNode;t&&t.removeChild(e)}function ir(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 sr(e,a,r,o,null)}function sr(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?++Yn.__v:o};return null!=Yn.vnode&&Yn.vnode(i),i}function ar(e){return e.children}function cr(e,t){this.props=e,this.context=t}function ur(e,t){if(null==t)return e.__?ur(e.__,e.__.__k.indexOf(e)+1):null;for(var n;t<e.__k.length;t++)if(null!=(n=e.__k[t])&&null!=n.__e)return n.__e;return"function"==typeof e.type?ur(e):null}function lr(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 lr(e)}}function dr(e){(!e.__d&&(e.__d=!0)&&Xn.push(e)&&!hr.__r++||Qn!==Yn.debounceRendering)&&((Qn=Yn.debounceRendering)||Zn)(hr)}function hr(){for(var e;hr.__r=Xn.length;)e=Xn.sort((function(e,t){return e.__v.__b-t.__v.__b})),Xn=[],e.some((function(e){var t,n,r,o,i,s;e.__d&&(i=(o=(t=e).__v).__e,(s=t.__P)&&(n=[],(r=rr({},o)).__v=o.__v+1,_r(s,o,r,t.__n,void 0!==s.ownerSVGElement,null!=o.__h?[i]:null,n,null==i?ur(o):i,o.__h),wr(n,o),o.__e!=i&&lr(o)))}))}function fr(e,t,n,r,o,i,s,a,c,u){var l,d,h,f,p,y,b,v=r&&r.__k||tr,m=v.length;for(n.__k=[],l=0;l<t.length;l++)if(null!=(f=n.__k[l]=null==(f=t[l])||"boolean"==typeof f?null:"string"==typeof f||"number"==typeof f||"bigint"==typeof f?sr(null,f,null,null,f):Array.isArray(f)?sr(ar,{children:f},null,null,null):f.__b>0?sr(f.type,f.props,f.key,null,f.__v):f)){if(f.__=n,f.__b=n.__b+1,null===(h=v[l])||h&&f.key==h.key&&f.type===h.type)v[l]=void 0;else for(d=0;d<m;d++){if((h=v[d])&&f.key==h.key&&f.type===h.type){v[d]=void 0;break}h=null}_r(e,f,h=h||er,o,i,s,a,c,u),p=f.__e,(d=f.ref)&&h.ref!=d&&(b||(b=[]),h.ref&&b.push(h.ref,null,f),b.push(d,f.__c||p,f)),null!=p?(null==y&&(y=p),"function"==typeof f.type&&null!=f.__k&&f.__k===h.__k?f.__d=c=pr(f,c,e):c=yr(e,f,h,v,p,c),u||"option"!==n.type?"function"==typeof n.type&&(n.__d=c):e.value=""):c&&h.__e==c&&c.parentNode!=e&&(c=ur(h))}for(n.__e=y,l=m;l--;)null!=v[l]&&("function"==typeof n.type&&null!=v[l].__e&&v[l].__e==n.__d&&(n.__d=ur(r,l+1)),xr(v[l],v[l]));if(b)for(l=0;l<b.length;l++)kr(b[l],b[++l],b[++l])}function pr(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?pr(o,t,n):yr(n,o,o,e.__k,o.__e,t));return t}function yr(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 br(e,t,n){"-"===t[0]?e.setProperty(t,n):e[t]=null==n?"":"number"!=typeof n||nr.test(t)?n:n+"px"}function vr(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||br(e.style,t,"");if(n)for(t in n)r&&n[t]===r[t]||br(e.style,t,n[t])}else if("o"===t[0]&&"n"===t[1])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?gr:mr,i):e.removeEventListener(t,i?gr:mr,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 mr(e){this.l[e.type+!1](Yn.event?Yn.event(e):e)}function gr(e){this.l[e.type+!0](Yn.event?Yn.event(e):e)}function _r(e,t,n,r,o,i,s,a,c){var u,l,d,h,f,p,y,b,v,m,g,_=t.type;if(void 0!==t.constructor)return null;null!=n.__h&&(c=n.__h,a=t.__e=n.__e,t.__h=null,i=[a]),(u=Yn.__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 cr(b,m),l.constructor=_,l.render=Er),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=rr({},l.__s)),rr(l.__s,_.getDerivedStateFromProps(b,l.__s))),h=l.props,f=l.state,d)null==_.getDerivedStateFromProps&&null!=l.componentWillMount&&l.componentWillMount(),null!=l.componentDidMount&&l.__h.push(l.componentDidMount);else{if(null==_.getDerivedStateFromProps&&b!==h&&null!=l.componentWillReceiveProps&&l.componentWillReceiveProps(b,m),!l.__e&&null!=l.shouldComponentUpdate&&!1===l.shouldComponentUpdate(b,l.__s,m)||t.__v===n.__v){l.props=b,l.state=l.__s,t.__v!==n.__v&&(l.__d=!1),l.__v=t,t.__e=n.__e,t.__k=n.__k,t.__k.forEach((function(e){e&&(e.__=t)})),l.__h.length&&s.push(l);break e}null!=l.componentWillUpdate&&l.componentWillUpdate(b,l.__s,m),null!=l.componentDidUpdate&&l.__h.push((function(){l.componentDidUpdate(h,f,p)}))}l.context=m,l.props=b,l.state=l.__s,(u=Yn.__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=rr(rr({},r),l.getChildContext())),d||null==l.getSnapshotBeforeUpdate||(p=l.getSnapshotBeforeUpdate(h,f)),g=null!=u&&u.type===ar&&null==u.key?u.props.children:u,fr(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=Sr(n.__e,t,n,r,o,i,s,c);(u=Yn.diffed)&&u(t)}catch(e){t.__v=null,(c||null!=i)&&(t.__e=a,t.__h=!!c,i[i.indexOf(a)]=null),Yn.__e(e,t,n)}}function wr(e,t){Yn.__c&&Yn.__c(t,e),e.some((function(t){try{e=t.__h,t.__h=[],e.some((function(e){e.call(t)}))}catch(e){Yn.__e(e,t.__v)}}))}function Sr(e,t,n,r,o,i,s,a){var c,u,l,d,h=n.props,f=t.props,p=t.type,y=0;if("svg"===p&&(o=!0),null!=i)for(;y<i.length;y++)if((c=i[y])&&(c===e||(p?c.localName==p:3==c.nodeType))){e=c,i[y]=null;break}if(null==e){if(null===p)return document.createTextNode(f);e=o?document.createElementNS("http://www.w3.org/2000/svg",p):document.createElement(p,f.is&&f),i=null,a=!1}if(null===p)h===f||a&&e.data===f||(e.data=f);else{if(i=i&&tr.slice.call(e.childNodes),u=(h=n.props||er).dangerouslySetInnerHTML,l=f.dangerouslySetInnerHTML,!a){if(null!=i)for(h={},d=0;d<e.attributes.length;d++)h[e.attributes[d].name]=e.attributes[d].value;(l||u)&&(l&&(u&&l.__html==u.__html||l.__html===e.innerHTML)||(e.innerHTML=l&&l.__html||""))}if(function(e,t,n,r,o){var i;for(i in n)"children"===i||"key"===i||i in t||vr(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]||vr(e,i,t[i],n[i],r)}(e,f,h,o,a),l)t.__k=[];else if(y=t.props.children,fr(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]&&or(i[y]);a||("value"in f&&void 0!==(y=f.value)&&(y!==e.value||"progress"===p&&!y)&&vr(e,"value",y,h.value,!1),"checked"in f&&void 0!==(y=f.checked)&&y!==e.checked&&vr(e,"checked",y,h.checked,!1))}return e}function kr(e,t,n){try{"function"==typeof e?e(t):e.current=t}catch(e){Yn.__e(e,n)}}function xr(e,t,n){var r,o,i;if(Yn.unmount&&Yn.unmount(e),(r=e.ref)&&(r.current&&r.current!==e.__e||kr(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){Yn.__e(e,t)}r.base=r.__P=null}if(r=e.__k)for(i=0;i<r.length;i++)r[i]&&xr(r[i],t,n);null!=o&&or(o)}function Er(e,t,n){return this.constructor(e,n)}Yn={__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},cr.prototype.setState=function(e,t){var n;n=null!=this.__s&&this.__s!==this.state?this.__s:this.__s=rr({},this.state),"function"==typeof e&&(e=e(rr({},n),this.props)),e&&rr(n,e),null!=e&&this.__v&&(t&&this.__h.push(t),dr(this))},cr.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),dr(this))},cr.prototype.render=ar,Xn=[],Zn="function"==typeof Promise?Promise.prototype.then.bind(Promise.resolve()):setTimeout,hr.__r=0;const Ir={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 Tr({children:e}){return ir("div",null,ir("div",{style:Ir.Darken}),ir("div",{style:Ir.DialogOuter},ir("div",{style:Ir.DialogInner},e)))}var Cr,Ar,Pr,Or=0,Ur=[],Dr=Yn.__b,$r=Yn.__r,Nr=Yn.diffed,Rr=Yn.__c,jr=Yn.unmount;function Lr(e,t){Yn.__h&&Yn.__h(Ar,e,Or||t),Or=0;var n=Ar.__H||(Ar.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function Wr(e){return Or=1,function(e,t,n){var r=Lr(Cr++,2);return r.t=e,r.__c||(r.__=[n?n(t):qr(void 0,t),function(e){var t=r.t(r.__[0],e);r.__[0]!==t&&(r.__=[t,r.__[1]],r.__c.setState({}))}],r.__c=Ar),r.__}(qr,e)}function Br(e){return Or=5,function(e,t){var n=Lr(Cr++,7);return Kr(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}((function(){return{current:e}}),[])}function Fr(){Ur.forEach((function(e){if(e.__P)try{e.__H.__h.forEach(Hr),e.__H.__h.forEach(Vr),e.__H.__h=[]}catch(t){e.__H.__h=[],Yn.__e(t,e.__v)}})),Ur=[]}Yn.__b=function(e){Ar=null,Dr&&Dr(e)},Yn.__r=function(e){$r&&$r(e),Cr=0;var t=(Ar=e.__c).__H;t&&(t.__h.forEach(Hr),t.__h.forEach(Vr),t.__h=[])},Yn.diffed=function(e){Nr&&Nr(e);var t=e.__c;t&&t.__H&&t.__H.__h.length&&(1!==Ur.push(t)&&Pr===Yn.requestAnimationFrame||((Pr=Yn.requestAnimationFrame)||function(e){var t,n=function(){clearTimeout(r),Mr&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,100);Mr&&(t=requestAnimationFrame(n))})(Fr)),Ar=void 0},Yn.__c=function(e,t){t.some((function(e){try{e.__h.forEach(Hr),e.__h=e.__h.filter((function(e){return!e.__||Vr(e)}))}catch(n){t.some((function(e){e.__h&&(e.__h=[])})),t=[],Yn.__e(n,e.__v)}})),Rr&&Rr(e,t)},Yn.unmount=function(e){jr&&jr(e);var t=e.__c;if(t&&t.__H)try{t.__H.__.forEach(Hr)}catch(e){Yn.__e(e,t.__v)}};var Mr="function"==typeof requestAnimationFrame;function Hr(e){var t=Ar;"function"==typeof e.__c&&e.__c(),Ar=t}function Vr(e){var t=Ar;e.__c=e.__(),Ar=t}function Kr(e,t){return!e||e.length!==t.length||t.some((function(t,n){return t!==e[n]}))}function qr(e,t){return"function"==typeof t?t(e):t}function zr({title:e,alerts:t,fields:n,onCancel:r,onSubmit:o}){const[i,s]=Wr({}),a=Br();return function(e,t){var n=Lr(Cr++,4);!Yn.__s&&Kr(n.__H,t)&&(n.__=e,n.__H=t,Ar.__h.push(n))}((()=>{var e;return null===(e=a.current)||void 0===e?void 0:e.focus()}),[]),ir(Tr,null,ir(ar,null,ir("h3",{style:Ir.WindowHeader},e),t.map((e=>ir("p",{style:Ir.Alert[e.type]},function({message:e,messageCode:t,messageParams:n}){return e.replace(/\{\w+\}/gi,(e=>n[e.substr(1,e.length-2)]))}(e)))),ir("form",{onSubmit:e=>{e.preventDefault(),o(i)}},Object.entries(n).map((([e,{type:t,label:n,placeholder:r}],o)=>ir("label",{style:Ir.Label},n?`${n}: `:"",ir("input",{ref:0===o?a:void 0,type:t,name:e,autoComplete:"on",style:Ir.Input,autoFocus:!0,placeholder:r,value:i[e]||"",onInput:n=>{var r;return s({...i,[e]:Gr(t,null===(r=n.target)||void 0===r?void 0:r.value)})}})))))),ir("div",{style:Ir.ButtonsDiv},ir("button",{type:"submit",style:Ir.Button,onClick:()=>o(i)},"Submit"),ir("button",{style:Ir.Button,onClick:r},"Cancel")))}function Gr(e,t){switch(e){case"email":return t.toLowerCase();case"otp":return t.toUpperCase();default:return t}}class Jr extends cr{constructor(e){super(e),this.observer=e=>this.setState({userInteraction:e}),this.state={userInteraction:void 0}}componentDidMount(){this.subscription=o(this.props.db.cloud.userInteraction).subscribe(this.observer)}componentWillUnmount(){this.subscription&&(this.subscription.unsubscribe(),delete this.subscription)}render(e,{userInteraction:t}){return t?ir(zr,Object.assign({},t)):null}}function Yr(e){const t=document.createElement("div");document.body.appendChild(t),function(e,t,n){var r,o,i;Yn.__&&Yn.__(e,t),o=(r="function"==typeof n)?null:n&&n.__k||t.__k,i=[],_r(t,e=(!r&&n||t).__k=ir(ar,null,[e]),o||er,er,void 0!==t.ownerSVGElement,!r&&n?[n]:o?null:t.firstChild?tr.slice.call(t.childNodes):null,i,!r&&n?n:o?o.__e:t.firstChild,r),wr(i,e)}(ir(Jr,{db:e.vip}),t);let n=!1;return{unsubscribe(){t.remove(),n=!0},get closed(){return n}}}function Xr(n){const a=n.name,c=new r(d),h=[];let f=null;n.on("ready",(async n=>{try{await async function(n){var r,a,d,b,v,m;p=!1;const g=an(n);yn||((null===(r=g.cloud.options)||void 0===r?void 0:r.customLoginGui)||h.push(Yr(n)),h.push(function(e){let t=e.cloud.webSocketStatus.value;const n=e.cloud.webSocketStatus.pipe(Re((e=>{const n=t;t=e;const r=s(e);switch(e){case"disconnected":return Un.value?r.pipe(he(500)):r;case"connecting":return"not-started"===n||"error"===n?r:r.pipe(he(4e3));default:return r}})));return l([n,e.syncStateChangedEvent.pipe(Ne({phase:"initial"})),Dn]).pipe(re((([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:Jt?a:"offline"}})))}(g).subscribe(n.cloud.syncState)));g.tables.every((e=>e.core))||bn();const _="serviceWorker"in navigator?await navigator.serviceWorker.getRegistrations():[],w=await g.transaction("rw",g.$syncState,(async()=>{var e,t;const{options:n,schema:r}=g.cloud,[o,i,s]=await Promise.all([g.getOptions(),g.getSchema(),g.getPersistedSyncState()]);if(n?o&&JSON.stringify(o)===JSON.stringify(n)||await g.$syncState.put(n,"options"):g.cloud.options=o||null,(null===(e=g.cloud.options)||void 0===e?void 0:e.tryUseServiceWorker)&&"serviceWorker"in navigator&&_.length>0&&!pn?(console.debug("Dexie Cloud Addon: Using service worker"),g.cloud.usingServiceWorker=!0):((null===(t=g.cloud.options)||void 0===t?void 0:t.tryUseServiceWorker)&&!yn&&console.debug("dexie-cloud-addon: Not using service worker.",0===_.length?"No SW registrations found.":"serviceWorker"in navigator&&pn?"Avoiding SW background sync and SW periodic bg sync for this browser due to browser bugs.":"navigator.serviceWorker not present"),g.cloud.usingServiceWorker=!1),Jn(r,g.cloud.options),Jn(i,g.cloud.options),r){if(!i||JSON.stringify(i)!==JSON.stringify(r)){const e=i||{};for(const[t,n]of Object.entries(r)){const r=e[t];r?(r.markedForSync=n.markedForSync,n.deleted=r.deleted,r.generatedGlobalId=n.generatedGlobalId):e[t]={...n}}await g.$syncState.put(e,"schema"),Object.assign(r,e)}}else g.cloud.schema=i||null;return null==s?void 0:s.initiallySynced}));w&&g.setInitiallySynced(!0);(function(t){var n,r;for(const o of t.tables)if(null===(r=null===(n=t.cloud.schema)||void 0===n?void 0:n[o.name])||void 0===r?void 0:r.markedForSync){if(o.schema.primKey.auto)throw new e.SchemaError(`Table ${o.name} is both autoIncremented and synced. Use db.cloud.configure({unsyncedTables: [${JSON.stringify(o.name)}]}) to blacklist it from sync`);if(!o.schema.primKey.keyPath)throw new e.SchemaError(`Table ${o.name} cannot be both synced and outbound. Use db.cloud.configure({unsyncedTables: [${JSON.stringify(o.name)}]}) to blacklist it from sync`)}})(g),(null===(a=g.cloud.options)||void 0===a?void 0:a.databaseUrl)&&!w&&(await async function(e,t,n){console.debug("Performing initial sync"),await On(e,"initialSync","$jobs",(async()=>{const r=await e.getPersistedSyncState();(null==r?void 0:r.initiallySynced)||await Zt(e,t,n,{isInitialSync:!0})}),{awaitRemoteJob:!0}),console.debug("Done initial sync")}(g,g.cloud.options,g.cloud.schema),g.setInitiallySynced(!0));y(),yn||(h.push(t((()=>g.getCurrentUser())).subscribe(c)),h.push(t((()=>g.getPersistedSyncState())).subscribe(g.cloud.persistedSyncState)));(null===(d=g.cloud.options)||void 0===d?void 0:d.requireAuth)&&await ln(g);f&&f.stop();f=null,y(),g.cloud.usingServiceWorker&&(null===(b=g.cloud.options)||void 0===b?void 0:b.databaseUrl)?(Et(g,"pull").catch((()=>{})),async function(e){var t;try{const{periodicSync:n}=await navigator.serviceWorker.ready;if(n)try{await n.register(`dexie-cloud:${e.name}`,null===(t=e.cloud.options)||void 0===t?void 0:t.periodicSync),console.debug(`Dexie Cloud: Successfully registered periodicsync event for ${e.name}`)}catch(e){console.debug("Dexie Cloud: Failed to register periodic sync. Your PWA must be installed to allow background sync.",e)}else console.debug("Dexie Cloud: periodicSync not supported.")}catch(t){console.debug(`Dexie Cloud: Could not register periodicSync for ${e.name}`,t)}}(g).catch((()=>{}))):(null===(v=g.cloud.options)||void 0===v?void 0:v.databaseUrl)&&g.cloud.schema&&!yn&&(f=Gn(g,g.cloud.options,g.cloud.schema),f.start());y(),yn||h.push(i(self,"online").subscribe((()=>{console.debug("online!"),g.syncStateChangedEvent.next({phase:"not-in-sync"}),It(g,"push")})),i(self,"offline").subscribe((()=>{console.debug("offline!"),g.syncStateChangedEvent.next({phase:"offline"})})));"undefined"!=typeof window&&!yn&&(null===(m=g.cloud.options)||void 0===m?void 0:m.databaseUrl)&&h.push(function(e){var t;if(!(null===(t=e.cloud.options)||void 0===t?void 0:t.databaseUrl))throw new Error("No database URL to connect WebSocket to");const n=e.messageConsumer.readyToServe.pipe(Ae((e=>e)),Re((()=>e.getPersistedSyncState())),Ae((e=>e&&e.serverRevision)),re((e=>({type:"ready",rev:e.serverRevision}))));return function t(){return e.cloud.persistedSyncState.pipe(Ae((e=>null==e?void 0:e.serverRevision)),Ue(1),Re((()=>e.cloud.currentUser)),Re((e=>Dn.pipe(re((t=>t?e:null))))),Re((t=>t?new Fn(e.cloud.options.databaseUrl,e.cloud.persistedSyncState.value.serverRevision,e.cloud.persistedSyncState.value.clientIdentity,n,e.cloud.webSocketStatus,t.accessToken,t.accessTokenExpiration):o([]))),J((n=>"TokenExpiredError"===(null==n?void 0:n.name)?(console.debug("WebSocket observable: Token expired. Refreshing token..."),s(!0).pipe(Re((async()=>{const t=await e.getCurrentUser(),n=await Vt(e.cloud.options.databaseUrl,t);await e.table("$logins").update(t.userId,{accessToken:n.accessToken,accessTokenExpiration:n.accessTokenExpiration})})),Re((()=>t())))):u(n))),J((e=>o(Vn(e)).pipe(Re((()=>t()))))))}().subscribe((t=>{t&&(console.debug("WS got message",t),e.messageConsumer.enqueue(t))}),(e=>{console.error("Oops! The main observable errored!",e)}),(()=>{console.error("Oops! The main observable completed!")}))}(g))}(n)}catch(e){console.error(e)}}),!0);let p=!1;function y(){if(p)throw new e.DatabaseClosedError}var b;!function(e,t){e.on.close.subscribe(t);const n=e.close;e.close=function(){n.call(this),t()}}(n,(()=>{h.forEach((e=>e.unsubscribe())),p=!0,f&&f.stop(),f=null,c.next(d)})),n.cloud={version:"1.0.0-beta.7",options:null,schema:null,serverState:null,get currentUserId(){return c.value.userId||d.userId},currentUser:c,syncState:new r({phase:"initial",status:"not-started"}),persistedSyncState:new r(void 0),userInteraction:new r(void 0),webSocketStatus:new r("not-started"),async login(e){const t=an(n);await t.cloud.sync(),await ln(t,e)},configure(e){n.cloud.options=e,e.databaseUrl&&(n.name=`${a}-${function(e){const t=new URL(e);return"/"===t.pathname?t.hostname.split(".")[0]:t.pathname.split("/")[1]}(e.databaseUrl)}`,an(n).reconfigure()),Jn(n.cloud.schema,n.cloud.options)},async sync({wait:e,purpose:r}={wait:!0,purpose:"push"}){void 0===e&&(e=!0);const i=an(n);if("pull"===r){const t=i.cloud.persistedSyncState.value;if(It(i,r),e){const e=await i.cloud.persistedSyncState.pipe(Ae((e=>null!=(null==e?void 0:e.timestamp)&&(!t||e.timestamp>t.timestamp))),Ue(1)).toPromise();if(null==e?void 0:e.error)throw new Error("Sync error: "+e.error)}}else if(await Kn(i)){const n=i.cloud.persistedSyncState.value;It(i,r),e&&(console.debug("db.cloud.login() is waiting for sync completion..."),await o(t((async()=>{const e=await Kn(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(Ae((e=>!e)),Ue(1)).toPromise(),console.debug("Done waiting for sync completion because we have nothing to push anymore"))}}},n.Version.prototype._parseStoresSpec=e.override(n.Version.prototype._parseStoresSpec,(e=>An(e,n))),n.use(Cn({currentUserObservable:n.cloud.currentUser,db:an(n)})),n.use((b=an(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=b.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(Sn(an(n)))}Xr.version="1.0.0-beta.7",e.Cloud=Xr;const Zr=new Map;function Qr(e){return e.startsWith("dexie-cloud:")&&e.split(":")[1]}const eo=new Map;function to(t,n){let r=eo.get(t+"/"+n);return r||(r=async function(t,n){var r;let o=Zr.get(t);if(!o){console.debug("Dexie Cloud SW: Creating new Dexie instance for",t);const n=new e(t,{addons:[Xr]});o=an(n),n.on("versionchange",i),await o.dx.open(),Zr.get(t)||Zr.set(t,o)}if(!(null===(r=o.cloud.options)||void 0===r?void 0:r.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),Zr.get(o.name)===o&&Zr.delete(o.name),o.dx.close(),!1}try{console.debug("Dexie Cloud SW: Syncing"),await zn(o,o.cloud.options,o.cloud.schema,{retryImmediatelyOnFetchError:!0,purpose:n}),console.debug("Dexie Cloud SW: Done Syncing")}catch(t){if(console.error("Dexie Cloud SW Error",t),i(),t.name!==e.errnames.NoSuchDatabase)throw t}}(t,n).then((()=>{eo.delete(t+"/"+n)})).catch((e=>(eo.delete(t+"/"+n),Promise.reject(e)))),eo.set(t+"/"+n,r)),r}pn||(self.addEventListener("sync",(e=>{console.debug('SW "sync" Event',e.tag);const t=Qr(e.tag);t&&e.waitUntil(to(t,"push"))})),self.addEventListener("periodicsync",(e=>{console.debug('SW "periodicsync" Event',e.tag);const t=Qr(e.tag);t&&e.waitUntil(to(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)=>to(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
|
+
import e,{cmp as t,liveQuery as n}from"dexie";import{Observable as r,BehaviorSubject as o,Subject as s,from as i,fromEvent as a,of as c,merge as u,Subscription as l,throwError as d,combineLatest as f,map as p,share as h,timer as y,switchMap as m}from"rxjs";const b={userId:"unauthorized",name:"Unauthorized",claims:{sub:"unauthorized"},lastLogin:new Date(0)};try{Object.freeze(b),Object.freeze(b.claims)}catch{}const v={},g=self.document&&navigator.serviceWorker;g&&g.ready.then((e=>v.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 w{constructor(e){this.name=e}subscribe(e){if(!g)return()=>{};const t=t=>{t.data?.type===`sw-broadcast-${this.name}`&&e(t.data.message)};return g.addEventListener("message",t),()=>g.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}))):v.registration&&v.registration.active?.postMessage({type:`sw-broadcast-${this.name}`,message:e})}}class _ extends r{constructor(e){const t="undefined"==typeof BroadcastChannel?new w(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 w?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 w?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 S(e){return"function"==typeof e}function k(e){return function(t){if(function(e){return S(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 x=function(e,t){return x=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])},x(e,t)};function E(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}x(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}function I(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 C(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 A(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 T(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 P(e,t){for(var n=0,r=t.length,o=e.length;n<r;n++,o++)e[o]=t[n];return e}function U(e){return this instanceof U?(this.v=e,this):new U(e)}function $(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 U?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 D(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,n=e[Symbol.asyncIterator];return n?n.call(e):(e=A(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 O=function(e){return e&&"number"==typeof e.length&&"function"!=typeof e};function R(e){return S(null==e?void 0:e.then)}function L(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 N=L((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 j(e,t){if(e){var n=e.indexOf(t);0<=n&&e.splice(n,1)}}var W=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=A(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(S(c))try{c()}catch(e){o=e instanceof N?e.errors:[e]}var u=this._teardowns;if(u){this._teardowns=null;try{for(var l=A(u),d=l.next();!d.done;d=l.next()){var f=d.value;try{M(f)}catch(e){o=null!=o?o:[],e instanceof N?o=P(P([],T(o)),T(e.errors)):o.push(e)}}}catch(e){n={error:e}}finally{try{d&&!d.done&&(r=l.return)&&r.call(l)}finally{if(n)throw n.error}}}if(o)throw new N(o)}},e.prototype.add=function(t){var n;if(t&&t!==this)if(this.closed)M(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)&&j(t,e)},e.prototype.remove=function(t){var n=this._teardowns;n&&j(n,t),t instanceof e&&t._removeParent(this)},e.EMPTY=((t=new e).closed=!0,t),e}();function B(e){return e instanceof W||e&&"closed"in e&&S(e.remove)&&S(e.add)&&S(e.unsubscribe)}function M(e){S(e)?e():e.unsubscribe()}var F={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},K=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return setTimeout.apply(void 0,P([],T(e)))};function H(e){K((function(){throw e}))}function q(){}var z=function(e){function t(t){var n=e.call(this)||this;return n.isStopped=!1,t?(n.destination=t,B(t)&&t.add(n)):n.destination=Y,n}return E(t,e),t.create=function(e,t,n){return new V(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}(W),V=function(e){function t(t,n,r){var o,s=e.call(this)||this;if(S(t))o=t;else if(t){var i;o=t.next,n=t.error,r=t.complete,s&&F.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?J(o):q,error:J(null!=n?n:G),complete:r?J(r):q},s}return E(t,e),t}(z);function J(e,t){return function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];try{e.apply(void 0,P([],T(t)))}catch(e){H(e)}}}function G(e){throw e}var Y={closed:!0,next:q,error:G,complete:q},Z="function"==typeof Symbol&&Symbol.observable||"@@observable";function X(e){return e}function Q(e){return 0===e.length?X:1===e.length?e[0]:function(t){return e.reduce((function(e,t){return t(e)}),t)}}var ee=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 z||function(e){return e&&S(e.next)&&S(e.error)&&S(e.complete)}(r)&&B(r)?e:new V(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=te(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[Z]=function(){return this},e.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Q(e)(this)},e.prototype.toPromise=function(e){var t=this;return new(e=te(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 te(e){var t;return null!==(t=null!=e?e:F.Promise)&&void 0!==t?t:Promise}function ne(e){return S(e[Z])}function re(e){return Symbol.asyncIterator&&S(null==e?void 0:e[Symbol.asyncIterator])}function oe(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 se="function"==typeof Symbol&&Symbol.iterator?Symbol.iterator:"@@iterator";function ie(e){return S(null==e?void 0:e[se])}function ae(e){return $(this,arguments,(function(){var t,n,r;return C(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,U(t.read())];case 3:return n=o.sent(),r=n.value,n.done?[4,U(void 0)]:[3,5];case 4:return[2,o.sent()];case 5:return[4,U(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 ce(e){return S(null==e?void 0:e.getReader)}function ue(e){if(e instanceof ee)return e;if(null!=e){if(ne(e))return o=e,new ee((function(e){var t=o[Z]();if(S(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")}));if(O(e))return r=e,new ee((function(e){for(var t=0;t<r.length&&!e.closed;t++)e.next(r[t]);e.complete()}));if(R(e))return n=e,new ee((function(e){n.then((function(t){e.closed||(e.next(t),e.complete())}),(function(t){return e.error(t)})).then(null,H)}));if(re(e))return le(e);if(ie(e))return t=e,new ee((function(e){var n,r;try{for(var o=A(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(ce(e))return le(ae(e))}var t,n,r,o;throw oe(e)}function le(e){return new ee((function(t){(function(e,t){var n,r,o,s;return I(this,void 0,void 0,(function(){var i,a;return C(this,(function(c){switch(c.label){case 0:c.trys.push([0,5,6,11]),n=D(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 de=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 E(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}(z),fe=function(e){function t(t,n){return e.call(this)||this}return E(t,e),t.prototype.schedule=function(e,t){return this},t}(W),pe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return setInterval.apply(void 0,P([],T(e)))},he=function(e){return clearInterval(e)},ye=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 E(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),pe(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;he(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,j(r,this),null!=t&&(this.id=this.recycleAsyncId(n,t,null)),this.delay=null,e.prototype.unsubscribe.call(this)}},t}(fe),me=function(){return Date.now()},be=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=me,e}(),ve=new(function(e){function t(t,n){void 0===n&&(n=be.now);var r=e.call(this,t,n)||this;return r.actions=[],r._active=!1,r._scheduled=void 0,r}return E(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}(be))(ye),ge=ve;function we(e){return e&&S(e.schedule)}function _e(e){return e instanceof Date&&!isNaN(e)}function Se(e){return we((t=e)[t.length-1])?e.pop():void 0;var t}function ke(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 xe(e){return k((function(t,n){var r,o=null,s=!1;o=t.subscribe(new de(n,void 0,void 0,(function(i){r=ue(e(i,xe(e)(t))),o?(o.unsubscribe(),o=null,r.subscribe(n)):s=!0}))),s&&(o.unsubscribe(),o=null,r.subscribe(n))}))}function Ee(e,t){return void 0===t&&(t=0),k((function(n,r){n.subscribe(new de(r,(function(n){return ke(r,e,(function(){return r.next(n)}),t)}),(function(){return ke(r,e,(function(){return r.complete()}),t)}),(function(n){return ke(r,e,(function(){return r.error(n)}),t)})))}))}function Ie(e,t){return void 0===t&&(t=0),k((function(n,r){r.add(e.schedule((function(){return n.subscribe(r)}),t))}))}function Ce(e,t){if(!e)throw new Error("Iterable cannot be null");return new ee((function(n){ke(n,t,(function(){var r=e[Symbol.asyncIterator]();ke(n,t,(function(){r.next().then((function(e){e.done?n.complete():n.next(e.value)}))}),0,!0)}))}))}function Ae(e,t){if(null!=e){if(ne(e))return function(e,t){return ue(e).pipe(Ie(t),Ee(t))}(e,t);if(O(e))return function(e,t){return new ee((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(R(e))return function(e,t){return ue(e).pipe(Ie(t),Ee(t))}(e,t);if(re(e))return Ce(e,t);if(ie(e))return function(e,t){return new ee((function(n){var r;return ke(n,t,(function(){r=e[se](),ke(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 S(null==r?void 0:r.return)&&r.return()}}))}(e,t);if(ce(e))return function(e,t){return Ce(ae(e),t)}(e,t)}throw oe(e)}function Te(e,t){return t?Ae(e,t):ue(e)}function Pe(e,t){return k((function(n,r){var o=0;n.subscribe(new de(r,(function(n){r.next(e.call(t,n,o++))})))}))}function Ue(e,t,n){return void 0===n&&(n=1/0),S(t)?Ue((function(n,r){return Pe((function(e,o){return t(n,e,r,o)}))(ue(e(n,r)))}),n):("number"==typeof t&&(n=t),k((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;ue(n(e,l++)).subscribe(new de(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?ke(t,i,(function(){return h(e)})):h(e)};c.length&&u<r;)e();f()}catch(e){t.error(e)}})))};return e.subscribe(new de(t,p,(function(){d=!0,f()}))),function(){null==a||a()}}(t,r,e,n)})))}function $e(){return void 0===(e=1)&&(e=1/0),Ue(X,e);var e}function De(e,t){return void 0===t&&(t=ve),k((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 de(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 Oe(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return $e()(Te(e,Se(e)))}var Re=new ee((function(e){return e.complete()}));function Le(e){return e<=0?function(){return Re}:k((function(t,n){var r=0;t.subscribe(new de(n,(function(t){++r<=e&&(n.next(t),e<=r&&n.complete())})))}))}function Ne(e,t){return t?function(n){return Oe(t.pipe(Le(1),k((function(e,t){e.subscribe(new de(t,q))}))),n.pipe(Ne(e)))}:Ue((function(t,n){return e(t,n).pipe(Le(1),function(e){return Pe((function(){return e}))}(t))}))}function je(e,t){void 0===t&&(t=ve);var n=function(e,t,n){void 0===e&&(e=0),void 0===n&&(n=ge);var r=-1;return null!=t&&(we(t)?n=t:r=t),new ee((function(t){var o=_e(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 Ne((function(){return n}))}function We(e,t){return e===t}function Be(e,t){return k((function(n,r){var o=0;n.subscribe(new de(r,(function(n){return e.call(t,n,o++)&&r.next(n)})))}))}function Me(e){return Be((function(t,n){return e<=n}))}function Fe(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=Se(e);return k((function(t,r){(n?Oe(e,t,n):Oe(e,t)).subscribe(r)}))}function Ke(e,t){return k((function(n,r){var o=null,s=0,i=!1,a=function(){return i&&!o&&r.complete()};n.subscribe(new de(r,(function(n){null==o||o.unsubscribe();var i=0,c=s++;ue(e(n,c)).subscribe(o=new de(r,(function(e){return r.next(t?t(n,e,c,i++):e)}),(function(){o=null,a()})))}),(function(){i=!0,a()})))}))}function He(e,t,n){var r=S(e)||t||n?{next:e,error:t,complete:n}:e;return r?k((function(e,t){var n;null===(n=r.subscribe)||void 0===n||n.call(r);var o=!0;e.subscribe(new de(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)})))})):X}var qe=L((function(e){return function(t){void 0===t&&(t=null),e(this),this.message="Timeout has occurred",this.name="TimeoutError",this.info=t}}));function ze(e){throw new qe(e)}let Ve=!1;async function Je(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){Ve||(console.debug("Dexie Cloud: Could not register sync event",e),Ve=!0)}}function Ge(e,t){e.cloud.usingServiceWorker?Je(e,t):e.localSyncEvent.next({purpose:t})}const Ye="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},Ze="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 Xe({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 Ze(o)}function Qe(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 et(e){return`$${e}_mutations`}function tt(e){const t=/^\$(.*)_mutations$/.exec(e)?.[1];if(!t)throw new Error(`Given mutationTable ${e} is not correct`);return t}const nt=[].concat;async function rt(e,t,{since:n={},limit:r=1/0}={}){const o=function(e){return nt.apply([],e)}(await Promise.all(e.map((async e=>{const t=tt(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 ot(e){const t=new Uint8Array(e);return crypto.getRandomValues(t),btoa(String.fromCharCode.apply(null,t))}const st=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 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]={}),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 at="undefined"==typeof self?e=>{const t=Buffer.alloc(e);return st(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(ut))}function ut(e){return"string"==typeof e||"number"==typeof e||Array.isArray(e)&&e.every(ut)}function lt(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))it(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 dt(e,t){for(const{table:n,muts:r}of t)for(const t of r)lt(e,n,t)}function ft(t,n){return new Promise(((r,o)=>{const s={...n,onSubmit:e=>{t.next(void 0),r(e)},onCancel:()=>{t.next(void 0),o(new e.AbortError("User cancelled"))}};t.next(s)}))}function pt(e,t,...n){return ft(e,{type:"message-alert",title:t,alerts:n,fields:{}})}async function ht(e,t,n){let r=n||"";for(;!r||!/^[\w-\.]+@([\w-]+\.)+[\w-]{2,10}$/.test(r);)r=(await ft(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 yt(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 ft(e,{type:"otp",title:"Enter OTP",alerts:r,fields:{otp:{type:"otp",label:"OTP",placeholder:"Paste OTP here"}}});return o}async function mt(e,t,n,r,o){return t.accessToken&&t.accessTokenExpiration.getTime()>Date.now()?t:t.refreshToken&&(!t.refreshTokenExpiration||t.refreshTokenExpiration.getTime()>Date.now())?await bt(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=Ze(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 ft(n,{type:"message-alert",title:"Authentication Alert",fields:{},alerts:o.alerts}),e}catch(e){throw await pt(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 bt(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=Ze(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:vt}={};const gt={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 wt(...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 gt;let s=n.get(r);if(void 0!==s)return s;const i=(o=e,vt.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:gt),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 _t={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 St={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 kt={bigint:{replace:e=>({$t:"bigint",v:""+e}),revive:e=>BigInt(e.v)}};var xt={Date:{replace:e=>({$t:"Date",v:isNaN(e.getTime())?"NaN":e.toISOString()}),revive:({v:e})=>new Date("NaN"===e?NaN:Date.parse(e))}},Et={Set:{replace:e=>({$t:"Set",v:Array.from(e.entries())}),revive:({v:e})=>new Set(e)}},It={Map:{replace:e=>({$t:"Map",v:Array.from(e.entries())}),revive:({v:e})=>new Map(e)}};const Ct="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"==typeof global?global:void 0;var At=["Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","DataView","BigInt64Array","BigUint64Array"].reduce(((e,t)=>({...e,[t]:{replace:(e,n,r)=>({$t:t,v:r.ArrayBuffer.replace(0===e.byteOffset&&e.byteLength===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),n,r).v}),revive:({v:e},n,r)=>{const o=Ct[t];return o&&new o(r.ArrayBuffer.revive({v:e},n,r))}}})),{});function Tt(e){return function(e){for(var t="",n=0,r=e.length;n<r;n++)t+=$t[e[n]];return t}(Ze(e))}function Pt(e){return Ye(function(e){if("string"!=typeof e)throw new Error("invalid decoder input: "+e);for(var t="",n=0,r=e.length;n<r;n++)t+=Ut[e[n]];return t}(e))}const Ut={"-":"=",0:"A",1:"B",2:"C",3:"D",4:"E",5:"F",6:"G",7:"H",8:"I",9:"J",A:"K",B:"L",C:"M",D:"N",E:"O",F:"P",G:"Q",H:"R",I:"S",J:"T",K:"U",L:"V",M:"W",N:"X",O:"Y",P:"Z",Q:"a",R:"b",S:"c",T:"d",U:"e",V:"f",W:"g",X:"h",Y:"i",Z:"j",_:"k",a:"l",b:"m",c:"n",d:"o",e:"p",f:"q",g:"r",h:"s",i:"t",j:"u",k:"v",l:"w",m:"x",n:"y",o:"z",p:"0",q:"1",r:"2",s:"3",t:"4",u:"5",v:"6",w:"7",x:"8",y:"9",z:"+","|":"/"},$t={};for(const e of Object.keys(Ut))$t[Ut[e]]=e;var Dt={ArrayBuffer:{replace:e=>({$t:"ArrayBuffer",v:Tt(e)}),revive:({v:e})=>{const t=Pt(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 Rt(e){const t=new XMLHttpRequest;if(t.overrideMimeType("text/plain; charset=x-user-defined"),t.open("GET",URL.createObjectURL(e),!1),t.send(),200!==t.status&&0!==t.status)throw new Error("Bad Blob access: "+t.status);return t.responseText}function Lt(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t[n]=e.charCodeAt(n);return t.buffer}var Nt={Blob:{test:(e,t)=>"Blob"===t||e instanceof Ot,replace:e=>({$t:"Blob",v:Ze(e instanceof Ot?e.buf:Lt(Rt(e))),type:e.type}),revive:({type:e,v:t})=>{const n=Ye(t);return void 0!==typeof Blob?new Blob([n]):new Ot(n.buffer,e)}}};const jt={...St,...kt,...xt,...Et,...It,...At,...Dt,...Nt};function Wt(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 Bt={undefined:{replace:()=>({$t:"undefined"}),revive:()=>{}}};const Mt="bigint"==typeof BigInt(0);class Ft{constructor(e){this.v=e}toString(){return this.v}}const Kt={...Bt,...Mt?{}:{bigint:{test:e=>e instanceof Ft,replace:e=>({$t:"bigint",...e}),revive:({v:e})=>new Ft(e)}}},Ht=wt(jt,Kt),qt=function(...e){const t=wt(jt,_t,...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 Wt(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 Wt(e.slice(0,4))).getUint32(0),n=e.slice(4,t+4),r=await function(e){return new Promise(((t,n)=>{const r=new FileReader;r.onabort=e=>n(new Error("file read aborted")),r.onerror=e=>n(e.target.error),r.onload=e=>t(e.target.result),r.readAsText(e)}))}(e.slice(t+4));return await this.parse(r,n)}}}(Kt);class zt extends Error{constructor(e,t){super(t||`${e.status} ${e.statusText}`),this.httpStatus=e.status}get name(){return"HttpError"}}function Vt(t,n,r){const o=[];for(let s of r){const{table:r,muts:i}=s,a=t.tables.find((e=>e.name===r));if(!a)throw new Error(`Internal error: table ${r} not found in DBCore schema`);const{primaryKey:c}=a;let u=s;i.forEach(((t,r)=>{const o=!c.outbound&&("upsert"===t.type||"insert"===t.type);t.keys.forEach(((t,i)=>{if(Array.isArray(t)){u===s&&(u=Jt(s,o));const n=u.muts[r],a=JSON.stringify(t);n.keys[i]=a,o&&e.setByKeyPath(n.values[i],c.keyPath,a)}else if("#"===t[0]){u===s&&(u=Jt(s,o));const a=u.muts[r];if(!n.isLoggedIn)throw new Error("Internal error: Cannot sync private IDs before authenticated");const l=`${t}:${n.userId}`;a.keys[i]=l,o&&e.setByKeyPath(a.values[i],c.keyPath,l)}}))})),o.push(u)}return o}function Jt(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 Gt(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 bt(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:Vt(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:Ht.stringify(l)});if(r.syncStateChangedEvent.next({phase:"pulling"}),!d.ok)throw new zt(d);if("application/x-bison"===d.headers.get("content-type"))return qt.fromBinary(await d.blob());{const e=await d.text();return Ht.parse(e)}}function Yt(t){if(t?.cancelled)throw new e.AbortError("Operation was cancelled")}let Zt=navigator.onLine;async function Xt(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 Qt(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 en(n,r,o){const s=await n.bulkGet(r),i=[],a=[];r.forEach(((r,c)=>{const u=s[c];if(u){for(const[s,i]of Object.entries(o[c]))if(s===n.schema.primKey.keyPath){if(0!==t(i,r))throw new Error("Cannot change primary key")}else e.setByKeyPath(u,s,i);i.push(r),a.push(u)}})),await(null==n.schema.primKey.keyPath?n.bulkPut(a,i):n.bulkPut(a))}async function tn(t,n){console.debug("Applying server changes",t,e.currentTransaction);for(const{table:r,muts:o}of t){const t=n.table(r);if(!t)continue;const{primaryKey:s}=t.core.schema,i=e=>{switch(e[0]){case"[":if(e.endsWith("]"))try{return JSON.parse(e)}catch{}return e;case"#":return e.endsWith(":"+n.cloud.currentUserId)?e.substr(0,e.length-n.cloud.currentUserId.length-1):e;default:return e}};for(const n of o){const r=n.keys.map(i);switch(n.type){case"insert":s.outbound?await t.bulkAdd(n.values,r):(r.forEach(((t,r)=>{e.setByKeyPath(n.values[r],s.keyPath,t)})),await t.bulkAdd(n.values));break;case"upsert":s.outbound?await t.bulkPut(n.values,r):(r.forEach(((t,r)=>{e.setByKeyPath(n.values[r],s.keyPath,t)})),await t.bulkPut(n.values));break;case"modify":1===r.length?await t.update(r[0],n.changeSpec):await t.where(":id").anyOf(r).modify(n.changeSpec);break;case"update":await en(t,r,n.changeSpecs);break;case"delete":await t.bulkDelete(r)}}}}self.addEventListener("online",(()=>Zt=!0)),self.addEventListener("offline",(()=>Zt=!1));function nn(e,t,n,r){return rn.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:Zt,syncOptions:r,error:o}),Zt&&r?.retryImmediatelyOnFetchError&&"TypeError"===o?.name&&/fetch/.test(o?.message)?(e.syncStateChangedEvent.next({phase:"error",error:o}),await new Promise((e=>setTimeout(e,500))),await nn(e,t,n,{...r,retryImmediatelyOnFetchError:!1})):(await e.$syncState.update("syncState",{timestamp:new Date,error:""+o}),e.syncStateChangedEvent.next({phase:Zt?"error":"offline",error:o}),Promise.reject(o)))))}async function rn(e,t,n,{isInitialSync:r,cancelToken:o,justCheckIfNeeded:s,purpose:i}={isInitialSync:!1}){if(s||console.debug("SYNC STARTED",{isInitialSync:r,purpose:i}),!e.cloud.options?.databaseUrl)throw new Error("Internal error: sync must not be called when no databaseUrl is configured");const{databaseUrl:a}=t,c=await e.getCurrentUser(),u=c.isLoggedIn?Qe(e):[],l=u.map((t=>e.table(et(t.name)))),d=await e.getPersistedSyncState(),f=!r&&c.isLoggedIn?function(e,t){const n=t?.syncedTables||[];return Qe(e).filter((e=>!n.includes(e.name)))}(e,d):[];Yt(o);const p=f.length>0;if(p){if(s)return!0;await e.transaction("rw",f,(async e=>{e.idbtrans.disableChangeTracking=!0,e.idbtrans.disableAccessControl=!0,await async function(e,t,n){const r=new Set(n||[]);for(const n of e)"members"===n.name?await n.toCollection().modify((e=>{r.has(e.realmId)||e.userId&&e.userId!==b.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!==b.userId||(e.owner=t.userId)})):await n.toCollection().modify((e=>{e.realmId&&r.has(e.realmId)||(e.owner&&e.owner!==b.userId||(e.owner=t.userId),e.realmId&&e.realmId!==b.userId||(e.realmId=t.userId))})))}(f,c,d?.realms)})),Yt(o)}const[h,y,m]=await e.transaction("r",e.tables,(async()=>{const t=await e.getPersistedSyncState(),r=await e.$baseRevs.toArray();let s=await rt(l);if(Yt(o),p){const e=[...d?.realms||[],...d?.inviteRealms||[]],i=await async function(e,t,n,r){const o=`upload-${ot(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||"")&&ct(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[]}(f,c,n,e);return Yt(o),s=s.concat(i),[s,t,r]}return[s,t,r]})),v=h.some((e=>e.muts.some((e=>e.keys.length>0))));if(s)return console.debug("Sync is needed:",v),v;if("push"===i&&!v)return!1;const g=Qt(h,y?.latestRevisions),w=y?.clientIdentity||at(16);Yt(o);const _=await Gt(h,y,m,e,a,n,w,c);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 rt(l,0,{since:g});for(const t of l){const n=tt(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()])}Qt(r,g),await Xt(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=Qe(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=u.map((e=>e.name)).concat(f.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=on(_.changes,r);return await tn(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 rn(e,t,n,{isInitialSync:r,cancelToken:o}))}function on(e,t){const n={};dt(n,e);const r={};return dt(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))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=at(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 sn(t){const n=[],r=new o(!0),s=new o(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()),r.next(!1);try{await async function(){for(;n.length>0;){const r=n.shift();try{await t.cloud.syncState.pipe(Be((({phase:e})=>"in-sync"===e||"error"===e)),Le(1)).toPromise(),console.debug("processing msg",r);const n=t.cloud.persistedSyncState.value;if(!r)continue;switch(r.type){case"token-expired":console.debug("WebSocket observable: Token expired. Refreshing token...");const o=t.cloud.currentUser.value,s=await bt(t.cloud.options.databaseUrl,o);await t.table("$logins").update(o.userId,{accessToken:s.accessToken,accessTokenExpiration:s.accessTokenExpiration});break;case"realm-added":case"realm-accepted":case"realms-changed":Ge(t,"pull");break;case"realm-removed":n?.realms?.includes(r.realm)||n?.inviteRealms?.includes(r.realm),Ge(t,"pull");break;case"changes":if(console.debug("changes"),"error"===t.cloud.syncState.value?.phase){Ge(t,"pull");break}await t.transaction("rw",t.dx.tables,(async n=>{n.idbtrans.disableChangeTracking=!0,n.idbtrans.disableAccessControl=!0;const[o,s,i]=await Promise.all([t.getSchema(),t.getPersistedSyncState(),t.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(r.baseRev!==s.serverRevision)return console.debug(`baseRev (${r.baseRev}) differs from our serverRevision in syncState (${s.serverRevision})`),void("string"!=typeof r.baseRev||"bigint"!=typeof s.serverRevision&&"object"!=typeof s.serverRevision||Ge(t,"pull"));const a=await e.waitFor(Xe(s));if(console.debug("ourRealmSetHash",a),a!==r.realmSetHash)return console.debug("not same realmSetHash",r.realmSetHash),void Ge(t,"pull");let c=[];if(i.isLoggedIn){const e=Qe(t).map((e=>t.table(et(e.name))));c=await rt(e),console.debug("msg queue: client changes",c)}if(r.changes.length>0){const e=on(r.changes,c);console.debug("applying filtered server changes",e),await tn(e,t)}s.latestRevisions=Qt(c,s.latestRevisions),s.serverRevision=r.newRev,console.debug("Updating baseRefs",s.latestRevisions),await Xt(t,o,s.latestRevisions,r.newRev),console.debug("Updating syncState",s),await t.$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,r.next(!0)}}})),{enqueue:function(e){n.push(e),s.next(null)},readyToServe:r}}const an=new WeakMap,cn={members:"@id, [userId+realmId], [email+realmId], realmId",roles:"[realmId+name]",realms:"@realmId",$jobs:"",$syncState:"",$baseRevs:"[tableName+clientRev]",$logins:"claims.sub, lastLogin"};let un=0;function ln(e){"vip"in e&&(e=e.vip);let t=an.get(e.cloud);if(!t){const n=new s;let r=new _(`syncstatechanged-${e.name}`);n.id=++un;let o=!1;t={get name(){return e.name},close:()=>e.close(),transaction:e.transaction.bind(e),table:e.table.bind(e),get tables(){return e.tables},cloud:e.cloud,get $jobs(){return e.table("$jobs")},get $syncState(){return e.table("$syncState")},get $baseRevs(){return e.table("$baseRevs")},get $logins(){return e.table("$logins")},get realms(){return e.realms},get members(){return e.members},get roles(){return e.roles},get initiallySynced(){return o},localSyncEvent:n,get syncStateChangedEvent(){return r},dx:e};const i={getCurrentUser:()=>t.$logins.toArray().then((e=>e.find((e=>e.isLoggedIn))||b)),getPersistedSyncState:()=>t.$syncState.get("syncState"),getSchema:()=>t.$syncState.get("schema"),getOptions:()=>t.$syncState.get("options"),setInitiallySynced(e){o=e},reconfigure(){r=new _(`syncstatechanged-${e.name}`)}};Object.assign(t,i),t.messageConsumer=sn(t),an.set(e.cloud,t)}return t}const dn=new WeakMap;class fn{constructor(e,t){dn.set(this,e),Object.assign(this,t)}static load(e,t){return e.table("$logins").get(t).then((n=>new fn(e,n||{userId:t,claims:{sub:t},lastLogin:new Date(0)})))}async save(){dn.get(this).table("$logins").put(this)}}async function pn(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 fn(e,{claims:{},lastLogin:new Date(0)});await mt(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 ht(t,"Enter a demo user email",r?.email||r?.userId),grant_type:"demo",scopes:["ACCESS_DB"],public_key:n}:{email:await ht(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 pt(t,"Token request failed",{type:"error",messageCode:"GENERIC_ERROR",message:e,messageParams:{}}).catch((()=>{})),new zt(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 yt(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 yt(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 pt(t,"OTP Authentication Failed",{type:"error",messageCode:"GENERIC_ERROR",message:e,messageParams:{}}).catch((()=>{})),new zt(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),Ge(e,"pull")}const hn="undefined"!=typeof InstallTrigger,yn="undefined"!=typeof navigator&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\/|Edge\//.test(navigator.userAgent),mn=yn?[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]:NaN,bn=yn&&mn<=605||hn;const vn="undefined"!=typeof self&&"clients"in self&&!self.document;function gn(){throw new e.SchemaError("Version increment needed to allow dexie-cloud change tracking")}const{toString:wn}={};function _n(e){return wn.call(e).slice(8,-1)}function Sn(e,t){return"delete"===t.type?t.keys:t.keys?.slice()||t.values.map(e.extractKey)}const kn=/b|c|d|f|g|h|j|k|l|m|n|p|q|r|s|t|v|x|y|z/i;let xn=0;function En(e,t){const n=new Uint8Array(18),r=new Uint8Array(n.buffer,0,6),o=Date.now();xn>=o?++xn:xn=o,r[0]=xn/1099511627776,r[1]=xn/4294967296,r[2]=xn/16777216,r[3]=xn/65536,r[4]=xn/256,r[5]=xn;const s=new Uint8Array(n.buffer,6);crypto.getRandomValues(s);return e+Tt(new Uint8Array(n.buffer))+(t||"")}function In(t){return{stack:"dbcore",name:"idGenerationMiddleware",level:1,create:n=>({...n,table:r=>{const o=n.table(r);return{...o,mutate:n=>{if(n.trans.disableChangeTracking)return o.mutate(n);if("add"===n.type||"put"===n.type){const s=t.cloud.schema?.[r];if(s?.generatedGlobalId){if(t.cloud.options?.databaseUrl&&!t.initiallySynced){const e=Sn(o.schema.primaryKey,n);return o.getMany({keys:e,trans:n.trans,cache:"immutable"}).then((t=>{if(t.length<e.length)throw new Error("Unable to create new objects without an initial sync having been performed.");return o.mutate(n)}))}return function(n,s){let i=null;const a=Sn(o.schema.primaryKey,n);return a.forEach(((c,u)=>{if(void 0===c){const r=n.values[u].realmId||t.cloud.currentUserId,c=r.substr(r.length-3);a[u]=En(s,c),o.schema.primaryKey.outbound||(i||(i=n.values.slice()),i[u]=e.deepClone(i[u]),e.setByKeyPath(i[u],o.schema.primaryKey.keyPath,a[u]))}else if("string"!=typeof c||!c.startsWith(s)&&!c.startsWith("#"+s))throw new e.ConstraintError(`The ID "${c}" is not valid for table "${r}". Primary '@' keys requires the key to be prefixed with "${s}" (or "#${s}).\nIf you want to generate IDs programmatically, remove '@' from the schema to get rid of this constraint. Dexie Cloud supports custom IDs as long as they are random and globally unique.`)})),o.mutate({...n,keys:a,values:i||n.values})}(n,s.idPrefix)}if(s?.markedForSync){Sn(o.schema.primaryKey,n).forEach(((t,n)=>{if(!ct(t)){const n=Array.isArray(t)?t.map(_n).join(","):_n(t);throw new e.ConstraintError(`Invalid primary key type ${n} for table ${r}. Tables marked for sync has primary keys of type string or Array of string (and optional numbers)`)}}))}}return o.mutate(n)}}}})}}let Cn=0;function An(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 Tn(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 Pn=new o(new Set);function Un({currentUserObservable:e,db:t}){return{stack:"dbcore",name:"MutationTrackingMiddleware",level:1,create:n=>{const r=n.schema.tables.filter((e=>!/^\$/.test(e.name)));let o;try{o=new Map(r.map((e=>[e.name,n.table(`$${e.name}_mutations`)])))}catch{gn()}return{...n,transaction:(r,o)=>{let s;if("readwrite"===o){const e=r.filter((e=>t.cloud.schema?.[e]?.markedForSync)).map((e=>et(e)));s=n.transaction([...r,...e],o)}else s=n.transaction(r,o);if("readwrite"===o){s.txid=ot(16),s.currentUser=e.value,Pn.value.add(s),Pn.next(Pn.value);const n=()=>{s.removeEventListener("complete",r),s.removeEventListener("error",n),s.removeEventListener("abort",n),Pn.value.delete(s),Pn.next(Pn.value)},r=()=>{s.mutationsAdded&&t.cloud.options?.databaseUrl&&(t.cloud.usingServiceWorker?(console.debug("registering sync event"),Je(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"+ ++Cn;return{...e,count:An(e.count,t),get:An(e.get,t),getMany:An(e.getMany,t),openCursor:An(e.openCursor,t),query:An(e.query,t),mutate:Tn(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 $n(e,t){return function(n,r){const o={...cn,...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)(kn.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 Dn=ot(16);async function On(e,t,r,o,{awaitRemoteJob:s}={}){const a=e.table(r);if(await async function o(){if(await e.transaction("rw!",r,(async()=>{const e=await a.get(t);return e?e.heartbeat.getTime()<Date.now()-6e4&&(console.warn(`Latest ${t} 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:Dn,started:new Date,heartbeat:new Date},t),!0):(await a.add({nodeId:Dn,started:new Date,heartbeat:new Date},t),!0)})))return!0;if(s)try{const e=i(n((()=>a.get(t)))).pipe(function(e,t){var n=_e(e)?{first:e}:"number"==typeof e?{each:e}:e,r=n.first,o=n.each,s=n.with,i=void 0===s?ze:s,a=n.scheduler,c=void 0===a?null!=t?t:ve:a,u=n.meta,l=void 0===u?null:u;if(null==r&&null==o)throw new TypeError("No timeout provided.");return k((function(e,t){var n,s,a=null,u=0,d=function(e){s=ke(t,c,(function(){try{n.unsubscribe(),ue(i({meta:l,lastValue:a,seen:u})).subscribe(t)}catch(e){t.error(e)}}),e)};n=e.subscribe(new de(t,(function(e){null==s||s.unsubscribe(),u++,t.next(a=e),o>0&&d(o)}),void 0,void 0,(function(){(null==s?void 0:s.closed)||null==s||s.unsubscribe(),a=null}))),d(null!=r?"number"==typeof r?r:+r-c.now():o)}))}(6e4),Be((e=>!e)));return await e.toPromise(),!1}catch(e){if("TimeoutError"!==e.name)throw e;return await o()}return!1}()){const n=setInterval((()=>{a.update(t,(e=>{e.nodeId===Dn&&(e.heartbeat=new Date)}))}),1e3);try{return await o()}finally{clearInterval(n),await e.transaction("rw!",r,(async()=>{const e=await a.get(t);e&&e.nodeId===Dn&&a.delete(t)}))}}}const Rn=new o(!0),Ln=new o(!0);var Nn,jn;Rn.pipe(Ke((e=>e?c(!0):c(!1).pipe(je(2e4)))),(void 0===jn&&(jn=X),Nn=null!=Nn?Nn:We,k((function(e,t){var n,r=!0;e.subscribe(new de(t,(function(e){var o=jn(e);!r&&Nn(n,o)||(r=!1,n=o,t.next(e))})))})))).subscribe(Ln);const Wn="undefined"!=typeof document?a(document,"visibilitychange"):c({}),Bn=Wn.pipe(Be((()=>"hidden"===document.visibilityState))),Mn=Wn.pipe(Be((()=>"visible"===document.visibilityState))),Fn="undefined"!=typeof window?u(Mn,a(window,"mousemove"),a(window,"keydown"),a(window,"wheel"),a(window,"touchmove")):c({});"undefined"!=typeof document&&u(c(!0),Bn,Fn).pipe(Pe((()=>"visible"===document.visibilityState)),He((e=>{Rn.value!==e&&Rn.next(e)})),Ke((e=>e?c(0).pipe(je(28e4),He((()=>Rn.next(!1)))):c(0)))).subscribe((()=>{}));class Kn extends Error{constructor(){super(...arguments),this.name="TokenExpiredError"}}class Hn extends r{constructor(e,t,n,r,o,s,i,a){super((c=>new zn(e,t,n,r,i,a,c,o,s)))}}let qn=0;class zn extends l{constructor(e,t,n,r,o,s,i,a,c){super((()=>this.teardown())),this.id=++qn,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 Kn);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=Ht.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(Ht.stringify(e)))}))}catch(e){this.pauseUntil=new Date(Date.now()+6e4)}}}async function Vn(e){var t;console.error("WebSocket observable: error but revive when user does some active thing...",e),await(t=3e3,new Promise((e=>setTimeout(e,t)))),console.debug("waiting for someone to do something"),await Fn.pipe(Le(1)).toPromise(),console.debug("someone did something!")}async function Jn(e){return!(!e.cloud.options?.databaseUrl||!e.cloud.schema)&&await nn(e,e.cloud.options,e.cloud.schema,{justCheckIfNeeded:!0})}const Gn=new WeakMap;function Yn(e,t,n,r){const o=Gn.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 Yn(e,t,n,r)}))}}const s=async function(){try{e.cloud.usingServiceWorker?vn&&await nn(e,t,n,r):await On(e,"currentSyncWorker","$jobs",(()=>nn(e,t,n,r))),Gn.delete(e),console.debug("Done sync")}catch(t){throw Gn.delete(e),console.error("Failed to sync client changes",t),t}}();return Gn.set(e,{promise:s,pull:"push"!==r?.purpose}),s}function Zn(e,t,n){let r=null,o={cancelled:!1};function s(r,a=1){setTimeout((()=>{Yn(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 Xn(e,t){if(e&&t&&t.unsyncedTables)for(const n of t.unsyncedTables)e[n]&&(e[n].markedForSync=!1)}var Qn,er,tr,nr,rr={},or=[],sr=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i;function ir(e,t){for(var n in t)e[n]=t[n];return e}function ar(e){var t=e.parentNode;t&&t.removeChild(e)}function cr(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 ur(e,a,r,o,null)}function ur(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?++Qn.__v:o};return null!=Qn.vnode&&Qn.vnode(s),s}function lr(e){return e.children}function dr(e,t){this.props=e,this.context=t}function fr(e,t){if(null==t)return e.__?fr(e.__,e.__.__k.indexOf(e)+1):null;for(var n;t<e.__k.length;t++)if(null!=(n=e.__k[t])&&null!=n.__e)return n.__e;return"function"==typeof e.type?fr(e):null}function pr(e){var t,n;if(null!=(e=e.__)&&null!=e.__c){for(e.__e=e.__c.base=null,t=0;t<e.__k.length;t++)if(null!=(n=e.__k[t])&&null!=n.__e){e.__e=e.__c.base=n.__e;break}return pr(e)}}function hr(e){(!e.__d&&(e.__d=!0)&&er.push(e)&&!yr.__r++||nr!==Qn.debounceRendering)&&((nr=Qn.debounceRendering)||tr)(yr)}function yr(){for(var e;yr.__r=er.length;)e=er.sort((function(e,t){return e.__v.__b-t.__v.__b})),er=[],e.some((function(e){var t,n,r,o,s,i;e.__d&&(s=(o=(t=e).__v).__e,(i=t.__P)&&(n=[],(r=ir({},o)).__v=o.__v+1,kr(i,o,r,t.__n,void 0!==i.ownerSVGElement,null!=o.__h?[s]:null,n,null==s?fr(o):s,o.__h),xr(n,o),o.__e!=s&&pr(o)))}))}function mr(e,t,n,r,o,s,i,a,c,u){var l,d,f,p,h,y,m,b=r&&r.__k||or,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?ur(null,p,null,null,p):Array.isArray(p)?ur(lr,{children:p},null,null,null):p.__b>0?ur(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}kr(e,p,f=f||rr,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=br(p,c,e):c=vr(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=fr(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=fr(r,l+1)),Cr(b[l],b[l]));if(m)for(l=0;l<m.length;l++)Ir(m[l],m[++l],m[++l])}function br(e,t,n){var r,o;for(r=0;r<e.__k.length;r++)(o=e.__k[r])&&(o.__=e,t="function"==typeof o.type?br(o,t,n):vr(n,o,o,e.__k,o.__e,t));return t}function vr(e,t,n,r,o,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 gr(e,t,n){"-"===t[0]?e.setProperty(t,n):e[t]=null==n?"":"number"!=typeof n||sr.test(t)?n:n+"px"}function wr(e,t,n,r,o){var 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||gr(e.style,t,"");if(n)for(t in n)r&&n[t]===r[t]||gr(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?Sr:_r,s):e.removeEventListener(t,s?Sr:_r,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 _r(e){this.l[e.type+!1](Qn.event?Qn.event(e):e)}function Sr(e){this.l[e.type+!0](Qn.event?Qn.event(e):e)}function kr(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=Qn.__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 dr(m,v),l.constructor=w,l.render=Ar),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=ir({},l.__s)),ir(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=Qn.__r)&&u(t),l.__d=!1,l.__v=t,l.__P=e,u=l.render(l.props,l.state,l.context),l.state=l.__s,null!=l.getChildContext&&(r=ir(ir({},r),l.getChildContext())),d||null==l.getSnapshotBeforeUpdate||(h=l.getSnapshotBeforeUpdate(f,p)),g=null!=u&&u.type===lr&&null==u.key?u.props.children:u,mr(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=Er(n.__e,t,n,r,o,s,i,c);(u=Qn.diffed)&&u(t)}catch(e){t.__v=null,(c||null!=s)&&(t.__e=a,t.__h=!!c,s[s.indexOf(a)]=null),Qn.__e(e,t,n)}}function xr(e,t){Qn.__c&&Qn.__c(t,e),e.some((function(t){try{e=t.__h,t.__h=[],e.some((function(e){e.call(t)}))}catch(e){Qn.__e(e,t.__v)}}))}function Er(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&&or.slice.call(e.childNodes),u=(f=n.props||rr).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||wr(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]||wr(e,s,t[s],n[s],r)}(e,p,f,o,a),l)t.__k=[];else if(y=t.props.children,mr(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]&&ar(s[y]);a||("value"in p&&void 0!==(y=p.value)&&(y!==e.value||"progress"===h&&!y)&&wr(e,"value",y,f.value,!1),"checked"in p&&void 0!==(y=p.checked)&&y!==e.checked&&wr(e,"checked",y,f.checked,!1))}return e}function Ir(e,t,n){try{"function"==typeof e?e(t):e.current=t}catch(e){Qn.__e(e,n)}}function Cr(e,t,n){var r,o,s;if(Qn.unmount&&Qn.unmount(e),(r=e.ref)&&(r.current&&r.current!==e.__e||Ir(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){Qn.__e(e,t)}r.base=r.__P=null}if(r=e.__k)for(s=0;s<r.length;s++)r[s]&&Cr(r[s],t,n);null!=o&&ar(o)}function Ar(e,t,n){return this.constructor(e,n)}Qn={__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},dr.prototype.setState=function(e,t){var n;n=null!=this.__s&&this.__s!==this.state?this.__s:this.__s=ir({},this.state),"function"==typeof e&&(e=e(ir({},n),this.props)),e&&ir(n,e),null!=e&&this.__v&&(t&&this.__h.push(t),hr(this))},dr.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),hr(this))},dr.prototype.render=lr,er=[],tr="function"==typeof Promise?Promise.prototype.then.bind(Promise.resolve()):setTimeout,yr.__r=0;const Tr={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 Pr({children:e}){return cr("div",null,cr("div",{style:Tr.Darken}),cr("div",{style:Tr.DialogOuter},cr("div",{style:Tr.DialogInner},e)))}var Ur,$r,Dr,Or=0,Rr=[],Lr=Qn.__b,Nr=Qn.__r,jr=Qn.diffed,Wr=Qn.__c,Br=Qn.unmount;function Mr(e,t){Qn.__h&&Qn.__h($r,e,Or||t),Or=0;var n=$r.__H||($r.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function Fr(e){return Or=1,function(e,t,n){var r=Mr(Ur++,2);return r.t=e,r.__c||(r.__=[n?n(t):Gr(void 0,t),function(e){var t=r.t(r.__[0],e);r.__[0]!==t&&(r.__=[t,r.__[1]],r.__c.setState({}))}],r.__c=$r),r.__}(Gr,e)}function Kr(e){return Or=5,function(e,t){var n=Mr(Ur++,7);return Jr(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}((function(){return{current:e}}),[])}function Hr(){Rr.forEach((function(e){if(e.__P)try{e.__H.__h.forEach(zr),e.__H.__h.forEach(Vr),e.__H.__h=[]}catch(t){e.__H.__h=[],Qn.__e(t,e.__v)}})),Rr=[]}Qn.__b=function(e){$r=null,Lr&&Lr(e)},Qn.__r=function(e){Nr&&Nr(e),Ur=0;var t=($r=e.__c).__H;t&&(t.__h.forEach(zr),t.__h.forEach(Vr),t.__h=[])},Qn.diffed=function(e){jr&&jr(e);var t=e.__c;t&&t.__H&&t.__H.__h.length&&(1!==Rr.push(t)&&Dr===Qn.requestAnimationFrame||((Dr=Qn.requestAnimationFrame)||function(e){var t,n=function(){clearTimeout(r),qr&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,100);qr&&(t=requestAnimationFrame(n))})(Hr)),$r=void 0},Qn.__c=function(e,t){t.some((function(e){try{e.__h.forEach(zr),e.__h=e.__h.filter((function(e){return!e.__||Vr(e)}))}catch(n){t.some((function(e){e.__h&&(e.__h=[])})),t=[],Qn.__e(n,e.__v)}})),Wr&&Wr(e,t)},Qn.unmount=function(e){Br&&Br(e);var t=e.__c;if(t&&t.__H)try{t.__H.__.forEach(zr)}catch(e){Qn.__e(e,t.__v)}};var qr="function"==typeof requestAnimationFrame;function zr(e){var t=$r;"function"==typeof e.__c&&e.__c(),$r=t}function Vr(e){var t=$r;e.__c=e.__(),$r=t}function Jr(e,t){return!e||e.length!==t.length||t.some((function(t,n){return t!==e[n]}))}function Gr(e,t){return"function"==typeof t?t(e):t}function Yr({title:e,alerts:t,fields:n,onCancel:r,onSubmit:o}){const[s,i]=Fr({}),a=Kr();return function(e,t){var n=Mr(Ur++,4);!Qn.__s&&Jr(n.__H,t)&&(n.__=e,n.__H=t,$r.__h.push(n))}((()=>a.current?.focus()),[]),cr(Pr,null,cr(lr,null,cr("h3",{style:Tr.WindowHeader},e),t.map((e=>cr("p",{style:Tr.Alert[e.type]},function({message:e,messageCode:t,messageParams:n}){return e.replace(/\{\w+\}/gi,(e=>n[e.substr(1,e.length-2)]))}(e)))),cr("form",{onSubmit:e=>{e.preventDefault(),o(s)}},Object.entries(n).map((([e,{type:t,label:n,placeholder:r}],o)=>cr("label",{style:Tr.Label},n?`${n}: `:"",cr("input",{ref:0===o?a:void 0,type:t,name:e,autoComplete:"on",style:Tr.Input,autoFocus:!0,placeholder:r,value:s[e]||"",onInput:n=>i({...s,[e]:Zr(t,n.target?.value)})})))))),cr("div",{style:Tr.ButtonsDiv},cr("button",{type:"submit",style:Tr.Button,onClick:()=>o(s)},"Submit"),cr("button",{style:Tr.Button,onClick:r},"Cancel")))}function Zr(e,t){switch(e){case"email":return t.toLowerCase();case"otp":return t.toUpperCase();default:return t}}class Xr extends dr{constructor(e){super(e),this.observer=e=>this.setState({userInteraction:e}),this.state={userInteraction:void 0}}componentDidMount(){this.subscription=i(this.props.db.cloud.userInteraction).subscribe(this.observer)}componentWillUnmount(){this.subscription&&(this.subscription.unsubscribe(),delete this.subscription)}render(e,{userInteraction:t}){return t?cr(Yr,{...t}):null}}function Qr(e){const t=document.createElement("div");document.body.appendChild(t),function(e,t,n){var r,o,s;Qn.__&&Qn.__(e,t),o=(r="function"==typeof n)?null:n&&n.__k||t.__k,s=[],kr(t,e=(!r&&n||t).__k=cr(lr,null,[e]),o||rr,rr,void 0!==t.ownerSVGElement,!r&&n?[n]:o?null:t.firstChild?or.slice.call(t.childNodes):null,s,!r&&n?n:o?o.__e:t.firstChild,r),xr(s,e)}(cr(Xr,{db:e.vip}),t);let n=!1;return{unsubscribe(){t.remove(),n=!0},get closed(){return n}}}function eo(e){const t=new WeakMap;return n=>{let r=t.get(n);return r||(r=e(n),t.set(n,r)),r}}function to(e,t){let n=t,o=i(e).pipe(p((e=>n=e)),h({resetOnRefCountZero:()=>y(1e3)}));const s=new r((e=>{let t=!1;const r=o.subscribe({next(n){t=!0,e.next(n)},error(t){e.error(t)},complete(){e.complete()}});return t||r.closed||e.next(n),r}));return s.getValue=()=>n,s}const no=eo((e=>new o(b))),ro=eo((e=>to(no(e._novip).pipe(Ke((t=>n((()=>e.transaction("r","realms","members",(()=>Promise.all([e.members.where({userId:t.userId}).toArray(),e.realms.toArray(),t.userId]).then((([e,t,n])=>({selfMembers:e,realms:t,userId:n})))))))))),{selfMembers:[],realms:[],get userId(){return e.cloud.currentUserId}})));function oo(...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 so=eo((e=>function(e,t){let n;const r=e.pipe(p((e=>n=t(e))));return r.getValue=()=>void 0!==n?n:n=t(e.getValue()),r}(ro(e._novip),(({selfMembers:e,realms:t,userId:n})=>{const r=t.map((t=>({...t,permissions:t.owner===n?{manage:"*"}:oo(...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 io{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 ao=eo((e=>{const t=no(e._novip).pipe(m((t=>n((()=>e.members.where({email:t.email||""}).toArray()))))),r=so(e._novip),o=ro(e._novip);return to(f([t,o,r]).pipe(p((([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))}))),[])})),co={nameSuffix:!0};function uo(t){const r=t.name,s=no(t),u=[];let l=null;t.on("ready",(async t=>{try{await async function(t){p=!1;const r=ln(t);vn||(r.cloud.options?.customLoginGui||u.push(Qr(t)),u.push(function(e){let t=e.cloud.webSocketStatus.value;const n=e.cloud.webSocketStatus.pipe(Ke((e=>{const n=t;t=e;const r=c(e);switch(e){case"disconnected":return Rn.value?r.pipe(De(500)):r;case"connecting":return"not-started"===n||"error"===n?r:r.pipe(De(4e3));default:return r}})));return f([n,e.syncStateChangedEvent.pipe(Fe({phase:"initial"})),Ln]).pipe(Pe((([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:Zt?a:"offline"}})))}(r).subscribe(t.cloud.syncState)));r.tables.every((e=>e.core))||gn();const o="serviceWorker"in navigator?await navigator.serviceWorker.getRegistrations():[],y=await r.transaction("rw",r.$syncState,(async()=>{const{options:e,schema:t}=r.cloud,[n,s,i]=await Promise.all([r.getOptions(),r.getSchema(),r.getPersistedSyncState()]);if(e?n&&JSON.stringify(n)===JSON.stringify(e)||await r.$syncState.put(e,"options"):r.cloud.options=n||null,r.cloud.options?.tryUseServiceWorker&&"serviceWorker"in navigator&&o.length>0&&!bn?(console.debug("Dexie Cloud Addon: Using service worker"),r.cloud.usingServiceWorker=!0):(r.cloud.options?.tryUseServiceWorker&&!vn&&console.debug("dexie-cloud-addon: Not using service worker.",0===o.length?"No SW registrations found.":"serviceWorker"in navigator&&bn?"Avoiding SW background sync and SW periodic bg sync for this browser due to browser bugs.":"navigator.serviceWorker not present"),r.cloud.usingServiceWorker=!1),Xn(t,r.cloud.options),Xn(s,r.cloud.options),t){if(!s||JSON.stringify(s)!==JSON.stringify(t)){const e=s||{};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 r.$syncState.put(e,"schema"),Object.assign(t,e)}}else r.cloud.schema=s||null;return i?.initiallySynced}));y&&r.setInitiallySynced(!0);(function(t){for(const n of t.tables)if(t.cloud.schema?.[n.name]?.markedForSync){if(n.schema.primKey.auto)throw new e.SchemaError(`Table ${n.name} is both autoIncremented and synced. Use db.cloud.configure({unsyncedTables: [${JSON.stringify(n.name)}]}) to blacklist it from sync`);if(!n.schema.primKey.keyPath)throw new e.SchemaError(`Table ${n.name} cannot be both synced and outbound. Use db.cloud.configure({unsyncedTables: [${JSON.stringify(n.name)}]}) to blacklist it from sync`)}})(r),r.cloud.options?.databaseUrl&&!y&&(await async function(e,t,n){console.debug("Performing initial sync"),await On(e,"initialSync","$jobs",(async()=>{(await e.getPersistedSyncState())?.initiallySynced||await nn(e,t,n,{isInitialSync:!0})}),{awaitRemoteJob:!0}),console.debug("Done initial sync")}(r,r.cloud.options,r.cloud.schema),r.setInitiallySynced(!0));h(),vn||(u.push(n((()=>r.getCurrentUser())).subscribe(s)),u.push(n((()=>r.getPersistedSyncState())).subscribe(r.cloud.persistedSyncState)),await f([s.pipe(Me(1),Le(1)),r.cloud.persistedSyncState.pipe(Me(1),Le(1))]).toPromise());r.cloud.options?.requireAuth&&await pn(r);l&&l.stop();l=null,h(),r.cloud.usingServiceWorker&&r.cloud.options?.databaseUrl?(Je(r,"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)}}(r).catch((()=>{}))):r.cloud.options?.databaseUrl&&r.cloud.schema&&!vn&&(l=Zn(r,r.cloud.options,r.cloud.schema),l.start(),Ge(r,"push"));h(),vn||u.push(a(self,"online").subscribe((()=>{console.debug("online!"),r.syncStateChangedEvent.next({phase:"not-in-sync"}),Ge(r,"push")})),a(self,"offline").subscribe((()=>{console.debug("offline!"),r.syncStateChangedEvent.next({phase:"offline"})})));"undefined"!=typeof window&&!vn&&r.cloud.options?.databaseUrl&&u.push(function(e){if(!e.cloud.options?.databaseUrl)throw new Error("No database URL to connect WebSocket to");const t=e.messageConsumer.readyToServe.pipe(Be((e=>e)),Ke((()=>e.getPersistedSyncState())),Be((e=>e&&e.serverRevision)),Pe((e=>({type:"ready",rev:e.serverRevision}))));return function n(){return e.cloud.persistedSyncState.pipe(Be((e=>e?.serverRevision)),Le(1),Ke((t=>e.cloud.currentUser.pipe(Pe((e=>[e,t]))))),Ke((([e,t])=>Ln.pipe(Pe((n=>[n?e:null,t]))))),Ke((async([e,t])=>[e,await Xe(t)])),Ke((([n,r])=>n?new Hn(e.cloud.options.databaseUrl,e.cloud.persistedSyncState.value.serverRevision,r,e.cloud.persistedSyncState.value.clientIdentity,t,e.cloud.webSocketStatus,n.accessToken,n.accessTokenExpiration):i([]))),xe((t=>"TokenExpiredError"===t?.name?(console.debug("WebSocket observable: Token expired. Refreshing token..."),c(!0).pipe(Ke((async()=>{const t=await e.getCurrentUser(),n=await bt(e.cloud.options.databaseUrl,t);await e.table("$logins").update(t.userId,{accessToken:n.accessToken,accessTokenExpiration:n.accessTokenExpiration})})),Ke((()=>n())))):d(t))),xe((e=>i(Vn(e)).pipe(Ke((()=>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!")}))}(r))}(t)}catch(e){console.error(e)}}),!0);let p=!1;function h(){if(p)throw new e.DatabaseClosedError}var y;!function(e,t){e.on.close.subscribe(t);const n=e.close;e.close=function(){n.call(this),t()}}(t,(()=>{u.forEach((e=>e.unsubscribe())),p=!0,l&&l.stop(),l=null,s.next(b)})),t.cloud={version:"4.0.0-beta.13",options:{...co},schema:null,serverState:null,get currentUserId(){return s.value.userId||b.userId},currentUser:s,syncState:new o({phase:"initial",status:"not-started"}),persistedSyncState:new o(void 0),userInteraction:new o(void 0),webSocketStatus:new o("not-started"),async login(e){const n=ln(t);await n.cloud.sync(),await pn(n,e)},invites:ao(t),configure(e){(e=t.cloud.options={...t.cloud.options,...e}).databaseUrl&&e.nameSuffix&&(t.name=`${r}-${function(e){const t=new URL(e);return"/"===t.pathname?t.hostname.split(".")[0]:t.pathname.split("/")[1]}(e.databaseUrl)}`,ln(t).reconfigure()),Xn(t.cloud.schema,t.cloud.options)},async sync({wait:e,purpose:r}={wait:!0,purpose:"push"}){void 0===e&&(e=!0);const o=ln(t);if("pull"===r){const t=o.cloud.persistedSyncState.value;if(Ge(o,r),e){const e=await o.cloud.persistedSyncState.pipe(Be((e=>null!=e?.timestamp&&(!t||e.timestamp>t.timestamp))),Le(1)).toPromise();if(e?.error)throw new Error("Sync error: "+e.error)}}else if(await Jn(o)){const t=o.cloud.persistedSyncState.value;Ge(o,r),e&&(console.debug("db.cloud.login() is waiting for sync completion..."),await i(n((async()=>{const e=await Jn(o),n=await o.getPersistedSyncState();if(n?.timestamp!==t?.timestamp&&n?.error)throw new Error("Sync error: "+n.error);return e}))).pipe(Be((e=>!e)),Le(1)).toPromise(),console.debug("Done waiting for sync completion because we have nothing to push anymore"))}},permissions:(e,n)=>function(e,t,n){if(!t)throw new TypeError("Cannot check permissions of undefined or null. A Dexie Cloud object with realmId and owner expected.");const{owner:r,realmId: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=so(e),i=t=>{const s=t[o||e.cloud.currentUserId];return new io(s?s.permissions:{},n,!r||r===e.cloud.currentUserId)},a=s.pipe(Pe(i));return a.getValue=()=>i(s.getValue()),a}(t._novip,e,n)},t.Version.prototype._parseStoresSpec=e.override(t.Version.prototype._parseStoresSpec,(e=>$n(e,t))),t.Table.prototype.newId=function({colocateWith:e}={}){const n=e&&e.substr(e.length-3);return En(t.cloud.schema[this.name].idPrefix||"",n)},t.Table.prototype.idPrefix=function(){return this.db.cloud.schema?.[this.name]?.idPrefix||""},t.use(Un({currentUserObservable:t.cloud.currentUser,db:ln(t)})),t.use((y=ln(t),{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(y.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)}}}})})),t.use(In(ln(t)))}uo.version="4.0.0-beta.13",e.Cloud=uo;const lo=new Map;function fo(e){return e.startsWith("dexie-cloud:")&&e.split(":")[1]}const po=new Map;function ho(t,n){let r=po.get(t+"/"+n);return r||(r=async function(t,n){let r=lo.get(t);if(!r){console.debug("Dexie Cloud SW: Creating new Dexie instance for",t);const n=new e(t,{addons:[uo]});r=ln(n),n.on("versionchange",o),await r.dx.open(),lo.get(t)||lo.set(t,r)}if(!r.cloud.options?.databaseUrl)return void console.error("Dexie Cloud: No databaseUrl configured");if(!r.cloud.schema)return void console.error("Dexie Cloud: No schema persisted");function o(){return r.dx.on.versionchange.unsubscribe(o),lo.get(r.name)===r&&lo.delete(r.name),console.debug(`Dexie Cloud SW: Closing Dexie instance for ${t}`),r.dx.close(),!1}try{console.debug("Dexie Cloud SW: Syncing"),await Yn(r,r.cloud.options,r.cloud.schema,{retryImmediatelyOnFetchError:!0,purpose:n}),console.debug("Dexie Cloud SW: Done Syncing")}catch(t){if(console.error("Dexie Cloud SW Error",t),o(),t.name!==e.errnames.NoSuchDatabase)throw t}}(t,n).then((()=>{po.delete(t+"/"+n)})).catch((e=>(po.delete(t+"/"+n),Promise.reject(e)))),po.set(t+"/"+n,r)),r}bn||(self.addEventListener("sync",(e=>{console.debug('SW "sync" Event',e.tag);const t=fo(e.tag);t&&e.waitUntil(ho(t,"push"))})),self.addEventListener("periodicsync",(e=>{console.debug('SW "periodicsync" Event',e.tag);const t=fo(e.tag);t&&e.waitUntil(ho(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)=>ho(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)))}})));
|