@thatopen/services 0.19.0 → 0.20.0

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/index.cjs.js CHANGED
@@ -1,3 +1,3 @@
1
- "use strict";var St=Object.defineProperty;var Xe=n=>{throw TypeError(n)};var Ot=(n,e,t)=>e in n?St(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var E=(n,e,t)=>Ot(n,typeof e!="symbol"?e+"":e,t),_e=(n,e,t)=>e.has(n)||Xe("Cannot "+t);var u=(n,e,t)=>(_e(n,e,"read from private field"),t?t.call(n):e.get(n)),_=(n,e,t)=>e.has(n)?Xe("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(n):e.set(n,t),T=(n,e,t,s)=>(_e(n,e,"write to private field"),s?s.call(n,t):e.set(n,t),t),a=(n,e,t)=>(_e(n,e,"access private method"),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const P=Object.create(null);P.open="0";P.close="1";P.ping="2";P.pong="3";P.message="4";P.upgrade="5";P.noop="6";const ce=Object.create(null);Object.keys(P).forEach(n=>{ce[P[n]]=n});const Se={type:"error",data:"parser error"},nt=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",rt=typeof ArrayBuffer=="function",it=n=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(n):n&&n.buffer instanceof ArrayBuffer,He=({type:n,data:e},t,s)=>nt&&e instanceof Blob?t?s(e):ze(e,s):rt&&(e instanceof ArrayBuffer||it(e))?t?s(e):ze(new Blob([e]),s):s(P[n]+(e||"")),ze=(n,e)=>{const t=new FileReader;return t.onload=function(){const s=t.result.split(",")[1];e("b"+(s||""))},t.readAsDataURL(n)};function Qe(n){return n instanceof Uint8Array?n:n instanceof ArrayBuffer?new Uint8Array(n):new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}let be;function Ct(n,e){if(nt&&n.data instanceof Blob)return n.data.arrayBuffer().then(Qe).then(e);if(rt&&(n.data instanceof ArrayBuffer||it(n.data)))return e(Qe(n.data));He(n,!1,t=>{be||(be=new TextEncoder),e(be.encode(t))})}const Ze="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",ee=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let n=0;n<Ze.length;n++)ee[Ze.charCodeAt(n)]=n;const Rt=n=>{let e=n.length*.75,t=n.length,s,r=0,i,o,h,f;n[n.length-1]==="="&&(e--,n[n.length-2]==="="&&e--);const m=new ArrayBuffer(e),y=new Uint8Array(m);for(s=0;s<t;s+=4)i=ee[n.charCodeAt(s)],o=ee[n.charCodeAt(s+1)],h=ee[n.charCodeAt(s+2)],f=ee[n.charCodeAt(s+3)],y[r++]=i<<2|o>>4,y[r++]=(o&15)<<4|h>>2,y[r++]=(h&3)<<6|f&63;return m},$t=typeof ArrayBuffer=="function",je=(n,e)=>{if(typeof n!="string")return{type:"message",data:ot(n,e)};const t=n.charAt(0);return t==="b"?{type:"message",data:Nt(n.substring(1),e)}:ce[t]?n.length>1?{type:ce[t],data:n.substring(1)}:{type:ce[t]}:Se},Nt=(n,e)=>{if($t){const t=Rt(n);return ot(t,e)}else return{base64:!0,data:n}},ot=(n,e)=>{switch(e){case"blob":return n instanceof Blob?n:new Blob([n]);case"arraybuffer":default:return n instanceof ArrayBuffer?n:n.buffer}},at="",Pt=(n,e)=>{const t=n.length,s=new Array(t);let r=0;n.forEach((i,o)=>{He(i,!1,h=>{s[o]=h,++r===t&&e(s.join(at))})})},Bt=(n,e)=>{const t=n.split(at),s=[];for(let r=0;r<t.length;r++){const i=je(t[r],e);if(s.push(i),i.type==="error")break}return s};function xt(){return new TransformStream({transform(n,e){Ct(n,t=>{const s=t.length;let r;if(s<126)r=new Uint8Array(1),new DataView(r.buffer).setUint8(0,s);else if(s<65536){r=new Uint8Array(3);const i=new DataView(r.buffer);i.setUint8(0,126),i.setUint16(1,s)}else{r=new Uint8Array(9);const i=new DataView(r.buffer);i.setUint8(0,127),i.setBigUint64(1,BigInt(s))}n.data&&typeof n.data!="string"&&(r[0]|=128),e.enqueue(r),e.enqueue(t)})}})}let Te;function oe(n){return n.reduce((e,t)=>e+t.length,0)}function ae(n,e){if(n[0].length===e)return n.shift();const t=new Uint8Array(e);let s=0;for(let r=0;r<e;r++)t[r]=n[0][s++],s===n[0].length&&(n.shift(),s=0);return n.length&&s<n[0].length&&(n[0]=n[0].slice(s)),t}function It(n,e){Te||(Te=new TextDecoder);const t=[];let s=0,r=-1,i=!1;return new TransformStream({transform(o,h){for(t.push(o);;){if(s===0){if(oe(t)<1)break;const f=ae(t,1);i=(f[0]&128)===128,r=f[0]&127,r<126?s=3:r===126?s=1:s=2}else if(s===1){if(oe(t)<2)break;const f=ae(t,2);r=new DataView(f.buffer,f.byteOffset,f.length).getUint16(0),s=3}else if(s===2){if(oe(t)<8)break;const f=ae(t,8),m=new DataView(f.buffer,f.byteOffset,f.length),y=m.getUint32(0);if(y>Math.pow(2,21)-1){h.enqueue(Se);break}r=y*Math.pow(2,32)+m.getUint32(4),s=3}else{if(oe(t)<r)break;const f=ae(t,r);h.enqueue(je(i?f:Te.decode(f),e)),s=0}if(r===0||r>n){h.enqueue(Se);break}}}})}const ct=4;function w(n){if(n)return Lt(n)}function Lt(n){for(var e in w.prototype)n[e]=w.prototype[e];return n}w.prototype.on=w.prototype.addEventListener=function(n,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+n]=this._callbacks["$"+n]||[]).push(e),this};w.prototype.once=function(n,e){function t(){this.off(n,t),e.apply(this,arguments)}return t.fn=e,this.on(n,t),this};w.prototype.off=w.prototype.removeListener=w.prototype.removeAllListeners=w.prototype.removeEventListener=function(n,e){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var t=this._callbacks["$"+n];if(!t)return this;if(arguments.length==1)return delete this._callbacks["$"+n],this;for(var s,r=0;r<t.length;r++)if(s=t[r],s===e||s.fn===e){t.splice(r,1);break}return t.length===0&&delete this._callbacks["$"+n],this};w.prototype.emit=function(n){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),t=this._callbacks["$"+n],s=1;s<arguments.length;s++)e[s-1]=arguments[s];if(t){t=t.slice(0);for(var s=0,r=t.length;s<r;++s)t[s].apply(this,e)}return this};w.prototype.emitReserved=w.prototype.emit;w.prototype.listeners=function(n){return this._callbacks=this._callbacks||{},this._callbacks["$"+n]||[]};w.prototype.hasListeners=function(n){return!!this.listeners(n).length};const me=typeof Promise=="function"&&typeof Promise.resolve=="function"?e=>Promise.resolve().then(e):(e,t)=>t(e,0),S=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),qt="arraybuffer";function ht(n,...e){return e.reduce((t,s)=>(n.hasOwnProperty(s)&&(t[s]=n[s]),t),{})}const Ut=S.setTimeout,Dt=S.clearTimeout;function ge(n,e){e.useNativeTimers?(n.setTimeoutFn=Ut.bind(S),n.clearTimeoutFn=Dt.bind(S)):(n.setTimeoutFn=S.setTimeout.bind(S),n.clearTimeoutFn=S.clearTimeout.bind(S))}const Ft=1.33;function Mt(n){return typeof n=="string"?Ht(n):Math.ceil((n.byteLength||n.size)*Ft)}function Ht(n){let e=0,t=0;for(let s=0,r=n.length;s<r;s++)e=n.charCodeAt(s),e<128?t+=1:e<2048?t+=2:e<55296||e>=57344?t+=3:(s++,t+=4);return t}function ut(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function jt(n){let e="";for(let t in n)n.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(n[t]));return e}function Vt(n){let e={},t=n.split("&");for(let s=0,r=t.length;s<r;s++){let i=t[s].split("=");e[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return e}class Jt extends Error{constructor(e,t,s){super(e),this.description=t,this.context=s,this.type="TransportError"}}class Ve extends w{constructor(e){super(),this.writable=!1,ge(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,s){return super.emitReserved("error",new Jt(e,t,s)),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 t=je(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){const e=this.opts.hostname;return e.indexOf(":")===-1?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(e){const t=jt(e);return t.length?"?"+t:""}}class Gt extends Ve{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";const t=()=>{this.readyState="paused",e()};if(this._polling||!this.writable){let s=0;this._polling&&(s++,this.once("pollComplete",function(){--s||t()})),this.writable||(s++,this.once("drain",function(){--s||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){const t=s=>{if(this.readyState==="opening"&&s.type==="open"&&this.onOpen(),s.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(s)};Bt(e,this.socket.binaryType).forEach(t),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,Pt(e,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return this.opts.timestampRequests!==!1&&(t[this.opts.timestampParam]=ut()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}}let lt=!1;try{lt=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const Yt=lt;function Wt(){}class Kt extends Gt{constructor(e){if(super(e),typeof location<"u"){const t=location.protocol==="https:";let s=location.port;s||(s=t?"443":"80"),this.xd=typeof location<"u"&&e.hostname!==location.hostname||s!==e.port}}doWrite(e,t){const s=this.request({method:"POST",data:e});s.on("success",t),s.on("error",(r,i)=>{this.onError("xhr post error",r,i)})}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(t,s)=>{this.onError("xhr poll error",t,s)}),this.pollXhr=e}}class N extends w{constructor(e,t,s){super(),this.createRequest=e,ge(this,s),this._opts=s,this._method=s.method||"GET",this._uri=t,this._data=s.data!==void 0?s.data:null,this._create()}_create(){var e;const t=ht(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;const s=this._xhr=this.createRequest(t);try{s.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){s.setDisableHeaderCheck&&s.setDisableHeaderCheck(!0);for(let r in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(r)&&s.setRequestHeader(r,this._opts.extraHeaders[r])}}catch{}if(this._method==="POST")try{s.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{s.setRequestHeader("Accept","*/*")}catch{}(e=this._opts.cookieJar)===null||e===void 0||e.addCookies(s),"withCredentials"in s&&(s.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(s.timeout=this._opts.requestTimeout),s.onreadystatechange=()=>{var r;s.readyState===3&&((r=this._opts.cookieJar)===null||r===void 0||r.parseCookies(s.getResponseHeader("set-cookie"))),s.readyState===4&&(s.status===200||s.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof s.status=="number"?s.status:0)},0))},s.send(this._data)}catch(r){this.setTimeoutFn(()=>{this._onError(r)},0);return}typeof document<"u"&&(this._index=N.requestsCount++,N.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=Wt,e)try{this._xhr.abort()}catch{}typeof document<"u"&&delete N.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()}}N.requestsCount=0;N.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",et);else if(typeof addEventListener=="function"){const n="onpagehide"in S?"pagehide":"unload";addEventListener(n,et,!1)}}function et(){for(let n in N.requests)N.requests.hasOwnProperty(n)&&N.requests[n].abort()}const Xt=function(){const n=ft({xdomain:!1});return n&&n.responseType!==null}();class zt extends Kt{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=Xt&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new N(ft,this.uri(),e)}}function ft(n){const e=n.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||Yt))return new XMLHttpRequest}catch{}if(!e)try{return new S[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const dt=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class Qt extends Ve{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,s=dt?{}:ht(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(s.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,s)}catch(r){return this.emitReserved("error",r)}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 t=0;t<e.length;t++){const s=e[t],r=t===e.length-1;He(s,this.supportsBinary,i=>{try{this.doWrite(s,i)}catch{}r&&me(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=ut()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const Ee=S.WebSocket||S.MozWebSocket;class Zt extends Qt{createSocket(e,t,s){return dt?new Ee(e,t,s):t?new Ee(e,t):new Ee(e)}doWrite(e,t){this.ws.send(t)}}class es extends Ve{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved("error",e)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{const t=It(Number.MAX_SAFE_INTEGER,this.socket.binaryType),s=e.readable.pipeThrough(t).getReader(),r=xt();r.readable.pipeTo(e.writable),this._writer=r.writable.getWriter();const i=()=>{s.read().then(({done:h,value:f})=>{h||(this.onPacket(f),i())}).catch(h=>{})};i();const o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this._writer.write(o).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const s=e[t],r=t===e.length-1;this._writer.write(s).then(()=>{r&&me(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}}const ts={websocket:Zt,webtransport:es,polling:zt},ss=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,ns=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Oe(n){if(n.length>8e3)throw"URI too long";const e=n,t=n.indexOf("["),s=n.indexOf("]");t!=-1&&s!=-1&&(n=n.substring(0,t)+n.substring(t,s).replace(/:/g,";")+n.substring(s,n.length));let r=ss.exec(n||""),i={},o=14;for(;o--;)i[ns[o]]=r[o]||"";return t!=-1&&s!=-1&&(i.source=e,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=rs(i,i.path),i.queryKey=is(i,i.query),i}function rs(n,e){const t=/\/{2,9}/g,s=e.replace(t,"/").split("/");return(e.slice(0,1)=="/"||e.length===0)&&s.splice(0,1),e.slice(-1)=="/"&&s.splice(s.length-1,1),s}function is(n,e){const t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(s,r,i){r&&(t[r]=i)}),t}const Ce=typeof addEventListener=="function"&&typeof removeEventListener=="function",he=[];Ce&&addEventListener("offline",()=>{he.forEach(n=>n())},!1);class M extends w{constructor(e,t){if(super(),this.binaryType=qt,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&typeof e=="object"&&(t=e,e=null),e){const s=Oe(e);t.hostname=s.host,t.secure=s.protocol==="https"||s.protocol==="wss",t.port=s.port,s.query&&(t.query=s.query)}else t.host&&(t.hostname=Oe(t.host).host);ge(this,t),this.secure=t.secure!=null?t.secure:typeof location<"u"&&location.protocol==="https:",t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=t.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(s=>{const r=s.prototype.name;this.transports.push(r),this._transportsByName[r]=s}),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},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=Vt(this.opts.query)),Ce&&(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"})},he.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=ct,t.transport=e,this.id&&(t.sid=this.id);const s=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](s)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const e=this.opts.rememberUpgrade&&M.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const t=this.createTransport(e);t.open(),this.setTransport(t)}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",t=>this._onClose("transport close",t))}onOpen(){this.readyState="open",M.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(e){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const t=new Error("server error");t.code=e.data,this._onError(t);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._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),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 t=1;for(let s=0;s<this.writeBuffer.length;s++){const r=this.writeBuffer[s].data;if(r&&(t+=Mt(r)),s>0&&t>this._maxPayload)return this.writeBuffer.slice(0,s);t+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,me(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,s){return this._sendPacket("message",e,t,s),this}send(e,t,s){return this._sendPacket("message",e,t,s),this}_sendPacket(e,t,s,r){if(typeof t=="function"&&(r=t,t=void 0),typeof s=="function"&&(r=s,s=null),this.readyState==="closing"||this.readyState==="closed")return;s=s||{},s.compress=s.compress!==!1;const i={type:e,data:t,options:s};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),r&&this.once("flush",r),this.flush()}close(){const e=()=>{this._onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},s=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?s():e()}):this.upgrading?s():e()),this}_onError(e){if(M.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),Ce&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const s=he.indexOf(this._offlineEventListener);s!==-1&&he.splice(s,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}M.protocol=ct;class os extends M{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}_probe(e){let t=this.createTransport(e),s=!1;M.priorWebsocketSuccess=!1;const r=()=>{s||(t.send([{type:"ping",data:"probe"}]),t.once("packet",g=>{if(!s)if(g.type==="pong"&&g.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;M.priorWebsocketSuccess=t.name==="websocket",this.transport.pause(()=>{s||this.readyState!=="closed"&&(y(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{const R=new Error("probe error");R.transport=t.name,this.emitReserved("upgradeError",R)}}))};function i(){s||(s=!0,y(),t.close(),t=null)}const o=g=>{const R=new Error("probe error: "+g);R.transport=t.name,i(),this.emitReserved("upgradeError",R)};function h(){o("transport closed")}function f(){o("socket closed")}function m(g){t&&g.name!==t.name&&i()}const y=()=>{t.removeListener("open",r),t.removeListener("error",o),t.removeListener("close",h),this.off("close",f),this.off("upgrading",m)};t.once("open",r),t.once("error",o),t.once("close",h),this.once("close",f),this.once("upgrading",m),this._upgrades.indexOf("webtransport")!==-1&&e!=="webtransport"?this.setTimeoutFn(()=>{s||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){const t=[];for(let s=0;s<e.length;s++)~this.transports.indexOf(e[s])&&t.push(e[s]);return t}}let as=class extends os{constructor(e,t={}){const s=typeof e=="object",r=s?{...e}:{...t};(!r.transports||r.transports&&typeof r.transports[0]=="string")&&(r.transports=(r.transports||["polling","websocket","webtransport"]).map(i=>ts[i]).filter(i=>!!i)),super(s?r:e,r)}};function cs(n,e="",t){let s=n;t=t||typeof location<"u"&&location,n==null&&(n=t.protocol+"//"+t.host),typeof n=="string"&&(n.charAt(0)==="/"&&(n.charAt(1)==="/"?n=t.protocol+n:n=t.host+n),/^(https?|wss?):\/\//.test(n)||(typeof t<"u"?n=t.protocol+"//"+n:n="https://"+n),s=Oe(n)),s.port||(/^(http|ws)$/.test(s.protocol)?s.port="80":/^(http|ws)s$/.test(s.protocol)&&(s.port="443")),s.path=s.path||"/";const i=s.host.indexOf(":")!==-1?"["+s.host+"]":s.host;return s.id=s.protocol+"://"+i+":"+s.port+e,s.href=s.protocol+"://"+i+(t&&t.port===s.port?"":":"+s.port),s}const hs=typeof ArrayBuffer=="function",us=n=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(n):n.buffer instanceof ArrayBuffer,pt=Object.prototype.toString,ls=typeof Blob=="function"||typeof Blob<"u"&&pt.call(Blob)==="[object BlobConstructor]",fs=typeof File=="function"||typeof File<"u"&&pt.call(File)==="[object FileConstructor]";function Je(n){return hs&&(n instanceof ArrayBuffer||us(n))||ls&&n instanceof Blob||fs&&n instanceof File}function ue(n,e){if(!n||typeof n!="object")return!1;if(Array.isArray(n)){for(let t=0,s=n.length;t<s;t++)if(ue(n[t]))return!0;return!1}if(Je(n))return!0;if(n.toJSON&&typeof n.toJSON=="function"&&arguments.length===1)return ue(n.toJSON(),!0);for(const t in n)if(Object.prototype.hasOwnProperty.call(n,t)&&ue(n[t]))return!0;return!1}function ds(n){const e=[],t=n.data,s=n;return s.data=Re(t,e),s.attachments=e.length,{packet:s,buffers:e}}function Re(n,e){if(!n)return n;if(Je(n)){const t={_placeholder:!0,num:e.length};return e.push(n),t}else if(Array.isArray(n)){const t=new Array(n.length);for(let s=0;s<n.length;s++)t[s]=Re(n[s],e);return t}else if(typeof n=="object"&&!(n instanceof Date)){const t={};for(const s in n)Object.prototype.hasOwnProperty.call(n,s)&&(t[s]=Re(n[s],e));return t}return n}function ps(n,e){return n.data=$e(n.data,e),delete n.attachments,n}function $e(n,e){if(!n)return n;if(n&&n._placeholder===!0){if(typeof n.num=="number"&&n.num>=0&&n.num<e.length)return e[n.num];throw new Error("illegal attachments")}else if(Array.isArray(n))for(let t=0;t<n.length;t++)n[t]=$e(n[t],e);else if(typeof n=="object")for(const t in n)Object.prototype.hasOwnProperty.call(n,t)&&(n[t]=$e(n[t],e));return n}const ys=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var p;(function(n){n[n.CONNECT=0]="CONNECT",n[n.DISCONNECT=1]="DISCONNECT",n[n.EVENT=2]="EVENT",n[n.ACK=3]="ACK",n[n.CONNECT_ERROR=4]="CONNECT_ERROR",n[n.BINARY_EVENT=5]="BINARY_EVENT",n[n.BINARY_ACK=6]="BINARY_ACK"})(p||(p={}));class ms{constructor(e){this.replacer=e}encode(e){return(e.type===p.EVENT||e.type===p.ACK)&&ue(e)?this.encodeAsBinary({type:e.type===p.EVENT?p.BINARY_EVENT:p.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===p.BINARY_EVENT||e.type===p.BINARY_ACK)&&(t+=e.attachments+"-"),e.nsp&&e.nsp!=="/"&&(t+=e.nsp+","),e.id!=null&&(t+=e.id),e.data!=null&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){const t=ds(e),s=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(s),r}}class Ge extends w{constructor(e){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},typeof e=="function"?{reviver:e}:e)}add(e){let t;if(typeof e=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const s=t.type===p.BINARY_EVENT;s||t.type===p.BINARY_ACK?(t.type=s?p.EVENT:p.ACK,this.reconstructor=new gs(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if(Je(e)||e.base64)if(this.reconstructor)t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+e)}decodeString(e){let t=0;const s={type:Number(e.charAt(0))};if(p[s.type]===void 0)throw new Error("unknown packet type "+s.type);if(s.type===p.BINARY_EVENT||s.type===p.BINARY_ACK){const i=t+1;for(;e.charAt(++t)!=="-"&&t!=e.length;);const o=e.substring(i,t);if(o!=Number(o)||e.charAt(t)!=="-")throw new Error("Illegal attachments");const h=Number(o);if(!ws(h)||h<0)throw new Error("Illegal attachments");if(h>this.opts.maxAttachments)throw new Error("too many attachments");s.attachments=h}if(e.charAt(t+1)==="/"){const i=t+1;for(;++t&&!(e.charAt(t)===","||t===e.length););s.nsp=e.substring(i,t)}else s.nsp="/";const r=e.charAt(t+1);if(r!==""&&Number(r)==r){const i=t+1;for(;++t;){const o=e.charAt(t);if(o==null||Number(o)!=o){--t;break}if(t===e.length)break}s.id=Number(e.substring(i,t+1))}if(e.charAt(++t)){const i=this.tryParse(e.substr(t));if(Ge.isPayloadValid(s.type,i))s.data=i;else throw new Error("invalid payload")}return s}tryParse(e){try{return JSON.parse(e,this.opts.reviver)}catch{return!1}}static isPayloadValid(e,t){switch(e){case p.CONNECT:return tt(t);case p.DISCONNECT:return t===void 0;case p.CONNECT_ERROR:return typeof t=="string"||tt(t);case p.EVENT:case p.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&ys.indexOf(t[0])===-1);case p.ACK:case p.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class gs{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const t=ps(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const ws=Number.isInteger||function(n){return typeof n=="number"&&isFinite(n)&&Math.floor(n)===n};function tt(n){return Object.prototype.toString.call(n)==="[object Object]"}const _s=Object.freeze(Object.defineProperty({__proto__:null,Decoder:Ge,Encoder:ms,get PacketType(){return p}},Symbol.toStringTag,{value:"Module"}));function C(n,e,t){return n.on(e,t),function(){n.off(e,t)}}const bs=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class yt extends w{constructor(e,t,s){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=t,s&&s.auth&&(this.auth=s.auth),this._opts=Object.assign({},s),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[C(e,"open",this.onopen.bind(this)),C(e,"packet",this.onpacket.bind(this)),C(e,"error",this.onerror.bind(this)),C(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,...t){var s,r,i;if(bs.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const o={type:p.EVENT,data:t};if(o.options={},o.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){const y=this.ids++,g=t.pop();this._registerAckCallback(y,g),o.id=y}const h=(r=(s=this.io.engine)===null||s===void 0?void 0:s.transport)===null||r===void 0?void 0:r.writable,f=this.connected&&!(!((i=this.io.engine)===null||i===void 0)&&i._hasPingExpired());return this.flags.volatile&&!h||(f?(this.notifyOutgoingListeners(o),this.packet(o)):this.sendBuffer.push(o)),this.flags={},this}_registerAckCallback(e,t){var s;const r=(s=this.flags.timeout)!==null&&s!==void 0?s:this._opts.ackTimeout;if(r===void 0){this.acks[e]=t;return}const i=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let h=0;h<this.sendBuffer.length;h++)this.sendBuffer[h].id===e&&this.sendBuffer.splice(h,1);t.call(this,new Error("operation has timed out"))},r),o=(...h)=>{this.io.clearTimeoutFn(i),t.apply(this,h)};o.withError=!0,this.acks[e]=o}emitWithAck(e,...t){return new Promise((s,r)=>{const i=(o,h)=>o?r(o):s(h);i.withError=!0,t.push(i),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]=="function"&&(t=e.pop());const s={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((r,...i)=>(this._queue[0],r!==null?s.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(r)):(this._queue.shift(),t&&t(null,...i)),s.pending=!1,this._drainQueue())),this._queue.push(s),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||this._queue.length===0)return;const t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.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:p.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,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(s=>String(s.id)===e)){const s=this.acks[e];delete this.acks[e],s.withError&&s.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case p.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 p.EVENT:case p.BINARY_EVENT:this.onevent(e);break;case p.ACK:case p.BINARY_ACK:this.onack(e);break;case p.DISCONNECT:this.ondisconnect();break;case p.CONNECT_ERROR:this.destroy();const s=new Error(e.data.message);s.data=e.data.data,this.emitReserved("connect_error",s);break}}onevent(e){const t=e.data||[];e.id!=null&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const s of t)s.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 t=this;let s=!1;return function(...r){s||(s=!0,t.packet({type:p.ACK,id:e,data:r}))}}onack(e){const t=this.acks[e.id];typeof t=="function"&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}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:p.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 t=this._anyListeners;for(let s=0;s<t.length;s++)if(e===t[s])return t.splice(s,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 t=this._anyOutgoingListeners;for(let s=0;s<t.length;s++)if(e===t[s])return t.splice(s,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const s of t)s.apply(this,e.data)}}}function Q(n){n=n||{},this.ms=n.min||100,this.max=n.max||1e4,this.factor=n.factor||2,this.jitter=n.jitter>0&&n.jitter<=1?n.jitter:0,this.attempts=0}Q.prototype.duration=function(){var n=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),t=Math.floor(e*this.jitter*n);n=Math.floor(e*10)&1?n+t:n-t}return Math.min(n,this.max)|0};Q.prototype.reset=function(){this.attempts=0};Q.prototype.setMin=function(n){this.ms=n};Q.prototype.setMax=function(n){this.max=n};Q.prototype.setJitter=function(n){this.jitter=n};class Ne extends w{constructor(e,t){var s;super(),this.nsps={},this.subs=[],e&&typeof e=="object"&&(t=e,e=void 0),t=t||{},t.path=t.path||"/socket.io",this.opts=t,ge(this,t),this.reconnection(t.reconnection!==!1),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor((s=t.randomizationFactor)!==null&&s!==void 0?s:.5),this.backoff=new Q({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState="closed",this.uri=e;const r=t.parser||_s;this.encoder=new r.Encoder,this.decoder=new r.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(t=this.backoff)===null||t===void 0||t.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)===null||t===void 0||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)===null||t===void 0||t.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 as(this.uri,this.opts);const t=this.engine,s=this;this._readyState="opening",this.skipReconnect=!1;const r=C(t,"open",function(){s.onopen(),e&&e()}),i=h=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",h),e?e(h):this.maybeReconnectOnOpen()},o=C(t,"error",i);if(this._timeout!==!1){const h=this._timeout,f=this.setTimeoutFn(()=>{r(),i(new Error("timeout")),t.close()},h);this.opts.autoUnref&&f.unref(),this.subs.push(()=>{this.clearTimeoutFn(f)})}return this.subs.push(r),this.subs.push(o),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(C(e,"ping",this.onping.bind(this)),C(e,"data",this.ondata.bind(this)),C(e,"error",this.onerror.bind(this)),C(e,"close",this.onclose.bind(this)),C(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(t){this.onclose("parse error",t)}}ondecoded(e){me(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let s=this.nsps[e];return s?this._autoConnect&&!s.active&&s.connect():(s=new yt(this,e,t),this.nsps[e]=s),s}_destroy(e){const t=Object.keys(this.nsps);for(const s of t)if(this.nsps[s].active)return;this._close()}_packet(e){const t=this.encoder.encode(e);for(let s=0;s<t.length;s++)this.engine.write(t[s],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")}disconnect(){return this._close()}onclose(e,t){var s;this.cleanup(),(s=this.engine)===null||s===void 0||s.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),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 t=this.backoff.duration();this._reconnecting=!0;const s=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(r=>{r?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",r)):e.onreconnect()}))},t);this.opts.autoUnref&&s.unref(),this.subs.push(()=>{this.clearTimeoutFn(s)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const Z={};function se(n,e){typeof n=="object"&&(e=n,n=void 0),e=e||{};const t=cs(n,e.path||"/socket.io"),s=t.source,r=t.id,i=t.path,o=Z[r]&&i in Z[r].nsps,h=e.forceNew||e["force new connection"]||e.multiplex===!1||o;let f;return h?f=new Ne(s,e):(Z[r]||(Z[r]=new Ne(s,e)),f=Z[r]),t.query&&!e.query&&(e.query=t.queryKey),f.socket(t.path,e)}Object.assign(se,{Manager:Ne,Socket:yt,io:se,connect:se});const Pe=100;function Ts(n){try{const e=JSON.parse(n);if(e&&typeof e=="object"){const t=e;return{message:typeof t.message=="string"?t.message:void 0,code:typeof t.code=="string"?t.code:void 0,details:t.details}}}catch{}return{}}function Es(n){if(!n||typeof n!="object")return;const e=n.retryAfter;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0}class we extends Error{constructor(t,s,r,i){const o=Ts(r);super(o.message??`${s||"Request failed"} (${t})`);E(this,"status");E(this,"code");E(this,"details");E(this,"body");E(this,"retryAfter");this.name="RequestError",this.status=t,this.code=o.code,this.details=o.details,this.body=r,this.retryAfter=i??Es(o.details)}}const $="item/folder",d="item",L="processor",vs="npm-registry",B="hidden",ve="FILE",ke="TOOL",Ae="APP",ks=500,st=3e4,As=.25,Ss=n=>new Promise(e=>setTimeout(e,n));function Os(n){var r,i;const e=(i=(r=n.headers)==null?void 0:r.get)==null?void 0:i.call(r,"Retry-After");if(!e)return;const t=Number(e);if(Number.isFinite(t))return Math.max(0,t);const s=Date.parse(e);if(!Number.isNaN(s))return Math.max(0,(s-Date.now())/1e3)}function Cs(n){return n instanceof we?n.status===429||n.status>=500:!0}function Rs(n,e){const t=Math.min(ks*2**e,st),s=t*As*Math.random(),r=n instanceof we&&n.retryAfter!=null?n.retryAfter*1e3:void 0;return r!=null?Math.min(r,st)+s:t+s}var c,Be,l,q,te,le,fe,xe,Ie,mt;const We=class We{constructor(e,t,s){_(this,c);E(this,"apiUrl");E(this,"accessToken");E(this,"wsUrl");E(this,"retries");E(this,"useBearer");E(this,"builtInGlobals",null);E(this,"localServerUrl",null);E(this,"context");const{retries:r=0,useBearer:i=!1,localServerUrl:o}=s||{};let h=t;if(h.charAt(h.length-1)==="/"&&(h=h.slice(0,-1)),this.apiUrl=`${h}/api`,this.accessToken=e,this.wsUrl=h,this.retries=r,this.useBearer=i,this.context={appId:"",projectId:"",accessToken:e,apiUrl:t},o){let f=o;f.charAt(f.length-1)==="/"&&(f=f.slice(0,-1)),this.localServerUrl=f}}static fromPlatformContext(e){const t=(typeof window<"u"?window.__THATOPEN_CONTEXT__:null)||{appId:"",projectId:"",accessToken:"",apiUrl:""},s=new We(t.accessToken,t.apiUrl,{...e,useBearer:!0});return s.context=t,s}setRetries(e){this.retries=e}setBuiltInGlobals(e){this.builtInGlobals=e}get socketOrigin(){return this.wsUrl.split("?")[0]}async resolveAccessToken(){return this.accessToken}async request(e,t,s){return a(this,c,l).call(this,e,t,s)}async listFiles(e){const{folderId:t,archived:s,projectId:r}=e||{};return t?await a(this,c,l).call(this,"GET",`${$}/${t}/items`,{query:{itemType:ve,archived:s}}):await a(this,c,l).call(this,"GET",`${d}`,{query:{itemType:ve,archived:s,...r&&{projectId:r}}})}async getFile(e,t){return await a(this,c,Ie).call(this,e,t)}async createFile(e){return await a(this,c,fe).call(this,e,ve)}async updateFile(e,t){return await a(this,c,xe).call(this,e,t)}async archiveFile(e){return await a(this,c,l).call(this,"DELETE",`${d}/${e}`)}async recoverFile(e){return await a(this,c,l).call(this,"PUT",`${d}/${e}/recover`)}async downloadFile(e,t){return await a(this,c,le).call(this,e,t)}async getFileVersionMetadata(e,t,s){const{withDraft:r}=s||{};return await a(this,c,l).call(this,"GET",`${d}/${encodeURIComponent(e)}/version/${encodeURIComponent(t)}/metadata`,{query:{...r&&{withDraft:"true"}}})}async updateFileVersionMetadata(e,t,s){return await a(this,c,l).call(this,"PUT",`${d}/${encodeURIComponent(e)}/version/${encodeURIComponent(t)}/metadata`,{body:JSON.stringify({metadata:s}),contentType:"application/json"})}async deleteFileVersionMetadata(e,t){return await a(this,c,l).call(this,"DELETE",`${d}/${encodeURIComponent(e)}/version/${encodeURIComponent(t)}/metadata`)}async getFileVersionMetadataBatch(e,t){const{withDraft:s}=t||{};return await a(this,c,te).call(this,e,async r=>(await a(this,c,l).call(this,"POST",`${d}/batch/version-metadata`,{body:JSON.stringify({entries:r,...s!==void 0&&{withDraft:s}}),contentType:"application/json"})).results)}async listFolders(e){const{archived:t,parentFolderId:s,projectId:r}=e||{};return await a(this,c,l).call(this,"GET",$,{query:{parentFolderId:s,archived:t,...r&&{projectId:r}}})}async getFolder(e){return await a(this,c,l).call(this,"GET",`${$}/${e}`)}async getFoldersBatch(e){return await a(this,c,te).call(this,e,async t=>(await a(this,c,l).call(this,"POST",`${d}/batch/folders`,{body:JSON.stringify({folderIds:t}),contentType:"application/json"})).results)}async createFolder(e,t,s){return await a(this,c,l).call(this,"POST",$,{body:JSON.stringify({name:e,...t&&{parentId:t},...s&&{projectId:s}}),contentType:"application/json"})}async updateFolder(e,t){const{name:s}=t;return await a(this,c,l).call(this,"PUT",`${$}/${e}`,{body:JSON.stringify({name:s}),contentType:"application/json"})}async archiveFolder(e){return await a(this,c,l).call(this,"DELETE",`${$}/${e}`)}async recoverFolder(e){return await a(this,c,l).call(this,"PUT",`${$}/${e}/recover`)}async downloadFolder(e){return await a(this,c,q).call(this,`${$}/${e}/download`)}async listComponents(e){const{folderId:t,ShowVersions:s,projectId:r}=e||{};return t?await a(this,c,l).call(this,"GET",`${$}/${t}/items`,{query:{itemType:ke,...s&&{ShowVersions:s}}}):await a(this,c,l).call(this,"GET",`${d}`,{query:{itemType:ke,...s&&{ShowVersions:s},...r&&{projectId:r}}})}async getComponent(e,t){return await a(this,c,Ie).call(this,e,t)}async createComponent(e){const{componentProps:t}=e;return await a(this,c,fe).call(this,e,ke,t)}async updateComponent(e,t){const{componentProps:s}=t;return await a(this,c,xe).call(this,e,t,s)}async downloadComponent(e,t){return await a(this,c,le).call(this,e,t)}async downloadComponentBundle(e,t){const{versionTag:s,withDraft:r}=t||{};return await a(this,c,q).call(this,`${d}/${e}/download/bundle`,{query:{...s&&{versionTag:s},...r&&{withDraft:r}}})}async archiveComponent(e){return await a(this,c,l).call(this,"DELETE",`${d}/${e}`)}async recoverComponent(e){return await a(this,c,l).call(this,"PUT",`${d}/${e}/recover`)}async getBuiltInComponent(e){return await(await a(this,c,q).call(this,`built-in/${e}/bundle`)).text()}async initBuiltInComponent(e,t,s){const r=await this.getBuiltInComponent(e.uuid),i=s??this.builtInGlobals??(typeof window<"u"?window.ThatOpenCompany:{})??{},o=Object.keys(i),h=o.map(g=>i[g]),m=new Function(...o,`${r}
2
- return main;`)(...h),y=(m==null?void 0:m.componentDefinition)??m;t.get(y)}async initBuiltInComponents(e,...t){await Promise.all(t.map(s=>this.initBuiltInComponent(s,e)))}async setup(e,...t){var o,h;const s=e.OBC,r=e.BUI;if(!(s!=null&&s.Components))throw new Error("globals.OBC must include Components");if(!(r!=null&&r.Manager))throw new Error("globals.BUI must include Manager");const i=new s.Components;return r.Manager.init(),this.setBuiltInGlobals(e),await this.initBuiltInComponents(i,...t),i.init(),(h=(o=this.context.appEventOrchestrator)==null?void 0:o.appLoaded)==null||h.call(o),{components:i}}throwError(e,t){var s,r;(r=(s=this.context.appEventOrchestrator)==null?void 0:s.appError)==null||r.call(s,e,t)}async listApps(e){const{folderId:t,ShowVersions:s,projectId:r}=e||{};return t?await a(this,c,l).call(this,"GET",`${$}/${t}/items`,{query:{itemType:Ae,...s&&{ShowVersions:s}}}):await a(this,c,l).call(this,"GET",`${d}`,{query:{itemType:Ae,...s&&{ShowVersions:s},...r&&{projectId:r}}})}async createApp(e){const{appProps:t}=e;return await a(this,c,fe).call(this,e,Ae,t)}async downloadApp(e,t){return await a(this,c,le).call(this,e,t)}async downloadAppBundle(e,t){const{versionTag:s,withDraft:r}=t||{};return await a(this,c,q).call(this,`${d}/${e}/download/bundle`,{query:{...s&&{versionTag:s},...r&&{withDraft:r}}})}async archiveApp(e){return await a(this,c,l).call(this,"DELETE",`${d}/${e}`)}async getNpmCredentials(){return await a(this,c,l).call(this,"GET",`${vs}/credentials`)}async executeComponent(e,t,s){if(this.localServerUrl){const r=`${this.localServerUrl}/api/${L}/${e}/execute`,i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!i.ok){const o=await i.text().catch(()=>"");throw new Error(`Local server request failed: ${i.status} - ${o}`)}return await i.json()}return await a(this,c,l).call(this,"POST",`${L}/${e}/execute`,{body:JSON.stringify(t),query:{...s&&{versionTag:s}},contentType:"application/json"})}async abortExecution(e){if(this.localServerUrl){const t=`${this.localServerUrl}/api/${L}/progress/${e}/abort`,s=await fetch(t,{method:"POST"});if(!s.ok){const r=await s.text().catch(()=>"");throw new Error(`Local server request failed: ${s.status} - ${r}`)}return await s.json()}return await a(this,c,l).call(this,"POST",`${L}/progress/${e}/abort`)}async listExecutions(e,t){if(this.localServerUrl){const s=t?`?projectId=${encodeURIComponent(t)}`:"",r=`${this.localServerUrl}/api/${L}/${e}/progress${s}`,i=await fetch(r);if(!i.ok){const o=await i.text().catch(()=>"");throw new Error(`Local server request failed: ${i.status} - ${o}`)}return await i.json()}return await a(this,c,l).call(this,"GET",`${L}/${e}/progress`,{query:{...t&&{projectId:t}}})}async getExecution(e){if(this.localServerUrl){const t=`${this.localServerUrl}/api/${L}/progress/${e}`,s=await fetch(t);if(!s.ok){const r=await s.text().catch(()=>"");throw new Error(`Local server request failed: ${s.status} - ${r}`)}return await s.json()}return await a(this,c,l).call(this,"GET",`${L}/progress/${e}`)}async onExecutionProgress(e,t){const s=this.localServerUrl??this.wsUrl,r=await se(s,{auth:{accessToken:this.accessToken},transports:["websocket"]});r.on("connect",function(){r.emit("executionSubscription",JSON.stringify({executionId:e})),r.on("execution",i=>{t(i)})}),r.on("connect_error",function(i){console.log(i)})}async createHiddenFile(e,t,s){const r=new FormData;return r.append("file",e),r.append("parentItemId",t),s!=null&&r.append("tag",s),await a(this,c,l).call(this,"POST",`${d}/${B}`,{body:r})}async createHiddenFilesBatch(e,t,s){const r=new FormData;for(const i of e)r.append("files",i);return r.append("parentItemId",t),s!=null&&r.append("tag",s),await a(this,c,l).call(this,"POST",`${d}/${B}/batch`,{body:r})}async deleteHiddenFile(e){return await a(this,c,l).call(this,"DELETE",`${d}/${B}/${e}`)}async getHiddenFile(e){return await a(this,c,l).call(this,"GET",`${d}/${B}/${e}`)}async downloadHiddenFile(e){return await a(this,c,q).call(this,`${d}/${B}/${e}/download`)}async getHiddenFileSignedUrl(e,t){return await a(this,c,l).call(this,"GET",`${d}/${B}/${e}/signed-url`,{...t!=null&&{query:{expiresIn:t}}})}async getHiddenFileSignedUrlsBatch(e,t){return await a(this,c,te).call(this,e,async s=>(await a(this,c,l).call(this,"POST",`${d}/${B}/signed-url/batch`,{body:JSON.stringify({hiddenFileIds:s,...t!=null&&{expiresIn:t}}),contentType:"application/json"})).results)}async getHiddenFilesByParent(e,t){return await a(this,c,l).call(this,"GET",`${d}/${e}/${B}`,{...t!=null&&{query:{tag:t}}})}async deleteHiddenFilesByParent(e){return await a(this,c,l).call(this,"DELETE",`${d}/${e}/${B}`)}async uploadItemIcon(e,t){const s=new FormData;return s.append("icon",t),await a(this,c,l).call(this,"PUT",`${d}/${e}/icon`,{body:s})}async getItemIcon(e){return await a(this,c,q).call(this,`${d}/${e}/icon`)}async removeItemIcon(e){return await a(this,c,l).call(this,"DELETE",`${d}/${e}/icon`)}async updateItem(e,t){return await a(this,c,l).call(this,"PUT",`${d}/${e}`,{body:JSON.stringify(t),contentType:"application/json"})}async createVersion(e,t,s,r,i){const o=new FormData;return o.append("file",t),o.append("versionTag",s),r&&o.append("extraProps",JSON.stringify(r)),i&&o.append("metadata",JSON.stringify(i)),await a(this,c,l).call(this,"POST",`${d}/${e}/version`,{body:o})}async listVersions(e,t={}){return await a(this,c,l).call(this,"GET",`${d}/${encodeURIComponent(e)}/versions`,{query:t})}async listVersionsBatch(e,t={}){const{archived:s}=t;return await a(this,c,te).call(this,e,async r=>(await a(this,c,l).call(this,"POST",`${d}/batch/versions`,{body:JSON.stringify({itemIds:r,...s!==void 0&&{archived:s}}),contentType:"application/json"})).results)}async archiveVersion(e,t){return await a(this,c,l).call(this,"PUT",`${d}/${encodeURIComponent(e)}/version/${encodeURIComponent(t)}/archive`)}async recoverVersion(e,t){return await a(this,c,l).call(this,"PUT",`${d}/${encodeURIComponent(e)}/version/${encodeURIComponent(t)}/recover`)}async deleteVersion(e,t){return await a(this,c,l).call(this,"DELETE",`${d}/${encodeURIComponent(e)}/version/${encodeURIComponent(t)}`)}};c=new WeakSet,Be=function(e){return`${this.apiUrl}/${e}`},l=async function(e,t,s){const{body:r,query:i,contentType:o,retries:h,responseType:f,retryAttempt:m}=s||{},y=a(this,c,Be).call(this,t),g=a(this,c,mt).call(this,i),R=await this.resolveAccessToken(),At={...g,...this.useBearer?{}:{accessToken:R}};try{const O=await fetch(y+"?"+new URLSearchParams(At).toString(),{method:e,headers:{Accept:"application/json",...o&&{"Content-Type":o},...this.useBearer&&{Authorization:`Bearer ${R}`}},...r&&{body:r}});if(!O.ok){const V=await O.text().then(ie=>ie).catch(()=>"");throw new we(O.status,O.statusText,V,Os(O))}return f==="blob"?await O.blob():O.json().then(V=>V).catch(()=>{})}catch(O){const V=h??this.retries;if(V>0&&Cs(O)){const ie=m??0;return await Ss(Rs(O,ie)),await a(this,c,l).call(this,e,t,{...s,retries:V-1,retryAttempt:ie+1})}throw O}},q=async function(e,t){const{query:s}=t||{},r=a(this,c,Be).call(this,e),i=await this.resolveAccessToken(),o={...s,...this.useBearer?{}:{accessToken:i}};return await fetch(r+"?"+new URLSearchParams(o).toString(),{method:"GET",...this.useBearer&&{headers:{Authorization:`Bearer ${i}`}}})},te=async function(e,t){if(!e.length)return[];const s=[];for(let i=0;i<e.length;i+=Pe)s.push(e.slice(i,i+Pe));return(await Promise.all(s.map(t))).flat()},le=async function(e,t){const{versionTag:s,withDraft:r}=t||{};return await a(this,c,q).call(this,`${d}/${e}/download`,{query:{...s&&{versionTag:s},...r&&{withDraft:r}}})},fe=async function(e,t,s){const{name:r,versionTag:i,parentFolderId:o,projectId:h,file:f,metadata:m}=e,y=new FormData;return y.append("file",f),y.append("name",r),y.append("versionTag",i),y.append("itemType",t),o&&y.append("folderId",o),h&&y.append("projectId",h),s&&y.append("extraProps",JSON.stringify(s)),m&&y.append("metadata",JSON.stringify(m)),await a(this,c,l).call(this,"POST",d,{body:y})},xe=async function(e,t,s){const{name:r,versionTag:i,parentFolderId:o,file:h,metadata:f}=t;let m,y;if(h){const g=new FormData;g.append("file",h),i&&g.append("versionTag",i),s&&g.append("extraProps",JSON.stringify(s)),f&&g.append("metadata",JSON.stringify(f)),y=await a(this,c,l).call(this,"POST",`${d}/${e}/version`,{body:g})}if(r||o){const g={...r&&{name:r},...o&&{folderId:o}},R=JSON.stringify(g);m=await a(this,c,l).call(this,"PUT",`${d}/${e}`,{body:R,contentType:"application/json"})}return{item:m,version:y}},Ie=async function(e,t){const{showVersions:s=!1}=t||{};return await a(this,c,l).call(this,"GET",`${d}/${e}`,{query:{showVersions:s}})},mt=function(e){return e&&Object.entries(e).filter(([,t])=>t!==void 0).reduce((t,[s,r])=>(t[s]=r,t),{})};let ye=We;function gt(){if(typeof window>"u"||window.parent===window)throw new Error("client.channel only works inside a That Open app, which runs in an iframe of the platform.");return{post:n=>window.parent.postMessage(n,"*"),listen:n=>{const e=t=>{t.source===window.parent&&n(t.data)};return window.addEventListener("message",e),()=>window.removeEventListener("message",e)}}}const Le="channel:",$s=1e4;function de(n){try{n()}catch(e){console.error("[channel] a listener threw:",e)}}var x,k,A,Y,W,K,v,qe,Ue,G;class Ye{constructor(e,t){_(this,v);_(this,x,!1);_(this,k,[]);_(this,A,[]);_(this,Y,new Set);_(this,W,new Set);_(this,K,new Set);this.transport=e,this.controls=t}get joined(){return u(this,x)}get peers(){return u(this,k)}join(){return u(this,x)?Promise.resolve():a(this,v,qe).call(this,"joined",this.controls.join)}leave(){return!u(this,x)&&!u(this,A).some(e=>e.want==="joined")?Promise.resolve():a(this,v,qe).call(this,"left",this.controls.leave)}onChange(e){return u(this,Y).add(e),()=>void u(this,Y).delete(e)}onPeerJoined(e){return u(this,W).add(e),()=>void u(this,W).delete(e)}onPeerLeft(e){return u(this,K).add(e),()=>void u(this,K).delete(e)}applyJoined(){T(this,x,!0),a(this,v,Ue).call(this,"joined"),a(this,v,G).call(this)}applyLeft(){T(this,x,!1),T(this,k,[]),a(this,v,Ue).call(this,"left"),a(this,v,G).call(this)}applyPeers(e){T(this,k,e),a(this,v,G).call(this)}applyPeerJoined(e){!u(this,x)||u(this,k).some(t=>t.from===e.from)||(T(this,k,[...u(this,k),e]),u(this,W).forEach(t=>de(()=>t(e))),a(this,v,G).call(this))}applyPeerLeft(e){const t=u(this,k).find(s=>s.from===e);t&&(T(this,k,u(this,k).filter(s=>s.from!==e)),u(this,K).forEach(s=>de(()=>s(t))),a(this,v,G).call(this))}failPending(e){const t=u(this,A);return T(this,A,[]),t.forEach(s=>{clearTimeout(s.timer),s.reject(e)}),t.length>0}post(e){this.transport.post(e)}}x=new WeakMap,k=new WeakMap,A=new WeakMap,Y=new WeakMap,W=new WeakMap,K=new WeakMap,v=new WeakSet,qe=function(e,t){return new Promise((s,r)=>{const i={want:e,resolve:s,reject:r,timer:setTimeout(()=>{T(this,A,u(this,A).filter(o=>o!==i)),r(new Error(`The platform did not confirm ${e==="joined"?"joining":"leaving"} in time.`))},$s)};u(this,A).push(i),this.transport.post({type:"APP_CHANNEL_CONTROL",...t})})},Ue=function(e){const t=u(this,A).filter(s=>s.want===e);T(this,A,u(this,A).filter(s=>s.want!==e)),t.forEach(s=>{clearTimeout(s.timer),s.resolve()})},G=function(){u(this,Y).forEach(e=>de(e))};var X;class wt extends Ye{constructor(t){super(t,{join:{action:"joinCollab"},leave:{action:"leaveCollab"}});_(this,X,new Map)}on(t,s){const r=u(this,X).get(t)??new Set;return r.add(s),u(this,X).set(t,r),()=>void r.delete(s)}send(t,s){if(t.startsWith(Le))throw new Error(`Message types starting with '${Le}' are reserved.`);this.joined&&this.post({type:"APP_CHANNEL_PUBLISH",message:{type:t,payload:s}})}accepts(t){return t===void 0||t==="collab"}async handle(t){const s=u(this,X).get(t.type);if(!(s!=null&&s.size))return{handled:!1};const r=bt(t);return s.forEach(i=>de(()=>i(t.payload,r))),{handled:!0}}}X=new WeakMap;var U;class _t extends Ye{constructor(t,s){super(t,{join:{action:"joinExternal",kind:s},leave:{action:"leaveExternal",kind:s}});_(this,U,new Map);this.kind=s}on(t,s){if(u(this,U).has(t))throw new Error(`"${t}" already has a handler in this room. Remove it first.`);return u(this,U).set(t,s),()=>void u(this,U).delete(t)}accepts(t,s){return t!==void 0&&t!=="external"?!1:this.kind===void 0||t===void 0||this.kind===s}get hasHandlers(){return u(this,U).size>0}async handle(t){const s=u(this,U).get(t.type);if(!s)return{handled:!1};try{return{handled:!0,value:await s(t.payload,bt(t))}}catch(r){return{handled:!0,error:r instanceof Error?r.message:String(r)}}}}U=new WeakMap;function bt(n){return{from:n.from,at:n.at,requestId:n.requestId,kind:n.kind}}function Ns(n){const e=n;if((e==null?void 0:e.type)!=="THATOPEN_CHANNEL_MESSAGE")return null;const t=e.message;return!t||typeof t.type!="string"?null:{type:t.type,requestId:typeof t.requestId=="string"?t.requestId:void 0,payload:t.payload,at:typeof t.at=="number"?t.at:Date.now(),from:typeof t.from=="string"?t.from:"",scope:t.scope==="collab"||t.scope==="external"?t.scope:void 0,kind:typeof t.kind=="string"?t.kind:void 0}}var j,ne,I,D,F,b,De,pe,Et,vt,kt,Fe;class Tt{constructor(e){_(this,b);_(this,j);_(this,ne);_(this,I);_(this,D,new Map);_(this,F,new Set);T(this,j,e),T(this,ne,e.listen(t=>void a(this,b,Et).call(this,t)))}collab(){return u(this,I)??T(this,I,new wt(u(this,j))),u(this,I)}external(e){const t=e??"";let s=u(this,D).get(t);return s||(s=new _t(u(this,j),e),u(this,D).set(t,s)),s}dispose(){u(this,ne).call(this)}}j=new WeakMap,ne=new WeakMap,I=new WeakMap,D=new WeakMap,F=new WeakMap,b=new WeakSet,De=function(){return[...u(this,I)?[u(this,I)]:[],...u(this,D).values()]},pe=function(e,t){if(e==="collab")return u(this,I);if(e==="external")return u(this,D).get(typeof t=="string"?t:"")},Et=async function(e){const t=Ns(e);if(t){if(t.type.startsWith(Le)){a(this,b,vt).call(this,t);return}await a(this,b,kt).call(this,t)}},vt=function(e){var s,r,i;const t=e.payload??{};switch(e.type){case"channel:joined":(s=a(this,b,pe).call(this,t.scope,t.kind))==null||s.applyJoined();break;case"channel:left":(r=a(this,b,pe).call(this,t.scope,t.kind))==null||r.applyLeft();break;case"channel:peers":(i=a(this,b,pe).call(this,t.scope,t.kind))==null||i.applyPeers(t.peers??[]);break;case"channel:peer-joined":case"channel:peer-left":{if(!t.from)break;const o=t.scope==="collab"?[u(this,I)]:[...u(this,D).values()].filter(h=>h.accepts("external",t.kind));for(const h of o)e.type==="channel:peer-joined"?h==null||h.applyPeerJoined({from:t.from,kind:t.kind}):h==null||h.applyPeerLeft(t.from);break}case"channel:error":{const o=new Error(String(e.payload));a(this,b,De).call(this).map(f=>f.failPending(o)).some(Boolean)||console.error("[channel] error:",e.payload);break}}},kt=async function(e){const t=a(this,b,De).call(this).filter(i=>i.accepts(e.scope,e.kind));let s=!1;for(const i of t){const o=await i.handle(e);o.handled&&(s=!0,e.requestId&&a(this,b,Fe).call(this,e.requestId,o))}e.requestId&&e.scope==="external"&&t.length>0&&!s&&a(this,b,Fe).call(this,e.requestId,{handled:!0,error:`No handler for "${e.type}".`})},Fe=function(e,t){u(this,F).has(e)||(u(this,F).add(e),u(this,F).size>500&&u(this,F).delete(u(this,F).values().next().value),u(this,j).post({type:"APP_CHANNEL_PUBLISH",message:{type:t.error===void 0?"reply":"reply-error",requestId:e,payload:t.error===void 0?t.value:{error:t.error}}}))};const H="project",J="notifications";var z,re;const Ke=class Ke extends ye{constructor(t,s,r){super(typeof t=="string"?t:"",s,{...r,useBearer:!0});_(this,z);_(this,re);typeof t=="function"&&T(this,z,t)}async resolveAccessToken(){return u(this,z)?await u(this,z).call(this):super.resolveAccessToken()}static fromPlatformContext(t){const s=(typeof window<"u"?window.__THATOPEN_CONTEXT__:null)||{appId:"",projectId:"",accessToken:"",apiUrl:""},r=new Ke(s.accessToken,s.apiUrl,t);return r.context=s,r}get channel(){return u(this,re)??T(this,re,new Tt(gt())),u(this,re)}async listProjects(){return await this.request("GET",H)}async getProject(t){return await this.request("GET",`${H}/${t}`)}async getProjectData(t){return await this.request("GET",`${H}/${t}/data`)}async getAvatar(t){return await this.request("GET",`account/${t}/avatar`,{responseType:"blob"})}async checkPermission(t){return await this.request("GET",`${H}/permissions/check`,{query:t})}async checkPermissionBatch(t){return(await this.request("POST",`${H}/permissions/check/batch`,{body:JSON.stringify({checks:t}),contentType:"application/json"})).results}async getNotifications(t){return await this.request("GET",J,{query:{...(t==null?void 0:t.cursor)!==void 0&&{cursor:t.cursor},...(t==null?void 0:t.limit)!==void 0&&{limit:String(t.limit)}}})}async getUnreadNotificationCount(){return(await this.request("GET",`${J}/unread-count`)).count}async markNotificationsRead(t){return await this.request("POST",`${J}/mark-read`,{body:JSON.stringify({ids:t}),contentType:"application/json"})}async markAllNotificationsRead(){return await this.request("POST",`${J}/mark-all-read`)}async getNotificationSubscriptions(){return await this.request("GET",`${J}/subscriptions`)}async unsubscribeFromAutomation(t){return await this.request("DELETE",`${J}/subscriptions/${t}`)}async subscribeToAutomation(t,s,r){return await this.request("POST",`${H}/${t}/events/hooks/${s}/subscription`,{body:JSON.stringify(r??{}),contentType:"application/json"})}async updateAutomationSubscription(t,s,r){return await this.request("PATCH",`${H}/${t}/events/hooks/${s}/subscription`,{body:JSON.stringify(r),contentType:"application/json"})}async onNotification(t){const s=await this.resolveAccessToken(),r=se(`${this.socketOrigin}/notifications`,{auth:{accessToken:s},transports:["websocket"]});return r.on("notification.created",i=>t({type:"created",id:i==null?void 0:i.id})),r.on("notification.read",i=>t({type:"read",id:i==null?void 0:i.id})),r.on("notifications.allRead",i=>t({type:"allRead",batch:i==null?void 0:i.batch})),()=>r.disconnect()}};z=new WeakMap,re=new WeakMap;let Me=Ke;const Ps={MAX_FIELDS:200,MAX_KEY_LENGTH:50,MAX_VALUE_LENGTH:50},Bs={uuid:"a3f82c1d-5b74-4e9a-bc30-d7e12f894a61"},xs={uuid:"2c9f4e8d-3a1b-4c5e-9d7f-0a2b6c8e1d3f"},Is={uuid:"b0b5e2a2-0b3a-4a6b-8b1c-0b1c4a6b8b1c"},Ls={uuid:"d8f3a1c2-6b4e-4f9a-8c1d-2e7b5a9f3c60"},qs={uuid:"3f9c1a7e-6b2d-4e18-9a5c-7d0e2f4b6c81"},Us={uuid:"2c4ae432-fc24-43e9-9783-0c960c674e96"},Ds={uuid:"6f3a9c2e-8b1d-4e6a-9c3f-1d7b5a8e2c4f"},Fs={uuid:"69af63aa-19ba-4fc7-b17b-75647bac1d76"},Ms={uuid:"234f1416-528d-452a-9cc9-a16c5239b2eb"};exports.CDEManager=Bs;exports.ChannelClient=Tt;exports.ChannelRoom=Ye;exports.ClashesManager=xs;exports.CollabRoom=wt;exports.EngineServicesClient=ye;exports.ExternalRoom=_t;exports.FileList=Is;exports.GISManager=Ls;exports.GitHistoryManager=qs;exports.HelloWorld=Us;exports.METADATA_LIMITS=Ps;exports.PlatformClient=Me;exports.ProjectManager=Ds;exports.RequestError=we;exports.STORAGE_BATCH_MAX=Pe;exports.TopicsManager=Fs;exports.UIManager=Ms;exports.windowTransport=gt;
1
+ "use strict";var ns=Object.defineProperty;var we=n=>{throw TypeError(n)};var rs=(n,t,e)=>t in n?ns(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e;var v=(n,t,e)=>rs(n,typeof t!="symbol"?t+"":t,e),Bt=(n,t,e)=>t.has(n)||we("Cannot "+e);var l=(n,t,e)=>(Bt(n,t,"read from private field"),e?e.call(n):t.get(n)),_=(n,t,e)=>t.has(n)?we("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(n):t.set(n,e),b=(n,t,e,s)=>(Bt(n,t,"write to private field"),s?s.call(n,e):t.set(n,e),e),a=(n,t,e)=>(Bt(n,t,"access private method"),e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const P=Object.create(null);P.open="0";P.close="1";P.ping="2";P.pong="3";P.message="4";P.upgrade="5";P.noop="6";const bt=Object.create(null);Object.keys(P).forEach(n=>{bt[P[n]]=n});const jt={type:"error",data:"parser error"},$e=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",Re=typeof ArrayBuffer=="function",Ce=n=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(n):n&&n.buffer instanceof ArrayBuffer,he=({type:n,data:t},e,s)=>$e&&t instanceof Blob?e?s(t):_e(t,s):Re&&(t instanceof ArrayBuffer||Ce(t))?e?s(t):_e(new Blob([t]),s):s(P[n]+(t||"")),_e=(n,t)=>{const e=new FileReader;return e.onload=function(){const s=e.result.split(",")[1];t("b"+(s||""))},e.readAsDataURL(n)};function be(n){return n instanceof Uint8Array?n:n instanceof ArrayBuffer?new Uint8Array(n):new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}let Lt;function is(n,t){if($e&&n.data instanceof Blob)return n.data.arrayBuffer().then(be).then(t);if(Re&&(n.data instanceof ArrayBuffer||Ce(n.data)))return t(be(n.data));he(n,!1,e=>{Lt||(Lt=new TextEncoder),t(Lt.encode(e))})}const Ee="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",ot=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let n=0;n<Ee.length;n++)ot[Ee.charCodeAt(n)]=n;const os=n=>{let t=n.length*.75,e=n.length,s,r=0,i,o,h,u;n[n.length-1]==="="&&(t--,n[n.length-2]==="="&&t--);const f=new ArrayBuffer(t),y=new Uint8Array(f);for(s=0;s<e;s+=4)i=ot[n.charCodeAt(s)],o=ot[n.charCodeAt(s+1)],h=ot[n.charCodeAt(s+2)],u=ot[n.charCodeAt(s+3)],y[r++]=i<<2|o>>4,y[r++]=(o&15)<<4|h>>2,y[r++]=(h&3)<<6|u&63;return f},as=typeof ArrayBuffer=="function",le=(n,t)=>{if(typeof n!="string")return{type:"message",data:Ne(n,t)};const e=n.charAt(0);return e==="b"?{type:"message",data:cs(n.substring(1),t)}:bt[e]?n.length>1?{type:bt[e],data:n.substring(1)}:{type:bt[e]}:jt},cs=(n,t)=>{if(as){const e=os(n);return Ne(e,t)}else return{base64:!0,data:n}},Ne=(n,t)=>{switch(t){case"blob":return n instanceof Blob?n:new Blob([n]);case"arraybuffer":default:return n instanceof ArrayBuffer?n:n.buffer}},Pe="",hs=(n,t)=>{const e=n.length,s=new Array(e);let r=0;n.forEach((i,o)=>{he(i,!1,h=>{s[o]=h,++r===e&&t(s.join(Pe))})})},ls=(n,t)=>{const e=n.split(Pe),s=[];for(let r=0;r<e.length;r++){const i=le(e[r],t);if(s.push(i),i.type==="error")break}return s};function us(){return new TransformStream({transform(n,t){is(n,e=>{const s=e.length;let r;if(s<126)r=new Uint8Array(1),new DataView(r.buffer).setUint8(0,s);else if(s<65536){r=new Uint8Array(3);const i=new DataView(r.buffer);i.setUint8(0,126),i.setUint16(1,s)}else{r=new Uint8Array(9);const i=new DataView(r.buffer);i.setUint8(0,127),i.setBigUint64(1,BigInt(s))}n.data&&typeof n.data!="string"&&(r[0]|=128),t.enqueue(r),t.enqueue(e)})}})}let Ft;function gt(n){return n.reduce((t,e)=>t+e.length,0)}function wt(n,t){if(n[0].length===t)return n.shift();const e=new Uint8Array(t);let s=0;for(let r=0;r<t;r++)e[r]=n[0][s++],s===n[0].length&&(n.shift(),s=0);return n.length&&s<n[0].length&&(n[0]=n[0].slice(s)),e}function ds(n,t){Ft||(Ft=new TextDecoder);const e=[];let s=0,r=-1,i=!1;return new TransformStream({transform(o,h){for(e.push(o);;){if(s===0){if(gt(e)<1)break;const u=wt(e,1);i=(u[0]&128)===128,r=u[0]&127,r<126?s=3:r===126?s=1:s=2}else if(s===1){if(gt(e)<2)break;const u=wt(e,2);r=new DataView(u.buffer,u.byteOffset,u.length).getUint16(0),s=3}else if(s===2){if(gt(e)<8)break;const u=wt(e,8),f=new DataView(u.buffer,u.byteOffset,u.length),y=f.getUint32(0);if(y>Math.pow(2,21)-1){h.enqueue(jt);break}r=y*Math.pow(2,32)+f.getUint32(4),s=3}else{if(gt(e)<r)break;const u=wt(e,r);h.enqueue(le(i?u:Ft.decode(u),t)),s=0}if(r===0||r>n){h.enqueue(jt);break}}}})}const Be=4;function E(n){if(n)return fs(n)}function fs(n){for(var t in E.prototype)n[t]=E.prototype[t];return n}E.prototype.on=E.prototype.addEventListener=function(n,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+n]=this._callbacks["$"+n]||[]).push(t),this};E.prototype.once=function(n,t){function e(){this.off(n,e),t.apply(this,arguments)}return e.fn=t,this.on(n,e),this};E.prototype.off=E.prototype.removeListener=E.prototype.removeAllListeners=E.prototype.removeEventListener=function(n,t){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var e=this._callbacks["$"+n];if(!e)return this;if(arguments.length==1)return delete this._callbacks["$"+n],this;for(var s,r=0;r<e.length;r++)if(s=e[r],s===t||s.fn===t){e.splice(r,1);break}return e.length===0&&delete this._callbacks["$"+n],this};E.prototype.emit=function(n){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),e=this._callbacks["$"+n],s=1;s<arguments.length;s++)t[s-1]=arguments[s];if(e){e=e.slice(0);for(var s=0,r=e.length;s<r;++s)e[s].apply(this,t)}return this};E.prototype.emitReserved=E.prototype.emit;E.prototype.listeners=function(n){return this._callbacks=this._callbacks||{},this._callbacks["$"+n]||[]};E.prototype.hasListeners=function(n){return!!this.listeners(n).length};const Ct=typeof Promise=="function"&&typeof Promise.resolve=="function"?t=>Promise.resolve().then(t):(t,e)=>e(t,0),O=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),ps="arraybuffer";function Le(n,...t){return t.reduce((e,s)=>(n.hasOwnProperty(s)&&(e[s]=n[s]),e),{})}const ys=O.setTimeout,ms=O.clearTimeout;function Nt(n,t){t.useNativeTimers?(n.setTimeoutFn=ys.bind(O),n.clearTimeoutFn=ms.bind(O)):(n.setTimeoutFn=O.setTimeout.bind(O),n.clearTimeoutFn=O.clearTimeout.bind(O))}const gs=1.33;function ws(n){return typeof n=="string"?_s(n):Math.ceil((n.byteLength||n.size)*gs)}function _s(n){let t=0,e=0;for(let s=0,r=n.length;s<r;s++)t=n.charCodeAt(s),t<128?e+=1:t<2048?e+=2:t<55296||t>=57344?e+=3:(s++,e+=4);return e}function Fe(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function bs(n){let t="";for(let e in n)n.hasOwnProperty(e)&&(t.length&&(t+="&"),t+=encodeURIComponent(e)+"="+encodeURIComponent(n[e]));return t}function Es(n){let t={},e=n.split("&");for(let s=0,r=e.length;s<r;s++){let i=e[s].split("=");t[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return t}class Ts extends Error{constructor(t,e,s){super(t),this.description=e,this.context=s,this.type="TransportError"}}class ue extends E{constructor(t){super(),this.writable=!1,Nt(this,t),this.opts=t,this.query=t.query,this.socket=t.socket,this.supportsBinary=!t.forceBase64}onError(t,e,s){return super.emitReserved("error",new Ts(t,e,s)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(t){this.readyState==="open"&&this.write(t)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(t){const e=le(t,this.socket.binaryType);this.onPacket(e)}onPacket(t){super.emitReserved("packet",t)}onClose(t){this.readyState="closed",super.emitReserved("close",t)}pause(t){}createUri(t,e={}){return t+"://"+this._hostname()+this._port()+this.opts.path+this._query(e)}_hostname(){const t=this.opts.hostname;return t.indexOf(":")===-1?t:"["+t+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(t){const e=bs(t);return e.length?"?"+e:""}}class vs extends ue{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(t){this.readyState="pausing";const e=()=>{this.readyState="paused",t()};if(this._polling||!this.writable){let s=0;this._polling&&(s++,this.once("pollComplete",function(){--s||e()})),this.writable||(s++,this.once("drain",function(){--s||e()}))}else e()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){const e=s=>{if(this.readyState==="opening"&&s.type==="open"&&this.onOpen(),s.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(s)};ls(t,this.socket.binaryType).forEach(e),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){const t=()=>{this.write([{type:"close"}])};this.readyState==="open"?t():this.once("open",t)}write(t){this.writable=!1,hs(t,e=>{this.doWrite(e,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const t=this.opts.secure?"https":"http",e=this.query||{};return this.opts.timestampRequests!==!1&&(e[this.opts.timestampParam]=Fe()),!this.supportsBinary&&!e.sid&&(e.b64=1),this.createUri(t,e)}}let qe=!1;try{qe=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const Ss=qe;function ks(){}class As extends vs{constructor(t){if(super(t),typeof location<"u"){const e=location.protocol==="https:";let s=location.port;s||(s=e?"443":"80"),this.xd=typeof location<"u"&&t.hostname!==location.hostname||s!==t.port}}doWrite(t,e){const s=this.request({method:"POST",data:t});s.on("success",e),s.on("error",(r,i)=>{this.onError("xhr post error",r,i)})}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(e,s)=>{this.onError("xhr poll error",e,s)}),this.pollXhr=t}}class N extends E{constructor(t,e,s){super(),this.createRequest=t,Nt(this,s),this._opts=s,this._method=s.method||"GET",this._uri=e,this._data=s.data!==void 0?s.data:null,this._create()}_create(){var t;const e=Le(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");e.xdomain=!!this._opts.xd;const s=this._xhr=this.createRequest(e);try{s.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){s.setDisableHeaderCheck&&s.setDisableHeaderCheck(!0);for(let r in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(r)&&s.setRequestHeader(r,this._opts.extraHeaders[r])}}catch{}if(this._method==="POST")try{s.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{s.setRequestHeader("Accept","*/*")}catch{}(t=this._opts.cookieJar)===null||t===void 0||t.addCookies(s),"withCredentials"in s&&(s.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(s.timeout=this._opts.requestTimeout),s.onreadystatechange=()=>{var r;s.readyState===3&&((r=this._opts.cookieJar)===null||r===void 0||r.parseCookies(s.getResponseHeader("set-cookie"))),s.readyState===4&&(s.status===200||s.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof s.status=="number"?s.status:0)},0))},s.send(this._data)}catch(r){this.setTimeoutFn(()=>{this._onError(r)},0);return}typeof document<"u"&&(this._index=N.requestsCount++,N.requests[this._index]=this)}_onError(t){this.emitReserved("error",t,this._xhr),this._cleanup(!0)}_cleanup(t){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=ks,t)try{this._xhr.abort()}catch{}typeof document<"u"&&delete N.requests[this._index],this._xhr=null}}_onLoad(){const t=this._xhr.responseText;t!==null&&(this.emitReserved("data",t),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}N.requestsCount=0;N.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",Te);else if(typeof addEventListener=="function"){const n="onpagehide"in O?"pagehide":"unload";addEventListener(n,Te,!1)}}function Te(){for(let n in N.requests)N.requests.hasOwnProperty(n)&&N.requests[n].abort()}const Os=function(){const n=Ue({xdomain:!1});return n&&n.responseType!==null}();class Is extends As{constructor(t){super(t);const e=t&&t.forceBase64;this.supportsBinary=Os&&!e}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new N(Ue,this.uri(),t)}}function Ue(n){const t=n.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!t||Ss))return new XMLHttpRequest}catch{}if(!t)try{return new O[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const De=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class xs extends ue{get name(){return"websocket"}doOpen(){const t=this.uri(),e=this.opts.protocols,s=De?{}:Le(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(s.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(t,e,s)}catch(r){return this.emitReserved("error",r)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const s=t[e],r=e===t.length-1;he(s,this.supportsBinary,i=>{try{this.doWrite(s,i)}catch{}r&&Ct(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const t=this.opts.secure?"wss":"ws",e=this.query||{};return this.opts.timestampRequests&&(e[this.opts.timestampParam]=Fe()),this.supportsBinary||(e.b64=1),this.createUri(t,e)}}const qt=O.WebSocket||O.MozWebSocket;class $s extends xs{createSocket(t,e,s){return De?new qt(t,e,s):e?new qt(t,e):new qt(t)}doWrite(t,e){this.ws.send(e)}}class Rs extends ue{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(t){return this.emitReserved("error",t)}this._transport.closed.then(()=>{this.onClose()}).catch(t=>{this.onError("webtransport error",t)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(t=>{const e=ds(Number.MAX_SAFE_INTEGER,this.socket.binaryType),s=t.readable.pipeThrough(e).getReader(),r=us();r.readable.pipeTo(t.writable),this._writer=r.writable.getWriter();const i=()=>{s.read().then(({done:h,value:u})=>{h||(this.onPacket(u),i())}).catch(h=>{})};i();const o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this._writer.write(o).then(()=>this.onOpen())})})}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const s=t[e],r=e===t.length-1;this._writer.write(s).then(()=>{r&&Ct(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this._transport)===null||t===void 0||t.close()}}const Cs={websocket:$s,webtransport:Rs,polling:Is},Ns=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Ps=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Ht(n){if(n.length>8e3)throw"URI too long";const t=n,e=n.indexOf("["),s=n.indexOf("]");e!=-1&&s!=-1&&(n=n.substring(0,e)+n.substring(e,s).replace(/:/g,";")+n.substring(s,n.length));let r=Ns.exec(n||""),i={},o=14;for(;o--;)i[Ps[o]]=r[o]||"";return e!=-1&&s!=-1&&(i.source=t,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=Bs(i,i.path),i.queryKey=Ls(i,i.query),i}function Bs(n,t){const e=/\/{2,9}/g,s=t.replace(e,"/").split("/");return(t.slice(0,1)=="/"||t.length===0)&&s.splice(0,1),t.slice(-1)=="/"&&s.splice(s.length-1,1),s}function Ls(n,t){const e={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(s,r,i){r&&(e[r]=i)}),e}const Gt=typeof addEventListener=="function"&&typeof removeEventListener=="function",Et=[];Gt&&addEventListener("offline",()=>{Et.forEach(n=>n())},!1);class V extends E{constructor(t,e){if(super(),this.binaryType=ps,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,t&&typeof t=="object"&&(e=t,t=null),t){const s=Ht(t);e.hostname=s.host,e.secure=s.protocol==="https"||s.protocol==="wss",e.port=s.port,s.query&&(e.query=s.query)}else e.host&&(e.hostname=Ht(e.host).host);Nt(this,e),this.secure=e.secure!=null?e.secure:typeof location<"u"&&location.protocol==="https:",e.hostname&&!e.port&&(e.port=this.secure?"443":"80"),this.hostname=e.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=e.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},e.transports.forEach(s=>{const r=s.prototype.name;this.transports.push(r),this._transportsByName[r]=s}),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},e),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=Es(this.opts.query)),Gt&&(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"})},Et.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(t){const e=Object.assign({},this.opts.query);e.EIO=Be,e.transport=t,this.id&&(e.sid=this.id);const s=Object.assign({},this.opts,{query:e,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new this._transportsByName[t](s)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const t=this.opts.rememberUpgrade&&V.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const e=this.createTransport(t);e.open(),this.setTransport(e)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",e=>this._onClose("transport close",e))}onOpen(){this.readyState="open",V.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",t),this.emitReserved("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const e=new Error("server error");e.code=t.data,this._onError(e);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data);break}}onHandshake(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this._pingInterval=t.pingInterval,this._pingTimeout=t.pingTimeout,this._maxPayload=t.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const t=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+t,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},t),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 t=this._getWritablePackets();this.transport.send(t),this._prevBufferLen=t.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let s=0;s<this.writeBuffer.length;s++){const r=this.writeBuffer[s].data;if(r&&(e+=ws(r)),s>0&&e>this._maxPayload)return this.writeBuffer.slice(0,s);e+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const t=Date.now()>this._pingTimeoutTime;return t&&(this._pingTimeoutTime=0,Ct(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),t}write(t,e,s){return this._sendPacket("message",t,e,s),this}send(t,e,s){return this._sendPacket("message",t,e,s),this}_sendPacket(t,e,s,r){if(typeof e=="function"&&(r=e,e=void 0),typeof s=="function"&&(r=s,s=null),this.readyState==="closing"||this.readyState==="closed")return;s=s||{},s.compress=s.compress!==!1;const i={type:t,data:e,options:s};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),r&&this.once("flush",r),this.flush()}close(){const t=()=>{this._onClose("forced close"),this.transport.close()},e=()=>{this.off("upgrade",e),this.off("upgradeError",e),t()},s=()=>{this.once("upgrade",e),this.once("upgradeError",e)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?s():t()}):this.upgrading?s():t()),this}_onError(t){if(V.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",t),this._onClose("transport error",t)}_onClose(t,e){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),Gt&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const s=Et.indexOf(this._offlineEventListener);s!==-1&&Et.splice(s,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,e),this.writeBuffer=[],this._prevBufferLen=0}}}V.protocol=Be;class Fs extends V{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let t=0;t<this._upgrades.length;t++)this._probe(this._upgrades[t])}_probe(t){let e=this.createTransport(t),s=!1;V.priorWebsocketSuccess=!1;const r=()=>{s||(e.send([{type:"ping",data:"probe"}]),e.once("packet",w=>{if(!s)if(w.type==="pong"&&w.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",e),!e)return;V.priorWebsocketSuccess=e.name==="websocket",this.transport.pause(()=>{s||this.readyState!=="closed"&&(y(),this.setTransport(e),e.send([{type:"upgrade"}]),this.emitReserved("upgrade",e),e=null,this.upgrading=!1,this.flush())})}else{const R=new Error("probe error");R.transport=e.name,this.emitReserved("upgradeError",R)}}))};function i(){s||(s=!0,y(),e.close(),e=null)}const o=w=>{const R=new Error("probe error: "+w);R.transport=e.name,i(),this.emitReserved("upgradeError",R)};function h(){o("transport closed")}function u(){o("socket closed")}function f(w){e&&w.name!==e.name&&i()}const y=()=>{e.removeListener("open",r),e.removeListener("error",o),e.removeListener("close",h),this.off("close",u),this.off("upgrading",f)};e.once("open",r),e.once("error",o),e.once("close",h),this.once("close",u),this.once("upgrading",f),this._upgrades.indexOf("webtransport")!==-1&&t!=="webtransport"?this.setTimeoutFn(()=>{s||e.open()},200):e.open()}onHandshake(t){this._upgrades=this._filterUpgrades(t.upgrades),super.onHandshake(t)}_filterUpgrades(t){const e=[];for(let s=0;s<t.length;s++)~this.transports.indexOf(t[s])&&e.push(t[s]);return e}}let qs=class extends Fs{constructor(t,e={}){const s=typeof t=="object",r=s?{...t}:{...e};(!r.transports||r.transports&&typeof r.transports[0]=="string")&&(r.transports=(r.transports||["polling","websocket","webtransport"]).map(i=>Cs[i]).filter(i=>!!i)),super(s?r:t,r)}};function Us(n,t="",e){let s=n;e=e||typeof location<"u"&&location,n==null&&(n=e.protocol+"//"+e.host),typeof n=="string"&&(n.charAt(0)==="/"&&(n.charAt(1)==="/"?n=e.protocol+n:n=e.host+n),/^(https?|wss?):\/\//.test(n)||(typeof e<"u"?n=e.protocol+"//"+n:n="https://"+n),s=Ht(n)),s.port||(/^(http|ws)$/.test(s.protocol)?s.port="80":/^(http|ws)s$/.test(s.protocol)&&(s.port="443")),s.path=s.path||"/";const i=s.host.indexOf(":")!==-1?"["+s.host+"]":s.host;return s.id=s.protocol+"://"+i+":"+s.port+t,s.href=s.protocol+"://"+i+(e&&e.port===s.port?"":":"+s.port),s}const Ds=typeof ArrayBuffer=="function",Ms=n=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(n):n.buffer instanceof ArrayBuffer,Me=Object.prototype.toString,js=typeof Blob=="function"||typeof Blob<"u"&&Me.call(Blob)==="[object BlobConstructor]",Hs=typeof File=="function"||typeof File<"u"&&Me.call(File)==="[object FileConstructor]";function de(n){return Ds&&(n instanceof ArrayBuffer||Ms(n))||js&&n instanceof Blob||Hs&&n instanceof File}function Tt(n,t){if(!n||typeof n!="object")return!1;if(Array.isArray(n)){for(let e=0,s=n.length;e<s;e++)if(Tt(n[e]))return!0;return!1}if(de(n))return!0;if(n.toJSON&&typeof n.toJSON=="function"&&arguments.length===1)return Tt(n.toJSON(),!0);for(const e in n)if(Object.prototype.hasOwnProperty.call(n,e)&&Tt(n[e]))return!0;return!1}function Gs(n){const t=[],e=n.data,s=n;return s.data=Vt(e,t),s.attachments=t.length,{packet:s,buffers:t}}function Vt(n,t){if(!n)return n;if(de(n)){const e={_placeholder:!0,num:t.length};return t.push(n),e}else if(Array.isArray(n)){const e=new Array(n.length);for(let s=0;s<n.length;s++)e[s]=Vt(n[s],t);return e}else if(typeof n=="object"&&!(n instanceof Date)){const e={};for(const s in n)Object.prototype.hasOwnProperty.call(n,s)&&(e[s]=Vt(n[s],t));return e}return n}function Vs(n,t){return n.data=Jt(n.data,t),delete n.attachments,n}function Jt(n,t){if(!n)return n;if(n&&n._placeholder===!0){if(typeof n.num=="number"&&n.num>=0&&n.num<t.length)return t[n.num];throw new Error("illegal attachments")}else if(Array.isArray(n))for(let e=0;e<n.length;e++)n[e]=Jt(n[e],t);else if(typeof n=="object")for(const e in n)Object.prototype.hasOwnProperty.call(n,e)&&(n[e]=Jt(n[e],t));return n}const Js=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var g;(function(n){n[n.CONNECT=0]="CONNECT",n[n.DISCONNECT=1]="DISCONNECT",n[n.EVENT=2]="EVENT",n[n.ACK=3]="ACK",n[n.CONNECT_ERROR=4]="CONNECT_ERROR",n[n.BINARY_EVENT=5]="BINARY_EVENT",n[n.BINARY_ACK=6]="BINARY_ACK"})(g||(g={}));class Ys{constructor(t){this.replacer=t}encode(t){return(t.type===g.EVENT||t.type===g.ACK)&&Tt(t)?this.encodeAsBinary({type:t.type===g.EVENT?g.BINARY_EVENT:g.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id}):[this.encodeAsString(t)]}encodeAsString(t){let e=""+t.type;return(t.type===g.BINARY_EVENT||t.type===g.BINARY_ACK)&&(e+=t.attachments+"-"),t.nsp&&t.nsp!=="/"&&(e+=t.nsp+","),t.id!=null&&(e+=t.id),t.data!=null&&(e+=JSON.stringify(t.data,this.replacer)),e}encodeAsBinary(t){const e=Gs(t),s=this.encodeAsString(e.packet),r=e.buffers;return r.unshift(s),r}}class fe extends E{constructor(t){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},typeof t=="function"?{reviver:t}:t)}add(t){let e;if(typeof t=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");e=this.decodeString(t);const s=e.type===g.BINARY_EVENT;s||e.type===g.BINARY_ACK?(e.type=s?g.EVENT:g.ACK,this.reconstructor=new Ws(e),e.attachments===0&&super.emitReserved("decoded",e)):super.emitReserved("decoded",e)}else if(de(t)||t.base64)if(this.reconstructor)e=this.reconstructor.takeBinaryData(t),e&&(this.reconstructor=null,super.emitReserved("decoded",e));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+t)}decodeString(t){let e=0;const s={type:Number(t.charAt(0))};if(g[s.type]===void 0)throw new Error("unknown packet type "+s.type);if(s.type===g.BINARY_EVENT||s.type===g.BINARY_ACK){const i=e+1;for(;t.charAt(++e)!=="-"&&e!=t.length;);const o=t.substring(i,e);if(o!=Number(o)||t.charAt(e)!=="-")throw new Error("Illegal attachments");const h=Number(o);if(!Xs(h)||h<0)throw new Error("Illegal attachments");if(h>this.opts.maxAttachments)throw new Error("too many attachments");s.attachments=h}if(t.charAt(e+1)==="/"){const i=e+1;for(;++e&&!(t.charAt(e)===","||e===t.length););s.nsp=t.substring(i,e)}else s.nsp="/";const r=t.charAt(e+1);if(r!==""&&Number(r)==r){const i=e+1;for(;++e;){const o=t.charAt(e);if(o==null||Number(o)!=o){--e;break}if(e===t.length)break}s.id=Number(t.substring(i,e+1))}if(t.charAt(++e)){const i=this.tryParse(t.substr(e));if(fe.isPayloadValid(s.type,i))s.data=i;else throw new Error("invalid payload")}return s}tryParse(t){try{return JSON.parse(t,this.opts.reviver)}catch{return!1}}static isPayloadValid(t,e){switch(t){case g.CONNECT:return ve(e);case g.DISCONNECT:return e===void 0;case g.CONNECT_ERROR:return typeof e=="string"||ve(e);case g.EVENT:case g.BINARY_EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&Js.indexOf(e[0])===-1);case g.ACK:case g.BINARY_ACK:return Array.isArray(e)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class Ws{constructor(t){this.packet=t,this.buffers=[],this.reconPack=t}takeBinaryData(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){const e=Vs(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const Xs=Number.isInteger||function(n){return typeof n=="number"&&isFinite(n)&&Math.floor(n)===n};function ve(n){return Object.prototype.toString.call(n)==="[object Object]"}const Ks=Object.freeze(Object.defineProperty({__proto__:null,Decoder:fe,Encoder:Ys,get PacketType(){return g}},Symbol.toStringTag,{value:"Module"}));function $(n,t,e){return n.on(t,e),function(){n.off(t,e)}}const zs=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class je extends E{constructor(t,e,s){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=t,this.nsp=e,s&&s.auth&&(this.auth=s.auth),this._opts=Object.assign({},s),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const t=this.io;this.subs=[$(t,"open",this.onopen.bind(this)),$(t,"packet",this.onpacket.bind(this)),$(t,"error",this.onerror.bind(this)),$(t,"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(...t){return t.unshift("message"),this.emit.apply(this,t),this}emit(t,...e){var s,r,i;if(zs.hasOwnProperty(t))throw new Error('"'+t.toString()+'" is a reserved event name');if(e.unshift(t),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(e),this;const o={type:g.EVENT,data:e};if(o.options={},o.options.compress=this.flags.compress!==!1,typeof e[e.length-1]=="function"){const y=this.ids++,w=e.pop();this._registerAckCallback(y,w),o.id=y}const h=(r=(s=this.io.engine)===null||s===void 0?void 0:s.transport)===null||r===void 0?void 0:r.writable,u=this.connected&&!(!((i=this.io.engine)===null||i===void 0)&&i._hasPingExpired());return this.flags.volatile&&!h||(u?(this.notifyOutgoingListeners(o),this.packet(o)):this.sendBuffer.push(o)),this.flags={},this}_registerAckCallback(t,e){var s;const r=(s=this.flags.timeout)!==null&&s!==void 0?s:this._opts.ackTimeout;if(r===void 0){this.acks[t]=e;return}const i=this.io.setTimeoutFn(()=>{delete this.acks[t];for(let h=0;h<this.sendBuffer.length;h++)this.sendBuffer[h].id===t&&this.sendBuffer.splice(h,1);e.call(this,new Error("operation has timed out"))},r),o=(...h)=>{this.io.clearTimeoutFn(i),e.apply(this,h)};o.withError=!0,this.acks[t]=o}emitWithAck(t,...e){return new Promise((s,r)=>{const i=(o,h)=>o?r(o):s(h);i.withError=!0,e.push(i),this.emit(t,...e)})}_addToQueue(t){let e;typeof t[t.length-1]=="function"&&(e=t.pop());const s={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((r,...i)=>(this._queue[0],r!==null?s.tryCount>this._opts.retries&&(this._queue.shift(),e&&e(r)):(this._queue.shift(),e&&e(null,...i)),s.pending=!1,this._drainQueue())),this._queue.push(s),this._drainQueue()}_drainQueue(t=!1){if(!this.connected||this._queue.length===0)return;const e=this._queue[0];e.pending&&!t||(e.pending=!0,e.tryCount++,this.flags=e.flags,this.emit.apply(this,e.args))}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){typeof this.auth=="function"?this.auth(t=>{this._sendConnectPacket(t)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:g.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,e){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,e),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(t=>{if(!this.sendBuffer.some(s=>String(s.id)===t)){const s=this.acks[t];delete this.acks[t],s.withError&&s.call(this,new Error("socket has been disconnected"))}})}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case g.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.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 g.EVENT:case g.BINARY_EVENT:this.onevent(t);break;case g.ACK:case g.BINARY_ACK:this.onack(t);break;case g.DISCONNECT:this.ondisconnect();break;case g.CONNECT_ERROR:this.destroy();const s=new Error(t.data.message);s.data=t.data.data,this.emitReserved("connect_error",s);break}}onevent(t){const e=t.data||[];t.id!=null&&e.push(this.ack(t.id)),this.connected?this.emitEvent(e):this.receiveBuffer.push(Object.freeze(e))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){const e=this._anyListeners.slice();for(const s of e)s.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&typeof t[t.length-1]=="string"&&(this._lastOffset=t[t.length-1])}ack(t){const e=this;let s=!1;return function(...r){s||(s=!0,e.packet({type:g.ACK,id:t,data:r}))}}onack(t){const e=this.acks[t.id];typeof e=="function"&&(delete this.acks[t.id],e.withError&&t.data.unshift(null),e.apply(this,t.data))}onconnect(t,e){this.id=t,this.recovered=e&&this._pid===e,this._pid=e,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:g.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){const e=this._anyListeners;for(let s=0;s<e.length;s++)if(t===e[s])return e.splice(s,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(t),this}prependAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(t),this}offAnyOutgoing(t){if(!this._anyOutgoingListeners)return this;if(t){const e=this._anyOutgoingListeners;for(let s=0;s<e.length;s++)if(t===e[s])return e.splice(s,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(t){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const e=this._anyOutgoingListeners.slice();for(const s of e)s.apply(this,t.data)}}}function nt(n){n=n||{},this.ms=n.min||100,this.max=n.max||1e4,this.factor=n.factor||2,this.jitter=n.jitter>0&&n.jitter<=1?n.jitter:0,this.attempts=0}nt.prototype.duration=function(){var n=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),e=Math.floor(t*this.jitter*n);n=Math.floor(t*10)&1?n+e:n-e}return Math.min(n,this.max)|0};nt.prototype.reset=function(){this.attempts=0};nt.prototype.setMin=function(n){this.ms=n};nt.prototype.setMax=function(n){this.max=n};nt.prototype.setJitter=function(n){this.jitter=n};class Yt extends E{constructor(t,e){var s;super(),this.nsps={},this.subs=[],t&&typeof t=="object"&&(e=t,t=void 0),e=e||{},e.path=e.path||"/socket.io",this.opts=e,Nt(this,e),this.reconnection(e.reconnection!==!1),this.reconnectionAttempts(e.reconnectionAttempts||1/0),this.reconnectionDelay(e.reconnectionDelay||1e3),this.reconnectionDelayMax(e.reconnectionDelayMax||5e3),this.randomizationFactor((s=e.randomizationFactor)!==null&&s!==void 0?s:.5),this.backoff=new nt({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(e.timeout==null?2e4:e.timeout),this._readyState="closed",this.uri=t;const r=e.parser||Ks;this.encoder=new r.Encoder,this.decoder=new r.Decoder,this._autoConnect=e.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,t||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(t){return t===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var e;return t===void 0?this._reconnectionDelay:(this._reconnectionDelay=t,(e=this.backoff)===null||e===void 0||e.setMin(t),this)}randomizationFactor(t){var e;return t===void 0?this._randomizationFactor:(this._randomizationFactor=t,(e=this.backoff)===null||e===void 0||e.setJitter(t),this)}reconnectionDelayMax(t){var e;return t===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,(e=this.backoff)===null||e===void 0||e.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(t){if(~this._readyState.indexOf("open"))return this;this.engine=new qs(this.uri,this.opts);const e=this.engine,s=this;this._readyState="opening",this.skipReconnect=!1;const r=$(e,"open",function(){s.onopen(),t&&t()}),i=h=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",h),t?t(h):this.maybeReconnectOnOpen()},o=$(e,"error",i);if(this._timeout!==!1){const h=this._timeout,u=this.setTimeoutFn(()=>{r(),i(new Error("timeout")),e.close()},h);this.opts.autoUnref&&u.unref(),this.subs.push(()=>{this.clearTimeoutFn(u)})}return this.subs.push(r),this.subs.push(o),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push($(t,"ping",this.onping.bind(this)),$(t,"data",this.ondata.bind(this)),$(t,"error",this.onerror.bind(this)),$(t,"close",this.onclose.bind(this)),$(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(e){this.onclose("parse error",e)}}ondecoded(t){Ct(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,e){let s=this.nsps[t];return s?this._autoConnect&&!s.active&&s.connect():(s=new je(this,t,e),this.nsps[t]=s),s}_destroy(t){const e=Object.keys(this.nsps);for(const s of e)if(this.nsps[s].active)return;this._close()}_packet(t){const e=this.encoder.encode(t);for(let s=0;s<e.length;s++)this.engine.write(e[s],t.options)}cleanup(){this.subs.forEach(t=>t()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(t,e){var s;this.cleanup(),(s=this.engine)===null||s===void 0||s.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,e),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const e=this.backoff.duration();this._reconnecting=!0;const s=this.setTimeoutFn(()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),!t.skipReconnect&&t.open(r=>{r?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",r)):t.onreconnect()}))},e);this.opts.autoUnref&&s.unref(),this.subs.push(()=>{this.clearTimeoutFn(s)})}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const rt={};function ut(n,t){typeof n=="object"&&(t=n,n=void 0),t=t||{};const e=Us(n,t.path||"/socket.io"),s=e.source,r=e.id,i=e.path,o=rt[r]&&i in rt[r].nsps,h=t.forceNew||t["force new connection"]||t.multiplex===!1||o;let u;return h?u=new Yt(s,t):(rt[r]||(rt[r]=new Yt(s,t)),u=rt[r]),e.query&&!t.query&&(t.query=e.queryKey),u.socket(e.path,t)}Object.assign(ut,{Manager:Yt,Socket:je,io:ut,connect:ut});class Wt extends Error{constructor(t,e){super(`The document history advanced while this version was being prepared: expected head ${t}, found ${e??"none"}. Read the timeline again and rebuild on the new head.`),this.expectedGuid=t,this.actualGuid=e,this.name="StaleHistoryError"}}const Se="bimterop",ke="revitflow_history.json",it="revitflow_ops.json",Ae="revitflow/ops@1",Qs="revitflow_model.frag",Zs="revitflow_",_t=()=>`v-${Date.now()}`;function Y(n){return String(n._id??n.id??"")}var x,dt,Xt;class He{constructor(t,e){_(this,dt);_(this,x);this.client=t,this.projectId=e}async docs(){const t=await a(this,dt,Xt).call(this);if(!t)return[];const e=await this.client.listFolders({parentFolderId:t,projectId:this.projectId}),s=[];for(const r of e){const i=String(r.name??""),o=i.indexOf("-");o<=0||s.push({source:i.slice(0,o),docId:i.slice(o+1),modelName:void 0})}return s}doc(t,e){return new Ge(this.client,this,t,e)}async rootFolderId(t=!1){if(l(this,x))return l(this,x);const e=await a(this,dt,Xt).call(this);if(e)return e;if(!t)return;const s=await this.client.createFolder(Se,void 0,this.projectId);return b(this,x,Y(s)),l(this,x)}}x=new WeakMap,dt=new WeakSet,Xt=async function(){if(l(this,x))return l(this,x);const e=(await this.client.listFolders({projectId:this.projectId})).find(s=>String(s.name??"")===Se&&!s.parentId);return e&&b(this,x,Y(e)),l(this,x)};var L,p,at,ct,Kt,vt,St,zt,kt,ht,At,Qt,Ve;class Ge{constructor(t,e,s,r){_(this,p);_(this,L);this.client=t,this.project=e,this.source=s,this.docId=r}async timeline(){const t=await a(this,p,kt).call(this);return pe((t==null?void 0:t.commits)??[])}async latest(){const t=await this.timeline();return t.length?t[t.length-1]:null}async delta(t){if(!t.deltaId)throw new Error(`Version ${t.guid} carries no delta: it is a full export — read model() instead.`);return await(await this.client.downloadHiddenFile(t.deltaId)).blob()}async model(){const t=await a(this,p,St).call(this);if(!t)throw new Error(`Document ${this.source}-${this.docId} has no model file yet.`);return await(await this.client.downloadFile(t.id)).blob()}async sync(t){var h;const e=await a(this,p,ct).call(this,!0);let s=await a(this,p,kt).call(this)??{model:this.docId,commits:[]};const r=Oe(s.commits);if(t.expectedLatestGuid!==void 0&&(r==null?void 0:r.guid)!==t.expectedLatestGuid)throw new Wt(t.expectedLatestGuid,r==null?void 0:r.guid);const i={guid:Ie(),...r?{parents:[r.guid]}:{},author:t.author,source:t.source,timestamp:new Date().toISOString(),...t.message?{message:t.message}:{},...t.userId?{userId:t.userId}:{},...(h=t.appliedOps)!=null&&h.length?{appliedOps:t.appliedOps}:{},changes:t.changes,counts:tn(t.changes)};if(t.model&&(await a(this,p,Ve).call(this,e,t.model),i.full=!0),t.delta){const u=await a(this,p,St).call(this);if(!u)throw new Error("A delta needs the model file to hang from: sync a full model first.");const f=await this.client.createHiddenFile(t.delta,u.id);i.deltaId=String(f._id??f.id)}const o=await a(this,p,kt).call(this);if(o){s=o;const u=Oe(s.commits);if(t.expectedLatestGuid!==void 0&&(u==null?void 0:u.guid)!==t.expectedLatestGuid)throw new Wt(t.expectedLatestGuid,u==null?void 0:u.guid);u&&!i.parents&&(i.parents=[u.guid])}return s.commits.push(i),await a(this,p,At).call(this,e,ke,s),i}async suggestions(){const t=await a(this,p,ht).call(this);return(t==null?void 0:t.ops)??[]}async pendingSuggestions(){return(await this.suggestions()).filter(t=>t.state==="pending")}async suggest(t){const e=await a(this,p,ct).call(this,!0),s=await a(this,p,ht).call(this)??{schema:Ae,ops:[]},r=await a(this,p,vt).call(this,it),i={opId:Ie(),title:t.title,verb:t.verb,author:t.author,createdAt:new Date().toISOString(),state:"pending",...t.targets!==void 0?{targets:t.targets}:{},...t.batchId?{batchId:t.batchId}:{},...t.userId?{userId:t.userId}:{},...t.baseCommitGuid?{baseCommitGuid:t.baseCommitGuid}:{}};if(t.payload){const h=r??await a(this,p,Qt).call(this,e,it,s),u=await this.client.createHiddenFile(t.payload,h.id);i.fragId=String(u._id??u.id)}const o=await a(this,p,ht).call(this)??s;return o.schema??(o.schema=Ae),o.ops.push(i),await a(this,p,At).call(this,e,it,o),i}async suggestionPayload(t){if(!t.fragId)throw new Error(`Suggestion ${t.opId} carries no payload.`);return await(await this.client.downloadHiddenFile(t.fragId)).blob()}async resolveSuggestion(t,e){const s=await a(this,p,ct).call(this,!1);if(!s)throw new Error("This document has no suggestion queue.");const r=await a(this,p,ht).call(this),i=r==null?void 0:r.ops.find(o=>o.opId===t);if(!r||!i)throw new Error(`No suggestion ${t} in this document's queue.`);return Object.assign(i,e),await a(this,p,At).call(this,s,it,r),i}}L=new WeakMap,p=new WeakSet,at=function(){return`${this.source}-${this.docId}`},ct=async function(t){if(l(this,L))return l(this,L);const e=await this.project.rootFolderId(t);if(!e)throw new Error(`Project ${this.project.projectId} has no connected documents yet.`);const r=(await this.client.listFolders({parentFolderId:e,projectId:this.project.projectId})).find(o=>String(o.name??"")===l(this,p,at));if(r)return b(this,L,Y(r)),l(this,L);if(!t)throw new Error(`Document ${l(this,p,at)} does not exist in this project.`);const i=await this.client.createFolder(l(this,p,at),e,this.project.projectId);return b(this,L,Y(i)),l(this,L)},Kt=async function(){const t=await a(this,p,ct).call(this,!1);return(await this.client.listFiles({folderId:t})).map(s=>({id:Y(s),name:String(s.name??"")}))},vt=async function(t){try{return(await a(this,p,Kt).call(this)).find(e=>e.name===t)}catch{return}},St=async function(){try{const t=await a(this,p,Kt).call(this);return t.find(e=>e.name===Qs)??t.find(e=>e.name.endsWith(".frag")&&!e.name.startsWith(Zs))}catch{return}},zt=async function(t){const e=await a(this,p,vt).call(this,t);if(!e)return;const r=await(await this.client.downloadFile(e.id)).text();if(r.trim())return JSON.parse(r)},kt=function(){return a(this,p,zt).call(this,ke)},ht=function(){return a(this,p,zt).call(this,it)},At=async function(t,e,s){const r=new Blob([JSON.stringify(s)],{type:"application/json"}),i=await a(this,p,vt).call(this,e);return i?(await this.client.updateFile(i.id,{file:r,versionTag:_t()}),i):await a(this,p,Qt).call(this,t,e,s)},Qt=async function(t,e,s){const r=new Blob([JSON.stringify(s)],{type:"application/json"}),i=await this.client.createFile({file:r,name:e,versionTag:_t(),parentFolderId:t,projectId:this.project.projectId}),o=i.item;return{id:Y(o??i),name:e}},Ve=async function(t,e){const s=await a(this,p,St).call(this);if(s)return await this.client.updateFile(s.id,{file:e,versionTag:_t()}),s;const r=`${l(this,p,at)}.frag`,i=await this.client.createFile({file:e,name:r,versionTag:_t(),parentFolderId:t,projectId:this.project.projectId}),o=i.item;return{id:Y(o??i),name:r}};function tn(n){const t={added:0,modified:0,removed:0};for(const e of n)e.type==="create"?t.added++:e.type==="delete"?t.removed++:t.modified++;return t}function pe(n){var u;if(n.length<=1)return n.forEach((f,y)=>f.ordinal=y),[...n];const t=new Map(n.map(f=>[f.guid,f])),e=new Map,s=[];for(const f of n){const y=(u=f.parents)==null?void 0:u[0];if(y&&t.has(y)){const w=e.get(y)??[];w.push(f),e.set(y,w)}else s.push(f)}const r=(f,y)=>String(f.timestamp).localeCompare(String(y.timestamp));s.sort(r);const i=[],o=[...s].reverse(),h=new Set;for(;o.length;){const f=o.pop();if(h.has(f.guid))continue;h.add(f.guid),i.push(f);const y=(e.get(f.guid)??[]).sort(r);for(let w=y.length-1;w>=0;w--)o.push(y[w])}for(const f of n)h.has(f.guid)||i.push(f);return i.forEach((f,y)=>f.ordinal=y),i}function Oe(n){const t=pe(n);return t[t.length-1]}function Ie(){const n=globalThis.crypto;return n!=null&&n.randomUUID?n.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}var M;class Je{constructor(t){_(this,M,new Map);this.client=t}register(t){if(l(this,M).has(t.name))throw new Error(`A recipe named "${t.name}" is already registered.`);l(this,M).set(t.name,t)}list(t){return[...l(this,M).values()].filter(s=>(!(t!=null&&t.to)||s.to===t.to)&&(!(t!=null&&t.input)||s.inputs.includes(t.input)))}get(t){return l(this,M).get(t)}async run(t,e){const s=l(this,M).get(t);if(!s)throw new Error(`No recipe named "${t}" is registered.`);if(s.to!==e.target.source)throw new Error(`Recipe "${t}" writes ${s.to}, but the target document belongs to ${e.target.source}.`);const r=this.client.history(e.projectId).doc(e.target.source,e.target.docId),i=await r.latest(),o=await s.run({client:this.client,projectId:e.projectId,targetDoc:r,input:e.input,settings:e.settings??{}});return{suggestion:await r.suggest({title:o.title,verb:o.verb,author:e.author,payload:o.payload,targets:o.targets,userId:e.userId,baseCommitGuid:i==null?void 0:i.guid}),result:o}}}M=new WeakMap;const Zt=100;function en(n){try{const t=JSON.parse(n);if(t&&typeof t=="object"){const e=t;return{message:typeof e.message=="string"?e.message:void 0,code:typeof e.code=="string"?e.code:void 0,details:e.details}}}catch{}return{}}function sn(n){if(!n||typeof n!="object")return;const t=n.retryAfter;return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}class Pt extends Error{constructor(e,s,r,i){const o=en(r);super(o.message??`${s||"Request failed"} (${e})`);v(this,"status");v(this,"code");v(this,"details");v(this,"body");v(this,"retryAfter");this.name="RequestError",this.status=e,this.code=o.code,this.details=o.details,this.body=r,this.retryAfter=i??sn(o.details)}}const C="item/folder",m="item",U="processor",nn="npm-registry",B="hidden",Ut="FILE",Dt="TOOL",Mt="APP",rn=500,xe=3e4,on=.25,an=n=>new Promise(t=>setTimeout(t,n));function cn(n){var r,i;const t=(i=(r=n.headers)==null?void 0:r.get)==null?void 0:i.call(r,"Retry-After");if(!t)return;const e=Number(t);if(Number.isFinite(e))return Math.max(0,e);const s=Date.parse(t);if(!Number.isNaN(s))return Math.max(0,(s-Date.now())/1e3)}function hn(n){return n instanceof Pt?n.status===429||n.status>=500:!0}function ln(n,t){const e=Math.min(rn*2**t,xe),s=e*on*Math.random(),r=n instanceof Pt&&n.retryAfter!=null?n.retryAfter*1e3:void 0;return r!=null?Math.min(r,xe)+s:e+s}var c,te,d,D,ft,lt,Ot,It,ee,se,Ye;const me=class me{constructor(t,e,s){_(this,c);v(this,"apiUrl");v(this,"accessToken");v(this,"wsUrl");v(this,"retries");v(this,"useBearer");v(this,"builtInGlobals",null);v(this,"localServerUrl",null);v(this,"context");_(this,ft);const{retries:r=0,useBearer:i=!1,localServerUrl:o}=s||{};let h=e;if(h.charAt(h.length-1)==="/"&&(h=h.slice(0,-1)),this.apiUrl=`${h}/api`,this.accessToken=t,this.wsUrl=h,this.retries=r,this.useBearer=i,this.context={appId:"",projectId:"",accessToken:t,apiUrl:e},o){let u=o;u.charAt(u.length-1)==="/"&&(u=u.slice(0,-1)),this.localServerUrl=u}}static fromPlatformContext(t){const e=(typeof window<"u"?window.__THATOPEN_CONTEXT__:null)||{appId:"",projectId:"",accessToken:"",apiUrl:""},s=new me(e.accessToken,e.apiUrl,{...t,useBearer:!0});return s.context=e,s}setRetries(t){this.retries=t}setBuiltInGlobals(t){this.builtInGlobals=t}get socketOrigin(){return this.wsUrl.split("?")[0]}async resolveAccessToken(){return this.accessToken}async request(t,e,s){return a(this,c,d).call(this,t,e,s)}async listFiles(t){const{folderId:e,archived:s,projectId:r}=t||{};return e?await a(this,c,d).call(this,"GET",`${C}/${e}/items`,{query:{itemType:Ut,archived:s}}):await a(this,c,d).call(this,"GET",`${m}`,{query:{itemType:Ut,archived:s,...r&&{projectId:r}}})}async getFile(t,e){return await a(this,c,se).call(this,t,e)}async createFile(t){return await a(this,c,It).call(this,t,Ut)}async updateFile(t,e){return await a(this,c,ee).call(this,t,e)}async archiveFile(t){return await a(this,c,d).call(this,"DELETE",`${m}/${t}`)}async recoverFile(t){return await a(this,c,d).call(this,"PUT",`${m}/${t}/recover`)}async downloadFile(t,e){return await a(this,c,Ot).call(this,t,e)}async getFileVersionMetadata(t,e,s){const{withDraft:r}=s||{};return await a(this,c,d).call(this,"GET",`${m}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/metadata`,{query:{...r&&{withDraft:"true"}}})}async updateFileVersionMetadata(t,e,s){return await a(this,c,d).call(this,"PUT",`${m}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/metadata`,{body:JSON.stringify({metadata:s}),contentType:"application/json"})}async deleteFileVersionMetadata(t,e){return await a(this,c,d).call(this,"DELETE",`${m}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/metadata`)}async getFileVersionMetadataBatch(t,e){const{withDraft:s}=e||{};return await a(this,c,lt).call(this,t,async r=>(await a(this,c,d).call(this,"POST",`${m}/batch/version-metadata`,{body:JSON.stringify({entries:r,...s!==void 0&&{withDraft:s}}),contentType:"application/json"})).results)}async listFolders(t){const{archived:e,parentFolderId:s,projectId:r}=t||{};return await a(this,c,d).call(this,"GET",C,{query:{parentFolderId:s,archived:e,...r&&{projectId:r}}})}async getFolder(t){return await a(this,c,d).call(this,"GET",`${C}/${t}`)}async getFoldersBatch(t){return await a(this,c,lt).call(this,t,async e=>(await a(this,c,d).call(this,"POST",`${m}/batch/folders`,{body:JSON.stringify({folderIds:e}),contentType:"application/json"})).results)}async createFolder(t,e,s){return await a(this,c,d).call(this,"POST",C,{body:JSON.stringify({name:t,...e&&{parentId:e},...s&&{projectId:s}}),contentType:"application/json"})}async updateFolder(t,e){const{name:s}=e;return await a(this,c,d).call(this,"PUT",`${C}/${t}`,{body:JSON.stringify({name:s}),contentType:"application/json"})}async archiveFolder(t){return await a(this,c,d).call(this,"DELETE",`${C}/${t}`)}async recoverFolder(t){return await a(this,c,d).call(this,"PUT",`${C}/${t}/recover`)}async downloadFolder(t){return await a(this,c,D).call(this,`${C}/${t}/download`)}async listComponents(t){const{folderId:e,ShowVersions:s,projectId:r}=t||{};return e?await a(this,c,d).call(this,"GET",`${C}/${e}/items`,{query:{itemType:Dt,...s&&{ShowVersions:s}}}):await a(this,c,d).call(this,"GET",`${m}`,{query:{itemType:Dt,...s&&{ShowVersions:s},...r&&{projectId:r}}})}async getComponent(t,e){return await a(this,c,se).call(this,t,e)}async createComponent(t){const{componentProps:e}=t;return await a(this,c,It).call(this,t,Dt,e)}async updateComponent(t,e){const{componentProps:s}=e;return await a(this,c,ee).call(this,t,e,s)}async downloadComponent(t,e){return await a(this,c,Ot).call(this,t,e)}async downloadComponentBundle(t,e){const{versionTag:s,withDraft:r}=e||{};return await a(this,c,D).call(this,`${m}/${t}/download/bundle`,{query:{...s&&{versionTag:s},...r&&{withDraft:r}}})}async archiveComponent(t){return await a(this,c,d).call(this,"DELETE",`${m}/${t}`)}async recoverComponent(t){return await a(this,c,d).call(this,"PUT",`${m}/${t}/recover`)}async getBuiltInComponent(t){return await(await a(this,c,D).call(this,`built-in/${t}/bundle`)).text()}async initBuiltInComponent(t,e,s){const r=await this.getBuiltInComponent(t.uuid),i=s??this.builtInGlobals??(typeof window<"u"?window.ThatOpenCompany:{})??{},o=Object.keys(i),h=o.map(w=>i[w]),f=new Function(...o,`${r}
2
+ return main;`)(...h),y=(f==null?void 0:f.componentDefinition)??f;e.get(y)}async initBuiltInComponents(t,...e){await Promise.all(e.map(s=>this.initBuiltInComponent(s,t)))}async setup(t,...e){var o,h;const s=t.OBC,r=t.BUI;if(!(s!=null&&s.Components))throw new Error("globals.OBC must include Components");if(!(r!=null&&r.Manager))throw new Error("globals.BUI must include Manager");const i=new s.Components;return r.Manager.init(),this.setBuiltInGlobals(t),await this.initBuiltInComponents(i,...e),i.init(),(h=(o=this.context.appEventOrchestrator)==null?void 0:o.appLoaded)==null||h.call(o),{components:i}}throwError(t,e){var s,r;(r=(s=this.context.appEventOrchestrator)==null?void 0:s.appError)==null||r.call(s,t,e)}async listApps(t){const{folderId:e,ShowVersions:s,projectId:r}=t||{};return e?await a(this,c,d).call(this,"GET",`${C}/${e}/items`,{query:{itemType:Mt,...s&&{ShowVersions:s}}}):await a(this,c,d).call(this,"GET",`${m}`,{query:{itemType:Mt,...s&&{ShowVersions:s},...r&&{projectId:r}}})}async createApp(t){const{appProps:e}=t;return await a(this,c,It).call(this,t,Mt,e)}async downloadApp(t,e){return await a(this,c,Ot).call(this,t,e)}async downloadAppBundle(t,e){const{versionTag:s,withDraft:r}=e||{};return await a(this,c,D).call(this,`${m}/${t}/download/bundle`,{query:{...s&&{versionTag:s},...r&&{withDraft:r}}})}async archiveApp(t){return await a(this,c,d).call(this,"DELETE",`${m}/${t}`)}async getNpmCredentials(){return await a(this,c,d).call(this,"GET",`${nn}/credentials`)}async executeComponent(t,e,s){if(this.localServerUrl){const r=`${this.localServerUrl}/api/${U}/${t}/execute`,i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!i.ok){const o=await i.text().catch(()=>"");throw new Error(`Local server request failed: ${i.status} - ${o}`)}return await i.json()}return await a(this,c,d).call(this,"POST",`${U}/${t}/execute`,{body:JSON.stringify(e),query:{...s&&{versionTag:s}},contentType:"application/json"})}async abortExecution(t){if(this.localServerUrl){const e=`${this.localServerUrl}/api/${U}/progress/${t}/abort`,s=await fetch(e,{method:"POST"});if(!s.ok){const r=await s.text().catch(()=>"");throw new Error(`Local server request failed: ${s.status} - ${r}`)}return await s.json()}return await a(this,c,d).call(this,"POST",`${U}/progress/${t}/abort`)}async listExecutions(t,e){if(this.localServerUrl){const s=e?`?projectId=${encodeURIComponent(e)}`:"",r=`${this.localServerUrl}/api/${U}/${t}/progress${s}`,i=await fetch(r);if(!i.ok){const o=await i.text().catch(()=>"");throw new Error(`Local server request failed: ${i.status} - ${o}`)}return await i.json()}return await a(this,c,d).call(this,"GET",`${U}/${t}/progress`,{query:{...e&&{projectId:e}}})}async getExecution(t){if(this.localServerUrl){const e=`${this.localServerUrl}/api/${U}/progress/${t}`,s=await fetch(e);if(!s.ok){const r=await s.text().catch(()=>"");throw new Error(`Local server request failed: ${s.status} - ${r}`)}return await s.json()}return await a(this,c,d).call(this,"GET",`${U}/progress/${t}`)}async onExecutionProgress(t,e){const s=this.localServerUrl??this.wsUrl,r=await ut(s,{auth:{accessToken:this.accessToken},transports:["websocket"]});r.on("connect",function(){r.emit("executionSubscription",JSON.stringify({executionId:t})),r.on("execution",i=>{e(i)})}),r.on("connect_error",function(i){console.log(i)})}history(t){return new He(this,t)}get recipes(){return l(this,ft)??b(this,ft,new Je(this)),l(this,ft)}async createHiddenFile(t,e,s){const r=new FormData;return r.append("file",t),r.append("parentItemId",e),s!=null&&r.append("tag",s),await a(this,c,d).call(this,"POST",`${m}/${B}`,{body:r})}async createHiddenFilesBatch(t,e,s){const r=new FormData;for(const i of t)r.append("files",i);return r.append("parentItemId",e),s!=null&&r.append("tag",s),await a(this,c,d).call(this,"POST",`${m}/${B}/batch`,{body:r})}async deleteHiddenFile(t){return await a(this,c,d).call(this,"DELETE",`${m}/${B}/${t}`)}async getHiddenFile(t){return await a(this,c,d).call(this,"GET",`${m}/${B}/${t}`)}async downloadHiddenFile(t){return await a(this,c,D).call(this,`${m}/${B}/${t}/download`)}async getHiddenFileSignedUrl(t,e){return await a(this,c,d).call(this,"GET",`${m}/${B}/${t}/signed-url`,{...e!=null&&{query:{expiresIn:e}}})}async getHiddenFileSignedUrlsBatch(t,e){return await a(this,c,lt).call(this,t,async s=>(await a(this,c,d).call(this,"POST",`${m}/${B}/signed-url/batch`,{body:JSON.stringify({hiddenFileIds:s,...e!=null&&{expiresIn:e}}),contentType:"application/json"})).results)}async getHiddenFilesByParent(t,e){return await a(this,c,d).call(this,"GET",`${m}/${t}/${B}`,{...e!=null&&{query:{tag:e}}})}async deleteHiddenFilesByParent(t){return await a(this,c,d).call(this,"DELETE",`${m}/${t}/${B}`)}async uploadItemIcon(t,e){const s=new FormData;return s.append("icon",e),await a(this,c,d).call(this,"PUT",`${m}/${t}/icon`,{body:s})}async getItemIcon(t){return await a(this,c,D).call(this,`${m}/${t}/icon`)}async removeItemIcon(t){return await a(this,c,d).call(this,"DELETE",`${m}/${t}/icon`)}async updateItem(t,e){return await a(this,c,d).call(this,"PUT",`${m}/${t}`,{body:JSON.stringify(e),contentType:"application/json"})}async createVersion(t,e,s,r,i){const o=new FormData;return o.append("file",e),o.append("versionTag",s),r&&o.append("extraProps",JSON.stringify(r)),i&&o.append("metadata",JSON.stringify(i)),await a(this,c,d).call(this,"POST",`${m}/${t}/version`,{body:o})}async listVersions(t,e={}){return await a(this,c,d).call(this,"GET",`${m}/${encodeURIComponent(t)}/versions`,{query:e})}async listVersionsBatch(t,e={}){const{archived:s}=e;return await a(this,c,lt).call(this,t,async r=>(await a(this,c,d).call(this,"POST",`${m}/batch/versions`,{body:JSON.stringify({itemIds:r,...s!==void 0&&{archived:s}}),contentType:"application/json"})).results)}async archiveVersion(t,e){return await a(this,c,d).call(this,"PUT",`${m}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/archive`)}async recoverVersion(t,e){return await a(this,c,d).call(this,"PUT",`${m}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/recover`)}async deleteVersion(t,e){return await a(this,c,d).call(this,"DELETE",`${m}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}`)}};c=new WeakSet,te=function(t){return`${this.apiUrl}/${t}`},d=async function(t,e,s){const{body:r,query:i,contentType:o,retries:h,responseType:u,retryAttempt:f}=s||{},y=a(this,c,te).call(this,e),w=a(this,c,Ye).call(this,i),R=await this.resolveAccessToken(),ss={...w,...this.useBearer?{}:{accessToken:R}};try{const I=await fetch(y+"?"+new URLSearchParams(ss).toString(),{method:t,headers:{Accept:"application/json",...o&&{"Content-Type":o},...this.useBearer&&{Authorization:`Bearer ${R}`}},...r&&{body:r}});if(!I.ok){const X=await I.text().then(mt=>mt).catch(()=>"");throw new Pt(I.status,I.statusText,X,cn(I))}return u==="blob"?await I.blob():I.json().then(X=>X).catch(()=>{})}catch(I){const X=h??this.retries;if(X>0&&hn(I)){const mt=f??0;return await an(ln(I,mt)),await a(this,c,d).call(this,t,e,{...s,retries:X-1,retryAttempt:mt+1})}throw I}},D=async function(t,e){const{query:s}=e||{},r=a(this,c,te).call(this,t),i=await this.resolveAccessToken(),o={...s,...this.useBearer?{}:{accessToken:i}};return await fetch(r+"?"+new URLSearchParams(o).toString(),{method:"GET",...this.useBearer&&{headers:{Authorization:`Bearer ${i}`}}})},ft=new WeakMap,lt=async function(t,e){if(!t.length)return[];const s=[];for(let i=0;i<t.length;i+=Zt)s.push(t.slice(i,i+Zt));return(await Promise.all(s.map(e))).flat()},Ot=async function(t,e){const{versionTag:s,withDraft:r}=e||{};return await a(this,c,D).call(this,`${m}/${t}/download`,{query:{...s&&{versionTag:s},...r&&{withDraft:r}}})},It=async function(t,e,s){const{name:r,versionTag:i,parentFolderId:o,projectId:h,file:u,metadata:f}=t,y=new FormData;return y.append("file",u),y.append("name",r),y.append("versionTag",i),y.append("itemType",e),o&&y.append("folderId",o),h&&y.append("projectId",h),s&&y.append("extraProps",JSON.stringify(s)),f&&y.append("metadata",JSON.stringify(f)),await a(this,c,d).call(this,"POST",m,{body:y})},ee=async function(t,e,s){const{name:r,versionTag:i,parentFolderId:o,file:h,metadata:u}=e;let f,y;if(h){const w=new FormData;w.append("file",h),i&&w.append("versionTag",i),s&&w.append("extraProps",JSON.stringify(s)),u&&w.append("metadata",JSON.stringify(u)),y=await a(this,c,d).call(this,"POST",`${m}/${t}/version`,{body:w})}if(r||o){const w={...r&&{name:r},...o&&{folderId:o}},R=JSON.stringify(w);f=await a(this,c,d).call(this,"PUT",`${m}/${t}`,{body:R,contentType:"application/json"})}return{item:f,version:y}},se=async function(t,e){const{showVersions:s=!1}=e||{};return await a(this,c,d).call(this,"GET",`${m}/${t}`,{query:{showVersions:s}})},Ye=function(t){return t&&Object.entries(t).filter(([,e])=>e!==void 0).reduce((e,[s,r])=>(e[s]=r,e),{})};let Rt=me;function We(){if(typeof window>"u"||window.parent===window)throw new Error("client.channel only works inside a That Open app, which runs in an iframe of the platform.");return{post:n=>window.parent.postMessage(n,"*"),listen:n=>{const t=e=>{e.source===window.parent&&n(e.data)};return window.addEventListener("message",t),()=>window.removeEventListener("message",t)}}}const ne="channel:",un=1e4;function xt(n){try{n()}catch(t){console.error("[channel] a listener threw:",t)}}var F,k,A,Q,Z,tt,S,re,ie,z;class ye{constructor(t,e){_(this,S);_(this,F,!1);_(this,k,[]);_(this,A,[]);_(this,Q,new Set);_(this,Z,new Set);_(this,tt,new Set);this.transport=t,this.controls=e}get joined(){return l(this,F)}get peers(){return l(this,k)}join(){return l(this,F)?Promise.resolve():a(this,S,re).call(this,"joined",this.controls.join)}leave(){return!l(this,F)&&!l(this,A).some(t=>t.want==="joined")?Promise.resolve():a(this,S,re).call(this,"left",this.controls.leave)}onChange(t){return l(this,Q).add(t),()=>void l(this,Q).delete(t)}onPeerJoined(t){return l(this,Z).add(t),()=>void l(this,Z).delete(t)}onPeerLeft(t){return l(this,tt).add(t),()=>void l(this,tt).delete(t)}applyJoined(){b(this,F,!0),a(this,S,ie).call(this,"joined"),a(this,S,z).call(this)}applyLeft(){b(this,F,!1),b(this,k,[]),a(this,S,ie).call(this,"left"),a(this,S,z).call(this)}applyPeers(t){b(this,k,t),a(this,S,z).call(this)}applyPeerJoined(t){!l(this,F)||l(this,k).some(e=>e.from===t.from)||(b(this,k,[...l(this,k),t]),l(this,Z).forEach(e=>xt(()=>e(t))),a(this,S,z).call(this))}applyPeerLeft(t){const e=l(this,k).find(s=>s.from===t);e&&(b(this,k,l(this,k).filter(s=>s.from!==t)),l(this,tt).forEach(s=>xt(()=>s(e))),a(this,S,z).call(this))}failPending(t){const e=l(this,A);return b(this,A,[]),e.forEach(s=>{clearTimeout(s.timer),s.reject(t)}),e.length>0}post(t){this.transport.post(t)}}F=new WeakMap,k=new WeakMap,A=new WeakMap,Q=new WeakMap,Z=new WeakMap,tt=new WeakMap,S=new WeakSet,re=function(t,e){return new Promise((s,r)=>{const i={want:t,resolve:s,reject:r,timer:setTimeout(()=>{b(this,A,l(this,A).filter(o=>o!==i)),r(new Error(`The platform did not confirm ${t==="joined"?"joining":"leaving"} in time.`))},un)};l(this,A).push(i),this.transport.post({type:"APP_CHANNEL_CONTROL",...e})})},ie=function(t){const e=l(this,A).filter(s=>s.want===t);b(this,A,l(this,A).filter(s=>s.want!==t)),e.forEach(s=>{clearTimeout(s.timer),s.resolve()})},z=function(){l(this,Q).forEach(t=>xt(t))};var et;class Xe extends ye{constructor(e){super(e,{join:{action:"joinCollab"},leave:{action:"leaveCollab"}});_(this,et,new Map)}on(e,s){const r=l(this,et).get(e)??new Set;return r.add(s),l(this,et).set(e,r),()=>void r.delete(s)}send(e,s){if(e.startsWith(ne))throw new Error(`Message types starting with '${ne}' are reserved.`);this.joined&&this.post({type:"APP_CHANNEL_PUBLISH",message:{type:e,payload:s}})}accepts(e){return e===void 0||e==="collab"}async handle(e){const s=l(this,et).get(e.type);if(!(s!=null&&s.size))return{handled:!1};const r=ze(e);return s.forEach(i=>xt(()=>i(e.payload,r))),{handled:!0}}}et=new WeakMap;var j;class Ke extends ye{constructor(e,s){super(e,{join:{action:"joinExternal",kind:s},leave:{action:"leaveExternal",kind:s}});_(this,j,new Map);this.kind=s}on(e,s){if(l(this,j).has(e))throw new Error(`"${e}" already has a handler in this room. Remove it first.`);return l(this,j).set(e,s),()=>void l(this,j).delete(e)}accepts(e,s){return e!==void 0&&e!=="external"?!1:this.kind===void 0||e===void 0||this.kind===s}get hasHandlers(){return l(this,j).size>0}async handle(e){const s=l(this,j).get(e.type);if(!s)return{handled:!1};try{return{handled:!0,value:await s(e.payload,ze(e))}}catch(r){return{handled:!0,error:r instanceof Error?r.message:String(r)}}}}j=new WeakMap;function ze(n){return{from:n.from,at:n.at,requestId:n.requestId,kind:n.kind}}function dn(n){const t=n;if((t==null?void 0:t.type)!=="THATOPEN_CHANNEL_MESSAGE")return null;const e=t.message;return!e||typeof e.type!="string"?null:{type:e.type,requestId:typeof e.requestId=="string"?e.requestId:void 0,payload:e.payload,at:typeof e.at=="number"?e.at:Date.now(),from:typeof e.from=="string"?e.from:"",scope:e.scope==="collab"||e.scope==="external"?e.scope:void 0,kind:typeof e.kind=="string"?e.kind:void 0}}var W,pt,q,H,G,T,oe,$t,Ze,ts,es,ae;class Qe{constructor(t){_(this,T);_(this,W);_(this,pt);_(this,q);_(this,H,new Map);_(this,G,new Set);b(this,W,t),b(this,pt,t.listen(e=>void a(this,T,Ze).call(this,e)))}collab(){return l(this,q)??b(this,q,new Xe(l(this,W))),l(this,q)}external(t){const e=t??"";let s=l(this,H).get(e);return s||(s=new Ke(l(this,W),t),l(this,H).set(e,s)),s}dispose(){l(this,pt).call(this)}}W=new WeakMap,pt=new WeakMap,q=new WeakMap,H=new WeakMap,G=new WeakMap,T=new WeakSet,oe=function(){return[...l(this,q)?[l(this,q)]:[],...l(this,H).values()]},$t=function(t,e){if(t==="collab")return l(this,q);if(t==="external")return l(this,H).get(typeof e=="string"?e:"")},Ze=async function(t){const e=dn(t);if(e){if(e.type.startsWith(ne)){a(this,T,ts).call(this,e);return}await a(this,T,es).call(this,e)}},ts=function(t){var s,r,i;const e=t.payload??{};switch(t.type){case"channel:joined":(s=a(this,T,$t).call(this,e.scope,e.kind))==null||s.applyJoined();break;case"channel:left":(r=a(this,T,$t).call(this,e.scope,e.kind))==null||r.applyLeft();break;case"channel:peers":(i=a(this,T,$t).call(this,e.scope,e.kind))==null||i.applyPeers(e.peers??[]);break;case"channel:peer-joined":case"channel:peer-left":{if(!e.from)break;const o=e.scope==="collab"?[l(this,q)]:[...l(this,H).values()].filter(h=>h.accepts("external",e.kind));for(const h of o)t.type==="channel:peer-joined"?h==null||h.applyPeerJoined({from:e.from,kind:e.kind}):h==null||h.applyPeerLeft(e.from);break}case"channel:error":{const o=new Error(String(t.payload));a(this,T,oe).call(this).map(u=>u.failPending(o)).some(Boolean)||console.error("[channel] error:",t.payload);break}}},es=async function(t){const e=a(this,T,oe).call(this).filter(i=>i.accepts(t.scope,t.kind));let s=!1;for(const i of e){const o=await i.handle(t);o.handled&&(s=!0,t.requestId&&a(this,T,ae).call(this,t.requestId,o))}t.requestId&&t.scope==="external"&&e.length>0&&!s&&a(this,T,ae).call(this,t.requestId,{handled:!0,error:`No handler for "${t.type}".`})},ae=function(t,e){l(this,G).has(t)||(l(this,G).add(t),l(this,G).size>500&&l(this,G).delete(l(this,G).values().next().value),l(this,W).post({type:"APP_CHANNEL_PUBLISH",message:{type:e.error===void 0?"reply":"reply-error",requestId:t,payload:e.error===void 0?e.value:{error:e.error}}}))};const J="project",K="notifications";var st,yt;const ge=class ge extends Rt{constructor(e,s,r){super(typeof e=="string"?e:"",s,{...r,useBearer:!0});_(this,st);_(this,yt);typeof e=="function"&&b(this,st,e)}async resolveAccessToken(){return l(this,st)?await l(this,st).call(this):super.resolveAccessToken()}static fromPlatformContext(e){const s=(typeof window<"u"?window.__THATOPEN_CONTEXT__:null)||{appId:"",projectId:"",accessToken:"",apiUrl:""},r=new ge(s.accessToken,s.apiUrl,e);return r.context=s,r}get channel(){return l(this,yt)??b(this,yt,new Qe(We())),l(this,yt)}async listProjects(){return await this.request("GET",J)}async getProject(e){return await this.request("GET",`${J}/${e}`)}async getProjectData(e){return await this.request("GET",`${J}/${e}/data`)}async getAvatar(e){return await this.request("GET",`account/${e}/avatar`,{responseType:"blob"})}async checkPermission(e){return await this.request("GET",`${J}/permissions/check`,{query:e})}async checkPermissionBatch(e){return(await this.request("POST",`${J}/permissions/check/batch`,{body:JSON.stringify({checks:e}),contentType:"application/json"})).results}async getNotifications(e){return await this.request("GET",K,{query:{...(e==null?void 0:e.cursor)!==void 0&&{cursor:e.cursor},...(e==null?void 0:e.limit)!==void 0&&{limit:String(e.limit)}}})}async getUnreadNotificationCount(){return(await this.request("GET",`${K}/unread-count`)).count}async markNotificationsRead(e){return await this.request("POST",`${K}/mark-read`,{body:JSON.stringify({ids:e}),contentType:"application/json"})}async markAllNotificationsRead(){return await this.request("POST",`${K}/mark-all-read`)}async getNotificationSubscriptions(){return await this.request("GET",`${K}/subscriptions`)}async unsubscribeFromAutomation(e){return await this.request("DELETE",`${K}/subscriptions/${e}`)}async subscribeToAutomation(e,s,r){return await this.request("POST",`${J}/${e}/events/hooks/${s}/subscription`,{body:JSON.stringify(r??{}),contentType:"application/json"})}async updateAutomationSubscription(e,s,r){return await this.request("PATCH",`${J}/${e}/events/hooks/${s}/subscription`,{body:JSON.stringify(r),contentType:"application/json"})}async onNotification(e){const s=await this.resolveAccessToken(),r=ut(`${this.socketOrigin}/notifications`,{auth:{accessToken:s},transports:["websocket"]});return r.on("notification.created",i=>e({type:"created",id:i==null?void 0:i.id})),r.on("notification.read",i=>e({type:"read",id:i==null?void 0:i.id})),r.on("notifications.allRead",i=>e({type:"allRead",batch:i==null?void 0:i.batch})),()=>r.disconnect()}};st=new WeakMap,yt=new WeakMap;let ce=ge;const fn={MAX_FIELDS:200,MAX_KEY_LENGTH:50,MAX_VALUE_LENGTH:50},pn={uuid:"a3f82c1d-5b74-4e9a-bc30-d7e12f894a61"},yn={uuid:"2c9f4e8d-3a1b-4c5e-9d7f-0a2b6c8e1d3f"},mn={uuid:"b0b5e2a2-0b3a-4a6b-8b1c-0b1c4a6b8b1c"},gn={uuid:"d8f3a1c2-6b4e-4f9a-8c1d-2e7b5a9f3c60"},wn={uuid:"3f9c1a7e-6b2d-4e18-9a5c-7d0e2f4b6c81"},_n={uuid:"2c4ae432-fc24-43e9-9783-0c960c674e96"},bn={uuid:"6f3a9c2e-8b1d-4e6a-9c3f-1d7b5a8e2c4f"},En={uuid:"69af63aa-19ba-4fc7-b17b-75647bac1d76"},Tn={uuid:"234f1416-528d-452a-9cc9-a16c5239b2eb"};exports.CDEManager=pn;exports.ChannelClient=Qe;exports.ChannelRoom=ye;exports.ClashesManager=yn;exports.CollabRoom=Xe;exports.EngineServicesClient=Rt;exports.ExternalRoom=Ke;exports.FileList=mn;exports.FlowDoc=Ge;exports.GISManager=gn;exports.GitHistoryManager=wn;exports.HelloWorld=_n;exports.METADATA_LIMITS=fn;exports.PlatformClient=ce;exports.ProjectHistory=He;exports.ProjectManager=bn;exports.Recipes=Je;exports.RequestError=Pt;exports.STORAGE_BATCH_MAX=Zt;exports.StaleHistoryError=Wt;exports.TopicsManager=En;exports.UIManager=Tn;exports.orderByGraph=pe;exports.windowTransport=We;
3
3
  //# sourceMappingURL=index.cjs.js.map