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