@rtc-agent/component 0.1.9-rc.1 → 0.1.9-rc.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{shared-worker-DE3XeXaG.js → shared-worker-CCX0JCJL.js} +7 -7
- package/dist/{en-US-DZNGN4YL.js → en-US-wWqZWdgx.js} +1 -1
- package/dist/{index-BW-EmCDb.js → index-98oa1ZRF.js} +1 -1
- package/dist/{index-BnIf1Sm8.js → index-BFdxPQmS.js} +3709 -3688
- package/dist/index.js +1 -1
- package/dist/index.umd.js +275 -275
- package/package.json +5 -5
|
@@ -8,7 +8,7 @@ var PN=Object.defineProperty;var wN=(Xs,ws,ja)=>ws in Xs?PN(Xs,ws,{enumerable:!0
|
|
|
8
8
|
`):r=e;try{yield this._writer.write(r)}catch{this.close()}})}}const QT=[-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=QT[127&this.getByte()])>=0;)e=(e<<6)+r;return this.pos--,e>>>0}}class eE{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 tE(t){let e=0,r=0,n=0,s=0,o=0,a=t.length;for(;a>=16;)e=e+t[o+0]|0,r=r+t[o+1]|0,n=n+t[o+2]|0,s=s+t[o+3]|0,e=e+t[o+4]|0,r=r+t[o+5]|0,n=n+t[o+6]|0,s=s+t[o+7]|0,e=e+t[o+8]|0,r=r+t[o+9]|0,n=n+t[o+10]|0,s=s+t[o+11]|0,e=e+t[o+12]|0,r=r+t[o+13]|0,n=n+t[o+14]|0,s=s+t[o+15]|0,o+=16,a-=16;for(;a>=4;)e=e+t[o+0]|0,r=r+t[o+1]|0,n=n+t[o+2]|0,s=s+t[o+3]|0,o+=4,a-=4;switch(s=((s+(n<<8)|0)+(r<<16)|0)+(e<<24)|0,a){case 3:s=s+(t[o+2]<<8)|0;case 2:s=s+(t[o+1]<<16)|0;case 1:s=s+(t[o+0]<<24)|0}return s>>>0}function rE(t,e){let r=0;const n=new ZT(e),s=t.length,o=e.length,a=n.getInt();if(n.getChar()!==`
|
|
9
9
|
`)throw new Error("size integer not terminated by '\\n'");const u=new eE;for(;n.haveBytes();){const p=n.getInt();let y;switch(n.getChar()){case"@":if(y=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(y+p>s)throw new Error("copy extends past end of input");u.putArray(t,y,y+p);break;case":":if(r+=p,r>a)throw new Error("insert command gives an output larger than predicted");if(p>o)throw new Error("insert count exceeds size of delta");u.putArray(n.a,n.pos,n.pos+p),n.pos+=p;break;case";":{const h=u.toByteArray(t);if(p!==tE(h))throw new Error("bad checksum");if(r!==a)throw new Error("generated size does not match predicted size");return h}default:throw new Error("unknown delta operator")}}throw new Error("unterminated delta")}class qy{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,o,a;if(e.delta){a=!0;const u=new TextEncoder().encode(e.data),p=rE(r,u);n=JSON.parse(new TextDecoder().decode(p)),s=p,o=u.length}else a=!1,n=JSON.parse(e.data),s=new TextEncoder().encode(e.data),o=s.length;return{newData:n,newPrevValue:s,isDelta:a,wireBytes:o,fullBytes:s.length}}}const nE={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 Cs extends Error{constructor(e){super(e),this.name=this.constructor.name}}class Bl extends Ly{constructor(e,r){super(),this._reconnectTimeout=null,this._refreshTimeout=null,this._serverPingTimeout=null,this.state=Rr.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 qy,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({},nE),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 GT(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 Mf(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 Mf(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 Mf(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 zT(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!==cn.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 Br(this,void 0,void 0,function*(){switch(this.state){case Rr.Disconnected:throw{code:ur.clientDisconnected,message:"client disconnected"};case Rr.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(La.disconnectCalled,"disconnect called",!1)}setToken(e){this._token=e}setData(e){this._data=e}setHeaders(e){this._config.headers=e}send(e){return Br(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 Br(this,void 0,void 0,function*(){const n={rpc:{method:e,data:r}};return yield this._methodCall(),{data:(yield this._callPromise(n,o=>o.rpc)).data}})}publish(e,r){return Br(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 Br(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 Br(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 Br(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),o=[];if(s.publications)for(let a=0;a<s.publications.length;a++)o.push(this._getPublicationContext(e,s.publications[a]));return{publications:o,epoch:s.epoch||"",offset:s.offset||0}})}presence(e){return Br(this,void 0,void 0,function*(){const r={presence:{channel:e}};yield this._methodCall();const s=(yield this._callPromise(r,o=>o.presence)).presence;for(const o in s)if(Object.prototype.hasOwnProperty.call(s,o)){const a=s[o],u=a.conn_info,p=a.chan_info;u&&(a.connInfo=u),p&&(a.chanInfo=p)}return{clients:s}})}presenceStats(e){return Br(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&&UT("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 qy,this._formatOverride(),(this._config.debug===!0||WT("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===Rr.Disconnected}_isConnecting(){return this.state===Rr.Connecting}_isConnected(){return this.state===Rr.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===Rr.Connected||this.state===Rr.Connecting)&&(this._disconnect(As.transportClosed,"transport closed",!0),this._deviceWentOffline=!0)}),e.addEventListener("online",()=>{this._debug("online event triggered"),this.state===Rr.Connecting&&(this._deviceWentOffline&&!this._transportClosed&&(this._deviceWentOffline=!1,this._transportClosed=!0),this._clearReconnectTimeout(),this._startReconnecting())}),this._networkEventsSet=!0)}_getReconnectDelay(){const e=la(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===cn.Subscribed&&r._setSubscribing(Dl.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 o=s.errback;o({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 o=null;if(this._config.readableStream!==null?o=this._config.readableStream:typeof globalThis.ReadableStream<"u"&&(o=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],P=O.transport,A=O.endpoint;if(P==="websocket"){if(this._debug("trying websocket transport"),this._transport=new Fy(A,{websocket:e}),!this._transport.supported()){this._debug("websocket transport not available"),this._advanceTransportIndex(),S++;continue}}else if(P==="webtransport"){if(this._debug("trying webtransport transport"),this._transport=new XT(A,{webtransport:globalThis.WebTransport,decoder:this._codec,encoder:this._codec}),!this._transport.supported()){this._debug("webtransport transport not available"),this._advanceTransportIndex(),S++;continue}}else if(P==="http_stream"){if(this._debug("trying http_stream transport"),this._transport=new JT(A,{fetch:s,readableStream:o,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(P==="sse"){if(this._debug("trying sse transport"),this._transport=new YT(A,{eventsource:n,fetch:s,emulationEndpoint:this._config.emulationEndpoint}),!this._transport.supported()){this._debug("sse transport not available"),this._advanceTransportIndex(),S++;continue}}else if(P==="sockjs"){if(this._debug("trying sockjs"),this._transport=new HT(A,{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 "+P);break}}else{if($T(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 Fy(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,u=this._transport,p=this._nextTransportId();a._debug("id of transport",p);let y=!1;const h=[];if(this._transport.emulation()){const S=a._sendConnect(!0);h.push(S)}this._setNetworkEvents();const g=this._codec.encodeCommands(h);this._transportClosed=!1;let b;b=setTimeout(function(){u.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"),u.close();return}y=!0,a._debug(u.subName(),"transport open"),!u.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(u.subName(),"transport closed"),a._transportClosed=!0,a._transportIsOpen=!1;let O="connection closed",P=!0,A=0;if(S&&"code"in S&&S.code&&(A=S.code),S&&S.reason)try{const C=JSON.parse(S.reason);O=C.reason,P=C.reconnect}catch{O=S.reason,(A>=3500&&A<4e3||A>=4500&&A<5e3)&&(P=!1)}A<3e3?(A===1009?(A=La.messageSizeLimit,O="message size limit exceeded",P=!1):(A=As.transportClosed,O="transport closed"),a._emulation&&!a._transportWasOpen&&a._advanceTransportIndex()):a._transportWasOpen=!0,a._isConnecting()&&!y&&a.emit("error",{type:"transport",error:{code:ur.transportClosed,message:"transport closed"},transport:u.name()}),a._reconnecting=!1,a._disconnect(A,O,P)},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 o=s.reply.connect;n._connectResponse(o),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(o){n._isConnecting()&&(n._data=o,n._initializeTransport())}).catch(o=>n._handleGetDataError(o)):n._initializeTransport()}}).catch(function(s){if(!n._isConnecting())return;if(s instanceof Cs){n._failUnauthorized();return}n.emit("error",{type:"connectToken",error:{code:ur.clientConnectToken,message:s!==void 0?s.toString():""}});const o=n._getReconnectDelay();n._debug("error on getting connection token, reconnect after "+o+" milliseconds",s),n._reconnecting=!1,n._reconnectTimeout=setTimeout(()=>{n._startReconnecting()},o)})}_handleGetDataError(e){if(e instanceof Cs){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===Rr.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 o={recover:!0};this._serverSubs[s].offset&&(o.offset=this._serverSubs[s].offset),this._serverSubs[s].epoch&&(o.epoch=this._serverSubs[s].epoch),r[s]=o}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(o=>{var a;const u=r(o.reply);n(u),(a=o.next)===null||a===void 0||a.call(o)},o=>{var a;s(o.error),(a=o.next)===null||a===void 0||a.call(o)})})}_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(o=>{r=o});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(Rr.Connecting)&&this.emit("connecting",{code:As.connectCalled,reason:"connect called"}),this._client=null,this._startReconnecting()}_disconnect(e,r,n){if(e===La.stateInvalidated){this._token="",this._refreshRequired=!0;for(const u in this._subs)this._subs.hasOwnProperty(u)&&this._subs[u]._invalidateState();for(const u in this._serverSubs)this._serverSubs.hasOwnProperty(u)&&(this._serverSubs[u].offset=0,this._serverSubs[u].epoch="_")}if(this._isDisconnected())return;this._transportIsOpen=!1;const s=this.state;this._reconnecting=!1;const o={code:e,reason:r};let a;if(n?a=this._setState(Rr.Connecting):(a=this._setState(Rr.Disconnected),this._rejectPromises({code:ur.clientDisconnected,message:"disconnected"})),this._clearOutgoingRequests(),s===Rr.Connecting&&this._clearReconnectTimeout(),s===Rr.Connected&&this._clearConnectedState(),a&&(this._isConnecting()?this.emit("connecting",o):this.emit("disconnected",o)),this._transport){this._debug("closing existing transport");const u=this._transport;this._transport=null,u.close(),this._transportClosed=!0,this._nextTransportId()}else this._debug("no transport to close");this._scheduleReconnect()}_failUnauthorized(){this._disconnect(La.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 Cs("")))}_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(o=>{const a=o.reply.refresh;r._refreshResponse(a),o.next&&o.next()},o=>{r._refreshError(o.error),o.next&&o.next()})}).catch(function(n){if(r._isConnected()){if(n instanceof Cs){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 la(0,5e3,1e4)}_refreshResponse(e){this._refreshTimeout&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null),e.expires&&(this._client=e.client,this._refreshTimeout=setTimeout(()=>this._refresh(),Co(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,u)=>{this._call(n,!1).then(p=>{a(),p.next&&p.next()},p=>{a(),p.next&&p.next(),s._disconnect(As.unsubscribeError,"unsubscribe error",!0)})})}_getSub(e,r){if(r&&r>0){for(const s in this._subs)if(this._subs.hasOwnProperty(s)){const o=this._subs[s];if(o._id===r)return o}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===cn.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(Rr.Connected),this._refreshTimeout&&clearTimeout(this._refreshTimeout),e.expires&&(this._refreshTimeout=setTimeout(()=>this._refresh(),Co(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 o in s)s.hasOwnProperty(o)&&this._handlePublication(r,s[o])}}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(As.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 o=0;return"offset"in r&&(o=r.offset),(n.positioned||n.recoverable)&&(n.streamPosition={offset:o,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],KT(e)){const o=s.errback;if(!o){r();return}const a={code:e.error.code,message:e.error.message||"",temporary:e.error.temporary||!1};o({error:a,next:r})}else{const o=s.callback;if(!o)return;o({reply:e,next:r})}}_handleJoin(e,r,n){const s=this._getSub(e,n);if(!s){if(e&&this._isServerSub(e)){const o={channel:e,info:this._getJoinLeaveContext(r.info)};this.emit("join",o)}return}s._handleJoin(r)}_handleLeave(e,r,n){const s=this._getSub(e,n);if(!s){if(e&&this._isServerSub(e)){const o={channel:e,info:this._getJoinLeaveContext(r.info)};this.emit("leave",o)}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===wo.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 o=this._getPublicationContext(e,r);this.emit("publication",o),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],Rf(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])}}Bl.SubscriptionState=cn,Bl.State=Rr,Bl.UnauthorizedError=Cs;const Dn={SessionList:"v1.session.list",SessionGet:"v1.session.get",SessionClose:"v1.session.close",SessionOpen:"v1.session.open",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"},$y={debug:0,info:1,warn:2,error:3};let iE="debug";function ss(t){const e=r=>$y[r]>=$y[iE];return{debug(...r){e("debug")&&console.debug(`[${t}]`,...r)},info(...r){e("info")&&console.info(`[${t}]`,...r)},warn(...r){e("warn")&&console.warn(`[${t}]`,...r)},error(...r){e("error")&&console.error(`[${t}]`,...r)}}}const gr=ss("RTCAgentClient"),Po=class Po{constructor(e){Vt(this,"options");Vt(this,"centrifuge",null);Vt(this,"connectionState","disconnected");Vt(this,"listeners",new Map);Vt(this,"shouldReconnect",!0);Vt(this,"wasConnected",!1);Vt(this,"applyUpdatesQueue",null);Vt(this,"subscriptions",new Map);Vt(this,"epochCache",new Map);Vt(this,"_reconnectTimer");this.options=e}async connect(){if(gr.debug("connect() called, current state:",this.connectionState),this.connectionState==="connected"||this.connectionState==="connecting"){gr.debug("connect() early return, already",this.connectionState);return}this.shouldReconnect=!0,this.setConnectionState("connecting"),this.centrifuge=new Bl(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",()=>{gr.debug("centrifuge connected, setting state to connected"),this.wasConnected=!0,this.setConnectionState("connected"),this.subscribeChannels()}),this.centrifuge.on("disconnected",e=>{if(gr.debug("centrifuge disconnected, reason:",e==null?void 0:e.reason),(e==null?void 0:e.reason)==="invalid token"&&this.options.onTokenExpired){const r=this.centrifuge;this.centrifuge=null,r==null||r.disconnect(),this.handleInvalidToken()}(e==null?void 0:e.reason)==="message size limit exceeded"&&(gr.warn("message size limit exceeded, will retry connection after delay"),this._reconnectTimer=setTimeout(()=>{this._reconnectTimer=void 0,this.shouldReconnect&&this.connectionState==="disconnected"&&(gr.debug("attempting reconnect after message size limit error"),this.reconnect().catch(r=>{gr.error("reconnect failed:",r)}))},Po.RECONNECT_AFTER_SIZE_LIMIT_DELAY_MS)),this.setConnectionState("disconnected",e==null?void 0:e.reason)}),this.centrifuge.on("error",e=>{var r;gr.error("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"))}),gr.debug("calling centrifuge.connect() synchronously"),this.centrifuge.connect(),gr.debug("centrifuge.connect() returned, state:",this.connectionState,"(WebSocket not yet established)")}disconnect(){var e;this.shouldReconnect=!1,this.wasConnected=!1,this._reconnectTimer&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=void 0),(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(Dn.SessionList,{cursor:e,limit:r})}async getSession(e){return this.rpc(Dn.SessionGet,{session_id:e})}async closeSession(e){return this.rpc(Dn.SessionClose,{session_id:e})}async openSession(e){return this.rpc(Dn.SessionOpen,{session_id:e})}async compactSession(e){return this.rpc(Dn.SessionCompact,e)}async updateSession(e){return this.rpc(Dn.SessionUpdate,e)}async sendMessage(e){return this.rpc(Dn.MessageSend,e)}async forkSession(e){return this.rpc(Dn.SessionFork,e)}async stopTurn(e){return this.rpc(Dn.TurnStop,{session_id:e})}async listMessages(e,r,n){return this.rpc(Dn.MessageList,{session_id:e,cursor:r,limit:n})}async listTurns(e,r,n){return this.rpc(Dn.TurnList,{session_id:e,cursor:r,limit:n})}async listRtc(e,r,n){return this.rpc(Dn.RtcList,{session_id:e,cursor:r,limit:n})}async updateRtcStatus(e,r){return this.rpc(Dn.RtcUpdateStatus,{rtc_id:e,status:r})}async submitRtcResult(e,r,n,s){return this.rpc(Dn.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,o,a,u,p;const r=`topic:u=${this.options.userId}`;if(e.offset>0){const y=await((s=(n=this.options).getLastOffset)==null?void 0:s.call(n,r)),h=y==null?void 0:y.offset,g=(y==null?void 0:y.epoch)??this.epochCache.get(r)??"";if(h!==void 0&&e.offset>h+1){await this.fillOffsetGap(r,h,g,e.offset);const b=await((a=(o=this.options).getLastOffset)==null?void 0:a.call(o,r)),S=b==null?void 0:b.offset,O=b==null?void 0:b.epoch,P=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!==P)throw new Error(`[RTCAgentClient] Epoch mismatch after gap fill: expected '${P}', got '${O}'. Rejecting update ${e.offset} to prevent data corruption.`)}}if(this.options.onPublication){const y={channel:`topic:u=${this.options.userId}`,offset:e.offset,data:e};await this.options.onPublication(y)}if(e.offset>0){const y=this.epochCache.get(r)??"";await((p=(u=this.options).updateOffset)==null?void 0:p.call(u,r,e.offset,y))}}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(o){gr.error(`listener for '${e}' threw:`,o)}}setConnectionState(e,r){var s,o;if(gr.debug("setConnectionState:",e,"reason:",r,"previous:",this.connectionState),this.connectionState===e)return;this.connectionState=e;const n={state:e,reason:r};this.emit("connection",n),(o=(s=this.options).onConnectionStateChange)==null||o.call(s,n)}async handleInvalidToken(){var e;if(!this.options.onTokenExpired){gr.warn("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")):(gr.debug("token refreshed, attempting to reconnect"),this._reconnectTimer=setTimeout(()=>{this._reconnectTimer=void 0,this.shouldReconnect&&this.reconnect().catch(n=>{gr.error("reconnect after token refresh failed:",n)})},Po.RECONNECT_AFTER_TOKEN_REFRESH_DELAY_MS))}catch(r){gr.error("handleInvalidToken failed:",r)}}_isTokenExpired(e){try{const r=e.split(".");if(r.length!==3)return gr.debug("_isTokenExpired: token does not have 3 parts, treating as not expired"),!1;const n=JSON.parse(atob(r[1]));if(typeof n.exp!="number")return gr.debug("_isTokenExpired: payload.exp is not a number, treating as not expired"),!1;const s=n.exp*1e3<Date.now();return gr.debug("_isTokenExpired: exp=",n.exp,"expired=",s),s}catch(r){return gr.debug("_isTokenExpired: failed to parse JWT, treating as not expired:",r),!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 gr.error(`RPC '${e}' failed:`,n),n}}subscribeChannels(){var s,o;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 u=>{const p=u.data;try{await this.applyUpdates([p])}catch(y){gr.error(`applyUpdates failed for offset ${p.offset} on channel ${r}:`,y),this.emit("error",y instanceof Error?y:new Error(String(y)))}}),a.on("subscribed",async u=>{var p,y,h,g,b,S,O,P;if(u.streamPosition){const A=u.streamPosition.epoch,C=u.streamPosition.offset;this.epochCache.set(r,A);const T=await((y=(p=this.options).getLastOffset)==null?void 0:y.call(p,r)),x=T==null?void 0:T.offset;if(x===void 0)await((g=(h=this.options).updateOffset)==null?void 0:g.call(h,r,C,A));else if(!(C<=x)){const E=(T==null?void 0:T.epoch)??this.epochCache.get(r)??"";try{await this.fillOffsetGap(r,x,E,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!==A)throw new Error(`[RTCAgentClient] Epoch mismatch after gap fill on subscribe: expected '${A}', got '${I}'. Server may have restarted.`);await((P=(O=this.options).updateOffset)==null?void 0:P.call(O,r,C,A))}catch(j){gr.error(`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 u=>{const p={channel:n,data:u.data};await this.handlePublication(p,a)})}(o=this.subscriptions.get(n))==null||o.subscribe()}async fillOffsetGap(e,r,n,s){const o=this.subscriptions.get(e);if(!o){gr.warn(`fillOffsetGap: subscription not found for channel ${e}`);return}let a={since:{offset:r,epoch:n},limit:void 0,reverse:!1};if(s){const u=s-r-1;if(u<=0)return;a.limit=u}try{const u=await o.history(a);for(const p of u.publications){const y=p.data;await this.processUpdate(y)}}catch(u){throw gr.error(`fillOffsetGap failed for channel ${e}:`,u),u}}async handlePublication(e,r){if(this.options.onPublication)try{await this.options.onPublication(e)}catch(n){throw gr.error(`onPublication threw for channel '${e.channel}':`,n),r.unsubscribe(),n}}};Vt(Po,"RECONNECT_AFTER_SIZE_LIMIT_DELAY_MS",3e3),Vt(Po,"RECONNECT_AFTER_TOKEN_REFRESH_DELAY_MS",1e3);let Lf=Po;var Di=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function sE(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Uy={exports:{}};(function(t,e){((r,n)=>{t.exports=n()})(Di,function(){var r=function(v,_){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,_)},n=function(){return(n=Object.assign||function(v){for(var _,M=1,V=arguments.length;M<V;M++)for(var re in _=arguments[M])Object.prototype.hasOwnProperty.call(_,re)&&(v[re]=_[re]);return v}).apply(this,arguments)};function s(v,_,M){for(var V,re=0,pe=_.length;re<pe;re++)!V&&re in _||((V=V||Array.prototype.slice.call(_,0,re))[re]=_[re]);return v.concat(V||Array.prototype.slice.call(_))}var o=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:Di,a=Object.keys,u=Array.isArray;function p(v,_){return typeof _=="object"&&a(_).forEach(function(M){v[M]=_[M]}),v}typeof Promise>"u"||o.Promise||(o.Promise=Promise);var y=Object.getPrototypeOf,h={}.hasOwnProperty;function g(v,_){return h.call(v,_)}function b(v,_){typeof _=="function"&&(_=_(y(v))),(typeof Reflect>"u"?a:Reflect.ownKeys)(_).forEach(function(M){O(v,M,_[M])})}var S=Object.defineProperty;function O(v,_,M,V){S(v,_,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 P(v){return{from:function(_){return v.prototype=Object.create(_.prototype),O(v.prototype,"constructor",v),{extend:b.bind(null,v.prototype)}}}}var A=Object.getOwnPropertyDescriptor,C=[].slice;function T(v,_,M){return C.call(v,_,M)}function x(v,_){return _(v)}function E(v){if(!v)throw new Error("Assertion Failed")}function j(v){o.setImmediate?setImmediate(v):setTimeout(v,0)}function R(v,_){if(typeof _=="string"&&g(v,_))return v[_];if(!_)return v;if(typeof _!="string"){for(var M=[],V=0,re=_.length;V<re;++V){var pe=R(v,_[V]);M.push(pe)}return M}var Te,Ne=_.indexOf(".");return Ne===-1||(Te=v[_.substr(0,Ne)])==null?void 0:R(Te,_.substr(Ne+1))}function I(v,_,M){if(v&&_!==void 0&&!("isFrozen"in Object&&Object.isFrozen(v)))if(typeof _!="string"&&"length"in _){E(typeof M!="string"&&"length"in M);for(var V=0,re=_.length;V<re;++V)I(v,_[V],M[V])}else{var pe=_.indexOf(".");if(pe!==-1){var Te=_.substr(0,pe),pe=_.substr(pe+1);if(pe==="")M===void 0?u(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?u(v)&&!isNaN(parseInt(_))?v.splice(_,1):delete v[_]:v[_]=M}}function D(v){var _,M={};for(_ in v)g(v,_)&&(M[_]=v[_]);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(_){return _+v+"Array"})}))).filter(function(v){return o[v]}),N=new Set(ae.map(function(v){return o[v]})),$=null;function ne(v){return $=new WeakMap,v=function _(M){if(!M||typeof M!="object")return M;var V=$.get(M);if(V)return V;if(u(M)){V=[],$.set(M,V);for(var re=0,pe=M.length;re<pe;++re)V.push(_(M[re]))}else if(N.has(M.constructor))V=M;else{var Te,Ne=y(M);for(Te in V=Ne===Object.prototype?{}:Object.create(Ne),$.set(M,V),M)g(M,Te)&&(V[Te]=_(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 _;return v!=null&&(_=v[Ae])&&_.apply(v)}:function(){return null};function ue(v,_){_=v.indexOf(_),0<=_&&v.splice(_,1)}var K={};function Y(v){var _,M,V,re;if(arguments.length===1){if(u(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(_=v.length)!="number")return[v];for(M=new Array(_);_--;)M[_]=v[_]}}else for(_=arguments.length,M=new Array(_);_--;)M[_]=arguments[_];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,_){this.name=v,this.message=_}function H(v,_){return v+". Errors: "+Object.keys(_).map(function(M){return _[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,o,a;if(e.delta){a=!0;const u=new TextEncoder().encode(e.data),p=rE(r,u);n=JSON.parse(new TextDecoder().decode(p)),s=p,o=u.length}else a=!1,n=JSON.parse(e.data),s=new TextEncoder().encode(e.data),o=s.length;return{newData:n,newPrevValue:s,isDelta:a,wireBytes:o,fullBytes:s.length}}}const nE={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 Cs extends Error{constructor(e){super(e),this.name=this.constructor.name}}class Bl extends Ly{constructor(e,r){super(),this._reconnectTimeout=null,this._refreshTimeout=null,this._serverPingTimeout=null,this.state=Rr.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 qy,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({},nE),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 GT(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 Mf(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 Mf(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 Mf(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 zT(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!==cn.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 Br(this,void 0,void 0,function*(){switch(this.state){case Rr.Disconnected:throw{code:ur.clientDisconnected,message:"client disconnected"};case Rr.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(La.disconnectCalled,"disconnect called",!1)}setToken(e){this._token=e}setData(e){this._data=e}setHeaders(e){this._config.headers=e}send(e){return Br(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 Br(this,void 0,void 0,function*(){const n={rpc:{method:e,data:r}};return yield this._methodCall(),{data:(yield this._callPromise(n,o=>o.rpc)).data}})}publish(e,r){return Br(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 Br(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 Br(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 Br(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),o=[];if(s.publications)for(let a=0;a<s.publications.length;a++)o.push(this._getPublicationContext(e,s.publications[a]));return{publications:o,epoch:s.epoch||"",offset:s.offset||0}})}presence(e){return Br(this,void 0,void 0,function*(){const r={presence:{channel:e}};yield this._methodCall();const s=(yield this._callPromise(r,o=>o.presence)).presence;for(const o in s)if(Object.prototype.hasOwnProperty.call(s,o)){const a=s[o],u=a.conn_info,p=a.chan_info;u&&(a.connInfo=u),p&&(a.chanInfo=p)}return{clients:s}})}presenceStats(e){return Br(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&&UT("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 qy,this._formatOverride(),(this._config.debug===!0||WT("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===Rr.Disconnected}_isConnecting(){return this.state===Rr.Connecting}_isConnected(){return this.state===Rr.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===Rr.Connected||this.state===Rr.Connecting)&&(this._disconnect(As.transportClosed,"transport closed",!0),this._deviceWentOffline=!0)}),e.addEventListener("online",()=>{this._debug("online event triggered"),this.state===Rr.Connecting&&(this._deviceWentOffline&&!this._transportClosed&&(this._deviceWentOffline=!1,this._transportClosed=!0),this._clearReconnectTimeout(),this._startReconnecting())}),this._networkEventsSet=!0)}_getReconnectDelay(){const e=la(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===cn.Subscribed&&r._setSubscribing(Dl.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 o=s.errback;o({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 o=null;if(this._config.readableStream!==null?o=this._config.readableStream:typeof globalThis.ReadableStream<"u"&&(o=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],P=O.transport,A=O.endpoint;if(P==="websocket"){if(this._debug("trying websocket transport"),this._transport=new Fy(A,{websocket:e}),!this._transport.supported()){this._debug("websocket transport not available"),this._advanceTransportIndex(),S++;continue}}else if(P==="webtransport"){if(this._debug("trying webtransport transport"),this._transport=new XT(A,{webtransport:globalThis.WebTransport,decoder:this._codec,encoder:this._codec}),!this._transport.supported()){this._debug("webtransport transport not available"),this._advanceTransportIndex(),S++;continue}}else if(P==="http_stream"){if(this._debug("trying http_stream transport"),this._transport=new JT(A,{fetch:s,readableStream:o,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(P==="sse"){if(this._debug("trying sse transport"),this._transport=new YT(A,{eventsource:n,fetch:s,emulationEndpoint:this._config.emulationEndpoint}),!this._transport.supported()){this._debug("sse transport not available"),this._advanceTransportIndex(),S++;continue}}else if(P==="sockjs"){if(this._debug("trying sockjs"),this._transport=new HT(A,{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 "+P);break}}else{if($T(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 Fy(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,u=this._transport,p=this._nextTransportId();a._debug("id of transport",p);let y=!1;const h=[];if(this._transport.emulation()){const S=a._sendConnect(!0);h.push(S)}this._setNetworkEvents();const g=this._codec.encodeCommands(h);this._transportClosed=!1;let b;b=setTimeout(function(){u.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"),u.close();return}y=!0,a._debug(u.subName(),"transport open"),!u.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(u.subName(),"transport closed"),a._transportClosed=!0,a._transportIsOpen=!1;let O="connection closed",P=!0,A=0;if(S&&"code"in S&&S.code&&(A=S.code),S&&S.reason)try{const C=JSON.parse(S.reason);O=C.reason,P=C.reconnect}catch{O=S.reason,(A>=3500&&A<4e3||A>=4500&&A<5e3)&&(P=!1)}A<3e3?(A===1009?(A=La.messageSizeLimit,O="message size limit exceeded",P=!1):(A=As.transportClosed,O="transport closed"),a._emulation&&!a._transportWasOpen&&a._advanceTransportIndex()):a._transportWasOpen=!0,a._isConnecting()&&!y&&a.emit("error",{type:"transport",error:{code:ur.transportClosed,message:"transport closed"},transport:u.name()}),a._reconnecting=!1,a._disconnect(A,O,P)},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 o=s.reply.connect;n._connectResponse(o),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(o){n._isConnecting()&&(n._data=o,n._initializeTransport())}).catch(o=>n._handleGetDataError(o)):n._initializeTransport()}}).catch(function(s){if(!n._isConnecting())return;if(s instanceof Cs){n._failUnauthorized();return}n.emit("error",{type:"connectToken",error:{code:ur.clientConnectToken,message:s!==void 0?s.toString():""}});const o=n._getReconnectDelay();n._debug("error on getting connection token, reconnect after "+o+" milliseconds",s),n._reconnecting=!1,n._reconnectTimeout=setTimeout(()=>{n._startReconnecting()},o)})}_handleGetDataError(e){if(e instanceof Cs){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===Rr.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 o={recover:!0};this._serverSubs[s].offset&&(o.offset=this._serverSubs[s].offset),this._serverSubs[s].epoch&&(o.epoch=this._serverSubs[s].epoch),r[s]=o}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(o=>{var a;const u=r(o.reply);n(u),(a=o.next)===null||a===void 0||a.call(o)},o=>{var a;s(o.error),(a=o.next)===null||a===void 0||a.call(o)})})}_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(o=>{r=o});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(Rr.Connecting)&&this.emit("connecting",{code:As.connectCalled,reason:"connect called"}),this._client=null,this._startReconnecting()}_disconnect(e,r,n){if(e===La.stateInvalidated){this._token="",this._refreshRequired=!0;for(const u in this._subs)this._subs.hasOwnProperty(u)&&this._subs[u]._invalidateState();for(const u in this._serverSubs)this._serverSubs.hasOwnProperty(u)&&(this._serverSubs[u].offset=0,this._serverSubs[u].epoch="_")}if(this._isDisconnected())return;this._transportIsOpen=!1;const s=this.state;this._reconnecting=!1;const o={code:e,reason:r};let a;if(n?a=this._setState(Rr.Connecting):(a=this._setState(Rr.Disconnected),this._rejectPromises({code:ur.clientDisconnected,message:"disconnected"})),this._clearOutgoingRequests(),s===Rr.Connecting&&this._clearReconnectTimeout(),s===Rr.Connected&&this._clearConnectedState(),a&&(this._isConnecting()?this.emit("connecting",o):this.emit("disconnected",o)),this._transport){this._debug("closing existing transport");const u=this._transport;this._transport=null,u.close(),this._transportClosed=!0,this._nextTransportId()}else this._debug("no transport to close");this._scheduleReconnect()}_failUnauthorized(){this._disconnect(La.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 Cs("")))}_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(o=>{const a=o.reply.refresh;r._refreshResponse(a),o.next&&o.next()},o=>{r._refreshError(o.error),o.next&&o.next()})}).catch(function(n){if(r._isConnected()){if(n instanceof Cs){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 la(0,5e3,1e4)}_refreshResponse(e){this._refreshTimeout&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null),e.expires&&(this._client=e.client,this._refreshTimeout=setTimeout(()=>this._refresh(),Co(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,u)=>{this._call(n,!1).then(p=>{a(),p.next&&p.next()},p=>{a(),p.next&&p.next(),s._disconnect(As.unsubscribeError,"unsubscribe error",!0)})})}_getSub(e,r){if(r&&r>0){for(const s in this._subs)if(this._subs.hasOwnProperty(s)){const o=this._subs[s];if(o._id===r)return o}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===cn.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(Rr.Connected),this._refreshTimeout&&clearTimeout(this._refreshTimeout),e.expires&&(this._refreshTimeout=setTimeout(()=>this._refresh(),Co(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 o in s)s.hasOwnProperty(o)&&this._handlePublication(r,s[o])}}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(As.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 o=0;return"offset"in r&&(o=r.offset),(n.positioned||n.recoverable)&&(n.streamPosition={offset:o,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],KT(e)){const o=s.errback;if(!o){r();return}const a={code:e.error.code,message:e.error.message||"",temporary:e.error.temporary||!1};o({error:a,next:r})}else{const o=s.callback;if(!o)return;o({reply:e,next:r})}}_handleJoin(e,r,n){const s=this._getSub(e,n);if(!s){if(e&&this._isServerSub(e)){const o={channel:e,info:this._getJoinLeaveContext(r.info)};this.emit("join",o)}return}s._handleJoin(r)}_handleLeave(e,r,n){const s=this._getSub(e,n);if(!s){if(e&&this._isServerSub(e)){const o={channel:e,info:this._getJoinLeaveContext(r.info)};this.emit("leave",o)}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===wo.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 o=this._getPublicationContext(e,r);this.emit("publication",o),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],Rf(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])}}Bl.SubscriptionState=cn,Bl.State=Rr,Bl.UnauthorizedError=Cs;const Dn={SessionList:"v1.session.list",SessionGet:"v1.session.get",SessionClose:"v1.session.close",SessionOpen:"v1.session.open",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"},$y={debug:0,info:1,warn:2,error:3};let iE="debug";function ss(t){const e=r=>$y[r]>=$y[iE];return{debug(...r){e("debug")&&console.debug(`[${t}]`,...r)},info(...r){e("info")&&console.info(`[${t}]`,...r)},warn(...r){e("warn")&&console.warn(`[${t}]`,...r)},error(...r){e("error")&&console.error(`[${t}]`,...r)}}}const mr=ss("RTCAgentClient"),Po=class Po{constructor(e){Vt(this,"options");Vt(this,"centrifuge",null);Vt(this,"connectionState","disconnected");Vt(this,"listeners",new Map);Vt(this,"shouldReconnect",!0);Vt(this,"wasConnected",!1);Vt(this,"applyUpdatesQueue",null);Vt(this,"subscriptions",new Map);Vt(this,"epochCache",new Map);Vt(this,"_reconnectTimer");this.options=e}async connect(){if(mr.debug("connect() called, current state:",this.connectionState),this.connectionState==="connected"||this.connectionState==="connecting"){mr.debug("connect() early return, already",this.connectionState);return}this.shouldReconnect=!0,this.setConnectionState("connecting"),this.centrifuge=new Bl(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",()=>{mr.debug("centrifuge connected, setting state to connected"),this.wasConnected=!0,this.setConnectionState("connected"),this.subscribeChannels()}),this.centrifuge.on("disconnected",e=>{if(mr.debug("centrifuge disconnected, reason:",e==null?void 0:e.reason),(e==null?void 0:e.reason)==="invalid token"&&this.options.onTokenExpired){const r=this.centrifuge;this.centrifuge=null,r==null||r.disconnect(),this.handleInvalidToken()}(e==null?void 0:e.reason)==="message size limit exceeded"&&(mr.warn("message size limit exceeded, will retry connection after delay"),this._reconnectTimer=setTimeout(()=>{this._reconnectTimer=void 0,this.shouldReconnect&&this.connectionState==="disconnected"&&(mr.debug("attempting reconnect after message size limit error"),this.reconnect().catch(r=>{mr.error("reconnect failed:",r)}))},Po.RECONNECT_AFTER_SIZE_LIMIT_DELAY_MS)),this.setConnectionState("disconnected",e==null?void 0:e.reason)}),this.centrifuge.on("error",e=>{var r;mr.error("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"))}),mr.debug("calling centrifuge.connect() synchronously"),this.centrifuge.connect(),mr.debug("centrifuge.connect() returned, state:",this.connectionState,"(WebSocket not yet established)")}disconnect(){var e;this.shouldReconnect=!1,this.wasConnected=!1,this._reconnectTimer&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=void 0),(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(Dn.SessionList,{cursor:e,limit:r})}async getSession(e){return this.rpc(Dn.SessionGet,{session_id:e})}async closeSession(e){return this.rpc(Dn.SessionClose,{session_id:e})}async openSession(e){return this.rpc(Dn.SessionOpen,{session_id:e})}async compactSession(e){return this.rpc(Dn.SessionCompact,e)}async updateSession(e){return this.rpc(Dn.SessionUpdate,e)}async sendMessage(e){return this.rpc(Dn.MessageSend,e)}async forkSession(e){return this.rpc(Dn.SessionFork,e)}async stopTurn(e){return this.rpc(Dn.TurnStop,{session_id:e})}async listMessages(e,r,n){return this.rpc(Dn.MessageList,{session_id:e,cursor:r,limit:n})}async listTurns(e,r,n){return this.rpc(Dn.TurnList,{session_id:e,cursor:r,limit:n})}async listRtc(e,r,n){return this.rpc(Dn.RtcList,{session_id:e,cursor:r,limit:n})}async updateRtcStatus(e,r){return this.rpc(Dn.RtcUpdateStatus,{rtc_id:e,status:r})}async submitRtcResult(e,r,n,s){return this.rpc(Dn.RtcSubmitResult,{rtc_id:e,success:r,result:n,error:s})}async applyUpdates(e,r){let n=this.applyUpdatesQueue;const s=(async()=>{if(n&&await n,r)await r();else for(const o of e)await this.processUpdate(o)})();this.applyUpdatesQueue=s;try{await s}finally{this.applyUpdatesQueue===s&&(this.applyUpdatesQueue=null)}}async processUpdate(e){var n,s,o,a,u,p;const r=`topic:u=${this.options.userId}`;if(e.offset>0){const y=await((s=(n=this.options).getLastOffset)==null?void 0:s.call(n,r)),h=y==null?void 0:y.offset,g=(y==null?void 0:y.epoch)??this.epochCache.get(r)??"";if(h!==void 0&&e.offset<=h){mr.debug(`Skipping duplicate/expired message: offset=${e.offset}, lastOffset=${h}`);return}if(h!==void 0&&e.offset>h+1){await this.fillOffsetGap(r,h,g,e.offset);const b=await((a=(o=this.options).getLastOffset)==null?void 0:a.call(o,r)),S=b==null?void 0:b.offset,O=b==null?void 0:b.epoch,P=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!==P)throw new Error(`[RTCAgentClient] Epoch mismatch after gap fill: expected '${P}', got '${O}'. Rejecting update ${e.offset} to prevent data corruption.`)}}if(this.options.onPublication){const y={channel:`topic:u=${this.options.userId}`,offset:e.offset,data:e};await this.options.onPublication(y)}if(e.offset>0){const y=this.epochCache.get(r)??"";await((p=(u=this.options).updateOffset)==null?void 0:p.call(u,r,e.offset,y))}}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(o){mr.error(`listener for '${e}' threw:`,o)}}setConnectionState(e,r){var s,o;if(mr.debug("setConnectionState:",e,"reason:",r,"previous:",this.connectionState),this.connectionState===e)return;this.connectionState=e;const n={state:e,reason:r};this.emit("connection",n),(o=(s=this.options).onConnectionStateChange)==null||o.call(s,n)}async handleInvalidToken(){var e;if(!this.options.onTokenExpired){mr.warn("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")):(mr.debug("token refreshed, attempting to reconnect"),this._reconnectTimer=setTimeout(()=>{this._reconnectTimer=void 0,this.shouldReconnect&&this.reconnect().catch(n=>{mr.error("reconnect after token refresh failed:",n)})},Po.RECONNECT_AFTER_TOKEN_REFRESH_DELAY_MS))}catch(r){mr.error("handleInvalidToken failed:",r)}}_isTokenExpired(e){try{const r=e.split(".");if(r.length!==3)return mr.debug("_isTokenExpired: token does not have 3 parts, treating as not expired"),!1;const n=JSON.parse(atob(r[1]));if(typeof n.exp!="number")return mr.debug("_isTokenExpired: payload.exp is not a number, treating as not expired"),!1;const s=n.exp*1e3<Date.now();return mr.debug("_isTokenExpired: exp=",n.exp,"expired=",s),s}catch(r){return mr.debug("_isTokenExpired: failed to parse JWT, treating as not expired:",r),!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 mr.error(`RPC '${e}' failed:`,n),n}}subscribeChannels(){var s,o;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 u=>{const p=u.data;try{await this.applyUpdates([p])}catch(y){mr.error(`applyUpdates failed for offset ${p.offset} on channel ${r}:`,y),this.emit("error",y instanceof Error?y:new Error(String(y)))}}),a.on("subscribed",async u=>{var p;if(u.streamPosition){const y=u.streamPosition.epoch,h=u.streamPosition.offset;this.epochCache.set(r,y);let g;try{await this.applyUpdates([],async()=>{var O,P,A,C,T,x,E,j,R,I;const b=await((P=(O=this.options).getLastOffset)==null?void 0:P.call(O,r));let S=!1;if(b&&b.epoch!==y?(mr.warn(`Epoch changed: '${b.epoch}' -> '${y}', resetting offset to 0`),await((C=(A=this.options).updateOffset)==null?void 0:C.call(A,r,0,y)),g=0,S=!0):g=b==null?void 0:b.offset,g===void 0)await((x=(T=this.options).updateOffset)==null?void 0:x.call(T,r,h,y));else if(!(h<=g)){const D=S?y:(b==null?void 0:b.epoch)??y;await this.fillOffsetGap(r,g,D,h+1);const Z=await((j=(E=this.options).getLastOffset)==null?void 0:j.call(E,r)),J=Z==null?void 0:Z.offset,N=Z==null?void 0:Z.epoch;if(J===void 0||J!==h)throw new Error(`[RTCAgentClient] Offset gap fill failed on subscribe: expected ${h}, got ${J}. Offline updates may be lost.`);if(N!==void 0&&N!==y)throw new Error(`[RTCAgentClient] Epoch mismatch after gap fill on subscribe: expected '${y}', got '${N}'. Server may have restarted.`);await((I=(R=this.options).updateOffset)==null?void 0:I.call(R,r,h,y))}})}catch(b){mr.error(`fillOffsetGap failed on subscribe for offset ${h}:`,b),this.emit("error",b instanceof Error?b:new Error(String(b))),(p=this.centrifuge)==null||p.disconnect(),this.setConnectionState("disconnected","gap fill failed"),this.emit("syncRequired",{reason:"gap_fill_failed",lastKnownOffset:g,serverOffset:h})}}})}(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 u=>{const p={channel:n,data:u.data};await this.handlePublication(p,a)})}(o=this.subscriptions.get(n))==null||o.subscribe()}async fillOffsetGap(e,r,n,s){const o=this.subscriptions.get(e);if(!o){mr.warn(`fillOffsetGap: subscription not found for channel ${e}`);return}let a={since:{offset:r,epoch:n},limit:void 0,reverse:!1};if(s){const u=s-r-1;if(u<=0)return;a.limit=u}try{const p=(await o.history(a)).publications;if(s!==void 0&&p.length>0){const y=p[0].data.offset;if(y!==r+1)throw new Error(`Gap fill missing messages: expected first offset ${r+1}, got ${y}`);for(let h=1;h<p.length;h++){const g=p[h-1].data.offset,b=p[h].data.offset;if(b!==g+1)throw new Error(`Gap fill non-continuous: offset jumped from ${g} to ${b}`)}}for(const y of p){const h=y.data;await this.processUpdate(h)}}catch(u){throw mr.error(`fillOffsetGap failed for channel ${e}:`,u),u}}async handlePublication(e,r){if(this.options.onPublication)try{await this.options.onPublication(e)}catch(n){throw mr.error(`onPublication threw for channel '${e.channel}':`,n),r.unsubscribe(),n}}};Vt(Po,"RECONNECT_AFTER_SIZE_LIMIT_DELAY_MS",3e3),Vt(Po,"RECONNECT_AFTER_TOKEN_REFRESH_DELAY_MS",1e3);let Lf=Po;var Di=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function sE(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Uy={exports:{}};(function(t,e){((r,n)=>{t.exports=n()})(Di,function(){var r=function(v,_){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,_)},n=function(){return(n=Object.assign||function(v){for(var _,M=1,V=arguments.length;M<V;M++)for(var re in _=arguments[M])Object.prototype.hasOwnProperty.call(_,re)&&(v[re]=_[re]);return v}).apply(this,arguments)};function s(v,_,M){for(var V,re=0,pe=_.length;re<pe;re++)!V&&re in _||((V=V||Array.prototype.slice.call(_,0,re))[re]=_[re]);return v.concat(V||Array.prototype.slice.call(_))}var o=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:Di,a=Object.keys,u=Array.isArray;function p(v,_){return typeof _=="object"&&a(_).forEach(function(M){v[M]=_[M]}),v}typeof Promise>"u"||o.Promise||(o.Promise=Promise);var y=Object.getPrototypeOf,h={}.hasOwnProperty;function g(v,_){return h.call(v,_)}function b(v,_){typeof _=="function"&&(_=_(y(v))),(typeof Reflect>"u"?a:Reflect.ownKeys)(_).forEach(function(M){O(v,M,_[M])})}var S=Object.defineProperty;function O(v,_,M,V){S(v,_,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 P(v){return{from:function(_){return v.prototype=Object.create(_.prototype),O(v.prototype,"constructor",v),{extend:b.bind(null,v.prototype)}}}}var A=Object.getOwnPropertyDescriptor,C=[].slice;function T(v,_,M){return C.call(v,_,M)}function x(v,_){return _(v)}function E(v){if(!v)throw new Error("Assertion Failed")}function j(v){o.setImmediate?setImmediate(v):setTimeout(v,0)}function R(v,_){if(typeof _=="string"&&g(v,_))return v[_];if(!_)return v;if(typeof _!="string"){for(var M=[],V=0,re=_.length;V<re;++V){var pe=R(v,_[V]);M.push(pe)}return M}var Te,Ne=_.indexOf(".");return Ne===-1||(Te=v[_.substr(0,Ne)])==null?void 0:R(Te,_.substr(Ne+1))}function I(v,_,M){if(v&&_!==void 0&&!("isFrozen"in Object&&Object.isFrozen(v)))if(typeof _!="string"&&"length"in _){E(typeof M!="string"&&"length"in M);for(var V=0,re=_.length;V<re;++V)I(v,_[V],M[V])}else{var pe=_.indexOf(".");if(pe!==-1){var Te=_.substr(0,pe),pe=_.substr(pe+1);if(pe==="")M===void 0?u(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?u(v)&&!isNaN(parseInt(_))?v.splice(_,1):delete v[_]:v[_]=M}}function D(v){var _,M={};for(_ in v)g(v,_)&&(M[_]=v[_]);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(_){return _+v+"Array"})}))).filter(function(v){return o[v]}),N=new Set(ae.map(function(v){return o[v]})),$=null;function ne(v){return $=new WeakMap,v=function _(M){if(!M||typeof M!="object")return M;var V=$.get(M);if(V)return V;if(u(M)){V=[],$.set(M,V);for(var re=0,pe=M.length;re<pe;++re)V.push(_(M[re]))}else if(N.has(M.constructor))V=M;else{var Te,Ne=y(M);for(Te in V=Ne===Object.prototype?{}:Object.create(Ne),$.set(M,V),M)g(M,Te)&&(V[Te]=_(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 _;return v!=null&&(_=v[Ae])&&_.apply(v)}:function(){return null};function ue(v,_){_=v.indexOf(_),0<=_&&v.splice(_,1)}var K={};function Y(v){var _,M,V,re;if(arguments.length===1){if(u(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(_=v.length)!="number")return[v];for(M=new Array(_);_--;)M[_]=v[_]}}else for(_=arguments.length,M=new Array(_);_--;)M[_]=arguments[_];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,_){this.name=v,this.message=_}function H(v,_){return v+". Errors: "+Object.keys(_).map(function(M){return _[M].toString()}).filter(function(M,V,re){return re.indexOf(M)===V}).join(`
|
|
12
12
|
`)}function ye(v,_,M,V){this.failures=_,this.failedKeys=V,this.successCount=M,this.message=H(v,_)}function Ie(v,_){this.name="BulkError",this.failures=Object.keys(_).map(function(M){return _[M]}),this.failuresByPos=_,this.message=H(v,this.failures)}P(L).from(Error).extend({toString:function(){return this.name+": "+this.message}}),P(ye).from(L),P(Ie).from(L);var Ee=oe.reduce(function(v,_){return v[_]=_+"Error",v},{}),De=L,Me=oe.reduce(function(v,_){var M=_+"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[_]||M,this.inner=null)}return P(V).from(De),v[_]=V,v},{}),Ve=(Me.Syntax=SyntaxError,Me.Type=TypeError,Me.Range=RangeError,ae.reduce(function(v,_){return v[_+"Error"]=Me[_],v},{}));ae=oe.reduce(function(v,_){return["Syntax","Type","Range"].indexOf(_)===-1&&(v[_+"Error"]=Me[_]),v},{});function Ze(){}function ut(v){return v}function st(v,_){return v==null||v===ut?_:function(M){return _(v(M))}}function dt(v,_){return function(){v.apply(this,arguments),_.apply(this,arguments)}}function $e(v,_){return v===Ze?_: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,_.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,_){return v===Ze?_:function(){v.apply(this,arguments);var M=this.onsuccess,V=this.onerror;this.onsuccess=this.onerror=null,_.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,_){return v===Ze?_:function(re){var V=v.apply(this,arguments),re=(p(re,V),this.onsuccess),pe=this.onerror,Te=(this.onsuccess=null,this.onerror=null,_.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,_){return v===Ze?_:function(){return _.apply(this,arguments)!==!1&&v.apply(this,arguments)}}function gt(v,_){return v===Ze?_: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 _.apply(V,pe)})}return _.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])),y(ee),oe]:[oe,y(oe),oe]),oe=ee[0],Nn=ee[1],Nn=Nn&&Nn.then,W=oe&&oe.constructor,fe=!!ee[2],Re=function(v,_){te.push([v,_]),Ke&&(queueMicrotask(Lt),Ke=!1)},Fe=!0,Ke=!0,it=[],Pt=[],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 _=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,++_.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&&Kt();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,_=Rt;function M(V,re){var pe=this,Te=!v.global&&(v!==xt||_!==Rt),Ne=Te&&!jr(),We=new be(function(at,Je){mt(pe,new ge(In(V,v,Te,Ne),In(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,_,M,V,re){this.onFulfilled=typeof v=="function"?v:null,this.onRejected=typeof _=="function"?_:null,this.resolve=M,this.reject=V,this.psd=re}function rt(v,_){var M,V;Pt.push(_),v._state===null&&(M=v._lib&&Kt(),_=Mt(_),v._state=!1,v._value=_,V=v,it.some(function(re){return re._value===V._value})||it.push(V),yt(v),M)&&Jt()}function yt(v){var _=v._listeners;v._listeners=[];for(var M=0,V=_.length;M<V;++M)mt(v,_[M]);var re=v._PSD;--re.ref||re.finalize(),de===0&&(++de,Re(function(){--de==0&&lr()},[]))}function mt(v,_){if(v._state===null)v._listeners.push(_);else{var M=v._state?_.onFulfilled:_.onRejected;if(M===null)return(v._state?_.resolve:_.reject)(v._value);++_.psd.ref,++de,Re(Bt,[M,v,_])}}function Bt(v,_,M){try{var V,re=_._value;!_._state&&Pt.length&&(Pt=[]),V=ht&&_._consoleTask?_._consoleTask.run(function(){return v(re)}):v(re),_._state||Pt.indexOf(re)!==-1||(pe=>{for(var Te=it.length;Te;)if(it[--Te]._value===pe._value)return it.splice(Te,1)})(_),M.resolve(V)}catch(pe){M.reject(pe)}finally{--de==0&&lr(),--M.psd.ref||M.psd.finalize()}}function Lt(){kr(pt,function(){Kt()&&Jt()})}function Kt(){var v=Fe;return Ke=Fe=!1,v}function Jt(){var v,_,M;do for(;0<te.length;)for(v=te,te=[],M=v.length,_=0;_<M;++_){var V=v[_];V[0].apply(null,V[1])}while(0<te.length);Ke=Fe=!0}function lr(){for(var v=it,_=(it=[],v.forEach(function(V){V._PSD.onunhandled.call(null,V._value,V)}),G.slice(0)),M=_.length;M;)_[--M]()}function _r(v){return new be(Se,!1,v)}function Gt(v,_){var M=xt;return function(){var V=Kt(),re=xt;try{return Wr(M,!0),v.apply(this,arguments)}catch(pe){_&&_(pe)}finally{Wr(re,!1),V&&Jt()}}}b(be.prototype,{then:et,_then:function(v,_){mt(this,new ge(null,null,v,_,xt))},catch:function(v){var _,M;return arguments.length===1?this.then(null,v):(_=v,M=arguments[1],typeof _=="function"?this.then(null,function(V){return(V instanceof _?M:_r)(V)}):this.then(null,function(V){return(V&&V.name===_?M:_r)(V)}))},finally:function(v){return this.then(function(_){return be.resolve(v()).then(function(){return _})},function(_){return be.resolve(v()).then(function(){return _r(_)})})},timeout:function(v,_){var M=this;return v<1/0?new be(function(V,re){var pe=setTimeout(function(){return re(new Me.Timeout(_))},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=Xn(),b(be,{all:function(){var v=Y.apply(null,arguments).map(Mr);return new be(function(_,M){v.length===0&&_([]);var V=v.length;v.forEach(function(re,pe){return be.resolve(re).then(function(Te){v[pe]=Te,--V||_(v)},M)})})},resolve:function(v){return v instanceof be?v:v&&typeof v.then=="function"?new be(function(_,M){v.then(_,M)}):new be(Se,!0,v)},reject:_r,race:function(){var v=Y.apply(null,arguments).map(Mr);return new be(function(_,M){v.map(function(V){return be.resolve(V).then(_,M)})})},PSD:{get:function(){return xt},set:function(v){return xt=v}},totalEchoes:{get:function(){return Rt}},newPSD:Kr,usePSD:kr,scheduler:{get:function(){return Re},set:function(v){Re=v}},rejectionMapper:{get:function(){return Mt},set:function(v){Mt=v}},follow:function(v,_){return new be(function(M,V){return Kr(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()},_,M,V)})}}),W&&(W.allSettled&&O(be,"allSettled",function(){var v=Y.apply(null,arguments).map(Mr);return new be(function(_){v.length===0&&_([]);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||_(V)})})})}),W.any&&typeof AggregateError<"u"&&O(be,"any",function(){var v=Y.apply(null,arguments).map(Mr);return new be(function(_,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 _(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},dn=0,hn=[],Tr=0,Rt=0,hi=0;function Kr(v,Te,M,V){var re=xt,pe=Object.create(re),Te=(pe.parent=re,pe.ref=0,pe.global=!1,pe.id=++hi,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()},kr(pe,v,M,V));return pe.ref===0&&pe.finalize(),Te}function rn(){return tr.id||(tr.id=++dn),++tr.awaits,tr.echoes+=se,tr.id}function jr(){return!!tr.awaits&&(--tr.awaits==0&&(tr.id=0),tr.echoes=tr.awaits*se,!0)}function Mr(v){return tr.echoes&&v&&v.constructor===W?(rn(),v.then(function(_){return jr(),_},function(_){return jr(),dr(_)})):v}function Mn(){var v=hn[hn.length-1];hn.pop(),Wr(v,!1)}function Wr(v,_){var M,V,re=xt;(_?!tr.echoes||Tr++&&v===xt:!Tr||--Tr&&v===xt)||queueMicrotask(_?(function(pe){++Rt,tr.echoes&&--tr.echoes!=0||(tr.echoes=tr.awaits=tr.id=0),hn.push(xt),Wr(pe,!0)}).bind(null,v):Mn),v!==xt&&(xt=v,re===pt&&(pt.env=Xn()),fe)&&(M=pt.env.Promise,V=v.env,re.global||v.global)&&(Object.defineProperty(o,"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 Xn(){var v=o.Promise;return fe?{Promise:v,PromiseProp:Object.getOwnPropertyDescriptor(o,"Promise"),all:v.all,race:v.race,allSettled:v.allSettled,any:v.any,resolve:v.resolve,reject:v.reject}:{}}function kr(v,_,M,V,re){var pe=xt;try{return Wr(v,!0),_(M,V,re)}finally{Wr(pe,!1)}}function In(v,_,M,V){return typeof v!="function"?v:function(){var re=xt;M&&rn(),Wr(_,!0);try{return v.apply(this,arguments)}finally{Wr(re,!1),V&&queueMicrotask(jr)}}}function yi(v){Promise===W&&tr.echoes===0?Tr===0?v():enqueueNativeMicroTask(v):setTimeout(v,0)}(""+Nn).indexOf("[native code]")===-1&&(rn=jr=Ze);var dr=be.reject,nn="",sn="Invalid key provided. Keys must be of type string, number, Date or Array<string | number | Date>.",yn="String expected.",Gr="__dbnames",mn="readonly",qi="readwrite";function On(v,_){return v?_?function(){return v.apply(this,arguments)&&_.apply(this,arguments)}:v:_}var us={type:3,lower:-1/0,lowerOpen:!1,upper:[[]],upperOpen:!1};function mi(v){return typeof v!="string"||/\./.test(v)?function(_){return _}:function(_){return _[v]===void 0&&v in _&&delete(_=ne(_))[v],_}}function Qn(){throw Me.Type("Entity instances must never be new:ed. Instances are generated by the framework bypassing the constructor.")}function Ht(v,_){try{var M=$i(v),V=$i(_);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 _<v?1:v<_?-1:0;case"binary":for(var re=fs(v),pe=fs(_),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=_,He=Je.length,nt=Ge.length,Xe=He<nt?He:nt,Ye=0;Ye<Xe;++Ye){var Qe=Ht(Je[Ye],Ge[Ye]);if(Qe!==0)return Qe}return He===nt?0:He<nt?-1:1}}catch{}return NaN}function $i(v){var _=typeof v;return _=="object"&&(ArrayBuffer.isView(v)||(_=Ce(v))==="ArrayBuffer")?"binary":_}function fs(v){return v instanceof Uint8Array?v:ArrayBuffer.isView(v)?new Uint8Array(v.buffer,v.byteOffset,v.byteLength):new Uint8Array(v)}function gn(v,_,M){var V=v.schema.yProps;return V?(_&&0<M.numFailures&&(_=_.filter(function(re,pe){return!M.failures[pe]})),Promise.all(V.map(function(re){return re=re.updatesTable,_?v.db.table(re).where("k").anyOf(_).delete():v.db.table(re).clear()})).then(function(){return M})):M}ps.prototype.execute=function(v){var _=this["@@propmod"];if(_.add!==void 0){var M=_.add;if(u(M))return s(s([],u(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(_.remove!==void 0){var V=_.remove;if(u(V))return u(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=_.replacePrefix)==null?void 0:M[0],M&&typeof v=="string"&&v.startsWith(M)?_.replacePrefix[1]+v.substring(M.length):v};var Pr=ps;function ps(v){this["@@propmod"]=v}function gi(v,_){for(var M=a(_),V=M.length,re=!1,pe=0;pe<V;++pe){var Te=M[pe],Ne=_[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}sr.prototype._trans=function(v,_,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 _(Ge.idbtrans,Ge);throw new Me.NotFound("Table "+re+" not part of transaction")}var Ne=Kt();try{var We=V&&V.db._novip===this.db._novip?V===xt.trans?V._promise(v,Te,M):Kr(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 Kr(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()}},sr.prototype.get=function(v,_){var M=this;return v&&v.constructor===Object?this.where(v).first(_):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(_)},sr.prototype.where=function(v){if(typeof v=="string")return new this.db.WhereClause(this,v);if(u(v))return new this.db.WhereClause(this,"[".concat(v.join("+"),"]"));var _=a(v);if(_.length===1)return this.where(_[0]).equals(v[_[0]]);var M=this.schema.indexes.concat(this.schema.primKey).filter(function(Ne){if(Ne.compound&&_.every(function(at){return 0<=Ne.keyPath.indexOf(at)})){for(var We=0;We<_.length;++We)if(_.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!==nn)return Te=M.keyPath.slice(0,_.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(_.join("+"),"]"));var V=this.schema.idxByName;function re(Ne,We){return Ht(Ne,We)===0}var Te=_.reduce(function(Je,We){var at=Je[0],Je=Je[1],Ge=V[We],He=v[We];return[at||Ge,at||!Ge?On(Je,Ge&&Ge.multi?function(nt){return nt=R(nt,We),u(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(_).equals("")},sr.prototype.filter=function(v){return this.toCollection().and(v)},sr.prototype.count=function(v){return this.toCollection().count(v)},sr.prototype.offset=function(v){return this.toCollection().offset(v)},sr.prototype.limit=function(v){return this.toCollection().limit(v)},sr.prototype.each=function(v){return this.toCollection().each(v)},sr.prototype.toArray=function(v){return this.toCollection().toArray(v)},sr.prototype.toCollection=function(){return new this.db.Collection(new this.db.WhereClause(this))},sr.prototype.orderBy=function(v){return new this.db.Collection(new this.db.WhereClause(this,u(v)?"[".concat(v.join("+"),"]"):v))},sr.prototype.reverse=function(){return this.toCollection().reverse()},sr.prototype.mapToClass=function(v){for(var _=this.db,M=this.name,V=((this.schema.mappedClass=v).prototype instanceof Qn&&(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 _},enumerable:!1,configurable:!0}),Je.prototype.table=function(){return M},Je})(v)),new Set),re=v.prototype;re;re=y(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},sr.prototype.defineClass=function(){return this.mapToClass(function(v){p(this,v)})},sr.prototype.add=function(v,_){var M=this,V=this.schema.primKey,re=V.auto,pe=V.keyPath,Te=v;return pe&&re&&(Te=mi(pe)(v)),this._trans("readwrite",function(Ne){return M.core.mutate({trans:Ne,type:"add",keys:_!=null?[_]: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})},sr.prototype.upsert=function(v,_){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 gi(Te,_),V&&I(Te,V,v),M.core.mutate({trans:re,type:"put",values:[Te],keys:[v],upsert:!0,updates:{keys:[v],changeSpecs:[_]}}).then(function(Ne){return Ne.numFailures?be.reject(Ne.failures[0]):!!pe})})})},sr.prototype.update=function(v,_){return typeof v!="object"||u(v)?this.where(":id").equals(v).modify(_):(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(_)},sr.prototype.put=function(v,_){var M=this,V=this.schema.primKey,re=V.auto,pe=V.keyPath,Te=v;return pe&&re&&(Te=mi(pe)(v)),this._trans("readwrite",function(Ne){return M.core.mutate({trans:Ne,type:"put",values:[Te],keys:_!=null?[_]: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})},sr.prototype.delete=function(v){var _=this;return this._trans("readwrite",function(M){return _.core.mutate({trans:M,type:"delete",keys:[v]}).then(function(V){return gn(_,[v],V)}).then(function(V){return V.numFailures?be.reject(V.failures[0]):void 0})})},sr.prototype.clear=function(){var v=this;return this._trans("readwrite",function(_){return v.core.mutate({trans:_,type:"deleteRange",range:us}).then(function(M){return gn(v,null,M)})}).then(function(_){return _.numFailures?be.reject(_.failures[0]):void 0})},sr.prototype.bulkGet=function(v){var _=this;return this._trans("readonly",function(M){return _.core.getMany({keys:v,trans:M}).then(function(V){return V.map(function(re){return _.hook.reading.fire(re)})})})},sr.prototype.bulkAdd=function(v,_,M){var V=this,re=Array.isArray(_)?_:void 0,pe=(M=M||(re?void 0:_))?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(mi(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)})})},sr.prototype.bulkPut=function(v,_,M){var V=this,re=Array.isArray(_)?_:void 0,pe=(M=M||(re?void 0:_))?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(mi(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)})})},sr.prototype.bulkUpdate=function(v){var _=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===_.schema.primKey.keyPath){if(Ht(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(_.name,".bulkUpdate(): ").concat(He," of ").concat(Je," operations failed"),nt)})})})},sr.prototype.bulkDelete=function(v){var _=this,M=v.length;return this._trans("readwrite",function(V){return _.core.mutate({trans:V,type:"delete",keys:v}).then(function(re){return gn(_,v,re)})}).then(function(V){var re=V.numFailures,pe=V.failures;if(re===0)return V.lastResult;throw new Ie("".concat(_.name,".bulkDelete(): ").concat(re," of ").concat(M," operations failed"),pe)})};var ds=sr;function sr(){}function bn(v){function _(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={};_.addEventType=pe;for(var V=1,re=arguments.length;V<re;++V)pe(arguments[V]);return _;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]=_[Te]=Je;a(at=Te).forEach(function(Ge){var He=at[Ge];if(u(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 Ln(v,_){return P(_).from({prototype:v}),_}function Fn(v,_){return!(v.filter||v.algorithm||v.or)&&(_?v.justLimit:!v.replayFilter)}function Ui(v,_){v.filter=On(v.filter,_)}function Zn(v,_,M){var V=v.replayFilter;v.replayFilter=V?function(){return On(V(),_())}:_,v.justLimit=M&&!V}function ei(v,_){if(v.isPrimKey)return _.primaryKey;var M=_.getIndexByKeyPath(v.index);if(M)return M;throw new Me.Schema("KeyPath "+v.index+" on object store "+_.name+" is not indexed")}function Vi(v,_,M){var V=ei(v,_.schema);return _.openCursor({trans:M,values:!v.keysOnly,reverse:v.dir==="prev",unique:!!v.unique,query:{index:V,range:v.range}})}function vn(v,_,M,V){var re,pe,Te=v.replayFilter?On(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,_(Ne,We,at))},Promise.all([v.or._iterate(pe,M),hs(Vi(v,V,M),v.algorithm,pe,!v.keysOnly&&v.valueMapper)])):hs(Vi(v,V,M),On(v.algorithm,Te),_,!v.keysOnly&&v.valueMapper)}function hs(v,_,M,V){var re=Gt(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()};_&&!_(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,_){var M=this._ctx;return M.error?M.table._trans(null,dr.bind(null,M.error)):M.table._trans("readonly",v).then(_)},Qt.prototype._write=function(v){var _=this._ctx;return _.error?_.table._trans(null,dr.bind(null,_.error)):_.table._trans("readwrite",v,"locked")},Qt.prototype._addAlgorithm=function(v){var _=this._ctx;_.algorithm=On(_.algorithm,v)},Qt.prototype._iterate=function(v,_){return vn(this._ctx,v,_,this._ctx.table.core)},Qt.prototype.clone=function(v){var _=Object.create(this.constructor.prototype),M=Object.create(this._ctx);return v&&p(M,v),_._ctx=M,_},Qt.prototype.raw=function(){return this._ctx.valueMapper=null,this},Qt.prototype.each=function(v){var _=this._ctx;return this._read(function(M){return vn(_,v,M,_.table.core)})},Qt.prototype.count=function(v){var _=this;return this._read(function(M){var V,re=_._ctx,pe=re.table.core;return Fn(re,!0)?pe.count({trans:M,query:{index:ei(re,pe.schema),range:re.range}}).then(function(Te){return Math.min(Te,re.limit)}):(V=0,vn(re,function(){return++V,!1},M,pe).then(function(){return V}))}).then(v)},Qt.prototype.sortBy=function(v,_){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 Ht(pe(We,re),pe(at,re))*Te}return this.toArray(function(We){return We.slice().sort(Ne)}).then(_)},Qt.prototype.toArray=function(v){var _=this;return this._read(function(M){var V,re,pe,Te=_._ctx;return Fn(Te,!0)&&0<Te.limit?(V=Te.valueMapper,re=ei(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=[],vn(Te,function(Ne){return pe.push(Ne)},M,Te.table.core).then(function(){return pe}))},v)},Qt.prototype.offset=function(v){var _=this._ctx;return v<=0||(_.offset+=v,Fn(_)?Zn(_,function(){var M=v;return function(V,re){return M===0||(M===1?--M:re(function(){V.advance(M),M=0}),!1)}}):Zn(_,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),Zn(this._ctx,function(){var _=v;return function(M,V,re){return--_<=0&&V(re),0<=_}},!0),this},Qt.prototype.until=function(v,_){return Ui(this._ctx,function(M,V,re){return!v(M.value)||(V(re),_)}),this},Qt.prototype.first=function(v){return this.limit(1).toArray(function(_){return _[0]}).then(v)},Qt.prototype.last=function(v){return this.reverse().first(v)},Qt.prototype.filter=function(v){var _;return Ui(this._ctx,function(M){return v(M.value)}),(_=this._ctx).isMatch=On(_.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 _=this._ctx;return _.keysOnly=!_.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 _=this._ctx;return _.keysOnly=!_.isMatch,this.each(function(M,V){v(V.primaryKey,V)})},Qt.prototype.keys=function(v){var _=this._ctx,M=(_.keysOnly=!_.isMatch,[]);return this.each(function(V,re){M.push(re.key)}).then(function(){return M}).then(v)},Qt.prototype.primaryKeys=function(v){var _=this._ctx;if(Fn(_,!0)&&0<_.limit)return this._read(function(V){var re=ei(_,_.table.core.schema);return _.table.core.query({trans:V,values:!1,limit:_.limit,direction:_.dir==="prev"?"prev":void 0,query:{index:re,range:_.range}})}).then(function(V){return V.result}).then(v);_.keysOnly=!_.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(_){return _[0]}).then(v)},Qt.prototype.lastKey=function(v){return this.reverse().firstKey(v)},Qt.prototype.distinct=function(){var v,_=this._ctx,_=_.index&&_.table.schema.idxByName[_.index];return _&&_.multi&&(v={},Ui(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 _=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 gi(Ye,v)},Te=M.table.core,Je=Te.schema.primaryKey,Ne=Je.outbound,We=Je.extractKey,at=200,Je=_.db._options.modifyChunkSize,Ge=(Je&&(at=typeof Je=="object"?Je[Te.name]||Je["*"]||200:Je),[]),He=0,nt=[],Xe=v===ys;return _.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=[],_t=[],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||Ht(We(St),We(qt.value))===0?(_t.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 Wt in $t.failures)At.splice(parseInt(Wt),1);re(Ct.length,$t)})).then(function(){return(0<_t.length||lt&&typeof v=="object")&&Te.mutate({trans:V,type:"put",keys:Dt,values:_t,criteria:lt,changeSpec:typeof v!="function"&&v,isAdditionalChunk:0<ot}).then(function($t){return re(_t.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 gn(M.table,At,$t)}).then(function($t){return re(At.length,$t)})}).then(function(){return Ye.length>ot+ft&&Qe(ot+at)})})}var lt=Fn(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,_=v.range;return!Fn(v)||v.table.schema.yProps||!v.isPrimKey&&_.type!==3?this.modify(ys):this._write(function(M){var V=v.table.core.schema.primaryKey,re=_;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 Sn=Qt;function Qt(){}var ys=function(v,_){return _.value=null};function Ks(v,_){return v<_?-1:v===_?0:1}function bi(v,_){return _<v?-1:v===_?0:1}function Cr(v,_,M){return v=v instanceof Ki?new v.Collection(v):v,v._ctx.error=new(M||TypeError)(_),v}function qn(v){return new v.Collection(v,function(){return ms("")}).limit(0)}function vi(nt,_,M,V){var re,pe,Te,Ne,We,at,Je,Ge=M.length;if(!M.every(function(Ye){return typeof Ye=="string"}))return Cr(nt,yn);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"?Ks:bi;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 Tn(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(_(ft,We,Xe))return!0;for(var bt=null,Et=Xe;Et<Ge;++Et){var Ct=((_t,Dt,At,jt,St,qt)=>{for(var $t=Math.min(_t.length,jt.length),Wt=-1,Yt=0;Yt<$t;++Yt){var B=Dt[Yt];if(B!==jt[Yt])return St(_t[Yt],At[Yt])<0?_t.substr(0,Yt)+At[Yt]+At.substr(Yt+1):St(_t[Yt],jt[Yt])<0?_t.substr(0,Yt)+jt[Yt]+At.substr(Yt+1):0<=Wt?_t.substr(0,Wt)+Dt[Wt]+At.substr(Wt+1):null;St(_t[Yt],B)<0&&(Wt=Yt)}return $t<jt.length&&qt==="next"?_t+At.substr(_t.length):$t<_t.length&&qt==="prev"?_t.substr(0,At.length):Wt<0?null:_t.substr(0,Wt)+jt[Wt]+At.substr(Wt+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 Tn(v,_,M,V){return{type:2,lower:v,upper:_,lowerOpen:M,upperOpen:V}}function ms(v){return{type:1,lower:v,upper:v}}Object.defineProperty(vr.prototype,"Collection",{get:function(){return this._ctx.table.db.Collection},enumerable:!1,configurable:!0}),vr.prototype.between=function(v,_,M,V){M=M!==!1,V=V===!0;try{return 0<this._cmp(v,_)||this._cmp(v,_)===0&&(M||V)&&(!M||!V)?qn(this):new this.Collection(this,function(){return Tn(v,_,!M,!V)})}catch{return Cr(this,sn)}},vr.prototype.equals=function(v){return v==null?Cr(this,sn):new this.Collection(this,function(){return ms(v)})},vr.prototype.above=function(v){return v==null?Cr(this,sn):new this.Collection(this,function(){return Tn(v,void 0,!0)})},vr.prototype.aboveOrEqual=function(v){return v==null?Cr(this,sn):new this.Collection(this,function(){return Tn(v,void 0,!1)})},vr.prototype.below=function(v){return v==null?Cr(this,sn):new this.Collection(this,function(){return Tn(void 0,v,!1,!0)})},vr.prototype.belowOrEqual=function(v){return v==null?Cr(this,sn):new this.Collection(this,function(){return Tn(void 0,v)})},vr.prototype.startsWith=function(v){return typeof v!="string"?Cr(this,yn):this.between(v,v+nn,!0,!0)},vr.prototype.startsWithIgnoreCase=function(v){return v===""?this.startsWith(v):vi(this,function(_,M){return _.indexOf(M[0])===0},[v],nn)},vr.prototype.equalsIgnoreCase=function(v){return vi(this,function(_,M){return _===M[0]},[v],"")},vr.prototype.anyOfIgnoreCase=function(){var v=Y.apply(K,arguments);return v.length===0?qn(this):vi(this,function(_,M){return M.indexOf(_)!==-1},v,"")},vr.prototype.startsWithAnyOfIgnoreCase=function(){var v=Y.apply(K,arguments);return v.length===0?qn(this):vi(this,function(_,M){return M.some(function(V){return _.indexOf(V)===0})},v,nn)},vr.prototype.anyOf=function(){var v,_,M=this,V=Y.apply(K,arguments),re=this._cmp;try{V.sort(re)}catch{return Cr(this,sn)}return V.length===0?qn(this):((v=new this.Collection(this,function(){return Tn(V[0],V[V.length-1])}))._ondirectionchange=function(pe){re=pe==="next"?M._ascending:M._descending,V.sort(re)},_=0,v._addAlgorithm(function(pe,Te,Ne){for(var We=pe.key;0<re(We,V[_]);)if(++_===V.length)return Te(Ne),!1;return re(We,V[_])===0||(Te(function(){pe.continue(V[_])}),!1)}),v)},vr.prototype.notEqual=function(v){return this.inAnyRange([[-1/0,v],[v,this.db._maxKey]],{includeLowers:!1,includeUppers:!1})},vr.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 Cr(this,sn)}var _=v.reduce(function(M,V){return M?M.concat([[M[M.length-1][1],V]]):[[-1/0,V]]},null);return _.push([v[v.length-1],this.db._maxKey]),this.inAnyRange(_,{includeLowers:!1,includeUppers:!1})},vr.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 qn(this);if(!v.every(function(ot){return ot[0]!==void 0&&ot[1]!==void 0&&re(ot[0],ot[1])<=0}))return Cr(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&<.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 Cr(this,sn)}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 Tn(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},vr.prototype.startsWithAnyOf=function(){var v=Y.apply(K,arguments);return v.every(function(_){return typeof _=="string"})?v.length===0?qn(this):this.inAnyRange(v.map(function(_){return[_,_+nn]})):Cr(this,"startsWithAnyOf() only works with strings")};var Ki=vr;function vr(){}function Ir(v){return Gt(function(_){return En(_),v(_.target.error),!1})}function En(v){v.stopPropagation&&v.stopPropagation(),v.preventDefault&&v.preventDefault()}var $n="storagemutated",Wi="x-storagemutated-1",Xr=bn(null,$n),Ws=(Lr.prototype._lock=function(){return E(!xt.global),++this._reculock,this._reculock!==1||xt.global||(xt.lockOwnerFor=this),this},Lr.prototype._unlock=function(){if(E(!xt.global),--this._reculock==0)for(xt.global||(xt.lockOwnerFor=null);0<this._blockedFuncs.length&&!this._locked();){var v=this._blockedFuncs.shift();try{kr(v[1],v[0])}catch{}}return this},Lr.prototype._locked=function(){return this._reculock&&xt.lockOwnerFor!==this},Lr.prototype.create=function(v){var _=this;if(this.mode){var M=this.db.idbdb,V=this.db._state.dbOpenError;if(E(!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;E(this._completion._state===null),(v=this.idbtrans=v||(this.db.core||M).transaction(this.storeNames,this.mode,{durability:this.chromeTransactionDurability})).onerror=Gt(function(re){En(re),_._reject(v.error)}),v.onabort=Gt(function(re){En(re),_.active&&_._reject(new Me.Abort(v.error)),_.active=!1,_.on("abort").fire(re)}),v.oncomplete=Gt(function(){_.active=!1,_._resolve(),"mutatedParts"in v&&Xr.storagemutated.fire(v.mutatedParts)})}return this},Lr.prototype._promise=function(v,_,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,_,M).then(pe,Te)},xt])}):M?Kr(function(){var pe=new be(function(Te,Ne){re._lock();var We=_(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=_(pe,Te,re);Ne&&Ne.then&&Ne.then(pe,Te)}))._lib=!0,V):dr(new Me.TransactionInactive)},Lr.prototype._root=function(){return this.parent?this.parent._root():this},Lr.prototype.waitFor=function(v){var _,M=this._root(),V=be.resolve(v),re=(M._waitingFor?M._waitingFor=M._waitingFor.then(function(){return V}):(M._waitingFor=V,M._waitingQueue=[],_=M.idbtrans.objectStore(M.storeNames[0]),function pe(){for(++M._spinCount;M._waitingQueue.length;)M._waitingQueue.shift()();M._waitingFor&&(_.get(-1/0).onsuccess=pe)}()),M._waitingFor);return new be(function(pe,Te){V.then(function(Ne){return M._waitingQueue.push(Gt(pe.bind(null,Ne)))},function(Ne){return M._waitingQueue.push(Gt(Te.bind(null,Ne)))}).finally(function(){M._waitingFor===re&&(M._waitingFor=null)})})},Lr.prototype.abort=function(){this.active&&(this.active=!1,this.idbtrans&&this.idbtrans.abort(),this._reject(new Me.Abort))},Lr.prototype.table=function(v){var _=this._memoizedTables||(this._memoizedTables={});if(g(_,v))return _[v];var M=this.schema[v];if(M)return(M=new this.db.Table(v,M,this)).core=this.db.core.table(v),_[v]=M;throw new Me.NotFound("Table "+v+" not part of transaction")},Lr);function Lr(){}function Gi(v,_,M,V,re,pe,Te,Ne){return{name:v,keyPath:_,unique:M,multi:V,auto:re,compound:pe,src:(M&&!Te?"&":"")+(V?"*":"")+(re?"++":"")+zi(_),type:Ne}}function zi(v){return typeof v=="string"?v:v?"["+[].join.call(v,"+")+"]":""}function It(v,_,M){return{name:v,primKey:_,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 ti=function(v){try{return v.only([[]]),ti=function(){return[[]]},[[]]}catch{return ti=function(){return nn},nn}};function Si(v){return v==null?function(){}:typeof v=="string"?(_=v).split(".").length===1?function(M){return M[_]}:function(M){return R(M,_)}:function(M){return R(M,v)};var _}function gs(v){return[].slice.call(v)}var Gs=0;function ri(v){return v==null?":id":typeof v=="string"?v:"[".concat(v.join("+"),"]")}function zs(v,_,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:_.upperBound(Xe,!!Qe):Xe===void 0?_.lowerBound(nt,!!Ye):_.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,_t){Ct=Gt(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,En(tt)}var Wt=[],Yt=[],B=0;if(ot==="deleteRange"){if(Et.type===4)return Ct({numFailures:B,failures:Yt,results:[],lastResult:void 0});Et.type===3?Wt.push(St=Dt.clear()):Wt.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)Wt.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)Wt.push(St=Dt[ot](k[ie])),St.onerror=$t}function ke(tt){tt=tt.target.result,Wt.forEach(function(Nt,cr){return Nt.error!=null&&(Yt[cr]=Nt.error)}),Ct({numFailures:B,failures:Yt,results:ot==="delete"?ft:Wt.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=Gt(ft);for(var Et,Ct=lt.objectStore(Ye),_t=ot.length,Dt=new Array(_t),At=0,jt=0,St=function(Wt){Wt=Wt.target,Dt[Wt._pos]=Wt.result,++jt===At&&ft(Dt)},qt=Ir(bt),$t=0;$t<_t;++$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=Gt(ft);var Et=lt.objectStore(Ye).get(ot);Et.onsuccess=function(Ct){return ft(Ct.target.result)},Et.onerror=Ir(bt)})},query:(nt=We,Xe=at,function(Qe){return new Promise(function(lt,ot){lt=Gt(lt);var ft,bt,Et,Ct,qt=Qe.trans,_t=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=_t?qt.getAll(St):qt.getAllKeys(St)).onsuccess=function(Wt){return lt({result:Wt.target.result})},ft.onerror=Ir(ot)):nt&&At==="next"?((ft=_t?qt.getAll($t,jt):qt.getAllKeys($t,jt)).onsuccess=function(Wt){return lt({result:Wt.target.result})},ft.onerror=Ir(ot)):(bt=0,Et=!_t&&"openKeyCursor"in qt?qt.openKeyCursor($t,At):qt.openCursor($t,At),Ct=[],Et.onsuccess=function(){var Wt=Et.result;return!Wt||(Ct.push(_t?Wt.value:Wt.primaryKey),++bt===Dt)?lt({result:Ct}):void Wt.continue()},Et.onerror=Ir(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,_t){Ct=Gt(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=Ir(_t),St.onsuccess=Gt(function(qt){var $t,Wt,Yt,B,k=St.result;k?(k.___id=++Gs,k.done=!1,$t=k.continue.bind(k),Wt=(Wt=k.continuePrimaryKey)&&Wt.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=Gt(_t),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=Gt(tt),St.onerror=Ir(Nt),k.fail=Nt,k.stop=function(cr){k.stop=k.continue=k.continuePrimaryKey=k.advance=B,tt(cr)}});return St.onsuccess=Gt(function(tt){St.onsuccess=ie,ie()}),k.continue=$t,k.continuePrimaryKey=Wt,k.advance=Yt,ie(),ke},Ct(k)):Ct(null)},_t)})},count:function(Qe){var lt=Qe.query,ot=Qe.trans,ft=lt.index,bt=lt.range;return new Promise(function(Et,Ct){var _t=ot.objectStore(Ye),_t=ft.isPrimaryKey?_t:_t.index(ft.name),Dt=V(bt),Dt=Dt?_t.count(Dt):_t.count();Dt.onsuccess=Gt(function(At){return Et(At.target.result)}),Dt.onerror=Ir(Ct)})}}}pe=Te,Ne=gs((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=u(nt),Ye={},Qe={name:He.name,primaryKey:{name:null,isPrimaryKey:!0,outbound:nt==null,compound:Qe,keyPath:nt,autoIncrement:Xe,unique:!0,extractKey:Si(nt)},indexes:gs(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:u(bt),keyPath:bt,unique:ot,multiEntry:ft,extractKey:Si(bt)};return Ye[ri(bt)]=Et}),getIndexByKeyPath:function(lt){return Ye[ri(lt)]}};return Ye[":id"]=Qe.primaryKey,nt!=null&&(Ye[ri(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:ti(_),schema:Ne}}function bs(v,_,M,V){return M=M.IDBKeyRange,_=zs(_,M,V),{dbcore:v.dbcore.reduce(function(re,pe){return pe=pe.create,n(n({},re),pe(re))},_)}}function Ti(v,_){var M=_.db,M=bs(v._middlewares,M,v._deps,_);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 ni(v,_,M,V){M.forEach(function(re){var pe=V[re];_.forEach(function(Te){var Ne=function We(at,Je){return A(at,Je)||(at=y(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 Ei(v,_){_.forEach(function(M){for(var V in M)M[V]instanceof v.Table&&delete M[V]})}function Hs(v,_){return v._cfg.version-_._cfg.version}function Js(v,_,M,V){var re=v._dbSchema,pe=(M.objectStoreNames.contains("$meta")&&!re.$meta&&(re.$meta=It("$meta",Ss("")[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;Kr(function(){if(xt.trans=pe,xt.transless=Ne,_!==0)return Ti(v,M),at=_,((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=Pi(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,_t=ot._cfg.dbschema,Dt=(Un(Ge,Ct,Xe),Un(Ge,_t,Xe),lt=Ge._dbSchema=_t,xi(Ct,_t)),At=(Dt.add.forEach(function(jt){Hi(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 _i(St,qt)}),jt.change.forEach(function(qt){St.deleteIndex(qt.name),_i(St,qt)}),jt.del.forEach(function(qt){return St.deleteIndex(qt)})}),ot._cfg.contentUpgrade);if(At&&ot._cfg.version>He)return Ti(Ge,Xe),nt._memoizedTables={},ft=D(_t),Dt.del.forEach(function(jt){ft[jt]=Ct[jt]}),Ei(Ge,[Ge.Transaction.prototype]),ni(Ge,[Ge.Transaction.prototype],a(ft),ft),nt.schema=ft,(bt=he(At))&&rn(),_t=be.follow(function(){var jt;(Et=At(nt))&&bt&&(jt=jr.bind(null,null),Et.then(jt,jt))}),Et&&typeof Et.then=="function"?be.resolve(Et):_t.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(_t){return bt[_t]==null&&Et.db.deleteObjectStore(_t)}),Ei(Ge,[Ge.Transaction.prototype]),ni(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(){Ji(lt,Xe)}))}).catch(Te);var We,at;a(re).forEach(function(Je){Hi(M,Je,re[Je].primKey,re[Je].indexes)}),Ti(v,M),be.follow(function(){return v.on.populate.fire(pe)}).catch(Te)})}function vs(v,_){Ji(v._dbSchema,_),_.db.version%10!=0||_.objectStoreNames.contains("$meta")||_.db.createObjectStore("$meta").add(Math.ceil(_.db.version/10-1),"version");var M=Pi(0,v.idbdb,_);Un(v,v._dbSchema,_);for(var V=0,re=xi(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=_.objectStore(Te.name);Te.add.forEach(function(We){ht&&console.debug("Dexie upgrade patch: Creating missing index ".concat(Te.name,".").concat(We.src)),_i(Ne,We)})})(re[V]);if(typeof pe=="object")return pe.value}}function xi(v,_){var M,V={del:[],add:[],change:[]};for(M in v)_[M]||V.del.push(M);for(M in _){var re=v[M],pe=_[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 Hi(v,_,M,V){var re=v.db.createObjectStore(_,M.keyPath?{keyPath:M.keyPath,autoIncrement:M.auto}:{autoIncrement:M.auto});V.forEach(function(pe){return _i(re,pe)})}function Ji(v,_){a(v).forEach(function(M){_.db.objectStoreNames.contains(M)||(ht&&console.debug("Dexie: Creating missing table",M),Hi(_,M,v[M].primKey,v[M].indexes))})}function _i(v,_){v.createIndex(_.name,_.keyPath,{unique:_.unique,multiEntry:_.multi})}function Pi(v,_,M){var V={};return T(_.objectStoreNames,0).forEach(function(re){for(var pe=M.objectStore(re),Te=Gi(zi(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=Gi(Je.name,at,!!Je.unique,!!Je.multiEntry,!1,at&&typeof at!="string",!1);Ne.push(Je)}V[re]=It(re,Te,Ne)}),V}function Un(v,_,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:"["+T(Je).join("+")+"]";_[pe]&&(We=_[pe].idxByName[Je])&&(We.name=at,delete _[pe].idxByName[Je],_[pe].idxByName[at]=We)}}typeof navigator<"u"&&/Safari/.test(navigator.userAgent)&&!/(Chrome\/|Edge\/)/.test(navigator.userAgent)&&o.WorkerGlobalScope&&o instanceof o.WorkerGlobalScope&&[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]<604&&(v._hasGetAll=!1)}function Ss(v){return v.split(",").map(function(_,M){var re=_.split(":"),V=(V=re[1])==null?void 0:V.trim(),re=(_=re[0].trim()).replace(/([&*]|\+\+)/g,""),pe=/^\[/.test(re)?re.match(/^\[(.*)\]$/)[1].split("+"):re;return Gi(re,pe||null,/\&/.test(_),/\*/.test(_),/\+\+/.test(_),u(pe),M===0,V)})}xn.prototype._createTableSchema=It,xn.prototype._parseIndexSyntax=Ss,xn.prototype._parseStoresSpec=function(v,_){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),_[V]=pe}})},xn.prototype.stores=function(M){var _=this.db,M=(this._cfg.storesSource=this._cfg.storesSource?p(this._cfg.storesSource,M):M,_._versions),V={},re={};return M.forEach(function(pe){p(V,pe._cfg.storesSource),re=pe._cfg.dbschema={},pe._parseStoresSpec(V,re)}),_._dbSchema=re,Ei(_,[_._allTables,_,_.Transaction.prototype]),ni(_,[_._allTables,_,_.Transaction.prototype,this._cfg.tables],a(re),re),_._storeNames=a(re),this},xn.prototype.upgrade=function(v){return this._cfg.contentUpgrade=gt(this._cfg.contentUpgrade||Ze,v),this};var Ys=xn;function xn(){}var ii=(()=>{var v,_,M;return typeof FinalizationRegistry<"u"&&typeof WeakRef<"u"?(v=new Set,_=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),_.register(V._novip,re,re),v.size>V._options.maxConnections&&(re=v.values().next().value,v.delete(re),_.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 _.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 Yi(v,_){var M=v._dbNamesDB;return M||(M=v._dbNamesDB=new Qr(Gr,{addons:[],indexedDB:v,IDBKeyRange:_})).version(1).stores({dbnames:"name"}),M.table("dbnames")}function wi(v){return v&&typeof v.databases=="function"}function Xi(v){return Kr(function(){return xt.letThrough=!0,v()})}function Qi(v){return!("from"in v)}var Er=function(v,_){var M;if(!this)return M=new Er,v&&"d"in v&&p(M,v),M;p(this,arguments.length?{d:1,from:v,to:1<arguments.length?_:v}:{d:0})};function si(v,_,M){var V=Ht(_,M);if(!isNaN(V)){if(0<V)throw RangeError();if(Qi(v))return p(v,{from:_,to:M,d:1});var V=v.l,re=v.r;if(Ht(M,v.from)<0)return V?si(V,_,M):v.l={from:_,to:M,d:1,l:null,r:null},z(v);if(0<Ht(_,v.to))return re?si(re,_,M):v.r={from:_,to:M,d:1,l:null,r:null},z(v);Ht(_,v.from)<0&&(v.from=_,v.l=null,v.d=re?re.d+1:1),0<Ht(M,v.to)&&(v.to=M,v.r=null,v.d=v.l?v.l.d+1:1),_=!v.r,V&&!v.l&&an(v,V),re&&_&&an(v,re)}}function an(v,_){Qi(_)||function M(V,re){var pe=re.from,Te=re.l,Ne=re.r;si(V,pe,re.to),Te&&M(V,Te),Ne&&M(V,Ne)}(v,_)}function Zi(v,_){var M=Ai(_),V=M.next();if(!V.done)for(var re=V.value,pe=Ai(v),Te=pe.next(re.from),Ne=Te.value;!V.done&&!Te.done;){if(Ht(Ne.from,re.to)<=0&&0<=Ht(Ne.to,re.from))return!0;Ht(re.from,Ne.from)<0?re=(V=M.next(Ne.from)).value:Ne=(Te=pe.next(re.from)).value}return!1}function Ai(v){var _=Qi(v)?null:{s:0,n:v};return{next:function(M){for(var V=0<arguments.length;_;)switch(_.s){case 0:if(_.s=1,V)for(;_.n.l&&Ht(M,_.n.from)<0;)_={up:_,n:_.n.l,s:1};else for(;_.n.l;)_={up:_,n:_.n.l,s:1};case 1:if(_.s=2,!V||Ht(M,_.n.to)<=0)return{value:_.n,done:!1};case 2:if(_.n.r){_.s=3,_={up:_,n:_.n.r,s:0};continue}case 3:_=_.up}return{done:!0}}}}function z(v){var _,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&&(_=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[_],(v[_]=M).d=l(M)),v.d=l(v)}function l(M){var _=M.r,M=M.l;return(_?M?Math.max(_.d,M.d):_.d:M?M.d:0)+1}function i(v,_){return a(_).forEach(function(M){v[M]?an(v[M],_[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}(_[M])}),v}function c(v,_){return v.all||_.all||Object.keys(v).some(function(M){return _[M]&&Zi(_[M],v[M])})}b(Er.prototype,((oe={add:function(v){return an(this,v),this},addKey:function(v){return si(this,v,v),this},addKeys:function(v){var _=this;return v.forEach(function(M){return si(_,M,M)}),this},hasKey:function(v){var _=Ai(this).next(v).value;return _&&Ht(_.from,v)<=0&&0<=Ht(_.to,v)}})[Ae]=function(){return Ai(this)},oe));var d={},w={},Q=!1;function le(v){i(w,v),Q||(Q=!0,setTimeout(function(){Q=!1,_e(w,!(w={}))},0))}function _e(v,_){_===void 0&&(_=!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,_);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,_)}M.forEach(function(We){return We()})}function Be(v,_,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];c(_,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 _=v._state,M=v._deps.indexedDB;if(_.isBeingOpened||v.idbdb)return _.dbReadyPromise.then(function(){return _.dbOpenError?dr(_.dbOpenError):v});_.isBeingOpened=!0,_.dbOpenError=null,_.openComplete=!1;var V=_.openCanceller,re=Math.round(10*v.verno),pe=!1;function Te(){if(_.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=_.autoSchema||!re?M.open(Xe):M.open(Xe,re);if(!Ye)throw new Me.MissingAPI;Ye.onerror=Ir(nt),Ye.onblocked=Gt(v._fireOnBlocked),Ye.onupgradeneeded=Gt(function(Qe){var lt;Je=Ye.transaction,_.autoSchema&&!v._options.allowEmptyDB?(Ye.onerror=En,Je.abort(),Ye.result.close(),(lt=M.deleteDatabase(Xe)).onsuccess=lt.onerror=Gt(function(){nt(new Me.NoSuchDatabase("Database ".concat(Xe," doesnt exist")))})):(Je.onerror=Ir(nt),lt=Qe.oldVersion>Math.pow(2,62)?0:Qe.oldVersion,Ge=lt<1,v.idbdb=Ye.result,pe&&vs(v,Je),Js(v,lt/10,Je,nt))},nt),Ye.onsuccess=Gt(function(){Je=null;var Qe,lt,ot,ft,bt,Et,Ct=v.idbdb=Ye.result,_t=T(Ct.objectStoreNames);if(0<_t.length)try{var Dt=Ct.transaction((bt=_t).length===1?bt[0]:bt,"readonly");if(_.autoSchema)Et=Ct,ft=Dt,(ot=v).verno=Et.version/10,ft=ot._dbSchema=Pi(0,Et,ft),ot._storeNames=T(Et.objectStoreNames,0),ni(ot,[ot._allTables],a(ft),ft);else if(Un(v,v._dbSchema,Dt),lt=Dt,((lt=xi(Pi(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());Ti(v,Dt)}catch{}ii.add(v),Ct.onversionchange=Gt(function(At){_.vcFired=!0,v.on("versionchange").fire(At)}),Ct.onclose=Gt(function(){v.close({disableAutoOpen:!1})}),Ge&&(_t=v._deps,bt=Xe,wi(Et=_t.indexedDB)||bt===Gr||Yi(Et,_t.IDBKeyRange).put({name:bt}).catch(Ze)),He()},nt)}).catch(function(He){switch(He==null?void 0:He.name){case"UnknownError":if(0<_.PR1398_maxLoop)return _.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=_.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(),_.onReadyBeingFired=[],be.resolve(Xi(function(){return v.on.ready.fire(v.vip)})).then(function He(){var nt;if(0<_.onReadyBeingFired.length)return nt=_.onReadyBeingFired.reduce(gt,Ze),_.onReadyBeingFired=[],be.resolve(Xi(function(){return nt(v.vip)})).then(He)})}).finally(function(){_.openCanceller===V&&(_.onReadyBeingFired=null,_.isBeingOpened=!1)}).catch(function(He){_.dbOpenError=He;try{Je&&Je.abort()}catch{}return V===_.openCanceller&&v._close(),dr(He)}).finally(function(){_.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 Er(-1/0,[[[]]]))}),He["idb://".concat(v.name,"/").concat(nt.name,"/")]=He["idb://".concat(v.name,"/").concat(nt.name,"/:dels")]=new Er(-1/0,[[[]]])}),Xr($n).fire(He),_e(He,!0)),v})}function ct(v){function _(pe){return v.next(pe)}var M=re(_),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):u(We)?Promise.all(We).then(M,V):M(We)}}return re(_)()}function vt(v,_,M){for(var V=u(v)?v.slice():[v],re=0;re<M;++re)V.push(_);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=ri(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:Si(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[ri(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,_,M,V){return M=M||{},V=V||"",a(v).forEach(function(re){var pe,Te,Ne;g(_,re)?(pe=v[re],Te=_[re],typeof pe=="object"&&typeof Te=="object"&&pe&&Te?(Ne=Ce(pe))!==Ce(Te)?M[V+re]=_[re]:Ne==="Object"?Ot(pe,Te,M,V+re+"."):pe!==Te&&(M[V+re]=_[re]):pe!==Te&&(M[V+re]=_[re])):M[V+re]=void 0}),a(_).forEach(function(re){g(v,re)||(M[V+re]=_[re])}),M}function zt(v,_){return _.type==="delete"?_.keys:_.keys||_.values.map(v.extractKey)}var or={stack:"dbcore",name:"HooksMiddleware",level:2,create:function(v){return n(n({},v),{table:function(_){var M=v.table(_),V=M.schema.primaryKey;return n(n({},M),{mutate:function(re){var pe=xt.trans,Te=pe.table(_).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||zt(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,_t,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))&&(_t=Ge.values[bt],Object.keys(Ct).forEach(function(jt){g(_t,jt)?_t[jt]=Ct[jt]:I(_t,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,_t=0;_t<Qe.length;++_t){var Dt=(Et||Qe)[_t],At=ot[_t];Dt==null?At.onerror&&At.onerror(bt[_t]):At.onsuccess&&At.onsuccess(Ge.type==="put"&<[_t]?Ge.values[_t]: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,_,M){try{if(!_||_.keys.length<v.length)return null;for(var V=[],re=0,pe=0;re<_.keys.length&&pe<v.length;++re)Ht(_.keys[re],v[pe])===0&&(V.push(M?ne(_.values[re]):_.values[re]),++pe);return V.length===v.length?V:null}catch{return null}}var ar={stack:"dbcore",level:-1,create:function(v){return{table:function(_){var M=v.table(_);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 _n(v,_){return v.trans.mode==="readonly"&&!!v.subscr&&!v.trans.explicit&&v.trans.db._options.cache!=="disabled"&&!_.schema.primaryKey.outbound}function on(v,_){switch(v){case"query":return _.values&&!_.unique;case"get":case"getMany":case"count":case"openCursor":return!1}}var Ts={stack:"dbcore",level:0,name:"Observability",create:function(v){var _=v.schema.name,M=new Er(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 Er((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(_,"/").concat(V,"/").concat(St),bt[St]||(bt[St]=new Er)}var Qe,lt,ot,ft=Xe.trans,bt=Xe.mutatedParts||(Xe.mutatedParts={}),Et=Ye(""),Ct=Ye(":dels"),_t=Xe.type,At=Xe.type==="deleteRange"?[Xe.range]:Xe.type==="delete"?[Xe.keys]:Xe.values.length<50?[zt(Ne,Xe).filter(function(St){return St}),Xe.values]:[],Dt=At[0],At=At[1],jt=Xe.trans._cache;return u(Dt)?(Et.addKeys(Dt),(_t=_t==="delete"||Dt.length===At.length?Ft(Dt,jt):null)||Ct.addKeys(Dt),(_t||At)&&(Qe=Ye,lt=_t,ot=At,Te.indexes.forEach(function(St){var qt=Qe(St.name||"");function $t(Yt){return Yt!=null?St.extractKey(Yt):null}function Wt(Yt){St.multiEntry&&u(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]);Ht(k,F)!==0&&(k!=null&&Wt(k),F!=null)&&Wt(F)})}))):Dt?(At={from:(jt=Dt.lower)!=null?jt:v.MIN_KEY,to:(_t=Dt.upper)!=null?_t: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)}),Wt=qt.keyPath.findIndex(function(k){return k===Ne.keyPath}),Yt=0,B=St.results.length;Yt<B;++Yt)$t[Yt][Wt]=St.results[Yt];Ye(qt.name).addKeys($t)})),ft.mutatedParts=i(ft.mutatedParts||{},bt),St})}}),nt={get:function(Xe){return[Ne,new Er(Xe.key)]},getMany:function(Xe){return[Ne,new Er().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=_n(xt,pe)&&on(Xe,Ye)?Ye.obsSet={}:Qe;if(lt){var ft,Qe=function(At){return At="idb://".concat(_,"/").concat(V,"/").concat(At),ot[At]||(ot[At]=new Er)},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 es(v,_,M){var V;return M.numFailures===0?_:_.type==="deleteRange"||(V=_.keys?_.keys.length:"values"in _&&_.values?_.values.length:1,M.numFailures===V)?null:(V=n({},_),u(V.keys)&&(V.keys=V.keys.filter(function(re,pe){return!(pe in M.failures)})),"values"in V&&u(V.values)&&(V.values=V.values.filter(function(re,pe){return!(pe in M.failures)})),V)}function Ci(v,_){return M=v,((V=_).lower===void 0||(V.lowerOpen?0<Ht(M,V.lower):0<=Ht(M,V.lower)))&&(M=v,(V=_).upper===void 0||(V.upperOpen?Ht(M,V.upper)<0:Ht(M,V.upper)<=0));var M,V}function ts(v,_,M,V,re,pe){var Te,Ne,We,at,Je,Ge,He;return!M||M.length===0||(Te=_.query.index,Ne=Te.multiEntry,We=_.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 Er,ot=Xe.values.length-1;0<=ot;--ot){var ft,bt=Xe.values[ot],Et=at(bt);!lt.hasKey(Et)&&(ft=Je(bt),Ne&&u(ft)?ft.some(function(jt){return Ci(jt,We)}):Ci(ft,We))&&(lt.addKey(Et),Qe.push(bt))}switch(Xe.type){case"add":var Ct=new Er().addKeys(_.values?nt.map(function(St){return at(St)}):nt),Ye=nt.concat(_.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 _t=new Er().addKeys(Xe.values.map(function(St){return at(St)}));Ye=nt.filter(function(St){return!_t.hasKey(_.values?at(St):St)}).concat(_.values?Qe:Qe.map(function(St){return at(St)}));break;case"delete":var Dt=new Er().addKeys(Xe.keys);Ye=nt.filter(function(St){return!Dt.hasKey(_.values?at(St):St)});break;case"deleteRange":var At=Xe.range;Ye=nt.filter(function(St){return!Ci(at(St),At)})}return Ye},v))===v)?v:(He=function(nt,Xe){return Ht(Ge(nt),Ge(Xe))||Ht(at(nt),at(Xe))},V.sort(_.direction==="prev"||_.direction==="prevunique"?function(nt,Xe){return He(Xe,nt)}:He),_.limit&&_.limit<1/0&&(V.length>_.limit?V.length=_.limit:v.length===_.limit&&V.length<_.limit&&(re.dirty=!0)),pe?Object.freeze(V):V)}function rs(v,_){return Ht(v.lower,_.lower)===0&&Ht(v.upper,_.upper)===0&&!!v.lowerOpen==!!_.lowerOpen&&!!v.upperOpen==!!_.upperOpen}function Es(v,_){return((M,V,re,pe)=>{if(M===void 0)return V!==void 0?-1:0;if(V===void 0)return 1;if((M=Ht(M,V))===0){if(re&&pe)return 0;if(re)return 1;if(pe)return-1}return M})(v.lower,_.lower,v.lowerOpen,_.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=Ht(M,V))===0){if(re&&pe)return 0;if(re)return-1;if(pe)return 1}return M})(v.upper,_.upper,v.upperOpen,_.upperOpen)}function xs(v,_,M,V){v.subscribers.add(M),V.addEventListener("abort",function(){var re,pe;v.subscribers.delete(M),v.subscribers.size===0&&(re=v,pe=_,setTimeout(function(){re.subscribers.size===0&&ue(pe,re)},3e3))})}var _s={stack:"dbcore",level:0,name:"Cache",create:function(v){var _=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(_,"/").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++)c((_t=ft[ot]).obsSet,Ne.mutatedParts)&&(ue(Ct,_t),_t.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,_t,Dt,At=0,jt=(Ct=Et[bt]).slice();At<jt.length;At++)(_t=jt[At]).res!=null&&Ne.mutatedParts&&(We&&!_t.dirty?(Dt=Object.isFrozen(_t.res),Dt=ts(_t.res,_t.req,Ye,Xe,_t,Dt),_t.dirty?(ue(Ct,_t),_t.subscribers.forEach(function(St){return at.add(St)})):Dt!==_t.res&&(_t.res=Dt,_t.promise=be.resolve({result:Dt}))):(_t.dirty&&ue(Ct,_t),_t.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(_,"/").concat(M)])?(Ne=V.mutate(pe),pe.type!=="add"&&pe.type!=="put"||!(50<=pe.values.length||zt(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=es(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=es(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 _n(xt,V)&&on("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&&rs(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)&&Es(Et.req.query.range,Qe.query.range)}),!1,lt,ot];case"count":return bt=ot.find(function(Et){return rs(Et.req.query.range,Qe.query.range)}),[bt,!!bt,lt,ot]}})(_,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(_,"/").concat(M)]={queries:{query:{},count:{}},objs:new Map,optimisticOps:[],unsignaledParts:{}})).queries.query[pe.query.index.name||""]=Je)),xs(He,Je,Ne,We),He.promise.then(function(nt){return nt=ts(nt.result,pe,at==null?void 0:at.optimisticOps,V,He,Te),{result:Te?nt:ne(nt)}})):V.query(pe)}})}})}};function ai(v,_){return new Proxy(v,{get:function(M,V,re){return V==="db"?_: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 _=this._versions,M=_.filter(function(V){return V._cfg.version===v})[0];return M||(M=new this.Version(v),_.push(M),_.sort(Hs),M.stores({}),this._state.autoSchema=!1),M},hr.prototype._whenReady=function(v){var _=this;return this.idbdb&&(this._state.openComplete||xt.letThrough||this._vip)?v():new be(function(M,V){if(_._state.openComplete)return V(new Me.DatabaseClosed(_._state.dbOpenError));if(!_._state.isBeingOpened){if(!_._state.autoOpen)return void V(new Me.DatabaseClosed);_.open().catch(Ze)}_._state.dbReadyPromise.then(M,V)}).then(v)},hr.prototype.use=function(re){var _=re.stack,M=re.create,V=re.level,re=re.name,pe=(re&&this.unuse({stack:_,name:re}),this._middlewares[_]||(this._middlewares[_]=[]));return pe.push({stack:_,create:M,level:V??10,name:re}),pe.sort(function(Te,Ne){return Te.level-Ne.level}),this},hr.prototype.unuse=function(v){var _=v.stack,M=v.name,V=v.create;return _&&this._middlewares[_]&&(this._middlewares[_]=this._middlewares[_].filter(function(re){return V?re.create!==V:!!M&&re.name!==M})),this},hr.prototype.open=function(){var v=this;return kr(pt,function(){return Ue(v)})},hr.prototype._close=function(){this.on.close.fire(new CustomEvent("close"));var v=this._state;if(ii.remove(this),this.idbdb){try{this.idbdb.close()}catch{}this.idbdb=null}v.isBeingOpened||(v.dbReadyPromise=new be(function(_){v.dbReadyResolve=_}),v.openCanceller=new be(function(_,M){v.cancelOpen=M}))},hr.prototype.close=function(_){var _=(_===void 0?{disableAutoOpen:!0}:_).disableAutoOpen,M=this._state;_?(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 _=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(){_.close(v);var Ne=_._deps.indexedDB.deleteDatabase(_.name);Ne.onsuccess=Gt(function(){var We,at,Je;We=_._deps,at=_.name,wi(Je=We.indexedDB)||at===Gr||Yi(Je,We.IDBKeyRange).delete(at).catch(Ze),re()}),Ne.onerror=Ir(pe),Ne.onblocked=_._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(_){return v._allTables[_]})},enumerable:!1,configurable:!0}),hr.prototype.transaction=function(){var v=(function(_,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(),[_,J(pe),V]}).apply(this,arguments);return this._transaction.apply(this,v)},hr.prototype._transaction=function(v,_,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=_.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===mn)V=mn;else{if(v!="rw"&&v!=qi)throw new Me.InvalidArgument("Invalid transaction mode: "+v);V=qi}if(Te){if(Te.mode===mn&&V===qi){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&&rn(),be.follow(function(){var ft;(Qe=Xe.call(Ye,Ye))&&(lt?(ft=jr.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?kr(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 Qr=hr;function hr(v,_){var M,V,re,pe,Te,Ne=this,We=(this._middlewares={},this.verno=0,hr.dependencies),We=(this._options=_=n({addons:hr.addons,autoOpen:!0,indexedDB:We.indexedDB,IDBKeyRange:We.IDBKeyRange,cache:"cloned",maxConnections:1e3},_),this._deps={indexedDB:_.indexedDB,IDBKeyRange:_.IDBKeyRange},_.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:_.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=bn(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,Ln(Sn.prototype,function(Qe,Ye){this.db=M;var nt=us,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,Ln(ds.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:bn(null,{creating:[$e,Ze],reading:[st,ut],updating:[qe,Ze],deleting:[je,Ze]})})),this.Transaction=(re=this,Ln(Ws.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=bn(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,Ln(Ys.prototype,function(Ge){this.db=pe,this._cfg={version:Ge,storesSource:null,dbschema:{},tables:{},contentUpgrade:null}})),this.WhereClause=(Te=this,Ln(Ki.prototype,function(Ge,He,nt){if(this.db=Te,this._ctx={table:Ge,index:He===":id"?null:He,or:nt},this._cmp=this._ascending=Ht,this._descending=function(Xe,Ye){return Ht(Ye,Xe)},this._max=function(Xe,Ye){return 0<Ht(Xe,Ye)?Xe:Ye},this._min=function(Xe,Ye){return Ht(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=ti(_.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),ii.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(ar),this.use(_s),this.use(Ts),this.use(wt),this.use(or),new Proxy(this,{get:function(Ge,He,nt){var Xe;return He==="_vip"||(He==="table"?function(Ye){return ai(Ne.table(Ye),Je)}:(Xe=Reflect.get(Ge,He,nt))instanceof ds?ai(Xe,Je):He==="tables"?Xe.map(function(Ye){return ai(Ye,Je)}):He==="_createTransaction"?function(){return ai(Xe.apply(this,arguments),Je)}:Xe)}}));this.vip=Je,We.forEach(function(Ge){return Ge(Ne)})}var oi,Nn=typeof Symbol<"u"&&"observable"in Symbol?Symbol.observable:"@@observable",Ps=(Ii.prototype.subscribe=function(v,_,M){return this._subscribe(v&&typeof v!="function"?v:{next:v,error:_,complete:M})},Ii.prototype[Nn]=function(){return this},Ii);function Ii(v){this._subscribe=v}try{oi={indexedDB:o.indexedDB||o.mozIndexedDB||o.webkitIndexedDB||o.msIndexedDB,IDBKeyRange:o.IDBKeyRange||o.webkitIDBKeyRange}}catch{oi={indexedDB:null,IDBKeyRange:null}}function ns(v){var _,M=!1,V=new Ps(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&&Xr.storagemutated.unsubscribe(Xe))}},Ge=(re.start&&re.start(Je),!1),He=function(){return yi(Ye)};function nt(){return c(at,We)}var Xe=function(Qe){i(We,Qe),nt()&&He()},Ye=function(){var Qe,lt,ot;!Ne&&oi.indexedDB&&(We={},Qe={},Te&&Te.abort(),Te=new AbortController,ot=(ft=>{var bt=Kt();try{pe&&rn();var Et=Kr(v,ft);return Et=pe?Et.finally(jr):Et}finally{bt&&Jt()}})(lt={subscr:Qe,signal:Te.signal,requery:He,querier:v,trans:null}),Ge||(Xr.storagemutated.subscribe(Xe),Ge=!0),Promise.resolve(ot).then(function(ft){M=!0,_=ft,Ne||lt.signal.aborted||(nt()||(at=Qe,nt())?He():(We={},yi(function(){return!Ne&&re.next&&re.next(ft)})))},function(ft){M=!1,["DatabaseClosedError","AbortError"].includes(ft==null?void 0:ft.name)||Ne||yi(function(){Ne||re.error&&re.error(ft)})}))};return setTimeout(He,0),Je});return V.hasValue=function(){return M},V.getValue=function(){return _},V}var Pn=Qr;function Oi(v){var _=ln;try{ln=!0,Xr.storagemutated.fire(v),_e(v,!0)}finally{ln=_}}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(_){return _.close(),!0}).catch("NoSuchDatabaseError",function(){return!1})},getDatabaseNames:function(v){try{return _=Pn.dependencies,M=_.indexedDB,_=_.IDBKeyRange,(wi(M)?Promise.resolve(M.databases()).then(function(V){return V.map(function(re){return re.name}).filter(function(re){return re!==Gr})}):Yi(M,_).toCollection().primaryKeys()).then(v)}catch{return dr(new Me.MissingAPI)}var _,M},defineClass:function(){return function(v){p(this,v)}},ignoreTransaction:function(v){return xt.trans?kr(xt.transless||pt,v):v()},vip:Xi,async:function(v){return function(){try{var _=ct(v.apply(this,arguments));return _&&typeof _.then=="function"?_:be.resolve(_)}catch(M){return dr(M)}}},spawn:function(v,_,M){try{var V=ct(v.apply(M,_||[]));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,_){return v=be.resolve(typeof v=="function"?Pn.ignoreTransaction(v):v).timeout(_||6e4),xt.trans?xt.trans.waitFor(v):v},Promise:be,debug:{get:function(){return ht},set:function(v){xe(v)}},derive:P,extend:p,props:b,override:x,Events:bn,on:Xr,liveQuery:ns,extendObservabilitySet:i,getByKeyPath:R,setByKeyPath:I,delByKeyPath:function(v,_){typeof _=="string"?I(v,_,void 0):"length"in _&&[].map.call(_,function(M){I(v,M,void 0)})},shallowClone:D,deepClone:ne,getObjectDiff:Ot,cmp:Ht,asap:j,minKey:-1/0,addons:[],connections:{get:ii.toArray},errnames:Ee,dependencies:oi,cache:d,semVer:"4.4.5",version:"4.4.5".split(".").map(function(v){return parseInt(v)}).reduce(function(v,_,M){return v+_/Math.pow(10,2*M)})})),Pn.maxKey=ti(Pn.dependencies.IDBKeyRange),typeof dispatchEvent<"u"&&typeof addEventListener<"u"&&(Xr($n,function(v){ln||(v=new CustomEvent(Wi,{detail:v}),ln=!0,dispatchEvent(v),ln=!1)}),addEventListener(Wi,function(v){v=v.detail,ln||Oi(v)}));var kn,ln=!1,is=function(){};return typeof BroadcastChannel<"u"&&((is=function(){(kn=new BroadcastChannel(Wi)).onmessage=function(v){return v.data&&Oi(v.data)}})(),typeof kn.unref=="function"&&kn.unref(),Xr($n,function(v){ln||kn.postMessage(v)})),typeof addEventListener<"u"&&(addEventListener("pagehide",function(v){if(!Qr.disableBfCache&&v.persisted){ht&&console.debug("Dexie: handling persisted pagehide"),kn!=null&&kn.close();for(var _=0,M=ii.toArray();_<M.length;_++)M[_].close({disableAutoOpen:!1})}}),addEventListener("pageshow",function(v){!Qr.disableBfCache&&v.persisted&&(ht&&console.debug("Dexie: handling persisted pageshow"),is(),Oi({all:new Er(-1/0,[[]])}))})),be.rejectionMapper=function(v,_){return!v||v instanceof L||v instanceof TypeError||v instanceof SyntaxError||!v.name||!Ve[v.name]?v:(_=new Ve[v.name](_||v.message,v),"stack"in v&&O(_,"stack",{get:function(){return this.inner.stack}}),_)},xe(ht),n(Qr,Object.freeze({__proto__:null,DEFAULT_MAX_CONNECTIONS:1e3,Dexie:Qr,Entity:Qn,PropModification:Pr,RangeSet:Er,add:function(v){return new Pr({add:v})},cmp:Ht,default:Qr,liveQuery:ns,mergeRanges:an,rangesOverlap:Zi,remove:function(v){return new Pr({remove:v})},replacePrefix:function(v,_){return new Pr({replacePrefix:[v,_]})}}),{default:Qr}),Qr})})(Uy);var aE=Uy.exports,Ff=sE(aE);const Vy=Symbol.for("Dexie"),Rl=globalThis[Vy]||(globalThis[Vy]=Ff);if(Ff.semVer!==Rl.semVer)throw new Error(`Two different versions of Dexie loaded in the same app: ${Ff.semVer} and ${Rl.semVer}`);const{liveQuery:AN,mergeRanges:CN,rangesOverlap:IN,RangeSet:ON,cmp:NN,Entity:kN,PropModification:DN,replacePrefix:BN,add:RN,remove:jN,DexieYProvider:MN}=Rl,Fa=ss("Database"),Io="rtc-agent-";class oE extends Rl{constructor(r){if(!r.startsWith(Io))throw new Error(`[RTCAgentDatabase] databaseName must start with "${Io}", got "${r}"`);Fa.info("Initializing database:",r);super(r);Vt(this,"sessions");Vt(this,"turns");Vt(this,"messages");Vt(this,"rtcs");Vt(this,"offsets");Vt(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=>{Fa.info("Migrating database from v1 to v2: switching to client_id as primary key");const s=n.table("sessions"),o=await s.toArray();await s.clear();const a=new Map;for(const u of o){const p=u,y=p.id,g=p.client_id||y||crypto.randomUUID();y&&a.set(y,g);const b={...p};b.client_id=g,b.server_id=y,delete b.id,await s.add(b)}for(const u of["turns","messages","rtcs"]){const p=n.table(u),y=await p.toArray();await p.clear();for(const h of y){const g=h,b=g.id,S=g.client_id,O=g.session_id,P={...g};if(P.client_id=S||b||crypto.randomUUID(),P.server_id=b,delete P.id,O){const A=a.get(O);P.session_client_id=A||O}else P.session_client_id="";delete P.session_id,await p.add(P)}}}),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"}),this.version(7).stores({sessions:"client_id, server_id, sync_status, owner_ref_id, status, updated_at, device_id",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"}),this.version(8).stores({sessions:"client_id, server_id, sync_status, owner_ref_id, status, updated_at, device_id",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, session_device_id",offsets:"channel",fileSystemEntries:"path, type, metadata.group, *metadata.tags"}).upgrade(async n=>{const s=await n.table("rtcs").toArray();for(const o of s)if(o.session_client_id&&!o.session_device_id){const a=await n.table("sessions").get(o.session_client_id);a!=null&&a.device_id&&await n.table("rtcs").update(o.client_id,{session_device_id:a.device_id})}})}}let as=null,Oo=null;function yr(t){if(t===void 0){if(as)return as;throw new Error(`[RTCAgentDatabase] getDatabase() called without a name before any database was initialized. Pass a databaseName starting with "${Io}".`)}if(!t.startsWith(Io))throw new Error(`[RTCAgentDatabase] databaseName must start with "${Io}", got "${t}"`);const e=t;return(!as||Oo!==e)&&(as&&(Fa.info("Closing previous database instance:",Oo),as.close()),Fa.info("Creating new database instance:",e),as=new oE(e),Oo=e),as}async function lE(){as&&(Fa.info("Closing database:",Oo),as.close(),as=null,Oo=null)}async function cE(){Fa.warn("flushAll: clearing all database tables");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()})}const qa=ss("OffsetManager");class uE{async getPosition(e){const n=await yr().offsets.get(e);if(!n){qa.debug("getPosition: no record for channel:",e);return}return qa.debug("getPosition:",e,"offset:",n.offset,"epoch:",n.epoch),{offset:n.offset,epoch:n.epoch}}async updatePosition(e,r,n){qa.debug("updatePosition:",e,"offset:",r,"epoch:",n);const s=yr(),o={channel:e,offset:r,epoch:n,updatedAt:Date.now()};await s.offsets.put(o)}async clearPosition(e){qa.debug("clearPosition:",e),await yr().offsets.delete(e)}async clearAll(){qa.info("clearAll: clearing all offset records"),await yr().offsets.clear()}async reset(){qa.info("reset: resetting all offsets"),await this.clearAll()}}let qf=null;function Ky(){return qf||(qf=new uE),qf}const fE=ss("UIUpdateBus");class pE{constructor(){Vt(this,"entityListeners",new Map);Vt(this,"wildcardListeners",new Set);Vt(this,"_processingChains",new Map);Vt(this,"_listenerCounter",0);Vt(this,"_listenerIds",new WeakMap)}_getListenerId(e){let r=this._listenerIds.get(e);return r===void 0&&(r=++this._listenerCounter,this._listenerIds.set(e,r)),r}_getChainKey(e,r,n){return`${e}:${r}:${this._getListenerId(n)}`}_dispatchToListener(e,r){const n=this._getChainKey(r.entity,r.entityId,e),o=(this._processingChains.get(n)??Promise.resolve()).then(()=>e(r)).catch(a=>{fE.error("listener error:",a)});this._processingChains.set(n,o),o.finally(()=>{this._processingChains.get(n)===o&&this._processingChains.delete(n)})}subscribe(e,r){if(typeof e=="function")return this.wildcardListeners.add(e),()=>{this.wildcardListeners.delete(e)};const n=e,s=r;let o=this.entityListeners.get(n);return o||(o=new Set,this.entityListeners.set(n,o)),o.add(s),()=>{o.delete(s),o.size===0&&this.entityListeners.delete(n)}}publish(e){for(const n of this.wildcardListeners)this._dispatchToListener(n,e);const r=this.entityListeners.get(e.entity);if(r)for(const n of r)this._dispatchToListener(n,e)}clear(){this.entityListeners.clear(),this.wildcardListeners.clear(),this._processingChains.clear()}}let $f=null;function Wy(){return $f||($f=new pE),$f}function dE(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"),o=String(t.getMinutes()).padStart(2,"0"),a=String(t.getSeconds()).padStart(2,"0"),u=String(t.getMilliseconds()).padStart(3,"0"),p=-t.getTimezoneOffset(),y=String(Math.floor(Math.abs(p)/60)).padStart(2,"0"),h=String(Math.abs(p)%60).padStart(2,"0"),g=p>=0?"+":"-";return`${e}-${r}-${n}T${s}:${o}:${a}.${u}${g}${y}:${h}`}function li(){return dE(new Date)}const Gy=["Date","RegExp","String","Number"],zy=Object.getOwnPropertyNames(globalThis.Temporal||{});function Hy(t,e,r={cyclesFix:!0},n=[]){var u,p;let s=[];const o=Array.isArray(t);for(const y in t){const h=t[y],g=o?+y:y;if(!(y in e)){s.push({type:"REMOVE",path:[g],oldValue:h});continue}const b=e[y],S=typeof h=="object"&&typeof b=="object"&&Array.isArray(h)===Array.isArray(b),O=S&&h?(p=(u=Object.getPrototypeOf(h))==null?void 0:u.constructor)==null?void 0:p.name:void 0;if(h&&b&&S&&!Gy.includes(O)&&!zy.includes(O)&&(!r.cyclesFix||!n.includes(h))){r.cyclesFix&&n.push(h);const P=Hy(h,b,r,n);r.cyclesFix&&n.pop();for(const A of P)A.path.unshift(g),s.push(A)}else Object.is(h,b)||zy.includes(O)&&String(h)===String(b)||Gy.includes(O)&&(isNaN(h)?h+""==b+"":+h==+b)||s.push({path:[g],type:"CHANGE",value:b,oldValue:h})}const a=Array.isArray(e);for(const y in e)y in t||s.push({type:"CREATE",path:[a?+y:y],value:e[y]});return s}const ci=ss("EntityRepository");function hE(t){return t.join(".")}function jl(t,e,r,n,s){const o=Wy(),a=Jy(s),u=n?Jy(n):void 0;if(!u){for(const[y,h]of Object.entries(a))o.publish({entity:t,action:e,entityId:r,field:y,oldValue:void 0,newValue:h});return}const p=Hy(u,a);for(const y of p)o.publish({entity:t,action:e,entityId:r,field:hE(y.path),oldValue:y.oldValue,newValue:y.value})}function Jy(t){try{return JSON.parse(JSON.stringify(t))}catch{return ci.warn("safeClone: failed to clone object, returning empty object"),{}}}class yE{constructor(e){Vt(this,"deviceId");if(!e)throw new Error("[EntityRepository] deviceId is required, got empty value");this.deviceId=e}async upsertSession(e,r="synced",n){const s=yr(),o=li();let a;e.client_id&&(a=await s.sessions.where("client_id").equals(e.client_id).first()),ci.debug("upsertSession:",a?"UPDATE":"CREATE","client_id:",e.client_id,"title:",e.title);let u,p;if(a){const y={...a},h={...a,...e,sync_status:r,server_id:e.server_id||a.server_id};await s.sessions.put(h),u={before:y,after:h},p="updated",ci.debug("upsertSession: After update - title:",h.title)}else{const y={...e,client_id:e.client_id||"",owner_kind:e.owner_kind||"",owner_ref_id:e.owner_ref_id||"",status:e.status||"active",created_at:e.created_at||o,updated_at:e.updated_at||o,sync_status:e.sync_status||r,pending_turn_count:e.pending_turn_count??0,running_turn_count:e.running_turn_count??0,agent_prompt:e.agent_prompt||""};await s.sessions.put(y),u={before:void 0,after:y},p="created",ci.debug("upsertSession: After create - title:",y.title)}return n!=null&&n.silent||jl("session",p,u.after.client_id,u.before,u.after),u}async getClientSession(e){return yr().sessions.get(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 o=await yr().sessions.orderBy("updated_at").reverse().toArray();ci.debug(`listSessions: total=${o.length}, with deleted_at=${o.filter(u=>u.deleted_at).length}`);const a=o.filter(u=>!u.deleted_at);if(ci.debug(`listSessions: after filter=${a.length}`),e){const u=a.findIndex(p=>p.client_id===e);return u===-1?a.slice(0,r):a.slice(u+1,u+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=li();ci.debug(`softDeleteSession: setting deleted_at=${n} for ${e}`);const s=await this.upsertSession({client_id:e,deleted_at:n,updated_at:n},"pending");return ci.debug(`softDeleteSession: after upsert, deleted_at=${s.after.deleted_at}`),s}async upsertTurn(e,r="synced",n){const s=yr(),o=li();let a;e.client_id&&(a=await s.turns.where("client_id").equals(e.client_id).first());let u,p;if(a){const y={...a},h={...a,...e,sync_status:r,server_id:e.server_id||a.server_id};await s.turns.put(h),u={before:y,after:h},p="updated"}else{const y={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||o,sync_status:e.sync_status||r};await s.turns.put(y),u={before:void 0,after:y},p="created"}return n!=null&&n.silent||jl("turn",p,u.after.client_id,u.before,u.after),u}async getClientTurn(e){return yr().turns.get(e)}async countActiveTurns(e){const r=yr(),n=r.turns.where("session_client_id").equals(e),[s,o]=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:o}}async upsertMessage(e,r="synced",n){const s=yr(),o=li();let a;e.client_id&&(a=await s.messages.where("client_id").equals(e.client_id).first());let u,p;if(a){const y={...a},h={...a,...e,sync_status:r,server_id:e.server_id||a.server_id};await s.messages.put(h),u={before:y,after:h},p="updated"}else{const y={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||o,updated_at:e.updated_at||o,sync_status:e.sync_status||r,parent_client_id:e.parent_client_id};await s.messages.put(y),u={before:void 0,after:y},p="created"}return n!=null&&n.silent||jl("message",p,u.after.client_id,u.before,u.after),u}async getClientMessage(e){return yr().messages.get(e)}async listMessagesBySession(e,r,n=50,s="backward"){const u=await yr().messages.where("session_client_id").equals(e).toArray(),p=h=>`${new Date(h.created_at).getTime()}|${h.client_id}`;u.sort((h,g)=>p(h).localeCompare(p(g)));let y=null;if(r&&(y=r),s==="backward"){let h=u;return y&&(h=u.filter(b=>p(b)<y)),h.slice(-n)}return y?u.filter(g=>p(g)>y).slice(0,n):u.slice(0,n)}async upsertRtc(e,r="synced",n){const s=yr(),o=li();let a;e.client_id&&(a=await s.rtcs.where("client_id").equals(e.client_id).first());let u,p;if(a){const y={...a},h={...a,...e,sync_status:r,server_id:e.server_id||a.server_id};await s.rtcs.put(h),u={before:y,after:h},p="updated"}else{const y={client_id:e.client_id||"",server_id:e.server_id,session_client_id:e.session_client_id||"",session_device_id:e.session_device_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||o,updated_at:e.updated_at||o,sync_status:e.sync_status||r};await s.rtcs.put(y),u={before:void 0,after:y},p="created"}return n!=null&&n.silent||jl("rtc",p,u.after.client_id,u.before,u.after),u}async getClientRtc(e){return yr().rtcs.get(e)}async getNextRtcToProcess(e){const r=yr(),n=p=>e?p.session_client_id===e:!0,s=p=>p.session_device_id?p.session_device_id===this.deviceId:!0,a=(await r.rtcs.where("sync_status").equals("failed").sortBy("offset")).find(p=>n(p)&&s(p));return a||(await r.rtcs.filter(p=>p.status==="pending").sortBy("offset")).find(p=>n(p)&&s(p))}async listRtcBySession(e,r,n=50){const a=(await yr().rtcs.where("session_client_id").equals(e).toArray()).sort((p,y)=>p.offset-y.offset),u=r||0;return a.slice(u,u+n)}async applyUpdate(e){var r;for(let n=0;n<e.items.length;n++){const s=e.items[n],o=(r=e.data_list)==null?void 0:r[n];o&&await this.applyUpdateItem(s,o)}}async _resolveSessionClientId(e,r,n){const s=await this.getSessionByServerId(e);return s?s.client_id:(ci.warn(`${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 o=s.session_client_id;if(o){const{pending:a,running:u}=await this.countActiveTurns(o),p=await this.getClientSession(o);p&&await this.upsertSession({client_id:o,pending_turn_count:a,running_turn_count:u},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 o=await this.getMessageByServerId(n.parent_message_id);o?s.parent_client_id=o.client_id:ci.warn(`[applyUpdateItem:message] 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;let s,o;if(n.session_id){const u=await this.getSessionByServerId(n.session_id);u?(s=u.client_id,o=u.device_id):(ci.warn(`RTC ${n.client_id||n.id} references unknown session ${n.session_id}`),s=n.session_id)}const a={...n,server_id:n.id,client_id:n.client_id||n.id,session_client_id:s||"",session_device_id:o};delete a.id,delete a.session_id,await this.upsertRtc(a,"pending");break}}}}let Ml=null;function mE(t){if(Ml){ci.warn("Already initialized, ignoring re-init");return}Ml=new yE(t)}function gE(){if(!Ml)throw new Error("[EntityRepository] Not initialized - call initEntityRepository(deviceId) first");return Ml}const Vn=ss("VirtualFS");class No extends Error{constructor(e,r){super(r),this.code=e,this.name="PathError"}}function Qs(t){if(!t||typeof t!="string")throw new No("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 No("EINVAL","Path traversal (..) is not allowed");return e="/"+r.join("/"),e==="/"?"/":e.replace(/\/$/,"")}function bE(t){const e=Qs(t),r=e.lastIndexOf("/");return e.substring(r+1)}function Yy(t,e){const r=t.replace(/[.+^${}()|[\]\\/+]/g,"\\$&").replace(/\*/g,"[^\\/]*").replace(/\?/g,"[^\\/]");return new RegExp(`^${r}$`).test(e)}class vE{async read(e,r,n){const s=Qs(e);Vn.debug("read:",s,"offset:",r,"limit:",n);const a=await yr().fileSystemEntries.get(s);if(!a)throw Vn.debug("read: file not found:",s),new No("ENOENT",`File not found: ${s}`);let u=a.content;if(r!==void 0||n!==void 0){const p=r||0,y=n!==void 0?p+n:void 0;u=u.substring(p,y)}return Vn.debug("read: success, content length:",u.length),u}async write(e,r,n="overwrite",s){const o=Qs(e);Vn.debug("write:",o,"mode:",n,"content length:",r.length);const a=yr(),u=this.inferFileType(o),p=await a.fileSystemEntries.get(o);if(n==="create-new"&&p)return Vn.debug("write: file already exists in create-new mode, skipping:",o),p.content.length;let y=r,h;if(p&&n==="append")y=p.content+r,h={...p.metadata,...s,updatedAt:new Date};else{const b=new Date;if(h={name:bE(o),description:"",createdAt:(p==null?void 0:p.metadata.createdAt)||b,updatedAt:b,...s},u==="function"){const S=this.extractGroupFromPath(o);S&&(h.group=S)}}const g={path:o,type:u,content:y,metadata:h};return await a.fileSystemEntries.put(g),Vn.debug("write: success, final content length:",y.length),y.length}async ls(e="/"){const r=Qs(e);Vn.debug("ls:",r);const n=yr(),s=new Set;if(r==="/"){const o=await n.fileSystemEntries.toArray();for(const a of o){const u=a.path.split("/").filter(Boolean);u.length>0&&s.add(u[0])}}else{const o=r+"/",a=await n.fileSystemEntries.filter(u=>u.path.startsWith(o)).toArray();for(const u of a){const y=u.path.substring(o.length).split("/");y.length>0&&s.add(y[0])}}return Array.from(s).sort()}async find(e,r="/"){const n=Qs(r);Vn.debug("find: pattern:",e,"path:",n);const s=yr();let o;if(n==="/")o=await s.fileSystemEntries.toArray();else{const u=n+"/";o=await s.fileSystemEntries.filter(p=>p.path.startsWith(u)).toArray()}const a=[];for(const u of o){const p=n==="/"?u.path.substring(1):u.path.substring(n.length+1);(Yy(e,p)||Yy(e,u.path))&&a.push(u.path)}return a.sort()}async grep(e,r="/",n=!1,s=100){const o=Qs(r);Vn.debug("grep: pattern:",e,"path:",o,"caseSensitive:",n);const a=yr();let u;try{const h=n?"":"i";u=new RegExp(e,h)}catch(h){throw Vn.warn("grep: invalid regex pattern:",e,h),new SyntaxError(`Invalid regex pattern: ${e}`)}let p;if(o==="/")p=await a.fileSystemEntries.toArray();else{const h=o+"/";p=await a.fileSystemEntries.filter(g=>g.path.startsWith(h)).toArray()}const y=[];for(const h of p){const g=h.content.split(`
|
|
14
14
|
`);for(let b=0;b<g.length;b++){const S=g[b];if(u.test(S)&&(y.push({file:h.path,line:S,lineNumber:b+1}),y.length>=s))return y}}return y}async queryByType(e){return yr().fileSystemEntries.where("type").equals(e).toArray()}async exists(e){const r=Qs(e);return await yr().fileSystemEntries.get(r)!==void 0}async remove(e){const r=Qs(e);Vn.debug("remove:",r);const n=yr();if(!await this.exists(r))throw Vn.debug("remove: file not found:",r),new No("ENOENT",`File not found: ${r}`);await n.fileSystemEntries.delete(r),Vn.debug("remove: success:",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 Fr=new vE;var Uf={},ko={},ui={},Vf={},Do={},Ll={},Fl={},Pe={},ql={},Xy;function Kf(){if(Xy)return ql;Xy=1,Object.defineProperty(ql,"__esModule",{value:!0}),ql.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 ql}var $l={},Qy;function Bo(){if(Qy)return $l;Qy=1,Object.defineProperty($l,"__esModule",{value:!0}),$l.default=e;const t=new Set;function e(n,s,o="",a=n){if(t.has(a))return;t.add(a);const{internal:u,trace:p}=r(1,2);u||console.warn(`${o}\`${n}\` has been deprecated, please migrate to \`${s}\`
|
|
@@ -2526,17 +2526,17 @@ If you have already enabled that plugin (or '@babel/preset-typescript'), make su
|
|
|
2526
2526
|
(o, v) => o.${Oe.types.cloneNode(t)} = v
|
|
2527
2527
|
`]}function Oh(t){if(t=(0,ia.skipTransparentExprWrappers)(t),t.isSequenceExpression()){const e=t.get("expressions");return Oh(e[e.length-1])}return t}function kO(t){const e=Oh(t);if(e.isConstantExpression())return Oe.types.cloneNode(t.node);if(e.isIdentifier()&&t.scope.hasUid(e.node.name))return Oe.types.cloneNode(t.node);if(e.isAssignmentExpression()&&e.get("left").isIdentifier())return Oe.types.cloneNode(e.node.left);throw new Error(`Internal Error: the computed key ${t.toString()} has not yet been memoised.`)}function El(t,e){const r=e.get("key");r.isSequenceExpression()?t.push(...r.node.expressions):t.push(r.node),r.replaceWith(aa(t))}function DO(t,e){const r=e.get("key"),n=Oh(r);if(n.isConstantExpression())El(t,e);else{const s=r.scope.parent,o=(0,Ef.memoiseComputedKey)(n.node,s,s.generateUid("computedKey"));if(!o)El(t,e);else{const a=[...t,Oe.types.cloneNode(o.left)],u=n.parentPath;u.isSequenceExpression()?u.pushContainer("expressions",a):n.replaceWith(aa([Oe.types.cloneNode(o),...a]))}}}function Nh(t,e){const r=e.get("value");r.node?t.push(r.node):t.length>0&&(t[t.length-1]=Oe.types.unaryExpression("void",t[t.length-1])),r.replaceWith(aa(t))}function BO(t,e){e.unshiftContainer("body",Oe.types.expressionStatement(aa(t)))}function RO(t,e){e.node.body.body.unshift(Oe.types.expressionStatement(aa(t)))}function WS(t,e){return Oe.types.isCallExpression(t)&&Oe.types.isIdentifier(t.callee,{name:e.name})}function jO(t,e){if(e){if(t.length>=2&&WS(t[1],e)){const r=Oe.types.callExpression(Oe.types.cloneNode(e),[t[0]]);t.splice(0,2,r)}t.length>=2&&Oe.types.isThisExpression(t[t.length-1])&&WS(t[t.length-2],e)&&t.splice(t.length-1,1)}return aa(t)}function MO(t,e,r){e.traverse({CallExpression:{exit(n){if(!n.get("callee").isSuper())return;const s=[n.node,...t.map(o=>Oe.types.cloneNode(o))];n.isCompletionRecord()&&s.push(Oe.types.thisExpression()),n.replaceWith(jO(s,r)),n.skip()}},ClassMethod(n){n.node.kind==="constructor"&&n.skip()}})}function GS(t,e){const r=[Oe.types.expressionStatement(aa(t))];return e&&r.unshift(Oe.types.expressionStatement(Oe.types.callExpression(Oe.types.super(),[Oe.types.spreadElement(Oe.types.identifier("args"))]))),Oe.types.classMethod("constructor",Oe.types.identifier("constructor"),e?[Oe.types.restElement(Oe.types.identifier("args"))]:[],Oe.types.blockStatement(r))}function zS(t){return Oe.types.staticBlock([Oe.types.expressionStatement(aa(t))])}const Na=0,sa=1,LO=2,HS=3,xf=4,FO=5,qO=8,$O=16;function UO(t){switch(t.node.type){case"ClassProperty":case"ClassPrivateProperty":return Na;case"ClassAccessorProperty":return sa;case"ClassMethod":case"ClassPrivateMethod":return t.node.kind==="get"?HS:t.node.kind==="set"?xf:LO}}function VO(t){return[...t.filter(e=>e.isStatic&&e.kind>=sa&&e.kind<=xf),...t.filter(e=>!e.isStatic&&e.kind>=sa&&e.kind<=xf),...t.filter(e=>e.isStatic&&e.kind===Na),...t.filter(e=>!e.isStatic&&e.kind===Na)]}function JS(t,e,r){const n=t.length,s=e.some(Boolean),o=[];for(let a=0;a<n;a++)(r==="2023-11"||r==="2023-05")&&s&&o.push(e[a]||Oe.types.unaryExpression("void",Oe.types.numericLiteral(0))),o.push(t[a].expression);return{haveThis:s,decs:o}}function KO(t,e){return Oe.types.arrayExpression(t.map(r=>{let n=r.kind;return r.isStatic&&(n+=e==="2023-11"||e==="2023-05"?qO:FO),r.decoratorsHaveThis&&(n+=$O),Oe.types.arrayExpression([r.decoratorsArray,Oe.types.numericLiteral(n),r.name,...r.privateMethods||[]])}))}function WO(t){const e=[];for(const r of t){const{locals:n}=r;Array.isArray(n)?e.push(...n):n!==void 0&&e.push(n)}return e}function GO(t,e,r,n,s,o){e.insertAfter(Oe.types.classPrivateMethod("get",Oe.types.cloneNode(r),[],Oe.types.blockStatement([Oe.types.returnStatement(Oe.types.callExpression(Oe.types.cloneNode(n),t==="2023-11"&&o?[]:[Oe.types.thisExpression()]))]),o)),e.insertAfter(Oe.types.classPrivateMethod("set",Oe.types.cloneNode(r),[Oe.types.identifier("v")],Oe.types.blockStatement([Oe.types.expressionStatement(Oe.types.callExpression(Oe.types.cloneNode(s),t==="2023-11"&&o?[Oe.types.identifier("v")]:[Oe.types.thisExpression(),Oe.types.identifier("v")]))]),o))}function zO(t,e,r,n){let s,o;t.node.kind==="set"?(s=[Oe.types.identifier("v")],o=[Oe.types.expressionStatement(Oe.types.callExpression(r,[Oe.types.thisExpression(),Oe.types.identifier("v")]))]):(s=[],o=[Oe.types.returnStatement(Oe.types.callExpression(r,[Oe.types.thisExpression()]))]),t.replaceWith(Oe.types.classPrivateMethod(t.node.kind,Oe.types.cloneNode(e),s,Oe.types.blockStatement(o),n))}function YS(t){const{type:e}=t;return e!=="TSDeclareMethod"&&e!=="TSIndexSignature"&&e!=="StaticBlock"}function HO(t){return Oe.types.callExpression(Oe.types.arrowFunctionExpression([],Oe.types.blockStatement(t.body)),[])}function JO(t){return Oe.types.functionExpression(null,[],Oe.types.blockStatement(t.body))}function YO(t){return Oe.types.functionExpression(null,[],Oe.types.blockStatement([Oe.types.returnStatement(t)]))}function aa(t){return t.length===0?Oe.types.unaryExpression("void",Oe.types.numericLiteral(0)):t.length===1?t[0]:Oe.types.sequenceExpression(t)}function XS(t){const{params:e,body:r,generator:n,async:s}=t;return Oe.types.functionExpression(void 0,e,r,n,s)}function QS(t,e){return Oe.types.callExpression(t.addHelper("setFunctionName"),[Oe.types.thisExpression(),e])}function kh(t,e){return Oe.types.callExpression(t.addHelper("toPropertyKey"),[e])}function Dh(t){return Oe.types.arrowFunctionExpression([Oe.types.identifier("_")],Oe.types.binaryExpression("in",Oe.types.cloneNode(t),Oe.types.identifier("_")))}function XO(t){try{return Oe.types.traverseFast(t,e=>{if(Oe.types.isPrivateName(e))throw null}),!1}catch{return!0}}function QO(t){const{node:e}=t;e.computed=!0,Oe.types.isIdentifier(e.key)&&(e.key=Oe.types.stringLiteral(e.key.name))}function Bh(t,e){let r=!1;if(e.length>0){const n=(0,qS.privateNameVisitorFactory)({PrivateName(o,a){a.privateNamesMap.has(o.node.id.name)&&(r=!0,o.stop())}}),s=new Map;for(const o of e)s.set(o,null);t.traverse(n,{privateNamesMap:s})}return r}function ZO(t,e){const r=(0,qS.privateNameVisitorFactory)({PrivateName(s,o){if(!o.privateNamesMap.has(s.node.id.name))return;const a=s.parentPath,u=a.parentPath;if(u.node.type==="AssignmentExpression"&&u.node.left===a.node||u.node.type==="UpdateExpression"||u.node.type==="RestElement"||u.node.type==="ArrayPattern"||u.node.type==="ObjectProperty"&&u.node.value===a.node&&u.parentPath.type==="ObjectPattern"||u.node.type==="ForOfStatement"&&u.node.left===a.node)throw s.buildCodeFrameError(`Decorated private methods are read-only, but "#${s.node.id.name}" is updated via this expression.`)}}),n=new Map;for(const s of e)n.set(s,null);t.traverse(r,{privateNamesMap:n})}function e4(t,e,r,n,s,o,a){var u;const p=t.get("body.body"),y=t.node.decorators;let h=!1,g=!1,b=!1;const S=OO(t),O=[],P=t.scope.parent,A=($e,je,qe)=>{const Le=Yn(P,je);return qe.push(Oe.types.assignmentExpression("=",Le,$e)),Oe.types.cloneNode(Le)};let C,T;const x=(u=t.node.id)==null?void 0:u.name,E=typeof s=="object"?s:void 0,j=$e=>{try{return Oe.types.traverseFast($e,je=>{if(Oe.types.isThisExpression(je)||Oe.types.isSuper(je)||Oe.types.isYieldExpression(je)||Oe.types.isAwaitExpression(je)||Oe.types.isIdentifier(je,{name:"arguments"})||x&&Oe.types.isIdentifier(je,{name:x})||Oe.types.isMetaProperty(je)&&je.meta.name!=="import")throw null}),!1}catch{return!0}},R=[];for(const $e of p){if(!YS($e))continue;const je=$e.node;if(!je.static&&Oe.types.isPrivateName(je.key)&&R.push(je.key.id.name),xl(je)){switch(je.type){case"ClassProperty":o.ClassProperty($e,e);break;case"ClassPrivateProperty":o.ClassPrivateProperty($e,e);break;case"ClassAccessorProperty":if(o.ClassAccessorProperty($e,e),a==="2023-11")break;default:je.static?T??(T=Yn(P,"initStatic")):C??(C=Yn(P,"initProto"));break}h=!0,b||(b=je.decorators.some(j))}else if(je.type==="ClassAccessorProperty"){o.ClassAccessorProperty($e,e);const{key:qe,value:Le,static:gt,computed:ht}=je,xe=S(),Se=US(xe,Le,gt),se=$e.get("key"),[ee]=$e.replaceWith(Se);let oe,W;ht&&!se.isConstantExpression()?(oe=(0,Ef.memoiseComputedKey)(kh(e,qe),P,P.generateUid("computedKey")),W=Oe.types.cloneNode(oe.left)):(oe=Oe.types.cloneNode(qe),W=Oe.types.cloneNode(qe)),Ih(t,s),VS(t.node.id,ee,oe,W,xe,ht,gt,a)}"computed"in $e.node&&$e.node.computed&&(g||(g=!P.isStatic($e.node.key)))}if(!y&&!h){!t.node.id&&typeof s=="string"&&(t.node.id=Oe.types.identifier(s)),E&&t.node.body.body.unshift(zS([QS(e,E)]));return}const I=[];let D;const Z=new Set;let J,N,$=null;function ne($e){let je=!1,qe=!1;const Le=[];for(const gt of $e){const{expression:ht}=gt;let xe;(a==="2023-11"||a==="2023-05")&&Oe.types.isMemberExpression(ht)&&(Oe.types.isSuper(ht.object)?xe=Oe.types.thisExpression():P.isStatic(ht.object)?xe=Oe.types.cloneNode(ht.object):($??($=Yn(P,"obj")),xe=Oe.types.assignmentExpression("=",Oe.types.cloneNode($),ht.object),ht.object=Oe.types.cloneNode($))),Le.push(xe),je||(je=!P.isStatic(ht)),qe||(qe=j(gt))}return{hasSideEffects:je,usesFnContext:qe,decoratorsThis:Le}}const me=g||b||a!=="2023-11";let Ce=!1,Ae=0,ce=[],ue,K=[];if(y){J=Yn(P,"initClass"),Ce=t.isClassDeclaration(),{id:N,path:t}=NO(t,s),t.node.decorators=null;const $e=y.some(XO),{hasSideEffects:je,usesFnContext:qe,decoratorsThis:Le}=ne(y),{haveThis:gt,decs:ht}=JS(y,Le,a);if(Ae=gt?1:0,ce=ht,(qe||je&&me||$e)&&(ue=A(Oe.types.arrayExpression(ce),"classDecs",O)),!h)for(const xe of t.get("body.body")){const{node:Se}=xe;if("computed"in Se&&Se.computed)if(xe.isClassProperty({static:!0})){if(!xe.get("key").isConstantExpression()){const ee=Se.key,oe=(0,Ef.memoiseComputedKey)(ee,P,P.generateUid("computedKey"));oe!=null&&(Se.key=Oe.types.cloneNode(oe.left),K.push(oe))}}else K.length>0&&(El(K,xe),K=[])}}else Ih(t,s),N=Oe.types.cloneNode(t.node.id);let Y,he=!1,ae=[],U=[];if(h){if(C){const $e=Oe.types.callExpression(Oe.types.cloneNode(C),[Oe.types.thisExpression()]);ae.push($e)}for(const $e of p){if(!YS($e)){U.length>0&&$e.isStaticBlock()&&(BO(U,$e),U=[]);continue}const{node:je}=$e,qe=je.decorators,Le=!!(qe!=null&&qe.length),gt="computed"in je&&je.computed;let ht="computedKey";je.key.type==="PrivateName"?ht=je.key.id.name:!gt&&je.key.type==="Identifier"&&(ht=je.key.name);let xe,Se;if(Le){const{hasSideEffects:Re,usesFnContext:Fe,decoratorsThis:Ke}=ne(qe),{decs:it,haveThis:Pt}=JS(qe,Ke,a);Se=Pt,xe=it.length===1?it[0]:Oe.types.arrayExpression(it),(Fe||Re&&me)&&(xe=A(xe,ht+"Decs",K))}if(gt&&!$e.get("key").isConstantExpression()){const Re=je.key,Fe=(0,Ef.memoiseComputedKey)(Le?kh(e,Re):Re,P,P.generateUid("computedKey"));Fe!=null&&(y&&$e.isClassProperty({static:!0})?(je.key=Oe.types.cloneNode(Fe.left),K.push(Fe)):je.key=Fe)}const{key:se,static:ee}=je,oe=se.type==="PrivateName",W=UO($e);oe&&!ee&&(Le&&(he=!0),(Oe.types.isClassPrivateProperty(je)||!Y)&&(Y=se)),$e.isClassMethod({kind:"constructor"})&&(D=$e);let fe;if(Le){let Re,Fe;if(gt?Fe=kO($e.get("key")):se.type==="PrivateName"?Fe=Oe.types.stringLiteral(se.id.name):se.type==="Identifier"?Fe=Oe.types.stringLiteral(se.name):Fe=Oe.types.cloneNode(se),W===sa){const{value:Ke}=$e.node,it=a==="2023-11"&&ee?[]:[Oe.types.thisExpression()];Ke&&it.push(Oe.types.cloneNode(Ke));const Pt=S(),Mt=Yn(P,`init_${ht}`),pt=Oe.types.callExpression(Oe.types.cloneNode(Mt),it),xt=US(Pt,pt,ee),[te]=$e.replaceWith(xt);if(oe){Re=KS(Pt,a);const de=Yn(P,`get_${ht}`),G=Yn(P,`set_${ht}`);GO(a,te,se,de,G,ee),fe=[Mt,de,G]}else Ih(t,s),VS(t.node.id,te,Oe.types.cloneNode(se),Oe.types.isAssignmentExpression(se)?Oe.types.cloneNode(se.left):Oe.types.cloneNode(se),Pt,gt,ee,a),fe=[Mt]}else if(W===Na){const Ke=Yn(P,`init_${ht}`),it=$e.get("value"),Pt=a==="2023-11"&&ee?[]:[Oe.types.thisExpression()];it.node&&Pt.push(it.node),it.replaceWith(Oe.types.callExpression(Oe.types.cloneNode(Ke),Pt)),fe=[Ke],oe&&(Re=KS(se,a))}else if(oe){const Ke=Yn(P,`call_${ht}`);if(fe=[Ke],new FS.default({constantSuper:r,methodPath:$e,objectRef:N,superRef:t.node.superClass,file:e.file,refToPreserve:N}).replace(),Re=[XS($e.node)],W===HS||W===xf)zO($e,Oe.types.cloneNode(se),Oe.types.cloneNode(Ke),ee);else{const Pt=$e.node;t.node.body.body.unshift(Oe.types.classPrivateProperty(se,Oe.types.cloneNode(Ke),[],Pt.static)),Z.add(se.id.name),$e.remove()}}I.push({kind:W,decoratorsArray:xe,decoratorsHaveThis:Se,name:Fe,isStatic:ee,privateMethods:Re,locals:fe}),$e.node&&($e.node.decorators=null)}if(gt&&K.length>0&&(y&&$e.isClassProperty({static:!0})||(El(K,W===sa?$e.getNextSibling():$e),K=[])),ae.length>0&&!ee&&(W===Na||W===sa)&&(Nh(ae,$e),ae=[]),U.length>0&&ee&&(W===Na||W===sa)&&(Nh(U,$e),U=[]),Le&&a==="2023-11"&&(W===Na||W===sa)){const Re=Yn(P,`init_extra_${ht}`);fe.push(Re);const Fe=Oe.types.callExpression(Oe.types.cloneNode(Re),ee?[]:[Oe.types.thisExpression()]);ee?U.push(Fe):ae.push(Fe)}}}if(K.length>0){const $e=t.get("body.body");let je;for(let qe=$e.length-1;qe>=0;qe--){const Le=$e[qe],gt=Le.node;if(gt.computed){if(y&&Oe.types.isClassProperty(gt,{static:!0}))continue;je=Le;break}}je!=null&&(DO(K,je),K=[])}if(ae.length>0){const $e=!!t.node.superClass;D?$e?MO(ae,D,C):RO(ae,D):t.node.body.body.unshift(GS(ae,$e)),ae=[]}U.length>0&&(t.node.body.body.push(zS(U)),U=[]);const L=VO(I),H=KO(a==="2023-11"?I:L,a),ye=WO(L);C&&ye.push(C),T&&ye.push(T);const Ie=[];let Ee=!1;const De=J&&Oe.types.callExpression(Oe.types.cloneNode(J),[]);let Me=t;const Ve=t.node,Ze=[];if(y){Ie.push(N,J);const $e=[];if(t.get("body.body").forEach(je=>{if((je.isStaticBlock()||!je.isClassMethod()&&je.node.static)&&new FS.default({constantSuper:r,methodPath:je,objectRef:N,superRef:t.node.superClass,file:e.file,refToPreserve:N}).replace(),je.isStaticBlock()){if(Bh(je,R)){const qe=A(JO(je.node),"staticBlock",Ze);U.push(Oe.types.callExpression(Oe.types.memberExpression(qe,Oe.types.identifier("call")),[Oe.types.thisExpression()]))}else U.push(HO(je.node));je.remove();return}if((je.isClassProperty()||je.isClassPrivateProperty())&&je.node.static){const qe=je.get("value");if(Bh(qe,R)){const Le=A(YO(qe.node),"fieldValue",Ze);qe.replaceWith(Oe.types.callExpression(Oe.types.memberExpression(Le,Oe.types.identifier("call")),[Oe.types.thisExpression()]))}U.length>0&&(Nh(U,je),U=[]),je.node.static=!1,$e.push(je.node),je.remove()}else if(je.isClassPrivateMethod({static:!0})){if(Bh(je,R)){const qe=A(XS(je.node),je.get("key.id").node.name,Ze);n?(je.node.params=[Oe.types.restElement(Oe.types.identifier("arg"))],je.node.body=Oe.types.blockStatement([Oe.types.returnStatement(Oe.types.callExpression(Oe.types.memberExpression(qe,Oe.types.identifier("apply")),[Oe.types.thisExpression(),Oe.types.identifier("arg")]))])):(je.node.params=je.node.params.map((Le,gt)=>Oe.types.isRestElement(Le)?Oe.types.restElement(Oe.types.identifier("arg")):Oe.types.identifier("_"+gt)),je.node.body=Oe.types.blockStatement([Oe.types.returnStatement(Oe.types.callExpression(Oe.types.memberExpression(qe,Oe.types.identifier("apply")),[Oe.types.thisExpression(),Oe.types.identifier("arguments")]))]))}je.node.static=!1,$e.push(je.node),je.remove()}}),$e.length>0||U.length>0){const je=Oe.template.expression.ast`
|
|
2528
2528
|
class extends ${e.addHelper("identity")} {}
|
|
2529
|
-
`;je.body.body=[Oe.types.classProperty(Oe.types.toExpression(Ve),void 0,void 0,void 0,!0,!0),...$e];const qe=[],Le=Oe.types.newExpression(je,[]);U.length>0&&qe.push(...U),De&&(Ee=!0,qe.push(De)),qe.length>0?(qe.unshift(Oe.types.callExpression(Oe.types.super(),[Oe.types.cloneNode(N)])),je.body.body.push(GS(qe,!1))):Le.arguments.push(Oe.types.cloneNode(N));const[gt]=t.replaceWith(Le);Me=gt.get("callee").get("body").get("body.0.key")}}!Ee&&De&&t.node.body.body.push(Oe.types.staticBlock([Oe.types.expressionStatement(De)]));let{superClass:ut}=Ve;if(ut&&(a==="2023-11"||a==="2023-05")){const $e=t.scope.maybeGenerateMemoised(ut);$e&&(Ve.superClass=Oe.types.assignmentExpression("=",$e,ut),ut=$e)}const st=Oe.types.staticBlock([]);Ve.body.body.unshift(st);const dt=st.body;if(K.length>0){const $e=Me.get("body.body");let je;for(const qe of $e)if((qe.isClassProperty()||qe.isClassMethod())&&qe.node.kind!=="constructor"){je=qe;break}je!=null?(QO(je),El(K,je)):(Ve.body.body.unshift(Oe.types.classProperty(Oe.types.sequenceExpression([...K,Oe.types.stringLiteral("_")]),void 0,void 0,void 0,!0,!0)),dt.push(Oe.types.expressionStatement(Oe.types.unaryExpression("delete",Oe.types.memberExpression(Oe.types.thisExpression(),Oe.types.identifier("_")))))),K=[]}if(dt.push(Oe.types.expressionStatement(t4(ye,Ie,H,ue??Oe.types.arrayExpression(ce),Oe.types.numericLiteral(Ae),he?Y:null,E,Oe.types.cloneNode(ut),e,a))),T&&dt.push(Oe.types.expressionStatement(Oe.types.callExpression(Oe.types.cloneNode(T),[Oe.types.thisExpression()]))),Ze.length>0&&dt.push(...Ze.map($e=>Oe.types.expressionStatement($e))),t.insertBefore(O.map($e=>Oe.types.expressionStatement($e))),Ce)if(!P.getBinding(N.name).constantViolations.length)t.insertBefore(Oe.types.variableDeclaration("let",[Oe.types.variableDeclarator(Oe.types.cloneNode(N))]));else{const je=P.generateUidIdentifier("t"+N.name),qe=N;t.replaceWithMultiple([Oe.types.variableDeclaration("let",[Oe.types.variableDeclarator(Oe.types.cloneNode(qe)),Oe.types.variableDeclarator(je)]),Oe.types.blockStatement([Oe.types.variableDeclaration("let",[Oe.types.variableDeclarator(Oe.types.cloneNode(N))]),t.node,Oe.types.expressionStatement(Oe.types.assignmentExpression("=",Oe.types.cloneNode(je),Oe.types.cloneNode(N)))]),Oe.types.expressionStatement(Oe.types.assignmentExpression("=",Oe.types.cloneNode(qe),Oe.types.cloneNode(je)))])}return Z.size>0&&ZO(t,Z),t.scope.crawl(),t}function t4(t,e,r,n,s,o,a,u,p,y){let h,g;const b=[a?QS(p,a):Oe.types.thisExpression(),n,r];return y!=="2023-11"&&b.splice(1,2,r,n),y==="2021-12"||y==="2022-03"&&!p.availableHelper("applyDecs2203R")?(h=Oe.types.arrayPattern([...t,...e]),g=Oe.types.callExpression(p.addHelper(y==="2021-12"?"applyDecs":"applyDecs2203"),b),Oe.types.assignmentExpression("=",h,g)):(y==="2022-03"?g=Oe.types.callExpression(p.addHelper("applyDecs2203R"),b):y==="2023-01"?(o&&b.push(Dh(o)),g=Oe.types.callExpression(p.addHelper("applyDecs2301"),b)):y==="2023-05"&&((o||u||s.value!==0)&&b.push(s),o?b.push(Dh(o)):u&&b.push(Oe.types.unaryExpression("void",Oe.types.numericLiteral(0))),u&&b.push(u),g=Oe.types.callExpression(p.addHelper("applyDecs2305"),b)),y==="2023-11"&&((o||u||s.value!==0)&&b.push(s),o?b.push(Dh(o)):u&&b.push(Oe.types.unaryExpression("void",Oe.types.numericLiteral(0))),u&&b.push(u),g=Oe.types.callExpression(p.addHelper("applyDecs2311"),b)),t.length>0?e.length>0?h=Oe.types.objectPattern([Oe.types.objectProperty(Oe.types.identifier("e"),Oe.types.arrayPattern(t)),Oe.types.objectProperty(Oe.types.identifier("c"),Oe.types.arrayPattern(e))]):(h=Oe.types.arrayPattern(t),g=Oe.types.memberExpression(g,Oe.types.identifier("e"),!1,!1)):(h=Oe.types.arrayPattern(e),g=Oe.types.memberExpression(g,Oe.types.identifier("c"),!1,!1)),Oe.types.assignmentExpression("=",h,g))}function r4(t){return t.type==="Identifier"?t.name==="__proto__":t.value==="__proto__"}function xl(t){return t.decorators&&t.decorators.length>0}function n4(t){switch(t.type){case"ClassAccessorProperty":return!0;case"ClassMethod":case"ClassProperty":case"ClassPrivateMethod":case"ClassPrivateProperty":return xl(t);default:return!1}}function i4(t){return xl(t)||t.body.body.some(n4)}function ZS(t,e){function r(n,s,o){switch(s.type){case"StringLiteral":return Oe.types.stringLiteral(s.value);case"NumericLiteral":case"BigIntLiteral":{const a=s.value+"";return n.get("key").replaceWith(Oe.types.stringLiteral(a)),Oe.types.stringLiteral(a)}default:{const a=n.scope.maybeGenerateMemoised(s);return n.get("key").replaceWith(Oe.types.assignmentExpression("=",a,kh(o,s))),Oe.types.cloneNode(a)}}}return{VariableDeclarator(n,s){const o=n.node.id;if(o.type==="Identifier"){const a=(0,ia.skipTransparentExprWrappers)(n.get("init"));if(t(a)){const u=o.name;e(a,s,u)}}},AssignmentExpression(n,s){const o=n.node.left;if(o.type==="Identifier"){const a=(0,ia.skipTransparentExprWrappers)(n.get("right"));if(t(a))switch(n.node.operator){case"=":case"&&=":case"||=":case"??=":e(a,s,o.name)}}},AssignmentPattern(n,s){const o=n.node.left;if(o.type==="Identifier"){const a=(0,ia.skipTransparentExprWrappers)(n.get("right"));if(t(a)){const u=o.name;e(a,s,u)}}},ObjectExpression(n,s){for(const o of n.get("properties")){if(!o.isObjectProperty())continue;const{node:a}=o,u=a.key,p=(0,ia.skipTransparentExprWrappers)(o.get("value"));if(t(p)){if(a.computed){const y=r(o,u,s);e(p,s,y)}else if(!r4(u))if(u.type==="Identifier")e(p,s,u.name);else{const y=Oe.types.stringLiteral(u.value+"");e(p,s,y)}}}},ClassPrivateProperty(n,s){const{node:o}=n,a=(0,ia.skipTransparentExprWrappers)(n.get("value"));if(t(a)){const u=Oe.types.stringLiteral("#"+o.key.id.name);e(a,s,u)}},ClassAccessorProperty(n,s){const{node:o}=n,a=o.key,u=(0,ia.skipTransparentExprWrappers)(n.get("value"));if(t(u))if(o.computed){const p=r(n,a,s);e(u,s,p)}else if(a.type==="Identifier")e(u,s,a.name);else if(a.type==="PrivateName"){const p=Oe.types.stringLiteral("#"+a.id.name);e(u,s,p)}else{const p=Oe.types.stringLiteral(a.value+"");e(u,s,p)}},ClassProperty(n,s){const{node:o}=n,a=o.key,u=(0,ia.skipTransparentExprWrappers)(n.get("value"));if(t(u))if(o.computed){const p=r(n,a,s);e(u,s,p)}else if(a.type==="Identifier")e(u,s,a.name);else{const p=Oe.types.stringLiteral(a.value+"");e(u,s,p)}}}}function s4(t){return t.isClassExpression({id:null})&&i4(t.node)}function Yn(t,e){const r=t.generateUidIdentifier(e);return t.push({id:r,kind:"let"}),Oe.types.cloneNode(r)}function a4({assertVersion:t,assumption:e},{loose:r},n,s){var o,a;t(n==="2023-11"||n==="2023-05"||n==="2023-01"?"^7.21.0":n==="2021-12"?"^7.16.0":"^7.19.0");const u=new WeakSet,p=(o=e("constantSuper"))!=null?o:r,y=(a=e("ignoreFunctionLength"))!=null?a:r,h=ZS(s4,g);function g(b,S,O){var P;if(u.has(b))return;const{node:A}=b;O??(O=(P=A.id)==null?void 0:P.name);const C=e4(b,S,p,y,O,h,n);if(C){u.add(C);return}u.add(b)}return{name:"proposal-decorators",inherits:s,visitor:Object.assign({ExportDefaultDeclaration(b,S){const{declaration:O}=b.node;if((O==null?void 0:O.type)==="ClassDeclaration"&&xl(O)){var P;const A=!O.id;(P=b.splitExportDeclaration)!=null||(b.splitExportDeclaration=$r().NodePath.prototype.splitExportDeclaration);const C=b.splitExportDeclaration();A&&g(C,S,Oe.types.stringLiteral("default"))}},ExportNamedDeclaration(b){const{declaration:S}=b.node;if((S==null?void 0:S.type)==="ClassDeclaration"&&xl(S)){var O;(O=b.splitExportDeclaration)!=null||(b.splitExportDeclaration=$r().NodePath.prototype.splitExportDeclaration),b.splitExportDeclaration()}},Class(b,S){g(b,S,void 0)}},h)}}var Rh={};Object.defineProperty(Rh,"__esModule",{value:!0}),Rh.buildDecoratedClass=p4;var
|
|
2529
|
+
`;je.body.body=[Oe.types.classProperty(Oe.types.toExpression(Ve),void 0,void 0,void 0,!0,!0),...$e];const qe=[],Le=Oe.types.newExpression(je,[]);U.length>0&&qe.push(...U),De&&(Ee=!0,qe.push(De)),qe.length>0?(qe.unshift(Oe.types.callExpression(Oe.types.super(),[Oe.types.cloneNode(N)])),je.body.body.push(GS(qe,!1))):Le.arguments.push(Oe.types.cloneNode(N));const[gt]=t.replaceWith(Le);Me=gt.get("callee").get("body").get("body.0.key")}}!Ee&&De&&t.node.body.body.push(Oe.types.staticBlock([Oe.types.expressionStatement(De)]));let{superClass:ut}=Ve;if(ut&&(a==="2023-11"||a==="2023-05")){const $e=t.scope.maybeGenerateMemoised(ut);$e&&(Ve.superClass=Oe.types.assignmentExpression("=",$e,ut),ut=$e)}const st=Oe.types.staticBlock([]);Ve.body.body.unshift(st);const dt=st.body;if(K.length>0){const $e=Me.get("body.body");let je;for(const qe of $e)if((qe.isClassProperty()||qe.isClassMethod())&&qe.node.kind!=="constructor"){je=qe;break}je!=null?(QO(je),El(K,je)):(Ve.body.body.unshift(Oe.types.classProperty(Oe.types.sequenceExpression([...K,Oe.types.stringLiteral("_")]),void 0,void 0,void 0,!0,!0)),dt.push(Oe.types.expressionStatement(Oe.types.unaryExpression("delete",Oe.types.memberExpression(Oe.types.thisExpression(),Oe.types.identifier("_")))))),K=[]}if(dt.push(Oe.types.expressionStatement(t4(ye,Ie,H,ue??Oe.types.arrayExpression(ce),Oe.types.numericLiteral(Ae),he?Y:null,E,Oe.types.cloneNode(ut),e,a))),T&&dt.push(Oe.types.expressionStatement(Oe.types.callExpression(Oe.types.cloneNode(T),[Oe.types.thisExpression()]))),Ze.length>0&&dt.push(...Ze.map($e=>Oe.types.expressionStatement($e))),t.insertBefore(O.map($e=>Oe.types.expressionStatement($e))),Ce)if(!P.getBinding(N.name).constantViolations.length)t.insertBefore(Oe.types.variableDeclaration("let",[Oe.types.variableDeclarator(Oe.types.cloneNode(N))]));else{const je=P.generateUidIdentifier("t"+N.name),qe=N;t.replaceWithMultiple([Oe.types.variableDeclaration("let",[Oe.types.variableDeclarator(Oe.types.cloneNode(qe)),Oe.types.variableDeclarator(je)]),Oe.types.blockStatement([Oe.types.variableDeclaration("let",[Oe.types.variableDeclarator(Oe.types.cloneNode(N))]),t.node,Oe.types.expressionStatement(Oe.types.assignmentExpression("=",Oe.types.cloneNode(je),Oe.types.cloneNode(N)))]),Oe.types.expressionStatement(Oe.types.assignmentExpression("=",Oe.types.cloneNode(qe),Oe.types.cloneNode(je)))])}return Z.size>0&&ZO(t,Z),t.scope.crawl(),t}function t4(t,e,r,n,s,o,a,u,p,y){let h,g;const b=[a?QS(p,a):Oe.types.thisExpression(),n,r];return y!=="2023-11"&&b.splice(1,2,r,n),y==="2021-12"||y==="2022-03"&&!p.availableHelper("applyDecs2203R")?(h=Oe.types.arrayPattern([...t,...e]),g=Oe.types.callExpression(p.addHelper(y==="2021-12"?"applyDecs":"applyDecs2203"),b),Oe.types.assignmentExpression("=",h,g)):(y==="2022-03"?g=Oe.types.callExpression(p.addHelper("applyDecs2203R"),b):y==="2023-01"?(o&&b.push(Dh(o)),g=Oe.types.callExpression(p.addHelper("applyDecs2301"),b)):y==="2023-05"&&((o||u||s.value!==0)&&b.push(s),o?b.push(Dh(o)):u&&b.push(Oe.types.unaryExpression("void",Oe.types.numericLiteral(0))),u&&b.push(u),g=Oe.types.callExpression(p.addHelper("applyDecs2305"),b)),y==="2023-11"&&((o||u||s.value!==0)&&b.push(s),o?b.push(Dh(o)):u&&b.push(Oe.types.unaryExpression("void",Oe.types.numericLiteral(0))),u&&b.push(u),g=Oe.types.callExpression(p.addHelper("applyDecs2311"),b)),t.length>0?e.length>0?h=Oe.types.objectPattern([Oe.types.objectProperty(Oe.types.identifier("e"),Oe.types.arrayPattern(t)),Oe.types.objectProperty(Oe.types.identifier("c"),Oe.types.arrayPattern(e))]):(h=Oe.types.arrayPattern(t),g=Oe.types.memberExpression(g,Oe.types.identifier("e"),!1,!1)):(h=Oe.types.arrayPattern(e),g=Oe.types.memberExpression(g,Oe.types.identifier("c"),!1,!1)),Oe.types.assignmentExpression("=",h,g))}function r4(t){return t.type==="Identifier"?t.name==="__proto__":t.value==="__proto__"}function xl(t){return t.decorators&&t.decorators.length>0}function n4(t){switch(t.type){case"ClassAccessorProperty":return!0;case"ClassMethod":case"ClassProperty":case"ClassPrivateMethod":case"ClassPrivateProperty":return xl(t);default:return!1}}function i4(t){return xl(t)||t.body.body.some(n4)}function ZS(t,e){function r(n,s,o){switch(s.type){case"StringLiteral":return Oe.types.stringLiteral(s.value);case"NumericLiteral":case"BigIntLiteral":{const a=s.value+"";return n.get("key").replaceWith(Oe.types.stringLiteral(a)),Oe.types.stringLiteral(a)}default:{const a=n.scope.maybeGenerateMemoised(s);return n.get("key").replaceWith(Oe.types.assignmentExpression("=",a,kh(o,s))),Oe.types.cloneNode(a)}}}return{VariableDeclarator(n,s){const o=n.node.id;if(o.type==="Identifier"){const a=(0,ia.skipTransparentExprWrappers)(n.get("init"));if(t(a)){const u=o.name;e(a,s,u)}}},AssignmentExpression(n,s){const o=n.node.left;if(o.type==="Identifier"){const a=(0,ia.skipTransparentExprWrappers)(n.get("right"));if(t(a))switch(n.node.operator){case"=":case"&&=":case"||=":case"??=":e(a,s,o.name)}}},AssignmentPattern(n,s){const o=n.node.left;if(o.type==="Identifier"){const a=(0,ia.skipTransparentExprWrappers)(n.get("right"));if(t(a)){const u=o.name;e(a,s,u)}}},ObjectExpression(n,s){for(const o of n.get("properties")){if(!o.isObjectProperty())continue;const{node:a}=o,u=a.key,p=(0,ia.skipTransparentExprWrappers)(o.get("value"));if(t(p)){if(a.computed){const y=r(o,u,s);e(p,s,y)}else if(!r4(u))if(u.type==="Identifier")e(p,s,u.name);else{const y=Oe.types.stringLiteral(u.value+"");e(p,s,y)}}}},ClassPrivateProperty(n,s){const{node:o}=n,a=(0,ia.skipTransparentExprWrappers)(n.get("value"));if(t(a)){const u=Oe.types.stringLiteral("#"+o.key.id.name);e(a,s,u)}},ClassAccessorProperty(n,s){const{node:o}=n,a=o.key,u=(0,ia.skipTransparentExprWrappers)(n.get("value"));if(t(u))if(o.computed){const p=r(n,a,s);e(u,s,p)}else if(a.type==="Identifier")e(u,s,a.name);else if(a.type==="PrivateName"){const p=Oe.types.stringLiteral("#"+a.id.name);e(u,s,p)}else{const p=Oe.types.stringLiteral(a.value+"");e(u,s,p)}},ClassProperty(n,s){const{node:o}=n,a=o.key,u=(0,ia.skipTransparentExprWrappers)(n.get("value"));if(t(u))if(o.computed){const p=r(n,a,s);e(u,s,p)}else if(a.type==="Identifier")e(u,s,a.name);else{const p=Oe.types.stringLiteral(a.value+"");e(u,s,p)}}}}function s4(t){return t.isClassExpression({id:null})&&i4(t.node)}function Yn(t,e){const r=t.generateUidIdentifier(e);return t.push({id:r,kind:"let"}),Oe.types.cloneNode(r)}function a4({assertVersion:t,assumption:e},{loose:r},n,s){var o,a;t(n==="2023-11"||n==="2023-05"||n==="2023-01"?"^7.21.0":n==="2021-12"?"^7.16.0":"^7.19.0");const u=new WeakSet,p=(o=e("constantSuper"))!=null?o:r,y=(a=e("ignoreFunctionLength"))!=null?a:r,h=ZS(s4,g);function g(b,S,O){var P;if(u.has(b))return;const{node:A}=b;O??(O=(P=A.id)==null?void 0:P.name);const C=e4(b,S,p,y,O,h,n);if(C){u.add(C);return}u.add(b)}return{name:"proposal-decorators",inherits:s,visitor:Object.assign({ExportDefaultDeclaration(b,S){const{declaration:O}=b.node;if((O==null?void 0:O.type)==="ClassDeclaration"&&xl(O)){var P;const A=!O.id;(P=b.splitExportDeclaration)!=null||(b.splitExportDeclaration=$r().NodePath.prototype.splitExportDeclaration);const C=b.splitExportDeclaration();A&&g(C,S,Oe.types.stringLiteral("default"))}},ExportNamedDeclaration(b){const{declaration:S}=b.node;if((S==null?void 0:S.type)==="ClassDeclaration"&&xl(S)){var O;(O=b.splitExportDeclaration)!=null||(b.splitExportDeclaration=$r().NodePath.prototype.splitExportDeclaration),b.splitExportDeclaration()}},Class(b,S){g(b,S,void 0)}},h)}}var Rh={};Object.defineProperty(Rh,"__esModule",{value:!0}),Rh.buildDecoratedClass=p4;var gr=Vr(),o4=na;function To(t,e){return e?gr.types.objectProperty(gr.types.identifier(t),e):null}function l4(t,e){return gr.types.objectMethod("method",gr.types.identifier(t),[],gr.types.blockStatement(e))}function eT(t){let e;return t.decorators&&t.decorators.length>0&&(e=gr.types.arrayExpression(t.decorators.map(r=>r.expression))),t.decorators=void 0,e}function c4(t){return t.computed?t.key:gr.types.isIdentifier(t.key)?gr.types.stringLiteral(t.key.name):gr.types.stringLiteral(String(t.key.value))}function u4(t,e,r,n){const s=n.isClassMethod();if(n.isPrivate())throw n.buildCodeFrameError(`Private ${s?"methods":"fields"} in decorated classes are not supported yet.`);if(n.node.type==="ClassAccessorProperty")throw n.buildCodeFrameError('Accessor properties are not supported in 2018-09 decorator transform, please specify { "version": "2021-12" } instead.');if(n.node.type==="StaticBlock")throw n.buildCodeFrameError('Static blocks are not supported in 2018-09 decorator transform, please specify { "version": "2021-12" } instead.');const{node:o,scope:a}=n;n.isTSDeclareMethod()||new o4.default({methodPath:n,objectRef:e,superRef:r,file:t,refToPreserve:e}).replace();const u=[To("kind",gr.types.stringLiteral(gr.types.isClassMethod(o)?o.kind:"field")),To("decorators",eT(o)),To("static",o.static&&gr.types.booleanLiteral(!0)),To("key",c4(o))].filter(Boolean);if(s){var p;(p=n.ensureFunctionName)!=null||(n.ensureFunctionName=$r().NodePath.prototype.ensureFunctionName),n.ensureFunctionName(!1),u.push(To("value",gr.types.toExpression(n.node)))}else gr.types.isClassProperty(o)&&o.value?u.push(l4("value",gr.template.statements.ast`return ${o.value}`)):u.push(To("value",a.buildUndefinedNode()));return n.remove(),gr.types.objectExpression(u)}function f4(t){return t.addHelper("decorate")}function p4(t,e,r,n){const{node:s,scope:o}=e,a=o.generateUidIdentifier("initialize"),u=s.id&&e.isDeclaration(),p=e.isInStrictMode(),{superClass:y}=s;s.type="ClassDeclaration",s.id||(s.id=gr.types.cloneNode(t));let h;y&&(h=o.generateUidIdentifierBasedOnNode(s.superClass,"super"),s.superClass=h);const g=eT(s),b=gr.types.arrayExpression(r.filter(A=>!A.node.abstract&&A.node.type!=="TSIndexSignature").map(A=>u4(n,s.id,h,A))),S=gr.template.expression.ast`
|
|
2530
2530
|
${f4(n)}(
|
|
2531
|
-
${g||
|
|
2532
|
-
function (${a}, ${y?
|
|
2531
|
+
${g||gr.types.nullLiteral()},
|
|
2532
|
+
function (${a}, ${y?gr.types.cloneNode(h):null}) {
|
|
2533
2533
|
${s}
|
|
2534
|
-
return { F: ${
|
|
2534
|
+
return { F: ${gr.types.cloneNode(s.id)}, d: ${b} };
|
|
2535
2535
|
},
|
|
2536
2536
|
${y}
|
|
2537
2537
|
)
|
|
2538
|
-
`;p||S.arguments[1].body.directives.push(
|
|
2539
|
-
${
|
|
2538
|
+
`;p||S.arguments[1].body.directives.push(gr.types.directive(gr.types.directiveLiteral("use strict")));let O=S,P="arguments.1.body.body.0";return u&&(O=gr.template.statement.ast`let ${t} = ${S}`,P="declarations.0.init."+P),{instanceNodes:[gr.template.statement.ast`
|
|
2539
|
+
${gr.types.cloneNode(a)}(this)
|
|
2540
2540
|
`],wrapClass(A){return A.replaceWith(O),A.get(P)}}}var ka={};Object.defineProperty(ka,"__esModule",{value:!0}),ka.FEATURES=void 0,ka.enableFeature=d4,ka.isLoose=Mh,ka.shouldTransform=h4;var tT=Oa;const qs=ka.FEATURES=Object.freeze({fields:2,privateMethods:4,decorators:8,privateIn:16,staticBlocks:32}),rT=new Map([[qs.fields,"@babel/plugin-transform-class-properties"],[qs.privateMethods,"@babel/plugin-transform-private-methods"],[qs.privateIn,"@babel/plugin-transform-private-property-in-object"]]),jh="@babel/plugin-class-features/featuresKey",_l="@babel/plugin-class-features/looseKey";var Da="@babel/plugin-class-features/looseLowPriorityKey/#__internal__@babel/preset-env__please-overwrite-loose-instead-of-throwing",nT=function(t,e){return!!(t.get(Da)&e)};function d4(t,e,r){(!$s(t,e)||nT(t,e))&&(t.set(jh,t.get(jh)|e),r==="#__internal__@babel/preset-env__prefer-true-but-false-is-ok-if-it-prevents-an-error"?(_f(t,e,!0),t.set(Da,t.get(Da)|e)):r==="#__internal__@babel/preset-env__prefer-false-but-true-is-ok-if-it-prevents-an-error"?(_f(t,e,!1),t.set(Da,t.get(Da)|e)):_f(t,e,r));let n;for(const[o,a]of rT){if(!$s(t,o)||nT(t,o))continue;const u=Mh(t,o);if(n===!u)throw new Error(`'loose' mode configuration must be the same for @babel/plugin-transform-class-properties, @babel/plugin-transform-private-methods and @babel/plugin-transform-private-property-in-object (when they are enabled).
|
|
2541
2541
|
|
|
2542
2542
|
`+iT(t));n=u;var s=a}if(n!==void 0)for(const[o,a]of rT)$s(t,o)&&Mh(t,o)!==n&&(_f(t,o,n),console.warn(`Though the "loose" option was set to "${!n}" in your @babel/preset-env config, it will not be used for ${a} since the "loose" mode option was set to "${n}" for ${s}.
|