@thatopen/services 0.24.0 → 0.25.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.
@@ -25,6 +25,20 @@ export interface DocumentDescriptor {
25
25
  }
26
26
  export declare const DOCUMENT_SCHEMA = "thatopen/document@1";
27
27
  export declare const DOCUMENT_FILE = "document.json";
28
+ /**
29
+ * Formats whose native file IS its own definitive view (the PDF rule): when
30
+ * {@link ProjectDocuments.fromFile} converts one, the same fileId is written
31
+ * as `native` and as `views[0]`. Deliberately NOT here: 'ifc' — its proper 3D
32
+ * view is the processed frag, so a converted IFC without one shows "Process"
33
+ * instead of opening a worse view.
34
+ */
35
+ export declare const SELF_VIEWING_FORMATS: string[];
36
+ /** One listed document: the folder, and what its descriptor says. */
37
+ export interface DocumentInfo {
38
+ /** The document folder's item id — the id interfaces know the document by. */
39
+ folderId: string;
40
+ descriptor: DocumentDescriptor;
41
+ }
28
42
  /**
29
43
  * Documents of one project. Get it from {@link EngineServicesClient.documents}.
30
44
  * Every method takes the document's FOLDER id — the id interfaces know the
@@ -35,6 +49,29 @@ export declare class ProjectDocuments {
35
49
  private readonly client;
36
50
  readonly projectId: string;
37
51
  constructor(client: EngineServicesClient, projectId: string);
52
+ /**
53
+ * Every document of the project: the folders that carry a descriptor.
54
+ * Plain folders and loose files simply do not appear. One folder listing
55
+ * for the project plus one file listing and one descriptor download per
56
+ * folder, fetched in parallel — the storage offers nothing cheaper yet.
57
+ */
58
+ list(): Promise<DocumentInfo[]>;
59
+ /**
60
+ * Converts a loose file into a document: creates the document folder next
61
+ * to the file, moves the file inside (moving preserves its id), and writes
62
+ * the descriptor with the file as `native` — and as `views[0]` too when its
63
+ * format views itself ({@link SELF_VIEWING_FORMATS}; override per call with
64
+ * `selfView`).
65
+ *
66
+ * A file that carries a processed derivative (the old `derivedFileId` link
67
+ * in its version metadata — an IFC's frag, a LAS's potree) brings it along:
68
+ * the derivative moves into the same folder and becomes a view, so the
69
+ * document is born ready to visualize and the link concept retires.
70
+ */
71
+ fromFile(fileId: string, options?: {
72
+ name?: string;
73
+ selfView?: boolean;
74
+ }): Promise<DocumentInfo>;
38
75
  /**
39
76
  * The document's descriptor, read and validated, or null when the folder
40
77
  * has none yet (an old folder, or a plain folder that is not a document).
package/dist/index.cjs.js CHANGED
@@ -1,3 +1,3 @@
1
- "use strict";var sr=Object.create;var Gt=Object.defineProperty;var rr=Object.getOwnPropertyDescriptor;var nr=Object.getOwnPropertyNames;var ir=Object.getPrototypeOf,or=Object.prototype.hasOwnProperty;var qe=r=>{throw TypeError(r)};var ar=(r,t,e)=>t in r?Gt(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e;var cr=(r,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of nr(t))!or.call(r,n)&&n!==e&&Gt(r,n,{get:()=>t[n],enumerable:!(s=rr(t,n))||s.enumerable});return r};var De=(r,t,e)=>(e=r!=null?sr(ir(r)):{},cr(t||!r||!r.__esModule?Gt(e,"default",{value:r,enumerable:!0}):e,r));var I=(r,t,e)=>ar(r,typeof t!="symbol"?t+"":t,e),Jt=(r,t,e)=>t.has(r)||qe("Cannot "+e);var u=(r,t,e)=>(Jt(r,t,"read from private field"),e?e.call(r):t.get(r)),b=(r,t,e)=>t.has(r)?qe("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(r):t.set(r,e),_=(r,t,e,s)=>(Jt(r,t,"write to private field"),s?s.call(r,e):t.set(r,e),e),a=(r,t,e)=>(Jt(r,t,"access private method"),e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const F=Object.create(null);F.open="0";F.close="1";F.ping="2";F.pong="3";F.message="4";F.upgrade="5";F.noop="6";const kt=Object.create(null);Object.keys(F).forEach(r=>{kt[F[r]]=r});const Zt={type:"error",data:"parser error"},Ze=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",ts=typeof ArrayBuffer=="function",es=r=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(r):r&&r.buffer instanceof ArrayBuffer,Se=({type:r,data:t},e,s)=>Ze&&t instanceof Blob?e?s(t):Me(t,s):ts&&(t instanceof ArrayBuffer||es(t))?e?s(t):Me(new Blob([t]),s):s(F[r]+(t||"")),Me=(r,t)=>{const e=new FileReader;return e.onload=function(){const s=e.result.split(",")[1];t("b"+(s||""))},e.readAsDataURL(r)};function Ue(r){return r instanceof Uint8Array?r:r instanceof ArrayBuffer?new Uint8Array(r):new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}let Yt;function hr(r,t){if(Ze&&r.data instanceof Blob)return r.data.arrayBuffer().then(Ue).then(t);if(ts&&(r.data instanceof ArrayBuffer||es(r.data)))return t(Ue(r.data));Se(r,!1,e=>{Yt||(Yt=new TextEncoder),t(Yt.encode(e))})}const je="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",pt=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let r=0;r<je.length;r++)pt[je.charCodeAt(r)]=r;const lr=r=>{let t=r.length*.75,e=r.length,s,n=0,i,o,c,d;r[r.length-1]==="="&&(t--,r[r.length-2]==="="&&t--);const f=new ArrayBuffer(t),h=new Uint8Array(f);for(s=0;s<e;s+=4)i=pt[r.charCodeAt(s)],o=pt[r.charCodeAt(s+1)],c=pt[r.charCodeAt(s+2)],d=pt[r.charCodeAt(s+3)],h[n++]=i<<2|o>>4,h[n++]=(o&15)<<4|c>>2,h[n++]=(c&3)<<6|d&63;return f},ur=typeof ArrayBuffer=="function",Ie=(r,t)=>{if(typeof r!="string")return{type:"message",data:ss(r,t)};const e=r.charAt(0);return e==="b"?{type:"message",data:dr(r.substring(1),t)}:kt[e]?r.length>1?{type:kt[e],data:r.substring(1)}:{type:kt[e]}:Zt},dr=(r,t)=>{if(ur){const e=lr(r);return ss(e,t)}else return{base64:!0,data:r}},ss=(r,t)=>{switch(t){case"blob":return r instanceof Blob?r:new Blob([r]);case"arraybuffer":default:return r instanceof ArrayBuffer?r:r.buffer}},rs="",fr=(r,t)=>{const e=r.length,s=new Array(e);let n=0;r.forEach((i,o)=>{Se(i,!1,c=>{s[o]=c,++n===e&&t(s.join(rs))})})},pr=(r,t)=>{const e=r.split(rs),s=[];for(let n=0;n<e.length;n++){const i=Ie(e[n],t);if(s.push(i),i.type==="error")break}return s};function yr(){return new TransformStream({transform(r,t){hr(r,e=>{const s=e.length;let n;if(s<126)n=new Uint8Array(1),new DataView(n.buffer).setUint8(0,s);else if(s<65536){n=new Uint8Array(3);const i=new DataView(n.buffer);i.setUint8(0,126),i.setUint16(1,s)}else{n=new Uint8Array(9);const i=new DataView(n.buffer);i.setUint8(0,127),i.setBigUint64(1,BigInt(s))}r.data&&typeof r.data!="string"&&(n[0]|=128),t.enqueue(n),t.enqueue(e)})}})}let Wt;function It(r){return r.reduce((t,e)=>t+e.length,0)}function Ot(r,t){if(r[0].length===t)return r.shift();const e=new Uint8Array(t);let s=0;for(let n=0;n<t;n++)e[n]=r[0][s++],s===r[0].length&&(r.shift(),s=0);return r.length&&s<r[0].length&&(r[0]=r[0].slice(s)),e}function mr(r,t){Wt||(Wt=new TextDecoder);const e=[];let s=0,n=-1,i=!1;return new TransformStream({transform(o,c){for(e.push(o);;){if(s===0){if(It(e)<1)break;const d=Ot(e,1);i=(d[0]&128)===128,n=d[0]&127,n<126?s=3:n===126?s=1:s=2}else if(s===1){if(It(e)<2)break;const d=Ot(e,2);n=new DataView(d.buffer,d.byteOffset,d.length).getUint16(0),s=3}else if(s===2){if(It(e)<8)break;const d=Ot(e,8),f=new DataView(d.buffer,d.byteOffset,d.length),h=f.getUint32(0);if(h>Math.pow(2,21)-1){c.enqueue(Zt);break}n=h*Math.pow(2,32)+f.getUint32(4),s=3}else{if(It(e)<n)break;const d=Ot(e,n);c.enqueue(Ie(i?d:Wt.decode(d),t)),s=0}if(n===0||n>r){c.enqueue(Zt);break}}}})}const ns=4;function E(r){if(r)return gr(r)}function gr(r){for(var t in E.prototype)r[t]=E.prototype[t];return r}E.prototype.on=E.prototype.addEventListener=function(r,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+r]=this._callbacks["$"+r]||[]).push(t),this};E.prototype.once=function(r,t){function e(){this.off(r,e),t.apply(this,arguments)}return e.fn=t,this.on(r,e),this};E.prototype.off=E.prototype.removeListener=E.prototype.removeAllListeners=E.prototype.removeEventListener=function(r,t){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var e=this._callbacks["$"+r];if(!e)return this;if(arguments.length==1)return delete this._callbacks["$"+r],this;for(var s,n=0;n<e.length;n++)if(s=e[n],s===t||s.fn===t){e.splice(n,1);break}return e.length===0&&delete this._callbacks["$"+r],this};E.prototype.emit=function(r){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),e=this._callbacks["$"+r],s=1;s<arguments.length;s++)t[s-1]=arguments[s];if(e){e=e.slice(0);for(var s=0,n=e.length;s<n;++s)e[s].apply(this,t)}return this};E.prototype.emitReserved=E.prototype.emit;E.prototype.listeners=function(r){return this._callbacks=this._callbacks||{},this._callbacks["$"+r]||[]};E.prototype.hasListeners=function(r){return!!this.listeners(r).length};const Mt=typeof Promise=="function"&&typeof Promise.resolve=="function"?t=>Promise.resolve().then(t):(t,e)=>e(t,0),R=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),wr="arraybuffer";function is(r,...t){return t.reduce((e,s)=>(r.hasOwnProperty(s)&&(e[s]=r[s]),e),{})}const br=R.setTimeout,_r=R.clearTimeout;function Ut(r,t){t.useNativeTimers?(r.setTimeoutFn=br.bind(R),r.clearTimeoutFn=_r.bind(R)):(r.setTimeoutFn=R.setTimeout.bind(R),r.clearTimeoutFn=R.clearTimeout.bind(R))}const Er=1.33;function Tr(r){return typeof r=="string"?vr(r):Math.ceil((r.byteLength||r.size)*Er)}function vr(r){let t=0,e=0;for(let s=0,n=r.length;s<n;s++)t=r.charCodeAt(s),t<128?e+=1:t<2048?e+=2:t<55296||t>=57344?e+=3:(s++,e+=4);return e}function os(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function Sr(r){let t="";for(let e in r)r.hasOwnProperty(e)&&(t.length&&(t+="&"),t+=encodeURIComponent(e)+"="+encodeURIComponent(r[e]));return t}function Ir(r){let t={},e=r.split("&");for(let s=0,n=e.length;s<n;s++){let i=e[s].split("=");t[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return t}class Or extends Error{constructor(t,e,s){super(t),this.description=e,this.context=s,this.type="TransportError"}}class Oe extends E{constructor(t){super(),this.writable=!1,Ut(this,t),this.opts=t,this.query=t.query,this.socket=t.socket,this.supportsBinary=!t.forceBase64}onError(t,e,s){return super.emitReserved("error",new Or(t,e,s)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(t){this.readyState==="open"&&this.write(t)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(t){const e=Ie(t,this.socket.binaryType);this.onPacket(e)}onPacket(t){super.emitReserved("packet",t)}onClose(t){this.readyState="closed",super.emitReserved("close",t)}pause(t){}createUri(t,e={}){return t+"://"+this._hostname()+this._port()+this.opts.path+this._query(e)}_hostname(){const t=this.opts.hostname;return t.indexOf(":")===-1?t:"["+t+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(t){const e=Sr(t);return e.length?"?"+e:""}}class Ar extends Oe{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(t){this.readyState="pausing";const e=()=>{this.readyState="paused",t()};if(this._polling||!this.writable){let s=0;this._polling&&(s++,this.once("pollComplete",function(){--s||e()})),this.writable||(s++,this.once("drain",function(){--s||e()}))}else e()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){const e=s=>{if(this.readyState==="opening"&&s.type==="open"&&this.onOpen(),s.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(s)};pr(t,this.socket.binaryType).forEach(e),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){const t=()=>{this.write([{type:"close"}])};this.readyState==="open"?t():this.once("open",t)}write(t){this.writable=!1,fr(t,e=>{this.doWrite(e,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const t=this.opts.secure?"https":"http",e=this.query||{};return this.opts.timestampRequests!==!1&&(e[this.opts.timestampParam]=os()),!this.supportsBinary&&!e.sid&&(e.b64=1),this.createUri(t,e)}}let as=!1;try{as=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const kr=as;function Cr(){}class xr extends Ar{constructor(t){if(super(t),typeof location<"u"){const e=location.protocol==="https:";let s=location.port;s||(s=e?"443":"80"),this.xd=typeof location<"u"&&t.hostname!==location.hostname||s!==t.port}}doWrite(t,e){const s=this.request({method:"POST",data:t});s.on("success",e),s.on("error",(n,i)=>{this.onError("xhr post error",n,i)})}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(e,s)=>{this.onError("xhr poll error",e,s)}),this.pollXhr=t}}class L extends E{constructor(t,e,s){super(),this.createRequest=t,Ut(this,s),this._opts=s,this._method=s.method||"GET",this._uri=e,this._data=s.data!==void 0?s.data:null,this._create()}_create(){var t;const e=is(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");e.xdomain=!!this._opts.xd;const s=this._xhr=this.createRequest(e);try{s.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){s.setDisableHeaderCheck&&s.setDisableHeaderCheck(!0);for(let n in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(n)&&s.setRequestHeader(n,this._opts.extraHeaders[n])}}catch{}if(this._method==="POST")try{s.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{s.setRequestHeader("Accept","*/*")}catch{}(t=this._opts.cookieJar)===null||t===void 0||t.addCookies(s),"withCredentials"in s&&(s.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(s.timeout=this._opts.requestTimeout),s.onreadystatechange=()=>{var n;s.readyState===3&&((n=this._opts.cookieJar)===null||n===void 0||n.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(n){this.setTimeoutFn(()=>{this._onError(n)},0);return}typeof document<"u"&&(this._index=L.requestsCount++,L.requests[this._index]=this)}_onError(t){this.emitReserved("error",t,this._xhr),this._cleanup(!0)}_cleanup(t){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=Cr,t)try{this._xhr.abort()}catch{}typeof document<"u"&&delete L.requests[this._index],this._xhr=null}}_onLoad(){const t=this._xhr.responseText;t!==null&&(this.emitReserved("data",t),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}L.requestsCount=0;L.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",Ve);else if(typeof addEventListener=="function"){const r="onpagehide"in R?"pagehide":"unload";addEventListener(r,Ve,!1)}}function Ve(){for(let r in L.requests)L.requests.hasOwnProperty(r)&&L.requests[r].abort()}const Rr=function(){const r=cs({xdomain:!1});return r&&r.responseType!==null}();class $r extends xr{constructor(t){super(t);const e=t&&t.forceBase64;this.supportsBinary=Rr&&!e}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new L(cs,this.uri(),t)}}function cs(r){const t=r.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!t||kr))return new XMLHttpRequest}catch{}if(!t)try{return new R[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const hs=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class Nr extends Oe{get name(){return"websocket"}doOpen(){const t=this.uri(),e=this.opts.protocols,s=hs?{}:is(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(s.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(t,e,s)}catch(n){return this.emitReserved("error",n)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const s=t[e],n=e===t.length-1;Se(s,this.supportsBinary,i=>{try{this.doWrite(s,i)}catch{}n&&Mt(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const t=this.opts.secure?"wss":"ws",e=this.query||{};return this.opts.timestampRequests&&(e[this.opts.timestampParam]=os()),this.supportsBinary||(e.b64=1),this.createUri(t,e)}}const Kt=R.WebSocket||R.MozWebSocket;class Pr extends Nr{createSocket(t,e,s){return hs?new Kt(t,e,s):e?new Kt(t,e):new Kt(t)}doWrite(t,e){this.ws.send(e)}}class Br extends Oe{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(t){return this.emitReserved("error",t)}this._transport.closed.then(()=>{this.onClose()}).catch(t=>{this.onError("webtransport error",t)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(t=>{const e=mr(Number.MAX_SAFE_INTEGER,this.socket.binaryType),s=t.readable.pipeThrough(e).getReader(),n=yr();n.readable.pipeTo(t.writable),this._writer=n.writable.getWriter();const i=()=>{s.read().then(({done:c,value:d})=>{c||(this.onPacket(d),i())}).catch(c=>{})};i();const o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this._writer.write(o).then(()=>this.onOpen())})})}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const s=t[e],n=e===t.length-1;this._writer.write(s).then(()=>{n&&Mt(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this._transport)===null||t===void 0||t.close()}}const Lr={websocket:Pr,webtransport:Br,polling:$r},Fr=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,qr=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function te(r){if(r.length>8e3)throw"URI too long";const t=r,e=r.indexOf("["),s=r.indexOf("]");e!=-1&&s!=-1&&(r=r.substring(0,e)+r.substring(e,s).replace(/:/g,";")+r.substring(s,r.length));let n=Fr.exec(r||""),i={},o=14;for(;o--;)i[qr[o]]=n[o]||"";return e!=-1&&s!=-1&&(i.source=t,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=Dr(i,i.path),i.queryKey=Mr(i,i.query),i}function Dr(r,t){const e=/\/{2,9}/g,s=t.replace(e,"/").split("/");return(t.slice(0,1)=="/"||t.length===0)&&s.splice(0,1),t.slice(-1)=="/"&&s.splice(s.length-1,1),s}function Mr(r,t){const e={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(s,n,i){n&&(e[n]=i)}),e}const ee=typeof addEventListener=="function"&&typeof removeEventListener=="function",Ct=[];ee&&addEventListener("offline",()=>{Ct.forEach(r=>r())},!1);class X extends E{constructor(t,e){if(super(),this.binaryType=wr,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,t&&typeof t=="object"&&(e=t,t=null),t){const s=te(t);e.hostname=s.host,e.secure=s.protocol==="https"||s.protocol==="wss",e.port=s.port,s.query&&(e.query=s.query)}else e.host&&(e.hostname=te(e.host).host);Ut(this,e),this.secure=e.secure!=null?e.secure:typeof location<"u"&&location.protocol==="https:",e.hostname&&!e.port&&(e.port=this.secure?"443":"80"),this.hostname=e.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=e.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},e.transports.forEach(s=>{const n=s.prototype.name;this.transports.push(n),this._transportsByName[n]=s}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},e),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=Ir(this.opts.query)),ee&&(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"})},Ct.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(t){const e=Object.assign({},this.opts.query);e.EIO=ns,e.transport=t,this.id&&(e.sid=this.id);const s=Object.assign({},this.opts,{query:e,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new this._transportsByName[t](s)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const t=this.opts.rememberUpgrade&&X.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const e=this.createTransport(t);e.open(),this.setTransport(e)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",e=>this._onClose("transport close",e))}onOpen(){this.readyState="open",X.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",t),this.emitReserved("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const e=new Error("server error");e.code=t.data,this._onError(e);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data);break}}onHandshake(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this._pingInterval=t.pingInterval,this._pingTimeout=t.pingTimeout,this._maxPayload=t.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const t=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+t,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},t),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const t=this._getWritablePackets();this.transport.send(t),this._prevBufferLen=t.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let s=0;s<this.writeBuffer.length;s++){const n=this.writeBuffer[s].data;if(n&&(e+=Tr(n)),s>0&&e>this._maxPayload)return this.writeBuffer.slice(0,s);e+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const t=Date.now()>this._pingTimeoutTime;return t&&(this._pingTimeoutTime=0,Mt(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),t}write(t,e,s){return this._sendPacket("message",t,e,s),this}send(t,e,s){return this._sendPacket("message",t,e,s),this}_sendPacket(t,e,s,n){if(typeof e=="function"&&(n=e,e=void 0),typeof s=="function"&&(n=s,s=null),this.readyState==="closing"||this.readyState==="closed")return;s=s||{},s.compress=s.compress!==!1;const i={type:t,data:e,options:s};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),n&&this.once("flush",n),this.flush()}close(){const t=()=>{this._onClose("forced close"),this.transport.close()},e=()=>{this.off("upgrade",e),this.off("upgradeError",e),t()},s=()=>{this.once("upgrade",e),this.once("upgradeError",e)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?s():t()}):this.upgrading?s():t()),this}_onError(t){if(X.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",t),this._onClose("transport error",t)}_onClose(t,e){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),ee&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const s=Ct.indexOf(this._offlineEventListener);s!==-1&&Ct.splice(s,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,e),this.writeBuffer=[],this._prevBufferLen=0}}}X.protocol=ns;class Ur extends X{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let t=0;t<this._upgrades.length;t++)this._probe(this._upgrades[t])}_probe(t){let e=this.createTransport(t),s=!1;X.priorWebsocketSuccess=!1;const n=()=>{s||(e.send([{type:"ping",data:"probe"}]),e.once("packet",g=>{if(!s)if(g.type==="pong"&&g.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",e),!e)return;X.priorWebsocketSuccess=e.name==="websocket",this.transport.pause(()=>{s||this.readyState!=="closed"&&(h(),this.setTransport(e),e.send([{type:"upgrade"}]),this.emitReserved("upgrade",e),e=null,this.upgrading=!1,this.flush())})}else{const S=new Error("probe error");S.transport=e.name,this.emitReserved("upgradeError",S)}}))};function i(){s||(s=!0,h(),e.close(),e=null)}const o=g=>{const S=new Error("probe error: "+g);S.transport=e.name,i(),this.emitReserved("upgradeError",S)};function c(){o("transport closed")}function d(){o("socket closed")}function f(g){e&&g.name!==e.name&&i()}const h=()=>{e.removeListener("open",n),e.removeListener("error",o),e.removeListener("close",c),this.off("close",d),this.off("upgrading",f)};e.once("open",n),e.once("error",o),e.once("close",c),this.once("close",d),this.once("upgrading",f),this._upgrades.indexOf("webtransport")!==-1&&t!=="webtransport"?this.setTimeoutFn(()=>{s||e.open()},200):e.open()}onHandshake(t){this._upgrades=this._filterUpgrades(t.upgrades),super.onHandshake(t)}_filterUpgrades(t){const e=[];for(let s=0;s<t.length;s++)~this.transports.indexOf(t[s])&&e.push(t[s]);return e}}let jr=class extends Ur{constructor(t,e={}){const s=typeof t=="object",n=s?{...t}:{...e};(!n.transports||n.transports&&typeof n.transports[0]=="string")&&(n.transports=(n.transports||["polling","websocket","webtransport"]).map(i=>Lr[i]).filter(i=>!!i)),super(s?n:t,n)}};function Vr(r,t="",e){let s=r;e=e||typeof location<"u"&&location,r==null&&(r=e.protocol+"//"+e.host),typeof r=="string"&&(r.charAt(0)==="/"&&(r.charAt(1)==="/"?r=e.protocol+r:r=e.host+r),/^(https?|wss?):\/\//.test(r)||(typeof e<"u"?r=e.protocol+"//"+r:r="https://"+r),s=te(r)),s.port||(/^(http|ws)$/.test(s.protocol)?s.port="80":/^(http|ws)s$/.test(s.protocol)&&(s.port="443")),s.path=s.path||"/";const i=s.host.indexOf(":")!==-1?"["+s.host+"]":s.host;return s.id=s.protocol+"://"+i+":"+s.port+t,s.href=s.protocol+"://"+i+(e&&e.port===s.port?"":":"+s.port),s}const Hr=typeof ArrayBuffer=="function",Gr=r=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(r):r.buffer instanceof ArrayBuffer,ls=Object.prototype.toString,Jr=typeof Blob=="function"||typeof Blob<"u"&&ls.call(Blob)==="[object BlobConstructor]",Yr=typeof File=="function"||typeof File<"u"&&ls.call(File)==="[object FileConstructor]";function Ae(r){return Hr&&(r instanceof ArrayBuffer||Gr(r))||Jr&&r instanceof Blob||Yr&&r instanceof File}function xt(r,t){if(!r||typeof r!="object")return!1;if(Array.isArray(r)){for(let e=0,s=r.length;e<s;e++)if(xt(r[e]))return!0;return!1}if(Ae(r))return!0;if(r.toJSON&&typeof r.toJSON=="function"&&arguments.length===1)return xt(r.toJSON(),!0);for(const e in r)if(Object.prototype.hasOwnProperty.call(r,e)&&xt(r[e]))return!0;return!1}function Wr(r){const t=[],e=r.data,s=r;return s.data=se(e,t),s.attachments=t.length,{packet:s,buffers:t}}function se(r,t){if(!r)return r;if(Ae(r)){const e={_placeholder:!0,num:t.length};return t.push(r),e}else if(Array.isArray(r)){const e=new Array(r.length);for(let s=0;s<r.length;s++)e[s]=se(r[s],t);return e}else if(typeof r=="object"&&!(r instanceof Date)){const e={};for(const s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=se(r[s],t));return e}return r}function Kr(r,t){return r.data=re(r.data,t),delete r.attachments,r}function re(r,t){if(!r)return r;if(r&&r._placeholder===!0){if(typeof r.num=="number"&&r.num>=0&&r.num<t.length)return t[r.num];throw new Error("illegal attachments")}else if(Array.isArray(r))for(let e=0;e<r.length;e++)r[e]=re(r[e],t);else if(typeof r=="object")for(const e in r)Object.prototype.hasOwnProperty.call(r,e)&&(r[e]=re(r[e],t));return r}const Xr=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var w;(function(r){r[r.CONNECT=0]="CONNECT",r[r.DISCONNECT=1]="DISCONNECT",r[r.EVENT=2]="EVENT",r[r.ACK=3]="ACK",r[r.CONNECT_ERROR=4]="CONNECT_ERROR",r[r.BINARY_EVENT=5]="BINARY_EVENT",r[r.BINARY_ACK=6]="BINARY_ACK"})(w||(w={}));class zr{constructor(t){this.replacer=t}encode(t){return(t.type===w.EVENT||t.type===w.ACK)&&xt(t)?this.encodeAsBinary({type:t.type===w.EVENT?w.BINARY_EVENT:w.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id}):[this.encodeAsString(t)]}encodeAsString(t){let e=""+t.type;return(t.type===w.BINARY_EVENT||t.type===w.BINARY_ACK)&&(e+=t.attachments+"-"),t.nsp&&t.nsp!=="/"&&(e+=t.nsp+","),t.id!=null&&(e+=t.id),t.data!=null&&(e+=JSON.stringify(t.data,this.replacer)),e}encodeAsBinary(t){const e=Wr(t),s=this.encodeAsString(e.packet),n=e.buffers;return n.unshift(s),n}}class ke extends E{constructor(t){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},typeof t=="function"?{reviver:t}:t)}add(t){let e;if(typeof t=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");e=this.decodeString(t);const s=e.type===w.BINARY_EVENT;s||e.type===w.BINARY_ACK?(e.type=s?w.EVENT:w.ACK,this.reconstructor=new Qr(e),e.attachments===0&&super.emitReserved("decoded",e)):super.emitReserved("decoded",e)}else if(Ae(t)||t.base64)if(this.reconstructor)e=this.reconstructor.takeBinaryData(t),e&&(this.reconstructor=null,super.emitReserved("decoded",e));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+t)}decodeString(t){let e=0;const s={type:Number(t.charAt(0))};if(w[s.type]===void 0)throw new Error("unknown packet type "+s.type);if(s.type===w.BINARY_EVENT||s.type===w.BINARY_ACK){const i=e+1;for(;t.charAt(++e)!=="-"&&e!=t.length;);const o=t.substring(i,e);if(o!=Number(o)||t.charAt(e)!=="-")throw new Error("Illegal attachments");const c=Number(o);if(!Zr(c)||c<0)throw new Error("Illegal attachments");if(c>this.opts.maxAttachments)throw new Error("too many attachments");s.attachments=c}if(t.charAt(e+1)==="/"){const i=e+1;for(;++e&&!(t.charAt(e)===","||e===t.length););s.nsp=t.substring(i,e)}else s.nsp="/";const n=t.charAt(e+1);if(n!==""&&Number(n)==n){const i=e+1;for(;++e;){const o=t.charAt(e);if(o==null||Number(o)!=o){--e;break}if(e===t.length)break}s.id=Number(t.substring(i,e+1))}if(t.charAt(++e)){const i=this.tryParse(t.substr(e));if(ke.isPayloadValid(s.type,i))s.data=i;else throw new Error("invalid payload")}return s}tryParse(t){try{return JSON.parse(t,this.opts.reviver)}catch{return!1}}static isPayloadValid(t,e){switch(t){case w.CONNECT:return He(e);case w.DISCONNECT:return e===void 0;case w.CONNECT_ERROR:return typeof e=="string"||He(e);case w.EVENT:case w.BINARY_EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&Xr.indexOf(e[0])===-1);case w.ACK:case w.BINARY_ACK:return Array.isArray(e)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class Qr{constructor(t){this.packet=t,this.buffers=[],this.reconPack=t}takeBinaryData(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){const e=Kr(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const Zr=Number.isInteger||function(r){return typeof r=="number"&&isFinite(r)&&Math.floor(r)===r};function He(r){return Object.prototype.toString.call(r)==="[object Object]"}const tn=Object.freeze(Object.defineProperty({__proto__:null,Decoder:ke,Encoder:zr,get PacketType(){return w}},Symbol.toStringTag,{value:"Module"}));function N(r,t,e){return r.on(t,e),function(){r.off(t,e)}}const en=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class us extends E{constructor(t,e,s){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=t,this.nsp=e,s&&s.auth&&(this.auth=s.auth),this._opts=Object.assign({},s),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const t=this.io;this.subs=[N(t,"open",this.onopen.bind(this)),N(t,"packet",this.onpacket.bind(this)),N(t,"error",this.onerror.bind(this)),N(t,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...t){return t.unshift("message"),this.emit.apply(this,t),this}emit(t,...e){var s,n,i;if(en.hasOwnProperty(t))throw new Error('"'+t.toString()+'" is a reserved event name');if(e.unshift(t),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(e),this;const o={type:w.EVENT,data:e};if(o.options={},o.options.compress=this.flags.compress!==!1,typeof e[e.length-1]=="function"){const h=this.ids++,g=e.pop();this._registerAckCallback(h,g),o.id=h}const c=(n=(s=this.io.engine)===null||s===void 0?void 0:s.transport)===null||n===void 0?void 0:n.writable,d=this.connected&&!(!((i=this.io.engine)===null||i===void 0)&&i._hasPingExpired());return this.flags.volatile&&!c||(d?(this.notifyOutgoingListeners(o),this.packet(o)):this.sendBuffer.push(o)),this.flags={},this}_registerAckCallback(t,e){var s;const n=(s=this.flags.timeout)!==null&&s!==void 0?s:this._opts.ackTimeout;if(n===void 0){this.acks[t]=e;return}const i=this.io.setTimeoutFn(()=>{delete this.acks[t];for(let c=0;c<this.sendBuffer.length;c++)this.sendBuffer[c].id===t&&this.sendBuffer.splice(c,1);e.call(this,new Error("operation has timed out"))},n),o=(...c)=>{this.io.clearTimeoutFn(i),e.apply(this,c)};o.withError=!0,this.acks[t]=o}emitWithAck(t,...e){return new Promise((s,n)=>{const i=(o,c)=>o?n(o):s(c);i.withError=!0,e.push(i),this.emit(t,...e)})}_addToQueue(t){let e;typeof t[t.length-1]=="function"&&(e=t.pop());const s={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((n,...i)=>(this._queue[0],n!==null?s.tryCount>this._opts.retries&&(this._queue.shift(),e&&e(n)):(this._queue.shift(),e&&e(null,...i)),s.pending=!1,this._drainQueue())),this._queue.push(s),this._drainQueue()}_drainQueue(t=!1){if(!this.connected||this._queue.length===0)return;const e=this._queue[0];e.pending&&!t||(e.pending=!0,e.tryCount++,this.flags=e.flags,this.emit.apply(this,e.args))}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){typeof this.auth=="function"?this.auth(t=>{this._sendConnectPacket(t)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:w.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,e){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,e),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(t=>{if(!this.sendBuffer.some(s=>String(s.id)===t)){const s=this.acks[t];delete this.acks[t],s.withError&&s.call(this,new Error("socket has been disconnected"))}})}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case w.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case w.EVENT:case w.BINARY_EVENT:this.onevent(t);break;case w.ACK:case w.BINARY_ACK:this.onack(t);break;case w.DISCONNECT:this.ondisconnect();break;case w.CONNECT_ERROR:this.destroy();const s=new Error(t.data.message);s.data=t.data.data,this.emitReserved("connect_error",s);break}}onevent(t){const e=t.data||[];t.id!=null&&e.push(this.ack(t.id)),this.connected?this.emitEvent(e):this.receiveBuffer.push(Object.freeze(e))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){const e=this._anyListeners.slice();for(const s of e)s.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&typeof t[t.length-1]=="string"&&(this._lastOffset=t[t.length-1])}ack(t){const e=this;let s=!1;return function(...n){s||(s=!0,e.packet({type:w.ACK,id:t,data:n}))}}onack(t){const e=this.acks[t.id];typeof e=="function"&&(delete this.acks[t.id],e.withError&&t.data.unshift(null),e.apply(this,t.data))}onconnect(t,e){this.id=t,this.recovered=e&&this._pid===e,this._pid=e,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:w.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){const e=this._anyListeners;for(let s=0;s<e.length;s++)if(t===e[s])return e.splice(s,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(t),this}prependAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(t),this}offAnyOutgoing(t){if(!this._anyOutgoingListeners)return this;if(t){const e=this._anyOutgoingListeners;for(let s=0;s<e.length;s++)if(t===e[s])return e.splice(s,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(t){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const e=this._anyOutgoingListeners.slice();for(const s of e)s.apply(this,t.data)}}}function ut(r){r=r||{},this.ms=r.min||100,this.max=r.max||1e4,this.factor=r.factor||2,this.jitter=r.jitter>0&&r.jitter<=1?r.jitter:0,this.attempts=0}ut.prototype.duration=function(){var r=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),e=Math.floor(t*this.jitter*r);r=Math.floor(t*10)&1?r+e:r-e}return Math.min(r,this.max)|0};ut.prototype.reset=function(){this.attempts=0};ut.prototype.setMin=function(r){this.ms=r};ut.prototype.setMax=function(r){this.max=r};ut.prototype.setJitter=function(r){this.jitter=r};class ne extends E{constructor(t,e){var s;super(),this.nsps={},this.subs=[],t&&typeof t=="object"&&(e=t,t=void 0),e=e||{},e.path=e.path||"/socket.io",this.opts=e,Ut(this,e),this.reconnection(e.reconnection!==!1),this.reconnectionAttempts(e.reconnectionAttempts||1/0),this.reconnectionDelay(e.reconnectionDelay||1e3),this.reconnectionDelayMax(e.reconnectionDelayMax||5e3),this.randomizationFactor((s=e.randomizationFactor)!==null&&s!==void 0?s:.5),this.backoff=new ut({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(e.timeout==null?2e4:e.timeout),this._readyState="closed",this.uri=t;const n=e.parser||tn;this.encoder=new n.Encoder,this.decoder=new n.Decoder,this._autoConnect=e.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,t||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(t){return t===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var e;return t===void 0?this._reconnectionDelay:(this._reconnectionDelay=t,(e=this.backoff)===null||e===void 0||e.setMin(t),this)}randomizationFactor(t){var e;return t===void 0?this._randomizationFactor:(this._randomizationFactor=t,(e=this.backoff)===null||e===void 0||e.setJitter(t),this)}reconnectionDelayMax(t){var e;return t===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,(e=this.backoff)===null||e===void 0||e.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(t){if(~this._readyState.indexOf("open"))return this;this.engine=new jr(this.uri,this.opts);const e=this.engine,s=this;this._readyState="opening",this.skipReconnect=!1;const n=N(e,"open",function(){s.onopen(),t&&t()}),i=c=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",c),t?t(c):this.maybeReconnectOnOpen()},o=N(e,"error",i);if(this._timeout!==!1){const c=this._timeout,d=this.setTimeoutFn(()=>{n(),i(new Error("timeout")),e.close()},c);this.opts.autoUnref&&d.unref(),this.subs.push(()=>{this.clearTimeoutFn(d)})}return this.subs.push(n),this.subs.push(o),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(N(t,"ping",this.onping.bind(this)),N(t,"data",this.ondata.bind(this)),N(t,"error",this.onerror.bind(this)),N(t,"close",this.onclose.bind(this)),N(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(e){this.onclose("parse error",e)}}ondecoded(t){Mt(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,e){let s=this.nsps[t];return s?this._autoConnect&&!s.active&&s.connect():(s=new us(this,t,e),this.nsps[t]=s),s}_destroy(t){const e=Object.keys(this.nsps);for(const s of e)if(this.nsps[s].active)return;this._close()}_packet(t){const e=this.encoder.encode(t);for(let s=0;s<e.length;s++)this.engine.write(e[s],t.options)}cleanup(){this.subs.forEach(t=>t()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(t,e){var s;this.cleanup(),(s=this.engine)===null||s===void 0||s.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,e),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const e=this.backoff.duration();this._reconnecting=!0;const s=this.setTimeoutFn(()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),!t.skipReconnect&&t.open(n=>{n?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",n)):t.onreconnect()}))},e);this.opts.autoUnref&&s.unref(),this.subs.push(()=>{this.clearTimeoutFn(s)})}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const ft={};function wt(r,t){typeof r=="object"&&(t=r,r=void 0),t=t||{};const e=Vr(r,t.path||"/socket.io"),s=e.source,n=e.id,i=e.path,o=ft[n]&&i in ft[n].nsps,c=t.forceNew||t["force new connection"]||t.multiplex===!1||o;let d;return c?d=new ne(s,t):(ft[n]||(ft[n]=new ne(s,t)),d=ft[n]),e.query&&!t.query&&(t.query=e.queryKey),d.socket(e.path,t)}Object.assign(wt,{Manager:ne,Socket:us,io:wt,connect:wt});const Ft="thatopen/document@1",ie="document.json",Ge=()=>`v-${Date.now()}`;function sn(r){return String(r._id??r.id??"")}var bt,oe;class Ce{constructor(t,e){b(this,bt);this.client=t,this.projectId=e}async descriptor(t){const e=await a(this,bt,oe).call(this,t);if(!e)return null;const n=await(await this.client.downloadFile(e.id)).text();if(!n.trim())return null;let i;try{i=JSON.parse(n)}catch{return null}return rn(i)}async view(t,e){const s=await this.descriptor(t);if(!s)return null;for(const n of e){const i=s.views.find(o=>o.format===n);if(i)return i}return null}async addView(t,e){const s=await this.descriptor(t);if(!s)throw new Error("This folder has no document descriptor yet: call setDescriptor first.");s.views=[...s.views.filter(n=>n.format!==e.format),e],await this.setDescriptor(t,s)}async setDescriptor(t,e){const s={...e,schema:Ft,views:e.views??[]},n=new Blob([JSON.stringify(s)],{type:"application/json"}),i=await a(this,bt,oe).call(this,t);if(i){await this.client.updateFile(i.id,{file:n,versionTag:Ge()});return}await this.client.createFile({file:n,name:ie,versionTag:Ge(),parentFolderId:t,projectId:this.projectId})}}bt=new WeakSet,oe=async function(t){const s=(await this.client.listFiles({folderId:t})).find(n=>String(n.name??"")===ie);return s?{id:sn(s)}:void 0};function rn(r){if(!r||typeof r!="object")return null;const t=r;if(t.schema!==Ft||typeof t.name!="string")return null;const e=Array.isArray(t.views)?t.views.filter(i=>!!i&&typeof i=="object"&&typeof i.fileId=="string"&&typeof i.format=="string"):[],s=t.native,n=!!s&&typeof s=="object"&&typeof s.fileId=="string"&&typeof s.format=="string";return{schema:Ft,name:t.name,...n?{native:{fileId:s.fileId,format:s.format}}:{},views:e}}class ae extends Error{constructor(t,e){super(`The document history advanced while this version was being prepared: expected head ${t}, found ${e??"none"}. Read the timeline again and rebuild on the new head.`),this.expectedGuid=t,this.actualGuid=e,this.name="StaleHistoryError"}}const Je="bimterop",ce="revitflow_history.json",et="revitflow_ops.json",Ye="revitflow/ops@1",ds="revitflow_model.frag",fs="revitflow_",nn="bimterop-locks-anchor",At=()=>`v-${Date.now()}`;function ps(r,t){return r.filter(e=>String(e.parentId??"")===t)}function B(r){return String(r._id??r.id??"")}var $,_t,he;class ys{constructor(t,e){b(this,_t);b(this,$);this.client=t,this.projectId=e}async docs(){const t=await a(this,_t,he).call(this);if(!t)return[];const e=await this.client.listFolders({parentFolderId:t,projectId:this.projectId}),s=[];for(const n of ps(e,t)){const i=String(n.name??""),o=i.indexOf("-");if(o<=0)continue;const d=(await this.client.listFiles({folderId:B(n)})).map(g=>String(g.name??"")),f=d.find(g=>g===ds)??d.find(g=>g.endsWith(".frag")&&!g.startsWith(fs)),h=d.includes(ce)||d.includes(et)||!!f;s.push({source:i.slice(0,o),docId:i.slice(o+1),folderId:B(n),modelName:f,...h?{}:{empty:!0}})}return s}doc(t,e){return new ms(this.client,this,t,e)}async rootFolderId(t=!1){if(u(this,$))return u(this,$);const e=await a(this,_t,he).call(this);if(e)return e;if(!t)return;const s=await this.client.createFolder(Je,void 0,this.projectId);return _(this,$,B(s)),u(this,$)}}$=new WeakMap,_t=new WeakSet,he=async function(){if(u(this,$))return u(this,$);const e=(await this.client.listFolders({projectId:this.projectId})).find(s=>String(s.name??"")===Je&&!s.parentId);return e&&_(this,$,B(e)),u(this,$)};var M,p,st,rt,D,le,yt,nt,ue,Rt,mt,$t,de,gs;class ms{constructor(t,e,s,n){b(this,p);b(this,M);this.client=t,this.project=e,this.source=s,this.docId=n}async timeline(){const t=await a(this,p,Rt).call(this);return xe((t==null?void 0:t.commits)??[])}async latest(){const t=await this.timeline();return t.length?t[t.length-1]:null}async delta(t){if(!t.deltaId)throw new Error(`Version ${t.guid} carries no delta: it is a full export — read model() instead.`);return await(await this.client.downloadHiddenFile(t.deltaId)).blob()}async model(){const t=await a(this,p,nt).call(this);if(!t)throw new Error(`Document ${this.source}-${this.docId} has no model file yet.`);return await(await this.client.downloadFile(t.id)).blob()}async folderId(){return await a(this,p,D).call(this,!1)}async descriptor(){return await u(this,p,st).descriptor(await a(this,p,D).call(this,!1))}async view(t){const e=await a(this,p,D).call(this,!1),s=await u(this,p,st).descriptor(e);if(s){for(const i of t){const o=s.views.find(c=>c.format===i);if(o)return o}return null}if(!t.includes("frag"))return null;const n=await a(this,p,nt).call(this);return n?{fileId:n.id,format:"frag"}:null}async addView(t){const e=await a(this,p,D).call(this,!0);if(await u(this,p,st).descriptor(e)){await u(this,p,st).addView(e,t);return}const n=await a(this,p,nt).call(this);await u(this,p,st).setDescriptor(e,{name:(n==null?void 0:n.name.replace(/\.frag$/,""))??u(this,p,rt),views:[t]})}async ownership(){const t=await a(this,p,yt).call(this,nn);if(!t)return[];const e=await this.client.getHiddenFilesByParent(t.id),s=await Promise.all(e.map(async o=>{try{const c=B(o),d=await this.client.downloadHiddenFile(c),f=JSON.parse(await d.text());return!f||typeof f!="object"||!("revitflowlock"in f)||!Array.isArray(f.keys)?null:{owner:String(f.user??""),keys:f.keys.filter(h=>typeof h=="string")}}catch{return null}})),n=new Set,i=new Map;for(const o of s)if(o)for(const c of o.keys){if(!c||n.has(c))continue;n.add(c);const d=i.get(o.owner)??[];d.push(c),i.set(o.owner,d)}return[...i.entries()].map(([o,c])=>({owner:o,elements:c}))}async sync(t){var c;const e=await a(this,p,D).call(this,!0);let s=await a(this,p,Rt).call(this)??{model:this.docId,commits:[]};const n=We(s.commits);if(t.expectedLatestGuid!==void 0&&(n==null?void 0:n.guid)!==t.expectedLatestGuid)throw new ae(t.expectedLatestGuid,n==null?void 0:n.guid);const i={guid:qt(),...n?{parents:[n.guid]}:{},author:t.author,source:t.source,timestamp:new Date().toISOString(),...t.message?{message:t.message}:{},...t.userId?{userId:t.userId}:{},...(c=t.appliedOps)!=null&&c.length?{appliedOps:t.appliedOps}:{},changes:t.changes,counts:on(t.changes)};if(t.model&&(await a(this,p,gs).call(this,e,t.model),i.full=!0),t.delta){const d=await a(this,p,nt).call(this);if(!d)throw new Error("A delta needs the model file to hang from: sync a full model first.");const f=await this.client.createHiddenFile(t.delta,d.id);i.deltaId=String(f._id??f.id)}const o=await a(this,p,Rt).call(this);if(o){s=o;const d=We(s.commits);if(t.expectedLatestGuid!==void 0&&(d==null?void 0:d.guid)!==t.expectedLatestGuid)throw new ae(t.expectedLatestGuid,d==null?void 0:d.guid);d&&!i.parents&&(i.parents=[d.guid])}return s.commits.push(i),await a(this,p,$t).call(this,e,ce,s),i}async suggestions(){const t=await a(this,p,mt).call(this);return(t==null?void 0:t.ops)??[]}async pendingSuggestions(){return(await this.suggestions()).filter(t=>t.state==="pending")}async suggest(t){const e=await a(this,p,D).call(this,!0),s=await a(this,p,mt).call(this)??{schema:Ye,ops:[]},n=await a(this,p,yt).call(this,et),i={opId:t.opId??qt(),to:t.to??this.source,title:t.title,verb:t.verb,author:t.author,createdAt:new Date().toISOString(),state:"pending",...t.targets!==void 0?{targets:t.targets}:{},...t.batchId?{batchId:t.batchId}:{},...t.userId?{userId:t.userId}:{},...t.baseCommitGuid?{baseCommitGuid:t.baseCommitGuid}:{}};if(t.payload){const c=n??await a(this,p,de).call(this,e,et,s),d=await this.client.createHiddenFile(t.payload,c.id);i.fragId=String(d._id??d.id)}const o=await a(this,p,mt).call(this)??s;return o.schema??(o.schema=Ye),o.ops.push(i),await a(this,p,$t).call(this,e,et,o),i}async suggestionPayload(t){if(!t.fragId)throw new Error(`Suggestion ${t.opId} carries no payload.`);return await(await this.client.downloadHiddenFile(t.fragId)).blob()}async resolveSuggestion(t,e){const s=await a(this,p,D).call(this,!1);if(!s)throw new Error("This document has no suggestion queue.");const n=await a(this,p,mt).call(this),i=n==null?void 0:n.ops.find(o=>o.opId===t);if(!n||!i)throw new Error(`No suggestion ${t} in this document's queue.`);return Object.assign(i,e),await a(this,p,$t).call(this,s,et,n),i}}M=new WeakMap,p=new WeakSet,st=function(){return new Ce(this.client,this.project.projectId)},rt=function(){return`${this.source}-${this.docId}`},D=async function(t){if(u(this,M))return u(this,M);const e=await this.project.rootFolderId(t);if(!e)throw new Error(`Project ${this.project.projectId} has no connected documents yet.`);const s=await this.client.listFolders({parentFolderId:e,projectId:this.project.projectId}),n=ps(s,e).find(o=>String(o.name??"")===u(this,p,rt));if(n)return _(this,M,B(n)),u(this,M);if(!t)throw new Error(`Document ${u(this,p,rt)} does not exist in this project.`);const i=await this.client.createFolder(u(this,p,rt),e,this.project.projectId);return _(this,M,B(i)),u(this,M)},le=async function(){const t=await a(this,p,D).call(this,!1);return(await this.client.listFiles({folderId:t})).map(s=>({id:B(s),name:String(s.name??"")}))},yt=async function(t){try{return(await a(this,p,le).call(this)).find(e=>e.name===t)}catch{return}},nt=async function(){try{const t=await a(this,p,le).call(this);return t.find(e=>e.name===ds)??t.find(e=>e.name.endsWith(".frag")&&!e.name.startsWith(fs))}catch{return}},ue=async function(t){const e=await a(this,p,yt).call(this,t);if(!e)return;const n=await(await this.client.downloadFile(e.id)).text();if(n.trim())return JSON.parse(n)},Rt=function(){return a(this,p,ue).call(this,ce)},mt=function(){return a(this,p,ue).call(this,et)},$t=async function(t,e,s){const n=new Blob([JSON.stringify(s)],{type:"application/json"}),i=await a(this,p,yt).call(this,e);return i?(await this.client.updateFile(i.id,{file:n,versionTag:At()}),i):await a(this,p,de).call(this,t,e,s)},de=async function(t,e,s){const n=new Blob([JSON.stringify(s)],{type:"application/json"}),i=await this.client.createFile({file:n,name:e,versionTag:At(),parentFolderId:t,projectId:this.project.projectId}),o=i.item;return{id:B(o??i),name:e}},gs=async function(t,e){const s=await a(this,p,nt).call(this);if(s)return await this.client.updateFile(s.id,{file:e,versionTag:At()}),s;const n=`${u(this,p,rt)}.frag`,i=await this.client.createFile({file:e,name:n,versionTag:At(),parentFolderId:t,projectId:this.project.projectId}),o=i.item;return{id:B(o??i),name:n}};function on(r){const t={added:0,modified:0,removed:0};for(const e of r)e.type==="create"?t.added++:e.type==="delete"?t.removed++:t.modified++;return t}function xe(r){var d;if(r.length<=1)return r.forEach((f,h)=>f.ordinal=h),[...r];const t=new Map(r.map(f=>[f.guid,f])),e=new Map,s=[];for(const f of r){const h=(d=f.parents)==null?void 0:d[0];if(h&&t.has(h)){const g=e.get(h)??[];g.push(f),e.set(h,g)}else s.push(f)}const n=(f,h)=>String(f.timestamp).localeCompare(String(h.timestamp));s.sort(n);const i=[],o=[...s].reverse(),c=new Set;for(;o.length;){const f=o.pop();if(c.has(f.guid))continue;c.add(f.guid),i.push(f);const h=(e.get(f.guid)??[]).sort(n);for(let g=h.length-1;g>=0;g--)o.push(h[g])}for(const f of r)c.has(f.guid)||i.push(f);return i.forEach((f,h)=>f.ordinal=h),i}function We(r){const t=xe(r);return t[t.length-1]}function qt(){const r=globalThis.crypto;return r!=null&&r.randomUUID?r.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}var J,Et,fe;class ws{constructor(t){b(this,Et);b(this,J,new Map);this.client=t}register(t){if(u(this,J).has(t.name))throw new Error(`A recipe named "${t.name}" is already registered.`);u(this,J).set(t.name,t)}list(t){return[...u(this,J).values()].filter(s=>(!(t!=null&&t.to)||s.to===t.to)&&(!(t!=null&&t.input)||s.inputs.includes(t.input)))}get(t){return u(this,J).get(t)}async plan(t,e){const{base:s,opId:n,result:i}=await a(this,Et,fe).call(this,t,e);return{opId:n,projectId:e.projectId,target:e.target,...s!=null&&s.guid?{baseCommitGuid:s.guid}:{},result:i}}async queue(t,e){return{suggestion:await this.client.history(t.projectId).doc(t.target.source,t.target.docId).suggest({opId:t.opId,title:t.result.title,verb:t.result.verb,author:e.author,payload:t.result.payload,targets:t.result.targets,userId:e.userId,baseCommitGuid:t.baseCommitGuid}),result:t.result}}async run(t,e){const{targetDoc:s,base:n,opId:i,result:o}=await a(this,Et,fe).call(this,t,e);return{suggestion:await s.suggest({opId:i,title:o.title,verb:o.verb,author:e.author,payload:o.payload,targets:o.targets,userId:e.userId,baseCommitGuid:n==null?void 0:n.guid}),result:o}}}J=new WeakMap,Et=new WeakSet,fe=async function(t,e){const s=u(this,J).get(t);if(!s)throw new Error(`No recipe named "${t}" is registered.`);if(s.to!==e.target.source)throw new Error(`Recipe "${t}" writes ${s.to}, but the target document belongs to ${e.target.source}.`);const n=this.client.history(e.projectId).doc(e.target.source,e.target.docId),i=await n.latest(),o=qt(),c=await s.run({client:this.client,projectId:e.projectId,targetDoc:n,opId:o,input:e.input,settings:e.settings??{}});return{recipe:s,targetDoc:n,base:i,opId:o,result:c}};const pe=100;function an(r){try{const t=JSON.parse(r);if(t&&typeof t=="object"){const e=t;return{message:typeof e.message=="string"?e.message:void 0,code:typeof e.code=="string"?e.code:void 0,details:e.details}}}catch{}return{}}function cn(r){if(!r||typeof r!="object")return;const t=r.retryAfter;return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}class jt extends Error{constructor(e,s,n,i){const o=an(n);super(o.message??`${s||"Request failed"} (${e})`);I(this,"status");I(this,"code");I(this,"details");I(this,"body");I(this,"retryAfter");this.name="RequestError",this.status=e,this.code=o.code,this.details=o.details,this.body=n,this.retryAfter=i??cn(o.details)}}const P="item/folder",m="item",H="processor",hn="npm-registry",q="hidden",Xt="FILE",zt="TOOL",Qt="APP",ln=500,Ke=3e4,un=.25,dn=r=>new Promise(t=>setTimeout(t,r));function fn(r){var n,i;const t=(i=(n=r.headers)==null?void 0:n.get)==null?void 0:i.call(n,"Retry-After");if(!t)return;const e=Number(t);if(Number.isFinite(e))return Math.max(0,e);const s=Date.parse(t);if(!Number.isNaN(s))return Math.max(0,(s-Date.now())/1e3)}function pn(r){return r instanceof jt?r.status===429||r.status>=500:!0}function yn(r,t){const e=Math.min(ln*2**t,Ke),s=e*un*Math.random(),n=r instanceof jt&&r.retryAfter!=null?r.retryAfter*1e3:void 0;return n!=null?Math.min(n,Ke)+s:e+s}var l,ye,y,G,Tt,gt,Nt,Pt,me,ge,bs;const $e=class $e{constructor(t,e,s){b(this,l);I(this,"apiUrl");I(this,"accessToken");I(this,"wsUrl");I(this,"retries");I(this,"useBearer");I(this,"builtInGlobals",null);I(this,"localServerUrl",null);I(this,"context");b(this,Tt);const{retries:n=0,useBearer:i=!1,localServerUrl:o}=s||{};let c=e;if(c.charAt(c.length-1)==="/"&&(c=c.slice(0,-1)),this.apiUrl=`${c}/api`,this.accessToken=t,this.wsUrl=c,this.retries=n,this.useBearer=i,this.context={appId:"",projectId:"",accessToken:t,apiUrl:e},o){let d=o;d.charAt(d.length-1)==="/"&&(d=d.slice(0,-1)),this.localServerUrl=d}}static fromPlatformContext(t){const e=(typeof window<"u"?window.__THATOPEN_CONTEXT__:null)||{appId:"",projectId:"",accessToken:"",apiUrl:""},s=new $e(e.accessToken,e.apiUrl,{...t,useBearer:!0});return s.context=e,s}setRetries(t){this.retries=t}setBuiltInGlobals(t){this.builtInGlobals=t}get socketOrigin(){return this.wsUrl.split("?")[0]}async resolveAccessToken(){return this.accessToken}async request(t,e,s){return a(this,l,y).call(this,t,e,s)}async listFiles(t){const{folderId:e,archived:s,projectId:n}=t||{};return e?await a(this,l,y).call(this,"GET",`${P}/${e}/items`,{query:{itemType:Xt,archived:s}}):await a(this,l,y).call(this,"GET",`${m}`,{query:{itemType:Xt,archived:s,...n&&{projectId:n}}})}async getFile(t,e){return await a(this,l,ge).call(this,t,e)}async createFile(t){return await a(this,l,Pt).call(this,t,Xt)}async updateFile(t,e){return await a(this,l,me).call(this,t,e)}async archiveFile(t){return await a(this,l,y).call(this,"DELETE",`${m}/${t}`)}async recoverFile(t){return await a(this,l,y).call(this,"PUT",`${m}/${t}/recover`)}async downloadFile(t,e){return await a(this,l,Nt).call(this,t,e)}async getFileVersionMetadata(t,e,s){const{withDraft:n}=s||{};return await a(this,l,y).call(this,"GET",`${m}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/metadata`,{query:{...n&&{withDraft:"true"}}})}async updateFileVersionMetadata(t,e,s){return await a(this,l,y).call(this,"PUT",`${m}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/metadata`,{body:JSON.stringify({metadata:s}),contentType:"application/json"})}async deleteFileVersionMetadata(t,e){return await a(this,l,y).call(this,"DELETE",`${m}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/metadata`)}async getFileVersionMetadataBatch(t,e){const{withDraft:s}=e||{};return await a(this,l,gt).call(this,t,async n=>(await a(this,l,y).call(this,"POST",`${m}/batch/version-metadata`,{body:JSON.stringify({entries:n,...s!==void 0&&{withDraft:s}}),contentType:"application/json"})).results)}async listFolders(t){const{archived:e,parentFolderId:s,projectId:n}=t||{};return await a(this,l,y).call(this,"GET",P,{query:{parentFolderId:s,archived:e,...n&&{projectId:n}}})}async getFolder(t){return await a(this,l,y).call(this,"GET",`${P}/${t}`)}async getFoldersBatch(t){return await a(this,l,gt).call(this,t,async e=>(await a(this,l,y).call(this,"POST",`${m}/batch/folders`,{body:JSON.stringify({folderIds:e}),contentType:"application/json"})).results)}async createFolder(t,e,s){return await a(this,l,y).call(this,"POST",P,{body:JSON.stringify({name:t,...e&&{parentId:e},...s&&{projectId:s}}),contentType:"application/json"})}async updateFolder(t,e){const{name:s}=e;return await a(this,l,y).call(this,"PUT",`${P}/${t}`,{body:JSON.stringify({name:s}),contentType:"application/json"})}async archiveFolder(t){return await a(this,l,y).call(this,"DELETE",`${P}/${t}`)}async recoverFolder(t){return await a(this,l,y).call(this,"PUT",`${P}/${t}/recover`)}async downloadFolder(t){return await a(this,l,G).call(this,`${P}/${t}/download`)}async listComponents(t){const{folderId:e,ShowVersions:s,projectId:n}=t||{};return e?await a(this,l,y).call(this,"GET",`${P}/${e}/items`,{query:{itemType:zt,...s&&{ShowVersions:s}}}):await a(this,l,y).call(this,"GET",`${m}`,{query:{itemType:zt,...s&&{ShowVersions:s},...n&&{projectId:n}}})}async getComponent(t,e){return await a(this,l,ge).call(this,t,e)}async createComponent(t){const{componentProps:e}=t;return await a(this,l,Pt).call(this,t,zt,e)}async updateComponent(t,e){const{componentProps:s}=e;return await a(this,l,me).call(this,t,e,s)}async downloadComponent(t,e){return await a(this,l,Nt).call(this,t,e)}async downloadComponentBundle(t,e){const{versionTag:s,withDraft:n}=e||{};return await a(this,l,G).call(this,`${m}/${t}/download/bundle`,{query:{...s&&{versionTag:s},...n&&{withDraft:n}}})}async archiveComponent(t){return await a(this,l,y).call(this,"DELETE",`${m}/${t}`)}async recoverComponent(t){return await a(this,l,y).call(this,"PUT",`${m}/${t}/recover`)}async getBuiltInComponent(t){return await(await a(this,l,G).call(this,`built-in/${t}/bundle`)).text()}async initBuiltInComponent(t,e,s){const n=await this.getBuiltInComponent(t.uuid),i=s??this.builtInGlobals??(typeof window<"u"?window.ThatOpenCompany:{})??{},o=Object.keys(i),c=o.map(g=>i[g]),f=new Function(...o,`${n}
2
- return main;`)(...c),h=(f==null?void 0:f.componentDefinition)??f;e.get(h)}async initBuiltInComponents(t,...e){await Promise.all(e.map(s=>this.initBuiltInComponent(s,t)))}async setup(t,...e){var o,c;const s=t.OBC,n=t.BUI;if(!(s!=null&&s.Components))throw new Error("globals.OBC must include Components");if(!(n!=null&&n.Manager))throw new Error("globals.BUI must include Manager");const i=new s.Components;return n.Manager.init(),this.setBuiltInGlobals(t),await this.initBuiltInComponents(i,...e),i.init(),(c=(o=this.context.appEventOrchestrator)==null?void 0:o.appLoaded)==null||c.call(o),{components:i}}throwError(t,e){var s,n;(n=(s=this.context.appEventOrchestrator)==null?void 0:s.appError)==null||n.call(s,t,e)}async listApps(t){const{folderId:e,ShowVersions:s,projectId:n}=t||{};return e?await a(this,l,y).call(this,"GET",`${P}/${e}/items`,{query:{itemType:Qt,...s&&{ShowVersions:s}}}):await a(this,l,y).call(this,"GET",`${m}`,{query:{itemType:Qt,...s&&{ShowVersions:s},...n&&{projectId:n}}})}async createApp(t){const{appProps:e}=t;return await a(this,l,Pt).call(this,t,Qt,e)}async downloadApp(t,e){return await a(this,l,Nt).call(this,t,e)}async downloadAppBundle(t,e){const{versionTag:s,withDraft:n}=e||{};return await a(this,l,G).call(this,`${m}/${t}/download/bundle`,{query:{...s&&{versionTag:s},...n&&{withDraft:n}}})}async archiveApp(t){return await a(this,l,y).call(this,"DELETE",`${m}/${t}`)}async getNpmCredentials(){return await a(this,l,y).call(this,"GET",`${hn}/credentials`)}async executeComponent(t,e,s){if(this.localServerUrl){const n=`${this.localServerUrl}/api/${H}/${t}/execute`,i=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!i.ok){const o=await i.text().catch(()=>"");throw new Error(`Local server request failed: ${i.status} - ${o}`)}return await i.json()}return await a(this,l,y).call(this,"POST",`${H}/${t}/execute`,{body:JSON.stringify(e),query:{...s&&{versionTag:s}},contentType:"application/json"})}async abortExecution(t){if(this.localServerUrl){const e=`${this.localServerUrl}/api/${H}/progress/${t}/abort`,s=await fetch(e,{method:"POST"});if(!s.ok){const n=await s.text().catch(()=>"");throw new Error(`Local server request failed: ${s.status} - ${n}`)}return await s.json()}return await a(this,l,y).call(this,"POST",`${H}/progress/${t}/abort`)}async listExecutions(t,e){if(this.localServerUrl){const s=e?`?projectId=${encodeURIComponent(e)}`:"",n=`${this.localServerUrl}/api/${H}/${t}/progress${s}`,i=await fetch(n);if(!i.ok){const o=await i.text().catch(()=>"");throw new Error(`Local server request failed: ${i.status} - ${o}`)}return await i.json()}return await a(this,l,y).call(this,"GET",`${H}/${t}/progress`,{query:{...e&&{projectId:e}}})}async getExecution(t){if(this.localServerUrl){const e=`${this.localServerUrl}/api/${H}/progress/${t}`,s=await fetch(e);if(!s.ok){const n=await s.text().catch(()=>"");throw new Error(`Local server request failed: ${s.status} - ${n}`)}return await s.json()}return await a(this,l,y).call(this,"GET",`${H}/progress/${t}`)}async onExecutionProgress(t,e){const s=this.localServerUrl??this.wsUrl,n=await wt(s,{auth:{accessToken:this.accessToken},transports:["websocket"]});n.on("connect",function(){n.emit("executionSubscription",JSON.stringify({executionId:t})),n.on("execution",i=>{e(i)})}),n.on("connect_error",function(i){console.log(i)})}documents(t){return new Ce(this,t)}history(t){return new ys(this,t)}get recipes(){return u(this,Tt)??_(this,Tt,new ws(this)),u(this,Tt)}async createHiddenFile(t,e,s){const n=new FormData;return n.append("file",t),n.append("parentItemId",e),s!=null&&n.append("tag",s),await a(this,l,y).call(this,"POST",`${m}/${q}`,{body:n})}async createHiddenFilesBatch(t,e,s){const n=new FormData;for(const i of t)n.append("files",i);return n.append("parentItemId",e),s!=null&&n.append("tag",s),await a(this,l,y).call(this,"POST",`${m}/${q}/batch`,{body:n})}async deleteHiddenFile(t){return await a(this,l,y).call(this,"DELETE",`${m}/${q}/${t}`)}async getHiddenFile(t){return await a(this,l,y).call(this,"GET",`${m}/${q}/${t}`)}async downloadHiddenFile(t){return await a(this,l,G).call(this,`${m}/${q}/${t}/download`)}async getHiddenFileSignedUrl(t,e){return await a(this,l,y).call(this,"GET",`${m}/${q}/${t}/signed-url`,{...e!=null&&{query:{expiresIn:e}}})}async getHiddenFileSignedUrlsBatch(t,e){return await a(this,l,gt).call(this,t,async s=>(await a(this,l,y).call(this,"POST",`${m}/${q}/signed-url/batch`,{body:JSON.stringify({hiddenFileIds:s,...e!=null&&{expiresIn:e}}),contentType:"application/json"})).results)}async getHiddenFilesByParent(t,e){return await a(this,l,y).call(this,"GET",`${m}/${t}/${q}`,{...e!=null&&{query:{tag:e}}})}async deleteHiddenFilesByParent(t){return await a(this,l,y).call(this,"DELETE",`${m}/${t}/${q}`)}async uploadItemIcon(t,e){const s=new FormData;return s.append("icon",e),await a(this,l,y).call(this,"PUT",`${m}/${t}/icon`,{body:s})}async getItemIcon(t){return await a(this,l,G).call(this,`${m}/${t}/icon`)}async removeItemIcon(t){return await a(this,l,y).call(this,"DELETE",`${m}/${t}/icon`)}async updateItem(t,e){return await a(this,l,y).call(this,"PUT",`${m}/${t}`,{body:JSON.stringify(e),contentType:"application/json"})}async createVersion(t,e,s,n,i){const o=new FormData;return o.append("file",e),o.append("versionTag",s),n&&o.append("extraProps",JSON.stringify(n)),i&&o.append("metadata",JSON.stringify(i)),await a(this,l,y).call(this,"POST",`${m}/${t}/version`,{body:o})}async listVersions(t,e={}){return await a(this,l,y).call(this,"GET",`${m}/${encodeURIComponent(t)}/versions`,{query:e})}async listVersionsBatch(t,e={}){const{archived:s}=e;return await a(this,l,gt).call(this,t,async n=>(await a(this,l,y).call(this,"POST",`${m}/batch/versions`,{body:JSON.stringify({itemIds:n,...s!==void 0&&{archived:s}}),contentType:"application/json"})).results)}async archiveVersion(t,e){return await a(this,l,y).call(this,"PUT",`${m}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/archive`)}async recoverVersion(t,e){return await a(this,l,y).call(this,"PUT",`${m}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/recover`)}async deleteVersion(t,e){return await a(this,l,y).call(this,"DELETE",`${m}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}`)}};l=new WeakSet,ye=function(t){return`${this.apiUrl}/${t}`},y=async function(t,e,s){const{body:n,query:i,contentType:o,retries:c,responseType:d,retryAttempt:f}=s||{},h=a(this,l,ye).call(this,e),g=a(this,l,bs).call(this,i),S=await this.resolveAccessToken(),dt={...g,...this.useBearer?{}:{accessToken:S}};try{const O=await fetch(h+"?"+new URLSearchParams(dt).toString(),{method:t,headers:{Accept:"application/json",...o&&{"Content-Type":o},...this.useBearer&&{Authorization:`Bearer ${S}`}},...n&&{body:n}});if(!O.ok){const k=await O.text().then(Z=>Z).catch(()=>"");throw new jt(O.status,O.statusText,k,fn(O))}return d==="blob"?await O.blob():O.json().then(k=>k).catch(()=>{})}catch(O){const k=c??this.retries;if(k>0&&pn(O)){const Z=f??0;return await dn(yn(O,Z)),await a(this,l,y).call(this,t,e,{...s,retries:k-1,retryAttempt:Z+1})}throw O}},G=async function(t,e){const{query:s}=e||{},n=a(this,l,ye).call(this,t),i=await this.resolveAccessToken(),o={...s,...this.useBearer?{}:{accessToken:i}};return await fetch(n+"?"+new URLSearchParams(o).toString(),{method:"GET",...this.useBearer&&{headers:{Authorization:`Bearer ${i}`}}})},Tt=new WeakMap,gt=async function(t,e){if(!t.length)return[];const s=[];for(let i=0;i<t.length;i+=pe)s.push(t.slice(i,i+pe));return(await Promise.all(s.map(e))).flat()},Nt=async function(t,e){const{versionTag:s,withDraft:n}=e||{};return await a(this,l,G).call(this,`${m}/${t}/download`,{query:{...s&&{versionTag:s},...n&&{withDraft:n}}})},Pt=async function(t,e,s){const{name:n,versionTag:i,parentFolderId:o,projectId:c,file:d,metadata:f}=t,h=new FormData;return h.append("file",d),h.append("name",n),h.append("versionTag",i),h.append("itemType",e),o&&h.append("folderId",o),c&&h.append("projectId",c),s&&h.append("extraProps",JSON.stringify(s)),f&&h.append("metadata",JSON.stringify(f)),await a(this,l,y).call(this,"POST",m,{body:h})},me=async function(t,e,s){const{name:n,versionTag:i,parentFolderId:o,file:c,metadata:d}=e;let f,h;if(c){const g=new FormData;g.append("file",c),i&&g.append("versionTag",i),s&&g.append("extraProps",JSON.stringify(s)),d&&g.append("metadata",JSON.stringify(d)),h=await a(this,l,y).call(this,"POST",`${m}/${t}/version`,{body:g})}if(n||o){const g={...n&&{name:n},...o&&{folderId:o}},S=JSON.stringify(g);f=await a(this,l,y).call(this,"PUT",`${m}/${t}`,{body:S,contentType:"application/json"})}return{item:f,version:h}},ge=async function(t,e){const{showVersions:s=!1}=e||{};return await a(this,l,y).call(this,"GET",`${m}/${t}`,{query:{showVersions:s}})},bs=function(t){return t&&Object.entries(t).filter(([,e])=>e!==void 0).reduce((e,[s,n])=>(e[s]=n,e),{})};let Dt=$e;function _s(){if(typeof window>"u"||window.parent===window)throw new Error("client.channel only works inside a That Open app, which runs in an iframe of the platform.");return{post:r=>window.parent.postMessage(r,"*"),listen:r=>{const t=e=>{e.source===window.parent&&r(e.data)};return window.addEventListener("message",t),()=>window.removeEventListener("message",t)}}}const we="channel:",mn=1e4;function Bt(r){try{r()}catch(t){console.error("[channel] a listener threw:",t)}}var U,C,x,ot,at,ct,A,be,_e,it;class Re{constructor(t,e){b(this,A);b(this,U,!1);b(this,C,[]);b(this,x,[]);b(this,ot,new Set);b(this,at,new Set);b(this,ct,new Set);this.transport=t,this.controls=e}get joined(){return u(this,U)}get peers(){return u(this,C)}join(){return u(this,U)?Promise.resolve():a(this,A,be).call(this,"joined",this.controls.join)}leave(){return!u(this,U)&&!u(this,x).some(t=>t.want==="joined")?Promise.resolve():a(this,A,be).call(this,"left",this.controls.leave)}onChange(t){return u(this,ot).add(t),()=>void u(this,ot).delete(t)}onPeerJoined(t){return u(this,at).add(t),()=>void u(this,at).delete(t)}onPeerLeft(t){return u(this,ct).add(t),()=>void u(this,ct).delete(t)}applyJoined(){_(this,U,!0),a(this,A,_e).call(this,"joined"),a(this,A,it).call(this)}applyLeft(){_(this,U,!1),_(this,C,[]),a(this,A,_e).call(this,"left"),a(this,A,it).call(this)}applyPeers(t){_(this,C,t),a(this,A,it).call(this)}applyPeerJoined(t){!u(this,U)||u(this,C).some(e=>e.from===t.from)||(_(this,C,[...u(this,C),t]),u(this,at).forEach(e=>Bt(()=>e(t))),a(this,A,it).call(this))}applyPeerLeft(t){const e=u(this,C).find(s=>s.from===t);e&&(_(this,C,u(this,C).filter(s=>s.from!==t)),u(this,ct).forEach(s=>Bt(()=>s(e))),a(this,A,it).call(this))}failPending(t){const e=u(this,x);return _(this,x,[]),e.forEach(s=>{clearTimeout(s.timer),s.reject(t)}),e.length>0}post(t){this.transport.post(t)}}U=new WeakMap,C=new WeakMap,x=new WeakMap,ot=new WeakMap,at=new WeakMap,ct=new WeakMap,A=new WeakSet,be=function(t,e){return new Promise((s,n)=>{const i={want:t,resolve:s,reject:n,timer:setTimeout(()=>{_(this,x,u(this,x).filter(o=>o!==i)),n(new Error(`The platform did not confirm ${t==="joined"?"joining":"leaving"} in time.`))},mn)};u(this,x).push(i),this.transport.post({type:"APP_CHANNEL_CONTROL",...e})})},_e=function(t){const e=u(this,x).filter(s=>s.want===t);_(this,x,u(this,x).filter(s=>s.want!==t)),e.forEach(s=>{clearTimeout(s.timer),s.resolve()})},it=function(){u(this,ot).forEach(t=>Bt(t))};var ht;class Es extends Re{constructor(e){super(e,{join:{action:"joinCollab"},leave:{action:"leaveCollab"}});b(this,ht,new Map)}on(e,s){const n=u(this,ht).get(e)??new Set;return n.add(s),u(this,ht).set(e,n),()=>void n.delete(s)}send(e,s){if(e.startsWith(we))throw new Error(`Message types starting with '${we}' are reserved.`);this.joined&&this.post({type:"APP_CHANNEL_PUBLISH",message:{type:e,payload:s}})}accepts(e){return e===void 0||e==="collab"}async handle(e){const s=u(this,ht).get(e.type);if(!(s!=null&&s.size))return{handled:!1};const n=vs(e);return s.forEach(i=>Bt(()=>i(e.payload,n))),{handled:!0}}}ht=new WeakMap;var Y;class Ts extends Re{constructor(e,s){super(e,{join:{action:"joinExternal",kind:s},leave:{action:"leaveExternal",kind:s}});b(this,Y,new Map);this.kind=s}on(e,s){if(u(this,Y).has(e))throw new Error(`"${e}" already has a handler in this room. Remove it first.`);return u(this,Y).set(e,s),()=>void u(this,Y).delete(e)}accepts(e,s){return e!==void 0&&e!=="external"?!1:this.kind===void 0||e===void 0||this.kind===s}get hasHandlers(){return u(this,Y).size>0}async handle(e){const s=u(this,Y).get(e.type);if(!s)return{handled:!1};try{return{handled:!0,value:await s(e.payload,vs(e))}}catch(n){return{handled:!0,error:n instanceof Error?n.message:String(n)}}}}Y=new WeakMap;function vs(r){return{from:r.from,at:r.at,requestId:r.requestId,kind:r.kind}}function gn(r){const t=r;if((t==null?void 0:t.type)!=="THATOPEN_CHANNEL_MESSAGE")return null;const e=t.message;return!e||typeof e.type!="string"?null:{type:e.type,requestId:typeof e.requestId=="string"?e.requestId:void 0,payload:e.payload,at:typeof e.at=="number"?e.at:Date.now(),from:typeof e.from=="string"?e.from:"",scope:e.scope==="collab"||e.scope==="external"?e.scope:void 0,kind:typeof e.kind=="string"?e.kind:void 0}}var Q,vt,j,W,K,T,Ee,Lt,Is,Os,As,Te;class Ss{constructor(t){b(this,T);b(this,Q);b(this,vt);b(this,j);b(this,W,new Map);b(this,K,new Set);_(this,Q,t),_(this,vt,t.listen(e=>void a(this,T,Is).call(this,e)))}collab(){return u(this,j)??_(this,j,new Es(u(this,Q))),u(this,j)}external(t){const e=t??"";let s=u(this,W).get(e);return s||(s=new Ts(u(this,Q),t),u(this,W).set(e,s)),s}dispose(){u(this,vt).call(this)}}Q=new WeakMap,vt=new WeakMap,j=new WeakMap,W=new WeakMap,K=new WeakMap,T=new WeakSet,Ee=function(){return[...u(this,j)?[u(this,j)]:[],...u(this,W).values()]},Lt=function(t,e){if(t==="collab")return u(this,j);if(t==="external")return u(this,W).get(typeof e=="string"?e:"")},Is=async function(t){const e=gn(t);if(e){if(e.type.startsWith(we)){a(this,T,Os).call(this,e);return}await a(this,T,As).call(this,e)}},Os=function(t){var s,n,i;const e=t.payload??{};switch(t.type){case"channel:joined":(s=a(this,T,Lt).call(this,e.scope,e.kind))==null||s.applyJoined();break;case"channel:left":(n=a(this,T,Lt).call(this,e.scope,e.kind))==null||n.applyLeft();break;case"channel:peers":(i=a(this,T,Lt).call(this,e.scope,e.kind))==null||i.applyPeers(e.peers??[]);break;case"channel:peer-joined":case"channel:peer-left":{if(!e.from)break;const o=e.scope==="collab"?[u(this,j)]:[...u(this,W).values()].filter(c=>c.accepts("external",e.kind));for(const c of o)t.type==="channel:peer-joined"?c==null||c.applyPeerJoined({from:e.from,kind:e.kind}):c==null||c.applyPeerLeft(e.from);break}case"channel:error":{const o=new Error(String(t.payload));a(this,T,Ee).call(this).map(d=>d.failPending(o)).some(Boolean)||console.error("[channel] error:",t.payload);break}}},As=async function(t){const e=a(this,T,Ee).call(this).filter(i=>i.accepts(t.scope,t.kind));let s=!1;for(const i of e){const o=await i.handle(t);o.handled&&(s=!0,t.requestId&&a(this,T,Te).call(this,t.requestId,o))}t.requestId&&t.scope==="external"&&e.length>0&&!s&&a(this,T,Te).call(this,t.requestId,{handled:!0,error:`No handler for "${t.type}".`})},Te=function(t,e){u(this,K).has(t)||(u(this,K).add(t),u(this,K).size>500&&u(this,K).delete(u(this,K).values().next().value),u(this,Q).post({type:"APP_CHANNEL_PUBLISH",message:{type:e.error===void 0?"reply":"reply-error",requestId:t,payload:e.error===void 0?e.value:{error:e.error}}}))};const z="project",tt="notifications";var lt,St;const Ne=class Ne extends Dt{constructor(e,s,n){super(typeof e=="string"?e:"",s,{...n,useBearer:!0});b(this,lt);b(this,St);typeof e=="function"&&_(this,lt,e)}async resolveAccessToken(){return u(this,lt)?await u(this,lt).call(this):super.resolveAccessToken()}static fromPlatformContext(e){const s=(typeof window<"u"?window.__THATOPEN_CONTEXT__:null)||{appId:"",projectId:"",accessToken:"",apiUrl:""},n=new Ne(s.accessToken,s.apiUrl,e);return n.context=s,n}get channel(){return u(this,St)??_(this,St,new Ss(_s())),u(this,St)}async listProjects(){return await this.request("GET",z)}async getProject(e){return await this.request("GET",`${z}/${e}`)}async getProjectData(e){return await this.request("GET",`${z}/${e}/data`)}async getAvatar(e){return await this.request("GET",`account/${e}/avatar`,{responseType:"blob"})}async checkPermission(e){return await this.request("GET",`${z}/permissions/check`,{query:e})}async checkPermissionBatch(e){return(await this.request("POST",`${z}/permissions/check/batch`,{body:JSON.stringify({checks:e}),contentType:"application/json"})).results}async getNotifications(e){return await this.request("GET",tt,{query:{...(e==null?void 0:e.cursor)!==void 0&&{cursor:e.cursor},...(e==null?void 0:e.limit)!==void 0&&{limit:String(e.limit)}}})}async getUnreadNotificationCount(){return(await this.request("GET",`${tt}/unread-count`)).count}async markNotificationsRead(e){return await this.request("POST",`${tt}/mark-read`,{body:JSON.stringify({ids:e}),contentType:"application/json"})}async markAllNotificationsRead(){return await this.request("POST",`${tt}/mark-all-read`)}async getNotificationSubscriptions(){return await this.request("GET",`${tt}/subscriptions`)}async unsubscribeFromAutomation(e){return await this.request("DELETE",`${tt}/subscriptions/${e}`)}async subscribeToAutomation(e,s,n){return await this.request("POST",`${z}/${e}/events/hooks/${s}/subscription`,{body:JSON.stringify(n??{}),contentType:"application/json"})}async updateAutomationSubscription(e,s,n){return await this.request("PATCH",`${z}/${e}/events/hooks/${s}/subscription`,{body:JSON.stringify(n),contentType:"application/json"})}async onNotification(e){const s=await this.resolveAccessToken(),n=wt(`${this.socketOrigin}/notifications`,{auth:{accessToken:s},transports:["websocket"]});return n.on("notification.created",i=>e({type:"created",id:i==null?void 0:i.id})),n.on("notification.read",i=>e({type:"read",id:i==null?void 0:i.id})),n.on("notifications.allRead",i=>e({type:"allRead",batch:i==null?void 0:i.batch})),()=>n.disconnect()}};lt=new WeakMap,St=new WeakMap;let ve=Ne;const wn="flow:",bn="flow:op",_n="flow:source",ks="revitflow/op@2",Xe="REVITFLOWCHANGE",ze="REVITFLOWOPERATION";class En{constructor(t){I(this,"changes",[]);this.target=t}get length(){return this.changes.length}get batchId(){return this.target.batchId}get title(){return this.target.title??`${this.changes.length} change(s)`}get author(){return this.target.author??"app"}get userId(){return this.target.userId}get baseCommit(){return this.target.baseCommit}add(t,e={}){return this.changes.push({op:"add",attrs:this.pack(t,e)}),this}set(t,e,s={}){return this.requireId(t,"set"),this.changes.push({op:"set",item:t,attrs:this.pack(e,s)}),this}remove(t){return this.requireId(t,"remove"),this.changes.push({op:"remove",item:t,attrs:{}}),this}get summary(){const t=new Set(this.changes.map(e=>e.op));return t.size===1?[...t][0]:"mixed"}async build(t){if(this.changes.length===0)throw new Error("An operation with no changes is not an operation. Add at least one.");const e={schema:ks,opId:t,batchId:this.batchId??t,targetProject:this.target.project,targetDocument:this.target.document,baseCommit:this.baseCommit,author:this.author,...this.userId?{userId:this.userId}:{},title:this.title,summary:this.summary},[s,n]=await Tn();return vn(this.flatbuffer(s,n,t,JSON.stringify(e)))}pack(t,e){const s={};for(const[n,i]of Object.entries(t??{}))n.startsWith(wn)||(s[n]=String(i));return e.position&&(s.Position=e.position.map(Qe).join(",")),e.rotationDeg!==void 0&&(s.Rotation=Qe(e.rotationDeg)),e.source&&(s[_n]=e.source),s}requireId(t,e){if(!t||!t.trim())throw new Error(`A '${e}' has to name the item it acts on.`)}flatbuffer(t,e,s,n){const{Attribute:i,Meshes:o,Model:c,SpatialStructure:d,Transform:f}=e,h=new t.Builder(1024),g=this.changes.length,S=new Uint32Array(g);let dt=1;for(let v=0;v<g;v++)S[v]=dt++;const O=dt++,k=v=>(v(h,0),h.endVector()),Z=o.createShellsVector(h,[]),Cs=o.createCircleExtrusionsVector(h,[]),xs=k(o.startSamplesVector),Rs=k(o.startRepresentationsVector),$s=k(o.startMaterialsVector),Ns=k(o.startLocalTransformsVector),Ps=k(o.startGlobalTransformsVector),Bs=o.createMeshesItemsVector(h,[]),Ls=o.createMaterialIdsVector(h,[]),Fs=o.createRepresentationIdsVector(h,[]),qs=o.createSampleIdsVector(h,[]),Ds=o.createLocalTransformIdsVector(h,[]),Ms=o.createGlobalTransformIdsVector(h,[]);o.startMeshes(h),o.addCoordinates(h,f.createTransform(h,0,0,0,1,0,0,0,1,0)),o.addGlobalTransforms(h,Ps),o.addShells(h,Z),o.addRepresentations(h,Rs),o.addSamples(h,xs),o.addLocalTransforms(h,Ns),o.addMaterials(h,$s),o.addCircleExtrusions(h,Cs),o.addMeshesItems(h,Bs),o.addRepresentationIds(h,Fs),o.addSampleIds(h,qs),o.addMaterialIds(h,Ls),o.addLocalTransformIds(h,Ds),o.addGlobalTransformIds(h,Ms);const Us=o.endMeshes(h),js=h.createString(n),Vt=new Set,Ht=[];for(const v of this.changes){const V=[],Zs={[bn]:v.op,...v.attrs};for(const[tr,er]of Object.entries(Zs)){const Fe=JSON.stringify([tr,er,"IFCTEXT"]);Vt.add(Fe),V.push(h.createString(Fe))}Ht.push(i.createAttribute(h,i.createDataVector(h,V)))}{const v=JSON.stringify(["Name",s,"IFCLABEL"]);Vt.add(v);const V=i.createDataVector(h,[h.createString(v)]);Ht.push(i.createAttribute(h,V))}const Vs=c.createAttributesVector(h,Ht),Hs=c.createUniqueAttributesVector(h,[...Vt].map(v=>h.createString(v))),Pe=this.changes.map(()=>h.createString(Xe));Pe.push(h.createString(ze));const Gs=c.createCategoriesVector(h,Pe),Be=[],Le=[];this.changes.forEach((v,V)=>{v.item&&(Be.push(h.createString(v.item)),Le.push(S[V]))});const Js=c.createGuidsVector(h,Be),Ys=c.createGuidsItemsVector(h,Le),Ws=c.createLocalIdsVector(h,[...S,O]),Ks=this.changes.map((v,V)=>d.createSpatialStructure(h,S[V],h.createString(Xe),0)),Xs=d.createSpatialStructure(h,O,h.createString(ze),d.createChildrenVector(h,Ks)),zs=h.createString(s);c.startModel(h),c.addMeshes(h,Us),c.addMetadata(h,js),c.addAttributes(h,Vs),c.addUniqueAttributes(h,Hs),c.addLocalIds(h,Ws),c.addCategories(h,Gs),c.addGuidsItems(h,Ys),c.addGuids(h,Js),c.addGuid(h,zs),c.addSpatialStructure(h,Xs),c.addMaxLocalId(h,dt);const Qs=c.endModel(h);return c.finishModelBuffer(h,Qs),h.asUint8Array()}}async function Tn(){try{return await Promise.all([import("flatbuffers"),import("@thatopen/fragments")])}catch(r){throw new Error(`OperationBuilder needs the optional peers \`flatbuffers\` and \`@thatopen/fragments\` installed — add them to the app that authors operations. (${r instanceof Error?r.message:String(r)})`)}}function Qe(r){return Number.isFinite(r)?String(r):"0"}async function vn(r){const t=new Blob([r]).stream().pipeThrough(new CompressionStream("deflate"));return new Uint8Array(await new Response(t).arrayBuffer())}const Sn={MAX_FIELDS:200,MAX_KEY_LENGTH:50,MAX_VALUE_LENGTH:50},In={uuid:"a3f82c1d-5b74-4e9a-bc30-d7e12f894a61"},On={uuid:"2c9f4e8d-3a1b-4c5e-9d7f-0a2b6c8e1d3f"},An={uuid:"b0b5e2a2-0b3a-4a6b-8b1c-0b1c4a6b8b1c"},kn={uuid:"d8f3a1c2-6b4e-4f9a-8c1d-2e7b5a9f3c60"},Cn={uuid:"3f9c1a7e-6b2d-4e18-9a5c-7d0e2f4b6c81"},xn={uuid:"2c4ae432-fc24-43e9-9783-0c960c674e96"},Rn={uuid:"6f3a9c2e-8b1d-4e6a-9c3f-1d7b5a8e2c4f"},$n={uuid:"69af63aa-19ba-4fc7-b17b-75647bac1d76"},Nn={uuid:"234f1416-528d-452a-9cc9-a16c5239b2eb"};exports.CDEManager=In;exports.ChannelClient=Ss;exports.ChannelRoom=Re;exports.ClashesManager=On;exports.CollabRoom=Es;exports.DOCUMENT_FILE=ie;exports.DOCUMENT_SCHEMA=Ft;exports.EngineServicesClient=Dt;exports.ExternalRoom=Ts;exports.FileList=An;exports.FlowDoc=ms;exports.GISManager=kn;exports.GitHistoryManager=Cn;exports.HelloWorld=xn;exports.METADATA_LIMITS=Sn;exports.OP_SCHEMA=ks;exports.OperationBuilder=En;exports.PlatformClient=ve;exports.ProjectDocuments=Ce;exports.ProjectHistory=ys;exports.ProjectManager=Rn;exports.Recipes=ws;exports.RequestError=jt;exports.STORAGE_BATCH_MAX=pe;exports.StaleHistoryError=ae;exports.TopicsManager=$n;exports.UIManager=Nn;exports.mintGuid=qt;exports.orderByGraph=xe;exports.windowTransport=_s;
1
+ "use strict";var or=Object.create;var Jt=Object.defineProperty;var ar=Object.getOwnPropertyDescriptor;var cr=Object.getOwnPropertyNames;var hr=Object.getPrototypeOf,lr=Object.prototype.hasOwnProperty;var De=r=>{throw TypeError(r)};var ur=(r,t,e)=>t in r?Jt(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e;var dr=(r,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of cr(t))!lr.call(r,n)&&n!==e&&Jt(r,n,{get:()=>t[n],enumerable:!(s=ar(t,n))||s.enumerable});return r};var Me=(r,t,e)=>(e=r!=null?or(hr(r)):{},dr(t||!r||!r.__esModule?Jt(e,"default",{value:r,enumerable:!0}):e,r));var I=(r,t,e)=>ur(r,typeof t!="symbol"?t+"":t,e),Yt=(r,t,e)=>t.has(r)||De("Cannot "+e);var u=(r,t,e)=>(Yt(r,t,"read from private field"),e?e.call(r):t.get(r)),b=(r,t,e)=>t.has(r)?De("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(r):t.set(r,e),_=(r,t,e,s)=>(Yt(r,t,"write to private field"),s?s.call(r,e):t.set(r,e),e),a=(r,t,e)=>(Yt(r,t,"access private method"),e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const F=Object.create(null);F.open="0";F.close="1";F.ping="2";F.pong="3";F.message="4";F.upgrade="5";F.noop="6";const xt=Object.create(null);Object.keys(F).forEach(r=>{xt[F[r]]=r});const te={type:"error",data:"parser error"},es=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",ss=typeof ArrayBuffer=="function",rs=r=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(r):r&&r.buffer instanceof ArrayBuffer,Ie=({type:r,data:t},e,s)=>es&&t instanceof Blob?e?s(t):Ue(t,s):ss&&(t instanceof ArrayBuffer||rs(t))?e?s(t):Ue(new Blob([t]),s):s(F[r]+(t||"")),Ue=(r,t)=>{const e=new FileReader;return e.onload=function(){const s=e.result.split(",")[1];t("b"+(s||""))},e.readAsDataURL(r)};function je(r){return r instanceof Uint8Array?r:r instanceof ArrayBuffer?new Uint8Array(r):new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}let Wt;function fr(r,t){if(es&&r.data instanceof Blob)return r.data.arrayBuffer().then(je).then(t);if(ss&&(r.data instanceof ArrayBuffer||rs(r.data)))return t(je(r.data));Ie(r,!1,e=>{Wt||(Wt=new TextEncoder),t(Wt.encode(e))})}const Ve="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",yt=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let r=0;r<Ve.length;r++)yt[Ve.charCodeAt(r)]=r;const pr=r=>{let t=r.length*.75,e=r.length,s,n=0,i,o,h,d;r[r.length-1]==="="&&(t--,r[r.length-2]==="="&&t--);const f=new ArrayBuffer(t),c=new Uint8Array(f);for(s=0;s<e;s+=4)i=yt[r.charCodeAt(s)],o=yt[r.charCodeAt(s+1)],h=yt[r.charCodeAt(s+2)],d=yt[r.charCodeAt(s+3)],c[n++]=i<<2|o>>4,c[n++]=(o&15)<<4|h>>2,c[n++]=(h&3)<<6|d&63;return f},yr=typeof ArrayBuffer=="function",Oe=(r,t)=>{if(typeof r!="string")return{type:"message",data:ns(r,t)};const e=r.charAt(0);return e==="b"?{type:"message",data:mr(r.substring(1),t)}:xt[e]?r.length>1?{type:xt[e],data:r.substring(1)}:{type:xt[e]}:te},mr=(r,t)=>{if(yr){const e=pr(r);return ns(e,t)}else return{base64:!0,data:r}},ns=(r,t)=>{switch(t){case"blob":return r instanceof Blob?r:new Blob([r]);case"arraybuffer":default:return r instanceof ArrayBuffer?r:r.buffer}},is="",gr=(r,t)=>{const e=r.length,s=new Array(e);let n=0;r.forEach((i,o)=>{Ie(i,!1,h=>{s[o]=h,++n===e&&t(s.join(is))})})},wr=(r,t)=>{const e=r.split(is),s=[];for(let n=0;n<e.length;n++){const i=Oe(e[n],t);if(s.push(i),i.type==="error")break}return s};function br(){return new TransformStream({transform(r,t){fr(r,e=>{const s=e.length;let n;if(s<126)n=new Uint8Array(1),new DataView(n.buffer).setUint8(0,s);else if(s<65536){n=new Uint8Array(3);const i=new DataView(n.buffer);i.setUint8(0,126),i.setUint16(1,s)}else{n=new Uint8Array(9);const i=new DataView(n.buffer);i.setUint8(0,127),i.setBigUint64(1,BigInt(s))}r.data&&typeof r.data!="string"&&(n[0]|=128),t.enqueue(n),t.enqueue(e)})}})}let Kt;function Ot(r){return r.reduce((t,e)=>t+e.length,0)}function At(r,t){if(r[0].length===t)return r.shift();const e=new Uint8Array(t);let s=0;for(let n=0;n<t;n++)e[n]=r[0][s++],s===r[0].length&&(r.shift(),s=0);return r.length&&s<r[0].length&&(r[0]=r[0].slice(s)),e}function _r(r,t){Kt||(Kt=new TextDecoder);const e=[];let s=0,n=-1,i=!1;return new TransformStream({transform(o,h){for(e.push(o);;){if(s===0){if(Ot(e)<1)break;const d=At(e,1);i=(d[0]&128)===128,n=d[0]&127,n<126?s=3:n===126?s=1:s=2}else if(s===1){if(Ot(e)<2)break;const d=At(e,2);n=new DataView(d.buffer,d.byteOffset,d.length).getUint16(0),s=3}else if(s===2){if(Ot(e)<8)break;const d=At(e,8),f=new DataView(d.buffer,d.byteOffset,d.length),c=f.getUint32(0);if(c>Math.pow(2,21)-1){h.enqueue(te);break}n=c*Math.pow(2,32)+f.getUint32(4),s=3}else{if(Ot(e)<n)break;const d=At(e,n);h.enqueue(Oe(i?d:Kt.decode(d),t)),s=0}if(n===0||n>r){h.enqueue(te);break}}}})}const os=4;function E(r){if(r)return Er(r)}function Er(r){for(var t in E.prototype)r[t]=E.prototype[t];return r}E.prototype.on=E.prototype.addEventListener=function(r,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+r]=this._callbacks["$"+r]||[]).push(t),this};E.prototype.once=function(r,t){function e(){this.off(r,e),t.apply(this,arguments)}return e.fn=t,this.on(r,e),this};E.prototype.off=E.prototype.removeListener=E.prototype.removeAllListeners=E.prototype.removeEventListener=function(r,t){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var e=this._callbacks["$"+r];if(!e)return this;if(arguments.length==1)return delete this._callbacks["$"+r],this;for(var s,n=0;n<e.length;n++)if(s=e[n],s===t||s.fn===t){e.splice(n,1);break}return e.length===0&&delete this._callbacks["$"+r],this};E.prototype.emit=function(r){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),e=this._callbacks["$"+r],s=1;s<arguments.length;s++)t[s-1]=arguments[s];if(e){e=e.slice(0);for(var s=0,n=e.length;s<n;++s)e[s].apply(this,t)}return this};E.prototype.emitReserved=E.prototype.emit;E.prototype.listeners=function(r){return this._callbacks=this._callbacks||{},this._callbacks["$"+r]||[]};E.prototype.hasListeners=function(r){return!!this.listeners(r).length};const Ut=typeof Promise=="function"&&typeof Promise.resolve=="function"?t=>Promise.resolve().then(t):(t,e)=>e(t,0),R=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),vr="arraybuffer";function as(r,...t){return t.reduce((e,s)=>(r.hasOwnProperty(s)&&(e[s]=r[s]),e),{})}const Tr=R.setTimeout,Sr=R.clearTimeout;function jt(r,t){t.useNativeTimers?(r.setTimeoutFn=Tr.bind(R),r.clearTimeoutFn=Sr.bind(R)):(r.setTimeoutFn=R.setTimeout.bind(R),r.clearTimeoutFn=R.clearTimeout.bind(R))}const Ir=1.33;function Or(r){return typeof r=="string"?Ar(r):Math.ceil((r.byteLength||r.size)*Ir)}function Ar(r){let t=0,e=0;for(let s=0,n=r.length;s<n;s++)t=r.charCodeAt(s),t<128?e+=1:t<2048?e+=2:t<55296||t>=57344?e+=3:(s++,e+=4);return e}function cs(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function kr(r){let t="";for(let e in r)r.hasOwnProperty(e)&&(t.length&&(t+="&"),t+=encodeURIComponent(e)+"="+encodeURIComponent(r[e]));return t}function Cr(r){let t={},e=r.split("&");for(let s=0,n=e.length;s<n;s++){let i=e[s].split("=");t[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return t}class xr extends Error{constructor(t,e,s){super(t),this.description=e,this.context=s,this.type="TransportError"}}class Ae extends E{constructor(t){super(),this.writable=!1,jt(this,t),this.opts=t,this.query=t.query,this.socket=t.socket,this.supportsBinary=!t.forceBase64}onError(t,e,s){return super.emitReserved("error",new xr(t,e,s)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(t){this.readyState==="open"&&this.write(t)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(t){const e=Oe(t,this.socket.binaryType);this.onPacket(e)}onPacket(t){super.emitReserved("packet",t)}onClose(t){this.readyState="closed",super.emitReserved("close",t)}pause(t){}createUri(t,e={}){return t+"://"+this._hostname()+this._port()+this.opts.path+this._query(e)}_hostname(){const t=this.opts.hostname;return t.indexOf(":")===-1?t:"["+t+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(t){const e=kr(t);return e.length?"?"+e:""}}class Rr extends Ae{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(t){this.readyState="pausing";const e=()=>{this.readyState="paused",t()};if(this._polling||!this.writable){let s=0;this._polling&&(s++,this.once("pollComplete",function(){--s||e()})),this.writable||(s++,this.once("drain",function(){--s||e()}))}else e()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){const e=s=>{if(this.readyState==="opening"&&s.type==="open"&&this.onOpen(),s.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(s)};wr(t,this.socket.binaryType).forEach(e),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){const t=()=>{this.write([{type:"close"}])};this.readyState==="open"?t():this.once("open",t)}write(t){this.writable=!1,gr(t,e=>{this.doWrite(e,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const t=this.opts.secure?"https":"http",e=this.query||{};return this.opts.timestampRequests!==!1&&(e[this.opts.timestampParam]=cs()),!this.supportsBinary&&!e.sid&&(e.b64=1),this.createUri(t,e)}}let hs=!1;try{hs=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const $r=hs;function Nr(){}class Pr extends Rr{constructor(t){if(super(t),typeof location<"u"){const e=location.protocol==="https:";let s=location.port;s||(s=e?"443":"80"),this.xd=typeof location<"u"&&t.hostname!==location.hostname||s!==t.port}}doWrite(t,e){const s=this.request({method:"POST",data:t});s.on("success",e),s.on("error",(n,i)=>{this.onError("xhr post error",n,i)})}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(e,s)=>{this.onError("xhr poll error",e,s)}),this.pollXhr=t}}class L extends E{constructor(t,e,s){super(),this.createRequest=t,jt(this,s),this._opts=s,this._method=s.method||"GET",this._uri=e,this._data=s.data!==void 0?s.data:null,this._create()}_create(){var t;const e=as(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");e.xdomain=!!this._opts.xd;const s=this._xhr=this.createRequest(e);try{s.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){s.setDisableHeaderCheck&&s.setDisableHeaderCheck(!0);for(let n in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(n)&&s.setRequestHeader(n,this._opts.extraHeaders[n])}}catch{}if(this._method==="POST")try{s.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{s.setRequestHeader("Accept","*/*")}catch{}(t=this._opts.cookieJar)===null||t===void 0||t.addCookies(s),"withCredentials"in s&&(s.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(s.timeout=this._opts.requestTimeout),s.onreadystatechange=()=>{var n;s.readyState===3&&((n=this._opts.cookieJar)===null||n===void 0||n.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(n){this.setTimeoutFn(()=>{this._onError(n)},0);return}typeof document<"u"&&(this._index=L.requestsCount++,L.requests[this._index]=this)}_onError(t){this.emitReserved("error",t,this._xhr),this._cleanup(!0)}_cleanup(t){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=Nr,t)try{this._xhr.abort()}catch{}typeof document<"u"&&delete L.requests[this._index],this._xhr=null}}_onLoad(){const t=this._xhr.responseText;t!==null&&(this.emitReserved("data",t),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}L.requestsCount=0;L.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",Ge);else if(typeof addEventListener=="function"){const r="onpagehide"in R?"pagehide":"unload";addEventListener(r,Ge,!1)}}function Ge(){for(let r in L.requests)L.requests.hasOwnProperty(r)&&L.requests[r].abort()}const Br=function(){const r=ls({xdomain:!1});return r&&r.responseType!==null}();class Lr extends Pr{constructor(t){super(t);const e=t&&t.forceBase64;this.supportsBinary=Br&&!e}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new L(ls,this.uri(),t)}}function ls(r){const t=r.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!t||$r))return new XMLHttpRequest}catch{}if(!t)try{return new R[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const us=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class Fr extends Ae{get name(){return"websocket"}doOpen(){const t=this.uri(),e=this.opts.protocols,s=us?{}:as(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(s.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(t,e,s)}catch(n){return this.emitReserved("error",n)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const s=t[e],n=e===t.length-1;Ie(s,this.supportsBinary,i=>{try{this.doWrite(s,i)}catch{}n&&Ut(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const t=this.opts.secure?"wss":"ws",e=this.query||{};return this.opts.timestampRequests&&(e[this.opts.timestampParam]=cs()),this.supportsBinary||(e.b64=1),this.createUri(t,e)}}const Xt=R.WebSocket||R.MozWebSocket;class qr extends Fr{createSocket(t,e,s){return us?new Xt(t,e,s):e?new Xt(t,e):new Xt(t)}doWrite(t,e){this.ws.send(e)}}class Dr extends Ae{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(t){return this.emitReserved("error",t)}this._transport.closed.then(()=>{this.onClose()}).catch(t=>{this.onError("webtransport error",t)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(t=>{const e=_r(Number.MAX_SAFE_INTEGER,this.socket.binaryType),s=t.readable.pipeThrough(e).getReader(),n=br();n.readable.pipeTo(t.writable),this._writer=n.writable.getWriter();const i=()=>{s.read().then(({done:h,value:d})=>{h||(this.onPacket(d),i())}).catch(h=>{})};i();const o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this._writer.write(o).then(()=>this.onOpen())})})}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const s=t[e],n=e===t.length-1;this._writer.write(s).then(()=>{n&&Ut(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this._transport)===null||t===void 0||t.close()}}const Mr={websocket:qr,webtransport:Dr,polling:Lr},Ur=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,jr=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function ee(r){if(r.length>8e3)throw"URI too long";const t=r,e=r.indexOf("["),s=r.indexOf("]");e!=-1&&s!=-1&&(r=r.substring(0,e)+r.substring(e,s).replace(/:/g,";")+r.substring(s,r.length));let n=Ur.exec(r||""),i={},o=14;for(;o--;)i[jr[o]]=n[o]||"";return e!=-1&&s!=-1&&(i.source=t,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=Vr(i,i.path),i.queryKey=Gr(i,i.query),i}function Vr(r,t){const e=/\/{2,9}/g,s=t.replace(e,"/").split("/");return(t.slice(0,1)=="/"||t.length===0)&&s.splice(0,1),t.slice(-1)=="/"&&s.splice(s.length-1,1),s}function Gr(r,t){const e={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(s,n,i){n&&(e[n]=i)}),e}const se=typeof addEventListener=="function"&&typeof removeEventListener=="function",Rt=[];se&&addEventListener("offline",()=>{Rt.forEach(r=>r())},!1);class z extends E{constructor(t,e){if(super(),this.binaryType=vr,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,t&&typeof t=="object"&&(e=t,t=null),t){const s=ee(t);e.hostname=s.host,e.secure=s.protocol==="https"||s.protocol==="wss",e.port=s.port,s.query&&(e.query=s.query)}else e.host&&(e.hostname=ee(e.host).host);jt(this,e),this.secure=e.secure!=null?e.secure:typeof location<"u"&&location.protocol==="https:",e.hostname&&!e.port&&(e.port=this.secure?"443":"80"),this.hostname=e.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=e.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},e.transports.forEach(s=>{const n=s.prototype.name;this.transports.push(n),this._transportsByName[n]=s}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},e),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=Cr(this.opts.query)),se&&(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"})},Rt.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(t){const e=Object.assign({},this.opts.query);e.EIO=os,e.transport=t,this.id&&(e.sid=this.id);const s=Object.assign({},this.opts,{query:e,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new this._transportsByName[t](s)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const t=this.opts.rememberUpgrade&&z.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const e=this.createTransport(t);e.open(),this.setTransport(e)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",e=>this._onClose("transport close",e))}onOpen(){this.readyState="open",z.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",t),this.emitReserved("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const e=new Error("server error");e.code=t.data,this._onError(e);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data);break}}onHandshake(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this._pingInterval=t.pingInterval,this._pingTimeout=t.pingTimeout,this._maxPayload=t.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const t=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+t,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},t),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const t=this._getWritablePackets();this.transport.send(t),this._prevBufferLen=t.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let s=0;s<this.writeBuffer.length;s++){const n=this.writeBuffer[s].data;if(n&&(e+=Or(n)),s>0&&e>this._maxPayload)return this.writeBuffer.slice(0,s);e+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const t=Date.now()>this._pingTimeoutTime;return t&&(this._pingTimeoutTime=0,Ut(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),t}write(t,e,s){return this._sendPacket("message",t,e,s),this}send(t,e,s){return this._sendPacket("message",t,e,s),this}_sendPacket(t,e,s,n){if(typeof e=="function"&&(n=e,e=void 0),typeof s=="function"&&(n=s,s=null),this.readyState==="closing"||this.readyState==="closed")return;s=s||{},s.compress=s.compress!==!1;const i={type:t,data:e,options:s};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),n&&this.once("flush",n),this.flush()}close(){const t=()=>{this._onClose("forced close"),this.transport.close()},e=()=>{this.off("upgrade",e),this.off("upgradeError",e),t()},s=()=>{this.once("upgrade",e),this.once("upgradeError",e)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?s():t()}):this.upgrading?s():t()),this}_onError(t){if(z.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",t),this._onClose("transport error",t)}_onClose(t,e){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),se&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const s=Rt.indexOf(this._offlineEventListener);s!==-1&&Rt.splice(s,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,e),this.writeBuffer=[],this._prevBufferLen=0}}}z.protocol=os;class Hr extends z{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let t=0;t<this._upgrades.length;t++)this._probe(this._upgrades[t])}_probe(t){let e=this.createTransport(t),s=!1;z.priorWebsocketSuccess=!1;const n=()=>{s||(e.send([{type:"ping",data:"probe"}]),e.once("packet",g=>{if(!s)if(g.type==="pong"&&g.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",e),!e)return;z.priorWebsocketSuccess=e.name==="websocket",this.transport.pause(()=>{s||this.readyState!=="closed"&&(c(),this.setTransport(e),e.send([{type:"upgrade"}]),this.emitReserved("upgrade",e),e=null,this.upgrading=!1,this.flush())})}else{const v=new Error("probe error");v.transport=e.name,this.emitReserved("upgradeError",v)}}))};function i(){s||(s=!0,c(),e.close(),e=null)}const o=g=>{const v=new Error("probe error: "+g);v.transport=e.name,i(),this.emitReserved("upgradeError",v)};function h(){o("transport closed")}function d(){o("socket closed")}function f(g){e&&g.name!==e.name&&i()}const c=()=>{e.removeListener("open",n),e.removeListener("error",o),e.removeListener("close",h),this.off("close",d),this.off("upgrading",f)};e.once("open",n),e.once("error",o),e.once("close",h),this.once("close",d),this.once("upgrading",f),this._upgrades.indexOf("webtransport")!==-1&&t!=="webtransport"?this.setTimeoutFn(()=>{s||e.open()},200):e.open()}onHandshake(t){this._upgrades=this._filterUpgrades(t.upgrades),super.onHandshake(t)}_filterUpgrades(t){const e=[];for(let s=0;s<t.length;s++)~this.transports.indexOf(t[s])&&e.push(t[s]);return e}}let Jr=class extends Hr{constructor(t,e={}){const s=typeof t=="object",n=s?{...t}:{...e};(!n.transports||n.transports&&typeof n.transports[0]=="string")&&(n.transports=(n.transports||["polling","websocket","webtransport"]).map(i=>Mr[i]).filter(i=>!!i)),super(s?n:t,n)}};function Yr(r,t="",e){let s=r;e=e||typeof location<"u"&&location,r==null&&(r=e.protocol+"//"+e.host),typeof r=="string"&&(r.charAt(0)==="/"&&(r.charAt(1)==="/"?r=e.protocol+r:r=e.host+r),/^(https?|wss?):\/\//.test(r)||(typeof e<"u"?r=e.protocol+"//"+r:r="https://"+r),s=ee(r)),s.port||(/^(http|ws)$/.test(s.protocol)?s.port="80":/^(http|ws)s$/.test(s.protocol)&&(s.port="443")),s.path=s.path||"/";const i=s.host.indexOf(":")!==-1?"["+s.host+"]":s.host;return s.id=s.protocol+"://"+i+":"+s.port+t,s.href=s.protocol+"://"+i+(e&&e.port===s.port?"":":"+s.port),s}const Wr=typeof ArrayBuffer=="function",Kr=r=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(r):r.buffer instanceof ArrayBuffer,ds=Object.prototype.toString,Xr=typeof Blob=="function"||typeof Blob<"u"&&ds.call(Blob)==="[object BlobConstructor]",zr=typeof File=="function"||typeof File<"u"&&ds.call(File)==="[object FileConstructor]";function ke(r){return Wr&&(r instanceof ArrayBuffer||Kr(r))||Xr&&r instanceof Blob||zr&&r instanceof File}function $t(r,t){if(!r||typeof r!="object")return!1;if(Array.isArray(r)){for(let e=0,s=r.length;e<s;e++)if($t(r[e]))return!0;return!1}if(ke(r))return!0;if(r.toJSON&&typeof r.toJSON=="function"&&arguments.length===1)return $t(r.toJSON(),!0);for(const e in r)if(Object.prototype.hasOwnProperty.call(r,e)&&$t(r[e]))return!0;return!1}function Qr(r){const t=[],e=r.data,s=r;return s.data=re(e,t),s.attachments=t.length,{packet:s,buffers:t}}function re(r,t){if(!r)return r;if(ke(r)){const e={_placeholder:!0,num:t.length};return t.push(r),e}else if(Array.isArray(r)){const e=new Array(r.length);for(let s=0;s<r.length;s++)e[s]=re(r[s],t);return e}else if(typeof r=="object"&&!(r instanceof Date)){const e={};for(const s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=re(r[s],t));return e}return r}function Zr(r,t){return r.data=ne(r.data,t),delete r.attachments,r}function ne(r,t){if(!r)return r;if(r&&r._placeholder===!0){if(typeof r.num=="number"&&r.num>=0&&r.num<t.length)return t[r.num];throw new Error("illegal attachments")}else if(Array.isArray(r))for(let e=0;e<r.length;e++)r[e]=ne(r[e],t);else if(typeof r=="object")for(const e in r)Object.prototype.hasOwnProperty.call(r,e)&&(r[e]=ne(r[e],t));return r}const tn=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var w;(function(r){r[r.CONNECT=0]="CONNECT",r[r.DISCONNECT=1]="DISCONNECT",r[r.EVENT=2]="EVENT",r[r.ACK=3]="ACK",r[r.CONNECT_ERROR=4]="CONNECT_ERROR",r[r.BINARY_EVENT=5]="BINARY_EVENT",r[r.BINARY_ACK=6]="BINARY_ACK"})(w||(w={}));class en{constructor(t){this.replacer=t}encode(t){return(t.type===w.EVENT||t.type===w.ACK)&&$t(t)?this.encodeAsBinary({type:t.type===w.EVENT?w.BINARY_EVENT:w.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id}):[this.encodeAsString(t)]}encodeAsString(t){let e=""+t.type;return(t.type===w.BINARY_EVENT||t.type===w.BINARY_ACK)&&(e+=t.attachments+"-"),t.nsp&&t.nsp!=="/"&&(e+=t.nsp+","),t.id!=null&&(e+=t.id),t.data!=null&&(e+=JSON.stringify(t.data,this.replacer)),e}encodeAsBinary(t){const e=Qr(t),s=this.encodeAsString(e.packet),n=e.buffers;return n.unshift(s),n}}class Ce extends E{constructor(t){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},typeof t=="function"?{reviver:t}:t)}add(t){let e;if(typeof t=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");e=this.decodeString(t);const s=e.type===w.BINARY_EVENT;s||e.type===w.BINARY_ACK?(e.type=s?w.EVENT:w.ACK,this.reconstructor=new sn(e),e.attachments===0&&super.emitReserved("decoded",e)):super.emitReserved("decoded",e)}else if(ke(t)||t.base64)if(this.reconstructor)e=this.reconstructor.takeBinaryData(t),e&&(this.reconstructor=null,super.emitReserved("decoded",e));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+t)}decodeString(t){let e=0;const s={type:Number(t.charAt(0))};if(w[s.type]===void 0)throw new Error("unknown packet type "+s.type);if(s.type===w.BINARY_EVENT||s.type===w.BINARY_ACK){const i=e+1;for(;t.charAt(++e)!=="-"&&e!=t.length;);const o=t.substring(i,e);if(o!=Number(o)||t.charAt(e)!=="-")throw new Error("Illegal attachments");const h=Number(o);if(!rn(h)||h<0)throw new Error("Illegal attachments");if(h>this.opts.maxAttachments)throw new Error("too many attachments");s.attachments=h}if(t.charAt(e+1)==="/"){const i=e+1;for(;++e&&!(t.charAt(e)===","||e===t.length););s.nsp=t.substring(i,e)}else s.nsp="/";const n=t.charAt(e+1);if(n!==""&&Number(n)==n){const i=e+1;for(;++e;){const o=t.charAt(e);if(o==null||Number(o)!=o){--e;break}if(e===t.length)break}s.id=Number(t.substring(i,e+1))}if(t.charAt(++e)){const i=this.tryParse(t.substr(e));if(Ce.isPayloadValid(s.type,i))s.data=i;else throw new Error("invalid payload")}return s}tryParse(t){try{return JSON.parse(t,this.opts.reviver)}catch{return!1}}static isPayloadValid(t,e){switch(t){case w.CONNECT:return He(e);case w.DISCONNECT:return e===void 0;case w.CONNECT_ERROR:return typeof e=="string"||He(e);case w.EVENT:case w.BINARY_EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&tn.indexOf(e[0])===-1);case w.ACK:case w.BINARY_ACK:return Array.isArray(e)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class sn{constructor(t){this.packet=t,this.buffers=[],this.reconPack=t}takeBinaryData(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){const e=Zr(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const rn=Number.isInteger||function(r){return typeof r=="number"&&isFinite(r)&&Math.floor(r)===r};function He(r){return Object.prototype.toString.call(r)==="[object Object]"}const nn=Object.freeze(Object.defineProperty({__proto__:null,Decoder:Ce,Encoder:en,get PacketType(){return w}},Symbol.toStringTag,{value:"Module"}));function N(r,t,e){return r.on(t,e),function(){r.off(t,e)}}const on=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class fs extends E{constructor(t,e,s){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=t,this.nsp=e,s&&s.auth&&(this.auth=s.auth),this._opts=Object.assign({},s),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const t=this.io;this.subs=[N(t,"open",this.onopen.bind(this)),N(t,"packet",this.onpacket.bind(this)),N(t,"error",this.onerror.bind(this)),N(t,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...t){return t.unshift("message"),this.emit.apply(this,t),this}emit(t,...e){var s,n,i;if(on.hasOwnProperty(t))throw new Error('"'+t.toString()+'" is a reserved event name');if(e.unshift(t),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(e),this;const o={type:w.EVENT,data:e};if(o.options={},o.options.compress=this.flags.compress!==!1,typeof e[e.length-1]=="function"){const c=this.ids++,g=e.pop();this._registerAckCallback(c,g),o.id=c}const h=(n=(s=this.io.engine)===null||s===void 0?void 0:s.transport)===null||n===void 0?void 0:n.writable,d=this.connected&&!(!((i=this.io.engine)===null||i===void 0)&&i._hasPingExpired());return this.flags.volatile&&!h||(d?(this.notifyOutgoingListeners(o),this.packet(o)):this.sendBuffer.push(o)),this.flags={},this}_registerAckCallback(t,e){var s;const n=(s=this.flags.timeout)!==null&&s!==void 0?s:this._opts.ackTimeout;if(n===void 0){this.acks[t]=e;return}const i=this.io.setTimeoutFn(()=>{delete this.acks[t];for(let h=0;h<this.sendBuffer.length;h++)this.sendBuffer[h].id===t&&this.sendBuffer.splice(h,1);e.call(this,new Error("operation has timed out"))},n),o=(...h)=>{this.io.clearTimeoutFn(i),e.apply(this,h)};o.withError=!0,this.acks[t]=o}emitWithAck(t,...e){return new Promise((s,n)=>{const i=(o,h)=>o?n(o):s(h);i.withError=!0,e.push(i),this.emit(t,...e)})}_addToQueue(t){let e;typeof t[t.length-1]=="function"&&(e=t.pop());const s={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((n,...i)=>(this._queue[0],n!==null?s.tryCount>this._opts.retries&&(this._queue.shift(),e&&e(n)):(this._queue.shift(),e&&e(null,...i)),s.pending=!1,this._drainQueue())),this._queue.push(s),this._drainQueue()}_drainQueue(t=!1){if(!this.connected||this._queue.length===0)return;const e=this._queue[0];e.pending&&!t||(e.pending=!0,e.tryCount++,this.flags=e.flags,this.emit.apply(this,e.args))}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){typeof this.auth=="function"?this.auth(t=>{this._sendConnectPacket(t)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:w.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,e){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,e),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(t=>{if(!this.sendBuffer.some(s=>String(s.id)===t)){const s=this.acks[t];delete this.acks[t],s.withError&&s.call(this,new Error("socket has been disconnected"))}})}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case w.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case w.EVENT:case w.BINARY_EVENT:this.onevent(t);break;case w.ACK:case w.BINARY_ACK:this.onack(t);break;case w.DISCONNECT:this.ondisconnect();break;case w.CONNECT_ERROR:this.destroy();const s=new Error(t.data.message);s.data=t.data.data,this.emitReserved("connect_error",s);break}}onevent(t){const e=t.data||[];t.id!=null&&e.push(this.ack(t.id)),this.connected?this.emitEvent(e):this.receiveBuffer.push(Object.freeze(e))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){const e=this._anyListeners.slice();for(const s of e)s.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&typeof t[t.length-1]=="string"&&(this._lastOffset=t[t.length-1])}ack(t){const e=this;let s=!1;return function(...n){s||(s=!0,e.packet({type:w.ACK,id:t,data:n}))}}onack(t){const e=this.acks[t.id];typeof e=="function"&&(delete this.acks[t.id],e.withError&&t.data.unshift(null),e.apply(this,t.data))}onconnect(t,e){this.id=t,this.recovered=e&&this._pid===e,this._pid=e,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:w.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){const e=this._anyListeners;for(let s=0;s<e.length;s++)if(t===e[s])return e.splice(s,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(t),this}prependAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(t),this}offAnyOutgoing(t){if(!this._anyOutgoingListeners)return this;if(t){const e=this._anyOutgoingListeners;for(let s=0;s<e.length;s++)if(t===e[s])return e.splice(s,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(t){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const e=this._anyOutgoingListeners.slice();for(const s of e)s.apply(this,t.data)}}}function ft(r){r=r||{},this.ms=r.min||100,this.max=r.max||1e4,this.factor=r.factor||2,this.jitter=r.jitter>0&&r.jitter<=1?r.jitter:0,this.attempts=0}ft.prototype.duration=function(){var r=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),e=Math.floor(t*this.jitter*r);r=Math.floor(t*10)&1?r+e:r-e}return Math.min(r,this.max)|0};ft.prototype.reset=function(){this.attempts=0};ft.prototype.setMin=function(r){this.ms=r};ft.prototype.setMax=function(r){this.max=r};ft.prototype.setJitter=function(r){this.jitter=r};class ie extends E{constructor(t,e){var s;super(),this.nsps={},this.subs=[],t&&typeof t=="object"&&(e=t,t=void 0),e=e||{},e.path=e.path||"/socket.io",this.opts=e,jt(this,e),this.reconnection(e.reconnection!==!1),this.reconnectionAttempts(e.reconnectionAttempts||1/0),this.reconnectionDelay(e.reconnectionDelay||1e3),this.reconnectionDelayMax(e.reconnectionDelayMax||5e3),this.randomizationFactor((s=e.randomizationFactor)!==null&&s!==void 0?s:.5),this.backoff=new ft({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(e.timeout==null?2e4:e.timeout),this._readyState="closed",this.uri=t;const n=e.parser||nn;this.encoder=new n.Encoder,this.decoder=new n.Decoder,this._autoConnect=e.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,t||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(t){return t===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var e;return t===void 0?this._reconnectionDelay:(this._reconnectionDelay=t,(e=this.backoff)===null||e===void 0||e.setMin(t),this)}randomizationFactor(t){var e;return t===void 0?this._randomizationFactor:(this._randomizationFactor=t,(e=this.backoff)===null||e===void 0||e.setJitter(t),this)}reconnectionDelayMax(t){var e;return t===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,(e=this.backoff)===null||e===void 0||e.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(t){if(~this._readyState.indexOf("open"))return this;this.engine=new Jr(this.uri,this.opts);const e=this.engine,s=this;this._readyState="opening",this.skipReconnect=!1;const n=N(e,"open",function(){s.onopen(),t&&t()}),i=h=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",h),t?t(h):this.maybeReconnectOnOpen()},o=N(e,"error",i);if(this._timeout!==!1){const h=this._timeout,d=this.setTimeoutFn(()=>{n(),i(new Error("timeout")),e.close()},h);this.opts.autoUnref&&d.unref(),this.subs.push(()=>{this.clearTimeoutFn(d)})}return this.subs.push(n),this.subs.push(o),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(N(t,"ping",this.onping.bind(this)),N(t,"data",this.ondata.bind(this)),N(t,"error",this.onerror.bind(this)),N(t,"close",this.onclose.bind(this)),N(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(e){this.onclose("parse error",e)}}ondecoded(t){Ut(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,e){let s=this.nsps[t];return s?this._autoConnect&&!s.active&&s.connect():(s=new fs(this,t,e),this.nsps[t]=s),s}_destroy(t){const e=Object.keys(this.nsps);for(const s of e)if(this.nsps[s].active)return;this._close()}_packet(t){const e=this.encoder.encode(t);for(let s=0;s<e.length;s++)this.engine.write(e[s],t.options)}cleanup(){this.subs.forEach(t=>t()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(t,e){var s;this.cleanup(),(s=this.engine)===null||s===void 0||s.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,e),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const e=this.backoff.duration();this._reconnecting=!0;const s=this.setTimeoutFn(()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),!t.skipReconnect&&t.open(n=>{n?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",n)):t.onreconnect()}))},e);this.opts.autoUnref&&s.unref(),this.subs.push(()=>{this.clearTimeoutFn(s)})}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const pt={};function bt(r,t){typeof r=="object"&&(t=r,r=void 0),t=t||{};const e=Yr(r,t.path||"/socket.io"),s=e.source,n=e.id,i=e.path,o=pt[n]&&i in pt[n].nsps,h=t.forceNew||t["force new connection"]||t.multiplex===!1||o;let d;return h?d=new ie(s,t):(pt[n]||(pt[n]=new ie(s,t)),d=pt[n]),e.query&&!t.query&&(t.query=e.queryKey),d.socket(e.path,t)}Object.assign(bt,{Manager:ie,Socket:fs,io:bt,connect:bt});const _t="thatopen/document@1",oe="document.json",ps=["pdf","txt","md","json","csv","tsv","frag"],Je=()=>`v-${Date.now()}`;function kt(r){return String(r._id??r.id??"")}var tt,ys,ae;class xe{constructor(t,e){b(this,tt);this.client=t,this.projectId=e}async list(){const t=await this.client.listFolders({projectId:this.projectId});return(await Promise.all(t.map(async s=>{const n=kt(s),i=await this.descriptor(n);return i?{folderId:n,descriptor:i}:null}))).filter(s=>s!==null)}async fromFile(t,e){const s=await this.client.getFile(t),n=String(s.name??""),i=Ye(n,s.fileExtension),o=(e==null?void 0:e.name)??n.replace(/\.[^.]+$/,"")??n,h=await this.client.createFolder(o,s.folderId?String(s.folderId):void 0,this.projectId),d=kt(h);await this.client.updateFile(t,{parentFolderId:d});const f=[],c=await a(this,tt,ys).call(this,s);if(c)try{const V=await this.client.getFile(c);await this.client.updateFile(c,{parentFolderId:d}),f.push({fileId:c,format:Ye(String(V.name??""),V.fileExtension)})}catch{}((e==null?void 0:e.selfView)??ps.includes(i))&&f.push({fileId:t,format:i});const v={schema:_t,name:o,native:{fileId:t,format:i},views:f};return await this.setDescriptor(d,v),{folderId:d,descriptor:v}}async descriptor(t){const e=await a(this,tt,ae).call(this,t);if(!e)return null;const n=await(await this.client.downloadFile(e.id)).text();if(!n.trim())return null;let i;try{i=JSON.parse(n)}catch{return null}return an(i)}async view(t,e){const s=await this.descriptor(t);if(!s)return null;for(const n of e){const i=s.views.find(o=>o.format===n);if(i)return i}return null}async addView(t,e){const s=await this.descriptor(t);if(!s)throw new Error("This folder has no document descriptor yet: call setDescriptor first.");s.views=[...s.views.filter(n=>n.format!==e.format),e],await this.setDescriptor(t,s)}async setDescriptor(t,e){const s={...e,schema:_t,views:e.views??[]},n=new Blob([JSON.stringify(s)],{type:"application/json"}),i=await a(this,tt,ae).call(this,t);if(i){await this.client.updateFile(i.id,{file:n,versionTag:Je()});return}await this.client.createFile({file:n,name:oe,versionTag:Je(),parentFolderId:t,projectId:this.projectId})}}tt=new WeakSet,ys=async function(t){const e=[...t.versions??[]].sort((s,n)=>String(n.createdAt??"").localeCompare(String(s.createdAt??"")));for(const s of e)try{const n=await this.client.getFileVersionMetadata(kt(t),s.tag),i=n==null?void 0:n.derivedFileId;if(typeof i=="string"&&i)return i}catch{}},ae=async function(t){const s=(await this.client.listFiles({folderId:t})).find(n=>String(n.name??"")===oe);return s?{id:kt(s)}:void 0};function Ye(r,t){const e=(t??"").replace(/^\./,"").toLowerCase();if(e)return e;const s=r.lastIndexOf(".");return s>0?r.slice(s+1).toLowerCase():""}function an(r){if(!r||typeof r!="object")return null;const t=r;if(t.schema!==_t||typeof t.name!="string")return null;const e=Array.isArray(t.views)?t.views.filter(i=>!!i&&typeof i=="object"&&typeof i.fileId=="string"&&typeof i.format=="string"):[],s=t.native,n=!!s&&typeof s=="object"&&typeof s.fileId=="string"&&typeof s.format=="string";return{schema:_t,name:t.name,...n?{native:{fileId:s.fileId,format:s.format}}:{},views:e}}class ce extends Error{constructor(t,e){super(`The document history advanced while this version was being prepared: expected head ${t}, found ${e??"none"}. Read the timeline again and rebuild on the new head.`),this.expectedGuid=t,this.actualGuid=e,this.name="StaleHistoryError"}}const We="bimterop",he="revitflow_history.json",rt="revitflow_ops.json",Ke="revitflow/ops@1",ms="revitflow_model.frag",gs="revitflow_",cn="bimterop-locks-anchor",Ct=()=>`v-${Date.now()}`;function ws(r,t){return r.filter(e=>String(e.parentId??"")===t)}function B(r){return String(r._id??r.id??"")}var $,Et,le;class bs{constructor(t,e){b(this,Et);b(this,$);this.client=t,this.projectId=e}async docs(){const t=await a(this,Et,le).call(this);if(!t)return[];const e=await this.client.listFolders({parentFolderId:t,projectId:this.projectId}),s=[];for(const n of ws(e,t)){const i=String(n.name??""),o=i.indexOf("-");if(o<=0)continue;const d=(await this.client.listFiles({folderId:B(n)})).map(g=>String(g.name??"")),f=d.find(g=>g===ms)??d.find(g=>g.endsWith(".frag")&&!g.startsWith(gs)),c=d.includes(he)||d.includes(rt)||!!f;s.push({source:i.slice(0,o),docId:i.slice(o+1),folderId:B(n),modelName:f,...c?{}:{empty:!0}})}return s}doc(t,e){return new _s(this.client,this,t,e)}async rootFolderId(t=!1){if(u(this,$))return u(this,$);const e=await a(this,Et,le).call(this);if(e)return e;if(!t)return;const s=await this.client.createFolder(We,void 0,this.projectId);return _(this,$,B(s)),u(this,$)}}$=new WeakMap,Et=new WeakSet,le=async function(){if(u(this,$))return u(this,$);const e=(await this.client.listFolders({projectId:this.projectId})).find(s=>String(s.name??"")===We&&!s.parentId);return e&&_(this,$,B(e)),u(this,$)};var M,p,nt,it,D,ue,mt,ot,de,Nt,gt,Pt,fe,Es;class _s{constructor(t,e,s,n){b(this,p);b(this,M);this.client=t,this.project=e,this.source=s,this.docId=n}async timeline(){const t=await a(this,p,Nt).call(this);return Re((t==null?void 0:t.commits)??[])}async latest(){const t=await this.timeline();return t.length?t[t.length-1]:null}async delta(t){if(!t.deltaId)throw new Error(`Version ${t.guid} carries no delta: it is a full export — read model() instead.`);return await(await this.client.downloadHiddenFile(t.deltaId)).blob()}async model(){const t=await a(this,p,ot).call(this);if(!t)throw new Error(`Document ${this.source}-${this.docId} has no model file yet.`);return await(await this.client.downloadFile(t.id)).blob()}async folderId(){return await a(this,p,D).call(this,!1)}async descriptor(){return await u(this,p,nt).descriptor(await a(this,p,D).call(this,!1))}async view(t){const e=await a(this,p,D).call(this,!1),s=await u(this,p,nt).descriptor(e);if(s){for(const i of t){const o=s.views.find(h=>h.format===i);if(o)return o}return null}if(!t.includes("frag"))return null;const n=await a(this,p,ot).call(this);return n?{fileId:n.id,format:"frag"}:null}async addView(t){const e=await a(this,p,D).call(this,!0);if(await u(this,p,nt).descriptor(e)){await u(this,p,nt).addView(e,t);return}const n=await a(this,p,ot).call(this);await u(this,p,nt).setDescriptor(e,{name:(n==null?void 0:n.name.replace(/\.frag$/,""))??u(this,p,it),views:[t]})}async ownership(){const t=await a(this,p,mt).call(this,cn);if(!t)return[];const e=await this.client.getHiddenFilesByParent(t.id),s=await Promise.all(e.map(async o=>{try{const h=B(o),d=await this.client.downloadHiddenFile(h),f=JSON.parse(await d.text());return!f||typeof f!="object"||!("revitflowlock"in f)||!Array.isArray(f.keys)?null:{owner:String(f.user??""),keys:f.keys.filter(c=>typeof c=="string")}}catch{return null}})),n=new Set,i=new Map;for(const o of s)if(o)for(const h of o.keys){if(!h||n.has(h))continue;n.add(h);const d=i.get(o.owner)??[];d.push(h),i.set(o.owner,d)}return[...i.entries()].map(([o,h])=>({owner:o,elements:h}))}async sync(t){var h;const e=await a(this,p,D).call(this,!0);let s=await a(this,p,Nt).call(this)??{model:this.docId,commits:[]};const n=Xe(s.commits);if(t.expectedLatestGuid!==void 0&&(n==null?void 0:n.guid)!==t.expectedLatestGuid)throw new ce(t.expectedLatestGuid,n==null?void 0:n.guid);const i={guid:Dt(),...n?{parents:[n.guid]}:{},author:t.author,source:t.source,timestamp:new Date().toISOString(),...t.message?{message:t.message}:{},...t.userId?{userId:t.userId}:{},...(h=t.appliedOps)!=null&&h.length?{appliedOps:t.appliedOps}:{},changes:t.changes,counts:hn(t.changes)};if(t.model&&(await a(this,p,Es).call(this,e,t.model),i.full=!0),t.delta){const d=await a(this,p,ot).call(this);if(!d)throw new Error("A delta needs the model file to hang from: sync a full model first.");const f=await this.client.createHiddenFile(t.delta,d.id);i.deltaId=String(f._id??f.id)}const o=await a(this,p,Nt).call(this);if(o){s=o;const d=Xe(s.commits);if(t.expectedLatestGuid!==void 0&&(d==null?void 0:d.guid)!==t.expectedLatestGuid)throw new ce(t.expectedLatestGuid,d==null?void 0:d.guid);d&&!i.parents&&(i.parents=[d.guid])}return s.commits.push(i),await a(this,p,Pt).call(this,e,he,s),i}async suggestions(){const t=await a(this,p,gt).call(this);return(t==null?void 0:t.ops)??[]}async pendingSuggestions(){return(await this.suggestions()).filter(t=>t.state==="pending")}async suggest(t){const e=await a(this,p,D).call(this,!0),s=await a(this,p,gt).call(this)??{schema:Ke,ops:[]},n=await a(this,p,mt).call(this,rt),i={opId:t.opId??Dt(),to:t.to??this.source,title:t.title,verb:t.verb,author:t.author,createdAt:new Date().toISOString(),state:"pending",...t.targets!==void 0?{targets:t.targets}:{},...t.batchId?{batchId:t.batchId}:{},...t.userId?{userId:t.userId}:{},...t.baseCommitGuid?{baseCommitGuid:t.baseCommitGuid}:{}};if(t.payload){const h=n??await a(this,p,fe).call(this,e,rt,s),d=await this.client.createHiddenFile(t.payload,h.id);i.fragId=String(d._id??d.id)}const o=await a(this,p,gt).call(this)??s;return o.schema??(o.schema=Ke),o.ops.push(i),await a(this,p,Pt).call(this,e,rt,o),i}async suggestionPayload(t){if(!t.fragId)throw new Error(`Suggestion ${t.opId} carries no payload.`);return await(await this.client.downloadHiddenFile(t.fragId)).blob()}async resolveSuggestion(t,e){const s=await a(this,p,D).call(this,!1);if(!s)throw new Error("This document has no suggestion queue.");const n=await a(this,p,gt).call(this),i=n==null?void 0:n.ops.find(o=>o.opId===t);if(!n||!i)throw new Error(`No suggestion ${t} in this document's queue.`);return Object.assign(i,e),await a(this,p,Pt).call(this,s,rt,n),i}}M=new WeakMap,p=new WeakSet,nt=function(){return new xe(this.client,this.project.projectId)},it=function(){return`${this.source}-${this.docId}`},D=async function(t){if(u(this,M))return u(this,M);const e=await this.project.rootFolderId(t);if(!e)throw new Error(`Project ${this.project.projectId} has no connected documents yet.`);const s=await this.client.listFolders({parentFolderId:e,projectId:this.project.projectId}),n=ws(s,e).find(o=>String(o.name??"")===u(this,p,it));if(n)return _(this,M,B(n)),u(this,M);if(!t)throw new Error(`Document ${u(this,p,it)} does not exist in this project.`);const i=await this.client.createFolder(u(this,p,it),e,this.project.projectId);return _(this,M,B(i)),u(this,M)},ue=async function(){const t=await a(this,p,D).call(this,!1);return(await this.client.listFiles({folderId:t})).map(s=>({id:B(s),name:String(s.name??"")}))},mt=async function(t){try{return(await a(this,p,ue).call(this)).find(e=>e.name===t)}catch{return}},ot=async function(){try{const t=await a(this,p,ue).call(this);return t.find(e=>e.name===ms)??t.find(e=>e.name.endsWith(".frag")&&!e.name.startsWith(gs))}catch{return}},de=async function(t){const e=await a(this,p,mt).call(this,t);if(!e)return;const n=await(await this.client.downloadFile(e.id)).text();if(n.trim())return JSON.parse(n)},Nt=function(){return a(this,p,de).call(this,he)},gt=function(){return a(this,p,de).call(this,rt)},Pt=async function(t,e,s){const n=new Blob([JSON.stringify(s)],{type:"application/json"}),i=await a(this,p,mt).call(this,e);return i?(await this.client.updateFile(i.id,{file:n,versionTag:Ct()}),i):await a(this,p,fe).call(this,t,e,s)},fe=async function(t,e,s){const n=new Blob([JSON.stringify(s)],{type:"application/json"}),i=await this.client.createFile({file:n,name:e,versionTag:Ct(),parentFolderId:t,projectId:this.project.projectId}),o=i.item;return{id:B(o??i),name:e}},Es=async function(t,e){const s=await a(this,p,ot).call(this);if(s)return await this.client.updateFile(s.id,{file:e,versionTag:Ct()}),s;const n=`${u(this,p,it)}.frag`,i=await this.client.createFile({file:e,name:n,versionTag:Ct(),parentFolderId:t,projectId:this.project.projectId}),o=i.item;return{id:B(o??i),name:n}};function hn(r){const t={added:0,modified:0,removed:0};for(const e of r)e.type==="create"?t.added++:e.type==="delete"?t.removed++:t.modified++;return t}function Re(r){var d;if(r.length<=1)return r.forEach((f,c)=>f.ordinal=c),[...r];const t=new Map(r.map(f=>[f.guid,f])),e=new Map,s=[];for(const f of r){const c=(d=f.parents)==null?void 0:d[0];if(c&&t.has(c)){const g=e.get(c)??[];g.push(f),e.set(c,g)}else s.push(f)}const n=(f,c)=>String(f.timestamp).localeCompare(String(c.timestamp));s.sort(n);const i=[],o=[...s].reverse(),h=new Set;for(;o.length;){const f=o.pop();if(h.has(f.guid))continue;h.add(f.guid),i.push(f);const c=(e.get(f.guid)??[]).sort(n);for(let g=c.length-1;g>=0;g--)o.push(c[g])}for(const f of r)h.has(f.guid)||i.push(f);return i.forEach((f,c)=>f.ordinal=c),i}function Xe(r){const t=Re(r);return t[t.length-1]}function Dt(){const r=globalThis.crypto;return r!=null&&r.randomUUID?r.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}var Y,vt,pe;class vs{constructor(t){b(this,vt);b(this,Y,new Map);this.client=t}register(t){if(u(this,Y).has(t.name))throw new Error(`A recipe named "${t.name}" is already registered.`);u(this,Y).set(t.name,t)}list(t){return[...u(this,Y).values()].filter(s=>(!(t!=null&&t.to)||s.to===t.to)&&(!(t!=null&&t.input)||s.inputs.includes(t.input)))}get(t){return u(this,Y).get(t)}async plan(t,e){const{base:s,opId:n,result:i}=await a(this,vt,pe).call(this,t,e);return{opId:n,projectId:e.projectId,target:e.target,...s!=null&&s.guid?{baseCommitGuid:s.guid}:{},result:i}}async queue(t,e){return{suggestion:await this.client.history(t.projectId).doc(t.target.source,t.target.docId).suggest({opId:t.opId,title:t.result.title,verb:t.result.verb,author:e.author,payload:t.result.payload,targets:t.result.targets,userId:e.userId,baseCommitGuid:t.baseCommitGuid}),result:t.result}}async run(t,e){const{targetDoc:s,base:n,opId:i,result:o}=await a(this,vt,pe).call(this,t,e);return{suggestion:await s.suggest({opId:i,title:o.title,verb:o.verb,author:e.author,payload:o.payload,targets:o.targets,userId:e.userId,baseCommitGuid:n==null?void 0:n.guid}),result:o}}}Y=new WeakMap,vt=new WeakSet,pe=async function(t,e){const s=u(this,Y).get(t);if(!s)throw new Error(`No recipe named "${t}" is registered.`);if(s.to!==e.target.source)throw new Error(`Recipe "${t}" writes ${s.to}, but the target document belongs to ${e.target.source}.`);const n=this.client.history(e.projectId).doc(e.target.source,e.target.docId),i=await n.latest(),o=Dt(),h=await s.run({client:this.client,projectId:e.projectId,targetDoc:n,opId:o,input:e.input,settings:e.settings??{}});return{recipe:s,targetDoc:n,base:i,opId:o,result:h}};const ye=100;function ln(r){try{const t=JSON.parse(r);if(t&&typeof t=="object"){const e=t;return{message:typeof e.message=="string"?e.message:void 0,code:typeof e.code=="string"?e.code:void 0,details:e.details}}}catch{}return{}}function un(r){if(!r||typeof r!="object")return;const t=r.retryAfter;return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}class Vt extends Error{constructor(e,s,n,i){const o=ln(n);super(o.message??`${s||"Request failed"} (${e})`);I(this,"status");I(this,"code");I(this,"details");I(this,"body");I(this,"retryAfter");this.name="RequestError",this.status=e,this.code=o.code,this.details=o.details,this.body=n,this.retryAfter=i??un(o.details)}}const P="item/folder",m="item",H="processor",dn="npm-registry",q="hidden",zt="FILE",Qt="TOOL",Zt="APP",fn=500,ze=3e4,pn=.25,yn=r=>new Promise(t=>setTimeout(t,r));function mn(r){var n,i;const t=(i=(n=r.headers)==null?void 0:n.get)==null?void 0:i.call(n,"Retry-After");if(!t)return;const e=Number(t);if(Number.isFinite(e))return Math.max(0,e);const s=Date.parse(t);if(!Number.isNaN(s))return Math.max(0,(s-Date.now())/1e3)}function gn(r){return r instanceof Vt?r.status===429||r.status>=500:!0}function wn(r,t){const e=Math.min(fn*2**t,ze),s=e*pn*Math.random(),n=r instanceof Vt&&r.retryAfter!=null?r.retryAfter*1e3:void 0;return n!=null?Math.min(n,ze)+s:e+s}var l,me,y,J,Tt,wt,Bt,Lt,ge,we,Ts;const Ne=class Ne{constructor(t,e,s){b(this,l);I(this,"apiUrl");I(this,"accessToken");I(this,"wsUrl");I(this,"retries");I(this,"useBearer");I(this,"builtInGlobals",null);I(this,"localServerUrl",null);I(this,"context");b(this,Tt);const{retries:n=0,useBearer:i=!1,localServerUrl:o}=s||{};let h=e;if(h.charAt(h.length-1)==="/"&&(h=h.slice(0,-1)),this.apiUrl=`${h}/api`,this.accessToken=t,this.wsUrl=h,this.retries=n,this.useBearer=i,this.context={appId:"",projectId:"",accessToken:t,apiUrl:e},o){let d=o;d.charAt(d.length-1)==="/"&&(d=d.slice(0,-1)),this.localServerUrl=d}}static fromPlatformContext(t){const e=(typeof window<"u"?window.__THATOPEN_CONTEXT__:null)||{appId:"",projectId:"",accessToken:"",apiUrl:""},s=new Ne(e.accessToken,e.apiUrl,{...t,useBearer:!0});return s.context=e,s}setRetries(t){this.retries=t}setBuiltInGlobals(t){this.builtInGlobals=t}get socketOrigin(){return this.wsUrl.split("?")[0]}async resolveAccessToken(){return this.accessToken}async request(t,e,s){return a(this,l,y).call(this,t,e,s)}async listFiles(t){const{folderId:e,archived:s,projectId:n}=t||{};return e?await a(this,l,y).call(this,"GET",`${P}/${e}/items`,{query:{itemType:zt,archived:s}}):await a(this,l,y).call(this,"GET",`${m}`,{query:{itemType:zt,archived:s,...n&&{projectId:n}}})}async getFile(t,e){return await a(this,l,we).call(this,t,e)}async createFile(t){return await a(this,l,Lt).call(this,t,zt)}async updateFile(t,e){return await a(this,l,ge).call(this,t,e)}async archiveFile(t){return await a(this,l,y).call(this,"DELETE",`${m}/${t}`)}async recoverFile(t){return await a(this,l,y).call(this,"PUT",`${m}/${t}/recover`)}async downloadFile(t,e){return await a(this,l,Bt).call(this,t,e)}async getFileVersionMetadata(t,e,s){const{withDraft:n}=s||{};return await a(this,l,y).call(this,"GET",`${m}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/metadata`,{query:{...n&&{withDraft:"true"}}})}async updateFileVersionMetadata(t,e,s){return await a(this,l,y).call(this,"PUT",`${m}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/metadata`,{body:JSON.stringify({metadata:s}),contentType:"application/json"})}async deleteFileVersionMetadata(t,e){return await a(this,l,y).call(this,"DELETE",`${m}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/metadata`)}async getFileVersionMetadataBatch(t,e){const{withDraft:s}=e||{};return await a(this,l,wt).call(this,t,async n=>(await a(this,l,y).call(this,"POST",`${m}/batch/version-metadata`,{body:JSON.stringify({entries:n,...s!==void 0&&{withDraft:s}}),contentType:"application/json"})).results)}async listFolders(t){const{archived:e,parentFolderId:s,projectId:n}=t||{};return await a(this,l,y).call(this,"GET",P,{query:{parentFolderId:s,archived:e,...n&&{projectId:n}}})}async getFolder(t){return await a(this,l,y).call(this,"GET",`${P}/${t}`)}async getFoldersBatch(t){return await a(this,l,wt).call(this,t,async e=>(await a(this,l,y).call(this,"POST",`${m}/batch/folders`,{body:JSON.stringify({folderIds:e}),contentType:"application/json"})).results)}async createFolder(t,e,s){return await a(this,l,y).call(this,"POST",P,{body:JSON.stringify({name:t,...e&&{parentId:e},...s&&{projectId:s}}),contentType:"application/json"})}async updateFolder(t,e){const{name:s}=e;return await a(this,l,y).call(this,"PUT",`${P}/${t}`,{body:JSON.stringify({name:s}),contentType:"application/json"})}async archiveFolder(t){return await a(this,l,y).call(this,"DELETE",`${P}/${t}`)}async recoverFolder(t){return await a(this,l,y).call(this,"PUT",`${P}/${t}/recover`)}async downloadFolder(t){return await a(this,l,J).call(this,`${P}/${t}/download`)}async listComponents(t){const{folderId:e,ShowVersions:s,projectId:n}=t||{};return e?await a(this,l,y).call(this,"GET",`${P}/${e}/items`,{query:{itemType:Qt,...s&&{ShowVersions:s}}}):await a(this,l,y).call(this,"GET",`${m}`,{query:{itemType:Qt,...s&&{ShowVersions:s},...n&&{projectId:n}}})}async getComponent(t,e){return await a(this,l,we).call(this,t,e)}async createComponent(t){const{componentProps:e}=t;return await a(this,l,Lt).call(this,t,Qt,e)}async updateComponent(t,e){const{componentProps:s}=e;return await a(this,l,ge).call(this,t,e,s)}async downloadComponent(t,e){return await a(this,l,Bt).call(this,t,e)}async downloadComponentBundle(t,e){const{versionTag:s,withDraft:n}=e||{};return await a(this,l,J).call(this,`${m}/${t}/download/bundle`,{query:{...s&&{versionTag:s},...n&&{withDraft:n}}})}async archiveComponent(t){return await a(this,l,y).call(this,"DELETE",`${m}/${t}`)}async recoverComponent(t){return await a(this,l,y).call(this,"PUT",`${m}/${t}/recover`)}async getBuiltInComponent(t){return await(await a(this,l,J).call(this,`built-in/${t}/bundle`)).text()}async initBuiltInComponent(t,e,s){const n=await this.getBuiltInComponent(t.uuid),i=s??this.builtInGlobals??(typeof window<"u"?window.ThatOpenCompany:{})??{},o=Object.keys(i),h=o.map(g=>i[g]),f=new Function(...o,`${n}
2
+ return main;`)(...h),c=(f==null?void 0:f.componentDefinition)??f;e.get(c)}async initBuiltInComponents(t,...e){await Promise.all(e.map(s=>this.initBuiltInComponent(s,t)))}async setup(t,...e){var o,h;const s=t.OBC,n=t.BUI;if(!(s!=null&&s.Components))throw new Error("globals.OBC must include Components");if(!(n!=null&&n.Manager))throw new Error("globals.BUI must include Manager");const i=new s.Components;return n.Manager.init(),this.setBuiltInGlobals(t),await this.initBuiltInComponents(i,...e),i.init(),(h=(o=this.context.appEventOrchestrator)==null?void 0:o.appLoaded)==null||h.call(o),{components:i}}throwError(t,e){var s,n;(n=(s=this.context.appEventOrchestrator)==null?void 0:s.appError)==null||n.call(s,t,e)}async listApps(t){const{folderId:e,ShowVersions:s,projectId:n}=t||{};return e?await a(this,l,y).call(this,"GET",`${P}/${e}/items`,{query:{itemType:Zt,...s&&{ShowVersions:s}}}):await a(this,l,y).call(this,"GET",`${m}`,{query:{itemType:Zt,...s&&{ShowVersions:s},...n&&{projectId:n}}})}async createApp(t){const{appProps:e}=t;return await a(this,l,Lt).call(this,t,Zt,e)}async downloadApp(t,e){return await a(this,l,Bt).call(this,t,e)}async downloadAppBundle(t,e){const{versionTag:s,withDraft:n}=e||{};return await a(this,l,J).call(this,`${m}/${t}/download/bundle`,{query:{...s&&{versionTag:s},...n&&{withDraft:n}}})}async archiveApp(t){return await a(this,l,y).call(this,"DELETE",`${m}/${t}`)}async getNpmCredentials(){return await a(this,l,y).call(this,"GET",`${dn}/credentials`)}async executeComponent(t,e,s){if(this.localServerUrl){const n=`${this.localServerUrl}/api/${H}/${t}/execute`,i=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!i.ok){const o=await i.text().catch(()=>"");throw new Error(`Local server request failed: ${i.status} - ${o}`)}return await i.json()}return await a(this,l,y).call(this,"POST",`${H}/${t}/execute`,{body:JSON.stringify(e),query:{...s&&{versionTag:s}},contentType:"application/json"})}async abortExecution(t){if(this.localServerUrl){const e=`${this.localServerUrl}/api/${H}/progress/${t}/abort`,s=await fetch(e,{method:"POST"});if(!s.ok){const n=await s.text().catch(()=>"");throw new Error(`Local server request failed: ${s.status} - ${n}`)}return await s.json()}return await a(this,l,y).call(this,"POST",`${H}/progress/${t}/abort`)}async listExecutions(t,e){if(this.localServerUrl){const s=e?`?projectId=${encodeURIComponent(e)}`:"",n=`${this.localServerUrl}/api/${H}/${t}/progress${s}`,i=await fetch(n);if(!i.ok){const o=await i.text().catch(()=>"");throw new Error(`Local server request failed: ${i.status} - ${o}`)}return await i.json()}return await a(this,l,y).call(this,"GET",`${H}/${t}/progress`,{query:{...e&&{projectId:e}}})}async getExecution(t){if(this.localServerUrl){const e=`${this.localServerUrl}/api/${H}/progress/${t}`,s=await fetch(e);if(!s.ok){const n=await s.text().catch(()=>"");throw new Error(`Local server request failed: ${s.status} - ${n}`)}return await s.json()}return await a(this,l,y).call(this,"GET",`${H}/progress/${t}`)}async onExecutionProgress(t,e){const s=this.localServerUrl??this.wsUrl,n=await bt(s,{auth:{accessToken:this.accessToken},transports:["websocket"]});n.on("connect",function(){n.emit("executionSubscription",JSON.stringify({executionId:t})),n.on("execution",i=>{e(i)})}),n.on("connect_error",function(i){console.log(i)})}documents(t){return new xe(this,t)}history(t){return new bs(this,t)}get recipes(){return u(this,Tt)??_(this,Tt,new vs(this)),u(this,Tt)}async createHiddenFile(t,e,s){const n=new FormData;return n.append("file",t),n.append("parentItemId",e),s!=null&&n.append("tag",s),await a(this,l,y).call(this,"POST",`${m}/${q}`,{body:n})}async createHiddenFilesBatch(t,e,s){const n=new FormData;for(const i of t)n.append("files",i);return n.append("parentItemId",e),s!=null&&n.append("tag",s),await a(this,l,y).call(this,"POST",`${m}/${q}/batch`,{body:n})}async deleteHiddenFile(t){return await a(this,l,y).call(this,"DELETE",`${m}/${q}/${t}`)}async getHiddenFile(t){return await a(this,l,y).call(this,"GET",`${m}/${q}/${t}`)}async downloadHiddenFile(t){return await a(this,l,J).call(this,`${m}/${q}/${t}/download`)}async getHiddenFileSignedUrl(t,e){return await a(this,l,y).call(this,"GET",`${m}/${q}/${t}/signed-url`,{...e!=null&&{query:{expiresIn:e}}})}async getHiddenFileSignedUrlsBatch(t,e){return await a(this,l,wt).call(this,t,async s=>(await a(this,l,y).call(this,"POST",`${m}/${q}/signed-url/batch`,{body:JSON.stringify({hiddenFileIds:s,...e!=null&&{expiresIn:e}}),contentType:"application/json"})).results)}async getHiddenFilesByParent(t,e){return await a(this,l,y).call(this,"GET",`${m}/${t}/${q}`,{...e!=null&&{query:{tag:e}}})}async deleteHiddenFilesByParent(t){return await a(this,l,y).call(this,"DELETE",`${m}/${t}/${q}`)}async uploadItemIcon(t,e){const s=new FormData;return s.append("icon",e),await a(this,l,y).call(this,"PUT",`${m}/${t}/icon`,{body:s})}async getItemIcon(t){return await a(this,l,J).call(this,`${m}/${t}/icon`)}async removeItemIcon(t){return await a(this,l,y).call(this,"DELETE",`${m}/${t}/icon`)}async updateItem(t,e){return await a(this,l,y).call(this,"PUT",`${m}/${t}`,{body:JSON.stringify(e),contentType:"application/json"})}async createVersion(t,e,s,n,i){const o=new FormData;return o.append("file",e),o.append("versionTag",s),n&&o.append("extraProps",JSON.stringify(n)),i&&o.append("metadata",JSON.stringify(i)),await a(this,l,y).call(this,"POST",`${m}/${t}/version`,{body:o})}async listVersions(t,e={}){return await a(this,l,y).call(this,"GET",`${m}/${encodeURIComponent(t)}/versions`,{query:e})}async listVersionsBatch(t,e={}){const{archived:s}=e;return await a(this,l,wt).call(this,t,async n=>(await a(this,l,y).call(this,"POST",`${m}/batch/versions`,{body:JSON.stringify({itemIds:n,...s!==void 0&&{archived:s}}),contentType:"application/json"})).results)}async archiveVersion(t,e){return await a(this,l,y).call(this,"PUT",`${m}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/archive`)}async recoverVersion(t,e){return await a(this,l,y).call(this,"PUT",`${m}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/recover`)}async deleteVersion(t,e){return await a(this,l,y).call(this,"DELETE",`${m}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}`)}};l=new WeakSet,me=function(t){return`${this.apiUrl}/${t}`},y=async function(t,e,s){const{body:n,query:i,contentType:o,retries:h,responseType:d,retryAttempt:f}=s||{},c=a(this,l,me).call(this,e),g=a(this,l,Ts).call(this,i),v=await this.resolveAccessToken(),V={...g,...this.useBearer?{}:{accessToken:v}};try{const O=await fetch(c+"?"+new URLSearchParams(V).toString(),{method:t,headers:{Accept:"application/json",...o&&{"Content-Type":o},...this.useBearer&&{Authorization:`Bearer ${v}`}},...n&&{body:n}});if(!O.ok){const k=await O.text().then(et=>et).catch(()=>"");throw new Vt(O.status,O.statusText,k,mn(O))}return d==="blob"?await O.blob():O.json().then(k=>k).catch(()=>{})}catch(O){const k=h??this.retries;if(k>0&&gn(O)){const et=f??0;return await yn(wn(O,et)),await a(this,l,y).call(this,t,e,{...s,retries:k-1,retryAttempt:et+1})}throw O}},J=async function(t,e){const{query:s}=e||{},n=a(this,l,me).call(this,t),i=await this.resolveAccessToken(),o={...s,...this.useBearer?{}:{accessToken:i}};return await fetch(n+"?"+new URLSearchParams(o).toString(),{method:"GET",...this.useBearer&&{headers:{Authorization:`Bearer ${i}`}}})},Tt=new WeakMap,wt=async function(t,e){if(!t.length)return[];const s=[];for(let i=0;i<t.length;i+=ye)s.push(t.slice(i,i+ye));return(await Promise.all(s.map(e))).flat()},Bt=async function(t,e){const{versionTag:s,withDraft:n}=e||{};return await a(this,l,J).call(this,`${m}/${t}/download`,{query:{...s&&{versionTag:s},...n&&{withDraft:n}}})},Lt=async function(t,e,s){const{name:n,versionTag:i,parentFolderId:o,projectId:h,file:d,metadata:f}=t,c=new FormData;return c.append("file",d),c.append("name",n),c.append("versionTag",i),c.append("itemType",e),o&&c.append("folderId",o),h&&c.append("projectId",h),s&&c.append("extraProps",JSON.stringify(s)),f&&c.append("metadata",JSON.stringify(f)),await a(this,l,y).call(this,"POST",m,{body:c})},ge=async function(t,e,s){const{name:n,versionTag:i,parentFolderId:o,file:h,metadata:d}=e;let f,c;if(h){const g=new FormData;g.append("file",h),i&&g.append("versionTag",i),s&&g.append("extraProps",JSON.stringify(s)),d&&g.append("metadata",JSON.stringify(d)),c=await a(this,l,y).call(this,"POST",`${m}/${t}/version`,{body:g})}if(n||o){const g={...n&&{name:n},...o&&{folderId:o}},v=JSON.stringify(g);f=await a(this,l,y).call(this,"PUT",`${m}/${t}`,{body:v,contentType:"application/json"})}return{item:f,version:c}},we=async function(t,e){const{showVersions:s=!1}=e||{};return await a(this,l,y).call(this,"GET",`${m}/${t}`,{query:{showVersions:s}})},Ts=function(t){return t&&Object.entries(t).filter(([,e])=>e!==void 0).reduce((e,[s,n])=>(e[s]=n,e),{})};let Mt=Ne;function Ss(){if(typeof window>"u"||window.parent===window)throw new Error("client.channel only works inside a That Open app, which runs in an iframe of the platform.");return{post:r=>window.parent.postMessage(r,"*"),listen:r=>{const t=e=>{e.source===window.parent&&r(e.data)};return window.addEventListener("message",t),()=>window.removeEventListener("message",t)}}}const be="channel:",bn=1e4;function Ft(r){try{r()}catch(t){console.error("[channel] a listener threw:",t)}}var U,C,x,ct,ht,lt,A,_e,Ee,at;class $e{constructor(t,e){b(this,A);b(this,U,!1);b(this,C,[]);b(this,x,[]);b(this,ct,new Set);b(this,ht,new Set);b(this,lt,new Set);this.transport=t,this.controls=e}get joined(){return u(this,U)}get peers(){return u(this,C)}join(){return u(this,U)?Promise.resolve():a(this,A,_e).call(this,"joined",this.controls.join)}leave(){return!u(this,U)&&!u(this,x).some(t=>t.want==="joined")?Promise.resolve():a(this,A,_e).call(this,"left",this.controls.leave)}onChange(t){return u(this,ct).add(t),()=>void u(this,ct).delete(t)}onPeerJoined(t){return u(this,ht).add(t),()=>void u(this,ht).delete(t)}onPeerLeft(t){return u(this,lt).add(t),()=>void u(this,lt).delete(t)}applyJoined(){_(this,U,!0),a(this,A,Ee).call(this,"joined"),a(this,A,at).call(this)}applyLeft(){_(this,U,!1),_(this,C,[]),a(this,A,Ee).call(this,"left"),a(this,A,at).call(this)}applyPeers(t){_(this,C,t),a(this,A,at).call(this)}applyPeerJoined(t){!u(this,U)||u(this,C).some(e=>e.from===t.from)||(_(this,C,[...u(this,C),t]),u(this,ht).forEach(e=>Ft(()=>e(t))),a(this,A,at).call(this))}applyPeerLeft(t){const e=u(this,C).find(s=>s.from===t);e&&(_(this,C,u(this,C).filter(s=>s.from!==t)),u(this,lt).forEach(s=>Ft(()=>s(e))),a(this,A,at).call(this))}failPending(t){const e=u(this,x);return _(this,x,[]),e.forEach(s=>{clearTimeout(s.timer),s.reject(t)}),e.length>0}post(t){this.transport.post(t)}}U=new WeakMap,C=new WeakMap,x=new WeakMap,ct=new WeakMap,ht=new WeakMap,lt=new WeakMap,A=new WeakSet,_e=function(t,e){return new Promise((s,n)=>{const i={want:t,resolve:s,reject:n,timer:setTimeout(()=>{_(this,x,u(this,x).filter(o=>o!==i)),n(new Error(`The platform did not confirm ${t==="joined"?"joining":"leaving"} in time.`))},bn)};u(this,x).push(i),this.transport.post({type:"APP_CHANNEL_CONTROL",...e})})},Ee=function(t){const e=u(this,x).filter(s=>s.want===t);_(this,x,u(this,x).filter(s=>s.want!==t)),e.forEach(s=>{clearTimeout(s.timer),s.resolve()})},at=function(){u(this,ct).forEach(t=>Ft(t))};var ut;class Is extends $e{constructor(e){super(e,{join:{action:"joinCollab"},leave:{action:"leaveCollab"}});b(this,ut,new Map)}on(e,s){const n=u(this,ut).get(e)??new Set;return n.add(s),u(this,ut).set(e,n),()=>void n.delete(s)}send(e,s){if(e.startsWith(be))throw new Error(`Message types starting with '${be}' are reserved.`);this.joined&&this.post({type:"APP_CHANNEL_PUBLISH",message:{type:e,payload:s}})}accepts(e){return e===void 0||e==="collab"}async handle(e){const s=u(this,ut).get(e.type);if(!(s!=null&&s.size))return{handled:!1};const n=As(e);return s.forEach(i=>Ft(()=>i(e.payload,n))),{handled:!0}}}ut=new WeakMap;var W;class Os extends $e{constructor(e,s){super(e,{join:{action:"joinExternal",kind:s},leave:{action:"leaveExternal",kind:s}});b(this,W,new Map);this.kind=s}on(e,s){if(u(this,W).has(e))throw new Error(`"${e}" already has a handler in this room. Remove it first.`);return u(this,W).set(e,s),()=>void u(this,W).delete(e)}accepts(e,s){return e!==void 0&&e!=="external"?!1:this.kind===void 0||e===void 0||this.kind===s}get hasHandlers(){return u(this,W).size>0}async handle(e){const s=u(this,W).get(e.type);if(!s)return{handled:!1};try{return{handled:!0,value:await s(e.payload,As(e))}}catch(n){return{handled:!0,error:n instanceof Error?n.message:String(n)}}}}W=new WeakMap;function As(r){return{from:r.from,at:r.at,requestId:r.requestId,kind:r.kind}}function _n(r){const t=r;if((t==null?void 0:t.type)!=="THATOPEN_CHANNEL_MESSAGE")return null;const e=t.message;return!e||typeof e.type!="string"?null:{type:e.type,requestId:typeof e.requestId=="string"?e.requestId:void 0,payload:e.payload,at:typeof e.at=="number"?e.at:Date.now(),from:typeof e.from=="string"?e.from:"",scope:e.scope==="collab"||e.scope==="external"?e.scope:void 0,kind:typeof e.kind=="string"?e.kind:void 0}}var Z,St,j,K,X,T,ve,qt,Cs,xs,Rs,Te;class ks{constructor(t){b(this,T);b(this,Z);b(this,St);b(this,j);b(this,K,new Map);b(this,X,new Set);_(this,Z,t),_(this,St,t.listen(e=>void a(this,T,Cs).call(this,e)))}collab(){return u(this,j)??_(this,j,new Is(u(this,Z))),u(this,j)}external(t){const e=t??"";let s=u(this,K).get(e);return s||(s=new Os(u(this,Z),t),u(this,K).set(e,s)),s}dispose(){u(this,St).call(this)}}Z=new WeakMap,St=new WeakMap,j=new WeakMap,K=new WeakMap,X=new WeakMap,T=new WeakSet,ve=function(){return[...u(this,j)?[u(this,j)]:[],...u(this,K).values()]},qt=function(t,e){if(t==="collab")return u(this,j);if(t==="external")return u(this,K).get(typeof e=="string"?e:"")},Cs=async function(t){const e=_n(t);if(e){if(e.type.startsWith(be)){a(this,T,xs).call(this,e);return}await a(this,T,Rs).call(this,e)}},xs=function(t){var s,n,i;const e=t.payload??{};switch(t.type){case"channel:joined":(s=a(this,T,qt).call(this,e.scope,e.kind))==null||s.applyJoined();break;case"channel:left":(n=a(this,T,qt).call(this,e.scope,e.kind))==null||n.applyLeft();break;case"channel:peers":(i=a(this,T,qt).call(this,e.scope,e.kind))==null||i.applyPeers(e.peers??[]);break;case"channel:peer-joined":case"channel:peer-left":{if(!e.from)break;const o=e.scope==="collab"?[u(this,j)]:[...u(this,K).values()].filter(h=>h.accepts("external",e.kind));for(const h of o)t.type==="channel:peer-joined"?h==null||h.applyPeerJoined({from:e.from,kind:e.kind}):h==null||h.applyPeerLeft(e.from);break}case"channel:error":{const o=new Error(String(t.payload));a(this,T,ve).call(this).map(d=>d.failPending(o)).some(Boolean)||console.error("[channel] error:",t.payload);break}}},Rs=async function(t){const e=a(this,T,ve).call(this).filter(i=>i.accepts(t.scope,t.kind));let s=!1;for(const i of e){const o=await i.handle(t);o.handled&&(s=!0,t.requestId&&a(this,T,Te).call(this,t.requestId,o))}t.requestId&&t.scope==="external"&&e.length>0&&!s&&a(this,T,Te).call(this,t.requestId,{handled:!0,error:`No handler for "${t.type}".`})},Te=function(t,e){u(this,X).has(t)||(u(this,X).add(t),u(this,X).size>500&&u(this,X).delete(u(this,X).values().next().value),u(this,Z).post({type:"APP_CHANNEL_PUBLISH",message:{type:e.error===void 0?"reply":"reply-error",requestId:t,payload:e.error===void 0?e.value:{error:e.error}}}))};const Q="project",st="notifications";var dt,It;const Pe=class Pe extends Mt{constructor(e,s,n){super(typeof e=="string"?e:"",s,{...n,useBearer:!0});b(this,dt);b(this,It);typeof e=="function"&&_(this,dt,e)}async resolveAccessToken(){return u(this,dt)?await u(this,dt).call(this):super.resolveAccessToken()}static fromPlatformContext(e){const s=(typeof window<"u"?window.__THATOPEN_CONTEXT__:null)||{appId:"",projectId:"",accessToken:"",apiUrl:""},n=new Pe(s.accessToken,s.apiUrl,e);return n.context=s,n}get channel(){return u(this,It)??_(this,It,new ks(Ss())),u(this,It)}async listProjects(){return await this.request("GET",Q)}async getProject(e){return await this.request("GET",`${Q}/${e}`)}async getProjectData(e){return await this.request("GET",`${Q}/${e}/data`)}async getAvatar(e){return await this.request("GET",`account/${e}/avatar`,{responseType:"blob"})}async checkPermission(e){return await this.request("GET",`${Q}/permissions/check`,{query:e})}async checkPermissionBatch(e){return(await this.request("POST",`${Q}/permissions/check/batch`,{body:JSON.stringify({checks:e}),contentType:"application/json"})).results}async getNotifications(e){return await this.request("GET",st,{query:{...(e==null?void 0:e.cursor)!==void 0&&{cursor:e.cursor},...(e==null?void 0:e.limit)!==void 0&&{limit:String(e.limit)}}})}async getUnreadNotificationCount(){return(await this.request("GET",`${st}/unread-count`)).count}async markNotificationsRead(e){return await this.request("POST",`${st}/mark-read`,{body:JSON.stringify({ids:e}),contentType:"application/json"})}async markAllNotificationsRead(){return await this.request("POST",`${st}/mark-all-read`)}async getNotificationSubscriptions(){return await this.request("GET",`${st}/subscriptions`)}async unsubscribeFromAutomation(e){return await this.request("DELETE",`${st}/subscriptions/${e}`)}async subscribeToAutomation(e,s,n){return await this.request("POST",`${Q}/${e}/events/hooks/${s}/subscription`,{body:JSON.stringify(n??{}),contentType:"application/json"})}async updateAutomationSubscription(e,s,n){return await this.request("PATCH",`${Q}/${e}/events/hooks/${s}/subscription`,{body:JSON.stringify(n),contentType:"application/json"})}async onNotification(e){const s=await this.resolveAccessToken(),n=bt(`${this.socketOrigin}/notifications`,{auth:{accessToken:s},transports:["websocket"]});return n.on("notification.created",i=>e({type:"created",id:i==null?void 0:i.id})),n.on("notification.read",i=>e({type:"read",id:i==null?void 0:i.id})),n.on("notifications.allRead",i=>e({type:"allRead",batch:i==null?void 0:i.batch})),()=>n.disconnect()}};dt=new WeakMap,It=new WeakMap;let Se=Pe;const En="flow:",vn="flow:op",Tn="flow:source",$s="revitflow/op@2",Qe="REVITFLOWCHANGE",Ze="REVITFLOWOPERATION";class Sn{constructor(t){I(this,"changes",[]);this.target=t}get length(){return this.changes.length}get batchId(){return this.target.batchId}get title(){return this.target.title??`${this.changes.length} change(s)`}get author(){return this.target.author??"app"}get userId(){return this.target.userId}get baseCommit(){return this.target.baseCommit}add(t,e={}){return this.changes.push({op:"add",attrs:this.pack(t,e)}),this}set(t,e,s={}){return this.requireId(t,"set"),this.changes.push({op:"set",item:t,attrs:this.pack(e,s)}),this}remove(t){return this.requireId(t,"remove"),this.changes.push({op:"remove",item:t,attrs:{}}),this}get summary(){const t=new Set(this.changes.map(e=>e.op));return t.size===1?[...t][0]:"mixed"}async build(t){if(this.changes.length===0)throw new Error("An operation with no changes is not an operation. Add at least one.");const e={schema:$s,opId:t,batchId:this.batchId??t,targetProject:this.target.project,targetDocument:this.target.document,baseCommit:this.baseCommit,author:this.author,...this.userId?{userId:this.userId}:{},title:this.title,summary:this.summary},[s,n]=await In();return On(this.flatbuffer(s,n,t,JSON.stringify(e)))}pack(t,e){const s={};for(const[n,i]of Object.entries(t??{}))n.startsWith(En)||(s[n]=String(i));return e.position&&(s.Position=e.position.map(ts).join(",")),e.rotationDeg!==void 0&&(s.Rotation=ts(e.rotationDeg)),e.source&&(s[Tn]=e.source),s}requireId(t,e){if(!t||!t.trim())throw new Error(`A '${e}' has to name the item it acts on.`)}flatbuffer(t,e,s,n){const{Attribute:i,Meshes:o,Model:h,SpatialStructure:d,Transform:f}=e,c=new t.Builder(1024),g=this.changes.length,v=new Uint32Array(g);let V=1;for(let S=0;S<g;S++)v[S]=V++;const O=V++,k=S=>(S(c,0),c.endVector()),et=o.createShellsVector(c,[]),Ns=o.createCircleExtrusionsVector(c,[]),Ps=k(o.startSamplesVector),Bs=k(o.startRepresentationsVector),Ls=k(o.startMaterialsVector),Fs=k(o.startLocalTransformsVector),qs=k(o.startGlobalTransformsVector),Ds=o.createMeshesItemsVector(c,[]),Ms=o.createMaterialIdsVector(c,[]),Us=o.createRepresentationIdsVector(c,[]),js=o.createSampleIdsVector(c,[]),Vs=o.createLocalTransformIdsVector(c,[]),Gs=o.createGlobalTransformIdsVector(c,[]);o.startMeshes(c),o.addCoordinates(c,f.createTransform(c,0,0,0,1,0,0,0,1,0)),o.addGlobalTransforms(c,qs),o.addShells(c,et),o.addRepresentations(c,Bs),o.addSamples(c,Ps),o.addLocalTransforms(c,Fs),o.addMaterials(c,Ls),o.addCircleExtrusions(c,Ns),o.addMeshesItems(c,Ds),o.addRepresentationIds(c,Us),o.addSampleIds(c,js),o.addMaterialIds(c,Ms),o.addLocalTransformIds(c,Vs),o.addGlobalTransformIds(c,Gs);const Hs=o.endMeshes(c),Js=c.createString(n),Gt=new Set,Ht=[];for(const S of this.changes){const G=[],rr={[vn]:S.op,...S.attrs};for(const[nr,ir]of Object.entries(rr)){const qe=JSON.stringify([nr,ir,"IFCTEXT"]);Gt.add(qe),G.push(c.createString(qe))}Ht.push(i.createAttribute(c,i.createDataVector(c,G)))}{const S=JSON.stringify(["Name",s,"IFCLABEL"]);Gt.add(S);const G=i.createDataVector(c,[c.createString(S)]);Ht.push(i.createAttribute(c,G))}const Ys=h.createAttributesVector(c,Ht),Ws=h.createUniqueAttributesVector(c,[...Gt].map(S=>c.createString(S))),Be=this.changes.map(()=>c.createString(Qe));Be.push(c.createString(Ze));const Ks=h.createCategoriesVector(c,Be),Le=[],Fe=[];this.changes.forEach((S,G)=>{S.item&&(Le.push(c.createString(S.item)),Fe.push(v[G]))});const Xs=h.createGuidsVector(c,Le),zs=h.createGuidsItemsVector(c,Fe),Qs=h.createLocalIdsVector(c,[...v,O]),Zs=this.changes.map((S,G)=>d.createSpatialStructure(c,v[G],c.createString(Qe),0)),tr=d.createSpatialStructure(c,O,c.createString(Ze),d.createChildrenVector(c,Zs)),er=c.createString(s);h.startModel(c),h.addMeshes(c,Hs),h.addMetadata(c,Js),h.addAttributes(c,Ys),h.addUniqueAttributes(c,Ws),h.addLocalIds(c,Qs),h.addCategories(c,Ks),h.addGuidsItems(c,zs),h.addGuids(c,Xs),h.addGuid(c,er),h.addSpatialStructure(c,tr),h.addMaxLocalId(c,V);const sr=h.endModel(c);return h.finishModelBuffer(c,sr),c.asUint8Array()}}async function In(){try{return await Promise.all([import("flatbuffers"),import("@thatopen/fragments")])}catch(r){throw new Error(`OperationBuilder needs the optional peers \`flatbuffers\` and \`@thatopen/fragments\` installed — add them to the app that authors operations. (${r instanceof Error?r.message:String(r)})`)}}function ts(r){return Number.isFinite(r)?String(r):"0"}async function On(r){const t=new Blob([r]).stream().pipeThrough(new CompressionStream("deflate"));return new Uint8Array(await new Response(t).arrayBuffer())}const An={MAX_FIELDS:200,MAX_KEY_LENGTH:50,MAX_VALUE_LENGTH:50},kn={uuid:"a3f82c1d-5b74-4e9a-bc30-d7e12f894a61"},Cn={uuid:"2c9f4e8d-3a1b-4c5e-9d7f-0a2b6c8e1d3f"},xn={uuid:"b0b5e2a2-0b3a-4a6b-8b1c-0b1c4a6b8b1c"},Rn={uuid:"d8f3a1c2-6b4e-4f9a-8c1d-2e7b5a9f3c60"},$n={uuid:"3f9c1a7e-6b2d-4e18-9a5c-7d0e2f4b6c81"},Nn={uuid:"2c4ae432-fc24-43e9-9783-0c960c674e96"},Pn={uuid:"6f3a9c2e-8b1d-4e6a-9c3f-1d7b5a8e2c4f"},Bn={uuid:"69af63aa-19ba-4fc7-b17b-75647bac1d76"},Ln={uuid:"234f1416-528d-452a-9cc9-a16c5239b2eb"};exports.CDEManager=kn;exports.ChannelClient=ks;exports.ChannelRoom=$e;exports.ClashesManager=Cn;exports.CollabRoom=Is;exports.DOCUMENT_FILE=oe;exports.DOCUMENT_SCHEMA=_t;exports.EngineServicesClient=Mt;exports.ExternalRoom=Os;exports.FileList=xn;exports.FlowDoc=_s;exports.GISManager=Rn;exports.GitHistoryManager=$n;exports.HelloWorld=Nn;exports.METADATA_LIMITS=An;exports.OP_SCHEMA=$s;exports.OperationBuilder=Sn;exports.PlatformClient=Se;exports.ProjectDocuments=xe;exports.ProjectHistory=bs;exports.ProjectManager=Pn;exports.Recipes=vs;exports.RequestError=Vt;exports.SELF_VIEWING_FORMATS=ps;exports.STORAGE_BATCH_MAX=ye;exports.StaleHistoryError=ce;exports.TopicsManager=Bn;exports.UIManager=Ln;exports.mintGuid=Dt;exports.orderByGraph=Re;exports.windowTransport=Ss;
3
3
  //# sourceMappingURL=index.cjs.js.map