@rtc-agent/component 0.1.4-rc.0 → 0.1.4-rc.1

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.
@@ -8,7 +8,7 @@ var fN=Object.defineProperty;var pN=(Gs,Ts,Na)=>Ts in Gs?fN(Gs,Ts,{enumerable:!0
8
8
  `):r=e;try{yield this._writer.write(r)}catch{this.close()}})}}const GT=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,-1,-1,-1,-1,36,-1,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,-1,-1,-1,63,-1];class zT{constructor(e){this.a=e,this.pos=0}haveBytes(){return this.pos<this.a.length}getByte(){const e=this.a[this.pos];if(this.pos++,this.pos>this.a.length)throw new RangeError("out of bounds");return e}getChar(){return String.fromCharCode(this.getByte())}getInt(){let e=0,r;for(;this.haveBytes()&&(r=GT[127&this.getByte()])>=0;)e=(e<<6)+r;return this.pos--,e>>>0}}class HT{constructor(){this.a=[]}toByteArray(e){return Array.isArray(e)?this.a:new Uint8Array(this.a)}putArray(e,r,n){for(let s=r;s<n;s++)this.a.push(e[s])}}function JT(t){let e=0,r=0,n=0,s=0,c=0,a=t.length;for(;a>=16;)e=e+t[c+0]|0,r=r+t[c+1]|0,n=n+t[c+2]|0,s=s+t[c+3]|0,e=e+t[c+4]|0,r=r+t[c+5]|0,n=n+t[c+6]|0,s=s+t[c+7]|0,e=e+t[c+8]|0,r=r+t[c+9]|0,n=n+t[c+10]|0,s=s+t[c+11]|0,e=e+t[c+12]|0,r=r+t[c+13]|0,n=n+t[c+14]|0,s=s+t[c+15]|0,c+=16,a-=16;for(;a>=4;)e=e+t[c+0]|0,r=r+t[c+1]|0,n=n+t[c+2]|0,s=s+t[c+3]|0,c+=4,a-=4;switch(s=((s+(n<<8)|0)+(r<<16)|0)+(e<<24)|0,a){case 3:s=s+(t[c+2]<<8)|0;case 2:s=s+(t[c+1]<<16)|0;case 1:s=s+(t[c+0]<<24)|0}return s>>>0}function YT(t,e){let r=0;const n=new zT(e),s=t.length,c=e.length,a=n.getInt();if(n.getChar()!==`
9
9
  `)throw new Error("size integer not terminated by '\\n'");const f=new HT;for(;n.haveBytes();){const p=n.getInt();let h;switch(n.getChar()){case"@":if(h=n.getInt(),n.haveBytes()&&n.getChar()!==",")throw new Error("copy command not terminated by ','");if(r+=p,r>a)throw new Error("copy exceeds output file size");if(h+p>s)throw new Error("copy extends past end of input");f.putArray(t,h,h+p);break;case":":if(r+=p,r>a)throw new Error("insert command gives an output larger than predicted");if(p>c)throw new Error("insert count exceeds size of delta");f.putArray(n.a,n.pos,n.pos+p),n.pos+=p;break;case";":{const y=f.toByteArray(t);if(p!==JT(y))throw new Error("bad checksum");if(r!==a)throw new Error("generated size does not match predicted size");return y}default:throw new Error("unknown delta operator")}}throw new Error("unterminated delta")}class By{name(){return"json"}encodeCommands(e){return e.map(r=>JSON.stringify(r)).join(`
10
10
  `)}decodeReplies(e){return e.trim().split(`
11
- `).map(r=>JSON.parse(r))}applyDeltaIfNeeded(e,r){let n,s,c,a;if(e.delta){a=!0;const f=new TextEncoder().encode(e.data),p=YT(r,f);n=JSON.parse(new TextDecoder().decode(p)),s=p,c=f.length}else a=!1,n=JSON.parse(e.data),s=new TextEncoder().encode(e.data),c=s.length;return{newData:n,newPrevValue:s,isDelta:a,wireBytes:c,fullBytes:s.length}}}const XT={headers:{},token:"",getToken:null,data:null,getData:null,debug:!1,name:"js",version:"",fetch:null,readableStream:null,websocket:null,eventsource:null,sockjs:null,sockjsOptions:{},emulationEndpoint:"/emulation",minReconnectDelay:500,maxReconnectDelay:2e4,timeout:5e3,maxServerPingDelay:1e4,networkEventTarget:null};class xs extends Error{constructor(e){super(e),this.name=this.constructor.name}}class wl extends ky{constructor(e,r){super(),this._reconnectTimeout=null,this._refreshTimeout=null,this._serverPingTimeout=null,this.state=Br.Disconnected,this._transportIsOpen=!1,this._endpoint=e,this._emulation=!1,this._transports=[],this._currentTransportIndex=0,this._triedAllTransports=!1,this._transportWasOpen=!1,this._transport=null,this._transportId=0,this._deviceWentOffline=!1,this._transportClosed=!0,this._codec=new By,this._reconnecting=!1,this._reconnectTimeout=null,this._reconnectAttempts=0,this._client=null,this._session="",this._node="",this._subs={},this._serverSubs={},this._commandId=0,this._commands=[],this._batching=!1,this._refreshRequired=!1,this._refreshTimeout=null,this._callbacks={},this._token="",this._data=null,this._dispatchPromise=Promise.resolve(),this._serverPing=0,this._serverPingTimeout=null,this._sendPong=!1,this._promises={},this._promiseId=0,this._debugEnabled=!1,this._networkEventsSet=!1,this._config=Object.assign(Object.assign({},XT),r),this._configure(),this._debugEnabled?(this.on("state",n=>{this._debug("client state",n.oldState,"->",n.newState)}),this.on("error",n=>{this._debug("client error",n)})):this.on("error",function(){Function.prototype()})}newSubscription(e,r){if(this.getSubscription(e)!==null)throw new Error("Subscription to the channel "+e+" already exists");const n=new qT(this,e,r);return this._subs[e]=n,n}newMapSubscription(e,r){if(this.getSubscription(e)!==null)throw new Error("Subscription to the channel "+e+" already exists");const n=new Af(this,e,{token:r==null?void 0:r.token,getToken:r==null?void 0:r.getToken,data:r==null?void 0:r.data,minResubscribeDelay:r==null?void 0:r.minResubscribeDelay,maxResubscribeDelay:r==null?void 0:r.maxResubscribeDelay,delta:r==null?void 0:r.delta,tagsFilter:r==null?void 0:r.tagsFilter,map:!0,mapPageSize:r==null?void 0:r.pageSize,mapUnrecoverableStrategy:r==null?void 0:r.unrecoverableStrategy});return this._subs[e]=n,n}newMapClientsSubscription(e,r){if(this.getSubscription(e)!==null)throw new Error("Subscription to the channel "+e+" already exists");const n=new Af(this,e,{token:r==null?void 0:r.token,getToken:r==null?void 0:r.getToken,data:r==null?void 0:r.data,minResubscribeDelay:r==null?void 0:r.minResubscribeDelay,maxResubscribeDelay:r==null?void 0:r.maxResubscribeDelay,delta:r==null?void 0:r.delta,tagsFilter:r==null?void 0:r.tagsFilter,map:!0,mapPresenceType:2,mapPageSize:r==null?void 0:r.pageSize,mapUnrecoverableStrategy:r==null?void 0:r.unrecoverableStrategy});return this._subs[e]=n,n}newMapUsersSubscription(e,r){if(this.getSubscription(e)!==null)throw new Error("Subscription to the channel "+e+" already exists");const n=new Af(this,e,{token:r==null?void 0:r.token,getToken:r==null?void 0:r.getToken,data:r==null?void 0:r.data,minResubscribeDelay:r==null?void 0:r.minResubscribeDelay,maxResubscribeDelay:r==null?void 0:r.maxResubscribeDelay,delta:r==null?void 0:r.delta,tagsFilter:r==null?void 0:r.tagsFilter,map:!0,mapPresenceType:3,mapPageSize:r==null?void 0:r.pageSize,mapUnrecoverableStrategy:r==null?void 0:r.unrecoverableStrategy});return this._subs[e]=n,n}newSharedPollSubscription(e,r){if(this.getSubscription(e)!==null)throw new Error("Subscription to the channel "+e+" already exists");const n=new $T(this,e,{token:r==null?void 0:r.token,getToken:r==null?void 0:r.getToken,data:r==null?void 0:r.data,minResubscribeDelay:r==null?void 0:r.minResubscribeDelay,maxResubscribeDelay:r==null?void 0:r.maxResubscribeDelay,delta:r==null?void 0:r.delta,sharedPoll:!0,sharedPollGetSignature:r==null?void 0:r.getSignature});return this._subs[e]=n,n}getSubscription(e){return this._getSub(e)}getMapSubscription(e){return this._getSub(e)}getSharedPollSubscription(e){return this._getSub(e)}removeSubscription(e){e&&(e.state!==ln.Unsubscribed&&e.unsubscribe(),this._removeSubscription(e))}removeMapSubscription(e){this.removeSubscription(e)}removeSharedPollSubscription(e){this.removeSubscription(e)}subscriptions(){return this._subs}mapSubscriptions(){const e={};for(const[r,n]of Object.entries(this._subs))n.type==="map"&&(e[r]=n);return e}sharedPollSubscriptions(){const e={};for(const[r,n]of Object.entries(this._subs))n.type==="shared_poll"&&(e[r]=n);return e}ready(e){return Dr(this,void 0,void 0,function*(){switch(this.state){case Br.Disconnected:throw{code:ur.clientDisconnected,message:"client disconnected"};case Br.Connected:return;default:return new Promise((r,n)=>{const s={resolve:r,reject:n};e&&(s.timeout=setTimeout(()=>{n({code:ur.timeout,message:"timeout"})},e)),this._promises[this._nextPromiseId()]=s})}})}connect(){if(this._isConnected()){this._debug("connect called when already connected");return}if(this._isConnecting()){this._debug("connect called when already connecting");return}this._debug("connect called"),this._reconnectAttempts=0,this._startConnecting()}disconnect(){this._disconnect(Da.disconnectCalled,"disconnect called",!1)}setToken(e){this._token=e}setData(e){this._data=e}setHeaders(e){this._config.headers=e}send(e){return Dr(this,void 0,void 0,function*(){const r={send:{data:e}};if(yield this._methodCall(),!this._transportSendCommands([r]))throw this._createErrorObject(ur.transportWriteError,"transport write error")})}rpc(e,r){return Dr(this,void 0,void 0,function*(){const n={rpc:{method:e,data:r}};return yield this._methodCall(),{data:(yield this._callPromise(n,c=>c.rpc)).data}})}publish(e,r){return Dr(this,void 0,void 0,function*(){const n={publish:{channel:e,data:r}};return yield this._methodCall(),yield this._callPromise(n,()=>({})),{}})}mapPublish(e,r,n){return Dr(this,void 0,void 0,function*(){const s={publish:{channel:e,type:1,key:r,data:n}};return yield this._methodCall(),yield this._callPromise(s,()=>({})),{}})}mapRemove(e,r){return Dr(this,void 0,void 0,function*(){const n={publish:{channel:e,type:1,key:r,removed:!0}};return yield this._methodCall(),yield this._callPromise(n,()=>({})),{}})}history(e,r){return Dr(this,void 0,void 0,function*(){const n={history:this._getHistoryRequest(e,r)};yield this._methodCall();const s=yield this._callPromise(n,a=>a.history),c=[];if(s.publications)for(let a=0;a<s.publications.length;a++)c.push(this._getPublicationContext(e,s.publications[a]));return{publications:c,epoch:s.epoch||"",offset:s.offset||0}})}presence(e){return Dr(this,void 0,void 0,function*(){const r={presence:{channel:e}};yield this._methodCall();const s=(yield this._callPromise(r,c=>c.presence)).presence;for(const c in s)if(Object.prototype.hasOwnProperty.call(s,c)){const a=s[c],f=a.conn_info,p=a.chan_info;f&&(a.connInfo=f),p&&(a.chanInfo=p)}return{clients:s}})}presenceStats(e){return Dr(this,void 0,void 0,function*(){const r={presence_stats:{channel:e}};yield this._methodCall();const n=yield this._callPromise(r,s=>s.presence_stats);return{numUsers:n.num_users,numClients:n.num_clients}})}startBatching(){this._batching=!0}stopBatching(){const e=this;Promise.resolve().then(function(){Promise.resolve().then(function(){e._batching=!1,e._flush()})})}_debug(...e){this._debugEnabled&&jT("debug",e)}_codecName(){return this._codec.name()}_formatOverride(){}_configure(){if(!("Promise"in globalThis))throw new Error("Promise polyfill required");if(!this._endpoint)throw new Error("endpoint configuration required");if(this._config.token!==null&&(this._token=this._config.token),this._config.data!==null&&(this._data=this._config.data),this._codec=new By,this._formatOverride(),(this._config.debug===!0||FT("centrifuge.debug"))&&(this._debugEnabled=!0),this._debug("config",this._config),typeof this._endpoint!="string")if(Array.isArray(this._endpoint)){this._transports=this._endpoint,this._emulation=!0;for(const e in this._transports)if(this._transports.hasOwnProperty(e)){const r=this._transports[e];if(!r.endpoint||!r.transport)throw new Error("malformed transport configuration");const n=r.transport;if(["websocket","http_stream","sse","sockjs","webtransport"].indexOf(n)<0)throw new Error("unsupported transport name: "+n)}}else throw new Error("unsupported url configuration type: only string or array of objects are supported")}_setState(e){if(this.state!==e){this._reconnecting=!1;const r=this.state;return this.state=e,this.emit("state",{newState:e,oldState:r}),!0}return!1}_isDisconnected(){return this.state===Br.Disconnected}_isConnecting(){return this.state===Br.Connecting}_isConnected(){return this.state===Br.Connected}_nextCommandId(){return++this._commandId}_setNetworkEvents(){if(this._networkEventsSet)return;let e=null;this._config.networkEventTarget!==null?e=this._config.networkEventTarget:typeof globalThis.addEventListener<"u"&&(e=globalThis),e&&(e.addEventListener("offline",()=>{this._debug("offline event triggered"),(this.state===Br.Connected||this.state===Br.Connecting)&&(this._disconnect(Es.transportClosed,"transport closed",!0),this._deviceWentOffline=!0)}),e.addEventListener("online",()=>{this._debug("online event triggered"),this.state===Br.Connecting&&(this._deviceWentOffline&&!this._transportClosed&&(this._deviceWentOffline=!1,this._transportClosed=!0),this._clearReconnectTimeout(),this._startReconnecting())}),this._networkEventsSet=!0)}_getReconnectDelay(){const e=na(this._reconnectAttempts,this._config.minReconnectDelay,this._config.maxReconnectDelay);return this._reconnectAttempts+=1,e}_clearOutgoingRequests(){for(const e in this._callbacks)if(this._callbacks.hasOwnProperty(e)){const r=this._callbacks[e];clearTimeout(r.timeout);const n=r.errback;if(!n)continue;n({error:this._createErrorObject(ur.connectionClosed,"connection closed")})}this._callbacks={}}_clearConnectedState(){this._client=null,this._clearServerPingTimeout(),this._clearRefreshTimeout();for(const e in this._subs){if(!this._subs.hasOwnProperty(e))continue;const r=this._subs[e];r.state===ln.Subscribed&&r._setSubscribing(_l.transportClosed,"transport closed")}for(const e in this._serverSubs)this._serverSubs.hasOwnProperty(e)&&this.emit("subscribing",{channel:e})}_handleWriteError(e){for(const r of e){const n=r.id;if(!(n in this._callbacks))continue;const s=this._callbacks[n];clearTimeout(this._callbacks[n].timeout),delete this._callbacks[n];const c=s.errback;c({error:this._createErrorObject(ur.transportWriteError,"transport write error")})}}_transportSendCommands(e){if(!e.length)return!0;if(!this._transport)return!1;try{this._transport.send(this._codec.encodeCommands(e),this._session,this._node)}catch(r){return this._debug("error writing commands",r),this._handleWriteError(e),!1}return!0}_advanceTransportIndex(){this._currentTransportIndex++,this._currentTransportIndex>=this._transports.length&&(this._triedAllTransports=!0,this._currentTransportIndex=0)}_initializeTransport(){let e;this._config.websocket!==null?e=this._config.websocket:typeof globalThis.WebSocket!="function"&&typeof globalThis.WebSocket!="object"||(e=globalThis.WebSocket);let r=null;this._config.sockjs!==null?r=this._config.sockjs:typeof globalThis.SockJS<"u"&&(r=globalThis.SockJS);let n=null;this._config.eventsource!==null?n=this._config.eventsource:typeof globalThis.EventSource<"u"&&(n=globalThis.EventSource);let s=null;this._config.fetch!==null?s=this._config.fetch:typeof globalThis.fetch<"u"&&(s=globalThis.fetch);let c=null;if(this._config.readableStream!==null?c=this._config.readableStream:typeof globalThis.ReadableStream<"u"&&(c=globalThis.ReadableStream),this._emulation){this._currentTransportIndex>=this._transports.length&&(this._triedAllTransports=!0,this._currentTransportIndex=0);let S=0;for(;;){if(S>=this._transports.length)throw new Error("no supported transport found");const O=this._transports[this._currentTransportIndex],A=O.transport,_=O.endpoint;if(A==="websocket"){if(this._debug("trying websocket transport"),this._transport=new Dy(_,{websocket:e}),!this._transport.supported()){this._debug("websocket transport not available"),this._advanceTransportIndex(),S++;continue}}else if(A==="webtransport"){if(this._debug("trying webtransport transport"),this._transport=new WT(_,{webtransport:globalThis.WebTransport,decoder:this._codec,encoder:this._codec}),!this._transport.supported()){this._debug("webtransport transport not available"),this._advanceTransportIndex(),S++;continue}}else if(A==="http_stream"){if(this._debug("trying http_stream transport"),this._transport=new VT(_,{fetch:s,readableStream:c,emulationEndpoint:this._config.emulationEndpoint,decoder:this._codec,encoder:this._codec}),!this._transport.supported()){this._debug("http_stream transport not available"),this._advanceTransportIndex(),S++;continue}}else if(A==="sse"){if(this._debug("trying sse transport"),this._transport=new KT(_,{eventsource:n,fetch:s,emulationEndpoint:this._config.emulationEndpoint}),!this._transport.supported()){this._debug("sse transport not available"),this._advanceTransportIndex(),S++;continue}}else if(A==="sockjs"){if(this._debug("trying sockjs"),this._transport=new UT(_,{sockjs:r,sockjsOptions:this._config.sockjsOptions}),!this._transport.supported()){this._debug("sockjs transport not available"),this._advanceTransportIndex(),S++;continue}}else throw new Error("unknown transport "+A);break}}else{if(RT(this._endpoint,"http"))throw new Error("Provide explicit transport endpoints configuration in case of using HTTP (i.e. using array of TransportEndpoint instead of a single string), or use ws(s):// scheme in an endpoint if you aimed using WebSocket transport");if(this._debug("client will use websocket"),this._transport=new Dy(this._endpoint,{websocket:e}),!this._transport.supported())throw new Error("WebSocket constructor not found, make sure it is available globally or passed as a dependency in Centrifuge options")}const a=this,f=this._transport,p=this._nextTransportId();a._debug("id of transport",p);let h=!1;const y=[];if(this._transport.emulation()){const S=a._sendConnect(!0);y.push(S)}this._setNetworkEvents();const g=this._codec.encodeCommands(y);this._transportClosed=!1;let b;b=setTimeout(function(){f.close()},this._config.timeout),this._transport.initialize(this._codecName(),{onOpen:function(){if(b&&(clearTimeout(b),b=null),a._transportId!=p){a._debug("open callback from non-actual transport"),f.close();return}h=!0,a._debug(f.subName(),"transport open"),!f.emulation()&&(a._transportIsOpen=!0,a._transportWasOpen=!0,a.startBatching(),a._sendConnect(!1),a._sendSubscribeCommands(),a.stopBatching(),a.emit("__centrifuge_debug:connect_frame_sent",{}))},onError:function(S){if(a._transportId!=p){a._debug("error callback from non-actual transport");return}a._debug("transport level error",S)},onClose:function(S){if(b&&(clearTimeout(b),b=null),a._transportId!=p){a._debug("close callback from non-actual transport");return}a._debug(f.subName(),"transport closed"),a._transportClosed=!0,a._transportIsOpen=!1;let O="connection closed",A=!0,_=0;if(S&&"code"in S&&S.code&&(_=S.code),S&&S.reason)try{const C=JSON.parse(S.reason);O=C.reason,A=C.reconnect}catch{O=S.reason,(_>=3500&&_<4e3||_>=4500&&_<5e3)&&(A=!1)}_<3e3?(_===1009?(_=Da.messageSizeLimit,O="message size limit exceeded",A=!1):(_=Es.transportClosed,O="transport closed"),a._emulation&&!a._transportWasOpen&&a._advanceTransportIndex()):a._transportWasOpen=!0,a._isConnecting()&&!h&&a.emit("error",{type:"transport",error:{code:ur.transportClosed,message:"transport closed"},transport:f.name()}),a._reconnecting=!1,a._disconnect(_,O,A)},onMessage:function(S){a._dataReceived(S)}},g),a.emit("__centrifuge_debug:transport_initialized",{})}_sendConnect(e){const r=this._constructConnectCommand(),n=this;return this._call(r,e).then(s=>{const c=s.reply.connect;n._connectResponse(c),s.next&&s.next()},s=>{n._connectError(s.error),s.next&&s.next()}),r}_startReconnecting(){if(this._debug("start reconnecting"),!this._isConnecting()){this._debug("stop reconnecting: client not in connecting state");return}if(this._reconnecting){this._debug("reconnect already in progress, return from reconnect routine");return}if(this._transportClosed===!1){this._debug("waiting for transport close");return}this._reconnecting=!0;const e=this._token==="";if(!(this._refreshRequired||e&&this._config.getToken!==null)){this._config.getData?this._config.getData().then(s=>{this._isConnecting()&&(this._data=s,this._initializeTransport())}).catch(s=>this._handleGetDataError(s)):this._initializeTransport();return}const n=this;this._getToken().then(function(s){if(n._isConnecting()){if(s==null||s==null){n._failUnauthorized();return}n._token=s,n._debug("connection token refreshed"),n._config.getData?n._config.getData().then(function(c){n._isConnecting()&&(n._data=c,n._initializeTransport())}).catch(c=>n._handleGetDataError(c)):n._initializeTransport()}}).catch(function(s){if(!n._isConnecting())return;if(s instanceof xs){n._failUnauthorized();return}n.emit("error",{type:"connectToken",error:{code:ur.clientConnectToken,message:s!==void 0?s.toString():""}});const c=n._getReconnectDelay();n._debug("error on getting connection token, reconnect after "+c+" milliseconds",s),n._reconnecting=!1,n._reconnectTimeout=setTimeout(()=>{n._startReconnecting()},c)})}_handleGetDataError(e){if(e instanceof xs){this._failUnauthorized();return}this.emit("error",{type:"connectData",error:{code:ur.badConfiguration,message:(e==null?void 0:e.toString())||""}});const r=this._getReconnectDelay();this._debug("error on getting connect data, reconnect after "+r+" milliseconds",e),this._reconnecting=!1,this._reconnectTimeout=setTimeout(()=>{this._startReconnecting()},r)}_connectError(e){this.state===Br.Connecting&&(e.code===109&&(this._refreshRequired=!0),e.code<100||e.temporary===!0||e.code===109?(this.emit("error",{type:"connect",error:e}),this._debug("closing transport due to connect error"),this._disconnect(e.code,e.message,!0)):this._disconnect(e.code,e.message,!1))}_scheduleReconnect(){if(!this._isConnecting())return;let e=!1;this._emulation&&!this._transportWasOpen&&!this._triedAllTransports&&(e=!0);let r=this._getReconnectDelay();e&&(r=0),this._debug("reconnect after "+r+" milliseconds"),this._clearReconnectTimeout(),this._reconnectTimeout=setTimeout(()=>{this._startReconnecting()},r)}_constructConnectCommand(){const e={};this._token&&(e.token=this._token),this._data&&(e.data=this._data),this._config.name&&(e.name=this._config.name),this._config.version&&(e.version=this._config.version),Object.keys(this._config.headers).length>0&&(e.headers=this._config.headers);const r={};let n=!1;for(const s in this._serverSubs)if(this._serverSubs.hasOwnProperty(s)&&this._serverSubs[s].recoverable){n=!0;const c={recover:!0};this._serverSubs[s].offset&&(c.offset=this._serverSubs[s].offset),this._serverSubs[s].epoch&&(c.epoch=this._serverSubs[s].epoch),r[s]=c}return n&&(e.subs=r),{connect:e}}_getHistoryRequest(e,r){const n={channel:e};return r!==void 0&&(r.since&&(n.since={offset:r.since.offset},r.since.epoch&&(n.since.epoch=r.since.epoch)),r.limit!==void 0&&(n.limit=r.limit),r.reverse===!0&&(n.reverse=!0)),n}_methodCall(){return this._isConnected()?Promise.resolve():new Promise((e,r)=>{const n=setTimeout(function(){r({code:ur.timeout,message:"timeout"})},this._config.timeout);this._promises[this._nextPromiseId()]={timeout:n,resolve:e,reject:r}})}_callPromise(e,r){return new Promise((n,s)=>{this._call(e,!1).then(c=>{var a;const f=r(c.reply);n(f),(a=c.next)===null||a===void 0||a.call(c)},c=>{var a;s(c.error),(a=c.next)===null||a===void 0||a.call(c)})})}_dataReceived(e){this._serverPing>0&&this._waitServerPing();const r=this._codec.decodeReplies(e);this._dispatchPromise=this._dispatchPromise.then(()=>{let n;this._dispatchPromise=new Promise(s=>{n=s}),this._dispatchSynchronized(r,n)})}_dispatchSynchronized(e,r){let n=Promise.resolve();for(const s in e)e.hasOwnProperty(s)&&(n=n.then(()=>this._dispatchReply(e[s])));n.then(()=>{r()})}_dispatchReply(e){let r;const n=new Promise(c=>{r=c});if(e==null)return this._debug("dispatch: got undefined or null reply"),r(),n;const s=e.id;return s&&s>0?this._handleReply(e,r):e.push?this._handlePush(e.push,r):this._handleServerPing(r),n}_call(e,r){return new Promise((n,s)=>{e.id=this._nextCommandId(),this._registerCall(e.id,n,s),r||this._addCommand(e)})}_startConnecting(){this._debug("start connecting"),this._setState(Br.Connecting)&&this.emit("connecting",{code:Es.connectCalled,reason:"connect called"}),this._client=null,this._startReconnecting()}_disconnect(e,r,n){if(e===Da.stateInvalidated){this._token="",this._refreshRequired=!0;for(const f in this._subs)this._subs.hasOwnProperty(f)&&this._subs[f]._invalidateState();for(const f in this._serverSubs)this._serverSubs.hasOwnProperty(f)&&(this._serverSubs[f].offset=0,this._serverSubs[f].epoch="_")}if(this._isDisconnected())return;this._transportIsOpen=!1;const s=this.state;this._reconnecting=!1;const c={code:e,reason:r};let a;if(n?a=this._setState(Br.Connecting):(a=this._setState(Br.Disconnected),this._rejectPromises({code:ur.clientDisconnected,message:"disconnected"})),this._clearOutgoingRequests(),s===Br.Connecting&&this._clearReconnectTimeout(),s===Br.Connected&&this._clearConnectedState(),a&&(this._isConnecting()?this.emit("connecting",c):this.emit("disconnected",c)),this._transport){this._debug("closing existing transport");const f=this._transport;this._transport=null,f.close(),this._transportClosed=!0,this._nextTransportId()}else this._debug("no transport to close");this._scheduleReconnect()}_failUnauthorized(){this._disconnect(Da.unauthorized,"unauthorized",!1)}_getToken(){return this._debug("get connection token"),this._config.getToken?this._config.getToken({}):(this.emit("error",{type:"configuration",error:{code:ur.badConfiguration,message:"token expired but no getToken function set in the configuration"}}),Promise.reject(new xs("")))}_refresh(){const e=this._client,r=this;this._getToken().then(function(n){if(e!==r._client)return;if(!n){r._failUnauthorized();return}if(r._token=n,r._debug("connection token refreshed"),!r._isConnected())return;const s={refresh:{token:r._token}};r._call(s,!1).then(c=>{const a=c.reply.refresh;r._refreshResponse(a),c.next&&c.next()},c=>{r._refreshError(c.error),c.next&&c.next()})}).catch(function(n){if(r._isConnected()){if(n instanceof xs){r._failUnauthorized();return}r.emit("error",{type:"refreshToken",error:{code:ur.clientRefreshToken,message:n!==void 0?n.toString():""}}),r._refreshTimeout=setTimeout(()=>r._refresh(),r._getRefreshRetryDelay())}})}_refreshError(e){e.code<100||e.temporary===!0?(this.emit("error",{type:"refresh",error:e}),this._refreshTimeout=setTimeout(()=>this._refresh(),this._getRefreshRetryDelay())):this._disconnect(e.code,e.message,!1)}_getRefreshRetryDelay(){return na(0,5e3,1e4)}_refreshResponse(e){this._refreshTimeout&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null),e.expires&&(this._client=e.client,this._refreshTimeout=setTimeout(()=>this._refresh(),To(e.ttl)))}_removeSubscription(e){e!==null&&delete this._subs[e.channel]}_unsubscribe(e){if(!this._transportIsOpen)return Promise.resolve();const n={unsubscribe:{channel:e.channel}},s=this;return new Promise((a,f)=>{this._call(n,!1).then(p=>{a(),p.next&&p.next()},p=>{a(),p.next&&p.next(),s._disconnect(Es.unsubscribeError,"unsubscribe error",!0)})})}_getSub(e,r){if(r&&r>0){for(const s in this._subs)if(this._subs.hasOwnProperty(s)){const c=this._subs[s];if(c._id===r)return c}return null}const n=this._subs[e];return n||null}_isServerSub(e){return this._serverSubs[e]!==void 0}_sendSubscribeCommands(){const e=[];for(const r in this._subs){if(!this._subs.hasOwnProperty(r))continue;const n=this._subs[r];if(n._inflight!==!0&&n.state===ln.Subscribing){const s=n._subscribe();s&&e.push(s)}}return e}_connectResponse(e){if(this._transportIsOpen=!0,this._transportWasOpen=!0,this._reconnectAttempts=0,this._refreshRequired=!1,this._isConnected())return;this._client=e.client,this._setState(Br.Connected),this._refreshTimeout&&clearTimeout(this._refreshTimeout),e.expires&&(this._refreshTimeout=setTimeout(()=>this._refresh(),To(e.ttl))),this._session=e.session,this._node=e.node,this.startBatching(),this._sendSubscribeCommands(),this.stopBatching();const r={client:e.client,transport:this._transport.subName()};e.data&&(r.data=e.data),this.emit("connected",r),this._resolvePromises(),this._processServerSubs(e.subs||{}),e.ping&&e.ping>0?(this._serverPing=e.ping*1e3,this._sendPong=e.pong===!0,this._waitServerPing()):this._serverPing=0}_processServerSubs(e){for(const r in e){if(!e.hasOwnProperty(r))continue;const n=e[r];this._serverSubs[r]={offset:n.offset,epoch:n.epoch,recoverable:n.recoverable||!1};const s=this._getSubscribeContext(r,n);this.emit("subscribed",s)}for(const r in e){if(!e.hasOwnProperty(r))continue;const n=e[r];if(n.recovered){const s=n.publications;if(s&&s.length>0)for(const c in s)s.hasOwnProperty(c)&&this._handlePublication(r,s[c])}}for(const r in this._serverSubs)this._serverSubs.hasOwnProperty(r)&&(e[r]||(this.emit("unsubscribed",{channel:r}),delete this._serverSubs[r]))}_clearRefreshTimeout(){this._refreshTimeout!==null&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null)}_clearReconnectTimeout(){this._reconnectTimeout!==null&&(clearTimeout(this._reconnectTimeout),this._reconnectTimeout=null)}_clearServerPingTimeout(){this._serverPingTimeout!==null&&(clearTimeout(this._serverPingTimeout),this._serverPingTimeout=null)}_waitServerPing(){this._config.maxServerPingDelay!==0&&this._isConnected()&&(this._clearServerPingTimeout(),this._serverPingTimeout=setTimeout(()=>{this._isConnected()&&this._disconnect(Es.noPing,"no ping",!0)},this._serverPing+this._config.maxServerPingDelay))}_getSubscribeContext(e,r){const n={channel:e,positioned:!1,recoverable:!1,wasRecovering:!1,recovered:!1,hasRecoveredPublications:!1};r.recovered&&(n.recovered=!0),r.positioned&&(n.positioned=!0),r.recoverable&&(n.recoverable=!0),r.was_recovering&&(n.wasRecovering=!0);let s="";"epoch"in r&&(s=r.epoch);let c=0;return"offset"in r&&(c=r.offset),(n.positioned||n.recoverable)&&(n.streamPosition={offset:c,epoch:s}),Array.isArray(r.publications)&&r.publications.length>0&&(n.hasRecoveredPublications=!0),r.data&&(n.data=r.data),n}_handleReply(e,r){const n=e.id;if(!(n in this._callbacks)){r();return}const s=this._callbacks[n];if(clearTimeout(this._callbacks[n].timeout),delete this._callbacks[n],LT(e)){const c=s.errback;if(!c){r();return}const a={code:e.error.code,message:e.error.message||"",temporary:e.error.temporary||!1};c({error:a,next:r})}else{const c=s.callback;if(!c)return;c({reply:e,next:r})}}_handleJoin(e,r,n){const s=this._getSub(e,n);if(!s){if(e&&this._isServerSub(e)){const c={channel:e,info:this._getJoinLeaveContext(r.info)};this.emit("join",c)}return}s._handleJoin(r)}_handleLeave(e,r,n){const s=this._getSub(e,n);if(!s){if(e&&this._isServerSub(e)){const c={channel:e,info:this._getJoinLeaveContext(r.info)};this.emit("leave",c)}return}s._handleLeave(r)}_handleUnsubscribe(e,r){const n=this._getSub(e,0);if(!n&&e){this._isServerSub(e)&&(delete this._serverSubs[e],this.emit("unsubscribed",{channel:e}));return}r.code<2500?n._setUnsubscribed(r.code,r.reason,!1):(r.code===vo.stateInvalidated&&n._invalidateState(),n._setSubscribing(r.code,r.reason))}_handleSubscribe(e,r){this._serverSubs[e]={offset:r.offset,epoch:r.epoch,recoverable:r.recoverable||!1},this.emit("subscribed",this._getSubscribeContext(e,r))}_handleDisconnect(e){const r=e.code;let n=!0;(r>=3500&&r<4e3||r>=4500&&r<5e3)&&(n=!1),this._disconnect(r,e.reason,n)}_getPublicationContext(e,r){const n={channel:e,data:r.data};return r.offset&&(n.offset=r.offset),r.info&&(n.info=this._getJoinLeaveContext(r.info)),r.tags&&(n.tags=r.tags),n}_getJoinLeaveContext(e){const r={client:e.client,user:e.user},n=e.conn_info;n&&(r.connInfo=n);const s=e.chan_info;return s&&(r.chanInfo=s),r}_handlePublication(e,r,n){const s=this._getSub(e,n);if(!s){if(e&&this._isServerSub(e)){const c=this._getPublicationContext(e,r);this.emit("publication",c),r.offset!==void 0&&(this._serverSubs[e].offset=r.offset)}return}s._handlePublication(r)}_handleMessage(e){this.emit("message",{data:e.data})}_handleServerPing(e){if(this._sendPong){const r={};this._transportSendCommands([r])}e()}_handlePush(e,r){const n=e.channel,s=e.id;e.pub?this._handlePublication(n,e.pub,s):e.message?this._handleMessage(e.message):e.join?this._handleJoin(n,e.join,s):e.leave?this._handleLeave(n,e.leave,s):e.unsubscribe?this._handleUnsubscribe(n,e.unsubscribe):e.subscribe?this._handleSubscribe(n,e.subscribe):e.disconnect&&this._handleDisconnect(e.disconnect),r()}_flush(){const e=this._commands.slice(0);this._commands=[],this._transportSendCommands(e)}_createErrorObject(e,r,n){const s={code:e,message:r};return n&&(s.temporary=!0),s}_registerCall(e,r,n){this._callbacks[e]={callback:r,errback:n,timeout:null},this._callbacks[e].timeout=setTimeout(()=>{delete this._callbacks[e],_f(n)&&n({error:this._createErrorObject(ur.timeout,"timeout")})},this._config.timeout)}_addCommand(e){this._batching?this._commands.push(e):this._transportSendCommands([e])}_nextPromiseId(){return++this._promiseId}_nextTransportId(){return++this._transportId}_resolvePromises(){for(const e in this._promises)this._promises.hasOwnProperty(e)&&(this._promises[e].timeout&&clearTimeout(this._promises[e].timeout),this._promises[e].resolve(),delete this._promises[e])}_rejectPromises(e){for(const r in this._promises)this._promises.hasOwnProperty(r)&&(this._promises[r].timeout&&clearTimeout(this._promises[r].timeout),this._promises[r].reject(e),delete this._promises[r])}}wl.SubscriptionState=ln,wl.State=Br,wl.UnauthorizedError=xs;const Fn={SessionList:"v1.session.list",SessionGet:"v1.session.get",SessionClose:"v1.session.close",SessionUpdate:"v1.session.update",SessionFork:"v1.session.fork",SessionCompact:"v1.session.compact",MessageSend:"v1.message.send",MessageList:"v1.message.list",TurnList:"v1.turn.list",TurnStop:"v1.turn.stop",RtcList:"v1.rtc.list",RtcUpdateStatus:"v1.rtc.update_status",RtcSubmitResult:"v1.rtc.submit_result"};class QT{constructor(e){Ht(this,"options");Ht(this,"centrifuge",null);Ht(this,"connectionState","disconnected");Ht(this,"listeners",new Map);Ht(this,"shouldReconnect",!0);Ht(this,"wasConnected",!1);Ht(this,"applyUpdatesQueue",null);Ht(this,"subscriptions",new Map);Ht(this,"epochCache",new Map);this.options=e}async connect(){if(console.log("[RTCAgentClient] connect() called, current state:",this.connectionState),this.connectionState==="connected"||this.connectionState==="connecting"){console.log("[RTCAgentClient] connect() early return, already",this.connectionState);return}this.shouldReconnect=!0,this.setConnectionState("connecting"),this.centrifuge=new wl(this.options.endpoint,{getToken:async()=>{var r;const e=await this.options.getToken();if(this._isTokenExpired(e)&&this.options.onTokenExpired){if(await this.options.onTokenExpired()==="relogin")throw this.shouldReconnect=!1,(r=this.centrifuge)==null||r.disconnect(),this.setConnectionState("disconnected","token expired, relogin required"),new Error("Token expired, user needs to re-login");return this.options.getToken()}return e}}),this.centrifuge.on("connecting",e=>{var n;if(!this.shouldReconnect){(n=this.centrifuge)==null||n.disconnect();return}const r=this.wasConnected?"reconnecting":"connecting";this.setConnectionState(r,e==null?void 0:e.reason)}),this.centrifuge.on("connected",()=>{console.log("[RTCAgentClient] centrifuge connected, setting state to connected"),this.wasConnected=!0,this.setConnectionState("connected"),this.subscribeChannels()}),this.centrifuge.on("disconnected",e=>{console.log("[RTCAgentClient] centrifuge disconnected, reason:",e==null?void 0:e.reason),this.setConnectionState("disconnected",e==null?void 0:e.reason)}),this.centrifuge.on("error",e=>{var r;console.error("[RTCAgentClient] centrifuge error:",e==null?void 0:e.error),this.emit("error",new Error(((r=e==null?void 0:e.error)==null?void 0:r.message)??"centrifuge error"))}),console.log("[RTCAgentClient] calling centrifuge.connect() synchronously"),this.centrifuge.connect(),console.log("[RTCAgentClient] centrifuge.connect() returned, state:",this.connectionState,"(WebSocket not yet established)")}disconnect(){var e;this.shouldReconnect=!1,this.wasConnected=!1,(e=this.centrifuge)==null||e.disconnect(),this.centrifuge=null,this.subscriptions.clear(),this.setConnectionState("disconnected")}async reconnect(){this.disconnect(),await this.connect()}getConnectionState(){return this.connectionState}getUserId(){return this.options.userId}async listSessions(e,r){return this.rpc(Fn.SessionList,{cursor:e,limit:r})}async getSession(e){return this.rpc(Fn.SessionGet,{session_id:e})}async closeSession(e){return this.rpc(Fn.SessionClose,{session_id:e})}async compactSession(e){return this.rpc(Fn.SessionCompact,e)}async updateSession(e){return this.rpc(Fn.SessionUpdate,e)}async sendMessage(e){return this.rpc(Fn.MessageSend,e)}async forkSession(e){return this.rpc(Fn.SessionFork,e)}async stopTurn(e){return this.rpc(Fn.TurnStop,{session_id:e})}async listMessages(e,r,n){return this.rpc(Fn.MessageList,{session_id:e,cursor:r,limit:n})}async listTurns(e,r,n){return this.rpc(Fn.TurnList,{session_id:e,cursor:r,limit:n})}async listRtc(e,r,n){return this.rpc(Fn.RtcList,{session_id:e,cursor:r,limit:n})}async updateRtcStatus(e,r){return this.rpc(Fn.RtcUpdateStatus,{rtc_id:e,status:r})}async submitRtcResult(e,r,n,s){return this.rpc(Fn.RtcSubmitResult,{rtc_id:e,success:r,result:n,error:s})}async applyUpdates(e){let r=this.applyUpdatesQueue;const n=(async()=>{r&&await r;for(const s of e)await this.processUpdate(s)})();this.applyUpdatesQueue=n;try{await n}finally{this.applyUpdatesQueue===n&&(this.applyUpdatesQueue=null)}}async processUpdate(e){var n,s,c,a,f,p;const r=`topic:u=${this.options.userId}`;if(e.offset>0){const h=await((s=(n=this.options).getLastOffset)==null?void 0:s.call(n,r)),y=h==null?void 0:h.offset,g=(h==null?void 0:h.epoch)??this.epochCache.get(r)??"";if(y!==void 0&&e.offset>y+1){await this.fillOffsetGap(r,y,g,e.offset);const b=await((a=(c=this.options).getLastOffset)==null?void 0:a.call(c,r)),S=b==null?void 0:b.offset,O=b==null?void 0:b.epoch,A=this.epochCache.get(r)??"";if(S===void 0||S!==e.offset-1)throw new Error(`[RTCAgentClient] Offset gap fill failed: expected ${e.offset-1}, got ${S}. Rejecting update ${e.offset} to maintain strict +1 continuity.`);if(O!==void 0&&O!==A)throw new Error(`[RTCAgentClient] Epoch mismatch after gap fill: expected '${A}', got '${O}'. Rejecting update ${e.offset} to prevent data corruption.`)}}if(this.options.onPublication){const h={channel:`topic:u=${this.options.userId}`,offset:e.offset,data:e};await this.options.onPublication(h)}if(e.offset>0){const h=this.epochCache.get(r)??"";await((p=(f=this.options).updateOffset)==null?void 0:p.call(f,r,e.offset,h))}}on(e,r){let n=this.listeners.get(e);return n||(n=new Set,this.listeners.set(e,n)),n.add(r),()=>{n.delete(r)}}emit(e,r){const n=this.listeners.get(e);if(n)for(const s of n)try{s(r)}catch(c){console.error(`[RTCAgentClient] listener for '${e}' threw:`,c)}}setConnectionState(e,r){var s,c;if(console.log("[RTCAgentClient] setConnectionState:",e,"reason:",r,"previous:",this.connectionState),this.connectionState===e)return;this.connectionState=e;const n={state:e,reason:r};this.emit("connection",n),(c=(s=this.options).onConnectionStateChange)==null||c.call(s,n)}_isTokenExpired(e){try{const r=e.split(".");if(r.length!==3)return!1;const n=JSON.parse(atob(r[1]));return typeof n.exp!="number"?!1:n.exp*1e3<Date.now()}catch{return!1}}async rpc(e,r){if(!this.centrifuge)throw new Error("RTCAgentClient not connected");if(this.connectionState!=="connected")throw new Error(`Cannot call RPC '${e}': connection state is ${this.connectionState}`);try{return(await this.centrifuge.rpc(e,r)).data}catch(n){throw console.error(`[RTCAgentClient] RPC '${e}' failed:`,n),n}}subscribeChannels(){var s,c;if(!this.centrifuge||!this.options.userId)return;const e=this.options.userId,r=`topic:u=${e}`;if(!this.subscriptions.has(r)){const a=this.centrifuge.newSubscription(r);this.subscriptions.set(r,a),a.on("publication",async f=>{const p=f.data;try{await this.applyUpdates([p])}catch(h){console.error(`[RTCAgentClient] applyUpdates failed for offset ${p.offset} on channel ${r}:`,h),this.emit("error",h instanceof Error?h:new Error(String(h)))}}),a.on("subscribed",async f=>{var p,h,y,g,b,S,O,A;if(f.streamPosition){const _=f.streamPosition.epoch,C=f.streamPosition.offset;this.epochCache.set(r,_);const E=await((h=(p=this.options).getLastOffset)==null?void 0:h.call(p,r)),x=E==null?void 0:E.offset;if(x===void 0)await((g=(y=this.options).updateOffset)==null?void 0:g.call(y,r,C,_));else if(!(C<=x)){const T=(E==null?void 0:E.epoch)??this.epochCache.get(r)??"";try{await this.fillOffsetGap(r,x,T,C+1);const j=await((S=(b=this.options).getLastOffset)==null?void 0:S.call(b,r)),R=j==null?void 0:j.offset,I=j==null?void 0:j.epoch;if(R===void 0||R!==C)throw new Error(`[RTCAgentClient] Offset gap fill failed on subscribe: expected ${C}, got ${R}. Offline updates may be lost.`);if(I!==void 0&&I!==_)throw new Error(`[RTCAgentClient] Epoch mismatch after gap fill on subscribe: expected '${_}', got '${I}'. Server may have restarted.`);await((A=(O=this.options).updateOffset)==null?void 0:A.call(O,r,C,_))}catch(j){console.error(`[RTCAgentClient] fillOffsetGap failed on subscribe for offset ${C}:`,j),this.emit("error",j instanceof Error?j:new Error(String(j)))}}}})}(s=this.subscriptions.get(r))==null||s.subscribe();const n=`live:u=${e}`;if(!this.subscriptions.has(n)){const a=this.centrifuge.newSubscription(n);this.subscriptions.set(n,a),a.on("publication",async f=>{const p={channel:n,data:f.data};await this.handlePublication(p,a)})}(c=this.subscriptions.get(n))==null||c.subscribe()}async fillOffsetGap(e,r,n,s){const c=this.subscriptions.get(e);if(!c){console.warn(`[RTCAgentClient] fillOffsetGap: subscription not found for channel ${e}`);return}let a={since:{offset:r,epoch:n},limit:void 0,reverse:!1};if(s){const f=s-r-1;if(f<=0)return;a.limit=f}try{const f=await c.history(a);for(const p of f.publications){const h=p.data;await this.processUpdate(h)}}catch(f){throw console.error(`[RTCAgentClient] fillOffsetGap failed for channel ${e}:`,f),f}}async handlePublication(e,r){if(this.options.onPublication)try{await this.options.onPublication(e)}catch(n){throw console.error(`[RTCAgentClient] onPublication threw for channel '${e.channel}':`,n),r.unsubscribe(),n}}}var Ii=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function ZT(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Ry={exports:{}};(function(t,e){((r,n)=>{t.exports=n()})(Ii,function(){var r=function(v,P){return(r=Object.setPrototypeOf||({__proto__:[]}instanceof Array?function(M,V){M.__proto__=V}:function(M,V){for(var re in V)Object.prototype.hasOwnProperty.call(V,re)&&(M[re]=V[re])}))(v,P)},n=function(){return(n=Object.assign||function(v){for(var P,M=1,V=arguments.length;M<V;M++)for(var re in P=arguments[M])Object.prototype.hasOwnProperty.call(P,re)&&(v[re]=P[re]);return v}).apply(this,arguments)};function s(v,P,M){for(var V,re=0,pe=P.length;re<pe;re++)!V&&re in P||((V=V||Array.prototype.slice.call(P,0,re))[re]=P[re]);return v.concat(V||Array.prototype.slice.call(P))}var c=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:Ii,a=Object.keys,f=Array.isArray;function p(v,P){return typeof P=="object"&&a(P).forEach(function(M){v[M]=P[M]}),v}typeof Promise>"u"||c.Promise||(c.Promise=Promise);var h=Object.getPrototypeOf,y={}.hasOwnProperty;function g(v,P){return y.call(v,P)}function b(v,P){typeof P=="function"&&(P=P(h(v))),(typeof Reflect>"u"?a:Reflect.ownKeys)(P).forEach(function(M){O(v,M,P[M])})}var S=Object.defineProperty;function O(v,P,M,V){S(v,P,p(M&&g(M,"get")&&typeof M.get=="function"?{get:M.get,set:M.set,configurable:!0}:{value:M,configurable:!0,writable:!0},V))}function A(v){return{from:function(P){return v.prototype=Object.create(P.prototype),O(v.prototype,"constructor",v),{extend:b.bind(null,v.prototype)}}}}var _=Object.getOwnPropertyDescriptor,C=[].slice;function E(v,P,M){return C.call(v,P,M)}function x(v,P){return P(v)}function T(v){if(!v)throw new Error("Assertion Failed")}function j(v){c.setImmediate?setImmediate(v):setTimeout(v,0)}function R(v,P){if(typeof P=="string"&&g(v,P))return v[P];if(!P)return v;if(typeof P!="string"){for(var M=[],V=0,re=P.length;V<re;++V){var pe=R(v,P[V]);M.push(pe)}return M}var Te,Ne=P.indexOf(".");return Ne===-1||(Te=v[P.substr(0,Ne)])==null?void 0:R(Te,P.substr(Ne+1))}function I(v,P,M){if(v&&P!==void 0&&!("isFrozen"in Object&&Object.isFrozen(v)))if(typeof P!="string"&&"length"in P){T(typeof M!="string"&&"length"in M);for(var V=0,re=P.length;V<re;++V)I(v,P[V],M[V])}else{var pe=P.indexOf(".");if(pe!==-1){var Te=P.substr(0,pe),pe=P.substr(pe+1);if(pe==="")M===void 0?f(v)&&!isNaN(parseInt(Te))?v.splice(Te,1):delete v[Te]:v[Te]=M;else{var Ne=v[Te];if(!Ne||!g(v,Te)){if(M===void 0)return;Ne=v[Te]={}}I(Ne,pe,M)}}else M===void 0?f(v)&&!isNaN(parseInt(P))?v.splice(P,1):delete v[P]:v[P]=M}}function D(v){var P,M={};for(P in v)g(v,P)&&(M[P]=v[P]);return M}var Z=[].concat;function J(v){return Z.apply([],v)}var ae="BigUint64Array,BigInt64Array,Array,Boolean,String,Date,RegExp,Blob,File,FileList,FileSystemFileHandle,FileSystemDirectoryHandle,ArrayBuffer,DataView,Uint8ClampedArray,ImageBitmap,ImageData,Map,Set,CryptoKey".split(",").concat(J([8,16,32,64].map(function(v){return["Int","Uint","Float"].map(function(P){return P+v+"Array"})}))).filter(function(v){return c[v]}),N=new Set(ae.map(function(v){return c[v]})),$=null;function ne(v){return $=new WeakMap,v=function P(M){if(!M||typeof M!="object")return M;var V=$.get(M);if(V)return V;if(f(M)){V=[],$.set(M,V);for(var re=0,pe=M.length;re<pe;++re)V.push(P(M[re]))}else if(N.has(M.constructor))V=M;else{var Te,Ne=h(M);for(Te in V=Ne===Object.prototype?{}:Object.create(Ne),$.set(M,V),M)g(M,Te)&&(V[Te]=P(M[Te]))}return V}(v),$=null,v}var me={}.toString;function Ce(v){return me.call(v).slice(8,-1)}var Ae=typeof Symbol<"u"?Symbol.iterator:"@@iterator",ce=typeof Ae=="symbol"?function(v){var P;return v!=null&&(P=v[Ae])&&P.apply(v)}:function(){return null};function ue(v,P){P=v.indexOf(P),0<=P&&v.splice(P,1)}var K={};function Y(v){var P,M,V,re;if(arguments.length===1){if(f(v))return v.slice();if(this===K&&typeof v=="string")return[v];if(re=ce(v))for(M=[];!(V=re.next()).done;)M.push(V.value);else{if(v==null)return[v];if(typeof(P=v.length)!="number")return[v];for(M=new Array(P);P--;)M[P]=v[P]}}else for(P=arguments.length,M=new Array(P);P--;)M[P]=arguments[P];return M}var he=typeof Symbol<"u"?function(v){return v[Symbol.toStringTag]==="AsyncFunction"}:function(){return!1},ae=["Unknown","Constraint","Data","TransactionInactive","ReadOnly","Version","NotFound","InvalidState","InvalidAccess","Abort","Timeout","QuotaExceeded","Syntax","DataClone"],oe=["Modify","Bulk","OpenFailed","VersionChange","Schema","Upgrade","InvalidTable","MissingAPI","NoSuchDatabase","InvalidArgument","SubTransaction","Unsupported","Internal","DatabaseClosed","PrematureCommit","ForeignAwait"].concat(ae),U={VersionChanged:"Database version changed by other database connection",DatabaseClosed:"Database has been closed",Abort:"Transaction aborted",TransactionInactive:"Transaction has already completed or failed",MissingAPI:"IndexedDB API missing. Please visit https://tinyurl.com/y2uuvskb"};function L(v,P){this.name=v,this.message=P}function H(v,P){return v+". Errors: "+Object.keys(P).map(function(M){return P[M].toString()}).filter(function(M,V,re){return re.indexOf(M)===V}).join(`
11
+ `).map(r=>JSON.parse(r))}applyDeltaIfNeeded(e,r){let n,s,c,a;if(e.delta){a=!0;const f=new TextEncoder().encode(e.data),p=YT(r,f);n=JSON.parse(new TextDecoder().decode(p)),s=p,c=f.length}else a=!1,n=JSON.parse(e.data),s=new TextEncoder().encode(e.data),c=s.length;return{newData:n,newPrevValue:s,isDelta:a,wireBytes:c,fullBytes:s.length}}}const XT={headers:{},token:"",getToken:null,data:null,getData:null,debug:!1,name:"js",version:"",fetch:null,readableStream:null,websocket:null,eventsource:null,sockjs:null,sockjsOptions:{},emulationEndpoint:"/emulation",minReconnectDelay:500,maxReconnectDelay:2e4,timeout:5e3,maxServerPingDelay:1e4,networkEventTarget:null};class xs extends Error{constructor(e){super(e),this.name=this.constructor.name}}class wl extends ky{constructor(e,r){super(),this._reconnectTimeout=null,this._refreshTimeout=null,this._serverPingTimeout=null,this.state=Br.Disconnected,this._transportIsOpen=!1,this._endpoint=e,this._emulation=!1,this._transports=[],this._currentTransportIndex=0,this._triedAllTransports=!1,this._transportWasOpen=!1,this._transport=null,this._transportId=0,this._deviceWentOffline=!1,this._transportClosed=!0,this._codec=new By,this._reconnecting=!1,this._reconnectTimeout=null,this._reconnectAttempts=0,this._client=null,this._session="",this._node="",this._subs={},this._serverSubs={},this._commandId=0,this._commands=[],this._batching=!1,this._refreshRequired=!1,this._refreshTimeout=null,this._callbacks={},this._token="",this._data=null,this._dispatchPromise=Promise.resolve(),this._serverPing=0,this._serverPingTimeout=null,this._sendPong=!1,this._promises={},this._promiseId=0,this._debugEnabled=!1,this._networkEventsSet=!1,this._config=Object.assign(Object.assign({},XT),r),this._configure(),this._debugEnabled?(this.on("state",n=>{this._debug("client state",n.oldState,"->",n.newState)}),this.on("error",n=>{this._debug("client error",n)})):this.on("error",function(){Function.prototype()})}newSubscription(e,r){if(this.getSubscription(e)!==null)throw new Error("Subscription to the channel "+e+" already exists");const n=new qT(this,e,r);return this._subs[e]=n,n}newMapSubscription(e,r){if(this.getSubscription(e)!==null)throw new Error("Subscription to the channel "+e+" already exists");const n=new Af(this,e,{token:r==null?void 0:r.token,getToken:r==null?void 0:r.getToken,data:r==null?void 0:r.data,minResubscribeDelay:r==null?void 0:r.minResubscribeDelay,maxResubscribeDelay:r==null?void 0:r.maxResubscribeDelay,delta:r==null?void 0:r.delta,tagsFilter:r==null?void 0:r.tagsFilter,map:!0,mapPageSize:r==null?void 0:r.pageSize,mapUnrecoverableStrategy:r==null?void 0:r.unrecoverableStrategy});return this._subs[e]=n,n}newMapClientsSubscription(e,r){if(this.getSubscription(e)!==null)throw new Error("Subscription to the channel "+e+" already exists");const n=new Af(this,e,{token:r==null?void 0:r.token,getToken:r==null?void 0:r.getToken,data:r==null?void 0:r.data,minResubscribeDelay:r==null?void 0:r.minResubscribeDelay,maxResubscribeDelay:r==null?void 0:r.maxResubscribeDelay,delta:r==null?void 0:r.delta,tagsFilter:r==null?void 0:r.tagsFilter,map:!0,mapPresenceType:2,mapPageSize:r==null?void 0:r.pageSize,mapUnrecoverableStrategy:r==null?void 0:r.unrecoverableStrategy});return this._subs[e]=n,n}newMapUsersSubscription(e,r){if(this.getSubscription(e)!==null)throw new Error("Subscription to the channel "+e+" already exists");const n=new Af(this,e,{token:r==null?void 0:r.token,getToken:r==null?void 0:r.getToken,data:r==null?void 0:r.data,minResubscribeDelay:r==null?void 0:r.minResubscribeDelay,maxResubscribeDelay:r==null?void 0:r.maxResubscribeDelay,delta:r==null?void 0:r.delta,tagsFilter:r==null?void 0:r.tagsFilter,map:!0,mapPresenceType:3,mapPageSize:r==null?void 0:r.pageSize,mapUnrecoverableStrategy:r==null?void 0:r.unrecoverableStrategy});return this._subs[e]=n,n}newSharedPollSubscription(e,r){if(this.getSubscription(e)!==null)throw new Error("Subscription to the channel "+e+" already exists");const n=new $T(this,e,{token:r==null?void 0:r.token,getToken:r==null?void 0:r.getToken,data:r==null?void 0:r.data,minResubscribeDelay:r==null?void 0:r.minResubscribeDelay,maxResubscribeDelay:r==null?void 0:r.maxResubscribeDelay,delta:r==null?void 0:r.delta,sharedPoll:!0,sharedPollGetSignature:r==null?void 0:r.getSignature});return this._subs[e]=n,n}getSubscription(e){return this._getSub(e)}getMapSubscription(e){return this._getSub(e)}getSharedPollSubscription(e){return this._getSub(e)}removeSubscription(e){e&&(e.state!==ln.Unsubscribed&&e.unsubscribe(),this._removeSubscription(e))}removeMapSubscription(e){this.removeSubscription(e)}removeSharedPollSubscription(e){this.removeSubscription(e)}subscriptions(){return this._subs}mapSubscriptions(){const e={};for(const[r,n]of Object.entries(this._subs))n.type==="map"&&(e[r]=n);return e}sharedPollSubscriptions(){const e={};for(const[r,n]of Object.entries(this._subs))n.type==="shared_poll"&&(e[r]=n);return e}ready(e){return Dr(this,void 0,void 0,function*(){switch(this.state){case Br.Disconnected:throw{code:ur.clientDisconnected,message:"client disconnected"};case Br.Connected:return;default:return new Promise((r,n)=>{const s={resolve:r,reject:n};e&&(s.timeout=setTimeout(()=>{n({code:ur.timeout,message:"timeout"})},e)),this._promises[this._nextPromiseId()]=s})}})}connect(){if(this._isConnected()){this._debug("connect called when already connected");return}if(this._isConnecting()){this._debug("connect called when already connecting");return}this._debug("connect called"),this._reconnectAttempts=0,this._startConnecting()}disconnect(){this._disconnect(Da.disconnectCalled,"disconnect called",!1)}setToken(e){this._token=e}setData(e){this._data=e}setHeaders(e){this._config.headers=e}send(e){return Dr(this,void 0,void 0,function*(){const r={send:{data:e}};if(yield this._methodCall(),!this._transportSendCommands([r]))throw this._createErrorObject(ur.transportWriteError,"transport write error")})}rpc(e,r){return Dr(this,void 0,void 0,function*(){const n={rpc:{method:e,data:r}};return yield this._methodCall(),{data:(yield this._callPromise(n,c=>c.rpc)).data}})}publish(e,r){return Dr(this,void 0,void 0,function*(){const n={publish:{channel:e,data:r}};return yield this._methodCall(),yield this._callPromise(n,()=>({})),{}})}mapPublish(e,r,n){return Dr(this,void 0,void 0,function*(){const s={publish:{channel:e,type:1,key:r,data:n}};return yield this._methodCall(),yield this._callPromise(s,()=>({})),{}})}mapRemove(e,r){return Dr(this,void 0,void 0,function*(){const n={publish:{channel:e,type:1,key:r,removed:!0}};return yield this._methodCall(),yield this._callPromise(n,()=>({})),{}})}history(e,r){return Dr(this,void 0,void 0,function*(){const n={history:this._getHistoryRequest(e,r)};yield this._methodCall();const s=yield this._callPromise(n,a=>a.history),c=[];if(s.publications)for(let a=0;a<s.publications.length;a++)c.push(this._getPublicationContext(e,s.publications[a]));return{publications:c,epoch:s.epoch||"",offset:s.offset||0}})}presence(e){return Dr(this,void 0,void 0,function*(){const r={presence:{channel:e}};yield this._methodCall();const s=(yield this._callPromise(r,c=>c.presence)).presence;for(const c in s)if(Object.prototype.hasOwnProperty.call(s,c)){const a=s[c],f=a.conn_info,p=a.chan_info;f&&(a.connInfo=f),p&&(a.chanInfo=p)}return{clients:s}})}presenceStats(e){return Dr(this,void 0,void 0,function*(){const r={presence_stats:{channel:e}};yield this._methodCall();const n=yield this._callPromise(r,s=>s.presence_stats);return{numUsers:n.num_users,numClients:n.num_clients}})}startBatching(){this._batching=!0}stopBatching(){const e=this;Promise.resolve().then(function(){Promise.resolve().then(function(){e._batching=!1,e._flush()})})}_debug(...e){this._debugEnabled&&jT("debug",e)}_codecName(){return this._codec.name()}_formatOverride(){}_configure(){if(!("Promise"in globalThis))throw new Error("Promise polyfill required");if(!this._endpoint)throw new Error("endpoint configuration required");if(this._config.token!==null&&(this._token=this._config.token),this._config.data!==null&&(this._data=this._config.data),this._codec=new By,this._formatOverride(),(this._config.debug===!0||FT("centrifuge.debug"))&&(this._debugEnabled=!0),this._debug("config",this._config),typeof this._endpoint!="string")if(Array.isArray(this._endpoint)){this._transports=this._endpoint,this._emulation=!0;for(const e in this._transports)if(this._transports.hasOwnProperty(e)){const r=this._transports[e];if(!r.endpoint||!r.transport)throw new Error("malformed transport configuration");const n=r.transport;if(["websocket","http_stream","sse","sockjs","webtransport"].indexOf(n)<0)throw new Error("unsupported transport name: "+n)}}else throw new Error("unsupported url configuration type: only string or array of objects are supported")}_setState(e){if(this.state!==e){this._reconnecting=!1;const r=this.state;return this.state=e,this.emit("state",{newState:e,oldState:r}),!0}return!1}_isDisconnected(){return this.state===Br.Disconnected}_isConnecting(){return this.state===Br.Connecting}_isConnected(){return this.state===Br.Connected}_nextCommandId(){return++this._commandId}_setNetworkEvents(){if(this._networkEventsSet)return;let e=null;this._config.networkEventTarget!==null?e=this._config.networkEventTarget:typeof globalThis.addEventListener<"u"&&(e=globalThis),e&&(e.addEventListener("offline",()=>{this._debug("offline event triggered"),(this.state===Br.Connected||this.state===Br.Connecting)&&(this._disconnect(Es.transportClosed,"transport closed",!0),this._deviceWentOffline=!0)}),e.addEventListener("online",()=>{this._debug("online event triggered"),this.state===Br.Connecting&&(this._deviceWentOffline&&!this._transportClosed&&(this._deviceWentOffline=!1,this._transportClosed=!0),this._clearReconnectTimeout(),this._startReconnecting())}),this._networkEventsSet=!0)}_getReconnectDelay(){const e=na(this._reconnectAttempts,this._config.minReconnectDelay,this._config.maxReconnectDelay);return this._reconnectAttempts+=1,e}_clearOutgoingRequests(){for(const e in this._callbacks)if(this._callbacks.hasOwnProperty(e)){const r=this._callbacks[e];clearTimeout(r.timeout);const n=r.errback;if(!n)continue;n({error:this._createErrorObject(ur.connectionClosed,"connection closed")})}this._callbacks={}}_clearConnectedState(){this._client=null,this._clearServerPingTimeout(),this._clearRefreshTimeout();for(const e in this._subs){if(!this._subs.hasOwnProperty(e))continue;const r=this._subs[e];r.state===ln.Subscribed&&r._setSubscribing(_l.transportClosed,"transport closed")}for(const e in this._serverSubs)this._serverSubs.hasOwnProperty(e)&&this.emit("subscribing",{channel:e})}_handleWriteError(e){for(const r of e){const n=r.id;if(!(n in this._callbacks))continue;const s=this._callbacks[n];clearTimeout(this._callbacks[n].timeout),delete this._callbacks[n];const c=s.errback;c({error:this._createErrorObject(ur.transportWriteError,"transport write error")})}}_transportSendCommands(e){if(!e.length)return!0;if(!this._transport)return!1;try{this._transport.send(this._codec.encodeCommands(e),this._session,this._node)}catch(r){return this._debug("error writing commands",r),this._handleWriteError(e),!1}return!0}_advanceTransportIndex(){this._currentTransportIndex++,this._currentTransportIndex>=this._transports.length&&(this._triedAllTransports=!0,this._currentTransportIndex=0)}_initializeTransport(){let e;this._config.websocket!==null?e=this._config.websocket:typeof globalThis.WebSocket!="function"&&typeof globalThis.WebSocket!="object"||(e=globalThis.WebSocket);let r=null;this._config.sockjs!==null?r=this._config.sockjs:typeof globalThis.SockJS<"u"&&(r=globalThis.SockJS);let n=null;this._config.eventsource!==null?n=this._config.eventsource:typeof globalThis.EventSource<"u"&&(n=globalThis.EventSource);let s=null;this._config.fetch!==null?s=this._config.fetch:typeof globalThis.fetch<"u"&&(s=globalThis.fetch);let c=null;if(this._config.readableStream!==null?c=this._config.readableStream:typeof globalThis.ReadableStream<"u"&&(c=globalThis.ReadableStream),this._emulation){this._currentTransportIndex>=this._transports.length&&(this._triedAllTransports=!0,this._currentTransportIndex=0);let S=0;for(;;){if(S>=this._transports.length)throw new Error("no supported transport found");const O=this._transports[this._currentTransportIndex],A=O.transport,_=O.endpoint;if(A==="websocket"){if(this._debug("trying websocket transport"),this._transport=new Dy(_,{websocket:e}),!this._transport.supported()){this._debug("websocket transport not available"),this._advanceTransportIndex(),S++;continue}}else if(A==="webtransport"){if(this._debug("trying webtransport transport"),this._transport=new WT(_,{webtransport:globalThis.WebTransport,decoder:this._codec,encoder:this._codec}),!this._transport.supported()){this._debug("webtransport transport not available"),this._advanceTransportIndex(),S++;continue}}else if(A==="http_stream"){if(this._debug("trying http_stream transport"),this._transport=new VT(_,{fetch:s,readableStream:c,emulationEndpoint:this._config.emulationEndpoint,decoder:this._codec,encoder:this._codec}),!this._transport.supported()){this._debug("http_stream transport not available"),this._advanceTransportIndex(),S++;continue}}else if(A==="sse"){if(this._debug("trying sse transport"),this._transport=new KT(_,{eventsource:n,fetch:s,emulationEndpoint:this._config.emulationEndpoint}),!this._transport.supported()){this._debug("sse transport not available"),this._advanceTransportIndex(),S++;continue}}else if(A==="sockjs"){if(this._debug("trying sockjs"),this._transport=new UT(_,{sockjs:r,sockjsOptions:this._config.sockjsOptions}),!this._transport.supported()){this._debug("sockjs transport not available"),this._advanceTransportIndex(),S++;continue}}else throw new Error("unknown transport "+A);break}}else{if(RT(this._endpoint,"http"))throw new Error("Provide explicit transport endpoints configuration in case of using HTTP (i.e. using array of TransportEndpoint instead of a single string), or use ws(s):// scheme in an endpoint if you aimed using WebSocket transport");if(this._debug("client will use websocket"),this._transport=new Dy(this._endpoint,{websocket:e}),!this._transport.supported())throw new Error("WebSocket constructor not found, make sure it is available globally or passed as a dependency in Centrifuge options")}const a=this,f=this._transport,p=this._nextTransportId();a._debug("id of transport",p);let h=!1;const y=[];if(this._transport.emulation()){const S=a._sendConnect(!0);y.push(S)}this._setNetworkEvents();const g=this._codec.encodeCommands(y);this._transportClosed=!1;let b;b=setTimeout(function(){f.close()},this._config.timeout),this._transport.initialize(this._codecName(),{onOpen:function(){if(b&&(clearTimeout(b),b=null),a._transportId!=p){a._debug("open callback from non-actual transport"),f.close();return}h=!0,a._debug(f.subName(),"transport open"),!f.emulation()&&(a._transportIsOpen=!0,a._transportWasOpen=!0,a.startBatching(),a._sendConnect(!1),a._sendSubscribeCommands(),a.stopBatching(),a.emit("__centrifuge_debug:connect_frame_sent",{}))},onError:function(S){if(a._transportId!=p){a._debug("error callback from non-actual transport");return}a._debug("transport level error",S)},onClose:function(S){if(b&&(clearTimeout(b),b=null),a._transportId!=p){a._debug("close callback from non-actual transport");return}a._debug(f.subName(),"transport closed"),a._transportClosed=!0,a._transportIsOpen=!1;let O="connection closed",A=!0,_=0;if(S&&"code"in S&&S.code&&(_=S.code),S&&S.reason)try{const C=JSON.parse(S.reason);O=C.reason,A=C.reconnect}catch{O=S.reason,(_>=3500&&_<4e3||_>=4500&&_<5e3)&&(A=!1)}_<3e3?(_===1009?(_=Da.messageSizeLimit,O="message size limit exceeded",A=!1):(_=Es.transportClosed,O="transport closed"),a._emulation&&!a._transportWasOpen&&a._advanceTransportIndex()):a._transportWasOpen=!0,a._isConnecting()&&!h&&a.emit("error",{type:"transport",error:{code:ur.transportClosed,message:"transport closed"},transport:f.name()}),a._reconnecting=!1,a._disconnect(_,O,A)},onMessage:function(S){a._dataReceived(S)}},g),a.emit("__centrifuge_debug:transport_initialized",{})}_sendConnect(e){const r=this._constructConnectCommand(),n=this;return this._call(r,e).then(s=>{const c=s.reply.connect;n._connectResponse(c),s.next&&s.next()},s=>{n._connectError(s.error),s.next&&s.next()}),r}_startReconnecting(){if(this._debug("start reconnecting"),!this._isConnecting()){this._debug("stop reconnecting: client not in connecting state");return}if(this._reconnecting){this._debug("reconnect already in progress, return from reconnect routine");return}if(this._transportClosed===!1){this._debug("waiting for transport close");return}this._reconnecting=!0;const e=this._token==="";if(!(this._refreshRequired||e&&this._config.getToken!==null)){this._config.getData?this._config.getData().then(s=>{this._isConnecting()&&(this._data=s,this._initializeTransport())}).catch(s=>this._handleGetDataError(s)):this._initializeTransport();return}const n=this;this._getToken().then(function(s){if(n._isConnecting()){if(s==null||s==null){n._failUnauthorized();return}n._token=s,n._debug("connection token refreshed"),n._config.getData?n._config.getData().then(function(c){n._isConnecting()&&(n._data=c,n._initializeTransport())}).catch(c=>n._handleGetDataError(c)):n._initializeTransport()}}).catch(function(s){if(!n._isConnecting())return;if(s instanceof xs){n._failUnauthorized();return}n.emit("error",{type:"connectToken",error:{code:ur.clientConnectToken,message:s!==void 0?s.toString():""}});const c=n._getReconnectDelay();n._debug("error on getting connection token, reconnect after "+c+" milliseconds",s),n._reconnecting=!1,n._reconnectTimeout=setTimeout(()=>{n._startReconnecting()},c)})}_handleGetDataError(e){if(e instanceof xs){this._failUnauthorized();return}this.emit("error",{type:"connectData",error:{code:ur.badConfiguration,message:(e==null?void 0:e.toString())||""}});const r=this._getReconnectDelay();this._debug("error on getting connect data, reconnect after "+r+" milliseconds",e),this._reconnecting=!1,this._reconnectTimeout=setTimeout(()=>{this._startReconnecting()},r)}_connectError(e){this.state===Br.Connecting&&(e.code===109&&(this._refreshRequired=!0),e.code<100||e.temporary===!0||e.code===109?(this.emit("error",{type:"connect",error:e}),this._debug("closing transport due to connect error"),this._disconnect(e.code,e.message,!0)):this._disconnect(e.code,e.message,!1))}_scheduleReconnect(){if(!this._isConnecting())return;let e=!1;this._emulation&&!this._transportWasOpen&&!this._triedAllTransports&&(e=!0);let r=this._getReconnectDelay();e&&(r=0),this._debug("reconnect after "+r+" milliseconds"),this._clearReconnectTimeout(),this._reconnectTimeout=setTimeout(()=>{this._startReconnecting()},r)}_constructConnectCommand(){const e={};this._token&&(e.token=this._token),this._data&&(e.data=this._data),this._config.name&&(e.name=this._config.name),this._config.version&&(e.version=this._config.version),Object.keys(this._config.headers).length>0&&(e.headers=this._config.headers);const r={};let n=!1;for(const s in this._serverSubs)if(this._serverSubs.hasOwnProperty(s)&&this._serverSubs[s].recoverable){n=!0;const c={recover:!0};this._serverSubs[s].offset&&(c.offset=this._serverSubs[s].offset),this._serverSubs[s].epoch&&(c.epoch=this._serverSubs[s].epoch),r[s]=c}return n&&(e.subs=r),{connect:e}}_getHistoryRequest(e,r){const n={channel:e};return r!==void 0&&(r.since&&(n.since={offset:r.since.offset},r.since.epoch&&(n.since.epoch=r.since.epoch)),r.limit!==void 0&&(n.limit=r.limit),r.reverse===!0&&(n.reverse=!0)),n}_methodCall(){return this._isConnected()?Promise.resolve():new Promise((e,r)=>{const n=setTimeout(function(){r({code:ur.timeout,message:"timeout"})},this._config.timeout);this._promises[this._nextPromiseId()]={timeout:n,resolve:e,reject:r}})}_callPromise(e,r){return new Promise((n,s)=>{this._call(e,!1).then(c=>{var a;const f=r(c.reply);n(f),(a=c.next)===null||a===void 0||a.call(c)},c=>{var a;s(c.error),(a=c.next)===null||a===void 0||a.call(c)})})}_dataReceived(e){this._serverPing>0&&this._waitServerPing();const r=this._codec.decodeReplies(e);this._dispatchPromise=this._dispatchPromise.then(()=>{let n;this._dispatchPromise=new Promise(s=>{n=s}),this._dispatchSynchronized(r,n)})}_dispatchSynchronized(e,r){let n=Promise.resolve();for(const s in e)e.hasOwnProperty(s)&&(n=n.then(()=>this._dispatchReply(e[s])));n.then(()=>{r()})}_dispatchReply(e){let r;const n=new Promise(c=>{r=c});if(e==null)return this._debug("dispatch: got undefined or null reply"),r(),n;const s=e.id;return s&&s>0?this._handleReply(e,r):e.push?this._handlePush(e.push,r):this._handleServerPing(r),n}_call(e,r){return new Promise((n,s)=>{e.id=this._nextCommandId(),this._registerCall(e.id,n,s),r||this._addCommand(e)})}_startConnecting(){this._debug("start connecting"),this._setState(Br.Connecting)&&this.emit("connecting",{code:Es.connectCalled,reason:"connect called"}),this._client=null,this._startReconnecting()}_disconnect(e,r,n){if(e===Da.stateInvalidated){this._token="",this._refreshRequired=!0;for(const f in this._subs)this._subs.hasOwnProperty(f)&&this._subs[f]._invalidateState();for(const f in this._serverSubs)this._serverSubs.hasOwnProperty(f)&&(this._serverSubs[f].offset=0,this._serverSubs[f].epoch="_")}if(this._isDisconnected())return;this._transportIsOpen=!1;const s=this.state;this._reconnecting=!1;const c={code:e,reason:r};let a;if(n?a=this._setState(Br.Connecting):(a=this._setState(Br.Disconnected),this._rejectPromises({code:ur.clientDisconnected,message:"disconnected"})),this._clearOutgoingRequests(),s===Br.Connecting&&this._clearReconnectTimeout(),s===Br.Connected&&this._clearConnectedState(),a&&(this._isConnecting()?this.emit("connecting",c):this.emit("disconnected",c)),this._transport){this._debug("closing existing transport");const f=this._transport;this._transport=null,f.close(),this._transportClosed=!0,this._nextTransportId()}else this._debug("no transport to close");this._scheduleReconnect()}_failUnauthorized(){this._disconnect(Da.unauthorized,"unauthorized",!1)}_getToken(){return this._debug("get connection token"),this._config.getToken?this._config.getToken({}):(this.emit("error",{type:"configuration",error:{code:ur.badConfiguration,message:"token expired but no getToken function set in the configuration"}}),Promise.reject(new xs("")))}_refresh(){const e=this._client,r=this;this._getToken().then(function(n){if(e!==r._client)return;if(!n){r._failUnauthorized();return}if(r._token=n,r._debug("connection token refreshed"),!r._isConnected())return;const s={refresh:{token:r._token}};r._call(s,!1).then(c=>{const a=c.reply.refresh;r._refreshResponse(a),c.next&&c.next()},c=>{r._refreshError(c.error),c.next&&c.next()})}).catch(function(n){if(r._isConnected()){if(n instanceof xs){r._failUnauthorized();return}r.emit("error",{type:"refreshToken",error:{code:ur.clientRefreshToken,message:n!==void 0?n.toString():""}}),r._refreshTimeout=setTimeout(()=>r._refresh(),r._getRefreshRetryDelay())}})}_refreshError(e){e.code<100||e.temporary===!0?(this.emit("error",{type:"refresh",error:e}),this._refreshTimeout=setTimeout(()=>this._refresh(),this._getRefreshRetryDelay())):this._disconnect(e.code,e.message,!1)}_getRefreshRetryDelay(){return na(0,5e3,1e4)}_refreshResponse(e){this._refreshTimeout&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null),e.expires&&(this._client=e.client,this._refreshTimeout=setTimeout(()=>this._refresh(),To(e.ttl)))}_removeSubscription(e){e!==null&&delete this._subs[e.channel]}_unsubscribe(e){if(!this._transportIsOpen)return Promise.resolve();const n={unsubscribe:{channel:e.channel}},s=this;return new Promise((a,f)=>{this._call(n,!1).then(p=>{a(),p.next&&p.next()},p=>{a(),p.next&&p.next(),s._disconnect(Es.unsubscribeError,"unsubscribe error",!0)})})}_getSub(e,r){if(r&&r>0){for(const s in this._subs)if(this._subs.hasOwnProperty(s)){const c=this._subs[s];if(c._id===r)return c}return null}const n=this._subs[e];return n||null}_isServerSub(e){return this._serverSubs[e]!==void 0}_sendSubscribeCommands(){const e=[];for(const r in this._subs){if(!this._subs.hasOwnProperty(r))continue;const n=this._subs[r];if(n._inflight!==!0&&n.state===ln.Subscribing){const s=n._subscribe();s&&e.push(s)}}return e}_connectResponse(e){if(this._transportIsOpen=!0,this._transportWasOpen=!0,this._reconnectAttempts=0,this._refreshRequired=!1,this._isConnected())return;this._client=e.client,this._setState(Br.Connected),this._refreshTimeout&&clearTimeout(this._refreshTimeout),e.expires&&(this._refreshTimeout=setTimeout(()=>this._refresh(),To(e.ttl))),this._session=e.session,this._node=e.node,this.startBatching(),this._sendSubscribeCommands(),this.stopBatching();const r={client:e.client,transport:this._transport.subName()};e.data&&(r.data=e.data),this.emit("connected",r),this._resolvePromises(),this._processServerSubs(e.subs||{}),e.ping&&e.ping>0?(this._serverPing=e.ping*1e3,this._sendPong=e.pong===!0,this._waitServerPing()):this._serverPing=0}_processServerSubs(e){for(const r in e){if(!e.hasOwnProperty(r))continue;const n=e[r];this._serverSubs[r]={offset:n.offset,epoch:n.epoch,recoverable:n.recoverable||!1};const s=this._getSubscribeContext(r,n);this.emit("subscribed",s)}for(const r in e){if(!e.hasOwnProperty(r))continue;const n=e[r];if(n.recovered){const s=n.publications;if(s&&s.length>0)for(const c in s)s.hasOwnProperty(c)&&this._handlePublication(r,s[c])}}for(const r in this._serverSubs)this._serverSubs.hasOwnProperty(r)&&(e[r]||(this.emit("unsubscribed",{channel:r}),delete this._serverSubs[r]))}_clearRefreshTimeout(){this._refreshTimeout!==null&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null)}_clearReconnectTimeout(){this._reconnectTimeout!==null&&(clearTimeout(this._reconnectTimeout),this._reconnectTimeout=null)}_clearServerPingTimeout(){this._serverPingTimeout!==null&&(clearTimeout(this._serverPingTimeout),this._serverPingTimeout=null)}_waitServerPing(){this._config.maxServerPingDelay!==0&&this._isConnected()&&(this._clearServerPingTimeout(),this._serverPingTimeout=setTimeout(()=>{this._isConnected()&&this._disconnect(Es.noPing,"no ping",!0)},this._serverPing+this._config.maxServerPingDelay))}_getSubscribeContext(e,r){const n={channel:e,positioned:!1,recoverable:!1,wasRecovering:!1,recovered:!1,hasRecoveredPublications:!1};r.recovered&&(n.recovered=!0),r.positioned&&(n.positioned=!0),r.recoverable&&(n.recoverable=!0),r.was_recovering&&(n.wasRecovering=!0);let s="";"epoch"in r&&(s=r.epoch);let c=0;return"offset"in r&&(c=r.offset),(n.positioned||n.recoverable)&&(n.streamPosition={offset:c,epoch:s}),Array.isArray(r.publications)&&r.publications.length>0&&(n.hasRecoveredPublications=!0),r.data&&(n.data=r.data),n}_handleReply(e,r){const n=e.id;if(!(n in this._callbacks)){r();return}const s=this._callbacks[n];if(clearTimeout(this._callbacks[n].timeout),delete this._callbacks[n],LT(e)){const c=s.errback;if(!c){r();return}const a={code:e.error.code,message:e.error.message||"",temporary:e.error.temporary||!1};c({error:a,next:r})}else{const c=s.callback;if(!c)return;c({reply:e,next:r})}}_handleJoin(e,r,n){const s=this._getSub(e,n);if(!s){if(e&&this._isServerSub(e)){const c={channel:e,info:this._getJoinLeaveContext(r.info)};this.emit("join",c)}return}s._handleJoin(r)}_handleLeave(e,r,n){const s=this._getSub(e,n);if(!s){if(e&&this._isServerSub(e)){const c={channel:e,info:this._getJoinLeaveContext(r.info)};this.emit("leave",c)}return}s._handleLeave(r)}_handleUnsubscribe(e,r){const n=this._getSub(e,0);if(!n&&e){this._isServerSub(e)&&(delete this._serverSubs[e],this.emit("unsubscribed",{channel:e}));return}r.code<2500?n._setUnsubscribed(r.code,r.reason,!1):(r.code===vo.stateInvalidated&&n._invalidateState(),n._setSubscribing(r.code,r.reason))}_handleSubscribe(e,r){this._serverSubs[e]={offset:r.offset,epoch:r.epoch,recoverable:r.recoverable||!1},this.emit("subscribed",this._getSubscribeContext(e,r))}_handleDisconnect(e){const r=e.code;let n=!0;(r>=3500&&r<4e3||r>=4500&&r<5e3)&&(n=!1),this._disconnect(r,e.reason,n)}_getPublicationContext(e,r){const n={channel:e,data:r.data};return r.offset&&(n.offset=r.offset),r.info&&(n.info=this._getJoinLeaveContext(r.info)),r.tags&&(n.tags=r.tags),n}_getJoinLeaveContext(e){const r={client:e.client,user:e.user},n=e.conn_info;n&&(r.connInfo=n);const s=e.chan_info;return s&&(r.chanInfo=s),r}_handlePublication(e,r,n){const s=this._getSub(e,n);if(!s){if(e&&this._isServerSub(e)){const c=this._getPublicationContext(e,r);this.emit("publication",c),r.offset!==void 0&&(this._serverSubs[e].offset=r.offset)}return}s._handlePublication(r)}_handleMessage(e){this.emit("message",{data:e.data})}_handleServerPing(e){if(this._sendPong){const r={};this._transportSendCommands([r])}e()}_handlePush(e,r){const n=e.channel,s=e.id;e.pub?this._handlePublication(n,e.pub,s):e.message?this._handleMessage(e.message):e.join?this._handleJoin(n,e.join,s):e.leave?this._handleLeave(n,e.leave,s):e.unsubscribe?this._handleUnsubscribe(n,e.unsubscribe):e.subscribe?this._handleSubscribe(n,e.subscribe):e.disconnect&&this._handleDisconnect(e.disconnect),r()}_flush(){const e=this._commands.slice(0);this._commands=[],this._transportSendCommands(e)}_createErrorObject(e,r,n){const s={code:e,message:r};return n&&(s.temporary=!0),s}_registerCall(e,r,n){this._callbacks[e]={callback:r,errback:n,timeout:null},this._callbacks[e].timeout=setTimeout(()=>{delete this._callbacks[e],_f(n)&&n({error:this._createErrorObject(ur.timeout,"timeout")})},this._config.timeout)}_addCommand(e){this._batching?this._commands.push(e):this._transportSendCommands([e])}_nextPromiseId(){return++this._promiseId}_nextTransportId(){return++this._transportId}_resolvePromises(){for(const e in this._promises)this._promises.hasOwnProperty(e)&&(this._promises[e].timeout&&clearTimeout(this._promises[e].timeout),this._promises[e].resolve(),delete this._promises[e])}_rejectPromises(e){for(const r in this._promises)this._promises.hasOwnProperty(r)&&(this._promises[r].timeout&&clearTimeout(this._promises[r].timeout),this._promises[r].reject(e),delete this._promises[r])}}wl.SubscriptionState=ln,wl.State=Br,wl.UnauthorizedError=xs;const Fn={SessionList:"v1.session.list",SessionGet:"v1.session.get",SessionClose:"v1.session.close",SessionUpdate:"v1.session.update",SessionFork:"v1.session.fork",SessionCompact:"v1.session.compact",MessageSend:"v1.message.send",MessageList:"v1.message.list",TurnList:"v1.turn.list",TurnStop:"v1.turn.stop",RtcList:"v1.rtc.list",RtcUpdateStatus:"v1.rtc.update_status",RtcSubmitResult:"v1.rtc.submit_result"};class QT{constructor(e){Ht(this,"options");Ht(this,"centrifuge",null);Ht(this,"connectionState","disconnected");Ht(this,"listeners",new Map);Ht(this,"shouldReconnect",!0);Ht(this,"wasConnected",!1);Ht(this,"applyUpdatesQueue",null);Ht(this,"subscriptions",new Map);Ht(this,"epochCache",new Map);this.options=e}async connect(){if(console.log("[RTCAgentClient] connect() called, current state:",this.connectionState),this.connectionState==="connected"||this.connectionState==="connecting"){console.log("[RTCAgentClient] connect() early return, already",this.connectionState);return}this.shouldReconnect=!0,this.setConnectionState("connecting"),this.centrifuge=new wl(this.options.endpoint,{getToken:async()=>{var r;const e=await this.options.getToken();if(this._isTokenExpired(e)&&this.options.onTokenExpired){if(await this.options.onTokenExpired()==="relogin")throw this.shouldReconnect=!1,(r=this.centrifuge)==null||r.disconnect(),this.setConnectionState("disconnected","token expired, relogin required"),new Error("Token expired, user needs to re-login");return this.options.getToken()}return e}}),this.centrifuge.on("connecting",e=>{var n;if(!this.shouldReconnect){(n=this.centrifuge)==null||n.disconnect();return}const r=this.wasConnected?"reconnecting":"connecting";this.setConnectionState(r,e==null?void 0:e.reason)}),this.centrifuge.on("connected",()=>{console.log("[RTCAgentClient] centrifuge connected, setting state to connected"),this.wasConnected=!0,this.setConnectionState("connected"),this.subscribeChannels()}),this.centrifuge.on("disconnected",e=>{console.log("[RTCAgentClient] centrifuge disconnected, reason:",e==null?void 0:e.reason),(e==null?void 0:e.reason)==="invalid token"&&this.options.onTokenExpired&&this.handleInvalidToken(),this.setConnectionState("disconnected",e==null?void 0:e.reason)}),this.centrifuge.on("error",e=>{var r;console.error("[RTCAgentClient] centrifuge error:",e==null?void 0:e.error),this.emit("error",new Error(((r=e==null?void 0:e.error)==null?void 0:r.message)??"centrifuge error"))}),console.log("[RTCAgentClient] calling centrifuge.connect() synchronously"),this.centrifuge.connect(),console.log("[RTCAgentClient] centrifuge.connect() returned, state:",this.connectionState,"(WebSocket not yet established)")}disconnect(){var e;this.shouldReconnect=!1,this.wasConnected=!1,(e=this.centrifuge)==null||e.disconnect(),this.centrifuge=null,this.subscriptions.clear(),this.setConnectionState("disconnected")}async reconnect(){this.disconnect(),await this.connect()}getConnectionState(){return this.connectionState}getUserId(){return this.options.userId}async listSessions(e,r){return this.rpc(Fn.SessionList,{cursor:e,limit:r})}async getSession(e){return this.rpc(Fn.SessionGet,{session_id:e})}async closeSession(e){return this.rpc(Fn.SessionClose,{session_id:e})}async compactSession(e){return this.rpc(Fn.SessionCompact,e)}async updateSession(e){return this.rpc(Fn.SessionUpdate,e)}async sendMessage(e){return this.rpc(Fn.MessageSend,e)}async forkSession(e){return this.rpc(Fn.SessionFork,e)}async stopTurn(e){return this.rpc(Fn.TurnStop,{session_id:e})}async listMessages(e,r,n){return this.rpc(Fn.MessageList,{session_id:e,cursor:r,limit:n})}async listTurns(e,r,n){return this.rpc(Fn.TurnList,{session_id:e,cursor:r,limit:n})}async listRtc(e,r,n){return this.rpc(Fn.RtcList,{session_id:e,cursor:r,limit:n})}async updateRtcStatus(e,r){return this.rpc(Fn.RtcUpdateStatus,{rtc_id:e,status:r})}async submitRtcResult(e,r,n,s){return this.rpc(Fn.RtcSubmitResult,{rtc_id:e,success:r,result:n,error:s})}async applyUpdates(e){let r=this.applyUpdatesQueue;const n=(async()=>{r&&await r;for(const s of e)await this.processUpdate(s)})();this.applyUpdatesQueue=n;try{await n}finally{this.applyUpdatesQueue===n&&(this.applyUpdatesQueue=null)}}async processUpdate(e){var n,s,c,a,f,p;const r=`topic:u=${this.options.userId}`;if(e.offset>0){const h=await((s=(n=this.options).getLastOffset)==null?void 0:s.call(n,r)),y=h==null?void 0:h.offset,g=(h==null?void 0:h.epoch)??this.epochCache.get(r)??"";if(y!==void 0&&e.offset>y+1){await this.fillOffsetGap(r,y,g,e.offset);const b=await((a=(c=this.options).getLastOffset)==null?void 0:a.call(c,r)),S=b==null?void 0:b.offset,O=b==null?void 0:b.epoch,A=this.epochCache.get(r)??"";if(S===void 0||S!==e.offset-1)throw new Error(`[RTCAgentClient] Offset gap fill failed: expected ${e.offset-1}, got ${S}. Rejecting update ${e.offset} to maintain strict +1 continuity.`);if(O!==void 0&&O!==A)throw new Error(`[RTCAgentClient] Epoch mismatch after gap fill: expected '${A}', got '${O}'. Rejecting update ${e.offset} to prevent data corruption.`)}}if(this.options.onPublication){const h={channel:`topic:u=${this.options.userId}`,offset:e.offset,data:e};await this.options.onPublication(h)}if(e.offset>0){const h=this.epochCache.get(r)??"";await((p=(f=this.options).updateOffset)==null?void 0:p.call(f,r,e.offset,h))}}on(e,r){let n=this.listeners.get(e);return n||(n=new Set,this.listeners.set(e,n)),n.add(r),()=>{n.delete(r)}}emit(e,r){const n=this.listeners.get(e);if(n)for(const s of n)try{s(r)}catch(c){console.error(`[RTCAgentClient] listener for '${e}' threw:`,c)}}setConnectionState(e,r){var s,c;if(console.log("[RTCAgentClient] setConnectionState:",e,"reason:",r,"previous:",this.connectionState),this.connectionState===e)return;this.connectionState=e;const n={state:e,reason:r};this.emit("connection",n),(c=(s=this.options).onConnectionStateChange)==null||c.call(s,n)}async handleInvalidToken(){var e;if(!this.options.onTokenExpired){console.warn("[RTCAgentClient] invalid token but no onTokenExpired callback provided");return}try{await this.options.onTokenExpired()==="relogin"?(this.shouldReconnect=!1,(e=this.centrifuge)==null||e.disconnect(),this.setConnectionState("disconnected","token expired, relogin required")):(console.log("[RTCAgentClient] token refreshed, attempting to reconnect"),setTimeout(()=>{this.shouldReconnect&&this.reconnect()},1e3))}catch(r){console.error("[RTCAgentClient] handleInvalidToken failed:",r)}}_isTokenExpired(e){try{const r=e.split(".");if(r.length!==3)return!1;const n=JSON.parse(atob(r[1]));return typeof n.exp!="number"?!1:n.exp*1e3<Date.now()}catch{return!1}}async rpc(e,r){if(!this.centrifuge)throw new Error("RTCAgentClient not connected");if(this.connectionState!=="connected")throw new Error(`Cannot call RPC '${e}': connection state is ${this.connectionState}`);try{return(await this.centrifuge.rpc(e,r)).data}catch(n){throw console.error(`[RTCAgentClient] RPC '${e}' failed:`,n),n}}subscribeChannels(){var s,c;if(!this.centrifuge||!this.options.userId)return;const e=this.options.userId,r=`topic:u=${e}`;if(!this.subscriptions.has(r)){const a=this.centrifuge.newSubscription(r);this.subscriptions.set(r,a),a.on("publication",async f=>{const p=f.data;try{await this.applyUpdates([p])}catch(h){console.error(`[RTCAgentClient] applyUpdates failed for offset ${p.offset} on channel ${r}:`,h),this.emit("error",h instanceof Error?h:new Error(String(h)))}}),a.on("subscribed",async f=>{var p,h,y,g,b,S,O,A;if(f.streamPosition){const _=f.streamPosition.epoch,C=f.streamPosition.offset;this.epochCache.set(r,_);const E=await((h=(p=this.options).getLastOffset)==null?void 0:h.call(p,r)),x=E==null?void 0:E.offset;if(x===void 0)await((g=(y=this.options).updateOffset)==null?void 0:g.call(y,r,C,_));else if(!(C<=x)){const T=(E==null?void 0:E.epoch)??this.epochCache.get(r)??"";try{await this.fillOffsetGap(r,x,T,C+1);const j=await((S=(b=this.options).getLastOffset)==null?void 0:S.call(b,r)),R=j==null?void 0:j.offset,I=j==null?void 0:j.epoch;if(R===void 0||R!==C)throw new Error(`[RTCAgentClient] Offset gap fill failed on subscribe: expected ${C}, got ${R}. Offline updates may be lost.`);if(I!==void 0&&I!==_)throw new Error(`[RTCAgentClient] Epoch mismatch after gap fill on subscribe: expected '${_}', got '${I}'. Server may have restarted.`);await((A=(O=this.options).updateOffset)==null?void 0:A.call(O,r,C,_))}catch(j){console.error(`[RTCAgentClient] fillOffsetGap failed on subscribe for offset ${C}:`,j),this.emit("error",j instanceof Error?j:new Error(String(j)))}}}})}(s=this.subscriptions.get(r))==null||s.subscribe();const n=`live:u=${e}`;if(!this.subscriptions.has(n)){const a=this.centrifuge.newSubscription(n);this.subscriptions.set(n,a),a.on("publication",async f=>{const p={channel:n,data:f.data};await this.handlePublication(p,a)})}(c=this.subscriptions.get(n))==null||c.subscribe()}async fillOffsetGap(e,r,n,s){const c=this.subscriptions.get(e);if(!c){console.warn(`[RTCAgentClient] fillOffsetGap: subscription not found for channel ${e}`);return}let a={since:{offset:r,epoch:n},limit:void 0,reverse:!1};if(s){const f=s-r-1;if(f<=0)return;a.limit=f}try{const f=await c.history(a);for(const p of f.publications){const h=p.data;await this.processUpdate(h)}}catch(f){throw console.error(`[RTCAgentClient] fillOffsetGap failed for channel ${e}:`,f),f}}async handlePublication(e,r){if(this.options.onPublication)try{await this.options.onPublication(e)}catch(n){throw console.error(`[RTCAgentClient] onPublication threw for channel '${e.channel}':`,n),r.unsubscribe(),n}}}var Ii=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function ZT(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Ry={exports:{}};(function(t,e){((r,n)=>{t.exports=n()})(Ii,function(){var r=function(v,P){return(r=Object.setPrototypeOf||({__proto__:[]}instanceof Array?function(M,V){M.__proto__=V}:function(M,V){for(var re in V)Object.prototype.hasOwnProperty.call(V,re)&&(M[re]=V[re])}))(v,P)},n=function(){return(n=Object.assign||function(v){for(var P,M=1,V=arguments.length;M<V;M++)for(var re in P=arguments[M])Object.prototype.hasOwnProperty.call(P,re)&&(v[re]=P[re]);return v}).apply(this,arguments)};function s(v,P,M){for(var V,re=0,pe=P.length;re<pe;re++)!V&&re in P||((V=V||Array.prototype.slice.call(P,0,re))[re]=P[re]);return v.concat(V||Array.prototype.slice.call(P))}var c=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:Ii,a=Object.keys,f=Array.isArray;function p(v,P){return typeof P=="object"&&a(P).forEach(function(M){v[M]=P[M]}),v}typeof Promise>"u"||c.Promise||(c.Promise=Promise);var h=Object.getPrototypeOf,y={}.hasOwnProperty;function g(v,P){return y.call(v,P)}function b(v,P){typeof P=="function"&&(P=P(h(v))),(typeof Reflect>"u"?a:Reflect.ownKeys)(P).forEach(function(M){O(v,M,P[M])})}var S=Object.defineProperty;function O(v,P,M,V){S(v,P,p(M&&g(M,"get")&&typeof M.get=="function"?{get:M.get,set:M.set,configurable:!0}:{value:M,configurable:!0,writable:!0},V))}function A(v){return{from:function(P){return v.prototype=Object.create(P.prototype),O(v.prototype,"constructor",v),{extend:b.bind(null,v.prototype)}}}}var _=Object.getOwnPropertyDescriptor,C=[].slice;function E(v,P,M){return C.call(v,P,M)}function x(v,P){return P(v)}function T(v){if(!v)throw new Error("Assertion Failed")}function j(v){c.setImmediate?setImmediate(v):setTimeout(v,0)}function R(v,P){if(typeof P=="string"&&g(v,P))return v[P];if(!P)return v;if(typeof P!="string"){for(var M=[],V=0,re=P.length;V<re;++V){var pe=R(v,P[V]);M.push(pe)}return M}var Te,Ne=P.indexOf(".");return Ne===-1||(Te=v[P.substr(0,Ne)])==null?void 0:R(Te,P.substr(Ne+1))}function I(v,P,M){if(v&&P!==void 0&&!("isFrozen"in Object&&Object.isFrozen(v)))if(typeof P!="string"&&"length"in P){T(typeof M!="string"&&"length"in M);for(var V=0,re=P.length;V<re;++V)I(v,P[V],M[V])}else{var pe=P.indexOf(".");if(pe!==-1){var Te=P.substr(0,pe),pe=P.substr(pe+1);if(pe==="")M===void 0?f(v)&&!isNaN(parseInt(Te))?v.splice(Te,1):delete v[Te]:v[Te]=M;else{var Ne=v[Te];if(!Ne||!g(v,Te)){if(M===void 0)return;Ne=v[Te]={}}I(Ne,pe,M)}}else M===void 0?f(v)&&!isNaN(parseInt(P))?v.splice(P,1):delete v[P]:v[P]=M}}function D(v){var P,M={};for(P in v)g(v,P)&&(M[P]=v[P]);return M}var Z=[].concat;function J(v){return Z.apply([],v)}var ae="BigUint64Array,BigInt64Array,Array,Boolean,String,Date,RegExp,Blob,File,FileList,FileSystemFileHandle,FileSystemDirectoryHandle,ArrayBuffer,DataView,Uint8ClampedArray,ImageBitmap,ImageData,Map,Set,CryptoKey".split(",").concat(J([8,16,32,64].map(function(v){return["Int","Uint","Float"].map(function(P){return P+v+"Array"})}))).filter(function(v){return c[v]}),N=new Set(ae.map(function(v){return c[v]})),$=null;function ne(v){return $=new WeakMap,v=function P(M){if(!M||typeof M!="object")return M;var V=$.get(M);if(V)return V;if(f(M)){V=[],$.set(M,V);for(var re=0,pe=M.length;re<pe;++re)V.push(P(M[re]))}else if(N.has(M.constructor))V=M;else{var Te,Ne=h(M);for(Te in V=Ne===Object.prototype?{}:Object.create(Ne),$.set(M,V),M)g(M,Te)&&(V[Te]=P(M[Te]))}return V}(v),$=null,v}var me={}.toString;function Ce(v){return me.call(v).slice(8,-1)}var Ae=typeof Symbol<"u"?Symbol.iterator:"@@iterator",ce=typeof Ae=="symbol"?function(v){var P;return v!=null&&(P=v[Ae])&&P.apply(v)}:function(){return null};function ue(v,P){P=v.indexOf(P),0<=P&&v.splice(P,1)}var K={};function Y(v){var P,M,V,re;if(arguments.length===1){if(f(v))return v.slice();if(this===K&&typeof v=="string")return[v];if(re=ce(v))for(M=[];!(V=re.next()).done;)M.push(V.value);else{if(v==null)return[v];if(typeof(P=v.length)!="number")return[v];for(M=new Array(P);P--;)M[P]=v[P]}}else for(P=arguments.length,M=new Array(P);P--;)M[P]=arguments[P];return M}var he=typeof Symbol<"u"?function(v){return v[Symbol.toStringTag]==="AsyncFunction"}:function(){return!1},ae=["Unknown","Constraint","Data","TransactionInactive","ReadOnly","Version","NotFound","InvalidState","InvalidAccess","Abort","Timeout","QuotaExceeded","Syntax","DataClone"],oe=["Modify","Bulk","OpenFailed","VersionChange","Schema","Upgrade","InvalidTable","MissingAPI","NoSuchDatabase","InvalidArgument","SubTransaction","Unsupported","Internal","DatabaseClosed","PrematureCommit","ForeignAwait"].concat(ae),U={VersionChanged:"Database version changed by other database connection",DatabaseClosed:"Database has been closed",Abort:"Transaction aborted",TransactionInactive:"Transaction has already completed or failed",MissingAPI:"IndexedDB API missing. Please visit https://tinyurl.com/y2uuvskb"};function L(v,P){this.name=v,this.message=P}function H(v,P){return v+". Errors: "+Object.keys(P).map(function(M){return P[M].toString()}).filter(function(M,V,re){return re.indexOf(M)===V}).join(`
12
12
  `)}function ye(v,P,M,V){this.failures=P,this.failedKeys=V,this.successCount=M,this.message=H(v,P)}function Ie(v,P){this.name="BulkError",this.failures=Object.keys(P).map(function(M){return P[M]}),this.failuresByPos=P,this.message=H(v,this.failures)}A(L).from(Error).extend({toString:function(){return this.name+": "+this.message}}),A(ye).from(L),A(Ie).from(L);var Ee=oe.reduce(function(v,P){return v[P]=P+"Error",v},{}),De=L,Me=oe.reduce(function(v,P){var M=P+"Error";function V(re,pe){this.name=M,re?typeof re=="string"?(this.message="".concat(re).concat(pe?`
13
13
  `+pe:""),this.inner=pe||null):typeof re=="object"&&(this.message="".concat(re.name," ").concat(re.message),this.inner=re):(this.message=U[P]||M,this.inner=null)}return A(V).from(De),v[P]=V,v},{}),Ve=(Me.Syntax=SyntaxError,Me.Type=TypeError,Me.Range=RangeError,ae.reduce(function(v,P){return v[P+"Error"]=Me[P],v},{}));ae=oe.reduce(function(v,P){return["Syntax","Type","Range"].indexOf(P)===-1&&(v[P+"Error"]=Me[P]),v},{});function Ze(){}function ut(v){return v}function st(v,P){return v==null||v===ut?P:function(M){return P(v(M))}}function dt(v,P){return function(){v.apply(this,arguments),P.apply(this,arguments)}}function $e(v,P){return v===Ze?P:function(){var M=v.apply(this,arguments),V=(M!==void 0&&(arguments[0]=M),this.onsuccess),re=this.onerror,pe=(this.onsuccess=null,this.onerror=null,P.apply(this,arguments));return V&&(this.onsuccess=this.onsuccess?dt(V,this.onsuccess):V),re&&(this.onerror=this.onerror?dt(re,this.onerror):re),pe!==void 0?pe:M}}function je(v,P){return v===Ze?P:function(){v.apply(this,arguments);var M=this.onsuccess,V=this.onerror;this.onsuccess=this.onerror=null,P.apply(this,arguments),M&&(this.onsuccess=this.onsuccess?dt(M,this.onsuccess):M),V&&(this.onerror=this.onerror?dt(V,this.onerror):V)}}function qe(v,P){return v===Ze?P:function(re){var V=v.apply(this,arguments),re=(p(re,V),this.onsuccess),pe=this.onerror,Te=(this.onsuccess=null,this.onerror=null,P.apply(this,arguments));return re&&(this.onsuccess=this.onsuccess?dt(re,this.onsuccess):re),pe&&(this.onerror=this.onerror?dt(pe,this.onerror):pe),V===void 0?Te===void 0?void 0:Te:p(V,Te)}}function Le(v,P){return v===Ze?P:function(){return P.apply(this,arguments)!==!1&&v.apply(this,arguments)}}function gt(v,P){return v===Ze?P:function(){var M=v.apply(this,arguments);if(M&&typeof M.then=="function"){for(var V=this,re=arguments.length,pe=new Array(re);re--;)pe[re]=arguments[re];return M.then(function(){return P.apply(V,pe)})}return P.apply(this,arguments)}}ae.ModifyError=ye,ae.DexieError=L,ae.BulkError=Ie;var ht=typeof location<"u"&&/^(http|https):\/\/(localhost|127\.0\.0\.1)/.test(location.href);function xe(v){ht=v}var Se={},se=100,ee=typeof Promise>"u"?[]:(oe=Promise.resolve(),typeof crypto<"u"&&crypto.subtle?[ee=crypto.subtle.digest("SHA-512",new Uint8Array([0])),h(ee),oe]:[oe,h(oe),oe]),oe=ee[0],In=ee[1],In=In&&In.then,W=oe&&oe.constructor,fe=!!ee[2],Re=function(v,P){te.push([v,P]),Ke&&(queueMicrotask(Lt),Ke=!1)},Fe=!0,Ke=!0,it=[],_t=[],Mt=ut,pt={id:"global",global:!0,ref:0,unhandleds:[],onunhandled:Ze,pgp:!1,env:{},finalize:Ze},xt=pt,te=[],de=0,G=[];function be(v){if(typeof this!="object")throw new TypeError("Promises must be constructed via new");this._listeners=[],this._lib=!1;var P=this._PSD=xt;if(typeof v!="function"){if(v!==Se)throw new TypeError("Not a function");this._state=arguments[1],this._value=arguments[2],this._state===!1&&rt(this,this._value)}else this._state=null,this._value=null,++P.ref,function M(V,re){try{re(function(pe){if(V._state===null){if(pe===V)throw new TypeError("A promise cannot be resolved with itself.");var Te=V._lib&&Vt();pe&&typeof pe.then=="function"?M(V,function(Ne,We){pe instanceof be?pe._then(Ne,We):pe.then(Ne,We)}):(V._state=!0,V._value=pe,yt(V)),Te&&Jt()}},rt.bind(null,V))}catch(pe){rt(V,pe)}}(this,v)}var et={get:function(){var v=xt,P=Rt;function M(V,re){var pe=this,Te=!v.global&&(v!==xt||P!==Rt),Ne=Te&&!Rr(),We=new be(function(at,Je){mt(pe,new ge(An(V,v,Te,Ne),An(re,v,Te,Ne),at,Je,v))});return this._consoleTask&&(We._consoleTask=this._consoleTask),We}return M.prototype=Se,M},set:function(v){O(this,"then",v&&v.prototype===Se?et:{get:function(){return v},set:et.set})}};function ge(v,P,M,V,re){this.onFulfilled=typeof v=="function"?v:null,this.onRejected=typeof P=="function"?P:null,this.resolve=M,this.reject=V,this.psd=re}function rt(v,P){var M,V;_t.push(P),v._state===null&&(M=v._lib&&Vt(),P=Mt(P),v._state=!1,v._value=P,V=v,it.some(function(re){return re._value===V._value})||it.push(V),yt(v),M)&&Jt()}function yt(v){var P=v._listeners;v._listeners=[];for(var M=0,V=P.length;M<V;++M)mt(v,P[M]);var re=v._PSD;--re.ref||re.finalize(),de===0&&(++de,Re(function(){--de==0&&lr()},[]))}function mt(v,P){if(v._state===null)v._listeners.push(P);else{var M=v._state?P.onFulfilled:P.onRejected;if(M===null)return(v._state?P.resolve:P.reject)(v._value);++P.psd.ref,++de,Re(Bt,[M,v,P])}}function Bt(v,P,M){try{var V,re=P._value;!P._state&&_t.length&&(_t=[]),V=ht&&P._consoleTask?P._consoleTask.run(function(){return v(re)}):v(re),P._state||_t.indexOf(re)!==-1||(pe=>{for(var Te=it.length;Te;)if(it[--Te]._value===pe._value)return it.splice(Te,1)})(P),M.resolve(V)}catch(pe){M.reject(pe)}finally{--de==0&&lr(),--M.psd.ref||M.psd.finalize()}}function Lt(){Nr(pt,function(){Vt()&&Jt()})}function Vt(){var v=Fe;return Ke=Fe=!1,v}function Jt(){var v,P,M;do for(;0<te.length;)for(v=te,te=[],M=v.length,P=0;P<M;++P){var V=v[P];V[0].apply(null,V[1])}while(0<te.length);Ke=Fe=!0}function lr(){for(var v=it,P=(it=[],v.forEach(function(V){V._PSD.onunhandled.call(null,V._value,V)}),G.slice(0)),M=P.length;M;)P[--M]()}function xr(v){return new be(Se,!1,v)}function Wt(v,P){var M=xt;return function(){var V=Vt(),re=xt;try{return Kr(M,!0),v.apply(this,arguments)}catch(pe){P&&P(pe)}finally{Kr(re,!1),V&&Jt()}}}b(be.prototype,{then:et,_then:function(v,P){mt(this,new ge(null,null,v,P,xt))},catch:function(v){var P,M;return arguments.length===1?this.then(null,v):(P=v,M=arguments[1],typeof P=="function"?this.then(null,function(V){return(V instanceof P?M:xr)(V)}):this.then(null,function(V){return(V&&V.name===P?M:xr)(V)}))},finally:function(v){return this.then(function(P){return be.resolve(v()).then(function(){return P})},function(P){return be.resolve(v()).then(function(){return xr(P)})})},timeout:function(v,P){var M=this;return v<1/0?new be(function(V,re){var pe=setTimeout(function(){return re(new Me.Timeout(P))},v);M.then(V,re).finally(clearTimeout.bind(null,pe))}):this}}),typeof Symbol<"u"&&Symbol.toStringTag&&O(be.prototype,Symbol.toStringTag,"Dexie.Promise"),pt.env=Hn(),b(be,{all:function(){var v=Y.apply(null,arguments).map(jr);return new be(function(P,M){v.length===0&&P([]);var V=v.length;v.forEach(function(re,pe){return be.resolve(re).then(function(Te){v[pe]=Te,--V||P(v)},M)})})},resolve:function(v){return v instanceof be?v:v&&typeof v.then=="function"?new be(function(P,M){v.then(P,M)}):new be(Se,!0,v)},reject:xr,race:function(){var v=Y.apply(null,arguments).map(jr);return new be(function(P,M){v.map(function(V){return be.resolve(V).then(P,M)})})},PSD:{get:function(){return xt},set:function(v){return xt=v}},totalEchoes:{get:function(){return Rt}},newPSD:Vr,usePSD:Nr,scheduler:{get:function(){return Re},set:function(v){Re=v}},rejectionMapper:{get:function(){return Mt},set:function(v){Mt=v}},follow:function(v,P){return new be(function(M,V){return Vr(function(re,pe){var Te=xt;Te.unhandleds=[],Te.onunhandled=pe,Te.finalize=dt(function(){var Ne,We=this;Ne=function(){We.unhandleds.length===0?re():pe(We.unhandleds[0])},G.push(function at(){Ne(),G.splice(G.indexOf(at),1)}),++de,Re(function(){--de==0&&lr()},[])},Te.finalize),v()},P,M,V)})}}),W&&(W.allSettled&&O(be,"allSettled",function(){var v=Y.apply(null,arguments).map(jr);return new be(function(P){v.length===0&&P([]);var M=v.length,V=new Array(M);v.forEach(function(re,pe){return be.resolve(re).then(function(Te){return V[pe]={status:"fulfilled",value:Te}},function(Te){return V[pe]={status:"rejected",reason:Te}}).then(function(){return--M||P(V)})})})}),W.any&&typeof AggregateError<"u"&&O(be,"any",function(){var v=Y.apply(null,arguments).map(jr);return new be(function(P,M){v.length===0&&M(new AggregateError([]));var V=v.length,re=new Array(V);v.forEach(function(pe,Te){return be.resolve(pe).then(function(Ne){return P(Ne)},function(Ne){re[Te]=Ne,--V||M(new AggregateError(re))})})})}),W.withResolvers)&&(be.withResolvers=W.withResolvers);var tr={awaits:0,echoes:0,id:0},pn=0,dn=[],Sr=0,Rt=0,ui=0;function Vr(v,Te,M,V){var re=xt,pe=Object.create(re),Te=(pe.parent=re,pe.ref=0,pe.global=!1,pe.id=++ui,pt.env,pe.env=fe?{Promise:be,PromiseProp:{value:be,configurable:!0,writable:!0},all:be.all,race:be.race,allSettled:be.allSettled,any:be.any,resolve:be.resolve,reject:be.reject}:{},Te&&p(pe,Te),++re.ref,pe.finalize=function(){--this.parent.ref||this.parent.finalize()},Nr(pe,v,M,V));return pe.ref===0&&pe.finalize(),Te}function tn(){return tr.id||(tr.id=++pn),++tr.awaits,tr.echoes+=se,tr.id}function Rr(){return!!tr.awaits&&(--tr.awaits==0&&(tr.id=0),tr.echoes=tr.awaits*se,!0)}function jr(v){return tr.echoes&&v&&v.constructor===W?(tn(),v.then(function(P){return Rr(),P},function(P){return Rr(),dr(P)})):v}function Dn(){var v=dn[dn.length-1];dn.pop(),Kr(v,!1)}function Kr(v,P){var M,V,re=xt;(P?!tr.echoes||Sr++&&v===xt:!Sr||--Sr&&v===xt)||queueMicrotask(P?(function(pe){++Rt,tr.echoes&&--tr.echoes!=0||(tr.echoes=tr.awaits=tr.id=0),dn.push(xt),Kr(pe,!0)}).bind(null,v):Dn),v!==xt&&(xt=v,re===pt&&(pt.env=Hn()),fe)&&(M=pt.env.Promise,V=v.env,re.global||v.global)&&(Object.defineProperty(c,"Promise",V.PromiseProp),M.all=V.all,M.race=V.race,M.resolve=V.resolve,M.reject=V.reject,V.allSettled&&(M.allSettled=V.allSettled),V.any)&&(M.any=V.any)}function Hn(){var v=c.Promise;return fe?{Promise:v,PromiseProp:Object.getOwnPropertyDescriptor(c,"Promise"),all:v.all,race:v.race,allSettled:v.allSettled,any:v.any,resolve:v.resolve,reject:v.reject}:{}}function Nr(v,P,M,V,re){var pe=xt;try{return Kr(v,!0),P(M,V,re)}finally{Kr(pe,!1)}}function An(v,P,M,V){return typeof v!="function"?v:function(){var re=xt;M&&tn(),Kr(P,!0);try{return v.apply(this,arguments)}finally{Kr(re,!1),V&&queueMicrotask(Rr)}}}function fi(v){Promise===W&&tr.echoes===0?Sr===0?v():enqueueNativeMicroTask(v):setTimeout(v,0)}(""+In).indexOf("[native code]")===-1&&(tn=Rr=Ze);var dr=be.reject,rn="￿",nn="Invalid key provided. Keys must be of type string, number, Date or Array<string | number | Date>.",hn="String expected.",Wr="__dbnames",yn="readonly",Ri="readwrite";function Cn(v,P){return v?P?function(){return v.apply(this,arguments)&&P.apply(this,arguments)}:v:P}var ss={type:3,lower:-1/0,lowerOpen:!1,upper:[[]],upperOpen:!1};function pi(v){return typeof v!="string"||/\./.test(v)?function(P){return P}:function(P){return P[v]===void 0&&v in P&&delete(P=ne(P))[v],P}}function Jn(){throw Me.Type("Entity instances must never be new:ed. Instances are generated by the framework bypassing the constructor.")}function zt(v,P){try{var M=ji(v),V=ji(P);if(M!==V)return M==="Array"?1:V==="Array"?-1:M==="binary"?1:V==="binary"?-1:M==="string"?1:V==="string"?-1:M==="Date"?1:V!=="Date"?NaN:-1;switch(M){case"number":case"Date":case"string":return P<v?1:v<P?-1:0;case"binary":for(var re=as(v),pe=as(P),Te=re.length,Ne=pe.length,We=Te<Ne?Te:Ne,at=0;at<We;++at)if(re[at]!==pe[at])return re[at]<pe[at]?-1:1;return Te===Ne?0:Te<Ne?-1:1;case"Array":for(var Je=v,Ge=P,He=Je.length,nt=Ge.length,Xe=He<nt?He:nt,Ye=0;Ye<Xe;++Ye){var Qe=zt(Je[Ye],Ge[Ye]);if(Qe!==0)return Qe}return He===nt?0:He<nt?-1:1}}catch{}return NaN}function ji(v){var P=typeof v;return P=="object"&&(ArrayBuffer.isView(v)||(P=Ce(v))==="ArrayBuffer")?"binary":P}function as(v){return v instanceof Uint8Array?v:ArrayBuffer.isView(v)?new Uint8Array(v.buffer,v.byteOffset,v.byteLength):new Uint8Array(v)}function mn(v,P,M){var V=v.schema.yProps;return V?(P&&0<M.numFailures&&(P=P.filter(function(re,pe){return!M.failures[pe]})),Promise.all(V.map(function(re){return re=re.updatesTable,P?v.db.table(re).where("k").anyOf(P).delete():v.db.table(re).clear()})).then(function(){return M})):M}os.prototype.execute=function(v){var P=this["@@propmod"];if(P.add!==void 0){var M=P.add;if(f(M))return s(s([],f(v)?v:[],!0),M).sort();if(typeof M=="number")return(Number(v)||0)+M;if(typeof M=="bigint")try{return BigInt(v)+M}catch{return BigInt(0)+M}throw new TypeError("Invalid term ".concat(M))}if(P.remove!==void 0){var V=P.remove;if(f(V))return f(v)?v.filter(function(re){return!V.includes(re)}).sort():[];if(typeof V=="number")return Number(v)-V;if(typeof V=="bigint")try{return BigInt(v)-V}catch{return BigInt(0)-V}throw new TypeError("Invalid subtrahend ".concat(V))}return M=(M=P.replacePrefix)==null?void 0:M[0],M&&typeof v=="string"&&v.startsWith(M)?P.replacePrefix[1]+v.substring(M.length):v};var Pr=os;function os(v){this["@@propmod"]=v}function di(v,P){for(var M=a(P),V=M.length,re=!1,pe=0;pe<V;++pe){var Te=M[pe],Ne=P[Te],We=R(v,Te);Ne instanceof Pr?(I(v,Te,Ne.execute(We)),re=!0):We!==Ne&&(I(v,Te,Ne),re=!0)}return re}ir.prototype._trans=function(v,P,M){var V=this._tx||xt.trans,re=this.name,pe=ht&&typeof console<"u"&&console.createTask&&console.createTask("Dexie: ".concat(v==="readonly"?"read":"write"," ").concat(this.name));function Te(at,Je,Ge){if(Ge.schema[re])return P(Ge.idbtrans,Ge);throw new Me.NotFound("Table "+re+" not part of transaction")}var Ne=Vt();try{var We=V&&V.db._novip===this.db._novip?V===xt.trans?V._promise(v,Te,M):Vr(function(){return V._promise(v,Te,M)},{trans:V,transless:xt.transless||xt}):function at(Je,Ge,He,nt){if(Je.idbdb&&(Je._state.openComplete||xt.letThrough||Je._vip)){var Xe=Je._createTransaction(Ge,He,Je._dbSchema);try{Xe.create(),Je._state.PR1398_maxLoop=3}catch(Ye){return Ye.name===Ee.InvalidState&&Je.isOpen()&&0<--Je._state.PR1398_maxLoop?(console.warn("Dexie: Need to reopen db"),Je.close({disableAutoOpen:!1}),Je.open().then(function(){return at(Je,Ge,He,nt)})):dr(Ye)}return Xe._promise(Ge,function(Ye,Qe){return Vr(function(){return xt.trans=Xe,nt(Ye,Qe,Xe)})}).then(function(Ye){if(Ge==="readwrite")try{Xe.idbtrans.commit()}catch{}return Ge==="readonly"?Ye:Xe._completion.then(function(){return Ye})})}if(Je._state.openComplete)return dr(new Me.DatabaseClosed(Je._state.dbOpenError));if(!Je._state.isBeingOpened){if(!Je._state.autoOpen)return dr(new Me.DatabaseClosed);Je.open().catch(Ze)}return Je._state.dbReadyPromise.then(function(){return at(Je,Ge,He,nt)})}(this.db,v,[this.name],Te);return pe&&(We._consoleTask=pe,We=We.catch(function(at){return console.trace(at),dr(at)})),We}finally{Ne&&Jt()}},ir.prototype.get=function(v,P){var M=this;return v&&v.constructor===Object?this.where(v).first(P):v==null?dr(new Me.Type("Invalid argument to Table.get()")):this._trans("readonly",function(V){return M.core.get({trans:V,key:v}).then(function(re){return M.hook.reading.fire(re)})}).then(P)},ir.prototype.where=function(v){if(typeof v=="string")return new this.db.WhereClause(this,v);if(f(v))return new this.db.WhereClause(this,"[".concat(v.join("+"),"]"));var P=a(v);if(P.length===1)return this.where(P[0]).equals(v[P[0]]);var M=this.schema.indexes.concat(this.schema.primKey).filter(function(Ne){if(Ne.compound&&P.every(function(at){return 0<=Ne.keyPath.indexOf(at)})){for(var We=0;We<P.length;++We)if(P.indexOf(Ne.keyPath[We])===-1)return!1;return!0}return!1}).sort(function(Ne,We){return Ne.keyPath.length-We.keyPath.length})[0];if(M&&this.db._maxKey!==rn)return Te=M.keyPath.slice(0,P.length),this.where(Te).equals(Te.map(function(Ne){return v[Ne]}));!M&&ht&&console.warn("The query ".concat(JSON.stringify(v)," on ").concat(this.name," would benefit from a ")+"compound index [".concat(P.join("+"),"]"));var V=this.schema.idxByName;function re(Ne,We){return zt(Ne,We)===0}var Te=P.reduce(function(Je,We){var at=Je[0],Je=Je[1],Ge=V[We],He=v[We];return[at||Ge,at||!Ge?Cn(Je,Ge&&Ge.multi?function(nt){return nt=R(nt,We),f(nt)&&nt.some(function(Xe){return re(He,Xe)})}:function(nt){return re(He,R(nt,We))}):Je]},[null,null]),pe=Te[0],Te=Te[1];return pe?this.where(pe.name).equals(v[pe.keyPath]).filter(Te):M?this.filter(Te):this.where(P).equals("")},ir.prototype.filter=function(v){return this.toCollection().and(v)},ir.prototype.count=function(v){return this.toCollection().count(v)},ir.prototype.offset=function(v){return this.toCollection().offset(v)},ir.prototype.limit=function(v){return this.toCollection().limit(v)},ir.prototype.each=function(v){return this.toCollection().each(v)},ir.prototype.toArray=function(v){return this.toCollection().toArray(v)},ir.prototype.toCollection=function(){return new this.db.Collection(new this.db.WhereClause(this))},ir.prototype.orderBy=function(v){return new this.db.Collection(new this.db.WhereClause(this,f(v)?"[".concat(v.join("+"),"]"):v))},ir.prototype.reverse=function(){return this.toCollection().reverse()},ir.prototype.mapToClass=function(v){for(var P=this.db,M=this.name,V=((this.schema.mappedClass=v).prototype instanceof Jn&&(v=(Te=>{var Ne=Je,We=Te;if(typeof We!="function"&&We!==null)throw new TypeError("Class extends value "+String(We)+" is not a constructor or null");function at(){this.constructor=Ne}function Je(){return Te!==null&&Te.apply(this,arguments)||this}return r(Ne,We),Ne.prototype=We===null?Object.create(We):(at.prototype=We.prototype,new at),Object.defineProperty(Je.prototype,"db",{get:function(){return P},enumerable:!1,configurable:!0}),Je.prototype.table=function(){return M},Je})(v)),new Set),re=v.prototype;re;re=h(re))Object.getOwnPropertyNames(re).forEach(function(Te){return V.add(Te)});function pe(Te){if(!Te)return Te;var Ne,We=Object.create(v.prototype);for(Ne in Te)if(!V.has(Ne))try{We[Ne]=Te[Ne]}catch{}return We}return this.schema.readHook&&this.hook.reading.unsubscribe(this.schema.readHook),this.schema.readHook=pe,this.hook("reading",pe),v},ir.prototype.defineClass=function(){return this.mapToClass(function(v){p(this,v)})},ir.prototype.add=function(v,P){var M=this,V=this.schema.primKey,re=V.auto,pe=V.keyPath,Te=v;return pe&&re&&(Te=pi(pe)(v)),this._trans("readwrite",function(Ne){return M.core.mutate({trans:Ne,type:"add",keys:P!=null?[P]:null,values:[Te]})}).then(function(Ne){return Ne.numFailures?be.reject(Ne.failures[0]):Ne.lastResult}).then(function(Ne){if(pe)try{I(v,pe,Ne)}catch{}return Ne})},ir.prototype.upsert=function(v,P){var M=this,V=this.schema.primKey.keyPath;return this._trans("readwrite",function(re){return M.core.get({trans:re,key:v}).then(function(pe){var Te=pe??{};return di(Te,P),V&&I(Te,V,v),M.core.mutate({trans:re,type:"put",values:[Te],keys:[v],upsert:!0,updates:{keys:[v],changeSpecs:[P]}}).then(function(Ne){return Ne.numFailures?be.reject(Ne.failures[0]):!!pe})})})},ir.prototype.update=function(v,P){return typeof v!="object"||f(v)?this.where(":id").equals(v).modify(P):(v=R(v,this.schema.primKey.keyPath))===void 0?dr(new Me.InvalidArgument("Given object does not contain its primary key")):this.where(":id").equals(v).modify(P)},ir.prototype.put=function(v,P){var M=this,V=this.schema.primKey,re=V.auto,pe=V.keyPath,Te=v;return pe&&re&&(Te=pi(pe)(v)),this._trans("readwrite",function(Ne){return M.core.mutate({trans:Ne,type:"put",values:[Te],keys:P!=null?[P]:null})}).then(function(Ne){return Ne.numFailures?be.reject(Ne.failures[0]):Ne.lastResult}).then(function(Ne){if(pe)try{I(v,pe,Ne)}catch{}return Ne})},ir.prototype.delete=function(v){var P=this;return this._trans("readwrite",function(M){return P.core.mutate({trans:M,type:"delete",keys:[v]}).then(function(V){return mn(P,[v],V)}).then(function(V){return V.numFailures?be.reject(V.failures[0]):void 0})})},ir.prototype.clear=function(){var v=this;return this._trans("readwrite",function(P){return v.core.mutate({trans:P,type:"deleteRange",range:ss}).then(function(M){return mn(v,null,M)})}).then(function(P){return P.numFailures?be.reject(P.failures[0]):void 0})},ir.prototype.bulkGet=function(v){var P=this;return this._trans("readonly",function(M){return P.core.getMany({keys:v,trans:M}).then(function(V){return V.map(function(re){return P.hook.reading.fire(re)})})})},ir.prototype.bulkAdd=function(v,P,M){var V=this,re=Array.isArray(P)?P:void 0,pe=(M=M||(re?void 0:P))?M.allKeys:void 0;return this._trans("readwrite",function(Te){var Ne=V.schema.primKey,at=Ne.auto,Ne=Ne.keyPath;if(Ne&&re)throw new Me.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbound keys");if(re&&re.length!==v.length)throw new Me.InvalidArgument("Arguments objects and keys must have the same length");var We=v.length,at=Ne&&at?v.map(pi(Ne)):v;return V.core.mutate({trans:Te,type:"add",keys:re,values:at,wantResults:pe}).then(function(Je){var Ge=Je.numFailures,He=Je.failures;if(Ge===0)return pe?Je.results:Je.lastResult;throw new Ie("".concat(V.name,".bulkAdd(): ").concat(Ge," of ").concat(We," operations failed"),He)})})},ir.prototype.bulkPut=function(v,P,M){var V=this,re=Array.isArray(P)?P:void 0,pe=(M=M||(re?void 0:P))?M.allKeys:void 0;return this._trans("readwrite",function(Te){var Ne=V.schema.primKey,at=Ne.auto,Ne=Ne.keyPath;if(Ne&&re)throw new Me.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys");if(re&&re.length!==v.length)throw new Me.InvalidArgument("Arguments objects and keys must have the same length");var We=v.length,at=Ne&&at?v.map(pi(Ne)):v;return V.core.mutate({trans:Te,type:"put",keys:re,values:at,wantResults:pe}).then(function(Je){var Ge=Je.numFailures,He=Je.failures;if(Ge===0)return pe?Je.results:Je.lastResult;throw new Ie("".concat(V.name,".bulkPut(): ").concat(Ge," of ").concat(We," operations failed"),He)})})},ir.prototype.bulkUpdate=function(v){var P=this,M=this.core,V=v.map(function(Te){return Te.key}),re=v.map(function(Te){return Te.changes}),pe=[];return this._trans("readwrite",function(Te){return M.getMany({trans:Te,keys:V,cache:"clone"}).then(function(Ne){var We=[],at=[],Je=(v.forEach(function(Ge,He){var nt=Ge.key,Xe=Ge.changes,Ye=Ne[He];if(Ye){for(var Qe=0,lt=Object.keys(Xe);Qe<lt.length;Qe++){var ot=lt[Qe],ft=Xe[ot];if(ot===P.schema.primKey.keyPath){if(zt(ft,nt)!==0)throw new Me.Constraint("Cannot update primary key in bulkUpdate()")}else I(Ye,ot,ft)}pe.push(He),We.push(nt),at.push(Ye)}}),We.length);return M.mutate({trans:Te,type:"put",keys:We,values:at,updates:{keys:V,changeSpecs:re}}).then(function(Ge){var He=Ge.numFailures,nt=Ge.failures;if(He===0)return Je;for(var Xe=0,Ye=Object.keys(nt);Xe<Ye.length;Xe++){var Qe,lt=Ye[Xe],ot=pe[Number(lt)];ot!=null&&(Qe=nt[lt],delete nt[lt],nt[ot]=Qe)}throw new Ie("".concat(P.name,".bulkUpdate(): ").concat(He," of ").concat(Je," operations failed"),nt)})})})},ir.prototype.bulkDelete=function(v){var P=this,M=v.length;return this._trans("readwrite",function(V){return P.core.mutate({trans:V,type:"delete",keys:v}).then(function(re){return mn(P,v,re)})}).then(function(V){var re=V.numFailures,pe=V.failures;if(re===0)return V.lastResult;throw new Ie("".concat(P.name,".bulkDelete(): ").concat(re," of ").concat(M," operations failed"),pe)})};var ls=ir;function ir(){}function gn(v){function P(Te,Ne){if(Ne){for(var We=arguments.length,at=new Array(We-1);--We;)at[We-1]=arguments[We];return M[Te].subscribe.apply(null,at),v}if(typeof Te=="string")return M[Te]}var M={};P.addEventType=pe;for(var V=1,re=arguments.length;V<re;++V)pe(arguments[V]);return P;function pe(Te,Ne,We){var at,Je;if(typeof Te!="object")return Ne=Ne||Le,Je={subscribers:[],fire:We=We||Ze,subscribe:function(Ge){Je.subscribers.indexOf(Ge)===-1&&(Je.subscribers.push(Ge),Je.fire=Ne(Je.fire,Ge))},unsubscribe:function(Ge){Je.subscribers=Je.subscribers.filter(function(He){return He!==Ge}),Je.fire=Je.subscribers.reduce(Ne,We)}},M[Te]=P[Te]=Je;a(at=Te).forEach(function(Ge){var He=at[Ge];if(f(He))pe(Ge,at[Ge][0],at[Ge][1]);else{if(He!=="asap")throw new Me.InvalidArgument("Invalid event config");var nt=pe(Ge,ut,function(){for(var Xe=arguments.length,Ye=new Array(Xe);Xe--;)Ye[Xe]=arguments[Xe];nt.subscribers.forEach(function(Qe){j(function(){Qe.apply(null,Ye)})})})}})}}function Bn(v,P){return A(P).from({prototype:v}),P}function Rn(v,P){return!(v.filter||v.algorithm||v.or)&&(P?v.justLimit:!v.replayFilter)}function Mi(v,P){v.filter=Cn(v.filter,P)}function Yn(v,P,M){var V=v.replayFilter;v.replayFilter=V?function(){return Cn(V(),P())}:P,v.justLimit=M&&!V}function Xn(v,P){if(v.isPrimKey)return P.primaryKey;var M=P.getIndexByKeyPath(v.index);if(M)return M;throw new Me.Schema("KeyPath "+v.index+" on object store "+P.name+" is not indexed")}function Li(v,P,M){var V=Xn(v,P.schema);return P.openCursor({trans:M,values:!v.keysOnly,reverse:v.dir==="prev",unique:!!v.unique,query:{index:V,range:v.range}})}function bn(v,P,M,V){var re,pe,Te=v.replayFilter?Cn(v.filter,v.replayFilter()):v.filter;return v.or?(re={},pe=function(Ne,We,at){var Je,Ge;Te&&!Te(We,at,function(He){return We.stop(He)},function(He){return We.fail(He)})||((Ge=""+(Je=We.primaryKey))=="[object ArrayBuffer]"&&(Ge=""+new Uint8Array(Je)),g(re,Ge))||(re[Ge]=!0,P(Ne,We,at))},Promise.all([v.or._iterate(pe,M),cs(Li(v,V,M),v.algorithm,pe,!v.keysOnly&&v.valueMapper)])):cs(Li(v,V,M),Cn(v.algorithm,Te),P,!v.keysOnly&&v.valueMapper)}function cs(v,P,M,V){var re=Wt(V?function(pe,Te,Ne){return M(V(pe),Te,Ne)}:M);return v.then(function(pe){if(pe)return pe.start(function(){var Te=function(){return pe.continue()};P&&!P(pe,function(Ne){return Te=Ne},function(Ne){pe.stop(Ne),Te=Ze},function(Ne){pe.fail(Ne),Te=Ze})||re(pe.value,pe,function(Ne){return Te=Ne}),Te()})})}Qt.prototype._read=function(v,P){var M=this._ctx;return M.error?M.table._trans(null,dr.bind(null,M.error)):M.table._trans("readonly",v).then(P)},Qt.prototype._write=function(v){var P=this._ctx;return P.error?P.table._trans(null,dr.bind(null,P.error)):P.table._trans("readwrite",v,"locked")},Qt.prototype._addAlgorithm=function(v){var P=this._ctx;P.algorithm=Cn(P.algorithm,v)},Qt.prototype._iterate=function(v,P){return bn(this._ctx,v,P,this._ctx.table.core)},Qt.prototype.clone=function(v){var P=Object.create(this.constructor.prototype),M=Object.create(this._ctx);return v&&p(M,v),P._ctx=M,P},Qt.prototype.raw=function(){return this._ctx.valueMapper=null,this},Qt.prototype.each=function(v){var P=this._ctx;return this._read(function(M){return bn(P,v,M,P.table.core)})},Qt.prototype.count=function(v){var P=this;return this._read(function(M){var V,re=P._ctx,pe=re.table.core;return Rn(re,!0)?pe.count({trans:M,query:{index:Xn(re,pe.schema),range:re.range}}).then(function(Te){return Math.min(Te,re.limit)}):(V=0,bn(re,function(){return++V,!1},M,pe).then(function(){return V}))}).then(v)},Qt.prototype.sortBy=function(v,P){var M=v.split(".").reverse(),V=M[0],re=M.length-1;function pe(We,at){return at?pe(We[M[at]],at-1):We[V]}var Te=this._ctx.dir==="next"?1:-1;function Ne(We,at){return zt(pe(We,re),pe(at,re))*Te}return this.toArray(function(We){return We.slice().sort(Ne)}).then(P)},Qt.prototype.toArray=function(v){var P=this;return this._read(function(M){var V,re,pe,Te=P._ctx;return Rn(Te,!0)&&0<Te.limit?(V=Te.valueMapper,re=Xn(Te,Te.table.core.schema),Te.table.core.query({trans:M,limit:Te.limit,values:!0,direction:Te.dir==="prev"?"prev":void 0,query:{index:re,range:Te.range}}).then(function(Ne){return Ne=Ne.result,V?Ne.map(V):Ne})):(pe=[],bn(Te,function(Ne){return pe.push(Ne)},M,Te.table.core).then(function(){return pe}))},v)},Qt.prototype.offset=function(v){var P=this._ctx;return v<=0||(P.offset+=v,Rn(P)?Yn(P,function(){var M=v;return function(V,re){return M===0||(M===1?--M:re(function(){V.advance(M),M=0}),!1)}}):Yn(P,function(){var M=v;return function(){return--M<0}})),this},Qt.prototype.limit=function(v){return this._ctx.limit=Math.min(this._ctx.limit,v),Yn(this._ctx,function(){var P=v;return function(M,V,re){return--P<=0&&V(re),0<=P}},!0),this},Qt.prototype.until=function(v,P){return Mi(this._ctx,function(M,V,re){return!v(M.value)||(V(re),P)}),this},Qt.prototype.first=function(v){return this.limit(1).toArray(function(P){return P[0]}).then(v)},Qt.prototype.last=function(v){return this.reverse().first(v)},Qt.prototype.filter=function(v){var P;return Mi(this._ctx,function(M){return v(M.value)}),(P=this._ctx).isMatch=Cn(P.isMatch,v),this},Qt.prototype.and=function(v){return this.filter(v)},Qt.prototype.or=function(v){return new this.db.WhereClause(this._ctx.table,v,this)},Qt.prototype.reverse=function(){return this._ctx.dir=this._ctx.dir==="prev"?"next":"prev",this._ondirectionchange&&this._ondirectionchange(this._ctx.dir),this},Qt.prototype.desc=function(){return this.reverse()},Qt.prototype.eachKey=function(v){var P=this._ctx;return P.keysOnly=!P.isMatch,this.each(function(M,V){v(V.key,V)})},Qt.prototype.eachUniqueKey=function(v){return this._ctx.unique="unique",this.eachKey(v)},Qt.prototype.eachPrimaryKey=function(v){var P=this._ctx;return P.keysOnly=!P.isMatch,this.each(function(M,V){v(V.primaryKey,V)})},Qt.prototype.keys=function(v){var P=this._ctx,M=(P.keysOnly=!P.isMatch,[]);return this.each(function(V,re){M.push(re.key)}).then(function(){return M}).then(v)},Qt.prototype.primaryKeys=function(v){var P=this._ctx;if(Rn(P,!0)&&0<P.limit)return this._read(function(V){var re=Xn(P,P.table.core.schema);return P.table.core.query({trans:V,values:!1,limit:P.limit,direction:P.dir==="prev"?"prev":void 0,query:{index:re,range:P.range}})}).then(function(V){return V.result}).then(v);P.keysOnly=!P.isMatch;var M=[];return this.each(function(V,re){M.push(re.primaryKey)}).then(function(){return M}).then(v)},Qt.prototype.uniqueKeys=function(v){return this._ctx.unique="unique",this.keys(v)},Qt.prototype.firstKey=function(v){return this.limit(1).keys(function(P){return P[0]}).then(v)},Qt.prototype.lastKey=function(v){return this.reverse().firstKey(v)},Qt.prototype.distinct=function(){var v,P=this._ctx,P=P.index&&P.table.schema.idxByName[P.index];return P&&P.multi&&(v={},Mi(this._ctx,function(V){var V=V.primaryKey.toString(),re=g(v,V);return v[V]=!0,!re})),this},Qt.prototype.modify=function(v){var P=this,M=this._ctx;return this._write(function(V){function re(Ye,Qe){var lt=Qe.failures;He+=Ye-Qe.numFailures;for(var ot=0,ft=a(lt);ot<ft.length;ot++){var bt=ft[ot];Ge.push(lt[bt])}}var pe=typeof v=="function"?v:function(Ye){return di(Ye,v)},Te=M.table.core,Je=Te.schema.primaryKey,Ne=Je.outbound,We=Je.extractKey,at=200,Je=P.db._options.modifyChunkSize,Ge=(Je&&(at=typeof Je=="object"?Je[Te.name]||Je["*"]||200:Je),[]),He=0,nt=[],Xe=v===us;return P.clone().primaryKeys().then(function(Ye){function Qe(ot){var ft=Math.min(at,Ye.length-ot),bt=Ye.slice(ot,ot+ft);return(Xe?Promise.resolve([]):Te.getMany({trans:V,keys:bt,cache:"immutable"})).then(function(Et){var Ct=[],Pt=[],Dt=Ne?[]:null,At=Xe?bt:[];if(!Xe)for(var jt=0;jt<ft;++jt){var St=Et[jt],qt={value:ne(St),primKey:Ye[ot+jt]};pe.call(qt,qt.value,qt)!==!1&&(qt.value==null?At.push(Ye[ot+jt]):Ne||zt(We(St),We(qt.value))===0?(Pt.push(qt.value),Ne&&Dt.push(Ye[ot+jt])):(At.push(Ye[ot+jt]),Ct.push(qt.value)))}return Promise.resolve(0<Ct.length&&Te.mutate({trans:V,type:"add",values:Ct}).then(function($t){for(var Kt in $t.failures)At.splice(parseInt(Kt),1);re(Ct.length,$t)})).then(function(){return(0<Pt.length||lt&&typeof v=="object")&&Te.mutate({trans:V,type:"put",keys:Dt,values:Pt,criteria:lt,changeSpec:typeof v!="function"&&v,isAdditionalChunk:0<ot}).then(function($t){return re(Pt.length,$t)})}).then(function(){return(0<At.length||lt&&Xe)&&Te.mutate({trans:V,type:"delete",keys:At,criteria:lt,isAdditionalChunk:0<ot}).then(function($t){return mn(M.table,At,$t)}).then(function($t){return re(At.length,$t)})}).then(function(){return Ye.length>ot+ft&&Qe(ot+at)})})}var lt=Rn(M)&&M.limit===1/0&&(typeof v!="function"||Xe)&&{index:M.index,range:M.range};return Qe(0).then(function(){if(0<Ge.length)throw new ye("Error modifying one or more objects",Ge,He,nt);return Ye.length})})})},Qt.prototype.delete=function(){var v=this._ctx,P=v.range;return!Rn(v)||v.table.schema.yProps||!v.isPrimKey&&P.type!==3?this.modify(us):this._write(function(M){var V=v.table.core.schema.primaryKey,re=P;return v.table.core.count({trans:M,query:{index:V,range:re}}).then(function(pe){return v.table.core.mutate({trans:M,type:"deleteRange",range:re}).then(function(We){var Ne=We.failures,We=We.numFailures;if(We)throw new ye("Could not delete some values",Object.keys(Ne).map(function(at){return Ne[at]}),pe-We);return pe-We})})})};var vn=Qt;function Qt(){}var us=function(v,P){return P.value=null};function Fs(v,P){return v<P?-1:v===P?0:1}function hi(v,P){return P<v?-1:v===P?0:1}function Ar(v,P,M){return v=v instanceof Fi?new v.Collection(v):v,v._ctx.error=new(M||TypeError)(P),v}function jn(v){return new v.Collection(v,function(){return fs("")}).limit(0)}function yi(nt,P,M,V){var re,pe,Te,Ne,We,at,Je,Ge=M.length;if(!M.every(function(Ye){return typeof Ye=="string"}))return Ar(nt,hn);function He(Ye){re=Ye==="next"?function(lt){return lt.toUpperCase()}:function(lt){return lt.toLowerCase()},pe=Ye==="next"?function(lt){return lt.toLowerCase()}:function(lt){return lt.toUpperCase()},Te=Ye==="next"?Fs:hi;var Qe=M.map(function(lt){return{lower:pe(lt),upper:re(lt)}}).sort(function(lt,ot){return Te(lt.lower,ot.lower)});Ne=Qe.map(function(lt){return lt.upper}),We=Qe.map(function(lt){return lt.lower}),Je=(at=Ye)==="next"?"":V}He("next");var nt=new nt.Collection(nt,function(){return Sn(Ne[0],We[Ge-1]+V)}),Xe=(nt._ondirectionchange=function(Ye){He(Ye)},0);return nt._addAlgorithm(function(Ye,Qe,lt){var ot=Ye.key;if(typeof ot=="string"){var ft=pe(ot);if(P(ft,We,Xe))return!0;for(var bt=null,Et=Xe;Et<Ge;++Et){var Ct=((Pt,Dt,At,jt,St,qt)=>{for(var $t=Math.min(Pt.length,jt.length),Kt=-1,Yt=0;Yt<$t;++Yt){var B=Dt[Yt];if(B!==jt[Yt])return St(Pt[Yt],At[Yt])<0?Pt.substr(0,Yt)+At[Yt]+At.substr(Yt+1):St(Pt[Yt],jt[Yt])<0?Pt.substr(0,Yt)+jt[Yt]+At.substr(Yt+1):0<=Kt?Pt.substr(0,Kt)+Dt[Kt]+At.substr(Kt+1):null;St(Pt[Yt],B)<0&&(Kt=Yt)}return $t<jt.length&&qt==="next"?Pt+At.substr(Pt.length):$t<Pt.length&&qt==="prev"?Pt.substr(0,At.length):Kt<0?null:Pt.substr(0,Kt)+jt[Kt]+At.substr(Kt+1)})(ot,ft,Ne[Et],We[Et],Te,at);Ct===null&&bt===null?Xe=Et+1:(bt===null||0<Te(bt,Ct))&&(bt=Ct)}Qe(bt!==null?function(){Ye.continue(bt+Je)}:lt)}return!1}),nt}function Sn(v,P,M,V){return{type:2,lower:v,upper:P,lowerOpen:M,upperOpen:V}}function fs(v){return{type:1,lower:v,upper:v}}Object.defineProperty(br.prototype,"Collection",{get:function(){return this._ctx.table.db.Collection},enumerable:!1,configurable:!0}),br.prototype.between=function(v,P,M,V){M=M!==!1,V=V===!0;try{return 0<this._cmp(v,P)||this._cmp(v,P)===0&&(M||V)&&(!M||!V)?jn(this):new this.Collection(this,function(){return Sn(v,P,!M,!V)})}catch{return Ar(this,nn)}},br.prototype.equals=function(v){return v==null?Ar(this,nn):new this.Collection(this,function(){return fs(v)})},br.prototype.above=function(v){return v==null?Ar(this,nn):new this.Collection(this,function(){return Sn(v,void 0,!0)})},br.prototype.aboveOrEqual=function(v){return v==null?Ar(this,nn):new this.Collection(this,function(){return Sn(v,void 0,!1)})},br.prototype.below=function(v){return v==null?Ar(this,nn):new this.Collection(this,function(){return Sn(void 0,v,!1,!0)})},br.prototype.belowOrEqual=function(v){return v==null?Ar(this,nn):new this.Collection(this,function(){return Sn(void 0,v)})},br.prototype.startsWith=function(v){return typeof v!="string"?Ar(this,hn):this.between(v,v+rn,!0,!0)},br.prototype.startsWithIgnoreCase=function(v){return v===""?this.startsWith(v):yi(this,function(P,M){return P.indexOf(M[0])===0},[v],rn)},br.prototype.equalsIgnoreCase=function(v){return yi(this,function(P,M){return P===M[0]},[v],"")},br.prototype.anyOfIgnoreCase=function(){var v=Y.apply(K,arguments);return v.length===0?jn(this):yi(this,function(P,M){return M.indexOf(P)!==-1},v,"")},br.prototype.startsWithAnyOfIgnoreCase=function(){var v=Y.apply(K,arguments);return v.length===0?jn(this):yi(this,function(P,M){return M.some(function(V){return P.indexOf(V)===0})},v,rn)},br.prototype.anyOf=function(){var v,P,M=this,V=Y.apply(K,arguments),re=this._cmp;try{V.sort(re)}catch{return Ar(this,nn)}return V.length===0?jn(this):((v=new this.Collection(this,function(){return Sn(V[0],V[V.length-1])}))._ondirectionchange=function(pe){re=pe==="next"?M._ascending:M._descending,V.sort(re)},P=0,v._addAlgorithm(function(pe,Te,Ne){for(var We=pe.key;0<re(We,V[P]);)if(++P===V.length)return Te(Ne),!1;return re(We,V[P])===0||(Te(function(){pe.continue(V[P])}),!1)}),v)},br.prototype.notEqual=function(v){return this.inAnyRange([[-1/0,v],[v,this.db._maxKey]],{includeLowers:!1,includeUppers:!1})},br.prototype.noneOf=function(){var v=Y.apply(K,arguments);if(v.length===0)return new this.Collection(this);try{v.sort(this._ascending)}catch{return Ar(this,nn)}var P=v.reduce(function(M,V){return M?M.concat([[M[M.length-1][1],V]]):[[-1/0,V]]},null);return P.push([v[v.length-1],this.db._maxKey]),this.inAnyRange(P,{includeLowers:!1,includeUppers:!1})},br.prototype.inAnyRange=function(v,lt){var M=this,V=this._cmp,re=this._ascending,pe=this._descending,Te=this._min,Ne=this._max;if(v.length===0)return jn(this);if(!v.every(function(ot){return ot[0]!==void 0&&ot[1]!==void 0&&re(ot[0],ot[1])<=0}))return Ar(this,"First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower",Me.InvalidArgument);var We=!lt||lt.includeLowers!==!1,at=lt&&lt.includeUppers===!0,Je,Ge=re;function He(ot,ft){return Ge(ot[0],ft[0])}try{(Je=v.reduce(function(ot,ft){for(var bt=0,Et=ot.length;bt<Et;++bt){var Ct=ot[bt];if(V(ft[0],Ct[1])<0&&0<V(ft[1],Ct[0])){Ct[0]=Te(Ct[0],ft[0]),Ct[1]=Ne(Ct[1],ft[1]);break}}return bt===Et&&ot.push(ft),ot},[])).sort(He)}catch{return Ar(this,nn)}var nt=0,Xe=at?function(ot){return 0<re(ot,Je[nt][1])}:function(ot){return 0<=re(ot,Je[nt][1])},Ye=We?function(ot){return 0<pe(ot,Je[nt][0])}:function(ot){return 0<=pe(ot,Je[nt][0])},Qe=Xe,lt=new this.Collection(this,function(){return Sn(Je[0][0],Je[Je.length-1][1],!We,!at)});return lt._ondirectionchange=function(ot){Ge=ot==="next"?(Qe=Xe,re):(Qe=Ye,pe),Je.sort(He)},lt._addAlgorithm(function(ot,ft,bt){for(var Et,Ct=ot.key;Qe(Ct);)if(++nt===Je.length)return ft(bt),!1;return!Xe(Et=Ct)&&!Ye(Et)||(M._cmp(Ct,Je[nt][1])===0||M._cmp(Ct,Je[nt][0])===0||ft(function(){Ge===re?ot.continue(Je[nt][0]):ot.continue(Je[nt][1])}),!1)}),lt},br.prototype.startsWithAnyOf=function(){var v=Y.apply(K,arguments);return v.every(function(P){return typeof P=="string"})?v.length===0?jn(this):this.inAnyRange(v.map(function(P){return[P,P+rn]})):Ar(this,"startsWithAnyOf() only works with strings")};var Fi=br;function br(){}function Cr(v){return Wt(function(P){return Tn(P),v(P.target.error),!1})}function Tn(v){v.stopPropagation&&v.stopPropagation(),v.preventDefault&&v.preventDefault()}var Mn="storagemutated",qi="x-storagemutated-1",Yr=gn(null,Mn),qs=(Mr.prototype._lock=function(){return T(!xt.global),++this._reculock,this._reculock!==1||xt.global||(xt.lockOwnerFor=this),this},Mr.prototype._unlock=function(){if(T(!xt.global),--this._reculock==0)for(xt.global||(xt.lockOwnerFor=null);0<this._blockedFuncs.length&&!this._locked();){var v=this._blockedFuncs.shift();try{Nr(v[1],v[0])}catch{}}return this},Mr.prototype._locked=function(){return this._reculock&&xt.lockOwnerFor!==this},Mr.prototype.create=function(v){var P=this;if(this.mode){var M=this.db.idbdb,V=this.db._state.dbOpenError;if(T(!this.idbtrans),!v&&!M)switch(V&&V.name){case"DatabaseClosedError":throw new Me.DatabaseClosed(V);case"MissingAPIError":throw new Me.MissingAPI(V.message,V);default:throw new Me.OpenFailed(V)}if(!this.active)throw new Me.TransactionInactive;T(this._completion._state===null),(v=this.idbtrans=v||(this.db.core||M).transaction(this.storeNames,this.mode,{durability:this.chromeTransactionDurability})).onerror=Wt(function(re){Tn(re),P._reject(v.error)}),v.onabort=Wt(function(re){Tn(re),P.active&&P._reject(new Me.Abort(v.error)),P.active=!1,P.on("abort").fire(re)}),v.oncomplete=Wt(function(){P.active=!1,P._resolve(),"mutatedParts"in v&&Yr.storagemutated.fire(v.mutatedParts)})}return this},Mr.prototype._promise=function(v,P,M){var V,re=this;return v==="readwrite"&&this.mode!=="readwrite"?dr(new Me.ReadOnly("Transaction is readonly")):this.active?this._locked()?new be(function(pe,Te){re._blockedFuncs.push([function(){re._promise(v,P,M).then(pe,Te)},xt])}):M?Vr(function(){var pe=new be(function(Te,Ne){re._lock();var We=P(Te,Ne,re);We&&We.then&&We.then(Te,Ne)});return pe.finally(function(){return re._unlock()}),pe._lib=!0,pe}):((V=new be(function(pe,Te){var Ne=P(pe,Te,re);Ne&&Ne.then&&Ne.then(pe,Te)}))._lib=!0,V):dr(new Me.TransactionInactive)},Mr.prototype._root=function(){return this.parent?this.parent._root():this},Mr.prototype.waitFor=function(v){var P,M=this._root(),V=be.resolve(v),re=(M._waitingFor?M._waitingFor=M._waitingFor.then(function(){return V}):(M._waitingFor=V,M._waitingQueue=[],P=M.idbtrans.objectStore(M.storeNames[0]),function pe(){for(++M._spinCount;M._waitingQueue.length;)M._waitingQueue.shift()();M._waitingFor&&(P.get(-1/0).onsuccess=pe)}()),M._waitingFor);return new be(function(pe,Te){V.then(function(Ne){return M._waitingQueue.push(Wt(pe.bind(null,Ne)))},function(Ne){return M._waitingQueue.push(Wt(Te.bind(null,Ne)))}).finally(function(){M._waitingFor===re&&(M._waitingFor=null)})})},Mr.prototype.abort=function(){this.active&&(this.active=!1,this.idbtrans&&this.idbtrans.abort(),this._reject(new Me.Abort))},Mr.prototype.table=function(v){var P=this._memoizedTables||(this._memoizedTables={});if(g(P,v))return P[v];var M=this.schema[v];if(M)return(M=new this.db.Table(v,M,this)).core=this.db.core.table(v),P[v]=M;throw new Me.NotFound("Table "+v+" not part of transaction")},Mr);function Mr(){}function $i(v,P,M,V,re,pe,Te,Ne){return{name:v,keyPath:P,unique:M,multi:V,auto:re,compound:pe,src:(M&&!Te?"&":"")+(V?"*":"")+(re?"++":"")+Ui(P),type:Ne}}function Ui(v){return typeof v=="string"?v:v?"["+[].join.call(v,"+")+"]":""}function It(v,P,M){return{name:v,primKey:P,indexes:M,mappedClass:null,idxByName:(V=function(re){return[re.name,re]},M.reduce(function(re,pe,Te){return pe=V(pe,Te),pe&&(re[pe[0]]=pe[1]),re},{}))};var V}var Qn=function(v){try{return v.only([[]]),Qn=function(){return[[]]},[[]]}catch{return Qn=function(){return rn},rn}};function mi(v){return v==null?function(){}:typeof v=="string"?(P=v).split(".").length===1?function(M){return M[P]}:function(M){return R(M,P)}:function(M){return R(M,v)};var P}function ps(v){return[].slice.call(v)}var $s=0;function Zn(v){return v==null?":id":typeof v=="string"?v:"[".concat(v.join("+"),"]")}function Us(v,P,Te){function V(Qe){if(Qe.type===3)return null;if(Qe.type===4)throw new Error("Cannot convert never type to IDBKeyRange");var nt=Qe.lower,Xe=Qe.upper,Ye=Qe.lowerOpen,Qe=Qe.upperOpen;return nt===void 0?Xe===void 0?null:P.upperBound(Xe,!!Qe):Xe===void 0?P.lowerBound(nt,!!Ye):P.bound(nt,Xe,!!Ye,!!Qe)}function re(He){var nt,Xe,Ye=He.name;return{name:Ye,schema:He,mutate:function(Qe){var lt=Qe.trans,ot=Qe.type,ft=Qe.keys,bt=Qe.values,Et=Qe.range;return new Promise(function(Ct,Pt){Ct=Wt(Ct);var Dt=lt.objectStore(Ye),At=Dt.keyPath==null,jt=ot==="put"||ot==="add";if(!jt&&ot!=="delete"&&ot!=="deleteRange")throw new Error("Invalid operation type: "+ot);var St,qt=(ft||bt||{length:1}).length;if(ft&&bt&&ft.length!==bt.length)throw new Error("Given keys array must have same length as given values array.");if(qt===0)return Ct({numFailures:0,failures:{},results:[],lastResult:void 0});function $t(tt){++B,Tn(tt)}var Kt=[],Yt=[],B=0;if(ot==="deleteRange"){if(Et.type===4)return Ct({numFailures:B,failures:Yt,results:[],lastResult:void 0});Et.type===3?Kt.push(St=Dt.clear()):Kt.push(St=Dt.delete(V(Et)))}else{var At=jt?At?[bt,ft]:[bt,null]:[ft,null],k=At[0],F=At[1];if(jt)for(var ie=0;ie<qt;++ie)Kt.push(St=F&&F[ie]!==void 0?Dt[ot](k[ie],F[ie]):Dt[ot](k[ie])),St.onerror=$t;else for(ie=0;ie<qt;++ie)Kt.push(St=Dt[ot](k[ie])),St.onerror=$t}function ke(tt){tt=tt.target.result,Kt.forEach(function(Nt,cr){return Nt.error!=null&&(Yt[cr]=Nt.error)}),Ct({numFailures:B,failures:Yt,results:ot==="delete"?ft:Kt.map(function(Nt){return Nt.result}),lastResult:tt})}St.onerror=function(tt){$t(tt),ke(tt)},St.onsuccess=ke})},getMany:function(Qe){var lt=Qe.trans,ot=Qe.keys;return new Promise(function(ft,bt){ft=Wt(ft);for(var Et,Ct=lt.objectStore(Ye),Pt=ot.length,Dt=new Array(Pt),At=0,jt=0,St=function(Kt){Kt=Kt.target,Dt[Kt._pos]=Kt.result,++jt===At&&ft(Dt)},qt=Cr(bt),$t=0;$t<Pt;++$t)ot[$t]!=null&&((Et=Ct.get(ot[$t]))._pos=$t,Et.onsuccess=St,Et.onerror=qt,++At);At===0&&ft(Dt)})},get:function(Qe){var lt=Qe.trans,ot=Qe.key;return new Promise(function(ft,bt){ft=Wt(ft);var Et=lt.objectStore(Ye).get(ot);Et.onsuccess=function(Ct){return ft(Ct.target.result)},Et.onerror=Cr(bt)})},query:(nt=We,Xe=at,function(Qe){return new Promise(function(lt,ot){lt=Wt(lt);var ft,bt,Et,Ct,qt=Qe.trans,Pt=Qe.values,Dt=Qe.limit,St=Qe.query,At=(At=Qe.direction)!=null?At:"next",jt=Dt===1/0?void 0:Dt,$t=St.index,St=St.range,qt=qt.objectStore(Ye),qt=$t.isPrimaryKey?qt:qt.index($t.name),$t=V(St);if(Dt===0)return lt({result:[]});Xe?(St={query:$t,count:jt,direction:At},(ft=Pt?qt.getAll(St):qt.getAllKeys(St)).onsuccess=function(Kt){return lt({result:Kt.target.result})},ft.onerror=Cr(ot)):nt&&At==="next"?((ft=Pt?qt.getAll($t,jt):qt.getAllKeys($t,jt)).onsuccess=function(Kt){return lt({result:Kt.target.result})},ft.onerror=Cr(ot)):(bt=0,Et=!Pt&&"openKeyCursor"in qt?qt.openKeyCursor($t,At):qt.openCursor($t,At),Ct=[],Et.onsuccess=function(){var Kt=Et.result;return!Kt||(Ct.push(Pt?Kt.value:Kt.primaryKey),++bt===Dt)?lt({result:Ct}):void Kt.continue()},Et.onerror=Cr(ot))})}),openCursor:function(Qe){var lt=Qe.trans,ot=Qe.values,ft=Qe.query,bt=Qe.reverse,Et=Qe.unique;return new Promise(function(Ct,Pt){Ct=Wt(Ct);var jt=ft.index,Dt=ft.range,At=lt.objectStore(Ye),At=jt.isPrimaryKey?At:At.index(jt.name),jt=bt?Et?"prevunique":"prev":Et?"nextunique":"next",St=!ot&&"openKeyCursor"in At?At.openKeyCursor(V(Dt),jt):At.openCursor(V(Dt),jt);St.onerror=Cr(Pt),St.onsuccess=Wt(function(qt){var $t,Kt,Yt,B,k=St.result;k?(k.___id=++$s,k.done=!1,$t=k.continue.bind(k),Kt=(Kt=k.continuePrimaryKey)&&Kt.bind(k),Yt=k.advance.bind(k),B=function(){throw new Error("Cursor not stopped")},k.trans=lt,k.stop=k.continue=k.continuePrimaryKey=k.advance=function(){throw new Error("Cursor not started")},k.fail=Wt(Pt),k.next=function(){var F=this,ie=1;return this.start(function(){return ie--?F.continue():F.stop()}).then(function(){return F})},k.start=function(F){function ie(){if(St.result)try{F()}catch(tt){k.fail(tt)}else k.done=!0,k.start=function(){throw new Error("Cursor behind last entry")},k.stop()}var ke=new Promise(function(tt,Nt){tt=Wt(tt),St.onerror=Cr(Nt),k.fail=Nt,k.stop=function(cr){k.stop=k.continue=k.continuePrimaryKey=k.advance=B,tt(cr)}});return St.onsuccess=Wt(function(tt){St.onsuccess=ie,ie()}),k.continue=$t,k.continuePrimaryKey=Kt,k.advance=Yt,ie(),ke},Ct(k)):Ct(null)},Pt)})},count:function(Qe){var lt=Qe.query,ot=Qe.trans,ft=lt.index,bt=lt.range;return new Promise(function(Et,Ct){var Pt=ot.objectStore(Ye),Pt=ft.isPrimaryKey?Pt:Pt.index(ft.name),Dt=V(bt),Dt=Dt?Pt.count(Dt):Pt.count();Dt.onsuccess=Wt(function(At){return Et(At.target.result)}),Dt.onerror=Cr(Ct)})}}}pe=Te,Ne=ps((Te=v).objectStoreNames),Je=0<Ne.length?pe.objectStore(Ne[0]):{};var pe,Te={schema:{name:Te.name,tables:Ne.map(function(He){return pe.objectStore(He)}).map(function(He){var nt=He.keyPath,Xe=He.autoIncrement,Qe=f(nt),Ye={},Qe={name:He.name,primaryKey:{name:null,isPrimaryKey:!0,outbound:nt==null,compound:Qe,keyPath:nt,autoIncrement:Xe,unique:!0,extractKey:mi(nt)},indexes:ps(He.indexNames).map(function(lt){return He.index(lt)}).map(function(bt){var Et=bt.name,ot=bt.unique,ft=bt.multiEntry,bt=bt.keyPath,Et={name:Et,compound:f(bt),keyPath:bt,unique:ot,multiEntry:ft,extractKey:mi(bt)};return Ye[Zn(bt)]=Et}),getIndexByKeyPath:function(lt){return Ye[Zn(lt)]}};return Ye[":id"]=Qe.primaryKey,nt!=null&&(Ye[Zn(nt)]=Qe.primaryKey),Qe})},hasGetAll:0<Ne.length&&"getAll"in Je&&!(typeof navigator<"u"&&/Safari/.test(navigator.userAgent)&&!/(Chrome\/|Edge\/)/.test(navigator.userAgent)&&[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]<604),hasIdb3Features:"getAllRecords"in Je},Ne=Te.schema,We=Te.hasGetAll,at=Te.hasIdb3Features,Je=Ne.tables.map(re),Ge={};return Je.forEach(function(He){return Ge[He.name]=He}),{stack:"dbcore",transaction:v.transaction.bind(v),table:function(He){if(Ge[He])return Ge[He];throw new Error("Table '".concat(He,"' not found"))},MIN_KEY:-1/0,MAX_KEY:Qn(P),schema:Ne}}function ds(v,P,M,V){return M=M.IDBKeyRange,P=Us(P,M,V),{dbcore:v.dbcore.reduce(function(re,pe){return pe=pe.create,n(n({},re),pe(re))},P)}}function gi(v,P){var M=P.db,M=ds(v._middlewares,M,v._deps,P);v.core=M.dbcore,v.tables.forEach(function(V){var re=V.name;v.core.schema.tables.some(function(pe){return pe.name===re})&&(V.core=v.core.table(re),v[re]instanceof v.Table)&&(v[re].core=V.core)})}function ei(v,P,M,V){M.forEach(function(re){var pe=V[re];P.forEach(function(Te){var Ne=function We(at,Je){return _(at,Je)||(at=h(at))&&We(at,Je)}(Te,re);(!Ne||"value"in Ne&&Ne.value===void 0)&&(Te===v.Transaction.prototype||Te instanceof v.Transaction?O(Te,re,{get:function(){return this.table(re)},set:function(We){S(this,re,{value:We,writable:!0,configurable:!0,enumerable:!0})}}):Te[re]=new v.Table(re,pe))})})}function bi(v,P){P.forEach(function(M){for(var V in M)M[V]instanceof v.Table&&delete M[V]})}function Vs(v,P){return v._cfg.version-P._cfg.version}function Ks(v,P,M,V){var re=v._dbSchema,pe=(M.objectStoreNames.contains("$meta")&&!re.$meta&&(re.$meta=It("$meta",ys("")[0],[]),v._storeNames.push("$meta")),v._createTransaction("readwrite",v._storeNames,re)),Te=(pe.create(M),pe._completion.catch(V),pe._reject.bind(pe)),Ne=xt.transless||xt;Vr(function(){if(xt.trans=pe,xt.transless=Ne,P!==0)return gi(v,M),at=P,((We=pe).storeNames.includes("$meta")?We.table("$meta").get("version").then(function(Je){return Je??at}):be.resolve(at)).then(function(Qe){var Ge=v,He=Qe,nt=pe,Xe=M,Ye=[],Qe=Ge._versions,lt=Ge._dbSchema=Ti(0,Ge.idbdb,Xe);return(Qe=Qe.filter(function(ot){return ot._cfg.version>=He})).length===0?be.resolve():(Qe.forEach(function(ot){Ye.push(function(){var ft,bt,Et,Ct=lt,Pt=ot._cfg.dbschema,Dt=(Ln(Ge,Ct,Xe),Ln(Ge,Pt,Xe),lt=Ge._dbSchema=Pt,vi(Ct,Pt)),At=(Dt.add.forEach(function(jt){Vi(Xe,jt[0],jt[1].primKey,jt[1].indexes)}),Dt.change.forEach(function(jt){if(jt.recreate)throw new Me.Upgrade("Not yet support for changing primary key");var St=Xe.objectStore(jt.name);jt.add.forEach(function(qt){return Si(St,qt)}),jt.change.forEach(function(qt){St.deleteIndex(qt.name),Si(St,qt)}),jt.del.forEach(function(qt){return St.deleteIndex(qt)})}),ot._cfg.contentUpgrade);if(At&&ot._cfg.version>He)return gi(Ge,Xe),nt._memoizedTables={},ft=D(Pt),Dt.del.forEach(function(jt){ft[jt]=Ct[jt]}),bi(Ge,[Ge.Transaction.prototype]),ei(Ge,[Ge.Transaction.prototype],a(ft),ft),nt.schema=ft,(bt=he(At))&&tn(),Pt=be.follow(function(){var jt;(Et=At(nt))&&bt&&(jt=Rr.bind(null,null),Et.then(jt,jt))}),Et&&typeof Et.then=="function"?be.resolve(Et):Pt.then(function(){return Et})}),Ye.push(function(ft){var bt,Et,Ct=ot._cfg.dbschema;bt=Ct,Et=ft,[].slice.call(Et.db.objectStoreNames).forEach(function(Pt){return bt[Pt]==null&&Et.db.deleteObjectStore(Pt)}),bi(Ge,[Ge.Transaction.prototype]),ei(Ge,[Ge.Transaction.prototype],Ge._storeNames,Ge._dbSchema),nt.schema=Ge._dbSchema}),Ye.push(function(ft){Ge.idbdb.objectStoreNames.contains("$meta")&&(Math.ceil(Ge.idbdb.version/10)===ot._cfg.version?(Ge.idbdb.deleteObjectStore("$meta"),delete Ge._dbSchema.$meta,Ge._storeNames=Ge._storeNames.filter(function(bt){return bt!=="$meta"})):ft.objectStore("$meta").put(ot._cfg.version,"version"))})}),function ot(){return Ye.length?be.resolve(Ye.shift()(nt.idbtrans)).then(ot):be.resolve()}().then(function(){Ki(lt,Xe)}))}).catch(Te);var We,at;a(re).forEach(function(Je){Vi(M,Je,re[Je].primKey,re[Je].indexes)}),gi(v,M),be.follow(function(){return v.on.populate.fire(pe)}).catch(Te)})}function hs(v,P){Ki(v._dbSchema,P),P.db.version%10!=0||P.objectStoreNames.contains("$meta")||P.db.createObjectStore("$meta").add(Math.ceil(P.db.version/10-1),"version");var M=Ti(0,v.idbdb,P);Ln(v,v._dbSchema,P);for(var V=0,re=vi(M,v._dbSchema).change;V<re.length;V++){var pe=(Te=>{if(Te.change.length||Te.recreate)return console.warn("Unable to patch indexes of table ".concat(Te.name," because it has changes on the type of index or primary key.")),{value:void 0};var Ne=P.objectStore(Te.name);Te.add.forEach(function(We){ht&&console.debug("Dexie upgrade patch: Creating missing index ".concat(Te.name,".").concat(We.src)),Si(Ne,We)})})(re[V]);if(typeof pe=="object")return pe.value}}function vi(v,P){var M,V={del:[],add:[],change:[]};for(M in v)P[M]||V.del.push(M);for(M in P){var re=v[M],pe=P[M];if(re){var Te={name:M,def:pe,recreate:!1,del:[],add:[],change:[]};if(""+(re.primKey.keyPath||"")!=""+(pe.primKey.keyPath||"")||re.primKey.auto!==pe.primKey.auto)Te.recreate=!0,V.change.push(Te);else{var Ne=re.idxByName,We=pe.idxByName,at=void 0;for(at in Ne)We[at]||Te.del.push(at);for(at in We){var Je=Ne[at],Ge=We[at];Je?Je.src!==Ge.src&&Te.change.push(Ge):Te.add.push(Ge)}(0<Te.del.length||0<Te.add.length||0<Te.change.length)&&V.change.push(Te)}}else V.add.push([M,pe])}return V}function Vi(v,P,M,V){var re=v.db.createObjectStore(P,M.keyPath?{keyPath:M.keyPath,autoIncrement:M.auto}:{autoIncrement:M.auto});V.forEach(function(pe){return Si(re,pe)})}function Ki(v,P){a(v).forEach(function(M){P.db.objectStoreNames.contains(M)||(ht&&console.debug("Dexie: Creating missing table",M),Vi(P,M,v[M].primKey,v[M].indexes))})}function Si(v,P){v.createIndex(P.name,P.keyPath,{unique:P.unique,multiEntry:P.multi})}function Ti(v,P,M){var V={};return E(P.objectStoreNames,0).forEach(function(re){for(var pe=M.objectStore(re),Te=$i(Ui(at=pe.keyPath),at||"",!0,!1,!!pe.autoIncrement,at&&typeof at!="string",!0),Ne=[],We=0;We<pe.indexNames.length;++We){var Je=pe.index(pe.indexNames[We]),at=Je.keyPath,Je=$i(Je.name,at,!!Je.unique,!!Je.multiEntry,!1,at&&typeof at!="string",!1);Ne.push(Je)}V[re]=It(re,Te,Ne)}),V}function Ln(v,P,M){for(var V=M.db.objectStoreNames,re=0;re<V.length;++re){var pe=V[re],Te=M.objectStore(pe);v._hasGetAll="getAll"in Te;for(var Ne=0;Ne<Te.indexNames.length;++Ne){var We,at=Te.indexNames[Ne],Je=Te.index(at).keyPath,Je=typeof Je=="string"?Je:"["+E(Je).join("+")+"]";P[pe]&&(We=P[pe].idxByName[Je])&&(We.name=at,delete P[pe].idxByName[Je],P[pe].idxByName[at]=We)}}typeof navigator<"u"&&/Safari/.test(navigator.userAgent)&&!/(Chrome\/|Edge\/)/.test(navigator.userAgent)&&c.WorkerGlobalScope&&c instanceof c.WorkerGlobalScope&&[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]<604&&(v._hasGetAll=!1)}function ys(v){return v.split(",").map(function(P,M){var re=P.split(":"),V=(V=re[1])==null?void 0:V.trim(),re=(P=re[0].trim()).replace(/([&*]|\+\+)/g,""),pe=/^\[/.test(re)?re.match(/^\[(.*)\]$/)[1].split("+"):re;return $i(re,pe||null,/\&/.test(P),/\*/.test(P),/\+\+/.test(P),f(pe),M===0,V)})}En.prototype._createTableSchema=It,En.prototype._parseIndexSyntax=ys,En.prototype._parseStoresSpec=function(v,P){var M=this;a(v).forEach(function(V){if(v[V]!==null){var re=M._parseIndexSyntax(v[V]),pe=re.shift();if(!pe)throw new Me.Schema("Invalid schema for table "+V+": "+v[V]);if(pe.unique=!0,pe.multi)throw new Me.Schema("Primary key cannot be multiEntry*");re.forEach(function(Te){if(Te.auto)throw new Me.Schema("Only primary key can be marked as autoIncrement (++)");if(!Te.keyPath)throw new Me.Schema("Index must have a name and cannot be an empty string")}),pe=M._createTableSchema(V,pe,re),P[V]=pe}})},En.prototype.stores=function(M){var P=this.db,M=(this._cfg.storesSource=this._cfg.storesSource?p(this._cfg.storesSource,M):M,P._versions),V={},re={};return M.forEach(function(pe){p(V,pe._cfg.storesSource),re=pe._cfg.dbschema={},pe._parseStoresSpec(V,re)}),P._dbSchema=re,bi(P,[P._allTables,P,P.Transaction.prototype]),ei(P,[P._allTables,P,P.Transaction.prototype,this._cfg.tables],a(re),re),P._storeNames=a(re),this},En.prototype.upgrade=function(v){return this._cfg.contentUpgrade=gt(this._cfg.contentUpgrade||Ze,v),this};var Ws=En;function En(){}var ti=(()=>{var v,P,M;return typeof FinalizationRegistry<"u"&&typeof WeakRef<"u"?(v=new Set,P=new FinalizationRegistry(function(V){v.delete(V)}),{toArray:function(){return Array.from(v).map(function(V){return V.deref()}).filter(function(V){return V!==void 0})},add:function(V){var re=new WeakRef(V._novip);v.add(re),P.register(V._novip,re,re),v.size>V._options.maxConnections&&(re=v.values().next().value,v.delete(re),P.unregister(re))},remove:function(V){if(V)for(var re=v.values(),pe=re.next();!pe.done;){var Te=pe.value;if(Te.deref()===V._novip)return v.delete(Te),void P.unregister(Te);pe=re.next()}}}):(M=[],{toArray:function(){return M},add:function(V){M.push(V._novip)},remove:function(V){V&&(V=M.indexOf(V._novip))!==-1&&M.splice(V,1)}})})();function Wi(v,P){var M=v._dbNamesDB;return M||(M=v._dbNamesDB=new Xr(Wr,{addons:[],indexedDB:v,IDBKeyRange:P})).version(1).stores({dbnames:"name"}),M.table("dbnames")}function Ei(v){return v&&typeof v.databases=="function"}function Gi(v){return Vr(function(){return xt.letThrough=!0,v()})}function zi(v){return!("from"in v)}var Tr=function(v,P){var M;if(!this)return M=new Tr,v&&"d"in v&&p(M,v),M;p(this,arguments.length?{d:1,from:v,to:1<arguments.length?P:v}:{d:0})};function ri(v,P,M){var V=zt(P,M);if(!isNaN(V)){if(0<V)throw RangeError();if(zi(v))return p(v,{from:P,to:M,d:1});var V=v.l,re=v.r;if(zt(M,v.from)<0)return V?ri(V,P,M):v.l={from:P,to:M,d:1,l:null,r:null},z(v);if(0<zt(P,v.to))return re?ri(re,P,M):v.r={from:P,to:M,d:1,l:null,r:null},z(v);zt(P,v.from)<0&&(v.from=P,v.l=null,v.d=re?re.d+1:1),0<zt(M,v.to)&&(v.to=M,v.r=null,v.d=v.l?v.l.d+1:1),P=!v.r,V&&!v.l&&sn(v,V),re&&P&&sn(v,re)}}function sn(v,P){zi(P)||function M(V,re){var pe=re.from,Te=re.l,Ne=re.r;ri(V,pe,re.to),Te&&M(V,Te),Ne&&M(V,Ne)}(v,P)}function Hi(v,P){var M=xi(P),V=M.next();if(!V.done)for(var re=V.value,pe=xi(v),Te=pe.next(re.from),Ne=Te.value;!V.done&&!Te.done;){if(zt(Ne.from,re.to)<=0&&0<=zt(Ne.to,re.from))return!0;zt(re.from,Ne.from)<0?re=(V=M.next(Ne.from)).value:Ne=(Te=pe.next(re.from)).value}return!1}function xi(v){var P=zi(v)?null:{s:0,n:v};return{next:function(M){for(var V=0<arguments.length;P;)switch(P.s){case 0:if(P.s=1,V)for(;P.n.l&&zt(M,P.n.from)<0;)P={up:P,n:P.n.l,s:1};else for(;P.n.l;)P={up:P,n:P.n.l,s:1};case 1:if(P.s=2,!V||zt(M,P.n.to)<=0)return{value:P.n,done:!1};case 2:if(P.n.r){P.s=3,P={up:P,n:P.n.r,s:0};continue}case 3:P=P.up}return{done:!0}}}}function z(v){var P,M,V,re=(((re=v.r)==null?void 0:re.d)||0)-(((re=v.l)==null?void 0:re.d)||0),re=1<re?"r":re<-1?"l":"";re&&(P=re=="r"?"l":"r",M=n({},v),V=v[re],v.from=V.from,v.to=V.to,v[re]=V[re],M[re]=V[P],(v[P]=M).d=o(M)),v.d=o(v)}function o(M){var P=M.r,M=M.l;return(P?M?Math.max(P.d,M.d):P.d:M?M.d:0)+1}function i(v,P){return a(P).forEach(function(M){v[M]?sn(v[M],P[M]):v[M]=function V(re){var pe,Te,Ne={};for(pe in re)g(re,pe)&&(Te=re[pe],Ne[pe]=!Te||typeof Te!="object"||N.has(Te.constructor)?Te:V(Te));return Ne}(P[M])}),v}function l(v,P){return v.all||P.all||Object.keys(v).some(function(M){return P[M]&&Hi(P[M],v[M])})}b(Tr.prototype,((oe={add:function(v){return sn(this,v),this},addKey:function(v){return ri(this,v,v),this},addKeys:function(v){var P=this;return v.forEach(function(M){return ri(P,M,M)}),this},hasKey:function(v){var P=xi(this).next(v).value;return P&&zt(P.from,v)<=0&&0<=zt(P.to,v)}})[Ae]=function(){return xi(this)},oe));var d={},w={},Q=!1;function le(v){i(w,v),Q||(Q=!0,setTimeout(function(){Q=!1,Pe(w,!(w={}))},0))}function Pe(v,P){P===void 0&&(P=!1);var M=new Set;if(v.all)for(var V=0,re=Object.values(d);V<re.length;V++)Be(Ne=re[V],v,M,P);else for(var pe in v){var Te,Ne,pe=/^idb\:\/\/(.*)\/(.*)\//.exec(pe);pe&&(Te=pe[1],pe=pe[2],Ne=d["idb://".concat(Te,"/").concat(pe)])&&Be(Ne,v,M,P)}M.forEach(function(We){return We()})}function Be(v,P,M,V){for(var re=[],pe=0,Te=Object.entries(v.queries.query);pe<Te.length;pe++){for(var Ne=Te[pe],We=Ne[0],at=[],Je=0,Ge=Ne[1];Je<Ge.length;Je++){var He=Ge[Je];l(P,He.obsSet)?He.subscribers.forEach(function(Qe){return M.add(Qe)}):V&&at.push(He)}V&&re.push([We,at])}if(V)for(var nt=0,Xe=re;nt<Xe.length;nt++){var Ye=Xe[nt],We=Ye[0],at=Ye[1];v.queries.query[We]=at}}function Ue(v){var P=v._state,M=v._deps.indexedDB;if(P.isBeingOpened||v.idbdb)return P.dbReadyPromise.then(function(){return P.dbOpenError?dr(P.dbOpenError):v});P.isBeingOpened=!0,P.dbOpenError=null,P.openComplete=!1;var V=P.openCanceller,re=Math.round(10*v.verno),pe=!1;function Te(){if(P.openCanceller!==V)throw new Me.DatabaseClosed("db.open() was cancelled")}function Ne(){return new be(function(He,nt){if(Te(),!M)throw new Me.MissingAPI;var Xe=v.name,Ye=P.autoSchema||!re?M.open(Xe):M.open(Xe,re);if(!Ye)throw new Me.MissingAPI;Ye.onerror=Cr(nt),Ye.onblocked=Wt(v._fireOnBlocked),Ye.onupgradeneeded=Wt(function(Qe){var lt;Je=Ye.transaction,P.autoSchema&&!v._options.allowEmptyDB?(Ye.onerror=Tn,Je.abort(),Ye.result.close(),(lt=M.deleteDatabase(Xe)).onsuccess=lt.onerror=Wt(function(){nt(new Me.NoSuchDatabase("Database ".concat(Xe," doesnt exist")))})):(Je.onerror=Cr(nt),lt=Qe.oldVersion>Math.pow(2,62)?0:Qe.oldVersion,Ge=lt<1,v.idbdb=Ye.result,pe&&hs(v,Je),Ks(v,lt/10,Je,nt))},nt),Ye.onsuccess=Wt(function(){Je=null;var Qe,lt,ot,ft,bt,Et,Ct=v.idbdb=Ye.result,Pt=E(Ct.objectStoreNames);if(0<Pt.length)try{var Dt=Ct.transaction((bt=Pt).length===1?bt[0]:bt,"readonly");if(P.autoSchema)Et=Ct,ft=Dt,(ot=v).verno=Et.version/10,ft=ot._dbSchema=Ti(0,Et,ft),ot._storeNames=E(Et.objectStoreNames,0),ei(ot,[ot._allTables],a(ft),ft);else if(Ln(v,v._dbSchema,Dt),lt=Dt,((lt=vi(Ti(0,(Qe=v).idbdb,lt),Qe._dbSchema)).add.length||lt.change.some(function(At){return At.add.length||At.change.length}))&&!pe)return console.warn("Dexie SchemaDiff: Schema was extended without increasing the number passed to db.version(). Dexie will add missing parts and increment native version number to workaround this."),Ct.close(),re=Ct.version+1,pe=!0,He(Ne());gi(v,Dt)}catch{}ti.add(v),Ct.onversionchange=Wt(function(At){P.vcFired=!0,v.on("versionchange").fire(At)}),Ct.onclose=Wt(function(){v.close({disableAutoOpen:!1})}),Ge&&(Pt=v._deps,bt=Xe,Ei(Et=Pt.indexedDB)||bt===Wr||Wi(Et,Pt.IDBKeyRange).put({name:bt}).catch(Ze)),He()},nt)}).catch(function(He){switch(He==null?void 0:He.name){case"UnknownError":if(0<P.PR1398_maxLoop)return P.PR1398_maxLoop--,console.warn("Dexie: Workaround for Chrome UnknownError on open()"),Ne();break;case"VersionError":if(0<re)return re=0,Ne()}return be.reject(He)})}var We,at=P.dbReadyResolve,Je=null,Ge=!1;return be.race([V,(typeof navigator>"u"?be.resolve():!navigator.userAgentData&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\//.test(navigator.userAgent)&&indexedDB.databases?new Promise(function(He){function nt(){return indexedDB.databases().finally(He)}We=setInterval(nt,100),nt()}).finally(function(){return clearInterval(We)}):Promise.resolve()).then(Ne)]).then(function(){return Te(),P.onReadyBeingFired=[],be.resolve(Gi(function(){return v.on.ready.fire(v.vip)})).then(function He(){var nt;if(0<P.onReadyBeingFired.length)return nt=P.onReadyBeingFired.reduce(gt,Ze),P.onReadyBeingFired=[],be.resolve(Gi(function(){return nt(v.vip)})).then(He)})}).finally(function(){P.openCanceller===V&&(P.onReadyBeingFired=null,P.isBeingOpened=!1)}).catch(function(He){P.dbOpenError=He;try{Je&&Je.abort()}catch{}return V===P.openCanceller&&v._close(),dr(He)}).finally(function(){P.openComplete=!0,at()}).then(function(){var He;return Ge&&(He={},v.tables.forEach(function(nt){nt.schema.indexes.forEach(function(Xe){Xe.name&&(He["idb://".concat(v.name,"/").concat(nt.name,"/").concat(Xe.name)]=new Tr(-1/0,[[[]]]))}),He["idb://".concat(v.name,"/").concat(nt.name,"/")]=He["idb://".concat(v.name,"/").concat(nt.name,"/:dels")]=new Tr(-1/0,[[[]]])}),Yr(Mn).fire(He),Pe(He,!0)),v})}function ct(v){function P(pe){return v.next(pe)}var M=re(P),V=re(function(pe){return v.throw(pe)});function re(pe){return function(Ne){var Ne=pe(Ne),We=Ne.value;return Ne.done?We:We&&typeof We.then=="function"?We.then(M,V):f(We)?Promise.all(We).then(M,V):M(We)}}return re(P)()}function vt(v,P,M){for(var V=f(v)?v.slice():[v],re=0;re<M;++re)V.push(P);return V}var wt={stack:"dbcore",name:"VirtualIndexMiddleware",level:1,create:function(v){return n(n({},v),{table:function(V){var M=v.table(V),V=M.schema,re=Object.create(null),pe=[];function Te(He,nt,Xe){var ot=Zn(He),Ye=re[ot]=re[ot]||[],Qe=He==null?0:typeof He=="string"?1:He.length,lt=0<nt,ot=n(n({},Xe),{name:lt?"".concat(ot,"(virtual-from:").concat(Xe.name,")"):Xe.name,lowLevelIndex:Xe,isVirtual:lt,keyTail:nt,keyLength:Qe,extractKey:mi(He),unique:!lt&&Xe.unique});return Ye.push(ot),ot.isPrimaryKey||pe.push(ot),1<Qe&&Te(Qe===2?He[0]:He.slice(0,Qe-1),nt+1,Xe),Ye.sort(function(ft,bt){return ft.keyTail-bt.keyTail}),ot}var Ne=Te(V.primaryKey.keyPath,0,V.primaryKey);re[":id"]=[Ne];for(var We=0,at=V.indexes;We<at.length;We++){var Je=at[We];Te(Je.keyPath,0,Je)}function Ge(He){var nt,Xe=He.query.index;return Xe.isVirtual?n(n({},He),{query:{index:Xe.lowLevelIndex,range:(nt=He.query.range,Xe=Xe.keyTail,{type:nt.type===1?2:nt.type,lower:vt(nt.lower,nt.lowerOpen?v.MAX_KEY:v.MIN_KEY,Xe),lowerOpen:!0,upper:vt(nt.upper,nt.upperOpen?v.MIN_KEY:v.MAX_KEY,Xe),upperOpen:!0})}}):He}return n(n({},M),{schema:n(n({},V),{primaryKey:Ne,indexes:pe,getIndexByKeyPath:function(He){return(He=re[Zn(He)])&&He[0]}}),count:function(He){return M.count(Ge(He))},query:function(He){return M.query(Ge(He))},openCursor:function(He){var nt=He.query.index,Xe=nt.keyTail,Ye=nt.keyLength;return nt.isVirtual?M.openCursor(Ge(He)).then(function(lt){return lt&&Qe(lt)}):M.openCursor(He);function Qe(lt){return Object.create(lt,{continue:{value:function(ot){ot!=null?lt.continue(vt(ot,He.reverse?v.MAX_KEY:v.MIN_KEY,Xe)):He.unique?lt.continue(lt.key.slice(0,Ye).concat(He.reverse?v.MIN_KEY:v.MAX_KEY,Xe)):lt.continue()}},continuePrimaryKey:{value:function(ot,ft){lt.continuePrimaryKey(vt(ot,v.MAX_KEY,Xe),ft)}},primaryKey:{get:function(){return lt.primaryKey}},key:{get:function(){var ot=lt.key;return Ye===1?ot[0]:ot.slice(0,Ye)}},value:{get:function(){return lt.value}}})}}})}})}};function Ot(v,P,M,V){return M=M||{},V=V||"",a(v).forEach(function(re){var pe,Te,Ne;g(P,re)?(pe=v[re],Te=P[re],typeof pe=="object"&&typeof Te=="object"&&pe&&Te?(Ne=Ce(pe))!==Ce(Te)?M[V+re]=P[re]:Ne==="Object"?Ot(pe,Te,M,V+re+"."):pe!==Te&&(M[V+re]=P[re]):pe!==Te&&(M[V+re]=P[re])):M[V+re]=void 0}),a(P).forEach(function(re){g(v,re)||(M[V+re]=P[re])}),M}function Gt(v,P){return P.type==="delete"?P.keys:P.keys||P.values.map(v.extractKey)}var or={stack:"dbcore",name:"HooksMiddleware",level:2,create:function(v){return n(n({},v),{table:function(P){var M=v.table(P),V=M.schema.primaryKey;return n(n({},M),{mutate:function(re){var pe=xt.trans,Te=pe.table(P).hook,Ne=Te.deleting,We=Te.creating,at=Te.updating;switch(re.type){case"add":if(We.fire===Ze)break;return pe._promise("readwrite",function(){return Je(re)},!0);case"put":if(We.fire===Ze&&at.fire===Ze)break;return pe._promise("readwrite",function(){return Je(re)},!0);case"delete":if(Ne.fire===Ze)break;return pe._promise("readwrite",function(){return Je(re)},!0);case"deleteRange":if(Ne.fire===Ze)break;return pe._promise("readwrite",function(){return function Ge(He,nt,Xe){return M.query({trans:He,values:!1,query:{index:V,range:nt},limit:Xe}).then(function(Ye){var Qe=Ye.result;return Je({type:"delete",keys:Qe,trans:He}).then(function(lt){return 0<lt.numFailures?Promise.reject(lt.failures[0]):Qe.length<Xe?{failures:[],numFailures:0,lastResult:void 0}:Ge(He,n(n({},nt),{lower:Qe[Qe.length-1],lowerOpen:!0}),Xe)})})}(re.trans,re.range,1e4)},!0)}return M.mutate(re);function Je(Ge){var He,nt,Xe,Ye=xt.trans,Qe=Ge.keys||Gt(V,Ge);if(Qe)return(Ge=Ge.type==="add"||Ge.type==="put"?n(n({},Ge),{keys:Qe}):n({},Ge)).type!=="delete"&&(Ge.values=s([],Ge.values)),Ge.keys&&(Ge.keys=s([],Ge.keys)),He=M,Xe=Qe,((nt=Ge).type==="add"?Promise.resolve([]):He.getMany({trans:nt.trans,keys:Xe,cache:"immutable"})).then(function(lt){var ot=Qe.map(function(ft,bt){var Et,Ct,Pt,Dt=lt[bt],At={onerror:null,onsuccess:null};return Ge.type==="delete"?Ne.fire.call(At,ft,Dt,Ye):Ge.type==="add"||Dt===void 0?(Et=We.fire.call(At,ft,Ge.values[bt],Ye),ft==null&&Et!=null&&(Ge.keys[bt]=ft=Et,V.outbound||I(Ge.values[bt],V.keyPath,ft))):(Et=Ot(Dt,Ge.values[bt]),(Ct=at.fire.call(At,Et,ft,Dt,Ye))&&(Pt=Ge.values[bt],Object.keys(Ct).forEach(function(jt){g(Pt,jt)?Pt[jt]=Ct[jt]:I(Pt,jt,Ct[jt])}))),At});return M.mutate(Ge).then(function(ft){for(var bt=ft.failures,Et=ft.results,Ct=ft.numFailures,ft=ft.lastResult,Pt=0;Pt<Qe.length;++Pt){var Dt=(Et||Qe)[Pt],At=ot[Pt];Dt==null?At.onerror&&At.onerror(bt[Pt]):At.onsuccess&&At.onsuccess(Ge.type==="put"&&lt[Pt]?Ge.values[Pt]:Dt)}return{failures:bt,results:Et,numFailures:Ct,lastResult:ft}}).catch(function(ft){return ot.forEach(function(bt){return bt.onerror&&bt.onerror(ft)}),Promise.reject(ft)})});throw new Error("Keys missing")}}})}})}};function Ft(v,P,M){try{if(!P||P.keys.length<v.length)return null;for(var V=[],re=0,pe=0;re<P.keys.length&&pe<v.length;++re)zt(P.keys[re],v[pe])===0&&(V.push(M?ne(P.values[re]):P.values[re]),++pe);return V.length===v.length?V:null}catch{return null}}var sr={stack:"dbcore",level:-1,create:function(v){return{table:function(P){var M=v.table(P);return n(n({},M),{getMany:function(V){var re;return V.cache?(re=Ft(V.keys,V.trans._cache,V.cache==="clone"))?be.resolve(re):M.getMany(V).then(function(pe){return V.trans._cache={keys:V.keys,values:V.cache==="clone"?ne(pe):pe},pe}):M.getMany(V)},mutate:function(V){return V.type!=="add"&&(V.trans._cache=null),M.mutate(V)}})}}}};function xn(v,P){return v.trans.mode==="readonly"&&!!v.subscr&&!v.trans.explicit&&v.trans.db._options.cache!=="disabled"&&!P.schema.primaryKey.outbound}function an(v,P){switch(v){case"query":return P.values&&!P.unique;case"get":case"getMany":case"count":case"openCursor":return!1}}var ms={stack:"dbcore",level:0,name:"Observability",create:function(v){var P=v.schema.name,M=new Tr(v.MIN_KEY,v.MAX_KEY);return n(n({},v),{transaction:function(V,re,pe){if(xt.subscr&&re!=="readonly")throw new Me.ReadOnly("Readwrite transaction in liveQuery context. Querier source: ".concat(xt.querier));return v.transaction(V,re,pe)},table:function(V){function re(Qe){var Ye,Qe=Qe.query;return[Ye=Qe.index,new Tr((Ye=(Qe=Qe.range).lower)!=null?Ye:v.MIN_KEY,(Ye=Qe.upper)!=null?Ye:v.MAX_KEY)]}var pe=v.table(V),Te=pe.schema,Ne=Te.primaryKey,We=Te.indexes,at=Ne.extractKey,Je=Ne.outbound,Ge=Ne.autoIncrement&&We.filter(function(Xe){return Xe.compound&&Xe.keyPath.includes(Ne.keyPath)}),He=n(n({},pe),{mutate:function(Xe){function Ye(St){return St="idb://".concat(P,"/").concat(V,"/").concat(St),bt[St]||(bt[St]=new Tr)}var Qe,lt,ot,ft=Xe.trans,bt=Xe.mutatedParts||(Xe.mutatedParts={}),Et=Ye(""),Ct=Ye(":dels"),Pt=Xe.type,At=Xe.type==="deleteRange"?[Xe.range]:Xe.type==="delete"?[Xe.keys]:Xe.values.length<50?[Gt(Ne,Xe).filter(function(St){return St}),Xe.values]:[],Dt=At[0],At=At[1],jt=Xe.trans._cache;return f(Dt)?(Et.addKeys(Dt),(Pt=Pt==="delete"||Dt.length===At.length?Ft(Dt,jt):null)||Ct.addKeys(Dt),(Pt||At)&&(Qe=Ye,lt=Pt,ot=At,Te.indexes.forEach(function(St){var qt=Qe(St.name||"");function $t(Yt){return Yt!=null?St.extractKey(Yt):null}function Kt(Yt){St.multiEntry&&f(Yt)?Yt.forEach(function(B){return qt.addKey(B)}):qt.addKey(Yt)}(lt||ot).forEach(function(Yt,F){var k=lt&&$t(lt[F]),F=ot&&$t(ot[F]);zt(k,F)!==0&&(k!=null&&Kt(k),F!=null)&&Kt(F)})}))):Dt?(At={from:(jt=Dt.lower)!=null?jt:v.MIN_KEY,to:(Pt=Dt.upper)!=null?Pt:v.MAX_KEY},Ct.add(At),Et.add(At)):(Et.add(M),Ct.add(M),Te.indexes.forEach(function(St){return Ye(St.name).add(M)})),pe.mutate(Xe).then(function(St){return!Dt||Xe.type!=="add"&&Xe.type!=="put"||(Et.addKeys(St.results),Ge&&Ge.forEach(function(qt){for(var $t=Xe.values.map(function(k){return qt.extractKey(k)}),Kt=qt.keyPath.findIndex(function(k){return k===Ne.keyPath}),Yt=0,B=St.results.length;Yt<B;++Yt)$t[Yt][Kt]=St.results[Yt];Ye(qt.name).addKeys($t)})),ft.mutatedParts=i(ft.mutatedParts||{},bt),St})}}),nt={get:function(Xe){return[Ne,new Tr(Xe.key)]},getMany:function(Xe){return[Ne,new Tr().addKeys(Xe.keys)]},count:re,query:re,openCursor:re};return a(nt).forEach(function(Xe){He[Xe]=function(Ye){var Qe=xt.subscr,lt=!!Qe,ot=xn(xt,pe)&&an(Xe,Ye)?Ye.obsSet={}:Qe;if(lt){var ft,Qe=function(At){return At="idb://".concat(P,"/").concat(V,"/").concat(At),ot[At]||(ot[At]=new Tr)},bt=Qe(""),Et=Qe(":dels"),lt=nt[Xe](Ye),Ct=lt[0],lt=lt[1];if((Xe==="query"&&Ct.isPrimaryKey&&!Ye.values?Et:Qe(Ct.name||"")).add(lt),!Ct.isPrimaryKey){if(Xe!=="count")return ft=Xe==="query"&&Je&&Ye.values&&pe.query(n(n({},Ye),{values:!1})),pe[Xe].apply(this,arguments).then(function(At){if(Xe==="query"){if(Je&&Ye.values)return ft.then(function($t){return $t=$t.result,bt.addKeys($t),At});var jt=Ye.values?At.result.map(at):At.result;(Ye.values?bt:Et).addKeys(jt)}else{var St,qt;if(Xe==="openCursor")return qt=Ye.values,(St=At)&&Object.create(St,{key:{get:function(){return Et.addKey(St.primaryKey),St.key}},primaryKey:{get:function(){var $t=St.primaryKey;return Et.addKey($t),$t}},value:{get:function(){return qt&&bt.addKey(St.primaryKey),St.value}}})}return At});Et.add(M)}}return pe[Xe].apply(this,arguments)}}),He}})}};function Ji(v,P,M){var V;return M.numFailures===0?P:P.type==="deleteRange"||(V=P.keys?P.keys.length:"values"in P&&P.values?P.values.length:1,M.numFailures===V)?null:(V=n({},P),f(V.keys)&&(V.keys=V.keys.filter(function(re,pe){return!(pe in M.failures)})),"values"in V&&f(V.values)&&(V.values=V.values.filter(function(re,pe){return!(pe in M.failures)})),V)}function Pi(v,P){return M=v,((V=P).lower===void 0||(V.lowerOpen?0<zt(M,V.lower):0<=zt(M,V.lower)))&&(M=v,(V=P).upper===void 0||(V.upperOpen?zt(M,V.upper)<0:zt(M,V.upper)<=0));var M,V}function Yi(v,P,M,V,re,pe){var Te,Ne,We,at,Je,Ge,He;return!M||M.length===0||(Te=P.query.index,Ne=Te.multiEntry,We=P.query.range,at=V.schema.primaryKey.extractKey,Je=Te.extractKey,Ge=(Te.lowLevelIndex||Te).extractKey,(V=M.reduce(function(nt,Xe){var Ye=nt,Qe=[];if(Xe.type==="add"||Xe.type==="put")for(var lt=new Tr,ot=Xe.values.length-1;0<=ot;--ot){var ft,bt=Xe.values[ot],Et=at(bt);!lt.hasKey(Et)&&(ft=Je(bt),Ne&&f(ft)?ft.some(function(jt){return Pi(jt,We)}):Pi(ft,We))&&(lt.addKey(Et),Qe.push(bt))}switch(Xe.type){case"add":var Ct=new Tr().addKeys(P.values?nt.map(function(St){return at(St)}):nt),Ye=nt.concat(P.values?Qe.filter(function(St){return St=at(St),!Ct.hasKey(St)&&(Ct.addKey(St),!0)}):Qe.map(function(St){return at(St)}).filter(function(St){return!Ct.hasKey(St)&&(Ct.addKey(St),!0)}));break;case"put":var Pt=new Tr().addKeys(Xe.values.map(function(St){return at(St)}));Ye=nt.filter(function(St){return!Pt.hasKey(P.values?at(St):St)}).concat(P.values?Qe:Qe.map(function(St){return at(St)}));break;case"delete":var Dt=new Tr().addKeys(Xe.keys);Ye=nt.filter(function(St){return!Dt.hasKey(P.values?at(St):St)});break;case"deleteRange":var At=Xe.range;Ye=nt.filter(function(St){return!Pi(at(St),At)})}return Ye},v))===v)?v:(He=function(nt,Xe){return zt(Ge(nt),Ge(Xe))||zt(at(nt),at(Xe))},V.sort(P.direction==="prev"||P.direction==="prevunique"?function(nt,Xe){return He(Xe,nt)}:He),P.limit&&P.limit<1/0&&(V.length>P.limit?V.length=P.limit:v.length===P.limit&&V.length<P.limit&&(re.dirty=!0)),pe?Object.freeze(V):V)}function Xi(v,P){return zt(v.lower,P.lower)===0&&zt(v.upper,P.upper)===0&&!!v.lowerOpen==!!P.lowerOpen&&!!v.upperOpen==!!P.upperOpen}function gs(v,P){return((M,V,re,pe)=>{if(M===void 0)return V!==void 0?-1:0;if(V===void 0)return 1;if((M=zt(M,V))===0){if(re&&pe)return 0;if(re)return 1;if(pe)return-1}return M})(v.lower,P.lower,v.lowerOpen,P.lowerOpen)<=0&&0<=((M,V,re,pe)=>{if(M===void 0)return V!==void 0?1:0;if(V===void 0)return-1;if((M=zt(M,V))===0){if(re&&pe)return 0;if(re)return-1;if(pe)return 1}return M})(v.upper,P.upper,v.upperOpen,P.upperOpen)}function bs(v,P,M,V){v.subscribers.add(M),V.addEventListener("abort",function(){var re,pe;v.subscribers.delete(M),v.subscribers.size===0&&(re=v,pe=P,setTimeout(function(){re.subscribers.size===0&&ue(pe,re)},3e3))})}var vs={stack:"dbcore",level:0,name:"Cache",create:function(v){var P=v.schema.name;return n(n({},v),{transaction:function(M,V,re){var pe,Te,Ne=v.transaction(M,V,re);return V==="readwrite"&&(re=(pe=new AbortController).signal,Ne.addEventListener("abort",(Te=function(We){return function(){if(pe.abort(),V==="readwrite"){for(var at=new Set,Je=0,Ge=M;Je<Ge.length;Je++){var He=Ge[Je],nt=d["idb://".concat(P,"/").concat(He)];if(nt){var Xe=v.table(He),Ye=nt.optimisticOps.filter(function(St){return St.trans===Ne});if(Ne._explicit&&We&&Ne.mutatedParts)for(var Qe=0,lt=Object.values(nt.queries.query);Qe<lt.length;Qe++)for(var ot=0,ft=(Ct=lt[Qe]).slice();ot<ft.length;ot++)l((Pt=ft[ot]).obsSet,Ne.mutatedParts)&&(ue(Ct,Pt),Pt.subscribers.forEach(function(St){return at.add(St)}));else if(0<Ye.length){nt.optimisticOps=nt.optimisticOps.filter(function(St){return St.trans!==Ne});for(var bt=0,Et=Object.values(nt.queries.query);bt<Et.length;bt++)for(var Ct,Pt,Dt,At=0,jt=(Ct=Et[bt]).slice();At<jt.length;At++)(Pt=jt[At]).res!=null&&Ne.mutatedParts&&(We&&!Pt.dirty?(Dt=Object.isFrozen(Pt.res),Dt=Yi(Pt.res,Pt.req,Ye,Xe,Pt,Dt),Pt.dirty?(ue(Ct,Pt),Pt.subscribers.forEach(function(St){return at.add(St)})):Dt!==Pt.res&&(Pt.res=Dt,Pt.promise=be.resolve({result:Dt}))):(Pt.dirty&&ue(Ct,Pt),Pt.subscribers.forEach(function(St){return at.add(St)})))}}}at.forEach(function(St){return St()})}}})(!1),{signal:re}),Ne.addEventListener("error",Te(!1),{signal:re}),Ne.addEventListener("complete",Te(!0),{signal:re})),Ne},table:function(M){var V=v.table(M),re=V.schema.primaryKey;return n(n({},V),{mutate:function(pe){var Te,Ne=xt.trans;return!re.outbound&&Ne.db._options.cache!=="disabled"&&!Ne.explicit&&Ne.idbtrans.mode==="readwrite"&&(Te=d["idb://".concat(P,"/").concat(M)])?(Ne=V.mutate(pe),pe.type!=="add"&&pe.type!=="put"||!(50<=pe.values.length||Gt(re,pe).some(function(We){return We==null}))?(Te.optimisticOps.push(pe),pe.mutatedParts&&le(pe.mutatedParts),Ne.then(function(We){0<We.numFailures&&(ue(Te.optimisticOps,pe),(We=Ji(0,pe,We))&&Te.optimisticOps.push(We),pe.mutatedParts)&&le(pe.mutatedParts)}),Ne.catch(function(){ue(Te.optimisticOps,pe),pe.mutatedParts&&le(pe.mutatedParts)})):Ne.then(function(We){var at=Ji(0,n(n({},pe),{values:pe.values.map(function(Je,Ge){var He;return We.failures[Ge]?Je:(I(He=(He=re.keyPath)!=null&&He.includes(".")?ne(Je):n({},Je),re.keyPath,We.results[Ge]),He)})}),We);Te.optimisticOps.push(at),queueMicrotask(function(){return pe.mutatedParts&&le(pe.mutatedParts)})}),Ne):V.mutate(pe)},query:function(pe){var Te,Ne,We,at,Je,Ge,He;return xn(xt,V)&&an("query",pe)?(Te=((We=xt.trans)==null?void 0:We.db._options.cache)==="immutable",Ne=(We=xt).requery,We=We.signal,Ge=((nt,Xe,Ye,Qe)=>{var lt=d["idb://".concat(nt,"/").concat(Xe)];if(!lt)return[];if(!(nt=lt.queries[Ye]))return[null,!1,lt,null];var ot=nt[(Qe.query?Qe.query.index.name:null)||""];if(!ot)return[null,!1,lt,null];switch(Ye){case"query":var ft=(bt=Qe.direction)!=null?bt:"next",bt=ot.find(function(Et){var Ct;return Et.req.limit===Qe.limit&&Et.req.values===Qe.values&&((Ct=Et.req.direction)!=null?Ct:"next")===ft&&Xi(Et.req.query.range,Qe.query.range)});return bt?[bt,!0,lt,ot]:[ot.find(function(Et){var Ct;return("limit"in Et.req?Et.req.limit:1/0)>=Qe.limit&&((Ct=Et.req.direction)!=null?Ct:"next")===ft&&(!Qe.values||Et.req.values)&&gs(Et.req.query.range,Qe.query.range)}),!1,lt,ot];case"count":return bt=ot.find(function(Et){return Xi(Et.req.query.range,Qe.query.range)}),[bt,!!bt,lt,ot]}})(P,M,"query",pe),He=Ge[0],at=Ge[2],Je=Ge[3],He&&Ge[1]?He.obsSet=pe.obsSet:(Ge=V.query(pe).then(function(nt){var Xe=nt.result;if(He&&(He.res=Xe),Te){for(var Ye=0,Qe=Xe.length;Ye<Qe;++Ye)Object.freeze(Xe[Ye]);Object.freeze(Xe)}return nt}).catch(function(nt){return Je&&He&&ue(Je,He),Promise.reject(nt)}),He={obsSet:pe.obsSet,promise:Ge,subscribers:new Set,type:"query",req:pe,dirty:!1},Je?Je.push(He):(Je=[He],(at=at||(d["idb://".concat(P,"/").concat(M)]={queries:{query:{},count:{}},objs:new Map,optimisticOps:[],unsignaledParts:{}})).queries.query[pe.query.index.name||""]=Je)),bs(He,Je,Ne,We),He.promise.then(function(nt){return nt=Yi(nt.result,pe,at==null?void 0:at.optimisticOps,V,He,Te),{result:Te?nt:ne(nt)}})):V.query(pe)}})}})}};function ni(v,P){return new Proxy(v,{get:function(M,V,re){return V==="db"?P:Reflect.get(M,V,re)}})}hr.prototype.version=function(v){if(isNaN(v)||v<.1)throw new Me.Type("Given version is not a positive number");if(v=Math.round(10*v)/10,this.idbdb||this._state.isBeingOpened)throw new Me.Schema("Cannot add version when database is open");this.verno=Math.max(this.verno,v);var P=this._versions,M=P.filter(function(V){return V._cfg.version===v})[0];return M||(M=new this.Version(v),P.push(M),P.sort(Vs),M.stores({}),this._state.autoSchema=!1),M},hr.prototype._whenReady=function(v){var P=this;return this.idbdb&&(this._state.openComplete||xt.letThrough||this._vip)?v():new be(function(M,V){if(P._state.openComplete)return V(new Me.DatabaseClosed(P._state.dbOpenError));if(!P._state.isBeingOpened){if(!P._state.autoOpen)return void V(new Me.DatabaseClosed);P.open().catch(Ze)}P._state.dbReadyPromise.then(M,V)}).then(v)},hr.prototype.use=function(re){var P=re.stack,M=re.create,V=re.level,re=re.name,pe=(re&&this.unuse({stack:P,name:re}),this._middlewares[P]||(this._middlewares[P]=[]));return pe.push({stack:P,create:M,level:V??10,name:re}),pe.sort(function(Te,Ne){return Te.level-Ne.level}),this},hr.prototype.unuse=function(v){var P=v.stack,M=v.name,V=v.create;return P&&this._middlewares[P]&&(this._middlewares[P]=this._middlewares[P].filter(function(re){return V?re.create!==V:!!M&&re.name!==M})),this},hr.prototype.open=function(){var v=this;return Nr(pt,function(){return Ue(v)})},hr.prototype._close=function(){this.on.close.fire(new CustomEvent("close"));var v=this._state;if(ti.remove(this),this.idbdb){try{this.idbdb.close()}catch{}this.idbdb=null}v.isBeingOpened||(v.dbReadyPromise=new be(function(P){v.dbReadyResolve=P}),v.openCanceller=new be(function(P,M){v.cancelOpen=M}))},hr.prototype.close=function(P){var P=(P===void 0?{disableAutoOpen:!0}:P).disableAutoOpen,M=this._state;P?(M.isBeingOpened&&M.cancelOpen(new Me.DatabaseClosed),this._close(),M.autoOpen=!1,M.dbOpenError=new Me.DatabaseClosed):(this._close(),M.autoOpen=this._options.autoOpen||M.isBeingOpened,M.openComplete=!1,M.dbOpenError=null)},hr.prototype.delete=function(v){var P=this,M=(v===void 0&&(v={disableAutoOpen:!0}),0<arguments.length&&typeof arguments[0]!="object"),V=this._state;return new be(function(re,pe){function Te(){P.close(v);var Ne=P._deps.indexedDB.deleteDatabase(P.name);Ne.onsuccess=Wt(function(){var We,at,Je;We=P._deps,at=P.name,Ei(Je=We.indexedDB)||at===Wr||Wi(Je,We.IDBKeyRange).delete(at).catch(Ze),re()}),Ne.onerror=Cr(pe),Ne.onblocked=P._fireOnBlocked}if(M)throw new Me.InvalidArgument("Invalid closeOptions argument to db.delete()");V.isBeingOpened?V.dbReadyPromise.then(Te):Te()})},hr.prototype.backendDB=function(){return this.idbdb},hr.prototype.isOpen=function(){return this.idbdb!==null},hr.prototype.hasBeenClosed=function(){var v=this._state.dbOpenError;return v&&v.name==="DatabaseClosed"},hr.prototype.hasFailed=function(){return this._state.dbOpenError!==null},hr.prototype.dynamicallyOpened=function(){return this._state.autoSchema},Object.defineProperty(hr.prototype,"tables",{get:function(){var v=this;return a(this._allTables).map(function(P){return v._allTables[P]})},enumerable:!1,configurable:!0}),hr.prototype.transaction=function(){var v=(function(P,M,V){var re=arguments.length;if(re<2)throw new Me.InvalidArgument("Too few arguments");for(var pe=new Array(re-1);--re;)pe[re-1]=arguments[re];return V=pe.pop(),[P,J(pe),V]}).apply(this,arguments);return this._transaction.apply(this,v)},hr.prototype._transaction=function(v,P,M){var V,re,pe=this,Te=xt.trans,Ne=(Te&&Te.db===this&&v.indexOf("!")===-1||(Te=null),v.indexOf("?")!==-1);v=v.replace("!","").replace("?","");try{if(re=P.map(function(at){if(at=at instanceof pe.Table?at.name:at,typeof at!="string")throw new TypeError("Invalid table argument to Dexie.transaction(). Only Table or String are allowed");return at}),v=="r"||v===yn)V=yn;else{if(v!="rw"&&v!=Ri)throw new Me.InvalidArgument("Invalid transaction mode: "+v);V=Ri}if(Te){if(Te.mode===yn&&V===Ri){if(!Ne)throw new Me.SubTransaction("Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY");Te=null}Te&&re.forEach(function(at){if(Te&&Te.storeNames.indexOf(at)===-1){if(!Ne)throw new Me.SubTransaction("Table "+at+" not included in parent transaction.");Te=null}}),Ne&&Te&&!Te.active&&(Te=null)}}catch(at){return Te?Te._promise(null,function(Je,Ge){Ge(at)}):dr(at)}var We=(function at(Je,Ge,He,nt,Xe){return be.resolve().then(function(){var ot=xt.transless||xt,Ye=Je._createTransaction(Ge,He,Je._dbSchema,nt),ot=(Ye.explicit=!0,{trans:Ye,transless:ot});if(nt)Ye.idbtrans=nt.idbtrans;else try{Ye.create(),Ye.idbtrans._explicit=!0,Je._state.PR1398_maxLoop=3}catch(ft){return ft.name===Ee.InvalidState&&Je.isOpen()&&0<--Je._state.PR1398_maxLoop?(console.warn("Dexie: Need to reopen db"),Je.close({disableAutoOpen:!1}),Je.open().then(function(){return at(Je,Ge,He,null,Xe)})):dr(ft)}var Qe,lt=he(Xe),ot=(lt&&tn(),be.follow(function(){var ft;(Qe=Xe.call(Ye,Ye))&&(lt?(ft=Rr.bind(null,null),Qe.then(ft,ft)):typeof Qe.next=="function"&&typeof Qe.throw=="function"&&(Qe=ct(Qe)))},ot));return(Qe&&typeof Qe.then=="function"?be.resolve(Qe).then(function(ft){return Ye.active?ft:dr(new Me.PrematureCommit("Transaction committed too early. See http://bit.ly/2kdckMn"))}):ot.then(function(){return Qe})).then(function(ft){return nt&&Ye._resolve(),Ye._completion.then(function(){return ft})}).catch(function(ft){return Ye._reject(ft),dr(ft)})})}).bind(null,this,V,re,Te,M);return Te?Te._promise(V,We,"lock"):xt.trans?Nr(xt.transless,function(){return pe._whenReady(We)}):this._whenReady(We)},hr.prototype.table=function(v){if(g(this._allTables,v))return this._allTables[v];throw new Me.InvalidTable("Table ".concat(v," does not exist"))};var Xr=hr;function hr(v,P){var M,V,re,pe,Te,Ne=this,We=(this._middlewares={},this.verno=0,hr.dependencies),We=(this._options=P=n({addons:hr.addons,autoOpen:!0,indexedDB:We.indexedDB,IDBKeyRange:We.IDBKeyRange,cache:"cloned",maxConnections:1e3},P),this._deps={indexedDB:P.indexedDB,IDBKeyRange:P.IDBKeyRange},P.addons),at=(this._dbSchema={},this._versions=[],this._storeNames=[],this._allTables={},this.idbdb=null,this._novip=this,{dbOpenError:null,isBeingOpened:!1,onReadyBeingFired:null,openComplete:!1,dbReadyResolve:Ze,dbReadyPromise:null,cancelOpen:Ze,openCanceller:null,autoSchema:!0,PR1398_maxLoop:3,autoOpen:P.autoOpen}),Je=(at.dbReadyPromise=new be(function(Ge){at.dbReadyResolve=Ge}),at.openCanceller=new be(function(Ge,He){at.cancelOpen=He}),this._state=at,this.name=v,this.on=gn(this,"populate","blocked","versionchange","close",{ready:[gt,Ze]}),this.once=function(Ge,He){var nt=function(){for(var Xe=[],Ye=0;Ye<arguments.length;Ye++)Xe[Ye]=arguments[Ye];Ne.on(Ge).unsubscribe(nt),He.apply(Ne,Xe)};return Ne.on(Ge,nt)},this.on.ready.subscribe=x(this.on.ready.subscribe,function(Ge){return function(He,nt){hr.vip(function(){var Xe,Ye=Ne._state;Ye.openComplete?(Ye.dbOpenError||be.resolve().then(He),nt&&Ge(He)):Ye.onReadyBeingFired?(Ye.onReadyBeingFired.push(He),nt&&Ge(He)):(Ge(He),Xe=Ne,nt||Ge(function Qe(){Xe.on.ready.unsubscribe(He),Xe.on.ready.unsubscribe(Qe)}))})}}),this.Collection=(M=this,Bn(vn.prototype,function(Qe,Ye){this.db=M;var nt=ss,Xe=null;if(Ye)try{nt=Ye()}catch(ot){Xe=ot}var Ye=Qe._ctx,Qe=Ye.table,lt=Qe.hook.reading.fire;this._ctx={table:Qe,index:Ye.index,isPrimKey:!Ye.index||Qe.schema.primKey.keyPath&&Ye.index===Qe.schema.primKey.name,range:nt,keysOnly:!1,dir:"next",unique:"",algorithm:null,filter:null,replayFilter:null,justLimit:!0,isMatch:null,offset:0,limit:1/0,error:Xe,or:Ye.or,valueMapper:lt!==ut?lt:null}})),this.Table=(V=this,Bn(ls.prototype,function(Ge,He,nt){this.db=V,this._tx=nt,this.name=Ge,this.schema=He,this.hook=V._allTables[Ge]?V._allTables[Ge].hook:gn(null,{creating:[$e,Ze],reading:[st,ut],updating:[qe,Ze],deleting:[je,Ze]})})),this.Transaction=(re=this,Bn(qs.prototype,function(Ge,He,nt,Xe,Ye){var Qe=this;Ge!=="readonly"&&He.forEach(function(lt){lt=(lt=nt[lt])==null?void 0:lt.yProps,lt&&(He=He.concat(lt.map(function(ot){return ot.updatesTable})))}),this.db=re,this.mode=Ge,this.storeNames=He,this.schema=nt,this.chromeTransactionDurability=Xe,this.idbtrans=null,this.on=gn(this,"complete","error","abort"),this.parent=Ye||null,this.active=!0,this._reculock=0,this._blockedFuncs=[],this._resolve=null,this._reject=null,this._waitingFor=null,this._waitingQueue=null,this._spinCount=0,this._completion=new be(function(lt,ot){Qe._resolve=lt,Qe._reject=ot}),this._completion.then(function(){Qe.active=!1,Qe.on.complete.fire()},function(lt){var ot=Qe.active;return Qe.active=!1,Qe.on.error.fire(lt),Qe.parent?Qe.parent._reject(lt):ot&&Qe.idbtrans&&Qe.idbtrans.abort(),dr(lt)})})),this.Version=(pe=this,Bn(Ws.prototype,function(Ge){this.db=pe,this._cfg={version:Ge,storesSource:null,dbschema:{},tables:{},contentUpgrade:null}})),this.WhereClause=(Te=this,Bn(Fi.prototype,function(Ge,He,nt){if(this.db=Te,this._ctx={table:Ge,index:He===":id"?null:He,or:nt},this._cmp=this._ascending=zt,this._descending=function(Xe,Ye){return zt(Ye,Xe)},this._max=function(Xe,Ye){return 0<zt(Xe,Ye)?Xe:Ye},this._min=function(Xe,Ye){return zt(Xe,Ye)<0?Xe:Ye},this._IDBKeyRange=Te._deps.IDBKeyRange,!this._IDBKeyRange)throw new Me.MissingAPI})),this.on("versionchange",function(Ge){0<Ge.newVersion?console.warn("Another connection wants to upgrade database '".concat(Ne.name,"'. Closing db now to resume the upgrade.")):console.warn("Another connection wants to delete database '".concat(Ne.name,"'. Closing db now to resume the delete request.")),Ne.close({disableAutoOpen:!1})}),this.on("blocked",function(Ge){!Ge.newVersion||Ge.newVersion<Ge.oldVersion?console.warn("Dexie.delete('".concat(Ne.name,"') was blocked")):console.warn("Upgrade '".concat(Ne.name,"' blocked by other connection holding version ").concat(Ge.oldVersion/10))}),this._maxKey=Qn(P.IDBKeyRange),this._createTransaction=function(Ge,He,nt,Xe){return new Ne.Transaction(Ge,He,nt,Ne._options.chromeTransactionDurability,Xe)},this._fireOnBlocked=function(Ge){Ne.on("blocked").fire(Ge),ti.toArray().filter(function(He){return He.name===Ne.name&&He!==Ne&&!He._state.vcFired}).map(function(He){return He.on("versionchange").fire(Ge)})},this.use(sr),this.use(vs),this.use(ms),this.use(wt),this.use(or),new Proxy(this,{get:function(Ge,He,nt){var Xe;return He==="_vip"||(He==="table"?function(Ye){return ni(Ne.table(Ye),Je)}:(Xe=Reflect.get(Ge,He,nt))instanceof ls?ni(Xe,Je):He==="tables"?Xe.map(function(Ye){return ni(Ye,Je)}):He==="_createTransaction"?function(){return ni(Xe.apply(this,arguments),Je)}:Xe)}}));this.vip=Je,We.forEach(function(Ge){return Ge(Ne)})}var ii,In=typeof Symbol<"u"&&"observable"in Symbol?Symbol.observable:"@@observable",Ss=(_i.prototype.subscribe=function(v,P,M){return this._subscribe(v&&typeof v!="function"?v:{next:v,error:P,complete:M})},_i.prototype[In]=function(){return this},_i);function _i(v){this._subscribe=v}try{ii={indexedDB:c.indexedDB||c.mozIndexedDB||c.webkitIndexedDB||c.msIndexedDB,IDBKeyRange:c.IDBKeyRange||c.webkitIDBKeyRange}}catch{ii={indexedDB:null,IDBKeyRange:null}}function Qi(v){var P,M=!1,V=new Ss(function(re){var pe=he(v),Te,Ne=!1,We={},at={},Je={get closed(){return Ne},unsubscribe:function(){Ne||(Ne=!0,Te&&Te.abort(),Ge&&Yr.storagemutated.unsubscribe(Xe))}},Ge=(re.start&&re.start(Je),!1),He=function(){return fi(Ye)};function nt(){return l(at,We)}var Xe=function(Qe){i(We,Qe),nt()&&He()},Ye=function(){var Qe,lt,ot;!Ne&&ii.indexedDB&&(We={},Qe={},Te&&Te.abort(),Te=new AbortController,ot=(ft=>{var bt=Vt();try{pe&&tn();var Et=Vr(v,ft);return Et=pe?Et.finally(Rr):Et}finally{bt&&Jt()}})(lt={subscr:Qe,signal:Te.signal,requery:He,querier:v,trans:null}),Ge||(Yr.storagemutated.subscribe(Xe),Ge=!0),Promise.resolve(ot).then(function(ft){M=!0,P=ft,Ne||lt.signal.aborted||(nt()||(at=Qe,nt())?He():(We={},fi(function(){return!Ne&&re.next&&re.next(ft)})))},function(ft){M=!1,["DatabaseClosedError","AbortError"].includes(ft==null?void 0:ft.name)||Ne||fi(function(){Ne||re.error&&re.error(ft)})}))};return setTimeout(He,0),Je});return V.hasValue=function(){return M},V.getValue=function(){return P},V}var Pn=Xr;function wi(v){var P=on;try{on=!0,Yr.storagemutated.fire(v),Pe(v,!0)}finally{on=P}}b(Pn,n(n({},ae),{delete:function(v){return new Pn(v,{addons:[]}).delete()},exists:function(v){return new Pn(v,{addons:[]}).open().then(function(P){return P.close(),!0}).catch("NoSuchDatabaseError",function(){return!1})},getDatabaseNames:function(v){try{return P=Pn.dependencies,M=P.indexedDB,P=P.IDBKeyRange,(Ei(M)?Promise.resolve(M.databases()).then(function(V){return V.map(function(re){return re.name}).filter(function(re){return re!==Wr})}):Wi(M,P).toCollection().primaryKeys()).then(v)}catch{return dr(new Me.MissingAPI)}var P,M},defineClass:function(){return function(v){p(this,v)}},ignoreTransaction:function(v){return xt.trans?Nr(xt.transless||pt,v):v()},vip:Gi,async:function(v){return function(){try{var P=ct(v.apply(this,arguments));return P&&typeof P.then=="function"?P:be.resolve(P)}catch(M){return dr(M)}}},spawn:function(v,P,M){try{var V=ct(v.apply(M,P||[]));return V&&typeof V.then=="function"?V:be.resolve(V)}catch(re){return dr(re)}},currentTransaction:{get:function(){return xt.trans||null}},waitFor:function(v,P){return v=be.resolve(typeof v=="function"?Pn.ignoreTransaction(v):v).timeout(P||6e4),xt.trans?xt.trans.waitFor(v):v},Promise:be,debug:{get:function(){return ht},set:function(v){xe(v)}},derive:A,extend:p,props:b,override:x,Events:gn,on:Yr,liveQuery:Qi,extendObservabilitySet:i,getByKeyPath:R,setByKeyPath:I,delByKeyPath:function(v,P){typeof P=="string"?I(v,P,void 0):"length"in P&&[].map.call(P,function(M){I(v,M,void 0)})},shallowClone:D,deepClone:ne,getObjectDiff:Ot,cmp:zt,asap:j,minKey:-1/0,addons:[],connections:{get:ti.toArray},errnames:Ee,dependencies:ii,cache:d,semVer:"4.4.5",version:"4.4.5".split(".").map(function(v){return parseInt(v)}).reduce(function(v,P,M){return v+P/Math.pow(10,2*M)})})),Pn.maxKey=Qn(Pn.dependencies.IDBKeyRange),typeof dispatchEvent<"u"&&typeof addEventListener<"u"&&(Yr(Mn,function(v){on||(v=new CustomEvent(qi,{detail:v}),on=!0,dispatchEvent(v),on=!1)}),addEventListener(qi,function(v){v=v.detail,on||wi(v)}));var On,on=!1,Zi=function(){};return typeof BroadcastChannel<"u"&&((Zi=function(){(On=new BroadcastChannel(qi)).onmessage=function(v){return v.data&&wi(v.data)}})(),typeof On.unref=="function"&&On.unref(),Yr(Mn,function(v){on||On.postMessage(v)})),typeof addEventListener<"u"&&(addEventListener("pagehide",function(v){if(!Xr.disableBfCache&&v.persisted){ht&&console.debug("Dexie: handling persisted pagehide"),On!=null&&On.close();for(var P=0,M=ti.toArray();P<M.length;P++)M[P].close({disableAutoOpen:!1})}}),addEventListener("pageshow",function(v){!Xr.disableBfCache&&v.persisted&&(ht&&console.debug("Dexie: handling persisted pageshow"),Zi(),wi({all:new Tr(-1/0,[[]])}))})),be.rejectionMapper=function(v,P){return!v||v instanceof L||v instanceof TypeError||v instanceof SyntaxError||!v.name||!Ve[v.name]?v:(P=new Ve[v.name](P||v.message,v),"stack"in v&&O(P,"stack",{get:function(){return this.inner.stack}}),P)},xe(ht),n(Xr,Object.freeze({__proto__:null,DEFAULT_MAX_CONNECTIONS:1e3,Dexie:Xr,Entity:Jn,PropModification:Pr,RangeSet:Tr,add:function(v){return new Pr({add:v})},cmp:zt,default:Xr,liveQuery:Qi,mergeRanges:sn,rangesOverlap:Hi,remove:function(v){return new Pr({remove:v})},replacePrefix:function(v,P){return new Pr({replacePrefix:[v,P]})}}),{default:Xr}),Xr})})(Ry);var eE=Ry.exports,Cf=ZT(eE);const jy=Symbol.for("Dexie"),Al=globalThis[jy]||(globalThis[jy]=Cf);if(Cf.semVer!==Al.semVer)throw new Error(`Two different versions of Dexie loaded in the same app: ${Cf.semVer} and ${Al.semVer}`);const{liveQuery:dN,mergeRanges:hN,rangesOverlap:yN,RangeSet:mN,cmp:gN,Entity:bN,PropModification:vN,replacePrefix:SN,add:TN,remove:EN,DexieYProvider:xN}=Al,Eo="rtc-agent-";class tE extends Al{constructor(r){if(!r.startsWith(Eo))throw new Error(`[RTCAgentDatabase] databaseName must start with "${Eo}", got "${r}"`);super(r);Ht(this,"sessions");Ht(this,"turns");Ht(this,"messages");Ht(this,"rtcs");Ht(this,"offsets");Ht(this,"fileSystemEntries");this.version(1).stores({sessions:"id, &client_id, sync_status, owner_ref_id, status",turns:"id, &client_id, sync_status, session_id, status",messages:"id, &client_id, sync_status, session_id, turn_id, global_offset",rtcs:"id, &client_id, sync_status, session_id, turn_id, status",offsets:"channel"}),this.version(2).stores({sessions:"client_id, server_id, sync_status, owner_ref_id, status",turns:"client_id, server_id, sync_status, session_client_id, status",messages:"client_id, server_id, sync_status, session_client_id, turn_id, global_offset",rtcs:"client_id, server_id, sync_status, session_client_id, turn_id, status",offsets:"channel"}).upgrade(async n=>{const s=n.table("sessions"),c=await s.toArray();await s.clear();const a=new Map;for(const f of c){const p=f,h=p.id,g=p.client_id||h||crypto.randomUUID();h&&a.set(h,g);const b={...p};b.client_id=g,b.server_id=h,delete b.id,await s.add(b)}for(const f of["turns","messages","rtcs"]){const p=n.table(f),h=await p.toArray();await p.clear();for(const y of h){const g=y,b=g.id,S=g.client_id,O=g.session_id,A={...g};if(A.client_id=S||b||crypto.randomUUID(),A.server_id=b,delete A.id,O){const _=a.get(O);A.session_client_id=_||O}else A.session_client_id="";delete A.session_id,await p.add(A)}}}),this.version(3).stores({sessions:"client_id, server_id, sync_status, owner_ref_id, status, updated_at",turns:"client_id, server_id, sync_status, session_client_id, status",messages:"client_id, server_id, sync_status, session_client_id, turn_id, global_offset",rtcs:"client_id, server_id, sync_status, session_client_id, turn_id, status",offsets:"channel"}),this.version(4).stores({sessions:"client_id, server_id, sync_status, owner_ref_id, status, updated_at",turns:"client_id, server_id, sync_status, session_client_id, status",messages:"client_id, server_id, sync_status, session_client_id, turn_id, global_offset, created_at",rtcs:"client_id, server_id, sync_status, session_client_id, turn_id, status",offsets:"channel"}),this.version(5).stores({sessions:"client_id, server_id, sync_status, owner_ref_id, status, updated_at",turns:"client_id, server_id, sync_status, session_client_id, status",messages:"client_id, server_id, sync_status, session_client_id, turn_id, global_offset, created_at",rtcs:"client_id, server_id, sync_status, session_client_id, turn_id, status, offset",offsets:"channel"}),this.version(6).stores({sessions:"client_id, server_id, sync_status, owner_ref_id, status, updated_at",turns:"client_id, server_id, sync_status, session_client_id, status",messages:"client_id, server_id, sync_status, session_client_id, turn_id, global_offset, created_at",rtcs:"client_id, server_id, sync_status, session_client_id, turn_id, status, offset",offsets:"channel",fileSystemEntries:"path, type, metadata.group, *metadata.tags"})}}let es=null,If=null;function yr(t){if(t===void 0){if(es)return es;throw new Error(`[RTCAgentDatabase] getDatabase() called without a name before any database was initialized. Pass a databaseName starting with "${Eo}".`)}if(!t.startsWith(Eo))throw new Error(`[RTCAgentDatabase] databaseName must start with "${Eo}", got "${t}"`);const e=t;return(!es||If!==e)&&(es&&es.close(),es=new tE(e),If=e),es}async function rE(){es&&(es.close(),es=null,If=null)}async function nE(){const t=yr(),e=[t.sessions,t.turns,t.messages,t.rtcs,t.offsets,t.fileSystemEntries];await t.transaction("rw",e,async()=>{await t.sessions.clear(),await t.turns.clear(),await t.messages.clear(),await t.rtcs.clear(),await t.offsets.clear(),await t.fileSystemEntries.clear()})}class iE{async getPosition(e){const n=await yr().offsets.get(e);if(n)return{offset:n.offset,epoch:n.epoch}}async updatePosition(e,r,n){const s=yr(),c={channel:e,offset:r,epoch:n,updatedAt:Date.now()};await s.offsets.put(c)}async clearPosition(e){await yr().offsets.delete(e)}async clearAll(){await yr().offsets.clear()}async reset(){await this.clearAll()}}let Of=null;function My(){return Of||(Of=new iE),Of}class sE{constructor(){Ht(this,"entityListeners",new Map);Ht(this,"wildcardListeners",new Set)}subscribe(e,r){if(typeof e=="function")return this.wildcardListeners.add(e),()=>{this.wildcardListeners.delete(e)};const n=e,s=r;let c=this.entityListeners.get(n);return c||(c=new Set,this.entityListeners.set(n,c)),c.add(s),()=>{c.delete(s),c.size===0&&this.entityListeners.delete(n)}}publish(e){for(const n of this.wildcardListeners)try{n(e)}catch(s){console.error("[UIUpdateBus] listener error:",s)}const r=this.entityListeners.get(e.entity);if(r)for(const n of r)try{n(e)}catch(s){console.error("[UIUpdateBus] listener error:",s)}}clear(){this.entityListeners.clear(),this.wildcardListeners.clear()}}let Nf=null;function Ly(){return Nf||(Nf=new sE),Nf}function aE(t=new Date){const e=t.getFullYear(),r=String(t.getMonth()+1).padStart(2,"0"),n=String(t.getDate()).padStart(2,"0"),s=String(t.getHours()).padStart(2,"0"),c=String(t.getMinutes()).padStart(2,"0"),a=String(t.getSeconds()).padStart(2,"0"),f=String(t.getMilliseconds()).padStart(3,"0"),p=-t.getTimezoneOffset(),h=String(Math.floor(Math.abs(p)/60)).padStart(2,"0"),y=String(Math.abs(p)%60).padStart(2,"0"),g=p>=0?"+":"-";return`${e}-${r}-${n}T${s}:${c}:${a}.${f}${g}${h}:${y}`}function si(){return aE(new Date)}const Fy=["Date","RegExp","String","Number"],qy=Object.getOwnPropertyNames(globalThis.Temporal||{});function $y(t,e,r={cyclesFix:!0},n=[]){var f,p;let s=[];const c=Array.isArray(t);for(const h in t){const y=t[h],g=c?+h:h;if(!(h in e)){s.push({type:"REMOVE",path:[g],oldValue:y});continue}const b=e[h],S=typeof y=="object"&&typeof b=="object"&&Array.isArray(y)===Array.isArray(b),O=S&&y?(p=(f=Object.getPrototypeOf(y))==null?void 0:f.constructor)==null?void 0:p.name:void 0;if(y&&b&&S&&!Fy.includes(O)&&!qy.includes(O)&&(!r.cyclesFix||!n.includes(y))){r.cyclesFix&&n.push(y);const A=$y(y,b,r,n);r.cyclesFix&&n.pop();for(const _ of A)_.path.unshift(g),s.push(_)}else Object.is(y,b)||qy.includes(O)&&String(y)===String(b)||Fy.includes(O)&&(isNaN(y)?y+""==b+"":+y==+b)||s.push({path:[g],type:"CHANGE",value:b,oldValue:y})}const a=Array.isArray(e);for(const h in e)h in t||s.push({type:"CREATE",path:[a?+h:h],value:e[h]});return s}function oE(t){return t.join(".")}function Cl(t,e,r,n,s){const c=Ly();if(!n){for(const[f,p]of Object.entries(s))c.publish({entity:t,action:e,entityId:r,field:f,oldValue:void 0,newValue:p});return}const a=$y(n,s);for(const f of a)c.publish({entity:t,action:e,entityId:r,field:oE(f.path),oldValue:f.oldValue,newValue:f.value})}class lE{async upsertSession(e,r="synced",n){const s=yr(),c=si();let a;e.client_id&&(a=await s.sessions.where("client_id").equals(e.client_id).first()),console.log("[EntityRepository.upsertSession]",a?"UPDATE":"CREATE","client_id:",e.client_id,"title:",e.title);let f,p;if(a){const h={...a},y={...a,...e,sync_status:r,server_id:e.server_id||a.server_id};await s.sessions.put(y),f={before:h,after:y},p="updated",console.log("[EntityRepository.upsertSession] After update - title:",y.title)}else{const h={client_id:e.client_id||"",server_id:e.server_id,owner_kind:e.owner_kind||"",owner_ref_id:e.owner_ref_id||"",title:e.title,status:e.status||"active",created_at:e.created_at||c,updated_at:e.updated_at||c,sync_status:r,pending_turn_count:0,running_turn_count:0,agent_prompt:e.agent_prompt||""};await s.sessions.put(h),f={before:void 0,after:h},p="created",console.log("[EntityRepository.upsertSession] After create - title:",h.title)}return n!=null&&n.silent||Cl("session",p,f.after.client_id,f.before,f.after),f}async getClientSession(e){return yr().sessions.get(e)}async getSessionByClientId(e){return this.getClientSession(e)}async getSessionByServerId(e){return yr().sessions.where("server_id").equals(e).first()}async getMessageByServerId(e){return yr().messages.where("server_id").equals(e).first()}async listSessions(e,r=50){const c=await yr().sessions.orderBy("updated_at").reverse().toArray();console.log(`[EntityRepository.listSessions] total=${c.length}, with deleted_at=${c.filter(f=>f.deleted_at).length}`);const a=c.filter(f=>!f.deleted_at);if(console.log(`[EntityRepository.listSessions] after filter=${a.length}`),e){const f=a.findIndex(p=>p.client_id===e);return f===-1?a.slice(0,r):a.slice(f+1,f+1+r)}return a.slice(0,r)}async softDeleteSession(e){if(!await this.getClientSession(e))throw new Error(`[EntityRepository] softDeleteSession: session not found: ${e}`);const n=si();console.log(`[EntityRepository.softDeleteSession] setting deleted_at=${n} for ${e}`);const s=await this.upsertSession({client_id:e,deleted_at:n,updated_at:n},"pending");return console.log(`[EntityRepository.softDeleteSession] after upsert, deleted_at=${s.after.deleted_at}`),s}async upsertTurn(e,r="synced",n){const s=yr(),c=si();let a;e.client_id&&(a=await s.turns.where("client_id").equals(e.client_id).first());let f,p;if(a){const h={...a},y={...a,...e,sync_status:r,server_id:e.server_id||a.server_id};await s.turns.put(y),f={before:h,after:y},p="updated"}else{const h={client_id:e.client_id||"",server_id:e.server_id,session_client_id:e.session_client_id||"",status:e.status||"pending",created_at:e.created_at||c,sync_status:r};await s.turns.put(h),f={before:void 0,after:h},p="created"}return n!=null&&n.silent||Cl("turn",p,f.after.client_id,f.before,f.after),f}async getClientTurn(e){return yr().turns.get(e)}async countActiveTurns(e){const r=yr(),n=r.turns.where("session_client_id").equals(e),[s,c]=await Promise.all([n.filter(a=>a.status==="pending").count(),r.turns.where("session_client_id").equals(e).filter(a=>a.status==="running").count()]);return{pending:s,running:c}}async upsertMessage(e,r="synced",n){const s=yr(),c=si();let a;e.client_id&&(a=await s.messages.where("client_id").equals(e.client_id).first());let f,p;if(a){const h={...a},y={...a,...e,sync_status:r,server_id:e.server_id||a.server_id};await s.messages.put(y),f={before:h,after:y},p="updated"}else{const h={client_id:e.client_id||"",server_id:e.server_id,session_client_id:e.session_client_id||"",turn_id:e.turn_id,global_offset:e.global_offset||0,turn_offset:e.turn_offset,role:e.role||"user",content:e.content,streaming_status:e.streaming_status||"pending",creator_kind:e.creator_kind||"user",creator_ref_id:e.creator_ref_id||"",created_at:e.created_at||c,updated_at:e.updated_at||c,sync_status:r,parent_client_id:e.parent_client_id};await s.messages.put(h),f={before:void 0,after:h},p="created"}return n!=null&&n.silent||Cl("message",p,f.after.client_id,f.before,f.after),f}async getClientMessage(e){return yr().messages.get(e)}async listMessagesBySession(e,r,n=50,s="backward"){const f=await yr().messages.where("session_client_id").equals(e).sortBy("created_at");if(s==="backward"){let p=f;return r!==void 0&&r>0&&(p=f.filter(y=>y.global_offset!==void 0&&y.global_offset<r)),p.slice(-n).sort((y,g)=>y.created_at.localeCompare(g.created_at))}if(r!==void 0&&r>0){const p=f.findIndex(h=>h.global_offset!==void 0&&h.global_offset>r);return p===-1?[]:f.slice(p,p+n)}return f.slice(0,n)}async upsertRtc(e,r="synced",n){const s=yr(),c=si();let a;e.client_id&&(a=await s.rtcs.where("client_id").equals(e.client_id).first());let f,p;if(a){const h={...a},y={...a,...e,sync_status:r,server_id:e.server_id||a.server_id};await s.rtcs.put(y),f={before:h,after:y},p="updated"}else{const h={client_id:e.client_id||"",server_id:e.server_id,session_client_id:e.session_client_id||"",turn_id:e.turn_id||"",offset:e.offset||0,tool_name:e.tool_name||"",parameters:e.parameters,status:e.status||"pending",result:e.result,error_message:e.error_message,created_at:e.created_at||c,updated_at:e.updated_at||c,sync_status:r};await s.rtcs.put(h),f={before:void 0,after:h},p="created"}return n!=null&&n.silent||Cl("rtc",p,f.after.client_id,f.before,f.after),f}async getClientRtc(e){return yr().rtcs.get(e)}async getNextRtcToProcess(e){const r=yr(),n=await r.rtcs.where("sync_status").equals("failed").sortBy("offset"),s=e?n.filter(a=>a.session_client_id===e):n;if(s.length>0)return s[0];const c=await r.rtcs.filter(a=>a.status==="pending").sortBy("offset");return e?c.find(a=>a.session_client_id===e):c[0]}async listRtcBySession(e,r,n=50){const a=(await yr().rtcs.where("session_client_id").equals(e).toArray()).sort((p,h)=>p.offset-h.offset),f=r||0;return a.slice(f,f+n)}async applyUpdate(e){var r;for(let n=0;n<e.items.length;n++){const s=e.items[n],c=(r=e.data_list)==null?void 0:r[n];c&&await this.applyUpdateItem(s,c)}}async _resolveSessionClientId(e,r,n){const s=await this.getSessionByServerId(e);return s?s.client_id:(console.warn(`[EntityRepository] ${r} ${n} references unknown session ${e}`),e)}async applyUpdateItem(e,r){switch(e.entity){case"session":{const n=r,s={...n,server_id:n.id,client_id:n.client_id||n.id};delete s.id,await this.upsertSession(s,"synced");break}case"turn":{const n=r,s={...n,server_id:n.id,client_id:n.client_id||n.id};delete s.id,n.session_id&&(s.session_client_id=await this._resolveSessionClientId(n.session_id,"Turn",n.client_id||n.id)),delete s.session_id,await this.upsertTurn(s,"synced");const c=s.session_client_id;if(c){const{pending:a,running:f}=await this.countActiveTurns(c),p=await this.getClientSession(c);p&&await this.upsertSession({client_id:c,pending_turn_count:a,running_turn_count:f},p.sync_status)}break}case"message":{const n=r,s={...n,server_id:n.id,client_id:n.client_id||n.id};if(delete s.id,n.session_id&&(s.session_client_id=await this._resolveSessionClientId(n.session_id,"Message",n.client_id||n.id)),delete s.session_id,n.parent_message_id){const c=await this.getMessageByServerId(n.parent_message_id);c?s.parent_client_id=c.client_id:console.warn(`[EntityRepository] Message ${n.client_id||n.id} references unknown parent ${n.parent_message_id}`)}delete s.parent_message_id,await this.upsertMessage(s,"synced");break}case"rtc":{const n=r,s={...n,server_id:n.id,client_id:n.client_id||n.id};if(delete s.id,n.session_id){const c=await this.getSessionByServerId(n.session_id);c?s.session_client_id=c.client_id:(console.warn(`[EntityRepository] Rtc ${n.client_id||n.id} references unknown session ${n.session_id}`),s.session_client_id=n.session_id)}delete s.session_id,await this.upsertRtc(s,"pending");break}}}}let kf=null;function cE(){return kf||(kf=new lE),kf}class xo extends Error{constructor(e,r){super(r),this.code=e,this.name="PathError"}}function zs(t){if(!t||typeof t!="string")throw new xo("EINVAL","Path must be a non-empty string");let e=t.startsWith("/")?t:"/"+t;const r=e.split("/").filter(n=>n&&n!==".");for(const n of r)if(n==="..")throw new xo("EINVAL","Path traversal (..) is not allowed");return e="/"+r.join("/"),e==="/"?"/":e.replace(/\/$/,"")}function uE(t){const e=zs(t),r=e.lastIndexOf("/");return e.substring(r+1)}function Uy(t,e){const r=t.replace(/[.+^${}()|[\]\\/+]/g,"\\$&").replace(/\*/g,"[^\\/]*").replace(/\?/g,"[^\\/]");return new RegExp(`^${r}$`).test(e)}class fE{async read(e,r,n){const s=zs(e),a=await yr().fileSystemEntries.get(s);if(!a)throw new xo("ENOENT",`File not found: ${s}`);let f=a.content;if(r!==void 0||n!==void 0){const p=r||0,h=n!==void 0?p+n:void 0;f=f.substring(p,h)}return f}async write(e,r,n="overwrite",s){const c=zs(e),a=yr(),f=this.inferFileType(c),p=await a.fileSystemEntries.get(c);if(n==="create-new"&&p)return p.content.length;let h=r,y;if(p&&n==="append")h=p.content+r,y={...p.metadata,...s,updatedAt:new Date};else{const b=new Date;if(y={name:uE(c),description:"",createdAt:(p==null?void 0:p.metadata.createdAt)||b,updatedAt:b,...s},f==="function"){const S=this.extractGroupFromPath(c);S&&(y.group=S)}}const g={path:c,type:f,content:h,metadata:y};return await a.fileSystemEntries.put(g),h.length}async ls(e="/"){const r=zs(e),n=yr(),s=new Set;if(r==="/"){const c=await n.fileSystemEntries.toArray();for(const a of c){const f=a.path.split("/").filter(Boolean);f.length>0&&s.add(f[0])}}else{const c=r+"/",a=await n.fileSystemEntries.filter(f=>f.path.startsWith(c)).toArray();for(const f of a){const h=f.path.substring(c.length).split("/");h.length>0&&s.add(h[0])}}return Array.from(s).sort()}async find(e,r="/"){const n=zs(r),s=yr();let c;if(n==="/")c=await s.fileSystemEntries.toArray();else{const f=n+"/";c=await s.fileSystemEntries.filter(p=>p.path.startsWith(f)).toArray()}const a=[];for(const f of c){const p=n==="/"?f.path.substring(1):f.path.substring(n.length+1);(Uy(e,p)||Uy(e,f.path))&&a.push(f.path)}return a.sort()}async grep(e,r="/",n=!1,s=100){const c=zs(r),a=yr();let f;try{const y=n?"":"i";f=new RegExp(e,y)}catch{throw new SyntaxError(`Invalid regex pattern: ${e}`)}let p;if(c==="/")p=await a.fileSystemEntries.toArray();else{const y=c+"/";p=await a.fileSystemEntries.filter(g=>g.path.startsWith(y)).toArray()}const h=[];for(const y of p){const g=y.content.split(`
14
14
  `);for(let b=0;b<g.length;b++){const S=g[b];if(f.test(S)&&(h.push({file:y.path,line:S,lineNumber:b+1}),h.length>=s))return h}}return h}async queryByType(e){return yr().fileSystemEntries.where("type").equals(e).toArray()}async exists(e){const r=zs(e);return await yr().fileSystemEntries.get(r)!==void 0}async remove(e){const r=zs(e),n=yr();if(!await this.exists(r))throw new xo("ENOENT",`File not found: ${r}`);await n.fileSystemEntries.delete(r)}inferFileType(e){return e.startsWith("/functions/")?"function":e.startsWith("/scenarios/")?"scenario":e.startsWith("/scripts/")?"script":(e.endsWith("/INDEX.md")||e==="/AGENT.md","index")}extractGroupFromPath(e){const r=e.split("/").filter(Boolean);if(r.length>=3&&r[0]==="functions")return r[1]}}const Lr=new fE;var Df={},Po={},ai={},Bf={},_o={},Il={},Ol={},_e={},Nl={},Vy;function Rf(){if(Vy)return Nl;Vy=1,Object.defineProperty(Nl,"__esModule",{value:!0}),Nl.default=t;function t(e,r){const n=Object.keys(r);for(const s of n)if(e[s]!==r[s])return!1;return!0}return Nl}var kl={},Ky;function wo(){if(Ky)return kl;Ky=1,Object.defineProperty(kl,"__esModule",{value:!0}),kl.default=e;const t=new Set;function e(n,s,c="",a=n){if(t.has(a))return;t.add(a);const{internal:f,trace:p}=r(1,2);f||console.warn(`${c}\`${n}\` has been deprecated, please migrate to \`${s}\`
@@ -1,4 +1,4 @@
1
- import { s as e } from "./index-C-FfTMfp.js";
1
+ import { s as e } from "./index-C9Ay7AV0.js";
2
2
  const s = {
3
3
  s0016a70887124d70: "Session",
4
4
  s0116da495c2a975c: "The AI wants to use a tool. Review the details below.",
@@ -1,4 +1,4 @@
1
- import { g as wl } from "./index-C-FfTMfp.js";
1
+ import { g as wl } from "./index-C9Ay7AV0.js";
2
2
  function ml(n) {
3
3
  return n instanceof Map ? n.clear = n.delete = n.set = function() {
4
4
  throw new Error("map is read-only");