@sciol/xyzen 1.9.97-beta.6cb1007 → 1.9.97

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/xyzen.umd.js CHANGED
@@ -570,7 +570,7 @@ const partysocket = new PartySocket({
570
570
  WebSocket: WS
571
571
  });
572
572
 
573
- `),HNt=!0);const o=this._options.WebSocket||WebSocket;this._debug("connect",{url:r,protocols:i}),this._ws=i?new o(r,i):new o(r),this._ws.binaryType=this._binaryType,this._connectLock=!1,this._addListeners(),this._connectTimeout=setTimeout(()=>this._handleTimeout(),n)}).catch(r=>{this._connectLock=!1,this._handleError(new bRe.ErrorEvent(Error(r.message),this))})}_handleTimeout(){this._debug("timeout event"),this._handleError(new bRe.ErrorEvent(Error("TIMEOUT"),this))}_disconnect(e=1e3,n){if(this._clearTimeouts(),!!this._ws){this._removeListeners();try{(this._ws.readyState===this.OPEN||this._ws.readyState===this.CONNECTING)&&this._ws.close(e,n),this._handleClose(new bRe.CloseEvent(e,n,this))}catch{}}}_acceptOpen(){this._debug("accept open"),this._retryCount=0}_handleOpen=e=>{this._debug("open event");const{minUptime:n=e3.minUptime}=this._options;clearTimeout(this._connectTimeout),this._uptimeTimeout=setTimeout(()=>this._acceptOpen(),n),MFr(this._ws,"WebSocket is not defined"),this._ws.binaryType=this._binaryType,this._messageQueue.forEach(r=>{this._ws?.send(r)}),this._messageQueue=[],this.onopen&&this.onopen(e),this.dispatchEvent(ole(e))};_handleMessage=e=>{this._debug("message event"),this.onmessage&&this.onmessage(e),this.dispatchEvent(ole(e))};_handleError=e=>{this._debug("error event",e.message),this._disconnect(void 0,e.message==="TIMEOUT"?"timeout":void 0),this.onerror&&this.onerror(e),this._debug("exec error listeners"),this.dispatchEvent(ole(e)),this._connect()};_handleClose=e=>{this._debug("close event"),this._clearTimeouts(),this._shouldReconnect&&this._connect(),this.onclose&&this.onclose(e),this.dispatchEvent(ole(e))};_removeListeners(){this._ws&&(this._debug("removeListeners"),this._ws.removeEventListener("open",this._handleOpen),this._ws.removeEventListener("close",this._handleClose),this._ws.removeEventListener("message",this._handleMessage),this._ws.removeEventListener("error",this._handleError))}_addListeners(){this._ws&&(this._debug("addListeners"),this._ws.addEventListener("open",this._handleOpen),this._ws.addEventListener("close",this._handleClose),this._ws.addEventListener("message",this._handleMessage),this._ws.addEventListener("error",this._handleError))}_clearTimeouts(){clearTimeout(this._connectTimeout),clearTimeout(this._uptimeTimeout)}};const ck=Object.create(null);ck.open="0",ck.close="1",ck.ping="2",ck.pong="3",ck.message="4",ck.upgrade="5",ck.noop="6";const lle=Object.create(null);Object.keys(ck).forEach(t=>{lle[ck[t]]=t});const yRe={type:"error",data:"parser error"},WNt=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",YNt=typeof ArrayBuffer=="function",VNt=t=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(t):t&&t.buffer instanceof ArrayBuffer,vRe=({type:t,data:e},n,r)=>WNt&&e instanceof Blob?n?r(e):KNt(e,r):YNt&&(e instanceof ArrayBuffer||VNt(e))?n?r(e):KNt(new Blob([e]),r):r(ck[t]+(e||"")),KNt=(t,e)=>{const n=new FileReader;return n.onload=function(){const r=n.result.split(",")[1];e("b"+(r||""))},n.readAsDataURL(t)};function ZNt(t){return t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}let _Re;function jFr(t,e){if(WNt&&t.data instanceof Blob)return t.data.arrayBuffer().then(ZNt).then(e);if(YNt&&(t.data instanceof ArrayBuffer||VNt(t.data)))return e(ZNt(t.data));vRe(t,!1,n=>{_Re||(_Re=new TextEncoder),e(_Re.encode(n))})}const XNt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",oG=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let t=0;t<XNt.length;t++)oG[XNt.charCodeAt(t)]=t;const zFr=t=>{let e=t.length*.75,n=t.length,r,i=0,o,l,u,d;t[t.length-1]==="="&&(e--,t[t.length-2]==="="&&e--);const p=new ArrayBuffer(e),m=new Uint8Array(p);for(r=0;r<n;r+=4)o=oG[t.charCodeAt(r)],l=oG[t.charCodeAt(r+1)],u=oG[t.charCodeAt(r+2)],d=oG[t.charCodeAt(r+3)],m[i++]=o<<2|l>>4,m[i++]=(l&15)<<4|u>>2,m[i++]=(u&3)<<6|d&63;return p},UFr=typeof ArrayBuffer=="function",wRe=(t,e)=>{if(typeof t!="string")return{type:"message",data:JNt(t,e)};const n=t.charAt(0);return n==="b"?{type:"message",data:qFr(t.substring(1),e)}:lle[n]?t.length>1?{type:lle[n],data:t.substring(1)}:{type:lle[n]}:yRe},qFr=(t,e)=>{if(UFr){const n=zFr(t);return JNt(n,e)}else return{base64:!0,data:t}},JNt=(t,e)=>e==="blob"?t instanceof Blob?t:new Blob([t]):t instanceof ArrayBuffer?t:t.buffer,eRt="",GFr=(t,e)=>{const n=t.length,r=new Array(n);let i=0;t.forEach((o,l)=>{vRe(o,!1,u=>{r[l]=u,++i===n&&e(r.join(eRt))})})},HFr=(t,e)=>{const n=t.split(eRt),r=[];for(let i=0;i<n.length;i++){const o=wRe(n[i],e);if(r.push(o),o.type==="error")break}return r};function WFr(){return new TransformStream({transform(t,e){jFr(t,n=>{const r=n.length;let i;if(r<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,r);else if(r<65536){i=new Uint8Array(3);const o=new DataView(i.buffer);o.setUint8(0,126),o.setUint16(1,r)}else{i=new Uint8Array(9);const o=new DataView(i.buffer);o.setUint8(0,127),o.setBigUint64(1,BigInt(r))}t.data&&typeof t.data!="string"&&(i[0]|=128),e.enqueue(i),e.enqueue(n)})}})}let xRe;function cle(t){return t.reduce((e,n)=>e+n.length,0)}function ule(t,e){if(t[0].length===e)return t.shift();const n=new Uint8Array(e);let r=0;for(let i=0;i<e;i++)n[i]=t[0][r++],r===t[0].length&&(t.shift(),r=0);return t.length&&r<t[0].length&&(t[0]=t[0].slice(r)),n}function YFr(t,e){xRe||(xRe=new TextDecoder);const n=[];let r=0,i=-1,o=!1;return new TransformStream({transform(l,u){for(n.push(l);;){if(r===0){if(cle(n)<1)break;const d=ule(n,1);o=(d[0]&128)===128,i=d[0]&127,i<126?r=3:i===126?r=1:r=2}else if(r===1){if(cle(n)<2)break;const d=ule(n,2);i=new DataView(d.buffer,d.byteOffset,d.length).getUint16(0),r=3}else if(r===2){if(cle(n)<8)break;const d=ule(n,8),p=new DataView(d.buffer,d.byteOffset,d.length),m=p.getUint32(0);if(m>Math.pow(2,21)-1){u.enqueue(yRe);break}i=m*Math.pow(2,32)+p.getUint32(4),r=3}else{if(cle(n)<i)break;const d=ule(n,i);u.enqueue(wRe(o?d:xRe.decode(d),e)),r=0}if(i===0||i>t){u.enqueue(yRe);break}}}})}const tRt=4;function mp(t){if(t)return VFr(t)}function VFr(t){for(var e in mp.prototype)t[e]=mp.prototype[e];return t}mp.prototype.on=mp.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},mp.prototype.once=function(t,e){function n(){this.off(t,n),e.apply(this,arguments)}return n.fn=e,this.on(t,n),this},mp.prototype.off=mp.prototype.removeListener=mp.prototype.removeAllListeners=mp.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var n=this._callbacks["$"+t];if(!n)return this;if(arguments.length==1)return delete this._callbacks["$"+t],this;for(var r,i=0;i<n.length;i++)if(r=n[i],r===e||r.fn===e){n.splice(i,1);break}return n.length===0&&delete this._callbacks["$"+t],this},mp.prototype.emit=function(t){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),n=this._callbacks["$"+t],r=1;r<arguments.length;r++)e[r-1]=arguments[r];if(n){n=n.slice(0);for(var r=0,i=n.length;r<i;++r)n[r].apply(this,e)}return this},mp.prototype.emitReserved=mp.prototype.emit,mp.prototype.listeners=function(t){return this._callbacks=this._callbacks||{},this._callbacks["$"+t]||[]},mp.prototype.hasListeners=function(t){return!!this.listeners(t).length};const Dy=typeof self<"u"?self:typeof window<"u"?window:Function("return this")();function nRt(t,...e){return e.reduce((n,r)=>(t.hasOwnProperty(r)&&(n[r]=t[r]),n),{})}const KFr=Dy.setTimeout,ZFr=Dy.clearTimeout;function dle(t,e){e.useNativeTimers?(t.setTimeoutFn=KFr.bind(Dy),t.clearTimeoutFn=ZFr.bind(Dy)):(t.setTimeoutFn=Dy.setTimeout.bind(Dy),t.clearTimeoutFn=Dy.clearTimeout.bind(Dy))}const XFr=1.33;function JFr(t){return typeof t=="string"?e8r(t):Math.ceil((t.byteLength||t.size)*XFr)}function e8r(t){let e=0,n=0;for(let r=0,i=t.length;r<i;r++)e=t.charCodeAt(r),e<128?n+=1:e<2048?n+=2:e<55296||e>=57344?n+=3:(r++,n+=4);return n}function t8r(t){let e="";for(let n in t)t.hasOwnProperty(n)&&(e.length&&(e+="&"),e+=encodeURIComponent(n)+"="+encodeURIComponent(t[n]));return e}function n8r(t){let e={},n=t.split("&");for(let r=0,i=n.length;r<i;r++){let o=n[r].split("=");e[decodeURIComponent(o[0])]=decodeURIComponent(o[1])}return e}class r8r extends Error{constructor(e,n,r){super(e),this.description=n,this.context=r,this.type="TransportError"}}class kRe extends mp{constructor(e){super(),this.writable=!1,dle(this,e),this.opts=e,this.query=e.query,this.socket=e.socket}onError(e,n,r){return super.emitReserved("error",new r8r(e,n,r)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(e){this.readyState==="open"&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const n=wRe(e,this.socket.binaryType);this.onPacket(n)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,n={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(n)}_hostname(){const e=this.opts.hostname;return e.indexOf(":")===-1?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&+(this.opts.port!==443)||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(e){const n=t8r(e);return n.length?"?"+n:""}}const rRt="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),ERe=64,a8r={};let aRt=0,ple=0,iRt;function sRt(t){let e="";do e=rRt[t%ERe]+e,t=Math.floor(t/ERe);while(t>0);return e}function oRt(){const t=sRt(+new Date);return t!==iRt?(aRt=0,iRt=t):t+"."+sRt(aRt++)}for(;ple<ERe;ple++)a8r[rRt[ple]]=ple;let lRt=!1;try{lRt=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const i8r=lRt;function cRt(t){const e=t.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||i8r))return new XMLHttpRequest}catch{}if(!e)try{return new Dy[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}function Uws(){}function s8r(){}const o8r=(function(){return new cRt({xdomain:!1}).responseType!=null})();class l8r extends kRe{constructor(e){if(super(e),this.polling=!1,typeof location<"u"){const r=location.protocol==="https:";let i=location.port;i||(i=r?"443":"80"),this.xd=typeof location<"u"&&e.hostname!==location.hostname||i!==e.port}const n=e&&e.forceBase64;this.supportsBinary=o8r&&!n,this.opts.withCredentials&&(this.cookieJar=void 0)}get name(){return"polling"}doOpen(){this.poll()}pause(e){this.readyState="pausing";const n=()=>{this.readyState="paused",e()};if(this.polling||!this.writable){let r=0;this.polling&&(r++,this.once("pollComplete",function(){--r||n()})),this.writable||(r++,this.once("drain",function(){--r||n()}))}else n()}poll(){this.polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){const n=r=>{if(this.readyState==="opening"&&r.type==="open"&&this.onOpen(),r.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(r)};HFr(e,this.socket.binaryType).forEach(n),this.readyState!=="closed"&&(this.polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this.poll())}doClose(){const e=()=>{this.write([{type:"close"}])};this.readyState==="open"?e():this.once("open",e)}write(e){this.writable=!1,GFr(e,n=>{this.doWrite(n,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const e=this.opts.secure?"https":"http",n=this.query||{};return this.opts.timestampRequests!==!1&&(n[this.opts.timestampParam]=oRt()),!this.supportsBinary&&!n.sid&&(n.b64=1),this.createUri(e,n)}request(e={}){return Object.assign(e,{xd:this.xd,cookieJar:this.cookieJar},this.opts),new gF(this.uri(),e)}doWrite(e,n){const r=this.request({method:"POST",data:e});r.on("success",n),r.on("error",(i,o)=>{this.onError("xhr post error",i,o)})}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(n,r)=>{this.onError("xhr poll error",n,r)}),this.pollXhr=e}}let gF=class Uxe extends mp{constructor(e,n){super(),dle(this,n),this.opts=n,this.method=n.method||"GET",this.uri=e,this.data=n.data!==void 0?n.data:null,this.create()}create(){var e;const n=nRt(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");n.xdomain=!!this.opts.xd;const r=this.xhr=new cRt(n);try{r.open(this.method,this.uri,!0);try{if(this.opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let i in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(i)&&r.setRequestHeader(i,this.opts.extraHeaders[i])}}catch{}if(this.method==="POST")try{r.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{r.setRequestHeader("Accept","*/*")}catch{}(e=this.opts.cookieJar)===null||e===void 0||e.addCookies(r),"withCredentials"in r&&(r.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(r.timeout=this.opts.requestTimeout),r.onreadystatechange=()=>{var i;r.readyState===3&&((i=this.opts.cookieJar)===null||i===void 0||i.parseCookies(r)),r.readyState===4&&(r.status===200||r.status===1223?this.onLoad():this.setTimeoutFn(()=>{this.onError(typeof r.status=="number"?r.status:0)},0))},r.send(this.data)}catch(i){this.setTimeoutFn(()=>{this.onError(i)},0);return}typeof document<"u"&&(this.index=Uxe.requestsCount++,Uxe.requests[this.index]=this)}onError(e){this.emitReserved("error",e,this.xhr),this.cleanup(!0)}cleanup(e){if(!(typeof this.xhr>"u"||this.xhr===null)){if(this.xhr.onreadystatechange=s8r,e)try{this.xhr.abort()}catch{}typeof document<"u"&&delete Uxe.requests[this.index],this.xhr=null}}onLoad(){const e=this.xhr.responseText;e!==null&&(this.emitReserved("data",e),this.emitReserved("success"),this.cleanup())}abort(){this.cleanup()}};if(gF.requestsCount=0,gF.requests={},typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",uRt);else if(typeof addEventListener=="function"){const t="onpagehide"in Dy?"pagehide":"unload";addEventListener(t,uRt,!1)}}function uRt(){for(let t in gF.requests)gF.requests.hasOwnProperty(t)&&gF.requests[t].abort()}const CRe=typeof Promise=="function"&&typeof Promise.resolve=="function"?e=>Promise.resolve().then(e):(e,n)=>n(e,0),mle=Dy.WebSocket||Dy.MozWebSocket,dRt=!0,c8r="arraybuffer",pRt=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class u8r extends kRe{constructor(e){super(e),this.supportsBinary=!e.forceBase64}get name(){return"websocket"}doOpen(){if(!this.check())return;const e=this.uri(),n=this.opts.protocols,r=pRt?{}:nRt(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(r.headers=this.opts.extraHeaders);try{this.ws=dRt&&!pRt?n?new mle(e,n):new mle(e):new mle(e,n,r)}catch(i){return this.emitReserved("error",i)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let n=0;n<e.length;n++){const r=e[n],i=n===e.length-1;vRe(r,this.supportsBinary,o=>{const l={};try{dRt&&this.ws.send(o)}catch{}i&&CRe(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",n=this.query||{};return this.opts.timestampRequests&&(n[this.opts.timestampParam]=oRt()),this.supportsBinary||(n.b64=1),this.createUri(e,n)}check(){return!!mle}}class d8r extends kRe{get name(){return"webtransport"}doOpen(){typeof WebTransport=="function"&&(this.transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name]),this.transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this.transport.ready.then(()=>{this.transport.createBidirectionalStream().then(e=>{const n=YFr(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=e.readable.pipeThrough(n).getReader(),i=WFr();i.readable.pipeTo(e.writable),this.writer=i.writable.getWriter();const o=()=>{r.read().then(({done:u,value:d})=>{u||(this.onPacket(d),o())}).catch(u=>{})};o();const l={type:"open"};this.query.sid&&(l.data=`{"sid":"${this.query.sid}"}`),this.writer.write(l).then(()=>this.onOpen())})}))}write(e){this.writable=!1;for(let n=0;n<e.length;n++){const r=e[n],i=n===e.length-1;this.writer.write(r).then(()=>{i&&CRe(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this.transport)===null||e===void 0||e.close()}}const p8r={websocket:u8r,webtransport:d8r,polling:l8r},m8r=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,g8r=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function SRe(t){if(t.length>2e3)throw"URI too long";const e=t,n=t.indexOf("["),r=t.indexOf("]");n!=-1&&r!=-1&&(t=t.substring(0,n)+t.substring(n,r).replace(/:/g,";")+t.substring(r,t.length));let i=m8r.exec(t||""),o={},l=14;for(;l--;)o[g8r[l]]=i[l]||"";return n!=-1&&r!=-1&&(o.source=e,o.host=o.host.substring(1,o.host.length-1).replace(/;/g,":"),o.authority=o.authority.replace("[","").replace("]","").replace(/;/g,":"),o.ipv6uri=!0),o.pathNames=h8r(o,o.path),o.queryKey=f8r(o,o.query),o}function h8r(t,e){const n=/\/{2,9}/g,r=e.replace(n,"/").split("/");return(e.slice(0,1)=="/"||e.length===0)&&r.splice(0,1),e.slice(-1)=="/"&&r.splice(r.length-1,1),r}function f8r(t,e){const n={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(r,i,o){i&&(n[i]=o)}),n}let mRt=class H7 extends mp{constructor(e,n={}){super(),this.binaryType=c8r,this.writeBuffer=[],e&&typeof e=="object"&&(n=e,e=null),e?(e=SRe(e),n.hostname=e.host,n.secure=e.protocol==="https"||e.protocol==="wss",n.port=e.port,e.query&&(n.query=e.query)):n.host&&(n.hostname=SRe(n.host).host),dle(this,n),this.secure=n.secure!=null?n.secure:typeof location<"u"&&location.protocol==="https:",n.hostname&&!n.port&&(n.port=this.secure?"443":"80"),this.hostname=n.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=n.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=n.transports||["polling","websocket","webtransport"],this.writeBuffer=[],this.prevBufferLen=0,this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},n),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=n8r(this.opts.query)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingTimeoutTimer=null,typeof addEventListener=="function"&&(this.opts.closeOnBeforeunload&&(this.beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this.beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this.offlineEventListener=()=>{this.onClose("transport close",{description:"network connection lost"})},addEventListener("offline",this.offlineEventListener,!1))),this.open()}createTransport(e){const n=Object.assign({},this.opts.query);n.EIO=tRt,n.transport=e,this.id&&(n.sid=this.id);const r=Object.assign({},this.opts,{query:n,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new p8r[e](r)}open(){let e;if(this.opts.rememberUpgrade&&H7.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1)e="websocket";else if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}else e=this.transports[0];this.readyState="opening";try{e=this.createTransport(e)}catch{this.transports.shift(),this.open();return}e.open(),this.setTransport(e)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",n=>this.onClose("transport close",n))}probe(e){let n=this.createTransport(e),r=!1;H7.priorWebsocketSuccess=!1;const i=()=>{r||(n.send([{type:"ping",data:"probe"}]),n.once("packet",g=>{if(!r)if(g.type==="pong"&&g.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",n),!n)return;H7.priorWebsocketSuccess=n.name==="websocket",this.transport.pause(()=>{r||this.readyState!=="closed"&&(m(),this.setTransport(n),n.send([{type:"upgrade"}]),this.emitReserved("upgrade",n),n=null,this.upgrading=!1,this.flush())})}else{const h=new Error("probe error");h.transport=n.name,this.emitReserved("upgradeError",h)}}))};function o(){r||(r=!0,m(),n.close(),n=null)}const l=g=>{const h=new Error("probe error: "+g);h.transport=n.name,o(),this.emitReserved("upgradeError",h)};function u(){l("transport closed")}function d(){l("socket closed")}function p(g){n&&g.name!==n.name&&o()}const m=()=>{n.removeListener("open",i),n.removeListener("error",l),n.removeListener("close",u),this.off("close",d),this.off("upgrading",p)};n.once("open",i),n.once("error",l),n.once("close",u),this.once("close",d),this.once("upgrading",p),this.upgrades.indexOf("webtransport")!==-1&&e!=="webtransport"?this.setTimeoutFn(()=>{r||n.open()},200):n.open()}onOpen(){if(this.readyState="open",H7.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush(),this.readyState==="open"&&this.opts.upgrade){let e=0;const n=this.upgrades.length;for(;e<n;e++)this.probe(this.upgrades[e])}}onPacket(e){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),this.resetPingTimeout(),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this.sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong");break;case"error":const n=new Error("server error");n.code=e.data,this.onError(n);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data);break}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this.upgrades=this.filterUpgrades(e.upgrades),this.pingInterval=e.pingInterval,this.pingTimeout=e.pingTimeout,this.maxPayload=e.maxPayload,this.onOpen(),this.readyState!=="closed"&&this.resetPingTimeout()}resetPingTimeout(){this.clearTimeoutFn(this.pingTimeoutTimer),this.pingTimeoutTimer=this.setTimeoutFn(()=>{this.onClose("ping timeout")},this.pingInterval+this.pingTimeout),this.opts.autoUnref&&this.pingTimeoutTimer.unref()}onDrain(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this.getWritablePackets();this.transport.send(e),this.prevBufferLen=e.length,this.emitReserved("flush")}}getWritablePackets(){if(!(this.maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let n=1;for(let r=0;r<this.writeBuffer.length;r++){const i=this.writeBuffer[r].data;if(i&&(n+=JFr(i)),r>0&&n>this.maxPayload)return this.writeBuffer.slice(0,r);n+=2}return this.writeBuffer}write(e,n,r){return this.sendPacket("message",e,n,r),this}send(e,n,r){return this.sendPacket("message",e,n,r),this}sendPacket(e,n,r,i){if(typeof n=="function"&&(i=n,n=void 0),typeof r=="function"&&(i=r,r=null),this.readyState==="closing"||this.readyState==="closed")return;r=r||{},r.compress=r.compress!==!1;const o={type:e,data:n,options:r};this.emitReserved("packetCreate",o),this.writeBuffer.push(o),i&&this.once("flush",i),this.flush()}close(){const e=()=>{this.onClose("forced close"),this.transport.close()},n=()=>{this.off("upgrade",n),this.off("upgradeError",n),e()},r=()=>{this.once("upgrade",n),this.once("upgradeError",n)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?r():e()}):this.upgrading?r():e()),this}onError(e){H7.priorWebsocketSuccess=!1,this.emitReserved("error",e),this.onClose("transport error",e)}onClose(e,n){(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")&&(this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),typeof removeEventListener=="function"&&(removeEventListener("beforeunload",this.beforeunloadEventListener,!1),removeEventListener("offline",this.offlineEventListener,!1)),this.readyState="closed",this.id=null,this.emitReserved("close",e,n),this.writeBuffer=[],this.prevBufferLen=0)}filterUpgrades(e){const n=[];let r=0;const i=e.length;for(;r<i;r++)~this.transports.indexOf(e[r])&&n.push(e[r]);return n}};mRt.protocol=tRt;function A8r(t,e="",n){let r=t;n=n||typeof location<"u"&&location,t==null&&(t=n.protocol+"//"+n.host),typeof t=="string"&&(t.charAt(0)==="/"&&(t.charAt(1)==="/"?t=n.protocol+t:t=n.host+t),/^(https?|wss?):\/\//.test(t)||(typeof n<"u"?t=n.protocol+"//"+t:t="https://"+t),r=SRe(t)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port="80":/^(http|ws)s$/.test(r.protocol)&&(r.port="443")),r.path=r.path||"/";const o=r.host.indexOf(":")!==-1?"["+r.host+"]":r.host;return r.id=r.protocol+"://"+o+":"+r.port+e,r.href=r.protocol+"://"+o+(n&&n.port===r.port?"":":"+r.port),r}const b8r=typeof ArrayBuffer=="function",y8r=t=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(t):t.buffer instanceof ArrayBuffer,gRt=Object.prototype.toString,v8r=typeof Blob=="function"||typeof Blob<"u"&&gRt.call(Blob)==="[object BlobConstructor]",_8r=typeof File=="function"||typeof File<"u"&&gRt.call(File)==="[object FileConstructor]";function IRe(t){return b8r&&(t instanceof ArrayBuffer||y8r(t))||v8r&&t instanceof Blob||_8r&&t instanceof File}function gle(t,e){if(!t||typeof t!="object")return!1;if(Array.isArray(t)){for(let n=0,r=t.length;n<r;n++)if(gle(t[n]))return!0;return!1}if(IRe(t))return!0;if(t.toJSON&&typeof t.toJSON=="function"&&arguments.length===1)return gle(t.toJSON(),!0);for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)&&gle(t[n]))return!0;return!1}function w8r(t){const e=[],n=t.data,r=t;return r.data=TRe(n,e),r.attachments=e.length,{packet:r,buffers:e}}function TRe(t,e){if(!t)return t;if(IRe(t)){const n={_placeholder:!0,num:e.length};return e.push(t),n}else if(Array.isArray(t)){const n=new Array(t.length);for(let r=0;r<t.length;r++)n[r]=TRe(t[r],e);return n}else if(typeof t=="object"&&!(t instanceof Date)){const n={};for(const r in t)Object.prototype.hasOwnProperty.call(t,r)&&(n[r]=TRe(t[r],e));return n}return t}function x8r(t,e){return t.data=BRe(t.data,e),delete t.attachments,t}function BRe(t,e){if(!t)return t;if(t&&t._placeholder===!0){if(typeof t.num=="number"&&t.num>=0&&t.num<e.length)return e[t.num];throw new Error("illegal attachments")}else if(Array.isArray(t))for(let n=0;n<t.length;n++)t[n]=BRe(t[n],e);else if(typeof t=="object")for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(t[n]=BRe(t[n],e));return t}const k8r=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var Oo;(function(t){t[t.CONNECT=0]="CONNECT",t[t.DISCONNECT=1]="DISCONNECT",t[t.EVENT=2]="EVENT",t[t.ACK=3]="ACK",t[t.CONNECT_ERROR=4]="CONNECT_ERROR",t[t.BINARY_EVENT=5]="BINARY_EVENT",t[t.BINARY_ACK=6]="BINARY_ACK"})(Oo||(Oo={}));class E8r{constructor(e){this.replacer=e}encode(e){return(e.type===Oo.EVENT||e.type===Oo.ACK)&&gle(e)?this.encodeAsBinary({type:e.type===Oo.EVENT?Oo.BINARY_EVENT:Oo.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let n=""+e.type;return(e.type===Oo.BINARY_EVENT||e.type===Oo.BINARY_ACK)&&(n+=e.attachments+"-"),e.nsp&&e.nsp!=="/"&&(n+=e.nsp+","),e.id!=null&&(n+=e.id),e.data!=null&&(n+=JSON.stringify(e.data,this.replacer)),n}encodeAsBinary(e){const n=w8r(e),r=this.encodeAsString(n.packet),i=n.buffers;return i.unshift(r),i}}class DRe extends mp{constructor(e){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},typeof e=="function"?{reviver:e}:e)}add(e){let n;if(typeof e=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");n=this.decodeString(e);const r=n.type===Oo.BINARY_EVENT;r||n.type===Oo.BINARY_ACK?(n.type=r?Oo.EVENT:Oo.ACK,this.reconstructor=new C8r(n),n.attachments===0&&super.emitReserved("decoded",n)):super.emitReserved("decoded",n)}else if(IRe(e)||e.base64)if(this.reconstructor)n=this.reconstructor.takeBinaryData(e),n&&(this.reconstructor=null,super.emitReserved("decoded",n));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+e)}decodeString(e){let n=0;const r={type:Number(e.charAt(0))};if(Oo[r.type]===void 0)throw new Error("unknown packet type "+r.type);if(r.type===Oo.BINARY_EVENT||r.type===Oo.BINARY_ACK){const o=n+1;for(;e.charAt(++n)!=="-"&&n!=e.length;);const l=e.substring(o,n);if(l!=Number(l)||e.charAt(n)!=="-")throw new Error("Illegal attachments");const u=Number(l);if(!S8r(u)||u<0)throw new Error("Illegal attachments");if(u>this.opts.maxAttachments)throw new Error("too many attachments");r.attachments=u}if(e.charAt(n+1)==="/"){const o=n+1;for(;++n&&!(e.charAt(n)===","||n===e.length););r.nsp=e.substring(o,n)}else r.nsp="/";const i=e.charAt(n+1);if(i!==""&&Number(i)==i){const o=n+1;for(;++n;){const l=e.charAt(n);if(l==null||Number(l)!=l){--n;break}if(n===e.length)break}r.id=Number(e.substring(o,n+1))}if(e.charAt(++n)){const o=this.tryParse(e.substr(n));if(DRe.isPayloadValid(r.type,o))r.data=o;else throw new Error("invalid payload")}return r}tryParse(e){try{return JSON.parse(e,this.opts.reviver)}catch{return!1}}static isPayloadValid(e,n){switch(e){case Oo.CONNECT:return hRt(n);case Oo.DISCONNECT:return n===void 0;case Oo.CONNECT_ERROR:return typeof n=="string"||hRt(n);case Oo.EVENT:case Oo.BINARY_EVENT:return Array.isArray(n)&&(typeof n[0]=="number"||typeof n[0]=="string"&&k8r.indexOf(n[0])===-1);case Oo.ACK:case Oo.BINARY_ACK:return Array.isArray(n)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class C8r{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const n=x8r(this.reconPack,this.buffers);return this.finishedReconstruction(),n}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const S8r=Number.isInteger||function(t){return typeof t=="number"&&isFinite(t)&&Math.floor(t)===t};function hRt(t){return Object.prototype.toString.call(t)==="[object Object]"}const I8r=Object.freeze(Object.defineProperty({__proto__:null,Decoder:DRe,Encoder:E8r,get PacketType(){return Oo}},Symbol.toStringTag,{value:"Module"}));function R_(t,e,n){return t.on(e,n),function(){t.off(e,n)}}const T8r=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});let fRt=class extends mp{constructor(e,n,r){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=n,r&&r.auth&&(this.auth=r.auth),this._opts=Object.assign({},r),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[R_(e,"open",this.onopen.bind(this)),R_(e,"packet",this.onpacket.bind(this)),R_(e,"error",this.onerror.bind(this)),R_(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...n){if(T8r.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(n.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(n),this;const r={type:Oo.EVENT,data:n};if(r.options={},r.options.compress=this.flags.compress!==!1,typeof n[n.length-1]=="function"){const l=this.ids++,u=n.pop();this._registerAckCallback(l,u),r.id=l}const i=this.io.engine&&this.io.engine.transport&&this.io.engine.transport.writable;return this.flags.volatile&&(!i||!this.connected)||(this.connected?(this.notifyOutgoingListeners(r),this.packet(r)):this.sendBuffer.push(r)),this.flags={},this}_registerAckCallback(e,n){var r;const i=(r=this.flags.timeout)!==null&&r!==void 0?r:this._opts.ackTimeout;if(i===void 0){this.acks[e]=n;return}const o=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let l=0;l<this.sendBuffer.length;l++)this.sendBuffer[l].id===e&&this.sendBuffer.splice(l,1);n.call(this,new Error("operation has timed out"))},i);this.acks[e]=(...l)=>{this.io.clearTimeoutFn(o),n.apply(this,[null,...l])}}emitWithAck(e,...n){const r=this.flags.timeout!==void 0||this._opts.ackTimeout!==void 0;return new Promise((i,o)=>{n.push((l,u)=>r?l?o(l):i(u):i(l)),this.emit(e,...n)})}_addToQueue(e){let n;typeof e[e.length-1]=="function"&&(n=e.pop());const r={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((i,...o)=>r!==this._queue[0]?void 0:(i!==null?r.tryCount>this._opts.retries&&(this._queue.shift(),n&&n(i)):(this._queue.shift(),n&&n(null,...o)),r.pending=!1,this._drainQueue())),this._queue.push(r),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||this._queue.length===0)return;const n=this._queue[0];n.pending&&!e||(n.pending=!0,n.tryCount++,this.flags=n.flags,this.emit.apply(this,n.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){typeof this.auth=="function"?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:Oo.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,n){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,n)}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case Oo.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case Oo.EVENT:case Oo.BINARY_EVENT:this.onevent(e);break;case Oo.ACK:case Oo.BINARY_ACK:this.onack(e);break;case Oo.DISCONNECT:this.ondisconnect();break;case Oo.CONNECT_ERROR:this.destroy();const r=new Error(e.data.message);r.data=e.data.data,this.emitReserved("connect_error",r);break}}onevent(e){const n=e.data||[];e.id!=null&&n.push(this.ack(e.id)),this.connected?this.emitEvent(n):this.receiveBuffer.push(Object.freeze(n))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const n=this._anyListeners.slice();for(const r of n)r.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&typeof e[e.length-1]=="string"&&(this._lastOffset=e[e.length-1])}ack(e){const n=this;let r=!1;return function(...i){r||(r=!0,n.packet({type:Oo.ACK,id:e,data:i}))}}onack(e){const n=this.acks[e.id];typeof n=="function"&&(n.apply(this,e.data),delete this.acks[e.id])}onconnect(e,n){this.id=e,this.recovered=n&&this._pid===n,this._pid=n,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:Oo.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const n=this._anyListeners;for(let r=0;r<n.length;r++)if(e===n[r])return n.splice(r,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const n=this._anyOutgoingListeners;for(let r=0;r<n.length;r++)if(e===n[r])return n.splice(r,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const n=this._anyOutgoingListeners.slice();for(const r of n)r.apply(this,e.data)}}};function hF(t){t=t||{},this.ms=t.min||100,this.max=t.max||1e4,this.factor=t.factor||2,this.jitter=t.jitter>0&&t.jitter<=1?t.jitter:0,this.attempts=0}hF.prototype.duration=function(){var t=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),n=Math.floor(e*this.jitter*t);t=(Math.floor(e*10)&1)==0?t-n:t+n}return Math.min(t,this.max)|0},hF.prototype.reset=function(){this.attempts=0},hF.prototype.setMin=function(t){this.ms=t},hF.prototype.setMax=function(t){this.max=t},hF.prototype.setJitter=function(t){this.jitter=t};class NRe extends mp{constructor(e,n){var r;super(),this.nsps={},this.subs=[],e&&typeof e=="object"&&(n=e,e=void 0),n=n||{},n.path=n.path||"/socket.io",this.opts=n,dle(this,n),this.reconnection(n.reconnection!==!1),this.reconnectionAttempts(n.reconnectionAttempts||1/0),this.reconnectionDelay(n.reconnectionDelay||1e3),this.reconnectionDelayMax(n.reconnectionDelayMax||5e3),this.randomizationFactor((r=n.randomizationFactor)!==null&&r!==void 0?r:.5),this.backoff=new hF({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(n.timeout==null?2e4:n.timeout),this._readyState="closed",this.uri=e;const i=n.parser||I8r;this.encoder=new i.Encoder,this.decoder=new i.Decoder,this._autoConnect=n.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var n;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(n=this.backoff)===null||n===void 0||n.setMin(e),this)}randomizationFactor(e){var n;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(n=this.backoff)===null||n===void 0||n.setJitter(e),this)}reconnectionDelayMax(e){var n;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(n=this.backoff)===null||n===void 0||n.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new mRt(this.uri,this.opts);const n=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const i=R_(n,"open",function(){r.onopen(),e&&e()}),o=u=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",u),e?e(u):this.maybeReconnectOnOpen()},l=R_(n,"error",o);if(this._timeout!==!1){const u=this._timeout,d=this.setTimeoutFn(()=>{i(),o(new Error("timeout")),n.close()},u);this.opts.autoUnref&&d.unref(),this.subs.push(()=>{this.clearTimeoutFn(d)})}return this.subs.push(i),this.subs.push(l),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(R_(e,"ping",this.onping.bind(this)),R_(e,"data",this.ondata.bind(this)),R_(e,"error",this.onerror.bind(this)),R_(e,"close",this.onclose.bind(this)),R_(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(n){this.onclose("parse error",n)}}ondecoded(e){CRe(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,n){let r=this.nsps[e];return r?this._autoConnect&&!r.active&&r.connect():(r=new fRt(this,e,n),this.nsps[e]=r),r}_destroy(e){const n=Object.keys(this.nsps);for(const r of n)if(this.nsps[r].active)return;this._close()}_packet(e){const n=this.encoder.encode(e);for(let r=0;r<n.length;r++)this.engine.write(n[r],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close"),this.engine&&this.engine.close()}disconnect(){return this._close()}onclose(e,n){this.cleanup(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,n),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const n=this.backoff.duration();this._reconnecting=!0;const r=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(i=>{i?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",i)):e.onreconnect()}))},n);this.opts.autoUnref&&r.unref(),this.subs.push(()=>{this.clearTimeoutFn(r)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const lG={};function hle(t,e){typeof t=="object"&&(e=t,t=void 0),e=e||{};const n=A8r(t,e.path||"/socket.io"),r=n.source,i=n.id,o=n.path,l=lG[i]&&o in lG[i].nsps,u=e.forceNew||e["force new connection"]||e.multiplex===!1||l;let d;return u?d=new NRe(r,e):(lG[i]||(lG[i]=new NRe(r,e)),d=lG[i]),n.query&&!e.query&&(e.query=n.queryKey),d.socket(n.path,e)}Object.assign(hle,{Manager:NRe,Socket:fRt,io:hle,connect:hle});var ARt=(t,e)=>t===e?!0:!t||!e||t.length!==e.length?!1:t.every((n,r)=>n===e[r]),RRe=(t,e)=>ARt(t,e)||!t&&e?.length===0||t?.length===0&&!e,B8r=(t,e)=>{const n=Array.isArray(t)?t:t?[t]:[],r=Array.isArray(e)?e:e?[e]:[];return ARt(n,r)},bRt=(t,e)=>{if(!t&&!e)return!0;if(!t||!e)return!1;try{return JSON.stringify(t)===JSON.stringify(e)}catch{return!1}},fle=(t,e)=>bRt(t.data,e.data)&&RRe(t.tags,e.tags)&&t.read===e.read&&t.archived===e.archived&&t.snoozed===e.snoozed&&t.seen===e.seen&&B8r(t.severity,e.severity);function D8r(t,e){return!e||Object.keys(e).length===0?!0:t?Object.entries(e).every(([n,r])=>{const i=t[n];if(i===void 0&&r!==void 0)return!1;if(Array.isArray(r))if(Array.isArray(i)){if(r.length!==i.length)return!1;const o=[...r].sort(),l=[...i].sort();return o.every((u,d)=>u===l[d])}else return r.includes(i);else return i===r}):!1}function N8r(t,e){return!e||e.length===0?!0:!t||t.length===0?!1:e.some(n=>t.includes(n))}function R8r(t,e){return!(e.read!==void 0&&t.isRead!==e.read||e.seen!==void 0&&t.isSeen!==e.seen||e.archived!==void 0&&t.isArchived!==e.archived||e.snoozed!==void 0&&t.isSnoozed!==e.snoozed)}function L8r(t,e){return R8r(t,e)&&N8r(t.tags,e.tags)&&D8r(t.data,e.data)}var vT,_T,t3,n3,cG,uG=class{constructor(t,e,n,r,i){Wa(this,vT),Wa(this,_T),Wa(this,t3),Wa(this,n3),Wa(this,cG,!1);var o;gi(this,vT,e),gi(this,_T,n),gi(this,t3,r),gi(this,n3,i),this.id=t.id,this.identifier=t.identifier,this.topicKey=t.topicKey,this.preferences=(o=t.preferences)==null?void 0:o.map(l=>new dG(bi({},l),nn(this,vT),nn(this,_T),nn(this,t3),nn(this,n3)))}update(t){return Lr(this,null,function*(){return yRt({emitter:nn(this,vT),apiService:nn(this,_T),cache:nn(this,t3),useCache:nn(this,n3),args:kc(bi({},t),{subscription:this})})})}updatePreference(t){return Lr(this,null,function*(){return nn(this,cG)?{error:new ho("Cannot update a deleted subscription",new Error("Subscription is stale"))}:vRt({emitter:nn(this,vT),apiService:nn(this,_T),cache:nn(this,t3),useCache:nn(this,n3),args:kc(bi({},t),{subscriptionId:this.identifier})})})}bulkUpdatePreferences(t){return Lr(this,null,function*(){return nn(this,cG)?{error:new ho("Cannot bulk update a deleted subscription",new Error("Subscription is stale"))}:F8r({emitter:nn(this,vT),apiService:nn(this,_T),cache:nn(this,t3),useCache:nn(this,n3),args:t.map(e=>kc(bi({},e),{subscriptionId:this.identifier}))})})}delete(){return Lr(this,null,function*(){return nn(this,cG)?{error:new ho("Cannot delete an already deleted subscription",new Error("Subscription is stale"))}:_Rt({emitter:nn(this,vT),apiService:nn(this,_T),args:{subscription:this}})})}};vT=new WeakMap,_T=new WeakMap,t3=new WeakMap,n3=new WeakMap,cG=new WeakMap;var M8r=t=>Lr(void 0,[t],function*({emitter:e,apiService:n,cache:r,options:i,args:o}){try{const{useCache:l,refetch:u}=i;let d=l&&!u?r.getAll(o):void 0;return e.emit("subscriptions.list.pending",{args:o,data:d}),(!d||u)&&(d=(yield n.fetchSubscriptions(o.topicKey)).map(m=>new uG(kc(bi({},m),{topicKey:o.topicKey}),e,n,r,l)),l&&(r.set(o,d),d=r.getAll(o))),e.emit("subscriptions.list.resolved",{args:o,data:d}),{data:d}}catch(l){return e.emit("subscriptions.list.resolved",{args:o,error:l}),{error:new ho("Failed to fetch subscriptions",l)}}}),P8r=t=>Lr(void 0,[t],function*({emitter:e,apiService:n,cache:r,options:i,args:o}){try{const{useCache:l,refetch:u}=i;let d=l&&!u?r.get(o):void 0;if(e.emit("subscription.get.pending",{args:o,data:d}),!d||u){const p=yield n.getSubscription(o.topicKey,o.identifier,o.workflowIds,o.tags);if(!p)return e.emit("subscription.get.resolved",{args:o,data:null}),{data:null};d=new uG(kc(bi({},p),{topicKey:o.topicKey}),e,n,r,l),l&&(r.setOne(o,d),d=r.get(o))}return e.emit("subscription.get.resolved",{args:o,data:d}),{data:d}}catch(l){return e.emit("subscription.get.resolved",{args:o,error:l}),{error:new ho("Failed to fetch subscription",l)}}}),O8r=t=>Lr(void 0,[t],function*({emitter:e,apiService:n,cache:r,useCache:i,args:o}){var l;try{e.emit("subscription.create.pending",{args:o});const u=yield n.createSubscription({identifier:(l=o.identifier)!=null?l:"",name:o.name,topicKey:o.topicKey,topicName:o.topicName,preferences:o.preferences}),d=new uG(kc(bi({},u),{topicKey:o.topicKey}),e,n,r,i);return e.emit("subscription.create.resolved",{args:o,data:d}),{data:d}}catch(u){return e.emit("subscription.create.resolved",{args:o,error:u}),{error:new ho("Failed to create subscription",u)}}}),yRt=t=>Lr(void 0,[t],function*({emitter:e,apiService:n,cache:r,useCache:i,args:o}){const l="identifier"in o?o.identifier:o.subscription.identifier,u="topicKey"in o?o.topicKey:o.subscription.topicKey;try{e.emit("subscription.update.pending",{args:o});const d=yield n.updateSubscription({topicKey:u,identifier:l,name:o.name,preferences:o.preferences}),p=new uG(kc(bi({},d),{topicKey:u}),e,n,r,i);return e.emit("subscription.update.resolved",{args:o,data:p}),{data:p}}catch(d){return e.emit("subscription.update.resolved",{args:o,error:d}),{error:new ho("Failed to update subscription",d)}}}),vRt=t=>Lr(void 0,[t],function*({emitter:e,apiService:n,cache:r,useCache:i,args:o}){var l,u;const d="workflowId"in o?o.workflowId:(u=(l=o.preference)==null?void 0:l.workflow)==null?void 0:u.id;try{e.emit("subscription.preference.update.pending",{args:o,data:"preference"in o?new dG(bi(bi({},o.preference),typeof o.value=="boolean"?{enabled:o.value}:{condition:o.value}),e,n,r,i):void 0});const p=yield n.updateSubscriptionPreference(bi({subscriptionIdentifier:o.subscriptionId,workflowId:d},typeof o.value=="boolean"?{enabled:o.value,email:o.value,sms:o.value,in_app:o.value,chat:o.value,push:o.value}:{condition:o.value})),m=new dG(bi({},p),e,n,r,i);return e.emit("subscription.preference.update.resolved",{args:o,data:m}),{data:m}}catch(p){return e.emit("subscription.preference.update.resolved",{args:o,error:p}),{error:new ho("Failed to update subscription",p)}}}),F8r=t=>Lr(void 0,[t],function*({emitter:e,apiService:n,cache:r,useCache:i,args:o}){try{const l=o.map(m=>"preference"in m?new dG(bi(bi({},m.preference),typeof m.value=="boolean"?{enabled:m.value}:{condition:m.value}),e,n,r,i):void 0).filter(m=>m!==void 0);e.emit("subscription.preferences.bulk_update.pending",{args:o,data:l});const u=o.map(m=>{var g,h,A,b,y,v;return bi({subscriptionIdentifier:m.subscriptionId,workflowId:"workflowId"in m?m.workflowId:(v=(y=(h=(g=m.preference)==null?void 0:g.workflow)==null?void 0:h.id)!=null?y:(b=(A=m.preference)==null?void 0:A.workflow)==null?void 0:b.identifier)!=null?v:""},typeof m.value=="boolean"?{enabled:m.value,email:m.value,sms:m.value,in_app:m.value,chat:m.value,push:m.value}:{condition:m.value})}),p=(yield n.bulkUpdateSubscriptionPreferences(u)).map(m=>new dG(m,e,n,r,i));return e.emit("subscription.preferences.bulk_update.resolved",{args:o,data:p}),{data:p}}catch(l){return e.emit("subscription.preferences.bulk_update.resolved",{args:o,error:l}),{error:new ho("Failed to bulk update subscription preferences",l)}}}),_Rt=t=>Lr(void 0,[t],function*({emitter:e,apiService:n,args:r}){const i="identifier"in r?r.identifier:r.subscription.identifier,o="topicKey"in r?r.topicKey:r.subscription.topicKey;try{return e.emit("subscription.delete.pending",{args:r}),yield n.deleteSubscription({topicKey:o,identifier:i}),e.emit("subscription.delete.resolved",{args:r}),{data:void 0}}catch(l){return e.emit("subscription.delete.resolved",{args:r,error:l}),{error:new ho("Failed to delete subscription",l)}}}),Ale,ble,yle,vle,dG=class{constructor(t,e,n,r,i){Wa(this,Ale),Wa(this,ble),Wa(this,yle),Wa(this,vle);var o;gi(this,Ale,e),gi(this,ble,n),gi(this,yle,r),gi(this,vle,i),this.enabled=t.enabled,this.condition=(o=t.condition)!=null?o:void 0,this.workflow=t.workflow,this.subscriptionId=t.subscriptionId}update(t){return Lr(this,null,function*(){var e;return vRt({emitter:nn(this,Ale),apiService:nn(this,ble),cache:nn(this,yle),useCache:nn(this,vle),args:{subscriptionId:this.subscriptionId,workflowId:(e=this.workflow)==null?void 0:e.id,value:t.value,preference:this}})})}};Ale=new WeakMap,ble=new WeakMap,yle=new WeakMap,vle=new WeakMap;var r3,pG,fF=class{constructor({inboxServiceInstance:t,eventEmitterInstance:e}){Wa(this,r3,[]),Wa(this,pG),this._emitter=e,this._inboxService=t,this._emitter.on("session.initialize.resolved",({error:n,data:r})=>{r?(this.onSessionSuccess(r),nn(this,r3).forEach(i=>Lr(this,[i],function*({fn:o,resolve:l}){l(yield o())})),gi(this,r3,[])):n&&(this.onSessionError(n),gi(this,pG,n),nn(this,r3).forEach(({resolve:i})=>{i({error:new ho("Failed to initialize session, please contact the support",n)})}),gi(this,r3,[]))})}onSessionSuccess(t){}onSessionError(t){}callWithSession(t){return Lr(this,null,function*(){return this._inboxService.isSessionInitialized?t():nn(this,pG)?Promise.resolve({error:new ho("Failed to initialize session, please contact the support",nn(this,pG))}):new Promise((e,n)=>{nn(this,r3).push({fn:t,resolve:e,reject:n})})})}};r3=new WeakMap,pG=new WeakMap;var uk,mG=class{constructor(){Wa(this,uk),gi(this,uk,new Map)}get(t){return nn(this,uk).get(t)}getValues(){return Array.from(nn(this,uk).values())}entries(){return Array.from(nn(this,uk).entries())}keys(){return Array.from(nn(this,uk).keys())}set(t,e){nn(this,uk).set(t,e)}remove(t){nn(this,uk).delete(t)}clear(){nn(this,uk).clear()}};uk=new WeakMap;var a3=t=>`list:${t.topicKey}`,wRt=t=>t.split(":")[1],wT=t=>`item:${t.topicKey}:${t.identifier}`,Nh,Ld,_le,gp,wle,Q8r=class{constructor({emitterInstance:t,inboxServiceInstance:e,useCache:n}){Wa(this,Nh),Wa(this,Ld),Wa(this,_le),Wa(this,gp),Wa(this,wle),this.handleCreate=r=>{const i=a3({topicKey:r.topicKey}),o=nn(this,Ld).get(i);if(o){const l=[...o,r];nn(this,Ld).set(i,l),nn(this,Nh).emit("subscriptions.list.updated",{data:{topicKey:r.topicKey,subscriptions:l}})}nn(this,gp).set(wT({topicKey:r.topicKey,identifier:r.identifier}),r)},this.handleUpdate=r=>{const i=a3({topicKey:r.topicKey}),o=nn(this,Ld).get(i);if(o){const l=o.map(u=>u.id===r.id?r:u);nn(this,Ld).set(i,l),nn(this,Nh).emit("subscriptions.list.updated",{data:{topicKey:r.topicKey,subscriptions:l}})}nn(this,gp).set(wT({topicKey:r.topicKey,identifier:r.identifier}),r)},this.handlePreferenceUpdate=r=>{this.updateSubscriptionPreferences([r])},this.handleBulkPreferenceUpdate=r=>{this.updateSubscriptionPreferences(r)},this.updateSubscriptionPreferences=r=>{var i;const o=new Map;for(const d of r){const p=(i=o.get(d.subscriptionId))!=null?i:[];p.push(d),o.set(d.subscriptionId,p)}const l=nn(this,Ld).keys();for(const d of l){const p=nn(this,Ld).get(d);if(!p)continue;let m=!1;const g=p.map(h=>{const A=o.get(h.id);return A?(m=!0,this.createUpdatedSubscription(h,A)):h});m&&(nn(this,Ld).set(d,g),nn(this,Nh).emit("subscriptions.list.updated",{data:{topicKey:wRt(d),subscriptions:g}}))}const u=nn(this,gp).keys();for(const d of u){const p=nn(this,gp).get(d);if(!p)continue;const m=o.get(p.id);if(m){const g=this.createUpdatedSubscription(p,m);nn(this,gp).set(d,g),nn(this,Nh).emit("subscription.update.resolved",{args:{subscription:p},data:g})}}},this.createUpdatedSubscription=(r,i)=>{var o;const l=(o=r.preferences)==null?void 0:o.map(u=>{const d=i.find(p=>p.workflow.id===u.workflow.id);return d||u});return new uG({id:r.id,identifier:r.identifier,topicKey:r.topicKey,preferences:l},nn(this,Nh),nn(this,wle),this,nn(this,_le))},this.handleDelete=r=>{const i=a3({topicKey:r.topicKey}),o=nn(this,Ld).get(i);if(o){const l=o.filter(u=>u.id!==r.id);nn(this,Ld).set(i,l),nn(this,Nh).emit("subscriptions.list.updated",{data:{topicKey:r.topicKey,subscriptions:l}})}nn(this,gp).remove(wT({topicKey:r.topicKey,identifier:r.identifier}))},this.handleDeleteByIdentifier=r=>{const i=nn(this,Ld).keys();for(const l of i){const u=nn(this,Ld).get(l);if(u){const d=u.find(p=>p.identifier===r);if(d){const p=u.filter(m=>m.identifier!==r);nn(this,Ld).set(l,p),nn(this,Nh).emit("subscriptions.list.updated",{data:{topicKey:wRt(l),subscriptions:p}}),nn(this,gp).remove(wT({topicKey:d.topicKey,identifier:d.identifier}));return}}}const o=nn(this,gp).keys();for(const l of o){const u=nn(this,gp).get(l);if(u&&u.identifier===r){nn(this,gp).remove(l);return}}},gi(this,Nh,t),gi(this,Ld,new mG),gi(this,gp,new mG),gi(this,wle,e),gi(this,_le,n),nn(this,Nh).on("subscription.create.resolved",({data:r})=>{r&&this.handleCreate(r)}),nn(this,Nh).on("subscription.update.resolved",({data:r})=>{r&&this.handleUpdate(r)}),nn(this,Nh).on("subscription.delete.resolved",({args:r})=>{"subscription"in r?this.handleDelete(r.subscription):"identifier"in r&&this.handleDeleteByIdentifier(r.identifier)}),nn(this,Nh).on("subscription.preference.update.pending",({data:r})=>{r&&this.handlePreferenceUpdate(r)}),nn(this,Nh).on("subscription.preference.update.resolved",({data:r})=>{r&&this.handlePreferenceUpdate(r)}),nn(this,Nh).on("subscription.preferences.bulk_update.resolved",({data:r})=>{r&&r.length>0&&this.handleBulkPreferenceUpdate(r)})}has(t){return nn(this,Ld).get(a3(t))!==void 0}set(t,e){nn(this,Ld).set(a3(t),e);for(const n of e)nn(this,gp).set(wT({topicKey:t.topicKey,identifier:n.identifier}),n)}setOne(t,e){nn(this,gp).set(wT(t),e)}getAll(t){return nn(this,Ld).get(a3(t))}get(t){return nn(this,gp).get(wT(t))}invalidate(t){const e=a3({topicKey:t.topicKey}),n=nn(this,Ld).get(e);if(n)for(const i of n)nn(this,gp).remove(wT({topicKey:t.topicKey,identifier:i.identifier}));nn(this,Ld).remove(e);const r=nn(this,gp).keys();for(const i of r)i.startsWith(`item:${t.topicKey}:`)&&nn(this,gp).remove(i)}clearAll(){nn(this,Ld).clear(),nn(this,gp).clear()}};Nh=new WeakMap,Ld=new WeakMap,_le=new WeakMap,gp=new WeakMap,wle=new WeakMap;var i3,xle,kle,$8r=class extends fF{constructor({useCache:t,inboxServiceInstance:e,eventEmitterInstance:n,subscriber:r,contextKey:i}){super({eventEmitterInstance:n,inboxServiceInstance:e}),Wa(this,i3),Wa(this,xle),Wa(this,kle),this.cache=new Q8r({emitterInstance:this._emitter,inboxServiceInstance:this._inboxService,useCache:t}),gi(this,i3,t),gi(this,xle,r),gi(this,kle,i)}list(t,e){return Lr(this,null,function*(){return this.callWithSession(()=>{var n;return M8r({emitter:this._emitter,apiService:this._inboxService,cache:this.cache,options:kc(bi({},e),{useCache:(n=e?.useCache)!=null?n:nn(this,i3)}),args:t})})})}get(t,e){return Lr(this,null,function*(){return this.callWithSession(()=>{var n,r;return P8r({emitter:this._emitter,apiService:this._inboxService,cache:this.cache,options:kc(bi({},e),{useCache:(n=e?.useCache)!=null?n:nn(this,i3)}),args:kc(bi({},t),{identifier:(r=t.identifier)!=null?r:SFr({topicKey:t.topicKey,subscriberId:nn(this,xle).subscriberId,contextKey:nn(this,kle)})})})})})}create(t){return Lr(this,null,function*(){return this.callWithSession(()=>O8r({emitter:this._emitter,apiService:this._inboxService,cache:this.cache,useCache:nn(this,i3),args:t}))})}update(t){return Lr(this,null,function*(){return this.callWithSession(()=>yRt({emitter:this._emitter,apiService:this._inboxService,cache:this.cache,useCache:nn(this,i3),args:t}))})}delete(t){return Lr(this,null,function*(){return this.callWithSession(()=>_Rt({emitter:this._emitter,apiService:this._inboxService,args:t}))})}};i3=new WeakMap,xle=new WeakMap,kle=new WeakMap;var j8r="v1",xRt="@novu/js@3.13.0",z8r=class{constructor(t={}){this.DEFAULT_BACKEND_URL=typeof window<"u"&&window.NOVU_LOCAL_BACKEND_URL||"https://api.novu.co";const{apiVersion:e=j8r,apiUrl:n=this.DEFAULT_BACKEND_URL,userAgent:r=xRt,headers:i={}}=t||{};this.apiVersion=e,this.apiUrl=`${n}/${e}`,this.headers=bi({"Novu-API-Version":"2024-06-26","Novu-Client-Version":xRt,"Content-Type":"application/json","User-Agent":r},i)}setAuthorizationToken(t){this.headers.Authorization=`Bearer ${t}`}setKeylessHeader(t){var e;const n=t||typeof window<"u"&&((e=window.localStorage)==null?void 0:e.getItem("novu_keyless_application_identifier"));!n||!n.startsWith("pk_keyless_")||(this.headers["Novu-Application-Identifier"]=n)}setHeaders(t){this.headers=bi(bi({},this.headers),t)}get(t,e,n=!0){return Lr(this,null,function*(){return this.doFetch({path:t,searchParams:e,options:{method:"GET"},unwrapEnvelope:n})})}post(t,e,n){return Lr(this,null,function*(){return this.doFetch({path:t,options:{method:"POST",body:e,headers:n?.headers}})})}patch(t,e){return Lr(this,null,function*(){return this.doFetch({path:t,options:{method:"PATCH",body:e}})})}delete(t,e){return Lr(this,null,function*(){return this.doFetch({path:t,options:{method:"DELETE",body:e}})})}doFetch(t){return Lr(this,arguments,function*({path:e,searchParams:n,options:r,unwrapEnvelope:i=!0}){const o=U8r(this.apiUrl,e,n?`?${n.toString()}`:""),l={method:r?.method||"GET",headers:bi(bi({},this.headers),r?.headers||{}),body:r?.body?JSON.stringify(r.body):void 0},u=yield fetch(o,l);if(!u.ok){const p=yield u.json();throw new Error(`${this.headers["Novu-Client-Version"]} error. Status: ${u.status}, Message: ${p.message}`)}if(u.status===204)return;const d=yield u.json();return i?d.data:d})}};function U8r(...t){return t.reduce((e,n)=>(n&&e.push(n.replace(new RegExp("(?<!https?:)\\/+","g"),"/").replace(/^\/+|\/+$/g,"")),e),[]).join("/").replace(/\/\?/,"?")}var WA="/inbox",Rh=`${WA}/notifications`,Fo,q8r=class{constructor(t={}){this.isSessionInitialized=!1,Wa(this,Fo),gi(this,Fo,new z8r(t))}initializeSession(t){return Lr(this,arguments,function*({applicationIdentifier:e,subscriberHash:n,contextHash:r,subscriber:i,defaultSchedule:o,context:l}){const u=yield nn(this,Fo).post(`${WA}/session`,{applicationIdentifier:e,subscriberHash:n,contextHash:r,subscriber:i,defaultSchedule:o,context:l});return nn(this,Fo).setAuthorizationToken(u.token),nn(this,Fo).setKeylessHeader(u.applicationIdentifier),this.isSessionInitialized=!0,u})}fetchNotifications({after:t,archived:e,limit:n=10,offset:r,read:i,tags:o,snoozed:l,seen:u,data:d,severity:p}){const m=new URLSearchParams(`limit=${n}`);if(t&&m.append("after",t),r&&m.append("offset",`${r}`),o)for(const g of o)m.append("tags[]",g);if(i!==void 0&&m.append("read",`${i}`),e!==void 0&&m.append("archived",`${e}`),l!==void 0&&m.append("snoozed",`${l}`),u!==void 0&&m.append("seen",`${u}`),d!==void 0&&m.append("data",JSON.stringify(d)),p&&Array.isArray(p))for(const g of p)m.append("severity[]",g);else p&&m.append("severity",p);return nn(this,Fo).get(Rh,m,!1)}count({filters:t}){return nn(this,Fo).get(`${Rh}/count`,new URLSearchParams({filters:JSON.stringify(t)}),!1)}read(t){return nn(this,Fo).patch(`${Rh}/${t}/read`)}unread(t){return nn(this,Fo).patch(`${Rh}/${t}/unread`)}archive(t){return nn(this,Fo).patch(`${Rh}/${t}/archive`)}unarchive(t){return nn(this,Fo).patch(`${Rh}/${t}/unarchive`)}snooze(t,e){return nn(this,Fo).patch(`${Rh}/${t}/snooze`,{snoozeUntil:e})}unsnooze(t){return nn(this,Fo).patch(`${Rh}/${t}/unsnooze`)}readAll({tags:t,data:e}){return nn(this,Fo).post(`${Rh}/read`,{tags:t,data:e?JSON.stringify(e):void 0})}archiveAll({tags:t,data:e}){return nn(this,Fo).post(`${Rh}/archive`,{tags:t,data:e?JSON.stringify(e):void 0})}archiveAllRead({tags:t,data:e}){return nn(this,Fo).post(`${Rh}/read-archive`,{tags:t,data:e?JSON.stringify(e):void 0})}delete(t){return nn(this,Fo).delete(`${Rh}/${t}/delete`)}deleteAll({tags:t,data:e}){return nn(this,Fo).post(`${Rh}/delete`,{tags:t,data:e?JSON.stringify(e):void 0})}markAsSeen({notificationIds:t,tags:e,data:n}){return nn(this,Fo).post(`${Rh}/seen`,{notificationIds:t,tags:e,data:n?JSON.stringify(n):void 0})}seen(t){return this.markAsSeen({notificationIds:[t]})}completeAction({actionType:t,notificationId:e}){return nn(this,Fo).patch(`${Rh}/${e}/complete`,{actionType:t})}revertAction({actionType:t,notificationId:e}){return nn(this,Fo).patch(`${Rh}/${e}/revert`,{actionType:t})}fetchPreferences({tags:t,severity:e,criticality:n}){const r=new URLSearchParams;if(t)for(const o of t)r.append("tags[]",o);if(e&&Array.isArray(e))for(const o of e)r.append("severity[]",o);else e&&r.append("severity",e);n&&r.append("criticality",n);const i=r.size?`?${r.toString()}`:"";return nn(this,Fo).get(`${WA}/preferences${i}`)}bulkUpdatePreferences(t){return nn(this,Fo).patch(`${WA}/preferences/bulk`,{preferences:t})}updateGlobalPreferences(t){return nn(this,Fo).patch(`${WA}/preferences`,t)}updateWorkflowPreferences({workflowId:t,channels:e}){return nn(this,Fo).patch(`${WA}/preferences/${t}`,e)}fetchGlobalPreferences(){return nn(this,Fo).get(`${WA}/preferences/global`)}triggerHelloWorldEvent(){const t={name:"hello-world",to:{subscriberId:"keyless-subscriber-id"},payload:{subject:"Novu Keyless Environment",body:"You're using a keyless demo environment. For full access to Novu features and cloud integration, obtain your API key.",primaryActionText:"Obtain API Key",primaryActionUrl:"https://go.novu.co/keyless",secondaryActionText:"Explore Documentation",secondaryActionUrl:"https://go.novu.co/keyless-docs"}};return nn(this,Fo).post("/inbox/events",t)}fetchSubscriptions(t){return nn(this,Fo).get(`${WA}/topics/${t}/subscriptions`)}getSubscription(t,e,n,r){const i=new URLSearchParams;if(n?.length)for(const l of n)i.append("workflowIds",l);if(r?.length)for(const l of r)i.append("tags",l);const o=i.size?`?${i.toString()}`:"";return nn(this,Fo).get(`${WA}/topics/${t}/subscriptions/${e}${o}`)}createSubscription({identifier:t,name:e,topicKey:n,topicName:r,preferences:i}){return nn(this,Fo).post(`${WA}/topics/${n}/subscriptions`,bi(bi({identifier:t,name:e},r&&{topic:{name:r}}),i!==void 0&&{preferences:i}))}updateSubscription({topicKey:t,identifier:e,name:n,preferences:r}){return nn(this,Fo).patch(`${WA}/topics/${t}/subscriptions/${e}`,bi({name:n},r!==void 0&&{preferences:r}))}updateSubscriptionPreference({subscriptionIdentifier:t,workflowId:e,enabled:n,condition:r,email:i,sms:o,in_app:l,chat:u,push:d}){return nn(this,Fo).patch(`${WA}/subscriptions/${t}/preferences/${e}`,{enabled:n,condition:r,email:i,sms:o,in_app:l,chat:u,push:d})}bulkUpdateSubscriptionPreferences(t){return nn(this,Fo).patch(`${WA}/preferences/bulk`,{preferences:t})}deleteSubscription({topicKey:t,identifier:e}){return nn(this,Fo).delete(`${WA}/topics/${t}/subscriptions/${e}`)}};Fo=new WeakMap;var AF,G8r=class{constructor(){Wa(this,AF),gi(this,AF,RFr())}on(t,e){return nn(this,AF).on(t,e),()=>{this.off(t,e)}}off(t,e){nn(this,AF).off(t,e)}emit(t,e){nn(this,AF).emit(t,e)}};AF=new WeakMap;var kRt=({tags:t,data:e,read:n,archived:r,snoozed:i,seen:o,severity:l,limit:u,offset:d,after:p})=>Object.entries({tags:t,data:e,read:n,archived:r,snoozed:i,seen:o,severity:l,limit:u,offset:d,after:p}).filter(([m,g])=>g!=null&&!(Array.isArray(g)&&g.length===0)).reduce((m,[g,h])=>(m[g]=h,m),{}),gG=({tags:t,data:e,read:n,archived:r,snoozed:i,seen:o,severity:l,limit:u,offset:d,after:p})=>JSON.stringify(kRt({tags:t,data:e,read:n,archived:r,snoozed:i,seen:o,severity:l,limit:u,offset:d,after:p})),H8r=({tags:t,data:e,read:n,archived:r,snoozed:i,seen:o,severity:l})=>JSON.stringify(kRt({tags:t,data:e,read:n,archived:r,snoozed:i,seen:o,severity:l})),s3=t=>JSON.parse(t),W8r=["notification.read.pending","notification.read.resolved","notification.unread.pending","notification.unread.resolved","notification.complete_action.pending","notification.complete_action.resolved","notification.revert_action.pending","notification.revert_action.resolved","notifications.read_all.pending","notifications.read_all.resolved"],Y8r=["notification.archive.pending","notification.unarchive.pending","notification.snooze.pending","notification.unsnooze.pending","notification.delete.pending","notifications.archive_all.pending","notifications.archive_all_read.pending","notifications.delete_all.pending"],xT,Ele,Md,V8r=class{constructor({emitter:t,inboxService:e}){Wa(this,xT),Wa(this,Ele),Wa(this,Md),this.updateNotification=(n,r)=>{const i=nn(this,Md).get(n);if(!i)return!1;const o=i.notifications.findIndex(u=>u.id===r.id);if(o===-1)return!1;const l=[...i.notifications];return l[o]=r,nn(this,Md).set(n,kc(bi({},i),{notifications:l})),!0},this.removeNotification=(n,r)=>{const i=nn(this,Md).get(n);if(!i)return!1;const o=i.notifications.findIndex(u=>u.id===r.id);if(o===-1)return!1;const l=[...i.notifications];return l.splice(o,1),nn(this,Md).set(n,kc(bi({},i),{notifications:l})),!0},this.handleNotificationEvent=({remove:n}={remove:!1})=>r=>{const{data:i,args:o}=r;let l=[];if(i!=null)Array.isArray(i)&&i.every(d=>typeof d=="object"&&"id"in d)?l=i:typeof i=="object"&&"id"in i&&(l=[i]);else if(n&&o){if("notification"in o&&o.notification)l=[o.notification];else if("notificationId"in o&&o.notificationId){const d=[];nn(this,Md).keys().forEach(p=>{const m=nn(this,Md).get(p);if(m){const g=m.notifications.find(h=>h.id===o.notificationId);g&&d.push(g)}}),l=d}}if(l.length===0)return;const u=new Set;nn(this,Md).keys().forEach(d=>{l.forEach(p=>{let m=!1;n?m=this.removeNotification(d,p):m=this.updateNotification(d,p),m&&u.add(H8r(s3(d)))})}),u.forEach(d=>{const p=this.getAggregated(s3(d));nn(this,xT).emit("notifications.list.updated",{data:p})})},gi(this,xT,t),gi(this,Ele,e),W8r.forEach(n=>{nn(this,xT).on(n,this.handleNotificationEvent())}),Y8r.forEach(n=>{nn(this,xT).on(n,this.handleNotificationEvent({remove:!0}))}),gi(this,Md,new mG)}getAggregated(t){return nn(this,Md).keys().filter(n=>{const r=s3(n);return fle(r,t)}).map(n=>nn(this,Md).get(n)).reduce((n,r)=>r?{hasMore:r.hasMore,filter:r.filter,notifications:[...n.notifications,...r.notifications]}:n,{hasMore:!1,filter:{},notifications:[]})}get(t){return nn(this,Md).get(gG(t))}has(t){return nn(this,Md).get(gG(t))!==void 0}set(t,e){nn(this,Md).set(gG(t),e)}unshift(t,e){const n=gG(t),r=nn(this,Md).get(n)||{hasMore:!1,filter:s3(n),notifications:[]},i=NFr({notification:bi({},e),emitter:nn(this,xT),inboxService:nn(this,Ele)});this.update(t,kc(bi({},r),{notifications:[i,...r.notifications]}))}update(t,e){this.set(t,e);const n=this.getAggregated(s3(gG(t)));nn(this,xT).emit("notifications.list.updated",{data:n})}getAll(t){if(this.has(t))return this.getAggregated({tags:t.tags,data:t.data,read:t.read,snoozed:t.snoozed,archived:t.archived,seen:t.seen,severity:t.severity})}getUniqueNotifications({tags:t,read:e,data:n}){const r=nn(this,Md).keys(),i=new Map;return r.forEach(o=>{const l=s3(o);if(RRe(t,l.tags)&&bRt(n,l.data)){const u=nn(this,Md).get(o);if(!u)return;u.notifications.filter(d=>typeof e>"u"||e===d.isRead).forEach(d=>{i.set(d.id,d)})}}),Array.from(i.values())}clear(t){nn(this,Md).keys().forEach(n=>{fle(s3(n),t)&&nn(this,Md).remove(n)})}clearAll(){nn(this,Md).clear()}};xT=new WeakMap,Ele=new WeakMap,Md=new WeakMap;var Cle,K8r=class extends fF{constructor({useCache:t,inboxServiceInstance:e,eventEmitterInstance:n}){super({eventEmitterInstance:n,inboxServiceInstance:e}),Wa(this,Cle),this.cache=new V8r({emitter:n,inboxService:e}),gi(this,Cle,t)}list(){return Lr(this,arguments,function*(t={}){var e=t,{limit:n=10}=e,r=CFr(e,["limit"]);return this.callWithSession(()=>Lr(this,null,function*(){const i=bi({limit:n},r);try{const o="useCache"in i?i.useCache:nn(this,Cle);let l=o?this.cache.getAll(i):void 0;if(this._emitter.emit("notifications.list.pending",{args:i,data:l}),!l){const u=yield this._inboxService.fetchNotifications(bi({limit:n},r));l={hasMore:u.hasMore,filter:u.filter,notifications:u.data.map(d=>new Mm(d,this._emitter,this._inboxService))},o&&(this.cache.set(i,l),l=this.cache.getAll(i))}return this._emitter.emit("notifications.list.resolved",{args:i,data:l}),{data:l}}catch(o){return this._emitter.emit("notifications.list.resolved",{args:i,error:o}),{error:new ho("Failed to fetch notifications",o)}}}))})}count(t){return Lr(this,null,function*(){return this.callWithSession(()=>Lr(this,null,function*(){const e=t&&"filters"in t?t.filters:[bi({},t)];try{this._emitter.emit("notifications.count.pending",{args:t});const n=yield this._inboxService.count({filters:e}),r=t&&"filters"in t?{counts:n.data}:n.data[0];return this._emitter.emit("notifications.count.resolved",{args:t,data:r}),{data:r}}catch(n){return this._emitter.emit("notifications.count.resolved",{args:t,error:n}),{error:new ho("Failed to count notifications",n)}}}))})}read(t){return Lr(this,null,function*(){return this.callWithSession(()=>Lr(this,null,function*(){return RNt({emitter:this._emitter,apiService:this._inboxService,args:t})}))})}unread(t){return Lr(this,null,function*(){return this.callWithSession(()=>Lr(this,null,function*(){return LNt({emitter:this._emitter,apiService:this._inboxService,args:t})}))})}seen(t){return Lr(this,null,function*(){return this.callWithSession(()=>Lr(this,null,function*(){return MNt({emitter:this._emitter,apiService:this._inboxService,args:t})}))})}archive(t){return Lr(this,null,function*(){return this.callWithSession(()=>Lr(this,null,function*(){return PNt({emitter:this._emitter,apiService:this._inboxService,args:t})}))})}unarchive(t){return Lr(this,null,function*(){return this.callWithSession(()=>Lr(this,null,function*(){return ONt({emitter:this._emitter,apiService:this._inboxService,args:t})}))})}delete(t){return Lr(this,null,function*(){return this.callWithSession(()=>Lr(this,null,function*(){return jNt({emitter:this._emitter,apiService:this._inboxService,args:t})}))})}snooze(t){return Lr(this,null,function*(){return this.callWithSession(()=>Lr(this,null,function*(){return FNt({emitter:this._emitter,apiService:this._inboxService,args:t})}))})}unsnooze(t){return Lr(this,null,function*(){return this.callWithSession(()=>Lr(this,null,function*(){return QNt({emitter:this._emitter,apiService:this._inboxService,args:t})}))})}completePrimary(t){return Lr(this,null,function*(){return this.callWithSession(()=>Lr(this,null,function*(){return ile({emitter:this._emitter,apiService:this._inboxService,args:t,actionType:"primary"})}))})}completeSecondary(t){return Lr(this,null,function*(){return this.callWithSession(()=>Lr(this,null,function*(){return ile({emitter:this._emitter,apiService:this._inboxService,args:t,actionType:"secondary"})}))})}revertPrimary(t){return Lr(this,null,function*(){return this.callWithSession(()=>Lr(this,null,function*(){return sle({emitter:this._emitter,apiService:this._inboxService,args:t,actionType:"primary"})}))})}revertSecondary(t){return Lr(this,null,function*(){return this.callWithSession(()=>Lr(this,null,function*(){return sle({emitter:this._emitter,apiService:this._inboxService,args:t,actionType:"secondary"})}))})}readAll(){return Lr(this,arguments,function*({tags:t,data:e}={}){return this.callWithSession(()=>Lr(this,null,function*(){return IFr({emitter:this._emitter,inboxService:this._inboxService,notificationsCache:this.cache,tags:t,data:e})}))})}seenAll(){return Lr(this,arguments,function*(t={}){return this.callWithSession(()=>Lr(this,null,function*(){return"notificationIds"in t?$Nt({emitter:this._emitter,inboxService:this._inboxService,notificationsCache:this.cache,notificationIds:t.notificationIds}):$Nt({emitter:this._emitter,inboxService:this._inboxService,notificationsCache:this.cache,tags:"tags"in t?t.tags:void 0,data:"data"in t?t.data:void 0})}))})}archiveAll(){return Lr(this,arguments,function*({tags:t,data:e}={}){return this.callWithSession(()=>Lr(this,null,function*(){return TFr({emitter:this._emitter,inboxService:this._inboxService,notificationsCache:this.cache,tags:t,data:e})}))})}archiveAllRead(){return Lr(this,arguments,function*({tags:t,data:e}={}){return this.callWithSession(()=>Lr(this,null,function*(){return BFr({emitter:this._emitter,inboxService:this._inboxService,notificationsCache:this.cache,tags:t,data:e})}))})}deleteAll(){return Lr(this,arguments,function*({tags:t,data:e}={}){return this.callWithSession(()=>Lr(this,null,function*(){return DFr({emitter:this._emitter,inboxService:this._inboxService,notificationsCache:this.cache,tags:t,data:e})}))})}clearCache({filter:t}={}){if(t){this.cache.clear(t??{});return}this.cache.clearAll()}triggerHelloWorldEvent(){return Lr(this,null,function*(){return this._inboxService.triggerHelloWorldEvent()})}};Cle=new WeakMap;var Sle,Ile,Tle,Ble,Dle=class{constructor(t,{emitterInstance:e,inboxServiceInstance:n,cache:r,useCache:i}){Wa(this,Sle),Wa(this,Ile),Wa(this,Tle),Wa(this,Ble),gi(this,Sle,e),gi(this,Ile,n),gi(this,Tle,r),gi(this,Ble,i),this.isEnabled=t.isEnabled,this.weeklySchedule=t.weeklySchedule}update(t){return Lr(this,null,function*(){var e;const n=!!t.weeklySchedule||!!this.weeklySchedule;return CRt({emitter:nn(this,Sle),apiService:nn(this,Ile),cache:nn(this,Tle),useCache:nn(this,Ble),args:bi({isEnabled:(e=t.isEnabled)!=null?e:this.isEnabled},n&&{weeklySchedule:bi(bi({},this.weeklySchedule),t.weeklySchedule)})})})}};Sle=new WeakMap,Ile=new WeakMap,Tle=new WeakMap,Ble=new WeakMap;var Nle,Rle,Lle,Mle,Ple,bF=class{constructor(t,{emitterInstance:e,inboxServiceInstance:n,cache:r,scheduleCache:i,useCache:o}){Wa(this,Nle),Wa(this,Rle),Wa(this,Lle),Wa(this,Mle),Wa(this,Ple),gi(this,Nle,e),gi(this,Rle,n),gi(this,Lle,r),gi(this,Mle,i),gi(this,Ple,o),this.level=t.level,this.enabled=t.enabled,this.channels=t.channels,this.workflow=t.workflow,this.schedule=new Dle(bi({},t.schedule),{emitterInstance:e,inboxServiceInstance:n,cache:i,useCache:o})}update({channels:t,channelPreferences:e}){var n;return ERt({emitter:nn(this,Nle),apiService:nn(this,Rle),cache:nn(this,Lle),scheduleCache:nn(this,Mle),useCache:nn(this,Ple),args:{workflowId:(n=this.workflow)==null?void 0:n.id,channels:t||e,preference:this}})}};Nle=new WeakMap,Rle=new WeakMap,Lle=new WeakMap,Mle=new WeakMap,Ple=new WeakMap;var ERt=t=>Lr(void 0,[t],function*({emitter:e,apiService:n,cache:r,scheduleCache:i,useCache:o,args:l}){var u;const{channels:d}=l,p="workflowId"in l?l.workflowId:(u=l.preference.workflow)==null?void 0:u.id;try{e.emit("preference.update.pending",{args:l,data:"preference"in l?new bF(kc(bi({},l.preference),{channels:bi(bi({},l.preference.channels),d)}),{emitterInstance:e,inboxServiceInstance:n,cache:r,scheduleCache:i,useCache:o}):void 0});let m;p?m=yield n.updateWorkflowPreferences({workflowId:p,channels:d}):(X8r({emitter:e,apiService:n,cache:r,scheduleCache:i,useCache:o,args:l}),m=yield n.updateGlobalPreferences(d));const g=new bF(m,{emitterInstance:e,inboxServiceInstance:n,cache:r,scheduleCache:i,useCache:o});return e.emit("preference.update.resolved",{args:l,data:g}),{data:g}}catch(m){return e.emit("preference.update.resolved",{args:l,error:m}),{error:new ho("Failed to update preference",m)}}}),Z8r=t=>Lr(void 0,[t],function*({emitter:e,apiService:n,cache:r,scheduleCache:i,useCache:o,args:l}){if(l.find(d=>"preference"in d&&d.preference.level==="global"))return{error:new ho("Global preference is not supported in bulk update","")};try{const d=l.map(h=>"preference"in h?new bF(kc(bi({},h.preference),{channels:bi(bi({},h.preference.channels),h.channels)}),{emitterInstance:e,inboxServiceInstance:n,cache:r,scheduleCache:i,useCache:o}):void 0).filter(h=>h!==void 0);e.emit("preferences.bulk_update.pending",{args:l,data:d});const p=l.map(h=>{var A,b,y,v;return bi({workflowId:"workflowId"in h?h.workflowId:(v=(y=(A=h.preference.workflow)==null?void 0:A.id)!=null?y:(b=h.preference.workflow)==null?void 0:b.identifier)!=null?v:""},h.channels)}),g=(yield n.bulkUpdatePreferences(p)).map(h=>new bF(h,{emitterInstance:e,inboxServiceInstance:n,cache:r,scheduleCache:i,useCache:o}));return e.emit("preferences.bulk_update.resolved",{args:l,data:g}),{data:g}}catch(d){return e.emit("preferences.bulk_update.resolved",{args:l,error:d}),{error:new ho("Failed to bulk update preferences",d)}}}),X8r=({emitter:t,apiService:e,cache:n,scheduleCache:r,useCache:i,args:o})=>{const l=i?n?.getAll({}):void 0;l?.forEach(u=>{var d,p;if(u.level==="template"){const m=kc(bi({},u),{channels:Object.entries(u.channels).reduce((h,[A,b])=>{var y;const v=A;return h[v]=(y=o.channels[v])!=null?y:b,h},{})}),g="preference"in o?new bF(m,{emitterInstance:t,inboxServiceInstance:e,cache:n,scheduleCache:r,useCache:i}):void 0;g&&t.emit("preference.update.pending",{args:{workflowId:(p=(d=u.workflow)==null?void 0:d.id)!=null?p:"",channels:g.channels},data:g})}})},CRt=t=>Lr(void 0,[t],function*({emitter:e,apiService:n,cache:r,useCache:i,args:o}){var l,u;try{const{isEnabled:d,weeklySchedule:p}=o,m=new Dle({isEnabled:d,weeklySchedule:p},{emitterInstance:e,inboxServiceInstance:n,cache:r,useCache:i});e.emit("preference.schedule.update.pending",{args:o,data:m});const g=yield n.updateGlobalPreferences({schedule:{isEnabled:d,weeklySchedule:p}}),h=new Dle({isEnabled:(l=g.schedule)==null?void 0:l.isEnabled,weeklySchedule:(u=g.schedule)==null?void 0:u.weeklySchedule},{emitterInstance:e,inboxServiceInstance:n,cache:r,useCache:i});return e.emit("preference.schedule.update.resolved",{args:o,data:h}),{data:h}}catch(d){return e.emit("preference.schedule.update.resolved",{args:o,error:d}),{error:new ho("Failed to update preference",d)}}}),o3,J8r=class extends fF{constructor({cache:t,useCache:e,inboxServiceInstance:n,eventEmitterInstance:r}){super({eventEmitterInstance:r,inboxServiceInstance:n}),Wa(this,o3),this.cache=t,gi(this,o3,e)}get(){return Lr(this,null,function*(){return this.callWithSession(()=>Lr(this,null,function*(){var t,e;try{let n=nn(this,o3)?this.cache.getAll():void 0;if(this._emitter.emit("preference.schedule.get.pending",{args:void 0,data:n}),!n){const r=yield this._inboxService.fetchGlobalPreferences();n=new Dle({isEnabled:(t=r?.schedule)==null?void 0:t.isEnabled,weeklySchedule:(e=r?.schedule)==null?void 0:e.weeklySchedule},{emitterInstance:this._emitter,inboxServiceInstance:this._inboxService,cache:this.cache,useCache:nn(this,o3)}),nn(this,o3)&&(this.cache.set(n),n=this.cache.getAll())}return this._emitter.emit("preference.schedule.get.resolved",{args:void 0,data:n}),{data:n}}catch(n){throw this._emitter.emit("preference.schedule.get.resolved",{args:void 0,error:n}),n}}))})}update(t){return Lr(this,null,function*(){return this.callWithSession(()=>CRt({emitter:this._emitter,apiService:this._inboxService,cache:this.cache,useCache:nn(this,o3),args:t}))})}};o3=new WeakMap;var e6r=["preference.update.pending","preference.update.resolved","preferences.bulk_update.pending","preferences.bulk_update.resolved"],t6r=["preference.schedule.update.pending","preference.schedule.update.resolved"],n6r=({tags:t,severity:e})=>Object.entries({tags:t,severity:e}).reduce((n,[r,i])=>(i==null||Array.isArray(i)&&i.length===0||(n[r]=i),n),{}),LRe=({tags:t,severity:e})=>JSON.stringify(n6r({tags:t,severity:e})),l3,Bg,r6r=class{constructor({emitterInstance:t}){Wa(this,l3),Wa(this,Bg),this.updatePreference=(e,n)=>{const r=nn(this,Bg).get(e);if(!r)return!1;const i=r.findIndex(l=>{var u,d;return((u=l.workflow)==null?void 0:u.id)===((d=n.workflow)==null?void 0:d.id)||l.level===n.level&&n.level==="global"});if(i===-1)return!1;const o=[...r];return o[i]=n,nn(this,Bg).set(e,o),!0},this.updatePreferenceSchedule=(e,n)=>{const r=nn(this,Bg).get(e);if(!r)return!1;const i=r.findIndex(l=>l.level==="global");if(i===-1)return!1;const o=[...r];return o[i].schedule=n,nn(this,Bg).set(e,o),!0},this.handleScheduleEvent=({data:e})=>{var n;if(!e)return;const r=nn(this,Bg).keys(),i=new Set;for(const o of r){const l=this.updatePreferenceSchedule(o,e),u=nn(this,Bg).get(o);!l||!u||i.add(o)}for(const o of i)nn(this,l3).emit("preferences.list.updated",{data:(n=nn(this,Bg).get(o))!=null?n:[]})},this.handlePreferenceEvent=({data:e})=>{if(!e)return;const n=Array.isArray(e)?e:[e],r=new Set;nn(this,Bg).keys().forEach(i=>{n.forEach(o=>{const l=this.updatePreference(i,o),u=nn(this,Bg).get(i);!l||!u||r.add(i)})}),r.forEach(i=>{var o;nn(this,l3).emit("preferences.list.updated",{data:(o=nn(this,Bg).get(i))!=null?o:[]})})},gi(this,l3,t);for(const e of e6r)nn(this,l3).on(e,this.handlePreferenceEvent);for(const e of t6r)nn(this,l3).on(e,this.handleScheduleEvent);gi(this,Bg,new mG)}has(t){return nn(this,Bg).get(LRe(t))!==void 0}set(t,e){nn(this,Bg).set(LRe(t),e)}getAll(t){if(this.has(t))return nn(this,Bg).get(LRe(t))}clearAll(){nn(this,Bg).clear()}};l3=new WeakMap,Bg=new WeakMap;var a6r=["preference.schedule.update.pending","preference.schedule.update.resolved"],MRe=()=>"schedule",hG,Ny,i6r=class{constructor({emitterInstance:t}){Wa(this,hG),Wa(this,Ny),this.updateScheduleInCache=(e,n)=>nn(this,Ny).get(e)?(nn(this,Ny).set(e,n),!0):!1,this.handleScheduleEvent=({data:e})=>{if(!e)return;const n=new Set,r=nn(this,Ny).keys();for(const i of r){const o=this.updateScheduleInCache(i,e),l=nn(this,Ny).get(i);!o||!l||n.add(i)}for(const i of n)nn(this,hG).emit("preference.schedule.get.updated",{data:nn(this,Ny).get(i)})},gi(this,hG,t);for(const e of a6r)nn(this,hG).on(e,this.handleScheduleEvent);gi(this,Ny,new mG)}has(){return nn(this,Ny).get(MRe())!==void 0}set(t){nn(this,Ny).set(MRe(),t)}getAll(){if(this.has())return nn(this,Ny).get(MRe())}clearAll(){nn(this,Ny).clear()}};hG=new WeakMap,Ny=new WeakMap;var kT,s6r=class extends fF{constructor({useCache:t,inboxServiceInstance:e,eventEmitterInstance:n}){super({eventEmitterInstance:n,inboxServiceInstance:e}),Wa(this,kT),this.cache=new r6r({emitterInstance:this._emitter}),this.scheduleCache=new i6r({emitterInstance:this._emitter}),gi(this,kT,t),this.schedule=new J8r({cache:this.scheduleCache,useCache:t,inboxServiceInstance:e,eventEmitterInstance:n})}list(){return Lr(this,arguments,function*(t={}){return this.callWithSession(()=>Lr(this,null,function*(){var e;try{let n=nn(this,kT)?this.cache.getAll(t):void 0;return this._emitter.emit("preferences.list.pending",{args:t,data:n}),n||(n=(yield this._inboxService.fetchPreferences({tags:t.tags,severity:t.severity,criticality:(e=t.criticality)!=null?e:"nonCritical"})).map(i=>new bF(i,{emitterInstance:this._emitter,inboxServiceInstance:this._inboxService,cache:this.cache,scheduleCache:this.scheduleCache,useCache:nn(this,kT)})),nn(this,kT)&&(this.cache.set(t,n),n=this.cache.getAll(t))),this._emitter.emit("preferences.list.resolved",{args:t,data:n}),{data:n}}catch(n){throw this._emitter.emit("preferences.list.resolved",{args:t,error:n}),n}}))})}update(t){return Lr(this,null,function*(){return this.callWithSession(()=>ERt({emitter:this._emitter,apiService:this._inboxService,cache:this.cache,scheduleCache:this.scheduleCache,useCache:nn(this,kT),args:t}))})}bulkUpdate(t){return Lr(this,null,function*(){return this.callWithSession(()=>Z8r({emitter:this._emitter,apiService:this._inboxService,cache:this.cache,scheduleCache:this.scheduleCache,useCache:nn(this,kT),args:t}))})}};kT=new WeakMap;function o6r(){return typeof window<"u"}var yF,Ole,Lh,l6r=class{constructor(t,e,n){Wa(this,yF),Wa(this,Ole),Wa(this,Lh),gi(this,yF,n),gi(this,Ole,e),gi(this,Lh,t)}get applicationIdentifier(){return nn(this,Lh).applicationIdentifier}get subscriberId(){var t;return(t=nn(this,Lh).subscriber)==null?void 0:t.subscriberId}get context(){return nn(this,Lh).context}get subscriberHash(){return nn(this,Lh).subscriberHash}get contextHash(){return nn(this,Lh).contextHash}get subscriber(){return nn(this,Lh).subscriber}handleApplicationIdentifier(t,e){if(typeof window>"u"||!window.localStorage)return null;const n="novu_keyless_application_identifier";switch(t){case"get":return window.localStorage.getItem(n);case"store":return e&&window.localStorage.setItem(n,e),null;case"delete":return window.localStorage.removeItem(n),null;default:return null}}initialize(t){return Lr(this,null,function*(){var e,n,r,i,o,l;const u=((e=nn(this,Lh).subscriber)==null?void 0:e.subscriberId)===((n=t?.subscriber)==null?void 0:n.subscriberId),d=JSON.stringify(nn(this,Lh).context)===JSON.stringify(t?.context);if(!(u&&d))try{t&&gi(this,Lh,t);const{subscriber:p,subscriberHash:m,contextHash:g,applicationIdentifier:h,defaultSchedule:A,context:b}=nn(this,Lh);let y;o6r()&&(y=Intl.DateTimeFormat().resolvedOptions().timeZone);let v=h;if(v)this.handleApplicationIdentifier("delete");else{const w=this.handleApplicationIdentifier("get");w&&(v=w)}nn(this,yF).emit("session.initialize.pending",{args:nn(this,Lh)});const _=yield nn(this,Ole).initializeSession({applicationIdentifier:v,subscriberHash:m,contextHash:g,subscriber:kc(bi({},p),{subscriberId:(r=p?.subscriberId)!=null?r:"",timezone:(i=p?.timezone)!=null?i:y}),defaultSchedule:A,context:b});(o=_?.applicationIdentifier)!=null&&o.startsWith("pk_keyless_")&&this.handleApplicationIdentifier("store",_.applicationIdentifier),(l=_?.applicationIdentifier)!=null&&l.startsWith("pk_keyless_")||this.handleApplicationIdentifier("delete"),nn(this,yF).emit("session.initialize.resolved",{args:nn(this,Lh),data:_})}catch(p){nn(this,yF).emit("session.initialize.resolved",{args:nn(this,Lh),error:p})}})}};yF=new WeakMap,Ole=new WeakMap,Lh=new WeakMap;var Fle="wss://socket.novu.co",SRt="notifications.notification_received",IRt="notifications.unseen_count_changed",TRt="notifications.unread_count_changed",c6r=({_id:t,transactionId:e,content:n,read:r,seen:i,archived:o,snoozedUntil:l,deliveredAt:u,createdAt:d,lastReadDate:p,firstSeenDate:m,archivedAt:g,channel:h,subscriber:A,subject:b,avatar:y,cta:v,tags:_,data:w,workflow:x,severity:k})=>{var C,E,S,I,B,N,L,M;const R={id:A?._id,subscriberId:A?.subscriberId,firstName:A?.firstName,lastName:A?.lastName,avatar:A?.avatar,locale:A?.locale,data:A?.data,timezone:A?.timezone,email:A?.email,phone:A?.phone},D=(E=(C=v.action)==null?void 0:C.buttons)==null?void 0:E.find($=>$.type==="primary"),P=(I=(S=v.action)==null?void 0:S.buttons)==null?void 0:I.find($=>$.type==="secondary"),O=(N=(B=v.action)==null?void 0:B.result)==null?void 0:N.type,F=(L=v.action)==null?void 0:L.status;return kc(bi(bi({id:t,transactionId:e,subject:b,body:n,to:R,isRead:r,isSeen:i,isArchived:o,isSnoozed:!!l},u&&{deliveredAt:u}),l&&{snoozedUntil:l}),{createdAt:d,readAt:p,firstSeenAt:m,archivedAt:g,avatar:y,primaryAction:D&&{label:D.content,isCompleted:O==="primary"&&F==="done",redirect:D.url?{target:D.target,url:D.url}:void 0},secondaryAction:P&&{label:P.content,isCompleted:O==="secondary"&&F==="done",redirect:P.url?{target:P.target,url:P.url}:void 0},channelType:h,tags:_,redirect:(M=v.data)!=null&&M.url?{url:v.data.url,target:v.data.target}:void 0,data:w,workflow:x,severity:k})},fG,dk,pk,AG,PRe,ORe,FRe,QRe,c3,BRt,$Re,jRe,u6r=class extends fF{constructor({socketUrl:t,inboxServiceInstance:e,eventEmitterInstance:n}){super({eventEmitterInstance:n,inboxServiceInstance:e}),Wa(this,c3),Wa(this,fG),Wa(this,dk),Wa(this,pk),Wa(this,AG),Wa(this,PRe,r=>{try{const i=JSON.parse(r.data);i.event==="notification_received"&&nn(this,dk).emit(SRt,{result:new Mm(c6r(i.data.message),nn(this,dk),this._inboxService)})}catch(i){console.log("error",i)}}),Wa(this,ORe,r=>{try{const i=JSON.parse(r.data);i.event==="unseen_count_changed"&&nn(this,dk).emit(IRt,{result:i.data.unseenCount})}catch{}}),Wa(this,FRe,r=>{try{const i=JSON.parse(r.data);i.event==="unread_count_changed"&&nn(this,dk).emit(TRt,{result:i.data.counts})}catch{}}),Wa(this,QRe,r=>{try{switch(JSON.parse(r.data).event){case"notification_received":nn(this,PRe).call(this,r);break;case"unseen_count_changed":nn(this,ORe).call(this,r);break;case"unread_count_changed":nn(this,FRe).call(this,r);break;default:}}catch{}}),gi(this,dk,n),gi(this,AG,t??Fle)}onSessionSuccess({token:t}){gi(this,fG,t)}isSocketEvent(t){return t===SRt||t===IRt||t===TRt}connect(){return Lr(this,null,function*(){return nn(this,fG)?ok(this,c3,$Re).call(this):this.callWithSession(ok(this,c3,$Re).bind(this))})}disconnect(){return Lr(this,null,function*(){return nn(this,pk)?ok(this,c3,jRe).call(this):this.callWithSession(ok(this,c3,jRe).bind(this))})}};fG=new WeakMap,dk=new WeakMap,pk=new WeakMap,AG=new WeakMap,PRe=new WeakMap,ORe=new WeakMap,FRe=new WeakMap,QRe=new WeakMap,c3=new WeakSet,BRt=function(){return Lr(this,null,function*(){if(nn(this,pk))return;const t={socketUrl:nn(this,AG)};nn(this,dk).emit("socket.connect.pending",{args:t});const e=new URL(nn(this,AG));e.searchParams.set("token",nn(this,fG)),gi(this,pk,new $Fr(e.toString())),nn(this,pk).addEventListener("open",()=>{nn(this,dk).emit("socket.connect.resolved",{args:t})}),nn(this,pk).addEventListener("error",n=>{nn(this,dk).emit("socket.connect.resolved",{args:t,error:n})}),nn(this,pk).addEventListener("message",nn(this,QRe))})},$Re=function(){return Lr(this,null,function*(){try{return yield ok(this,c3,BRt).call(this),{}}catch(t){return{error:new ho("Failed to initialize the PartySocket",t)}}})},jRe=function(){return Lr(this,null,function*(){var t;try{return(t=nn(this,pk))==null||t.close(),gi(this,pk,void 0),{}}catch(e){return{error:new ho("Failed to disconnect from the PartySocket",e)}}})};var d6r="https://ws.novu.co",DRt="notifications.notification_received",NRt="notifications.unseen_count_changed",RRt="notifications.unread_count_changed",p6r=({_id:t,transactionId:e,content:n,read:r,seen:i,archived:o,snoozedUntil:l,deliveredAt:u,createdAt:d,lastReadDate:p,firstSeenDate:m,archivedAt:g,channel:h,subscriber:A,subject:b,avatar:y,cta:v,tags:_,data:w,workflow:x,severity:k})=>{var C,E,S,I,B,N,L,M;const R={id:A?._id,subscriberId:A?.subscriberId,firstName:A?.firstName,lastName:A?.lastName,avatar:A?.avatar,locale:A?.locale,data:A?.data,timezone:A?.timezone,email:A?.email,phone:A?.phone},D=(E=(C=v.action)==null?void 0:C.buttons)==null?void 0:E.find($=>$.type==="primary"),P=(I=(S=v.action)==null?void 0:S.buttons)==null?void 0:I.find($=>$.type==="secondary"),O=(N=(B=v.action)==null?void 0:B.result)==null?void 0:N.type,F=(L=v.action)==null?void 0:L.status;return kc(bi(bi({id:t,transactionId:e,subject:b,body:n,to:R,isRead:r,isSeen:i,isArchived:o,isSnoozed:!!l},u&&{deliveredAt:u}),l&&{snoozedUntil:l}),{createdAt:d,readAt:p,firstSeenAt:m,archivedAt:g,avatar:y,primaryAction:D&&{label:D.content,isCompleted:O==="primary"&&F==="done",redirect:D.url?{target:D.target,url:D.url}:void 0},secondaryAction:P&&{label:P.content,isCompleted:O==="secondary"&&F==="done",redirect:P.url?{target:P.target,url:P.url}:void 0},channelType:h,tags:_,redirect:(M=v.data)!=null&&M.url?{url:v.data.url,target:v.data.target}:void 0,data:w,workflow:x,severity:k})},bG,mk,Ry,yG,zRe,URe,qRe,u3,LRt,GRe,HRe,m6r=class extends fF{constructor({socketUrl:t,inboxServiceInstance:e,eventEmitterInstance:n}){super({eventEmitterInstance:n,inboxServiceInstance:e}),Wa(this,u3),Wa(this,bG),Wa(this,mk),Wa(this,Ry),Wa(this,yG),Wa(this,zRe,({message:r})=>{nn(this,mk).emit(DRt,{result:new Mm(p6r(r),nn(this,mk),this._inboxService)})}),Wa(this,URe,({unseenCount:r})=>{nn(this,mk).emit(NRt,{result:r})}),Wa(this,qRe,({counts:r})=>{nn(this,mk).emit(RRt,{result:r})}),gi(this,mk,n),gi(this,yG,t??d6r)}onSessionSuccess({token:t}){gi(this,bG,t)}isSocketEvent(t){return t===DRt||t===NRt||t===RRt}connect(){return Lr(this,null,function*(){return nn(this,bG)?ok(this,u3,GRe).call(this):this.callWithSession(ok(this,u3,GRe).bind(this))})}disconnect(){return Lr(this,null,function*(){return nn(this,Ry)?ok(this,u3,HRe).call(this):this.callWithSession(ok(this,u3,HRe).bind(this))})}};bG=new WeakMap,mk=new WeakMap,Ry=new WeakMap,yG=new WeakMap,zRe=new WeakMap,URe=new WeakMap,qRe=new WeakMap,u3=new WeakSet,LRt=function(){return Lr(this,null,function*(){var t,e,n;if(nn(this,Ry))return;const r={socketUrl:nn(this,yG)};nn(this,mk).emit("socket.connect.pending",{args:r}),gi(this,Ry,hle(nn(this,yG),{reconnectionDelayMax:1e4,transports:["websocket"],query:{token:`${nn(this,bG)}`}})),nn(this,Ry).on("connect",()=>{nn(this,mk).emit("socket.connect.resolved",{args:r})}),nn(this,Ry).on("connect_error",i=>{nn(this,mk).emit("socket.connect.resolved",{args:r,error:i})}),(t=nn(this,Ry))==null||t.on("notification_received",nn(this,zRe)),(e=nn(this,Ry))==null||e.on("unseen_count_changed",nn(this,URe)),(n=nn(this,Ry))==null||n.on("unread_count_changed",nn(this,qRe))})},GRe=function(){return Lr(this,null,function*(){try{return yield ok(this,u3,LRt).call(this),{}}catch(t){return{error:new ho("Failed to initialize the socket",t)}}})},HRe=function(){return Lr(this,null,function*(){var t;try{return(t=nn(this,Ry))==null||t.disconnect(),gi(this,Ry,void 0),{}}catch(e){return{error:new ho("Failed to disconnect from the socket",e)}}})};var g6r=["wss://eu.socket.novu.co",Fle,"wss://socket.novu-staging.co","wss://socket-worker-local.cli-shortener.workers.dev"],h6r={"https://eu.ws.novu.co":"wss://eu.socket.novu.co","https://ws.novu.co":Fle,"https://dev.ws.novu.co":"wss://socket.novu-staging.co"};function f6r(t){return t?h6r[t]||t:Fle}function A6r(t){return!t||g6r.includes(t)}function b6r({socketUrl:t,inboxServiceInstance:e,eventEmitterInstance:n}){const r=f6r(t);return(A6r(r)?"partysocket":"socket.io")==="partysocket"?new u6r({socketUrl:r,inboxServiceInstance:e,eventEmitterInstance:n}):new m6r({socketUrl:r,inboxServiceInstance:e,eventEmitterInstance:n})}var gk,Mh,ET,Qle,y6r=class{constructor(t){Wa(this,gk),Wa(this,Mh),Wa(this,ET),Wa(this,Qle);var e,n,r;gi(this,Qle,t),gi(this,ET,new q8r({apiUrl:t.apiUrl||t.backendUrl,userAgent:t.__userAgent})),gi(this,gk,new G8r);const i=ARe({subscriberId:t.subscriberId,subscriber:t.subscriber}),o=NNt(t.context);gi(this,Mh,new l6r({applicationIdentifier:t.applicationIdentifier||"",subscriberHash:t.subscriberHash,subscriber:i,defaultSchedule:t.defaultSchedule,context:t.context,contextHash:t.contextHash},nn(this,ET),nn(this,gk))),nn(this,Mh).initialize(),this.notifications=new K8r({useCache:(e=t.useCache)!=null?e:!0,inboxServiceInstance:nn(this,ET),eventEmitterInstance:nn(this,gk)}),this.preferences=new s6r({useCache:(n=t.useCache)!=null?n:!0,inboxServiceInstance:nn(this,ET),eventEmitterInstance:nn(this,gk)}),this.subscriptions=new $8r({subscriber:i,contextKey:o,useCache:(r=t.useCache)!=null?r:!0,inboxServiceInstance:nn(this,ET),eventEmitterInstance:nn(this,gk)}),this.socket=b6r({socketUrl:t.socketUrl,eventEmitterInstance:nn(this,gk),inboxServiceInstance:nn(this,ET)}),this.on=(l,u)=>{this.socket.isSocketEvent(l)&&this.socket.connect();const d=nn(this,gk).on(l,u);return()=>{d()}},this.off=(l,u)=>{nn(this,gk).off(l,u)}}get applicationIdentifier(){return nn(this,Mh).applicationIdentifier}get subscriberId(){return nn(this,Mh).subscriberId}get context(){return nn(this,Mh).context}get options(){return nn(this,Qle)}get contextKey(){return NNt(nn(this,Mh).context)}clearCache(){this.notifications.cache.clearAll(),this.preferences.cache.clearAll(),this.preferences.scheduleCache.clearAll(),this.subscriptions.cache.clearAll()}changeSubscriber(t){return Lr(this,null,function*(){yield nn(this,Mh).initialize({applicationIdentifier:nn(this,Mh).applicationIdentifier||"",subscriberHash:t.subscriberHash,subscriber:t.subscriber,context:nn(this,Mh).context,contextHash:nn(this,Mh).contextHash}),this.clearCache(),(yield this.socket.disconnect()).error||(yield this.socket.connect())})}changeContext(t){return Lr(this,null,function*(){const e=nn(this,Mh).subscriber;if(!e)throw new Error("Cannot change context without an active subscriber");yield nn(this,Mh).initialize({applicationIdentifier:nn(this,Mh).applicationIdentifier||"",subscriberHash:nn(this,Mh).subscriberHash,subscriber:e,context:t.context,contextHash:t.contextHash}),this.clearCache(),(yield this.socket.disconnect()).error||(yield this.socket.connect())})}};gk=new WeakMap,Mh=new WeakMap,ET=new WeakMap,Qle=new WeakMap;var v6r="3.13.0",_6r="@novu/react",w6r=`${_6r}@${v6r}`,MRt=T.createContext(void 0),x6r=t=>{const{subscriberId:e,...n}=t,r=T.useMemo(()=>ARe({subscriberId:e,subscriber:t.subscriber}),[e,t.subscriber]),i=n.applicationIdentifier?n.applicationIdentifier:"",o={...n,applicationIdentifier:i,subscriber:r};return f.jsx(k6r,{...o,applicationIdentifier:i,userAgentType:"hooks",children:t.children})},k6r=t=>{const e=t.applicationIdentifier||"",n=T.useMemo(()=>ARe({subscriberId:t.subscriberId,subscriber:t.subscriber}),[t.subscriberId,t.subscriber]),{children:r,subscriberHash:i,contextHash:o,backendUrl:l,apiUrl:u,socketUrl:d,useCache:p,userAgentType:m,defaultSchedule:g,context:h}=t,A=T.useMemo(()=>new y6r({applicationIdentifier:e,subscriberHash:i,contextHash:o,backendUrl:l,apiUrl:u,socketUrl:d,useCache:p,__userAgent:`${w6r} ${m}`,subscriber:n,defaultSchedule:g,context:h}),[e,i,n,h,o,l,u,d,p,m]);return f.jsx(MRt.Provider,{value:A,children:r})},$le=()=>{const t=T.useContext(MRt);if(!t)throw new Error("useNovu must be used within a <NovuProvider />");return t},jle=t=>{const e=T.useRef(t);return e.current=t,e};function E6r(t,e){if(!("locks"in navigator))return e(t),()=>{};let n=!1,r;const i=new Promise(o=>{r=o});return navigator.locks.request(t,()=>(n||e(t),i)),()=>{n=!0,r()}}var C6r=({channelName:t,onMessage:e})=>{const[n]=T.useState(typeof BroadcastChannel<"u"?new BroadcastChannel(t):void 0),r=i=>{n?.postMessage(i)};return T.useEffect(()=>{const i=o=>{e(o.data)};return n?.addEventListener("message",i),()=>{n?.removeEventListener("message",i)}},[]),{postMessage:r}},WRe=({event:t,eventHandler:e})=>{const n=$le(),r=`nv_ws_connection:a=${n.applicationIdentifier}:s=${n.subscriberId}:c=${n.contextKey}:e=${t}`,{postMessage:i}=C6r({channelName:r,onMessage:e}),o=l=>{e(l),i(l)};T.useEffect(()=>{let l;const u=E6r(r,()=>{l=n.on(t,o)});return()=>{l&&l(),u()}},[])},S6r=t=>{const{filters:e,onSuccess:n,onError:r}=t,{notifications:i}=$le(),o=jle(e),[l,u]=T.useState(),[d,p]=T.useState(),[m,g]=T.useState(!0),[h,A]=T.useState(!1),b=async(v,_)=>{const w=_||o.current,x=w.map(S=>({count:0,filter:S}));let k=[];if(v)for(let S=0;S<x.length;S++){const I=w[S],B=!I.severity||Array.isArray(I.severity)&&I.severity.length===0||Array.isArray(I.severity)&&I.severity.includes(v.severity)||!Array.isArray(I.severity)&&I.severity===v.severity;RRe(I.tags,v.tags)&&B&&k.push(I)}else k=w;if(k.length===0)return;A(!0);const C=await i.count({filters:k});if(A(!1),g(!1),C.error){u(C.error),r?.(C.error);return}const E=C.data;n?.(E.counts),p(S=>{const I=[],B=E.counts;for(let N=0;N<x.length;N++){const L=x[N].filter,R=B.find(D=>fle(D.filter,L))||S?.[N];R&&I.push(R)}return I})};return WRe({event:"notifications.notification_received",eventHandler:v=>{b(v.result)}}),WRe({event:"notifications.unread_count_changed",eventHandler:()=>{b()}}),T.useEffect(()=>{u(void 0),g(!0),A(!1),b(void 0,e)},[JSON.stringify(e)]),{counts:d,error:l,refetch:async()=>{await b()},isLoading:m,isFetching:h}},I6r=t=>{const{tags:e,data:n,read:r,archived:i=!1,snoozed:o=!1,seen:l,severity:u,limit:d=10,onSuccess:p,onError:m}=t||{},g=jle(d),h=jle({tags:e,data:n,read:r,archived:i,snoozed:o,seen:l,severity:u}),A=$le(),[b,y]=T.useState(),[v,_]=T.useState(),[w,x]=T.useState(!0),[k,C]=T.useState(!1),[E,S]=T.useState(!1),I=b?.length,B=I?b[I-1].id:void 0,N=jle(B);T.useEffect(()=>{const $=({data:Q})=>{!Q||!fle(h.current,Q.filter)||(y(Q.notifications),S(Q.hasMore))},j=A.on("notifications.list.updated",$);return()=>{j()}},[h,A]),WRe({event:"notifications.notification_received",eventHandler:({result:$})=>{const j=h.current;if(L8r($,j)){const z={...j,limit:g.current};A.notifications.cache.unshift(z,$)}}});const L=T.useCallback(async $=>{$?.refetch&&(_(void 0),x(!0),C(!1)),C(!0);const j=await A.notifications.list({...h.current,limit:d,after:$?.refetch?void 0:N.current});if(j.error)_(j.error),m?.(j.error),x(!1),C(!1);else if(j.data){const Q=j.data;p?.(Q.notifications),y(Q.notifications),S(Q.hasMore),x(!1),C(!1)}},[A,h,N,d,m,p]);T.useEffect(()=>{A.notifications.clearCache({filter:h.current}),L({refetch:!0})},[h,A,JSON.stringify(h.current),L]);const M=T.useCallback(()=>(A.notifications.clearCache({filter:h.current}),L({refetch:!0})),[h,A,L]),R=T.useCallback(async()=>{if(!(!E||k))return L()},[E,k,L]),D=T.useCallback(async()=>await A.notifications.readAll({tags:h.current.tags,data:h.current.data}),[h,A]),P=T.useCallback(async()=>await A.notifications.seenAll({tags:h.current.tags,data:h.current.data}),[h,A]),O=T.useCallback(async()=>await A.notifications.archiveAll({tags:h.current.tags,data:h.current.data}),[h,A]),F=T.useCallback(async()=>await A.notifications.archiveAllRead({tags:h.current.tags,data:h.current.data}),[h,A]);return{readAll:D,seenAll:P,archiveAll:O,archiveAllRead:F,notifications:b,error:v,isLoading:w,isFetching:k,refetch:M,fetchMore:R,hasMore:E}};const YRe=[{id:"pwa-install",titleKey:"notifications.system.pwa.title",bodyKey:"notifications.system.pwa.body",dismissStorageKey:"xyzen-pwa-prompt-dismissed",condition:()=>{const t=window.matchMedia("(display-mode: standalone)").matches;return window.matchMedia("(min-width: 1024px)").matches&&!t}}];function T6r(){const{t}=yn(),[e,n]=T.useState(()=>{const o=new Set;for(const l of YRe)localStorage.getItem(l.dismissStorageKey)&&o.add(l.id);return o}),r=T.useMemo(()=>YRe.filter(o=>!e.has(o.id)&&o.condition()).map(o=>({id:o.id,title:t(o.titleKey),body:t(o.bodyKey)})),[t,e]),i=T.useCallback(o=>{const l=YRe.find(u=>u.id===o);l&&localStorage.setItem(l.dismissStorageKey,"true"),n(u=>new Set(u).add(o))},[]);return{notifications:r,dismiss:i,count:r.length}}const B6r=[{key:"all",icon:MXn},{key:"unread",icon:KAt},{key:"archived",icon:eSe}],D6r=/\n<!-- meta:(.*?) -->$/;function PRt(t){const e={body:t,title:"",agentName:"",agentAvatar:"",url:"",messageId:"",actionType:"",invitationId:"",teamId:"",teamName:"",inviterUsername:"",inviterAvatarUrl:"",role:""},n=D6r.exec(t);if(!n)return e;const r=t.slice(0,n.index);try{const i=JSON.parse(n[1]);return{body:r,title:i.title??"",agentName:i.agent_name??"",agentAvatar:i.agent_avatar??"",url:i.url??"",messageId:i.message_id??"",actionType:i.action_type??"",invitationId:i.invitation_id??"",teamId:i.team_id??"",teamName:i.team_name??"",inviterUsername:i.inviter_username??"",inviterAvatarUrl:i.inviter_avatar_url??"",role:i.role??""}}catch{return e}}function ORt({items:t,onDismiss:e}){const{t:n}=yn();return t.length===0?null:f.jsxs("div",{className:"border-b border-neutral-100 dark:border-neutral-800/60",children:[f.jsx("div",{className:"px-4 pt-2 pb-1",children:f.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-wide text-neutral-400 dark:text-neutral-500",children:n("notifications.system.title")})}),t.map(r=>f.jsxs("div",{className:"group flex gap-3 px-4 py-3 bg-amber-50/40 dark:bg-amber-950/10",children:[f.jsx("div",{className:"flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-full bg-amber-100 text-amber-600 dark:bg-amber-500/10 dark:text-amber-400",children:f.jsx(iie,{className:"h-4.5 w-4.5"})}),f.jsxs("div",{className:"min-w-0 flex-1",children:[f.jsx("p",{className:"text-[13px] font-semibold text-neutral-900 dark:text-neutral-100",children:r.title}),f.jsx("p",{className:"mt-0.5 text-[13px] leading-snug text-neutral-500 dark:text-neutral-400",children:r.body})]}),f.jsx("button",{onClick:()=>e(r.id),className:"flex-shrink-0 self-start rounded-md p-1.5 text-neutral-400 transition-colors hover:bg-neutral-200/70 hover:text-neutral-600 dark:hover:bg-neutral-700/50 dark:hover:text-neutral-300",title:n("notifications.system.dismiss"),children:f.jsx(q1,{className:"h-3.5 w-3.5"})})]},r.id))]})}function N6r({systemCount:t=0}){const{counts:e}=S6r({filters:[{read:!1}]}),n=(e?.[0]?.count??0)+t;return n===0?null:f.jsx("span",{className:"absolute -top-1 -right-1 flex h-4 min-w-4 items-center justify-center rounded-full bg-red-500 px-1 text-[10px] font-bold text-white shadow-sm",children:n>99?"99+":n})}const vG="rounded-md p-1.5 text-neutral-400 transition-colors hover:bg-neutral-200/70 hover:text-neutral-600 active:bg-neutral-200/70 dark:hover:bg-neutral-700/50 dark:hover:text-neutral-300",R6r=T.memo(function({notification:e,isArchivedView:n,onNavigate:r,onTeamInvitationAction:i}){const o=SNt(e.createdAt),l=PRt(e.body??""),u=T.useCallback(async()=>{if(e.isRead||await e.read(),l.actionType==="team_invitation"){i?.({invitationId:l.invitationId,teamId:l.teamId,teamName:l.teamName,inviterUsername:l.inviterUsername,inviterAvatarUrl:l.inviterAvatarUrl,role:l.role});return}const A=l.url||e.redirect?.url;if(!A)return;const b=/\/#\/chat\/([a-zA-Z0-9_-]+)/.exec(A),y=/[?&]topic=([^&]+)/.exec(A),v=b?.[1]??y?.[1];v&&r?r(v,l.messageId||void 0):window.location.hash=`#${A}`},[e,l.url,l.messageId,l.actionType,l.invitationId,l.teamId,l.teamName,l.inviterUsername,l.inviterAvatarUrl,l.role,r,i]),d=T.useCallback(async A=>{A.stopPropagation(),e.isRead?await e.unread():await e.read()},[e]),p=T.useCallback(async A=>{A.stopPropagation(),await e.delete()},[e]),m=T.useCallback(async A=>{A.stopPropagation(),await e.unarchive()},[e]),g=T.useCallback(async A=>{A.stopPropagation(),await e.archive()},[e]),h=l.agentName||l.title;return f.jsxs(Et.div,{layout:!0,initial:{opacity:0,y:8},animate:{opacity:1,y:0},exit:{opacity:0,x:60},transition:{duration:.2},onClick:u,className:Yt("group relative flex cursor-pointer gap-3 px-4 py-3","border-b border-neutral-100 dark:border-neutral-800/60","transition-colors hover:bg-neutral-50/80 dark:hover:bg-neutral-800/40",!e.isRead&&"bg-blue-50/40 dark:bg-blue-950/20"),children:[f.jsxs("div",{className:"relative flex-shrink-0 pt-0.5",children:[l.agentAvatar?f.jsx("img",{src:l.agentAvatar,alt:h,className:"h-9 w-9 rounded-full object-cover"}):f.jsx("div",{className:"flex h-9 w-9 items-center justify-center rounded-full bg-neutral-200 text-xs font-semibold text-neutral-600 dark:bg-neutral-700 dark:text-neutral-300",children:(h||"N").charAt(0).toUpperCase()}),!e.isRead&&f.jsx("span",{className:"absolute -top-0.5 -right-0.5 h-2.5 w-2.5 rounded-full border-2 border-white bg-blue-500 dark:border-neutral-900"})]}),f.jsxs("div",{className:"min-w-0 flex-1",children:[f.jsxs("div",{className:"flex items-center gap-1",children:[h&&f.jsx("p",{className:"truncate text-[13px] font-semibold text-neutral-900 dark:text-neutral-100",children:h}),f.jsx("span",{className:"flex-shrink-0 text-[11px] text-neutral-400 dark:text-neutral-500",children:o}),f.jsx("div",{className:"ml-auto flex flex-shrink-0 items-center gap-0.5 opacity-0 transition-opacity group-hover:opacity-100 max-md:opacity-100",children:n?f.jsxs(f.Fragment,{children:[f.jsx("button",{onClick:m,className:vG,title:"Restore",children:f.jsx(tbt,{className:"h-3.5 w-3.5"})}),f.jsx("button",{onClick:p,className:vG,title:"Delete",children:f.jsx(Ure,{className:"h-3.5 w-3.5"})})]}):f.jsxs(f.Fragment,{children:[f.jsx("button",{onClick:d,className:vG,title:e.isRead?"Mark as unread":"Mark as read",children:e.isRead?f.jsx(KAt,{className:"h-3.5 w-3.5"}):f.jsx(mh,{className:"h-3.5 w-3.5"})}),f.jsx("button",{onClick:g,className:vG,title:"Archive",children:f.jsx(eSe,{className:"h-3.5 w-3.5"})}),f.jsx("button",{onClick:p,className:vG,title:"Delete",children:f.jsx(Ure,{className:"h-3.5 w-3.5"})})]})})]}),f.jsx("p",{className:Yt("mt-0.5 line-clamp-2 text-[13px] leading-snug",h?"text-neutral-500 dark:text-neutral-400":"text-neutral-700 dark:text-neutral-300"),children:l.body})]})]})});function L6r({filter:t,onNavigate:e,onTeamInvitationAction:n}){const{t:r}=yn(),{notifications:i,isLoading:o,hasMore:l,fetchMore:u,readAll:d,archiveAllRead:p}=I6r(t),m=!!t.archived,[g,h]=T.useState(!1),A=T.useCallback(async()=>{if(!(!i||i.length===0||g)){h(!0);try{await Promise.all(i.map(y=>y.delete()))}finally{h(!1)}}},[i,g]),b=T.useRef(null);return T.useEffect(()=>{if(!b.current||!l)return;const y=new IntersectionObserver(([v])=>{v.isIntersecting&&u()},{rootMargin:"200px"});return y.observe(b.current),()=>y.disconnect()},[l,u]),f.jsxs("div",{className:"flex h-full flex-col",children:[!m&&f.jsxs("div",{className:"flex items-center justify-end gap-1 border-b border-neutral-100 px-4 py-1.5 dark:border-neutral-800/60",children:[f.jsx("button",{onClick:()=>d(),className:"rounded-md p-1.5 text-neutral-400 transition-colors hover:bg-neutral-100 hover:text-neutral-600 dark:hover:bg-neutral-800/40 dark:hover:text-neutral-300",title:r("notifications.actions.readAll"),children:f.jsx(bXn,{className:"h-3.5 w-3.5"})}),f.jsx("button",{onClick:()=>p(),className:"rounded-md p-1.5 text-neutral-400 transition-colors hover:bg-neutral-100 hover:text-neutral-600 dark:hover:bg-neutral-800/40 dark:hover:text-neutral-300",title:r("notifications.actions.archiveRead"),children:f.jsx(eSe,{className:"h-3.5 w-3.5"})})]}),m&&i&&i.length>0&&f.jsx("div",{className:"flex items-center justify-end gap-1 border-b border-neutral-100 px-4 py-1.5 dark:border-neutral-800/60",children:f.jsxs(sRe,{children:[f.jsx(fFr,{asChild:!0,children:f.jsx("button",{disabled:g,className:"rounded-md p-1.5 text-neutral-400 transition-colors hover:bg-red-50 hover:text-red-500 disabled:opacity-40 dark:hover:bg-red-500/10 dark:hover:text-red-400",title:r("notifications.actions.deleteAll"),children:f.jsx(Ure,{className:"h-3.5 w-3.5"})})}),f.jsxs(oRe,{className:"sm:max-w-sm rounded-sm",children:[f.jsxs(lRe,{children:[f.jsx(uRe,{className:"text-sm",children:r("notifications.actions.deleteAll")}),f.jsx(dRe,{className:"text-xs",children:r("notifications.actions.deleteAllConfirm")})]}),f.jsxs(cRe,{children:[f.jsx(mRe,{className:"h-8 rounded-sm text-xs",children:r("common.cancel")}),f.jsx(pRe,{onClick:A,className:"h-8 rounded-sm bg-red-500 text-xs text-white hover:bg-red-600 dark:bg-red-600 dark:hover:bg-red-500",children:r("notifications.actions.confirmDelete")})]})]})]})}),f.jsxs("div",{className:"custom-scrollbar flex-1 overflow-y-auto",children:[f.jsx(Qr,{mode:"popLayout",children:i?.map(y=>f.jsx(R6r,{notification:y,isArchivedView:m,onNavigate:e,onTeamInvitationAction:n},y.id))}),o&&f.jsx("div",{className:"space-y-1 p-4",children:Array.from({length:3}).map((y,v)=>f.jsxs("div",{className:"flex animate-pulse gap-3 py-3",children:[f.jsx("div",{className:"h-9 w-9 flex-shrink-0 rounded-full bg-neutral-200 dark:bg-neutral-700"}),f.jsxs("div",{className:"flex-1 space-y-2",children:[f.jsx("div",{className:"h-3 w-3/4 rounded bg-neutral-200 dark:bg-neutral-700"}),f.jsx("div",{className:"h-3 w-1/2 rounded bg-neutral-200 dark:bg-neutral-700"})]})]},v))}),!o&&(!i||i.length===0)&&f.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-neutral-400 dark:text-neutral-500",children:[f.jsx(iie,{className:"mb-3 h-10 w-10 opacity-40"}),f.jsx("p",{className:"text-sm",children:r("notifications.empty")})]}),l&&f.jsx("div",{ref:b,className:"h-4"})]})]})}const M6r={all:{archived:!1},unread:{read:!1,archived:!1},archived:{archived:!0}};function FRt({onNavigate:t,onTeamInvitationAction:e}){const{t:n}=yn(),[r,i]=T.useState("all");return f.jsxs("div",{className:"flex h-full flex-col",children:[f.jsx("div",{className:"px-4 pt-1 pb-1.5",children:f.jsx("div",{className:"flex rounded-lg bg-neutral-100/80 p-0.5 dark:bg-neutral-800/50",children:B6r.map(({key:o,icon:l})=>f.jsxs("button",{onClick:()=>i(o),className:Yt("relative flex flex-1 items-center justify-center gap-1.5 rounded-md py-1.5 text-xs font-medium transition-colors",r===o?"text-neutral-900 dark:text-neutral-100":"text-neutral-500 hover:text-neutral-700 dark:text-neutral-400 dark:hover:text-neutral-200"),children:[r===o&&f.jsx(Et.div,{layoutId:"notification-tab",className:"absolute inset-0 rounded-md bg-white shadow-sm dark:bg-neutral-700",transition:{type:"spring",stiffness:400,damping:30}}),f.jsxs("span",{className:"relative z-10 flex items-center gap-1.5",children:[f.jsx(l,{className:"h-3.5 w-3.5"}),n(`notifications.filter.${o}`)]})]},o))})}),f.jsx(L6r,{filter:M6r[r],onNavigate:t,onTeamInvitationAction:e},r)]})}function P6r({toastId:t,parsed:e,onView:n}){const{t:r}=yn();return f.jsxs("div",{className:"w-[360px] rounded-sm border border-white/20 bg-white/70 p-4 shadow-2xl backdrop-blur-2xl dark:border-white/10 dark:bg-neutral-900/70",children:[f.jsxs("div",{className:"flex items-start gap-3",children:[f.jsx(JR,{src:e.inviterAvatarUrl,name:e.inviterUsername,size:"md"}),f.jsxs("div",{className:"min-w-0 flex-1",children:[f.jsx("p",{className:"text-[13px] font-semibold text-neutral-900 dark:text-neutral-100",children:e.title||"Team Invitation"}),f.jsx("p",{className:"mt-0.5 text-[13px] leading-snug text-neutral-600 dark:text-neutral-400",children:e.body})]})]}),f.jsxs("div",{className:"mt-3 flex justify-end gap-2",children:[f.jsx("button",{onClick:()=>br.dismiss(t),className:"rounded-sm px-3 py-1.5 text-xs font-medium text-neutral-500 transition-colors hover:bg-neutral-200/60 dark:text-neutral-400 dark:hover:bg-white/10",children:r("common.dismiss","Dismiss")}),f.jsx("button",{onClick:()=>{n(),br.dismiss(t)},className:"rounded-sm bg-neutral-900 px-3 py-1.5 text-xs font-medium text-white transition-colors hover:bg-neutral-800 dark:bg-white dark:text-neutral-900 dark:hover:bg-neutral-200",children:r("teams.viewDetails","View")})]})]})}function O6r(t){const e=$le();T.useEffect(()=>e.on("notifications.notification_received",({result:r})=>{const i=PRt(r.body??"");if(i.actionType==="team_invitation"&&t){const o={invitationId:i.invitationId,teamId:i.teamId,teamName:i.teamName,inviterUsername:i.inviterUsername,inviterAvatarUrl:i.inviterAvatarUrl,role:i.role};br.custom(l=>f.jsx(P6r,{toastId:l,parsed:i,onView:()=>t(o)}),{duration:1e4})}}),[e,t])}function F6r(){const{t}=yn(),e=iG(),n=T6r(),{activateChannel:r,setActivePanel:i,requestFocusAgent:o,setMobilePage:l,setMobileCeoOverlay:u,highlightMessage:d}=zn(Vs(E=>({activateChannel:E.activateChannel,setActivePanel:E.setActivePanel,requestFocusAgent:E.requestFocusAgent,setMobilePage:E.setMobilePage,setMobileCeoOverlay:E.setMobileCeoOverlay,highlightMessage:E.highlightMessage}))),[p,m]=T.useState(!1),[g,h]=T.useState(!1),[A,b]=T.useState(null),y=T.useCallback(E=>{b(E)},[]);O6r(y);const v=T.useCallback(()=>m(E=>!E),[]),_=T.useCallback(()=>m(!1),[]),w=T.useCallback(async(E,S)=>{_(),i("chat"),e&&(u(!1),l(1)),await r(E);const I=zn.getState().channels[E];I?.agentId&&o(I.agentId),S&&d(S)},[_,r,i,o,e,l,u,d]),x=T.useCallback(E=>{_(),b(E)},[_]),k=T.useCallback(()=>{b(null),i("teams")},[i]),C=T.useCallback(()=>{b(null)},[]);return T.useEffect(()=>{if(!p)return;const E=S=>{S.key==="Escape"&&_()};return document.addEventListener("keydown",E),()=>document.removeEventListener("keydown",E)},[p,_]),f.jsxs(f.Fragment,{children:[f.jsxs("div",{className:"relative",children:[f.jsxs(Et.button,{whileHover:{scale:1.1},whileTap:{scale:.9},onClick:v,onMouseEnter:()=>h(!0),onMouseLeave:()=>h(!1),className:"relative flex items-center justify-center h-7 w-7 text-neutral-500 dark:text-neutral-400 hover:text-neutral-700 dark:hover:text-neutral-200 transition-colors",children:[f.jsx(iie,{className:"h-4.5 w-4.5"}),f.jsx(N6r,{systemCount:n.count})]}),f.jsx(Qr,{children:g&&!p&&!e&&f.jsxs(Et.div,{initial:{opacity:0,y:8,scale:.95},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:4,scale:.95},transition:{duration:.15},className:"absolute -top-10 left-1/2 -translate-x-1/2 whitespace-nowrap rounded-lg bg-neutral-900 px-3 py-1.5 text-xs font-medium text-white shadow-lg dark:bg-neutral-100 dark:text-neutral-900",children:[t("notifications.bell.title"),f.jsx("div",{className:"absolute -bottom-1 left-1/2 -translate-x-1/2 border-4 border-transparent border-t-neutral-900 dark:border-t-neutral-100"})]})})]}),e&&f.jsx(El,{isOpen:p,onClose:_,mobileHeight:"h-[85vh]",size:"sm",children:f.jsxs("div",{className:"flex h-full flex-col",children:[f.jsxs("div",{className:"flex items-center justify-between px-5 pt-6 pb-2 md:py-2",children:[f.jsx("h2",{className:"text-base font-semibold text-neutral-900 dark:text-neutral-100",children:t("notifications.bell.title")}),f.jsx("button",{onClick:_,className:"rounded-lg p-1.5 text-neutral-400 transition-colors hover:bg-neutral-100 hover:text-neutral-600 dark:hover:bg-neutral-800 dark:hover:text-neutral-300",children:f.jsx(q1,{className:"h-5 w-5"})})]}),f.jsx(ORt,{items:n.notifications,onDismiss:n.dismiss}),f.jsx(FRt,{onNavigate:w,onTeamInvitationAction:x})]})}),!e&&ji.createPortal(f.jsx(Qr,{children:p&&f.jsxs(f.Fragment,{children:[f.jsx(Et.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.2},className:"fixed inset-0 z-[70]",onClick:_}),f.jsx(Et.div,{initial:{x:"100%"},animate:{x:0},exit:{x:"100%"},transition:{type:"spring",damping:30,stiffness:300,mass:.8},className:Yt("fixed top-0 right-0 z-[71] h-full w-[380px]","bg-white/90 dark:bg-neutral-900/90","backdrop-blur-2xl","border-l border-neutral-200/60 dark:border-neutral-700/50","shadow-2xl","text-neutral-900 dark:text-neutral-100"),style:{paddingBottom:YA},children:f.jsxs("div",{className:"flex h-full flex-col",children:[f.jsxs("div",{className:"flex items-center justify-between px-5 py-4",children:[f.jsx("h2",{className:"text-base font-semibold",children:t("notifications.bell.title")}),f.jsx("button",{onClick:_,className:"rounded-lg p-1.5 text-neutral-400 transition-colors hover:bg-neutral-100 hover:text-neutral-600 dark:hover:bg-neutral-800 dark:hover:text-neutral-300",children:f.jsx(q1,{className:"h-5 w-5"})})]}),f.jsx(ORt,{items:n.notifications,onDismiss:n.dismiss}),f.jsx(FRt,{onNavigate:w,onTeamInvitationAction:x})]})},"notification-drawer")]})}),document.body),f.jsx(Q6r,{data:A,onClose:()=>b(null),onAccepted:k,onDeclined:C})]})}function Q6r({data:t,onClose:e,onAccepted:n,onDeclined:r}){const{t:i}=yn(),[o,l]=T.useState(null),[u,d]=T.useState(!1),[p,m]=T.useState(!1);T.useEffect(()=>{if(!t?.teamId){l(null);return}let A=!1;return d(!0),Lm.getTeam(t.teamId).then(b=>{A||l(b)}).catch(()=>{A||l(null)}).finally(()=>{A||d(!1)}),()=>{A=!0}},[t?.teamId]);const g=async()=>{if(t?.invitationId){m(!0);try{await Lm.acceptInvitation(t.invitationId),br.success(i("teams.invitationAccepted","Joined {{team}}",{team:t.teamName})),n()}catch{br.error(i("common.error","Error"))}finally{m(!1)}}},h=async()=>{if(t?.invitationId){m(!0);try{await Lm.declineInvitation(t.invitationId),br.success(i("teams.invitationDeclined","Invitation declined")),r()}catch{br.error(i("common.error","Error"))}finally{m(!1)}}};return f.jsxs(El,{isOpen:!!t,onClose:e,size:"sm",children:[f.jsx("div",{className:"shrink-0 border-b border-neutral-200/60 px-5 pb-3 pt-5 dark:border-neutral-800/60",children:f.jsx("h2",{className:"text-lg font-semibold text-neutral-900 dark:text-white",children:i("teams.invitationDetail","Team Invitation")})}),f.jsx("div",{className:"flex-1 overflow-y-auto custom-scrollbar",children:f.jsx("div",{className:"space-y-5 px-5 py-5",children:u?f.jsx("div",{className:"flex justify-center py-8",children:f.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-neutral-300 border-t-neutral-900 dark:border-t-neutral-100"})}):f.jsxs(f.Fragment,{children:[f.jsxs("div",{className:"rounded-lg bg-neutral-100/60 p-4 dark:bg-white/[0.04]",children:[f.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[f.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-lg bg-neutral-200 dark:bg-neutral-700",children:f.jsx(mie,{className:"h-5 w-5 text-neutral-600 dark:text-neutral-300"})}),f.jsxs("div",{children:[f.jsx("div",{className:"text-[13px] font-semibold text-neutral-900 dark:text-neutral-100",children:t?.teamName}),o?.member_count!=null&&f.jsxs("div",{className:"text-xs text-neutral-500 dark:text-neutral-400",children:[o.member_count," ",i("teams.members","members")]})]})]}),o?.description&&f.jsx("p",{className:"text-[13px] text-neutral-600 dark:text-neutral-400",children:o.description})]}),f.jsxs("div",{className:"space-y-3",children:[f.jsxs("div",{className:"flex items-center justify-between",children:[f.jsx("span",{className:"text-xs text-neutral-500 dark:text-neutral-400",children:i("teams.invitedBy","Invited by")}),f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx(JR,{src:t?.inviterAvatarUrl,name:t?.inviterUsername||"",size:"sm"}),f.jsx("span",{className:"text-[13px] font-medium text-neutral-900 dark:text-neutral-100",children:t?.inviterUsername})]})]}),f.jsxs("div",{className:"flex items-center justify-between",children:[f.jsx("span",{className:"text-xs text-neutral-500 dark:text-neutral-400",children:i("teams.roleLabel","Role")}),f.jsx("span",{className:"text-[13px] font-medium text-neutral-900 dark:text-neutral-100 capitalize",children:t?.role})]})]})]})})}),f.jsx("div",{className:"shrink-0 border-t border-neutral-200/60 px-5 py-4 dark:border-neutral-800/60",children:f.jsxs("div",{className:"flex justify-end gap-2.5",children:[f.jsx(Oa,{variant:"secondary",onClick:h,disabled:p,className:"text-red-500 hover:text-red-600",children:i("teams.decline","Decline")}),f.jsx(Oa,{onClick:g,disabled:p,children:i("teams.accept","Accept")})]})})]})}function QRt(){const{notificationEnabled:t,novuAppIdentifier:e,novuApiUrl:n,novuWsUrl:r}=gRe(),i=fg();return!t||!e||!i.isAuthenticated?null:f.jsx(x6r,{applicationIdentifier:e,subscriberId:i.user?.id??"",backendUrl:n||void 0,socketUrl:r||void 0,children:f.jsx(F6r,{})})}const YA=72,Dg=8;function $6r({mouseX:t,item:e,isActive:n,onClick:r}){const i=T.useRef(null),[o,l]=T.useState(!1),u=Wb(t,y=>{const v=i.current?.getBoundingClientRect()??{x:0,width:0};return y-v.x-v.width/2}),d=Wb(u,[-100,0,100],[44,56,44]),p=Wb(u,[-100,0,100],[20,26,20]),m=Wb(u,[-100,0,100],[0,-6,0]),g=tR(d,{mass:.1,stiffness:200,damping:15}),h=tR(p,{mass:.1,stiffness:200,damping:15}),A=tR(m,{mass:.1,stiffness:200,damping:15}),b=e.icon;return f.jsxs(Et.button,{ref:i,style:{width:g,height:g,y:A},onClick:r,onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),className:Yt("relative flex flex-col items-center justify-center gap-0.5 rounded-sm transition-colors duration-200","bg-white/80 dark:bg-neutral-800/60","hover:bg-white dark:hover:bg-neutral-700/80","border border-neutral-200/40 dark:border-neutral-700/30",n&&"bg-white dark:bg-neutral-700/80 shadow-md"),children:[f.jsx(Qr,{children:o&&f.jsxs(Et.div,{initial:{opacity:0,y:8,scale:.95},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:4,scale:.95},transition:{duration:.15},className:"absolute -top-10 left-1/2 -translate-x-1/2 whitespace-nowrap rounded-lg bg-neutral-900 px-3 py-1.5 text-xs font-medium text-white shadow-lg dark:bg-neutral-100 dark:text-neutral-900",children:[e.label,f.jsx("div",{className:"absolute -bottom-1 left-1/2 -translate-x-1/2 border-4 border-transparent border-t-neutral-900 dark:border-t-neutral-100"})]})}),f.jsx(Et.div,{style:{width:h,height:h},className:"flex items-center justify-center",children:f.jsx(b,{className:Yt("w-full h-full transition-colors duration-200",n?"text-indigo-600 dark:text-indigo-400":"text-neutral-600 dark:text-neutral-400")})}),n&&f.jsx(Et.div,{layoutId:"dock-active-indicator",className:"h-1 w-1 rounded-full bg-indigo-500",transition:{type:"spring",stiffness:300,damping:30}})]})}function j6r({compact:t=!1}){const e=fg(),{t:n}=yn(),[r,i]=T.useState(!1),[o,l]=T.useState(!1),[u,d]=T.useState(!1),[p,m]=T.useState(!1),g=zn(y=>y.openSettingsModal),h=zO(),A=e.isAuthenticated||!!e.token,b=t?"h-10 w-10":"h-11 w-11";return e.isLoading?f.jsx("div",{className:Yt(b,"flex items-center justify-center rounded-full bg-white/80 dark:bg-neutral-800/60"),children:f.jsx("div",{className:"h-4 w-4 animate-spin rounded-full border-2 border-neutral-300 border-t-indigo-600 dark:border-neutral-700 dark:border-t-indigo-500"})}):A?f.jsxs(f.Fragment,{children:[f.jsxs(bq,{open:r,onOpenChange:i,children:[f.jsx(yq,{asChild:!0,children:f.jsx(Et.button,{whileHover:{scale:1.05},whileTap:{scale:.95},className:Yt(b,"relative flex items-center justify-center rounded-full overflow-hidden transition-shadow hover:shadow-lg","ring-2 ring-neutral-200/60 dark:ring-neutral-700/50"),children:e.user?.avatar?f.jsx("img",{src:e.user.avatar,alt:e.user?.username??"User",className:"h-full w-full object-cover"}):f.jsx("div",{className:"flex h-full w-full items-center justify-center bg-gradient-to-br from-indigo-500 to-purple-600",children:f.jsx(rO,{className:"h-5 w-5 text-white"})})})}),f.jsxs(vq,{align:"start",side:"top",sideOffset:12,className:"w-72 mb-2",children:[f.jsxs(lDe,{className:"flex items-center gap-3 p-3",children:[e.user?.avatar?f.jsx("img",{src:e.user.avatar,alt:e.user?.username??"User",className:"h-10 w-10 rounded-full"}):f.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-full bg-gradient-to-br from-indigo-500 to-purple-600",children:f.jsx(rO,{className:"h-5 w-5 text-white"})}),f.jsx("div",{className:"flex flex-col",children:f.jsx("span",{className:"text-sm font-semibold text-neutral-900 dark:text-neutral-100",children:e.user?.username??n("app.authStatus.loggedIn")})})]}),f.jsx(OO,{}),h&&f.jsx("div",{className:"px-3 py-2",children:f.jsxs("div",{className:"flex items-center justify-between rounded-lg bg-gradient-to-r from-indigo-50 to-purple-50 dark:from-indigo-950/30 dark:to-purple-950/30 px-3 py-2",children:[f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx(Xo,{className:"h-5 w-5 text-indigo-600 dark:text-indigo-400"}),f.jsxs("div",{children:[f.jsx("div",{className:"text-xs text-neutral-500 dark:text-neutral-400",children:n("app.authStatus.pointsBalance")}),f.jsx("div",{className:"text-lg font-bold text-indigo-600 dark:text-indigo-400",children:h.isLoading?"...":h.points??"--"})]})]}),f.jsx("button",{onClick:()=>{i(!1),d(!0)},className:"rounded-full p-1.5 text-neutral-400 hover:bg-white/50 hover:text-indigo-600 dark:hover:bg-neutral-800 dark:hover:text-indigo-400 transition-colors",children:f.jsx(mu,{className:"h-5 w-5"})})]})}),f.jsx(OO,{}),$A("developerReward")&&f.jsxs(gC,{onSelect:()=>{i(!1),m(!0)},className:"flex items-center gap-2 px-3 py-2 cursor-pointer",children:[f.jsx(nO,{className:"h-4 w-4"}),n("subscription.creator")]}),f.jsxs(gC,{onSelect:()=>{i(!1),g()},className:"flex items-center gap-2 px-3 py-2 cursor-pointer",children:[f.jsx(bh,{className:"h-4 w-4"}),n("app.authStatus.settings")]}),f.jsx(OO,{}),f.jsxs(gC,{onSelect:()=>{i(!1),Z5()},className:"flex items-center gap-2 px-3 py-2 cursor-pointer text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-950/20",children:[f.jsx(K2e,{className:"h-4 w-4"}),n("app.authStatus.logout")]})]})]}),h&&f.jsx(qO,{isOpen:u,onClose:()=>d(!1)}),f.jsx(cDe,{isOpen:p,onClose:()=>m(!1)})]}):f.jsxs(f.Fragment,{children:[f.jsx(Et.button,{whileHover:{scale:1.05},whileTap:{scale:.95},onClick:()=>l(!0),className:Yt(b,"flex items-center justify-center rounded-full bg-white/80 dark:bg-neutral-800/60 border border-amber-200/60 dark:border-amber-700/50 transition-shadow hover:shadow-lg"),title:n("app.authStatus.unauthorized"),children:f.jsx(Qp,{className:"h-5 w-5 text-amber-500"})}),f.jsx(L2t,{isOpen:o,onClose:()=>l(!1),onSubmit:async y=>{await e.login(y)}})]})}const z6r="https://github.com/ScienceOL/Xyzen";function U6r(){const{backend:t}=FNe(),{t:e}=yn(),[n,r]=T.useState(!1),[i,o]=T.useState(!1),u=B1()!=="zh-cn";return f.jsxs("div",{className:"relative flex items-center gap-1.5",children:[f.jsx(lFr,{onClick:()=>o(!0),children:e("app.toolbar.joinBeta")}),f.jsx(gFr,{isOpen:i,onClose:()=>o(!1)}),f.jsx("a",{href:z6r,target:"_blank",rel:"noopener noreferrer",className:"flex items-center justify-center h-7 w-7 rounded-md transition-colors hover:bg-white/50 dark:hover:bg-neutral-700/50",children:f.jsx(WAt,{className:"h-4 w-4 text-neutral-500 dark:text-neutral-500 hover:text-neutral-700 dark:hover:text-neutral-300 transition-colors"})}),f.jsxs("div",{className:"relative flex items-center gap-1 cursor-default",onMouseEnter:()=>r(!0),onMouseLeave:()=>r(!1),children:[f.jsx("span",{className:"text-[11px] font-medium text-neutral-500 dark:text-neutral-500 tabular-nums",children:t.version||"..."}),f.jsx("div",{className:"flex items-center justify-center h-4 w-4 rounded-sm",title:e(`app.region.${u?"international":"china"}`),children:f.jsx(nU,{className:Yt("h-3 w-3 transition-colors",u?"text-indigo-400/60 dark:text-indigo-500/60":"text-emerald-400/60 dark:text-emerald-500/60")})}),f.jsx(Qr,{children:n&&f.jsxs(Et.div,{initial:{opacity:0,y:8,scale:.95},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:4,scale:.95},transition:{duration:.15},className:"absolute -top-12 left-1/2 -translate-x-1/2 whitespace-nowrap rounded-lg bg-neutral-900 px-3 py-1.5 text-xs text-white shadow-lg dark:bg-neutral-100 dark:text-neutral-900",children:[f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("span",{className:"font-medium",children:e(`app.region.${u?"international":"china"}`)}),f.jsx("span",{className:"text-neutral-400 dark:text-neutral-500",children:"•"}),f.jsx("span",{className:"text-neutral-300 dark:text-neutral-600",children:t.versionName||t.version})]}),f.jsx("div",{className:"absolute -bottom-1 left-1/2 -translate-x-1/2 border-4 border-transparent border-t-neutral-900 dark:border-t-neutral-100"})]})})]})]})}const $Rt={free:{bg:"bg-neutral-100/80 dark:bg-neutral-800/80",text:"text-neutral-600 dark:text-neutral-400",border:"border-neutral-200/50 dark:border-neutral-700/50",icon:qre},standard:{bg:"bg-blue-50/80 dark:bg-blue-950/40",text:"text-blue-600 dark:text-blue-400",border:"border-blue-200/50 dark:border-blue-800/50",icon:zre},professional:{bg:"bg-purple-50/80 dark:bg-purple-950/40",text:"text-purple-600 dark:text-purple-400",border:"border-purple-200/50 dark:border-purple-800/50",icon:$re},ultra:{bg:"bg-amber-100/90 dark:bg-amber-950/40",text:"text-amber-600 dark:text-amber-400",border:"border-amber-300/70 dark:border-amber-800/50",icon:z1}};function jRt(t){return t<1024*1024?`${(t/1024).toFixed(0)} KB`:t<1024*1024*1024?`${(t/(1024*1024)).toFixed(0)} MB`:`${(t/(1024*1024*1024)).toFixed(1)} GB`}function q6r({visible:t,anchorRef:e,usage:n,daysLeft:r,roleName:i,isExpired:o,isUrgent:l,isWarning:u,respondingCount:d,chatLimit:p,hasOverQuota:m}){const g=e.current?.getBoundingClientRect(),h=t&&n&&g;return ji.createPortal(f.jsx(Qr,{children:h&&f.jsxs(Et.div,{initial:{opacity:0,y:8,scale:.95},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:4,scale:.95},transition:{duration:.2,ease:"easeOut"},style:{position:"fixed",bottom:window.innerHeight-g.top+8,right:window.innerWidth-g.right},className:"z-[60]",children:[f.jsx("div",{className:Yt("relative flex flex-col gap-1.5 min-w-[180px] rounded-2xl px-4 py-3 text-xs shadow-2xl","bg-white/90 text-neutral-900 backdrop-blur-lg","border border-neutral-200/60","dark:bg-white/5 dark:text-white","dark:border-white/[0.08]"),children:f.jsxs("div",{className:"flex flex-col gap-1.5",children:[r!==null&&i!=="free"&&f.jsxs("div",{className:"flex flex-col gap-1 pb-1.5 mb-0.5 border-b border-neutral-200/40 dark:border-neutral-700/40",children:[f.jsxs("div",{className:"flex justify-between gap-4",children:[f.jsx("span",{className:"text-neutral-500 dark:text-neutral-400",children:"Expires"}),f.jsx("span",{className:Yt(o&&"text-red-500 dark:text-red-400",l&&"text-red-500 dark:text-red-400",u&&"text-amber-500 dark:text-amber-400"),children:o?"Expired":r===0?"Today":`${r} day${r===1?"":"s"}`})]}),!o&&f.jsx("div",{className:"h-1 rounded-full bg-neutral-200 dark:bg-neutral-700/50 overflow-hidden",children:f.jsx("div",{className:Yt("h-full rounded-full transition-all",l&&"bg-red-500",u&&"bg-amber-500",!l&&!u&&"bg-emerald-500"),style:{width:`${Math.min(100,Math.max(2,r/30*100))}%`}})})]}),f.jsxs("div",{className:"flex justify-between gap-4",children:[f.jsx("span",{className:"text-neutral-500 dark:text-neutral-400",children:"Storage"}),f.jsxs("span",{className:"font-medium",children:[jRt(n.storage.used_bytes)," /"," ",jRt(n.storage.limit_bytes)]})]}),d>0&&f.jsxs("div",{className:"flex justify-between gap-4",children:[f.jsx("span",{className:"text-neutral-500 dark:text-neutral-400",children:"Chats"}),f.jsxs("span",{className:"font-medium",children:[d," / ",p||"∞"]})]}),n.sandboxes.limit>0&&f.jsxs("div",{className:"flex justify-between gap-4",children:[f.jsx("span",{className:"text-neutral-500 dark:text-neutral-400",children:"Sandboxes"}),f.jsxs("span",{className:"font-medium",children:[n.sandboxes.used," / ",n.sandboxes.limit]})]}),n.scheduled_tasks?.limit>0&&f.jsxs("div",{className:"flex justify-between gap-4",children:[f.jsx("span",{className:"text-neutral-500 dark:text-neutral-400",children:"Tasks"}),f.jsxs("span",{className:"font-medium",children:[n.scheduled_tasks.used," / ",n.scheduled_tasks.limit]})]}),f.jsxs("div",{className:"flex justify-between gap-4",children:[f.jsx("span",{className:"text-neutral-500 dark:text-neutral-400",children:"Files"}),f.jsxs("span",{className:"font-medium",children:[n.files.used," / ",n.files.limit]})]}),m&&f.jsx("div",{className:"text-red-500 dark:text-red-400 text-[10px] mt-0.5 font-semibold",children:"Quota exceeded"})]})}),f.jsx("div",{className:"absolute -bottom-[5px] right-4 h-2.5 w-2.5 rotate-45 bg-white/90 dark:bg-white/5 backdrop-blur-lg border-b border-r border-neutral-200/60 dark:border-white/[0.06]"})]})}),document.body)}function G6r(){const{t}=yn(),e=UO(),n=zO(),r=zn(B=>B.respondingChannelIds.size),[i,o]=T.useState(!1),[l,u]=T.useState(!1),d=T.useRef(null);if(!e||e.subQuery.isLoading)return null;const{subQuery:p,usageQuery:m,roleName:g}=e,h=t(`subscription.plan.${g}`),A=p.data?.subscription?.expires_at,b=p.data?.can_claim_credits??!1,y=$Rt[g]??$Rt.free,v=g==="free",_=!v&&A?new Date(A)<new Date:!1,w=!v&&A?Math.max(0,Math.ceil((new Date(A).getTime()-Date.now())/(1e3*60*60*24))):null,x=w!==null&&w<=3&&!_,k=w!==null&&w<=7&&!x&&!_,C=m.data,E=C?.chats.limit??0,S=C&&(E>0&&r>E||C.storage.usage_percentage>100),I=y.icon;return f.jsxs(f.Fragment,{children:[f.jsx("div",{className:"relative",ref:d,children:f.jsxs(Et.button,{whileHover:{scale:1.03},whileTap:{scale:.97},onClick:()=>o(!0),onMouseEnter:()=>u(!0),onMouseLeave:()=>u(!1),className:Yt("flex items-center gap-1.5 px-2.5 py-1 rounded-lg transition-colors border text-xs font-medium",y.bg,y.text,y.border,_&&"opacity-60",S&&"ring-1 ring-red-400/50"),children:[f.jsx(I,{className:"size-3.5"}),f.jsx("span",{children:h}),_&&f.jsx("span",{className:"text-[10px] text-red-500 dark:text-red-400 font-semibold",children:"expired"}),b&&!_&&f.jsxs("span",{className:"absolute -top-1 -right-1 flex h-2.5 w-2.5",children:[f.jsx("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full bg-red-400 opacity-75"}),f.jsx("span",{className:"relative inline-flex h-2.5 w-2.5 rounded-full bg-red-500"})]})]})}),f.jsx(q6r,{visible:l&&!!C,anchorRef:d,usage:C??null,daysLeft:w,roleName:g,isExpired:_,isUrgent:x,isWarning:k,respondingCount:r,chatLimit:E,hasOverQuota:!!S}),n&&f.jsx(qO,{isOpen:i,onClose:()=>o(!1)})]})}function H6r({activePanel:t,onPanelChange:e,className:n}){const{t:r}=yn(),i=fg(),o=dy(1/0),l=kDe(),[u,d]=T.useState(!1),p=zn(A=>A.dockMinimized),m=i.isAuthenticated||!!i.token,g=[{id:"chat",icon:UA,label:r("app.activityBar.chat"),panel:"chat"},{id:"teams",icon:nO,label:r("app.activityBar.teams"),panel:"teams"},{id:"knowledge",icon:tC,label:r("app.activityBar.knowledge"),panel:"knowledge"},{id:"skills",icon:YI,label:r("app.activityBar.skills","Skills"),panel:"skills"},{id:"memory",icon:sIe,label:r("app.activityBar.memory"),panel:"memory"},{id:"sandbox",icon:yh,label:r("app.activityBar.sandbox","Sandbox"),panel:"sandbox"},{id:"runner",icon:eO,label:r("app.activityBar.runner"),panel:"runner"},{id:"tasks",icon:J1,label:r("app.activityBar.tasks","Tasks"),panel:"tasks"},{id:"marketplace",icon:Xo,label:r("app.activityBar.community"),panel:"marketplace"}],h=T.useCallback(A=>{A.panel&&e(A.panel),A.onClick?.()},[e]);return p?null:f.jsxs(f.Fragment,{children:[f.jsx("div",{className:Yt("fixed bottom-0 left-0 z-50 pb-2",n),style:{paddingLeft:Dg,paddingRight:Dg},children:f.jsx("div",{className:Yt("h-14 rounded-2xl px-4","bg-white/80 dark:bg-neutral-900/60","backdrop-blur-2xl","border border-neutral-200/50 dark:border-neutral-700/50"),style:{width:`calc(100vw - ${Dg*2}px)`,boxShadow:"0 8px 32px rgba(0,0,0,.10), 0 2px 8px rgba(0,0,0,.06), inset 0 1px 0 rgba(255,255,255,.12)"},children:f.jsxs("div",{className:"flex h-full items-center",children:[f.jsx("div",{className:"shrink-0",children:f.jsx(j6r,{compact:!0})}),f.jsxs("div",{className:"flex items-center gap-3",children:[f.jsx("div",{className:"h-8 w-px bg-neutral-300/80 dark:bg-neutral-600/30 ml-3"}),f.jsx("div",{className:"flex items-end gap-1.5",onMouseMove:A=>o.set(A.pageX),onMouseLeave:()=>o.set(1/0),children:g.map(A=>f.jsx($6r,{mouseX:o,item:A,isActive:A.panel===t,onClick:()=>h(A)},A.id))})]}),f.jsx("div",{className:"flex-1"}),f.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[f.jsx(U6r,{}),f.jsx("div",{className:"h-6 w-px bg-neutral-300/80 dark:bg-neutral-600/30"}),l&&m&&f.jsx(Et.button,{whileHover:{scale:1.1},whileTap:{scale:.95},onClick:()=>d(!0),className:"relative flex items-center justify-center h-8 w-8 rounded-lg text-amber-600 transition-colors hover:text-amber-700 dark:text-amber-400 dark:hover:text-amber-300",title:r("app.toolbar.checkIn"),children:f.jsx(SR,{className:"h-5 w-5"})}),f.jsx("div",{className:"h-6 w-px bg-neutral-300/80 dark:bg-neutral-600/30"}),f.jsx(G6r,{}),f.jsx(QRt,{})]})]})})}),l&&f.jsx(iRe,{isOpen:u,onClose:()=>d(!1)})]})}const W6r=fh("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-[box-shadow,_color,_background-color,_border-color,_outline-color,_text-decoration-color,_fill,_stroke] disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",{variants:{variant:{default:"bg-primary text-primary-foreground shadow-xs hover:bg-primary/90",accent:"bg-accent text-accent-foreground shadow-xs hover:bg-accent/90",destructive:"bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",sm:"h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-md px-6 has-[>svg]:px-4",icon:"size-9","icon-sm":"size-8 rounded-md","icon-lg":"size-10 rounded-md"}},defaultVariants:{variant:"default",size:"default"}}),[Y6r,V6r]=QA("RippleButtonContext");function K6r({ref:t,onClick:e,hoverScale:n=1.05,tapScale:r=.95,asChild:i=!1,style:o,...l}){const[u,d]=J.useState([]),p=J.useRef(null);J.useImperativeHandle(t,()=>p.current);const m=J.useCallback(A=>{const b=p.current;if(!b)return;const y=b.getBoundingClientRect(),v=A.clientX-y.left,_=A.clientY-y.top,w={id:Date.now(),x:v,y:_};d(x=>[...x,w]),setTimeout(()=>{d(x=>x.filter(k=>k.id!==w.id))},600)},[]),g=J.useCallback(A=>{m(A),e&&e(A)},[m,e]),h=i?Z1:Et.button;return f.jsx(Y6r,{value:{ripples:u,setRipples:d},children:f.jsx(h,{ref:p,"data-slot":"ripple-button",onClick:g,whileTap:{scale:r},whileHover:{scale:n},style:{position:"relative",overflow:"hidden",...o},...l})})}function Z6r({color:t="var(--ripple-button-ripple-color)",scale:e=10,transition:n={duration:.6,ease:"easeOut"},asChild:r=!1,style:i,...o}){const{ripples:l}=V6r(),u=r?Z1:Et.span;return l.map(d=>f.jsx(u,{initial:{scale:0,opacity:.5},animate:{scale:e,opacity:0},transition:n,style:{position:"absolute",borderRadius:"50%",pointerEvents:"none",width:"20px",height:"20px",backgroundColor:t,top:d.y-10,left:d.x-10,...i},...o},d.id))}const X6r={default:"[--ripple-button-ripple-color:var(--primary-foreground)]",accent:"[--ripple-button-ripple-color:var(--accent-foreground)]",destructive:"[--ripple-button-ripple-color:var(--destructive-foreground)]",outline:"[--ripple-button-ripple-color:var(--foreground)]",secondary:"[--ripple-button-ripple-color:var(--secondary-foreground)]",ghost:"[--ripple-button-ripple-color:var(--foreground)]",link:"[--ripple-button-ripple-color:var(--primary-foreground)]"};function J6r({className:t,variant:e,size:n,...r}){return f.jsx(K6r,{className:Yt(W6r({variant:e,size:n,className:t}),X6r[e]),...r})}function e9r(t){return f.jsx(Z6r,{...t})}const zRt=["adventurer","avataaars","bottts","fun-emoji","lorelei","micah","miniavs","notionists","open-peeps","personas","pixel-art","shapes","thumbs"],_G=(t,e,n)=>n?`${n}/xyzen/api/v1/avatar/${t}/svg?seed=${encodeURIComponent(e)}`:`https://api.dicebear.com/9.x/${t}/svg?seed=${e}`,t9r=t=>{const e=[];return zRt.forEach(n=>{for(let r=0;r<6;r++){const i=`${n}_${r}_preset`;e.push({url:_G(n,i,t),seed:i,style:n})}}),e},URt=t=>{if(!t)return"";try{const e=new URL(t).searchParams.get("seed");return e?decodeURIComponent(e):""}catch{const e=t.match(/[?&]seed=([^&]*)/);return e?decodeURIComponent(e[1]):""}};function VRe({currentAvatar:t,onSelect:e,backendUrl:n}){const{t:r}=yn(),[i,o]=T.useState("avataaars"),[l,u]=T.useState(()=>URt(t)),[d,p]=T.useState(!1);T.useEffect(()=>{const _=URt(t);u(_)},[t]);const[m,g]=T.useState(!1),A=T.useMemo(()=>t9r(n),[n]).filter(_=>_.style===i),b=T.useCallback(async()=>{g(!0),await new Promise(x=>setTimeout(x,300));const _=Math.random().toString(36).slice(2,10),w=_G(i,_,n);e(w),g(!1)},[i,e,n]),y=T.useCallback(async()=>{if(!l.trim())return;g(!0),await new Promise(w=>setTimeout(w,200));const _=_G(i,l.trim(),n);e(_),g(!1)},[i,l,e,n]),v=T.useCallback(async _=>{g(!0),await new Promise(w=>setTimeout(w,150)),e(_),g(!1)},[e]);return f.jsxs("div",{className:"flex gap-5",children:[f.jsx("div",{className:"flex shrink-0 items-start pt-6 px-2",children:f.jsxs(Et.div,{className:"group relative",whileHover:{scale:1.05},transition:{type:"spring",stiffness:300},children:[f.jsx("div",{className:"absolute -inset-1 rounded-full bg-linear-to-tr from-indigo-500 via-purple-500 to-pink-500 opacity-40 blur-md transition-opacity duration-500 group-hover:opacity-70"}),f.jsx(Qr,{children:m&&f.jsx(Et.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"absolute inset-0 z-10 flex items-center justify-center rounded-full bg-white/50 dark:bg-black/50",children:f.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-2 border-indigo-500 border-t-transparent"})})}),f.jsx("img",{src:t||_G("avataaars","default",n),alt:"Current avatar",className:"relative h-20 w-20 rounded-full border-[3px] border-white bg-white shadow-xl dark:border-neutral-700 dark:bg-neutral-800"}),t&&!m&&f.jsx(Et.div,{initial:{scale:0},animate:{scale:1},className:"absolute -bottom-0.5 -right-0.5 flex h-6 w-6 items-center justify-center rounded-full border-2 border-white bg-green-500 shadow dark:border-neutral-800",children:f.jsx(Zs,{className:"h-3 w-3 text-white"})})]})}),f.jsxs("div",{className:"min-w-0 flex-1 space-y-3",children:[f.jsxs("div",{className:"space-y-1.5",children:[f.jsx("label",{className:"pl-0.5 text-[13px] font-medium text-neutral-600 dark:text-neutral-400",children:r("agents.sessionSettings.avatar.style")}),f.jsx("div",{className:"custom-scrollbar -mx-1 flex max-h-16 flex-wrap gap-1.5 overflow-y-auto p-1",children:zRt.map(_=>f.jsx(Oa,{type:"button",variant:i===_?"default":"outline",size:"sm",className:Yt("h-7 rounded-full px-2.5 text-xs transition-all duration-300",i===_?"border-transparent bg-indigo-600 text-white shadow-md shadow-indigo-500/25 hover:bg-indigo-700":"border-neutral-200 text-neutral-600 hover:bg-neutral-100 dark:border-neutral-700 dark:text-neutral-400 dark:hover:bg-neutral-800"),onClick:()=>o(_),children:_},_))})]}),f.jsx("div",{className:"grid grid-cols-8 gap-2",children:A.map((_,w)=>f.jsx(Et.button,{type:"button",whileHover:{scale:1.12},whileTap:{scale:.95},onClick:()=>v(_.url),className:Yt("aspect-square h-16 rounded-full overflow-hidden border-2 transition-colors duration-200 shadow-sm hover:shadow-lg",t===_.url?"border-indigo-500 ring-2 ring-indigo-200 dark:ring-indigo-900 shadow-indigo-500/30":"border-transparent hover:border-neutral-300 dark:hover:border-neutral-600 bg-neutral-50 dark:bg-neutral-800"),children:f.jsx("img",{src:_.url,alt:`Avatar option ${w+1}`,className:"h-full w-full object-cover"})},w))}),f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsxs(J6r,{type:"button",variant:"outline",onClick:b,disabled:m,className:"h-8 shrink-0 gap-1.5 px-3 text-xs font-medium",children:[f.jsx(Xo,{className:"h-3.5 w-3.5 text-indigo-500"}),f.jsx("span",{className:"truncate",children:r(m?"agents.sessionSettings.avatar.loading":"agents.sessionSettings.avatar.random")}),f.jsx(e9r,{})]}),f.jsxs("button",{type:"button",onClick:()=>p(_=>!_),className:"flex items-center gap-1 rounded px-1.5 py-1 text-xs text-neutral-400 transition-colors hover:text-neutral-600 dark:hover:text-neutral-300",children:[r("agents.sessionSettings.avatar.advanced"),f.jsx(h_,{className:Yt("h-3 w-3 transition-transform duration-200",d&&"rotate-180")})]})]}),f.jsx(Qr,{children:d&&f.jsx(Et.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.2},className:"overflow-hidden",children:f.jsxs("div",{className:"flex gap-2 p-1",children:[f.jsx("div",{className:"flex-1",children:f.jsx(Ri,{type:"text",placeholder:r("agents.sessionSettings.avatar.seedPlaceholder"),value:l,onChange:_=>u(_.target.value),onKeyDown:_=>_.key==="Enter"&&y(),className:"text-xs",wrapperClassName:"h-8"})}),f.jsx(Oa,{type:"button",size:"sm",onClick:y,disabled:!l.trim()||m,className:"h-8 px-3 text-xs transition-all hover:shadow-md",children:r("agents.sessionSettings.avatar.apply")})]})})})]})]})}function qRt({isOpen:t,onClose:e,onCreated:n,parentId:r}){const{t:i}=yn(),{createAgent:o,isCreatingAgent:l,backendUrl:u,agents:d}=zn(Vs(x=>({createAgent:x.createAgent,isCreatingAgent:x.isCreatingAgent,backendUrl:x.backendUrl,agents:x.agents}))),[p,m]=T.useState({name:"",description:"",prompt:""}),[g,h]=T.useState(""),[A,b]=T.useState(!1);T.useEffect(()=>{if(t&&!g){const x=Math.random().toString(36).slice(2,10);h(_G("avataaars",x,u))}},[t,g,u]);const y=x=>{const{name:k,value:C}=x.target;m(E=>({...E,[k]:C}))},v=async x=>{if(x.preventDefault(),!A){if(!p.name){alert(i("agents.errors.nameRequired"));return}if(d.some(k=>k.name===p.name)){alert(i("agents.errors.nameDuplicate"));return}b(!0);try{const k=await o({...p,avatar:g,parent_id:r??void 0,mcp_server_ids:[],user_id:"temp",mcp_servers:[],created_at:new Date().toISOString(),updated_at:new Date().toISOString()});w(),k&&n&&n(k)}catch(k){console.error("Failed to create agent:",k),alert(i("agents.errors.createFailed"))}finally{b(!1)}}},_=A||l||!p.name,w=()=>{m({name:"",description:"",prompt:""}),h(""),e()};return f.jsx(El,{isOpen:t,onClose:w,size:"md",children:f.jsxs("div",{className:"flex h-full flex-col overflow-hidden",children:[f.jsx("div",{className:"shrink-0 px-5 pt-5 pb-1 md:pt-2",children:f.jsx("h2",{className:"text-lg font-bold text-neutral-900 dark:text-neutral-100",children:i("agents.createTitle")})}),f.jsxs("form",{onSubmit:v,className:"flex-1 overflow-y-auto custom-scrollbar px-5 pb-5 space-y-5",children:[f.jsx(VRe,{currentAvatar:g,onSelect:h,backendUrl:u}),f.jsx("div",{className:"border-t border-neutral-200 dark:border-neutral-700"}),f.jsx(Za,{label:i("agents.fields.name.required"),required:!0,children:f.jsx(Ri,{name:"name",value:p.name,onChange:y,placeholder:i("agents.fields.name.placeholder"),required:!0})}),f.jsx(Za,{label:i("agents.fields.description.label"),children:f.jsx(Ri,{name:"description",value:p.description,onChange:y,placeholder:i("agents.fields.description.placeholder")})}),f.jsxs("div",{className:"flex justify-end gap-3 pt-4 border-t border-neutral-200 dark:border-neutral-700",children:[f.jsx(Hc,{type:"button",onClick:w,className:"inline-flex items-center gap-2 rounded-md bg-neutral-100 py-2 px-4 text-sm font-medium text-neutral-700 hover:bg-neutral-200 dark:bg-neutral-800 dark:text-neutral-200 dark:hover:bg-neutral-700 transition-colors",children:i("agents.actions.cancel")}),f.jsx(Hc,{type:"submit",disabled:_,className:Yt("inline-flex items-center gap-2 rounded-md py-2 px-4 text-sm font-medium transition-colors",_?"bg-neutral-400 text-white cursor-not-allowed":"bg-indigo-600 text-white hover:bg-indigo-500"),children:i(A||l?"agents.actions.creating":"agents.actions.create")})]})]})]})})}class n9r{listSecrets(){return en.get("/xyzen/api/v1/payment-secrets")}createSecret(e){return en.post("/xyzen/api/v1/payment-secrets",e)}updateSecret(e,n){return en.put(`/xyzen/api/v1/payment-secrets/${e}`,n)}deleteSecret(e){return en.delete(`/xyzen/api/v1/payment-secrets/${e}`)}getBinding(e){return en.get(`/xyzen/api/v1/agents/${e}/payment-binding`)}upsertBinding(e,n){return en.put(`/xyzen/api/v1/agents/${e}/payment-binding`,n)}deleteBinding(e){return en.delete(`/xyzen/api/v1/agents/${e}/payment-binding`)}}const hk=new n9r;class r9r{async createKnowledgeSet(e){return en.post("/xyzen/api/v1/knowledge-sets/",e)}async listKnowledgeSets(e=!1){return en.get("/xyzen/api/v1/knowledge-sets/",{params:{include_deleted:e||void 0}})}async getKnowledgeSet(e){return en.get(`/xyzen/api/v1/knowledge-sets/${e}`)}async updateKnowledgeSet(e,n){return en.patch(`/xyzen/api/v1/knowledge-sets/${e}`,n)}async deleteKnowledgeSet(e,n=!1){return en.delete(`/xyzen/api/v1/knowledge-sets/${e}`,void 0,{params:{hard_delete:n}})}async linkFileToKnowledgeSet(e,n){return en.post(`/xyzen/api/v1/knowledge-sets/${e}/files/${n}`)}async unlinkFileFromKnowledgeSet(e,n){return en.delete(`/xyzen/api/v1/knowledge-sets/${e}/files/${n}`)}async getFilesInKnowledgeSet(e){return en.get(`/xyzen/api/v1/knowledge-sets/${e}/files`)}async bulkLinkFilesToKnowledgeSet(e,n){return en.post(`/xyzen/api/v1/knowledge-sets/${e}/files/bulk-link`,{file_ids:n})}async bulkUnlinkFilesFromKnowledgeSet(e,n){return en.post(`/xyzen/api/v1/knowledge-sets/${e}/files/bulk-unlink`,{file_ids:n})}}const Ph=new r9r;class a9r{async listSkills(){return en.get("/xyzen/api/v1/skills/")}async listAgentSkills(e){return en.get(`/xyzen/api/v1/agents/${e}/skills`)}async attachSkill(e,n){const r={skill_id:n};return en.post(`/xyzen/api/v1/agents/${e}/skills`,r)}async detachSkill(e,n){return en.delete(`/xyzen/api/v1/agents/${e}/skills/${n}`)}async parseSkill(e){return en.post("/xyzen/api/v1/skills/parse",e)}async createSkill(e){return en.post("/xyzen/api/v1/skills/",e)}async listSkillResources(e){return en.get(`/xyzen/api/v1/skills/${e}/resources`)}async updateSkill(e,n){return en.patch(`/xyzen/api/v1/skills/${e}`,n)}async deleteSkill(e){return en.delete(`/xyzen/api/v1/skills/${e}`)}}const Oh=new a9r,GRt=["official","builtin:"];function HRt({open:t,onOpenChange:e,agentId:n,graphConfig:r,mcpServers:i=[],knowledgeSetId:o,tags:l,isPublished:u=!1,readme:d,onPublishSuccess:p}){const{t:m}=yn(),[g,h]=T.useState(""),[A,b]=T.useState(d||""),[y,v]=T.useState(!0),[_,w]=T.useState("editable"),[x,k]=T.useState(l??[]),[C,E]=T.useState(""),[S,I]=T.useState([]),[B,N]=T.useState(o??null),[L,M]=T.useState([]),[R,D]=T.useState(new Set),[P,O]=T.useState(new Set),[F,$]=T.useState(""),[j,Q]=T.useState(null),z=$sr(),U=V2e(t),H=m("marketplace.realPerson.publishAgent");T.useEffect(()=>{if(t){const X=(l??[]).filter(ne=>!GRt.some(ce=>ne===ce||ne.startsWith(ce)));k(X)}},[t,l]);const te=T.useCallback(X=>{const ne=X.trim().toLowerCase();if(!ne||x.includes(ne)){E("");return}if(GRt.some(ce=>ne===ce||ne.startsWith(ce))){E("");return}k(ce=>[...ce,ne]),E("")},[x]),V=T.useCallback(X=>{k(ne=>ne.filter(ce=>ce!==X))},[]),ae=T.useCallback(X=>{X.key==="Enter"||X.key===","?(X.preventDefault(),te(C)):X.key==="Backspace"&&!C&&x.length>0&&k(ne=>ne.slice(0,-1))},[te,C,x.length]);T.useEffect(()=>{if(!t)return;let X=!1;$("");async function ne(){try{const[ce,oe,ue,me]=await Promise.all([Ph.listKnowledgeSets(),Oh.listAgentSkills(n),Oh.listSkills(),hk.getBinding(n)]);if(X)return;I(ce),M(ue),Q(me);const fe=new Set(oe.map(Be=>Be.id));D(fe),O(new Set(fe)),N(o??null)}catch(ce){console.error("Failed to fetch publish modal data:",ce)}}return ne(),()=>{X=!0}},[t,n,o]);const ie=async(X=!1)=>{if(g.trim()&&!(!X&&!await U.ensureVerified()))try{const ne=await z.mutateAsync({agent_id:n,commit_message:g.trim(),is_published:y,readme:A.trim()||null,fork_mode:_,knowledge_set_id:B||null,skill_ids:P.size>0?Array.from(P):void 0,tags:x});p&&p(ne.marketplace_id),h(""),e(!1)}catch(ne){if(U.handleRequiredError(ne))return;console.error("Failed to publish agent:",ne)}},Z=X=>{O(ne=>{const ce=new Set(ne);return ce.has(X)?ce.delete(X):ce.add(X),ce})},W=T.useMemo(()=>{const X=F.trim().toLowerCase();if(!X)return L;const ne=ue=>ue.name.toLowerCase().includes(X)||ue.description?.toLowerCase().includes(X)||ue.tags?.some(me=>me.toLowerCase().includes(X)),ce=[],oe=[];for(const ue of L){if(P.has(ue.id)){ce.push(ue);continue}ne(ue)&&oe.push(ue)}return[...ce,...oe]},[L,P,F]),q=!!r&&Object.keys(r).length>0,Y=g.trim().length>0&&q;return f.jsxs(f.Fragment,{children:[f.jsxs(El,{isOpen:t,onClose:()=>e(!1),size:"xl",children:[f.jsxs("div",{className:"shrink-0 border-b border-neutral-200/60 px-5 pb-3 pt-5 dark:border-neutral-800/60",children:[f.jsx("h2",{className:"text-lg font-semibold text-neutral-900 dark:text-white",children:m(u?"marketplace.publish.titleUpdate":"marketplace.publish.title")}),f.jsx("p",{className:"mt-1 text-[13px] text-neutral-500 dark:text-neutral-400",children:m(u?"marketplace.publish.descriptionUpdate":"marketplace.publish.description")})]}),f.jsx("div",{className:"custom-scrollbar flex-1 overflow-y-auto",children:f.jsxs("div",{className:"space-y-6 px-5 py-5",children:[f.jsx(cIe,{status:U.statusQuery.data,isLoading:U.statusQuery.isLoading,actionLabel:H,onVerify:()=>U.setVerificationOpen(!0)}),(()=>{const X=f.jsxs("div",{className:"flex gap-2.5 rounded-lg bg-neutral-100/60 px-4 py-3 dark:bg-white/[0.04]",children:[f.jsx(mu,{className:"h-4 w-4 shrink-0 text-neutral-400"}),f.jsxs("p",{className:"text-[13px] text-neutral-600 dark:text-neutral-400",children:[f.jsx("strong",{children:m("marketplace.publish.info.title")})," ",m("marketplace.publish.info.content")," ",f.jsx("strong",{children:m("marketplace.publish.info.note")})," ",m("marketplace.publish.info.noteContent")]})]}),ne=f.jsx(Za,{label:m("marketplace.publish.commitMessage.label"),required:!0,hint:m("marketplace.publish.commitMessage.charCount",{count:g.length}),children:f.jsx(qp,{id:"commit-message",placeholder:m("marketplace.publish.commitMessage.placeholder"),value:g,onChange:et=>h(et.target.value),rows:3})}),ce=f.jsx(Za,{label:m("marketplace.publish.readme.label"),hint:m("marketplace.publish.readme.hint"),children:f.jsx(qp,{id:"readme-editor",placeholder:m("marketplace.publish.readme.placeholder"),value:A,onChange:et=>b(et.target.value),rows:6,className:"font-mono"})}),oe=f.jsx(Za,{label:m("marketplace.publish.tags.label"),hint:m("marketplace.publish.tags.hint"),children:f.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 rounded-sm border border-neutral-200 bg-white px-2.5 py-2 transition-colors focus-within:border-indigo-400 focus-within:ring-2 focus-within:ring-indigo-500/20 dark:border-neutral-700 dark:bg-neutral-800",children:[x.map(et=>f.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full bg-indigo-50/80 px-2.5 py-0.5 text-xs font-medium text-indigo-700 dark:bg-indigo-900/30 dark:text-indigo-300",children:[et,f.jsx("button",{type:"button",onClick:()=>V(et),className:"ml-0.5 rounded-full p-0.5 transition-colors hover:bg-indigo-200/60 dark:hover:bg-indigo-800/40",children:f.jsx(ul,{className:"h-3 w-3"})})]},et)),f.jsx("input",{type:"text",value:C,onChange:et=>E(et.target.value),onKeyDown:ae,onBlur:()=>C.trim()&&te(C),placeholder:x.length===0?m("marketplace.publish.tags.placeholder"):"",className:"min-w-[80px] flex-1 border-none bg-transparent py-0.5 text-[13px] text-neutral-700 outline-none placeholder:text-neutral-400 dark:text-neutral-300 dark:placeholder:text-neutral-500"})]})}),ue=f.jsx(Za,{label:m("marketplace.publish.knowledgeBase.label"),hint:m("marketplace.publish.knowledgeBase.hint"),children:f.jsxs("select",{value:B??"",onChange:et=>N(et.target.value||null),className:"w-full rounded-sm border border-neutral-200 bg-white px-3 py-2 text-[13px] text-neutral-700 transition-colors focus:border-indigo-400 focus:outline-none focus:ring-2 focus:ring-indigo-500/20 dark:border-neutral-700 dark:bg-neutral-800 dark:text-neutral-300",children:[f.jsx("option",{value:"",children:m("marketplace.publish.knowledgeBase.none")}),S.map(et=>f.jsxs("option",{value:et.id,children:[et.name," (",m("marketplace.publish.knowledgeBase.fileCount",{count:et.file_count}),")"]},et.id))]})}),me=f.jsx(Za,{label:m("marketplace.publish.skills.label"),hint:m("marketplace.publish.skills.hint"),children:L.length===0?f.jsx("p",{className:"text-xs text-neutral-400 dark:text-neutral-500",children:m("marketplace.publish.skills.empty")}):f.jsxs("div",{className:"space-y-1.5",children:[f.jsx(Ri,{value:F,onChange:et=>$(et.target.value),placeholder:m("marketplace.publish.skills.searchPlaceholder")}),W.length===0?f.jsx("p",{className:"rounded-lg bg-neutral-100/60 px-3 py-2.5 text-xs text-neutral-500 dark:bg-white/[0.04] dark:text-neutral-400",children:m("marketplace.publish.skills.noResults")}):W.map(et=>f.jsxs("label",{className:"flex cursor-pointer items-center gap-3 rounded-lg bg-neutral-100/60 px-3 py-2.5 transition-colors hover:bg-neutral-100 dark:bg-white/[0.04] dark:hover:bg-white/[0.06]",children:[f.jsx("input",{type:"checkbox",checked:P.has(et.id),onChange:()=>Z(et.id),className:"h-4 w-4 rounded border-neutral-300 text-indigo-500 focus:ring-indigo-500/40 dark:border-neutral-600"}),f.jsxs("div",{className:"min-w-0 flex-1",children:[f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("span",{className:"text-[13px] font-medium text-neutral-900 dark:text-neutral-100",children:et.name}),et.scope==="builtin"&&f.jsx("span",{className:"rounded bg-indigo-50/80 px-1.5 py-0.5 text-[10px] font-medium text-indigo-600 dark:bg-indigo-900/30 dark:text-indigo-400",children:m("marketplace.publish.skills.builtin")}),R.has(et.id)&&f.jsx("span",{className:"rounded bg-green-50/80 px-1.5 py-0.5 text-[10px] font-medium text-green-600 dark:bg-green-900/30 dark:text-green-400",children:m("marketplace.publish.skills.attached")})]}),et.description&&f.jsx("p",{className:"mt-0.5 line-clamp-1 text-xs text-neutral-500 dark:text-neutral-400",children:et.description})]})]},et.id))]})}),fe=f.jsx(Za,{label:m("marketplace.publish.mcpServers.label"),hint:m("marketplace.publish.mcpServers.hint"),children:i.length===0?f.jsx("p",{className:"text-xs text-neutral-400 dark:text-neutral-500",children:m("marketplace.publish.mcpServers.empty")}):f.jsx("div",{className:"space-y-1.5",children:i.map(et=>f.jsxs("div",{className:"rounded-lg bg-neutral-100/60 px-3 py-2.5 dark:bg-white/[0.04]",children:[f.jsx("div",{className:"text-[13px] font-medium text-neutral-900 dark:text-neutral-100",children:et.name}),et.description&&f.jsx("p",{className:"mt-0.5 text-xs text-neutral-500 dark:text-neutral-400 line-clamp-1",children:et.description})]},et.id))})}),Be=j?f.jsx(Za,{label:m("agents.payment.publishSummaryTitle"),hint:m("agents.payment.publishSummaryHint"),children:f.jsxs("div",{className:"rounded-lg bg-neutral-100/60 px-4 py-3 dark:bg-white/[0.04]",children:[f.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[f.jsx("span",{className:"text-[13px] font-medium text-neutral-900 dark:text-neutral-100",children:j.provider.toUpperCase()}),f.jsx("span",{className:"rounded-full bg-green-50/80 px-2 py-0.5 text-[10px] font-medium text-green-700 dark:bg-green-900/30 dark:text-green-400",children:j.enabled?m("agents.payment.enabled"):m("agents.payment.disabled")}),f.jsx("span",{className:"rounded-full bg-indigo-50/80 px-2 py-0.5 text-[10px] font-medium text-indigo-700 dark:bg-indigo-900/30 dark:text-indigo-400",children:j.required?m("agents.payment.required"):m("agents.payment.optional")}),f.jsx("span",{className:"rounded-full bg-neutral-200/80 px-2 py-0.5 text-[10px] font-medium text-neutral-700 dark:bg-white/[0.08] dark:text-neutral-300",children:j.status})]}),f.jsx("p",{className:"mt-2 text-xs text-neutral-500 dark:text-neutral-400",children:j.secret?.app_id_masked??m("agents.payment.unconfigured")}),f.jsx("p",{className:"mt-2 text-xs text-neutral-500 dark:text-neutral-400",children:j.tool_names.join(", ")})]})}):null,He=f.jsxs(ld,{className:"flex items-center justify-between rounded-lg bg-neutral-100/60 px-4 py-3.5 dark:bg-white/[0.04]",children:[f.jsxs("div",{className:"space-y-0.5 pr-4",children:[f.jsx(Wc,{htmlFor:"publish-toggle",className:"cursor-pointer text-[13px] font-medium text-neutral-900 dark:text-neutral-100",children:m("marketplace.publish.publishImmediately.label")}),f.jsx("p",{className:"text-xs text-neutral-500 dark:text-neutral-400",children:m("marketplace.publish.publishImmediately.description")})]}),f.jsx(R2e,{id:"publish-toggle",checked:y,onChange:v,className:`${y?"bg-indigo-500":"bg-neutral-300 dark:bg-neutral-600"} relative inline-flex h-[26px] w-[46px] shrink-0 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-indigo-500/40 focus:ring-offset-2`,children:f.jsx("span",{className:`${y?"translate-x-[22px]":"translate-x-[3px]"} inline-block h-5 w-5 transform rounded-full bg-white shadow-sm transition-transform`})})]}),Le=f.jsx(Za,{label:m("marketplace.publish.forkMode.label"),hint:m("marketplace.publish.forkMode.help"),children:f.jsxs("div",{className:"grid grid-cols-2 gap-2.5",children:[f.jsxs("button",{type:"button",onClick:()=>w("editable"),className:`flex items-center gap-3 rounded-lg p-3 text-left transition-colors ${_==="editable"?"bg-green-50/80 ring-1 ring-green-500/30 dark:bg-green-900/15 dark:ring-green-500/20":"bg-neutral-100/60 hover:bg-neutral-100 dark:bg-white/[0.04] dark:hover:bg-white/[0.06]"}`,children:[f.jsx("div",{className:`flex h-8 w-8 shrink-0 items-center justify-center rounded-lg ${_==="editable"?"bg-green-500 text-white":"bg-neutral-200/70 text-neutral-500 dark:bg-neutral-700/70 dark:text-neutral-400"}`,children:f.jsx(oIe,{className:"h-4 w-4"})}),f.jsxs("div",{className:"flex-1 min-w-0",children:[f.jsx("div",{className:"text-[13px] font-medium text-neutral-900 dark:text-neutral-100",children:m("marketplace.forkMode.editable")}),f.jsx("div",{className:"text-xs text-neutral-500 dark:text-neutral-400",children:m("marketplace.forkMode.editableDescription")}),f.jsx("div",{className:"mt-1 text-[10px] font-medium text-green-600 dark:text-green-400",children:m("marketplace.forkMode.rewardRate",{rate:"30%"})})]})]}),f.jsxs("button",{type:"button",onClick:()=>w("locked"),className:`flex items-center gap-3 rounded-lg p-3 text-left transition-colors ${_==="locked"?"bg-amber-50/80 ring-1 ring-amber-500/30 dark:bg-amber-900/15 dark:ring-amber-500/20":"bg-neutral-100/60 hover:bg-neutral-100 dark:bg-white/[0.04] dark:hover:bg-white/[0.06]"}`,children:[f.jsx("div",{className:`flex h-8 w-8 shrink-0 items-center justify-center rounded-lg ${_==="locked"?"bg-amber-500 text-white":"bg-neutral-200/70 text-neutral-500 dark:bg-neutral-700/70 dark:text-neutral-400"}`,children:f.jsx(Xb,{className:"h-4 w-4"})}),f.jsxs("div",{className:"flex-1 min-w-0",children:[f.jsx("div",{className:"text-[13px] font-medium text-neutral-900 dark:text-neutral-100",children:m("marketplace.forkMode.locked")}),f.jsx("div",{className:"text-xs text-neutral-500 dark:text-neutral-400",children:m("marketplace.forkMode.lockedDescription")}),f.jsx("div",{className:"mt-1 text-[10px] font-medium text-amber-600 dark:text-amber-400",children:m("marketplace.forkMode.rewardRate",{rate:"3%"})})]})]})]})});return f.jsxs("div",{className:"space-y-6",children:[!q&&f.jsxs("div",{className:"flex gap-2.5 rounded-lg bg-red-50/80 px-4 py-3 dark:bg-red-950/30",children:[f.jsx(Qp,{className:"h-4 w-4 shrink-0 text-red-500 dark:text-red-400"}),f.jsx("p",{className:"text-[13px] text-red-700 dark:text-red-400",children:m("marketplace.publish.validation.noConfig")})]}),f.jsxs("div",{className:"space-y-6 md:hidden",children:[X,ne,ce,oe,ue,me,fe,Be,He,$A("developerReward")&&Le]}),f.jsxs("div",{className:"hidden md:grid md:grid-cols-[55%_45%]",children:[f.jsxs("div",{className:"space-y-6 pr-5 border-r border-neutral-200/60 dark:border-neutral-800/60",children:[X,ne,ce,oe]}),f.jsxs("div",{className:"space-y-6 pl-5",children:[ue,me,fe,Be,He,$A("developerReward")&&Le]})]}),z.isSuccess&&f.jsxs("div",{className:"flex gap-2.5 rounded-lg bg-green-50/80 px-4 py-3 dark:bg-green-950/30",children:[f.jsx(Sl,{className:"h-4 w-4 shrink-0 text-green-500"}),f.jsx("p",{className:"text-[13px] text-green-700 dark:text-green-400",children:m(u?"marketplace.publish.success.updated":"marketplace.publish.success.published")})]}),z.isError&&f.jsxs("div",{className:"flex gap-2.5 rounded-lg bg-red-50/80 px-4 py-3 dark:bg-red-950/30",children:[f.jsx(Qp,{className:"h-4 w-4 shrink-0 text-red-500 dark:text-red-400"}),f.jsx("p",{className:"text-[13px] text-red-700 dark:text-red-400",children:z.error instanceof Error?z.error.message:m("marketplace.publish.error.default")})]})]})})()]})}),f.jsx("div",{className:"shrink-0 border-t border-neutral-200/60 px-5 py-4 dark:border-neutral-800/60",children:f.jsxs("div",{className:"flex justify-end gap-2.5",children:[f.jsx(Hc,{onClick:()=>{h(""),e(!1)},disabled:z.isPending,className:"rounded-lg bg-neutral-100/80 px-4 py-2 text-[13px] font-medium text-neutral-700 transition-colors hover:bg-neutral-200/80 disabled:opacity-50 dark:bg-white/[0.06] dark:text-neutral-300 dark:hover:bg-white/[0.1]",children:m("marketplace.publish.actions.cancel")}),f.jsx(Hc,{onClick:()=>{ie()},disabled:!Y||z.isPending,className:"rounded-lg bg-indigo-500 px-4 py-2 text-[13px] font-semibold text-white transition-colors hover:bg-indigo-600 disabled:opacity-50 dark:bg-indigo-500 dark:hover:bg-indigo-400",children:z.isPending?m("marketplace.publish.actions.publishing"):m(u?"marketplace.publish.actions.update":y?"marketplace.publish.actions.publish":"marketplace.publish.actions.saveAsDraft")})]})})]}),f.jsx(die,{open:U.verificationOpen,onOpenChange:U.setVerificationOpen,actionLabel:H,onStatusChange:()=>{U.statusQuery.refetch()},onVerified:()=>{U.statusQuery.refetch(),ie(!0)}})]})}const i9r=["create-alipay-payment-agent","query-alipay-payment","refund-alipay-payment","query-alipay-refund"],s9r=T.lazy(()=>Promise.resolve().then(()=>MSa)),o9r=[{id:"profile",icon:lIe,labelKey:"profile"},{id:"automation",icon:Xo,labelKey:"automation"},{id:"size",icon:EU,labelKey:"size"},{id:"workflow",icon:bh,labelKey:"workflow"},{id:"danger",icon:Qp,labelKey:"danger",color:"text-red-500"}];function l9r({currentW:t=1,currentH:e=1,onResize:n}){const[r,i]=T.useState(null);return f.jsxs("div",{className:"flex flex-col gap-6",children:[f.jsx("div",{className:"flex justify-center",children:f.jsx("div",{className:"grid grid-cols-3 gap-3",onMouseLeave:()=>i(null),children:Array.from({length:9}).map((o,l)=>{const u=l%3+1,d=Math.floor(l/3)+1,p=r&&u<=r.w&&d<=r.h,m=!r&&u<=t&&d<=e;return f.jsx(Et.div,{whileHover:{scale:1.05},whileTap:{scale:.95},className:Yt("h-14 w-14 cursor-pointer rounded-sm border-2 transition-colors duration-200 shadow-sm",p||m?"border-indigo-500 bg-indigo-500/20 dark:border-indigo-400 dark:bg-indigo-400/20 shadow-indigo-500/30 shadow-lg":"border-neutral-200 bg-white hover:border-neutral-300 dark:border-neutral-700 dark:bg-neutral-800 dark:hover:border-neutral-600"),onMouseEnter:()=>i({w:u,h:d}),onClick:g=>{g.preventDefault(),g.stopPropagation(),n(u,d)}},l)})})}),f.jsx("div",{className:"text-center",children:f.jsx(Et.span,{initial:{opacity:0,y:-10},animate:{opacity:1,y:0},className:"inline-block px-5 py-2 rounded-full bg-neutral-100 dark:bg-neutral-800 text-base font-bold text-neutral-700 dark:text-neutral-200 shadow-sm border border-neutral-200 dark:border-neutral-700",children:r?`${r.w} × ${r.h}`:`${t} × ${e}`},r?`${r.w}x${r.h}`:`${t}x${e}`)})]})}function c9r({agent:t,currentAvatar:e,onAvatarChange:n,onClose:r}){const{t:i}=yn(),o=zn(L=>L.backendUrl),{updateAgent:l,agents:u,openSettingsModal:d}=zn(Vs(L=>({updateAgent:L.updateAgent,agents:L.agents,openSettingsModal:L.openSettingsModal}))),p=t.original_source_id!=null,[m,g]=T.useState(t),[h,A]=T.useState(!1),[b,y]=T.useState(null),[v,_]=T.useState([]),[w,x]=T.useState(""),[k,C]=T.useState(!1),[E,S]=T.useState(!1);T.useEffect(()=>{g(t)},[t]),T.useEffect(()=>{let L=!1;async function M(){try{const[R,D]=await Promise.all([hk.getBinding(t.id),hk.listSecrets()]);if(L)return;y(R),_(D),x(R?.secret?.id??""),C(R?.enabled??!1),S(R?.required??!1)}catch(R){console.error("Failed to load agent payment binding:",R)}}return M(),()=>{L=!0}},[t.id]);const I=L=>{const{name:M,value:R}=L.target;g({...m,[M]:R})},B=async L=>{if(L.preventDefault(),!h){if(m.name!==t.name&&u.some(M=>M.id!==m.id&&M.name===m.name)){alert(i("agents.errors.nameDuplicate"));return}A(!0);try{if(await l({id:m.id,name:m.name,description:m.description}),!p&&b!=null&&!k&&!w)await hk.deleteBinding(m.id),y(null),x(""),C(!1),S(!1);else{if(!(!p&&(b!=null||k))){br.success(i("agents.payment.saveSuccess")),r();return}if(!w){br.error(i("agents.payment.noSecretsHint"));return}const D=await hk.upsertBinding(m.id,{enabled:k,required:k&&E,secret_id:w,tool_names:[...i9r]});y(D)}br.success(i("agents.payment.saveSuccess")),r()}catch(M){console.error("Failed to update agent:",M),br.error(M instanceof Error?M.message:i("agents.errors.updateFailed"))}finally{A(!1)}}},N=async()=>{if(b){A(!0);try{await hk.deleteBinding(m.id),y(null),x(""),C(!1),S(!1),br.success(i("agents.payment.deleteSuccess"))}catch(L){console.error("Failed to delete payment binding:",L),br.error(L instanceof Error?L.message:i("agents.payment.deleteFailed"))}finally{A(!1)}}};return f.jsxs("form",{onSubmit:B,className:"space-y-6 px-4",children:[f.jsx(VRe,{currentAvatar:e,onSelect:n,backendUrl:o}),f.jsx("div",{className:"border-t border-neutral-200 dark:border-neutral-700"}),f.jsxs("div",{className:"space-y-4",children:[f.jsxs(ld,{children:[f.jsx(Wc,{className:"text-sm font-medium text-neutral-700 dark:text-neutral-300",children:i("agents.fields.name.label")}),f.jsx(Ri,{name:"name",value:m.name,onChange:I,placeholder:i("agents.fields.name.placeholder"),required:!0})]}),f.jsxs(ld,{children:[f.jsx(Wc,{className:"text-sm font-medium text-neutral-700 dark:text-neutral-300",children:i("agents.fields.description.label")}),f.jsx(Ri,{name:"description",value:m.description,onChange:I,placeholder:i("agents.fields.description.placeholder")})]})]}),!p&&f.jsxs(f.Fragment,{children:[f.jsx("div",{className:"border-t border-neutral-200 dark:border-neutral-700"}),f.jsxs("div",{className:"space-y-4",children:[f.jsxs("div",{className:"rounded-lg bg-neutral-100/60 px-4 py-4 dark:bg-white/[0.04]",children:[f.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[f.jsxs("div",{children:[f.jsx("p",{className:"text-[13px] font-medium text-neutral-900 dark:text-neutral-100",children:i("agents.payment.title")}),f.jsx("p",{className:"mt-1 text-xs text-neutral-500 dark:text-neutral-400",children:i("agents.payment.description")})]}),f.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[f.jsx("span",{className:"rounded-full bg-neutral-200/80 px-2 py-0.5 text-[10px] font-medium text-neutral-700 dark:bg-white/[0.08] dark:text-neutral-300",children:b?.status??i("agents.payment.unconfigured")}),b?.required&&f.jsx("span",{className:"rounded-full bg-indigo-50/80 px-2 py-0.5 text-[10px] font-medium text-indigo-700 dark:bg-indigo-900/30 dark:text-indigo-300",children:i("agents.payment.required")})]})]}),b?.last_error&&f.jsx("p",{className:"mt-2 text-xs text-red-600 dark:text-red-400",children:b.last_error})]}),f.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[f.jsxs("label",{className:"flex items-center justify-between rounded-lg bg-neutral-100/60 px-4 py-3 dark:bg-white/[0.04]",children:[f.jsx("span",{className:"text-[13px] font-medium text-neutral-800 dark:text-neutral-200",children:i("agents.payment.enabled")}),f.jsx("input",{type:"checkbox",checked:k,onChange:L=>{const M=L.target.checked;C(M),M||S(!1)},className:"h-4 w-4 rounded border-neutral-300 text-indigo-500 focus:ring-indigo-500/40 dark:border-neutral-600"})]}),f.jsxs("label",{className:"flex items-center justify-between rounded-lg bg-neutral-100/60 px-4 py-3 dark:bg-white/[0.04]",children:[f.jsx("span",{className:Yt("text-[13px] font-medium",k?"text-neutral-800 dark:text-neutral-200":"text-neutral-400 dark:text-neutral-500"),children:i("agents.payment.required")}),f.jsx("input",{type:"checkbox",checked:E,disabled:!k,onChange:L=>S(L.target.checked),className:"h-4 w-4 rounded border-neutral-300 text-indigo-500 focus:ring-indigo-500/40 dark:border-neutral-600"})]})]}),f.jsxs(ld,{children:[f.jsx(Wc,{className:"text-sm font-medium text-neutral-700 dark:text-neutral-300",children:i("agents.payment.secret")}),f.jsxs("select",{value:w,onChange:L=>x(L.target.value),className:"mt-2 w-full rounded-sm border border-neutral-200 bg-white px-3 py-2 text-[13px] text-neutral-900 focus:border-indigo-400 focus:outline-none focus:ring-2 focus:ring-indigo-400/20 dark:border-neutral-700 dark:bg-neutral-900 dark:text-neutral-100",children:[f.jsx("option",{value:"",children:i("agents.payment.secretPlaceholder")}),v.map(L=>f.jsx("option",{value:L.id,children:L.app_id_masked},L.id))]})]}),w&&f.jsx("div",{className:"rounded-lg bg-neutral-100/60 px-4 py-3 text-xs text-neutral-500 dark:bg-white/[0.04] dark:text-neutral-400",children:v.find(L=>L.id===w)?.gateway}),k&&v.length===0&&f.jsxs("div",{className:"rounded-lg bg-neutral-100/60 px-4 py-3 text-xs text-neutral-500 dark:bg-white/[0.04] dark:text-neutral-400",children:[f.jsx("p",{children:i("agents.payment.noSecretsHint")}),f.jsx("button",{type:"button",onClick:()=>d("payment"),className:"mt-2 text-xs font-medium text-indigo-600 hover:text-indigo-500 dark:text-indigo-400",children:i("agents.payment.manageSecrets")})]}),b&&f.jsx("div",{className:"flex justify-end",children:f.jsx("button",{type:"button",onClick:()=>{N()},className:"rounded-lg bg-red-50/80 px-3 py-2 text-xs font-medium text-red-700 transition-colors hover:bg-red-100 dark:bg-red-950/30 dark:text-red-400 dark:hover:bg-red-950/50",children:i("agents.payment.delete")})})]})]}),f.jsx("div",{className:"flex justify-end gap-3 pt-4 border-t border-neutral-200 dark:border-neutral-700",children:f.jsx(Hc,{type:"submit",disabled:h,className:`inline-flex items-center gap-2 rounded-md py-2 px-4 text-sm font-medium transition-colors ${h?"bg-indigo-400 text-white cursor-not-allowed":"bg-indigo-600 text-white hover:bg-indigo-500"}`,children:i(h?"agents.actions.saving":"agents.actions.save")})})]})}const KRe="09:00",u9r=[{value:"0",label:"Sunday"},{value:"1",label:"Monday"},{value:"2",label:"Tuesday"},{value:"3",label:"Wednesday"},{value:"4",label:"Thursday"},{value:"5",label:"Friday"},{value:"6",label:"Saturday"}];function WRt(){return typeof Intl>"u"?"UTC":Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC"}function d9r(t){if(!t)return{mode:"daily",time:KRe,dayOfWeek:"1",cronExpression:"0 9 * * *"};const e=t.trim().split(/\s+/);if(e.length===5){const[n,r,i,o,l]=e;if(/^\d+$/.test(n)&&/^\d+$/.test(r)&&i==="*"&&o==="*"&&l==="*")return{mode:"daily",time:`${r.padStart(2,"0")}:${n.padStart(2,"0")}`,dayOfWeek:"1",cronExpression:t};if(/^\d+$/.test(n)&&/^\d+$/.test(r)&&i==="*"&&o==="*"&&/^\d+$/.test(l))return{mode:"weekly",time:`${r.padStart(2,"0")}:${n.padStart(2,"0")}`,dayOfWeek:l,cronExpression:t}}return{mode:"cron",time:KRe,dayOfWeek:"1",cronExpression:t}}function p9r(t,e,n,r){if(t==="cron")return r.trim();const[i="9",o="0"]=e.split(":"),l=String(Number(o||"0")),u=String(Number(i||"9"));return t==="weekly"?`${l} ${u} * * ${n}`:`${l} ${u} * * *`}function YRt(t){if(!t)return null;const e=new Date(t);return Number.isNaN(e.getTime())?t:new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}).format(e)}function m9r(){const{t}=yn(),{autoExplore:e,autoExploreLoading:n,fetchAutoExplore:r,saveAutoExplore:i,toggleAutoExplore:o}=zn(Vs(E=>({autoExplore:E.autoExplore,autoExploreLoading:E.autoExploreLoading,fetchAutoExplore:E.fetchAutoExplore,saveAutoExplore:E.saveAutoExplore,toggleAutoExplore:E.toggleAutoExplore}))),[l,u]=T.useState("daily"),[d,p]=T.useState(KRe),[m,g]=T.useState("1"),[h,A]=T.useState("0 9 * * *"),[b,y]=T.useState(WRt()),[v,_]=T.useState("auto");T.useEffect(()=>{if(!e){r().catch(()=>{});return}const E=d9r(e.cron_expression);u(E.mode),p(E.time),g(E.dayOfWeek),A(E.cronExpression),y(e.timezone||WRt()),_(e.language||"auto")},[e,r]);const w=async()=>{const E=p9r(l,d,m,h);try{await i({cronExpression:E,timezone:b,language:v}),br.success(t("agents.rootAgent.autoExploreUpdated"))}catch(S){console.error("Failed to save auto-explore:",S),br.error(t("agents.rootAgent.autoExploreFailed"))}},x=async()=>{try{await o(!1),br.success(t("agents.rootAgent.autoExploreDisabled"))}catch(E){console.error("Failed to disable auto-explore:",E),br.error(t("agents.rootAgent.autoExploreFailed"))}},k=YRt(e?.next_run_at||null),C=YRt(e?.last_run_at||null);return f.jsxs("div",{className:"space-y-6 px-4",children:[f.jsxs("div",{className:"rounded-lg bg-neutral-100/60 px-4 py-4 dark:bg-white/[0.04]",children:[f.jsxs("div",{className:"flex items-center justify-between gap-3",children:[f.jsxs("div",{children:[f.jsx("p",{className:"text-[13px] font-medium text-neutral-800 dark:text-neutral-200",children:t("agents.rootAgent.autoExploreSchedule")}),f.jsx("p",{className:"mt-1 text-xs text-neutral-500 dark:text-neutral-400",children:t("agents.rootAgent.autoExploreScheduleHint")})]}),f.jsx("span",{className:Yt("rounded-sm px-2 py-1 text-xs font-medium",e?.enabled?"bg-amber-500/10 text-amber-700 dark:text-amber-300":"bg-neutral-200/80 text-neutral-600 dark:bg-white/[0.06] dark:text-neutral-400"),children:e?.enabled?t("agents.rootAgent.autoExploreEnabledState"):t("agents.rootAgent.autoExploreDisabledState")})]}),f.jsxs("div",{className:"mt-3 space-y-1 text-xs text-neutral-500 dark:text-neutral-400",children:[f.jsxs("p",{children:[t("agents.rootAgent.autoExploreTimezone"),": ",b]}),k&&f.jsxs("p",{children:[t("agents.rootAgent.autoExploreNextRun"),": ",k]}),C&&f.jsxs("p",{children:[t("agents.rootAgent.autoExploreLastRun"),": ",C]}),e?.last_error&&f.jsxs("p",{className:"text-red-600 dark:text-red-400",children:[t("agents.rootAgent.autoExploreLastError"),":"," ",e.last_error]})]})]}),f.jsxs("div",{className:"space-y-4",children:[f.jsxs(ld,{children:[f.jsx(Wc,{className:"text-sm font-medium text-neutral-700 dark:text-neutral-300",children:t("agents.rootAgent.autoExploreCadence")}),f.jsx("div",{className:"mt-2 grid grid-cols-3 gap-2",children:["daily","weekly","cron"].map(E=>f.jsx("button",{type:"button",onClick:()=>u(E),className:Yt("rounded-lg px-3 py-2 text-sm transition-colors",l===E?"bg-indigo-500 text-white":"bg-neutral-100 text-neutral-700 hover:bg-neutral-200 dark:bg-white/[0.04] dark:text-neutral-300 dark:hover:bg-white/[0.08]"),children:t(`agents.rootAgent.autoExploreCadence${E[0].toUpperCase()}${E.slice(1)}`)},E))})]}),l!=="cron"&&f.jsxs(ld,{children:[f.jsx(Wc,{className:"text-sm font-medium text-neutral-700 dark:text-neutral-300",children:t("agents.rootAgent.autoExploreTime")}),f.jsx(Ri,{type:"time",value:d,onChange:E=>p(E.target.value)})]}),l==="weekly"&&f.jsxs(ld,{children:[f.jsx(Wc,{className:"text-sm font-medium text-neutral-700 dark:text-neutral-300",children:t("agents.rootAgent.autoExploreWeekday")}),f.jsx("select",{value:m,onChange:E=>g(E.target.value),className:"mt-2 w-full rounded-sm border border-neutral-200 bg-white px-3 py-2 text-sm text-neutral-700 dark:border-neutral-700 dark:bg-neutral-900 dark:text-neutral-200",children:u9r.map(E=>f.jsx("option",{value:E.value,children:t(`agents.rootAgent.autoExploreWeekday${E.label}`)},E.value))})]}),l==="cron"&&f.jsxs(ld,{children:[f.jsx(Wc,{className:"text-sm font-medium text-neutral-700 dark:text-neutral-300",children:t("agents.rootAgent.autoExploreCron")}),f.jsx(Ri,{value:h,onChange:E=>A(E.target.value),placeholder:"0 9 * * *"})]}),f.jsxs(ld,{children:[f.jsx(Wc,{className:"text-sm font-medium text-neutral-700 dark:text-neutral-300",children:t("agents.rootAgent.autoExploreLanguage")}),f.jsxs("select",{value:v,onChange:E=>_(E.target.value),className:"mt-2 w-full rounded-sm border border-neutral-200 bg-white px-3 py-2 text-sm text-neutral-700 dark:border-neutral-700 dark:bg-neutral-900 dark:text-neutral-200",children:[f.jsx("option",{value:"auto",children:t("agents.rootAgent.autoExploreLanguageAuto")}),f.jsx("option",{value:"zh",children:"中文"}),f.jsx("option",{value:"en",children:"English"}),f.jsx("option",{value:"ja",children:"日本語"})]})]})]}),f.jsxs("div",{className:"flex justify-end gap-3 border-t border-neutral-200 pt-4 dark:border-neutral-700",children:[e?.enabled&&f.jsx(Oa,{type:"button",variant:"outline",disabled:n,onClick:x,children:t("agents.rootAgent.autoExploreDisableAction")}),f.jsx(Oa,{type:"button",disabled:n,onClick:w,children:e?.enabled?t("agents.rootAgent.autoExploreUpdateAction"):t("agents.rootAgent.autoExploreEnableAction")})]})]})}const ZRe=({isOpen:t,onClose:e,agentName:n,agent:r,currentAvatar:i,currentGridSize:o,onAvatarChange:l,onGridSizeChange:u,onDelete:d})=>{const{t:p}=yn(),m=zn(P=>P.backendUrl),g=zn(P=>P.rootAgentId),h=!!r&&!!g&&r.id===g,[A,b]=T.useState("profile"),[y,v]=T.useState(null),[_,w]=T.useState(!1),[x,k]=T.useState(!1),C=typeof window<"u"&&window.innerWidth<768,E=!!r,S=r?.config_visibility!=="hidden",I=r?.original_source_id!=null,B=T.useMemo(()=>o9r.filter(P=>!(P.id==="automation"&&!h||P.id==="workflow"&&(!E||!S)||P.id==="danger"&&!d)),[E,S,d]),N=P=>{C?v(P):b(P),w(!1)},L=()=>{v(null),w(!1)},M=P=>{switch(P){case"profile":return r?f.jsx(c9r,{agent:r,currentAvatar:i,onAvatarChange:l,onClose:e}):f.jsx(VRe,{currentAvatar:i,onSelect:l,backendUrl:m});case"automation":return f.jsx(m9r,{});case"size":return f.jsxs("div",{className:"flex flex-col items-center justify-center h-full py-8",children:[f.jsx("p",{className:"text-sm text-neutral-600 dark:text-neutral-400 mb-8 text-center max-w-64",children:p("agents.sessionSettings.size.description")}),f.jsx(l9r,{currentW:o?.w,currentH:o?.h,onResize:u})]});case"workflow":return r?f.jsx(T.Suspense,{children:f.jsx(s9r,{agent:r,onClose:e})}):null;case"danger":return f.jsx("div",{className:"flex flex-col items-center justify-center h-full py-8 space-y-6",children:_?f.jsxs(Et.div,{initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},className:"w-full max-w-sm rounded-2xl bg-red-50 dark:bg-red-900/10 p-6 space-y-4 border border-red-100 dark:border-red-900/20",children:[f.jsxs("div",{className:"text-center space-y-2",children:[f.jsx("h3",{className:"text-base font-semibold text-red-700 dark:text-red-300",children:p("agents.sessionSettings.danger.deleteConfirmTitle")}),f.jsx("p",{className:"text-sm text-red-600 dark:text-red-400",children:p("agents.sessionSettings.danger.deleteConfirmMessage",{name:n})})]}),f.jsxs("div",{className:"flex gap-3",children:[f.jsx(Oa,{variant:"outline",className:"flex-1 bg-white dark:bg-transparent border-red-200 dark:border-red-900/30 text-red-700 dark:text-red-300 hover:bg-red-100 dark:hover:bg-red-900/20",onClick:()=>w(!1),children:p("common.cancel")}),f.jsx(Oa,{variant:"destructive",className:"flex-1 shadow-lg shadow-red-500/20",onClick:()=>{d?.(),e()},children:p("common.delete")})]})]}):f.jsxs(f.Fragment,{children:[f.jsxs("div",{className:"text-center space-y-2",children:[f.jsx(Qp,{className:"w-12 h-12 mx-auto text-red-400"}),f.jsx("p",{className:"text-sm text-neutral-600 dark:text-neutral-400 max-w-64",children:p("agents.sessionSettings.danger.description")})]}),d&&f.jsxs(Oa,{variant:"destructive",size:"lg",className:"h-11 px-6 gap-3 shadow-lg shadow-red-500/20",onClick:()=>w(!0),children:[f.jsx(Jo,{className:"w-5 h-5"}),p("agents.sessionSettings.danger.deleteButton")]})]})});default:return null}},R=f.jsx("div",{className:"flex-1 min-w-0",children:f.jsx(Qr,{mode:"wait",children:y===null?f.jsx(Et.div,{initial:{opacity:0,x:-20},animate:{opacity:1,x:0},exit:{opacity:0,x:-20},className:"space-y-2",children:B.map(P=>f.jsxs("button",{onClick:()=>N(P.id),className:Yt("w-full flex items-center gap-4 px-4 py-4 rounded-sm transition-all text-left","bg-neutral-50 dark:bg-neutral-800/50 hover:bg-neutral-100 dark:hover:bg-neutral-800",P.color),children:[f.jsx(P.icon,{className:"w-6 h-6 shrink-0"}),f.jsx("span",{className:"text-base font-medium",children:p(`agents.sessionSettings.tabs.${P.labelKey}`)})]},P.id))},"nav"):f.jsxs(Et.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:20},children:[f.jsxs("button",{onClick:L,className:"flex items-center gap-2 text-sm text-neutral-500 hover:text-neutral-700 dark:hover:text-neutral-300 mb-4",children:[f.jsx(g_,{className:"w-4 h-4"}),p("settings.modal.back")]}),M(y)]},y)})}),D=f.jsxs(YP,{value:A,onValueChange:P=>{b(P),w(!1)},className:"flex flex-row gap-6",children:[f.jsx("div",{className:"w-44 shrink-0",children:f.jsx(VP,{className:"flex items-start flex-col w-full h-auto bg-neutral-50 dark:bg-neutral-900 rounded-sm p-1.5",children:B.map(P=>f.jsxs(Fp,{value:P.id,className:Yt("w-44 justify-start gap-3 px-3 py-2.5 text-sm font-medium rounded-lg","data-[state=active]:bg-white data-[state=active]:shadow-sm dark:data-[state=active]:bg-neutral-800",P.id==="danger"&&"data-[state=active]:text-red-600 dark:data-[state=active]:text-red-400",P.color&&A!==P.id&&P.color),children:[f.jsx(P.icon,{className:"w-5 h-5 shrink-0"}),p(`agents.sessionSettings.tabs.${P.labelKey}`)]},P.id))})}),f.jsx("div",{className:"flex-1 min-w-0",children:f.jsx(wU,{children:B.map(P=>f.jsx(Ah,{value:P.id,className:"h-full",children:M(P.id)},P.id))})})]});return f.jsxs(f.Fragment,{children:[f.jsx(El,{isOpen:t,onClose:e,size:"lg",children:f.jsxs("div",{className:"flex h-full flex-col overflow-hidden",children:[f.jsx("div",{className:"shrink-0 px-5 pt-5 pb-1 md:pt-2",children:f.jsx("h2",{className:"text-lg font-bold text-neutral-900 dark:text-neutral-100",children:p("agents.sessionSettings.title",{name:n})})}),f.jsxs("div",{className:"flex-1 overflow-y-auto custom-scrollbar px-5 pb-5",children:[f.jsxs("div",{className:"py-2",children:[f.jsx("div",{className:"md:hidden",children:R}),f.jsx("div",{className:"hidden md:block",children:D})]}),r&&!I&&!h&&f.jsx("div",{className:"mt-4 pt-4 border-t border-neutral-200 dark:border-neutral-700",children:f.jsxs(Oa,{type:"button",variant:"outline",onClick:()=>k(!0),disabled:!r.graph_config,className:"w-full gap-2 h-10 text-purple-700 border-purple-200 hover:bg-purple-50 dark:text-purple-300 dark:border-purple-800 dark:hover:bg-purple-900/20",title:r.graph_config?p("agents.actions.publish"):p("agents.actions.publishTooltip"),children:[f.jsx(Xo,{className:"h-4 w-4"}),p("agents.actions.publish")]})})]})]})}),r&&!I&&!h&&f.jsx(HRt,{open:x,onOpenChange:k,agentId:r.id,agentName:r.name,agentDescription:r.description,graphConfig:r.graph_config,mcpServers:r.mcp_servers?.map(P=>({id:P.id,name:P.name,description:P.description||void 0})),knowledgeSetId:r.knowledge_set_id,tags:r.tags,onPublishSuccess:P=>{console.log("Agent published to marketplace:",P),k(!1)}})]})};function g9r({isOpen:t,onClose:e,onConfirm:n,title:r,message:i,confirmLabel:o="Confirm",cancelLabel:l="Cancel",destructive:u=!0,className:d}){return f.jsx(sRe,{open:t,onOpenChange:p=>!p&&e(),children:f.jsxs(oRe,{className:Yt("space-y-4 border border-neutral-200/20 bg-white/95 shadow-2xl shadow-black/20 backdrop-blur-xl dark:border-neutral-700/30 dark:bg-neutral-900/95 dark:shadow-black/40","p-6 sm:p-6 rounded-sm",d),children:[f.jsx(lRe,{children:f.jsx(uRe,{className:"text-lg font-bold text-neutral-900 dark:text-neutral-100",children:r})}),f.jsxs("div",{className:"custom-scrollbar flex max-h-[60vh] items-start gap-4 overflow-y-auto",children:[f.jsx("div",{className:"flex h-12 w-12 shrink-0 items-center justify-center rounded-full bg-red-100 dark:bg-red-900/30",children:f.jsx(Qp,{className:"h-6 w-6 text-red-600 dark:text-red-400","aria-hidden":"true"})}),f.jsx(dRe,{className:"whitespace-pre-line text-sm text-neutral-600 dark:text-neutral-400",children:i})]}),f.jsxs(cRe,{children:[f.jsx(mRe,{className:Yt("inline-flex items-center gap-2","font-semibold","dark:bg-neutral-800 dark:text-neutral-200 dark:hover:bg-neutral-700"),children:l}),f.jsx(pRe,{autoFocus:!0,onClick:async()=>{await n(),e()},className:Yt("inline-flex items-center gap-2 font-semibold",u?"bg-red-600 text-white shadow-inner shadow-white/10 hover:bg-red-500 dark:bg-red-500 dark:hover:bg-red-400":"bg-neutral-900 text-white hover:bg-neutral-800 dark:bg-neutral-100 dark:text-neutral-900 dark:hover:bg-neutral-200"),children:o})]})]})})}const VA=J.memo(g9r);function VRt(){const{t}=yn(),e=zn(i=>i.toggleAutoExplore),n=zn(i=>i.autoExploreLoading);return{handleToggle:T.useCallback(async i=>{if(!n)try{await e(i),br.success(t(i?"agents.rootAgent.autoExploreEnabled":"agents.rootAgent.autoExploreDisabled"))}catch(o){console.error("Failed to toggle auto-explore:",o),br.error(t("agents.rootAgent.autoExploreFailed"))}},[n,e,t]),loading:n}}function KRt(t,e){const n={};for(const r of t){const i=e[r.id];if(!i)continue;const o=n[i];(!o||r.updatedAt>o)&&(n[i]=r.updatedAt)}return n}function h9r({onClick:t}){const{t:e}=yn();return f.jsxs(Et.button,{onClick:t,initial:{opacity:0,y:10},animate:{opacity:1,y:0},whileHover:{scale:1.02},whileTap:{scale:.98},transition:{type:"spring",stiffness:400,damping:25},className:`inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg
573
+ `),HNt=!0);const o=this._options.WebSocket||WebSocket;this._debug("connect",{url:r,protocols:i}),this._ws=i?new o(r,i):new o(r),this._ws.binaryType=this._binaryType,this._connectLock=!1,this._addListeners(),this._connectTimeout=setTimeout(()=>this._handleTimeout(),n)}).catch(r=>{this._connectLock=!1,this._handleError(new bRe.ErrorEvent(Error(r.message),this))})}_handleTimeout(){this._debug("timeout event"),this._handleError(new bRe.ErrorEvent(Error("TIMEOUT"),this))}_disconnect(e=1e3,n){if(this._clearTimeouts(),!!this._ws){this._removeListeners();try{(this._ws.readyState===this.OPEN||this._ws.readyState===this.CONNECTING)&&this._ws.close(e,n),this._handleClose(new bRe.CloseEvent(e,n,this))}catch{}}}_acceptOpen(){this._debug("accept open"),this._retryCount=0}_handleOpen=e=>{this._debug("open event");const{minUptime:n=e3.minUptime}=this._options;clearTimeout(this._connectTimeout),this._uptimeTimeout=setTimeout(()=>this._acceptOpen(),n),MFr(this._ws,"WebSocket is not defined"),this._ws.binaryType=this._binaryType,this._messageQueue.forEach(r=>{this._ws?.send(r)}),this._messageQueue=[],this.onopen&&this.onopen(e),this.dispatchEvent(ole(e))};_handleMessage=e=>{this._debug("message event"),this.onmessage&&this.onmessage(e),this.dispatchEvent(ole(e))};_handleError=e=>{this._debug("error event",e.message),this._disconnect(void 0,e.message==="TIMEOUT"?"timeout":void 0),this.onerror&&this.onerror(e),this._debug("exec error listeners"),this.dispatchEvent(ole(e)),this._connect()};_handleClose=e=>{this._debug("close event"),this._clearTimeouts(),this._shouldReconnect&&this._connect(),this.onclose&&this.onclose(e),this.dispatchEvent(ole(e))};_removeListeners(){this._ws&&(this._debug("removeListeners"),this._ws.removeEventListener("open",this._handleOpen),this._ws.removeEventListener("close",this._handleClose),this._ws.removeEventListener("message",this._handleMessage),this._ws.removeEventListener("error",this._handleError))}_addListeners(){this._ws&&(this._debug("addListeners"),this._ws.addEventListener("open",this._handleOpen),this._ws.addEventListener("close",this._handleClose),this._ws.addEventListener("message",this._handleMessage),this._ws.addEventListener("error",this._handleError))}_clearTimeouts(){clearTimeout(this._connectTimeout),clearTimeout(this._uptimeTimeout)}};const ck=Object.create(null);ck.open="0",ck.close="1",ck.ping="2",ck.pong="3",ck.message="4",ck.upgrade="5",ck.noop="6";const lle=Object.create(null);Object.keys(ck).forEach(t=>{lle[ck[t]]=t});const yRe={type:"error",data:"parser error"},WNt=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",YNt=typeof ArrayBuffer=="function",VNt=t=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(t):t&&t.buffer instanceof ArrayBuffer,vRe=({type:t,data:e},n,r)=>WNt&&e instanceof Blob?n?r(e):KNt(e,r):YNt&&(e instanceof ArrayBuffer||VNt(e))?n?r(e):KNt(new Blob([e]),r):r(ck[t]+(e||"")),KNt=(t,e)=>{const n=new FileReader;return n.onload=function(){const r=n.result.split(",")[1];e("b"+(r||""))},n.readAsDataURL(t)};function ZNt(t){return t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}let _Re;function jFr(t,e){if(WNt&&t.data instanceof Blob)return t.data.arrayBuffer().then(ZNt).then(e);if(YNt&&(t.data instanceof ArrayBuffer||VNt(t.data)))return e(ZNt(t.data));vRe(t,!1,n=>{_Re||(_Re=new TextEncoder),e(_Re.encode(n))})}const XNt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",oG=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let t=0;t<XNt.length;t++)oG[XNt.charCodeAt(t)]=t;const zFr=t=>{let e=t.length*.75,n=t.length,r,i=0,o,l,u,d;t[t.length-1]==="="&&(e--,t[t.length-2]==="="&&e--);const p=new ArrayBuffer(e),m=new Uint8Array(p);for(r=0;r<n;r+=4)o=oG[t.charCodeAt(r)],l=oG[t.charCodeAt(r+1)],u=oG[t.charCodeAt(r+2)],d=oG[t.charCodeAt(r+3)],m[i++]=o<<2|l>>4,m[i++]=(l&15)<<4|u>>2,m[i++]=(u&3)<<6|d&63;return p},UFr=typeof ArrayBuffer=="function",wRe=(t,e)=>{if(typeof t!="string")return{type:"message",data:JNt(t,e)};const n=t.charAt(0);return n==="b"?{type:"message",data:qFr(t.substring(1),e)}:lle[n]?t.length>1?{type:lle[n],data:t.substring(1)}:{type:lle[n]}:yRe},qFr=(t,e)=>{if(UFr){const n=zFr(t);return JNt(n,e)}else return{base64:!0,data:t}},JNt=(t,e)=>e==="blob"?t instanceof Blob?t:new Blob([t]):t instanceof ArrayBuffer?t:t.buffer,eRt="",GFr=(t,e)=>{const n=t.length,r=new Array(n);let i=0;t.forEach((o,l)=>{vRe(o,!1,u=>{r[l]=u,++i===n&&e(r.join(eRt))})})},HFr=(t,e)=>{const n=t.split(eRt),r=[];for(let i=0;i<n.length;i++){const o=wRe(n[i],e);if(r.push(o),o.type==="error")break}return r};function WFr(){return new TransformStream({transform(t,e){jFr(t,n=>{const r=n.length;let i;if(r<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,r);else if(r<65536){i=new Uint8Array(3);const o=new DataView(i.buffer);o.setUint8(0,126),o.setUint16(1,r)}else{i=new Uint8Array(9);const o=new DataView(i.buffer);o.setUint8(0,127),o.setBigUint64(1,BigInt(r))}t.data&&typeof t.data!="string"&&(i[0]|=128),e.enqueue(i),e.enqueue(n)})}})}let xRe;function cle(t){return t.reduce((e,n)=>e+n.length,0)}function ule(t,e){if(t[0].length===e)return t.shift();const n=new Uint8Array(e);let r=0;for(let i=0;i<e;i++)n[i]=t[0][r++],r===t[0].length&&(t.shift(),r=0);return t.length&&r<t[0].length&&(t[0]=t[0].slice(r)),n}function YFr(t,e){xRe||(xRe=new TextDecoder);const n=[];let r=0,i=-1,o=!1;return new TransformStream({transform(l,u){for(n.push(l);;){if(r===0){if(cle(n)<1)break;const d=ule(n,1);o=(d[0]&128)===128,i=d[0]&127,i<126?r=3:i===126?r=1:r=2}else if(r===1){if(cle(n)<2)break;const d=ule(n,2);i=new DataView(d.buffer,d.byteOffset,d.length).getUint16(0),r=3}else if(r===2){if(cle(n)<8)break;const d=ule(n,8),p=new DataView(d.buffer,d.byteOffset,d.length),m=p.getUint32(0);if(m>Math.pow(2,21)-1){u.enqueue(yRe);break}i=m*Math.pow(2,32)+p.getUint32(4),r=3}else{if(cle(n)<i)break;const d=ule(n,i);u.enqueue(wRe(o?d:xRe.decode(d),e)),r=0}if(i===0||i>t){u.enqueue(yRe);break}}}})}const tRt=4;function mp(t){if(t)return VFr(t)}function VFr(t){for(var e in mp.prototype)t[e]=mp.prototype[e];return t}mp.prototype.on=mp.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},mp.prototype.once=function(t,e){function n(){this.off(t,n),e.apply(this,arguments)}return n.fn=e,this.on(t,n),this},mp.prototype.off=mp.prototype.removeListener=mp.prototype.removeAllListeners=mp.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var n=this._callbacks["$"+t];if(!n)return this;if(arguments.length==1)return delete this._callbacks["$"+t],this;for(var r,i=0;i<n.length;i++)if(r=n[i],r===e||r.fn===e){n.splice(i,1);break}return n.length===0&&delete this._callbacks["$"+t],this},mp.prototype.emit=function(t){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),n=this._callbacks["$"+t],r=1;r<arguments.length;r++)e[r-1]=arguments[r];if(n){n=n.slice(0);for(var r=0,i=n.length;r<i;++r)n[r].apply(this,e)}return this},mp.prototype.emitReserved=mp.prototype.emit,mp.prototype.listeners=function(t){return this._callbacks=this._callbacks||{},this._callbacks["$"+t]||[]},mp.prototype.hasListeners=function(t){return!!this.listeners(t).length};const Dy=typeof self<"u"?self:typeof window<"u"?window:Function("return this")();function nRt(t,...e){return e.reduce((n,r)=>(t.hasOwnProperty(r)&&(n[r]=t[r]),n),{})}const KFr=Dy.setTimeout,ZFr=Dy.clearTimeout;function dle(t,e){e.useNativeTimers?(t.setTimeoutFn=KFr.bind(Dy),t.clearTimeoutFn=ZFr.bind(Dy)):(t.setTimeoutFn=Dy.setTimeout.bind(Dy),t.clearTimeoutFn=Dy.clearTimeout.bind(Dy))}const XFr=1.33;function JFr(t){return typeof t=="string"?e8r(t):Math.ceil((t.byteLength||t.size)*XFr)}function e8r(t){let e=0,n=0;for(let r=0,i=t.length;r<i;r++)e=t.charCodeAt(r),e<128?n+=1:e<2048?n+=2:e<55296||e>=57344?n+=3:(r++,n+=4);return n}function t8r(t){let e="";for(let n in t)t.hasOwnProperty(n)&&(e.length&&(e+="&"),e+=encodeURIComponent(n)+"="+encodeURIComponent(t[n]));return e}function n8r(t){let e={},n=t.split("&");for(let r=0,i=n.length;r<i;r++){let o=n[r].split("=");e[decodeURIComponent(o[0])]=decodeURIComponent(o[1])}return e}class r8r extends Error{constructor(e,n,r){super(e),this.description=n,this.context=r,this.type="TransportError"}}class kRe extends mp{constructor(e){super(),this.writable=!1,dle(this,e),this.opts=e,this.query=e.query,this.socket=e.socket}onError(e,n,r){return super.emitReserved("error",new r8r(e,n,r)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(e){this.readyState==="open"&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const n=wRe(e,this.socket.binaryType);this.onPacket(n)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,n={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(n)}_hostname(){const e=this.opts.hostname;return e.indexOf(":")===-1?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&+(this.opts.port!==443)||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(e){const n=t8r(e);return n.length?"?"+n:""}}const rRt="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),ERe=64,a8r={};let aRt=0,ple=0,iRt;function sRt(t){let e="";do e=rRt[t%ERe]+e,t=Math.floor(t/ERe);while(t>0);return e}function oRt(){const t=sRt(+new Date);return t!==iRt?(aRt=0,iRt=t):t+"."+sRt(aRt++)}for(;ple<ERe;ple++)a8r[rRt[ple]]=ple;let lRt=!1;try{lRt=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const i8r=lRt;function cRt(t){const e=t.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||i8r))return new XMLHttpRequest}catch{}if(!e)try{return new Dy[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}function Uws(){}function s8r(){}const o8r=(function(){return new cRt({xdomain:!1}).responseType!=null})();class l8r extends kRe{constructor(e){if(super(e),this.polling=!1,typeof location<"u"){const r=location.protocol==="https:";let i=location.port;i||(i=r?"443":"80"),this.xd=typeof location<"u"&&e.hostname!==location.hostname||i!==e.port}const n=e&&e.forceBase64;this.supportsBinary=o8r&&!n,this.opts.withCredentials&&(this.cookieJar=void 0)}get name(){return"polling"}doOpen(){this.poll()}pause(e){this.readyState="pausing";const n=()=>{this.readyState="paused",e()};if(this.polling||!this.writable){let r=0;this.polling&&(r++,this.once("pollComplete",function(){--r||n()})),this.writable||(r++,this.once("drain",function(){--r||n()}))}else n()}poll(){this.polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){const n=r=>{if(this.readyState==="opening"&&r.type==="open"&&this.onOpen(),r.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(r)};HFr(e,this.socket.binaryType).forEach(n),this.readyState!=="closed"&&(this.polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this.poll())}doClose(){const e=()=>{this.write([{type:"close"}])};this.readyState==="open"?e():this.once("open",e)}write(e){this.writable=!1,GFr(e,n=>{this.doWrite(n,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const e=this.opts.secure?"https":"http",n=this.query||{};return this.opts.timestampRequests!==!1&&(n[this.opts.timestampParam]=oRt()),!this.supportsBinary&&!n.sid&&(n.b64=1),this.createUri(e,n)}request(e={}){return Object.assign(e,{xd:this.xd,cookieJar:this.cookieJar},this.opts),new gF(this.uri(),e)}doWrite(e,n){const r=this.request({method:"POST",data:e});r.on("success",n),r.on("error",(i,o)=>{this.onError("xhr post error",i,o)})}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(n,r)=>{this.onError("xhr poll error",n,r)}),this.pollXhr=e}}let gF=class Uxe extends mp{constructor(e,n){super(),dle(this,n),this.opts=n,this.method=n.method||"GET",this.uri=e,this.data=n.data!==void 0?n.data:null,this.create()}create(){var e;const n=nRt(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");n.xdomain=!!this.opts.xd;const r=this.xhr=new cRt(n);try{r.open(this.method,this.uri,!0);try{if(this.opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let i in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(i)&&r.setRequestHeader(i,this.opts.extraHeaders[i])}}catch{}if(this.method==="POST")try{r.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{r.setRequestHeader("Accept","*/*")}catch{}(e=this.opts.cookieJar)===null||e===void 0||e.addCookies(r),"withCredentials"in r&&(r.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(r.timeout=this.opts.requestTimeout),r.onreadystatechange=()=>{var i;r.readyState===3&&((i=this.opts.cookieJar)===null||i===void 0||i.parseCookies(r)),r.readyState===4&&(r.status===200||r.status===1223?this.onLoad():this.setTimeoutFn(()=>{this.onError(typeof r.status=="number"?r.status:0)},0))},r.send(this.data)}catch(i){this.setTimeoutFn(()=>{this.onError(i)},0);return}typeof document<"u"&&(this.index=Uxe.requestsCount++,Uxe.requests[this.index]=this)}onError(e){this.emitReserved("error",e,this.xhr),this.cleanup(!0)}cleanup(e){if(!(typeof this.xhr>"u"||this.xhr===null)){if(this.xhr.onreadystatechange=s8r,e)try{this.xhr.abort()}catch{}typeof document<"u"&&delete Uxe.requests[this.index],this.xhr=null}}onLoad(){const e=this.xhr.responseText;e!==null&&(this.emitReserved("data",e),this.emitReserved("success"),this.cleanup())}abort(){this.cleanup()}};if(gF.requestsCount=0,gF.requests={},typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",uRt);else if(typeof addEventListener=="function"){const t="onpagehide"in Dy?"pagehide":"unload";addEventListener(t,uRt,!1)}}function uRt(){for(let t in gF.requests)gF.requests.hasOwnProperty(t)&&gF.requests[t].abort()}const CRe=typeof Promise=="function"&&typeof Promise.resolve=="function"?e=>Promise.resolve().then(e):(e,n)=>n(e,0),mle=Dy.WebSocket||Dy.MozWebSocket,dRt=!0,c8r="arraybuffer",pRt=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class u8r extends kRe{constructor(e){super(e),this.supportsBinary=!e.forceBase64}get name(){return"websocket"}doOpen(){if(!this.check())return;const e=this.uri(),n=this.opts.protocols,r=pRt?{}:nRt(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(r.headers=this.opts.extraHeaders);try{this.ws=dRt&&!pRt?n?new mle(e,n):new mle(e):new mle(e,n,r)}catch(i){return this.emitReserved("error",i)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let n=0;n<e.length;n++){const r=e[n],i=n===e.length-1;vRe(r,this.supportsBinary,o=>{const l={};try{dRt&&this.ws.send(o)}catch{}i&&CRe(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",n=this.query||{};return this.opts.timestampRequests&&(n[this.opts.timestampParam]=oRt()),this.supportsBinary||(n.b64=1),this.createUri(e,n)}check(){return!!mle}}class d8r extends kRe{get name(){return"webtransport"}doOpen(){typeof WebTransport=="function"&&(this.transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name]),this.transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this.transport.ready.then(()=>{this.transport.createBidirectionalStream().then(e=>{const n=YFr(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=e.readable.pipeThrough(n).getReader(),i=WFr();i.readable.pipeTo(e.writable),this.writer=i.writable.getWriter();const o=()=>{r.read().then(({done:u,value:d})=>{u||(this.onPacket(d),o())}).catch(u=>{})};o();const l={type:"open"};this.query.sid&&(l.data=`{"sid":"${this.query.sid}"}`),this.writer.write(l).then(()=>this.onOpen())})}))}write(e){this.writable=!1;for(let n=0;n<e.length;n++){const r=e[n],i=n===e.length-1;this.writer.write(r).then(()=>{i&&CRe(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this.transport)===null||e===void 0||e.close()}}const p8r={websocket:u8r,webtransport:d8r,polling:l8r},m8r=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,g8r=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function SRe(t){if(t.length>2e3)throw"URI too long";const e=t,n=t.indexOf("["),r=t.indexOf("]");n!=-1&&r!=-1&&(t=t.substring(0,n)+t.substring(n,r).replace(/:/g,";")+t.substring(r,t.length));let i=m8r.exec(t||""),o={},l=14;for(;l--;)o[g8r[l]]=i[l]||"";return n!=-1&&r!=-1&&(o.source=e,o.host=o.host.substring(1,o.host.length-1).replace(/;/g,":"),o.authority=o.authority.replace("[","").replace("]","").replace(/;/g,":"),o.ipv6uri=!0),o.pathNames=h8r(o,o.path),o.queryKey=f8r(o,o.query),o}function h8r(t,e){const n=/\/{2,9}/g,r=e.replace(n,"/").split("/");return(e.slice(0,1)=="/"||e.length===0)&&r.splice(0,1),e.slice(-1)=="/"&&r.splice(r.length-1,1),r}function f8r(t,e){const n={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(r,i,o){i&&(n[i]=o)}),n}let mRt=class H7 extends mp{constructor(e,n={}){super(),this.binaryType=c8r,this.writeBuffer=[],e&&typeof e=="object"&&(n=e,e=null),e?(e=SRe(e),n.hostname=e.host,n.secure=e.protocol==="https"||e.protocol==="wss",n.port=e.port,e.query&&(n.query=e.query)):n.host&&(n.hostname=SRe(n.host).host),dle(this,n),this.secure=n.secure!=null?n.secure:typeof location<"u"&&location.protocol==="https:",n.hostname&&!n.port&&(n.port=this.secure?"443":"80"),this.hostname=n.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=n.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=n.transports||["polling","websocket","webtransport"],this.writeBuffer=[],this.prevBufferLen=0,this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},n),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=n8r(this.opts.query)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingTimeoutTimer=null,typeof addEventListener=="function"&&(this.opts.closeOnBeforeunload&&(this.beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this.beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this.offlineEventListener=()=>{this.onClose("transport close",{description:"network connection lost"})},addEventListener("offline",this.offlineEventListener,!1))),this.open()}createTransport(e){const n=Object.assign({},this.opts.query);n.EIO=tRt,n.transport=e,this.id&&(n.sid=this.id);const r=Object.assign({},this.opts,{query:n,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new p8r[e](r)}open(){let e;if(this.opts.rememberUpgrade&&H7.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1)e="websocket";else if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}else e=this.transports[0];this.readyState="opening";try{e=this.createTransport(e)}catch{this.transports.shift(),this.open();return}e.open(),this.setTransport(e)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",n=>this.onClose("transport close",n))}probe(e){let n=this.createTransport(e),r=!1;H7.priorWebsocketSuccess=!1;const i=()=>{r||(n.send([{type:"ping",data:"probe"}]),n.once("packet",g=>{if(!r)if(g.type==="pong"&&g.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",n),!n)return;H7.priorWebsocketSuccess=n.name==="websocket",this.transport.pause(()=>{r||this.readyState!=="closed"&&(m(),this.setTransport(n),n.send([{type:"upgrade"}]),this.emitReserved("upgrade",n),n=null,this.upgrading=!1,this.flush())})}else{const h=new Error("probe error");h.transport=n.name,this.emitReserved("upgradeError",h)}}))};function o(){r||(r=!0,m(),n.close(),n=null)}const l=g=>{const h=new Error("probe error: "+g);h.transport=n.name,o(),this.emitReserved("upgradeError",h)};function u(){l("transport closed")}function d(){l("socket closed")}function p(g){n&&g.name!==n.name&&o()}const m=()=>{n.removeListener("open",i),n.removeListener("error",l),n.removeListener("close",u),this.off("close",d),this.off("upgrading",p)};n.once("open",i),n.once("error",l),n.once("close",u),this.once("close",d),this.once("upgrading",p),this.upgrades.indexOf("webtransport")!==-1&&e!=="webtransport"?this.setTimeoutFn(()=>{r||n.open()},200):n.open()}onOpen(){if(this.readyState="open",H7.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush(),this.readyState==="open"&&this.opts.upgrade){let e=0;const n=this.upgrades.length;for(;e<n;e++)this.probe(this.upgrades[e])}}onPacket(e){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),this.resetPingTimeout(),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this.sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong");break;case"error":const n=new Error("server error");n.code=e.data,this.onError(n);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data);break}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this.upgrades=this.filterUpgrades(e.upgrades),this.pingInterval=e.pingInterval,this.pingTimeout=e.pingTimeout,this.maxPayload=e.maxPayload,this.onOpen(),this.readyState!=="closed"&&this.resetPingTimeout()}resetPingTimeout(){this.clearTimeoutFn(this.pingTimeoutTimer),this.pingTimeoutTimer=this.setTimeoutFn(()=>{this.onClose("ping timeout")},this.pingInterval+this.pingTimeout),this.opts.autoUnref&&this.pingTimeoutTimer.unref()}onDrain(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this.getWritablePackets();this.transport.send(e),this.prevBufferLen=e.length,this.emitReserved("flush")}}getWritablePackets(){if(!(this.maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let n=1;for(let r=0;r<this.writeBuffer.length;r++){const i=this.writeBuffer[r].data;if(i&&(n+=JFr(i)),r>0&&n>this.maxPayload)return this.writeBuffer.slice(0,r);n+=2}return this.writeBuffer}write(e,n,r){return this.sendPacket("message",e,n,r),this}send(e,n,r){return this.sendPacket("message",e,n,r),this}sendPacket(e,n,r,i){if(typeof n=="function"&&(i=n,n=void 0),typeof r=="function"&&(i=r,r=null),this.readyState==="closing"||this.readyState==="closed")return;r=r||{},r.compress=r.compress!==!1;const o={type:e,data:n,options:r};this.emitReserved("packetCreate",o),this.writeBuffer.push(o),i&&this.once("flush",i),this.flush()}close(){const e=()=>{this.onClose("forced close"),this.transport.close()},n=()=>{this.off("upgrade",n),this.off("upgradeError",n),e()},r=()=>{this.once("upgrade",n),this.once("upgradeError",n)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?r():e()}):this.upgrading?r():e()),this}onError(e){H7.priorWebsocketSuccess=!1,this.emitReserved("error",e),this.onClose("transport error",e)}onClose(e,n){(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")&&(this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),typeof removeEventListener=="function"&&(removeEventListener("beforeunload",this.beforeunloadEventListener,!1),removeEventListener("offline",this.offlineEventListener,!1)),this.readyState="closed",this.id=null,this.emitReserved("close",e,n),this.writeBuffer=[],this.prevBufferLen=0)}filterUpgrades(e){const n=[];let r=0;const i=e.length;for(;r<i;r++)~this.transports.indexOf(e[r])&&n.push(e[r]);return n}};mRt.protocol=tRt;function A8r(t,e="",n){let r=t;n=n||typeof location<"u"&&location,t==null&&(t=n.protocol+"//"+n.host),typeof t=="string"&&(t.charAt(0)==="/"&&(t.charAt(1)==="/"?t=n.protocol+t:t=n.host+t),/^(https?|wss?):\/\//.test(t)||(typeof n<"u"?t=n.protocol+"//"+t:t="https://"+t),r=SRe(t)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port="80":/^(http|ws)s$/.test(r.protocol)&&(r.port="443")),r.path=r.path||"/";const o=r.host.indexOf(":")!==-1?"["+r.host+"]":r.host;return r.id=r.protocol+"://"+o+":"+r.port+e,r.href=r.protocol+"://"+o+(n&&n.port===r.port?"":":"+r.port),r}const b8r=typeof ArrayBuffer=="function",y8r=t=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(t):t.buffer instanceof ArrayBuffer,gRt=Object.prototype.toString,v8r=typeof Blob=="function"||typeof Blob<"u"&&gRt.call(Blob)==="[object BlobConstructor]",_8r=typeof File=="function"||typeof File<"u"&&gRt.call(File)==="[object FileConstructor]";function IRe(t){return b8r&&(t instanceof ArrayBuffer||y8r(t))||v8r&&t instanceof Blob||_8r&&t instanceof File}function gle(t,e){if(!t||typeof t!="object")return!1;if(Array.isArray(t)){for(let n=0,r=t.length;n<r;n++)if(gle(t[n]))return!0;return!1}if(IRe(t))return!0;if(t.toJSON&&typeof t.toJSON=="function"&&arguments.length===1)return gle(t.toJSON(),!0);for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)&&gle(t[n]))return!0;return!1}function w8r(t){const e=[],n=t.data,r=t;return r.data=TRe(n,e),r.attachments=e.length,{packet:r,buffers:e}}function TRe(t,e){if(!t)return t;if(IRe(t)){const n={_placeholder:!0,num:e.length};return e.push(t),n}else if(Array.isArray(t)){const n=new Array(t.length);for(let r=0;r<t.length;r++)n[r]=TRe(t[r],e);return n}else if(typeof t=="object"&&!(t instanceof Date)){const n={};for(const r in t)Object.prototype.hasOwnProperty.call(t,r)&&(n[r]=TRe(t[r],e));return n}return t}function x8r(t,e){return t.data=BRe(t.data,e),delete t.attachments,t}function BRe(t,e){if(!t)return t;if(t&&t._placeholder===!0){if(typeof t.num=="number"&&t.num>=0&&t.num<e.length)return e[t.num];throw new Error("illegal attachments")}else if(Array.isArray(t))for(let n=0;n<t.length;n++)t[n]=BRe(t[n],e);else if(typeof t=="object")for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(t[n]=BRe(t[n],e));return t}const k8r=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var Oo;(function(t){t[t.CONNECT=0]="CONNECT",t[t.DISCONNECT=1]="DISCONNECT",t[t.EVENT=2]="EVENT",t[t.ACK=3]="ACK",t[t.CONNECT_ERROR=4]="CONNECT_ERROR",t[t.BINARY_EVENT=5]="BINARY_EVENT",t[t.BINARY_ACK=6]="BINARY_ACK"})(Oo||(Oo={}));class E8r{constructor(e){this.replacer=e}encode(e){return(e.type===Oo.EVENT||e.type===Oo.ACK)&&gle(e)?this.encodeAsBinary({type:e.type===Oo.EVENT?Oo.BINARY_EVENT:Oo.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let n=""+e.type;return(e.type===Oo.BINARY_EVENT||e.type===Oo.BINARY_ACK)&&(n+=e.attachments+"-"),e.nsp&&e.nsp!=="/"&&(n+=e.nsp+","),e.id!=null&&(n+=e.id),e.data!=null&&(n+=JSON.stringify(e.data,this.replacer)),n}encodeAsBinary(e){const n=w8r(e),r=this.encodeAsString(n.packet),i=n.buffers;return i.unshift(r),i}}class DRe extends mp{constructor(e){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},typeof e=="function"?{reviver:e}:e)}add(e){let n;if(typeof e=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");n=this.decodeString(e);const r=n.type===Oo.BINARY_EVENT;r||n.type===Oo.BINARY_ACK?(n.type=r?Oo.EVENT:Oo.ACK,this.reconstructor=new C8r(n),n.attachments===0&&super.emitReserved("decoded",n)):super.emitReserved("decoded",n)}else if(IRe(e)||e.base64)if(this.reconstructor)n=this.reconstructor.takeBinaryData(e),n&&(this.reconstructor=null,super.emitReserved("decoded",n));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+e)}decodeString(e){let n=0;const r={type:Number(e.charAt(0))};if(Oo[r.type]===void 0)throw new Error("unknown packet type "+r.type);if(r.type===Oo.BINARY_EVENT||r.type===Oo.BINARY_ACK){const o=n+1;for(;e.charAt(++n)!=="-"&&n!=e.length;);const l=e.substring(o,n);if(l!=Number(l)||e.charAt(n)!=="-")throw new Error("Illegal attachments");const u=Number(l);if(!S8r(u)||u<0)throw new Error("Illegal attachments");if(u>this.opts.maxAttachments)throw new Error("too many attachments");r.attachments=u}if(e.charAt(n+1)==="/"){const o=n+1;for(;++n&&!(e.charAt(n)===","||n===e.length););r.nsp=e.substring(o,n)}else r.nsp="/";const i=e.charAt(n+1);if(i!==""&&Number(i)==i){const o=n+1;for(;++n;){const l=e.charAt(n);if(l==null||Number(l)!=l){--n;break}if(n===e.length)break}r.id=Number(e.substring(o,n+1))}if(e.charAt(++n)){const o=this.tryParse(e.substr(n));if(DRe.isPayloadValid(r.type,o))r.data=o;else throw new Error("invalid payload")}return r}tryParse(e){try{return JSON.parse(e,this.opts.reviver)}catch{return!1}}static isPayloadValid(e,n){switch(e){case Oo.CONNECT:return hRt(n);case Oo.DISCONNECT:return n===void 0;case Oo.CONNECT_ERROR:return typeof n=="string"||hRt(n);case Oo.EVENT:case Oo.BINARY_EVENT:return Array.isArray(n)&&(typeof n[0]=="number"||typeof n[0]=="string"&&k8r.indexOf(n[0])===-1);case Oo.ACK:case Oo.BINARY_ACK:return Array.isArray(n)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class C8r{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const n=x8r(this.reconPack,this.buffers);return this.finishedReconstruction(),n}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const S8r=Number.isInteger||function(t){return typeof t=="number"&&isFinite(t)&&Math.floor(t)===t};function hRt(t){return Object.prototype.toString.call(t)==="[object Object]"}const I8r=Object.freeze(Object.defineProperty({__proto__:null,Decoder:DRe,Encoder:E8r,get PacketType(){return Oo}},Symbol.toStringTag,{value:"Module"}));function R_(t,e,n){return t.on(e,n),function(){t.off(e,n)}}const T8r=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});let fRt=class extends mp{constructor(e,n,r){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=n,r&&r.auth&&(this.auth=r.auth),this._opts=Object.assign({},r),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[R_(e,"open",this.onopen.bind(this)),R_(e,"packet",this.onpacket.bind(this)),R_(e,"error",this.onerror.bind(this)),R_(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...n){if(T8r.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(n.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(n),this;const r={type:Oo.EVENT,data:n};if(r.options={},r.options.compress=this.flags.compress!==!1,typeof n[n.length-1]=="function"){const l=this.ids++,u=n.pop();this._registerAckCallback(l,u),r.id=l}const i=this.io.engine&&this.io.engine.transport&&this.io.engine.transport.writable;return this.flags.volatile&&(!i||!this.connected)||(this.connected?(this.notifyOutgoingListeners(r),this.packet(r)):this.sendBuffer.push(r)),this.flags={},this}_registerAckCallback(e,n){var r;const i=(r=this.flags.timeout)!==null&&r!==void 0?r:this._opts.ackTimeout;if(i===void 0){this.acks[e]=n;return}const o=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let l=0;l<this.sendBuffer.length;l++)this.sendBuffer[l].id===e&&this.sendBuffer.splice(l,1);n.call(this,new Error("operation has timed out"))},i);this.acks[e]=(...l)=>{this.io.clearTimeoutFn(o),n.apply(this,[null,...l])}}emitWithAck(e,...n){const r=this.flags.timeout!==void 0||this._opts.ackTimeout!==void 0;return new Promise((i,o)=>{n.push((l,u)=>r?l?o(l):i(u):i(l)),this.emit(e,...n)})}_addToQueue(e){let n;typeof e[e.length-1]=="function"&&(n=e.pop());const r={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((i,...o)=>r!==this._queue[0]?void 0:(i!==null?r.tryCount>this._opts.retries&&(this._queue.shift(),n&&n(i)):(this._queue.shift(),n&&n(null,...o)),r.pending=!1,this._drainQueue())),this._queue.push(r),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||this._queue.length===0)return;const n=this._queue[0];n.pending&&!e||(n.pending=!0,n.tryCount++,this.flags=n.flags,this.emit.apply(this,n.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){typeof this.auth=="function"?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:Oo.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,n){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,n)}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case Oo.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case Oo.EVENT:case Oo.BINARY_EVENT:this.onevent(e);break;case Oo.ACK:case Oo.BINARY_ACK:this.onack(e);break;case Oo.DISCONNECT:this.ondisconnect();break;case Oo.CONNECT_ERROR:this.destroy();const r=new Error(e.data.message);r.data=e.data.data,this.emitReserved("connect_error",r);break}}onevent(e){const n=e.data||[];e.id!=null&&n.push(this.ack(e.id)),this.connected?this.emitEvent(n):this.receiveBuffer.push(Object.freeze(n))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const n=this._anyListeners.slice();for(const r of n)r.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&typeof e[e.length-1]=="string"&&(this._lastOffset=e[e.length-1])}ack(e){const n=this;let r=!1;return function(...i){r||(r=!0,n.packet({type:Oo.ACK,id:e,data:i}))}}onack(e){const n=this.acks[e.id];typeof n=="function"&&(n.apply(this,e.data),delete this.acks[e.id])}onconnect(e,n){this.id=e,this.recovered=n&&this._pid===n,this._pid=n,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:Oo.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const n=this._anyListeners;for(let r=0;r<n.length;r++)if(e===n[r])return n.splice(r,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const n=this._anyOutgoingListeners;for(let r=0;r<n.length;r++)if(e===n[r])return n.splice(r,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const n=this._anyOutgoingListeners.slice();for(const r of n)r.apply(this,e.data)}}};function hF(t){t=t||{},this.ms=t.min||100,this.max=t.max||1e4,this.factor=t.factor||2,this.jitter=t.jitter>0&&t.jitter<=1?t.jitter:0,this.attempts=0}hF.prototype.duration=function(){var t=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),n=Math.floor(e*this.jitter*t);t=(Math.floor(e*10)&1)==0?t-n:t+n}return Math.min(t,this.max)|0},hF.prototype.reset=function(){this.attempts=0},hF.prototype.setMin=function(t){this.ms=t},hF.prototype.setMax=function(t){this.max=t},hF.prototype.setJitter=function(t){this.jitter=t};class NRe extends mp{constructor(e,n){var r;super(),this.nsps={},this.subs=[],e&&typeof e=="object"&&(n=e,e=void 0),n=n||{},n.path=n.path||"/socket.io",this.opts=n,dle(this,n),this.reconnection(n.reconnection!==!1),this.reconnectionAttempts(n.reconnectionAttempts||1/0),this.reconnectionDelay(n.reconnectionDelay||1e3),this.reconnectionDelayMax(n.reconnectionDelayMax||5e3),this.randomizationFactor((r=n.randomizationFactor)!==null&&r!==void 0?r:.5),this.backoff=new hF({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(n.timeout==null?2e4:n.timeout),this._readyState="closed",this.uri=e;const i=n.parser||I8r;this.encoder=new i.Encoder,this.decoder=new i.Decoder,this._autoConnect=n.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var n;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(n=this.backoff)===null||n===void 0||n.setMin(e),this)}randomizationFactor(e){var n;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(n=this.backoff)===null||n===void 0||n.setJitter(e),this)}reconnectionDelayMax(e){var n;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(n=this.backoff)===null||n===void 0||n.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new mRt(this.uri,this.opts);const n=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const i=R_(n,"open",function(){r.onopen(),e&&e()}),o=u=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",u),e?e(u):this.maybeReconnectOnOpen()},l=R_(n,"error",o);if(this._timeout!==!1){const u=this._timeout,d=this.setTimeoutFn(()=>{i(),o(new Error("timeout")),n.close()},u);this.opts.autoUnref&&d.unref(),this.subs.push(()=>{this.clearTimeoutFn(d)})}return this.subs.push(i),this.subs.push(l),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(R_(e,"ping",this.onping.bind(this)),R_(e,"data",this.ondata.bind(this)),R_(e,"error",this.onerror.bind(this)),R_(e,"close",this.onclose.bind(this)),R_(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(n){this.onclose("parse error",n)}}ondecoded(e){CRe(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,n){let r=this.nsps[e];return r?this._autoConnect&&!r.active&&r.connect():(r=new fRt(this,e,n),this.nsps[e]=r),r}_destroy(e){const n=Object.keys(this.nsps);for(const r of n)if(this.nsps[r].active)return;this._close()}_packet(e){const n=this.encoder.encode(e);for(let r=0;r<n.length;r++)this.engine.write(n[r],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close"),this.engine&&this.engine.close()}disconnect(){return this._close()}onclose(e,n){this.cleanup(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,n),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const n=this.backoff.duration();this._reconnecting=!0;const r=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(i=>{i?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",i)):e.onreconnect()}))},n);this.opts.autoUnref&&r.unref(),this.subs.push(()=>{this.clearTimeoutFn(r)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const lG={};function hle(t,e){typeof t=="object"&&(e=t,t=void 0),e=e||{};const n=A8r(t,e.path||"/socket.io"),r=n.source,i=n.id,o=n.path,l=lG[i]&&o in lG[i].nsps,u=e.forceNew||e["force new connection"]||e.multiplex===!1||l;let d;return u?d=new NRe(r,e):(lG[i]||(lG[i]=new NRe(r,e)),d=lG[i]),n.query&&!e.query&&(e.query=n.queryKey),d.socket(n.path,e)}Object.assign(hle,{Manager:NRe,Socket:fRt,io:hle,connect:hle});var ARt=(t,e)=>t===e?!0:!t||!e||t.length!==e.length?!1:t.every((n,r)=>n===e[r]),RRe=(t,e)=>ARt(t,e)||!t&&e?.length===0||t?.length===0&&!e,B8r=(t,e)=>{const n=Array.isArray(t)?t:t?[t]:[],r=Array.isArray(e)?e:e?[e]:[];return ARt(n,r)},bRt=(t,e)=>{if(!t&&!e)return!0;if(!t||!e)return!1;try{return JSON.stringify(t)===JSON.stringify(e)}catch{return!1}},fle=(t,e)=>bRt(t.data,e.data)&&RRe(t.tags,e.tags)&&t.read===e.read&&t.archived===e.archived&&t.snoozed===e.snoozed&&t.seen===e.seen&&B8r(t.severity,e.severity);function D8r(t,e){return!e||Object.keys(e).length===0?!0:t?Object.entries(e).every(([n,r])=>{const i=t[n];if(i===void 0&&r!==void 0)return!1;if(Array.isArray(r))if(Array.isArray(i)){if(r.length!==i.length)return!1;const o=[...r].sort(),l=[...i].sort();return o.every((u,d)=>u===l[d])}else return r.includes(i);else return i===r}):!1}function N8r(t,e){return!e||e.length===0?!0:!t||t.length===0?!1:e.some(n=>t.includes(n))}function R8r(t,e){return!(e.read!==void 0&&t.isRead!==e.read||e.seen!==void 0&&t.isSeen!==e.seen||e.archived!==void 0&&t.isArchived!==e.archived||e.snoozed!==void 0&&t.isSnoozed!==e.snoozed)}function L8r(t,e){return R8r(t,e)&&N8r(t.tags,e.tags)&&D8r(t.data,e.data)}var vT,_T,t3,n3,cG,uG=class{constructor(t,e,n,r,i){Wa(this,vT),Wa(this,_T),Wa(this,t3),Wa(this,n3),Wa(this,cG,!1);var o;gi(this,vT,e),gi(this,_T,n),gi(this,t3,r),gi(this,n3,i),this.id=t.id,this.identifier=t.identifier,this.topicKey=t.topicKey,this.preferences=(o=t.preferences)==null?void 0:o.map(l=>new dG(bi({},l),nn(this,vT),nn(this,_T),nn(this,t3),nn(this,n3)))}update(t){return Lr(this,null,function*(){return yRt({emitter:nn(this,vT),apiService:nn(this,_T),cache:nn(this,t3),useCache:nn(this,n3),args:kc(bi({},t),{subscription:this})})})}updatePreference(t){return Lr(this,null,function*(){return nn(this,cG)?{error:new ho("Cannot update a deleted subscription",new Error("Subscription is stale"))}:vRt({emitter:nn(this,vT),apiService:nn(this,_T),cache:nn(this,t3),useCache:nn(this,n3),args:kc(bi({},t),{subscriptionId:this.identifier})})})}bulkUpdatePreferences(t){return Lr(this,null,function*(){return nn(this,cG)?{error:new ho("Cannot bulk update a deleted subscription",new Error("Subscription is stale"))}:F8r({emitter:nn(this,vT),apiService:nn(this,_T),cache:nn(this,t3),useCache:nn(this,n3),args:t.map(e=>kc(bi({},e),{subscriptionId:this.identifier}))})})}delete(){return Lr(this,null,function*(){return nn(this,cG)?{error:new ho("Cannot delete an already deleted subscription",new Error("Subscription is stale"))}:_Rt({emitter:nn(this,vT),apiService:nn(this,_T),args:{subscription:this}})})}};vT=new WeakMap,_T=new WeakMap,t3=new WeakMap,n3=new WeakMap,cG=new WeakMap;var M8r=t=>Lr(void 0,[t],function*({emitter:e,apiService:n,cache:r,options:i,args:o}){try{const{useCache:l,refetch:u}=i;let d=l&&!u?r.getAll(o):void 0;return e.emit("subscriptions.list.pending",{args:o,data:d}),(!d||u)&&(d=(yield n.fetchSubscriptions(o.topicKey)).map(m=>new uG(kc(bi({},m),{topicKey:o.topicKey}),e,n,r,l)),l&&(r.set(o,d),d=r.getAll(o))),e.emit("subscriptions.list.resolved",{args:o,data:d}),{data:d}}catch(l){return e.emit("subscriptions.list.resolved",{args:o,error:l}),{error:new ho("Failed to fetch subscriptions",l)}}}),P8r=t=>Lr(void 0,[t],function*({emitter:e,apiService:n,cache:r,options:i,args:o}){try{const{useCache:l,refetch:u}=i;let d=l&&!u?r.get(o):void 0;if(e.emit("subscription.get.pending",{args:o,data:d}),!d||u){const p=yield n.getSubscription(o.topicKey,o.identifier,o.workflowIds,o.tags);if(!p)return e.emit("subscription.get.resolved",{args:o,data:null}),{data:null};d=new uG(kc(bi({},p),{topicKey:o.topicKey}),e,n,r,l),l&&(r.setOne(o,d),d=r.get(o))}return e.emit("subscription.get.resolved",{args:o,data:d}),{data:d}}catch(l){return e.emit("subscription.get.resolved",{args:o,error:l}),{error:new ho("Failed to fetch subscription",l)}}}),O8r=t=>Lr(void 0,[t],function*({emitter:e,apiService:n,cache:r,useCache:i,args:o}){var l;try{e.emit("subscription.create.pending",{args:o});const u=yield n.createSubscription({identifier:(l=o.identifier)!=null?l:"",name:o.name,topicKey:o.topicKey,topicName:o.topicName,preferences:o.preferences}),d=new uG(kc(bi({},u),{topicKey:o.topicKey}),e,n,r,i);return e.emit("subscription.create.resolved",{args:o,data:d}),{data:d}}catch(u){return e.emit("subscription.create.resolved",{args:o,error:u}),{error:new ho("Failed to create subscription",u)}}}),yRt=t=>Lr(void 0,[t],function*({emitter:e,apiService:n,cache:r,useCache:i,args:o}){const l="identifier"in o?o.identifier:o.subscription.identifier,u="topicKey"in o?o.topicKey:o.subscription.topicKey;try{e.emit("subscription.update.pending",{args:o});const d=yield n.updateSubscription({topicKey:u,identifier:l,name:o.name,preferences:o.preferences}),p=new uG(kc(bi({},d),{topicKey:u}),e,n,r,i);return e.emit("subscription.update.resolved",{args:o,data:p}),{data:p}}catch(d){return e.emit("subscription.update.resolved",{args:o,error:d}),{error:new ho("Failed to update subscription",d)}}}),vRt=t=>Lr(void 0,[t],function*({emitter:e,apiService:n,cache:r,useCache:i,args:o}){var l,u;const d="workflowId"in o?o.workflowId:(u=(l=o.preference)==null?void 0:l.workflow)==null?void 0:u.id;try{e.emit("subscription.preference.update.pending",{args:o,data:"preference"in o?new dG(bi(bi({},o.preference),typeof o.value=="boolean"?{enabled:o.value}:{condition:o.value}),e,n,r,i):void 0});const p=yield n.updateSubscriptionPreference(bi({subscriptionIdentifier:o.subscriptionId,workflowId:d},typeof o.value=="boolean"?{enabled:o.value,email:o.value,sms:o.value,in_app:o.value,chat:o.value,push:o.value}:{condition:o.value})),m=new dG(bi({},p),e,n,r,i);return e.emit("subscription.preference.update.resolved",{args:o,data:m}),{data:m}}catch(p){return e.emit("subscription.preference.update.resolved",{args:o,error:p}),{error:new ho("Failed to update subscription",p)}}}),F8r=t=>Lr(void 0,[t],function*({emitter:e,apiService:n,cache:r,useCache:i,args:o}){try{const l=o.map(m=>"preference"in m?new dG(bi(bi({},m.preference),typeof m.value=="boolean"?{enabled:m.value}:{condition:m.value}),e,n,r,i):void 0).filter(m=>m!==void 0);e.emit("subscription.preferences.bulk_update.pending",{args:o,data:l});const u=o.map(m=>{var g,h,A,b,y,v;return bi({subscriptionIdentifier:m.subscriptionId,workflowId:"workflowId"in m?m.workflowId:(v=(y=(h=(g=m.preference)==null?void 0:g.workflow)==null?void 0:h.id)!=null?y:(b=(A=m.preference)==null?void 0:A.workflow)==null?void 0:b.identifier)!=null?v:""},typeof m.value=="boolean"?{enabled:m.value,email:m.value,sms:m.value,in_app:m.value,chat:m.value,push:m.value}:{condition:m.value})}),p=(yield n.bulkUpdateSubscriptionPreferences(u)).map(m=>new dG(m,e,n,r,i));return e.emit("subscription.preferences.bulk_update.resolved",{args:o,data:p}),{data:p}}catch(l){return e.emit("subscription.preferences.bulk_update.resolved",{args:o,error:l}),{error:new ho("Failed to bulk update subscription preferences",l)}}}),_Rt=t=>Lr(void 0,[t],function*({emitter:e,apiService:n,args:r}){const i="identifier"in r?r.identifier:r.subscription.identifier,o="topicKey"in r?r.topicKey:r.subscription.topicKey;try{return e.emit("subscription.delete.pending",{args:r}),yield n.deleteSubscription({topicKey:o,identifier:i}),e.emit("subscription.delete.resolved",{args:r}),{data:void 0}}catch(l){return e.emit("subscription.delete.resolved",{args:r,error:l}),{error:new ho("Failed to delete subscription",l)}}}),Ale,ble,yle,vle,dG=class{constructor(t,e,n,r,i){Wa(this,Ale),Wa(this,ble),Wa(this,yle),Wa(this,vle);var o;gi(this,Ale,e),gi(this,ble,n),gi(this,yle,r),gi(this,vle,i),this.enabled=t.enabled,this.condition=(o=t.condition)!=null?o:void 0,this.workflow=t.workflow,this.subscriptionId=t.subscriptionId}update(t){return Lr(this,null,function*(){var e;return vRt({emitter:nn(this,Ale),apiService:nn(this,ble),cache:nn(this,yle),useCache:nn(this,vle),args:{subscriptionId:this.subscriptionId,workflowId:(e=this.workflow)==null?void 0:e.id,value:t.value,preference:this}})})}};Ale=new WeakMap,ble=new WeakMap,yle=new WeakMap,vle=new WeakMap;var r3,pG,fF=class{constructor({inboxServiceInstance:t,eventEmitterInstance:e}){Wa(this,r3,[]),Wa(this,pG),this._emitter=e,this._inboxService=t,this._emitter.on("session.initialize.resolved",({error:n,data:r})=>{r?(this.onSessionSuccess(r),nn(this,r3).forEach(i=>Lr(this,[i],function*({fn:o,resolve:l}){l(yield o())})),gi(this,r3,[])):n&&(this.onSessionError(n),gi(this,pG,n),nn(this,r3).forEach(({resolve:i})=>{i({error:new ho("Failed to initialize session, please contact the support",n)})}),gi(this,r3,[]))})}onSessionSuccess(t){}onSessionError(t){}callWithSession(t){return Lr(this,null,function*(){return this._inboxService.isSessionInitialized?t():nn(this,pG)?Promise.resolve({error:new ho("Failed to initialize session, please contact the support",nn(this,pG))}):new Promise((e,n)=>{nn(this,r3).push({fn:t,resolve:e,reject:n})})})}};r3=new WeakMap,pG=new WeakMap;var uk,mG=class{constructor(){Wa(this,uk),gi(this,uk,new Map)}get(t){return nn(this,uk).get(t)}getValues(){return Array.from(nn(this,uk).values())}entries(){return Array.from(nn(this,uk).entries())}keys(){return Array.from(nn(this,uk).keys())}set(t,e){nn(this,uk).set(t,e)}remove(t){nn(this,uk).delete(t)}clear(){nn(this,uk).clear()}};uk=new WeakMap;var a3=t=>`list:${t.topicKey}`,wRt=t=>t.split(":")[1],wT=t=>`item:${t.topicKey}:${t.identifier}`,Nh,Ld,_le,gp,wle,Q8r=class{constructor({emitterInstance:t,inboxServiceInstance:e,useCache:n}){Wa(this,Nh),Wa(this,Ld),Wa(this,_le),Wa(this,gp),Wa(this,wle),this.handleCreate=r=>{const i=a3({topicKey:r.topicKey}),o=nn(this,Ld).get(i);if(o){const l=[...o,r];nn(this,Ld).set(i,l),nn(this,Nh).emit("subscriptions.list.updated",{data:{topicKey:r.topicKey,subscriptions:l}})}nn(this,gp).set(wT({topicKey:r.topicKey,identifier:r.identifier}),r)},this.handleUpdate=r=>{const i=a3({topicKey:r.topicKey}),o=nn(this,Ld).get(i);if(o){const l=o.map(u=>u.id===r.id?r:u);nn(this,Ld).set(i,l),nn(this,Nh).emit("subscriptions.list.updated",{data:{topicKey:r.topicKey,subscriptions:l}})}nn(this,gp).set(wT({topicKey:r.topicKey,identifier:r.identifier}),r)},this.handlePreferenceUpdate=r=>{this.updateSubscriptionPreferences([r])},this.handleBulkPreferenceUpdate=r=>{this.updateSubscriptionPreferences(r)},this.updateSubscriptionPreferences=r=>{var i;const o=new Map;for(const d of r){const p=(i=o.get(d.subscriptionId))!=null?i:[];p.push(d),o.set(d.subscriptionId,p)}const l=nn(this,Ld).keys();for(const d of l){const p=nn(this,Ld).get(d);if(!p)continue;let m=!1;const g=p.map(h=>{const A=o.get(h.id);return A?(m=!0,this.createUpdatedSubscription(h,A)):h});m&&(nn(this,Ld).set(d,g),nn(this,Nh).emit("subscriptions.list.updated",{data:{topicKey:wRt(d),subscriptions:g}}))}const u=nn(this,gp).keys();for(const d of u){const p=nn(this,gp).get(d);if(!p)continue;const m=o.get(p.id);if(m){const g=this.createUpdatedSubscription(p,m);nn(this,gp).set(d,g),nn(this,Nh).emit("subscription.update.resolved",{args:{subscription:p},data:g})}}},this.createUpdatedSubscription=(r,i)=>{var o;const l=(o=r.preferences)==null?void 0:o.map(u=>{const d=i.find(p=>p.workflow.id===u.workflow.id);return d||u});return new uG({id:r.id,identifier:r.identifier,topicKey:r.topicKey,preferences:l},nn(this,Nh),nn(this,wle),this,nn(this,_le))},this.handleDelete=r=>{const i=a3({topicKey:r.topicKey}),o=nn(this,Ld).get(i);if(o){const l=o.filter(u=>u.id!==r.id);nn(this,Ld).set(i,l),nn(this,Nh).emit("subscriptions.list.updated",{data:{topicKey:r.topicKey,subscriptions:l}})}nn(this,gp).remove(wT({topicKey:r.topicKey,identifier:r.identifier}))},this.handleDeleteByIdentifier=r=>{const i=nn(this,Ld).keys();for(const l of i){const u=nn(this,Ld).get(l);if(u){const d=u.find(p=>p.identifier===r);if(d){const p=u.filter(m=>m.identifier!==r);nn(this,Ld).set(l,p),nn(this,Nh).emit("subscriptions.list.updated",{data:{topicKey:wRt(l),subscriptions:p}}),nn(this,gp).remove(wT({topicKey:d.topicKey,identifier:d.identifier}));return}}}const o=nn(this,gp).keys();for(const l of o){const u=nn(this,gp).get(l);if(u&&u.identifier===r){nn(this,gp).remove(l);return}}},gi(this,Nh,t),gi(this,Ld,new mG),gi(this,gp,new mG),gi(this,wle,e),gi(this,_le,n),nn(this,Nh).on("subscription.create.resolved",({data:r})=>{r&&this.handleCreate(r)}),nn(this,Nh).on("subscription.update.resolved",({data:r})=>{r&&this.handleUpdate(r)}),nn(this,Nh).on("subscription.delete.resolved",({args:r})=>{"subscription"in r?this.handleDelete(r.subscription):"identifier"in r&&this.handleDeleteByIdentifier(r.identifier)}),nn(this,Nh).on("subscription.preference.update.pending",({data:r})=>{r&&this.handlePreferenceUpdate(r)}),nn(this,Nh).on("subscription.preference.update.resolved",({data:r})=>{r&&this.handlePreferenceUpdate(r)}),nn(this,Nh).on("subscription.preferences.bulk_update.resolved",({data:r})=>{r&&r.length>0&&this.handleBulkPreferenceUpdate(r)})}has(t){return nn(this,Ld).get(a3(t))!==void 0}set(t,e){nn(this,Ld).set(a3(t),e);for(const n of e)nn(this,gp).set(wT({topicKey:t.topicKey,identifier:n.identifier}),n)}setOne(t,e){nn(this,gp).set(wT(t),e)}getAll(t){return nn(this,Ld).get(a3(t))}get(t){return nn(this,gp).get(wT(t))}invalidate(t){const e=a3({topicKey:t.topicKey}),n=nn(this,Ld).get(e);if(n)for(const i of n)nn(this,gp).remove(wT({topicKey:t.topicKey,identifier:i.identifier}));nn(this,Ld).remove(e);const r=nn(this,gp).keys();for(const i of r)i.startsWith(`item:${t.topicKey}:`)&&nn(this,gp).remove(i)}clearAll(){nn(this,Ld).clear(),nn(this,gp).clear()}};Nh=new WeakMap,Ld=new WeakMap,_le=new WeakMap,gp=new WeakMap,wle=new WeakMap;var i3,xle,kle,$8r=class extends fF{constructor({useCache:t,inboxServiceInstance:e,eventEmitterInstance:n,subscriber:r,contextKey:i}){super({eventEmitterInstance:n,inboxServiceInstance:e}),Wa(this,i3),Wa(this,xle),Wa(this,kle),this.cache=new Q8r({emitterInstance:this._emitter,inboxServiceInstance:this._inboxService,useCache:t}),gi(this,i3,t),gi(this,xle,r),gi(this,kle,i)}list(t,e){return Lr(this,null,function*(){return this.callWithSession(()=>{var n;return M8r({emitter:this._emitter,apiService:this._inboxService,cache:this.cache,options:kc(bi({},e),{useCache:(n=e?.useCache)!=null?n:nn(this,i3)}),args:t})})})}get(t,e){return Lr(this,null,function*(){return this.callWithSession(()=>{var n,r;return P8r({emitter:this._emitter,apiService:this._inboxService,cache:this.cache,options:kc(bi({},e),{useCache:(n=e?.useCache)!=null?n:nn(this,i3)}),args:kc(bi({},t),{identifier:(r=t.identifier)!=null?r:SFr({topicKey:t.topicKey,subscriberId:nn(this,xle).subscriberId,contextKey:nn(this,kle)})})})})})}create(t){return Lr(this,null,function*(){return this.callWithSession(()=>O8r({emitter:this._emitter,apiService:this._inboxService,cache:this.cache,useCache:nn(this,i3),args:t}))})}update(t){return Lr(this,null,function*(){return this.callWithSession(()=>yRt({emitter:this._emitter,apiService:this._inboxService,cache:this.cache,useCache:nn(this,i3),args:t}))})}delete(t){return Lr(this,null,function*(){return this.callWithSession(()=>_Rt({emitter:this._emitter,apiService:this._inboxService,args:t}))})}};i3=new WeakMap,xle=new WeakMap,kle=new WeakMap;var j8r="v1",xRt="@novu/js@3.13.0",z8r=class{constructor(t={}){this.DEFAULT_BACKEND_URL=typeof window<"u"&&window.NOVU_LOCAL_BACKEND_URL||"https://api.novu.co";const{apiVersion:e=j8r,apiUrl:n=this.DEFAULT_BACKEND_URL,userAgent:r=xRt,headers:i={}}=t||{};this.apiVersion=e,this.apiUrl=`${n}/${e}`,this.headers=bi({"Novu-API-Version":"2024-06-26","Novu-Client-Version":xRt,"Content-Type":"application/json","User-Agent":r},i)}setAuthorizationToken(t){this.headers.Authorization=`Bearer ${t}`}setKeylessHeader(t){var e;const n=t||typeof window<"u"&&((e=window.localStorage)==null?void 0:e.getItem("novu_keyless_application_identifier"));!n||!n.startsWith("pk_keyless_")||(this.headers["Novu-Application-Identifier"]=n)}setHeaders(t){this.headers=bi(bi({},this.headers),t)}get(t,e,n=!0){return Lr(this,null,function*(){return this.doFetch({path:t,searchParams:e,options:{method:"GET"},unwrapEnvelope:n})})}post(t,e,n){return Lr(this,null,function*(){return this.doFetch({path:t,options:{method:"POST",body:e,headers:n?.headers}})})}patch(t,e){return Lr(this,null,function*(){return this.doFetch({path:t,options:{method:"PATCH",body:e}})})}delete(t,e){return Lr(this,null,function*(){return this.doFetch({path:t,options:{method:"DELETE",body:e}})})}doFetch(t){return Lr(this,arguments,function*({path:e,searchParams:n,options:r,unwrapEnvelope:i=!0}){const o=U8r(this.apiUrl,e,n?`?${n.toString()}`:""),l={method:r?.method||"GET",headers:bi(bi({},this.headers),r?.headers||{}),body:r?.body?JSON.stringify(r.body):void 0},u=yield fetch(o,l);if(!u.ok){const p=yield u.json();throw new Error(`${this.headers["Novu-Client-Version"]} error. Status: ${u.status}, Message: ${p.message}`)}if(u.status===204)return;const d=yield u.json();return i?d.data:d})}};function U8r(...t){return t.reduce((e,n)=>(n&&e.push(n.replace(new RegExp("(?<!https?:)\\/+","g"),"/").replace(/^\/+|\/+$/g,"")),e),[]).join("/").replace(/\/\?/,"?")}var WA="/inbox",Rh=`${WA}/notifications`,Fo,q8r=class{constructor(t={}){this.isSessionInitialized=!1,Wa(this,Fo),gi(this,Fo,new z8r(t))}initializeSession(t){return Lr(this,arguments,function*({applicationIdentifier:e,subscriberHash:n,contextHash:r,subscriber:i,defaultSchedule:o,context:l}){const u=yield nn(this,Fo).post(`${WA}/session`,{applicationIdentifier:e,subscriberHash:n,contextHash:r,subscriber:i,defaultSchedule:o,context:l});return nn(this,Fo).setAuthorizationToken(u.token),nn(this,Fo).setKeylessHeader(u.applicationIdentifier),this.isSessionInitialized=!0,u})}fetchNotifications({after:t,archived:e,limit:n=10,offset:r,read:i,tags:o,snoozed:l,seen:u,data:d,severity:p}){const m=new URLSearchParams(`limit=${n}`);if(t&&m.append("after",t),r&&m.append("offset",`${r}`),o)for(const g of o)m.append("tags[]",g);if(i!==void 0&&m.append("read",`${i}`),e!==void 0&&m.append("archived",`${e}`),l!==void 0&&m.append("snoozed",`${l}`),u!==void 0&&m.append("seen",`${u}`),d!==void 0&&m.append("data",JSON.stringify(d)),p&&Array.isArray(p))for(const g of p)m.append("severity[]",g);else p&&m.append("severity",p);return nn(this,Fo).get(Rh,m,!1)}count({filters:t}){return nn(this,Fo).get(`${Rh}/count`,new URLSearchParams({filters:JSON.stringify(t)}),!1)}read(t){return nn(this,Fo).patch(`${Rh}/${t}/read`)}unread(t){return nn(this,Fo).patch(`${Rh}/${t}/unread`)}archive(t){return nn(this,Fo).patch(`${Rh}/${t}/archive`)}unarchive(t){return nn(this,Fo).patch(`${Rh}/${t}/unarchive`)}snooze(t,e){return nn(this,Fo).patch(`${Rh}/${t}/snooze`,{snoozeUntil:e})}unsnooze(t){return nn(this,Fo).patch(`${Rh}/${t}/unsnooze`)}readAll({tags:t,data:e}){return nn(this,Fo).post(`${Rh}/read`,{tags:t,data:e?JSON.stringify(e):void 0})}archiveAll({tags:t,data:e}){return nn(this,Fo).post(`${Rh}/archive`,{tags:t,data:e?JSON.stringify(e):void 0})}archiveAllRead({tags:t,data:e}){return nn(this,Fo).post(`${Rh}/read-archive`,{tags:t,data:e?JSON.stringify(e):void 0})}delete(t){return nn(this,Fo).delete(`${Rh}/${t}/delete`)}deleteAll({tags:t,data:e}){return nn(this,Fo).post(`${Rh}/delete`,{tags:t,data:e?JSON.stringify(e):void 0})}markAsSeen({notificationIds:t,tags:e,data:n}){return nn(this,Fo).post(`${Rh}/seen`,{notificationIds:t,tags:e,data:n?JSON.stringify(n):void 0})}seen(t){return this.markAsSeen({notificationIds:[t]})}completeAction({actionType:t,notificationId:e}){return nn(this,Fo).patch(`${Rh}/${e}/complete`,{actionType:t})}revertAction({actionType:t,notificationId:e}){return nn(this,Fo).patch(`${Rh}/${e}/revert`,{actionType:t})}fetchPreferences({tags:t,severity:e,criticality:n}){const r=new URLSearchParams;if(t)for(const o of t)r.append("tags[]",o);if(e&&Array.isArray(e))for(const o of e)r.append("severity[]",o);else e&&r.append("severity",e);n&&r.append("criticality",n);const i=r.size?`?${r.toString()}`:"";return nn(this,Fo).get(`${WA}/preferences${i}`)}bulkUpdatePreferences(t){return nn(this,Fo).patch(`${WA}/preferences/bulk`,{preferences:t})}updateGlobalPreferences(t){return nn(this,Fo).patch(`${WA}/preferences`,t)}updateWorkflowPreferences({workflowId:t,channels:e}){return nn(this,Fo).patch(`${WA}/preferences/${t}`,e)}fetchGlobalPreferences(){return nn(this,Fo).get(`${WA}/preferences/global`)}triggerHelloWorldEvent(){const t={name:"hello-world",to:{subscriberId:"keyless-subscriber-id"},payload:{subject:"Novu Keyless Environment",body:"You're using a keyless demo environment. For full access to Novu features and cloud integration, obtain your API key.",primaryActionText:"Obtain API Key",primaryActionUrl:"https://go.novu.co/keyless",secondaryActionText:"Explore Documentation",secondaryActionUrl:"https://go.novu.co/keyless-docs"}};return nn(this,Fo).post("/inbox/events",t)}fetchSubscriptions(t){return nn(this,Fo).get(`${WA}/topics/${t}/subscriptions`)}getSubscription(t,e,n,r){const i=new URLSearchParams;if(n?.length)for(const l of n)i.append("workflowIds",l);if(r?.length)for(const l of r)i.append("tags",l);const o=i.size?`?${i.toString()}`:"";return nn(this,Fo).get(`${WA}/topics/${t}/subscriptions/${e}${o}`)}createSubscription({identifier:t,name:e,topicKey:n,topicName:r,preferences:i}){return nn(this,Fo).post(`${WA}/topics/${n}/subscriptions`,bi(bi({identifier:t,name:e},r&&{topic:{name:r}}),i!==void 0&&{preferences:i}))}updateSubscription({topicKey:t,identifier:e,name:n,preferences:r}){return nn(this,Fo).patch(`${WA}/topics/${t}/subscriptions/${e}`,bi({name:n},r!==void 0&&{preferences:r}))}updateSubscriptionPreference({subscriptionIdentifier:t,workflowId:e,enabled:n,condition:r,email:i,sms:o,in_app:l,chat:u,push:d}){return nn(this,Fo).patch(`${WA}/subscriptions/${t}/preferences/${e}`,{enabled:n,condition:r,email:i,sms:o,in_app:l,chat:u,push:d})}bulkUpdateSubscriptionPreferences(t){return nn(this,Fo).patch(`${WA}/preferences/bulk`,{preferences:t})}deleteSubscription({topicKey:t,identifier:e}){return nn(this,Fo).delete(`${WA}/topics/${t}/subscriptions/${e}`)}};Fo=new WeakMap;var AF,G8r=class{constructor(){Wa(this,AF),gi(this,AF,RFr())}on(t,e){return nn(this,AF).on(t,e),()=>{this.off(t,e)}}off(t,e){nn(this,AF).off(t,e)}emit(t,e){nn(this,AF).emit(t,e)}};AF=new WeakMap;var kRt=({tags:t,data:e,read:n,archived:r,snoozed:i,seen:o,severity:l,limit:u,offset:d,after:p})=>Object.entries({tags:t,data:e,read:n,archived:r,snoozed:i,seen:o,severity:l,limit:u,offset:d,after:p}).filter(([m,g])=>g!=null&&!(Array.isArray(g)&&g.length===0)).reduce((m,[g,h])=>(m[g]=h,m),{}),gG=({tags:t,data:e,read:n,archived:r,snoozed:i,seen:o,severity:l,limit:u,offset:d,after:p})=>JSON.stringify(kRt({tags:t,data:e,read:n,archived:r,snoozed:i,seen:o,severity:l,limit:u,offset:d,after:p})),H8r=({tags:t,data:e,read:n,archived:r,snoozed:i,seen:o,severity:l})=>JSON.stringify(kRt({tags:t,data:e,read:n,archived:r,snoozed:i,seen:o,severity:l})),s3=t=>JSON.parse(t),W8r=["notification.read.pending","notification.read.resolved","notification.unread.pending","notification.unread.resolved","notification.complete_action.pending","notification.complete_action.resolved","notification.revert_action.pending","notification.revert_action.resolved","notifications.read_all.pending","notifications.read_all.resolved"],Y8r=["notification.archive.pending","notification.unarchive.pending","notification.snooze.pending","notification.unsnooze.pending","notification.delete.pending","notifications.archive_all.pending","notifications.archive_all_read.pending","notifications.delete_all.pending"],xT,Ele,Md,V8r=class{constructor({emitter:t,inboxService:e}){Wa(this,xT),Wa(this,Ele),Wa(this,Md),this.updateNotification=(n,r)=>{const i=nn(this,Md).get(n);if(!i)return!1;const o=i.notifications.findIndex(u=>u.id===r.id);if(o===-1)return!1;const l=[...i.notifications];return l[o]=r,nn(this,Md).set(n,kc(bi({},i),{notifications:l})),!0},this.removeNotification=(n,r)=>{const i=nn(this,Md).get(n);if(!i)return!1;const o=i.notifications.findIndex(u=>u.id===r.id);if(o===-1)return!1;const l=[...i.notifications];return l.splice(o,1),nn(this,Md).set(n,kc(bi({},i),{notifications:l})),!0},this.handleNotificationEvent=({remove:n}={remove:!1})=>r=>{const{data:i,args:o}=r;let l=[];if(i!=null)Array.isArray(i)&&i.every(d=>typeof d=="object"&&"id"in d)?l=i:typeof i=="object"&&"id"in i&&(l=[i]);else if(n&&o){if("notification"in o&&o.notification)l=[o.notification];else if("notificationId"in o&&o.notificationId){const d=[];nn(this,Md).keys().forEach(p=>{const m=nn(this,Md).get(p);if(m){const g=m.notifications.find(h=>h.id===o.notificationId);g&&d.push(g)}}),l=d}}if(l.length===0)return;const u=new Set;nn(this,Md).keys().forEach(d=>{l.forEach(p=>{let m=!1;n?m=this.removeNotification(d,p):m=this.updateNotification(d,p),m&&u.add(H8r(s3(d)))})}),u.forEach(d=>{const p=this.getAggregated(s3(d));nn(this,xT).emit("notifications.list.updated",{data:p})})},gi(this,xT,t),gi(this,Ele,e),W8r.forEach(n=>{nn(this,xT).on(n,this.handleNotificationEvent())}),Y8r.forEach(n=>{nn(this,xT).on(n,this.handleNotificationEvent({remove:!0}))}),gi(this,Md,new mG)}getAggregated(t){return nn(this,Md).keys().filter(n=>{const r=s3(n);return fle(r,t)}).map(n=>nn(this,Md).get(n)).reduce((n,r)=>r?{hasMore:r.hasMore,filter:r.filter,notifications:[...n.notifications,...r.notifications]}:n,{hasMore:!1,filter:{},notifications:[]})}get(t){return nn(this,Md).get(gG(t))}has(t){return nn(this,Md).get(gG(t))!==void 0}set(t,e){nn(this,Md).set(gG(t),e)}unshift(t,e){const n=gG(t),r=nn(this,Md).get(n)||{hasMore:!1,filter:s3(n),notifications:[]},i=NFr({notification:bi({},e),emitter:nn(this,xT),inboxService:nn(this,Ele)});this.update(t,kc(bi({},r),{notifications:[i,...r.notifications]}))}update(t,e){this.set(t,e);const n=this.getAggregated(s3(gG(t)));nn(this,xT).emit("notifications.list.updated",{data:n})}getAll(t){if(this.has(t))return this.getAggregated({tags:t.tags,data:t.data,read:t.read,snoozed:t.snoozed,archived:t.archived,seen:t.seen,severity:t.severity})}getUniqueNotifications({tags:t,read:e,data:n}){const r=nn(this,Md).keys(),i=new Map;return r.forEach(o=>{const l=s3(o);if(RRe(t,l.tags)&&bRt(n,l.data)){const u=nn(this,Md).get(o);if(!u)return;u.notifications.filter(d=>typeof e>"u"||e===d.isRead).forEach(d=>{i.set(d.id,d)})}}),Array.from(i.values())}clear(t){nn(this,Md).keys().forEach(n=>{fle(s3(n),t)&&nn(this,Md).remove(n)})}clearAll(){nn(this,Md).clear()}};xT=new WeakMap,Ele=new WeakMap,Md=new WeakMap;var Cle,K8r=class extends fF{constructor({useCache:t,inboxServiceInstance:e,eventEmitterInstance:n}){super({eventEmitterInstance:n,inboxServiceInstance:e}),Wa(this,Cle),this.cache=new V8r({emitter:n,inboxService:e}),gi(this,Cle,t)}list(){return Lr(this,arguments,function*(t={}){var e=t,{limit:n=10}=e,r=CFr(e,["limit"]);return this.callWithSession(()=>Lr(this,null,function*(){const i=bi({limit:n},r);try{const o="useCache"in i?i.useCache:nn(this,Cle);let l=o?this.cache.getAll(i):void 0;if(this._emitter.emit("notifications.list.pending",{args:i,data:l}),!l){const u=yield this._inboxService.fetchNotifications(bi({limit:n},r));l={hasMore:u.hasMore,filter:u.filter,notifications:u.data.map(d=>new Mm(d,this._emitter,this._inboxService))},o&&(this.cache.set(i,l),l=this.cache.getAll(i))}return this._emitter.emit("notifications.list.resolved",{args:i,data:l}),{data:l}}catch(o){return this._emitter.emit("notifications.list.resolved",{args:i,error:o}),{error:new ho("Failed to fetch notifications",o)}}}))})}count(t){return Lr(this,null,function*(){return this.callWithSession(()=>Lr(this,null,function*(){const e=t&&"filters"in t?t.filters:[bi({},t)];try{this._emitter.emit("notifications.count.pending",{args:t});const n=yield this._inboxService.count({filters:e}),r=t&&"filters"in t?{counts:n.data}:n.data[0];return this._emitter.emit("notifications.count.resolved",{args:t,data:r}),{data:r}}catch(n){return this._emitter.emit("notifications.count.resolved",{args:t,error:n}),{error:new ho("Failed to count notifications",n)}}}))})}read(t){return Lr(this,null,function*(){return this.callWithSession(()=>Lr(this,null,function*(){return RNt({emitter:this._emitter,apiService:this._inboxService,args:t})}))})}unread(t){return Lr(this,null,function*(){return this.callWithSession(()=>Lr(this,null,function*(){return LNt({emitter:this._emitter,apiService:this._inboxService,args:t})}))})}seen(t){return Lr(this,null,function*(){return this.callWithSession(()=>Lr(this,null,function*(){return MNt({emitter:this._emitter,apiService:this._inboxService,args:t})}))})}archive(t){return Lr(this,null,function*(){return this.callWithSession(()=>Lr(this,null,function*(){return PNt({emitter:this._emitter,apiService:this._inboxService,args:t})}))})}unarchive(t){return Lr(this,null,function*(){return this.callWithSession(()=>Lr(this,null,function*(){return ONt({emitter:this._emitter,apiService:this._inboxService,args:t})}))})}delete(t){return Lr(this,null,function*(){return this.callWithSession(()=>Lr(this,null,function*(){return jNt({emitter:this._emitter,apiService:this._inboxService,args:t})}))})}snooze(t){return Lr(this,null,function*(){return this.callWithSession(()=>Lr(this,null,function*(){return FNt({emitter:this._emitter,apiService:this._inboxService,args:t})}))})}unsnooze(t){return Lr(this,null,function*(){return this.callWithSession(()=>Lr(this,null,function*(){return QNt({emitter:this._emitter,apiService:this._inboxService,args:t})}))})}completePrimary(t){return Lr(this,null,function*(){return this.callWithSession(()=>Lr(this,null,function*(){return ile({emitter:this._emitter,apiService:this._inboxService,args:t,actionType:"primary"})}))})}completeSecondary(t){return Lr(this,null,function*(){return this.callWithSession(()=>Lr(this,null,function*(){return ile({emitter:this._emitter,apiService:this._inboxService,args:t,actionType:"secondary"})}))})}revertPrimary(t){return Lr(this,null,function*(){return this.callWithSession(()=>Lr(this,null,function*(){return sle({emitter:this._emitter,apiService:this._inboxService,args:t,actionType:"primary"})}))})}revertSecondary(t){return Lr(this,null,function*(){return this.callWithSession(()=>Lr(this,null,function*(){return sle({emitter:this._emitter,apiService:this._inboxService,args:t,actionType:"secondary"})}))})}readAll(){return Lr(this,arguments,function*({tags:t,data:e}={}){return this.callWithSession(()=>Lr(this,null,function*(){return IFr({emitter:this._emitter,inboxService:this._inboxService,notificationsCache:this.cache,tags:t,data:e})}))})}seenAll(){return Lr(this,arguments,function*(t={}){return this.callWithSession(()=>Lr(this,null,function*(){return"notificationIds"in t?$Nt({emitter:this._emitter,inboxService:this._inboxService,notificationsCache:this.cache,notificationIds:t.notificationIds}):$Nt({emitter:this._emitter,inboxService:this._inboxService,notificationsCache:this.cache,tags:"tags"in t?t.tags:void 0,data:"data"in t?t.data:void 0})}))})}archiveAll(){return Lr(this,arguments,function*({tags:t,data:e}={}){return this.callWithSession(()=>Lr(this,null,function*(){return TFr({emitter:this._emitter,inboxService:this._inboxService,notificationsCache:this.cache,tags:t,data:e})}))})}archiveAllRead(){return Lr(this,arguments,function*({tags:t,data:e}={}){return this.callWithSession(()=>Lr(this,null,function*(){return BFr({emitter:this._emitter,inboxService:this._inboxService,notificationsCache:this.cache,tags:t,data:e})}))})}deleteAll(){return Lr(this,arguments,function*({tags:t,data:e}={}){return this.callWithSession(()=>Lr(this,null,function*(){return DFr({emitter:this._emitter,inboxService:this._inboxService,notificationsCache:this.cache,tags:t,data:e})}))})}clearCache({filter:t}={}){if(t){this.cache.clear(t??{});return}this.cache.clearAll()}triggerHelloWorldEvent(){return Lr(this,null,function*(){return this._inboxService.triggerHelloWorldEvent()})}};Cle=new WeakMap;var Sle,Ile,Tle,Ble,Dle=class{constructor(t,{emitterInstance:e,inboxServiceInstance:n,cache:r,useCache:i}){Wa(this,Sle),Wa(this,Ile),Wa(this,Tle),Wa(this,Ble),gi(this,Sle,e),gi(this,Ile,n),gi(this,Tle,r),gi(this,Ble,i),this.isEnabled=t.isEnabled,this.weeklySchedule=t.weeklySchedule}update(t){return Lr(this,null,function*(){var e;const n=!!t.weeklySchedule||!!this.weeklySchedule;return CRt({emitter:nn(this,Sle),apiService:nn(this,Ile),cache:nn(this,Tle),useCache:nn(this,Ble),args:bi({isEnabled:(e=t.isEnabled)!=null?e:this.isEnabled},n&&{weeklySchedule:bi(bi({},this.weeklySchedule),t.weeklySchedule)})})})}};Sle=new WeakMap,Ile=new WeakMap,Tle=new WeakMap,Ble=new WeakMap;var Nle,Rle,Lle,Mle,Ple,bF=class{constructor(t,{emitterInstance:e,inboxServiceInstance:n,cache:r,scheduleCache:i,useCache:o}){Wa(this,Nle),Wa(this,Rle),Wa(this,Lle),Wa(this,Mle),Wa(this,Ple),gi(this,Nle,e),gi(this,Rle,n),gi(this,Lle,r),gi(this,Mle,i),gi(this,Ple,o),this.level=t.level,this.enabled=t.enabled,this.channels=t.channels,this.workflow=t.workflow,this.schedule=new Dle(bi({},t.schedule),{emitterInstance:e,inboxServiceInstance:n,cache:i,useCache:o})}update({channels:t,channelPreferences:e}){var n;return ERt({emitter:nn(this,Nle),apiService:nn(this,Rle),cache:nn(this,Lle),scheduleCache:nn(this,Mle),useCache:nn(this,Ple),args:{workflowId:(n=this.workflow)==null?void 0:n.id,channels:t||e,preference:this}})}};Nle=new WeakMap,Rle=new WeakMap,Lle=new WeakMap,Mle=new WeakMap,Ple=new WeakMap;var ERt=t=>Lr(void 0,[t],function*({emitter:e,apiService:n,cache:r,scheduleCache:i,useCache:o,args:l}){var u;const{channels:d}=l,p="workflowId"in l?l.workflowId:(u=l.preference.workflow)==null?void 0:u.id;try{e.emit("preference.update.pending",{args:l,data:"preference"in l?new bF(kc(bi({},l.preference),{channels:bi(bi({},l.preference.channels),d)}),{emitterInstance:e,inboxServiceInstance:n,cache:r,scheduleCache:i,useCache:o}):void 0});let m;p?m=yield n.updateWorkflowPreferences({workflowId:p,channels:d}):(X8r({emitter:e,apiService:n,cache:r,scheduleCache:i,useCache:o,args:l}),m=yield n.updateGlobalPreferences(d));const g=new bF(m,{emitterInstance:e,inboxServiceInstance:n,cache:r,scheduleCache:i,useCache:o});return e.emit("preference.update.resolved",{args:l,data:g}),{data:g}}catch(m){return e.emit("preference.update.resolved",{args:l,error:m}),{error:new ho("Failed to update preference",m)}}}),Z8r=t=>Lr(void 0,[t],function*({emitter:e,apiService:n,cache:r,scheduleCache:i,useCache:o,args:l}){if(l.find(d=>"preference"in d&&d.preference.level==="global"))return{error:new ho("Global preference is not supported in bulk update","")};try{const d=l.map(h=>"preference"in h?new bF(kc(bi({},h.preference),{channels:bi(bi({},h.preference.channels),h.channels)}),{emitterInstance:e,inboxServiceInstance:n,cache:r,scheduleCache:i,useCache:o}):void 0).filter(h=>h!==void 0);e.emit("preferences.bulk_update.pending",{args:l,data:d});const p=l.map(h=>{var A,b,y,v;return bi({workflowId:"workflowId"in h?h.workflowId:(v=(y=(A=h.preference.workflow)==null?void 0:A.id)!=null?y:(b=h.preference.workflow)==null?void 0:b.identifier)!=null?v:""},h.channels)}),g=(yield n.bulkUpdatePreferences(p)).map(h=>new bF(h,{emitterInstance:e,inboxServiceInstance:n,cache:r,scheduleCache:i,useCache:o}));return e.emit("preferences.bulk_update.resolved",{args:l,data:g}),{data:g}}catch(d){return e.emit("preferences.bulk_update.resolved",{args:l,error:d}),{error:new ho("Failed to bulk update preferences",d)}}}),X8r=({emitter:t,apiService:e,cache:n,scheduleCache:r,useCache:i,args:o})=>{const l=i?n?.getAll({}):void 0;l?.forEach(u=>{var d,p;if(u.level==="template"){const m=kc(bi({},u),{channels:Object.entries(u.channels).reduce((h,[A,b])=>{var y;const v=A;return h[v]=(y=o.channels[v])!=null?y:b,h},{})}),g="preference"in o?new bF(m,{emitterInstance:t,inboxServiceInstance:e,cache:n,scheduleCache:r,useCache:i}):void 0;g&&t.emit("preference.update.pending",{args:{workflowId:(p=(d=u.workflow)==null?void 0:d.id)!=null?p:"",channels:g.channels},data:g})}})},CRt=t=>Lr(void 0,[t],function*({emitter:e,apiService:n,cache:r,useCache:i,args:o}){var l,u;try{const{isEnabled:d,weeklySchedule:p}=o,m=new Dle({isEnabled:d,weeklySchedule:p},{emitterInstance:e,inboxServiceInstance:n,cache:r,useCache:i});e.emit("preference.schedule.update.pending",{args:o,data:m});const g=yield n.updateGlobalPreferences({schedule:{isEnabled:d,weeklySchedule:p}}),h=new Dle({isEnabled:(l=g.schedule)==null?void 0:l.isEnabled,weeklySchedule:(u=g.schedule)==null?void 0:u.weeklySchedule},{emitterInstance:e,inboxServiceInstance:n,cache:r,useCache:i});return e.emit("preference.schedule.update.resolved",{args:o,data:h}),{data:h}}catch(d){return e.emit("preference.schedule.update.resolved",{args:o,error:d}),{error:new ho("Failed to update preference",d)}}}),o3,J8r=class extends fF{constructor({cache:t,useCache:e,inboxServiceInstance:n,eventEmitterInstance:r}){super({eventEmitterInstance:r,inboxServiceInstance:n}),Wa(this,o3),this.cache=t,gi(this,o3,e)}get(){return Lr(this,null,function*(){return this.callWithSession(()=>Lr(this,null,function*(){var t,e;try{let n=nn(this,o3)?this.cache.getAll():void 0;if(this._emitter.emit("preference.schedule.get.pending",{args:void 0,data:n}),!n){const r=yield this._inboxService.fetchGlobalPreferences();n=new Dle({isEnabled:(t=r?.schedule)==null?void 0:t.isEnabled,weeklySchedule:(e=r?.schedule)==null?void 0:e.weeklySchedule},{emitterInstance:this._emitter,inboxServiceInstance:this._inboxService,cache:this.cache,useCache:nn(this,o3)}),nn(this,o3)&&(this.cache.set(n),n=this.cache.getAll())}return this._emitter.emit("preference.schedule.get.resolved",{args:void 0,data:n}),{data:n}}catch(n){throw this._emitter.emit("preference.schedule.get.resolved",{args:void 0,error:n}),n}}))})}update(t){return Lr(this,null,function*(){return this.callWithSession(()=>CRt({emitter:this._emitter,apiService:this._inboxService,cache:this.cache,useCache:nn(this,o3),args:t}))})}};o3=new WeakMap;var e6r=["preference.update.pending","preference.update.resolved","preferences.bulk_update.pending","preferences.bulk_update.resolved"],t6r=["preference.schedule.update.pending","preference.schedule.update.resolved"],n6r=({tags:t,severity:e})=>Object.entries({tags:t,severity:e}).reduce((n,[r,i])=>(i==null||Array.isArray(i)&&i.length===0||(n[r]=i),n),{}),LRe=({tags:t,severity:e})=>JSON.stringify(n6r({tags:t,severity:e})),l3,Bg,r6r=class{constructor({emitterInstance:t}){Wa(this,l3),Wa(this,Bg),this.updatePreference=(e,n)=>{const r=nn(this,Bg).get(e);if(!r)return!1;const i=r.findIndex(l=>{var u,d;return((u=l.workflow)==null?void 0:u.id)===((d=n.workflow)==null?void 0:d.id)||l.level===n.level&&n.level==="global"});if(i===-1)return!1;const o=[...r];return o[i]=n,nn(this,Bg).set(e,o),!0},this.updatePreferenceSchedule=(e,n)=>{const r=nn(this,Bg).get(e);if(!r)return!1;const i=r.findIndex(l=>l.level==="global");if(i===-1)return!1;const o=[...r];return o[i].schedule=n,nn(this,Bg).set(e,o),!0},this.handleScheduleEvent=({data:e})=>{var n;if(!e)return;const r=nn(this,Bg).keys(),i=new Set;for(const o of r){const l=this.updatePreferenceSchedule(o,e),u=nn(this,Bg).get(o);!l||!u||i.add(o)}for(const o of i)nn(this,l3).emit("preferences.list.updated",{data:(n=nn(this,Bg).get(o))!=null?n:[]})},this.handlePreferenceEvent=({data:e})=>{if(!e)return;const n=Array.isArray(e)?e:[e],r=new Set;nn(this,Bg).keys().forEach(i=>{n.forEach(o=>{const l=this.updatePreference(i,o),u=nn(this,Bg).get(i);!l||!u||r.add(i)})}),r.forEach(i=>{var o;nn(this,l3).emit("preferences.list.updated",{data:(o=nn(this,Bg).get(i))!=null?o:[]})})},gi(this,l3,t);for(const e of e6r)nn(this,l3).on(e,this.handlePreferenceEvent);for(const e of t6r)nn(this,l3).on(e,this.handleScheduleEvent);gi(this,Bg,new mG)}has(t){return nn(this,Bg).get(LRe(t))!==void 0}set(t,e){nn(this,Bg).set(LRe(t),e)}getAll(t){if(this.has(t))return nn(this,Bg).get(LRe(t))}clearAll(){nn(this,Bg).clear()}};l3=new WeakMap,Bg=new WeakMap;var a6r=["preference.schedule.update.pending","preference.schedule.update.resolved"],MRe=()=>"schedule",hG,Ny,i6r=class{constructor({emitterInstance:t}){Wa(this,hG),Wa(this,Ny),this.updateScheduleInCache=(e,n)=>nn(this,Ny).get(e)?(nn(this,Ny).set(e,n),!0):!1,this.handleScheduleEvent=({data:e})=>{if(!e)return;const n=new Set,r=nn(this,Ny).keys();for(const i of r){const o=this.updateScheduleInCache(i,e),l=nn(this,Ny).get(i);!o||!l||n.add(i)}for(const i of n)nn(this,hG).emit("preference.schedule.get.updated",{data:nn(this,Ny).get(i)})},gi(this,hG,t);for(const e of a6r)nn(this,hG).on(e,this.handleScheduleEvent);gi(this,Ny,new mG)}has(){return nn(this,Ny).get(MRe())!==void 0}set(t){nn(this,Ny).set(MRe(),t)}getAll(){if(this.has())return nn(this,Ny).get(MRe())}clearAll(){nn(this,Ny).clear()}};hG=new WeakMap,Ny=new WeakMap;var kT,s6r=class extends fF{constructor({useCache:t,inboxServiceInstance:e,eventEmitterInstance:n}){super({eventEmitterInstance:n,inboxServiceInstance:e}),Wa(this,kT),this.cache=new r6r({emitterInstance:this._emitter}),this.scheduleCache=new i6r({emitterInstance:this._emitter}),gi(this,kT,t),this.schedule=new J8r({cache:this.scheduleCache,useCache:t,inboxServiceInstance:e,eventEmitterInstance:n})}list(){return Lr(this,arguments,function*(t={}){return this.callWithSession(()=>Lr(this,null,function*(){var e;try{let n=nn(this,kT)?this.cache.getAll(t):void 0;return this._emitter.emit("preferences.list.pending",{args:t,data:n}),n||(n=(yield this._inboxService.fetchPreferences({tags:t.tags,severity:t.severity,criticality:(e=t.criticality)!=null?e:"nonCritical"})).map(i=>new bF(i,{emitterInstance:this._emitter,inboxServiceInstance:this._inboxService,cache:this.cache,scheduleCache:this.scheduleCache,useCache:nn(this,kT)})),nn(this,kT)&&(this.cache.set(t,n),n=this.cache.getAll(t))),this._emitter.emit("preferences.list.resolved",{args:t,data:n}),{data:n}}catch(n){throw this._emitter.emit("preferences.list.resolved",{args:t,error:n}),n}}))})}update(t){return Lr(this,null,function*(){return this.callWithSession(()=>ERt({emitter:this._emitter,apiService:this._inboxService,cache:this.cache,scheduleCache:this.scheduleCache,useCache:nn(this,kT),args:t}))})}bulkUpdate(t){return Lr(this,null,function*(){return this.callWithSession(()=>Z8r({emitter:this._emitter,apiService:this._inboxService,cache:this.cache,scheduleCache:this.scheduleCache,useCache:nn(this,kT),args:t}))})}};kT=new WeakMap;function o6r(){return typeof window<"u"}var yF,Ole,Lh,l6r=class{constructor(t,e,n){Wa(this,yF),Wa(this,Ole),Wa(this,Lh),gi(this,yF,n),gi(this,Ole,e),gi(this,Lh,t)}get applicationIdentifier(){return nn(this,Lh).applicationIdentifier}get subscriberId(){var t;return(t=nn(this,Lh).subscriber)==null?void 0:t.subscriberId}get context(){return nn(this,Lh).context}get subscriberHash(){return nn(this,Lh).subscriberHash}get contextHash(){return nn(this,Lh).contextHash}get subscriber(){return nn(this,Lh).subscriber}handleApplicationIdentifier(t,e){if(typeof window>"u"||!window.localStorage)return null;const n="novu_keyless_application_identifier";switch(t){case"get":return window.localStorage.getItem(n);case"store":return e&&window.localStorage.setItem(n,e),null;case"delete":return window.localStorage.removeItem(n),null;default:return null}}initialize(t){return Lr(this,null,function*(){var e,n,r,i,o,l;const u=((e=nn(this,Lh).subscriber)==null?void 0:e.subscriberId)===((n=t?.subscriber)==null?void 0:n.subscriberId),d=JSON.stringify(nn(this,Lh).context)===JSON.stringify(t?.context);if(!(u&&d))try{t&&gi(this,Lh,t);const{subscriber:p,subscriberHash:m,contextHash:g,applicationIdentifier:h,defaultSchedule:A,context:b}=nn(this,Lh);let y;o6r()&&(y=Intl.DateTimeFormat().resolvedOptions().timeZone);let v=h;if(v)this.handleApplicationIdentifier("delete");else{const w=this.handleApplicationIdentifier("get");w&&(v=w)}nn(this,yF).emit("session.initialize.pending",{args:nn(this,Lh)});const _=yield nn(this,Ole).initializeSession({applicationIdentifier:v,subscriberHash:m,contextHash:g,subscriber:kc(bi({},p),{subscriberId:(r=p?.subscriberId)!=null?r:"",timezone:(i=p?.timezone)!=null?i:y}),defaultSchedule:A,context:b});(o=_?.applicationIdentifier)!=null&&o.startsWith("pk_keyless_")&&this.handleApplicationIdentifier("store",_.applicationIdentifier),(l=_?.applicationIdentifier)!=null&&l.startsWith("pk_keyless_")||this.handleApplicationIdentifier("delete"),nn(this,yF).emit("session.initialize.resolved",{args:nn(this,Lh),data:_})}catch(p){nn(this,yF).emit("session.initialize.resolved",{args:nn(this,Lh),error:p})}})}};yF=new WeakMap,Ole=new WeakMap,Lh=new WeakMap;var Fle="wss://socket.novu.co",SRt="notifications.notification_received",IRt="notifications.unseen_count_changed",TRt="notifications.unread_count_changed",c6r=({_id:t,transactionId:e,content:n,read:r,seen:i,archived:o,snoozedUntil:l,deliveredAt:u,createdAt:d,lastReadDate:p,firstSeenDate:m,archivedAt:g,channel:h,subscriber:A,subject:b,avatar:y,cta:v,tags:_,data:w,workflow:x,severity:k})=>{var C,E,S,I,B,N,L,M;const R={id:A?._id,subscriberId:A?.subscriberId,firstName:A?.firstName,lastName:A?.lastName,avatar:A?.avatar,locale:A?.locale,data:A?.data,timezone:A?.timezone,email:A?.email,phone:A?.phone},D=(E=(C=v.action)==null?void 0:C.buttons)==null?void 0:E.find($=>$.type==="primary"),P=(I=(S=v.action)==null?void 0:S.buttons)==null?void 0:I.find($=>$.type==="secondary"),O=(N=(B=v.action)==null?void 0:B.result)==null?void 0:N.type,F=(L=v.action)==null?void 0:L.status;return kc(bi(bi({id:t,transactionId:e,subject:b,body:n,to:R,isRead:r,isSeen:i,isArchived:o,isSnoozed:!!l},u&&{deliveredAt:u}),l&&{snoozedUntil:l}),{createdAt:d,readAt:p,firstSeenAt:m,archivedAt:g,avatar:y,primaryAction:D&&{label:D.content,isCompleted:O==="primary"&&F==="done",redirect:D.url?{target:D.target,url:D.url}:void 0},secondaryAction:P&&{label:P.content,isCompleted:O==="secondary"&&F==="done",redirect:P.url?{target:P.target,url:P.url}:void 0},channelType:h,tags:_,redirect:(M=v.data)!=null&&M.url?{url:v.data.url,target:v.data.target}:void 0,data:w,workflow:x,severity:k})},fG,dk,pk,AG,PRe,ORe,FRe,QRe,c3,BRt,$Re,jRe,u6r=class extends fF{constructor({socketUrl:t,inboxServiceInstance:e,eventEmitterInstance:n}){super({eventEmitterInstance:n,inboxServiceInstance:e}),Wa(this,c3),Wa(this,fG),Wa(this,dk),Wa(this,pk),Wa(this,AG),Wa(this,PRe,r=>{try{const i=JSON.parse(r.data);i.event==="notification_received"&&nn(this,dk).emit(SRt,{result:new Mm(c6r(i.data.message),nn(this,dk),this._inboxService)})}catch(i){console.log("error",i)}}),Wa(this,ORe,r=>{try{const i=JSON.parse(r.data);i.event==="unseen_count_changed"&&nn(this,dk).emit(IRt,{result:i.data.unseenCount})}catch{}}),Wa(this,FRe,r=>{try{const i=JSON.parse(r.data);i.event==="unread_count_changed"&&nn(this,dk).emit(TRt,{result:i.data.counts})}catch{}}),Wa(this,QRe,r=>{try{switch(JSON.parse(r.data).event){case"notification_received":nn(this,PRe).call(this,r);break;case"unseen_count_changed":nn(this,ORe).call(this,r);break;case"unread_count_changed":nn(this,FRe).call(this,r);break;default:}}catch{}}),gi(this,dk,n),gi(this,AG,t??Fle)}onSessionSuccess({token:t}){gi(this,fG,t)}isSocketEvent(t){return t===SRt||t===IRt||t===TRt}connect(){return Lr(this,null,function*(){return nn(this,fG)?ok(this,c3,$Re).call(this):this.callWithSession(ok(this,c3,$Re).bind(this))})}disconnect(){return Lr(this,null,function*(){return nn(this,pk)?ok(this,c3,jRe).call(this):this.callWithSession(ok(this,c3,jRe).bind(this))})}};fG=new WeakMap,dk=new WeakMap,pk=new WeakMap,AG=new WeakMap,PRe=new WeakMap,ORe=new WeakMap,FRe=new WeakMap,QRe=new WeakMap,c3=new WeakSet,BRt=function(){return Lr(this,null,function*(){if(nn(this,pk))return;const t={socketUrl:nn(this,AG)};nn(this,dk).emit("socket.connect.pending",{args:t});const e=new URL(nn(this,AG));e.searchParams.set("token",nn(this,fG)),gi(this,pk,new $Fr(e.toString())),nn(this,pk).addEventListener("open",()=>{nn(this,dk).emit("socket.connect.resolved",{args:t})}),nn(this,pk).addEventListener("error",n=>{nn(this,dk).emit("socket.connect.resolved",{args:t,error:n})}),nn(this,pk).addEventListener("message",nn(this,QRe))})},$Re=function(){return Lr(this,null,function*(){try{return yield ok(this,c3,BRt).call(this),{}}catch(t){return{error:new ho("Failed to initialize the PartySocket",t)}}})},jRe=function(){return Lr(this,null,function*(){var t;try{return(t=nn(this,pk))==null||t.close(),gi(this,pk,void 0),{}}catch(e){return{error:new ho("Failed to disconnect from the PartySocket",e)}}})};var d6r="https://ws.novu.co",DRt="notifications.notification_received",NRt="notifications.unseen_count_changed",RRt="notifications.unread_count_changed",p6r=({_id:t,transactionId:e,content:n,read:r,seen:i,archived:o,snoozedUntil:l,deliveredAt:u,createdAt:d,lastReadDate:p,firstSeenDate:m,archivedAt:g,channel:h,subscriber:A,subject:b,avatar:y,cta:v,tags:_,data:w,workflow:x,severity:k})=>{var C,E,S,I,B,N,L,M;const R={id:A?._id,subscriberId:A?.subscriberId,firstName:A?.firstName,lastName:A?.lastName,avatar:A?.avatar,locale:A?.locale,data:A?.data,timezone:A?.timezone,email:A?.email,phone:A?.phone},D=(E=(C=v.action)==null?void 0:C.buttons)==null?void 0:E.find($=>$.type==="primary"),P=(I=(S=v.action)==null?void 0:S.buttons)==null?void 0:I.find($=>$.type==="secondary"),O=(N=(B=v.action)==null?void 0:B.result)==null?void 0:N.type,F=(L=v.action)==null?void 0:L.status;return kc(bi(bi({id:t,transactionId:e,subject:b,body:n,to:R,isRead:r,isSeen:i,isArchived:o,isSnoozed:!!l},u&&{deliveredAt:u}),l&&{snoozedUntil:l}),{createdAt:d,readAt:p,firstSeenAt:m,archivedAt:g,avatar:y,primaryAction:D&&{label:D.content,isCompleted:O==="primary"&&F==="done",redirect:D.url?{target:D.target,url:D.url}:void 0},secondaryAction:P&&{label:P.content,isCompleted:O==="secondary"&&F==="done",redirect:P.url?{target:P.target,url:P.url}:void 0},channelType:h,tags:_,redirect:(M=v.data)!=null&&M.url?{url:v.data.url,target:v.data.target}:void 0,data:w,workflow:x,severity:k})},bG,mk,Ry,yG,zRe,URe,qRe,u3,LRt,GRe,HRe,m6r=class extends fF{constructor({socketUrl:t,inboxServiceInstance:e,eventEmitterInstance:n}){super({eventEmitterInstance:n,inboxServiceInstance:e}),Wa(this,u3),Wa(this,bG),Wa(this,mk),Wa(this,Ry),Wa(this,yG),Wa(this,zRe,({message:r})=>{nn(this,mk).emit(DRt,{result:new Mm(p6r(r),nn(this,mk),this._inboxService)})}),Wa(this,URe,({unseenCount:r})=>{nn(this,mk).emit(NRt,{result:r})}),Wa(this,qRe,({counts:r})=>{nn(this,mk).emit(RRt,{result:r})}),gi(this,mk,n),gi(this,yG,t??d6r)}onSessionSuccess({token:t}){gi(this,bG,t)}isSocketEvent(t){return t===DRt||t===NRt||t===RRt}connect(){return Lr(this,null,function*(){return nn(this,bG)?ok(this,u3,GRe).call(this):this.callWithSession(ok(this,u3,GRe).bind(this))})}disconnect(){return Lr(this,null,function*(){return nn(this,Ry)?ok(this,u3,HRe).call(this):this.callWithSession(ok(this,u3,HRe).bind(this))})}};bG=new WeakMap,mk=new WeakMap,Ry=new WeakMap,yG=new WeakMap,zRe=new WeakMap,URe=new WeakMap,qRe=new WeakMap,u3=new WeakSet,LRt=function(){return Lr(this,null,function*(){var t,e,n;if(nn(this,Ry))return;const r={socketUrl:nn(this,yG)};nn(this,mk).emit("socket.connect.pending",{args:r}),gi(this,Ry,hle(nn(this,yG),{reconnectionDelayMax:1e4,transports:["websocket"],query:{token:`${nn(this,bG)}`}})),nn(this,Ry).on("connect",()=>{nn(this,mk).emit("socket.connect.resolved",{args:r})}),nn(this,Ry).on("connect_error",i=>{nn(this,mk).emit("socket.connect.resolved",{args:r,error:i})}),(t=nn(this,Ry))==null||t.on("notification_received",nn(this,zRe)),(e=nn(this,Ry))==null||e.on("unseen_count_changed",nn(this,URe)),(n=nn(this,Ry))==null||n.on("unread_count_changed",nn(this,qRe))})},GRe=function(){return Lr(this,null,function*(){try{return yield ok(this,u3,LRt).call(this),{}}catch(t){return{error:new ho("Failed to initialize the socket",t)}}})},HRe=function(){return Lr(this,null,function*(){var t;try{return(t=nn(this,Ry))==null||t.disconnect(),gi(this,Ry,void 0),{}}catch(e){return{error:new ho("Failed to disconnect from the socket",e)}}})};var g6r=["wss://eu.socket.novu.co",Fle,"wss://socket.novu-staging.co","wss://socket-worker-local.cli-shortener.workers.dev"],h6r={"https://eu.ws.novu.co":"wss://eu.socket.novu.co","https://ws.novu.co":Fle,"https://dev.ws.novu.co":"wss://socket.novu-staging.co"};function f6r(t){return t?h6r[t]||t:Fle}function A6r(t){return!t||g6r.includes(t)}function b6r({socketUrl:t,inboxServiceInstance:e,eventEmitterInstance:n}){const r=f6r(t);return(A6r(r)?"partysocket":"socket.io")==="partysocket"?new u6r({socketUrl:r,inboxServiceInstance:e,eventEmitterInstance:n}):new m6r({socketUrl:r,inboxServiceInstance:e,eventEmitterInstance:n})}var gk,Mh,ET,Qle,y6r=class{constructor(t){Wa(this,gk),Wa(this,Mh),Wa(this,ET),Wa(this,Qle);var e,n,r;gi(this,Qle,t),gi(this,ET,new q8r({apiUrl:t.apiUrl||t.backendUrl,userAgent:t.__userAgent})),gi(this,gk,new G8r);const i=ARe({subscriberId:t.subscriberId,subscriber:t.subscriber}),o=NNt(t.context);gi(this,Mh,new l6r({applicationIdentifier:t.applicationIdentifier||"",subscriberHash:t.subscriberHash,subscriber:i,defaultSchedule:t.defaultSchedule,context:t.context,contextHash:t.contextHash},nn(this,ET),nn(this,gk))),nn(this,Mh).initialize(),this.notifications=new K8r({useCache:(e=t.useCache)!=null?e:!0,inboxServiceInstance:nn(this,ET),eventEmitterInstance:nn(this,gk)}),this.preferences=new s6r({useCache:(n=t.useCache)!=null?n:!0,inboxServiceInstance:nn(this,ET),eventEmitterInstance:nn(this,gk)}),this.subscriptions=new $8r({subscriber:i,contextKey:o,useCache:(r=t.useCache)!=null?r:!0,inboxServiceInstance:nn(this,ET),eventEmitterInstance:nn(this,gk)}),this.socket=b6r({socketUrl:t.socketUrl,eventEmitterInstance:nn(this,gk),inboxServiceInstance:nn(this,ET)}),this.on=(l,u)=>{this.socket.isSocketEvent(l)&&this.socket.connect();const d=nn(this,gk).on(l,u);return()=>{d()}},this.off=(l,u)=>{nn(this,gk).off(l,u)}}get applicationIdentifier(){return nn(this,Mh).applicationIdentifier}get subscriberId(){return nn(this,Mh).subscriberId}get context(){return nn(this,Mh).context}get options(){return nn(this,Qle)}get contextKey(){return NNt(nn(this,Mh).context)}clearCache(){this.notifications.cache.clearAll(),this.preferences.cache.clearAll(),this.preferences.scheduleCache.clearAll(),this.subscriptions.cache.clearAll()}changeSubscriber(t){return Lr(this,null,function*(){yield nn(this,Mh).initialize({applicationIdentifier:nn(this,Mh).applicationIdentifier||"",subscriberHash:t.subscriberHash,subscriber:t.subscriber,context:nn(this,Mh).context,contextHash:nn(this,Mh).contextHash}),this.clearCache(),(yield this.socket.disconnect()).error||(yield this.socket.connect())})}changeContext(t){return Lr(this,null,function*(){const e=nn(this,Mh).subscriber;if(!e)throw new Error("Cannot change context without an active subscriber");yield nn(this,Mh).initialize({applicationIdentifier:nn(this,Mh).applicationIdentifier||"",subscriberHash:nn(this,Mh).subscriberHash,subscriber:e,context:t.context,contextHash:t.contextHash}),this.clearCache(),(yield this.socket.disconnect()).error||(yield this.socket.connect())})}};gk=new WeakMap,Mh=new WeakMap,ET=new WeakMap,Qle=new WeakMap;var v6r="3.13.0",_6r="@novu/react",w6r=`${_6r}@${v6r}`,MRt=T.createContext(void 0),x6r=t=>{const{subscriberId:e,...n}=t,r=T.useMemo(()=>ARe({subscriberId:e,subscriber:t.subscriber}),[e,t.subscriber]),i=n.applicationIdentifier?n.applicationIdentifier:"",o={...n,applicationIdentifier:i,subscriber:r};return f.jsx(k6r,{...o,applicationIdentifier:i,userAgentType:"hooks",children:t.children})},k6r=t=>{const e=t.applicationIdentifier||"",n=T.useMemo(()=>ARe({subscriberId:t.subscriberId,subscriber:t.subscriber}),[t.subscriberId,t.subscriber]),{children:r,subscriberHash:i,contextHash:o,backendUrl:l,apiUrl:u,socketUrl:d,useCache:p,userAgentType:m,defaultSchedule:g,context:h}=t,A=T.useMemo(()=>new y6r({applicationIdentifier:e,subscriberHash:i,contextHash:o,backendUrl:l,apiUrl:u,socketUrl:d,useCache:p,__userAgent:`${w6r} ${m}`,subscriber:n,defaultSchedule:g,context:h}),[e,i,n,h,o,l,u,d,p,m]);return f.jsx(MRt.Provider,{value:A,children:r})},$le=()=>{const t=T.useContext(MRt);if(!t)throw new Error("useNovu must be used within a <NovuProvider />");return t},jle=t=>{const e=T.useRef(t);return e.current=t,e};function E6r(t,e){if(!("locks"in navigator))return e(t),()=>{};let n=!1,r;const i=new Promise(o=>{r=o});return navigator.locks.request(t,()=>(n||e(t),i)),()=>{n=!0,r()}}var C6r=({channelName:t,onMessage:e})=>{const[n]=T.useState(typeof BroadcastChannel<"u"?new BroadcastChannel(t):void 0),r=i=>{n?.postMessage(i)};return T.useEffect(()=>{const i=o=>{e(o.data)};return n?.addEventListener("message",i),()=>{n?.removeEventListener("message",i)}},[]),{postMessage:r}},WRe=({event:t,eventHandler:e})=>{const n=$le(),r=`nv_ws_connection:a=${n.applicationIdentifier}:s=${n.subscriberId}:c=${n.contextKey}:e=${t}`,{postMessage:i}=C6r({channelName:r,onMessage:e}),o=l=>{e(l),i(l)};T.useEffect(()=>{let l;const u=E6r(r,()=>{l=n.on(t,o)});return()=>{l&&l(),u()}},[])},S6r=t=>{const{filters:e,onSuccess:n,onError:r}=t,{notifications:i}=$le(),o=jle(e),[l,u]=T.useState(),[d,p]=T.useState(),[m,g]=T.useState(!0),[h,A]=T.useState(!1),b=async(v,_)=>{const w=_||o.current,x=w.map(S=>({count:0,filter:S}));let k=[];if(v)for(let S=0;S<x.length;S++){const I=w[S],B=!I.severity||Array.isArray(I.severity)&&I.severity.length===0||Array.isArray(I.severity)&&I.severity.includes(v.severity)||!Array.isArray(I.severity)&&I.severity===v.severity;RRe(I.tags,v.tags)&&B&&k.push(I)}else k=w;if(k.length===0)return;A(!0);const C=await i.count({filters:k});if(A(!1),g(!1),C.error){u(C.error),r?.(C.error);return}const E=C.data;n?.(E.counts),p(S=>{const I=[],B=E.counts;for(let N=0;N<x.length;N++){const L=x[N].filter,R=B.find(D=>fle(D.filter,L))||S?.[N];R&&I.push(R)}return I})};return WRe({event:"notifications.notification_received",eventHandler:v=>{b(v.result)}}),WRe({event:"notifications.unread_count_changed",eventHandler:()=>{b()}}),T.useEffect(()=>{u(void 0),g(!0),A(!1),b(void 0,e)},[JSON.stringify(e)]),{counts:d,error:l,refetch:async()=>{await b()},isLoading:m,isFetching:h}},I6r=t=>{const{tags:e,data:n,read:r,archived:i=!1,snoozed:o=!1,seen:l,severity:u,limit:d=10,onSuccess:p,onError:m}=t||{},g=jle(d),h=jle({tags:e,data:n,read:r,archived:i,snoozed:o,seen:l,severity:u}),A=$le(),[b,y]=T.useState(),[v,_]=T.useState(),[w,x]=T.useState(!0),[k,C]=T.useState(!1),[E,S]=T.useState(!1),I=b?.length,B=I?b[I-1].id:void 0,N=jle(B);T.useEffect(()=>{const $=({data:Q})=>{!Q||!fle(h.current,Q.filter)||(y(Q.notifications),S(Q.hasMore))},j=A.on("notifications.list.updated",$);return()=>{j()}},[h,A]),WRe({event:"notifications.notification_received",eventHandler:({result:$})=>{const j=h.current;if(L8r($,j)){const z={...j,limit:g.current};A.notifications.cache.unshift(z,$)}}});const L=T.useCallback(async $=>{$?.refetch&&(_(void 0),x(!0),C(!1)),C(!0);const j=await A.notifications.list({...h.current,limit:d,after:$?.refetch?void 0:N.current});if(j.error)_(j.error),m?.(j.error),x(!1),C(!1);else if(j.data){const Q=j.data;p?.(Q.notifications),y(Q.notifications),S(Q.hasMore),x(!1),C(!1)}},[A,h,N,d,m,p]);T.useEffect(()=>{A.notifications.clearCache({filter:h.current}),L({refetch:!0})},[h,A,JSON.stringify(h.current),L]);const M=T.useCallback(()=>(A.notifications.clearCache({filter:h.current}),L({refetch:!0})),[h,A,L]),R=T.useCallback(async()=>{if(!(!E||k))return L()},[E,k,L]),D=T.useCallback(async()=>await A.notifications.readAll({tags:h.current.tags,data:h.current.data}),[h,A]),P=T.useCallback(async()=>await A.notifications.seenAll({tags:h.current.tags,data:h.current.data}),[h,A]),O=T.useCallback(async()=>await A.notifications.archiveAll({tags:h.current.tags,data:h.current.data}),[h,A]),F=T.useCallback(async()=>await A.notifications.archiveAllRead({tags:h.current.tags,data:h.current.data}),[h,A]);return{readAll:D,seenAll:P,archiveAll:O,archiveAllRead:F,notifications:b,error:v,isLoading:w,isFetching:k,refetch:M,fetchMore:R,hasMore:E}};const YRe=[{id:"pwa-install",titleKey:"notifications.system.pwa.title",bodyKey:"notifications.system.pwa.body",dismissStorageKey:"xyzen-pwa-prompt-dismissed",condition:()=>{const t=window.matchMedia("(display-mode: standalone)").matches;return window.matchMedia("(min-width: 1024px)").matches&&!t}}];function T6r(){const{t}=yn(),[e,n]=T.useState(()=>{const o=new Set;for(const l of YRe)localStorage.getItem(l.dismissStorageKey)&&o.add(l.id);return o}),r=T.useMemo(()=>YRe.filter(o=>!e.has(o.id)&&o.condition()).map(o=>({id:o.id,title:t(o.titleKey),body:t(o.bodyKey)})),[t,e]),i=T.useCallback(o=>{const l=YRe.find(u=>u.id===o);l&&localStorage.setItem(l.dismissStorageKey,"true"),n(u=>new Set(u).add(o))},[]);return{notifications:r,dismiss:i,count:r.length}}const B6r=[{key:"all",icon:MXn},{key:"unread",icon:KAt},{key:"archived",icon:eSe}],D6r=/\n<!-- meta:(.*?) -->$/;function PRt(t){const e={body:t,title:"",agentName:"",agentAvatar:"",url:"",messageId:"",actionType:"",invitationId:"",teamId:"",teamName:"",inviterUsername:"",inviterAvatarUrl:"",role:""},n=D6r.exec(t);if(!n)return e;const r=t.slice(0,n.index);try{const i=JSON.parse(n[1]);return{body:r,title:i.title??"",agentName:i.agent_name??"",agentAvatar:i.agent_avatar??"",url:i.url??"",messageId:i.message_id??"",actionType:i.action_type??"",invitationId:i.invitation_id??"",teamId:i.team_id??"",teamName:i.team_name??"",inviterUsername:i.inviter_username??"",inviterAvatarUrl:i.inviter_avatar_url??"",role:i.role??""}}catch{return e}}function ORt({items:t,onDismiss:e}){const{t:n}=yn();return t.length===0?null:f.jsxs("div",{className:"border-b border-neutral-100 dark:border-neutral-800/60",children:[f.jsx("div",{className:"px-4 pt-2 pb-1",children:f.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-wide text-neutral-400 dark:text-neutral-500",children:n("notifications.system.title")})}),t.map(r=>f.jsxs("div",{className:"group flex gap-3 px-4 py-3 bg-amber-50/40 dark:bg-amber-950/10",children:[f.jsx("div",{className:"flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-full bg-amber-100 text-amber-600 dark:bg-amber-500/10 dark:text-amber-400",children:f.jsx(iie,{className:"h-4.5 w-4.5"})}),f.jsxs("div",{className:"min-w-0 flex-1",children:[f.jsx("p",{className:"text-[13px] font-semibold text-neutral-900 dark:text-neutral-100",children:r.title}),f.jsx("p",{className:"mt-0.5 text-[13px] leading-snug text-neutral-500 dark:text-neutral-400",children:r.body})]}),f.jsx("button",{onClick:()=>e(r.id),className:"flex-shrink-0 self-start rounded-md p-1.5 text-neutral-400 transition-colors hover:bg-neutral-200/70 hover:text-neutral-600 dark:hover:bg-neutral-700/50 dark:hover:text-neutral-300",title:n("notifications.system.dismiss"),children:f.jsx(q1,{className:"h-3.5 w-3.5"})})]},r.id))]})}function N6r({systemCount:t=0}){const{counts:e}=S6r({filters:[{read:!1}]}),n=(e?.[0]?.count??0)+t;return n===0?null:f.jsx("span",{className:"absolute -top-1 -right-1 flex h-4 min-w-4 items-center justify-center rounded-full bg-red-500 px-1 text-[10px] font-bold text-white shadow-sm",children:n>99?"99+":n})}const vG="rounded-md p-1.5 text-neutral-400 transition-colors hover:bg-neutral-200/70 hover:text-neutral-600 active:bg-neutral-200/70 dark:hover:bg-neutral-700/50 dark:hover:text-neutral-300",R6r=T.memo(function({notification:e,isArchivedView:n,onNavigate:r,onTeamInvitationAction:i}){const o=SNt(e.createdAt),l=PRt(e.body??""),u=T.useCallback(async()=>{if(e.isRead||await e.read(),l.actionType==="team_invitation"){i?.({invitationId:l.invitationId,teamId:l.teamId,teamName:l.teamName,inviterUsername:l.inviterUsername,inviterAvatarUrl:l.inviterAvatarUrl,role:l.role});return}const A=l.url||e.redirect?.url;if(!A)return;const b=/\/#\/chat\/([a-zA-Z0-9_-]+)/.exec(A),y=/[?&]topic=([^&]+)/.exec(A),v=b?.[1]??y?.[1];v&&r?r(v,l.messageId||void 0):window.location.hash=`#${A}`},[e,l.url,l.messageId,l.actionType,l.invitationId,l.teamId,l.teamName,l.inviterUsername,l.inviterAvatarUrl,l.role,r,i]),d=T.useCallback(async A=>{A.stopPropagation(),e.isRead?await e.unread():await e.read()},[e]),p=T.useCallback(async A=>{A.stopPropagation(),await e.delete()},[e]),m=T.useCallback(async A=>{A.stopPropagation(),await e.unarchive()},[e]),g=T.useCallback(async A=>{A.stopPropagation(),await e.archive()},[e]),h=l.agentName||l.title;return f.jsxs(Et.div,{layout:!0,initial:{opacity:0,y:8},animate:{opacity:1,y:0},exit:{opacity:0,x:60},transition:{duration:.2},onClick:u,className:Yt("group relative flex cursor-pointer gap-3 px-4 py-3","border-b border-neutral-100 dark:border-neutral-800/60","transition-colors hover:bg-neutral-50/80 dark:hover:bg-neutral-800/40",!e.isRead&&"bg-blue-50/40 dark:bg-blue-950/20"),children:[f.jsxs("div",{className:"relative flex-shrink-0 pt-0.5",children:[l.agentAvatar?f.jsx("img",{src:l.agentAvatar,alt:h,className:"h-9 w-9 rounded-full object-cover"}):f.jsx("div",{className:"flex h-9 w-9 items-center justify-center rounded-full bg-neutral-200 text-xs font-semibold text-neutral-600 dark:bg-neutral-700 dark:text-neutral-300",children:(h||"N").charAt(0).toUpperCase()}),!e.isRead&&f.jsx("span",{className:"absolute -top-0.5 -right-0.5 h-2.5 w-2.5 rounded-full border-2 border-white bg-blue-500 dark:border-neutral-900"})]}),f.jsxs("div",{className:"min-w-0 flex-1",children:[f.jsxs("div",{className:"flex items-center gap-1",children:[h&&f.jsx("p",{className:"truncate text-[13px] font-semibold text-neutral-900 dark:text-neutral-100",children:h}),f.jsx("span",{className:"flex-shrink-0 text-[11px] text-neutral-400 dark:text-neutral-500",children:o}),f.jsx("div",{className:"ml-auto flex flex-shrink-0 items-center gap-0.5 opacity-0 transition-opacity group-hover:opacity-100 max-md:opacity-100",children:n?f.jsxs(f.Fragment,{children:[f.jsx("button",{onClick:m,className:vG,title:"Restore",children:f.jsx(tbt,{className:"h-3.5 w-3.5"})}),f.jsx("button",{onClick:p,className:vG,title:"Delete",children:f.jsx(Ure,{className:"h-3.5 w-3.5"})})]}):f.jsxs(f.Fragment,{children:[f.jsx("button",{onClick:d,className:vG,title:e.isRead?"Mark as unread":"Mark as read",children:e.isRead?f.jsx(KAt,{className:"h-3.5 w-3.5"}):f.jsx(mh,{className:"h-3.5 w-3.5"})}),f.jsx("button",{onClick:g,className:vG,title:"Archive",children:f.jsx(eSe,{className:"h-3.5 w-3.5"})}),f.jsx("button",{onClick:p,className:vG,title:"Delete",children:f.jsx(Ure,{className:"h-3.5 w-3.5"})})]})})]}),f.jsx("p",{className:Yt("mt-0.5 line-clamp-2 text-[13px] leading-snug",h?"text-neutral-500 dark:text-neutral-400":"text-neutral-700 dark:text-neutral-300"),children:l.body})]})]})});function L6r({filter:t,onNavigate:e,onTeamInvitationAction:n}){const{t:r}=yn(),{notifications:i,isLoading:o,hasMore:l,fetchMore:u,readAll:d,archiveAllRead:p}=I6r(t),m=!!t.archived,[g,h]=T.useState(!1),A=T.useCallback(async()=>{if(!(!i||i.length===0||g)){h(!0);try{await Promise.all(i.map(y=>y.delete()))}finally{h(!1)}}},[i,g]),b=T.useRef(null);return T.useEffect(()=>{if(!b.current||!l)return;const y=new IntersectionObserver(([v])=>{v.isIntersecting&&u()},{rootMargin:"200px"});return y.observe(b.current),()=>y.disconnect()},[l,u]),f.jsxs("div",{className:"flex h-full flex-col",children:[!m&&f.jsxs("div",{className:"flex items-center justify-end gap-1 border-b border-neutral-100 px-4 py-1.5 dark:border-neutral-800/60",children:[f.jsx("button",{onClick:()=>d(),className:"rounded-md p-1.5 text-neutral-400 transition-colors hover:bg-neutral-100 hover:text-neutral-600 dark:hover:bg-neutral-800/40 dark:hover:text-neutral-300",title:r("notifications.actions.readAll"),children:f.jsx(bXn,{className:"h-3.5 w-3.5"})}),f.jsx("button",{onClick:()=>p(),className:"rounded-md p-1.5 text-neutral-400 transition-colors hover:bg-neutral-100 hover:text-neutral-600 dark:hover:bg-neutral-800/40 dark:hover:text-neutral-300",title:r("notifications.actions.archiveRead"),children:f.jsx(eSe,{className:"h-3.5 w-3.5"})})]}),m&&i&&i.length>0&&f.jsx("div",{className:"flex items-center justify-end gap-1 border-b border-neutral-100 px-4 py-1.5 dark:border-neutral-800/60",children:f.jsxs(sRe,{children:[f.jsx(fFr,{asChild:!0,children:f.jsx("button",{disabled:g,className:"rounded-md p-1.5 text-neutral-400 transition-colors hover:bg-red-50 hover:text-red-500 disabled:opacity-40 dark:hover:bg-red-500/10 dark:hover:text-red-400",title:r("notifications.actions.deleteAll"),children:f.jsx(Ure,{className:"h-3.5 w-3.5"})})}),f.jsxs(oRe,{className:"sm:max-w-sm rounded-sm",children:[f.jsxs(lRe,{children:[f.jsx(uRe,{className:"text-sm",children:r("notifications.actions.deleteAll")}),f.jsx(dRe,{className:"text-xs",children:r("notifications.actions.deleteAllConfirm")})]}),f.jsxs(cRe,{children:[f.jsx(mRe,{className:"h-8 rounded-sm text-xs",children:r("common.cancel")}),f.jsx(pRe,{onClick:A,className:"h-8 rounded-sm bg-red-500 text-xs text-white hover:bg-red-600 dark:bg-red-600 dark:hover:bg-red-500",children:r("notifications.actions.confirmDelete")})]})]})]})}),f.jsxs("div",{className:"custom-scrollbar flex-1 overflow-y-auto",children:[f.jsx(Qr,{mode:"popLayout",children:i?.map(y=>f.jsx(R6r,{notification:y,isArchivedView:m,onNavigate:e,onTeamInvitationAction:n},y.id))}),o&&f.jsx("div",{className:"space-y-1 p-4",children:Array.from({length:3}).map((y,v)=>f.jsxs("div",{className:"flex animate-pulse gap-3 py-3",children:[f.jsx("div",{className:"h-9 w-9 flex-shrink-0 rounded-full bg-neutral-200 dark:bg-neutral-700"}),f.jsxs("div",{className:"flex-1 space-y-2",children:[f.jsx("div",{className:"h-3 w-3/4 rounded bg-neutral-200 dark:bg-neutral-700"}),f.jsx("div",{className:"h-3 w-1/2 rounded bg-neutral-200 dark:bg-neutral-700"})]})]},v))}),!o&&(!i||i.length===0)&&f.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-neutral-400 dark:text-neutral-500",children:[f.jsx(iie,{className:"mb-3 h-10 w-10 opacity-40"}),f.jsx("p",{className:"text-sm",children:r("notifications.empty")})]}),l&&f.jsx("div",{ref:b,className:"h-4"})]})]})}const M6r={all:{archived:!1},unread:{read:!1,archived:!1},archived:{archived:!0}};function FRt({onNavigate:t,onTeamInvitationAction:e}){const{t:n}=yn(),[r,i]=T.useState("all");return f.jsxs("div",{className:"flex h-full flex-col",children:[f.jsx("div",{className:"px-4 pt-1 pb-1.5",children:f.jsx("div",{className:"flex rounded-lg bg-neutral-100/80 p-0.5 dark:bg-neutral-800/50",children:B6r.map(({key:o,icon:l})=>f.jsxs("button",{onClick:()=>i(o),className:Yt("relative flex flex-1 items-center justify-center gap-1.5 rounded-md py-1.5 text-xs font-medium transition-colors",r===o?"text-neutral-900 dark:text-neutral-100":"text-neutral-500 hover:text-neutral-700 dark:text-neutral-400 dark:hover:text-neutral-200"),children:[r===o&&f.jsx(Et.div,{layoutId:"notification-tab",className:"absolute inset-0 rounded-md bg-white shadow-sm dark:bg-neutral-700",transition:{type:"spring",stiffness:400,damping:30}}),f.jsxs("span",{className:"relative z-10 flex items-center gap-1.5",children:[f.jsx(l,{className:"h-3.5 w-3.5"}),n(`notifications.filter.${o}`)]})]},o))})}),f.jsx(L6r,{filter:M6r[r],onNavigate:t,onTeamInvitationAction:e},r)]})}function P6r({toastId:t,parsed:e,onView:n}){const{t:r}=yn();return f.jsxs("div",{className:"w-[360px] rounded-sm border border-white/20 bg-white/70 p-4 shadow-2xl backdrop-blur-2xl dark:border-white/10 dark:bg-neutral-900/70",children:[f.jsxs("div",{className:"flex items-start gap-3",children:[f.jsx(JR,{src:e.inviterAvatarUrl,name:e.inviterUsername,size:"md"}),f.jsxs("div",{className:"min-w-0 flex-1",children:[f.jsx("p",{className:"text-[13px] font-semibold text-neutral-900 dark:text-neutral-100",children:e.title||"Team Invitation"}),f.jsx("p",{className:"mt-0.5 text-[13px] leading-snug text-neutral-600 dark:text-neutral-400",children:e.body})]})]}),f.jsxs("div",{className:"mt-3 flex justify-end gap-2",children:[f.jsx("button",{onClick:()=>br.dismiss(t),className:"rounded-sm px-3 py-1.5 text-xs font-medium text-neutral-500 transition-colors hover:bg-neutral-200/60 dark:text-neutral-400 dark:hover:bg-white/10",children:r("common.dismiss","Dismiss")}),f.jsx("button",{onClick:()=>{n(),br.dismiss(t)},className:"rounded-sm bg-neutral-900 px-3 py-1.5 text-xs font-medium text-white transition-colors hover:bg-neutral-800 dark:bg-white dark:text-neutral-900 dark:hover:bg-neutral-200",children:r("teams.viewDetails","View")})]})]})}function O6r(t){const e=$le();T.useEffect(()=>e.on("notifications.notification_received",({result:r})=>{const i=PRt(r.body??""),o=i.title||"New notification",l=i.body||"";if(i.actionType==="team_invitation"&&t){const u={invitationId:i.invitationId,teamId:i.teamId,teamName:i.teamName,inviterUsername:i.inviterUsername,inviterAvatarUrl:i.inviterAvatarUrl,role:i.role};br.custom(d=>f.jsx(P6r,{toastId:d,parsed:i,onView:()=>t(u)}),{duration:1e4})}else br(o,{description:l,duration:5e3})}),[e,t])}function F6r(){const{t}=yn(),e=iG(),n=T6r(),{activateChannel:r,setActivePanel:i,requestFocusAgent:o,setMobilePage:l,setMobileCeoOverlay:u,highlightMessage:d}=zn(Vs(E=>({activateChannel:E.activateChannel,setActivePanel:E.setActivePanel,requestFocusAgent:E.requestFocusAgent,setMobilePage:E.setMobilePage,setMobileCeoOverlay:E.setMobileCeoOverlay,highlightMessage:E.highlightMessage}))),[p,m]=T.useState(!1),[g,h]=T.useState(!1),[A,b]=T.useState(null),y=T.useCallback(E=>{b(E)},[]);O6r(y);const v=T.useCallback(()=>m(E=>!E),[]),_=T.useCallback(()=>m(!1),[]),w=T.useCallback(async(E,S)=>{_(),i("chat"),e&&(u(!1),l(1)),await r(E);const I=zn.getState().channels[E];I?.agentId&&o(I.agentId),S&&d(S)},[_,r,i,o,e,l,u,d]),x=T.useCallback(E=>{_(),b(E)},[_]),k=T.useCallback(()=>{b(null),i("teams")},[i]),C=T.useCallback(()=>{b(null)},[]);return T.useEffect(()=>{if(!p)return;const E=S=>{S.key==="Escape"&&_()};return document.addEventListener("keydown",E),()=>document.removeEventListener("keydown",E)},[p,_]),f.jsxs(f.Fragment,{children:[f.jsxs("div",{className:"relative",children:[f.jsxs(Et.button,{whileHover:{scale:1.1},whileTap:{scale:.9},onClick:v,onMouseEnter:()=>h(!0),onMouseLeave:()=>h(!1),className:"relative flex items-center justify-center h-7 w-7 text-neutral-500 dark:text-neutral-400 hover:text-neutral-700 dark:hover:text-neutral-200 transition-colors",children:[f.jsx(iie,{className:"h-4.5 w-4.5"}),f.jsx(N6r,{systemCount:n.count})]}),f.jsx(Qr,{children:g&&!p&&!e&&f.jsxs(Et.div,{initial:{opacity:0,y:8,scale:.95},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:4,scale:.95},transition:{duration:.15},className:"absolute -top-10 left-1/2 -translate-x-1/2 whitespace-nowrap rounded-lg bg-neutral-900 px-3 py-1.5 text-xs font-medium text-white shadow-lg dark:bg-neutral-100 dark:text-neutral-900",children:[t("notifications.bell.title"),f.jsx("div",{className:"absolute -bottom-1 left-1/2 -translate-x-1/2 border-4 border-transparent border-t-neutral-900 dark:border-t-neutral-100"})]})})]}),e&&f.jsx(El,{isOpen:p,onClose:_,mobileHeight:"h-[85vh]",size:"sm",children:f.jsxs("div",{className:"flex h-full flex-col",children:[f.jsxs("div",{className:"flex items-center justify-between px-5 pt-6 pb-2 md:py-2",children:[f.jsx("h2",{className:"text-base font-semibold text-neutral-900 dark:text-neutral-100",children:t("notifications.bell.title")}),f.jsx("button",{onClick:_,className:"rounded-lg p-1.5 text-neutral-400 transition-colors hover:bg-neutral-100 hover:text-neutral-600 dark:hover:bg-neutral-800 dark:hover:text-neutral-300",children:f.jsx(q1,{className:"h-5 w-5"})})]}),f.jsx(ORt,{items:n.notifications,onDismiss:n.dismiss}),f.jsx(FRt,{onNavigate:w,onTeamInvitationAction:x})]})}),!e&&ji.createPortal(f.jsx(Qr,{children:p&&f.jsxs(f.Fragment,{children:[f.jsx(Et.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.2},className:"fixed inset-0 z-[70]",onClick:_}),f.jsx(Et.div,{initial:{x:"100%"},animate:{x:0},exit:{x:"100%"},transition:{type:"spring",damping:30,stiffness:300,mass:.8},className:Yt("fixed top-0 right-0 z-[71] h-full w-[380px]","bg-white/90 dark:bg-neutral-900/90","backdrop-blur-2xl","border-l border-neutral-200/60 dark:border-neutral-700/50","shadow-2xl","text-neutral-900 dark:text-neutral-100"),style:{paddingBottom:YA},children:f.jsxs("div",{className:"flex h-full flex-col",children:[f.jsxs("div",{className:"flex items-center justify-between px-5 py-4",children:[f.jsx("h2",{className:"text-base font-semibold",children:t("notifications.bell.title")}),f.jsx("button",{onClick:_,className:"rounded-lg p-1.5 text-neutral-400 transition-colors hover:bg-neutral-100 hover:text-neutral-600 dark:hover:bg-neutral-800 dark:hover:text-neutral-300",children:f.jsx(q1,{className:"h-5 w-5"})})]}),f.jsx(ORt,{items:n.notifications,onDismiss:n.dismiss}),f.jsx(FRt,{onNavigate:w,onTeamInvitationAction:x})]})},"notification-drawer")]})}),document.body),f.jsx(Q6r,{data:A,onClose:()=>b(null),onAccepted:k,onDeclined:C})]})}function Q6r({data:t,onClose:e,onAccepted:n,onDeclined:r}){const{t:i}=yn(),[o,l]=T.useState(null),[u,d]=T.useState(!1),[p,m]=T.useState(!1);T.useEffect(()=>{if(!t?.teamId){l(null);return}let A=!1;return d(!0),Lm.getTeam(t.teamId).then(b=>{A||l(b)}).catch(()=>{A||l(null)}).finally(()=>{A||d(!1)}),()=>{A=!0}},[t?.teamId]);const g=async()=>{if(t?.invitationId){m(!0);try{await Lm.acceptInvitation(t.invitationId),br.success(i("teams.invitationAccepted","Joined {{team}}",{team:t.teamName})),n()}catch{br.error(i("common.error","Error"))}finally{m(!1)}}},h=async()=>{if(t?.invitationId){m(!0);try{await Lm.declineInvitation(t.invitationId),br.success(i("teams.invitationDeclined","Invitation declined")),r()}catch{br.error(i("common.error","Error"))}finally{m(!1)}}};return f.jsxs(El,{isOpen:!!t,onClose:e,size:"sm",children:[f.jsx("div",{className:"shrink-0 border-b border-neutral-200/60 px-5 pb-3 pt-5 dark:border-neutral-800/60",children:f.jsx("h2",{className:"text-lg font-semibold text-neutral-900 dark:text-white",children:i("teams.invitationDetail","Team Invitation")})}),f.jsx("div",{className:"flex-1 overflow-y-auto custom-scrollbar",children:f.jsx("div",{className:"space-y-5 px-5 py-5",children:u?f.jsx("div",{className:"flex justify-center py-8",children:f.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-neutral-300 border-t-neutral-900 dark:border-t-neutral-100"})}):f.jsxs(f.Fragment,{children:[f.jsxs("div",{className:"rounded-lg bg-neutral-100/60 p-4 dark:bg-white/[0.04]",children:[f.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[f.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-lg bg-neutral-200 dark:bg-neutral-700",children:f.jsx(mie,{className:"h-5 w-5 text-neutral-600 dark:text-neutral-300"})}),f.jsxs("div",{children:[f.jsx("div",{className:"text-[13px] font-semibold text-neutral-900 dark:text-neutral-100",children:t?.teamName}),o?.member_count!=null&&f.jsxs("div",{className:"text-xs text-neutral-500 dark:text-neutral-400",children:[o.member_count," ",i("teams.members","members")]})]})]}),o?.description&&f.jsx("p",{className:"text-[13px] text-neutral-600 dark:text-neutral-400",children:o.description})]}),f.jsxs("div",{className:"space-y-3",children:[f.jsxs("div",{className:"flex items-center justify-between",children:[f.jsx("span",{className:"text-xs text-neutral-500 dark:text-neutral-400",children:i("teams.invitedBy","Invited by")}),f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx(JR,{src:t?.inviterAvatarUrl,name:t?.inviterUsername||"",size:"sm"}),f.jsx("span",{className:"text-[13px] font-medium text-neutral-900 dark:text-neutral-100",children:t?.inviterUsername})]})]}),f.jsxs("div",{className:"flex items-center justify-between",children:[f.jsx("span",{className:"text-xs text-neutral-500 dark:text-neutral-400",children:i("teams.roleLabel","Role")}),f.jsx("span",{className:"text-[13px] font-medium text-neutral-900 dark:text-neutral-100 capitalize",children:t?.role})]})]})]})})}),f.jsx("div",{className:"shrink-0 border-t border-neutral-200/60 px-5 py-4 dark:border-neutral-800/60",children:f.jsxs("div",{className:"flex justify-end gap-2.5",children:[f.jsx(Oa,{variant:"secondary",onClick:h,disabled:p,className:"text-red-500 hover:text-red-600",children:i("teams.decline","Decline")}),f.jsx(Oa,{onClick:g,disabled:p,children:i("teams.accept","Accept")})]})})]})}function QRt(){const{notificationEnabled:t,novuAppIdentifier:e,novuApiUrl:n,novuWsUrl:r}=gRe(),i=fg();return!t||!e||!i.isAuthenticated?null:f.jsx(x6r,{applicationIdentifier:e,subscriberId:i.user?.id??"",backendUrl:n||void 0,socketUrl:r||void 0,children:f.jsx(F6r,{})})}const YA=72,Dg=8;function $6r({mouseX:t,item:e,isActive:n,onClick:r}){const i=T.useRef(null),[o,l]=T.useState(!1),u=Wb(t,y=>{const v=i.current?.getBoundingClientRect()??{x:0,width:0};return y-v.x-v.width/2}),d=Wb(u,[-100,0,100],[44,56,44]),p=Wb(u,[-100,0,100],[20,26,20]),m=Wb(u,[-100,0,100],[0,-6,0]),g=tR(d,{mass:.1,stiffness:200,damping:15}),h=tR(p,{mass:.1,stiffness:200,damping:15}),A=tR(m,{mass:.1,stiffness:200,damping:15}),b=e.icon;return f.jsxs(Et.button,{ref:i,style:{width:g,height:g,y:A},onClick:r,onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),className:Yt("relative flex flex-col items-center justify-center gap-0.5 rounded-sm transition-colors duration-200","bg-white/80 dark:bg-neutral-800/60","hover:bg-white dark:hover:bg-neutral-700/80","border border-neutral-200/40 dark:border-neutral-700/30",n&&"bg-white dark:bg-neutral-700/80 shadow-md"),children:[f.jsx(Qr,{children:o&&f.jsxs(Et.div,{initial:{opacity:0,y:8,scale:.95},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:4,scale:.95},transition:{duration:.15},className:"absolute -top-10 left-1/2 -translate-x-1/2 whitespace-nowrap rounded-lg bg-neutral-900 px-3 py-1.5 text-xs font-medium text-white shadow-lg dark:bg-neutral-100 dark:text-neutral-900",children:[e.label,f.jsx("div",{className:"absolute -bottom-1 left-1/2 -translate-x-1/2 border-4 border-transparent border-t-neutral-900 dark:border-t-neutral-100"})]})}),f.jsx(Et.div,{style:{width:h,height:h},className:"flex items-center justify-center",children:f.jsx(b,{className:Yt("w-full h-full transition-colors duration-200",n?"text-indigo-600 dark:text-indigo-400":"text-neutral-600 dark:text-neutral-400")})}),n&&f.jsx(Et.div,{layoutId:"dock-active-indicator",className:"h-1 w-1 rounded-full bg-indigo-500",transition:{type:"spring",stiffness:300,damping:30}})]})}function j6r({compact:t=!1}){const e=fg(),{t:n}=yn(),[r,i]=T.useState(!1),[o,l]=T.useState(!1),[u,d]=T.useState(!1),[p,m]=T.useState(!1),g=zn(y=>y.openSettingsModal),h=zO(),A=e.isAuthenticated||!!e.token,b=t?"h-10 w-10":"h-11 w-11";return e.isLoading?f.jsx("div",{className:Yt(b,"flex items-center justify-center rounded-full bg-white/80 dark:bg-neutral-800/60"),children:f.jsx("div",{className:"h-4 w-4 animate-spin rounded-full border-2 border-neutral-300 border-t-indigo-600 dark:border-neutral-700 dark:border-t-indigo-500"})}):A?f.jsxs(f.Fragment,{children:[f.jsxs(bq,{open:r,onOpenChange:i,children:[f.jsx(yq,{asChild:!0,children:f.jsx(Et.button,{whileHover:{scale:1.05},whileTap:{scale:.95},className:Yt(b,"relative flex items-center justify-center rounded-full overflow-hidden transition-shadow hover:shadow-lg","ring-2 ring-neutral-200/60 dark:ring-neutral-700/50"),children:e.user?.avatar?f.jsx("img",{src:e.user.avatar,alt:e.user?.username??"User",className:"h-full w-full object-cover"}):f.jsx("div",{className:"flex h-full w-full items-center justify-center bg-gradient-to-br from-indigo-500 to-purple-600",children:f.jsx(rO,{className:"h-5 w-5 text-white"})})})}),f.jsxs(vq,{align:"start",side:"top",sideOffset:12,className:"w-72 mb-2",children:[f.jsxs(lDe,{className:"flex items-center gap-3 p-3",children:[e.user?.avatar?f.jsx("img",{src:e.user.avatar,alt:e.user?.username??"User",className:"h-10 w-10 rounded-full"}):f.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-full bg-gradient-to-br from-indigo-500 to-purple-600",children:f.jsx(rO,{className:"h-5 w-5 text-white"})}),f.jsx("div",{className:"flex flex-col",children:f.jsx("span",{className:"text-sm font-semibold text-neutral-900 dark:text-neutral-100",children:e.user?.username??n("app.authStatus.loggedIn")})})]}),f.jsx(OO,{}),h&&f.jsx("div",{className:"px-3 py-2",children:f.jsxs("div",{className:"flex items-center justify-between rounded-lg bg-gradient-to-r from-indigo-50 to-purple-50 dark:from-indigo-950/30 dark:to-purple-950/30 px-3 py-2",children:[f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx(Xo,{className:"h-5 w-5 text-indigo-600 dark:text-indigo-400"}),f.jsxs("div",{children:[f.jsx("div",{className:"text-xs text-neutral-500 dark:text-neutral-400",children:n("app.authStatus.pointsBalance")}),f.jsx("div",{className:"text-lg font-bold text-indigo-600 dark:text-indigo-400",children:h.isLoading?"...":h.points??"--"})]})]}),f.jsx("button",{onClick:()=>{i(!1),d(!0)},className:"rounded-full p-1.5 text-neutral-400 hover:bg-white/50 hover:text-indigo-600 dark:hover:bg-neutral-800 dark:hover:text-indigo-400 transition-colors",children:f.jsx(mu,{className:"h-5 w-5"})})]})}),f.jsx(OO,{}),$A("developerReward")&&f.jsxs(gC,{onSelect:()=>{i(!1),m(!0)},className:"flex items-center gap-2 px-3 py-2 cursor-pointer",children:[f.jsx(nO,{className:"h-4 w-4"}),n("subscription.creator")]}),f.jsxs(gC,{onSelect:()=>{i(!1),g()},className:"flex items-center gap-2 px-3 py-2 cursor-pointer",children:[f.jsx(bh,{className:"h-4 w-4"}),n("app.authStatus.settings")]}),f.jsx(OO,{}),f.jsxs(gC,{onSelect:()=>{i(!1),Z5()},className:"flex items-center gap-2 px-3 py-2 cursor-pointer text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-950/20",children:[f.jsx(K2e,{className:"h-4 w-4"}),n("app.authStatus.logout")]})]})]}),h&&f.jsx(qO,{isOpen:u,onClose:()=>d(!1)}),f.jsx(cDe,{isOpen:p,onClose:()=>m(!1)})]}):f.jsxs(f.Fragment,{children:[f.jsx(Et.button,{whileHover:{scale:1.05},whileTap:{scale:.95},onClick:()=>l(!0),className:Yt(b,"flex items-center justify-center rounded-full bg-white/80 dark:bg-neutral-800/60 border border-amber-200/60 dark:border-amber-700/50 transition-shadow hover:shadow-lg"),title:n("app.authStatus.unauthorized"),children:f.jsx(Qp,{className:"h-5 w-5 text-amber-500"})}),f.jsx(L2t,{isOpen:o,onClose:()=>l(!1),onSubmit:async y=>{await e.login(y)}})]})}const z6r="https://github.com/ScienceOL/Xyzen";function U6r(){const{backend:t}=FNe(),{t:e}=yn(),[n,r]=T.useState(!1),[i,o]=T.useState(!1),u=B1()!=="zh-cn";return f.jsxs("div",{className:"relative flex items-center gap-1.5",children:[f.jsx(lFr,{onClick:()=>o(!0),children:e("app.toolbar.joinBeta")}),f.jsx(gFr,{isOpen:i,onClose:()=>o(!1)}),f.jsx("a",{href:z6r,target:"_blank",rel:"noopener noreferrer",className:"flex items-center justify-center h-7 w-7 rounded-md transition-colors hover:bg-white/50 dark:hover:bg-neutral-700/50",children:f.jsx(WAt,{className:"h-4 w-4 text-neutral-500 dark:text-neutral-500 hover:text-neutral-700 dark:hover:text-neutral-300 transition-colors"})}),f.jsxs("div",{className:"relative flex items-center gap-1 cursor-default",onMouseEnter:()=>r(!0),onMouseLeave:()=>r(!1),children:[f.jsx("span",{className:"text-[11px] font-medium text-neutral-500 dark:text-neutral-500 tabular-nums",children:t.version||"..."}),f.jsx("div",{className:"flex items-center justify-center h-4 w-4 rounded-sm",title:e(`app.region.${u?"international":"china"}`),children:f.jsx(nU,{className:Yt("h-3 w-3 transition-colors",u?"text-indigo-400/60 dark:text-indigo-500/60":"text-emerald-400/60 dark:text-emerald-500/60")})}),f.jsx(Qr,{children:n&&f.jsxs(Et.div,{initial:{opacity:0,y:8,scale:.95},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:4,scale:.95},transition:{duration:.15},className:"absolute -top-12 left-1/2 -translate-x-1/2 whitespace-nowrap rounded-lg bg-neutral-900 px-3 py-1.5 text-xs text-white shadow-lg dark:bg-neutral-100 dark:text-neutral-900",children:[f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("span",{className:"font-medium",children:e(`app.region.${u?"international":"china"}`)}),f.jsx("span",{className:"text-neutral-400 dark:text-neutral-500",children:"•"}),f.jsx("span",{className:"text-neutral-300 dark:text-neutral-600",children:t.versionName||t.version})]}),f.jsx("div",{className:"absolute -bottom-1 left-1/2 -translate-x-1/2 border-4 border-transparent border-t-neutral-900 dark:border-t-neutral-100"})]})})]})]})}const $Rt={free:{bg:"bg-neutral-100/80 dark:bg-neutral-800/80",text:"text-neutral-600 dark:text-neutral-400",border:"border-neutral-200/50 dark:border-neutral-700/50",icon:qre},standard:{bg:"bg-blue-50/80 dark:bg-blue-950/40",text:"text-blue-600 dark:text-blue-400",border:"border-blue-200/50 dark:border-blue-800/50",icon:zre},professional:{bg:"bg-purple-50/80 dark:bg-purple-950/40",text:"text-purple-600 dark:text-purple-400",border:"border-purple-200/50 dark:border-purple-800/50",icon:$re},ultra:{bg:"bg-amber-100/90 dark:bg-amber-950/40",text:"text-amber-600 dark:text-amber-400",border:"border-amber-300/70 dark:border-amber-800/50",icon:z1}};function jRt(t){return t<1024*1024?`${(t/1024).toFixed(0)} KB`:t<1024*1024*1024?`${(t/(1024*1024)).toFixed(0)} MB`:`${(t/(1024*1024*1024)).toFixed(1)} GB`}function q6r({visible:t,anchorRef:e,usage:n,daysLeft:r,roleName:i,isExpired:o,isUrgent:l,isWarning:u,respondingCount:d,chatLimit:p,hasOverQuota:m}){const g=e.current?.getBoundingClientRect(),h=t&&n&&g;return ji.createPortal(f.jsx(Qr,{children:h&&f.jsxs(Et.div,{initial:{opacity:0,y:8,scale:.95},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:4,scale:.95},transition:{duration:.2,ease:"easeOut"},style:{position:"fixed",bottom:window.innerHeight-g.top+8,right:window.innerWidth-g.right},className:"z-[60]",children:[f.jsx("div",{className:Yt("relative flex flex-col gap-1.5 min-w-[180px] rounded-2xl px-4 py-3 text-xs shadow-2xl","bg-white/90 text-neutral-900 backdrop-blur-lg","border border-neutral-200/60","dark:bg-white/5 dark:text-white","dark:border-white/[0.08]"),children:f.jsxs("div",{className:"flex flex-col gap-1.5",children:[r!==null&&i!=="free"&&f.jsxs("div",{className:"flex flex-col gap-1 pb-1.5 mb-0.5 border-b border-neutral-200/40 dark:border-neutral-700/40",children:[f.jsxs("div",{className:"flex justify-between gap-4",children:[f.jsx("span",{className:"text-neutral-500 dark:text-neutral-400",children:"Expires"}),f.jsx("span",{className:Yt(o&&"text-red-500 dark:text-red-400",l&&"text-red-500 dark:text-red-400",u&&"text-amber-500 dark:text-amber-400"),children:o?"Expired":r===0?"Today":`${r} day${r===1?"":"s"}`})]}),!o&&f.jsx("div",{className:"h-1 rounded-full bg-neutral-200 dark:bg-neutral-700/50 overflow-hidden",children:f.jsx("div",{className:Yt("h-full rounded-full transition-all",l&&"bg-red-500",u&&"bg-amber-500",!l&&!u&&"bg-emerald-500"),style:{width:`${Math.min(100,Math.max(2,r/30*100))}%`}})})]}),f.jsxs("div",{className:"flex justify-between gap-4",children:[f.jsx("span",{className:"text-neutral-500 dark:text-neutral-400",children:"Storage"}),f.jsxs("span",{className:"font-medium",children:[jRt(n.storage.used_bytes)," /"," ",jRt(n.storage.limit_bytes)]})]}),d>0&&f.jsxs("div",{className:"flex justify-between gap-4",children:[f.jsx("span",{className:"text-neutral-500 dark:text-neutral-400",children:"Chats"}),f.jsxs("span",{className:"font-medium",children:[d," / ",p||"∞"]})]}),n.sandboxes.limit>0&&f.jsxs("div",{className:"flex justify-between gap-4",children:[f.jsx("span",{className:"text-neutral-500 dark:text-neutral-400",children:"Sandboxes"}),f.jsxs("span",{className:"font-medium",children:[n.sandboxes.used," / ",n.sandboxes.limit]})]}),n.scheduled_tasks?.limit>0&&f.jsxs("div",{className:"flex justify-between gap-4",children:[f.jsx("span",{className:"text-neutral-500 dark:text-neutral-400",children:"Tasks"}),f.jsxs("span",{className:"font-medium",children:[n.scheduled_tasks.used," / ",n.scheduled_tasks.limit]})]}),f.jsxs("div",{className:"flex justify-between gap-4",children:[f.jsx("span",{className:"text-neutral-500 dark:text-neutral-400",children:"Files"}),f.jsxs("span",{className:"font-medium",children:[n.files.used," / ",n.files.limit]})]}),m&&f.jsx("div",{className:"text-red-500 dark:text-red-400 text-[10px] mt-0.5 font-semibold",children:"Quota exceeded"})]})}),f.jsx("div",{className:"absolute -bottom-[5px] right-4 h-2.5 w-2.5 rotate-45 bg-white/90 dark:bg-white/5 backdrop-blur-lg border-b border-r border-neutral-200/60 dark:border-white/[0.06]"})]})}),document.body)}function G6r(){const{t}=yn(),e=UO(),n=zO(),r=zn(B=>B.respondingChannelIds.size),[i,o]=T.useState(!1),[l,u]=T.useState(!1),d=T.useRef(null);if(!e||e.subQuery.isLoading)return null;const{subQuery:p,usageQuery:m,roleName:g}=e,h=t(`subscription.plan.${g}`),A=p.data?.subscription?.expires_at,b=p.data?.can_claim_credits??!1,y=$Rt[g]??$Rt.free,v=g==="free",_=!v&&A?new Date(A)<new Date:!1,w=!v&&A?Math.max(0,Math.ceil((new Date(A).getTime()-Date.now())/(1e3*60*60*24))):null,x=w!==null&&w<=3&&!_,k=w!==null&&w<=7&&!x&&!_,C=m.data,E=C?.chats.limit??0,S=C&&(E>0&&r>E||C.storage.usage_percentage>100),I=y.icon;return f.jsxs(f.Fragment,{children:[f.jsx("div",{className:"relative",ref:d,children:f.jsxs(Et.button,{whileHover:{scale:1.03},whileTap:{scale:.97},onClick:()=>o(!0),onMouseEnter:()=>u(!0),onMouseLeave:()=>u(!1),className:Yt("flex items-center gap-1.5 px-2.5 py-1 rounded-lg transition-colors border text-xs font-medium",y.bg,y.text,y.border,_&&"opacity-60",S&&"ring-1 ring-red-400/50"),children:[f.jsx(I,{className:"size-3.5"}),f.jsx("span",{children:h}),_&&f.jsx("span",{className:"text-[10px] text-red-500 dark:text-red-400 font-semibold",children:"expired"}),b&&!_&&f.jsxs("span",{className:"absolute -top-1 -right-1 flex h-2.5 w-2.5",children:[f.jsx("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full bg-red-400 opacity-75"}),f.jsx("span",{className:"relative inline-flex h-2.5 w-2.5 rounded-full bg-red-500"})]})]})}),f.jsx(q6r,{visible:l&&!!C,anchorRef:d,usage:C??null,daysLeft:w,roleName:g,isExpired:_,isUrgent:x,isWarning:k,respondingCount:r,chatLimit:E,hasOverQuota:!!S}),n&&f.jsx(qO,{isOpen:i,onClose:()=>o(!1)})]})}function H6r({activePanel:t,onPanelChange:e,className:n}){const{t:r}=yn(),i=fg(),o=dy(1/0),l=kDe(),[u,d]=T.useState(!1),p=zn(A=>A.dockMinimized),m=i.isAuthenticated||!!i.token,g=[{id:"chat",icon:UA,label:r("app.activityBar.chat"),panel:"chat"},{id:"teams",icon:nO,label:r("app.activityBar.teams"),panel:"teams"},{id:"knowledge",icon:tC,label:r("app.activityBar.knowledge"),panel:"knowledge"},{id:"skills",icon:YI,label:r("app.activityBar.skills","Skills"),panel:"skills"},{id:"memory",icon:sIe,label:r("app.activityBar.memory"),panel:"memory"},{id:"sandbox",icon:yh,label:r("app.activityBar.sandbox","Sandbox"),panel:"sandbox"},{id:"runner",icon:eO,label:r("app.activityBar.runner"),panel:"runner"},{id:"tasks",icon:J1,label:r("app.activityBar.tasks","Tasks"),panel:"tasks"},{id:"marketplace",icon:Xo,label:r("app.activityBar.community"),panel:"marketplace"}],h=T.useCallback(A=>{A.panel&&e(A.panel),A.onClick?.()},[e]);return p?null:f.jsxs(f.Fragment,{children:[f.jsx("div",{className:Yt("fixed bottom-0 left-0 z-50 pb-2",n),style:{paddingLeft:Dg,paddingRight:Dg},children:f.jsx("div",{className:Yt("h-14 rounded-2xl px-4","bg-white/80 dark:bg-neutral-900/60","backdrop-blur-2xl","border border-neutral-200/50 dark:border-neutral-700/50"),style:{width:`calc(100vw - ${Dg*2}px)`,boxShadow:"0 8px 32px rgba(0,0,0,.10), 0 2px 8px rgba(0,0,0,.06), inset 0 1px 0 rgba(255,255,255,.12)"},children:f.jsxs("div",{className:"flex h-full items-center",children:[f.jsx("div",{className:"shrink-0",children:f.jsx(j6r,{compact:!0})}),f.jsxs("div",{className:"flex items-center gap-3",children:[f.jsx("div",{className:"h-8 w-px bg-neutral-300/80 dark:bg-neutral-600/30 ml-3"}),f.jsx("div",{className:"flex items-end gap-1.5",onMouseMove:A=>o.set(A.pageX),onMouseLeave:()=>o.set(1/0),children:g.map(A=>f.jsx($6r,{mouseX:o,item:A,isActive:A.panel===t,onClick:()=>h(A)},A.id))})]}),f.jsx("div",{className:"flex-1"}),f.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[f.jsx(U6r,{}),f.jsx("div",{className:"h-6 w-px bg-neutral-300/80 dark:bg-neutral-600/30"}),l&&m&&f.jsx(Et.button,{whileHover:{scale:1.1},whileTap:{scale:.95},onClick:()=>d(!0),className:"relative flex items-center justify-center h-8 w-8 rounded-lg text-amber-600 transition-colors hover:text-amber-700 dark:text-amber-400 dark:hover:text-amber-300",title:r("app.toolbar.checkIn"),children:f.jsx(SR,{className:"h-5 w-5"})}),f.jsx("div",{className:"h-6 w-px bg-neutral-300/80 dark:bg-neutral-600/30"}),f.jsx(G6r,{}),f.jsx(QRt,{})]})]})})}),l&&f.jsx(iRe,{isOpen:u,onClose:()=>d(!1)})]})}const W6r=fh("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-[box-shadow,_color,_background-color,_border-color,_outline-color,_text-decoration-color,_fill,_stroke] disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",{variants:{variant:{default:"bg-primary text-primary-foreground shadow-xs hover:bg-primary/90",accent:"bg-accent text-accent-foreground shadow-xs hover:bg-accent/90",destructive:"bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",sm:"h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-md px-6 has-[>svg]:px-4",icon:"size-9","icon-sm":"size-8 rounded-md","icon-lg":"size-10 rounded-md"}},defaultVariants:{variant:"default",size:"default"}}),[Y6r,V6r]=QA("RippleButtonContext");function K6r({ref:t,onClick:e,hoverScale:n=1.05,tapScale:r=.95,asChild:i=!1,style:o,...l}){const[u,d]=J.useState([]),p=J.useRef(null);J.useImperativeHandle(t,()=>p.current);const m=J.useCallback(A=>{const b=p.current;if(!b)return;const y=b.getBoundingClientRect(),v=A.clientX-y.left,_=A.clientY-y.top,w={id:Date.now(),x:v,y:_};d(x=>[...x,w]),setTimeout(()=>{d(x=>x.filter(k=>k.id!==w.id))},600)},[]),g=J.useCallback(A=>{m(A),e&&e(A)},[m,e]),h=i?Z1:Et.button;return f.jsx(Y6r,{value:{ripples:u,setRipples:d},children:f.jsx(h,{ref:p,"data-slot":"ripple-button",onClick:g,whileTap:{scale:r},whileHover:{scale:n},style:{position:"relative",overflow:"hidden",...o},...l})})}function Z6r({color:t="var(--ripple-button-ripple-color)",scale:e=10,transition:n={duration:.6,ease:"easeOut"},asChild:r=!1,style:i,...o}){const{ripples:l}=V6r(),u=r?Z1:Et.span;return l.map(d=>f.jsx(u,{initial:{scale:0,opacity:.5},animate:{scale:e,opacity:0},transition:n,style:{position:"absolute",borderRadius:"50%",pointerEvents:"none",width:"20px",height:"20px",backgroundColor:t,top:d.y-10,left:d.x-10,...i},...o},d.id))}const X6r={default:"[--ripple-button-ripple-color:var(--primary-foreground)]",accent:"[--ripple-button-ripple-color:var(--accent-foreground)]",destructive:"[--ripple-button-ripple-color:var(--destructive-foreground)]",outline:"[--ripple-button-ripple-color:var(--foreground)]",secondary:"[--ripple-button-ripple-color:var(--secondary-foreground)]",ghost:"[--ripple-button-ripple-color:var(--foreground)]",link:"[--ripple-button-ripple-color:var(--primary-foreground)]"};function J6r({className:t,variant:e,size:n,...r}){return f.jsx(K6r,{className:Yt(W6r({variant:e,size:n,className:t}),X6r[e]),...r})}function e9r(t){return f.jsx(Z6r,{...t})}const zRt=["adventurer","avataaars","bottts","fun-emoji","lorelei","micah","miniavs","notionists","open-peeps","personas","pixel-art","shapes","thumbs"],_G=(t,e,n)=>n?`${n}/xyzen/api/v1/avatar/${t}/svg?seed=${encodeURIComponent(e)}`:`https://api.dicebear.com/9.x/${t}/svg?seed=${e}`,t9r=t=>{const e=[];return zRt.forEach(n=>{for(let r=0;r<6;r++){const i=`${n}_${r}_preset`;e.push({url:_G(n,i,t),seed:i,style:n})}}),e},URt=t=>{if(!t)return"";try{const e=new URL(t).searchParams.get("seed");return e?decodeURIComponent(e):""}catch{const e=t.match(/[?&]seed=([^&]*)/);return e?decodeURIComponent(e[1]):""}};function VRe({currentAvatar:t,onSelect:e,backendUrl:n}){const{t:r}=yn(),[i,o]=T.useState("avataaars"),[l,u]=T.useState(()=>URt(t)),[d,p]=T.useState(!1);T.useEffect(()=>{const _=URt(t);u(_)},[t]);const[m,g]=T.useState(!1),A=T.useMemo(()=>t9r(n),[n]).filter(_=>_.style===i),b=T.useCallback(async()=>{g(!0),await new Promise(x=>setTimeout(x,300));const _=Math.random().toString(36).slice(2,10),w=_G(i,_,n);e(w),g(!1)},[i,e,n]),y=T.useCallback(async()=>{if(!l.trim())return;g(!0),await new Promise(w=>setTimeout(w,200));const _=_G(i,l.trim(),n);e(_),g(!1)},[i,l,e,n]),v=T.useCallback(async _=>{g(!0),await new Promise(w=>setTimeout(w,150)),e(_),g(!1)},[e]);return f.jsxs("div",{className:"flex gap-5",children:[f.jsx("div",{className:"flex shrink-0 items-start pt-6 px-2",children:f.jsxs(Et.div,{className:"group relative",whileHover:{scale:1.05},transition:{type:"spring",stiffness:300},children:[f.jsx("div",{className:"absolute -inset-1 rounded-full bg-linear-to-tr from-indigo-500 via-purple-500 to-pink-500 opacity-40 blur-md transition-opacity duration-500 group-hover:opacity-70"}),f.jsx(Qr,{children:m&&f.jsx(Et.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"absolute inset-0 z-10 flex items-center justify-center rounded-full bg-white/50 dark:bg-black/50",children:f.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-2 border-indigo-500 border-t-transparent"})})}),f.jsx("img",{src:t||_G("avataaars","default",n),alt:"Current avatar",className:"relative h-20 w-20 rounded-full border-[3px] border-white bg-white shadow-xl dark:border-neutral-700 dark:bg-neutral-800"}),t&&!m&&f.jsx(Et.div,{initial:{scale:0},animate:{scale:1},className:"absolute -bottom-0.5 -right-0.5 flex h-6 w-6 items-center justify-center rounded-full border-2 border-white bg-green-500 shadow dark:border-neutral-800",children:f.jsx(Zs,{className:"h-3 w-3 text-white"})})]})}),f.jsxs("div",{className:"min-w-0 flex-1 space-y-3",children:[f.jsxs("div",{className:"space-y-1.5",children:[f.jsx("label",{className:"pl-0.5 text-[13px] font-medium text-neutral-600 dark:text-neutral-400",children:r("agents.sessionSettings.avatar.style")}),f.jsx("div",{className:"custom-scrollbar -mx-1 flex max-h-16 flex-wrap gap-1.5 overflow-y-auto p-1",children:zRt.map(_=>f.jsx(Oa,{type:"button",variant:i===_?"default":"outline",size:"sm",className:Yt("h-7 rounded-full px-2.5 text-xs transition-all duration-300",i===_?"border-transparent bg-indigo-600 text-white shadow-md shadow-indigo-500/25 hover:bg-indigo-700":"border-neutral-200 text-neutral-600 hover:bg-neutral-100 dark:border-neutral-700 dark:text-neutral-400 dark:hover:bg-neutral-800"),onClick:()=>o(_),children:_},_))})]}),f.jsx("div",{className:"grid grid-cols-8 gap-2",children:A.map((_,w)=>f.jsx(Et.button,{type:"button",whileHover:{scale:1.12},whileTap:{scale:.95},onClick:()=>v(_.url),className:Yt("aspect-square h-16 rounded-full overflow-hidden border-2 transition-colors duration-200 shadow-sm hover:shadow-lg",t===_.url?"border-indigo-500 ring-2 ring-indigo-200 dark:ring-indigo-900 shadow-indigo-500/30":"border-transparent hover:border-neutral-300 dark:hover:border-neutral-600 bg-neutral-50 dark:bg-neutral-800"),children:f.jsx("img",{src:_.url,alt:`Avatar option ${w+1}`,className:"h-full w-full object-cover"})},w))}),f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsxs(J6r,{type:"button",variant:"outline",onClick:b,disabled:m,className:"h-8 shrink-0 gap-1.5 px-3 text-xs font-medium",children:[f.jsx(Xo,{className:"h-3.5 w-3.5 text-indigo-500"}),f.jsx("span",{className:"truncate",children:r(m?"agents.sessionSettings.avatar.loading":"agents.sessionSettings.avatar.random")}),f.jsx(e9r,{})]}),f.jsxs("button",{type:"button",onClick:()=>p(_=>!_),className:"flex items-center gap-1 rounded px-1.5 py-1 text-xs text-neutral-400 transition-colors hover:text-neutral-600 dark:hover:text-neutral-300",children:[r("agents.sessionSettings.avatar.advanced"),f.jsx(h_,{className:Yt("h-3 w-3 transition-transform duration-200",d&&"rotate-180")})]})]}),f.jsx(Qr,{children:d&&f.jsx(Et.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.2},className:"overflow-hidden",children:f.jsxs("div",{className:"flex gap-2 p-1",children:[f.jsx("div",{className:"flex-1",children:f.jsx(Ri,{type:"text",placeholder:r("agents.sessionSettings.avatar.seedPlaceholder"),value:l,onChange:_=>u(_.target.value),onKeyDown:_=>_.key==="Enter"&&y(),className:"text-xs",wrapperClassName:"h-8"})}),f.jsx(Oa,{type:"button",size:"sm",onClick:y,disabled:!l.trim()||m,className:"h-8 px-3 text-xs transition-all hover:shadow-md",children:r("agents.sessionSettings.avatar.apply")})]})})})]})]})}function qRt({isOpen:t,onClose:e,onCreated:n,parentId:r}){const{t:i}=yn(),{createAgent:o,isCreatingAgent:l,backendUrl:u,agents:d}=zn(Vs(x=>({createAgent:x.createAgent,isCreatingAgent:x.isCreatingAgent,backendUrl:x.backendUrl,agents:x.agents}))),[p,m]=T.useState({name:"",description:"",prompt:""}),[g,h]=T.useState(""),[A,b]=T.useState(!1);T.useEffect(()=>{if(t&&!g){const x=Math.random().toString(36).slice(2,10);h(_G("avataaars",x,u))}},[t,g,u]);const y=x=>{const{name:k,value:C}=x.target;m(E=>({...E,[k]:C}))},v=async x=>{if(x.preventDefault(),!A){if(!p.name){alert(i("agents.errors.nameRequired"));return}if(d.some(k=>k.name===p.name)){alert(i("agents.errors.nameDuplicate"));return}b(!0);try{const k=await o({...p,avatar:g,parent_id:r??void 0,mcp_server_ids:[],user_id:"temp",mcp_servers:[],created_at:new Date().toISOString(),updated_at:new Date().toISOString()});w(),k&&n&&n(k)}catch(k){console.error("Failed to create agent:",k),alert(i("agents.errors.createFailed"))}finally{b(!1)}}},_=A||l||!p.name,w=()=>{m({name:"",description:"",prompt:""}),h(""),e()};return f.jsx(El,{isOpen:t,onClose:w,size:"md",children:f.jsxs("div",{className:"flex h-full flex-col overflow-hidden",children:[f.jsx("div",{className:"shrink-0 px-5 pt-5 pb-1 md:pt-2",children:f.jsx("h2",{className:"text-lg font-bold text-neutral-900 dark:text-neutral-100",children:i("agents.createTitle")})}),f.jsxs("form",{onSubmit:v,className:"flex-1 overflow-y-auto custom-scrollbar px-5 pb-5 space-y-5",children:[f.jsx(VRe,{currentAvatar:g,onSelect:h,backendUrl:u}),f.jsx("div",{className:"border-t border-neutral-200 dark:border-neutral-700"}),f.jsx(Za,{label:i("agents.fields.name.required"),required:!0,children:f.jsx(Ri,{name:"name",value:p.name,onChange:y,placeholder:i("agents.fields.name.placeholder"),required:!0})}),f.jsx(Za,{label:i("agents.fields.description.label"),children:f.jsx(Ri,{name:"description",value:p.description,onChange:y,placeholder:i("agents.fields.description.placeholder")})}),f.jsxs("div",{className:"flex justify-end gap-3 pt-4 border-t border-neutral-200 dark:border-neutral-700",children:[f.jsx(Hc,{type:"button",onClick:w,className:"inline-flex items-center gap-2 rounded-md bg-neutral-100 py-2 px-4 text-sm font-medium text-neutral-700 hover:bg-neutral-200 dark:bg-neutral-800 dark:text-neutral-200 dark:hover:bg-neutral-700 transition-colors",children:i("agents.actions.cancel")}),f.jsx(Hc,{type:"submit",disabled:_,className:Yt("inline-flex items-center gap-2 rounded-md py-2 px-4 text-sm font-medium transition-colors",_?"bg-neutral-400 text-white cursor-not-allowed":"bg-indigo-600 text-white hover:bg-indigo-500"),children:i(A||l?"agents.actions.creating":"agents.actions.create")})]})]})]})})}class n9r{listSecrets(){return en.get("/xyzen/api/v1/payment-secrets")}createSecret(e){return en.post("/xyzen/api/v1/payment-secrets",e)}updateSecret(e,n){return en.put(`/xyzen/api/v1/payment-secrets/${e}`,n)}deleteSecret(e){return en.delete(`/xyzen/api/v1/payment-secrets/${e}`)}getBinding(e){return en.get(`/xyzen/api/v1/agents/${e}/payment-binding`)}upsertBinding(e,n){return en.put(`/xyzen/api/v1/agents/${e}/payment-binding`,n)}deleteBinding(e){return en.delete(`/xyzen/api/v1/agents/${e}/payment-binding`)}}const hk=new n9r;class r9r{async createKnowledgeSet(e){return en.post("/xyzen/api/v1/knowledge-sets/",e)}async listKnowledgeSets(e=!1){return en.get("/xyzen/api/v1/knowledge-sets/",{params:{include_deleted:e||void 0}})}async getKnowledgeSet(e){return en.get(`/xyzen/api/v1/knowledge-sets/${e}`)}async updateKnowledgeSet(e,n){return en.patch(`/xyzen/api/v1/knowledge-sets/${e}`,n)}async deleteKnowledgeSet(e,n=!1){return en.delete(`/xyzen/api/v1/knowledge-sets/${e}`,void 0,{params:{hard_delete:n}})}async linkFileToKnowledgeSet(e,n){return en.post(`/xyzen/api/v1/knowledge-sets/${e}/files/${n}`)}async unlinkFileFromKnowledgeSet(e,n){return en.delete(`/xyzen/api/v1/knowledge-sets/${e}/files/${n}`)}async getFilesInKnowledgeSet(e){return en.get(`/xyzen/api/v1/knowledge-sets/${e}/files`)}async bulkLinkFilesToKnowledgeSet(e,n){return en.post(`/xyzen/api/v1/knowledge-sets/${e}/files/bulk-link`,{file_ids:n})}async bulkUnlinkFilesFromKnowledgeSet(e,n){return en.post(`/xyzen/api/v1/knowledge-sets/${e}/files/bulk-unlink`,{file_ids:n})}}const Ph=new r9r;class a9r{async listSkills(){return en.get("/xyzen/api/v1/skills/")}async listAgentSkills(e){return en.get(`/xyzen/api/v1/agents/${e}/skills`)}async attachSkill(e,n){const r={skill_id:n};return en.post(`/xyzen/api/v1/agents/${e}/skills`,r)}async detachSkill(e,n){return en.delete(`/xyzen/api/v1/agents/${e}/skills/${n}`)}async parseSkill(e){return en.post("/xyzen/api/v1/skills/parse",e)}async createSkill(e){return en.post("/xyzen/api/v1/skills/",e)}async listSkillResources(e){return en.get(`/xyzen/api/v1/skills/${e}/resources`)}async updateSkill(e,n){return en.patch(`/xyzen/api/v1/skills/${e}`,n)}async deleteSkill(e){return en.delete(`/xyzen/api/v1/skills/${e}`)}}const Oh=new a9r,GRt=["official","builtin:"];function HRt({open:t,onOpenChange:e,agentId:n,graphConfig:r,mcpServers:i=[],knowledgeSetId:o,tags:l,isPublished:u=!1,readme:d,onPublishSuccess:p}){const{t:m}=yn(),[g,h]=T.useState(""),[A,b]=T.useState(d||""),[y,v]=T.useState(!0),[_,w]=T.useState("editable"),[x,k]=T.useState(l??[]),[C,E]=T.useState(""),[S,I]=T.useState([]),[B,N]=T.useState(o??null),[L,M]=T.useState([]),[R,D]=T.useState(new Set),[P,O]=T.useState(new Set),[F,$]=T.useState(""),[j,Q]=T.useState(null),z=$sr(),U=V2e(t),H=m("marketplace.realPerson.publishAgent");T.useEffect(()=>{if(t){const X=(l??[]).filter(ne=>!GRt.some(ce=>ne===ce||ne.startsWith(ce)));k(X)}},[t,l]);const te=T.useCallback(X=>{const ne=X.trim().toLowerCase();if(!ne||x.includes(ne)){E("");return}if(GRt.some(ce=>ne===ce||ne.startsWith(ce))){E("");return}k(ce=>[...ce,ne]),E("")},[x]),V=T.useCallback(X=>{k(ne=>ne.filter(ce=>ce!==X))},[]),ae=T.useCallback(X=>{X.key==="Enter"||X.key===","?(X.preventDefault(),te(C)):X.key==="Backspace"&&!C&&x.length>0&&k(ne=>ne.slice(0,-1))},[te,C,x.length]);T.useEffect(()=>{if(!t)return;let X=!1;$("");async function ne(){try{const[ce,oe,ue,me]=await Promise.all([Ph.listKnowledgeSets(),Oh.listAgentSkills(n),Oh.listSkills(),hk.getBinding(n)]);if(X)return;I(ce),M(ue),Q(me);const fe=new Set(oe.map(Be=>Be.id));D(fe),O(new Set(fe)),N(o??null)}catch(ce){console.error("Failed to fetch publish modal data:",ce)}}return ne(),()=>{X=!0}},[t,n,o]);const ie=async(X=!1)=>{if(g.trim()&&!(!X&&!await U.ensureVerified()))try{const ne=await z.mutateAsync({agent_id:n,commit_message:g.trim(),is_published:y,readme:A.trim()||null,fork_mode:_,knowledge_set_id:B||null,skill_ids:P.size>0?Array.from(P):void 0,tags:x});p&&p(ne.marketplace_id),h(""),e(!1)}catch(ne){if(U.handleRequiredError(ne))return;console.error("Failed to publish agent:",ne)}},Z=X=>{O(ne=>{const ce=new Set(ne);return ce.has(X)?ce.delete(X):ce.add(X),ce})},W=T.useMemo(()=>{const X=F.trim().toLowerCase();if(!X)return L;const ne=ue=>ue.name.toLowerCase().includes(X)||ue.description?.toLowerCase().includes(X)||ue.tags?.some(me=>me.toLowerCase().includes(X)),ce=[],oe=[];for(const ue of L){if(P.has(ue.id)){ce.push(ue);continue}ne(ue)&&oe.push(ue)}return[...ce,...oe]},[L,P,F]),q=!!r&&Object.keys(r).length>0,Y=g.trim().length>0&&q;return f.jsxs(f.Fragment,{children:[f.jsxs(El,{isOpen:t,onClose:()=>e(!1),size:"xl",children:[f.jsxs("div",{className:"shrink-0 border-b border-neutral-200/60 px-5 pb-3 pt-5 dark:border-neutral-800/60",children:[f.jsx("h2",{className:"text-lg font-semibold text-neutral-900 dark:text-white",children:m(u?"marketplace.publish.titleUpdate":"marketplace.publish.title")}),f.jsx("p",{className:"mt-1 text-[13px] text-neutral-500 dark:text-neutral-400",children:m(u?"marketplace.publish.descriptionUpdate":"marketplace.publish.description")})]}),f.jsx("div",{className:"custom-scrollbar flex-1 overflow-y-auto",children:f.jsxs("div",{className:"space-y-6 px-5 py-5",children:[f.jsx(cIe,{status:U.statusQuery.data,isLoading:U.statusQuery.isLoading,actionLabel:H,onVerify:()=>U.setVerificationOpen(!0)}),(()=>{const X=f.jsxs("div",{className:"flex gap-2.5 rounded-lg bg-neutral-100/60 px-4 py-3 dark:bg-white/[0.04]",children:[f.jsx(mu,{className:"h-4 w-4 shrink-0 text-neutral-400"}),f.jsxs("p",{className:"text-[13px] text-neutral-600 dark:text-neutral-400",children:[f.jsx("strong",{children:m("marketplace.publish.info.title")})," ",m("marketplace.publish.info.content")," ",f.jsx("strong",{children:m("marketplace.publish.info.note")})," ",m("marketplace.publish.info.noteContent")]})]}),ne=f.jsx(Za,{label:m("marketplace.publish.commitMessage.label"),required:!0,hint:m("marketplace.publish.commitMessage.charCount",{count:g.length}),children:f.jsx(qp,{id:"commit-message",placeholder:m("marketplace.publish.commitMessage.placeholder"),value:g,onChange:et=>h(et.target.value),rows:3})}),ce=f.jsx(Za,{label:m("marketplace.publish.readme.label"),hint:m("marketplace.publish.readme.hint"),children:f.jsx(qp,{id:"readme-editor",placeholder:m("marketplace.publish.readme.placeholder"),value:A,onChange:et=>b(et.target.value),rows:6,className:"font-mono"})}),oe=f.jsx(Za,{label:m("marketplace.publish.tags.label"),hint:m("marketplace.publish.tags.hint"),children:f.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 rounded-sm border border-neutral-200 bg-white px-2.5 py-2 transition-colors focus-within:border-indigo-400 focus-within:ring-2 focus-within:ring-indigo-500/20 dark:border-neutral-700 dark:bg-neutral-800",children:[x.map(et=>f.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full bg-indigo-50/80 px-2.5 py-0.5 text-xs font-medium text-indigo-700 dark:bg-indigo-900/30 dark:text-indigo-300",children:[et,f.jsx("button",{type:"button",onClick:()=>V(et),className:"ml-0.5 rounded-full p-0.5 transition-colors hover:bg-indigo-200/60 dark:hover:bg-indigo-800/40",children:f.jsx(ul,{className:"h-3 w-3"})})]},et)),f.jsx("input",{type:"text",value:C,onChange:et=>E(et.target.value),onKeyDown:ae,onBlur:()=>C.trim()&&te(C),placeholder:x.length===0?m("marketplace.publish.tags.placeholder"):"",className:"min-w-[80px] flex-1 border-none bg-transparent py-0.5 text-[13px] text-neutral-700 outline-none placeholder:text-neutral-400 dark:text-neutral-300 dark:placeholder:text-neutral-500"})]})}),ue=f.jsx(Za,{label:m("marketplace.publish.knowledgeBase.label"),hint:m("marketplace.publish.knowledgeBase.hint"),children:f.jsxs("select",{value:B??"",onChange:et=>N(et.target.value||null),className:"w-full rounded-sm border border-neutral-200 bg-white px-3 py-2 text-[13px] text-neutral-700 transition-colors focus:border-indigo-400 focus:outline-none focus:ring-2 focus:ring-indigo-500/20 dark:border-neutral-700 dark:bg-neutral-800 dark:text-neutral-300",children:[f.jsx("option",{value:"",children:m("marketplace.publish.knowledgeBase.none")}),S.map(et=>f.jsxs("option",{value:et.id,children:[et.name," (",m("marketplace.publish.knowledgeBase.fileCount",{count:et.file_count}),")"]},et.id))]})}),me=f.jsx(Za,{label:m("marketplace.publish.skills.label"),hint:m("marketplace.publish.skills.hint"),children:L.length===0?f.jsx("p",{className:"text-xs text-neutral-400 dark:text-neutral-500",children:m("marketplace.publish.skills.empty")}):f.jsxs("div",{className:"space-y-1.5",children:[f.jsx(Ri,{value:F,onChange:et=>$(et.target.value),placeholder:m("marketplace.publish.skills.searchPlaceholder")}),W.length===0?f.jsx("p",{className:"rounded-lg bg-neutral-100/60 px-3 py-2.5 text-xs text-neutral-500 dark:bg-white/[0.04] dark:text-neutral-400",children:m("marketplace.publish.skills.noResults")}):W.map(et=>f.jsxs("label",{className:"flex cursor-pointer items-center gap-3 rounded-lg bg-neutral-100/60 px-3 py-2.5 transition-colors hover:bg-neutral-100 dark:bg-white/[0.04] dark:hover:bg-white/[0.06]",children:[f.jsx("input",{type:"checkbox",checked:P.has(et.id),onChange:()=>Z(et.id),className:"h-4 w-4 rounded border-neutral-300 text-indigo-500 focus:ring-indigo-500/40 dark:border-neutral-600"}),f.jsxs("div",{className:"min-w-0 flex-1",children:[f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("span",{className:"text-[13px] font-medium text-neutral-900 dark:text-neutral-100",children:et.name}),et.scope==="builtin"&&f.jsx("span",{className:"rounded bg-indigo-50/80 px-1.5 py-0.5 text-[10px] font-medium text-indigo-600 dark:bg-indigo-900/30 dark:text-indigo-400",children:m("marketplace.publish.skills.builtin")}),R.has(et.id)&&f.jsx("span",{className:"rounded bg-green-50/80 px-1.5 py-0.5 text-[10px] font-medium text-green-600 dark:bg-green-900/30 dark:text-green-400",children:m("marketplace.publish.skills.attached")})]}),et.description&&f.jsx("p",{className:"mt-0.5 line-clamp-1 text-xs text-neutral-500 dark:text-neutral-400",children:et.description})]})]},et.id))]})}),fe=f.jsx(Za,{label:m("marketplace.publish.mcpServers.label"),hint:m("marketplace.publish.mcpServers.hint"),children:i.length===0?f.jsx("p",{className:"text-xs text-neutral-400 dark:text-neutral-500",children:m("marketplace.publish.mcpServers.empty")}):f.jsx("div",{className:"space-y-1.5",children:i.map(et=>f.jsxs("div",{className:"rounded-lg bg-neutral-100/60 px-3 py-2.5 dark:bg-white/[0.04]",children:[f.jsx("div",{className:"text-[13px] font-medium text-neutral-900 dark:text-neutral-100",children:et.name}),et.description&&f.jsx("p",{className:"mt-0.5 text-xs text-neutral-500 dark:text-neutral-400 line-clamp-1",children:et.description})]},et.id))})}),Be=j?f.jsx(Za,{label:m("agents.payment.publishSummaryTitle"),hint:m("agents.payment.publishSummaryHint"),children:f.jsxs("div",{className:"rounded-lg bg-neutral-100/60 px-4 py-3 dark:bg-white/[0.04]",children:[f.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[f.jsx("span",{className:"text-[13px] font-medium text-neutral-900 dark:text-neutral-100",children:j.provider.toUpperCase()}),f.jsx("span",{className:"rounded-full bg-green-50/80 px-2 py-0.5 text-[10px] font-medium text-green-700 dark:bg-green-900/30 dark:text-green-400",children:j.enabled?m("agents.payment.enabled"):m("agents.payment.disabled")}),f.jsx("span",{className:"rounded-full bg-indigo-50/80 px-2 py-0.5 text-[10px] font-medium text-indigo-700 dark:bg-indigo-900/30 dark:text-indigo-400",children:j.required?m("agents.payment.required"):m("agents.payment.optional")}),f.jsx("span",{className:"rounded-full bg-neutral-200/80 px-2 py-0.5 text-[10px] font-medium text-neutral-700 dark:bg-white/[0.08] dark:text-neutral-300",children:j.status})]}),f.jsx("p",{className:"mt-2 text-xs text-neutral-500 dark:text-neutral-400",children:j.secret?.app_id_masked??m("agents.payment.unconfigured")}),f.jsx("p",{className:"mt-2 text-xs text-neutral-500 dark:text-neutral-400",children:j.tool_names.join(", ")})]})}):null,He=f.jsxs(ld,{className:"flex items-center justify-between rounded-lg bg-neutral-100/60 px-4 py-3.5 dark:bg-white/[0.04]",children:[f.jsxs("div",{className:"space-y-0.5 pr-4",children:[f.jsx(Wc,{htmlFor:"publish-toggle",className:"cursor-pointer text-[13px] font-medium text-neutral-900 dark:text-neutral-100",children:m("marketplace.publish.publishImmediately.label")}),f.jsx("p",{className:"text-xs text-neutral-500 dark:text-neutral-400",children:m("marketplace.publish.publishImmediately.description")})]}),f.jsx(R2e,{id:"publish-toggle",checked:y,onChange:v,className:`${y?"bg-indigo-500":"bg-neutral-300 dark:bg-neutral-600"} relative inline-flex h-[26px] w-[46px] shrink-0 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-indigo-500/40 focus:ring-offset-2`,children:f.jsx("span",{className:`${y?"translate-x-[22px]":"translate-x-[3px]"} inline-block h-5 w-5 transform rounded-full bg-white shadow-sm transition-transform`})})]}),Le=f.jsx(Za,{label:m("marketplace.publish.forkMode.label"),hint:m("marketplace.publish.forkMode.help"),children:f.jsxs("div",{className:"grid grid-cols-2 gap-2.5",children:[f.jsxs("button",{type:"button",onClick:()=>w("editable"),className:`flex items-center gap-3 rounded-lg p-3 text-left transition-colors ${_==="editable"?"bg-green-50/80 ring-1 ring-green-500/30 dark:bg-green-900/15 dark:ring-green-500/20":"bg-neutral-100/60 hover:bg-neutral-100 dark:bg-white/[0.04] dark:hover:bg-white/[0.06]"}`,children:[f.jsx("div",{className:`flex h-8 w-8 shrink-0 items-center justify-center rounded-lg ${_==="editable"?"bg-green-500 text-white":"bg-neutral-200/70 text-neutral-500 dark:bg-neutral-700/70 dark:text-neutral-400"}`,children:f.jsx(oIe,{className:"h-4 w-4"})}),f.jsxs("div",{className:"flex-1 min-w-0",children:[f.jsx("div",{className:"text-[13px] font-medium text-neutral-900 dark:text-neutral-100",children:m("marketplace.forkMode.editable")}),f.jsx("div",{className:"text-xs text-neutral-500 dark:text-neutral-400",children:m("marketplace.forkMode.editableDescription")}),f.jsx("div",{className:"mt-1 text-[10px] font-medium text-green-600 dark:text-green-400",children:m("marketplace.forkMode.rewardRate",{rate:"30%"})})]})]}),f.jsxs("button",{type:"button",onClick:()=>w("locked"),className:`flex items-center gap-3 rounded-lg p-3 text-left transition-colors ${_==="locked"?"bg-amber-50/80 ring-1 ring-amber-500/30 dark:bg-amber-900/15 dark:ring-amber-500/20":"bg-neutral-100/60 hover:bg-neutral-100 dark:bg-white/[0.04] dark:hover:bg-white/[0.06]"}`,children:[f.jsx("div",{className:`flex h-8 w-8 shrink-0 items-center justify-center rounded-lg ${_==="locked"?"bg-amber-500 text-white":"bg-neutral-200/70 text-neutral-500 dark:bg-neutral-700/70 dark:text-neutral-400"}`,children:f.jsx(Xb,{className:"h-4 w-4"})}),f.jsxs("div",{className:"flex-1 min-w-0",children:[f.jsx("div",{className:"text-[13px] font-medium text-neutral-900 dark:text-neutral-100",children:m("marketplace.forkMode.locked")}),f.jsx("div",{className:"text-xs text-neutral-500 dark:text-neutral-400",children:m("marketplace.forkMode.lockedDescription")}),f.jsx("div",{className:"mt-1 text-[10px] font-medium text-amber-600 dark:text-amber-400",children:m("marketplace.forkMode.rewardRate",{rate:"3%"})})]})]})]})});return f.jsxs("div",{className:"space-y-6",children:[!q&&f.jsxs("div",{className:"flex gap-2.5 rounded-lg bg-red-50/80 px-4 py-3 dark:bg-red-950/30",children:[f.jsx(Qp,{className:"h-4 w-4 shrink-0 text-red-500 dark:text-red-400"}),f.jsx("p",{className:"text-[13px] text-red-700 dark:text-red-400",children:m("marketplace.publish.validation.noConfig")})]}),f.jsxs("div",{className:"space-y-6 md:hidden",children:[X,ne,ce,oe,ue,me,fe,Be,He,$A("developerReward")&&Le]}),f.jsxs("div",{className:"hidden md:grid md:grid-cols-[55%_45%]",children:[f.jsxs("div",{className:"space-y-6 pr-5 border-r border-neutral-200/60 dark:border-neutral-800/60",children:[X,ne,ce,oe]}),f.jsxs("div",{className:"space-y-6 pl-5",children:[ue,me,fe,Be,He,$A("developerReward")&&Le]})]}),z.isSuccess&&f.jsxs("div",{className:"flex gap-2.5 rounded-lg bg-green-50/80 px-4 py-3 dark:bg-green-950/30",children:[f.jsx(Sl,{className:"h-4 w-4 shrink-0 text-green-500"}),f.jsx("p",{className:"text-[13px] text-green-700 dark:text-green-400",children:m(u?"marketplace.publish.success.updated":"marketplace.publish.success.published")})]}),z.isError&&f.jsxs("div",{className:"flex gap-2.5 rounded-lg bg-red-50/80 px-4 py-3 dark:bg-red-950/30",children:[f.jsx(Qp,{className:"h-4 w-4 shrink-0 text-red-500 dark:text-red-400"}),f.jsx("p",{className:"text-[13px] text-red-700 dark:text-red-400",children:z.error instanceof Error?z.error.message:m("marketplace.publish.error.default")})]})]})})()]})}),f.jsx("div",{className:"shrink-0 border-t border-neutral-200/60 px-5 py-4 dark:border-neutral-800/60",children:f.jsxs("div",{className:"flex justify-end gap-2.5",children:[f.jsx(Hc,{onClick:()=>{h(""),e(!1)},disabled:z.isPending,className:"rounded-lg bg-neutral-100/80 px-4 py-2 text-[13px] font-medium text-neutral-700 transition-colors hover:bg-neutral-200/80 disabled:opacity-50 dark:bg-white/[0.06] dark:text-neutral-300 dark:hover:bg-white/[0.1]",children:m("marketplace.publish.actions.cancel")}),f.jsx(Hc,{onClick:()=>{ie()},disabled:!Y||z.isPending,className:"rounded-lg bg-indigo-500 px-4 py-2 text-[13px] font-semibold text-white transition-colors hover:bg-indigo-600 disabled:opacity-50 dark:bg-indigo-500 dark:hover:bg-indigo-400",children:z.isPending?m("marketplace.publish.actions.publishing"):m(u?"marketplace.publish.actions.update":y?"marketplace.publish.actions.publish":"marketplace.publish.actions.saveAsDraft")})]})})]}),f.jsx(die,{open:U.verificationOpen,onOpenChange:U.setVerificationOpen,actionLabel:H,onStatusChange:()=>{U.statusQuery.refetch()},onVerified:()=>{U.statusQuery.refetch(),ie(!0)}})]})}const i9r=["create-alipay-payment-agent","query-alipay-payment","refund-alipay-payment","query-alipay-refund"],s9r=T.lazy(()=>Promise.resolve().then(()=>MSa)),o9r=[{id:"profile",icon:lIe,labelKey:"profile"},{id:"automation",icon:Xo,labelKey:"automation"},{id:"size",icon:EU,labelKey:"size"},{id:"workflow",icon:bh,labelKey:"workflow"},{id:"danger",icon:Qp,labelKey:"danger",color:"text-red-500"}];function l9r({currentW:t=1,currentH:e=1,onResize:n}){const[r,i]=T.useState(null);return f.jsxs("div",{className:"flex flex-col gap-6",children:[f.jsx("div",{className:"flex justify-center",children:f.jsx("div",{className:"grid grid-cols-3 gap-3",onMouseLeave:()=>i(null),children:Array.from({length:9}).map((o,l)=>{const u=l%3+1,d=Math.floor(l/3)+1,p=r&&u<=r.w&&d<=r.h,m=!r&&u<=t&&d<=e;return f.jsx(Et.div,{whileHover:{scale:1.05},whileTap:{scale:.95},className:Yt("h-14 w-14 cursor-pointer rounded-sm border-2 transition-colors duration-200 shadow-sm",p||m?"border-indigo-500 bg-indigo-500/20 dark:border-indigo-400 dark:bg-indigo-400/20 shadow-indigo-500/30 shadow-lg":"border-neutral-200 bg-white hover:border-neutral-300 dark:border-neutral-700 dark:bg-neutral-800 dark:hover:border-neutral-600"),onMouseEnter:()=>i({w:u,h:d}),onClick:g=>{g.preventDefault(),g.stopPropagation(),n(u,d)}},l)})})}),f.jsx("div",{className:"text-center",children:f.jsx(Et.span,{initial:{opacity:0,y:-10},animate:{opacity:1,y:0},className:"inline-block px-5 py-2 rounded-full bg-neutral-100 dark:bg-neutral-800 text-base font-bold text-neutral-700 dark:text-neutral-200 shadow-sm border border-neutral-200 dark:border-neutral-700",children:r?`${r.w} × ${r.h}`:`${t} × ${e}`},r?`${r.w}x${r.h}`:`${t}x${e}`)})]})}function c9r({agent:t,currentAvatar:e,onAvatarChange:n,onClose:r}){const{t:i}=yn(),o=zn(L=>L.backendUrl),{updateAgent:l,agents:u,openSettingsModal:d}=zn(Vs(L=>({updateAgent:L.updateAgent,agents:L.agents,openSettingsModal:L.openSettingsModal}))),p=t.original_source_id!=null,[m,g]=T.useState(t),[h,A]=T.useState(!1),[b,y]=T.useState(null),[v,_]=T.useState([]),[w,x]=T.useState(""),[k,C]=T.useState(!1),[E,S]=T.useState(!1);T.useEffect(()=>{g(t)},[t]),T.useEffect(()=>{let L=!1;async function M(){try{const[R,D]=await Promise.all([hk.getBinding(t.id),hk.listSecrets()]);if(L)return;y(R),_(D),x(R?.secret?.id??""),C(R?.enabled??!1),S(R?.required??!1)}catch(R){console.error("Failed to load agent payment binding:",R)}}return M(),()=>{L=!0}},[t.id]);const I=L=>{const{name:M,value:R}=L.target;g({...m,[M]:R})},B=async L=>{if(L.preventDefault(),!h){if(m.name!==t.name&&u.some(M=>M.id!==m.id&&M.name===m.name)){alert(i("agents.errors.nameDuplicate"));return}A(!0);try{if(await l({id:m.id,name:m.name,description:m.description}),!p&&b!=null&&!k&&!w)await hk.deleteBinding(m.id),y(null),x(""),C(!1),S(!1);else{if(!(!p&&(b!=null||k))){br.success(i("agents.payment.saveSuccess")),r();return}if(!w){br.error(i("agents.payment.noSecretsHint"));return}const D=await hk.upsertBinding(m.id,{enabled:k,required:k&&E,secret_id:w,tool_names:[...i9r]});y(D)}br.success(i("agents.payment.saveSuccess")),r()}catch(M){console.error("Failed to update agent:",M),br.error(M instanceof Error?M.message:i("agents.errors.updateFailed"))}finally{A(!1)}}},N=async()=>{if(b){A(!0);try{await hk.deleteBinding(m.id),y(null),x(""),C(!1),S(!1),br.success(i("agents.payment.deleteSuccess"))}catch(L){console.error("Failed to delete payment binding:",L),br.error(L instanceof Error?L.message:i("agents.payment.deleteFailed"))}finally{A(!1)}}};return f.jsxs("form",{onSubmit:B,className:"space-y-6 px-4",children:[f.jsx(VRe,{currentAvatar:e,onSelect:n,backendUrl:o}),f.jsx("div",{className:"border-t border-neutral-200 dark:border-neutral-700"}),f.jsxs("div",{className:"space-y-4",children:[f.jsxs(ld,{children:[f.jsx(Wc,{className:"text-sm font-medium text-neutral-700 dark:text-neutral-300",children:i("agents.fields.name.label")}),f.jsx(Ri,{name:"name",value:m.name,onChange:I,placeholder:i("agents.fields.name.placeholder"),required:!0})]}),f.jsxs(ld,{children:[f.jsx(Wc,{className:"text-sm font-medium text-neutral-700 dark:text-neutral-300",children:i("agents.fields.description.label")}),f.jsx(Ri,{name:"description",value:m.description,onChange:I,placeholder:i("agents.fields.description.placeholder")})]})]}),!p&&f.jsxs(f.Fragment,{children:[f.jsx("div",{className:"border-t border-neutral-200 dark:border-neutral-700"}),f.jsxs("div",{className:"space-y-4",children:[f.jsxs("div",{className:"rounded-lg bg-neutral-100/60 px-4 py-4 dark:bg-white/[0.04]",children:[f.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[f.jsxs("div",{children:[f.jsx("p",{className:"text-[13px] font-medium text-neutral-900 dark:text-neutral-100",children:i("agents.payment.title")}),f.jsx("p",{className:"mt-1 text-xs text-neutral-500 dark:text-neutral-400",children:i("agents.payment.description")})]}),f.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[f.jsx("span",{className:"rounded-full bg-neutral-200/80 px-2 py-0.5 text-[10px] font-medium text-neutral-700 dark:bg-white/[0.08] dark:text-neutral-300",children:b?.status??i("agents.payment.unconfigured")}),b?.required&&f.jsx("span",{className:"rounded-full bg-indigo-50/80 px-2 py-0.5 text-[10px] font-medium text-indigo-700 dark:bg-indigo-900/30 dark:text-indigo-300",children:i("agents.payment.required")})]})]}),b?.last_error&&f.jsx("p",{className:"mt-2 text-xs text-red-600 dark:text-red-400",children:b.last_error})]}),f.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[f.jsxs("label",{className:"flex items-center justify-between rounded-lg bg-neutral-100/60 px-4 py-3 dark:bg-white/[0.04]",children:[f.jsx("span",{className:"text-[13px] font-medium text-neutral-800 dark:text-neutral-200",children:i("agents.payment.enabled")}),f.jsx("input",{type:"checkbox",checked:k,onChange:L=>{const M=L.target.checked;C(M),M||S(!1)},className:"h-4 w-4 rounded border-neutral-300 text-indigo-500 focus:ring-indigo-500/40 dark:border-neutral-600"})]}),f.jsxs("label",{className:"flex items-center justify-between rounded-lg bg-neutral-100/60 px-4 py-3 dark:bg-white/[0.04]",children:[f.jsx("span",{className:Yt("text-[13px] font-medium",k?"text-neutral-800 dark:text-neutral-200":"text-neutral-400 dark:text-neutral-500"),children:i("agents.payment.required")}),f.jsx("input",{type:"checkbox",checked:E,disabled:!k,onChange:L=>S(L.target.checked),className:"h-4 w-4 rounded border-neutral-300 text-indigo-500 focus:ring-indigo-500/40 dark:border-neutral-600"})]})]}),f.jsxs(ld,{children:[f.jsx(Wc,{className:"text-sm font-medium text-neutral-700 dark:text-neutral-300",children:i("agents.payment.secret")}),f.jsxs("select",{value:w,onChange:L=>x(L.target.value),className:"mt-2 w-full rounded-sm border border-neutral-200 bg-white px-3 py-2 text-[13px] text-neutral-900 focus:border-indigo-400 focus:outline-none focus:ring-2 focus:ring-indigo-400/20 dark:border-neutral-700 dark:bg-neutral-900 dark:text-neutral-100",children:[f.jsx("option",{value:"",children:i("agents.payment.secretPlaceholder")}),v.map(L=>f.jsx("option",{value:L.id,children:L.app_id_masked},L.id))]})]}),w&&f.jsx("div",{className:"rounded-lg bg-neutral-100/60 px-4 py-3 text-xs text-neutral-500 dark:bg-white/[0.04] dark:text-neutral-400",children:v.find(L=>L.id===w)?.gateway}),k&&v.length===0&&f.jsxs("div",{className:"rounded-lg bg-neutral-100/60 px-4 py-3 text-xs text-neutral-500 dark:bg-white/[0.04] dark:text-neutral-400",children:[f.jsx("p",{children:i("agents.payment.noSecretsHint")}),f.jsx("button",{type:"button",onClick:()=>d("payment"),className:"mt-2 text-xs font-medium text-indigo-600 hover:text-indigo-500 dark:text-indigo-400",children:i("agents.payment.manageSecrets")})]}),b&&f.jsx("div",{className:"flex justify-end",children:f.jsx("button",{type:"button",onClick:()=>{N()},className:"rounded-lg bg-red-50/80 px-3 py-2 text-xs font-medium text-red-700 transition-colors hover:bg-red-100 dark:bg-red-950/30 dark:text-red-400 dark:hover:bg-red-950/50",children:i("agents.payment.delete")})})]})]}),f.jsx("div",{className:"flex justify-end gap-3 pt-4 border-t border-neutral-200 dark:border-neutral-700",children:f.jsx(Hc,{type:"submit",disabled:h,className:`inline-flex items-center gap-2 rounded-md py-2 px-4 text-sm font-medium transition-colors ${h?"bg-indigo-400 text-white cursor-not-allowed":"bg-indigo-600 text-white hover:bg-indigo-500"}`,children:i(h?"agents.actions.saving":"agents.actions.save")})})]})}const KRe="09:00",u9r=[{value:"0",label:"Sunday"},{value:"1",label:"Monday"},{value:"2",label:"Tuesday"},{value:"3",label:"Wednesday"},{value:"4",label:"Thursday"},{value:"5",label:"Friday"},{value:"6",label:"Saturday"}];function WRt(){return typeof Intl>"u"?"UTC":Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC"}function d9r(t){if(!t)return{mode:"daily",time:KRe,dayOfWeek:"1",cronExpression:"0 9 * * *"};const e=t.trim().split(/\s+/);if(e.length===5){const[n,r,i,o,l]=e;if(/^\d+$/.test(n)&&/^\d+$/.test(r)&&i==="*"&&o==="*"&&l==="*")return{mode:"daily",time:`${r.padStart(2,"0")}:${n.padStart(2,"0")}`,dayOfWeek:"1",cronExpression:t};if(/^\d+$/.test(n)&&/^\d+$/.test(r)&&i==="*"&&o==="*"&&/^\d+$/.test(l))return{mode:"weekly",time:`${r.padStart(2,"0")}:${n.padStart(2,"0")}`,dayOfWeek:l,cronExpression:t}}return{mode:"cron",time:KRe,dayOfWeek:"1",cronExpression:t}}function p9r(t,e,n,r){if(t==="cron")return r.trim();const[i="9",o="0"]=e.split(":"),l=String(Number(o||"0")),u=String(Number(i||"9"));return t==="weekly"?`${l} ${u} * * ${n}`:`${l} ${u} * * *`}function YRt(t){if(!t)return null;const e=new Date(t);return Number.isNaN(e.getTime())?t:new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}).format(e)}function m9r(){const{t}=yn(),{autoExplore:e,autoExploreLoading:n,fetchAutoExplore:r,saveAutoExplore:i,toggleAutoExplore:o}=zn(Vs(E=>({autoExplore:E.autoExplore,autoExploreLoading:E.autoExploreLoading,fetchAutoExplore:E.fetchAutoExplore,saveAutoExplore:E.saveAutoExplore,toggleAutoExplore:E.toggleAutoExplore}))),[l,u]=T.useState("daily"),[d,p]=T.useState(KRe),[m,g]=T.useState("1"),[h,A]=T.useState("0 9 * * *"),[b,y]=T.useState(WRt()),[v,_]=T.useState("auto");T.useEffect(()=>{if(!e){r().catch(()=>{});return}const E=d9r(e.cron_expression);u(E.mode),p(E.time),g(E.dayOfWeek),A(E.cronExpression),y(e.timezone||WRt()),_(e.language||"auto")},[e,r]);const w=async()=>{const E=p9r(l,d,m,h);try{await i({cronExpression:E,timezone:b,language:v}),br.success(t("agents.rootAgent.autoExploreUpdated"))}catch(S){console.error("Failed to save auto-explore:",S),br.error(t("agents.rootAgent.autoExploreFailed"))}},x=async()=>{try{await o(!1),br.success(t("agents.rootAgent.autoExploreDisabled"))}catch(E){console.error("Failed to disable auto-explore:",E),br.error(t("agents.rootAgent.autoExploreFailed"))}},k=YRt(e?.next_run_at||null),C=YRt(e?.last_run_at||null);return f.jsxs("div",{className:"space-y-6 px-4",children:[f.jsxs("div",{className:"rounded-lg bg-neutral-100/60 px-4 py-4 dark:bg-white/[0.04]",children:[f.jsxs("div",{className:"flex items-center justify-between gap-3",children:[f.jsxs("div",{children:[f.jsx("p",{className:"text-[13px] font-medium text-neutral-800 dark:text-neutral-200",children:t("agents.rootAgent.autoExploreSchedule")}),f.jsx("p",{className:"mt-1 text-xs text-neutral-500 dark:text-neutral-400",children:t("agents.rootAgent.autoExploreScheduleHint")})]}),f.jsx("span",{className:Yt("rounded-sm px-2 py-1 text-xs font-medium",e?.enabled?"bg-amber-500/10 text-amber-700 dark:text-amber-300":"bg-neutral-200/80 text-neutral-600 dark:bg-white/[0.06] dark:text-neutral-400"),children:e?.enabled?t("agents.rootAgent.autoExploreEnabledState"):t("agents.rootAgent.autoExploreDisabledState")})]}),f.jsxs("div",{className:"mt-3 space-y-1 text-xs text-neutral-500 dark:text-neutral-400",children:[f.jsxs("p",{children:[t("agents.rootAgent.autoExploreTimezone"),": ",b]}),k&&f.jsxs("p",{children:[t("agents.rootAgent.autoExploreNextRun"),": ",k]}),C&&f.jsxs("p",{children:[t("agents.rootAgent.autoExploreLastRun"),": ",C]}),e?.last_error&&f.jsxs("p",{className:"text-red-600 dark:text-red-400",children:[t("agents.rootAgent.autoExploreLastError"),":"," ",e.last_error]})]})]}),f.jsxs("div",{className:"space-y-4",children:[f.jsxs(ld,{children:[f.jsx(Wc,{className:"text-sm font-medium text-neutral-700 dark:text-neutral-300",children:t("agents.rootAgent.autoExploreCadence")}),f.jsx("div",{className:"mt-2 grid grid-cols-3 gap-2",children:["daily","weekly","cron"].map(E=>f.jsx("button",{type:"button",onClick:()=>u(E),className:Yt("rounded-lg px-3 py-2 text-sm transition-colors",l===E?"bg-indigo-500 text-white":"bg-neutral-100 text-neutral-700 hover:bg-neutral-200 dark:bg-white/[0.04] dark:text-neutral-300 dark:hover:bg-white/[0.08]"),children:t(`agents.rootAgent.autoExploreCadence${E[0].toUpperCase()}${E.slice(1)}`)},E))})]}),l!=="cron"&&f.jsxs(ld,{children:[f.jsx(Wc,{className:"text-sm font-medium text-neutral-700 dark:text-neutral-300",children:t("agents.rootAgent.autoExploreTime")}),f.jsx(Ri,{type:"time",value:d,onChange:E=>p(E.target.value)})]}),l==="weekly"&&f.jsxs(ld,{children:[f.jsx(Wc,{className:"text-sm font-medium text-neutral-700 dark:text-neutral-300",children:t("agents.rootAgent.autoExploreWeekday")}),f.jsx("select",{value:m,onChange:E=>g(E.target.value),className:"mt-2 w-full rounded-sm border border-neutral-200 bg-white px-3 py-2 text-sm text-neutral-700 dark:border-neutral-700 dark:bg-neutral-900 dark:text-neutral-200",children:u9r.map(E=>f.jsx("option",{value:E.value,children:t(`agents.rootAgent.autoExploreWeekday${E.label}`)},E.value))})]}),l==="cron"&&f.jsxs(ld,{children:[f.jsx(Wc,{className:"text-sm font-medium text-neutral-700 dark:text-neutral-300",children:t("agents.rootAgent.autoExploreCron")}),f.jsx(Ri,{value:h,onChange:E=>A(E.target.value),placeholder:"0 9 * * *"})]}),f.jsxs(ld,{children:[f.jsx(Wc,{className:"text-sm font-medium text-neutral-700 dark:text-neutral-300",children:t("agents.rootAgent.autoExploreLanguage")}),f.jsxs("select",{value:v,onChange:E=>_(E.target.value),className:"mt-2 w-full rounded-sm border border-neutral-200 bg-white px-3 py-2 text-sm text-neutral-700 dark:border-neutral-700 dark:bg-neutral-900 dark:text-neutral-200",children:[f.jsx("option",{value:"auto",children:t("agents.rootAgent.autoExploreLanguageAuto")}),f.jsx("option",{value:"zh",children:"中文"}),f.jsx("option",{value:"en",children:"English"}),f.jsx("option",{value:"ja",children:"日本語"})]})]})]}),f.jsxs("div",{className:"flex justify-end gap-3 border-t border-neutral-200 pt-4 dark:border-neutral-700",children:[e?.enabled&&f.jsx(Oa,{type:"button",variant:"outline",disabled:n,onClick:x,children:t("agents.rootAgent.autoExploreDisableAction")}),f.jsx(Oa,{type:"button",disabled:n,onClick:w,children:e?.enabled?t("agents.rootAgent.autoExploreUpdateAction"):t("agents.rootAgent.autoExploreEnableAction")})]})]})}const ZRe=({isOpen:t,onClose:e,agentName:n,agent:r,currentAvatar:i,currentGridSize:o,onAvatarChange:l,onGridSizeChange:u,onDelete:d})=>{const{t:p}=yn(),m=zn(P=>P.backendUrl),g=zn(P=>P.rootAgentId),h=!!r&&!!g&&r.id===g,[A,b]=T.useState("profile"),[y,v]=T.useState(null),[_,w]=T.useState(!1),[x,k]=T.useState(!1),C=typeof window<"u"&&window.innerWidth<768,E=!!r,S=r?.config_visibility!=="hidden",I=r?.original_source_id!=null,B=T.useMemo(()=>o9r.filter(P=>!(P.id==="automation"&&!h||P.id==="workflow"&&(!E||!S)||P.id==="danger"&&!d)),[E,S,d]),N=P=>{C?v(P):b(P),w(!1)},L=()=>{v(null),w(!1)},M=P=>{switch(P){case"profile":return r?f.jsx(c9r,{agent:r,currentAvatar:i,onAvatarChange:l,onClose:e}):f.jsx(VRe,{currentAvatar:i,onSelect:l,backendUrl:m});case"automation":return f.jsx(m9r,{});case"size":return f.jsxs("div",{className:"flex flex-col items-center justify-center h-full py-8",children:[f.jsx("p",{className:"text-sm text-neutral-600 dark:text-neutral-400 mb-8 text-center max-w-64",children:p("agents.sessionSettings.size.description")}),f.jsx(l9r,{currentW:o?.w,currentH:o?.h,onResize:u})]});case"workflow":return r?f.jsx(T.Suspense,{children:f.jsx(s9r,{agent:r,onClose:e})}):null;case"danger":return f.jsx("div",{className:"flex flex-col items-center justify-center h-full py-8 space-y-6",children:_?f.jsxs(Et.div,{initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},className:"w-full max-w-sm rounded-2xl bg-red-50 dark:bg-red-900/10 p-6 space-y-4 border border-red-100 dark:border-red-900/20",children:[f.jsxs("div",{className:"text-center space-y-2",children:[f.jsx("h3",{className:"text-base font-semibold text-red-700 dark:text-red-300",children:p("agents.sessionSettings.danger.deleteConfirmTitle")}),f.jsx("p",{className:"text-sm text-red-600 dark:text-red-400",children:p("agents.sessionSettings.danger.deleteConfirmMessage",{name:n})})]}),f.jsxs("div",{className:"flex gap-3",children:[f.jsx(Oa,{variant:"outline",className:"flex-1 bg-white dark:bg-transparent border-red-200 dark:border-red-900/30 text-red-700 dark:text-red-300 hover:bg-red-100 dark:hover:bg-red-900/20",onClick:()=>w(!1),children:p("common.cancel")}),f.jsx(Oa,{variant:"destructive",className:"flex-1 shadow-lg shadow-red-500/20",onClick:()=>{d?.(),e()},children:p("common.delete")})]})]}):f.jsxs(f.Fragment,{children:[f.jsxs("div",{className:"text-center space-y-2",children:[f.jsx(Qp,{className:"w-12 h-12 mx-auto text-red-400"}),f.jsx("p",{className:"text-sm text-neutral-600 dark:text-neutral-400 max-w-64",children:p("agents.sessionSettings.danger.description")})]}),d&&f.jsxs(Oa,{variant:"destructive",size:"lg",className:"h-11 px-6 gap-3 shadow-lg shadow-red-500/20",onClick:()=>w(!0),children:[f.jsx(Jo,{className:"w-5 h-5"}),p("agents.sessionSettings.danger.deleteButton")]})]})});default:return null}},R=f.jsx("div",{className:"flex-1 min-w-0",children:f.jsx(Qr,{mode:"wait",children:y===null?f.jsx(Et.div,{initial:{opacity:0,x:-20},animate:{opacity:1,x:0},exit:{opacity:0,x:-20},className:"space-y-2",children:B.map(P=>f.jsxs("button",{onClick:()=>N(P.id),className:Yt("w-full flex items-center gap-4 px-4 py-4 rounded-sm transition-all text-left","bg-neutral-50 dark:bg-neutral-800/50 hover:bg-neutral-100 dark:hover:bg-neutral-800",P.color),children:[f.jsx(P.icon,{className:"w-6 h-6 shrink-0"}),f.jsx("span",{className:"text-base font-medium",children:p(`agents.sessionSettings.tabs.${P.labelKey}`)})]},P.id))},"nav"):f.jsxs(Et.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:20},children:[f.jsxs("button",{onClick:L,className:"flex items-center gap-2 text-sm text-neutral-500 hover:text-neutral-700 dark:hover:text-neutral-300 mb-4",children:[f.jsx(g_,{className:"w-4 h-4"}),p("settings.modal.back")]}),M(y)]},y)})}),D=f.jsxs(YP,{value:A,onValueChange:P=>{b(P),w(!1)},className:"flex flex-row gap-6",children:[f.jsx("div",{className:"w-44 shrink-0",children:f.jsx(VP,{className:"flex items-start flex-col w-full h-auto bg-neutral-50 dark:bg-neutral-900 rounded-sm p-1.5",children:B.map(P=>f.jsxs(Fp,{value:P.id,className:Yt("w-44 justify-start gap-3 px-3 py-2.5 text-sm font-medium rounded-lg","data-[state=active]:bg-white data-[state=active]:shadow-sm dark:data-[state=active]:bg-neutral-800",P.id==="danger"&&"data-[state=active]:text-red-600 dark:data-[state=active]:text-red-400",P.color&&A!==P.id&&P.color),children:[f.jsx(P.icon,{className:"w-5 h-5 shrink-0"}),p(`agents.sessionSettings.tabs.${P.labelKey}`)]},P.id))})}),f.jsx("div",{className:"flex-1 min-w-0",children:f.jsx(wU,{children:B.map(P=>f.jsx(Ah,{value:P.id,className:"h-full",children:M(P.id)},P.id))})})]});return f.jsxs(f.Fragment,{children:[f.jsx(El,{isOpen:t,onClose:e,size:"lg",children:f.jsxs("div",{className:"flex h-full flex-col overflow-hidden",children:[f.jsx("div",{className:"shrink-0 px-5 pt-5 pb-1 md:pt-2",children:f.jsx("h2",{className:"text-lg font-bold text-neutral-900 dark:text-neutral-100",children:p("agents.sessionSettings.title",{name:n})})}),f.jsxs("div",{className:"flex-1 overflow-y-auto custom-scrollbar px-5 pb-5",children:[f.jsxs("div",{className:"py-2",children:[f.jsx("div",{className:"md:hidden",children:R}),f.jsx("div",{className:"hidden md:block",children:D})]}),r&&!I&&!h&&f.jsx("div",{className:"mt-4 pt-4 border-t border-neutral-200 dark:border-neutral-700",children:f.jsxs(Oa,{type:"button",variant:"outline",onClick:()=>k(!0),disabled:!r.graph_config,className:"w-full gap-2 h-10 text-purple-700 border-purple-200 hover:bg-purple-50 dark:text-purple-300 dark:border-purple-800 dark:hover:bg-purple-900/20",title:r.graph_config?p("agents.actions.publish"):p("agents.actions.publishTooltip"),children:[f.jsx(Xo,{className:"h-4 w-4"}),p("agents.actions.publish")]})})]})]})}),r&&!I&&!h&&f.jsx(HRt,{open:x,onOpenChange:k,agentId:r.id,agentName:r.name,agentDescription:r.description,graphConfig:r.graph_config,mcpServers:r.mcp_servers?.map(P=>({id:P.id,name:P.name,description:P.description||void 0})),knowledgeSetId:r.knowledge_set_id,tags:r.tags,onPublishSuccess:P=>{console.log("Agent published to marketplace:",P),k(!1)}})]})};function g9r({isOpen:t,onClose:e,onConfirm:n,title:r,message:i,confirmLabel:o="Confirm",cancelLabel:l="Cancel",destructive:u=!0,className:d}){return f.jsx(sRe,{open:t,onOpenChange:p=>!p&&e(),children:f.jsxs(oRe,{className:Yt("space-y-4 border border-neutral-200/20 bg-white/95 shadow-2xl shadow-black/20 backdrop-blur-xl dark:border-neutral-700/30 dark:bg-neutral-900/95 dark:shadow-black/40","p-6 sm:p-6 rounded-sm",d),children:[f.jsx(lRe,{children:f.jsx(uRe,{className:"text-lg font-bold text-neutral-900 dark:text-neutral-100",children:r})}),f.jsxs("div",{className:"custom-scrollbar flex max-h-[60vh] items-start gap-4 overflow-y-auto",children:[f.jsx("div",{className:"flex h-12 w-12 shrink-0 items-center justify-center rounded-full bg-red-100 dark:bg-red-900/30",children:f.jsx(Qp,{className:"h-6 w-6 text-red-600 dark:text-red-400","aria-hidden":"true"})}),f.jsx(dRe,{className:"whitespace-pre-line text-sm text-neutral-600 dark:text-neutral-400",children:i})]}),f.jsxs(cRe,{children:[f.jsx(mRe,{className:Yt("inline-flex items-center gap-2","font-semibold","dark:bg-neutral-800 dark:text-neutral-200 dark:hover:bg-neutral-700"),children:l}),f.jsx(pRe,{autoFocus:!0,onClick:async()=>{await n(),e()},className:Yt("inline-flex items-center gap-2 font-semibold",u?"bg-red-600 text-white shadow-inner shadow-white/10 hover:bg-red-500 dark:bg-red-500 dark:hover:bg-red-400":"bg-neutral-900 text-white hover:bg-neutral-800 dark:bg-neutral-100 dark:text-neutral-900 dark:hover:bg-neutral-200"),children:o})]})]})})}const VA=J.memo(g9r);function VRt(){const{t}=yn(),e=zn(i=>i.toggleAutoExplore),n=zn(i=>i.autoExploreLoading);return{handleToggle:T.useCallback(async i=>{if(!n)try{await e(i),br.success(t(i?"agents.rootAgent.autoExploreEnabled":"agents.rootAgent.autoExploreDisabled"))}catch(o){console.error("Failed to toggle auto-explore:",o),br.error(t("agents.rootAgent.autoExploreFailed"))}},[n,e,t]),loading:n}}function KRt(t,e){const n={};for(const r of t){const i=e[r.id];if(!i)continue;const o=n[i];(!o||r.updatedAt>o)&&(n[i]=r.updatedAt)}return n}function h9r({onClick:t}){const{t:e}=yn();return f.jsxs(Et.button,{onClick:t,initial:{opacity:0,y:10},animate:{opacity:1,y:0},whileHover:{scale:1.02},whileTap:{scale:.98},transition:{type:"spring",stiffness:400,damping:25},className:`inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg
574
574
  text-sm font-medium text-neutral-600 dark:text-neutral-400
575
575
  bg-white/60 dark:bg-neutral-800/60 backdrop-blur-sm
576
576
  border border-neutral-200/60 dark:border-neutral-700/60