@thatopen/services 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CONTEXT.md +258 -0
- package/README.md +285 -0
- package/dist/built-in/index.d.ts +723 -0
- package/dist/cli/commands/create-tests.d.ts +3 -0
- package/dist/cli/commands/create.d.ts +3 -0
- package/dist/cli/commands/local-server.d.ts +3 -0
- package/dist/cli/commands/login.d.ts +3 -0
- package/dist/cli/commands/publish.d.ts +3 -0
- package/dist/cli/commands/run.d.ts +3 -0
- package/dist/cli/commands/serve-tests.d.ts +3 -0
- package/dist/cli/commands/serve.d.ts +3 -0
- package/dist/cli/index.d.ts +1 -0
- package/dist/cli/lib/config.d.ts +25 -0
- package/dist/cli/lib/declarations.d.ts +19 -0
- package/dist/cli/lib/engine-script.d.ts +10 -0
- package/dist/cli/lib/execution-manager.d.ts +52 -0
- package/dist/cli/lib/zip.d.ts +6 -0
- package/dist/cli.js +11566 -0
- package/dist/core/client.d.ts +682 -0
- package/dist/core/client.test.d.ts +1 -0
- package/dist/core/platform-client.d.ts +106 -0
- package/dist/core/platform-client.test.d.ts +1 -0
- package/dist/core/request-error.d.ts +25 -0
- package/dist/core/request-error.test.d.ts +1 -0
- package/dist/index.cjs.js +2 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.es.js +3310 -0
- package/dist/types/base.d.ts +9 -0
- package/dist/types/context.d.ts +20 -0
- package/dist/types/execution.d.ts +19 -0
- package/dist/types/files.d.ts +19 -0
- package/dist/types/item.dto.d.ts +24 -0
- package/dist/types/items.d.ts +57 -0
- package/dist/types/projects.d.ts +59 -0
- package/dist/types/response.d.ts +10 -0
- package/dist/types/storage.d.ts +11 -0
- package/dist/vite-env.d.ts +1 -0
- package/package.json +100 -0
- package/src/built-in/index.ts +755 -0
- package/src/cli/templates/bim/CONTEXT.md +244 -0
- package/src/cli/templates/bim/package.json +26 -0
- package/src/cli/templates/bim/src/app.ts +16 -0
- package/src/cli/templates/bim/src/bim-components/CloudRunner/index.ts +91 -0
- package/src/cli/templates/bim/src/bim-components/CloudRunner/src/index.ts +1 -0
- package/src/cli/templates/bim/src/bim-components/CloudRunner/src/types.ts +5 -0
- package/src/cli/templates/bim/src/bim-components/index.ts +1 -0
- package/src/cli/templates/bim/src/globals.ts +1 -0
- package/src/cli/templates/bim/src/main.ts +90 -0
- package/src/cli/templates/bim/src/setups/cloud-runner.ts +13 -0
- package/src/cli/templates/bim/src/setups/index.ts +3 -0
- package/src/cli/templates/bim/src/setups/ui-manager.ts +27 -0
- package/src/cli/templates/bim/src/setups/viewports-manager.ts +22 -0
- package/src/cli/templates/bim/src/ui-components/app-info-section/index.ts +26 -0
- package/src/cli/templates/bim/src/ui-components/app-info-section/src/index.ts +1 -0
- package/src/cli/templates/bim/src/ui-components/app-info-section/src/types.ts +15 -0
- package/src/cli/templates/bim/src/ui-components/cloud-runner-section/index.ts +37 -0
- package/src/cli/templates/bim/src/ui-components/cloud-runner-section/src/index.ts +1 -0
- package/src/cli/templates/bim/src/ui-components/cloud-runner-section/src/types.ts +14 -0
- package/src/cli/templates/bim/src/ui-components/index.ts +2 -0
- package/src/cli/templates/cloud/CONTEXT.md +205 -0
- package/src/cli/templates/cloud/_thatopen +5 -0
- package/src/cli/templates/cloud/declarations.json +4 -0
- package/src/cli/templates/cloud/package.json +22 -0
- package/src/cli/templates/cloud/src/main.ts +70 -0
- package/src/cli/templates/cloud-test/CONTEXT.md +56 -0
- package/src/cli/templates/cloud-test/_thatopen +5 -0
- package/src/cli/templates/cloud-test/package.json +22 -0
- package/src/cli/templates/cloud-test/src/main.ts +565 -0
- package/src/cli/templates/default/CONTEXT.md +92 -0
- package/src/cli/templates/default/package.json +15 -0
- package/src/cli/templates/default/src/main.ts +62 -0
- package/src/cli/templates/shared/_gitignore +4 -0
- package/src/cli/templates/shared/app/index.html +27 -0
- package/src/cli/templates/shared/app/tsconfig.json +16 -0
- package/src/cli/templates/shared/app/vite.config.js +23 -0
- package/src/cli/templates/shared/cloud/tsconfig.json +16 -0
- package/src/cli/templates/shared/cloud/vite.config.js +27 -0
- package/src/cli/templates/test/CONTEXT.md +53 -0
- package/src/cli/templates/test/package.json +25 -0
- package/src/cli/templates/test/src/main.ts +955 -0
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { EngineServicesClient, EngineServicesClientProps } from './client';
|
|
2
|
+
import { Project, ProjectData } from '../types/projects';
|
|
3
|
+
|
|
4
|
+
/** Scope by which a permission was granted (or `'none'` if denied). */
|
|
5
|
+
export type PermissionScope = 'global' | 'project' | 'entity' | 'none';
|
|
6
|
+
/** Result of a single permission check. */
|
|
7
|
+
export interface PermissionCheckResult {
|
|
8
|
+
hasPermission: boolean;
|
|
9
|
+
scope: PermissionScope;
|
|
10
|
+
}
|
|
11
|
+
/** One entry in a batch permission check. */
|
|
12
|
+
export interface PermissionCheckEntry {
|
|
13
|
+
resourceType: string;
|
|
14
|
+
action: string;
|
|
15
|
+
resourceId?: string;
|
|
16
|
+
projectId?: string;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Accepts either a static JWT string or a provider function that returns the
|
|
20
|
+
* current JWT. Use a provider to keep refresh in the caller's hands — the
|
|
21
|
+
* client calls it on every request so expired tokens never stick.
|
|
22
|
+
*
|
|
23
|
+
* @example Static token (simplest):
|
|
24
|
+
* ```ts
|
|
25
|
+
* new PlatformClient(jwt, apiUrl)
|
|
26
|
+
* ```
|
|
27
|
+
*
|
|
28
|
+
* @example Auth0 React:
|
|
29
|
+
* ```ts
|
|
30
|
+
* const { getAccessTokenSilently } = useAuth0();
|
|
31
|
+
* new PlatformClient(() => getAccessTokenSilently(), apiUrl)
|
|
32
|
+
* ```
|
|
33
|
+
*/
|
|
34
|
+
export type BearerTokenSource = string | (() => string | Promise<string>);
|
|
35
|
+
/**
|
|
36
|
+
* Client for apps, frontends, and any caller authenticating with a user JWT.
|
|
37
|
+
* Extends `EngineServicesClient` — the full API-token-compatible surface is
|
|
38
|
+
* inherited. On top, it exposes the JWT-only routes `getProject`,
|
|
39
|
+
* `getProjectData`, `checkPermission`, and `checkPermissionBatch`. Those hit
|
|
40
|
+
* `ProjectController` which is guarded by `AccountActiveGuard +
|
|
41
|
+
* ProjectAccessGuard` and is not reachable via an access token.
|
|
42
|
+
*
|
|
43
|
+
* **Token refresh.** The constructor accepts a function that returns a JWT
|
|
44
|
+
* (sync or async); the client calls it before every request, so an Auth0
|
|
45
|
+
* SDK's `getAccessTokenSilently()` or similar refreshing source Just Works.
|
|
46
|
+
*
|
|
47
|
+
* Use `EngineServicesClient` for components (API-token auth, local server,
|
|
48
|
+
* WebSocket progress). Use `PlatformClient` when you have a user JWT and
|
|
49
|
+
* need project-level reads or permission introspection.
|
|
50
|
+
*
|
|
51
|
+
* @example
|
|
52
|
+
* ```ts
|
|
53
|
+
* const client = new PlatformClient(
|
|
54
|
+
* () => auth0.getAccessTokenSilently(),
|
|
55
|
+
* 'https://api.thatopen.com',
|
|
56
|
+
* );
|
|
57
|
+
* const project = await client.getProject(projectId);
|
|
58
|
+
* ```
|
|
59
|
+
*/
|
|
60
|
+
export declare class PlatformClient extends EngineServicesClient {
|
|
61
|
+
#private;
|
|
62
|
+
/**
|
|
63
|
+
* @param token - A bearer JWT, OR a function returning the current JWT
|
|
64
|
+
* (sync or async). When a function is passed, it's invoked before every
|
|
65
|
+
* request — ideal for token-refreshing sources like Auth0.
|
|
66
|
+
* @param apiUrl - Base URL of the API (e.g. `https://api.thatopen.com`).
|
|
67
|
+
* @param props - Optional client configuration. `useBearer` is forced to
|
|
68
|
+
* `true` and cannot be overridden.
|
|
69
|
+
*/
|
|
70
|
+
constructor(token: BearerTokenSource, apiUrl: string, props?: Omit<EngineServicesClientProps, 'useBearer'>);
|
|
71
|
+
protected resolveAccessToken(): Promise<string>;
|
|
72
|
+
/**
|
|
73
|
+
* Creates a client from the platform context injected into
|
|
74
|
+
* `window.__THATOPEN_CONTEXT__` by the That Open Platform. Recommended
|
|
75
|
+
* entry point for apps running inside the platform's iframe — the context
|
|
76
|
+
* carries a fresh JWT on every navigation.
|
|
77
|
+
*/
|
|
78
|
+
static fromPlatformContext(props?: Omit<EngineServicesClientProps, 'useBearer'>): PlatformClient;
|
|
79
|
+
/**
|
|
80
|
+
* Gets a project by ID. JWT-only — lives here because
|
|
81
|
+
* `GET /project/:id` is guarded by `AccountActiveGuard + ProjectAccessGuard`.
|
|
82
|
+
*/
|
|
83
|
+
getProject(projectId: string): Promise<Project>;
|
|
84
|
+
/**
|
|
85
|
+
* Gets the full project data (users, roles, files, folders) for a project.
|
|
86
|
+
* User data is stripped of sensitive fields server-side.
|
|
87
|
+
*/
|
|
88
|
+
getProjectData(projectId: string): Promise<ProjectData>;
|
|
89
|
+
/**
|
|
90
|
+
* Checks whether the caller has a specific permission within a project.
|
|
91
|
+
* Returns `{ hasPermission, scope }` where `scope` is `'global'` for
|
|
92
|
+
* admin/owner, `'project'` for a role broad grant, `'entity'` for a
|
|
93
|
+
* per-entity override, `'none'` for denied.
|
|
94
|
+
*/
|
|
95
|
+
checkPermission(params: {
|
|
96
|
+
resourceId?: string;
|
|
97
|
+
resourceType: string;
|
|
98
|
+
action: string;
|
|
99
|
+
projectId?: string;
|
|
100
|
+
}): Promise<PermissionCheckResult>;
|
|
101
|
+
/**
|
|
102
|
+
* Batch variant of {@link checkPermission}. Evaluates multiple checks in a
|
|
103
|
+
* single round-trip; results come back in the same order as `checks`.
|
|
104
|
+
*/
|
|
105
|
+
checkPermissionBatch(checks: PermissionCheckEntry[]): Promise<PermissionCheckResult[]>;
|
|
106
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Error thrown by {@link EngineServicesClient} when the platform API responds
|
|
3
|
+
* with a non-2xx status. Exposes the HTTP `status` and — when the API returns a
|
|
4
|
+
* structured JSON body — its `code` and `details`, so callers can react to
|
|
5
|
+
* specific failures (e.g. `code === 'LIMIT_EXCEEDED'`) instead of string-
|
|
6
|
+
* matching the message.
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
* ```ts
|
|
10
|
+
* try {
|
|
11
|
+
* await client.createComponent(props);
|
|
12
|
+
* } catch (err) {
|
|
13
|
+
* if (err instanceof RequestError && err.code === 'LIMIT_EXCEEDED') {
|
|
14
|
+
* console.error(err.message); // "Components limit reached (10/10)..."
|
|
15
|
+
* }
|
|
16
|
+
* }
|
|
17
|
+
* ```
|
|
18
|
+
*/
|
|
19
|
+
export declare class RequestError extends Error {
|
|
20
|
+
readonly status: number;
|
|
21
|
+
readonly code?: string;
|
|
22
|
+
readonly details?: unknown;
|
|
23
|
+
readonly body: string;
|
|
24
|
+
constructor(status: number, statusText: string, body: string);
|
|
25
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";var Me=Object.defineProperty;var we=n=>{throw TypeError(n)};var Ve=(n,e,t)=>e in n?Me(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var _=(n,e,t)=>Ve(n,typeof e!="symbol"?e+"":e,t),G=(n,e,t)=>e.has(n)||we("Cannot "+t);var K=(n,e,t)=>(G(n,e,"read from private field"),t?t.call(n):e.get(n)),W=(n,e,t)=>e.has(n)?we("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(n):e.set(n,t),_e=(n,e,t,s)=>(G(n,e,"write to private field"),s?s.call(n,t):e.set(n,t),t),c=(n,e,t)=>(G(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 q=Object.create(null);Object.keys(k).forEach(n=>{q[k[n]]=n});const te={type:"error",data:"parser error"},Ae=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",Se=typeof ArrayBuffer=="function",Oe=n=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(n):n&&n.buffer instanceof ArrayBuffer,le=({type:n,data:e},t,s)=>Ae&&e instanceof Blob?t?s(e):be(e,s):Se&&(e instanceof ArrayBuffer||Oe(e))?t?s(e):be(new Blob([e]),s):s(k[n]+(e||"")),be=(n,e)=>{const t=new FileReader;return t.onload=function(){const s=t.result.split(",")[1];e("b"+(s||""))},t.readAsDataURL(n)};function Ee(n){return n instanceof Uint8Array?n:n instanceof ArrayBuffer?new Uint8Array(n):new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}let Y;function He(n,e){if(Ae&&n.data instanceof Blob)return n.data.arrayBuffer().then(Ee).then(e);if(Se&&(n.data instanceof ArrayBuffer||Oe(n.data)))return e(Ee(n.data));le(n,!1,t=>{Y||(Y=new TextEncoder),e(Y.encode(t))})}const Te="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",N=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let n=0;n<Te.length;n++)N[Te.charCodeAt(n)]=n;const je=n=>{let e=n.length*.75,t=n.length,s,r=0,i,o,h,u;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=N[n.charCodeAt(s)],o=N[n.charCodeAt(s+1)],h=N[n.charCodeAt(s+2)],u=N[n.charCodeAt(s+3)],d[r++]=i<<2|o>>4,d[r++]=(o&15)<<4|h>>2,d[r++]=(h&3)<<6|u&63;return y},Je=typeof ArrayBuffer=="function",fe=(n,e)=>{if(typeof n!="string")return{type:"message",data:Ce(n,e)};const t=n.charAt(0);return t==="b"?{type:"message",data:Ge(n.substring(1),e)}:q[t]?n.length>1?{type:q[t],data:n.substring(1)}:{type:q[t]}:te},Ge=(n,e)=>{if(Je){const t=je(n);return Ce(t,e)}else return{base64:!0,data:n}},Ce=(n,e)=>{switch(e){case"blob":return n instanceof Blob?n:new Blob([n]);case"arraybuffer":default:return n instanceof ArrayBuffer?n:n.buffer}},Re="",Ke=(n,e)=>{const t=n.length,s=new Array(t);let r=0;n.forEach((i,o)=>{le(i,!1,h=>{s[o]=h,++r===t&&e(s.join(Re))})})},We=(n,e)=>{const t=n.split(Re),s=[];for(let r=0;r<t.length;r++){const i=fe(t[r],e);if(s.push(i),i.type==="error")break}return s};function Ye(){return new TransformStream({transform(n,e){He(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 z;function P(n){return n.reduce((e,t)=>e+t.length,0)}function L(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 ze(n,e){z||(z=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(P(t)<1)break;const u=L(t,1);i=(u[0]&128)===128,r=u[0]&127,r<126?s=3:r===126?s=1:s=2}else if(s===1){if(P(t)<2)break;const u=L(t,2);r=new DataView(u.buffer,u.byteOffset,u.length).getUint16(0),s=3}else if(s===2){if(P(t)<8)break;const u=L(t,8),y=new DataView(u.buffer,u.byteOffset,u.length),d=y.getUint32(0);if(d>Math.pow(2,21)-1){h.enqueue(te);break}r=d*Math.pow(2,32)+y.getUint32(4),s=3}else{if(P(t)<r)break;const u=L(t,r);h.enqueue(fe(i?u:z.decode(u),e)),s=0}if(r===0||r>n){h.enqueue(te);break}}}})}const $e=4;function g(n){if(n)return Xe(n)}function Xe(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 j=typeof Promise=="function"&&typeof Promise.resolve=="function"?e=>Promise.resolve().then(e):(e,t)=>t(e,0),b=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),Qe="arraybuffer";function Be(n,...e){return e.reduce((t,s)=>(n.hasOwnProperty(s)&&(t[s]=n[s]),t),{})}const Ze=b.setTimeout,et=b.clearTimeout;function J(n,e){e.useNativeTimers?(n.setTimeoutFn=Ze.bind(b),n.clearTimeoutFn=et.bind(b)):(n.setTimeoutFn=b.setTimeout.bind(b),n.clearTimeoutFn=b.clearTimeout.bind(b))}const tt=1.33;function st(n){return typeof n=="string"?nt(n):Math.ceil((n.byteLength||n.size)*tt)}function nt(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 xe(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function rt(n){let e="";for(let t in n)n.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(n[t]));return e}function it(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 ot extends Error{constructor(e,t,s){super(e),this.description=t,this.context=s,this.type="TransportError"}}class pe extends g{constructor(e){super(),this.writable=!1,J(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 ot(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=fe(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=rt(e);return t.length?"?"+t:""}}class at extends pe{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)};We(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,Ke(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]=xe()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}}let Ne=!1;try{Ne=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const ct=Ne;function ht(){}class ut extends at{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 v extends g{constructor(e,t,s){super(),this.createRequest=e,J(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=Be(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=v.requestsCount++,v.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=ht,e)try{this._xhr.abort()}catch{}typeof document<"u"&&delete v.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()}}v.requestsCount=0;v.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",ve);else if(typeof addEventListener=="function"){const n="onpagehide"in b?"pagehide":"unload";addEventListener(n,ve,!1)}}function ve(){for(let n in v.requests)v.requests.hasOwnProperty(n)&&v.requests[n].abort()}const lt=function(){const n=Pe({xdomain:!1});return n&&n.responseType!==null}();class ft extends ut{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=lt&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new v(Pe,this.uri(),e)}}function Pe(n){const e=n.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||ct))return new XMLHttpRequest}catch{}if(!e)try{return new b[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const Le=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class pt extends pe{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,s=Le?{}:Be(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;le(s,this.supportsBinary,i=>{try{this.doWrite(s,i)}catch{}r&&j(()=>{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]=xe()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const X=b.WebSocket||b.MozWebSocket;class dt extends pt{createSocket(e,t,s){return Le?new X(e,t,s):t?new X(e,t):new X(e)}doWrite(e,t){this.ws.send(t)}}class yt extends pe{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=ze(Number.MAX_SAFE_INTEGER,this.socket.binaryType),s=e.readable.pipeThrough(t).getReader(),r=Ye();r.readable.pipeTo(e.writable),this._writer=r.writable.getWriter();const i=()=>{s.read().then(({done:h,value:u})=>{h||(this.onPacket(u),i())}).catch(h=>{})};i();const o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this._writer.write(o).then(()=>this.onOpen())})})}write(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&&j(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}}const mt={websocket:dt,webtransport:yt,polling:ft},gt=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,wt=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function se(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=gt.exec(n||""),i={},o=14;for(;o--;)i[wt[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=_t(i,i.path),i.queryKey=bt(i,i.query),i}function _t(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 bt(n,e){const t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(s,r,i){r&&(t[r]=i)}),t}const ne=typeof addEventListener=="function"&&typeof removeEventListener=="function",U=[];ne&&addEventListener("offline",()=>{U.forEach(n=>n())},!1);class C extends g{constructor(e,t){if(super(),this.binaryType=Qe,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=se(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=se(t.host).host);J(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=it(this.opts.query)),ne&&(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"})},U.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=$e,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&&C.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",C.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+=st(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,j(()=>{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(C.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(),ne&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const s=U.indexOf(this._offlineEventListener);s!==-1&&U.splice(s,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}C.protocol=$e;class Et extends C{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;C.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;C.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 w=new Error("probe error");w.transport=t.name,this.emitReserved("upgradeError",w)}}))};function i(){s||(s=!0,d(),t.close(),t=null)}const o=m=>{const w=new Error("probe error: "+m);w.transport=t.name,i(),this.emitReserved("upgradeError",w)};function h(){o("transport closed")}function u(){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",u),this.off("upgrading",y)};t.once("open",r),t.once("error",o),t.once("close",h),this.once("close",u),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 Tt=class extends Et{constructor(e,t={}){const s=typeof e=="object"?e:t;(!s.transports||s.transports&&typeof s.transports[0]=="string")&&(s.transports=(s.transports||["polling","websocket","webtransport"]).map(r=>mt[r]).filter(r=>!!r)),super(e,s)}};function vt(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=se(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 kt=typeof ArrayBuffer=="function",At=n=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(n):n.buffer instanceof ArrayBuffer,Ie=Object.prototype.toString,St=typeof Blob=="function"||typeof Blob<"u"&&Ie.call(Blob)==="[object BlobConstructor]",Ot=typeof File=="function"||typeof File<"u"&&Ie.call(File)==="[object FileConstructor]";function de(n){return kt&&(n instanceof ArrayBuffer||At(n))||St&&n instanceof Blob||Ot&&n instanceof File}function D(n,e){if(!n||typeof n!="object")return!1;if(Array.isArray(n)){for(let t=0,s=n.length;t<s;t++)if(D(n[t]))return!0;return!1}if(de(n))return!0;if(n.toJSON&&typeof n.toJSON=="function"&&arguments.length===1)return D(n.toJSON(),!0);for(const t in n)if(Object.prototype.hasOwnProperty.call(n,t)&&D(n[t]))return!0;return!1}function Ct(n){const e=[],t=n.data,s=n;return s.data=re(t,e),s.attachments=e.length,{packet:s,buffers:e}}function re(n,e){if(!n)return n;if(de(n)){const t={_placeholder:!0,num:e.length};return e.push(n),t}else if(Array.isArray(n)){const t=new Array(n.length);for(let s=0;s<n.length;s++)t[s]=re(n[s],e);return t}else if(typeof n=="object"&&!(n instanceof Date)){const t={};for(const s in n)Object.prototype.hasOwnProperty.call(n,s)&&(t[s]=re(n[s],e));return t}return n}function Rt(n,e){return n.data=ie(n.data,e),delete n.attachments,n}function ie(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]=ie(n[t],e);else if(typeof n=="object")for(const t in n)Object.prototype.hasOwnProperty.call(n,t)&&(n[t]=ie(n[t],e));return n}const $t=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var f;(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"})(f||(f={}));class Bt{constructor(e){this.replacer=e}encode(e){return(e.type===f.EVENT||e.type===f.ACK)&&D(e)?this.encodeAsBinary({type:e.type===f.EVENT?f.BINARY_EVENT:f.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===f.BINARY_EVENT||e.type===f.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=Ct(e),s=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(s),r}}class ye extends g{constructor(e){super(),this.reviver=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===f.BINARY_EVENT;s||t.type===f.BINARY_ACK?(t.type=s?f.EVENT:f.ACK,this.reconstructor=new xt(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if(de(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(f[s.type]===void 0)throw new Error("unknown packet type "+s.type);if(s.type===f.BINARY_EVENT||s.type===f.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");s.attachments=Number(o)}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(ye.isPayloadValid(s.type,i))s.data=i;else throw new Error("invalid payload")}return s}tryParse(e){try{return JSON.parse(e,this.reviver)}catch{return!1}}static isPayloadValid(e,t){switch(e){case f.CONNECT:return ke(t);case f.DISCONNECT:return t===void 0;case f.CONNECT_ERROR:return typeof t=="string"||ke(t);case f.EVENT:case f.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&$t.indexOf(t[0])===-1);case f.ACK:case f.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class xt{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=Rt(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}function ke(n){return Object.prototype.toString.call(n)==="[object Object]"}const Nt=Object.freeze(Object.defineProperty({__proto__:null,Decoder:ye,Encoder:Bt,get PacketType(){return f}},Symbol.toStringTag,{value:"Module"}));function E(n,e,t){return n.on(e,t),function(){n.off(e,t)}}const Pt=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class qe 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=[E(e,"open",this.onopen.bind(this)),E(e,"packet",this.onpacket.bind(this)),E(e,"error",this.onerror.bind(this)),E(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(Pt.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:f.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,u=this.connected&&!(!((i=this.io.engine)===null||i===void 0)&&i._hasPingExpired());return this.flags.volatile&&!h||(u?(this.notifyOutgoingListeners(o),this.packet(o)):this.sendBuffer.push(o)),this.flags={},this}_registerAckCallback(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:f.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 f.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 f.EVENT:case f.BINARY_EVENT:this.onevent(e);break;case f.ACK:case f.BINARY_ACK:this.onack(e);break;case f.DISCONNECT:this.ondisconnect();break;case f.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:f.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:f.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 B(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}B.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};B.prototype.reset=function(){this.attempts=0};B.prototype.setMin=function(n){this.ms=n};B.prototype.setMax=function(n){this.max=n};B.prototype.setJitter=function(n){this.jitter=n};class oe 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,J(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 B({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||Nt;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 Tt(this.uri,this.opts);const t=this.engine,s=this;this._readyState="opening",this.skipReconnect=!1;const r=E(t,"open",function(){s.onopen(),e&&e()}),i=h=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",h),e?e(h):this.maybeReconnectOnOpen()},o=E(t,"error",i);if(this._timeout!==!1){const h=this._timeout,u=this.setTimeoutFn(()=>{r(),i(new Error("timeout")),t.close()},h);this.opts.autoUnref&&u.unref(),this.subs.push(()=>{this.clearTimeoutFn(u)})}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(E(e,"ping",this.onping.bind(this)),E(e,"data",this.ondata.bind(this)),E(e,"error",this.onerror.bind(this)),E(e,"close",this.onclose.bind(this)),E(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){j(()=>{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 qe(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 x={};function F(n,e){typeof n=="object"&&(e=n,n=void 0),e=e||{};const t=vt(n,e.path||"/socket.io"),s=t.source,r=t.id,i=t.path,o=x[r]&&i in x[r].nsps,h=e.forceNew||e["force new connection"]||e.multiplex===!1||o;let u;return h?u=new oe(s,e):(x[r]||(x[r]=new oe(s,e)),u=x[r]),t.query&&!e.query&&(e.query=t.queryKey),u.socket(t.path,e)}Object.assign(F,{Manager:oe,Socket:qe,io:F,connect:F});function Lt(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 Ue extends Error{constructor(t,s,r){const i=Lt(r);super(i.message??`${s||"Request failed"} (${t})`);_(this,"status");_(this,"code");_(this,"details");_(this,"body");this.name="RequestError",this.status=t,this.code=i.code,this.details=i.details,this.body=r}}const T="item/folder",p="item",S="processor",R="hidden",Q="FILE",Z="TOOL",ee="APP";var a,ae,l,O,M,V,ce,he,De;const me=class me{constructor(e,t,s){W(this,a);_(this,"apiUrl");_(this,"accessToken");_(this,"wsUrl");_(this,"retries");_(this,"useBearer");_(this,"builtInGlobals",null);_(this,"localServerUrl",null);_(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 u=o;u.charAt(u.length-1)==="/"&&(u=u.slice(0,-1)),this.localServerUrl=u}}static fromPlatformContext(e){const t=(typeof window<"u"?window.__THATOPEN_CONTEXT__:null)||{appId:"",projectId:"",accessToken:"",apiUrl:""},s=new me(t.accessToken,t.apiUrl,{...e,useBearer:!0});return s.context=t,s}setRetries(e){this.retries=e}setBuiltInGlobals(e){this.builtInGlobals=e}async resolveAccessToken(){return this.accessToken}async request(e,t,s){return c(this,a,l).call(this,e,t,s)}async listFiles(e){const{folderId:t,archived:s,projectId:r}=e||{};return t?await c(this,a,l).call(this,"GET",`${T}/${t}/items`,{query:{itemType:Q,archived:s}}):await c(this,a,l).call(this,"GET",`${p}`,{query:{itemType:Q,archived:s,...r&&{projectId:r}}})}async getFile(e,t){return await c(this,a,he).call(this,e,t)}async createFile(e){return await c(this,a,V).call(this,e,Q)}async updateFile(e,t){return await c(this,a,ce).call(this,e,t)}async archiveFile(e){return await c(this,a,l).call(this,"DELETE",`${p}/${e}`)}async recoverFile(e){return await c(this,a,l).call(this,"PUT",`${p}/${e}/recover`)}async downloadFile(e,t){return await c(this,a,M).call(this,e,t)}async getFileVersionMetadata(e,t,s){const{withDraft:r}=s||{};return await c(this,a,l).call(this,"GET",`${p}/${encodeURIComponent(e)}/version/${encodeURIComponent(t)}/metadata`,{query:{...r&&{withDraft:"true"}}})}async updateFileVersionMetadata(e,t,s){return await c(this,a,l).call(this,"PUT",`${p}/${encodeURIComponent(e)}/version/${encodeURIComponent(t)}/metadata`,{body:JSON.stringify({metadata:s}),contentType:"application/json"})}async deleteFileVersionMetadata(e,t){return await c(this,a,l).call(this,"DELETE",`${p}/${encodeURIComponent(e)}/version/${encodeURIComponent(t)}/metadata`)}async listFolders(e){const{archived:t,parentFolderId:s,projectId:r}=e||{};return await c(this,a,l).call(this,"GET",T,{query:{parentFolderId:s,archived:t,...r&&{projectId:r}}})}async getFolder(e){return await c(this,a,l).call(this,"GET",`${T}/${e}`)}async createFolder(e,t,s){return await c(this,a,l).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,a,l).call(this,"PUT",`${T}/${e}`,{body:JSON.stringify({name:s}),contentType:"application/json"})}async archiveFolder(e){return await c(this,a,l).call(this,"DELETE",`${T}/${e}`)}async recoverFolder(e){return await c(this,a,l).call(this,"PUT",`${T}/${e}/recover`)}async downloadFolder(e){return await c(this,a,O).call(this,`${T}/${e}/download`)}async listComponents(e){const{folderId:t,ShowVersions:s,projectId:r}=e||{};return t?await c(this,a,l).call(this,"GET",`${T}/${t}/items`,{query:{itemType:Z,...s&&{ShowVersions:s}}}):await c(this,a,l).call(this,"GET",`${p}`,{query:{itemType:Z,...s&&{ShowVersions:s},...r&&{projectId:r}}})}async getComponent(e,t){return await c(this,a,he).call(this,e,t)}async createComponent(e){const{componentProps:t}=e;return await c(this,a,V).call(this,e,Z,t)}async updateComponent(e,t){const{componentProps:s}=t;return await c(this,a,ce).call(this,e,t,s)}async downloadComponent(e,t){return await c(this,a,M).call(this,e,t)}async downloadComponentBundle(e,t){const{versionTag:s,withDraft:r}=t||{};return await c(this,a,O).call(this,`${p}/${e}/download/bundle`,{query:{...s&&{versionTag:s},...r&&{withDraft:r}}})}async archiveComponent(e){return await c(this,a,l).call(this,"DELETE",`${p}/${e}`)}async recoverComponent(e){return await c(this,a,l).call(this,"PUT",`${p}/${e}/recover`)}async getBuiltInComponent(e){return await(await c(this,a,O).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,l).call(this,"GET",`${T}/${t}/items`,{query:{itemType:ee,...s&&{ShowVersions:s}}}):await c(this,a,l).call(this,"GET",`${p}`,{query:{itemType:ee,...s&&{ShowVersions:s},...r&&{projectId:r}}})}async createApp(e){const{appProps:t}=e;return await c(this,a,V).call(this,e,ee,t)}async downloadApp(e,t){return await c(this,a,M).call(this,e,t)}async downloadAppBundle(e,t){const{versionTag:s,withDraft:r}=t||{};return await c(this,a,O).call(this,`${p}/${e}/download/bundle`,{query:{...s&&{versionTag:s},...r&&{withDraft:r}}})}async archiveApp(e){return await c(this,a,l).call(this,"DELETE",`${p}/${e}`)}async executeComponent(e,t,s){if(this.localServerUrl){const r=`${this.localServerUrl}/api/${S}/${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,l).call(this,"POST",`${S}/${e}/execute`,{body:JSON.stringify(t),query:{...s&&{versionTag:s}},contentType:"application/json"})}async abortExecution(e){if(this.localServerUrl){const t=`${this.localServerUrl}/api/${S}/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,l).call(this,"POST",`${S}/progress/${e}/abort`)}async listExecutions(e,t){if(this.localServerUrl){const s=t?`?projectId=${encodeURIComponent(t)}`:"",r=`${this.localServerUrl}/api/${S}/${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,l).call(this,"GET",`${S}/${e}/progress`,{query:{...t&&{projectId:t}}})}async getExecution(e){if(this.localServerUrl){const t=`${this.localServerUrl}/api/${S}/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,l).call(this,"GET",`${S}/progress/${e}`)}async onExecutionProgress(e,t){const s=this.localServerUrl?`${this.localServerUrl}?accessToken=${this.accessToken}`:this.wsUrl,r=await F(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,l).call(this,"POST",`${p}/${R}`,{body:s})}async deleteHiddenFile(e){return await c(this,a,l).call(this,"DELETE",`${p}/${R}/${e}`)}async getHiddenFile(e){return await c(this,a,l).call(this,"GET",`${p}/${R}/${e}`)}async downloadHiddenFile(e){return await c(this,a,O).call(this,`${p}/${R}/${e}/download`)}async getHiddenFilesByParent(e){return await c(this,a,l).call(this,"GET",`${p}/${e}/${R}`)}async deleteHiddenFilesByParent(e){return await c(this,a,l).call(this,"DELETE",`${p}/${e}/${R}`)}async uploadItemIcon(e,t){const s=new FormData;return s.append("icon",t),await c(this,a,l).call(this,"PUT",`${p}/${e}/icon`,{body:s})}async getItemIcon(e){return await c(this,a,O).call(this,`${p}/${e}/icon`)}async removeItemIcon(e){return await c(this,a,l).call(this,"DELETE",`${p}/${e}/icon`)}async updateItem(e,t){return await c(this,a,l).call(this,"PUT",`${p}/${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,l).call(this,"POST",`${p}/${e}/version`,{body:o})}async listVersions(e,t={}){return await c(this,a,l).call(this,"GET",`${p}/${encodeURIComponent(e)}/versions`,{query:t})}async archiveVersion(e,t){return await c(this,a,l).call(this,"PUT",`${p}/${encodeURIComponent(e)}/version/${encodeURIComponent(t)}/archive`)}async recoverVersion(e,t){return await c(this,a,l).call(this,"PUT",`${p}/${encodeURIComponent(e)}/version/${encodeURIComponent(t)}/recover`)}async deleteVersion(e,t){return await c(this,a,l).call(this,"DELETE",`${p}/${encodeURIComponent(e)}/version/${encodeURIComponent(t)}`)}};a=new WeakSet,ae=function(e){return`${this.apiUrl}/${e}`},l=async function(e,t,s){const{body:r,query:i,contentType:o,retries:h}=s||{},u=c(this,a,ae).call(this,t),y=c(this,a,De).call(this,i),d=await this.resolveAccessToken(),m={...y,...this.useBearer?{}:{accessToken:d}};try{const w=await fetch(u+"?"+new URLSearchParams(m).toString(),{method:e,headers:{Accept:"application/json",...o&&{"Content-Type":o},...this.useBearer&&{Authorization:`Bearer ${d}`}},...r&&{body:r}});if(!w.ok){const A=await w.text().then(Fe=>Fe).catch(()=>"");throw new Ue(w.status,w.statusText,A)}return w.json().then(A=>A).catch(()=>{})}catch(w){let A=h??this.retries;if(A)return A=A-1,await c(this,a,l).call(this,e,t,{...s,retries:A});throw w}},O=async function(e,t){const{query:s}=t||{},r=c(this,a,ae).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}`}}})},M=async function(e,t){const{versionTag:s,withDraft:r}=t||{};return await c(this,a,O).call(this,`${p}/${e}/download`,{query:{...s&&{versionTag:s},...r&&{withDraft:r}}})},V=async function(e,t,s){const{name:r,versionTag:i,parentFolderId:o,projectId:h,file:u,metadata:y}=e,d=new FormData;return d.append("file",u),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,l).call(this,"POST",p,{body:d})},ce=async function(e,t,s){const{name:r,versionTag:i,parentFolderId:o,file:h,metadata:u}=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)),u&&m.append("metadata",JSON.stringify(u)),d=await c(this,a,l).call(this,"POST",`${p}/${e}/version`,{body:m})}if(r||o){const m={...r&&{name:r},...o&&{folderId:o}},w=JSON.stringify(m);y=await c(this,a,l).call(this,"PUT",`${p}/${e}`,{body:w,contentType:"application/json"})}return{item:y,version:d}},he=async function(e,t){const{showVersions:s=!1}=t||{};return await c(this,a,l).call(this,"GET",`${p}/${e}`,{query:{showVersions:s}})},De=function(e){return e&&Object.entries(e).filter(([,t])=>t!==void 0).reduce((t,[s,r])=>(t[s]=r,t),{})};let H=me;const I="project";var $;const ge=class ge extends H{constructor(t,s,r){super(typeof t=="string"?t:"",s,{...r,useBearer:!0});W(this,$);typeof t=="function"&&_e(this,$,t)}async resolveAccessToken(){return K(this,$)?await K(this,$).call(this):super.resolveAccessToken()}static fromPlatformContext(t){const s=(typeof window<"u"?window.__THATOPEN_CONTEXT__:null)||{appId:"",projectId:"",accessToken:"",apiUrl:""},r=new ge(s.accessToken,s.apiUrl,t);return r.context=s,r}async getProject(t){return await this.request("GET",`${I}/${t}`)}async getProjectData(t){return await this.request("GET",`${I}/${t}/data`)}async checkPermission(t){return await this.request("GET",`${I}/permissions/check`,{query:t})}async checkPermissionBatch(t){return(await this.request("POST",`${I}/permissions/check/batch`,{body:JSON.stringify({checks:t}),contentType:"application/json"})).results}};$=new WeakMap;let ue=ge;const It={MAX_FIELDS:200,MAX_KEY_LENGTH:50,MAX_VALUE_LENGTH:50},qt={uuid:"2e32d873-02c9-421c-8743-d8a5ca6ad38a"},Ut={uuid:"b0b5e2a2-0b3a-4a6b-8b1c-0b1c4a6b8b1c"},Dt={uuid:"2c4ae432-fc24-43e9-9783-0c960c674e96"},Ft={uuid:"3c2a9f34-8b6c-4d1b-8f7a-1e4a5b2c9f08"},Mt={uuid:"234f1416-528d-452a-9cc9-a16c5239b2eb"},Vt={uuid:"def81d43-6b44-4f4a-9c08-7649486112a4"};exports.AppManager=qt;exports.EngineServicesClient=H;exports.FileList=Ut;exports.HelloWorld=Dt;exports.METADATA_LIMITS=It;exports.PlatformClient=ue;exports.RequestError=Ue;exports.TabbedNavigation=Ft;exports.UIManager=Mt;exports.ViewportsManager=Vt;
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export * from './core/client';
|
|
2
|
+
export * from './core/platform-client';
|
|
3
|
+
export * from './core/request-error';
|
|
4
|
+
export * from './types/items';
|
|
5
|
+
export * from './types/base';
|
|
6
|
+
export * from './types/execution';
|
|
7
|
+
export * from './types/files';
|
|
8
|
+
export * from './types/response';
|
|
9
|
+
export * from './types/item.dto';
|
|
10
|
+
export * from './types/projects';
|
|
11
|
+
export * from './types/context';
|
|
12
|
+
export * from './built-in';
|