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