@thatopen/services 0.10.0 → 0.11.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/cli.js +54 -10
- package/dist/core/client.d.ts +10 -2
- package/dist/core/request-error.d.ts +17 -1
- package/dist/index.cjs.js +2 -2
- package/dist/index.es.js +581 -545
- package/docs/ai-quickstart.md +5 -0
- package/docs/rate-limits.md +123 -0
- package/package.json +1 -1
- package/resources/AGENTS.md +11 -1
package/dist/cli.js
CHANGED
|
@@ -6811,12 +6811,22 @@ function parseErrorBody(body) {
|
|
|
6811
6811
|
}
|
|
6812
6812
|
return {};
|
|
6813
6813
|
}
|
|
6814
|
+
function retryAfterFromDetails(details) {
|
|
6815
|
+
if (!details || typeof details !== "object") return void 0;
|
|
6816
|
+
const value2 = details.retryAfter;
|
|
6817
|
+
return typeof value2 === "number" && Number.isFinite(value2) && value2 >= 0 ? value2 : void 0;
|
|
6818
|
+
}
|
|
6814
6819
|
class RequestError extends Error {
|
|
6815
6820
|
status;
|
|
6816
6821
|
code;
|
|
6817
6822
|
details;
|
|
6818
6823
|
body;
|
|
6819
|
-
|
|
6824
|
+
/**
|
|
6825
|
+
* Seconds to wait before retrying, taken from the `Retry-After` header or
|
|
6826
|
+
* from `details.retryAfter`. Only present on rate-limited (429) responses.
|
|
6827
|
+
*/
|
|
6828
|
+
retryAfter;
|
|
6829
|
+
constructor(status, statusText, body, retryAfter) {
|
|
6820
6830
|
const parsed = parseErrorBody(body);
|
|
6821
6831
|
super(parsed.message ?? `${statusText || "Request failed"} (${status})`);
|
|
6822
6832
|
this.name = "RequestError";
|
|
@@ -6824,6 +6834,7 @@ class RequestError extends Error {
|
|
|
6824
6834
|
this.code = parsed.code;
|
|
6825
6835
|
this.details = parsed.details;
|
|
6826
6836
|
this.body = body;
|
|
6837
|
+
this.retryAfter = retryAfter ?? retryAfterFromDetails(parsed.details);
|
|
6827
6838
|
}
|
|
6828
6839
|
}
|
|
6829
6840
|
const FOLDER_PATH = "item/folder";
|
|
@@ -6834,6 +6845,35 @@ const HIDDEN_PATH = "hidden";
|
|
|
6834
6845
|
const ITEM_TYPE_FILE = "FILE";
|
|
6835
6846
|
const ITEM_TYPE_COMPONENT = "TOOL";
|
|
6836
6847
|
const ITEM_TYPE_APP = "APP";
|
|
6848
|
+
const RETRY_BASE_DELAY_MS = 500;
|
|
6849
|
+
const RETRY_MAX_DELAY_MS = 3e4;
|
|
6850
|
+
const RETRY_JITTER_RATIO = 0.25;
|
|
6851
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
6852
|
+
function parseRetryAfter(response) {
|
|
6853
|
+
const raw = response.headers?.get?.("Retry-After");
|
|
6854
|
+
if (!raw) return void 0;
|
|
6855
|
+
const seconds = Number(raw);
|
|
6856
|
+
if (Number.isFinite(seconds)) return Math.max(0, seconds);
|
|
6857
|
+
const timestamp = Date.parse(raw);
|
|
6858
|
+
if (Number.isNaN(timestamp)) return void 0;
|
|
6859
|
+
return Math.max(0, (timestamp - Date.now()) / 1e3);
|
|
6860
|
+
}
|
|
6861
|
+
function isRetryable(error2) {
|
|
6862
|
+
if (!(error2 instanceof RequestError)) return true;
|
|
6863
|
+
return error2.status === 429 || error2.status >= 500;
|
|
6864
|
+
}
|
|
6865
|
+
function retryDelayMs(error2, attempt) {
|
|
6866
|
+
const backoff = Math.min(
|
|
6867
|
+
RETRY_BASE_DELAY_MS * 2 ** attempt,
|
|
6868
|
+
RETRY_MAX_DELAY_MS
|
|
6869
|
+
);
|
|
6870
|
+
const jitter = backoff * RETRY_JITTER_RATIO * Math.random();
|
|
6871
|
+
const serverDelay = error2 instanceof RequestError && error2.retryAfter != null ? error2.retryAfter * 1e3 : void 0;
|
|
6872
|
+
if (serverDelay != null) {
|
|
6873
|
+
return Math.min(serverDelay, RETRY_MAX_DELAY_MS) + jitter;
|
|
6874
|
+
}
|
|
6875
|
+
return backoff + jitter;
|
|
6876
|
+
}
|
|
6837
6877
|
class EngineServicesClient {
|
|
6838
6878
|
apiUrl;
|
|
6839
6879
|
accessToken;
|
|
@@ -6906,7 +6946,9 @@ class EngineServicesClient {
|
|
|
6906
6946
|
}
|
|
6907
6947
|
}
|
|
6908
6948
|
/**
|
|
6909
|
-
* Sets the number of automatic retries for failed requests.
|
|
6949
|
+
* Sets the number of automatic retries for failed requests. Retries use
|
|
6950
|
+
* exponential backoff with jitter and honour `Retry-After`; only network
|
|
6951
|
+
* failures, 429s and 5xx are retried.
|
|
6910
6952
|
* @param retries - Number of retries (0 = no retries).
|
|
6911
6953
|
*/
|
|
6912
6954
|
setRetries(retries) {
|
|
@@ -6966,7 +7008,7 @@ class EngineServicesClient {
|
|
|
6966
7008
|
return this.accessToken;
|
|
6967
7009
|
}
|
|
6968
7010
|
async #requestApi(method, path2, requestData) {
|
|
6969
|
-
const { body, query, contentType, retries, responseType } = requestData || {};
|
|
7011
|
+
const { body, query, contentType, retries, responseType, retryAttempt } = requestData || {};
|
|
6970
7012
|
const url2 = this.#buildUrl(path2);
|
|
6971
7013
|
const cleanQuery = this.#cleanData(query);
|
|
6972
7014
|
const token = await this.resolveAccessToken();
|
|
@@ -6992,7 +7034,8 @@ class EngineServicesClient {
|
|
|
6992
7034
|
throw new RequestError(
|
|
6993
7035
|
response.status,
|
|
6994
7036
|
response.statusText,
|
|
6995
|
-
textResponse
|
|
7037
|
+
textResponse,
|
|
7038
|
+
parseRetryAfter(response)
|
|
6996
7039
|
);
|
|
6997
7040
|
}
|
|
6998
7041
|
if (responseType === "blob") {
|
|
@@ -7000,16 +7043,17 @@ class EngineServicesClient {
|
|
|
7000
7043
|
}
|
|
7001
7044
|
return response.json().then((data) => data).catch(() => void 0);
|
|
7002
7045
|
} catch (e) {
|
|
7003
|
-
|
|
7004
|
-
if (
|
|
7005
|
-
|
|
7046
|
+
const retriesLeft = retries != null ? retries : this.retries;
|
|
7047
|
+
if (retriesLeft > 0 && isRetryable(e)) {
|
|
7048
|
+
const attempt = retryAttempt ?? 0;
|
|
7049
|
+
await sleep(retryDelayMs(e, attempt));
|
|
7006
7050
|
return await this.#requestApi(method, path2, {
|
|
7007
7051
|
...requestData,
|
|
7008
|
-
retries:
|
|
7052
|
+
retries: retriesLeft - 1,
|
|
7053
|
+
retryAttempt: attempt + 1
|
|
7009
7054
|
});
|
|
7010
|
-
} else {
|
|
7011
|
-
throw e;
|
|
7012
7055
|
}
|
|
7056
|
+
throw e;
|
|
7013
7057
|
}
|
|
7014
7058
|
}
|
|
7015
7059
|
/**
|
package/dist/core/client.d.ts
CHANGED
|
@@ -84,7 +84,13 @@ export type DownloadItemFileParams = {
|
|
|
84
84
|
};
|
|
85
85
|
/** Configuration options for the {@link EngineServicesClient} constructor. */
|
|
86
86
|
export type EngineServicesClientProps = {
|
|
87
|
-
/**
|
|
87
|
+
/**
|
|
88
|
+
* Number of automatic retries on request failure. Default: 0.
|
|
89
|
+
*
|
|
90
|
+
* Retries are spaced with exponential backoff plus jitter, and honour the
|
|
91
|
+
* server's `Retry-After` when it sends one. Only network failures, 429s and
|
|
92
|
+
* 5xx are retried — other 4xx fail immediately.
|
|
93
|
+
*/
|
|
88
94
|
retries?: number;
|
|
89
95
|
/**
|
|
90
96
|
* If true, sends the token as an `Authorization: Bearer` header instead of
|
|
@@ -167,7 +173,9 @@ export declare class EngineServicesClient {
|
|
|
167
173
|
*/
|
|
168
174
|
constructor(accessToken: string, apiUrl: string, props?: EngineServicesClientProps);
|
|
169
175
|
/**
|
|
170
|
-
* Sets the number of automatic retries for failed requests.
|
|
176
|
+
* Sets the number of automatic retries for failed requests. Retries use
|
|
177
|
+
* exponential backoff with jitter and honour `Retry-After`; only network
|
|
178
|
+
* failures, 429s and 5xx are retried.
|
|
171
179
|
* @param retries - Number of retries (0 = no retries).
|
|
172
180
|
*/
|
|
173
181
|
setRetries(retries: number): void;
|
|
@@ -15,11 +15,27 @@
|
|
|
15
15
|
* }
|
|
16
16
|
* }
|
|
17
17
|
* ```
|
|
18
|
+
*
|
|
19
|
+
* @example Rate limiting
|
|
20
|
+
* ```ts
|
|
21
|
+
* catch (err) {
|
|
22
|
+
* if (err instanceof RequestError && err.status === 429) {
|
|
23
|
+
* console.log(err.code); // "RATE_LIMITED"
|
|
24
|
+
* console.log(err.details); // { limit, windowSeconds, retryAfter, scope }
|
|
25
|
+
* console.log(err.retryAfter); // seconds to wait before trying again
|
|
26
|
+
* }
|
|
27
|
+
* }
|
|
28
|
+
* ```
|
|
18
29
|
*/
|
|
19
30
|
export declare class RequestError extends Error {
|
|
20
31
|
readonly status: number;
|
|
21
32
|
readonly code?: string;
|
|
22
33
|
readonly details?: unknown;
|
|
23
34
|
readonly body: string;
|
|
24
|
-
|
|
35
|
+
/**
|
|
36
|
+
* Seconds to wait before retrying, taken from the `Retry-After` header or
|
|
37
|
+
* from `details.retryAfter`. Only present on rate-limited (429) responses.
|
|
38
|
+
*/
|
|
39
|
+
readonly retryAfter?: number;
|
|
40
|
+
constructor(status: number, statusText: string, body: string, retryAfter?: number);
|
|
25
41
|
}
|
package/dist/index.cjs.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var je=Object.defineProperty;var Ee=n=>{throw TypeError(n)};var Je=(n,e,t)=>e in n?je(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var w=(n,e,t)=>Je(n,typeof e!="symbol"?e+"":e,t),W=(n,e,t)=>e.has(n)||Ee("Cannot "+t);var X=(n,e,t)=>(W(n,e,"read from private field"),t?t.call(n):e.get(n)),z=(n,e,t)=>e.has(n)?Ee("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(n):e.set(n,t),ve=(n,e,t,s)=>(W(n,e,"write to private field"),s?s.call(n,t):e.set(n,t),t),c=(n,e,t)=>(W(n,e,"access private method"),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const v=Object.create(null);v.open="0";v.close="1";v.ping="2";v.pong="3";v.message="4";v.upgrade="5";v.noop="6";const M=Object.create(null);Object.keys(v).forEach(n=>{M[v[n]]=n});const ie={type:"error",data:"parser error"},Ce=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",Re=typeof ArrayBuffer=="function",Be=n=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(n):n&&n.buffer instanceof ArrayBuffer,ye=({type:n,data:e},t,s)=>Ce&&e instanceof Blob?t?s(e):ke(e,s):Re&&(e instanceof ArrayBuffer||Be(e))?t?s(e):ke(new Blob([e]),s):s(v[n]+(e||"")),ke=(n,e)=>{const t=new FileReader;return t.onload=function(){const s=t.result.split(",")[1];e("b"+(s||""))},t.readAsDataURL(n)};function Oe(n){return n instanceof Uint8Array?n:n instanceof ArrayBuffer?new Uint8Array(n):new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}let Q;function Ye(n,e){if(Ce&&n.data instanceof Blob)return n.data.arrayBuffer().then(Oe).then(e);if(Re&&(n.data instanceof ArrayBuffer||Be(n.data)))return e(Oe(n.data));ye(n,!1,t=>{Q||(Q=new TextEncoder),e(Q.encode(t))})}const Se="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",L=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let n=0;n<Se.length;n++)L[Se.charCodeAt(n)]=n;const Ke=n=>{let e=n.length*.75,t=n.length,s,i=0,r,a,h,l;n[n.length-1]==="="&&(e--,n[n.length-2]==="="&&e--);const y=new ArrayBuffer(e),d=new Uint8Array(y);for(s=0;s<t;s+=4)r=L[n.charCodeAt(s)],a=L[n.charCodeAt(s+1)],h=L[n.charCodeAt(s+2)],l=L[n.charCodeAt(s+3)],d[i++]=r<<2|a>>4,d[i++]=(a&15)<<4|h>>2,d[i++]=(h&3)<<6|l&63;return y},We=typeof ArrayBuffer=="function",me=(n,e)=>{if(typeof n!="string")return{type:"message",data:Ne(n,e)};const t=n.charAt(0);return t==="b"?{type:"message",data:Xe(n.substring(1),e)}:M[t]?n.length>1?{type:M[t],data:n.substring(1)}:{type:M[t]}:ie},Xe=(n,e)=>{if(We){const t=Ke(n);return Ne(t,e)}else return{base64:!0,data:n}},Ne=(n,e)=>{switch(e){case"blob":return n instanceof Blob?n:new Blob([n]);case"arraybuffer":default:return n instanceof ArrayBuffer?n:n.buffer}},Pe="",ze=(n,e)=>{const t=n.length,s=new Array(t);let i=0;n.forEach((r,a)=>{ye(r,!1,h=>{s[a]=h,++i===t&&e(s.join(Pe))})})},Qe=(n,e)=>{const t=n.split(Pe),s=[];for(let i=0;i<t.length;i++){const r=me(t[i],e);if(s.push(r),r.type==="error")break}return s};function Ze(){return new TransformStream({transform(n,e){Ye(n,t=>{const s=t.length;let i;if(s<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,s);else if(s<65536){i=new Uint8Array(3);const r=new DataView(i.buffer);r.setUint8(0,126),r.setUint16(1,s)}else{i=new Uint8Array(9);const r=new DataView(i.buffer);r.setUint8(0,127),r.setBigUint64(1,BigInt(s))}n.data&&typeof n.data!="string"&&(i[0]|=128),e.enqueue(i),e.enqueue(t)})}})}let Z;function F(n){return n.reduce((e,t)=>e+t.length,0)}function D(n,e){if(n[0].length===e)return n.shift();const t=new Uint8Array(e);let s=0;for(let i=0;i<e;i++)t[i]=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 et(n,e){Z||(Z=new TextDecoder);const t=[];let s=0,i=-1,r=!1;return new TransformStream({transform(a,h){for(t.push(a);;){if(s===0){if(F(t)<1)break;const l=D(t,1);r=(l[0]&128)===128,i=l[0]&127,i<126?s=3:i===126?s=1:s=2}else if(s===1){if(F(t)<2)break;const l=D(t,2);i=new DataView(l.buffer,l.byteOffset,l.length).getUint16(0),s=3}else if(s===2){if(F(t)<8)break;const l=D(t,8),y=new DataView(l.buffer,l.byteOffset,l.length),d=y.getUint32(0);if(d>Math.pow(2,21)-1){h.enqueue(ie);break}i=d*Math.pow(2,32)+y.getUint32(4),s=3}else{if(F(t)<i)break;const l=D(t,i);h.enqueue(me(r?l:Z.decode(l),e)),s=0}if(i===0||i>n){h.enqueue(ie);break}}}})}const xe=4;function g(n){if(n)return tt(n)}function tt(n){for(var e in g.prototype)n[e]=g.prototype[e];return n}g.prototype.on=g.prototype.addEventListener=function(n,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+n]=this._callbacks["$"+n]||[]).push(e),this};g.prototype.once=function(n,e){function t(){this.off(n,t),e.apply(this,arguments)}return t.fn=e,this.on(n,t),this};g.prototype.off=g.prototype.removeListener=g.prototype.removeAllListeners=g.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,i=0;i<t.length;i++)if(s=t[i],s===e||s.fn===e){t.splice(i,1);break}return t.length===0&&delete this._callbacks["$"+n],this};g.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,i=t.length;s<i;++s)t[s].apply(this,e)}return this};g.prototype.emitReserved=g.prototype.emit;g.prototype.listeners=function(n){return this._callbacks=this._callbacks||{},this._callbacks["$"+n]||[]};g.prototype.hasListeners=function(n){return!!this.listeners(n).length};const Y=typeof Promise=="function"&&typeof Promise.resolve=="function"?e=>Promise.resolve().then(e):(e,t)=>t(e,0),_=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),st="arraybuffer";function Ie(n,...e){return e.reduce((t,s)=>(n.hasOwnProperty(s)&&(t[s]=n[s]),t),{})}const nt=_.setTimeout,it=_.clearTimeout;function K(n,e){e.useNativeTimers?(n.setTimeoutFn=nt.bind(_),n.clearTimeoutFn=it.bind(_)):(n.setTimeoutFn=_.setTimeout.bind(_),n.clearTimeoutFn=_.clearTimeout.bind(_))}const rt=1.33;function ot(n){return typeof n=="string"?at(n):Math.ceil((n.byteLength||n.size)*rt)}function at(n){let e=0,t=0;for(let s=0,i=n.length;s<i;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 Le(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function ct(n){let e="";for(let t in n)n.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(n[t]));return e}function ht(n){let e={},t=n.split("&");for(let s=0,i=t.length;s<i;s++){let r=t[s].split("=");e[decodeURIComponent(r[0])]=decodeURIComponent(r[1])}return e}class ut extends Error{constructor(e,t,s){super(e),this.description=t,this.context=s,this.type="TransportError"}}class ge extends g{constructor(e){super(),this.writable=!1,K(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 ut(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=me(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=ct(e);return t.length?"?"+t:""}}class lt extends ge{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)};Qe(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,ze(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]=Le()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}}let qe=!1;try{qe=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const ft=qe;function pt(){}class dt extends lt{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",(i,r)=>{this.onError("xhr post error",i,r)})}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 E extends g{constructor(e,t,s){super(),this.createRequest=e,K(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=Ie(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 i in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(i)&&s.setRequestHeader(i,this._opts.extraHeaders[i])}}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 i;s.readyState===3&&((i=this._opts.cookieJar)===null||i===void 0||i.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(i){this.setTimeoutFn(()=>{this._onError(i)},0);return}typeof document<"u"&&(this._index=E.requestsCount++,E.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=pt,e)try{this._xhr.abort()}catch{}typeof document<"u"&&delete E.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()}}E.requestsCount=0;E.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",Ae);else if(typeof addEventListener=="function"){const n="onpagehide"in _?"pagehide":"unload";addEventListener(n,Ae,!1)}}function Ae(){for(let n in E.requests)E.requests.hasOwnProperty(n)&&E.requests[n].abort()}const yt=function(){const n=Ue({xdomain:!1});return n&&n.responseType!==null}();class mt extends dt{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=yt&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new E(Ue,this.uri(),e)}}function Ue(n){const e=n.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||ft))return new XMLHttpRequest}catch{}if(!e)try{return new _[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const Fe=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class gt extends ge{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,s=Fe?{}:Ie(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(i){return this.emitReserved("error",i)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const s=e[t],i=t===e.length-1;ye(s,this.supportsBinary,r=>{try{this.doWrite(s,r)}catch{}i&&Y(()=>{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]=Le()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const ee=_.WebSocket||_.MozWebSocket;class wt extends gt{createSocket(e,t,s){return Fe?new ee(e,t,s):t?new ee(e,t):new ee(e)}doWrite(e,t){this.ws.send(t)}}class _t extends ge{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=et(Number.MAX_SAFE_INTEGER,this.socket.binaryType),s=e.readable.pipeThrough(t).getReader(),i=Ze();i.readable.pipeTo(e.writable),this._writer=i.writable.getWriter();const r=()=>{s.read().then(({done:h,value:l})=>{h||(this.onPacket(l),r())}).catch(h=>{})};r();const a={type:"open"};this.query.sid&&(a.data=`{"sid":"${this.query.sid}"}`),this._writer.write(a).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const s=e[t],i=t===e.length-1;this._writer.write(s).then(()=>{i&&Y(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}}const bt={websocket:wt,webtransport:_t,polling:mt},Tt=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Et=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function re(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 i=Tt.exec(n||""),r={},a=14;for(;a--;)r[Et[a]]=i[a]||"";return t!=-1&&s!=-1&&(r.source=e,r.host=r.host.substring(1,r.host.length-1).replace(/;/g,":"),r.authority=r.authority.replace("[","").replace("]","").replace(/;/g,":"),r.ipv6uri=!0),r.pathNames=vt(r,r.path),r.queryKey=kt(r,r.query),r}function vt(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 kt(n,e){const t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(s,i,r){i&&(t[i]=r)}),t}const oe=typeof addEventListener=="function"&&typeof removeEventListener=="function",V=[];oe&&addEventListener("offline",()=>{V.forEach(n=>n())},!1);class R extends g{constructor(e,t){if(super(),this.binaryType=st,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=re(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=re(t.host).host);K(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 i=s.prototype.name;this.transports.push(i),this._transportsByName[i]=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=ht(this.opts.query)),oe&&(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"})},V.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=xe,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&&R.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",R.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 i=this.writeBuffer[s].data;if(i&&(t+=ot(i)),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,Y(()=>{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,i){if(typeof t=="function"&&(i=t,t=void 0),typeof s=="function"&&(i=s,s=null),this.readyState==="closing"||this.readyState==="closed")return;s=s||{},s.compress=s.compress!==!1;const r={type:e,data:t,options:s};this.emitReserved("packetCreate",r),this.writeBuffer.push(r),i&&this.once("flush",i),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(R.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(),oe&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const s=V.indexOf(this._offlineEventListener);s!==-1&&V.splice(s,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}R.protocol=xe;class Ot extends R{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;R.priorWebsocketSuccess=!1;const i=()=>{s||(t.send([{type:"ping",data:"probe"}]),t.once("packet",m=>{if(!s)if(m.type==="pong"&&m.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;R.priorWebsocketSuccess=t.name==="websocket",this.transport.pause(()=>{s||this.readyState!=="closed"&&(d(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{const k=new Error("probe error");k.transport=t.name,this.emitReserved("upgradeError",k)}}))};function r(){s||(s=!0,d(),t.close(),t=null)}const a=m=>{const k=new Error("probe error: "+m);k.transport=t.name,r(),this.emitReserved("upgradeError",k)};function h(){a("transport closed")}function l(){a("socket closed")}function y(m){t&&m.name!==t.name&&r()}const d=()=>{t.removeListener("open",i),t.removeListener("error",a),t.removeListener("close",h),this.off("close",l),this.off("upgrading",y)};t.once("open",i),t.once("error",a),t.once("close",h),this.once("close",l),this.once("upgrading",y),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 St=class extends Ot{constructor(e,t={}){const s=typeof e=="object",i=s?{...e}:{...t};(!i.transports||i.transports&&typeof i.transports[0]=="string")&&(i.transports=(i.transports||["polling","websocket","webtransport"]).map(r=>bt[r]).filter(r=>!!r)),super(s?i:e,i)}};function At(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=re(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 r=s.host.indexOf(":")!==-1?"["+s.host+"]":s.host;return s.id=s.protocol+"://"+r+":"+s.port+e,s.href=s.protocol+"://"+r+(t&&t.port===s.port?"":":"+s.port),s}const $t=typeof ArrayBuffer=="function",Ct=n=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(n):n.buffer instanceof ArrayBuffer,De=Object.prototype.toString,Rt=typeof Blob=="function"||typeof Blob<"u"&&De.call(Blob)==="[object BlobConstructor]",Bt=typeof File=="function"||typeof File<"u"&&De.call(File)==="[object FileConstructor]";function we(n){return $t&&(n instanceof ArrayBuffer||Ct(n))||Rt&&n instanceof Blob||Bt&&n instanceof File}function H(n,e){if(!n||typeof n!="object")return!1;if(Array.isArray(n)){for(let t=0,s=n.length;t<s;t++)if(H(n[t]))return!0;return!1}if(we(n))return!0;if(n.toJSON&&typeof n.toJSON=="function"&&arguments.length===1)return H(n.toJSON(),!0);for(const t in n)if(Object.prototype.hasOwnProperty.call(n,t)&&H(n[t]))return!0;return!1}function Nt(n){const e=[],t=n.data,s=n;return s.data=ae(t,e),s.attachments=e.length,{packet:s,buffers:e}}function ae(n,e){if(!n)return n;if(we(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]=ae(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]=ae(n[s],e));return t}return n}function Pt(n,e){return n.data=ce(n.data,e),delete n.attachments,n}function ce(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]=ce(n[t],e);else if(typeof n=="object")for(const t in n)Object.prototype.hasOwnProperty.call(n,t)&&(n[t]=ce(n[t],e));return n}const xt=["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 It{constructor(e){this.replacer=e}encode(e){return(e.type===p.EVENT||e.type===p.ACK)&&H(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=Nt(e),s=this.encodeAsString(t.packet),i=t.buffers;return i.unshift(s),i}}class _e extends g{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 Lt(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if(we(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 r=t+1;for(;e.charAt(++t)!=="-"&&t!=e.length;);const a=e.substring(r,t);if(a!=Number(a)||e.charAt(t)!=="-")throw new Error("Illegal attachments");const h=Number(a);if(!qt(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 r=t+1;for(;++t&&!(e.charAt(t)===","||t===e.length););s.nsp=e.substring(r,t)}else s.nsp="/";const i=e.charAt(t+1);if(i!==""&&Number(i)==i){const r=t+1;for(;++t;){const a=e.charAt(t);if(a==null||Number(a)!=a){--t;break}if(t===e.length)break}s.id=Number(e.substring(r,t+1))}if(e.charAt(++t)){const r=this.tryParse(e.substr(t));if(_e.isPayloadValid(s.type,r))s.data=r;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 $e(t);case p.DISCONNECT:return t===void 0;case p.CONNECT_ERROR:return typeof t=="string"||$e(t);case p.EVENT:case p.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&xt.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 Lt{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=Pt(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const qt=Number.isInteger||function(n){return typeof n=="number"&&isFinite(n)&&Math.floor(n)===n};function $e(n){return Object.prototype.toString.call(n)==="[object Object]"}const Ut=Object.freeze(Object.defineProperty({__proto__:null,Decoder:_e,Encoder:It,get PacketType(){return p}},Symbol.toStringTag,{value:"Module"}));function b(n,e,t){return n.on(e,t),function(){n.off(e,t)}}const Ft=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Me extends g{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=[b(e,"open",this.onopen.bind(this)),b(e,"packet",this.onpacket.bind(this)),b(e,"error",this.onerror.bind(this)),b(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,i,r;if(Ft.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 a={type:p.EVENT,data:t};if(a.options={},a.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){const d=this.ids++,m=t.pop();this._registerAckCallback(d,m),a.id=d}const h=(i=(s=this.io.engine)===null||s===void 0?void 0:s.transport)===null||i===void 0?void 0:i.writable,l=this.connected&&!(!((r=this.io.engine)===null||r===void 0)&&r._hasPingExpired());return this.flags.volatile&&!h||(l?(this.notifyOutgoingListeners(a),this.packet(a)):this.sendBuffer.push(a)),this.flags={},this}_registerAckCallback(e,t){var s;const i=(s=this.flags.timeout)!==null&&s!==void 0?s:this._opts.ackTimeout;if(i===void 0){this.acks[e]=t;return}const r=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"))},i),a=(...h)=>{this.io.clearTimeoutFn(r),t.apply(this,h)};a.withError=!0,this.acks[e]=a}emitWithAck(e,...t){return new Promise((s,i)=>{const r=(a,h)=>a?i(a):s(h);r.withError=!0,t.push(r),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((i,...r)=>(this._queue[0],i!==null?s.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(i)):(this._queue.shift(),t&&t(null,...r)),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(...i){s||(s=!0,t.packet({type:p.ACK,id:e,data:i}))}}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 x(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}x.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};x.prototype.reset=function(){this.attempts=0};x.prototype.setMin=function(n){this.ms=n};x.prototype.setMax=function(n){this.max=n};x.prototype.setJitter=function(n){this.jitter=n};class he extends g{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,K(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 x({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState="closed",this.uri=e;const i=t.parser||Ut;this.encoder=new i.Encoder,this.decoder=new i.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 St(this.uri,this.opts);const t=this.engine,s=this;this._readyState="opening",this.skipReconnect=!1;const i=b(t,"open",function(){s.onopen(),e&&e()}),r=h=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",h),e?e(h):this.maybeReconnectOnOpen()},a=b(t,"error",r);if(this._timeout!==!1){const h=this._timeout,l=this.setTimeoutFn(()=>{i(),r(new Error("timeout")),t.close()},h);this.opts.autoUnref&&l.unref(),this.subs.push(()=>{this.clearTimeoutFn(l)})}return this.subs.push(i),this.subs.push(a),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(b(e,"ping",this.onping.bind(this)),b(e,"data",this.ondata.bind(this)),b(e,"error",this.onerror.bind(this)),b(e,"close",this.onclose.bind(this)),b(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){Y(()=>{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 Me(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(i=>{i?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",i)):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 I={};function U(n,e){typeof n=="object"&&(e=n,n=void 0),e=e||{};const t=At(n,e.path||"/socket.io"),s=t.source,i=t.id,r=t.path,a=I[i]&&r in I[i].nsps,h=e.forceNew||e["force new connection"]||e.multiplex===!1||a;let l;return h?l=new he(s,e):(I[i]||(I[i]=new he(s,e)),l=I[i]),t.query&&!e.query&&(e.query=t.queryKey),l.socket(t.path,e)}Object.assign(U,{Manager:he,Socket:Me,io:U,connect:U});const ue=100;function Dt(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{}}class Ve extends Error{constructor(t,s,i){const r=Dt(i);super(r.message??`${s||"Request failed"} (${t})`);w(this,"status");w(this,"code");w(this,"details");w(this,"body");this.name="RequestError",this.status=t,this.code=r.code,this.details=r.details,this.body=i}}const T="item/folder",f="item",$="processor",Mt="npm-registry",O="hidden",te="FILE",se="TOOL",ne="APP";var o,le,u,C,q,G,j,fe,pe,He;const be=class be{constructor(e,t,s){z(this,o);w(this,"apiUrl");w(this,"accessToken");w(this,"wsUrl");w(this,"retries");w(this,"useBearer");w(this,"builtInGlobals",null);w(this,"localServerUrl",null);w(this,"context");const{retries:i=0,useBearer:r=!1,localServerUrl:a}=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}?accessToken=${e}`,this.retries=i,this.useBearer=r,this.context={appId:"",projectId:"",accessToken:e,apiUrl:t},a){let l=a;l.charAt(l.length-1)==="/"&&(l=l.slice(0,-1)),this.localServerUrl=l}}static fromPlatformContext(e){const t=(typeof window<"u"?window.__THATOPEN_CONTEXT__:null)||{appId:"",projectId:"",accessToken:"",apiUrl:""},s=new be(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 c(this,o,u).call(this,e,t,s)}async listFiles(e){const{folderId:t,archived:s,projectId:i}=e||{};return t?await c(this,o,u).call(this,"GET",`${T}/${t}/items`,{query:{itemType:te,archived:s}}):await c(this,o,u).call(this,"GET",`${f}`,{query:{itemType:te,archived:s,...i&&{projectId:i}}})}async getFile(e,t){return await c(this,o,pe).call(this,e,t)}async createFile(e){return await c(this,o,j).call(this,e,te)}async updateFile(e,t){return await c(this,o,fe).call(this,e,t)}async archiveFile(e){return await c(this,o,u).call(this,"DELETE",`${f}/${e}`)}async recoverFile(e){return await c(this,o,u).call(this,"PUT",`${f}/${e}/recover`)}async downloadFile(e,t){return await c(this,o,G).call(this,e,t)}async getFileVersionMetadata(e,t,s){const{withDraft:i}=s||{};return await c(this,o,u).call(this,"GET",`${f}/${encodeURIComponent(e)}/version/${encodeURIComponent(t)}/metadata`,{query:{...i&&{withDraft:"true"}}})}async updateFileVersionMetadata(e,t,s){return await c(this,o,u).call(this,"PUT",`${f}/${encodeURIComponent(e)}/version/${encodeURIComponent(t)}/metadata`,{body:JSON.stringify({metadata:s}),contentType:"application/json"})}async deleteFileVersionMetadata(e,t){return await c(this,o,u).call(this,"DELETE",`${f}/${encodeURIComponent(e)}/version/${encodeURIComponent(t)}/metadata`)}async getFileVersionMetadataBatch(e,t){const{withDraft:s}=t||{};return await c(this,o,q).call(this,e,async i=>(await c(this,o,u).call(this,"POST",`${f}/batch/version-metadata`,{body:JSON.stringify({entries:i,...s!==void 0&&{withDraft:s}}),contentType:"application/json"})).results)}async listFolders(e){const{archived:t,parentFolderId:s,projectId:i}=e||{};return await c(this,o,u).call(this,"GET",T,{query:{parentFolderId:s,archived:t,...i&&{projectId:i}}})}async getFolder(e){return await c(this,o,u).call(this,"GET",`${T}/${e}`)}async getFoldersBatch(e){return await c(this,o,q).call(this,e,async t=>(await c(this,o,u).call(this,"POST",`${f}/batch/folders`,{body:JSON.stringify({folderIds:t}),contentType:"application/json"})).results)}async createFolder(e,t,s){return await c(this,o,u).call(this,"POST",T,{body:JSON.stringify({name:e,...t&&{parentId:t},...s&&{projectId:s}}),contentType:"application/json"})}async updateFolder(e,t){const{name:s}=t;return await c(this,o,u).call(this,"PUT",`${T}/${e}`,{body:JSON.stringify({name:s}),contentType:"application/json"})}async archiveFolder(e){return await c(this,o,u).call(this,"DELETE",`${T}/${e}`)}async recoverFolder(e){return await c(this,o,u).call(this,"PUT",`${T}/${e}/recover`)}async downloadFolder(e){return await c(this,o,C).call(this,`${T}/${e}/download`)}async listComponents(e){const{folderId:t,ShowVersions:s,projectId:i}=e||{};return t?await c(this,o,u).call(this,"GET",`${T}/${t}/items`,{query:{itemType:se,...s&&{ShowVersions:s}}}):await c(this,o,u).call(this,"GET",`${f}`,{query:{itemType:se,...s&&{ShowVersions:s},...i&&{projectId:i}}})}async getComponent(e,t){return await c(this,o,pe).call(this,e,t)}async createComponent(e){const{componentProps:t}=e;return await c(this,o,j).call(this,e,se,t)}async updateComponent(e,t){const{componentProps:s}=t;return await c(this,o,fe).call(this,e,t,s)}async downloadComponent(e,t){return await c(this,o,G).call(this,e,t)}async downloadComponentBundle(e,t){const{versionTag:s,withDraft:i}=t||{};return await c(this,o,C).call(this,`${f}/${e}/download/bundle`,{query:{...s&&{versionTag:s},...i&&{withDraft:i}}})}async archiveComponent(e){return await c(this,o,u).call(this,"DELETE",`${f}/${e}`)}async recoverComponent(e){return await c(this,o,u).call(this,"PUT",`${f}/${e}/recover`)}async getBuiltInComponent(e){return await(await c(this,o,C).call(this,`built-in/${e}/bundle`)).text()}async initBuiltInComponent(e,t,s){const i=await this.getBuiltInComponent(e.uuid),r=s??this.builtInGlobals??(typeof window<"u"?window.ThatOpenCompany:{})??{},a=Object.keys(r),h=a.map(m=>r[m]),y=new Function(...a,`${i}
|
|
2
|
-
return main;`)(...h),d=(y==null?void 0:y.componentDefinition)??y;t.get(d)}async initBuiltInComponents(e,...t){await Promise.all(t.map(s=>this.initBuiltInComponent(s,e)))}async setup(e,...t){var a,h;const s=e.OBC,i=e.BUI;if(!(s!=null&&s.Components))throw new Error("globals.OBC must include Components");if(!(i!=null&&i.Manager))throw new Error("globals.BUI must include Manager");const r=new s.Components;return i.Manager.init(),this.setBuiltInGlobals(e),await this.initBuiltInComponents(r,...t),r.init(),(h=(a=this.context.appEventOrchestrator)==null?void 0:a.appLoaded)==null||h.call(a),{components:r}}throwError(e,t){var s,i;(i=(s=this.context.appEventOrchestrator)==null?void 0:s.appError)==null||i.call(s,e,t)}async listApps(e){const{folderId:t,ShowVersions:s,projectId:i}=e||{};return t?await c(this,o,u).call(this,"GET",`${T}/${t}/items`,{query:{itemType:ne,...s&&{ShowVersions:s}}}):await c(this,o,u).call(this,"GET",`${f}`,{query:{itemType:ne,...s&&{ShowVersions:s},...i&&{projectId:i}}})}async createApp(e){const{appProps:t}=e;return await c(this,o,j).call(this,e,ne,t)}async downloadApp(e,t){return await c(this,o,G).call(this,e,t)}async downloadAppBundle(e,t){const{versionTag:s,withDraft:i}=t||{};return await c(this,o,C).call(this,`${f}/${e}/download/bundle`,{query:{...s&&{versionTag:s},...i&&{withDraft:i}}})}async archiveApp(e){return await c(this,o,u).call(this,"DELETE",`${f}/${e}`)}async getNpmCredentials(){return await c(this,o,u).call(this,"GET",`${Mt}/credentials`)}async executeComponent(e,t,s){if(this.localServerUrl){const i=`${this.localServerUrl}/api/${$}/${e}/execute`,r=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){const a=await r.text().catch(()=>"");throw new Error(`Local server request failed: ${r.status} - ${a}`)}return await r.json()}return await c(this,o,u).call(this,"POST",`${$}/${e}/execute`,{body:JSON.stringify(t),query:{...s&&{versionTag:s}},contentType:"application/json"})}async abortExecution(e){if(this.localServerUrl){const t=`${this.localServerUrl}/api/${$}/progress/${e}/abort`,s=await fetch(t,{method:"POST"});if(!s.ok){const i=await s.text().catch(()=>"");throw new Error(`Local server request failed: ${s.status} - ${i}`)}return await s.json()}return await c(this,o,u).call(this,"POST",`${$}/progress/${e}/abort`)}async listExecutions(e,t){if(this.localServerUrl){const s=t?`?projectId=${encodeURIComponent(t)}`:"",i=`${this.localServerUrl}/api/${$}/${e}/progress${s}`,r=await fetch(i);if(!r.ok){const a=await r.text().catch(()=>"");throw new Error(`Local server request failed: ${r.status} - ${a}`)}return await r.json()}return await c(this,o,u).call(this,"GET",`${$}/${e}/progress`,{query:{...t&&{projectId:t}}})}async getExecution(e){if(this.localServerUrl){const t=`${this.localServerUrl}/api/${$}/progress/${e}`,s=await fetch(t);if(!s.ok){const i=await s.text().catch(()=>"");throw new Error(`Local server request failed: ${s.status} - ${i}`)}return await s.json()}return await c(this,o,u).call(this,"GET",`${$}/progress/${e}`)}async onExecutionProgress(e,t){const s=this.localServerUrl?`${this.localServerUrl}?accessToken=${this.accessToken}`:this.wsUrl,i=await U(s,{...this.localServerUrl&&{transports:["websocket"]}});i.on("connect",function(){i.emit("executionSubscription",JSON.stringify({executionId:e})),i.on("execution",r=>{t(r)})}),i.on("connect_error",function(r){console.log(r)})}async createHiddenFile(e,t){const s=new FormData;return s.append("file",e),s.append("parentItemId",t),await c(this,o,u).call(this,"POST",`${f}/${O}`,{body:s})}async createHiddenFilesBatch(e,t){const s=new FormData;for(const i of e)s.append("files",i);return s.append("parentItemId",t),await c(this,o,u).call(this,"POST",`${f}/${O}/batch`,{body:s})}async deleteHiddenFile(e){return await c(this,o,u).call(this,"DELETE",`${f}/${O}/${e}`)}async getHiddenFile(e){return await c(this,o,u).call(this,"GET",`${f}/${O}/${e}`)}async downloadHiddenFile(e){return await c(this,o,C).call(this,`${f}/${O}/${e}/download`)}async getHiddenFileSignedUrl(e,t){return await c(this,o,u).call(this,"GET",`${f}/${O}/${e}/signed-url`,{...t!=null&&{query:{expiresIn:t}}})}async getHiddenFileSignedUrlsBatch(e,t){return await c(this,o,q).call(this,e,async s=>(await c(this,o,u).call(this,"POST",`${f}/${O}/signed-url/batch`,{body:JSON.stringify({hiddenFileIds:s,...t!=null&&{expiresIn:t}}),contentType:"application/json"})).results)}async getHiddenFilesByParent(e){return await c(this,o,u).call(this,"GET",`${f}/${e}/${O}`)}async deleteHiddenFilesByParent(e){return await c(this,o,u).call(this,"DELETE",`${f}/${e}/${O}`)}async uploadItemIcon(e,t){const s=new FormData;return s.append("icon",t),await c(this,o,u).call(this,"PUT",`${f}/${e}/icon`,{body:s})}async getItemIcon(e){return await c(this,o,C).call(this,`${f}/${e}/icon`)}async removeItemIcon(e){return await c(this,o,u).call(this,"DELETE",`${f}/${e}/icon`)}async updateItem(e,t){return await c(this,o,u).call(this,"PUT",`${f}/${e}`,{body:JSON.stringify(t),contentType:"application/json"})}async createVersion(e,t,s,i,r){const a=new FormData;return a.append("file",t),a.append("versionTag",s),i&&a.append("extraProps",JSON.stringify(i)),r&&a.append("metadata",JSON.stringify(r)),await c(this,o,u).call(this,"POST",`${f}/${e}/version`,{body:a})}async listVersions(e,t={}){return await c(this,o,u).call(this,"GET",`${f}/${encodeURIComponent(e)}/versions`,{query:t})}async listVersionsBatch(e,t={}){const{archived:s}=t;return await c(this,o,q).call(this,e,async i=>(await c(this,o,u).call(this,"POST",`${f}/batch/versions`,{body:JSON.stringify({itemIds:i,...s!==void 0&&{archived:s}}),contentType:"application/json"})).results)}async archiveVersion(e,t){return await c(this,o,u).call(this,"PUT",`${f}/${encodeURIComponent(e)}/version/${encodeURIComponent(t)}/archive`)}async recoverVersion(e,t){return await c(this,o,u).call(this,"PUT",`${f}/${encodeURIComponent(e)}/version/${encodeURIComponent(t)}/recover`)}async deleteVersion(e,t){return await c(this,o,u).call(this,"DELETE",`${f}/${encodeURIComponent(e)}/version/${encodeURIComponent(t)}`)}};o=new WeakSet,le=function(e){return`${this.apiUrl}/${e}`},u=async function(e,t,s){const{body:i,query:r,contentType:a,retries:h,responseType:l}=s||{},y=c(this,o,le).call(this,t),d=c(this,o,He).call(this,r),m=await this.resolveAccessToken(),k={...d,...this.useBearer?{}:{accessToken:m}};try{const S=await fetch(y+"?"+new URLSearchParams(k).toString(),{method:e,headers:{Accept:"application/json",...a&&{"Content-Type":a},...this.useBearer&&{Authorization:`Bearer ${m}`}},...i&&{body:i}});if(!S.ok){const A=await S.text().then(Ge=>Ge).catch(()=>"");throw new Ve(S.status,S.statusText,A)}return l==="blob"?await S.blob():S.json().then(A=>A).catch(()=>{})}catch(S){let A=h??this.retries;if(A)return A=A-1,await c(this,o,u).call(this,e,t,{...s,retries:A});throw S}},C=async function(e,t){const{query:s}=t||{},i=c(this,o,le).call(this,e),r=await this.resolveAccessToken(),a={...s,...this.useBearer?{}:{accessToken:r}};return await fetch(i+"?"+new URLSearchParams(a).toString(),{method:"GET",...this.useBearer&&{headers:{Authorization:`Bearer ${r}`}}})},q=async function(e,t){if(!e.length)return[];const s=[];for(let r=0;r<e.length;r+=ue)s.push(e.slice(r,r+ue));return(await Promise.all(s.map(t))).flat()},G=async function(e,t){const{versionTag:s,withDraft:i}=t||{};return await c(this,o,C).call(this,`${f}/${e}/download`,{query:{...s&&{versionTag:s},...i&&{withDraft:i}}})},j=async function(e,t,s){const{name:i,versionTag:r,parentFolderId:a,projectId:h,file:l,metadata:y}=e,d=new FormData;return d.append("file",l),d.append("name",i),d.append("versionTag",r),d.append("itemType",t),a&&d.append("folderId",a),h&&d.append("projectId",h),s&&d.append("extraProps",JSON.stringify(s)),y&&d.append("metadata",JSON.stringify(y)),await c(this,o,u).call(this,"POST",f,{body:d})},fe=async function(e,t,s){const{name:i,versionTag:r,parentFolderId:a,file:h,metadata:l}=t;let y,d;if(h){const m=new FormData;m.append("file",h),r&&m.append("versionTag",r),s&&m.append("extraProps",JSON.stringify(s)),l&&m.append("metadata",JSON.stringify(l)),d=await c(this,o,u).call(this,"POST",`${f}/${e}/version`,{body:m})}if(i||a){const m={...i&&{name:i},...a&&{folderId:a}},k=JSON.stringify(m);y=await c(this,o,u).call(this,"PUT",`${f}/${e}`,{body:k,contentType:"application/json"})}return{item:y,version:d}},pe=async function(e,t){const{showVersions:s=!1}=t||{};return await c(this,o,u).call(this,"GET",`${f}/${e}`,{query:{showVersions:s}})},He=function(e){return e&&Object.entries(e).filter(([,t])=>t!==void 0).reduce((t,[s,i])=>(t[s]=i,t),{})};let J=be;const B="project",N="notifications";var P;const Te=class Te extends J{constructor(t,s,i){super(typeof t=="string"?t:"",s,{...i,useBearer:!0});z(this,P);typeof t=="function"&&ve(this,P,t)}async resolveAccessToken(){return X(this,P)?await X(this,P).call(this):super.resolveAccessToken()}static fromPlatformContext(t){const s=(typeof window<"u"?window.__THATOPEN_CONTEXT__:null)||{appId:"",projectId:"",accessToken:"",apiUrl:""},i=new Te(s.accessToken,s.apiUrl,t);return i.context=s,i}async getProject(t){return await this.request("GET",`${B}/${t}`)}async getProjectData(t){return await this.request("GET",`${B}/${t}/data`)}async getAvatar(t){return await this.request("GET",`account/${t}/avatar`,{responseType:"blob"})}async checkPermission(t){return await this.request("GET",`${B}/permissions/check`,{query:t})}async checkPermissionBatch(t){return(await this.request("POST",`${B}/permissions/check/batch`,{body:JSON.stringify({checks:t}),contentType:"application/json"})).results}async getNotifications(t){return await this.request("GET",N,{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",`${N}/unread-count`)).count}async markNotificationsRead(t){return await this.request("POST",`${N}/mark-read`,{body:JSON.stringify({ids:t}),contentType:"application/json"})}async markAllNotificationsRead(){return await this.request("POST",`${N}/mark-all-read`)}async getNotificationSubscriptions(){return await this.request("GET",`${N}/subscriptions`)}async unsubscribeFromAutomation(t){return await this.request("DELETE",`${N}/subscriptions/${t}`)}async subscribeToAutomation(t,s,i){return await this.request("POST",`${B}/${t}/events/hooks/${s}/subscription`,{body:JSON.stringify(i??{}),contentType:"application/json"})}async updateAutomationSubscription(t,s,i){return await this.request("PATCH",`${B}/${t}/events/hooks/${s}/subscription`,{body:JSON.stringify(i),contentType:"application/json"})}async onNotification(t){const s=await this.resolveAccessToken(),i=U(`${this.socketOrigin}/notifications?accessToken=${encodeURIComponent(s)}`,{transports:["websocket"]});return i.on("notification.created",r=>t({type:"created",id:r==null?void 0:r.id})),i.on("notification.read",r=>t({type:"read",id:r==null?void 0:r.id})),i.on("notifications.allRead",r=>t({type:"allRead",batch:r==null?void 0:r.batch})),()=>i.disconnect()}};P=new WeakMap;let de=Te;const Vt={MAX_FIELDS:200,MAX_KEY_LENGTH:50,MAX_VALUE_LENGTH:50},Ht={uuid:"a3f82c1d-5b74-4e9a-bc30-d7e12f894a61"},Gt={uuid:"2c9f4e8d-3a1b-4c5e-9d7f-0a2b6c8e1d3f"},jt={uuid:"b0b5e2a2-0b3a-4a6b-8b1c-0b1c4a6b8b1c"},Jt={uuid:"3f9c1a7e-6b2d-4e18-9a5c-7d0e2f4b6c81"},Yt={uuid:"2c4ae432-fc24-43e9-9783-0c960c674e96"},Kt={uuid:"69af63aa-19ba-4fc7-b17b-75647bac1d76"},Wt={uuid:"234f1416-528d-452a-9cc9-a16c5239b2eb"};exports.CDEManager=Ht;exports.ClashesManager=Gt;exports.EngineServicesClient=J;exports.FileList=jt;exports.GitHistoryManager=Jt;exports.HelloWorld=Yt;exports.METADATA_LIMITS=Vt;exports.PlatformClient=de;exports.RequestError=Ve;exports.STORAGE_BATCH_MAX=ue;exports.TopicsManager=Kt;exports.UIManager=Wt;
|
|
1
|
+
"use strict";var Ye=Object.defineProperty;var Ae=n=>{throw TypeError(n)};var Ke=(n,e,t)=>e in n?Ye(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var w=(n,e,t)=>Ke(n,typeof e!="symbol"?e+"":e,t),z=(n,e,t)=>e.has(n)||Ae("Cannot "+t);var Q=(n,e,t)=>(z(n,e,"read from private field"),t?t.call(n):e.get(n)),Z=(n,e,t)=>e.has(n)?Ae("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(n):e.set(n,t),ke=(n,e,t,s)=>(z(n,e,"write to private field"),s?s.call(n,t):e.set(n,t),t),c=(n,e,t)=>(z(n,e,"access private method"),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const k=Object.create(null);k.open="0";k.close="1";k.ping="2";k.pong="3";k.message="4";k.upgrade="5";k.noop="6";const V=Object.create(null);Object.keys(k).forEach(n=>{V[k[n]]=n});const oe={type:"error",data:"parser error"},Ne=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",xe=typeof ArrayBuffer=="function",Pe=n=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(n):n&&n.buffer instanceof ArrayBuffer,ge=({type:n,data:e},t,s)=>Ne&&e instanceof Blob?t?s(e):Se(e,s):xe&&(e instanceof ArrayBuffer||Pe(e))?t?s(e):Se(new Blob([e]),s):s(k[n]+(e||"")),Se=(n,e)=>{const t=new FileReader;return t.onload=function(){const s=t.result.split(",")[1];e("b"+(s||""))},t.readAsDataURL(n)};function Oe(n){return n instanceof Uint8Array?n:n instanceof ArrayBuffer?new Uint8Array(n):new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}let ee;function We(n,e){if(Ne&&n.data instanceof Blob)return n.data.arrayBuffer().then(Oe).then(e);if(xe&&(n.data instanceof ArrayBuffer||Pe(n.data)))return e(Oe(n.data));ge(n,!1,t=>{ee||(ee=new TextEncoder),e(ee.encode(t))})}const $e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",L=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let n=0;n<$e.length;n++)L[$e.charCodeAt(n)]=n;const Xe=n=>{let e=n.length*.75,t=n.length,s,r=0,i,o,h,l;n[n.length-1]==="="&&(e--,n[n.length-2]==="="&&e--);const y=new ArrayBuffer(e),d=new Uint8Array(y);for(s=0;s<t;s+=4)i=L[n.charCodeAt(s)],o=L[n.charCodeAt(s+1)],h=L[n.charCodeAt(s+2)],l=L[n.charCodeAt(s+3)],d[r++]=i<<2|o>>4,d[r++]=(o&15)<<4|h>>2,d[r++]=(h&3)<<6|l&63;return y},ze=typeof ArrayBuffer=="function",we=(n,e)=>{if(typeof n!="string")return{type:"message",data:Ie(n,e)};const t=n.charAt(0);return t==="b"?{type:"message",data:Qe(n.substring(1),e)}:V[t]?n.length>1?{type:V[t],data:n.substring(1)}:{type:V[t]}:oe},Qe=(n,e)=>{if(ze){const t=Xe(n);return Ie(t,e)}else return{base64:!0,data:n}},Ie=(n,e)=>{switch(e){case"blob":return n instanceof Blob?n:new Blob([n]);case"arraybuffer":default:return n instanceof ArrayBuffer?n:n.buffer}},Le="",Ze=(n,e)=>{const t=n.length,s=new Array(t);let r=0;n.forEach((i,o)=>{ge(i,!1,h=>{s[o]=h,++r===t&&e(s.join(Le))})})},et=(n,e)=>{const t=n.split(Le),s=[];for(let r=0;r<t.length;r++){const i=we(t[r],e);if(s.push(i),i.type==="error")break}return s};function tt(){return new TransformStream({transform(n,e){We(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 F(n){return n.reduce((e,t)=>e+t.length,0)}function M(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 st(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(F(t)<1)break;const l=M(t,1);i=(l[0]&128)===128,r=l[0]&127,r<126?s=3:r===126?s=1:s=2}else if(s===1){if(F(t)<2)break;const l=M(t,2);r=new DataView(l.buffer,l.byteOffset,l.length).getUint16(0),s=3}else if(s===2){if(F(t)<8)break;const l=M(t,8),y=new DataView(l.buffer,l.byteOffset,l.length),d=y.getUint32(0);if(d>Math.pow(2,21)-1){h.enqueue(oe);break}r=d*Math.pow(2,32)+y.getUint32(4),s=3}else{if(F(t)<r)break;const l=M(t,r);h.enqueue(we(i?l:te.decode(l),e)),s=0}if(r===0||r>n){h.enqueue(oe);break}}}})}const qe=4;function g(n){if(n)return nt(n)}function nt(n){for(var e in g.prototype)n[e]=g.prototype[e];return n}g.prototype.on=g.prototype.addEventListener=function(n,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+n]=this._callbacks["$"+n]||[]).push(e),this};g.prototype.once=function(n,e){function t(){this.off(n,t),e.apply(this,arguments)}return t.fn=e,this.on(n,t),this};g.prototype.off=g.prototype.removeListener=g.prototype.removeAllListeners=g.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};g.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};g.prototype.emitReserved=g.prototype.emit;g.prototype.listeners=function(n){return this._callbacks=this._callbacks||{},this._callbacks["$"+n]||[]};g.prototype.hasListeners=function(n){return!!this.listeners(n).length};const K=typeof Promise=="function"&&typeof Promise.resolve=="function"?e=>Promise.resolve().then(e):(e,t)=>t(e,0),_=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),rt="arraybuffer";function Ue(n,...e){return e.reduce((t,s)=>(n.hasOwnProperty(s)&&(t[s]=n[s]),t),{})}const it=_.setTimeout,ot=_.clearTimeout;function W(n,e){e.useNativeTimers?(n.setTimeoutFn=it.bind(_),n.clearTimeoutFn=ot.bind(_)):(n.setTimeoutFn=_.setTimeout.bind(_),n.clearTimeoutFn=_.clearTimeout.bind(_))}const at=1.33;function ct(n){return typeof n=="string"?ht(n):Math.ceil((n.byteLength||n.size)*at)}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 De(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function ut(n){let e="";for(let t in n)n.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(n[t]));return e}function lt(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 ft extends Error{constructor(e,t,s){super(e),this.description=t,this.context=s,this.type="TransportError"}}class _e extends g{constructor(e){super(),this.writable=!1,W(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 ft(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=we(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=ut(e);return t.length?"?"+t:""}}class pt extends _e{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)};et(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,Ze(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]=De()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}}let Fe=!1;try{Fe=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const dt=Fe;function yt(){}class mt extends pt{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 A extends g{constructor(e,t,s){super(),this.createRequest=e,W(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=Ue(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=A.requestsCount++,A.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=yt,e)try{this._xhr.abort()}catch{}typeof document<"u"&&delete A.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()}}A.requestsCount=0;A.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",Re);else if(typeof addEventListener=="function"){const n="onpagehide"in _?"pagehide":"unload";addEventListener(n,Re,!1)}}function Re(){for(let n in A.requests)A.requests.hasOwnProperty(n)&&A.requests[n].abort()}const gt=function(){const n=Me({xdomain:!1});return n&&n.responseType!==null}();class wt extends mt{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=gt&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new A(Me,this.uri(),e)}}function Me(n){const e=n.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||dt))return new XMLHttpRequest}catch{}if(!e)try{return new _[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const Ve=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class _t extends _e{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,s=Ve?{}:Ue(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;ge(s,this.supportsBinary,i=>{try{this.doWrite(s,i)}catch{}r&&K(()=>{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]=De()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const se=_.WebSocket||_.MozWebSocket;class bt extends _t{createSocket(e,t,s){return Ve?new se(e,t,s):t?new se(e,t):new se(e)}doWrite(e,t){this.ws.send(t)}}class Tt extends _e{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=st(Number.MAX_SAFE_INTEGER,this.socket.binaryType),s=e.readable.pipeThrough(t).getReader(),r=tt();r.readable.pipeTo(e.writable),this._writer=r.writable.getWriter();const i=()=>{s.read().then(({done:h,value:l})=>{h||(this.onPacket(l),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&&K(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}}const Et={websocket:bt,webtransport:Tt,polling:wt},vt=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,At=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function ae(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=vt.exec(n||""),i={},o=14;for(;o--;)i[At[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=kt(i,i.path),i.queryKey=St(i,i.query),i}function kt(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 St(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",H=[];ce&&addEventListener("offline",()=>{H.forEach(n=>n())},!1);class R extends g{constructor(e,t){if(super(),this.binaryType=rt,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=ae(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=ae(t.host).host);W(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=lt(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"})},H.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=qe,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&&R.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",R.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+=ct(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,K(()=>{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(R.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=H.indexOf(this._offlineEventListener);s!==-1&&H.splice(s,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}R.protocol=qe;class Ot extends R{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;R.priorWebsocketSuccess=!1;const r=()=>{s||(t.send([{type:"ping",data:"probe"}]),t.once("packet",m=>{if(!s)if(m.type==="pong"&&m.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;R.priorWebsocketSuccess=t.name==="websocket",this.transport.pause(()=>{s||this.readyState!=="closed"&&(d(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{const E=new Error("probe error");E.transport=t.name,this.emitReserved("upgradeError",E)}}))};function i(){s||(s=!0,d(),t.close(),t=null)}const o=m=>{const E=new Error("probe error: "+m);E.transport=t.name,i(),this.emitReserved("upgradeError",E)};function h(){o("transport closed")}function l(){o("socket closed")}function y(m){t&&m.name!==t.name&&i()}const d=()=>{t.removeListener("open",r),t.removeListener("error",o),t.removeListener("close",h),this.off("close",l),this.off("upgrading",y)};t.once("open",r),t.once("error",o),t.once("close",h),this.once("close",l),this.once("upgrading",y),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 $t=class extends Ot{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=>Et[i]).filter(i=>!!i)),super(s?r:e,r)}};function Rt(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=ae(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 Ct=typeof ArrayBuffer=="function",Bt=n=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(n):n.buffer instanceof ArrayBuffer,He=Object.prototype.toString,Nt=typeof Blob=="function"||typeof Blob<"u"&&He.call(Blob)==="[object BlobConstructor]",xt=typeof File=="function"||typeof File<"u"&&He.call(File)==="[object FileConstructor]";function be(n){return Ct&&(n instanceof ArrayBuffer||Bt(n))||Nt&&n instanceof Blob||xt&&n instanceof File}function j(n,e){if(!n||typeof n!="object")return!1;if(Array.isArray(n)){for(let t=0,s=n.length;t<s;t++)if(j(n[t]))return!0;return!1}if(be(n))return!0;if(n.toJSON&&typeof n.toJSON=="function"&&arguments.length===1)return j(n.toJSON(),!0);for(const t in n)if(Object.prototype.hasOwnProperty.call(n,t)&&j(n[t]))return!0;return!1}function Pt(n){const e=[],t=n.data,s=n;return s.data=he(t,e),s.attachments=e.length,{packet:s,buffers:e}}function he(n,e){if(!n)return n;if(be(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]=he(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]=he(n[s],e));return t}return n}function It(n,e){return n.data=ue(n.data,e),delete n.attachments,n}function ue(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]=ue(n[t],e);else if(typeof n=="object")for(const t in n)Object.prototype.hasOwnProperty.call(n,t)&&(n[t]=ue(n[t],e));return n}const Lt=["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 qt{constructor(e){this.replacer=e}encode(e){return(e.type===p.EVENT||e.type===p.ACK)&&j(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=Pt(e),s=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(s),r}}class Te extends g{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 Ut(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if(be(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(!Dt(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(Te.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 Ce(t);case p.DISCONNECT:return t===void 0;case p.CONNECT_ERROR:return typeof t=="string"||Ce(t);case p.EVENT:case p.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&Lt.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 Ut{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=It(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const Dt=Number.isInteger||function(n){return typeof n=="number"&&isFinite(n)&&Math.floor(n)===n};function Ce(n){return Object.prototype.toString.call(n)==="[object Object]"}const Ft=Object.freeze(Object.defineProperty({__proto__:null,Decoder:Te,Encoder:qt,get PacketType(){return p}},Symbol.toStringTag,{value:"Module"}));function T(n,e,t){return n.on(e,t),function(){n.off(e,t)}}const Mt=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class je extends g{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=[T(e,"open",this.onopen.bind(this)),T(e,"packet",this.onpacket.bind(this)),T(e,"error",this.onerror.bind(this)),T(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(Mt.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 d=this.ids++,m=t.pop();this._registerAckCallback(d,m),o.id=d}const h=(r=(s=this.io.engine)===null||s===void 0?void 0:s.transport)===null||r===void 0?void 0:r.writable,l=this.connected&&!(!((i=this.io.engine)===null||i===void 0)&&i._hasPingExpired());return this.flags.volatile&&!h||(l?(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 P(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}P.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};P.prototype.reset=function(){this.attempts=0};P.prototype.setMin=function(n){this.ms=n};P.prototype.setMax=function(n){this.max=n};P.prototype.setJitter=function(n){this.jitter=n};class le extends g{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,W(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 P({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||Ft;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 $t(this.uri,this.opts);const t=this.engine,s=this;this._readyState="opening",this.skipReconnect=!1;const r=T(t,"open",function(){s.onopen(),e&&e()}),i=h=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",h),e?e(h):this.maybeReconnectOnOpen()},o=T(t,"error",i);if(this._timeout!==!1){const h=this._timeout,l=this.setTimeoutFn(()=>{r(),i(new Error("timeout")),t.close()},h);this.opts.autoUnref&&l.unref(),this.subs.push(()=>{this.clearTimeoutFn(l)})}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(T(e,"ping",this.onping.bind(this)),T(e,"data",this.ondata.bind(this)),T(e,"error",this.onerror.bind(this)),T(e,"close",this.onclose.bind(this)),T(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){K(()=>{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 je(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 I={};function U(n,e){typeof n=="object"&&(e=n,n=void 0),e=e||{};const t=Rt(n,e.path||"/socket.io"),s=t.source,r=t.id,i=t.path,o=I[r]&&i in I[r].nsps,h=e.forceNew||e["force new connection"]||e.multiplex===!1||o;let l;return h?l=new le(s,e):(I[r]||(I[r]=new le(s,e)),l=I[r]),t.query&&!e.query&&(e.query=t.queryKey),l.socket(t.path,e)}Object.assign(U,{Manager:le,Socket:je,io:U,connect:U});const fe=100;function Vt(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 Ht(n){if(!n||typeof n!="object")return;const e=n.retryAfter;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0}class X extends Error{constructor(t,s,r,i){const o=Vt(r);super(o.message??`${s||"Request failed"} (${t})`);w(this,"status");w(this,"code");w(this,"details");w(this,"body");w(this,"retryAfter");this.name="RequestError",this.status=t,this.code=o.code,this.details=o.details,this.body=r,this.retryAfter=i??Ht(o.details)}}const v="item/folder",f="item",O="processor",jt="npm-registry",S="hidden",ne="FILE",re="TOOL",ie="APP",Gt=500,Be=3e4,Jt=.25,Yt=n=>new Promise(e=>setTimeout(e,n));function Kt(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 Wt(n){return n instanceof X?n.status===429||n.status>=500:!0}function Xt(n,e){const t=Math.min(Gt*2**e,Be),s=t*Jt*Math.random(),r=n instanceof X&&n.retryAfter!=null?n.retryAfter*1e3:void 0;return r!=null?Math.min(r,Be)+s:t+s}var a,pe,u,$,q,G,J,de,ye,Ge;const Ee=class Ee{constructor(e,t,s){Z(this,a);w(this,"apiUrl");w(this,"accessToken");w(this,"wsUrl");w(this,"retries");w(this,"useBearer");w(this,"builtInGlobals",null);w(this,"localServerUrl",null);w(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}?accessToken=${e}`,this.retries=r,this.useBearer=i,this.context={appId:"",projectId:"",accessToken:e,apiUrl:t},o){let l=o;l.charAt(l.length-1)==="/"&&(l=l.slice(0,-1)),this.localServerUrl=l}}static fromPlatformContext(e){const t=(typeof window<"u"?window.__THATOPEN_CONTEXT__:null)||{appId:"",projectId:"",accessToken:"",apiUrl:""},s=new Ee(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 c(this,a,u).call(this,e,t,s)}async listFiles(e){const{folderId:t,archived:s,projectId:r}=e||{};return t?await c(this,a,u).call(this,"GET",`${v}/${t}/items`,{query:{itemType:ne,archived:s}}):await c(this,a,u).call(this,"GET",`${f}`,{query:{itemType:ne,archived:s,...r&&{projectId:r}}})}async getFile(e,t){return await c(this,a,ye).call(this,e,t)}async createFile(e){return await c(this,a,J).call(this,e,ne)}async updateFile(e,t){return await c(this,a,de).call(this,e,t)}async archiveFile(e){return await c(this,a,u).call(this,"DELETE",`${f}/${e}`)}async recoverFile(e){return await c(this,a,u).call(this,"PUT",`${f}/${e}/recover`)}async downloadFile(e,t){return await c(this,a,G).call(this,e,t)}async getFileVersionMetadata(e,t,s){const{withDraft:r}=s||{};return await c(this,a,u).call(this,"GET",`${f}/${encodeURIComponent(e)}/version/${encodeURIComponent(t)}/metadata`,{query:{...r&&{withDraft:"true"}}})}async updateFileVersionMetadata(e,t,s){return await c(this,a,u).call(this,"PUT",`${f}/${encodeURIComponent(e)}/version/${encodeURIComponent(t)}/metadata`,{body:JSON.stringify({metadata:s}),contentType:"application/json"})}async deleteFileVersionMetadata(e,t){return await c(this,a,u).call(this,"DELETE",`${f}/${encodeURIComponent(e)}/version/${encodeURIComponent(t)}/metadata`)}async getFileVersionMetadataBatch(e,t){const{withDraft:s}=t||{};return await c(this,a,q).call(this,e,async r=>(await c(this,a,u).call(this,"POST",`${f}/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 c(this,a,u).call(this,"GET",v,{query:{parentFolderId:s,archived:t,...r&&{projectId:r}}})}async getFolder(e){return await c(this,a,u).call(this,"GET",`${v}/${e}`)}async getFoldersBatch(e){return await c(this,a,q).call(this,e,async t=>(await c(this,a,u).call(this,"POST",`${f}/batch/folders`,{body:JSON.stringify({folderIds:t}),contentType:"application/json"})).results)}async createFolder(e,t,s){return await c(this,a,u).call(this,"POST",v,{body:JSON.stringify({name:e,...t&&{parentId:t},...s&&{projectId:s}}),contentType:"application/json"})}async updateFolder(e,t){const{name:s}=t;return await c(this,a,u).call(this,"PUT",`${v}/${e}`,{body:JSON.stringify({name:s}),contentType:"application/json"})}async archiveFolder(e){return await c(this,a,u).call(this,"DELETE",`${v}/${e}`)}async recoverFolder(e){return await c(this,a,u).call(this,"PUT",`${v}/${e}/recover`)}async downloadFolder(e){return await c(this,a,$).call(this,`${v}/${e}/download`)}async listComponents(e){const{folderId:t,ShowVersions:s,projectId:r}=e||{};return t?await c(this,a,u).call(this,"GET",`${v}/${t}/items`,{query:{itemType:re,...s&&{ShowVersions:s}}}):await c(this,a,u).call(this,"GET",`${f}`,{query:{itemType:re,...s&&{ShowVersions:s},...r&&{projectId:r}}})}async getComponent(e,t){return await c(this,a,ye).call(this,e,t)}async createComponent(e){const{componentProps:t}=e;return await c(this,a,J).call(this,e,re,t)}async updateComponent(e,t){const{componentProps:s}=t;return await c(this,a,de).call(this,e,t,s)}async downloadComponent(e,t){return await c(this,a,G).call(this,e,t)}async downloadComponentBundle(e,t){const{versionTag:s,withDraft:r}=t||{};return await c(this,a,$).call(this,`${f}/${e}/download/bundle`,{query:{...s&&{versionTag:s},...r&&{withDraft:r}}})}async archiveComponent(e){return await c(this,a,u).call(this,"DELETE",`${f}/${e}`)}async recoverComponent(e){return await c(this,a,u).call(this,"PUT",`${f}/${e}/recover`)}async getBuiltInComponent(e){return await(await c(this,a,$).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(m=>i[m]),y=new Function(...o,`${r}
|
|
2
|
+
return main;`)(...h),d=(y==null?void 0:y.componentDefinition)??y;t.get(d)}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 c(this,a,u).call(this,"GET",`${v}/${t}/items`,{query:{itemType:ie,...s&&{ShowVersions:s}}}):await c(this,a,u).call(this,"GET",`${f}`,{query:{itemType:ie,...s&&{ShowVersions:s},...r&&{projectId:r}}})}async createApp(e){const{appProps:t}=e;return await c(this,a,J).call(this,e,ie,t)}async downloadApp(e,t){return await c(this,a,G).call(this,e,t)}async downloadAppBundle(e,t){const{versionTag:s,withDraft:r}=t||{};return await c(this,a,$).call(this,`${f}/${e}/download/bundle`,{query:{...s&&{versionTag:s},...r&&{withDraft:r}}})}async archiveApp(e){return await c(this,a,u).call(this,"DELETE",`${f}/${e}`)}async getNpmCredentials(){return await c(this,a,u).call(this,"GET",`${jt}/credentials`)}async executeComponent(e,t,s){if(this.localServerUrl){const r=`${this.localServerUrl}/api/${O}/${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 c(this,a,u).call(this,"POST",`${O}/${e}/execute`,{body:JSON.stringify(t),query:{...s&&{versionTag:s}},contentType:"application/json"})}async abortExecution(e){if(this.localServerUrl){const t=`${this.localServerUrl}/api/${O}/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 c(this,a,u).call(this,"POST",`${O}/progress/${e}/abort`)}async listExecutions(e,t){if(this.localServerUrl){const s=t?`?projectId=${encodeURIComponent(t)}`:"",r=`${this.localServerUrl}/api/${O}/${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 c(this,a,u).call(this,"GET",`${O}/${e}/progress`,{query:{...t&&{projectId:t}}})}async getExecution(e){if(this.localServerUrl){const t=`${this.localServerUrl}/api/${O}/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 c(this,a,u).call(this,"GET",`${O}/progress/${e}`)}async onExecutionProgress(e,t){const s=this.localServerUrl?`${this.localServerUrl}?accessToken=${this.accessToken}`:this.wsUrl,r=await U(s,{...this.localServerUrl&&{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){const s=new FormData;return s.append("file",e),s.append("parentItemId",t),await c(this,a,u).call(this,"POST",`${f}/${S}`,{body:s})}async createHiddenFilesBatch(e,t){const s=new FormData;for(const r of e)s.append("files",r);return s.append("parentItemId",t),await c(this,a,u).call(this,"POST",`${f}/${S}/batch`,{body:s})}async deleteHiddenFile(e){return await c(this,a,u).call(this,"DELETE",`${f}/${S}/${e}`)}async getHiddenFile(e){return await c(this,a,u).call(this,"GET",`${f}/${S}/${e}`)}async downloadHiddenFile(e){return await c(this,a,$).call(this,`${f}/${S}/${e}/download`)}async getHiddenFileSignedUrl(e,t){return await c(this,a,u).call(this,"GET",`${f}/${S}/${e}/signed-url`,{...t!=null&&{query:{expiresIn:t}}})}async getHiddenFileSignedUrlsBatch(e,t){return await c(this,a,q).call(this,e,async s=>(await c(this,a,u).call(this,"POST",`${f}/${S}/signed-url/batch`,{body:JSON.stringify({hiddenFileIds:s,...t!=null&&{expiresIn:t}}),contentType:"application/json"})).results)}async getHiddenFilesByParent(e){return await c(this,a,u).call(this,"GET",`${f}/${e}/${S}`)}async deleteHiddenFilesByParent(e){return await c(this,a,u).call(this,"DELETE",`${f}/${e}/${S}`)}async uploadItemIcon(e,t){const s=new FormData;return s.append("icon",t),await c(this,a,u).call(this,"PUT",`${f}/${e}/icon`,{body:s})}async getItemIcon(e){return await c(this,a,$).call(this,`${f}/${e}/icon`)}async removeItemIcon(e){return await c(this,a,u).call(this,"DELETE",`${f}/${e}/icon`)}async updateItem(e,t){return await c(this,a,u).call(this,"PUT",`${f}/${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 c(this,a,u).call(this,"POST",`${f}/${e}/version`,{body:o})}async listVersions(e,t={}){return await c(this,a,u).call(this,"GET",`${f}/${encodeURIComponent(e)}/versions`,{query:t})}async listVersionsBatch(e,t={}){const{archived:s}=t;return await c(this,a,q).call(this,e,async r=>(await c(this,a,u).call(this,"POST",`${f}/batch/versions`,{body:JSON.stringify({itemIds:r,...s!==void 0&&{archived:s}}),contentType:"application/json"})).results)}async archiveVersion(e,t){return await c(this,a,u).call(this,"PUT",`${f}/${encodeURIComponent(e)}/version/${encodeURIComponent(t)}/archive`)}async recoverVersion(e,t){return await c(this,a,u).call(this,"PUT",`${f}/${encodeURIComponent(e)}/version/${encodeURIComponent(t)}/recover`)}async deleteVersion(e,t){return await c(this,a,u).call(this,"DELETE",`${f}/${encodeURIComponent(e)}/version/${encodeURIComponent(t)}`)}};a=new WeakSet,pe=function(e){return`${this.apiUrl}/${e}`},u=async function(e,t,s){const{body:r,query:i,contentType:o,retries:h,responseType:l,retryAttempt:y}=s||{},d=c(this,a,pe).call(this,t),m=c(this,a,Ge).call(this,i),E=await this.resolveAccessToken(),Je={...m,...this.useBearer?{}:{accessToken:E}};try{const b=await fetch(d+"?"+new URLSearchParams(Je).toString(),{method:e,headers:{Accept:"application/json",...o&&{"Content-Type":o},...this.useBearer&&{Authorization:`Bearer ${E}`}},...r&&{body:r}});if(!b.ok){const C=await b.text().then(D=>D).catch(()=>"");throw new X(b.status,b.statusText,C,Kt(b))}return l==="blob"?await b.blob():b.json().then(C=>C).catch(()=>{})}catch(b){const C=h??this.retries;if(C>0&&Wt(b)){const D=y??0;return await Yt(Xt(b,D)),await c(this,a,u).call(this,e,t,{...s,retries:C-1,retryAttempt:D+1})}throw b}},$=async function(e,t){const{query:s}=t||{},r=c(this,a,pe).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}`}}})},q=async function(e,t){if(!e.length)return[];const s=[];for(let i=0;i<e.length;i+=fe)s.push(e.slice(i,i+fe));return(await Promise.all(s.map(t))).flat()},G=async function(e,t){const{versionTag:s,withDraft:r}=t||{};return await c(this,a,$).call(this,`${f}/${e}/download`,{query:{...s&&{versionTag:s},...r&&{withDraft:r}}})},J=async function(e,t,s){const{name:r,versionTag:i,parentFolderId:o,projectId:h,file:l,metadata:y}=e,d=new FormData;return d.append("file",l),d.append("name",r),d.append("versionTag",i),d.append("itemType",t),o&&d.append("folderId",o),h&&d.append("projectId",h),s&&d.append("extraProps",JSON.stringify(s)),y&&d.append("metadata",JSON.stringify(y)),await c(this,a,u).call(this,"POST",f,{body:d})},de=async function(e,t,s){const{name:r,versionTag:i,parentFolderId:o,file:h,metadata:l}=t;let y,d;if(h){const m=new FormData;m.append("file",h),i&&m.append("versionTag",i),s&&m.append("extraProps",JSON.stringify(s)),l&&m.append("metadata",JSON.stringify(l)),d=await c(this,a,u).call(this,"POST",`${f}/${e}/version`,{body:m})}if(r||o){const m={...r&&{name:r},...o&&{folderId:o}},E=JSON.stringify(m);y=await c(this,a,u).call(this,"PUT",`${f}/${e}`,{body:E,contentType:"application/json"})}return{item:y,version:d}},ye=async function(e,t){const{showVersions:s=!1}=t||{};return await c(this,a,u).call(this,"GET",`${f}/${e}`,{query:{showVersions:s}})},Ge=function(e){return e&&Object.entries(e).filter(([,t])=>t!==void 0).reduce((t,[s,r])=>(t[s]=r,t),{})};let Y=Ee;const B="project",N="notifications";var x;const ve=class ve extends Y{constructor(t,s,r){super(typeof t=="string"?t:"",s,{...r,useBearer:!0});Z(this,x);typeof t=="function"&&ke(this,x,t)}async resolveAccessToken(){return Q(this,x)?await Q(this,x).call(this):super.resolveAccessToken()}static fromPlatformContext(t){const s=(typeof window<"u"?window.__THATOPEN_CONTEXT__:null)||{appId:"",projectId:"",accessToken:"",apiUrl:""},r=new ve(s.accessToken,s.apiUrl,t);return r.context=s,r}async getProject(t){return await this.request("GET",`${B}/${t}`)}async getProjectData(t){return await this.request("GET",`${B}/${t}/data`)}async getAvatar(t){return await this.request("GET",`account/${t}/avatar`,{responseType:"blob"})}async checkPermission(t){return await this.request("GET",`${B}/permissions/check`,{query:t})}async checkPermissionBatch(t){return(await this.request("POST",`${B}/permissions/check/batch`,{body:JSON.stringify({checks:t}),contentType:"application/json"})).results}async getNotifications(t){return await this.request("GET",N,{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",`${N}/unread-count`)).count}async markNotificationsRead(t){return await this.request("POST",`${N}/mark-read`,{body:JSON.stringify({ids:t}),contentType:"application/json"})}async markAllNotificationsRead(){return await this.request("POST",`${N}/mark-all-read`)}async getNotificationSubscriptions(){return await this.request("GET",`${N}/subscriptions`)}async unsubscribeFromAutomation(t){return await this.request("DELETE",`${N}/subscriptions/${t}`)}async subscribeToAutomation(t,s,r){return await this.request("POST",`${B}/${t}/events/hooks/${s}/subscription`,{body:JSON.stringify(r??{}),contentType:"application/json"})}async updateAutomationSubscription(t,s,r){return await this.request("PATCH",`${B}/${t}/events/hooks/${s}/subscription`,{body:JSON.stringify(r),contentType:"application/json"})}async onNotification(t){const s=await this.resolveAccessToken(),r=U(`${this.socketOrigin}/notifications?accessToken=${encodeURIComponent(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()}};x=new WeakMap;let me=ve;const zt={MAX_FIELDS:200,MAX_KEY_LENGTH:50,MAX_VALUE_LENGTH:50},Qt={uuid:"a3f82c1d-5b74-4e9a-bc30-d7e12f894a61"},Zt={uuid:"2c9f4e8d-3a1b-4c5e-9d7f-0a2b6c8e1d3f"},es={uuid:"b0b5e2a2-0b3a-4a6b-8b1c-0b1c4a6b8b1c"},ts={uuid:"3f9c1a7e-6b2d-4e18-9a5c-7d0e2f4b6c81"},ss={uuid:"2c4ae432-fc24-43e9-9783-0c960c674e96"},ns={uuid:"69af63aa-19ba-4fc7-b17b-75647bac1d76"},rs={uuid:"234f1416-528d-452a-9cc9-a16c5239b2eb"};exports.CDEManager=Qt;exports.ClashesManager=Zt;exports.EngineServicesClient=Y;exports.FileList=es;exports.GitHistoryManager=ts;exports.HelloWorld=ss;exports.METADATA_LIMITS=zt;exports.PlatformClient=me;exports.RequestError=X;exports.STORAGE_BATCH_MAX=fe;exports.TopicsManager=ns;exports.UIManager=rs;
|