@thatopen/services 0.30.0 → 0.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs.js CHANGED
@@ -1,5 +1,5 @@
1
- "use strict";var xi=Object.create;var Fn=Object.defineProperty;var Ri=Object.getOwnPropertyDescriptor;var ki=Object.getOwnPropertyNames;var Ni=Object.getPrototypeOf,Mi=Object.prototype.hasOwnProperty;var dr=s=>{throw TypeError(s)};var Fi=(s,t,e)=>t in s?Fn(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e;var Li=(s,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of ki(t))!Mi.call(s,r)&&r!==e&&Fn(s,r,{get:()=>t[r],enumerable:!(n=Ri(t,r))||n.enumerable});return s};var dn=(s,t,e)=>(e=s!=null?xi(Ni(s)):{},Li(t||!s||!s.__esModule?Fn(e,"default",{value:s,enumerable:!0}):e,s));var xt=(s,t,e)=>Fi(s,typeof t!="symbol"?t+"":t,e),Ln=(s,t,e)=>t.has(s)||dr("Cannot "+e);var m=(s,t,e)=>(Ln(s,t,"read from private field"),e?e.call(s):t.get(s)),z=(s,t,e)=>t.has(s)?dr("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(s):t.set(s,e),rt=(s,t,e,n)=>(Ln(s,t,"write to private field"),n?n.call(s,e):t.set(s,e),e),p=(s,t,e)=>(Ln(s,t,"access private method"),e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Qt=Object.create(null);Qt.open="0";Qt.close="1";Qt.ping="2";Qt.pong="3";Qt.message="4";Qt.upgrade="5";Qt.noop="6";const mn=Object.create(null);Object.keys(Qt).forEach(s=>{mn[Qt[s]]=s});const Hn={type:"error",data:"parser error"},Rr=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",kr=typeof ArrayBuffer=="function",Nr=s=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(s):s&&s.buffer instanceof ArrayBuffer,vs=({type:s,data:t},e,n)=>Rr&&t instanceof Blob?e?n(t):fr(t,n):kr&&(t instanceof ArrayBuffer||Nr(t))?e?n(t):fr(new Blob([t]),n):n(Qt[s]+(t||"")),fr=(s,t)=>{const e=new FileReader;return e.onload=function(){const n=e.result.split(",")[1];t("b"+(n||""))},e.readAsDataURL(s)};function ur(s){return s instanceof Uint8Array?s:s instanceof ArrayBuffer?new Uint8Array(s):new Uint8Array(s.buffer,s.byteOffset,s.byteLength)}let Pn;function Pi(s,t){if(Rr&&s.data instanceof Blob)return s.data.arrayBuffer().then(ur).then(t);if(kr&&(s.data instanceof ArrayBuffer||Nr(s.data)))return t(ur(s.data));vs(s,!1,e=>{Pn||(Pn=new TextEncoder),t(Pn.encode(e))})}const pr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",We=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let s=0;s<pr.length;s++)We[pr.charCodeAt(s)]=s;const Bi=s=>{let t=s.length*.75,e=s.length,n,r=0,i,o,a,l;s[s.length-1]==="="&&(t--,s[s.length-2]==="="&&t--);const d=new ArrayBuffer(t),c=new Uint8Array(d);for(n=0;n<e;n+=4)i=We[s.charCodeAt(n)],o=We[s.charCodeAt(n+1)],a=We[s.charCodeAt(n+2)],l=We[s.charCodeAt(n+3)],c[r++]=i<<2|o>>4,c[r++]=(o&15)<<4|a>>2,c[r++]=(a&3)<<6|l&63;return d},Di=typeof ArrayBuffer=="function",bs=(s,t)=>{if(typeof s!="string")return{type:"message",data:Mr(s,t)};const e=s.charAt(0);return e==="b"?{type:"message",data:ji(s.substring(1),t)}:mn[e]?s.length>1?{type:mn[e],data:s.substring(1)}:{type:mn[e]}:Hn},ji=(s,t)=>{if(Di){const e=Bi(s);return Mr(e,t)}else return{base64:!0,data:s}},Mr=(s,t)=>{switch(t){case"blob":return s instanceof Blob?s:new Blob([s]);case"arraybuffer":default:return s instanceof ArrayBuffer?s:s.buffer}},Fr="",Ui=(s,t)=>{const e=s.length,n=new Array(e);let r=0;s.forEach((i,o)=>{vs(i,!1,a=>{n[o]=a,++r===e&&t(n.join(Fr))})})},qi=(s,t)=>{const e=s.split(Fr),n=[];for(let r=0;r<e.length;r++){const i=bs(e[r],t);if(n.push(i),i.type==="error")break}return n};function Vi(){return new TransformStream({transform(s,t){Pi(s,e=>{const n=e.length;let r;if(n<126)r=new Uint8Array(1),new DataView(r.buffer).setUint8(0,n);else if(n<65536){r=new Uint8Array(3);const i=new DataView(r.buffer);i.setUint8(0,126),i.setUint16(1,n)}else{r=new Uint8Array(9);const i=new DataView(r.buffer);i.setUint8(0,127),i.setBigUint64(1,BigInt(n))}s.data&&typeof s.data!="string"&&(r[0]|=128),t.enqueue(r),t.enqueue(e)})}})}let Bn;function fn(s){return s.reduce((t,e)=>t+e.length,0)}function un(s,t){if(s[0].length===t)return s.shift();const e=new Uint8Array(t);let n=0;for(let r=0;r<t;r++)e[r]=s[0][n++],n===s[0].length&&(s.shift(),n=0);return s.length&&n<s[0].length&&(s[0]=s[0].slice(n)),e}function Gi(s,t){Bn||(Bn=new TextDecoder);const e=[];let n=0,r=-1,i=!1;return new TransformStream({transform(o,a){for(e.push(o);;){if(n===0){if(fn(e)<1)break;const l=un(e,1);i=(l[0]&128)===128,r=l[0]&127,r<126?n=3:r===126?n=1:n=2}else if(n===1){if(fn(e)<2)break;const l=un(e,2);r=new DataView(l.buffer,l.byteOffset,l.length).getUint16(0),n=3}else if(n===2){if(fn(e)<8)break;const l=un(e,8),d=new DataView(l.buffer,l.byteOffset,l.length),c=d.getUint32(0);if(c>Math.pow(2,21)-1){a.enqueue(Hn);break}r=c*Math.pow(2,32)+d.getUint32(4),n=3}else{if(fn(e)<r)break;const l=un(e,r);a.enqueue(bs(i?l:Bn.decode(l),t)),n=0}if(r===0||r>s){a.enqueue(Hn);break}}}})}const Lr=4;function Et(s){if(s)return Hi(s)}function Hi(s){for(var t in Et.prototype)s[t]=Et.prototype[t];return s}Et.prototype.on=Et.prototype.addEventListener=function(s,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+s]=this._callbacks["$"+s]||[]).push(t),this};Et.prototype.once=function(s,t){function e(){this.off(s,e),t.apply(this,arguments)}return e.fn=t,this.on(s,e),this};Et.prototype.off=Et.prototype.removeListener=Et.prototype.removeAllListeners=Et.prototype.removeEventListener=function(s,t){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var e=this._callbacks["$"+s];if(!e)return this;if(arguments.length==1)return delete this._callbacks["$"+s],this;for(var n,r=0;r<e.length;r++)if(n=e[r],n===t||n.fn===t){e.splice(r,1);break}return e.length===0&&delete this._callbacks["$"+s],this};Et.prototype.emit=function(s){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),e=this._callbacks["$"+s],n=1;n<arguments.length;n++)t[n-1]=arguments[n];if(e){e=e.slice(0);for(var n=0,r=e.length;n<r;++n)e[n].apply(this,t)}return this};Et.prototype.emitReserved=Et.prototype.emit;Et.prototype.listeners=function(s){return this._callbacks=this._callbacks||{},this._callbacks["$"+s]||[]};Et.prototype.hasListeners=function(s){return!!this.listeners(s).length};const Cn=typeof Promise=="function"&&typeof Promise.resolve=="function"?t=>Promise.resolve().then(t):(t,e)=>e(t,0),jt=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),Ji="arraybuffer";function Pr(s,...t){return t.reduce((e,n)=>(s.hasOwnProperty(n)&&(e[n]=s[n]),e),{})}const Wi=jt.setTimeout,zi=jt.clearTimeout;function $n(s,t){t.useNativeTimers?(s.setTimeoutFn=Wi.bind(jt),s.clearTimeoutFn=zi.bind(jt)):(s.setTimeoutFn=jt.setTimeout.bind(jt),s.clearTimeoutFn=jt.clearTimeout.bind(jt))}const Yi=1.33;function Ki(s){return typeof s=="string"?Xi(s):Math.ceil((s.byteLength||s.size)*Yi)}function Xi(s){let t=0,e=0;for(let n=0,r=s.length;n<r;n++)t=s.charCodeAt(n),t<128?e+=1:t<2048?e+=2:t<55296||t>=57344?e+=3:(n++,e+=4);return e}function Br(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function Qi(s){let t="";for(let e in s)s.hasOwnProperty(e)&&(t.length&&(t+="&"),t+=encodeURIComponent(e)+"="+encodeURIComponent(s[e]));return t}function Zi(s){let t={},e=s.split("&");for(let n=0,r=e.length;n<r;n++){let i=e[n].split("=");t[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return t}class to extends Error{constructor(t,e,n){super(t),this.description=e,this.context=n,this.type="TransportError"}}class Ts extends Et{constructor(t){super(),this.writable=!1,$n(this,t),this.opts=t,this.query=t.query,this.socket=t.socket,this.supportsBinary=!t.forceBase64}onError(t,e,n){return super.emitReserved("error",new to(t,e,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(t){this.readyState==="open"&&this.write(t)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(t){const e=bs(t,this.socket.binaryType);this.onPacket(e)}onPacket(t){super.emitReserved("packet",t)}onClose(t){this.readyState="closed",super.emitReserved("close",t)}pause(t){}createUri(t,e={}){return t+"://"+this._hostname()+this._port()+this.opts.path+this._query(e)}_hostname(){const t=this.opts.hostname;return t.indexOf(":")===-1?t:"["+t+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(t){const e=Qi(t);return e.length?"?"+e:""}}class eo extends Ts{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(t){this.readyState="pausing";const e=()=>{this.readyState="paused",t()};if(this._polling||!this.writable){let n=0;this._polling&&(n++,this.once("pollComplete",function(){--n||e()})),this.writable||(n++,this.once("drain",function(){--n||e()}))}else e()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){const e=n=>{if(this.readyState==="opening"&&n.type==="open"&&this.onOpen(),n.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(n)};qi(t,this.socket.binaryType).forEach(e),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){const t=()=>{this.write([{type:"close"}])};this.readyState==="open"?t():this.once("open",t)}write(t){this.writable=!1,Ui(t,e=>{this.doWrite(e,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const t=this.opts.secure?"https":"http",e=this.query||{};return this.opts.timestampRequests!==!1&&(e[this.opts.timestampParam]=Br()),!this.supportsBinary&&!e.sid&&(e.b64=1),this.createUri(t,e)}}let Dr=!1;try{Dr=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const no=Dr;function so(){}class ro extends eo{constructor(t){if(super(t),typeof location<"u"){const e=location.protocol==="https:";let n=location.port;n||(n=e?"443":"80"),this.xd=typeof location<"u"&&t.hostname!==location.hostname||n!==t.port}}doWrite(t,e){const n=this.request({method:"POST",data:t});n.on("success",e),n.on("error",(r,i)=>{this.onError("xhr post error",r,i)})}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(e,n)=>{this.onError("xhr poll error",e,n)}),this.pollXhr=t}}class Xt extends Et{constructor(t,e,n){super(),this.createRequest=t,$n(this,n),this._opts=n,this._method=n.method||"GET",this._uri=e,this._data=n.data!==void 0?n.data:null,this._create()}_create(){var t;const e=Pr(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");e.xdomain=!!this._opts.xd;const n=this._xhr=this.createRequest(e);try{n.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let r in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(r)&&n.setRequestHeader(r,this._opts.extraHeaders[r])}}catch{}if(this._method==="POST")try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{n.setRequestHeader("Accept","*/*")}catch{}(t=this._opts.cookieJar)===null||t===void 0||t.addCookies(n),"withCredentials"in n&&(n.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(n.timeout=this._opts.requestTimeout),n.onreadystatechange=()=>{var r;n.readyState===3&&((r=this._opts.cookieJar)===null||r===void 0||r.parseCookies(n.getResponseHeader("set-cookie"))),n.readyState===4&&(n.status===200||n.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof n.status=="number"?n.status:0)},0))},n.send(this._data)}catch(r){this.setTimeoutFn(()=>{this._onError(r)},0);return}typeof document<"u"&&(this._index=Xt.requestsCount++,Xt.requests[this._index]=this)}_onError(t){this.emitReserved("error",t,this._xhr),this._cleanup(!0)}_cleanup(t){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=so,t)try{this._xhr.abort()}catch{}typeof document<"u"&&delete Xt.requests[this._index],this._xhr=null}}_onLoad(){const t=this._xhr.responseText;t!==null&&(this.emitReserved("data",t),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}Xt.requestsCount=0;Xt.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",mr);else if(typeof addEventListener=="function"){const s="onpagehide"in jt?"pagehide":"unload";addEventListener(s,mr,!1)}}function mr(){for(let s in Xt.requests)Xt.requests.hasOwnProperty(s)&&Xt.requests[s].abort()}const io=function(){const s=jr({xdomain:!1});return s&&s.responseType!==null}();class oo extends ro{constructor(t){super(t);const e=t&&t.forceBase64;this.supportsBinary=io&&!e}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new Xt(jr,this.uri(),t)}}function jr(s){const t=s.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!t||no))return new XMLHttpRequest}catch{}if(!t)try{return new jt[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const Ur=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class ao extends Ts{get name(){return"websocket"}doOpen(){const t=this.uri(),e=this.opts.protocols,n=Ur?{}:Pr(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(t,e,n)}catch(r){return this.emitReserved("error",r)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const n=t[e],r=e===t.length-1;vs(n,this.supportsBinary,i=>{try{this.doWrite(n,i)}catch{}r&&Cn(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const t=this.opts.secure?"wss":"ws",e=this.query||{};return this.opts.timestampRequests&&(e[this.opts.timestampParam]=Br()),this.supportsBinary||(e.b64=1),this.createUri(t,e)}}const Dn=jt.WebSocket||jt.MozWebSocket;class co extends ao{createSocket(t,e,n){return Ur?new Dn(t,e,n):e?new Dn(t,e):new Dn(t)}doWrite(t,e){this.ws.send(e)}}class lo extends Ts{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(t){return this.emitReserved("error",t)}this._transport.closed.then(()=>{this.onClose()}).catch(t=>{this.onError("webtransport error",t)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(t=>{const e=Gi(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=t.readable.pipeThrough(e).getReader(),r=Vi();r.readable.pipeTo(t.writable),this._writer=r.writable.getWriter();const i=()=>{n.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(t){this.writable=!1;for(let e=0;e<t.length;e++){const n=t[e],r=e===t.length-1;this._writer.write(n).then(()=>{r&&Cn(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this._transport)===null||t===void 0||t.close()}}const ho={websocket:co,webtransport:lo,polling:oo},fo=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,uo=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Jn(s){if(s.length>8e3)throw"URI too long";const t=s,e=s.indexOf("["),n=s.indexOf("]");e!=-1&&n!=-1&&(s=s.substring(0,e)+s.substring(e,n).replace(/:/g,";")+s.substring(n,s.length));let r=fo.exec(s||""),i={},o=14;for(;o--;)i[uo[o]]=r[o]||"";return e!=-1&&n!=-1&&(i.source=t,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=po(i,i.path),i.queryKey=mo(i,i.query),i}function po(s,t){const e=/\/{2,9}/g,n=t.replace(e,"/").split("/");return(t.slice(0,1)=="/"||t.length===0)&&n.splice(0,1),t.slice(-1)=="/"&&n.splice(n.length-1,1),n}function mo(s,t){const e={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(n,r,i){r&&(e[r]=i)}),e}const Wn=typeof addEventListener=="function"&&typeof removeEventListener=="function",gn=[];Wn&&addEventListener("offline",()=>{gn.forEach(s=>s())},!1);class Te extends Et{constructor(t,e){if(super(),this.binaryType=Ji,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,t&&typeof t=="object"&&(e=t,t=null),t){const n=Jn(t);e.hostname=n.host,e.secure=n.protocol==="https"||n.protocol==="wss",e.port=n.port,n.query&&(e.query=n.query)}else e.host&&(e.hostname=Jn(e.host).host);$n(this,e),this.secure=e.secure!=null?e.secure:typeof location<"u"&&location.protocol==="https:",e.hostname&&!e.port&&(e.port=this.secure?"443":"80"),this.hostname=e.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=e.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},e.transports.forEach(n=>{const r=n.prototype.name;this.transports.push(r),this._transportsByName[r]=n}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},e),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=Zi(this.opts.query)),Wn&&(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"})},gn.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(t){const e=Object.assign({},this.opts.query);e.EIO=Lr,e.transport=t,this.id&&(e.sid=this.id);const n=Object.assign({},this.opts,{query:e,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new this._transportsByName[t](n)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const t=this.opts.rememberUpgrade&&Te.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const e=this.createTransport(t);e.open(),this.setTransport(e)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",e=>this._onClose("transport close",e))}onOpen(){this.readyState="open",Te.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",t),this.emitReserved("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const e=new Error("server error");e.code=t.data,this._onError(e);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data);break}}onHandshake(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this._pingInterval=t.pingInterval,this._pingTimeout=t.pingTimeout,this._maxPayload=t.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const t=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+t,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},t),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const t=this._getWritablePackets();this.transport.send(t),this._prevBufferLen=t.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let n=0;n<this.writeBuffer.length;n++){const r=this.writeBuffer[n].data;if(r&&(e+=Ki(r)),n>0&&e>this._maxPayload)return this.writeBuffer.slice(0,n);e+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const t=Date.now()>this._pingTimeoutTime;return t&&(this._pingTimeoutTime=0,Cn(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),t}write(t,e,n){return this._sendPacket("message",t,e,n),this}send(t,e,n){return this._sendPacket("message",t,e,n),this}_sendPacket(t,e,n,r){if(typeof e=="function"&&(r=e,e=void 0),typeof n=="function"&&(r=n,n=null),this.readyState==="closing"||this.readyState==="closed")return;n=n||{},n.compress=n.compress!==!1;const i={type:t,data:e,options:n};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),r&&this.once("flush",r),this.flush()}close(){const t=()=>{this._onClose("forced close"),this.transport.close()},e=()=>{this.off("upgrade",e),this.off("upgradeError",e),t()},n=()=>{this.once("upgrade",e),this.once("upgradeError",e)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?n():t()}):this.upgrading?n():t()),this}_onError(t){if(Te.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",t),this._onClose("transport error",t)}_onClose(t,e){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),Wn&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const n=gn.indexOf(this._offlineEventListener);n!==-1&&gn.splice(n,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,e),this.writeBuffer=[],this._prevBufferLen=0}}}Te.protocol=Lr;class go extends Te{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let t=0;t<this._upgrades.length;t++)this._probe(this._upgrades[t])}_probe(t){let e=this.createTransport(t),n=!1;Te.priorWebsocketSuccess=!1;const r=()=>{n||(e.send([{type:"ping",data:"probe"}]),e.once("packet",y=>{if(!n)if(y.type==="pong"&&y.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",e),!e)return;Te.priorWebsocketSuccess=e.name==="websocket",this.transport.pause(()=>{n||this.readyState!=="closed"&&(c(),this.setTransport(e),e.send([{type:"upgrade"}]),this.emitReserved("upgrade",e),e=null,this.upgrading=!1,this.flush())})}else{const O=new Error("probe error");O.transport=e.name,this.emitReserved("upgradeError",O)}}))};function i(){n||(n=!0,c(),e.close(),e=null)}const o=y=>{const O=new Error("probe error: "+y);O.transport=e.name,i(),this.emitReserved("upgradeError",O)};function a(){o("transport closed")}function l(){o("socket closed")}function d(y){e&&y.name!==e.name&&i()}const c=()=>{e.removeListener("open",r),e.removeListener("error",o),e.removeListener("close",a),this.off("close",l),this.off("upgrading",d)};e.once("open",r),e.once("error",o),e.once("close",a),this.once("close",l),this.once("upgrading",d),this._upgrades.indexOf("webtransport")!==-1&&t!=="webtransport"?this.setTimeoutFn(()=>{n||e.open()},200):e.open()}onHandshake(t){this._upgrades=this._filterUpgrades(t.upgrades),super.onHandshake(t)}_filterUpgrades(t){const e=[];for(let n=0;n<t.length;n++)~this.transports.indexOf(t[n])&&e.push(t[n]);return e}}let yo=class extends go{constructor(t,e={}){const n=typeof t=="object",r=n?{...t}:{...e};(!r.transports||r.transports&&typeof r.transports[0]=="string")&&(r.transports=(r.transports||["polling","websocket","webtransport"]).map(i=>ho[i]).filter(i=>!!i)),super(n?r:t,r)}};function wo(s,t="",e){let n=s;e=e||typeof location<"u"&&location,s==null&&(s=e.protocol+"//"+e.host),typeof s=="string"&&(s.charAt(0)==="/"&&(s.charAt(1)==="/"?s=e.protocol+s:s=e.host+s),/^(https?|wss?):\/\//.test(s)||(typeof e<"u"?s=e.protocol+"//"+s:s="https://"+s),n=Jn(s)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";const i=n.host.indexOf(":")!==-1?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+i+":"+n.port+t,n.href=n.protocol+"://"+i+(e&&e.port===n.port?"":":"+n.port),n}const vo=typeof ArrayBuffer=="function",bo=s=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(s):s.buffer instanceof ArrayBuffer,qr=Object.prototype.toString,To=typeof Blob=="function"||typeof Blob<"u"&&qr.call(Blob)==="[object BlobConstructor]",Eo=typeof File=="function"||typeof File<"u"&&qr.call(File)==="[object FileConstructor]";function Es(s){return vo&&(s instanceof ArrayBuffer||bo(s))||To&&s instanceof Blob||Eo&&s instanceof File}function yn(s,t){if(!s||typeof s!="object")return!1;if(Array.isArray(s)){for(let e=0,n=s.length;e<n;e++)if(yn(s[e]))return!0;return!1}if(Es(s))return!0;if(s.toJSON&&typeof s.toJSON=="function"&&arguments.length===1)return yn(s.toJSON(),!0);for(const e in s)if(Object.prototype.hasOwnProperty.call(s,e)&&yn(s[e]))return!0;return!1}function Io(s){const t=[],e=s.data,n=s;return n.data=zn(e,t),n.attachments=t.length,{packet:n,buffers:t}}function zn(s,t){if(!s)return s;if(Es(s)){const e={_placeholder:!0,num:t.length};return t.push(s),e}else if(Array.isArray(s)){const e=new Array(s.length);for(let n=0;n<s.length;n++)e[n]=zn(s[n],t);return e}else if(typeof s=="object"&&!(s instanceof Date)){const e={};for(const n in s)Object.prototype.hasOwnProperty.call(s,n)&&(e[n]=zn(s[n],t));return e}return s}function So(s,t){return s.data=Yn(s.data,t),delete s.attachments,s}function Yn(s,t){if(!s)return s;if(s&&s._placeholder===!0){if(typeof s.num=="number"&&s.num>=0&&s.num<t.length)return t[s.num];throw new Error("illegal attachments")}else if(Array.isArray(s))for(let e=0;e<s.length;e++)s[e]=Yn(s[e],t);else if(typeof s=="object")for(const e in s)Object.prototype.hasOwnProperty.call(s,e)&&(s[e]=Yn(s[e],t));return s}const _o=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var Y;(function(s){s[s.CONNECT=0]="CONNECT",s[s.DISCONNECT=1]="DISCONNECT",s[s.EVENT=2]="EVENT",s[s.ACK=3]="ACK",s[s.CONNECT_ERROR=4]="CONNECT_ERROR",s[s.BINARY_EVENT=5]="BINARY_EVENT",s[s.BINARY_ACK=6]="BINARY_ACK"})(Y||(Y={}));class Ao{constructor(t){this.replacer=t}encode(t){return(t.type===Y.EVENT||t.type===Y.ACK)&&yn(t)?this.encodeAsBinary({type:t.type===Y.EVENT?Y.BINARY_EVENT:Y.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id}):[this.encodeAsString(t)]}encodeAsString(t){let e=""+t.type;return(t.type===Y.BINARY_EVENT||t.type===Y.BINARY_ACK)&&(e+=t.attachments+"-"),t.nsp&&t.nsp!=="/"&&(e+=t.nsp+","),t.id!=null&&(e+=t.id),t.data!=null&&(e+=JSON.stringify(t.data,this.replacer)),e}encodeAsBinary(t){const e=Io(t),n=this.encodeAsString(e.packet),r=e.buffers;return r.unshift(n),r}}class Is extends Et{constructor(t){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},typeof t=="function"?{reviver:t}:t)}add(t){let e;if(typeof t=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");e=this.decodeString(t);const n=e.type===Y.BINARY_EVENT;n||e.type===Y.BINARY_ACK?(e.type=n?Y.EVENT:Y.ACK,this.reconstructor=new Oo(e),e.attachments===0&&super.emitReserved("decoded",e)):super.emitReserved("decoded",e)}else if(Es(t)||t.base64)if(this.reconstructor)e=this.reconstructor.takeBinaryData(t),e&&(this.reconstructor=null,super.emitReserved("decoded",e));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+t)}decodeString(t){let e=0;const n={type:Number(t.charAt(0))};if(Y[n.type]===void 0)throw new Error("unknown packet type "+n.type);if(n.type===Y.BINARY_EVENT||n.type===Y.BINARY_ACK){const i=e+1;for(;t.charAt(++e)!=="-"&&e!=t.length;);const o=t.substring(i,e);if(o!=Number(o)||t.charAt(e)!=="-")throw new Error("Illegal attachments");const a=Number(o);if(!Co(a)||a<0)throw new Error("Illegal attachments");if(a>this.opts.maxAttachments)throw new Error("too many attachments");n.attachments=a}if(t.charAt(e+1)==="/"){const i=e+1;for(;++e&&!(t.charAt(e)===","||e===t.length););n.nsp=t.substring(i,e)}else n.nsp="/";const r=t.charAt(e+1);if(r!==""&&Number(r)==r){const i=e+1;for(;++e;){const o=t.charAt(e);if(o==null||Number(o)!=o){--e;break}if(e===t.length)break}n.id=Number(t.substring(i,e+1))}if(t.charAt(++e)){const i=this.tryParse(t.substr(e));if(Is.isPayloadValid(n.type,i))n.data=i;else throw new Error("invalid payload")}return n}tryParse(t){try{return JSON.parse(t,this.opts.reviver)}catch{return!1}}static isPayloadValid(t,e){switch(t){case Y.CONNECT:return gr(e);case Y.DISCONNECT:return e===void 0;case Y.CONNECT_ERROR:return typeof e=="string"||gr(e);case Y.EVENT:case Y.BINARY_EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&_o.indexOf(e[0])===-1);case Y.ACK:case Y.BINARY_ACK:return Array.isArray(e)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class Oo{constructor(t){this.packet=t,this.buffers=[],this.reconPack=t}takeBinaryData(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){const e=So(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const Co=Number.isInteger||function(s){return typeof s=="number"&&isFinite(s)&&Math.floor(s)===s};function gr(s){return Object.prototype.toString.call(s)==="[object Object]"}const $o=Object.freeze(Object.defineProperty({__proto__:null,Decoder:Is,Encoder:Ao,get PacketType(){return Y}},Symbol.toStringTag,{value:"Module"}));function Gt(s,t,e){return s.on(t,e),function(){s.off(t,e)}}const xo=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Vr extends Et{constructor(t,e,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=t,this.nsp=e,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const t=this.io;this.subs=[Gt(t,"open",this.onopen.bind(this)),Gt(t,"packet",this.onpacket.bind(this)),Gt(t,"error",this.onerror.bind(this)),Gt(t,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...t){return t.unshift("message"),this.emit.apply(this,t),this}emit(t,...e){var n,r,i;if(xo.hasOwnProperty(t))throw new Error('"'+t.toString()+'" is a reserved event name');if(e.unshift(t),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(e),this;const o={type:Y.EVENT,data:e};if(o.options={},o.options.compress=this.flags.compress!==!1,typeof e[e.length-1]=="function"){const c=this.ids++,y=e.pop();this._registerAckCallback(c,y),o.id=c}const a=(r=(n=this.io.engine)===null||n===void 0?void 0:n.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(t,e){var n;const r=(n=this.flags.timeout)!==null&&n!==void 0?n:this._opts.ackTimeout;if(r===void 0){this.acks[t]=e;return}const i=this.io.setTimeoutFn(()=>{delete this.acks[t];for(let a=0;a<this.sendBuffer.length;a++)this.sendBuffer[a].id===t&&this.sendBuffer.splice(a,1);e.call(this,new Error("operation has timed out"))},r),o=(...a)=>{this.io.clearTimeoutFn(i),e.apply(this,a)};o.withError=!0,this.acks[t]=o}emitWithAck(t,...e){return new Promise((n,r)=>{const i=(o,a)=>o?r(o):n(a);i.withError=!0,e.push(i),this.emit(t,...e)})}_addToQueue(t){let e;typeof t[t.length-1]=="function"&&(e=t.pop());const n={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((r,...i)=>(this._queue[0],r!==null?n.tryCount>this._opts.retries&&(this._queue.shift(),e&&e(r)):(this._queue.shift(),e&&e(null,...i)),n.pending=!1,this._drainQueue())),this._queue.push(n),this._drainQueue()}_drainQueue(t=!1){if(!this.connected||this._queue.length===0)return;const e=this._queue[0];e.pending&&!t||(e.pending=!0,e.tryCount++,this.flags=e.flags,this.emit.apply(this,e.args))}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){typeof this.auth=="function"?this.auth(t=>{this._sendConnectPacket(t)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:Y.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,e){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,e),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(t=>{if(!this.sendBuffer.some(n=>String(n.id)===t)){const n=this.acks[t];delete this.acks[t],n.withError&&n.call(this,new Error("socket has been disconnected"))}})}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case Y.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case Y.EVENT:case Y.BINARY_EVENT:this.onevent(t);break;case Y.ACK:case Y.BINARY_ACK:this.onack(t);break;case Y.DISCONNECT:this.ondisconnect();break;case Y.CONNECT_ERROR:this.destroy();const n=new Error(t.data.message);n.data=t.data.data,this.emitReserved("connect_error",n);break}}onevent(t){const e=t.data||[];t.id!=null&&e.push(this.ack(t.id)),this.connected?this.emitEvent(e):this.receiveBuffer.push(Object.freeze(e))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){const e=this._anyListeners.slice();for(const n of e)n.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&typeof t[t.length-1]=="string"&&(this._lastOffset=t[t.length-1])}ack(t){const e=this;let n=!1;return function(...r){n||(n=!0,e.packet({type:Y.ACK,id:t,data:r}))}}onack(t){const e=this.acks[t.id];typeof e=="function"&&(delete this.acks[t.id],e.withError&&t.data.unshift(null),e.apply(this,t.data))}onconnect(t,e){this.id=t,this.recovered=e&&this._pid===e,this._pid=e,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:Y.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){const e=this._anyListeners;for(let n=0;n<e.length;n++)if(t===e[n])return e.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(t),this}prependAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(t),this}offAnyOutgoing(t){if(!this._anyOutgoingListeners)return this;if(t){const e=this._anyOutgoingListeners;for(let n=0;n<e.length;n++)if(t===e[n])return e.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(t){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const e=this._anyOutgoingListeners.slice();for(const n of e)n.apply(this,t.data)}}}function je(s){s=s||{},this.ms=s.min||100,this.max=s.max||1e4,this.factor=s.factor||2,this.jitter=s.jitter>0&&s.jitter<=1?s.jitter:0,this.attempts=0}je.prototype.duration=function(){var s=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),e=Math.floor(t*this.jitter*s);s=Math.floor(t*10)&1?s+e:s-e}return Math.min(s,this.max)|0};je.prototype.reset=function(){this.attempts=0};je.prototype.setMin=function(s){this.ms=s};je.prototype.setMax=function(s){this.max=s};je.prototype.setJitter=function(s){this.jitter=s};class Kn extends Et{constructor(t,e){var n;super(),this.nsps={},this.subs=[],t&&typeof t=="object"&&(e=t,t=void 0),e=e||{},e.path=e.path||"/socket.io",this.opts=e,$n(this,e),this.reconnection(e.reconnection!==!1),this.reconnectionAttempts(e.reconnectionAttempts||1/0),this.reconnectionDelay(e.reconnectionDelay||1e3),this.reconnectionDelayMax(e.reconnectionDelayMax||5e3),this.randomizationFactor((n=e.randomizationFactor)!==null&&n!==void 0?n:.5),this.backoff=new je({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(e.timeout==null?2e4:e.timeout),this._readyState="closed",this.uri=t;const r=e.parser||$o;this.encoder=new r.Encoder,this.decoder=new r.Decoder,this._autoConnect=e.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,t||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(t){return t===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var e;return t===void 0?this._reconnectionDelay:(this._reconnectionDelay=t,(e=this.backoff)===null||e===void 0||e.setMin(t),this)}randomizationFactor(t){var e;return t===void 0?this._randomizationFactor:(this._randomizationFactor=t,(e=this.backoff)===null||e===void 0||e.setJitter(t),this)}reconnectionDelayMax(t){var e;return t===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,(e=this.backoff)===null||e===void 0||e.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(t){if(~this._readyState.indexOf("open"))return this;this.engine=new yo(this.uri,this.opts);const e=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const r=Gt(e,"open",function(){n.onopen(),t&&t()}),i=a=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",a),t?t(a):this.maybeReconnectOnOpen()},o=Gt(e,"error",i);if(this._timeout!==!1){const a=this._timeout,l=this.setTimeoutFn(()=>{r(),i(new Error("timeout")),e.close()},a);this.opts.autoUnref&&l.unref(),this.subs.push(()=>{this.clearTimeoutFn(l)})}return this.subs.push(r),this.subs.push(o),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(Gt(t,"ping",this.onping.bind(this)),Gt(t,"data",this.ondata.bind(this)),Gt(t,"error",this.onerror.bind(this)),Gt(t,"close",this.onclose.bind(this)),Gt(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(e){this.onclose("parse error",e)}}ondecoded(t){Cn(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,e){let n=this.nsps[t];return n?this._autoConnect&&!n.active&&n.connect():(n=new Vr(this,t,e),this.nsps[t]=n),n}_destroy(t){const e=Object.keys(this.nsps);for(const n of e)if(this.nsps[n].active)return;this._close()}_packet(t){const e=this.encoder.encode(t);for(let n=0;n<e.length;n++)this.engine.write(e[n],t.options)}cleanup(){this.subs.forEach(t=>t()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(t,e){var n;this.cleanup(),(n=this.engine)===null||n===void 0||n.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,e),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const e=this.backoff.duration();this._reconnecting=!0;const n=this.setTimeoutFn(()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),!t.skipReconnect&&t.open(r=>{r?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",r)):t.onreconnect()}))},e);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const Ge={};function Xe(s,t){typeof s=="object"&&(t=s,s=void 0),t=t||{};const e=wo(s,t.path||"/socket.io"),n=e.source,r=e.id,i=e.path,o=Ge[r]&&i in Ge[r].nsps,a=t.forceNew||t["force new connection"]||t.multiplex===!1||o;let l;return a?l=new Kn(n,t):(Ge[r]||(Ge[r]=new Kn(n,t)),l=Ge[r]),e.query&&!t.query&&(t.query=e.queryKey),l.socket(e.path,t)}Object.assign(Xe,{Manager:Kn,Socket:Vr,io:Xe,connect:Xe});class Xn extends Error{constructor(t,e){super(`The document history advanced while this version was being prepared: expected head ${t}, found ${e??"none"}. Read the timeline again and rebuild on the new head.`),this.expectedGuid=t,this.actualGuid=e,this.name="StaleHistoryError"}}const yr="bimterop",Qn="revitflow_history.json",Gr="revitflow_model.frag",Hr="revitflow_",Ro="bimterop-locks-anchor";function ko(s,t){return s.filter(e=>String(e.parentId??"")===t)}function No(s){const t=s==null?void 0:s.hiddenFileId;if(typeof t!="string"||!t)throw new Error("The hidden-file upload answered without a hiddenFileId.");return t}function Yt(s){return String(s._id??s.id??"")}var Vt,Se,ie,Ze,tn,Zn;class Ss{constructor(t,e){z(this,tn);z(this,Vt);z(this,Se,new Map);z(this,ie);z(this,Ze,0);this.client=t,this.projectId=e}async docs(){const t=await p(this,tn,Zn).call(this);if(!t)return[];const e=await this.childFolders(t,!0),n=[];for(const r of e){if(r.archived)continue;const i=String(r.name??""),o=i.indexOf("-");if(o<=0)continue;const l=(await this.client.listFiles({folderId:Yt(r)})).map(y=>String(y.name??"")),d=l.find(y=>y===Gr)??l.find(y=>y.endsWith(".frag")&&!y.startsWith(Hr)),c=l.includes(Qn)||!!d;n.push({source:i.slice(0,o),docId:i.slice(o+1),folderId:Yt(r),modelName:d,...c?{}:{empty:!0}})}return n}doc(t,e){const n=`${t}-${e}`;let r=m(this,Se).get(n);return r||(r=new ts(this.client,this,t,e),m(this,Se).set(n,r)),r}document(t){const e=`platform-${t}`;let n=m(this,Se).get(e);return n||(n=new ts(this.client,this,"platform",t,t),m(this,Se).set(e,n)),n}async childFolders(t,e=!1){return(e||!m(this,ie)||Date.now()-m(this,Ze)>3e4)&&(rt(this,Ze,Date.now()),rt(this,ie,this.client.listFolders({parentFolderId:t,projectId:this.projectId}).then(n=>ko(n,t))),m(this,ie).catch(()=>{rt(this,ie,void 0)})),m(this,ie)}forgetFolders(){rt(this,ie,void 0)}async rootFolderId(t=!1){if(m(this,Vt))return m(this,Vt);const e=await p(this,tn,Zn).call(this);if(e)return e;if(!t)return;const n=await this.client.createFolder(yr,void 0,this.projectId);return rt(this,Vt,Yt(n)),m(this,Vt)}}Vt=new WeakMap,Se=new WeakMap,ie=new WeakMap,Ze=new WeakMap,tn=new WeakSet,Zn=async function(){if(m(this,Vt))return m(this,Vt);const e=(await this.client.listFolders({projectId:this.projectId})).find(n=>String(n.name??"")===yr&&!n.parentId);return e&&rt(this,Vt,Yt(e)),m(this,Vt)};var Wt,$,re,xe,pe,zt,en,es,wn,me,Jr,vn,Wr,zr,Yr;class ts{constructor(t,e,n,r,i){z(this,$);z(this,Wt);z(this,zt);z(this,en,0);this.client=t,this.project=e,this.source=n,this.docId=r,rt(this,Wt,i)}async timeline(){const t=await p(this,$,vn).call(this);return _s((t==null?void 0:t.commits)??[])}async latest(){const t=await this.timeline();return t.length?t[t.length-1]:null}async delta(t){if(!t.deltaId)throw new Error(`Version ${t.guid} carries no delta: it is a full export — read model() instead.`);return await(await this.client.downloadHiddenFile(t.deltaId)).blob()}async model(){const t=await p(this,$,me).call(this);if(!t)throw new Error(`Document ${this.source}-${this.docId} has no model file yet.`);return await(await this.client.downloadFile(t.id)).blob()}async modelParts(t){const e=await this.timeline();if(e.length===0)throw new Error(`Document ${this.source}-${this.docId} has no history yet.`);const n=t==null?void 0:t.at,r=n?e.findIndex(c=>c.guid===n):e.length-1;if(r<0)throw new Error(`No version ${n} in this document's timeline.`);let i=0;for(let c=r;c>=0;c--)if(e[c].full){i=c;break}const o=await p(this,$,me).call(this);if(!o)throw new Error(`Document ${this.source}-${this.docId} has no model file yet.`);const a=e[i],l=e.slice(r+1).some(c=>c.full),d=e.slice(i+1,r+1).map(c=>({guid:c.guid,...c.deltaId?{deltaId:c.deltaId}:{},...c.streamId?{streamId:c.streamId}:{},removedUniqueIds:c.changes.filter(y=>y.type==="delete").map(y=>y.uniqueId)}));return{baseline:{fileId:o.id,guid:a.guid,current:!l,...a.version!==void 0?{storageVersion:a.version}:{}},steps:d,at:e[r].guid}}async folderId(){return await p(this,$,pe).call(this,!1)}async descriptor(){return await m(this,$,re).descriptor(await p(this,$,pe).call(this,!1))}async view(t){const e=await p(this,$,pe).call(this,!1),n=await m(this,$,re).descriptor(e);if(n){for(const i of t){const o=n.views.find(a=>a.format===i);if(o)return o}return null}if(!t.includes("frag"))return null;const r=await p(this,$,me).call(this);return r?{fileId:r.id,format:"frag"}:null}async addView(t){const e=await p(this,$,pe).call(this,!0);if(await m(this,$,re).descriptor(e)){await m(this,$,re).addView(e,t);return}const r=await p(this,$,me).call(this);await m(this,$,re).setDescriptor(e,{name:(r==null?void 0:r.name.replace(/\.frag$/,""))??m(this,$,xe),views:[t]})}async ensureDescriptor(){const t=await p(this,$,pe).call(this,!1),e=await m(this,$,re).descriptor(t);if(e)return e;const n=await p(this,$,me).call(this);if(!n)return null;const r={name:n.name.replace(/\.frag$/,""),views:[{fileId:n.id,format:"frag"}]};return await m(this,$,re).setDescriptor(t,r),await m(this,$,re).descriptor(t)}async ownership(){const t=await p(this,$,wn).call(this,Ro);if(!t)return[];const e=await this.client.getHiddenFilesByParent(t.id),n=await Promise.all(e.map(async o=>{try{const a=Yt(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 n)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(t){var a;const e=await p(this,$,pe).call(this,!0);let n=await p(this,$,vn).call(this)??{model:this.docId,commits:[]};const r=wr(n.commits);if(t.expectedLatestGuid!==void 0&&(r==null?void 0:r.guid)!==t.expectedLatestGuid)throw new Xn(t.expectedLatestGuid,r==null?void 0:r.guid);const i={guid:As(),...r?{parents:[r.guid]}:{},author:t.author,source:t.source,timestamp:new Date().toISOString(),...t.message?{message:t.message}:{},...t.userId?{userId:t.userId}:{},...t.kind?{kind:t.kind}:{},...t.file?{file:t.file}:{},...t.origin?{origin:t.origin}:{},...(a=t.origins)!=null&&a.length?{origins:t.origins}:{},changes:t.changes,counts:Mo(t.changes)};if(t.model&&(await p(this,$,Yr).call(this,e,t.model),i.full=!0),t.delta){const l=await p(this,$,me).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(t.delta,l.id);i.deltaId=No(d)}const o=await p(this,$,vn).call(this);if(o){n=o;const l=wr(n.commits);if(t.expectedLatestGuid!==void 0&&(l==null?void 0:l.guid)!==t.expectedLatestGuid)throw new Xn(t.expectedLatestGuid,l==null?void 0:l.guid);l&&!i.parents&&(i.parents=[l.guid])}return n.commits.push(i),await p(this,$,Wr).call(this,e,Qn,n),i}}Wt=new WeakMap,$=new WeakSet,re=function(){return new Cs(this.client,this.project.projectId)},xe=function(){return`${this.source}-${this.docId}`},pe=async function(t){if(m(this,Wt))return m(this,Wt);const e=await this.project.rootFolderId(t);if(!e)throw new Error(`Project ${this.project.projectId} has no connected documents yet.`);const n=o=>o.find(a=>String(a.name??"")===m(this,$,xe)),r=n(await this.project.childFolders(e))??n(await this.project.childFolders(e,!0));if(r)return rt(this,Wt,Yt(r)),m(this,Wt);if(!t)throw new Error(`Document ${m(this,$,xe)} does not exist in this project.`);const i=await this.client.createFolder(m(this,$,xe),e,this.project.projectId);return this.project.forgetFolders(),rt(this,Wt,Yt(i)),m(this,Wt)},zt=new WeakMap,en=new WeakMap,es=async function(){return(!m(this,zt)||Date.now()-m(this,en)>5e3)&&(rt(this,en,Date.now()),rt(this,zt,(async()=>{const t=await p(this,$,pe).call(this,!1);return(await this.client.listFiles({folderId:t})).map(n=>({id:Yt(n),name:String(n.name??"")}))})()),m(this,zt).catch(()=>{rt(this,zt,void 0)})),m(this,zt)},wn=async function(t){try{return(await p(this,$,es).call(this)).find(e=>e.name===t)}catch{return}},me=async function(){try{const t=await p(this,$,es).call(this);return t.find(e=>e.name===Gr)??t.find(e=>e.name.endsWith(".frag")&&!e.name.startsWith(Hr))}catch{return}},Jr=async function(t){const e=await p(this,$,wn).call(this,t);if(!e)return;const r=await(await this.client.downloadFile(e.id)).text();if(r.trim())return JSON.parse(r)},vn=function(){return p(this,$,Jr).call(this,Qn)},Wr=async function(t,e,n){const r=new Blob([JSON.stringify(n)],{type:"application/json"}),i=await p(this,$,wn).call(this,e);return i?(await this.client.updateFile(i.id,{file:r,versionTag:await this.client.nextVersionTag(i.id)}),i):await p(this,$,zr).call(this,t,e,n)},zr=async function(t,e,n){const r=new Blob([JSON.stringify(n)],{type:"application/json"}),i=await this.client.createFile({file:r,name:e,versionTag:"v1",parentFolderId:t,projectId:this.project.projectId});rt(this,zt,void 0);const o=i.item;return{id:Yt(o??i),name:e}},Yr=async function(t,e){const n=await p(this,$,me).call(this);if(n)return await this.client.updateFile(n.id,{file:e,versionTag:await this.client.nextVersionTag(n.id)}),n;const r=`${m(this,$,xe)}.frag`,i=await this.client.createFile({file:e,name:r,versionTag:"v1",parentFolderId:t,projectId:this.project.projectId});rt(this,zt,void 0);const o=i.item;return{id:Yt(o??i),name:r}};function Mo(s){const t={added:0,modified:0,removed:0};for(const e of s)e.type==="create"?t.added++:e.type==="delete"?t.removed++:t.modified++;return t}function _s(s){var l;if(s.length<=1)return s.forEach((d,c)=>d.ordinal=c),[...s];const t=new Map(s.map(d=>[d.guid,d])),e=new Map,n=[];for(const d of s){const c=(l=d.parents)==null?void 0:l[0];if(c&&t.has(c)){const y=e.get(c)??[];y.push(d),e.set(c,y)}else n.push(d)}const r=(d,c)=>String(d.timestamp).localeCompare(String(c.timestamp));n.sort(r);const i=[],o=[...n].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=(e.get(d.guid)??[]).sort(r);for(let y=c.length-1;y>=0;y--)o.push(c[y])}for(const d of s)a.has(d.guid)||i.push(d);return i.forEach((d,c)=>d.ordinal=c),i}function wr(s){const t=_s(s);return t[t.length-1]}function As(){const s=globalThis.crypto;return s!=null&&s.randomUUID?s.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}const Os={bim:{label:"BIM model",icon:"tabler:building"},drawings:{label:"Drawings",icon:"tabler:layout-board"},reality:{label:"Reality capture",icon:"tabler:3d-cube-sphere"},generic:{label:"Generic",icon:"tabler:file"}},Fo={rvt:"bim",rfa:"bim",ifc:"bim",frag:"bim","3dm":"bim",nwd:"bim",dgn:"bim",dwg:"drawings",dxf:"drawings",las:"reality",laz:"reality",e57:"reality",ply:"reality",potree:"reality",splat:"reality",spz:"reality",ksplat:"reality"};function ns(s){var e;if(s.type&&s.type in Os)return s.type;const t=[(e=s.native)==null?void 0:e.format,...s.views.map(n=>n.format)];for(const n of t){const r=n?Fo[n.toLowerCase()]:void 0;if(r)return r}return"generic"}const Qe="thatopen/document@1",bn="document.json",Kr=["pdf","txt","md","json","csv","tsv","frag"];function ne(s){return String(s._id??s.id??"")}var Nt,Xr,ss,Qr,Zr,Tn;class Cs{constructor(t,e){z(this,Nt);this.client=t,this.projectId=e}async list(t){const e=await p(this,Nt,Xr).call(this),n=t==null?void 0:t.types;return n!=null&&n.length?e.filter(r=>n.includes(ns(r.descriptor))):e}async fromFile(t,e){const n=await this.client.getFile(t),r=String(n.name??""),i=jn(r,n.fileExtension),o=(e==null?void 0:e.name)??r.replace(/\.[^.]+$/,"")??r,a=await this.client.createFolder(o,n.folderId?String(n.folderId):void 0,this.projectId),l=ne(a);await this.client.updateFile(t,{parentFolderId:l});const d=[],c=await p(this,Nt,Qr).call(this,n);if(c)try{const b=await this.client.getFile(c);await this.client.updateFile(c,{parentFolderId:l}),d.push({fileId:c,format:jn(String(b.name??""),b.fileExtension)})}catch{}((e==null?void 0:e.selfView)??Kr.includes(i))&&d.push({fileId:t,format:i});const O={schema:Qe,name:o,native:{fileId:t,format:i},views:d};return O.type=(e==null?void 0:e.type)??ns(O),await this.setDescriptor(l,O),await this.recordUpload(l,{fileId:t,name:r,format:i},(e==null?void 0:e.author)??String(n.createdBy??"")),{folderId:l,descriptor:O}}async recordUpload(t,e,n){const r=new Ss(this.client,this.projectId).document(t),i=(await r.timeline()).length===0;await r.sync({author:n||"unknown",source:"platform",kind:"upload",message:i?"Uploaded to the platform":"New version uploaded",file:{...e,format:e.format??jn(e.name,void 0)},changes:[]})}async descriptor(t){const e=await p(this,Nt,Tn).call(this,t);return e?p(this,Nt,ss).call(this,e.id):null}async view(t,e){const n=await this.descriptor(t);if(!n)return null;for(const r of e){const i=n.views.find(o=>o.format===r);if(i)return i}return null}async addView(t,e){const n=await this.descriptor(t);if(!n)throw new Error("This folder has no document descriptor yet: call setDescriptor first.");n.views=[...n.views.filter(r=>r.format!==e.format),e],await this.setDescriptor(t,n)}async setType(t,e){const n=await this.descriptor(t);if(!n)throw new Error("This folder has no document descriptor yet: call setDescriptor first.");n.type!==e&&await this.setDescriptor(t,{...n,type:e})}async setDescriptor(t,e){const n={...e,schema:Qe,views:e.views??[]},r=new Blob([JSON.stringify(n)],{type:"application/json"}),i=await p(this,Nt,Tn).call(this,t);if(i){await this.client.updateFile(i.id,{file:r,versionTag:await this.client.nextVersionTag(i.id)});return}await this.client.createFile({file:r,name:bn,versionTag:"v1",parentFolderId:t,projectId:this.projectId})}drafts(t){return new ti(this.client,()=>p(this,Nt,Tn).call(this,t))}}Nt=new WeakSet,Xr=async function(){const e=(await this.client.listFiles({projectId:this.projectId})).filter(r=>String(r.name??"")===bn);return(await Promise.all(e.map(async r=>{const i=r,o=String(i.folderId??i.parentFolderId??"");if(!o)return null;const a=await p(this,Nt,ss).call(this,ne(r));return a?{folderId:o,descriptor:a}:null}))).filter(r=>r!==null)},ss=async function(t){const n=await(await this.client.downloadFile(t)).text();if(!n.trim())return null;let r;try{r=JSON.parse(n)}catch{return null}return Do(r)},Qr=async function(t){let e=t.versions??[],n;if(e.length===0){n=await this.client.listFiles({projectId:this.projectId}).catch(()=>[]);const a=n.find(l=>ne(l)===ne(t));e=(a==null?void 0:a.versions)??[]}const r=await p(this,Nt,Zr).call(this,t,e);if(r)return r;const i=String(t.name??"").replace(/\.[^.]+$/,"").toLowerCase();if(!i)return;n??(n=await this.client.listFiles({projectId:this.projectId}).catch(()=>[]));const o=n.find(a=>String(a.name??"").toLowerCase()===`${i}.frag`&&!a.archived&&ne(a)!==ne(t));return o?ne(o):void 0},Zr=async function(t,e){const n=[...e].sort((r,i)=>String(i.createdAt??"").localeCompare(String(r.createdAt??"")));for(const r of n)try{const i=await this.client.getFileVersionMetadata(ne(t),r.tag),o=i==null?void 0:i.derivedFileId;if(typeof o=="string"&&o)return o}catch{}},Tn=async function(t){const n=(await this.client.listFiles({folderId:t})).find(r=>String(r.name??"")===bn);return n?{id:ne(n)}:void 0};const rs="draft:",Re="TODRAFT1";var Kt,ze,is;class ti{constructor(t,e){z(this,Kt);this.client=t,this.holder=e}async list(){const t=await this.holder();if(!t)return[];const e=new Map;for(const n of await p(this,Kt,ze).call(this,t.id)){const r=e.get(n.userId);(!r||n.savedAt>r.savedAt)&&e.set(n.userId,{userId:n.userId,savedAt:n.savedAt})}return[...e.values()].sort((n,r)=>+r.savedAt-+n.savedAt)}async get(t){const e=await this.holder();if(!e)return null;const r=(await p(this,Kt,ze).call(this,e.id)).filter(l=>!(t!=null&&t.userId)||l.userId===t.userId).sort((l,d)=>+d.savedAt-+l.savedAt)[0];if(!r)return null;const i=await this.client.downloadHiddenFile(r.hiddenId),{meta:o,blob:a}=await Bo(await i.blob());return{userId:r.userId,savedAt:r.savedAt,meta:o,blob:a}}async put(t,e){const n=await this.holder();if(!n)throw new Error("This folder is not a document (no document.json): drafts need one.");const r=Lo(e.userId),i=(await p(this,Kt,ze).call(this,n.id)).filter(l=>l.userId===e.userId),a=(await this.client.createHiddenFile(await Po(t,e.meta??{}),n.id,r)).hiddenFileId;if(!a)throw new Error("The draft upload answered without a hiddenFileId.");return await p(this,Kt,is).call(this,i.map(l=>l.hiddenId)),{userId:e.userId,savedAt:vr(a)}}async delete(t){const e=await this.holder();if(!e)return;const n=(await p(this,Kt,ze).call(this,e.id)).filter(r=>r.userId===t.userId);await p(this,Kt,is).call(this,n.map(r=>r.hiddenId))}}Kt=new WeakSet,ze=async function(t){return(await this.client.getHiddenFilesByParent(t)).filter(n=>typeof n.tag=="string"&&n.tag.startsWith(rs)).map(n=>{const r=String(n._id);return{hiddenId:r,userId:n.tag.slice(rs.length),savedAt:vr(r)}})},is=async function(t){for(const e of t)try{await this.client.deleteHiddenFile(e)}catch{}};function Lo(s){const t=`${rs}${s}`;if(!/^[A-Za-z0-9][A-Za-z0-9:._-]{0,49}$/.test(t))throw new Error(`A draft cannot be tagged for user "${s}": ids must be letters, digits or :._- and short.`);return t}function vr(s){const t=parseInt(s.slice(0,8),16);return new Date(Number.isFinite(t)?t*1e3:0)}async function Po(s,t){const e=new TextEncoder().encode(JSON.stringify(t)),n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,e.length,!0),new Blob([new TextEncoder().encode(Re),n,e,s])}async function Bo(s){const t=new Uint8Array(await s.slice(0,Re.length+4).arrayBuffer());if(new TextDecoder().decode(t.slice(0,Re.length))!==Re)return{meta:{},blob:s};const e=new DataView(t.buffer).getUint32(Re.length,!0),n=Re.length+4,r=await s.slice(n,n+e).text();let i={};try{i=JSON.parse(r)}catch{}return{meta:i,blob:s.slice(n+e)}}function jn(s,t){const e=(t??"").replace(/^\./,"").toLowerCase();if(e)return e;const n=s.lastIndexOf(".");return n>0?s.slice(n+1).toLowerCase():""}function Do(s){if(!s||typeof s!="object")return null;const t=s;if(t.schema!==Qe||typeof t.name!="string")return null;const e=Array.isArray(t.views)?t.views.filter(o=>!!o&&typeof o=="object"&&typeof o.fileId=="string"&&typeof o.format=="string"):[],n=t.native,r=!!n&&typeof n=="object"&&typeof n.fileId=="string"&&typeof n.format=="string",i=typeof t.type=="string"&&t.type in Os?t.type:void 0;return{schema:Qe,name:t.name,...i?{type:i}:{},...r?{native:{fileId:n.fileId,format:n.format}}:{},views:e}}const jo="flow:",Uo="flow:op",qo="flow:source",Vo="flow:host",$s="revitflow/op@2",br="REVITFLOWCHANGE",Tr="REVITFLOWOPERATION";class xn{constructor(t){xt(this,"changes",[]);this.target=t}get length(){return this.changes.length}get batchId(){return this.target.batchId}get title(){return this.target.title??`${this.changes.length} change(s)`}get author(){return this.target.author??"app"}get userId(){return this.target.userId}get baseCommit(){return this.target.baseCommit}add(t,e={}){return this.changes.push({op:"add",attrs:this.pack(t,e)}),this}set(t,e,n={}){return this.requireId(t,"set"),this.changes.push({op:"set",item:t,attrs:this.pack(e,n)}),this}remove(t){return this.requireId(t,"remove"),this.changes.push({op:"remove",item:t,attrs:{}}),this}get summary(){const t=new Set(this.changes.map(e=>e.op));return t.size===1?[...t][0]:"mixed"}async build(t){if(this.changes.length===0)throw new Error("An operation with no changes is not an operation. Add at least one.");const e={schema:$s,opId:t,batchId:this.batchId??t,targetProject:this.target.project,targetDocument:this.target.document,baseCommit:this.baseCommit,author:this.author,...this.userId?{userId:this.userId}:{},title:this.title,summary:this.summary},[n,r]=await Go();return Ho(this.flatbuffer(n,r,t,JSON.stringify(e)))}pack(t,e){const n={};for(const[r,i]of Object.entries(t??{}))r.startsWith(jo)||(n[r]=String(i));return e.position&&(n.Position=e.position.map(Er).join(",")),e.rotationDeg!==void 0&&(n.Rotation=Er(e.rotationDeg)),e.source&&(n[qo]=e.source),e.host&&(n[Vo]=e.host),n}requireId(t,e){if(!t||!t.trim())throw new Error(`A '${e}' has to name the item it acts on.`)}flatbuffer(t,e,n,r){const{Attribute:i,Meshes:o,Model:a,SpatialStructure:l,Transform:d}=e,c=new t.Builder(1024),y=this.changes.length,O=new Uint32Array(y);let b=1;for(let bt=0;bt<y;bt++)O[bt]=b++;const B=b++,H=bt=>(bt(c,0),c.endVector()),G=o.createShellsVector(c,[]),F=o.createCircleExtrusionsVector(c,[]),D=H(o.startSamplesVector),u=H(o.startRepresentationsVector),L=H(o.startMaterialsVector),I=H(o.startLocalTransformsVector),j=H(o.startGlobalTransformsVector),st=o.createMeshesItemsVector(c,[]),Z=o.createMaterialIdsVector(c,[]),mt=o.createRepresentationIdsVector(c,[]),Rt=o.createSampleIdsVector(c,[]),Tt=o.createLocalTransformIdsVector(c,[]),Zt=o.createGlobalTransformIdsVector(c,[]);o.startMeshes(c),o.addCoordinates(c,d.createTransform(c,0,0,0,1,0,0,0,1,0)),o.addGlobalTransforms(c,j),o.addShells(c,G),o.addRepresentations(c,u),o.addSamples(c,D),o.addLocalTransforms(c,I),o.addMaterials(c,L),o.addCircleExtrusions(c,F),o.addMeshesItems(c,st),o.addRepresentationIds(c,mt),o.addSampleIds(c,Rt),o.addMaterialIds(c,Z),o.addLocalTransformIds(c,Tt),o.addGlobalTransformIds(c,Zt);const Ee=o.endMeshes(c),te=c.createString(r),Q=new Set,J=[];for(const bt of this.changes){const Ut=[],Ae={[Uo]:bt.op,...bt.attrs};for(const[ln,Ue]of Object.entries(Ae)){const Oe=JSON.stringify([ln,Ue,"IFCTEXT"]);Q.add(Oe),Ut.push(c.createString(Oe))}J.push(i.createAttribute(c,i.createDataVector(c,Ut)))}{const bt=JSON.stringify(["Name",n,"IFCLABEL"]);Q.add(bt);const Ut=i.createDataVector(c,[c.createString(bt)]);J.push(i.createAttribute(c,Ut))}const E=a.createAttributesVector(c,J),kt=a.createUniqueAttributesVector(c,[...Q].map(bt=>c.createString(bt))),lt=this.changes.map(()=>c.createString(br));lt.push(c.createString(Tr));const At=a.createCategoriesVector(c,lt),Mt=[],Lt=[];this.changes.forEach((bt,Ut)=>{bt.item&&(Mt.push(c.createString(bt.item)),Lt.push(O[Ut]))});const Ot=a.createGuidsVector(c,Mt),tt=a.createGuidsItemsVector(c,Lt),vt=a.createLocalIdsVector(c,[...O,B]),Ht=this.changes.map((bt,Ut)=>l.createSpatialStructure(c,O[Ut],c.createString(br),0)),le=l.createSpatialStructure(c,B,c.createString(Tr),l.createChildrenVector(c,Ht)),ee=c.createString(n);a.startModel(c),a.addMeshes(c,Ee),a.addMetadata(c,te),a.addAttributes(c,E),a.addUniqueAttributes(c,kt),a.addLocalIds(c,vt),a.addCategories(c,At),a.addGuidsItems(c,tt),a.addGuids(c,Ot),a.addGuid(c,ee),a.addSpatialStructure(c,le),a.addMaxLocalId(c,b);const It=a.endModel(c);return a.finishModelBuffer(c,It),c.asUint8Array()}}async function Go(){try{return await Promise.all([import("flatbuffers"),import("@thatopen/fragments")])}catch(s){throw new Error(`OperationBuilder needs the optional peers \`flatbuffers\` and \`@thatopen/fragments\` installed — add them to the app that authors operations. (${s instanceof Error?s.message:String(s)})`)}}function Er(s){return Number.isFinite(s)?String(s):"0"}async function Ho(s){const t=new Blob([s]).stream().pipeThrough(new CompressionStream("deflate"));return new Uint8Array(await new Response(t).arrayBuffer())}async function Rn(s){const[t,e]=await Jo(),n=e.Model.getRootAsModel(new t.ByteBuffer(await Wo(s)));let r={};try{r=JSON.parse(n.metadata()??"{}")}catch{}const i=new Map;for(let a=0;a<n.guidsLength();a++){const l=n.guidsItems(a),d=n.guids(a);l!==null&&d&&i.set(l,d)}const o=[];for(let a=0;a<n.attributesLength();a++){const l=n.localIds(a);if(l===null)continue;const d={},c=n.attributes(a);for(let y=0;y<((c==null?void 0:c.dataLength())??0);y++){const O=c.data(y);if(O)try{const[b,B]=JSON.parse(O);d[b]=B}catch{}}o.push({localId:l,guid:i.get(l)??null,category:n.categories(a)??null,attrs:d})}return{metadata:r,items:o}}async function Jo(){try{return await Promise.all([import("flatbuffers"),import("@thatopen/fragments")])}catch(s){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). (${s instanceof Error?s.message:String(s)})`)}}async function Wo(s){const t=new Blob([s]).stream().pipeThrough(new DecompressionStream("deflate"));return new Uint8Array(await new Response(t).arrayBuffer())}const ei="Element",ni="Carried",Ne=1/.3048;function si(s){const t=[];for(const e of s)for(const n of[ei,ni]){const r=e.attrs[n];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"||t.push({id:a.id,kind:a.kind,params:a.params??{},item:e})}}catch{}}return t}function Pt(s,t){const e=s.params[t];if(typeof e!="string")return null;try{return JSON.parse(e)}catch{return null}}function zo(s){const t=new Map;for(const[e,n]of xs(s))t.set(e,n.name);return t}function xs(s){const t=new Map;for(const e of s){if(e.kind!=="datum"||e.params.of!=="level")continue;const n=e.params.named,r=e.params.at;typeof n=="string"&&typeof r=="number"&&t.set(e.id,{name:n,at:r})}return t}function ri(s){const t=new Map;for(const e of s){if(!e.kind.endsWith("Style"))continue;const n=e.params.name;typeof n=="string"&&t.set(n,e)}return t}function Rs(s,t){const e=new Map;for(const[n,r]of s.made)e.set(n,r.id),r.print&&(t==null||t.set(n,r.print));return e}function ii(s){const t=r=>Array.isArray(r)?r.map(t):r&&typeof r=="object"?Object.fromEntries(Object.keys(r).sort().map(i=>[i,t(r[i])])):r,e=JSON.stringify(t(s));let n=2166136261;for(let r=0;r<e.length;r++)n^=e.charCodeAt(r),n=Math.imul(n,16777619);return(n>>>0).toString(36)}async function ks(s,t){var o,a;if(!(t!=null&&t.fileId))throw new Error("Choose the model file to read.");s.progress(`Downloading ${t.name}`);let e=new Uint8Array(await(await s.client.downloadFile(t.fileId,t.version?{versionTag:t.version}:void 0)).arrayBuffer());const n=((a=(o=/\.([^.]+)$/.exec(t.name))==null?void 0:o[1])==null?void 0:a.toLowerCase())??"frag";let r=null,i=null;if(n!=="frag"){const l=s.client.recipes.importerFor(n);if(!l)throw new Error(`This app cannot read .${n} files: it provides no importer for them.`);n==="ifc"&&(r=oi(e));const d=s.client.recipes.shapesFor(n);d&&(s.progress(`Reading the shapes of ${t.name}`),i=await d(e,t.name)),s.progress(`Reading ${t.name}`),e=await l(e,t.name)}return{picked:t,contents:await Rn(e),site:r,shapes:i}}function oi(s){var j;const t=new TextDecoder("latin1").decode(s),e=st=>new RegExp(`^${st}=\\s*([A-Z0-9_]+)\\((.*)\\);\\s*$`,"m").exec(t),n=st=>[...st.matchAll(/#\d+|\$/g)].map(Z=>Z[0]),r=st=>[...st.matchAll(/-?\d+(?:\.\d*)?(?:E[-+]?\d+)?/gi)].map(Z=>Number(Z[0])),i=/^(#\d+)=\s*IFCSITE\((.*)\);\s*$/m.exec(t);if(!i)return null;const o=(j=i[2].split(",")[5])==null?void 0:j.trim();if(!(o!=null&&o.startsWith("#")))return null;const a=e(o);if((a==null?void 0:a[1])!=="IFCLOCALPLACEMENT")return null;const[l,d]=n(a[2]);if(l!=="$"||!d)return null;const c=e(d);if((c==null?void 0:c[1])!=="IFCAXIS2PLACEMENT3D")return null;const[y,,O]=n(c[2]),b=y&&y!=="$"?e(y):null;if(!b)return null;const[B=0,H=0,G=0]=r(b[2]);let F=0;const D=O&&O!=="$"?e(O):null;if(D){const[st=1,Z=0]=r(D[2]);F=Math.atan2(Z,st)*180/Math.PI}const u=/IFCSIUNIT\([^)]*\.LENGTHUNIT\.\s*,\s*(\.([A-Z]+)\.|\$)\s*,\s*\.METRE\./i.exec(t),L={MILLI:.001,CENTI:.01,DECI:.1,KILO:1e3},I=u?u[2]?L[u[2].toUpperCase()]??1:1:/IFCCONVERSIONBASEDUNIT\([^)]*\.LENGTHUNIT\.[^)]*'FOOT'/i.test(t)?.3048:1;return{east:B*I,north:H*I,elevation:G*I,angleDeg:F}}const Ns="thatopen/recipe@1",Ir="__project_data",Sr="recipes",Yo=s=>`${s}.recipe.json`,ai={OperationBuilder:xn,OP_SCHEMA:$s,readFrag:Rn,readPickedFrag:ks,recordsOf:si,innerJson:Pt,levelsOf:xs,levelNames:zo,stylesOf:ri,printOf:ii,siteLocationOf:oi,whatItMadeBefore:Rs,ELEMENT_FIELD:ei,CARRIED_FIELD:ni,FEET_PER_METRE:Ne},ci=/^[a-z0-9][a-z0-9-]{1,62}$/;async function li(s,t,e){const n=d=>[...d].sort((c,y)=>String(c._id).localeCompare(String(y._id)))[0],r=await s.listFolders({projectId:t,archived:!1});let i=n(r.filter(d=>d.name===Ir&&!d.parentId));if(!i){if(!e)return null;i=await s.createFolder(Ir,void 0,t)}const o=String(i._id),a=await s.listFolders({parentFolderId:o,projectId:t,archived:!1});let l=n(a.filter(d=>d.name===Sr&&String(d.parentId)===o));if(!l){if(!e)return null;l=await s.createFolder(Sr,o,t)}return String(l._id)}const Ko=s=>String(s._id??s.id??""),Xo=s=>String(s.tag??s.versionTag??""),os=s=>{var t;return Number(((t=/(\d+)/.exec(s))==null?void 0:t[1])??-1)};async function He(s,t){const e=await li(s,t,!1);if(!e)return new Map;const n=await s.listFiles({folderId:e}),r=new Map;for(const i of n){const o=String(i.name??"");o.endsWith(".recipe.json")&&r.set(o.slice(0,-12),{id:Ko(i)})}return r}async function pn(s,t,e){var i;const n=await s.downloadFile(t,e?{versionTag:e}:void 0),r=JSON.parse(await n.text());if((r==null?void 0:r.schema)!==Ns||!((i=r.manifest)!=null&&i.name)||typeof r.code!="string")throw new Error(`This is not a recipe this library can read (${String(r==null?void 0:r.schema)}).`);return r}async function Je(s,t){return(await s.listVersions(t)).map(n=>({tag:Xo(n),createdAt:String(n.createdAt??"")})).filter(n=>n.tag).sort((n,r)=>os(n.tag)-os(r.tag))}var nn;class hi{constructor(t,e){z(this,nn,new Map);this.client=t,this.builtinNames=e}async list(t){const e=await He(this.client,t);return(await Promise.all([...e.entries()].map(async([,{id:r}])=>{var i;try{const o=await Je(this.client,r),a=(i=o[o.length-1])==null?void 0:i.tag,l=await pn(this.client,r,a);return{manifest:l.manifest,origin:"project",version:a,author:l.author,savedAt:l.savedAt}}catch{return null}}))).filter(r=>r!==null)}async versions(t,e){const n=(await He(this.client,t)).get(e);if(!n)throw new Error(`The project has no recipe named "${e}".`);const r=await Je(this.client,n.id);return await Promise.all(r.map(async({tag:i,createdAt:o})=>{try{const a=await pn(this.client,n.id,i);return{version:i,author:a.author,note:a.note,savedAt:a.savedAt??o}}catch{return{version:i,savedAt:o}}}))}async source(t,e,n){var o;const r=(await He(this.client,t)).get(e);if(!r)throw new Error(`The project has no recipe named "${e}".`);const i=n??((o=(await Je(this.client,r.id)).pop())==null?void 0:o.tag);if(!i)throw new Error(`The recipe "${e}" has no saved version.`);return{...await pn(this.client,r.id,i),version:i}}async save(t,e,n){const{manifest:r,code:i}=e;if(!ci.test((r==null?void 0:r.name)??""))throw new Error('A recipe name is lower case letters, digits and dashes, 2 to 63 of them: "walls-from-ifc".');if(this.builtinNames().has(r.name))throw new Error(`"${r.name}" is a built-in recipe. Give yours a name of its own.`);if(!r.to||!r.description||!Array.isArray(r.inputs))throw new Error("A recipe says what it writes (`to`), what it does (`description`) and what it reads (`inputs`).");await as(r,i);const o={schema:Ns,manifest:r,code:i,author:n.author,...n.note?{note:n.note}:{},savedAt:new Date().toISOString()},a=new Blob([JSON.stringify(o,null,2)],{type:"application/json"}),l=(await He(this.client,t)).get(r.name);if(l){const c=await Je(this.client,l.id),y=`v${Math.max(0,...c.map(O=>os(O.tag)))+1}`;return await this.client.createVersion(l.id,a,y),y}const d=await li(this.client,t,!0);return await this.client.createFile({file:a,name:Yo(r.name),versionTag:"v1",projectId:t,parentFolderId:d}),"v1"}async load(t,e,n){var l;const r=(await He(this.client,t)).get(e);if(!r)throw new Error(`The project has no recipe named "${e}".`);const i=n??((l=(await Je(this.client,r.id)).pop())==null?void 0:l.tag);if(!i)throw new Error(`The recipe "${e}" has no saved version.`);const o=`${r.id}@${i}`;let a=m(this,nn).get(o);if(!a){const d=await pn(this.client,r.id,i);a=await as(d.manifest,d.code),m(this,nn).set(o,a)}return{recipe:a,version:i}}}nn=new WeakMap;async function as(s,t){var r;let e;try{e=await import(`data:text/javascript;base64,${Qo(t)}`)}catch(i){throw new Error(`The recipe's code does not load: ${i instanceof Error?i.message:String(i)}`)}const n=e.run??((r=e.default)==null?void 0:r.run);if(typeof n!="function")throw new Error("The recipe's code exports no `run(context)` function.");return{...s,run:i=>n({...i,kit:ai})}}function Qo(s){const t=new TextEncoder().encode(s);let e="";for(let n=0;n<t.length;n+=32768)e+=String.fromCharCode(...t.subarray(n,n+32768));return btoa(e)}async function Zo(s){const t=s instanceof Uint8Array?s:new Uint8Array(await s.arrayBuffer()),{items:e,metadata:n}=await Rn(t),r=e.filter(i=>i.attrs["flow:op"]).map(i=>{const o={};for(const[a,l]of Object.entries(i.attrs))a.startsWith("flow:")||(o[a]=l);return{op:i.attrs["flow:op"],...i.guid?{target:i.guid}:{},...i.attrs["flow:source"]?{source:i.attrs["flow:source"]}:{},attrs:o}});return{envelope:n??{},changes:r}}class Ms extends Error{constructor(t){super(t),this.name="UpToDate"}}var oe,sn,rn;class di{constructor(t){z(this,oe,new Map);z(this,sn,new Map);z(this,rn,new Map);xt(this,"project");this.client=t,this.project=new hi(t,()=>new Set(m(this,oe).keys()))}provideImporter(t,e){m(this,sn).set(t.toLowerCase(),e)}provideShapes(t,e){m(this,rn).set(t.toLowerCase(),e)}shapesFor(t){return m(this,rn).get(t.toLowerCase())}importerFor(t){return m(this,sn).get(t.toLowerCase())}register(t){if(m(this,oe).has(t.name))throw new Error(`A recipe named "${t.name}" is already registered.`);m(this,oe).set(t.name,t)}list(t){return[...m(this,oe).values()].filter(n=>(!(t!=null&&t.to)||n.to===t.to)&&(!(t!=null&&t.input)||n.inputs.includes(t.input)))}get(t){return m(this,oe).get(t)}async catalog(t,e){const n=this.list(e).map(i=>({manifest:i,origin:"builtin"}));let r=[];try{r=(await this.project.list(t)).filter(i=>!(e!=null&&e.to)||i.manifest.to===e.to)}catch{}return[...n,...r.sort((i,o)=>i.manifest.name.localeCompare(o.manifest.name))]}async resolve(t,e,n){const r=m(this,oe).get(t);return r?{recipe:r,origin:"builtin"}:{...await this.project.load(e,t,n),origin:"project"}}async choices(t,e){const{recipe:n}=await this.resolve(t,e),r=n.source;if((r==null?void 0:r.kind)!=="project-file")return[];const i=(r.extensions??[]).map(d=>d.toLowerCase()),a=(await this.client.documents(e).list()).filter(d=>d.descriptor.native&&(i.length===0||i.includes(d.descriptor.native.format.toLowerCase()))),l=await fi(this.client,a.map(d=>d.descriptor.native.fileId));return a.map(d=>{const c=d.descriptor.native;return{label:d.descriptor.name,fileId:c.fileId,name:`${d.descriptor.name}.${c.format}`,folderId:d.folderId,version:l.get(c.fileId)??"v1"}}).sort((d,c)=>d.label.localeCompare(c.label))}async run(t,e){const{recipe:n}=await this.resolve(t,e.projectId,e.recipeVersion);if(n.to!==e.target.source)throw new Error(`Recipe "${t}" writes ${n.to}, but the target document belongs to ${e.target.source}.`);return await n.run({client:this.client,projectId:e.projectId,target:e.target,made:e.made??new Map,opId:e.opId??As(),input:e.input,settings:e.settings??{},progress:e.progress??(()=>{})})}}oe=new WeakMap,sn=new WeakMap,rn=new WeakMap;async function fi(s,t){const e=new Map;if(t.length===0)return e;const n=i=>{var o;return Number(((o=/(\d+)/.exec(String(i??"")))==null?void 0:o[1])??-1)},r=i=>{const a=i.slice().sort((l,d)=>{const c=l!=null&&l.createdAt?new Date(String(l.createdAt)).getTime():NaN,y=d!=null&&d.createdAt?new Date(String(d.createdAt)).getTime():NaN;return!Number.isNaN(c)&&!Number.isNaN(y)&&c!==y?y-c:n((d==null?void 0:d.tag)??(d==null?void 0:d.versionTag))-n((l==null?void 0:l.tag)??(l==null?void 0:l.versionTag))})[0];return a?String(a.tag??a.versionTag??"v1"):"v1"};return await Promise.all(t.map(async i=>{try{e.set(i,r(await s.listVersions(i)))}catch{e.set(i,"v1")}})),e}const cs=100;function ta(s){try{const t=JSON.parse(s);if(t&&typeof t=="object"){const e=t;return{message:typeof e.message=="string"?e.message:void 0,code:typeof e.code=="string"?e.code:void 0,details:e.details}}}catch{}return{}}function ea(s){if(!s||typeof s!="object")return;const t=s.retryAfter;return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}class kn extends Error{constructor(e,n,r,i){const o=ta(r);super(o.message??`${n||"Request failed"} (${e})`);xt(this,"status");xt(this,"code");xt(this,"details");xt(this,"body");xt(this,"retryAfter");this.name="RequestError",this.status=e,this.code=o.code,this.details=o.details,this.body=r,this.retryAfter=i??ea(o.details)}}const Jt="item/folder",U="item",fe="processor",na="npm-registry",se="hidden",Un="FILE",qn="TOOL",Vn="APP",sa=500,_r=3e4,ra=.25,ia=s=>new Promise(t=>setTimeout(t,s));function oa(s){var r,i;const t=(i=(r=s.headers)==null?void 0:r.get)==null?void 0:i.call(r,"Retry-After");if(!t)return;const e=Number(t);if(Number.isFinite(e))return Math.max(0,e);const n=Date.parse(t);if(!Number.isNaN(n))return Math.max(0,(n-Date.now())/1e3)}function aa(s){return s instanceof kn?s.status===429||s.status>=500:!0}function ca(s,t){const e=Math.min(sa*2**t,_r),n=e*ra*Math.random(),r=s instanceof kn&&s.retryAfter!=null?s.retryAfter*1e3:void 0;return r!=null?Math.min(r,_r)+n:e+n}var v,ls,C,ge,on,Ye,En,In,hs,ds,ui;const Ps=class Ps{constructor(t,e,n){z(this,v);xt(this,"apiUrl");xt(this,"accessToken");xt(this,"wsUrl");xt(this,"retries");xt(this,"useBearer");xt(this,"builtInGlobals",null);xt(this,"localServerUrl",null);xt(this,"context");z(this,on);const{retries:r=0,useBearer:i=!1,localServerUrl:o}=n||{};let a=e;if(a.charAt(a.length-1)==="/"&&(a=a.slice(0,-1)),this.apiUrl=`${a}/api`,this.accessToken=t,this.wsUrl=a,this.retries=r,this.useBearer=i,this.context={appId:"",projectId:"",accessToken:t,apiUrl:e},o){let l=o;l.charAt(l.length-1)==="/"&&(l=l.slice(0,-1)),this.localServerUrl=l}}static fromPlatformContext(t){const e=(typeof window<"u"?window.__THATOPEN_CONTEXT__:null)||{appId:"",projectId:"",accessToken:"",apiUrl:""},n=new Ps(e.accessToken,e.apiUrl,{...t,useBearer:!0});return n.context=e,n}setRetries(t){this.retries=t}setBuiltInGlobals(t){this.builtInGlobals=t}get socketOrigin(){return this.wsUrl.split("?")[0]}async resolveAccessToken(){return this.accessToken}async request(t,e,n){return p(this,v,C).call(this,t,e,n)}async listFiles(t){const{folderId:e,archived:n,projectId:r}=t||{};return e?await p(this,v,C).call(this,"GET",`${Jt}/${e}/items`,{query:{itemType:Un,archived:n}}):await p(this,v,C).call(this,"GET",`${U}`,{query:{itemType:Un,archived:n,...r&&{projectId:r}}})}async getFile(t,e){return await p(this,v,ds).call(this,t,e)}async createFile(t){return await p(this,v,In).call(this,t,Un)}async updateFile(t,e){return await p(this,v,hs).call(this,t,e)}async archiveFile(t){return await p(this,v,C).call(this,"DELETE",`${U}/${t}`)}async recoverFile(t){return await p(this,v,C).call(this,"PUT",`${U}/${t}/recover`)}async downloadFile(t,e){return await p(this,v,En).call(this,t,e)}async getFileVersionMetadata(t,e,n){const{withDraft:r}=n||{};return await p(this,v,C).call(this,"GET",`${U}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/metadata`,{query:{...r&&{withDraft:"true"}}})}async updateFileVersionMetadata(t,e,n){return await p(this,v,C).call(this,"PUT",`${U}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/metadata`,{body:JSON.stringify({metadata:n}),contentType:"application/json"})}async deleteFileVersionMetadata(t,e){return await p(this,v,C).call(this,"DELETE",`${U}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/metadata`)}async getFileVersionMetadataBatch(t,e){const{withDraft:n}=e||{};return await p(this,v,Ye).call(this,t,async r=>(await p(this,v,C).call(this,"POST",`${U}/batch/version-metadata`,{body:JSON.stringify({entries:r,...n!==void 0&&{withDraft:n}}),contentType:"application/json"})).results)}async listFolders(t){const{archived:e,parentFolderId:n,projectId:r}=t||{};return await p(this,v,C).call(this,"GET",Jt,{query:{parentFolderId:n,archived:e,...r&&{projectId:r}}})}async getFolder(t){return await p(this,v,C).call(this,"GET",`${Jt}/${t}`)}async getFoldersBatch(t){return await p(this,v,Ye).call(this,t,async e=>(await p(this,v,C).call(this,"POST",`${U}/batch/folders`,{body:JSON.stringify({folderIds:e}),contentType:"application/json"})).results)}async createFolder(t,e,n){return await p(this,v,C).call(this,"POST",Jt,{body:JSON.stringify({name:t,...e&&{parentId:e},...n&&{projectId:n}}),contentType:"application/json"})}async updateFolder(t,e){const{name:n}=e;return await p(this,v,C).call(this,"PUT",`${Jt}/${t}`,{body:JSON.stringify({name:n}),contentType:"application/json"})}async archiveFolder(t){return await p(this,v,C).call(this,"DELETE",`${Jt}/${t}`)}async recoverFolder(t){return await p(this,v,C).call(this,"PUT",`${Jt}/${t}/recover`)}async downloadFolder(t){return await p(this,v,ge).call(this,`${Jt}/${t}/download`)}async listComponents(t){const{folderId:e,ShowVersions:n,projectId:r}=t||{};return e?await p(this,v,C).call(this,"GET",`${Jt}/${e}/items`,{query:{itemType:qn,...n&&{ShowVersions:n}}}):await p(this,v,C).call(this,"GET",`${U}`,{query:{itemType:qn,...n&&{ShowVersions:n},...r&&{projectId:r}}})}async getComponent(t,e){return await p(this,v,ds).call(this,t,e)}async createComponent(t){const{componentProps:e}=t;return await p(this,v,In).call(this,t,qn,e)}async updateComponent(t,e){const{componentProps:n}=e;return await p(this,v,hs).call(this,t,e,n)}async downloadComponent(t,e){return await p(this,v,En).call(this,t,e)}async downloadComponentBundle(t,e){const{versionTag:n,withDraft:r}=e||{};return await p(this,v,ge).call(this,`${U}/${t}/download/bundle`,{query:{...n&&{versionTag:n},...r&&{withDraft:r}}})}async archiveComponent(t){return await p(this,v,C).call(this,"DELETE",`${U}/${t}`)}async recoverComponent(t){return await p(this,v,C).call(this,"PUT",`${U}/${t}/recover`)}async getBuiltInComponent(t){return await(await p(this,v,ge).call(this,`built-in/${t}/bundle`)).text()}async initBuiltInComponent(t,e,n){const r=await this.getBuiltInComponent(t.uuid),i=n??this.builtInGlobals??(typeof window<"u"?window.ThatOpenCompany:{})??{},o=Object.keys(i),a=o.map(y=>i[y]),d=new Function(...o,`${r}
2
- return main;`)(...a),c=(d==null?void 0:d.componentDefinition)??d;e.get(c)}async initBuiltInComponents(t,...e){await Promise.all(e.map(n=>this.initBuiltInComponent(n,t)))}async setup(t,...e){var o,a;const n=t.OBC,r=t.BUI;if(!(n!=null&&n.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 n.Components;return r.Manager.init(),this.setBuiltInGlobals(t),await this.initBuiltInComponents(i,...e),i.init(),(a=(o=this.context.appEventOrchestrator)==null?void 0:o.appLoaded)==null||a.call(o),{components:i}}throwError(t,e){var n,r;(r=(n=this.context.appEventOrchestrator)==null?void 0:n.appError)==null||r.call(n,t,e)}async listApps(t){const{folderId:e,ShowVersions:n,projectId:r}=t||{};return e?await p(this,v,C).call(this,"GET",`${Jt}/${e}/items`,{query:{itemType:Vn,...n&&{ShowVersions:n}}}):await p(this,v,C).call(this,"GET",`${U}`,{query:{itemType:Vn,...n&&{ShowVersions:n},...r&&{projectId:r}}})}async createApp(t){const{appProps:e}=t;return await p(this,v,In).call(this,t,Vn,e)}async downloadApp(t,e){return await p(this,v,En).call(this,t,e)}async downloadAppBundle(t,e){const{versionTag:n,withDraft:r}=e||{};return await p(this,v,ge).call(this,`${U}/${t}/download/bundle`,{query:{...n&&{versionTag:n},...r&&{withDraft:r}}})}async archiveApp(t){return await p(this,v,C).call(this,"DELETE",`${U}/${t}`)}async getNpmCredentials(){return await p(this,v,C).call(this,"GET",`${na}/credentials`)}async executeComponent(t,e,n){if(this.localServerUrl){const r=`${this.localServerUrl}/api/${fe}/${t}/execute`,i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!i.ok){const o=await i.text().catch(()=>"");throw new Error(`Local server request failed: ${i.status} - ${o}`)}return await i.json()}return await p(this,v,C).call(this,"POST",`${fe}/${t}/execute`,{body:JSON.stringify(e),query:{...n&&{versionTag:n}},contentType:"application/json"})}async abortExecution(t){if(this.localServerUrl){const e=`${this.localServerUrl}/api/${fe}/progress/${t}/abort`,n=await fetch(e,{method:"POST"});if(!n.ok){const r=await n.text().catch(()=>"");throw new Error(`Local server request failed: ${n.status} - ${r}`)}return await n.json()}return await p(this,v,C).call(this,"POST",`${fe}/progress/${t}/abort`)}async listExecutions(t,e){if(this.localServerUrl){const n=e?`?projectId=${encodeURIComponent(e)}`:"",r=`${this.localServerUrl}/api/${fe}/${t}/progress${n}`,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 p(this,v,C).call(this,"GET",`${fe}/${t}/progress`,{query:{...e&&{projectId:e}}})}async getExecution(t){if(this.localServerUrl){const e=`${this.localServerUrl}/api/${fe}/progress/${t}`,n=await fetch(e);if(!n.ok){const r=await n.text().catch(()=>"");throw new Error(`Local server request failed: ${n.status} - ${r}`)}return await n.json()}return await p(this,v,C).call(this,"GET",`${fe}/progress/${t}`)}async onExecutionProgress(t,e){const n=this.localServerUrl??this.wsUrl,r=await Xe(n,{auth:{accessToken:this.accessToken},transports:["websocket"]});r.on("connect",function(){r.emit("executionSubscription",JSON.stringify({executionId:t})),r.on("execution",i=>{e(i)})}),r.on("connect_error",function(i){console.log(i)})}documents(t){return new Cs(this,t)}history(t){return new Ss(this,t)}get recipes(){return m(this,on)??rt(this,on,new di(this)),m(this,on)}async createHiddenFile(t,e,n){const r=new FormData;return r.append("file",t),r.append("parentItemId",e),n!=null&&r.append("tag",n),await p(this,v,C).call(this,"POST",`${U}/${se}`,{body:r})}async createHiddenFilesBatch(t,e,n){const r=new FormData;for(const i of t)r.append("files",i);return r.append("parentItemId",e),n!=null&&r.append("tag",n),await p(this,v,C).call(this,"POST",`${U}/${se}/batch`,{body:r})}async deleteHiddenFile(t){return await p(this,v,C).call(this,"DELETE",`${U}/${se}/${t}`)}async getHiddenFile(t){return await p(this,v,C).call(this,"GET",`${U}/${se}/${t}`)}async downloadHiddenFile(t){return await p(this,v,ge).call(this,`${U}/${se}/${t}/download`)}async getHiddenFileSignedUrl(t,e){return await p(this,v,C).call(this,"GET",`${U}/${se}/${t}/signed-url`,{...e!=null&&{query:{expiresIn:e}}})}async getFileSignedUrl(t,e){const n={...(e==null?void 0:e.versionTag)&&{versionTag:e.versionTag},...(e==null?void 0:e.expiresIn)!=null&&{expiresIn:e.expiresIn}};return await p(this,v,C).call(this,"GET",`${U}/${encodeURIComponent(t)}/signed-url`,{...Object.keys(n).length>0&&{query:n}})}async getHiddenFileSignedUrlsBatch(t,e){return await p(this,v,Ye).call(this,t,async n=>(await p(this,v,C).call(this,"POST",`${U}/${se}/signed-url/batch`,{body:JSON.stringify({hiddenFileIds:n,...e!=null&&{expiresIn:e}}),contentType:"application/json"})).results)}async getHiddenFilesByParent(t,e){return await p(this,v,C).call(this,"GET",`${U}/${t}/${se}`,{...e!=null&&{query:{tag:e}}})}async deleteHiddenFilesByParent(t){return await p(this,v,C).call(this,"DELETE",`${U}/${t}/${se}`)}async uploadItemIcon(t,e){const n=new FormData;return n.append("icon",e),await p(this,v,C).call(this,"PUT",`${U}/${t}/icon`,{body:n})}async getItemIcon(t){return await p(this,v,ge).call(this,`${U}/${t}/icon`)}async removeItemIcon(t){return await p(this,v,C).call(this,"DELETE",`${U}/${t}/icon`)}async updateItem(t,e){return await p(this,v,C).call(this,"PUT",`${U}/${t}`,{body:JSON.stringify(e),contentType:"application/json"})}async createVersion(t,e,n,r,i){const o=new FormData;return o.append("file",e),o.append("versionTag",n),r&&o.append("extraProps",JSON.stringify(r)),i&&o.append("metadata",JSON.stringify(i)),await p(this,v,C).call(this,"POST",`${U}/${t}/version`,{body:o})}async nextVersionTag(t){if(!t)return"v1";let e=[];try{e=await this.listVersions(t)}catch{return`v-${Date.now()}`}let n=0;for(const r of e){const i=/^v(\d{1,6})$/.exec(String(r.tag??r.versionTag??""));i&&(n=Math.max(n,Number(i[1])))}return`v${Math.max(n,e.length)+1}`}async listVersions(t,e={}){return await p(this,v,C).call(this,"GET",`${U}/${encodeURIComponent(t)}/versions`,{query:e})}async listVersionsBatch(t,e={}){const{archived:n}=e;return await p(this,v,Ye).call(this,t,async r=>(await p(this,v,C).call(this,"POST",`${U}/batch/versions`,{body:JSON.stringify({itemIds:r,...n!==void 0&&{archived:n}}),contentType:"application/json"})).results)}async archiveVersion(t,e){return await p(this,v,C).call(this,"PUT",`${U}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/archive`)}async recoverVersion(t,e){return await p(this,v,C).call(this,"PUT",`${U}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/recover`)}async deleteVersion(t,e){return await p(this,v,C).call(this,"DELETE",`${U}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}`)}};v=new WeakSet,ls=function(t){return`${this.apiUrl}/${t}`},C=async function(t,e,n){const{body:r,query:i,contentType:o,retries:a,responseType:l,retryAttempt:d}=n||{},c=p(this,v,ls).call(this,e),y=p(this,v,ui).call(this,i),O=await this.resolveAccessToken(),b={...y,...this.useBearer?{}:{accessToken:O}};try{const B=await fetch(c+"?"+new URLSearchParams(b).toString(),{method:t,headers:{Accept:"application/json",...o&&{"Content-Type":o},...this.useBearer&&{Authorization:`Bearer ${O}`}},...r&&{body:r}});if(!B.ok){const H=await B.text().then(G=>G).catch(()=>"");throw new kn(B.status,B.statusText,H,oa(B))}return l==="blob"?await B.blob():B.json().then(H=>H).catch(()=>{})}catch(B){const H=a??this.retries;if(H>0&&aa(B)){const G=d??0;return await ia(ca(B,G)),await p(this,v,C).call(this,t,e,{...n,retries:H-1,retryAttempt:G+1})}throw B}},ge=async function(t,e){const{query:n}=e||{},r=p(this,v,ls).call(this,t),i=await this.resolveAccessToken(),o={...n,...this.useBearer?{}:{accessToken:i}};return await fetch(r+"?"+new URLSearchParams(o).toString(),{method:"GET",...this.useBearer&&{headers:{Authorization:`Bearer ${i}`}}})},on=new WeakMap,Ye=async function(t,e){if(!t.length)return[];const n=[];for(let i=0;i<t.length;i+=cs)n.push(t.slice(i,i+cs));return(await Promise.all(n.map(e))).flat()},En=async function(t,e){const{versionTag:n,withDraft:r}=e||{};return await p(this,v,ge).call(this,`${U}/${t}/download`,{query:{...n&&{versionTag:n},...r&&{withDraft:r}}})},In=async function(t,e,n){const{name:r,versionTag:i,parentFolderId:o,projectId:a,file:l,metadata:d}=t,c=new FormData;return c.append("file",l),c.append("name",r),c.append("versionTag",i),c.append("itemType",e),o&&c.append("folderId",o),a&&c.append("projectId",a),n&&c.append("extraProps",JSON.stringify(n)),d&&c.append("metadata",JSON.stringify(d)),await p(this,v,C).call(this,"POST",U,{body:c})},hs=async function(t,e,n){const{name:r,versionTag:i,parentFolderId:o,file:a,metadata:l}=e;let d,c;if(a){const y=new FormData;y.append("file",a),i&&y.append("versionTag",i),n&&y.append("extraProps",JSON.stringify(n)),l&&y.append("metadata",JSON.stringify(l)),c=await p(this,v,C).call(this,"POST",`${U}/${t}/version`,{body:y})}if(r||o){const y={...r&&{name:r},...o&&{folderId:o}},O=JSON.stringify(y);d=await p(this,v,C).call(this,"PUT",`${U}/${t}`,{body:O,contentType:"application/json"})}return{item:d,version:c}},ds=async function(t,e){const{showVersions:n=!1}=e||{};return await p(this,v,C).call(this,"GET",`${U}/${t}`,{query:{showVersions:n}})},ui=function(t){return t&&Object.entries(t).filter(([,e])=>e!==void 0).reduce((e,[n,r])=>(e[n]=r,e),{})};let An=Ps;function pi(){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:s=>window.parent.postMessage(s,"*"),listen:s=>{const t=e=>{e.source===window.parent&&s(e.data)};return window.addEventListener("message",t),()=>window.removeEventListener("message",t)}}}const fs="channel:",la=1e4;function Sn(s){try{s()}catch(t){console.error("[channel] a listener threw:",t)}}var ae,Bt,Dt,Me,Fe,Le,Ft,us,ps,ke;class Fs{constructor(t,e){z(this,Ft);z(this,ae,!1);z(this,Bt,[]);z(this,Dt,[]);z(this,Me,new Set);z(this,Fe,new Set);z(this,Le,new Set);this.transport=t,this.controls=e}get joined(){return m(this,ae)}get peers(){return m(this,Bt)}join(){return m(this,ae)?Promise.resolve():p(this,Ft,us).call(this,"joined",this.controls.join)}leave(){return!m(this,ae)&&!m(this,Dt).some(t=>t.want==="joined")?Promise.resolve():p(this,Ft,us).call(this,"left",this.controls.leave)}onChange(t){return m(this,Me).add(t),()=>void m(this,Me).delete(t)}onPeerJoined(t){return m(this,Fe).add(t),()=>void m(this,Fe).delete(t)}onPeerLeft(t){return m(this,Le).add(t),()=>void m(this,Le).delete(t)}applyJoined(){rt(this,ae,!0),p(this,Ft,ps).call(this,"joined"),p(this,Ft,ke).call(this)}applyLeft(){rt(this,ae,!1),rt(this,Bt,[]),p(this,Ft,ps).call(this,"left"),p(this,Ft,ke).call(this)}applyPeers(t){rt(this,Bt,t),p(this,Ft,ke).call(this)}applyPeerJoined(t){!m(this,ae)||m(this,Bt).some(e=>e.from===t.from)||(rt(this,Bt,[...m(this,Bt),t]),m(this,Fe).forEach(e=>Sn(()=>e(t))),p(this,Ft,ke).call(this))}applyPeerLeft(t){const e=m(this,Bt).find(n=>n.from===t);e&&(rt(this,Bt,m(this,Bt).filter(n=>n.from!==t)),m(this,Le).forEach(n=>Sn(()=>n(e))),p(this,Ft,ke).call(this))}failPending(t){const e=m(this,Dt);return rt(this,Dt,[]),e.forEach(n=>{clearTimeout(n.timer),n.reject(t)}),e.length>0}post(t){this.transport.post(t)}}ae=new WeakMap,Bt=new WeakMap,Dt=new WeakMap,Me=new WeakMap,Fe=new WeakMap,Le=new WeakMap,Ft=new WeakSet,us=function(t,e){return new Promise((n,r)=>{const i={want:t,resolve:n,reject:r,timer:setTimeout(()=>{rt(this,Dt,m(this,Dt).filter(o=>o!==i)),r(new Error(`The platform did not confirm ${t==="joined"?"joining":"leaving"} in time.`))},la)};m(this,Dt).push(i),this.transport.post({type:"APP_CHANNEL_CONTROL",...e})})},ps=function(t){const e=m(this,Dt).filter(n=>n.want===t);rt(this,Dt,m(this,Dt).filter(n=>n.want!==t)),e.forEach(n=>{clearTimeout(n.timer),n.resolve()})},ke=function(){m(this,Me).forEach(t=>Sn(t))};var Pe;class mi extends Fs{constructor(e){super(e,{join:{action:"joinCollab"},leave:{action:"leaveCollab"}});z(this,Pe,new Map)}on(e,n){const r=m(this,Pe).get(e)??new Set;return r.add(n),m(this,Pe).set(e,r),()=>void r.delete(n)}send(e,n){if(e.startsWith(fs))throw new Error(`Message types starting with '${fs}' are reserved.`);this.joined&&this.post({type:"APP_CHANNEL_PUBLISH",message:{type:e,payload:n}})}accepts(e){return e===void 0||e==="collab"}async handle(e){const n=m(this,Pe).get(e.type);if(!(n!=null&&n.size))return{handled:!1};const r=yi(e);return n.forEach(i=>Sn(()=>i(e.payload,r))),{handled:!0}}}Pe=new WeakMap;var we;class gi extends Fs{constructor(e,n){super(e,{join:{action:"joinExternal",kind:n},leave:{action:"leaveExternal",kind:n}});z(this,we,new Map);this.kind=n}on(e,n){if(m(this,we).has(e))throw new Error(`"${e}" already has a handler in this room. Remove it first.`);return m(this,we).set(e,n),()=>void m(this,we).delete(e)}accepts(e,n){return e!==void 0&&e!=="external"?!1:this.kind===void 0||e===void 0||this.kind===n}get hasHandlers(){return m(this,we).size>0}async handle(e){const n=m(this,we).get(e.type);if(!n)return{handled:!1};try{return{handled:!0,value:await n(e.payload,yi(e))}}catch(r){return{handled:!0,error:r instanceof Error?r.message:String(r)}}}}we=new WeakMap;function yi(s){return{from:s.from,at:s.at,requestId:s.requestId,kind:s.kind}}function ha(s){const t=s;if((t==null?void 0:t.type)!=="THATOPEN_CHANNEL_MESSAGE")return null;const e=t.message;return!e||typeof e.type!="string"?null:{type:e.type,requestId:typeof e.requestId=="string"?e.requestId:void 0,payload:e.payload,at:typeof e.at=="number"?e.at:Date.now(),from:typeof e.from=="string"?e.from:"",scope:e.scope==="collab"||e.scope==="external"?e.scope:void 0,kind:typeof e.kind=="string"?e.kind:void 0}}var _e,an,ce,ve,be,_t,ms,_n,vi,bi,Ti,gs;class wi{constructor(t){z(this,_t);z(this,_e);z(this,an);z(this,ce);z(this,ve,new Map);z(this,be,new Set);rt(this,_e,t),rt(this,an,t.listen(e=>void p(this,_t,vi).call(this,e)))}collab(){return m(this,ce)??rt(this,ce,new mi(m(this,_e))),m(this,ce)}external(t){const e=t??"";let n=m(this,ve).get(e);return n||(n=new gi(m(this,_e),t),m(this,ve).set(e,n)),n}dispose(){m(this,an).call(this)}}_e=new WeakMap,an=new WeakMap,ce=new WeakMap,ve=new WeakMap,be=new WeakMap,_t=new WeakSet,ms=function(){return[...m(this,ce)?[m(this,ce)]:[],...m(this,ve).values()]},_n=function(t,e){if(t==="collab")return m(this,ce);if(t==="external")return m(this,ve).get(typeof e=="string"?e:"")},vi=async function(t){const e=ha(t);if(e){if(e.type.startsWith(fs)){p(this,_t,bi).call(this,e);return}await p(this,_t,Ti).call(this,e)}},bi=function(t){var n,r,i;const e=t.payload??{};switch(t.type){case"channel:joined":(n=p(this,_t,_n).call(this,e.scope,e.kind))==null||n.applyJoined();break;case"channel:left":(r=p(this,_t,_n).call(this,e.scope,e.kind))==null||r.applyLeft();break;case"channel:peers":(i=p(this,_t,_n).call(this,e.scope,e.kind))==null||i.applyPeers(e.peers??[]);break;case"channel:peer-joined":case"channel:peer-left":{if(!e.from)break;const o=e.scope==="collab"?[m(this,ce)]:[...m(this,ve).values()].filter(a=>a.accepts("external",e.kind));for(const a of o)t.type==="channel:peer-joined"?a==null||a.applyPeerJoined({from:e.from,kind:e.kind}):a==null||a.applyPeerLeft(e.from);break}case"channel:error":{const o=new Error(String(t.payload));p(this,_t,ms).call(this).map(l=>l.failPending(o)).some(Boolean)||console.error("[channel] error:",t.payload);break}}},Ti=async function(t){const e=p(this,_t,ms).call(this).filter(i=>i.accepts(t.scope,t.kind));let n=!1;for(const i of e){const o=await i.handle(t);o.handled&&(n=!0,t.requestId&&p(this,_t,gs).call(this,t.requestId,o))}t.requestId&&t.scope==="external"&&e.length>0&&!n&&p(this,_t,gs).call(this,t.requestId,{handled:!0,error:`No handler for "${t.type}".`})},gs=function(t,e){m(this,be).has(t)||(m(this,be).add(t),m(this,be).size>500&&m(this,be).delete(m(this,be).values().next().value),m(this,_e).post({type:"APP_CHANNEL_PUBLISH",message:{type:e.error===void 0?"reply":"reply-error",requestId:t,payload:e.error===void 0?e.value:{error:e.error}}}))};const Ie="project",Ce="notifications";var Be,cn;const Bs=class Bs extends An{constructor(e,n,r){super(typeof e=="string"?e:"",n,{...r,useBearer:!0});z(this,Be);z(this,cn);typeof e=="function"&&rt(this,Be,e)}async resolveAccessToken(){return m(this,Be)?await m(this,Be).call(this):super.resolveAccessToken()}static fromPlatformContext(e){const n=(typeof window<"u"?window.__THATOPEN_CONTEXT__:null)||{appId:"",projectId:"",accessToken:"",apiUrl:""},r=new Bs(n.accessToken,n.apiUrl,e);return r.context=n,r}get channel(){return m(this,cn)??rt(this,cn,new wi(pi())),m(this,cn)}async listProjects(){return await this.request("GET",Ie)}async getProject(e){return await this.request("GET",`${Ie}/${e}`)}async getProjectData(e){return await this.request("GET",`${Ie}/${e}/data`)}async getAvatar(e){return await this.request("GET",`account/${e}/avatar`,{responseType:"blob"})}async checkPermission(e){return await this.request("GET",`${Ie}/permissions/check`,{query:e})}async checkPermissionBatch(e){return(await this.request("POST",`${Ie}/permissions/check/batch`,{body:JSON.stringify({checks:e}),contentType:"application/json"})).results}async getNotifications(e){return await this.request("GET",Ce,{query:{...(e==null?void 0:e.cursor)!==void 0&&{cursor:e.cursor},...(e==null?void 0:e.limit)!==void 0&&{limit:String(e.limit)}}})}async getUnreadNotificationCount(){return(await this.request("GET",`${Ce}/unread-count`)).count}async markNotificationsRead(e){return await this.request("POST",`${Ce}/mark-read`,{body:JSON.stringify({ids:e}),contentType:"application/json"})}async markAllNotificationsRead(){return await this.request("POST",`${Ce}/mark-all-read`)}async getNotificationSubscriptions(){return await this.request("GET",`${Ce}/subscriptions`)}async unsubscribeFromAutomation(e){return await this.request("DELETE",`${Ce}/subscriptions/${e}`)}async subscribeToAutomation(e,n,r){return await this.request("POST",`${Ie}/${e}/events/hooks/${n}/subscription`,{body:JSON.stringify(r??{}),contentType:"application/json"})}async updateAutomationSubscription(e,n,r){return await this.request("PATCH",`${Ie}/${e}/events/hooks/${n}/subscription`,{body:JSON.stringify(r),contentType:"application/json"})}async onNotification(e){const n=await this.resolveAccessToken(),r=Xe(`${this.socketOrigin}/notifications`,{auth:{accessToken:n},transports:["websocket"]});return r.on("notification.created",i=>e({type:"created",id:i==null?void 0:i.id})),r.on("notification.read",i=>e({type:"read",id:i==null?void 0:i.id})),r.on("notifications.allRead",i=>e({type:"allRead",batch:i==null?void 0:i.batch})),()=>r.disconnect()}};Be=new WeakMap,cn=new WeakMap;let ys=Bs;const $e=1/.3048,da={IFCDOOR:"OST_Doors",IFCWINDOW:"OST_Windows",IFCFURNITURE:"OST_Furniture",IFCFURNISHINGELEMENT:"OST_Furniture",IFCSYSTEMFURNITUREELEMENT:"OST_FurnitureSystems",IFCLIGHTFIXTURE:"OST_LightingFixtures",IFCSANITARYTERMINAL:"OST_PlumbingFixtures",IFCFLOWTERMINAL:"OST_PlumbingFixtures",IFCCOLUMN:"OST_Columns",IFCFOOTING:"OST_StructuralFoundation",IFCGEOGRAPHICELEMENT:"OST_Site",IFCELECTRICAPPLIANCE:"OST_ElectricalEquipment",IFCELECTRICDISTRIBUTIONBOARD:"OST_ElectricalEquipment",IFCUNITARYEQUIPMENT:"OST_MechanicalEquipment"},fa="OST_GenericModel",ua=new Set(["IFCSPACE","IFCOPENINGELEMENT","IFCSITE","IFCANNOTATION","IFCGRID","IFCVIRTUALELEMENT","IFCBUILDING","IFCBUILDINGSTOREY"]),ye=(s,t)=>Math.round(s/t)*t,pa=s=>({x:[s[0],s[1],s[2]],y:[s[4],s[5],s[6]],z:[s[8],s[9],s[10]],t:[s[12],s[13],s[14]]}),On=(s,t)=>s[0]*t[0]+s[1]*t[1]+s[2]*t[2],Gn=s=>Math.sqrt(On(s,s)),ws=(s,t)=>[s[1]*t[2]-s[2]*t[1],s[2]*t[0]-s[0]*t[2],s[0]*t[1]-s[1]*t[0]];function ma(s,t,e){const n=new Set,r=new Map;for(const l of t){const d=l.split(":")[1];d&&(n.add(d),r.has(d)||r.set(d,l))}const i=new Map,o=new Map,a=[];for(const l of s.elements.values()){if(n.has(l.gid)||ua.has(l.ifcClass.toUpperCase())||l.parent&&n.has(l.parent)&&!/^IFC(DOOR|WINDOW)$/i.test(l.ifcClass)||l.pieces.length===0)continue;const d=da[l.ifcClass.toUpperCase()]??fa,c=pa(l.pieces[0].matrix),y=Gn(c.x),O=Gn(c.y),b=Gn(c.z),B=c.z.map(Q=>Q/(b||1)),G=Math.abs(B[2]-1)<1e-6&&On(ws(c.x,c.y),c.z)>0&&Math.abs(y-O)<1e-6&&Math.abs(y-b)<1e-6?Math.atan2(c.x[1],c.x[0]):0,F=Math.cos(-G),D=Math.sin(-G),u=[c.t[0],c.t[1],c.t[2]],L=/COLUMN/i.test(d),I=Q=>{const J=Q[0]-u[0],E=Q[1]-u[1];return[F*J-D*E,D*J+F*E,Q[2]-u[2]]},j=[],st=[d];for(const Q of l.pieces){const J=s.geometries.get(Q.geometry);if(!J)continue;const E=Q.matrix,kt=[];for(let tt=0;tt<J.verts.length;tt+=3){const vt=J.verts[tt],Ht=J.verts[tt+1],le=J.verts[tt+2],ee=[E[0]*vt+E[4]*Ht+E[8]*le+E[12],E[1]*vt+E[5]*Ht+E[9]*le+E[13],E[2]*vt+E[6]*Ht+E[10]*le+E[14]],It=I(ee);kt.push(ye(It[0]*$e,1e-5),ye(It[1]*$e,1e-5),ye(It[2]*$e,1e-5))}const lt=On(ws([E[0],E[1],E[2]],[E[4],E[5],E[6]]),[E[8],E[9],E[10]])<0,At=[];for(let tt=0;tt+2<J.tris.length;tt+=3)lt?At.push(J.tris[tt],J.tris[tt+2],J.tris[tt+1]):At.push(J.tris[tt],J.tris[tt+1],J.tris[tt+2]);At.length&&j.push({v:kt,t:At});const Mt=I([E[12],E[13],E[14]]),Lt=[F*E[0]-D*E[1],D*E[0]+F*E[1],E[2]],Ot=[F*E[4]-D*E[5],D*E[4]+F*E[5],E[6]];st.push(`${Q.geometry}@${[...Mt,...Lt,...Ot].map(tt=>ye(tt,1e-4).toFixed(4)).join(",")}`)}if(j.length===0)continue;const Z=!l.host&&j.length===1?ya(j[0]):null;if(Z){const Q=Z.loops.map(Ot=>Ot.map(([tt,vt])=>`${Math.round(tt*304.8)},${Math.round(vt*304.8)}`).join(";")).join("|"),J=`prism|${d}|${Z.axis}|${Q}`;let E=i.get(J);if(!E){const Ot=Ar(l.typeName??l.objectType??l.name??l.ifcClass),tt=(o.get(Ot)??0)+1;o.set(Ot,tt);const vt=tt===1?Ot:`${Ot} (${tt})`;E={family:vt,type:vt,first:!0,key:Or(J)},i.set(J,E)}const kt={ShapeCategory:d,Family:E.family,Type:E.type,ShapeKey:E.key,PrismLength:String(ye(Z.length,1e-5)),...L?{ColumnFree:"1"}:{}};E.first&&(kt.Prism=JSON.stringify({axis:Z.axis,loops:Z.loops}),E.first=!1);const lt=[0,0,0];lt[Z.axis]=Z.from/$e;const At=Math.cos(G),Mt=Math.sin(G),Lt=[u[0]+At*lt[0]-Mt*lt[1],u[1]+Mt*lt[0]+At*lt[1],u[2]+lt[2]];a.push({key:`${e}:${l.gid}:shape`,attrs:kt,at:Lt,rotationDeg:G*180/Math.PI});continue}const mt=`${d}|${j.map(Q=>`${Q.v.map(J=>Math.round(J*304.8/2)).join(",")}/${Q.t.join(",")}`).join("|")}`,Rt=st.join("|");let Tt=i.get(Rt)??i.get(mt);if(Tt&&(i.set(Rt,Tt),i.set(mt,Tt)),!Tt){const Q=Ar(l.typeName??l.objectType??l.name??l.ifcClass),J=(o.get(Q)??0)+1;o.set(Q,J);const E=J===1?Q:`${Q} (${J})`;Tt={family:E,type:E,first:!0,key:Or(mt)},i.set(mt,Tt),i.set(Rt,Tt)}const Zt={ShapeCategory:d,Family:Tt.family,Type:Tt.type,ShapeKey:Tt.key,...L?{ColumnFree:"1"}:{}};Tt.first&&(Zt.Shape=JSON.stringify({pieces:j}),Tt.first=!1);const Ee=l.host?r.get(l.host):void 0,te=l.opening?s.elements.get(l.opening):void 0;if(Ee&&te){const Q=[1/0,1/0,1/0],J=[-1/0,-1/0,-1/0];for(const E of te.pieces){const kt=s.geometries.get(E.geometry);if(!kt)continue;const lt=E.matrix;for(let At=0;At<kt.verts.length;At+=3){const Mt=kt.verts[At],Lt=kt.verts[At+1],Ot=kt.verts[At+2],tt=I([lt[0]*Mt+lt[4]*Lt+lt[8]*Ot+lt[12],lt[1]*Mt+lt[5]*Lt+lt[9]*Ot+lt[13],lt[2]*Mt+lt[6]*Lt+lt[10]*Ot+lt[14]]);for(let vt=0;vt<3;vt++)Q[vt]=Math.min(Q[vt],tt[vt]*$e),J[vt]=Math.max(J[vt],tt[vt]*$e)}}Number.isFinite(Q[0])&&(Zt.Opening=[...Q,...J].map(E=>ye(E,1e-5)).join(","))}a.push({key:`${e}:${l.gid}:shape`,attrs:Zt,at:[u[0],u[1],u[2]],rotationDeg:G*180/Math.PI,...Ee?{host:Ee}:{}})}return a}function Ar(s){return(s.replace(/[\\:{}[\]|;<>?`~]/g,"-").replace(/\s+/g," ").trim()||"Shape").slice(0,120)}function Or(s){let t=2166136261;for(let e=0;e<s.length;e++)t^=s.charCodeAt(e),t=Math.imul(t,16777619);return(t>>>0).toString(36)}function ga(s,t,e){const n=new Map;for(const i of t){const[,o,a]=i.split(":");o&&/^run/.test(a??"")&&!n.has(o)&&n.set(o,i)}const r=[];for(const i of s.elements.values()){if(i.ifcClass.toUpperCase()!=="IFCOPENINGELEMENT"||!i.host)continue;const o=n.get(i.host);if(!o)continue;const a=De(s,i.gid);if(a.length<4)continue;const l=va(De(s,i.host));if(!l)continue;const d=a.map(b=>(b[0]-l.a[0])*l.u[0]+(b[1]-l.a[1])*l.u[1]),c=a.map(b=>-(b[0]-l.a[0])*l.u[1]+(b[1]-l.a[1])*l.u[0]),y=b=>Math.max(...b)-Math.min(...b),O=y(d)*y(c)*y(a.map(b=>b[2]));!(O>0)||Math.abs(ba(s,i.gid))<.75*O||r.push({key:`${e}:${i.gid}:opening`,host:o,box:a.flat()})}return r}function ya(s){const e=s.v.length/3;if(e<6)return null;const n=[0,1,2].map(r=>{let i=1/0,o=-1/0;for(let a=0;a<e;a++){const l=s.v[a*3+r];i=Math.min(i,l),o=Math.max(o,l)}return o-i});for(const r of[0,1,2].sort((i,o)=>n[o]-n[i])){let i=1/0,o=-1/0;for(let u=0;u<e;u++){const L=s.v[u*3+r];i=Math.min(i,L),o=Math.max(o,L)}if(o-i<.01)continue;let a=!0;for(let u=0;u<e&&a;u++){const L=s.v[u*3+r];Math.abs(L-i)>.001&&Math.abs(L-o)>.001&&(a=!1)}if(!a)continue;const l=(r+1)%3,d=(r+2)%3,c=new Map,y=[],O=u=>{const L=[s.v[u*3+l],s.v[u*3+d]],I=`${Math.round(L[0]*3048)},${Math.round(L[1]*3048)}`;return c.has(I)||(c.set(I,y.length),y.push(L)),c.get(I)},b=new Map,B=[];for(let u=0;u+2<s.t.length;u+=3){const L=[s.t[u],s.t[u+1],s.t[u+2]];if(!L.every(j=>Math.abs(s.v[j*3+r]-i)<=.001))continue;const I=L.map(O);if(!(I[0]===I[1]||I[1]===I[2]||I[0]===I[2])){B.push(I);for(let j=0;j<3;j++){const st=I[j],Z=I[(j+1)%3],mt=st<Z?`${st},${Z}`:`${Z},${st}`;b.set(mt,(b.get(mt)??0)+1)}}}if(B.length===0)continue;const H=new Map;for(const u of B)for(let L=0;L<3;L++){const I=u[L],j=u[(L+1)%3];b.get(I<j?`${I},${j}`:`${j},${I}`)===1&&H.set(I,[...H.get(I)??[],j])}if([...H.values()].some(u=>u.length!==1))continue;const G=[],F=new Set(H.keys());for(;F.size;){const u=F.values().next().value,L=[];let I=u,j=0;do L.push(y[I]),F.delete(I),I=H.get(I)[0];while(I!==u&&j++<1e5&&H.has(I));if(I!==u||L.length<3){G.length=0;break}const st=L.filter((Z,mt)=>{const Rt=L[(mt-1+L.length)%L.length],Tt=L[(mt+1)%L.length];return Math.abs((Z[0]-Rt[0])*(Tt[1]-Rt[1])-(Z[1]-Rt[1])*(Tt[0]-Rt[0]))>1e-7});G.push(st.map(([Z,mt])=>[ye(Z,1e-5),ye(mt,1e-5)]))}if(G.length===0||G.some(u=>u.length<3))continue;let D=0;for(let u=0;u<e;u++)Math.abs(s.v[u*3+r]-o)<=.001&&D++;if(!(D<3))return{axis:r,from:i,length:o-i,loops:G}}return null}function wa(s,t){const e=[];for(const n of s.elements.values()){if(n.ifcClass.toUpperCase()!=="IFCSPACE")continue;let r=1/0,i=-1/0;const o=[];for(const d of n.pieces){const c=s.geometries.get(d.geometry);if(!c)continue;const y=d.matrix,O=b=>{const B=c.verts[b*3],H=c.verts[b*3+1],G=c.verts[b*3+2];return[y[0]*B+y[4]*H+y[8]*G+y[12],y[1]*B+y[5]*H+y[9]*G+y[13],y[2]*B+y[6]*H+y[10]*G+y[14]]};for(let b=0;b+2<c.tris.length;b+=3){const B=[O(c.tris[b]),O(c.tris[b+1]),O(c.tris[b+2])];for(const H of B)r=Math.min(r,H[2]),i=Math.max(i,H[2]);o.push(B)}}if(!Number.isFinite(r)||i-r<.1)continue;let a=null,l=0;for(const d of o){if(!d.every(y=>Math.abs(y[2]-r)<.001))continue;const c=Math.abs((d[1][0]-d[0][0])*(d[2][1]-d[0][1])-(d[2][0]-d[0][0])*(d[1][1]-d[0][1]))/2;c>l&&(l=c,a=d)}a&&e.push({key:`${t}:${n.gid}:room`,at:[(a[0][0]+a[1][0]+a[2][0])/3,(a[0][1]+a[1][1]+a[2][1])/3,r],height:i-r,number:n.name??"",name:n.longName??n.name??""})}return e}function va(s){if(s.length<2)return;let t=s[0],e=s[0],n=0;for(const r of s){const i=Math.hypot(r[0]-s[0][0],r[1]-s[0][1]);i>n&&(n=i,e=r)}n=0;for(const r of s){const i=Math.hypot(r[0]-e[0],r[1]-e[1]);i>n&&(n=i,t=r)}if(!(n<.1))return{a:t,u:[(e[0]-t[0])/n,(e[1]-t[1])/n]}}function ba(s,t){const e=s.elements.get(t);let n=0;if(!e)return n;for(const r of e.pieces){const i=s.geometries.get(r.geometry);if(!i)continue;const o=r.matrix,a=l=>{const d=i.verts[l*3],c=i.verts[l*3+1],y=i.verts[l*3+2];return[o[0]*d+o[4]*c+o[8]*y+o[12],o[1]*d+o[5]*c+o[9]*y+o[13],o[2]*d+o[6]*c+o[10]*y+o[14]]};for(let l=0;l+2<i.tris.length;l+=3)n+=On(a(i.tris[l]),ws(a(i.tris[l+1]),a(i.tris[l+2])))/6}return n}function De(s,t){const e=s.elements.get(t),n=[];if(!e)return n;for(const r of e.pieces){const i=s.geometries.get(r.geometry);if(!i)continue;const o=r.matrix;for(let a=0;a<i.verts.length;a+=3){const l=i.verts[a],d=i.verts[a+1],c=i.verts[a+2];n.push([o[0]*l+o[4]*d+o[8]*c+o[12],o[1]*l+o[5]*d+o[9]*c+o[13],o[2]*l+o[6]*d+o[10]*c+o[14]])}}return n}function Ta(s,t,e){const n=De(s,t);if(n.length<4||e.length===0)return;let r=n[0],i=n[0],o=0;for(const F of n){const D=Math.hypot(F[0]-n[0][0],F[1]-n[0][1]);D>o&&(o=D,i=F)}o=0;for(const F of n){const D=Math.hypot(F[0]-i[0],F[1]-i[1]);D>o&&(o=D,r=F)}if(o<.3)return;const a=(i[0]-r[0])/o,l=(i[1]-r[1])/o,d=F=>(F[0]-r[0])*a+(F[1]-r[1])*l,c=Math.max(...n.map(F=>F[2])),y=F=>Math.max(...n.filter(D=>Math.abs(d(D)-F)<.05).map(D=>D[2]),-1/0),O=y(0),b=y(o);if(Math.abs(O-b)<.05&&c-Math.max(O,b)<.05)return;const B=(r[0]+i[0])/2,H=(r[1]+i[1])/2;let G;for(const F of e){const D=De(s,F.gid);if(D.length===0)continue;const u=D.map(st=>st[0]),L=D.map(st=>st[1]),I=D.map(st=>st[2]);if(B<Math.min(...u)-.2||B>Math.max(...u)+.2||H<Math.min(...L)-.2||H>Math.max(...L)+.2)continue;const j=Math.min(...I)-c;j>1.5||Math.max(...I)<c-.05||(!G||Math.abs(j)<Math.abs(G.gap))&&(G={id:F.id,gap:j})}return G==null?void 0:G.id}const ue={levels:"-2000240",walls:"-2000011",floors:"-2000032",roofs:"-2000035",ceilings:"-2000038",structuralFoundations:"-2001300",stairs:"-2000120"};function Ke(s){const t=s.item.attrs.Name;if(typeof t!="string")return null;const e=t.indexOf(":"),n=t.lastIndexOf(":");if(e<=0||n<=e)return null;const r=t.slice(e+1,n).trim();return r?{family:t.slice(0,e).trim(),type:r}:null}function Cr(s){const t=Ke(s),e=s.item.attrs.PredefinedType;return t?/escalera|stair|landing|descansillo/i.test(t.family)||e==="LANDING"||/plataforma|^pad\b|building pad/i.test(t.family)?"other":/cubierta|roof/i.test(t.family)||e==="ROOF"?"roof":/cimentaci|foundation/i.test(t.family)||e==="BASESLAB"?"foundation":"floor":"floor"}const $r=180/Math.PI;function xr(s){if(typeof s!="string")return null;const t=s.indexOf(":");return t<=0||t===s.length-1?null:{family:s.slice(0,t),type:s.slice(t+1)}}const pt=s=>String(s);function Ei(s){return async t=>{var js,Us,qs,Vs,Gs,Hs,Js,Ws,zs,Ys,Ks,Xs,Qs,Zs,tr,er,nr,sr,rr,ir,or;const{picked:e,contents:n,site:r,shapes:i}=await ks(t,t.input),o=si(n.items),a=/CoordinateBase:\s*(Coordenadas compartidas|Shared Coordinates|Shared)/i.test(JSON.stringify(n.metadata??{})),l=a&&r?[r.east*Ne,r.north*Ne,r.elevation*Ne,r.angleDeg].map(h=>h.toFixed(6)).join(","):void 0;if(o.length===0)throw new Error(s==="ifc"?`Nothing in "${e.name}" could be read as a building element (walls, floors, levels...).`:`"${e.name}" carries no platform records, so there is nothing semantic to convert.`);const{columnType:d,trustStyleNames:c,includeInstances:y}=t.settings,O=t.settings.createLevels!==!1;if(y&&!c)throw new Error("Free-standing instances can only be made by their style names: turn trustStyleNames on.");const b=xs(o),B=ri(o),H=`recipe:${s}-to-revit`,G=new Map,F=Rs(t,G);t.progress("Writing the changes for Revit");const D=new xn({project:t.projectId,document:t.target.docId??"",baseCommit:t.target.version??0,author:H}),u=Ne,L=new Map;{const h=new Map;for(const f of o){const g=f.item.guid;if(!g)continue;const w=`${g}:${f.kind}`,A=h.get(w)??0;h.set(w,A+1),L.set(f.id,`${e.fileId}:${w}${A?`:${A}`:""}`)}}const I=h=>L.get(h)??`${e.fileId}:${h}`,j=new Set;let st=0,Z=0;const mt=(h,f,g)=>{j.add(h);const w=a?{...f,Frame:"shared",...l?{SharedAt:l}:{}}:f,A=ii({attrs:w,placement:g??{}}),T=F.get(h);if(T){const _=G.get(h);return!_||_===A?(st++,!1):(D.remove(T),D.add({...w,"flow:print":A},{...g,source:h}),Z++,!1)}return D.add({...w,"flow:print":A},{...g,source:h}),!0},Rt=h=>{const f=typeof h=="string"?B.get(h):void 0,g=f==null?void 0:f.params.thickness;return typeof g=="number"&&g>0?g*u:void 0},Tt=h=>{var N,it;const f=Pt(h,"extrusion"),g=b.get(String((f==null?void 0:f.level)??h.params.level??"")),w=f==null?void 0:f.slopes,A=((it=(N=f==null?void 0:f.profile)==null?void 0:N.outline)==null?void 0:it.curves)??[],T=Array.isArray(w)?w.map(q=>typeof q=="number"):[],_=T.indexOf(!0);if(h.params.of!=="roof"||!g||A.length!==4||T.filter(Boolean).length!==2||_<0||_>1||!T[_+2])return null;const[S,R]=[A[_],A[_+2]],nt=S.from,ht=S.to,W=Math.hypot(ht[0]-nt[0],ht[1]-nt[1]),St=[(ht[0]-nt[0])/W,(ht[1]-nt[1])/W];let M=[-St[1],St[0]];const at=(R.from[0]-nt[0])*M[0]+(R.from[1]-nt[1])*M[1];at<0&&(M=[-M[0],-M[1]]);const gt=Math.abs(at),[k,K]=[w[_],w[_+2]],ct=g.at+(typeof h.params.base=="number"?h.params.base:0),Ct=(f==null?void 0:f.eaves)??[],[et,yt]=[ct+(Number(Ct[_])||0),ct+(Number(Ct[_+2])||0)],ft=(yt-et+K*gt)/(k+K);return{A:nt,u:St,n:M,L:W,W:gt,si:k,sj:K,ridge:ft,top:ct,ti:et,tj:yt,zAt:(q,x)=>{const P=(q-nt[0])*M[0]+(x-nt[1])*M[1];return Math.min(et+k*P,yt+K*(gt-P))}}},Zt=new Map(o.filter(h=>h.kind==="extrusion"&&h.params.of==="roof").map(h=>[h.id,h])),Ee=[...Zt.values()].filter(h=>h.item.guid).map(h=>({id:h.id,gid:h.item.guid}));let te=0;if(O)for(const[h,f]of b)mt(I(h),{CategoryId:ue.levels,Name:f.name,Elevation:pt(f.at*u)})&&te++;let Q=0,J=0;const E=[];for(const h of o){if(h.kind!=="run"||h.params.of!=="wall")continue;const f=Pt(h,"run"),g=((Us=(js=f==null?void 0:f.run)==null?void 0:js.line)==null?void 0:Us.curves)??[],w=h.params.lookRef,A=b.get(String((f==null?void 0:f.level)??h.params.level??""));if(typeof w!="string"||typeof(f==null?void 0:f.height)!="number"||!A){J++;continue}const T=(Rt(w)??0)/u,_=g.filter(S=>S.kind==="segment"&&S.from&&S.to);J+=g.length-_.length,_.forEach((S,R)=>E.push({record:h,i:R,width:T,from:[...S.from],to:[...S.to],joinStart:R===0&&String(h.params.meetsAtStart)==="true",joinEnd:R===_.length-1&&String(h.params.meetsAtEnd)==="true"}))}const kt=(h,f)=>{const g=[h.to[0]-h.from[0],h.to[1]-h.from[1]],w=[f.to[0]-f.from[0],f.to[1]-f.from[1]],A=g[0]*w[1]-g[1]*w[0];if(Math.abs(A)<1e-9*Math.hypot(...g)*Math.hypot(...w)*1e3)return null;const T=((f.from[0]-h.from[0])*w[1]-(f.from[1]-h.from[1])*w[0])/A;return[h.from[0]+T*g[0],h.from[1]+T*g[1]]},lt=(h,f)=>{const g=f.to[0]-f.from[0],w=f.to[1]-f.from[1],A=g*g+w*w||1,T=Math.max(0,Math.min(1,((h[0]-f.from[0])*g+(h[1]-f.from[1])*w)/A));return Math.hypot(h[0]-(f.from[0]+T*g),h[1]-(f.from[1]+T*w))},At=(h,f)=>{const g=Pt(h.record,"run"),w=Pt(f.record,"run"),A=[g.base,g.base+g.height],T=[w.base,w.base+w.height],_=b.get(String((g==null?void 0:g.level)??h.record.params.level)).at,S=b.get(String((w==null?void 0:w.level)??f.record.params.level)).at;return Math.min(_+A[1],S+T[1])>Math.max(_+A[0],S+T[0])},Mt=1,Lt=new Map;for(const h of E){const f=[["from",h.joinStart],["to",h.joinEnd]],g={from:h.from,to:h.to};for(const[w,A]of f){if(!A)continue;const T=h[w];let _=null,S=1/0;for(const ht of E){if(ht===h||!At(h,ht))continue;const W=lt(T,ht);W<S&&(S=W,_=ht)}if(!_||S>Mt)continue;const R=kt(h,_);if(!R)continue;const nt=Math.min(Mt,2*Math.max(h.width,_.width)+.02);Math.hypot(R[0]-T[0],R[1]-T[1])>nt||lt(R,_)>_.width+.01||(g[w]=R)}Lt.set(h,g)}for(const h of E){const{record:f}=h,g=Pt(f,"run"),w=typeof g.base=="number"?g.base:0,A=g.height,T=b.get(String(g.level??f.params.level??"")),_=f.params.lookRef;let{from:S,to:R}=Lt.get(h);const nt=new Set;if(i&&f.item.guid&&E.filter(N=>N.record===f).length===1?i.elements.get(f.item.guid):void 0){const N=De(i,f.item.guid),it=Math.hypot(R[0]-S[0],R[1]-S[1]);if(N.length>=4&&it>.05){const q=[(R[0]-S[0])/it,(R[1]-S[1])/it],x=N.map(wt=>(wt[0]-S[0])*q[0]+(wt[1]-S[1])*q[1]),P=Math.min(...x),ot=Math.max(...x),dt=N.map(wt=>-(wt[0]-S[0])*q[1]+(wt[1]-S[1])*q[0]),$t=Math.max(...dt)-Math.min(...dt),X=wt=>{const qt=dt.filter((he,de)=>Math.abs(x[de]-wt)<.002);return qt.length>=2&&Math.max(...qt)-Math.min(...qt)>.9*$t},V=S;X(P)&&(S=[V[0]+q[0]*P,V[1]+q[1]*P],nt.add("start")),X(ot)&&(R=[V[0]+q[0]*ot,V[1]+q[1]*ot],nt.add("end"))}}const W=(T.at+w)*u,St=`${pt(S[0]*u)},${pt(S[1]*u)},${pt(W)};${pt(R[0]*u)},${pt(R[1]*u)},${pt(W)}`,M={CategoryId:ue.walls,Type:((qs=Ke(f))==null?void 0:qs.type)??_,LocationLine:St,Level:T.name,BaseOffset:pt(w*u),Height:pt(A*u)},at=[S!==h.from||h.joinStart?"start":"",R!==h.to||h.joinEnd?"end":""].filter(N=>!!N&&!nt.has(N));at.length&&(M.JoinEnds=at.join(","));const gt=at.filter(N=>f.params[N==="start"?"wantedAtStart":"wantedAtEnd"]==="mitre");gt.length&&(M.Mitre=gt.join(","));const k=b.get(String(f.params.topLevel??""));k&&(M.TopLevel=k.name,M.TopOffset=pt((T.at+w+A-k.at)*u));const K=g.profile;if(Array.isArray(K)&&K.length>=3&&h.i===0&&!E.some(N=>N!==h&&N.record===f)){const N=Math.hypot(h.to[0]-h.from[0],h.to[1]-h.from[1]),it=[(h.to[0]-h.from[0])/N,(h.to[1]-h.from[1])/N],q=[],x=-((S[0]-h.from[0])*it[0]+(S[1]-h.from[1])*it[1]),P=(R[0]-h.to[0])*it[0]+(R[1]-h.to[1])*it[1];K.forEach(([ot,dt],$t)=>{const X=Math.abs(ot)<1e-6,V=Math.abs(ot-N)<1e-6;let wt=ot,qt=dt;if(X||V){wt=X?-x:N+P;const de=[K[($t-1+K.length)%K.length],K[($t+1)%K.length]].find(([Ve])=>Math.abs(Ve-ot)>1e-6);de&&(qt=dt+(de[1]-dt)/(de[0]-ot)*(wt-ot))}const he=[h.from[0]+wt*it[0],h.from[1]+wt*it[1]];q.push(he[0]*u,he[1]*u,(T.at+w+qt)*u)}),M.Profile=JSON.stringify([q]),delete M.TopLevel,delete M.TopOffset}const ct=f.params.topAttachedTo,Ct=f.params.topAttachedAt==="top"||g.topAttachedAt==="top",et=typeof ct=="string"&&Ct&&!M.Profile&&Zt.has(ct)?Tt(Zt.get(ct)):null;if(et){const N=Math.hypot(R[0]-S[0],R[1]-S[1]),it=X=>[S[0]+(R[0]-S[0])*X/N,S[1]+(R[1]-S[1])*X/N],q=(S[0]-et.A[0])*et.n[0]+(S[1]-et.A[1])*et.n[1],x=(R[0]-et.A[0])*et.n[0]+(R[1]-et.A[1])*et.n[1],P=[0,N];(q-et.ridge)*(x-et.ridge)<0&&P.splice(1,0,(et.ridge-q)/(x-q)*N);const ot=T.at+w,dt=[],$t=(X,V)=>{const wt=it(X);dt.push(wt[0]*u,wt[1]*u,V*u)};$t(0,ot),$t(N,ot);for(const X of[...P].reverse()){const V=it(X);$t(X,et.zAt(V[0],V[1]))}M.Profile=JSON.stringify([dt]),delete M.TopLevel,delete M.TopOffset}const yt=typeof ct=="string"?ct:i&&f.item.guid?Ta(i,f.item.guid,Ee):void 0;yt&&!M.Profile&&(M.AttachTop=I(yt));const ft=Rt(_);ft&&(M["Type.Width"]=pt(ft));const ut=f.item.guid?i==null?void 0:i.elements.get(f.item.guid):void 0;ut!=null&&ut.layers&&ut.layers.length>1&&(M["Type.Layers"]=JSON.stringify([...ut.layers].reverse().map(N=>[+pt(N.thickness*u),N.material??"",N.function??""])),ut.layersFlipped&&(M.FlipLayers="1")),mt(`${I(f.id)}#${h.i}`,M)&&Q++}const Ot=(h,f,g)=>{if(!(f>0)||f>=h)return[];const w=h-Math.floor(h/f+1e-9)*f,A=g==="beginning"?0:g==="end"?w:g==="centreLine"?h/2%f:w/2,T=[];for(let _=A;_<=h+1e-4;_+=f)_>1e-4&&_<h-1e-4&&T.push(_);return T};let tt=0,vt=0;for(const h of o){if(h.kind!=="run"||h.params.of!=="curtainWall")continue;vt++;const f=Pt(h,"run"),g=(Hs=(Gs=(Vs=f==null?void 0:f.run)==null?void 0:Vs.line)==null?void 0:Gs.curves)==null?void 0:Hs[0],w=b.get(String((f==null?void 0:f.level)??h.params.level??"")),A=h.params.lookRef,T=typeof A=="string"?(Js=B.get(A))==null?void 0:Js.params:void 0;if(!(g!=null&&g.from)||!g.to||typeof(f==null?void 0:f.height)!="number"||!w||!T)continue;const _=ft=>typeof ft=="number"?ft:Number(ft)||0,S=_(T.uprightWidth)/2,R=_(T.horizontalWidth)/2,nt=Math.hypot(g.to[0]-g.from[0],g.to[1]-g.from[1]),ht=[(g.to[0]-g.from[0])/nt,(g.to[1]-g.from[1])/nt],W=[g.from[0]-ht[0]*S,g.from[1]-ht[1]*S],St=[g.to[0]+ht[0]*S,g.to[1]+ht[1]*S],M=(typeof f.base=="number"?f.base:0)-R,at=f.height+2*R,gt=(w.at+M)*u,k=((Ws=f.lines)==null?void 0:Ws.along)??Ot(nt,_(T.alongSpacing),T.alongJustify),K=((zs=f.lines)==null?void 0:zs.up)??Ot(f.height,_(T.upSpacing),T.upJustify),ct=(f.omitted??[]).flatMap(ft=>{const ut=/^(horizontal|vertical)@(-?[\d.]+):(-?[\d.]+)$/.exec(ft);if(!ut)return[];const N=ut[1]==="horizontal",it=Number(ut[2])/1e3+(N?R:S),q=Number(ut[3])/1e3+(N?S:R);return[{horizontal:N,at:it*u,from:q*u}]}),Ct=(f.omitted??[]).flatMap(ft=>{const ut=/^panel@(-?[\d.]+),(-?[\d.]+)$/.exec(ft);return ut?[{along:(Number(ut[1])/1e3+S)*u,up:(Number(ut[2])/1e3+R)*u}]:[]}),et={CategoryId:ue.walls,Type:((Ys=Ke(h))==null?void 0:Ys.type)??String(A),LocationLine:`${pt(W[0]*u)},${pt(W[1]*u)},${pt(gt)};${pt(St[0]*u)},${pt(St[1]*u)},${pt(gt)}`,Level:w.name,BaseOffset:pt(M*u),Height:pt(at*u),Curtain:JSON.stringify({along:k.map(ft=>(ft+S)*u),up:K.map(ft=>(ft+R)*u),omit:ct,empty:Ct,mullion:{width:_(T.uprightWidth)*u,depth:_(T.depth)*u},panel:{thickness:_(T.panelDepth)*u,offset:-_(T.panelOffset)*u}})},yt=f.profile;if(Array.isArray(yt)&&yt.length>=3){const ut=yt.reduce((x,P,ot)=>{const dt=yt[(ot+1)%yt.length];return x+P[0]*dt[1]-dt[0]*P[1]},0)>0?1:-1,N=yt.length,it=yt.map((x,P)=>{const ot=yt[(P-1+N)%N],dt=yt[(P+1)%N],$t=(he,de)=>{const Ve=de[0]-he[0],Mn=de[1]-he[1],ar=Math.hypot(Ve,Mn)||1,cr=ut*Mn/ar,lr=-ut*Ve/ar,hr=Math.abs(cr)>Math.abs(lr)?S:R;return{p:[he[0]+cr*hr,he[1]+lr*hr],d:[Ve,Mn]}},X=$t(ot,x),V=$t(x,dt),wt=X.d[0]*V.d[1]-X.d[1]*V.d[0];if(Math.abs(wt)<1e-12)return[V.p[0],V.p[1]];const qt=((V.p[0]-X.p[0])*V.d[1]-(V.p[1]-X.p[1])*V.d[0])/wt;return[X.p[0]+qt*X.d[0],X.p[1]+qt*X.d[1]]}),q=[];for(const[x,P]of it)q.push((g.from[0]+ht[0]*x)*u,(g.from[1]+ht[1]*x)*u,(w.at+M+R+P)*u);et.Profile=JSON.stringify([q])}mt(I(h.id),et)&&tt++}let Ht=0,le=0;for(const h of o){if(h.kind!=="stair"||h.params.of!=="stair")continue;le++;const f=Pt(h,"stair"),g=h.params.lookRef,w=typeof g=="string"?(Ks=B.get(g))==null?void 0:Ks.params:void 0,A=b.get(String((f==null?void 0:f.level)??h.params.level??""));if(!(f!=null&&f.start)||!f.end||!(Number(f.rise)>0)||!A||!w)continue;const T=k=>typeof k=="number"?k:Number(k)||0,_=Number(f.rise),S=Math.max(1,Math.ceil(_/T(w.maxRiser)-1e-6)),R=T(w.tread),nt=k=>[k[0]*u,k[1]*u],ht={family:String(g).split(":")[0],base:(A.at+T(h.params.base))*u,height:_*u,risers:S,tread:R*u,width:T(w.width)*u,sizes:{maxRiser:Math.ceil(_/S*1e3-1e-6)/1e3*u,minTread:R*u,waist:T(w.waist)*u,treadThickness:T(w.treadThickness)*u,riserThickness:T(w.riserThickness)*u,notchExtension:T(w.notchExtension)*u,notchThickness:T(w.notchThickness)*u}},W=f.sketch;if(W!=null&&W.boundary&&W.boundary.length>=4&&W.risers&&W.risers.length>=2){const k=W.boundary,K=W.risers[W.risers.length-1],ct=x=>[(x[0][0]+x[1][0])/2,(x[0][1]+x[1][1])/2],Ct=ct(K);let et=1,yt=1/0;for(let x=1;x<k.length;x++){const P=ct([k[x],k[(x+1)%k.length]]),ot=Math.abs(Math.hypot(P[0]-Ct[0],P[1]-Ct[1])-R);ot<yt&&(yt=ot,et=x)}const ft=(x,P)=>{const ot=[];for(let dt=x;dt!==P;dt=(dt+1)%k.length)ot.push([nt(k[dt]),nt(k[(dt+1)%k.length])]);return ot},ut=[...ft(1,et),...ft((et+1)%k.length,0)],N=W.risers.map(([x,P])=>[nt(x),nt(P)]);nt(k[et]),nt(k[(et+1)%k.length]);const it=N.map(([x,P])=>[(x[0]+P[0])/2,(x[1]+P[1])/2]);ht.sketch={boundary:ut,risers:N,path:it};let q=1/0;for(let x=0;x+1<W.risers.length;x++){const[P,ot]=W.risers[x],[dt,$t]=W.risers[x+1],X=[ot[0]-P[0],ot[1]-P[1]],V=[$t[0]-dt[0],$t[1]-dt[1]],wt=Math.hypot(X[0],X[1]),qt=Math.hypot(V[0],V[1]);Math.abs((X[0]*V[1]-X[1]*V[0])/(wt*qt))>.001||(q=Math.min(q,Math.abs(((dt[0]-P[0])*X[1]-(dt[1]-P[1])*X[0])/wt)))}Number.isFinite(q)&&(ht.tread=q*u,ht.sizes.minTread=q*u)}else ht.path=[nt([f.start[0],f.start[1]]),nt([f.end[0],f.end[1]])];const St=String(h.item.attrs.Name??""),M=St.replace(/ Run \d+$/,""),at=[];for(const k of o){if(k.kind!=="extrusion"||M===St||!new RegExp(`^${M.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")} Landing \\d+$`).test(String(k.item.attrs.Name??"")))continue;const K=Pt(k,"extrusion"),ct=K==null?void 0:K.on,Ct=(((Qs=(Xs=K==null?void 0:K.profile)==null?void 0:Xs.outline)==null?void 0:Qs.curves)??[]).flatMap(V=>V.from?[V.from]:[]),et=Rt(k.params.lookRef),yt=b.get(String((K==null?void 0:K.level)??k.params.level??""));if(!(ct!=null&&ct.origin)||!ct.u||!ct.v||Math.abs(ct.v[2]??0)<.99||!Ct.length||!et||!yt)continue;const[ft,ut]=[Math.min(...Ct.map(V=>V[0])),Math.max(...Ct.map(V=>V[0]))],[N,it]=[Math.min(...Ct.map(V=>V[1])),Math.max(...Ct.map(V=>V[1]))],q=ct.origin,x=ct.u;let P=[x[1],-x[0]];const ot=[(f.start[0]+f.end[0])/2,(f.start[1]+f.end[1])/2];(ot[0]-q[0])*P[0]+(ot[1]-q[1])*P[1]<0&&(P=[-P[0],-P[1]]);const $t=et/u,X=(V,wt)=>[(q[0]+x[0]*V+P[0]*wt)*u,(q[1]+x[1]*V+P[1]*wt)*u];at.push({outline:[X(ft,0),X(ut,0),X(ut,$t),X(ft,$t)],top:(yt.at+T(k.params.base)+q[2]+it)*u,thickness:(it-N)*u})}at.length&&(ht.landings=at);const gt={CategoryId:ue.stairs,Type:((Zs=Ke(h))==null?void 0:Zs.type)??String(g),Level:A.name,Stairs:JSON.stringify(ht)};mt(I(h.id),gt)&&Ht++}const ee={floor:0,foundation:0,roof:0,ceiling:0},It={floor:0,foundation:0,roof:0,ceiling:0};for(const h of o){const f=h.params.of;if(h.kind!=="extrusion"||f!=="slab"&&f!=="roof"&&f!=="covering")continue;const g=f==="covering"?"ceiling":f==="roof"?"roof":Cr(h);if(g==="other")continue;ee[g]++;const w=Pt(h,"extrusion"),A=typeof h.params.base=="number"?h.params.base:0,T=b.get(String((w==null?void 0:w.level)??h.params.level??"")),_=h.params.lookRef,S=M=>{if(!(M!=null&&M.length))return null;const at=[];for(const gt of M){if(gt.kind!=="segment"||!gt.from)return null;at.push(gt.from[0]*u,gt.from[1]*u,A*u)}return at.length>=9?at:null},R=S((er=(tr=w==null?void 0:w.profile)==null?void 0:tr.outline)==null?void 0:er.curves);if(typeof _!="string"||!T||!R)continue;const nt=[R],ht=g==="roof"?Tt(h):null;for(const M of((nr=w==null?void 0:w.profile)==null?void 0:nr.holes)??[]){const at=S(M==null?void 0:M.curves);if(at&&ht)for(let gt=0;gt+2<at.length;gt+=3)at[gt+2]=ht.zAt(at[gt]/u,at[gt+1]/u)*u;at&&nt.push(at)}const W={CategoryId:g==="roof"?ue.roofs:g==="ceiling"?ue.ceilings:g==="foundation"?ue.structuralFoundations:ue.floors,Type:((sr=Ke(h))==null?void 0:sr.type)??_,Profile:JSON.stringify(nt),Level:T.name},St=Rt(_);if(St&&(W["Type.Width"]=pt(St)),g==="roof"||g==="ceiling"){W.BaseOffset=pt(A*u);const M=Number(h.params.drop??((rr=w==null?void 0:w.said)==null?void 0:rr.drop));if(g==="ceiling"&&Number.isFinite(M)&&St){const k=[...b.values()].filter(K=>K.at>T.at+1e-6).sort((K,ct)=>K.at-ct.at)[0];k&&(W.BaseOffset=pt((k.at-M-St/u-T.at)*u))}const at=w==null?void 0:w.slopes;g==="roof"&&Array.isArray(at)&&at.some(k=>typeof k=="number")&&(W.Slopes=JSON.stringify(at.map(k=>typeof k=="number"?k:null)));const gt=g==="roof"?Tt(h):null;if(gt){const{A:k,n:K,u:ct,W:Ct,ridge:et,si:yt,ti:ft,tj:ut,L:N}=gt,it=(q,x)=>[(k[0]+K[0]*q)*u,(k[1]+K[1]*q)*u,x*u];W.Extrusion=JSON.stringify({profile:[it(0,ft),it(et,ft+yt*et),it(Ct,ut)],along:[ct[0],ct[1]],length:N*u}),delete W.Slopes}}else St&&(W.HeightOffset=pt(A*u+St));mt(I(h.id),W)&&It[g]++}let bt=0,Ut=0;for(const h of o){if(h.kind!=="member"||h.params.of!=="column")continue;Ut++;const f=Pt(h,"member"),g=f==null?void 0:f.start;if(!g||g.length!==3)continue;const w=c?xr(h.params.lookRef):null;if(c&&!w||!w&&!d)continue;const A=w??{family:d.family,type:d.type},T=b.get(String((f==null?void 0:f.level)??""));mt(I(h.id),{...d&&!w?{CategoryId:d.categoryId}:{},Family:A.family,Type:A.type,...T?{Level:T.name}:{}},{position:[g[0]*u,g[1]*u,g[2]*u],rotationDeg:(Number((f==null?void 0:f.roll)??0)||0)*$r})&&bt++}let Ae=0,ln=0,Ue=0;for(const h of o){if(h.kind!=="familyInstance")continue;if(h.params.host){Ue++;continue}if(ln++,!y)continue;const f=Pt(h,"instance"),g=(ir=f==null?void 0:f.placement)==null?void 0:ir.at;if(!g||g.length!==3)continue;const w=xr(h.params.type);if(!w)continue;const A=(or=f==null?void 0:f.placement)==null?void 0:or.right,T=A?Math.atan2(A[1],A[0])*$r:0;mt(I(h.id),{Family:w.family,Type:w.type},{position:[g[0]*u,g[1]*u,g[2]*u],rotationDeg:T})&&Ae++}const Oe=(()=>{if(!i)return 0;const h=[];for(const g of E){const w=g.record.item.guid;if(!w||!i.elements.has(w))continue;const A=Pt(g.record,"run"),T=b.get(String((A==null?void 0:A.level)??g.record.params.level??""));if(!A||!T)continue;const _=De(i,w);if(!_.length)continue;let S=1/0;for(const R of _)S=Math.min(S,R[2]);h.push(S-(T.at+(typeof A.base=="number"?A.base:0)))}h.sort((g,w)=>g-w);const f=h.length?h[Math.floor(h.length/2)]:0;return Math.abs(f)>.5?f:0})(),Ds=i?ma(i,j,e.fileId):[];let hn=0;for(const h of Ds)mt(h.key,h.attrs,{position:[h.at[0]*u,h.at[1]*u,(h.at[2]-Oe)*u],rotationDeg:h.rotationDeg,...h.host?{host:h.host}:{}})&&hn++;if(i)for(const h of ga(i,j,e.fileId))mt(h.key,{WallOpening:h.box.map((f,g)=>pt((g%3===2?f-Oe:f)*u)).join(",")},{host:h.host});if(i)for(const h of wa(i,e.fileId))mt(h.key,{Room:"1",Name:h.name,Number:h.number,Height:pt(h.height*u)},{position:[h.at[0]*u,h.at[1]*u,(h.at[2]-Oe)*u]});let Nn=0;const Ci=new Set(["slab","roof","covering"]);for(const h of o){const f=h.params.of;(h.kind==="footing"||h.kind==="ramp"||h.kind==="stair"&&f!=="stair"||h.kind==="extrusion"&&!Ci.has(String(f))||h.kind==="extrusion"&&f==="slab"&&Cr(h)==="other"&&!/ Landing \d+$/.test(String(h.item.attrs.Name??""))||h.kind==="run"&&f!=="wall"&&f!=="curtainWall")&&Nn++}let qe=0;for(const[h,f]of F)!h.startsWith(`${e.fileId}:`)||j.has(h)||(D.remove(f),qe++);if(D.length===0)throw new Ms(`Up to date: "${e.name}" holds ${st} element(s) this recipe already made, ${Ue+Nn} waiting on the applier, and nothing is left to remove.`);const $i=[te?`${te} level(s)`:"",Q?`${Q} wall(s)`:"",tt?`${tt} curtain wall(s)`:"",It.floor?`${It.floor} floor(s)`:"",It.foundation?`${It.foundation} foundation slab(s)`:"",It.roof?`${It.roof} roof(s)`:"",It.ceiling?`${It.ceiling} ceiling(s)`:"",Ht?`${Ht} stair(s)`:"",bt?`${bt} column(s)`:"",Ae?`${Ae} instance(s)`:"",hn?`${hn} family instance(s)`:"",Z?`${Z} changed`:"",qe?`${qe} gone`:""].filter(Boolean);return{title:`${s==="ifc"?"IFC":"Model"} to Revit: ${$i.join(", ")}`,verb:D.summary,targets:D.length,payload:new Blob([await D.build(t.opId)]),ruleTallies:[{read:b.size,written:te},{read:E.length+J,written:Q},{read:vt,written:tt},{read:ee.floor+ee.foundation,written:It.floor+It.foundation},{read:ee.roof,written:It.roof},{read:ee.ceiling,written:It.ceiling},{read:le,written:Ht},{read:Ut,written:bt},{read:ln,written:Ae},{read:Ds.length,written:hn},{read:qe,written:qe},{read:Ue+Nn,written:0}]}}}const Ea={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 bring free-standing instances (needs style names)",default:!1},createLevels:{type:"boolean",title:"Carry the model's levels (ensured by name)",default:!0}}},Ia=[{reads:"Levels (datums)",writes:"The same level in Revit, ensured by name"},{reads:"Wall runs, one per straight segment",writes:"A native wall: line, type (made from its width when missing), level, height, joins; its edited profile or its top on a roof"},{reads:"Curtain wall runs",writes:"Revit's curtain wall: its grid lines, mullions and panels"},{reads:"Slabs: floors and foundation slabs",writes:"A native floor or foundation slab from the profile, holes included"},{reads:"Roofs",writes:"A footprint roof with its sloping edges, or a roof by extrusion for a gable"},{reads:"Ceilings (coverings)",writes:"A native ceiling from the profile, hung at its drop"},{reads:"Stairs",writes:"A native stair: a straight or sketched run, with its landings"},{reads:"Column records (members)",writes:"A Revit column at each, on its level"},{reads:"Free-standing family instances",writes:"When turned on: a new instance of the same-named type, placed and turned"},{reads:"Everything else with a body: doors, windows, furniture, fixtures, proxies, columns, railings",writes:"A family made from the file's own shape, one per shape, placed where the file has it (doors and windows in their wall)"},{reads:"Things this recipe made whose record is gone",writes:"That element removed"},{reads:"Hosted doors/windows, footings, ramps, other bodies",writes:"Nothing yet - read and counted"}],Ii=`
1
+ "use strict";var Fi=Object.create;var jn=Object.defineProperty;var Li=Object.getOwnPropertyDescriptor;var Pi=Object.getOwnPropertyNames;var Bi=Object.getPrototypeOf,ji=Object.prototype.hasOwnProperty;var mr=s=>{throw TypeError(s)};var Di=(s,t,e)=>t in s?jn(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e;var Ui=(s,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Pi(t))!ji.call(s,r)&&r!==e&&jn(s,r,{get:()=>t[r],enumerable:!(n=Li(t,r))||n.enumerable});return s};var pn=(s,t,e)=>(e=s!=null?Fi(Bi(s)):{},Ui(t||!s||!s.__esModule?jn(e,"default",{value:s,enumerable:!0}):e,s));var kt=(s,t,e)=>Di(s,typeof t!="symbol"?t+"":t,e),Dn=(s,t,e)=>t.has(s)||mr("Cannot "+e);var g=(s,t,e)=>(Dn(s,t,"read from private field"),e?e.call(s):t.get(s)),K=(s,t,e)=>t.has(s)?mr("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(s):t.set(s,e),it=(s,t,e,n)=>(Dn(s,t,"write to private field"),n?n.call(s,e):t.set(s,e),e),p=(s,t,e)=>(Dn(s,t,"access private method"),e);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 wn=Object.create(null);Object.keys(ne).forEach(s=>{wn[ne[s]]=s});const Yn={type:"error",data:"parser error"},Lr=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",Pr=typeof ArrayBuffer=="function",Br=s=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(s):s&&s.buffer instanceof ArrayBuffer,Is=({type:s,data:t},e,n)=>Lr&&t instanceof Blob?e?n(t):gr(t,n):Pr&&(t instanceof ArrayBuffer||Br(t))?e?n(t):gr(new Blob([t]),n):n(ne[s]+(t||"")),gr=(s,t)=>{const e=new FileReader;return e.onload=function(){const n=e.result.split(",")[1];t("b"+(n||""))},e.readAsDataURL(s)};function yr(s){return s instanceof Uint8Array?s:s instanceof ArrayBuffer?new Uint8Array(s):new Uint8Array(s.buffer,s.byteOffset,s.byteLength)}let Un;function qi(s,t){if(Lr&&s.data instanceof Blob)return s.data.arrayBuffer().then(yr).then(t);if(Pr&&(s.data instanceof ArrayBuffer||Br(s.data)))return t(yr(s.data));Is(s,!1,e=>{Un||(Un=new TextEncoder),t(Un.encode(e))})}const wr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Ye=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let s=0;s<wr.length;s++)Ye[wr.charCodeAt(s)]=s;const Vi=s=>{let t=s.length*.75,e=s.length,n,r=0,i,o,a,l;s[s.length-1]==="="&&(t--,s[s.length-2]==="="&&t--);const d=new ArrayBuffer(t),c=new Uint8Array(d);for(n=0;n<e;n+=4)i=Ye[s.charCodeAt(n)],o=Ye[s.charCodeAt(n+1)],a=Ye[s.charCodeAt(n+2)],l=Ye[s.charCodeAt(n+3)],c[r++]=i<<2|o>>4,c[r++]=(o&15)<<4|a>>2,c[r++]=(a&3)<<6|l&63;return d},Gi=typeof ArrayBuffer=="function",Ss=(s,t)=>{if(typeof s!="string")return{type:"message",data:jr(s,t)};const e=s.charAt(0);return e==="b"?{type:"message",data:Hi(s.substring(1),t)}:wn[e]?s.length>1?{type:wn[e],data:s.substring(1)}:{type:wn[e]}:Yn},Hi=(s,t)=>{if(Gi){const e=Vi(s);return jr(e,t)}else return{base64:!0,data:s}},jr=(s,t)=>{switch(t){case"blob":return s instanceof Blob?s:new Blob([s]);case"arraybuffer":default:return s instanceof ArrayBuffer?s:s.buffer}},Dr="",Ji=(s,t)=>{const e=s.length,n=new Array(e);let r=0;s.forEach((i,o)=>{Is(i,!1,a=>{n[o]=a,++r===e&&t(n.join(Dr))})})},Wi=(s,t)=>{const e=s.split(Dr),n=[];for(let r=0;r<e.length;r++){const i=Ss(e[r],t);if(n.push(i),i.type==="error")break}return n};function zi(){return new TransformStream({transform(s,t){qi(s,e=>{const n=e.length;let r;if(n<126)r=new Uint8Array(1),new DataView(r.buffer).setUint8(0,n);else if(n<65536){r=new Uint8Array(3);const i=new DataView(r.buffer);i.setUint8(0,126),i.setUint16(1,n)}else{r=new Uint8Array(9);const i=new DataView(r.buffer);i.setUint8(0,127),i.setBigUint64(1,BigInt(n))}s.data&&typeof s.data!="string"&&(r[0]|=128),t.enqueue(r),t.enqueue(e)})}})}let qn;function mn(s){return s.reduce((t,e)=>t+e.length,0)}function gn(s,t){if(s[0].length===t)return s.shift();const e=new Uint8Array(t);let n=0;for(let r=0;r<t;r++)e[r]=s[0][n++],n===s[0].length&&(s.shift(),n=0);return s.length&&n<s[0].length&&(s[0]=s[0].slice(n)),e}function Yi(s,t){qn||(qn=new TextDecoder);const e=[];let n=0,r=-1,i=!1;return new TransformStream({transform(o,a){for(e.push(o);;){if(n===0){if(mn(e)<1)break;const l=gn(e,1);i=(l[0]&128)===128,r=l[0]&127,r<126?n=3:r===126?n=1:n=2}else if(n===1){if(mn(e)<2)break;const l=gn(e,2);r=new DataView(l.buffer,l.byteOffset,l.length).getUint16(0),n=3}else if(n===2){if(mn(e)<8)break;const l=gn(e,8),d=new DataView(l.buffer,l.byteOffset,l.length),c=d.getUint32(0);if(c>Math.pow(2,21)-1){a.enqueue(Yn);break}r=c*Math.pow(2,32)+d.getUint32(4),n=3}else{if(mn(e)<r)break;const l=gn(e,r);a.enqueue(Ss(i?l:qn.decode(l),t)),n=0}if(r===0||r>s){a.enqueue(Yn);break}}}})}const Ur=4;function _t(s){if(s)return Ki(s)}function Ki(s){for(var t in _t.prototype)s[t]=_t.prototype[t];return s}_t.prototype.on=_t.prototype.addEventListener=function(s,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+s]=this._callbacks["$"+s]||[]).push(t),this};_t.prototype.once=function(s,t){function e(){this.off(s,e),t.apply(this,arguments)}return e.fn=t,this.on(s,e),this};_t.prototype.off=_t.prototype.removeListener=_t.prototype.removeAllListeners=_t.prototype.removeEventListener=function(s,t){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var e=this._callbacks["$"+s];if(!e)return this;if(arguments.length==1)return delete this._callbacks["$"+s],this;for(var n,r=0;r<e.length;r++)if(n=e[r],n===t||n.fn===t){e.splice(r,1);break}return e.length===0&&delete this._callbacks["$"+s],this};_t.prototype.emit=function(s){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),e=this._callbacks["$"+s],n=1;n<arguments.length;n++)t[n-1]=arguments[n];if(e){e=e.slice(0);for(var n=0,r=e.length;n<r;++n)e[n].apply(this,t)}return this};_t.prototype.emitReserved=_t.prototype.emit;_t.prototype.listeners=function(s){return this._callbacks=this._callbacks||{},this._callbacks["$"+s]||[]};_t.prototype.hasListeners=function(s){return!!this.listeners(s).length};const kn=typeof Promise=="function"&&typeof Promise.resolve=="function"?t=>Promise.resolve().then(t):(t,e)=>e(t,0),qt=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),Xi="arraybuffer";function qr(s,...t){return t.reduce((e,n)=>(s.hasOwnProperty(n)&&(e[n]=s[n]),e),{})}const Qi=qt.setTimeout,Zi=qt.clearTimeout;function Mn(s,t){t.useNativeTimers?(s.setTimeoutFn=Qi.bind(qt),s.clearTimeoutFn=Zi.bind(qt)):(s.setTimeoutFn=qt.setTimeout.bind(qt),s.clearTimeoutFn=qt.clearTimeout.bind(qt))}const to=1.33;function eo(s){return typeof s=="string"?no(s):Math.ceil((s.byteLength||s.size)*to)}function no(s){let t=0,e=0;for(let n=0,r=s.length;n<r;n++)t=s.charCodeAt(n),t<128?e+=1:t<2048?e+=2:t<55296||t>=57344?e+=3:(n++,e+=4);return e}function Vr(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function so(s){let t="";for(let e in s)s.hasOwnProperty(e)&&(t.length&&(t+="&"),t+=encodeURIComponent(e)+"="+encodeURIComponent(s[e]));return t}function ro(s){let t={},e=s.split("&");for(let n=0,r=e.length;n<r;n++){let i=e[n].split("=");t[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return t}class io extends Error{constructor(t,e,n){super(t),this.description=e,this.context=n,this.type="TransportError"}}class _s extends _t{constructor(t){super(),this.writable=!1,Mn(this,t),this.opts=t,this.query=t.query,this.socket=t.socket,this.supportsBinary=!t.forceBase64}onError(t,e,n){return super.emitReserved("error",new io(t,e,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(t){this.readyState==="open"&&this.write(t)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(t){const e=Ss(t,this.socket.binaryType);this.onPacket(e)}onPacket(t){super.emitReserved("packet",t)}onClose(t){this.readyState="closed",super.emitReserved("close",t)}pause(t){}createUri(t,e={}){return t+"://"+this._hostname()+this._port()+this.opts.path+this._query(e)}_hostname(){const t=this.opts.hostname;return t.indexOf(":")===-1?t:"["+t+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(t){const e=so(t);return e.length?"?"+e:""}}class oo extends _s{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(t){this.readyState="pausing";const e=()=>{this.readyState="paused",t()};if(this._polling||!this.writable){let n=0;this._polling&&(n++,this.once("pollComplete",function(){--n||e()})),this.writable||(n++,this.once("drain",function(){--n||e()}))}else e()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){const e=n=>{if(this.readyState==="opening"&&n.type==="open"&&this.onOpen(),n.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(n)};Wi(t,this.socket.binaryType).forEach(e),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){const t=()=>{this.write([{type:"close"}])};this.readyState==="open"?t():this.once("open",t)}write(t){this.writable=!1,Ji(t,e=>{this.doWrite(e,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const t=this.opts.secure?"https":"http",e=this.query||{};return this.opts.timestampRequests!==!1&&(e[this.opts.timestampParam]=Vr()),!this.supportsBinary&&!e.sid&&(e.b64=1),this.createUri(t,e)}}let Gr=!1;try{Gr=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const ao=Gr;function co(){}class lo extends oo{constructor(t){if(super(t),typeof location<"u"){const e=location.protocol==="https:";let n=location.port;n||(n=e?"443":"80"),this.xd=typeof location<"u"&&t.hostname!==location.hostname||n!==t.port}}doWrite(t,e){const n=this.request({method:"POST",data:t});n.on("success",e),n.on("error",(r,i)=>{this.onError("xhr post error",r,i)})}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(e,n)=>{this.onError("xhr poll error",e,n)}),this.pollXhr=t}}class ee extends _t{constructor(t,e,n){super(),this.createRequest=t,Mn(this,n),this._opts=n,this._method=n.method||"GET",this._uri=e,this._data=n.data!==void 0?n.data:null,this._create()}_create(){var t;const e=qr(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");e.xdomain=!!this._opts.xd;const n=this._xhr=this.createRequest(e);try{n.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let r in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(r)&&n.setRequestHeader(r,this._opts.extraHeaders[r])}}catch{}if(this._method==="POST")try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{n.setRequestHeader("Accept","*/*")}catch{}(t=this._opts.cookieJar)===null||t===void 0||t.addCookies(n),"withCredentials"in n&&(n.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(n.timeout=this._opts.requestTimeout),n.onreadystatechange=()=>{var r;n.readyState===3&&((r=this._opts.cookieJar)===null||r===void 0||r.parseCookies(n.getResponseHeader("set-cookie"))),n.readyState===4&&(n.status===200||n.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof n.status=="number"?n.status:0)},0))},n.send(this._data)}catch(r){this.setTimeoutFn(()=>{this._onError(r)},0);return}typeof document<"u"&&(this._index=ee.requestsCount++,ee.requests[this._index]=this)}_onError(t){this.emitReserved("error",t,this._xhr),this._cleanup(!0)}_cleanup(t){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=co,t)try{this._xhr.abort()}catch{}typeof document<"u"&&delete ee.requests[this._index],this._xhr=null}}_onLoad(){const t=this._xhr.responseText;t!==null&&(this.emitReserved("data",t),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}ee.requestsCount=0;ee.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",vr);else if(typeof addEventListener=="function"){const s="onpagehide"in qt?"pagehide":"unload";addEventListener(s,vr,!1)}}function vr(){for(let s in ee.requests)ee.requests.hasOwnProperty(s)&&ee.requests[s].abort()}const ho=function(){const s=Hr({xdomain:!1});return s&&s.responseType!==null}();class fo extends lo{constructor(t){super(t);const e=t&&t.forceBase64;this.supportsBinary=ho&&!e}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new ee(Hr,this.uri(),t)}}function Hr(s){const t=s.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!t||ao))return new XMLHttpRequest}catch{}if(!t)try{return new qt[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const Jr=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class uo extends _s{get name(){return"websocket"}doOpen(){const t=this.uri(),e=this.opts.protocols,n=Jr?{}:qr(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(t,e,n)}catch(r){return this.emitReserved("error",r)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const n=t[e],r=e===t.length-1;Is(n,this.supportsBinary,i=>{try{this.doWrite(n,i)}catch{}r&&kn(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const t=this.opts.secure?"wss":"ws",e=this.query||{};return this.opts.timestampRequests&&(e[this.opts.timestampParam]=Vr()),this.supportsBinary||(e.b64=1),this.createUri(t,e)}}const Vn=qt.WebSocket||qt.MozWebSocket;class po extends uo{createSocket(t,e,n){return Jr?new Vn(t,e,n):e?new Vn(t,e):new Vn(t)}doWrite(t,e){this.ws.send(e)}}class mo extends _s{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(t){return this.emitReserved("error",t)}this._transport.closed.then(()=>{this.onClose()}).catch(t=>{this.onError("webtransport error",t)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(t=>{const e=Yi(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=t.readable.pipeThrough(e).getReader(),r=zi();r.readable.pipeTo(t.writable),this._writer=r.writable.getWriter();const i=()=>{n.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(t){this.writable=!1;for(let e=0;e<t.length;e++){const n=t[e],r=e===t.length-1;this._writer.write(n).then(()=>{r&&kn(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this._transport)===null||t===void 0||t.close()}}const go={websocket:po,webtransport:mo,polling:fo},yo=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,wo=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Kn(s){if(s.length>8e3)throw"URI too long";const t=s,e=s.indexOf("["),n=s.indexOf("]");e!=-1&&n!=-1&&(s=s.substring(0,e)+s.substring(e,n).replace(/:/g,";")+s.substring(n,s.length));let r=yo.exec(s||""),i={},o=14;for(;o--;)i[wo[o]]=r[o]||"";return e!=-1&&n!=-1&&(i.source=t,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=vo(i,i.path),i.queryKey=bo(i,i.query),i}function vo(s,t){const e=/\/{2,9}/g,n=t.replace(e,"/").split("/");return(t.slice(0,1)=="/"||t.length===0)&&n.splice(0,1),t.slice(-1)=="/"&&n.splice(n.length-1,1),n}function bo(s,t){const e={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(n,r,i){r&&(e[r]=i)}),e}const Xn=typeof addEventListener=="function"&&typeof removeEventListener=="function",vn=[];Xn&&addEventListener("offline",()=>{vn.forEach(s=>s())},!1);class Se extends _t{constructor(t,e){if(super(),this.binaryType=Xi,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,t&&typeof t=="object"&&(e=t,t=null),t){const n=Kn(t);e.hostname=n.host,e.secure=n.protocol==="https"||n.protocol==="wss",e.port=n.port,n.query&&(e.query=n.query)}else e.host&&(e.hostname=Kn(e.host).host);Mn(this,e),this.secure=e.secure!=null?e.secure:typeof location<"u"&&location.protocol==="https:",e.hostname&&!e.port&&(e.port=this.secure?"443":"80"),this.hostname=e.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=e.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},e.transports.forEach(n=>{const r=n.prototype.name;this.transports.push(r),this._transportsByName[r]=n}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},e),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=ro(this.opts.query)),Xn&&(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"})},vn.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(t){const e=Object.assign({},this.opts.query);e.EIO=Ur,e.transport=t,this.id&&(e.sid=this.id);const n=Object.assign({},this.opts,{query:e,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new this._transportsByName[t](n)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const t=this.opts.rememberUpgrade&&Se.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const e=this.createTransport(t);e.open(),this.setTransport(e)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",e=>this._onClose("transport close",e))}onOpen(){this.readyState="open",Se.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",t),this.emitReserved("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const e=new Error("server error");e.code=t.data,this._onError(e);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data);break}}onHandshake(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this._pingInterval=t.pingInterval,this._pingTimeout=t.pingTimeout,this._maxPayload=t.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const t=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+t,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},t),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const t=this._getWritablePackets();this.transport.send(t),this._prevBufferLen=t.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let n=0;n<this.writeBuffer.length;n++){const r=this.writeBuffer[n].data;if(r&&(e+=eo(r)),n>0&&e>this._maxPayload)return this.writeBuffer.slice(0,n);e+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const t=Date.now()>this._pingTimeoutTime;return t&&(this._pingTimeoutTime=0,kn(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),t}write(t,e,n){return this._sendPacket("message",t,e,n),this}send(t,e,n){return this._sendPacket("message",t,e,n),this}_sendPacket(t,e,n,r){if(typeof e=="function"&&(r=e,e=void 0),typeof n=="function"&&(r=n,n=null),this.readyState==="closing"||this.readyState==="closed")return;n=n||{},n.compress=n.compress!==!1;const i={type:t,data:e,options:n};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),r&&this.once("flush",r),this.flush()}close(){const t=()=>{this._onClose("forced close"),this.transport.close()},e=()=>{this.off("upgrade",e),this.off("upgradeError",e),t()},n=()=>{this.once("upgrade",e),this.once("upgradeError",e)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?n():t()}):this.upgrading?n():t()),this}_onError(t){if(Se.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",t),this._onClose("transport error",t)}_onClose(t,e){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),Xn&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const n=vn.indexOf(this._offlineEventListener);n!==-1&&vn.splice(n,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,e),this.writeBuffer=[],this._prevBufferLen=0}}}Se.protocol=Ur;class To extends Se{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let t=0;t<this._upgrades.length;t++)this._probe(this._upgrades[t])}_probe(t){let e=this.createTransport(t),n=!1;Se.priorWebsocketSuccess=!1;const r=()=>{n||(e.send([{type:"ping",data:"probe"}]),e.once("packet",m=>{if(!n)if(m.type==="pong"&&m.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",e),!e)return;Se.priorWebsocketSuccess=e.name==="websocket",this.transport.pause(()=>{n||this.readyState!=="closed"&&(c(),this.setTransport(e),e.send([{type:"upgrade"}]),this.emitReserved("upgrade",e),e=null,this.upgrading=!1,this.flush())})}else{const w=new Error("probe error");w.transport=e.name,this.emitReserved("upgradeError",w)}}))};function i(){n||(n=!0,c(),e.close(),e=null)}const o=m=>{const w=new Error("probe error: "+m);w.transport=e.name,i(),this.emitReserved("upgradeError",w)};function a(){o("transport closed")}function l(){o("socket closed")}function d(m){e&&m.name!==e.name&&i()}const c=()=>{e.removeListener("open",r),e.removeListener("error",o),e.removeListener("close",a),this.off("close",l),this.off("upgrading",d)};e.once("open",r),e.once("error",o),e.once("close",a),this.once("close",l),this.once("upgrading",d),this._upgrades.indexOf("webtransport")!==-1&&t!=="webtransport"?this.setTimeoutFn(()=>{n||e.open()},200):e.open()}onHandshake(t){this._upgrades=this._filterUpgrades(t.upgrades),super.onHandshake(t)}_filterUpgrades(t){const e=[];for(let n=0;n<t.length;n++)~this.transports.indexOf(t[n])&&e.push(t[n]);return e}}let Eo=class extends To{constructor(t,e={}){const n=typeof t=="object",r=n?{...t}:{...e};(!r.transports||r.transports&&typeof r.transports[0]=="string")&&(r.transports=(r.transports||["polling","websocket","webtransport"]).map(i=>go[i]).filter(i=>!!i)),super(n?r:t,r)}};function Io(s,t="",e){let n=s;e=e||typeof location<"u"&&location,s==null&&(s=e.protocol+"//"+e.host),typeof s=="string"&&(s.charAt(0)==="/"&&(s.charAt(1)==="/"?s=e.protocol+s:s=e.host+s),/^(https?|wss?):\/\//.test(s)||(typeof e<"u"?s=e.protocol+"//"+s:s="https://"+s),n=Kn(s)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";const i=n.host.indexOf(":")!==-1?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+i+":"+n.port+t,n.href=n.protocol+"://"+i+(e&&e.port===n.port?"":":"+n.port),n}const So=typeof ArrayBuffer=="function",_o=s=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(s):s.buffer instanceof ArrayBuffer,Wr=Object.prototype.toString,Ao=typeof Blob=="function"||typeof Blob<"u"&&Wr.call(Blob)==="[object BlobConstructor]",Oo=typeof File=="function"||typeof File<"u"&&Wr.call(File)==="[object FileConstructor]";function As(s){return So&&(s instanceof ArrayBuffer||_o(s))||Ao&&s instanceof Blob||Oo&&s instanceof File}function bn(s,t){if(!s||typeof s!="object")return!1;if(Array.isArray(s)){for(let e=0,n=s.length;e<n;e++)if(bn(s[e]))return!0;return!1}if(As(s))return!0;if(s.toJSON&&typeof s.toJSON=="function"&&arguments.length===1)return bn(s.toJSON(),!0);for(const e in s)if(Object.prototype.hasOwnProperty.call(s,e)&&bn(s[e]))return!0;return!1}function Co(s){const t=[],e=s.data,n=s;return n.data=Qn(e,t),n.attachments=t.length,{packet:n,buffers:t}}function Qn(s,t){if(!s)return s;if(As(s)){const e={_placeholder:!0,num:t.length};return t.push(s),e}else if(Array.isArray(s)){const e=new Array(s.length);for(let n=0;n<s.length;n++)e[n]=Qn(s[n],t);return e}else if(typeof s=="object"&&!(s instanceof Date)){const e={};for(const n in s)Object.prototype.hasOwnProperty.call(s,n)&&(e[n]=Qn(s[n],t));return e}return s}function $o(s,t){return s.data=Zn(s.data,t),delete s.attachments,s}function Zn(s,t){if(!s)return s;if(s&&s._placeholder===!0){if(typeof s.num=="number"&&s.num>=0&&s.num<t.length)return t[s.num];throw new Error("illegal attachments")}else if(Array.isArray(s))for(let e=0;e<s.length;e++)s[e]=Zn(s[e],t);else if(typeof s=="object")for(const e in s)Object.prototype.hasOwnProperty.call(s,e)&&(s[e]=Zn(s[e],t));return s}const xo=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var X;(function(s){s[s.CONNECT=0]="CONNECT",s[s.DISCONNECT=1]="DISCONNECT",s[s.EVENT=2]="EVENT",s[s.ACK=3]="ACK",s[s.CONNECT_ERROR=4]="CONNECT_ERROR",s[s.BINARY_EVENT=5]="BINARY_EVENT",s[s.BINARY_ACK=6]="BINARY_ACK"})(X||(X={}));class Ro{constructor(t){this.replacer=t}encode(t){return(t.type===X.EVENT||t.type===X.ACK)&&bn(t)?this.encodeAsBinary({type:t.type===X.EVENT?X.BINARY_EVENT:X.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id}):[this.encodeAsString(t)]}encodeAsString(t){let e=""+t.type;return(t.type===X.BINARY_EVENT||t.type===X.BINARY_ACK)&&(e+=t.attachments+"-"),t.nsp&&t.nsp!=="/"&&(e+=t.nsp+","),t.id!=null&&(e+=t.id),t.data!=null&&(e+=JSON.stringify(t.data,this.replacer)),e}encodeAsBinary(t){const e=Co(t),n=this.encodeAsString(e.packet),r=e.buffers;return r.unshift(n),r}}class Os extends _t{constructor(t){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},typeof t=="function"?{reviver:t}:t)}add(t){let e;if(typeof t=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");e=this.decodeString(t);const n=e.type===X.BINARY_EVENT;n||e.type===X.BINARY_ACK?(e.type=n?X.EVENT:X.ACK,this.reconstructor=new ko(e),e.attachments===0&&super.emitReserved("decoded",e)):super.emitReserved("decoded",e)}else if(As(t)||t.base64)if(this.reconstructor)e=this.reconstructor.takeBinaryData(t),e&&(this.reconstructor=null,super.emitReserved("decoded",e));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+t)}decodeString(t){let e=0;const n={type:Number(t.charAt(0))};if(X[n.type]===void 0)throw new Error("unknown packet type "+n.type);if(n.type===X.BINARY_EVENT||n.type===X.BINARY_ACK){const i=e+1;for(;t.charAt(++e)!=="-"&&e!=t.length;);const o=t.substring(i,e);if(o!=Number(o)||t.charAt(e)!=="-")throw new Error("Illegal attachments");const a=Number(o);if(!Mo(a)||a<0)throw new Error("Illegal attachments");if(a>this.opts.maxAttachments)throw new Error("too many attachments");n.attachments=a}if(t.charAt(e+1)==="/"){const i=e+1;for(;++e&&!(t.charAt(e)===","||e===t.length););n.nsp=t.substring(i,e)}else n.nsp="/";const r=t.charAt(e+1);if(r!==""&&Number(r)==r){const i=e+1;for(;++e;){const o=t.charAt(e);if(o==null||Number(o)!=o){--e;break}if(e===t.length)break}n.id=Number(t.substring(i,e+1))}if(t.charAt(++e)){const i=this.tryParse(t.substr(e));if(Os.isPayloadValid(n.type,i))n.data=i;else throw new Error("invalid payload")}return n}tryParse(t){try{return JSON.parse(t,this.opts.reviver)}catch{return!1}}static isPayloadValid(t,e){switch(t){case X.CONNECT:return br(e);case X.DISCONNECT:return e===void 0;case X.CONNECT_ERROR:return typeof e=="string"||br(e);case X.EVENT:case X.BINARY_EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&xo.indexOf(e[0])===-1);case X.ACK:case X.BINARY_ACK:return Array.isArray(e)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class ko{constructor(t){this.packet=t,this.buffers=[],this.reconPack=t}takeBinaryData(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){const e=$o(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const Mo=Number.isInteger||function(s){return typeof s=="number"&&isFinite(s)&&Math.floor(s)===s};function br(s){return Object.prototype.toString.call(s)==="[object Object]"}const No=Object.freeze(Object.defineProperty({__proto__:null,Decoder:Os,Encoder:Ro,get PacketType(){return X}},Symbol.toStringTag,{value:"Module"}));function zt(s,t,e){return s.on(t,e),function(){s.off(t,e)}}const Fo=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class zr extends _t{constructor(t,e,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=t,this.nsp=e,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const t=this.io;this.subs=[zt(t,"open",this.onopen.bind(this)),zt(t,"packet",this.onpacket.bind(this)),zt(t,"error",this.onerror.bind(this)),zt(t,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...t){return t.unshift("message"),this.emit.apply(this,t),this}emit(t,...e){var n,r,i;if(Fo.hasOwnProperty(t))throw new Error('"'+t.toString()+'" is a reserved event name');if(e.unshift(t),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(e),this;const o={type:X.EVENT,data:e};if(o.options={},o.options.compress=this.flags.compress!==!1,typeof e[e.length-1]=="function"){const c=this.ids++,m=e.pop();this._registerAckCallback(c,m),o.id=c}const a=(r=(n=this.io.engine)===null||n===void 0?void 0:n.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(t,e){var n;const r=(n=this.flags.timeout)!==null&&n!==void 0?n:this._opts.ackTimeout;if(r===void 0){this.acks[t]=e;return}const i=this.io.setTimeoutFn(()=>{delete this.acks[t];for(let a=0;a<this.sendBuffer.length;a++)this.sendBuffer[a].id===t&&this.sendBuffer.splice(a,1);e.call(this,new Error("operation has timed out"))},r),o=(...a)=>{this.io.clearTimeoutFn(i),e.apply(this,a)};o.withError=!0,this.acks[t]=o}emitWithAck(t,...e){return new Promise((n,r)=>{const i=(o,a)=>o?r(o):n(a);i.withError=!0,e.push(i),this.emit(t,...e)})}_addToQueue(t){let e;typeof t[t.length-1]=="function"&&(e=t.pop());const n={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((r,...i)=>(this._queue[0],r!==null?n.tryCount>this._opts.retries&&(this._queue.shift(),e&&e(r)):(this._queue.shift(),e&&e(null,...i)),n.pending=!1,this._drainQueue())),this._queue.push(n),this._drainQueue()}_drainQueue(t=!1){if(!this.connected||this._queue.length===0)return;const e=this._queue[0];e.pending&&!t||(e.pending=!0,e.tryCount++,this.flags=e.flags,this.emit.apply(this,e.args))}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){typeof this.auth=="function"?this.auth(t=>{this._sendConnectPacket(t)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:X.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,e){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,e),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(t=>{if(!this.sendBuffer.some(n=>String(n.id)===t)){const n=this.acks[t];delete this.acks[t],n.withError&&n.call(this,new Error("socket has been disconnected"))}})}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case X.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case X.EVENT:case X.BINARY_EVENT:this.onevent(t);break;case X.ACK:case X.BINARY_ACK:this.onack(t);break;case X.DISCONNECT:this.ondisconnect();break;case X.CONNECT_ERROR:this.destroy();const n=new Error(t.data.message);n.data=t.data.data,this.emitReserved("connect_error",n);break}}onevent(t){const e=t.data||[];t.id!=null&&e.push(this.ack(t.id)),this.connected?this.emitEvent(e):this.receiveBuffer.push(Object.freeze(e))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){const e=this._anyListeners.slice();for(const n of e)n.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&typeof t[t.length-1]=="string"&&(this._lastOffset=t[t.length-1])}ack(t){const e=this;let n=!1;return function(...r){n||(n=!0,e.packet({type:X.ACK,id:t,data:r}))}}onack(t){const e=this.acks[t.id];typeof e=="function"&&(delete this.acks[t.id],e.withError&&t.data.unshift(null),e.apply(this,t.data))}onconnect(t,e){this.id=t,this.recovered=e&&this._pid===e,this._pid=e,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:X.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){const e=this._anyListeners;for(let n=0;n<e.length;n++)if(t===e[n])return e.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(t),this}prependAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(t),this}offAnyOutgoing(t){if(!this._anyOutgoingListeners)return this;if(t){const e=this._anyOutgoingListeners;for(let n=0;n<e.length;n++)if(t===e[n])return e.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(t){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const e=this._anyOutgoingListeners.slice();for(const n of e)n.apply(this,t.data)}}}function De(s){s=s||{},this.ms=s.min||100,this.max=s.max||1e4,this.factor=s.factor||2,this.jitter=s.jitter>0&&s.jitter<=1?s.jitter:0,this.attempts=0}De.prototype.duration=function(){var s=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),e=Math.floor(t*this.jitter*s);s=Math.floor(t*10)&1?s+e:s-e}return Math.min(s,this.max)|0};De.prototype.reset=function(){this.attempts=0};De.prototype.setMin=function(s){this.ms=s};De.prototype.setMax=function(s){this.max=s};De.prototype.setJitter=function(s){this.jitter=s};class ts extends _t{constructor(t,e){var n;super(),this.nsps={},this.subs=[],t&&typeof t=="object"&&(e=t,t=void 0),e=e||{},e.path=e.path||"/socket.io",this.opts=e,Mn(this,e),this.reconnection(e.reconnection!==!1),this.reconnectionAttempts(e.reconnectionAttempts||1/0),this.reconnectionDelay(e.reconnectionDelay||1e3),this.reconnectionDelayMax(e.reconnectionDelayMax||5e3),this.randomizationFactor((n=e.randomizationFactor)!==null&&n!==void 0?n:.5),this.backoff=new De({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(e.timeout==null?2e4:e.timeout),this._readyState="closed",this.uri=t;const r=e.parser||No;this.encoder=new r.Encoder,this.decoder=new r.Decoder,this._autoConnect=e.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,t||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(t){return t===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var e;return t===void 0?this._reconnectionDelay:(this._reconnectionDelay=t,(e=this.backoff)===null||e===void 0||e.setMin(t),this)}randomizationFactor(t){var e;return t===void 0?this._randomizationFactor:(this._randomizationFactor=t,(e=this.backoff)===null||e===void 0||e.setJitter(t),this)}reconnectionDelayMax(t){var e;return t===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,(e=this.backoff)===null||e===void 0||e.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(t){if(~this._readyState.indexOf("open"))return this;this.engine=new Eo(this.uri,this.opts);const e=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const r=zt(e,"open",function(){n.onopen(),t&&t()}),i=a=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",a),t?t(a):this.maybeReconnectOnOpen()},o=zt(e,"error",i);if(this._timeout!==!1){const a=this._timeout,l=this.setTimeoutFn(()=>{r(),i(new Error("timeout")),e.close()},a);this.opts.autoUnref&&l.unref(),this.subs.push(()=>{this.clearTimeoutFn(l)})}return this.subs.push(r),this.subs.push(o),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(zt(t,"ping",this.onping.bind(this)),zt(t,"data",this.ondata.bind(this)),zt(t,"error",this.onerror.bind(this)),zt(t,"close",this.onclose.bind(this)),zt(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(e){this.onclose("parse error",e)}}ondecoded(t){kn(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,e){let n=this.nsps[t];return n?this._autoConnect&&!n.active&&n.connect():(n=new zr(this,t,e),this.nsps[t]=n),n}_destroy(t){const e=Object.keys(this.nsps);for(const n of e)if(this.nsps[n].active)return;this._close()}_packet(t){const e=this.encoder.encode(t);for(let n=0;n<e.length;n++)this.engine.write(e[n],t.options)}cleanup(){this.subs.forEach(t=>t()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(t,e){var n;this.cleanup(),(n=this.engine)===null||n===void 0||n.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,e),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const e=this.backoff.duration();this._reconnecting=!0;const n=this.setTimeoutFn(()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),!t.skipReconnect&&t.open(r=>{r?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",r)):t.onreconnect()}))},e);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const Ge={};function Ze(s,t){typeof s=="object"&&(t=s,s=void 0),t=t||{};const e=Io(s,t.path||"/socket.io"),n=e.source,r=e.id,i=e.path,o=Ge[r]&&i in Ge[r].nsps,a=t.forceNew||t["force new connection"]||t.multiplex===!1||o;let l;return a?l=new ts(n,t):(Ge[r]||(Ge[r]=new ts(n,t)),l=Ge[r]),e.query&&!t.query&&(t.query=e.queryKey),l.socket(e.path,t)}Object.assign(Ze,{Manager:ts,Socket:zr,io:Ze,connect:Ze});class es extends Error{constructor(t,e){super(`The document history advanced while this version was being prepared: expected head ${t}, found ${e??"none"}. Read the timeline again and rebuild on the new head.`),this.expectedGuid=t,this.actualGuid=e,this.name="StaleHistoryError"}}const Tr="bimterop",ns="revitflow_history.json",Yr="revitflow_model.frag",Kr="revitflow_",Lo="bimterop-locks-anchor";function Po(s,t){return s.filter(e=>String(e.parentId??"")===t)}function Bo(s){const t=s==null?void 0:s.hiddenFileId;if(typeof t!="string"||!t)throw new Error("The hidden-file upload answered without a hiddenFileId.");return t}function Zt(s){return String(s._id??s.id??"")}var Wt,Ae,oe,sn,rn,ss;class Cs{constructor(t,e){K(this,rn);K(this,Wt);K(this,Ae,new Map);K(this,oe);K(this,sn,0);this.client=t,this.projectId=e}async docs(){const t=await p(this,rn,ss).call(this);if(!t)return[];const e=await this.childFolders(t,!0),n=[];for(const r of e){if(r.archived)continue;const i=String(r.name??""),o=i.indexOf("-");if(o<=0)continue;const l=(await this.client.listFiles({folderId:Zt(r)})).map(m=>String(m.name??"")),d=l.find(m=>m===Yr)??l.find(m=>m.endsWith(".frag")&&!m.startsWith(Kr)),c=l.includes(ns)||!!d;n.push({source:i.slice(0,o),docId:i.slice(o+1),folderId:Zt(r),modelName:d,...c?{}:{empty:!0}})}return n}doc(t,e){const n=`${t}-${e}`;let r=g(this,Ae).get(n);return r||(r=new rs(this.client,this,t,e),g(this,Ae).set(n,r)),r}document(t){const e=`platform-${t}`;let n=g(this,Ae).get(e);return n||(n=new rs(this.client,this,"platform",t,t),g(this,Ae).set(e,n)),n}async childFolders(t,e=!1){return(e||!g(this,oe)||Date.now()-g(this,sn)>3e4)&&(it(this,sn,Date.now()),it(this,oe,this.client.listFolders({parentFolderId:t,projectId:this.projectId}).then(n=>Po(n,t))),g(this,oe).catch(()=>{it(this,oe,void 0)})),g(this,oe)}forgetFolders(){it(this,oe,void 0)}async rootFolderId(t=!1){if(g(this,Wt))return g(this,Wt);const e=await p(this,rn,ss).call(this);if(e)return e;if(!t)return;const n=await this.client.createFolder(Tr,void 0,this.projectId);return it(this,Wt,Zt(n)),g(this,Wt)}}Wt=new WeakMap,Ae=new WeakMap,oe=new WeakMap,sn=new WeakMap,rn=new WeakSet,ss=async function(){if(g(this,Wt))return g(this,Wt);const e=(await this.client.listFolders({projectId:this.projectId})).find(n=>String(n.name??"")===Tr&&!n.parentId);return e&&it(this,Wt,Zt(e)),g(this,Wt)};var Xt,M,ie,Re,ye,Qt,on,is,Tn,we,Xr,En,Qr,Zr,ti;class rs{constructor(t,e,n,r,i){K(this,M);K(this,Xt);K(this,Qt);K(this,on,0);this.client=t,this.project=e,this.source=n,this.docId=r,it(this,Xt,i)}async timeline(){const t=await p(this,M,En).call(this);return $s((t==null?void 0:t.commits)??[])}async latest(){const t=await this.timeline();return t.length?t[t.length-1]:null}async delta(t){if(!t.deltaId)throw new Error(`Version ${t.guid} carries no delta: it is a full export — read model() instead.`);return await(await this.client.downloadHiddenFile(t.deltaId)).blob()}async model(){const t=await p(this,M,we).call(this);if(!t)throw new Error(`Document ${this.source}-${this.docId} has no model file yet.`);const e=await this.client.downloadFile(t.id);if(!e.ok)throw new Error(`Reading the model answered ${e.status}`);return await e.blob()}async modelParts(t){const e=await this.timeline();if(e.length===0)throw new Error(`Document ${this.source}-${this.docId} has no history yet.`);const n=t==null?void 0:t.at,r=n?e.findIndex(c=>c.guid===n):e.length-1;if(r<0)throw new Error(`No version ${n} in this document's timeline.`);let i=0;for(let c=r;c>=0;c--)if(e[c].full){i=c;break}const o=await p(this,M,we).call(this);if(!o)throw new Error(`Document ${this.source}-${this.docId} has no model file yet.`);const a=e[i],l=e.slice(r+1).some(c=>c.full),d=e.slice(i+1,r+1).map(c=>({guid:c.guid,...c.deltaId?{deltaId:c.deltaId}:{},...c.streamId?{streamId:c.streamId}:{},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:e[r].guid}}async folderId(){return await p(this,M,ye).call(this,!1)}async descriptor(){return await g(this,M,ie).descriptor(await p(this,M,ye).call(this,!1))}async view(t){const e=await p(this,M,ye).call(this,!1),n=await g(this,M,ie).descriptor(e);if(n){for(const i of t){const o=n.views.find(a=>a.format===i);if(o)return o}return null}if(!t.includes("frag"))return null;const r=await p(this,M,we).call(this);return r?{fileId:r.id,format:"frag"}:null}async addView(t){const e=await p(this,M,ye).call(this,!0);if(await g(this,M,ie).descriptor(e)){await g(this,M,ie).addView(e,t);return}const r=await p(this,M,we).call(this);await g(this,M,ie).setDescriptor(e,{name:(r==null?void 0:r.name.replace(/\.frag$/,""))??g(this,M,Re),views:[t]})}async ensureDescriptor(){const t=await p(this,M,ye).call(this,!1),e=await g(this,M,ie).descriptor(t);if(e)return e;const n=await p(this,M,we).call(this);if(!n)return null;const r={name:n.name.replace(/\.frag$/,""),views:[{fileId:n.id,format:"frag"}]};return await g(this,M,ie).setDescriptor(t,r),await g(this,M,ie).descriptor(t)}async ownership(){const t=await p(this,M,Tn).call(this,Lo);if(!t)return[];const e=await this.client.getHiddenFilesByParent(t.id),n=await Promise.all(e.map(async o=>{try{const a=Zt(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 n)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(t){var a;const e=await p(this,M,ye).call(this,!0);let n=await p(this,M,En).call(this)??{model:this.docId,commits:[]};const r=Er(n.commits);if(t.expectedLatestGuid!==void 0&&(r==null?void 0:r.guid)!==t.expectedLatestGuid)throw new es(t.expectedLatestGuid,r==null?void 0:r.guid);const i={guid:xs(),...r?{parents:[r.guid]}:{},author:t.author,source:t.source,timestamp:new Date().toISOString(),...t.message?{message:t.message}:{},...t.userId?{userId:t.userId}:{},...t.kind?{kind:t.kind}:{},...t.file?{file:t.file}:{},...t.origin?{origin:t.origin}:{},...(a=t.origins)!=null&&a.length?{origins:t.origins}:{},changes:t.changes,counts:jo(t.changes)};if(t.model&&(await p(this,M,ti).call(this,e,t.model),i.full=!0),t.delta){const l=await p(this,M,we).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(t.delta,l.id);i.deltaId=Bo(d)}const o=await p(this,M,En).call(this);if(o){n=o;const l=Er(n.commits);if(t.expectedLatestGuid!==void 0&&(l==null?void 0:l.guid)!==t.expectedLatestGuid)throw new es(t.expectedLatestGuid,l==null?void 0:l.guid);l&&!i.parents&&(i.parents=[l.guid])}return n.commits.push(i),await p(this,M,Qr).call(this,e,ns,n),i}}Xt=new WeakMap,M=new WeakSet,ie=function(){return new ks(this.client,this.project.projectId)},Re=function(){return`${this.source}-${this.docId}`},ye=async function(t){if(g(this,Xt))return g(this,Xt);const e=await this.project.rootFolderId(t);if(!e)throw new Error(`Project ${this.project.projectId} has no connected documents yet.`);const n=o=>o.find(a=>String(a.name??"")===g(this,M,Re)),r=n(await this.project.childFolders(e))??n(await this.project.childFolders(e,!0));if(r)return it(this,Xt,Zt(r)),g(this,Xt);if(!t)throw new Error(`Document ${g(this,M,Re)} does not exist in this project.`);const i=await this.client.createFolder(g(this,M,Re),e,this.project.projectId);return this.project.forgetFolders(),it(this,Xt,Zt(i)),g(this,Xt)},Qt=new WeakMap,on=new WeakMap,is=async function(){return(!g(this,Qt)||Date.now()-g(this,on)>5e3)&&(it(this,on,Date.now()),it(this,Qt,(async()=>{const t=await p(this,M,ye).call(this,!1);return(await this.client.listFiles({projectId:this.project.projectId})).filter(n=>{const r=n;return String(r.folderId??r.parentFolderId??"")===t}).map(n=>({id:Zt(n),name:String(n.name??"")}))})()),g(this,Qt).catch(()=>{it(this,Qt,void 0)})),g(this,Qt)},Tn=async function(t){try{return(await p(this,M,is).call(this)).find(e=>e.name===t)}catch{return}},we=async function(){try{const t=await p(this,M,is).call(this);return t.find(e=>e.name===Yr)??t.find(e=>e.name.endsWith(".frag")&&!e.name.startsWith(Kr))}catch{return}},Xr=async function(t){const e=await p(this,M,Tn).call(this,t);if(!e)return;const n=await this.client.downloadFile(e.id);if(!n.ok)throw new Error(`Reading ${t} answered ${n.status}`);const r=await n.text();if(r.trim())return JSON.parse(r)},En=function(){return p(this,M,Xr).call(this,ns)},Qr=async function(t,e,n){const r=new Blob([JSON.stringify(n)],{type:"application/json"}),i=await p(this,M,Tn).call(this,e);return i?(await this.client.updateFile(i.id,{file:r,versionTag:await this.client.nextVersionTag(i.id)}),i):await p(this,M,Zr).call(this,t,e,n)},Zr=async function(t,e,n){const r=new Blob([JSON.stringify(n)],{type:"application/json"}),i=await this.client.createFile({file:r,name:e,versionTag:"v1",parentFolderId:t,projectId:this.project.projectId});it(this,Qt,void 0);const o=i.item;return{id:Zt(o??i),name:e}},ti=async function(t,e){const n=await p(this,M,we).call(this);if(n)return await this.client.updateFile(n.id,{file:e,versionTag:await this.client.nextVersionTag(n.id)}),n;const r=`${g(this,M,Re)}.frag`,i=await this.client.createFile({file:e,name:r,versionTag:"v1",parentFolderId:t,projectId:this.project.projectId});it(this,Qt,void 0);const o=i.item;return{id:Zt(o??i),name:r}};function jo(s){const t={added:0,modified:0,removed:0};for(const e of s)e.type==="create"?t.added++:e.type==="delete"?t.removed++:t.modified++;return t}function $s(s){var l;if(s.length<=1)return s.forEach((d,c)=>d.ordinal=c),[...s];const t=new Map(s.map(d=>[d.guid,d])),e=new Map,n=[];for(const d of s){const c=(l=d.parents)==null?void 0:l[0];if(c&&t.has(c)){const m=e.get(c)??[];m.push(d),e.set(c,m)}else n.push(d)}const r=(d,c)=>String(d.timestamp).localeCompare(String(c.timestamp));n.sort(r);const i=[],o=[...n].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=(e.get(d.guid)??[]).sort(r);for(let m=c.length-1;m>=0;m--)o.push(c[m])}for(const d of s)a.has(d.guid)||i.push(d);return i.forEach((d,c)=>d.ordinal=c),i}function Er(s){const t=$s(s);return t[t.length-1]}function xs(){const s=globalThis.crypto;return s!=null&&s.randomUUID?s.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}const Rs={bim:{label:"BIM model",icon:"tabler:building"},drawings:{label:"Drawings",icon:"tabler:layout-board"},reality:{label:"Reality capture",icon:"tabler:3d-cube-sphere"},coordination:{label:"Coordination set",icon:"tabler:messages"},generic:{label:"Generic",icon:"tabler:file"}},Do={rvt:"bim",rfa:"bim",ifc:"bim",frag:"bim",tostrm:"bim","3dm":"bim",nwd:"bim",dgn:"bim",dwg:"drawings",dxf:"drawings",las:"reality",laz:"reality",e57:"reality",ply:"reality",potree:"reality",splat:"reality",spz:"reality",ksplat:"reality",bcf:"coordination",bcfzip:"coordination"};function os(s){var e;if(s.type&&s.type in Rs)return s.type;const t=[(e=s.native)==null?void 0:e.format,...s.views.map(n=>n.format)];for(const n of t){const r=n?Do[n.toLowerCase()]:void 0;if(r)return r}return"generic"}const en="thatopen/document@1",In="document.json",ei=["pdf","txt","md","json","csv","tsv","frag"];function se(s){return String(s._id??s.id??"")}const He=new Map,Ir=s=>{const t=s,e=[...t.versions??[]].sort((r,i)=>String(i.createdAt??"").localeCompare(String(r.createdAt??"")))[0],n=(e==null?void 0:e.tag)??t.versionTag;return n==null?void 0:String(n)};var Rt,ni,as,si,ri,ii,Sn;class ks{constructor(t,e){K(this,Rt);this.client=t,this.projectId=e}async list(t){const e=await p(this,Rt,ni).call(this),n=t==null?void 0:t.types;return n!=null&&n.length?e.filter(r=>n.includes(os(r.descriptor))):e}async fromFile(t,e){const n=await this.client.getFile(t),r=String(n.name??""),i=Gn(r,n.fileExtension),o=(e==null?void 0:e.name)??r.replace(/\.[^.]+$/,"")??r,a=await this.client.createFolder(o,n.folderId?String(n.folderId):void 0,this.projectId),l=se(a);await this.client.updateFile(t,{parentFolderId:l});const d=[],c=await p(this,Rt,ri).call(this,n);if(c)try{const v=await this.client.getFile(c);await this.client.updateFile(c,{parentFolderId:l}),d.push({fileId:c,format:Gn(String(v.name??""),v.fileExtension)})}catch{}((e==null?void 0:e.selfView)??ei.includes(i))&&d.push({fileId:t,format:i});const w={schema:en,name:o,native:{fileId:t,format:i},views:d};return w.type=(e==null?void 0:e.type)??os(w),await this.setDescriptor(l,w),await this.recordUpload(l,{fileId:t,name:r,format:i},(e==null?void 0:e.author)??String(n.createdBy??"")),{folderId:l,descriptor:w}}async recordUpload(t,e,n){const r=new Cs(this.client,this.projectId).document(t),i=(await r.timeline()).length===0;await r.sync({author:n||"unknown",source:"platform",kind:"upload",message:i?"Uploaded to the platform":"New version uploaded",file:{...e,format:e.format??Gn(e.name,void 0)},changes:[]})}async descriptor(t){const e=await p(this,Rt,Sn).call(this,t);return e?p(this,Rt,as).call(this,e.id,e.stamp):null}async view(t,e){const n=await this.descriptor(t);if(!n)return null;for(const r of e){const i=n.views.find(o=>o.format===r);if(i)return i}return null}async addView(t,e){const n=await this.descriptor(t);if(!n)throw new Error("This folder has no document descriptor yet: call setDescriptor first.");n.views=[...n.views.filter(r=>r.format!==e.format),e],await this.setDescriptor(t,n)}async setType(t,e){const n=await this.descriptor(t);if(!n)throw new Error("This folder has no document descriptor yet: call setDescriptor first.");n.type!==e&&await this.setDescriptor(t,{...n,type:e})}async setDescriptor(t,e){const n={...e,schema:en,views:e.views??[]},r=new Blob([JSON.stringify(n)],{type:"application/json"}),i=await p(this,Rt,Sn).call(this,t);if(i){He.delete(i.id),await this.client.updateFile(i.id,{file:r,versionTag:await this.client.nextVersionTag(i.id)});return}await this.client.createFile({file:r,name:In,versionTag:"v1",parentFolderId:t,projectId:this.projectId})}drafts(t){return new oi(this.client,()=>p(this,Rt,Sn).call(this,t))}}Rt=new WeakSet,ni=async function(){const e=(await this.client.listFiles({projectId:this.projectId})).filter(r=>String(r.name??"")===In);return(await Promise.all(e.map(async r=>{const i=r,o=String(i.folderId??i.parentFolderId??"");if(!o)return null;const a=await p(this,Rt,as).call(this,se(r),Ir(r));return a?{folderId:o,descriptor:a}:null}))).filter(r=>r!==null)},as=function(t,e){const n=e?He.get(t):void 0;if(n&&n.stamp===e)return n.value;const r=p(this,Rt,si).call(this,t);return e&&(He.set(t,{stamp:e,value:r}),r.catch(()=>{var i;((i=He.get(t))==null?void 0:i.value)===r&&He.delete(t)})),r},si=async function(t){const e=await this.client.downloadFile(t);if(!e.ok)throw new Error(`Reading a document's descriptor answered ${e.status}`);const n=await e.text();if(!n.trim())return null;let r;try{r=JSON.parse(n)}catch{return null}return Go(r)},ri=async function(t){let e=t.versions??[],n;if(e.length===0){n=await this.client.listFiles({projectId:this.projectId}).catch(()=>[]);const a=n.find(l=>se(l)===se(t));e=(a==null?void 0:a.versions)??[]}const r=await p(this,Rt,ii).call(this,t,e);if(r)return r;const i=String(t.name??"").replace(/\.[^.]+$/,"").toLowerCase();if(!i)return;n??(n=await this.client.listFiles({projectId:this.projectId}).catch(()=>[]));const o=n.find(a=>String(a.name??"").toLowerCase()===`${i}.frag`&&!a.archived&&se(a)!==se(t));return o?se(o):void 0},ii=async function(t,e){const n=[...e].sort((r,i)=>String(i.createdAt??"").localeCompare(String(r.createdAt??"")));for(const r of n)try{const i=await this.client.getFileVersionMetadata(se(t),r.tag),o=i==null?void 0:i.derivedFileId;if(typeof o=="string"&&o)return o}catch{}},Sn=async function(t){const n=(await this.client.listFiles({projectId:this.projectId})).filter(r=>{const i=r;return String(i.folderId??i.parentFolderId??"")===t}).find(r=>String(r.name??"")===In);return n?{id:se(n),stamp:Ir(n)}:void 0};const cs="draft:",ke="TODRAFT1";var te,Ke,ls;class oi{constructor(t,e){K(this,te);this.client=t,this.holder=e}async list(){const t=await this.holder();if(!t)return[];const e=new Map;for(const n of await p(this,te,Ke).call(this,t.id)){const r=e.get(n.userId);(!r||n.savedAt>r.savedAt)&&e.set(n.userId,{userId:n.userId,savedAt:n.savedAt})}return[...e.values()].sort((n,r)=>+r.savedAt-+n.savedAt)}async get(t){const e=await this.holder();if(!e)return null;const r=(await p(this,te,Ke).call(this,e.id)).filter(l=>!(t!=null&&t.userId)||l.userId===t.userId).sort((l,d)=>+d.savedAt-+l.savedAt)[0];if(!r)return null;const i=await this.client.downloadHiddenFile(r.hiddenId),{meta:o,blob:a}=await Vo(await i.blob());return{userId:r.userId,savedAt:r.savedAt,meta:o,blob:a}}async put(t,e){const n=await this.holder();if(!n)throw new Error("This folder is not a document (no document.json): drafts need one.");const r=Uo(e.userId),i=(await p(this,te,Ke).call(this,n.id)).filter(l=>l.userId===e.userId),a=(await this.client.createHiddenFile(await qo(t,e.meta??{}),n.id,r)).hiddenFileId;if(!a)throw new Error("The draft upload answered without a hiddenFileId.");return await p(this,te,ls).call(this,i.map(l=>l.hiddenId)),{userId:e.userId,savedAt:Sr(a)}}async delete(t){const e=await this.holder();if(!e)return;const n=(await p(this,te,Ke).call(this,e.id)).filter(r=>r.userId===t.userId);await p(this,te,ls).call(this,n.map(r=>r.hiddenId))}}te=new WeakSet,Ke=async function(t){return(await this.client.getHiddenFilesByParent(t)).filter(n=>typeof n.tag=="string"&&n.tag.startsWith(cs)).map(n=>{const r=String(n._id);return{hiddenId:r,userId:n.tag.slice(cs.length),savedAt:Sr(r)}})},ls=async function(t){for(const e of t)try{await this.client.deleteHiddenFile(e)}catch{}};function Uo(s){const t=`${cs}${s}`;if(!/^[A-Za-z0-9][A-Za-z0-9:._-]{0,49}$/.test(t))throw new Error(`A draft cannot be tagged for user "${s}": ids must be letters, digits or :._- and short.`);return t}function Sr(s){const t=parseInt(s.slice(0,8),16);return new Date(Number.isFinite(t)?t*1e3:0)}async function qo(s,t){const e=new TextEncoder().encode(JSON.stringify(t)),n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,e.length,!0),new Blob([new TextEncoder().encode(ke),n,e,s])}async function Vo(s){const t=new Uint8Array(await s.slice(0,ke.length+4).arrayBuffer());if(new TextDecoder().decode(t.slice(0,ke.length))!==ke)return{meta:{},blob:s};const e=new DataView(t.buffer).getUint32(ke.length,!0),n=ke.length+4,r=await s.slice(n,n+e).text();let i={};try{i=JSON.parse(r)}catch{}return{meta:i,blob:s.slice(n+e)}}function Gn(s,t){const e=(t??"").replace(/^\./,"").toLowerCase();if(e)return e;const n=s.lastIndexOf(".");return n>0?s.slice(n+1).toLowerCase():""}function Go(s){if(!s||typeof s!="object")return null;const t=s;if(t.schema!==en||typeof t.name!="string")return null;const e=Array.isArray(t.views)?t.views.filter(o=>!!o&&typeof o=="object"&&typeof o.fileId=="string"&&typeof o.format=="string"):[],n=t.native,r=!!n&&typeof n=="object"&&typeof n.fileId=="string"&&typeof n.format=="string",i=typeof t.type=="string"&&t.type in Rs?t.type:void 0;return{schema:en,name:t.name,...i?{type:i}:{},...r?{native:{fileId:n.fileId,format:n.format}}:{},views:e}}const Ho="flow:",Jo="flow:op",Wo="flow:source",zo="flow:host",Ms="revitflow/op@2",_r="REVITFLOWCHANGE",Ar="REVITFLOWOPERATION";class Nn{constructor(t){kt(this,"changes",[]);this.target=t}get length(){return this.changes.length}get batchId(){return this.target.batchId}get title(){return this.target.title??`${this.changes.length} change(s)`}get author(){return this.target.author??"app"}get userId(){return this.target.userId}get baseCommit(){return this.target.baseCommit}add(t,e={}){return this.changes.push({op:"add",attrs:this.pack(t,e)}),this}set(t,e,n={}){return this.requireId(t,"set"),this.changes.push({op:"set",item:t,attrs:this.pack(e,n)}),this}remove(t){return this.requireId(t,"remove"),this.changes.push({op:"remove",item:t,attrs:{}}),this}get summary(){const t=new Set(this.changes.map(e=>e.op));return t.size===1?[...t][0]:"mixed"}async build(t){if(this.changes.length===0)throw new Error("An operation with no changes is not an operation. Add at least one.");const e={schema:Ms,opId:t,batchId:this.batchId??t,targetProject:this.target.project,targetDocument:this.target.document,baseCommit:this.baseCommit,author:this.author,...this.userId?{userId:this.userId}:{},title:this.title,summary:this.summary},[n,r]=await Yo();return Ko(this.flatbuffer(n,r,t,JSON.stringify(e)))}pack(t,e){const n={};for(const[r,i]of Object.entries(t??{}))r.startsWith(Ho)||(n[r]=String(i));return e.position&&(n.Position=e.position.map(Or).join(",")),e.rotationDeg!==void 0&&(n.Rotation=Or(e.rotationDeg)),e.source&&(n[Wo]=e.source),e.host&&(n[zo]=e.host),n}requireId(t,e){if(!t||!t.trim())throw new Error(`A '${e}' has to name the item it acts on.`)}flatbuffer(t,e,n,r){const{Attribute:i,Meshes:o,Model:a,SpatialStructure:l,Transform:d}=e,c=new t.Builder(1024),m=this.changes.length,w=new Uint32Array(m);let v=1;for(let et=0;et<m;et++)w[et]=v++;const I=v++,_=et=>(et(c,0),c.endVector()),L=o.createShellsVector(c,[]),C=o.createCircleExtrusionsVector(c,[]),O=_(o.startSamplesVector),u=_(o.startRepresentationsVector),$=_(o.startMaterialsVector),E=_(o.startLocalTransformsVector),N=_(o.startGlobalTransformsVector),z=o.createMeshesItemsVector(c,[]),ut=o.createMaterialIdsVector(c,[]),wt=o.createRepresentationIdsVector(c,[]),Ot=o.createSampleIdsVector(c,[]),Vt=o.createLocalTransformIdsVector(c,[]),Mt=o.createGlobalTransformIdsVector(c,[]);o.startMeshes(c),o.addCoordinates(c,d.createTransform(c,0,0,0,1,0,0,0,1,0)),o.addGlobalTransforms(c,N),o.addShells(c,L),o.addRepresentations(c,u),o.addSamples(c,O),o.addLocalTransforms(c,E),o.addMaterials(c,$),o.addCircleExtrusions(c,C),o.addMeshesItems(c,z),o.addRepresentationIds(c,wt),o.addSampleIds(c,Ot),o.addMaterialIds(c,ut),o.addLocalTransformIds(c,Vt),o.addGlobalTransformIds(c,Mt);const he=o.endMeshes(c),Yt=c.createString(r),It=new Set,Gt=[];for(const et of this.changes){const At=[],Ht={[Jo]:et.op,...et.attrs};for(const[de,Ue]of Object.entries(Ht)){const $e=JSON.stringify([de,Ue,"IFCTEXT"]);It.add($e),At.push(c.createString($e))}Gt.push(i.createAttribute(c,i.createDataVector(c,At)))}{const et=JSON.stringify(["Name",n,"IFCLABEL"]);It.add(et);const At=i.createDataVector(c,[c.createString(et)]);Gt.push(i.createAttribute(c,At))}const Nt=a.createAttributesVector(c,Gt),Ce=a.createUniqueAttributesVector(c,[...It].map(et=>c.createString(et))),q=this.changes.map(()=>c.createString(_r));q.push(c.createString(Ar));const Z=a.createCategoriesVector(c,q),x=[],Tt=[];this.changes.forEach((et,At)=>{et.item&&(x.push(c.createString(et.item)),Tt.push(w[At]))});const Et=a.createGuidsVector(c,x),pt=a.createGuidsItemsVector(c,Tt),jt=a.createLocalIdsVector(c,[...w,I]),Ft=this.changes.map((et,At)=>l.createSpatialStructure(c,w[At],c.createString(_r),0)),Pt=l.createSpatialStructure(c,I,c.createString(Ar),l.createChildrenVector(c,Ft)),st=c.createString(n);a.startModel(c),a.addMeshes(c,he),a.addMetadata(c,Yt),a.addAttributes(c,Nt),a.addUniqueAttributes(c,Ce),a.addLocalIds(c,jt),a.addCategories(c,Z),a.addGuidsItems(c,pt),a.addGuids(c,Et),a.addGuid(c,st),a.addSpatialStructure(c,Pt),a.addMaxLocalId(c,v);const rt=a.endModel(c);return a.finishModelBuffer(c,rt),c.asUint8Array()}}async function Yo(){try{return await Promise.all([import("flatbuffers"),import("@thatopen/fragments")])}catch(s){throw new Error(`OperationBuilder needs the optional peers \`flatbuffers\` and \`@thatopen/fragments\` installed — add them to the app that authors operations. (${s instanceof Error?s.message:String(s)})`)}}function Or(s){return Number.isFinite(s)?String(s):"0"}async function Ko(s){const t=new Blob([s]).stream().pipeThrough(new CompressionStream("deflate"));return new Uint8Array(await new Response(t).arrayBuffer())}async function Fn(s){const[t,e]=await Xo(),n=e.Model.getRootAsModel(new t.ByteBuffer(await Qo(s)));let r={};try{r=JSON.parse(n.metadata()??"{}")}catch{}const i=new Map;for(let a=0;a<n.guidsLength();a++){const l=n.guidsItems(a),d=n.guids(a);l!==null&&d&&i.set(l,d)}const o=[];for(let a=0;a<n.attributesLength();a++){const l=n.localIds(a);if(l===null)continue;const d={},c=n.attributes(a);for(let m=0;m<((c==null?void 0:c.dataLength())??0);m++){const w=c.data(m);if(w)try{const[v,I]=JSON.parse(w);d[v]=I}catch{}}o.push({localId:l,guid:i.get(l)??null,category:n.categories(a)??null,attrs:d})}return{metadata:r,items:o}}async function Xo(){try{return await Promise.all([import("flatbuffers"),import("@thatopen/fragments")])}catch(s){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). (${s instanceof Error?s.message:String(s)})`)}}async function Qo(s){const t=new Blob([s]).stream().pipeThrough(new DecompressionStream("deflate"));return new Uint8Array(await new Response(t).arrayBuffer())}const ai="Element",ci="Carried",Ne=1/.3048;function li(s){const t=[];for(const e of s)for(const n of[ai,ci]){const r=e.attrs[n];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"||t.push({id:a.id,kind:a.kind,params:a.params??{},item:e})}}catch{}}return t}function Bt(s,t){const e=s.params[t];if(typeof e!="string")return null;try{return JSON.parse(e)}catch{return null}}function Zo(s){const t=new Map;for(const[e,n]of Ns(s))t.set(e,n.name);return t}function Ns(s){const t=new Map;for(const e of s){if(e.kind!=="datum"||e.params.of!=="level")continue;const n=e.params.named,r=e.params.at;typeof n=="string"&&typeof r=="number"&&t.set(e.id,{name:n,at:r})}return t}function hi(s){const t=new Map;for(const e of s){if(!e.kind.endsWith("Style"))continue;const n=e.params.name;typeof n=="string"&&t.set(n,e)}return t}function Fs(s,t){const e=new Map;for(const[n,r]of s.made)e.set(n,r.id),r.print&&(t==null||t.set(n,r.print));return e}function di(s){const t=r=>Array.isArray(r)?r.map(t):r&&typeof r=="object"?Object.fromEntries(Object.keys(r).sort().map(i=>[i,t(r[i])])):r,e=JSON.stringify(t(s));let n=2166136261;for(let r=0;r<e.length;r++)n^=e.charCodeAt(r),n=Math.imul(n,16777619);return(n>>>0).toString(36)}async function Ls(s,t){var o,a;if(!(t!=null&&t.fileId))throw new Error("Choose the model file to read.");s.progress(`Downloading ${t.name}`);let e=new Uint8Array(await(await s.client.downloadFile(t.fileId,t.version?{versionTag:t.version}:void 0)).arrayBuffer());const n=((a=(o=/\.([^.]+)$/.exec(t.name))==null?void 0:o[1])==null?void 0:a.toLowerCase())??"frag";let r=null,i=null;if(n!=="frag"){const l=s.client.recipes.importerFor(n);if(!l)throw new Error(`This app cannot read .${n} files: it provides no importer for them.`);n==="ifc"&&(r=fi(e));const d=s.client.recipes.shapesFor(n);d&&(s.progress(`Reading the shapes of ${t.name}`),i=await d(e,t.name)),s.progress(`Reading ${t.name}`),e=await l(e,t.name)}return{picked:t,contents:await Fn(e),site:r,shapes:i}}function fi(s){var N;const t=new TextDecoder("latin1").decode(s),e=z=>new RegExp(`^${z}=\\s*([A-Z0-9_]+)\\((.*)\\);\\s*$`,"m").exec(t),n=z=>[...z.matchAll(/#\d+|\$/g)].map(ut=>ut[0]),r=z=>[...z.matchAll(/-?\d+(?:\.\d*)?(?:E[-+]?\d+)?/gi)].map(ut=>Number(ut[0])),i=/^(#\d+)=\s*IFCSITE\((.*)\);\s*$/m.exec(t);if(!i)return null;const o=(N=i[2].split(",")[5])==null?void 0:N.trim();if(!(o!=null&&o.startsWith("#")))return null;const a=e(o);if((a==null?void 0:a[1])!=="IFCLOCALPLACEMENT")return null;const[l,d]=n(a[2]);if(l!=="$"||!d)return null;const c=e(d);if((c==null?void 0:c[1])!=="IFCAXIS2PLACEMENT3D")return null;const[m,,w]=n(c[2]),v=m&&m!=="$"?e(m):null;if(!v)return null;const[I=0,_=0,L=0]=r(v[2]);let C=0;const O=w&&w!=="$"?e(w):null;if(O){const[z=1,ut=0]=r(O[2]);C=Math.atan2(ut,z)*180/Math.PI}const u=/IFCSIUNIT\([^)]*\.LENGTHUNIT\.\s*,\s*(\.([A-Z]+)\.|\$)\s*,\s*\.METRE\./i.exec(t),$={MILLI:.001,CENTI:.01,DECI:.1,KILO:1e3},E=u?u[2]?$[u[2].toUpperCase()]??1:1:/IFCCONVERSIONBASEDUNIT\([^)]*\.LENGTHUNIT\.[^)]*'FOOT'/i.test(t)?.3048:1;return{east:I*E,north:_*E,elevation:L*E,angleDeg:C}}const Ps="thatopen/recipe@1",Cr="__project_data",$r="recipes",ta=s=>`${s}.recipe.json`,ui={OperationBuilder:Nn,OP_SCHEMA:Ms,readFrag:Fn,readPickedFrag:Ls,recordsOf:li,innerJson:Bt,levelsOf:Ns,levelNames:Zo,stylesOf:hi,printOf:di,siteLocationOf:fi,whatItMadeBefore:Fs,ELEMENT_FIELD:ai,CARRIED_FIELD:ci,FEET_PER_METRE:Ne},pi=/^[a-z0-9][a-z0-9-]{1,62}$/;async function mi(s,t,e){const n=d=>[...d].sort((c,m)=>String(c._id).localeCompare(String(m._id)))[0],r=await s.listFolders({projectId:t,archived:!1});let i=n(r.filter(d=>d.name===Cr&&!d.parentId));if(!i){if(!e)return null;i=await s.createFolder(Cr,void 0,t)}const o=String(i._id),a=await s.listFolders({parentFolderId:o,projectId:t,archived:!1});let l=n(a.filter(d=>d.name===$r&&String(d.parentId)===o));if(!l){if(!e)return null;l=await s.createFolder($r,o,t)}return String(l._id)}const ea=s=>String(s._id??s.id??""),na=s=>String(s.tag??s.versionTag??""),hs=s=>{var t;return Number(((t=/(\d+)/.exec(s))==null?void 0:t[1])??-1)};async function Je(s,t){const e=await mi(s,t,!1);if(!e)return new Map;const n=await s.listFiles({folderId:e}),r=new Map;for(const i of n){const o=String(i.name??"");o.endsWith(".recipe.json")&&r.set(o.slice(0,-12),{id:ea(i)})}return r}async function yn(s,t,e){var i;const n=await s.downloadFile(t,e?{versionTag:e}:void 0),r=JSON.parse(await n.text());if((r==null?void 0:r.schema)!==Ps||!((i=r.manifest)!=null&&i.name)||typeof r.code!="string")throw new Error(`This is not a recipe this library can read (${String(r==null?void 0:r.schema)}).`);return r}async function We(s,t){return(await s.listVersions(t)).map(n=>({tag:na(n),createdAt:String(n.createdAt??"")})).filter(n=>n.tag).sort((n,r)=>hs(n.tag)-hs(r.tag))}var an;class gi{constructor(t,e){K(this,an,new Map);this.client=t,this.builtinNames=e}async list(t){const e=await Je(this.client,t);return(await Promise.all([...e.entries()].map(async([,{id:r}])=>{var i;try{const o=await We(this.client,r),a=(i=o[o.length-1])==null?void 0:i.tag,l=await yn(this.client,r,a);return{manifest:l.manifest,origin:"project",version:a,author:l.author,savedAt:l.savedAt}}catch{return null}}))).filter(r=>r!==null)}async versions(t,e){const n=(await Je(this.client,t)).get(e);if(!n)throw new Error(`The project has no recipe named "${e}".`);const r=await We(this.client,n.id);return await Promise.all(r.map(async({tag:i,createdAt:o})=>{try{const a=await yn(this.client,n.id,i);return{version:i,author:a.author,note:a.note,savedAt:a.savedAt??o}}catch{return{version:i,savedAt:o}}}))}async source(t,e,n){var o;const r=(await Je(this.client,t)).get(e);if(!r)throw new Error(`The project has no recipe named "${e}".`);const i=n??((o=(await We(this.client,r.id)).pop())==null?void 0:o.tag);if(!i)throw new Error(`The recipe "${e}" has no saved version.`);return{...await yn(this.client,r.id,i),version:i}}async save(t,e,n){const{manifest:r,code:i}=e;if(!pi.test((r==null?void 0:r.name)??""))throw new Error('A recipe name is lower case letters, digits and dashes, 2 to 63 of them: "walls-from-ifc".');if(this.builtinNames().has(r.name))throw new Error(`"${r.name}" is a built-in recipe. Give yours a name of its own.`);if(!r.to||!r.description||!Array.isArray(r.inputs))throw new Error("A recipe says what it writes (`to`), what it does (`description`) and what it reads (`inputs`).");await ds(r,i);const o={schema:Ps,manifest:r,code:i,author:n.author,...n.note?{note:n.note}:{},savedAt:new Date().toISOString()},a=new Blob([JSON.stringify(o,null,2)],{type:"application/json"}),l=(await Je(this.client,t)).get(r.name);if(l){const c=await We(this.client,l.id),m=`v${Math.max(0,...c.map(w=>hs(w.tag)))+1}`;return await this.client.createVersion(l.id,a,m),m}const d=await mi(this.client,t,!0);return await this.client.createFile({file:a,name:ta(r.name),versionTag:"v1",projectId:t,parentFolderId:d}),"v1"}async load(t,e,n){var l;const r=(await Je(this.client,t)).get(e);if(!r)throw new Error(`The project has no recipe named "${e}".`);const i=n??((l=(await We(this.client,r.id)).pop())==null?void 0:l.tag);if(!i)throw new Error(`The recipe "${e}" has no saved version.`);const o=`${r.id}@${i}`;let a=g(this,an).get(o);if(!a){const d=await yn(this.client,r.id,i);a=await ds(d.manifest,d.code),g(this,an).set(o,a)}return{recipe:a,version:i}}}an=new WeakMap;async function ds(s,t){var r;let e;try{e=await import(`data:text/javascript;base64,${sa(t)}`)}catch(i){throw new Error(`The recipe's code does not load: ${i instanceof Error?i.message:String(i)}`)}const n=e.run??((r=e.default)==null?void 0:r.run);if(typeof n!="function")throw new Error("The recipe's code exports no `run(context)` function.");return{...s,run:i=>n({...i,kit:ui})}}function sa(s){const t=new TextEncoder().encode(s);let e="";for(let n=0;n<t.length;n+=32768)e+=String.fromCharCode(...t.subarray(n,n+32768));return btoa(e)}async function ra(s){const t=s instanceof Uint8Array?s:new Uint8Array(await s.arrayBuffer()),{items:e,metadata:n}=await Fn(t),r=e.filter(i=>i.attrs["flow:op"]).map(i=>{const o={};for(const[a,l]of Object.entries(i.attrs))a.startsWith("flow:")||(o[a]=l);return{op:i.attrs["flow:op"],...i.guid?{target:i.guid}:{},...i.attrs["flow:source"]?{source:i.attrs["flow:source"]}:{},attrs:o}});return{envelope:n??{},changes:r}}class Bs extends Error{constructor(t){super(t),this.name="UpToDate"}}var ae,cn,ln;class yi{constructor(t){K(this,ae,new Map);K(this,cn,new Map);K(this,ln,new Map);kt(this,"project");this.client=t,this.project=new gi(t,()=>new Set(g(this,ae).keys()))}provideImporter(t,e){g(this,cn).set(t.toLowerCase(),e)}provideShapes(t,e){g(this,ln).set(t.toLowerCase(),e)}shapesFor(t){return g(this,ln).get(t.toLowerCase())}importerFor(t){return g(this,cn).get(t.toLowerCase())}register(t){if(g(this,ae).has(t.name))throw new Error(`A recipe named "${t.name}" is already registered.`);g(this,ae).set(t.name,t)}list(t){return[...g(this,ae).values()].filter(n=>(!(t!=null&&t.to)||n.to===t.to)&&(!(t!=null&&t.input)||n.inputs.includes(t.input)))}get(t){return g(this,ae).get(t)}async catalog(t,e){const n=this.list(e).map(i=>({manifest:i,origin:"builtin"}));let r=[];try{r=(await this.project.list(t)).filter(i=>!(e!=null&&e.to)||i.manifest.to===e.to)}catch{}return[...n,...r.sort((i,o)=>i.manifest.name.localeCompare(o.manifest.name))]}async resolve(t,e,n){const r=g(this,ae).get(t);return r?{recipe:r,origin:"builtin"}:{...await this.project.load(e,t,n),origin:"project"}}async choices(t,e){const{recipe:n}=await this.resolve(t,e),r=n.source;if((r==null?void 0:r.kind)!=="project-file")return[];const i=(r.extensions??[]).map(d=>d.toLowerCase()),a=(await this.client.documents(e).list()).filter(d=>d.descriptor.native&&(i.length===0||i.includes(d.descriptor.native.format.toLowerCase()))),l=await wi(this.client,a.map(d=>d.descriptor.native.fileId));return a.map(d=>{const c=d.descriptor.native;return{label:d.descriptor.name,fileId:c.fileId,name:`${d.descriptor.name}.${c.format}`,folderId:d.folderId,version:l.get(c.fileId)??"v1"}}).sort((d,c)=>d.label.localeCompare(c.label))}async run(t,e){const{recipe:n}=await this.resolve(t,e.projectId,e.recipeVersion);if(n.to!==e.target.source)throw new Error(`Recipe "${t}" writes ${n.to}, but the target document belongs to ${e.target.source}.`);return await n.run({client:this.client,projectId:e.projectId,target:e.target,made:e.made??new Map,opId:e.opId??xs(),input:e.input,settings:e.settings??{},progress:e.progress??(()=>{})})}}ae=new WeakMap,cn=new WeakMap,ln=new WeakMap;async function wi(s,t){const e=new Map;if(t.length===0)return e;const n=i=>{var o;return Number(((o=/(\d+)/.exec(String(i??"")))==null?void 0:o[1])??-1)},r=i=>{const a=i.slice().sort((l,d)=>{const c=l!=null&&l.createdAt?new Date(String(l.createdAt)).getTime():NaN,m=d!=null&&d.createdAt?new Date(String(d.createdAt)).getTime():NaN;return!Number.isNaN(c)&&!Number.isNaN(m)&&c!==m?m-c:n((d==null?void 0:d.tag)??(d==null?void 0:d.versionTag))-n((l==null?void 0:l.tag)??(l==null?void 0:l.versionTag))})[0];return a?String(a.tag??a.versionTag??"v1"):"v1"};return await Promise.all(t.map(async i=>{try{e.set(i,r(await s.listVersions(i)))}catch{e.set(i,"v1")}})),e}const fs=100;function ia(s){try{const t=JSON.parse(s);if(t&&typeof t=="object"){const e=t;return{message:typeof e.message=="string"?e.message:void 0,code:typeof e.code=="string"?e.code:void 0,details:e.details}}}catch{}return{}}function oa(s){if(!s||typeof s!="object")return;const t=s.retryAfter;return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}class Ln extends Error{constructor(e,n,r,i){const o=ia(r);super(o.message??`${n||"Request failed"} (${e})`);kt(this,"status");kt(this,"code");kt(this,"details");kt(this,"body");kt(this,"retryAfter");this.name="RequestError",this.status=e,this.code=o.code,this.details=o.details,this.body=r,this.retryAfter=i??oa(o.details)}}const Kt="item/folder",W="item",pe="processor",aa="npm-registry",re="hidden",Hn="FILE",Jn="TOOL",Wn="APP",ca=500,xr=3e4,la=2e3,ze=new Map,ha=.25,da=s=>new Promise(t=>setTimeout(t,s));function fa(s){var r,i;const t=(i=(r=s.headers)==null?void 0:r.get)==null?void 0:i.call(r,"Retry-After");if(!t)return;const e=Number(t);if(Number.isFinite(e))return Math.max(0,e);const n=Date.parse(t);if(!Number.isNaN(n))return Math.max(0,(n-Date.now())/1e3)}function ua(s){return s instanceof Ln?s.status===429||s.status>=500:!0}function pa(s,t){const e=Math.min(ca*2**t,xr),n=e*ha*Math.random(),r=s instanceof Ln&&s.retryAfter!=null?s.retryAfter*1e3:void 0;return r!=null?Math.min(r,xr)+n:e+n}var T,_n,F,us,ve,hn,Xe,An,On,ps,ms,gs;const Us=class Us{constructor(t,e,n){K(this,T);kt(this,"apiUrl");kt(this,"accessToken");kt(this,"wsUrl");kt(this,"retries");kt(this,"useBearer");kt(this,"builtInGlobals",null);kt(this,"localServerUrl",null);kt(this,"context");K(this,hn);const{retries:r=0,useBearer:i=!1,localServerUrl:o}=n||{};let a=e;if(a.charAt(a.length-1)==="/"&&(a=a.slice(0,-1)),this.apiUrl=`${a}/api`,this.accessToken=t,this.wsUrl=a,this.retries=r,this.useBearer=i,this.context={appId:"",projectId:"",accessToken:t,apiUrl:e},o){let l=o;l.charAt(l.length-1)==="/"&&(l=l.slice(0,-1)),this.localServerUrl=l}}static fromPlatformContext(t){const e=(typeof window<"u"?window.__THATOPEN_CONTEXT__:null)||{appId:"",projectId:"",accessToken:"",apiUrl:""},n=new Us(e.accessToken,e.apiUrl,{...t,useBearer:!0});return n.context=e,n}setRetries(t){this.retries=t}setBuiltInGlobals(t){this.builtInGlobals=t}get socketOrigin(){return this.wsUrl.split("?")[0]}async resolveAccessToken(){return this.accessToken}async request(t,e,n){return p(this,T,F).call(this,t,e,n)}async listFiles(t){const{folderId:e,archived:n,projectId:r}=t||{};return e?await p(this,T,F).call(this,"GET",`${Kt}/${e}/items`,{query:{itemType:Hn,archived:n}}):await p(this,T,F).call(this,"GET",`${W}`,{query:{itemType:Hn,archived:n,...r&&{projectId:r}}})}async getFile(t,e){return await p(this,T,ms).call(this,t,e)}async createFile(t){return await p(this,T,On).call(this,t,Hn)}async updateFile(t,e){return await p(this,T,ps).call(this,t,e)}async archiveFile(t){return await p(this,T,F).call(this,"DELETE",`${W}/${t}`)}async recoverFile(t){return await p(this,T,F).call(this,"PUT",`${W}/${t}/recover`)}async downloadFile(t,e){return await p(this,T,An).call(this,t,e)}async getFileVersionMetadata(t,e,n){const{withDraft:r}=n||{};return await p(this,T,F).call(this,"GET",`${W}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/metadata`,{query:{...r&&{withDraft:"true"}}})}async updateFileVersionMetadata(t,e,n){return await p(this,T,F).call(this,"PUT",`${W}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/metadata`,{body:JSON.stringify({metadata:n}),contentType:"application/json"})}async deleteFileVersionMetadata(t,e){return await p(this,T,F).call(this,"DELETE",`${W}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/metadata`)}async getFileVersionMetadataBatch(t,e){const{withDraft:n}=e||{};return await p(this,T,Xe).call(this,t,async r=>(await p(this,T,F).call(this,"POST",`${W}/batch/version-metadata`,{body:JSON.stringify({entries:r,...n!==void 0&&{withDraft:n}}),contentType:"application/json"})).results)}async listFolders(t){const{archived:e,parentFolderId:n,projectId:r}=t||{};return await p(this,T,F).call(this,"GET",Kt,{query:{parentFolderId:n,archived:e,...r&&{projectId:r}}})}async getFolder(t){return await p(this,T,F).call(this,"GET",`${Kt}/${t}`)}async getFoldersBatch(t){return await p(this,T,Xe).call(this,t,async e=>(await p(this,T,F).call(this,"POST",`${W}/batch/folders`,{body:JSON.stringify({folderIds:e}),contentType:"application/json"})).results)}async createFolder(t,e,n){return await p(this,T,F).call(this,"POST",Kt,{body:JSON.stringify({name:t,...e&&{parentId:e},...n&&{projectId:n}}),contentType:"application/json"})}async updateFolder(t,e){const{name:n}=e;return await p(this,T,F).call(this,"PUT",`${Kt}/${t}`,{body:JSON.stringify({name:n}),contentType:"application/json"})}async archiveFolder(t){return await p(this,T,F).call(this,"DELETE",`${Kt}/${t}`)}async recoverFolder(t){return await p(this,T,F).call(this,"PUT",`${Kt}/${t}/recover`)}async downloadFolder(t){return await p(this,T,ve).call(this,`${Kt}/${t}/download`)}async listComponents(t){const{folderId:e,ShowVersions:n,projectId:r}=t||{};return e?await p(this,T,F).call(this,"GET",`${Kt}/${e}/items`,{query:{itemType:Jn,...n&&{ShowVersions:n}}}):await p(this,T,F).call(this,"GET",`${W}`,{query:{itemType:Jn,...n&&{ShowVersions:n},...r&&{projectId:r}}})}async getComponent(t,e){return await p(this,T,ms).call(this,t,e)}async createComponent(t){const{componentProps:e}=t;return await p(this,T,On).call(this,t,Jn,e)}async updateComponent(t,e){const{componentProps:n}=e;return await p(this,T,ps).call(this,t,e,n)}async downloadComponent(t,e){return await p(this,T,An).call(this,t,e)}async downloadComponentBundle(t,e){const{versionTag:n,withDraft:r}=e||{};return await p(this,T,ve).call(this,`${W}/${t}/download/bundle`,{query:{...n&&{versionTag:n},...r&&{withDraft:r}}})}async archiveComponent(t){return await p(this,T,F).call(this,"DELETE",`${W}/${t}`)}async recoverComponent(t){return await p(this,T,F).call(this,"PUT",`${W}/${t}/recover`)}async getBuiltInComponent(t){return await(await p(this,T,ve).call(this,`built-in/${t}/bundle`)).text()}async initBuiltInComponent(t,e,n){const r=await this.getBuiltInComponent(t.uuid),i=n??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;e.get(c)}async initBuiltInComponents(t,...e){await Promise.all(e.map(n=>this.initBuiltInComponent(n,t)))}async setup(t,...e){var o,a;const n=t.OBC,r=t.BUI;if(!(n!=null&&n.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 n.Components;return r.Manager.init(),this.setBuiltInGlobals(t),await this.initBuiltInComponents(i,...e),i.init(),(a=(o=this.context.appEventOrchestrator)==null?void 0:o.appLoaded)==null||a.call(o),{components:i}}throwError(t,e){var n,r;(r=(n=this.context.appEventOrchestrator)==null?void 0:n.appError)==null||r.call(n,t,e)}async listApps(t){const{folderId:e,ShowVersions:n,projectId:r}=t||{};return e?await p(this,T,F).call(this,"GET",`${Kt}/${e}/items`,{query:{itemType:Wn,...n&&{ShowVersions:n}}}):await p(this,T,F).call(this,"GET",`${W}`,{query:{itemType:Wn,...n&&{ShowVersions:n},...r&&{projectId:r}}})}async createApp(t){const{appProps:e}=t;return await p(this,T,On).call(this,t,Wn,e)}async downloadApp(t,e){return await p(this,T,An).call(this,t,e)}async downloadAppBundle(t,e){const{versionTag:n,withDraft:r}=e||{};return await p(this,T,ve).call(this,`${W}/${t}/download/bundle`,{query:{...n&&{versionTag:n},...r&&{withDraft:r}}})}async archiveApp(t){return await p(this,T,F).call(this,"DELETE",`${W}/${t}`)}async getNpmCredentials(){return await p(this,T,F).call(this,"GET",`${aa}/credentials`)}async executeComponent(t,e,n){if(this.localServerUrl){const r=`${this.localServerUrl}/api/${pe}/${t}/execute`,i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!i.ok){const o=await i.text().catch(()=>"");throw new Error(`Local server request failed: ${i.status} - ${o}`)}return await i.json()}return await p(this,T,F).call(this,"POST",`${pe}/${t}/execute`,{body:JSON.stringify(e),query:{...n&&{versionTag:n}},contentType:"application/json"})}async abortExecution(t){if(this.localServerUrl){const e=`${this.localServerUrl}/api/${pe}/progress/${t}/abort`,n=await fetch(e,{method:"POST"});if(!n.ok){const r=await n.text().catch(()=>"");throw new Error(`Local server request failed: ${n.status} - ${r}`)}return await n.json()}return await p(this,T,F).call(this,"POST",`${pe}/progress/${t}/abort`)}async listExecutions(t,e){if(this.localServerUrl){const n=e?`?projectId=${encodeURIComponent(e)}`:"",r=`${this.localServerUrl}/api/${pe}/${t}/progress${n}`,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 p(this,T,F).call(this,"GET",`${pe}/${t}/progress`,{query:{...e&&{projectId:e}}})}async getExecution(t){if(this.localServerUrl){const e=`${this.localServerUrl}/api/${pe}/progress/${t}`,n=await fetch(e);if(!n.ok){const r=await n.text().catch(()=>"");throw new Error(`Local server request failed: ${n.status} - ${r}`)}return await n.json()}return await p(this,T,F).call(this,"GET",`${pe}/progress/${t}`)}async onExecutionProgress(t,e){const n=this.localServerUrl??this.wsUrl,r=await Ze(n,{auth:{accessToken:this.accessToken},transports:["websocket"]});r.on("connect",function(){r.emit("executionSubscription",JSON.stringify({executionId:t})),r.on("execution",i=>{e(i)})}),r.on("connect_error",function(i){console.log(i)})}documents(t){return new ks(this,t)}history(t){return new Cs(this,t)}get recipes(){return g(this,hn)??it(this,hn,new yi(this)),g(this,hn)}async createHiddenFile(t,e,n){const r=new FormData;return r.append("file",t),r.append("parentItemId",e),n!=null&&r.append("tag",n),await p(this,T,F).call(this,"POST",`${W}/${re}`,{body:r})}async createHiddenFilesBatch(t,e,n){const r=new FormData;for(const i of t)r.append("files",i);return r.append("parentItemId",e),n!=null&&r.append("tag",n),await p(this,T,F).call(this,"POST",`${W}/${re}/batch`,{body:r})}async deleteHiddenFile(t){return await p(this,T,F).call(this,"DELETE",`${W}/${re}/${t}`)}async getHiddenFile(t){return await p(this,T,F).call(this,"GET",`${W}/${re}/${t}`)}async downloadHiddenFile(t){return await p(this,T,ve).call(this,`${W}/${re}/${t}/download`)}async getHiddenFileSignedUrl(t,e){return await p(this,T,F).call(this,"GET",`${W}/${re}/${t}/signed-url`,{...e!=null&&{query:{expiresIn:e}}})}async getHiddenFileSignedUrlsBatch(t,e){return await p(this,T,Xe).call(this,t,async n=>(await p(this,T,F).call(this,"POST",`${W}/${re}/signed-url/batch`,{body:JSON.stringify({hiddenFileIds:n,...e!=null&&{expiresIn:e}}),contentType:"application/json"})).results)}async getHiddenFilesByParent(t,e){return await p(this,T,F).call(this,"GET",`${W}/${t}/${re}`,{...e!=null&&{query:{tag:e}}})}async deleteHiddenFilesByParent(t){return await p(this,T,F).call(this,"DELETE",`${W}/${t}/${re}`)}async uploadItemIcon(t,e){const n=new FormData;return n.append("icon",e),await p(this,T,F).call(this,"PUT",`${W}/${t}/icon`,{body:n})}async getItemIcon(t){return await p(this,T,ve).call(this,`${W}/${t}/icon`)}async removeItemIcon(t){return await p(this,T,F).call(this,"DELETE",`${W}/${t}/icon`)}async updateItem(t,e){return await p(this,T,F).call(this,"PUT",`${W}/${t}`,{body:JSON.stringify(e),contentType:"application/json"})}async createVersion(t,e,n,r,i){const o=new FormData;return o.append("file",e),o.append("versionTag",n),r&&o.append("extraProps",JSON.stringify(r)),i&&o.append("metadata",JSON.stringify(i)),await p(this,T,F).call(this,"POST",`${W}/${t}/version`,{body:o})}async nextVersionTag(t){if(!t)return"v1";let e=[];try{e=await this.listVersions(t)}catch{return`v-${Date.now()}`}let n=0;for(const r of e){const i=/^v(\d{1,6})$/.exec(String(r.tag??r.versionTag??""));i&&(n=Math.max(n,Number(i[1])))}return`v${Math.max(n,e.length)+1}`}async listVersions(t,e={}){return await p(this,T,F).call(this,"GET",`${W}/${encodeURIComponent(t)}/versions`,{query:e})}async listVersionsBatch(t,e={}){const{archived:n}=e;return await p(this,T,Xe).call(this,t,async r=>(await p(this,T,F).call(this,"POST",`${W}/batch/versions`,{body:JSON.stringify({itemIds:r,...n!==void 0&&{archived:n}}),contentType:"application/json"})).results)}async archiveVersion(t,e){return await p(this,T,F).call(this,"PUT",`${W}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/archive`)}async recoverVersion(t,e){return await p(this,T,F).call(this,"PUT",`${W}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/recover`)}async deleteVersion(t,e){return await p(this,T,F).call(this,"DELETE",`${W}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}`)}};T=new WeakSet,_n=function(t){return`${this.apiUrl}/${t}`},F=async function(t,e,n){if(t==="GET"&&(n==null?void 0:n.responseType)!=="blob"&&!(n!=null&&n.retryAttempt)){const r=`${p(this,T,_n).call(this,e)}?${new URLSearchParams(p(this,T,gs).call(this,n==null?void 0:n.query)).toString()}`,i=Date.now(),o=ze.get(r);if(o&&(o.pending||i-o.at<la))return o.answer.then(l=>l===void 0?l:structuredClone(l));const a={at:i,pending:!0,answer:p(this,T,us).call(this,t,e,n)};return ze.set(r,a),a.answer.then(()=>{a.pending=!1,a.at=Date.now()},()=>{ze.get(r)===a&&ze.delete(r)}),a.answer.then(l=>l===void 0?l:structuredClone(l))}return t!=="GET"&&ze.clear(),p(this,T,us).call(this,t,e,n)},us=async function(t,e,n){const{body:r,query:i,contentType:o,retries:a,responseType:l,retryAttempt:d}=n||{},c=p(this,T,_n).call(this,e),m=p(this,T,gs).call(this,i),w=await this.resolveAccessToken(),v={...m,...this.useBearer?{}:{accessToken:w}};try{const I=await fetch(c+"?"+new URLSearchParams(v).toString(),{method:t,headers:{Accept:"application/json",...o&&{"Content-Type":o},...this.useBearer&&{Authorization:`Bearer ${w}`}},...r&&{body:r}});if(!I.ok){const _=await I.text().then(L=>L).catch(()=>"");throw new Ln(I.status,I.statusText,_,fa(I))}return l==="blob"?await I.blob():I.json().then(_=>_).catch(()=>{})}catch(I){const _=a??this.retries;if(_>0&&ua(I)){const L=d??0;return await da(pa(I,L)),await p(this,T,F).call(this,t,e,{...n,retries:_-1,retryAttempt:L+1})}throw I}},ve=async function(t,e){const{query:n}=e||{},r=p(this,T,_n).call(this,t),i=await this.resolveAccessToken(),o={...n,...this.useBearer?{}:{accessToken:i}};return await fetch(r+"?"+new URLSearchParams(o).toString(),{method:"GET",...this.useBearer&&{headers:{Authorization:`Bearer ${i}`}}})},hn=new WeakMap,Xe=async function(t,e){if(!t.length)return[];const n=[];for(let i=0;i<t.length;i+=fs)n.push(t.slice(i,i+fs));return(await Promise.all(n.map(e))).flat()},An=async function(t,e){const{versionTag:n,withDraft:r}=e||{},i=await p(this,T,ve).call(this,`${W}/${t}/download`,{query:{...n&&{versionTag:n},...r&&{withDraft:r}}});if(i.status===429||i.status>=500)throw new Error(`Downloading ${t} answered ${i.status}${i.status===429?" (rate limited)":""}`);return i},On=async function(t,e,n){const{name:r,versionTag:i,parentFolderId:o,projectId:a,file:l,metadata:d}=t,c=new FormData;return c.append("file",l),c.append("name",r),c.append("versionTag",i),c.append("itemType",e),o&&c.append("folderId",o),a&&c.append("projectId",a),n&&c.append("extraProps",JSON.stringify(n)),d&&c.append("metadata",JSON.stringify(d)),await p(this,T,F).call(this,"POST",W,{body:c})},ps=async function(t,e,n){const{name:r,versionTag:i,parentFolderId:o,file:a,metadata:l}=e;let d,c;if(a){const m=new FormData;m.append("file",a),i&&m.append("versionTag",i),n&&m.append("extraProps",JSON.stringify(n)),l&&m.append("metadata",JSON.stringify(l)),c=await p(this,T,F).call(this,"POST",`${W}/${t}/version`,{body:m})}if(r||o){const m={...r&&{name:r},...o&&{folderId:o}},w=JSON.stringify(m);d=await p(this,T,F).call(this,"PUT",`${W}/${t}`,{body:w,contentType:"application/json"})}return{item:d,version:c}},ms=async function(t,e){const{showVersions:n=!1}=e||{};return await p(this,T,F).call(this,"GET",`${W}/${t}`,{query:{showVersions:n}})},gs=function(t){return t&&Object.entries(t).filter(([,e])=>e!==void 0).reduce((e,[n,r])=>(e[n]=r,e),{})};let Rn=Us;function vi(){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:s=>window.parent.postMessage(s,"*"),listen:s=>{const t=e=>{e.source===window.parent&&s(e.data)};return window.addEventListener("message",t),()=>window.removeEventListener("message",t)}}}const ys="channel:",ma=1e4;function Cn(s){try{s()}catch(t){console.error("[channel] a listener threw:",t)}}var ce,Dt,Ut,Fe,Le,Pe,Lt,ws,vs,Me;class js{constructor(t,e){K(this,Lt);K(this,ce,!1);K(this,Dt,[]);K(this,Ut,[]);K(this,Fe,new Set);K(this,Le,new Set);K(this,Pe,new Set);this.transport=t,this.controls=e}get joined(){return g(this,ce)}get peers(){return g(this,Dt)}join(){return g(this,ce)?Promise.resolve():p(this,Lt,ws).call(this,"joined",this.controls.join)}leave(){return!g(this,ce)&&!g(this,Ut).some(t=>t.want==="joined")?Promise.resolve():p(this,Lt,ws).call(this,"left",this.controls.leave)}onChange(t){return g(this,Fe).add(t),()=>void g(this,Fe).delete(t)}onPeerJoined(t){return g(this,Le).add(t),()=>void g(this,Le).delete(t)}onPeerLeft(t){return g(this,Pe).add(t),()=>void g(this,Pe).delete(t)}applyJoined(){it(this,ce,!0),p(this,Lt,vs).call(this,"joined"),p(this,Lt,Me).call(this)}applyLeft(){it(this,ce,!1),it(this,Dt,[]),p(this,Lt,vs).call(this,"left"),p(this,Lt,Me).call(this)}applyPeers(t){it(this,Dt,t),p(this,Lt,Me).call(this)}applyPeerJoined(t){!g(this,ce)||g(this,Dt).some(e=>e.from===t.from)||(it(this,Dt,[...g(this,Dt),t]),g(this,Le).forEach(e=>Cn(()=>e(t))),p(this,Lt,Me).call(this))}applyPeerLeft(t){const e=g(this,Dt).find(n=>n.from===t);e&&(it(this,Dt,g(this,Dt).filter(n=>n.from!==t)),g(this,Pe).forEach(n=>Cn(()=>n(e))),p(this,Lt,Me).call(this))}failPending(t){const e=g(this,Ut);return it(this,Ut,[]),e.forEach(n=>{clearTimeout(n.timer),n.reject(t)}),e.length>0}post(t){this.transport.post(t)}}ce=new WeakMap,Dt=new WeakMap,Ut=new WeakMap,Fe=new WeakMap,Le=new WeakMap,Pe=new WeakMap,Lt=new WeakSet,ws=function(t,e){return new Promise((n,r)=>{const i={want:t,resolve:n,reject:r,timer:setTimeout(()=>{it(this,Ut,g(this,Ut).filter(o=>o!==i)),r(new Error(`The platform did not confirm ${t==="joined"?"joining":"leaving"} in time.`))},ma)};g(this,Ut).push(i),this.transport.post({type:"APP_CHANNEL_CONTROL",...e})})},vs=function(t){const e=g(this,Ut).filter(n=>n.want===t);it(this,Ut,g(this,Ut).filter(n=>n.want!==t)),e.forEach(n=>{clearTimeout(n.timer),n.resolve()})},Me=function(){g(this,Fe).forEach(t=>Cn(t))};var Be;class bi extends js{constructor(e){super(e,{join:{action:"joinCollab"},leave:{action:"leaveCollab"}});K(this,Be,new Map)}on(e,n){const r=g(this,Be).get(e)??new Set;return r.add(n),g(this,Be).set(e,r),()=>void r.delete(n)}send(e,n){if(e.startsWith(ys))throw new Error(`Message types starting with '${ys}' are reserved.`);this.joined&&this.post({type:"APP_CHANNEL_PUBLISH",message:{type:e,payload:n}})}accepts(e){return e===void 0||e==="collab"}async handle(e){const n=g(this,Be).get(e.type);if(!(n!=null&&n.size))return{handled:!1};const r=Ei(e);return n.forEach(i=>Cn(()=>i(e.payload,r))),{handled:!0}}}Be=new WeakMap;var Te;class Ti extends js{constructor(e,n){super(e,{join:{action:"joinExternal",kind:n},leave:{action:"leaveExternal",kind:n}});K(this,Te,new Map);this.kind=n}on(e,n){if(g(this,Te).has(e))throw new Error(`"${e}" already has a handler in this room. Remove it first.`);return g(this,Te).set(e,n),()=>void g(this,Te).delete(e)}accepts(e,n){return e!==void 0&&e!=="external"?!1:this.kind===void 0||e===void 0||this.kind===n}get hasHandlers(){return g(this,Te).size>0}async handle(e){const n=g(this,Te).get(e.type);if(!n)return{handled:!1};try{return{handled:!0,value:await n(e.payload,Ei(e))}}catch(r){return{handled:!0,error:r instanceof Error?r.message:String(r)}}}}Te=new WeakMap;function Ei(s){return{from:s.from,at:s.at,requestId:s.requestId,kind:s.kind}}function ga(s){const t=s;if((t==null?void 0:t.type)!=="THATOPEN_CHANNEL_MESSAGE")return null;const e=t.message;return!e||typeof e.type!="string"?null:{type:e.type,requestId:typeof e.requestId=="string"?e.requestId:void 0,payload:e.payload,at:typeof e.at=="number"?e.at:Date.now(),from:typeof e.from=="string"?e.from:"",scope:e.scope==="collab"||e.scope==="external"?e.scope:void 0,kind:typeof e.kind=="string"?e.kind:void 0}}var Oe,dn,le,Ee,Ie,Ct,bs,$n,Si,_i,Ai,Ts;class Ii{constructor(t){K(this,Ct);K(this,Oe);K(this,dn);K(this,le);K(this,Ee,new Map);K(this,Ie,new Set);it(this,Oe,t),it(this,dn,t.listen(e=>void p(this,Ct,Si).call(this,e)))}collab(){return g(this,le)??it(this,le,new bi(g(this,Oe))),g(this,le)}external(t){const e=t??"";let n=g(this,Ee).get(e);return n||(n=new Ti(g(this,Oe),t),g(this,Ee).set(e,n)),n}dispose(){g(this,dn).call(this)}}Oe=new WeakMap,dn=new WeakMap,le=new WeakMap,Ee=new WeakMap,Ie=new WeakMap,Ct=new WeakSet,bs=function(){return[...g(this,le)?[g(this,le)]:[],...g(this,Ee).values()]},$n=function(t,e){if(t==="collab")return g(this,le);if(t==="external")return g(this,Ee).get(typeof e=="string"?e:"")},Si=async function(t){const e=ga(t);if(e){if(e.type.startsWith(ys)){p(this,Ct,_i).call(this,e);return}await p(this,Ct,Ai).call(this,e)}},_i=function(t){var n,r,i;const e=t.payload??{};switch(t.type){case"channel:joined":(n=p(this,Ct,$n).call(this,e.scope,e.kind))==null||n.applyJoined();break;case"channel:left":(r=p(this,Ct,$n).call(this,e.scope,e.kind))==null||r.applyLeft();break;case"channel:peers":(i=p(this,Ct,$n).call(this,e.scope,e.kind))==null||i.applyPeers(e.peers??[]);break;case"channel:peer-joined":case"channel:peer-left":{if(!e.from)break;const o=e.scope==="collab"?[g(this,le)]:[...g(this,Ee).values()].filter(a=>a.accepts("external",e.kind));for(const a of o)t.type==="channel:peer-joined"?a==null||a.applyPeerJoined({from:e.from,kind:e.kind}):a==null||a.applyPeerLeft(e.from);break}case"channel:error":{const o=new Error(String(t.payload));p(this,Ct,bs).call(this).map(l=>l.failPending(o)).some(Boolean)||console.error("[channel] error:",t.payload);break}}},Ai=async function(t){const e=p(this,Ct,bs).call(this).filter(i=>i.accepts(t.scope,t.kind));let n=!1;for(const i of e){const o=await i.handle(t);o.handled&&(n=!0,t.requestId&&p(this,Ct,Ts).call(this,t.requestId,o))}t.requestId&&t.scope==="external"&&e.length>0&&!n&&p(this,Ct,Ts).call(this,t.requestId,{handled:!0,error:`No handler for "${t.type}".`})},Ts=function(t,e){g(this,Ie).has(t)||(g(this,Ie).add(t),g(this,Ie).size>500&&g(this,Ie).delete(g(this,Ie).values().next().value),g(this,Oe).post({type:"APP_CHANNEL_PUBLISH",message:{type:e.error===void 0?"reply":"reply-error",requestId:t,payload:e.error===void 0?e.value:{error:e.error}}}))};const _e="project",xe="notifications";var je,fn;const qs=class qs extends Rn{constructor(e,n,r){super(typeof e=="string"?e:"",n,{...r,useBearer:!0});K(this,je);K(this,fn);typeof e=="function"&&it(this,je,e)}async resolveAccessToken(){return g(this,je)?await g(this,je).call(this):super.resolveAccessToken()}static fromPlatformContext(e){const n=(typeof window<"u"?window.__THATOPEN_CONTEXT__:null)||{appId:"",projectId:"",accessToken:"",apiUrl:""},r=new qs(n.accessToken,n.apiUrl,e);return r.context=n,r}get channel(){return g(this,fn)??it(this,fn,new Ii(vi())),g(this,fn)}async listProjects(){return await this.request("GET",_e)}async getProject(e){return await this.request("GET",`${_e}/${e}`)}async getProjectData(e){return await this.request("GET",`${_e}/${e}/data`)}async getAvatar(e){return await this.request("GET",`account/${e}/avatar`,{responseType:"blob"})}async checkPermission(e){return await this.request("GET",`${_e}/permissions/check`,{query:e})}async checkPermissionBatch(e){return(await this.request("POST",`${_e}/permissions/check/batch`,{body:JSON.stringify({checks:e}),contentType:"application/json"})).results}async getNotifications(e){return await this.request("GET",xe,{query:{...(e==null?void 0:e.cursor)!==void 0&&{cursor:e.cursor},...(e==null?void 0:e.limit)!==void 0&&{limit:String(e.limit)}}})}async getUnreadNotificationCount(){return(await this.request("GET",`${xe}/unread-count`)).count}async markNotificationsRead(e){return await this.request("POST",`${xe}/mark-read`,{body:JSON.stringify({ids:e}),contentType:"application/json"})}async markAllNotificationsRead(){return await this.request("POST",`${xe}/mark-all-read`)}async getNotificationSubscriptions(){return await this.request("GET",`${xe}/subscriptions`)}async unsubscribeFromAutomation(e){return await this.request("DELETE",`${xe}/subscriptions/${e}`)}async subscribeToAutomation(e,n,r){return await this.request("POST",`${_e}/${e}/events/hooks/${n}/subscription`,{body:JSON.stringify(r??{}),contentType:"application/json"})}async updateAutomationSubscription(e,n,r){return await this.request("PATCH",`${_e}/${e}/events/hooks/${n}/subscription`,{body:JSON.stringify(r),contentType:"application/json"})}async onNotification(e){const n=await this.resolveAccessToken(),r=Ze(`${this.socketOrigin}/notifications`,{auth:{accessToken:n},transports:["websocket"]});return r.on("notification.created",i=>e({type:"created",id:i==null?void 0:i.id})),r.on("notification.read",i=>e({type:"read",id:i==null?void 0:i.id})),r.on("notifications.allRead",i=>e({type:"allRead",batch:i==null?void 0:i.batch})),()=>r.disconnect()}};je=new WeakMap,fn=new WeakMap;let Es=qs;const me=1/.3048,ya={IFCDOOR:"OST_Doors",IFCWINDOW:"OST_Windows",IFCFURNITURE:"OST_Furniture",IFCFURNISHINGELEMENT:"OST_Furniture",IFCSYSTEMFURNITUREELEMENT:"OST_FurnitureSystems",IFCLIGHTFIXTURE:"OST_LightingFixtures",IFCSANITARYTERMINAL:"OST_PlumbingFixtures",IFCFLOWTERMINAL:"OST_PlumbingFixtures",IFCCOLUMN:"OST_Columns",IFCFOOTING:"OST_StructuralFoundation",IFCGEOGRAPHICELEMENT:"OST_Site",IFCELECTRICAPPLIANCE:"OST_ElectricalEquipment",IFCELECTRICDISTRIBUTIONBOARD:"OST_ElectricalEquipment",IFCUNITARYEQUIPMENT:"OST_MechanicalEquipment"},wa="OST_GenericModel",va=new Set(["IFCSPACE","IFCOPENINGELEMENT","IFCSITE","IFCANNOTATION","IFCGRID","IFCVIRTUALELEMENT","IFCBUILDING","IFCBUILDINGSTOREY"]),be=(s,t)=>Math.round(s/t)*t,ba=s=>({x:[s[0],s[1],s[2]],y:[s[4],s[5],s[6]],z:[s[8],s[9],s[10]],t:[s[12],s[13],s[14]]}),tn=(s,t)=>s[0]*t[0]+s[1]*t[1]+s[2]*t[2],zn=s=>Math.sqrt(tn(s,s)),xn=(s,t)=>[s[1]*t[2]-s[2]*t[1],s[2]*t[0]-s[0]*t[2],s[0]*t[1]-s[1]*t[0]];function Ta(s,t,e){const n=new Set,r=new Map;for(const l of t){const d=l.split(":")[1];d&&(n.add(d),r.has(d)||r.set(d,l))}const i=new Map,o=new Map,a=[];for(const l of s.elements.values()){if(n.has(l.gid)||va.has(l.ifcClass.toUpperCase())||l.parent&&n.has(l.parent)&&!/^IFC(DOOR|WINDOW)$/i.test(l.ifcClass)||l.pieces.length===0)continue;const c=/^IFCCOLUMN$/i.test(l.ifcClass)&&/structural|estructural|结构柱|tragend|tragwerk/i.test(`${l.typeName??""} ${l.objectType??""} ${l.name??""}`)?"OST_StructuralColumns":ya[l.ifcClass.toUpperCase()]??wa,m=ba(l.pieces[0].matrix),w=zn(m.x),v=zn(m.y),I=zn(m.z),_=m.z.map(q=>q/(I||1)),L=Math.abs(_[2]-1)<1e-6&&tn(xn(m.x,m.y),m.z)>0&&Math.abs(w-v)<1e-6&&Math.abs(w-I)<1e-6,C=tn(xn(m.x,m.y),m.z)>0&&Math.abs(w-v)<1e-6&&Math.abs(w-I)<1e-6,O=[m.x,m.y,m.z].map(q=>q.map(Z=>Z/(w||1))),u=C&&!L&&O.some(q=>Math.abs(Math.abs(q[2])-1)<1e-6)?O.find(q=>Math.abs(q[2])<1e-6):void 0,$=L?Math.atan2(m.x[1],m.x[0]):u?Math.atan2(u[1],u[0]):0,E=Math.cos(-$),N=Math.sin(-$),z=[m.t[0],m.t[1],m.t[2]],ut=/COLUMN/i.test(c),wt=q=>{const Z=q[0]-z[0],x=q[1]-z[1];return[E*Z-N*x,N*Z+E*x,q[2]-z[2]]},Ot=[],Vt=[c];for(const q of l.pieces){const Z=s.geometries.get(q.geometry);if(!Z)continue;const x=q.matrix,Tt=[];for(let st=0;st<Z.verts.length;st+=3){const rt=Z.verts[st],et=Z.verts[st+1],At=Z.verts[st+2],Ht=[x[0]*rt+x[4]*et+x[8]*At+x[12],x[1]*rt+x[5]*et+x[9]*At+x[13],x[2]*rt+x[6]*et+x[10]*At+x[14]],de=wt(Ht);Tt.push(be(de[0]*me,1e-5),be(de[1]*me,1e-5),be(de[2]*me,1e-5))}const Et=tn(xn([x[0],x[1],x[2]],[x[4],x[5],x[6]]),[x[8],x[9],x[10]])<0,pt=[];for(let st=0;st+2<Z.tris.length;st+=3)Et?pt.push(Z.tris[st],Z.tris[st+2],Z.tris[st+1]):pt.push(Z.tris[st],Z.tris[st+1],Z.tris[st+2]);pt.length&&Ot.push({v:Tt,t:pt});const jt=wt([x[12],x[13],x[14]]),Ft=[E*x[0]-N*x[1],N*x[0]+E*x[1],x[2]],Pt=[E*x[4]-N*x[5],N*x[4]+E*x[5],x[6]];Vt.push(`${q.geometry}@${[...jt,...Ft,...Pt].map(st=>be(st,1e-4).toFixed(4)).join(",")}`)}if(Ot.length===0)continue;const Mt=!l.host&&Ot.length===1?Sa(Ot[0]):null;if(Mt){const q=Ia(Mt),Z=q.key,x=`prism|${c}|${q.axis}|${Z}`;let Tt=i.get(x);if(!Tt){const et=Rr(l.typeName??l.objectType??l.name??l.ifcClass),At=(o.get(et)??0)+1;o.set(et,At);const Ht=At===1?et:`${et} (${At})`;Tt={family:Ht,type:Ht,first:!0,key:kr(x)},i.set(x,Tt)}const Et={ShapeCategory:c,Family:Tt.family,Type:Tt.type,ShapeKey:Tt.key,PrismLength:String(be(Mt.length,1e-5)),...ut?{ColumnFree:"1"}:{}};Tt.first&&(Et.Prism=JSON.stringify({axis:q.axis,loops:q.loops}),Tt.first=!1);const pt=[0,0,0];pt[Mt.axis]=(q.flipped?Mt.from+Mt.length:Mt.from)/me;const jt=(Mt.axis+1)%3,Ft=(Mt.axis+2)%3;pt[jt]+=q.centre[0]/me,pt[Ft]+=q.centre[1]/me;const Pt=Math.cos($),st=Math.sin($),rt=[z[0]+Pt*pt[0]-st*pt[1],z[1]+st*pt[0]+Pt*pt[1],z[2]+pt[2]];a.push({key:`${e}:${l.gid}:shape`,attrs:Et,at:rt,rotationDeg:($+q.turn)*180/Math.PI});continue}const he=`${c}|${Ot.map(q=>`${q.v.map(Z=>Math.round(Z*304.8/2)).join(",")}/${q.t.join(",")}`).join("|")}`,Yt=Vt.join("|");let It=i.get(Yt)??i.get(he);if(It&&(i.set(Yt,It),i.set(he,It)),!It){const q=Rr(l.typeName??l.objectType??l.name??l.ifcClass),Z=(o.get(q)??0)+1;o.set(q,Z);const x=Z===1?q:`${q} (${Z})`;It={family:x,type:x,first:!0,key:kr(he)},i.set(he,It),i.set(Yt,It)}const Gt={ShapeCategory:c,Family:It.family,Type:It.type,ShapeKey:It.key,...ut?{ColumnFree:"1"}:{}};It.first&&(Gt.Shape=JSON.stringify({pieces:Ot}),It.first=!1);const Nt=l.host?r.get(l.host):void 0,Ce=l.opening?s.elements.get(l.opening):void 0;if(Nt&&Ce){const q=[1/0,1/0,1/0],Z=[-1/0,-1/0,-1/0];for(const x of Ce.pieces){const Tt=s.geometries.get(x.geometry);if(!Tt)continue;const Et=x.matrix;for(let pt=0;pt<Tt.verts.length;pt+=3){const jt=Tt.verts[pt],Ft=Tt.verts[pt+1],Pt=Tt.verts[pt+2],st=wt([Et[0]*jt+Et[4]*Ft+Et[8]*Pt+Et[12],Et[1]*jt+Et[5]*Ft+Et[9]*Pt+Et[13],Et[2]*jt+Et[6]*Ft+Et[10]*Pt+Et[14]]);for(let rt=0;rt<3;rt++)q[rt]=Math.min(q[rt],st[rt]*me),Z[rt]=Math.max(Z[rt],st[rt]*me)}}Number.isFinite(q[0])&&(Gt.Opening=[...q,...Z].map(x=>be(x,1e-5)).join(","))}a.push({key:`${e}:${l.gid}:shape`,attrs:Gt,at:[z[0],z[1],z[2]],rotationDeg:$*180/Math.PI,...Nt?{host:Nt}:{}})}return a}function Rr(s){return(s.replace(/[\\:{}[\]|;<>?`~]/g,"-").replace(/\s+/g," ").trim()||"Shape").slice(0,120)}function kr(s){let t=2166136261;for(let e=0;e<s.length;e++)t^=s.charCodeAt(e),t=Math.imul(t,16777619);return(t>>>0).toString(36)}function Ea(s,t,e){const n=new Map;for(const i of t){const[,o,a]=i.split(":");o&&/^run/.test(a??"")&&!n.has(o)&&n.set(o,i)}const r=[];for(const i of s.elements.values()){if(i.ifcClass.toUpperCase()!=="IFCOPENINGELEMENT"||!i.host)continue;const o=n.get(i.host);if(o)for(const a of Oa(s,i.gid)){const l=a.pts;if(l.length<4)continue;const d=Aa(nn(s,i.host));if(!d)continue;const c=l.map(I=>(I[0]-d.a[0])*d.u[0]+(I[1]-d.a[1])*d.u[1]),m=l.map(I=>-(I[0]-d.a[0])*d.u[1]+(I[1]-d.a[1])*d.u[0]),w=I=>Math.max(...I)-Math.min(...I),v=w(c)*w(m)*w(l.map(I=>I[2]));!(v>0)||Math.abs(a.volume)<.75*v||r.push({key:`${e}:${i.gid}:opening${a.index===0&&a.of===1?"":`#${a.index}`}`,host:o,box:l.flat()})}}return r}function Ia(s){const t=s.loops.flat(),e=[t.reduce((w,v)=>w+v[0],0)/t.length,t.reduce((w,v)=>w+v[1],0)/t.length],n=s.loops.map(w=>{const v=w.map(([O,u])=>[O-e[0],u-e[1]]),I=v.map(([O,u])=>Math.hypot(O,u)),_=I.reduce((O,u)=>O+u,0)/I.length;if(v.length<8||_<=0||I.some(O=>Math.abs(O-_)>.02*_))return v;const C=v.reduce((O,u,$)=>{const E=v[($+1)%v.length];return O+u[0]*E[1]-E[0]*u[1]},0)>=0?1:-1;return v.map((O,u)=>[_*Math.cos(C*2*Math.PI*u/v.length),_*Math.sin(C*2*Math.PI*u/v.length)])}),r=w=>w.map(I=>{const _=I.map(([C,O])=>`${Math.round(C*304.8)},${Math.round(O*304.8)}`);let L=0;for(let C=1;C<_.length;C++)_[C]<_[L]&&(L=C);return[..._.slice(L),..._.slice(0,L)].join(";")}).sort().join("|"),i=(w,v)=>{const I=Math.cos(-v),_=Math.sin(-v);return w.map(L=>L.map(([C,O])=>[I*C-_*O,_*C+I*O]))},o=[];let a=s.axis,l=0,d=n;if(a===1&&(a=0,l=Math.PI/2,d=n.map(w=>w.map(([v,I])=>[-I,v]))),a===2){let w=0,v=0,I=0;const _=n.flat();for(const[E,N]of _)w+=E*E,v+=N*N,I+=E*N;const L=new Set,C=.5*Math.atan2(2*I,w-v);for(let E=0;E<4;E++)L.add(C+E*Math.PI/2);const O=_.map(([E,N])=>Math.hypot(E,N)),u=Math.max(...O),$=_.filter((E,N)=>O[N]>u-.003);if(Math.abs(w-v)<.001*(w+v)||$.length>4)for(const[E,N]of $.slice(0,64))L.add(Math.atan2(N,E));for(const E of L)o.push({loops:i(n,E),turn:E,flipped:!1})}else o.push({loops:d,turn:0,flipped:!1}),o.push({loops:d.map(w=>w.map(([v,I])=>[-v,I]).reverse()),turn:Math.PI,flipped:!0});let c=o[0],m=r(c.loops);for(const w of o.slice(1)){const v=r(w.loops);v<m&&(c=w,m=v)}return{axis:a,loops:c.loops,key:m,centre:e,turn:l+c.turn,flipped:c.flipped}}function Sa(s){const e=s.v.length/3;if(e<6)return null;const n=[0,1,2].map(r=>{let i=1/0,o=-1/0;for(let a=0;a<e;a++){const l=s.v[a*3+r];i=Math.min(i,l),o=Math.max(o,l)}return o-i});for(const r of[0,1,2].sort((i,o)=>n[o]-n[i])){let i=1/0,o=-1/0;for(let u=0;u<e;u++){const $=s.v[u*3+r];i=Math.min(i,$),o=Math.max(o,$)}if(o-i<.01)continue;let a=!0;for(let u=0;u<e&&a;u++){const $=s.v[u*3+r];Math.abs($-i)>.001&&Math.abs($-o)>.001&&(a=!1)}if(!a)continue;const l=(r+1)%3,d=(r+2)%3,c=new Map,m=[],w=u=>{const $=[s.v[u*3+l],s.v[u*3+d]],E=`${Math.round($[0]*3048)},${Math.round($[1]*3048)}`;return c.has(E)||(c.set(E,m.length),m.push($)),c.get(E)},v=new Map,I=[];for(let u=0;u+2<s.t.length;u+=3){const $=[s.t[u],s.t[u+1],s.t[u+2]];if(!$.every(N=>Math.abs(s.v[N*3+r]-i)<=.001))continue;const E=$.map(w);if(!(E[0]===E[1]||E[1]===E[2]||E[0]===E[2])){I.push(E);for(let N=0;N<3;N++){const z=E[N],ut=E[(N+1)%3],wt=z<ut?`${z},${ut}`:`${ut},${z}`;v.set(wt,(v.get(wt)??0)+1)}}}if(I.length===0)continue;const _=new Map;for(const u of I)for(let $=0;$<3;$++){const E=u[$],N=u[($+1)%3];v.get(E<N?`${E},${N}`:`${N},${E}`)===1&&_.set(E,[..._.get(E)??[],N])}if([..._.values()].some(u=>u.length!==1))continue;const L=[],C=new Set(_.keys());for(;C.size;){const u=C.values().next().value,$=[];let E=u,N=0;do $.push(m[E]),C.delete(E),E=_.get(E)[0];while(E!==u&&N++<1e5&&_.has(E));if(E!==u||$.length<3){L.length=0;break}const z=$.filter((ut,wt)=>{const Ot=$[(wt-1+$.length)%$.length],Vt=$[(wt+1)%$.length];return Math.abs((ut[0]-Ot[0])*(Vt[1]-Ot[1])-(ut[1]-Ot[1])*(Vt[0]-Ot[0]))>1e-7});L.push(z.map(([ut,wt])=>[be(ut,1e-5),be(wt,1e-5)]))}if(L.length===0||L.some(u=>u.length<3))continue;let O=0;for(let u=0;u<e;u++)Math.abs(s.v[u*3+r]-o)<=.001&&O++;if(!(O<3))return{axis:r,from:i,length:o-i,loops:L}}return null}function _a(s,t){const e=[];for(const n of s.elements.values()){if(n.ifcClass.toUpperCase()!=="IFCSPACE")continue;let r=1/0,i=-1/0;const o=[];for(const d of n.pieces){const c=s.geometries.get(d.geometry);if(!c)continue;const m=d.matrix,w=v=>{const I=c.verts[v*3],_=c.verts[v*3+1],L=c.verts[v*3+2];return[m[0]*I+m[4]*_+m[8]*L+m[12],m[1]*I+m[5]*_+m[9]*L+m[13],m[2]*I+m[6]*_+m[10]*L+m[14]]};for(let v=0;v+2<c.tris.length;v+=3){const I=[w(c.tris[v]),w(c.tris[v+1]),w(c.tris[v+2])];for(const _ of I)r=Math.min(r,_[2]),i=Math.max(i,_[2]);o.push(I)}}if(!Number.isFinite(r)||i-r<.1)continue;let a=null,l=0;for(const d of o){if(!d.every(m=>Math.abs(m[2]-r)<.001))continue;const c=Math.abs((d[1][0]-d[0][0])*(d[2][1]-d[0][1])-(d[2][0]-d[0][0])*(d[1][1]-d[0][1]))/2;c>l&&(l=c,a=d)}a&&e.push({key:`${t}:${n.gid}:room`,at:[(a[0][0]+a[1][0]+a[2][0])/3,(a[0][1]+a[1][1]+a[2][1])/3,r],height:i-r,number:n.name??"",name:n.longName??n.name??""})}return e}function Aa(s){if(s.length<2)return;let t=s[0],e=s[0],n=0;for(const r of s){const i=Math.hypot(r[0]-s[0][0],r[1]-s[0][1]);i>n&&(n=i,e=r)}n=0;for(const r of s){const i=Math.hypot(r[0]-e[0],r[1]-e[1]);i>n&&(n=i,t=r)}if(!(n<.1))return{a:t,u:[(e[0]-t[0])/n,(e[1]-t[1])/n]}}function Oa(s,t){const e=s.elements.get(t);if(!e)return[];const n=[],r=[],i=new Map;for(const c of e.pieces){const m=s.geometries.get(c.geometry);if(!m)continue;const w=c.matrix,v=[];for(let I=0;I<m.verts.length;I+=3){const _=m.verts[I],L=m.verts[I+1],C=m.verts[I+2],O=[w[0]*_+w[4]*L+w[8]*C+w[12],w[1]*_+w[5]*L+w[9]*C+w[13],w[2]*_+w[6]*L+w[10]*C+w[14]],u=O.map(E=>Math.round(E*1e4)).join(",");let $=i.get(u);$===void 0&&($=n.length,i.set(u,$),n.push(O)),v.push($)}for(let I=0;I+2<m.tris.length;I+=3)r.push(v[m.tris[I]],v[m.tris[I+1]],v[m.tris[I+2]])}const o=n.map((c,m)=>m),a=c=>{for(;o[c]!==c;)o[c]=o[o[c]],c=o[c];return c};for(let c=0;c<r.length;c+=3){const m=a(r[c]);o[a(r[c+1])]=m,o[a(r[c+2])]=m}const l=new Map;for(let c=0;c<r.length;c+=3){const m=a(r[c]);let w=l.get(m);w||(w={pts:new Set,volume:0},l.set(m,w));const[v,I,_]=[n[r[c]],n[r[c+1]],n[r[c+2]]];w.volume+=tn(v,xn(I,_))/6,w.pts.add(r[c]),w.pts.add(r[c+1]),w.pts.add(r[c+2])}const d=[...l.values()];return d.map((c,m)=>({pts:[...c.pts].map(w=>n[w]),volume:c.volume,index:m,of:d.length}))}function nn(s,t,e){const n=s.elements.get(t),r=[];if(!n)return r;for(const i of n.pieces){const o=s.geometries.get(i.geometry);if(!o)continue;const a=i.matrix;for(let l=0;l<o.verts.length;l+=3){const d=o.verts[l],c=o.verts[l+1],m=o.verts[l+2];r.push([a[0]*d+a[4]*c+a[8]*m+a[12],a[1]*d+a[5]*c+a[9]*m+a[13],a[2]*d+a[6]*c+a[10]*m+a[14]])}}return r}function Ca(s,t,e){const n=nn(s,t);if(n.length<4||e.length===0)return;let r=n[0],i=n[0],o=0;for(const C of n){const O=Math.hypot(C[0]-n[0][0],C[1]-n[0][1]);O>o&&(o=O,i=C)}o=0;for(const C of n){const O=Math.hypot(C[0]-i[0],C[1]-i[1]);O>o&&(o=O,r=C)}if(o<.3)return;const a=(i[0]-r[0])/o,l=(i[1]-r[1])/o,d=C=>(C[0]-r[0])*a+(C[1]-r[1])*l,c=Math.max(...n.map(C=>C[2])),m=C=>Math.max(...n.filter(O=>Math.abs(d(O)-C)<.05).map(O=>O[2]),-1/0),w=m(0),v=m(o);if(Math.abs(w-v)<.05&&c-Math.max(w,v)<.05)return;const I=(r[0]+i[0])/2,_=(r[1]+i[1])/2;let L;for(const C of e){const O=nn(s,C.gid);if(O.length===0)continue;const u=O.map(z=>z[0]),$=O.map(z=>z[1]),E=O.map(z=>z[2]);if(I<Math.min(...u)-.2||I>Math.max(...u)+.2||_<Math.min(...$)-.2||_>Math.max(...$)+.2)continue;const N=Math.min(...E)-c;N>1.5||Math.max(...E)<c-.05||(!L||Math.abs(N)<Math.abs(L.gap))&&(L={id:C.id,gap:N})}return L==null?void 0:L.id}const ge={levels:"-2000240",walls:"-2000011",floors:"-2000032",roofs:"-2000035",ceilings:"-2000038",structuralFoundations:"-2001300",stairs:"-2000120"};function Qe(s){const t=s.item.attrs.Name;if(typeof t!="string")return null;const e=t.indexOf(":"),n=t.lastIndexOf(":");if(e<=0||n<=e)return null;const r=t.slice(e+1,n).trim();return r?{family:t.slice(0,e).trim(),type:r}:null}function Mr(s){const t=Qe(s),e=s.item.attrs.PredefinedType;return t?/escalera|stair|landing|descansillo/i.test(t.family)||e==="LANDING"||/plataforma|^pad\b|building pad/i.test(t.family)?"other":/cubierta|roof/i.test(t.family)||e==="ROOF"?"roof":/cimentaci|foundation/i.test(t.family)||e==="BASESLAB"?"foundation":"floor":"floor"}const Nr=180/Math.PI;function Fr(s){if(typeof s!="string")return null;const t=s.indexOf(":");return t<=0||t===s.length-1?null:{family:s.slice(0,t),type:s.slice(t+1)}}const ft=s=>String(s);function Oi(s){return async t=>{var Gs,Hs,Js,Ws,zs,Ys,Ks,Xs,Qs,Zs,tr,er,nr,sr,rr,ir,or,ar,cr,lr,hr;const{picked:e,contents:n,site:r,shapes:i}=await Ls(t,t.input),o=li(n.items),a=/CoordinateBase:\s*(Coordenadas compartidas|Shared Coordinates|Shared)/i.test(JSON.stringify(n.metadata??{})),l=a&&r?[r.east*Ne,r.north*Ne,r.elevation*Ne,r.angleDeg].map(h=>h.toFixed(6)).join(","):void 0;if(o.length===0)throw new Error(s==="ifc"?`Nothing in "${e.name}" could be read as a building element (walls, floors, levels...).`:`"${e.name}" carries no platform records, so there is nothing semantic to convert.`);const{columnType:d,trustStyleNames:c,includeInstances:m}=t.settings,w=t.settings.createLevels!==!1;if(m&&!c)throw new Error("Free-standing instances can only be made by their style names: turn trustStyleNames on.");const v=Ns(o),I=hi(o),_=`recipe:${s}-to-revit`,L=new Map,C=Fs(t,L);t.progress("Writing the changes for Revit");const O=new Nn({project:t.projectId,document:t.target.docId??"",baseCommit:t.target.version??0,author:_}),u=Ne,$=new Map;{const h=new Map;for(const f of o){const y=f.item.guid;if(!y)continue;const b=`${y}:${f.kind}`,R=h.get(b)??0;h.set(b,R+1),$.set(f.id,`${e.fileId}:${b}${R?`:${R}`:""}`)}}const E=h=>$.get(h)??`${e.fileId}:${h}`,N=new Set;let z=0,ut=0;const wt=(h,f,y)=>{N.add(h);const b=a?{...f,Frame:"shared",...l?{SharedAt:l}:{}}:f,R=di({attrs:b,placement:y??{}}),S=C.get(h);if(S){const k=L.get(h);return!k||k===R?(z++,!1):(O.remove(S),O.add({...b,"flow:print":R},{...y,source:h}),ut++,!1)}return O.add({...b,"flow:print":R},{...y,source:h}),!0},Ot=h=>{const f=typeof h=="string"?I.get(h):void 0,y=f==null?void 0:f.params.thickness;return typeof y=="number"&&y>0?y*u:void 0},Vt=h=>{var D,at;const f=Bt(h,"extrusion"),y=v.get(String((f==null?void 0:f.level)??h.params.level??"")),b=f==null?void 0:f.slopes,R=((at=(D=f==null?void 0:f.profile)==null?void 0:D.outline)==null?void 0:at.curves)??[],S=Array.isArray(b)?b.map(H=>typeof H=="number"):[],k=S.indexOf(!0);if(h.params.of!=="roof"||!y||R.length!==4||S.filter(Boolean).length!==2||k<0||k>1||!S[k+2])return null;const[A,j]=[R[k],R[k+2]],nt=A.from,ht=A.to,Y=Math.hypot(ht[0]-nt[0],ht[1]-nt[1]),St=[(ht[0]-nt[0])/Y,(ht[1]-nt[1])/Y];let U=[-St[1],St[0]];const ot=(j.from[0]-nt[0])*U[0]+(j.from[1]-nt[1])*U[1];ot<0&&(U=[-U[0],-U[1]]);const yt=Math.abs(ot),[P,G]=[b[k],b[k+2]],lt=y.at+(typeof h.params.base=="number"?h.params.base:0),$t=(f==null?void 0:f.eaves)??[],[tt,vt]=[lt+(Number($t[k])||0),lt+(Number($t[k+2])||0)],mt=(vt-tt+G*yt)/(P+G);return{A:nt,u:St,n:U,L:Y,W:yt,si:P,sj:G,ridge:mt,top:lt,ti:tt,tj:vt,zAt:(H,B)=>{const V=(H-nt[0])*U[0]+(B-nt[1])*U[1];return Math.min(tt+P*V,vt+G*(yt-V))}}},Mt=new Map(o.filter(h=>h.kind==="extrusion"&&h.params.of==="roof").map(h=>[h.id,h])),he=[...Mt.values()].filter(h=>h.item.guid).map(h=>({id:h.id,gid:h.item.guid}));let Yt=0;if(w)for(const[h,f]of v)wt(E(h),{CategoryId:ge.levels,Name:f.name,Elevation:ft(f.at*u)})&&Yt++;let It=0,Gt=0;const Nt=[];for(const h of o){if(h.kind!=="run"||h.params.of!=="wall")continue;const f=Bt(h,"run"),y=((Hs=(Gs=f==null?void 0:f.run)==null?void 0:Gs.line)==null?void 0:Hs.curves)??[],b=h.params.lookRef,R=v.get(String((f==null?void 0:f.level)??h.params.level??""));if(typeof b!="string"||typeof(f==null?void 0:f.height)!="number"||!R){Gt++;continue}const S=(Ot(b)??0)/u,k=y.filter(A=>A.kind==="segment"&&A.from&&A.to);Gt+=y.length-k.length,k.forEach((A,j)=>Nt.push({record:h,i:j,width:S,from:[...A.from],to:[...A.to],joinStart:j===0&&String(h.params.meetsAtStart)==="true",joinEnd:j===k.length-1&&String(h.params.meetsAtEnd)==="true"}))}const Ce=(h,f)=>{const y=[h.to[0]-h.from[0],h.to[1]-h.from[1]],b=[f.to[0]-f.from[0],f.to[1]-f.from[1]],R=y[0]*b[1]-y[1]*b[0];if(Math.abs(R)<1e-9*Math.hypot(...y)*Math.hypot(...b)*1e3)return null;const S=((f.from[0]-h.from[0])*b[1]-(f.from[1]-h.from[1])*b[0])/R;return[h.from[0]+S*y[0],h.from[1]+S*y[1]]},q=(h,f)=>{const y=f.to[0]-f.from[0],b=f.to[1]-f.from[1],R=y*y+b*b||1,S=Math.max(0,Math.min(1,((h[0]-f.from[0])*y+(h[1]-f.from[1])*b)/R));return Math.hypot(h[0]-(f.from[0]+S*y),h[1]-(f.from[1]+S*b))},Z=(h,f)=>{const y=Bt(h.record,"run"),b=Bt(f.record,"run"),R=[y.base,y.base+y.height],S=[b.base,b.base+b.height],k=v.get(String((y==null?void 0:y.level)??h.record.params.level)).at,A=v.get(String((b==null?void 0:b.level)??f.record.params.level)).at;return Math.min(k+R[1],A+S[1])>Math.max(k+R[0],A+S[0])},x=1,Tt=new Map;for(const h of Nt){const f=[["from",h.joinStart],["to",h.joinEnd]],y={from:h.from,to:h.to};for(const[b,R]of f){if(!R)continue;const S=h[b];let k=null,A=1/0;for(const ht of Nt){if(ht===h||!Z(h,ht))continue;const Y=q(S,ht);Y<A&&(A=Y,k=ht)}if(!k||A>x)continue;const j=Ce(h,k);if(!j)continue;const nt=Math.min(x,2*Math.max(h.width,k.width)+.02);Math.hypot(j[0]-S[0],j[1]-S[1])>nt||q(j,k)>k.width+.01||(y[b]=j)}Tt.set(h,y)}for(const h of Nt){const{record:f}=h,y=Bt(f,"run"),b=typeof y.base=="number"?y.base:0,R=y.height,S=v.get(String(y.level??f.params.level??"")),k=f.params.lookRef;let{from:A,to:j}=Tt.get(h);const nt=new Set;if(i&&f.item.guid&&Nt.filter(D=>D.record===f).length===1?i.elements.get(f.item.guid):void 0){const D=nn(i,f.item.guid),at=Math.hypot(j[0]-A[0],j[1]-A[1]);if(D.length>=4&&at>.05){const H=[(j[0]-A[0])/at,(j[1]-A[1])/at],B=D.map(bt=>(bt[0]-A[0])*H[0]+(bt[1]-A[1])*H[1]),V=Math.min(...B),ct=Math.max(...B),dt=D.map(bt=>-(bt[0]-A[0])*H[1]+(bt[1]-A[1])*H[0]),xt=Math.max(...dt)-Math.min(...dt),Q=bt=>{const Jt=dt.filter((fe,ue)=>Math.abs(B[ue]-bt)<.002);return Jt.length>=2&&Math.max(...Jt)-Math.min(...Jt)>.9*xt},J=A;Q(V)&&(A=[J[0]+H[0]*V,J[1]+H[1]*V],nt.add("start")),Q(ct)&&(j=[J[0]+H[0]*ct,J[1]+H[1]*ct],nt.add("end"))}}const Y=(S.at+b)*u,St=`${ft(A[0]*u)},${ft(A[1]*u)},${ft(Y)};${ft(j[0]*u)},${ft(j[1]*u)},${ft(Y)}`,U={CategoryId:ge.walls,Type:((Js=Qe(f))==null?void 0:Js.type)??k,LocationLine:St,Level:S.name,BaseOffset:ft(b*u),Height:ft(R*u)},ot=[A!==h.from||h.joinStart?"start":"",j!==h.to||h.joinEnd?"end":""].filter(D=>!!D&&!nt.has(D));ot.length&&(U.JoinEnds=ot.join(","));const yt=ot.filter(D=>f.params[D==="start"?"wantedAtStart":"wantedAtEnd"]==="mitre");yt.length&&(U.Mitre=yt.join(","));const P=v.get(String(f.params.topLevel??""));P&&(U.TopLevel=P.name,U.TopOffset=ft((S.at+b+R-P.at)*u));const G=y.profile;if(Array.isArray(G)&&G.length>=3&&h.i===0&&!Nt.some(D=>D!==h&&D.record===f)){const D=Math.hypot(h.to[0]-h.from[0],h.to[1]-h.from[1]),at=[(h.to[0]-h.from[0])/D,(h.to[1]-h.from[1])/D],H=[],B=-((A[0]-h.from[0])*at[0]+(A[1]-h.from[1])*at[1]),V=(j[0]-h.to[0])*at[0]+(j[1]-h.to[1])*at[1];G.forEach(([ct,dt],xt)=>{const Q=Math.abs(ct)<1e-6,J=Math.abs(ct-D)<1e-6;let bt=ct,Jt=dt;if(Q||J){bt=Q?-B:D+V;const ue=[G[(xt-1+G.length)%G.length],G[(xt+1)%G.length]].find(([Ve])=>Math.abs(Ve-ct)>1e-6);ue&&(Jt=dt+(ue[1]-dt)/(ue[0]-ct)*(bt-ct))}const fe=[h.from[0]+bt*at[0],h.from[1]+bt*at[1]];H.push(fe[0]*u,fe[1]*u,(S.at+b+Jt)*u)}),U.Profile=JSON.stringify([H]),delete U.TopLevel,delete U.TopOffset}const lt=f.params.topAttachedTo,$t=f.params.topAttachedAt==="top"||y.topAttachedAt==="top",tt=typeof lt=="string"&&$t&&!U.Profile&&Mt.has(lt)?Vt(Mt.get(lt)):null;if(tt){const D=Math.hypot(j[0]-A[0],j[1]-A[1]),at=Q=>[A[0]+(j[0]-A[0])*Q/D,A[1]+(j[1]-A[1])*Q/D],H=(A[0]-tt.A[0])*tt.n[0]+(A[1]-tt.A[1])*tt.n[1],B=(j[0]-tt.A[0])*tt.n[0]+(j[1]-tt.A[1])*tt.n[1],V=[0,D];(H-tt.ridge)*(B-tt.ridge)<0&&V.splice(1,0,(tt.ridge-H)/(B-H)*D);const ct=S.at+b,dt=[],xt=(Q,J)=>{const bt=at(Q);dt.push(bt[0]*u,bt[1]*u,J*u)};xt(0,ct),xt(D,ct);for(const Q of[...V].reverse()){const J=at(Q);xt(Q,tt.zAt(J[0],J[1]))}U.Profile=JSON.stringify([dt]),delete U.TopLevel,delete U.TopOffset}const vt=typeof lt=="string"?lt:i&&f.item.guid?Ca(i,f.item.guid,he):void 0;vt&&!U.Profile&&(U.AttachTop=E(vt));const mt=Ot(k);mt&&(U["Type.Width"]=ft(mt));const gt=f.item.guid?i==null?void 0:i.elements.get(f.item.guid):void 0;gt!=null&&gt.layers&&gt.layers.length>1&&(U["Type.Layers"]=JSON.stringify([...gt.layers].reverse().map(D=>[+ft(D.thickness*u),D.material??"",D.function??""])),gt.layersFlipped&&(U.FlipLayers="1")),wt(`${E(f.id)}#${h.i}`,U)&&It++}const Et=(h,f,y)=>{if(!(f>0)||f>=h)return[];const b=h-Math.floor(h/f+1e-9)*f,R=y==="beginning"?0:y==="end"?b:y==="centreLine"?h/2%f:b/2,S=[];for(let k=R;k<=h+1e-4;k+=f)k>1e-4&&k<h-1e-4&&S.push(k);return S};let pt=0,jt=0;for(const h of o){if(h.kind!=="run"||h.params.of!=="curtainWall")continue;jt++;const f=Bt(h,"run"),y=(Ys=(zs=(Ws=f==null?void 0:f.run)==null?void 0:Ws.line)==null?void 0:zs.curves)==null?void 0:Ys[0],b=v.get(String((f==null?void 0:f.level)??h.params.level??"")),R=h.params.lookRef,S=typeof R=="string"?(Ks=I.get(R))==null?void 0:Ks.params:void 0;if(!(y!=null&&y.from)||!y.to||typeof(f==null?void 0:f.height)!="number"||!b||!S)continue;const k=mt=>typeof mt=="number"?mt:Number(mt)||0,A=k(S.uprightWidth)/2,j=k(S.horizontalWidth)/2,nt=Math.hypot(y.to[0]-y.from[0],y.to[1]-y.from[1]),ht=[(y.to[0]-y.from[0])/nt,(y.to[1]-y.from[1])/nt],Y=[y.from[0]-ht[0]*A,y.from[1]-ht[1]*A],St=[y.to[0]+ht[0]*A,y.to[1]+ht[1]*A],U=(typeof f.base=="number"?f.base:0)-j,ot=f.height+2*j,yt=(b.at+U)*u,P=((Xs=f.lines)==null?void 0:Xs.along)??Et(nt,k(S.alongSpacing),S.alongJustify),G=((Qs=f.lines)==null?void 0:Qs.up)??Et(f.height,k(S.upSpacing),S.upJustify),lt=(f.omitted??[]).flatMap(mt=>{const gt=/^(horizontal|vertical)@(-?[\d.]+):(-?[\d.]+)$/.exec(mt);if(!gt)return[];const D=gt[1]==="horizontal",at=Number(gt[2])/1e3+(D?j:A),H=Number(gt[3])/1e3+(D?A:j);return[{horizontal:D,at:at*u,from:H*u}]}),$t=(f.omitted??[]).flatMap(mt=>{const gt=/^panel@(-?[\d.]+),(-?[\d.]+)$/.exec(mt);return gt?[{along:(Number(gt[1])/1e3+A)*u,up:(Number(gt[2])/1e3+j)*u}]:[]}),tt={CategoryId:ge.walls,Type:((Zs=Qe(h))==null?void 0:Zs.type)??String(R),LocationLine:`${ft(Y[0]*u)},${ft(Y[1]*u)},${ft(yt)};${ft(St[0]*u)},${ft(St[1]*u)},${ft(yt)}`,Level:b.name,BaseOffset:ft(U*u),Height:ft(ot*u),Curtain:JSON.stringify({along:P.map(mt=>(mt+A)*u),up:G.map(mt=>(mt+j)*u),omit:lt,empty:$t,mullion:{width:k(S.uprightWidth)*u,depth:k(S.depth)*u},panel:{thickness:k(S.panelDepth)*u,offset:-k(S.panelOffset)*u}})},vt=f.profile;if(Array.isArray(vt)&&vt.length>=3){const gt=vt.reduce((B,V,ct)=>{const dt=vt[(ct+1)%vt.length];return B+V[0]*dt[1]-dt[0]*V[1]},0)>0?1:-1,D=vt.length,at=vt.map((B,V)=>{const ct=vt[(V-1+D)%D],dt=vt[(V+1)%D],xt=(fe,ue)=>{const Ve=ue[0]-fe[0],Bn=ue[1]-fe[1],dr=Math.hypot(Ve,Bn)||1,fr=gt*Bn/dr,ur=-gt*Ve/dr,pr=Math.abs(fr)>Math.abs(ur)?A:j;return{p:[fe[0]+fr*pr,fe[1]+ur*pr],d:[Ve,Bn]}},Q=xt(ct,B),J=xt(B,dt),bt=Q.d[0]*J.d[1]-Q.d[1]*J.d[0];if(Math.abs(bt)<1e-12)return[J.p[0],J.p[1]];const Jt=((J.p[0]-Q.p[0])*J.d[1]-(J.p[1]-Q.p[1])*J.d[0])/bt;return[Q.p[0]+Jt*Q.d[0],Q.p[1]+Jt*Q.d[1]]}),H=[];for(const[B,V]of at)H.push((y.from[0]+ht[0]*B)*u,(y.from[1]+ht[1]*B)*u,(b.at+U+j+V)*u);tt.Profile=JSON.stringify([H])}wt(E(h.id),tt)&&pt++}let Ft=0,Pt=0;for(const h of o){if(h.kind!=="stair"||h.params.of!=="stair")continue;Pt++;const f=Bt(h,"stair"),y=h.params.lookRef,b=typeof y=="string"?(tr=I.get(y))==null?void 0:tr.params:void 0,R=v.get(String((f==null?void 0:f.level)??h.params.level??""));if(!(f!=null&&f.start)||!f.end||!(Number(f.rise)>0)||!R||!b)continue;const S=P=>typeof P=="number"?P:Number(P)||0,k=Number(f.rise),A=Math.max(1,Math.ceil(k/S(b.maxRiser)-1e-6)),j=S(b.tread),nt=P=>[P[0]*u,P[1]*u],ht={family:String(y).split(":")[0],base:(R.at+S(h.params.base))*u,height:k*u,risers:A,tread:j*u,width:S(b.width)*u,sizes:{maxRiser:Math.ceil(k/A*1e3-1e-6)/1e3*u,minTread:j*u,waist:S(b.waist)*u,treadThickness:S(b.treadThickness)*u,riserThickness:S(b.riserThickness)*u,notchExtension:S(b.notchExtension)*u,notchThickness:S(b.notchThickness)*u}},Y=f.sketch;if(Y!=null&&Y.boundary&&Y.boundary.length>=4&&Y.risers&&Y.risers.length>=2){const P=Y.boundary,G=Y.risers[Y.risers.length-1],lt=B=>[(B[0][0]+B[1][0])/2,(B[0][1]+B[1][1])/2],$t=lt(G);let tt=1,vt=1/0;for(let B=1;B<P.length;B++){const V=lt([P[B],P[(B+1)%P.length]]),ct=Math.abs(Math.hypot(V[0]-$t[0],V[1]-$t[1])-j);ct<vt&&(vt=ct,tt=B)}const mt=(B,V)=>{const ct=[];for(let dt=B;dt!==V;dt=(dt+1)%P.length)ct.push([nt(P[dt]),nt(P[(dt+1)%P.length])]);return ct},gt=[...mt(1,tt),...mt((tt+1)%P.length,0)],D=Y.risers.map(([B,V])=>[nt(B),nt(V)]);nt(P[tt]),nt(P[(tt+1)%P.length]);const at=D.map(([B,V])=>[(B[0]+V[0])/2,(B[1]+V[1])/2]);ht.sketch={boundary:gt,risers:D,path:at};let H=1/0;for(let B=0;B+1<Y.risers.length;B++){const[V,ct]=Y.risers[B],[dt,xt]=Y.risers[B+1],Q=[ct[0]-V[0],ct[1]-V[1]],J=[xt[0]-dt[0],xt[1]-dt[1]],bt=Math.hypot(Q[0],Q[1]),Jt=Math.hypot(J[0],J[1]);Math.abs((Q[0]*J[1]-Q[1]*J[0])/(bt*Jt))>.001||(H=Math.min(H,Math.abs(((dt[0]-V[0])*Q[1]-(dt[1]-V[1])*Q[0])/bt)))}Number.isFinite(H)&&(ht.tread=H*u,ht.sizes.minTread=H*u)}else ht.path=[nt([f.start[0],f.start[1]]),nt([f.end[0],f.end[1]])];const St=String(h.item.attrs.Name??""),U=St.replace(/ Run \d+$/,""),ot=[];for(const P of o){if(P.kind!=="extrusion"||U===St||!new RegExp(`^${U.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")} Landing \\d+$`).test(String(P.item.attrs.Name??"")))continue;const G=Bt(P,"extrusion"),lt=G==null?void 0:G.on,$t=(((nr=(er=G==null?void 0:G.profile)==null?void 0:er.outline)==null?void 0:nr.curves)??[]).flatMap(J=>J.from?[J.from]:[]),tt=Ot(P.params.lookRef),vt=v.get(String((G==null?void 0:G.level)??P.params.level??""));if(!(lt!=null&&lt.origin)||!lt.u||!lt.v||Math.abs(lt.v[2]??0)<.99||!$t.length||!tt||!vt)continue;const[mt,gt]=[Math.min(...$t.map(J=>J[0])),Math.max(...$t.map(J=>J[0]))],[D,at]=[Math.min(...$t.map(J=>J[1])),Math.max(...$t.map(J=>J[1]))],H=lt.origin,B=lt.u;let V=[B[1],-B[0]];const ct=[(f.start[0]+f.end[0])/2,(f.start[1]+f.end[1])/2];(ct[0]-H[0])*V[0]+(ct[1]-H[1])*V[1]<0&&(V=[-V[0],-V[1]]);const xt=tt/u,Q=(J,bt)=>[(H[0]+B[0]*J+V[0]*bt)*u,(H[1]+B[1]*J+V[1]*bt)*u];ot.push({outline:[Q(mt,0),Q(gt,0),Q(gt,xt),Q(mt,xt)],top:(vt.at+S(P.params.base)+H[2]+at)*u,thickness:(at-D)*u})}ot.length&&(ht.landings=ot);const yt={CategoryId:ge.stairs,Type:((sr=Qe(h))==null?void 0:sr.type)??String(y),Level:R.name,Stairs:JSON.stringify(ht)};wt(E(h.id),yt)&&Ft++}const st={floor:0,foundation:0,roof:0,ceiling:0},rt={floor:0,foundation:0,roof:0,ceiling:0};for(const h of o){const f=h.params.of;if(h.kind!=="extrusion"||f!=="slab"&&f!=="roof"&&f!=="covering")continue;const y=f==="covering"?"ceiling":f==="roof"?"roof":Mr(h);if(y==="other")continue;st[y]++;const b=Bt(h,"extrusion"),R=typeof h.params.base=="number"?h.params.base:0,S=v.get(String((b==null?void 0:b.level)??h.params.level??"")),k=h.params.lookRef,A=U=>{if(!(U!=null&&U.length))return null;const ot=[];for(const yt of U){if(yt.kind!=="segment"||!yt.from)return null;ot.push(yt.from[0]*u,yt.from[1]*u,R*u)}return ot.length>=9?ot:null},j=A((ir=(rr=b==null?void 0:b.profile)==null?void 0:rr.outline)==null?void 0:ir.curves);if(typeof k!="string"||!S||!j)continue;const nt=[j],ht=y==="roof"?Vt(h):null;for(const U of((or=b==null?void 0:b.profile)==null?void 0:or.holes)??[]){const ot=A(U==null?void 0:U.curves);if(ot&&ht)for(let yt=0;yt+2<ot.length;yt+=3)ot[yt+2]=ht.zAt(ot[yt]/u,ot[yt+1]/u)*u;ot&&nt.push(ot)}const Y={CategoryId:y==="roof"?ge.roofs:y==="ceiling"?ge.ceilings:y==="foundation"?ge.structuralFoundations:ge.floors,Type:((ar=Qe(h))==null?void 0:ar.type)??k,Profile:JSON.stringify(nt),Level:S.name},St=Ot(k);if(St&&(Y["Type.Width"]=ft(St)),y==="roof"||y==="ceiling"){Y.BaseOffset=ft(R*u);const U=Number(h.params.drop??((cr=b==null?void 0:b.said)==null?void 0:cr.drop));if(y==="ceiling"&&Number.isFinite(U)&&St){const P=[...v.values()].filter(G=>G.at>S.at+1e-6).sort((G,lt)=>G.at-lt.at)[0];P&&(Y.BaseOffset=ft((P.at-U-St/u-S.at)*u))}const ot=b==null?void 0:b.slopes;if(y==="roof"&&Array.isArray(ot)&&ot.some(P=>typeof P=="number")){Y.Slopes=JSON.stringify(ot.map(G=>typeof G=="number"?G:null));const P=Math.max(...ot.filter(G=>typeof G=="number").map(G=>Math.abs(G)));St&&P>0&&(Y.BaseOffset=ft(R*u-St*Math.sqrt(1+P*P)))}const yt=y==="roof"?Vt(h):null;if(yt){const{A:P,n:G,u:lt,W:$t,ridge:tt,si:vt,ti:mt,tj:gt,L:D}=yt,at=(H,B)=>[(P[0]+G[0]*H)*u,(P[1]+G[1]*H)*u,B*u];Y.Extrusion=JSON.stringify({profile:[at(0,mt),at(tt,mt+vt*tt),at($t,gt)],along:[lt[0],lt[1]],length:D*u}),delete Y.Slopes}}else St&&(Y.HeightOffset=ft(R*u+St));wt(E(h.id),Y)&&rt[y]++}let et=0,At=0;for(const h of o){if(h.kind!=="member"||h.params.of!=="column")continue;At++;const f=Bt(h,"member"),y=f==null?void 0:f.start;if(!y||y.length!==3)continue;const b=c?Fr(h.params.lookRef):null;if(c&&!b||!b&&!d)continue;const R=b??{family:d.family,type:d.type},S=v.get(String((f==null?void 0:f.level)??""));wt(E(h.id),{...d&&!b?{CategoryId:d.categoryId}:{},Family:R.family,Type:R.type,...S?{Level:S.name}:{}},{position:[y[0]*u,y[1]*u,y[2]*u],rotationDeg:(Number((f==null?void 0:f.roll)??0)||0)*Nr})&&et++}let Ht=0,de=0,Ue=0;for(const h of o){if(h.kind!=="familyInstance")continue;if(h.params.host){Ue++;continue}if(de++,!m)continue;const f=Bt(h,"instance"),y=(lr=f==null?void 0:f.placement)==null?void 0:lr.at;if(!y||y.length!==3)continue;const b=Fr(h.params.type);if(!b)continue;const R=(hr=f==null?void 0:f.placement)==null?void 0:hr.right,S=R?Math.atan2(R[1],R[0])*Nr:0;wt(E(h.id),{Family:b.family,Type:b.type},{position:[y[0]*u,y[1]*u,y[2]*u],rotationDeg:S})&&Ht++}const $e=(()=>{if(!i)return 0;const h=[];for(const y of Nt){const b=y.record.item.guid;if(!b||!i.elements.has(b))continue;const R=Bt(y.record,"run"),S=v.get(String((R==null?void 0:R.level)??y.record.params.level??""));if(!R||!S)continue;const k=nn(i,b);if(!k.length)continue;let A=1/0;for(const j of k)A=Math.min(A,j[2]);h.push(A-(S.at+(typeof R.base=="number"?R.base:0)))}h.sort((y,b)=>y-b);const f=h.length?h[Math.floor(h.length/2)]:0;return Math.abs(f)>.5?f:0})(),Vs=i?Ta(i,N,e.fileId):[];let un=0;for(const h of Vs)wt(h.key,h.attrs,{position:[h.at[0]*u,h.at[1]*u,(h.at[2]-$e)*u],rotationDeg:h.rotationDeg,...h.host?{host:h.host}:{}})&&un++;if(i)for(const h of Ea(i,N,e.fileId))wt(h.key,{WallOpening:h.box.map((f,y)=>ft((y%3===2?f-$e:f)*u)).join(",")},{host:h.host});if(i)for(const h of _a(i,e.fileId))wt(h.key,{Room:"1",Name:h.name,Number:h.number,Height:ft(h.height*u)},{position:[h.at[0]*u,h.at[1]*u,(h.at[2]-$e)*u]});let Pn=0;const Mi=new Set(["slab","roof","covering"]);for(const h of o){const f=h.params.of;(h.kind==="footing"||h.kind==="ramp"||h.kind==="stair"&&f!=="stair"||h.kind==="extrusion"&&!Mi.has(String(f))||h.kind==="extrusion"&&f==="slab"&&Mr(h)==="other"&&!/ Landing \d+$/.test(String(h.item.attrs.Name??""))||h.kind==="run"&&f!=="wall"&&f!=="curtainWall")&&Pn++}let qe=0;for(const[h,f]of C)!h.startsWith(`${e.fileId}:`)||N.has(h)||(O.remove(f),qe++);if(O.length===0)throw new Bs(`Up to date: "${e.name}" holds ${z} element(s) this recipe already made, ${Ue+Pn} waiting on the applier, and nothing is left to remove.`);const Ni=[Yt?`${Yt} level(s)`:"",It?`${It} wall(s)`:"",pt?`${pt} curtain wall(s)`:"",rt.floor?`${rt.floor} floor(s)`:"",rt.foundation?`${rt.foundation} foundation slab(s)`:"",rt.roof?`${rt.roof} roof(s)`:"",rt.ceiling?`${rt.ceiling} ceiling(s)`:"",Ft?`${Ft} stair(s)`:"",et?`${et} column(s)`:"",Ht?`${Ht} instance(s)`:"",un?`${un} family instance(s)`:"",ut?`${ut} changed`:"",qe?`${qe} gone`:""].filter(Boolean);return{title:`${s==="ifc"?"IFC":"Model"} to Revit: ${Ni.join(", ")}`,verb:O.summary,targets:O.length,payload:new Blob([await O.build(t.opId)]),ruleTallies:[{read:v.size,written:Yt},{read:Nt.length+Gt,written:It},{read:jt,written:pt},{read:st.floor+st.foundation,written:rt.floor+rt.foundation},{read:st.roof,written:rt.roof},{read:st.ceiling,written:rt.ceiling},{read:Pt,written:Ft},{read:At,written:et},{read:de,written:Ht},{read:Vs.length,written:un},{read:qe,written:qe},{read:Ue+Pn,written:0}]}}}const $a={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 bring free-standing instances (needs style names)",default:!1},createLevels:{type:"boolean",title:"Carry the model's levels (ensured by name)",default:!0}}},xa=[{reads:"Levels (datums)",writes:"The same level in Revit, ensured by name"},{reads:"Wall runs, one per straight segment",writes:"A native wall: line, type (made from its width when missing), level, height, joins; its edited profile or its top on a roof"},{reads:"Curtain wall runs",writes:"Revit's curtain wall: its grid lines, mullions and panels"},{reads:"Slabs: floors and foundation slabs",writes:"A native floor or foundation slab from the profile, holes included"},{reads:"Roofs",writes:"A footprint roof with its sloping edges, or a roof by extrusion for a gable"},{reads:"Ceilings (coverings)",writes:"A native ceiling from the profile, hung at its drop"},{reads:"Stairs",writes:"A native stair: a straight or sketched run, with its landings"},{reads:"Column records (members)",writes:"A Revit column at each, on its level"},{reads:"Free-standing family instances",writes:"When turned on: a new instance of the same-named type, placed and turned"},{reads:"Everything else with a body: doors, windows, furniture, fixtures, proxies, columns, railings",writes:"A family made from the file's own shape, one per shape, placed where the file has it (doors and windows in their wall)"},{reads:"Things this recipe made whose record is gone",writes:"That element removed"},{reads:"Hosted doors/windows, footings, ramps, other bodies",writes:"Nothing yet - read and counted"}],Ci=`
3
3
  ## How to use it
4
4
 
5
5
  In Revit, with the That Open plugin: **That Open > Select recipe**, pick this
@@ -47,13 +47,13 @@ are read and counted, and their rule row says so.
47
47
  Records are metres and radians, Z up; Revit gets feet and degrees. Types are
48
48
  matched exactly by name; Revit refuses the whole apply when a loadable type is
49
49
  missing (system types are created from their width instead).
50
- `,Ls={name:"frag-to-revit",title:"Platform model to Revit",description:"Builds in Revit the platform records of a .frag: levels, walls, curtain walls, floors, roofs, ceilings, stairs, columns, instances.",to:"revit",inputs:["frag-model"],source:{kind:"project-file",extensions:["frag"]},settingsSchema:Ea,rules:Ia,doc:Ii,run:Ei("frag")},Si={...Ls,name:"ifc-to-revit",title:"IFC to Revit",description:"Builds an IFC of the project in Revit as native elements: levels, walls, floors, roofs, stairs, curtain walls, columns, instances.",inputs:["ifc-model"],source:{kind:"project-file",extensions:["ifc"]},doc:`
50
+ `,Ds={name:"frag-to-revit",title:"Platform model to Revit",description:"Builds in Revit the platform records of a .frag: levels, walls, curtain walls, floors, roofs, ceilings, stairs, columns, instances.",to:"revit",inputs:["frag-model"],source:{kind:"project-file",extensions:["frag"]},settingsSchema:$a,rules:xa,doc:Ci,run:Oi("frag")},$i={...Ds,name:"ifc-to-revit",title:"IFC to Revit",description:"Builds an IFC of the project in Revit as native elements: levels, walls, floors, roofs, stairs, curtain walls, columns, instances.",inputs:["ifc-model"],source:{kind:"project-file",extensions:["ifc"]},doc:`
51
51
  ## Point it at the IFC
52
52
 
53
53
  It reads the IFC file itself, the version uploaded last. Its first step
54
54
  converts it into the platform's records - what each element is, not only its
55
55
  shape - and Revit gets those. Nothing has to be prepared before.
56
- `+Ii,run:Ei("ifc")},Sa={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},_i="rhino-to-revit",_a=`recipe:${_i}`;function Aa(s){const t=(s.attrs.Position??"").split(",").map(e=>Number(e.trim()));return t.length!==3||t.some(e=>!Number.isFinite(e))?null:[t[0],t[1],t[2]]}const Ai={name:_i,title:"Rhino to Revit",description:"Places in Revit an instance of a chosen type at each placed object of a Rhino layer.",to:"revit",inputs:["rhino-model"],source:{kind:"project-file",extensions:["frag"]},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",writes:"A new instance of the chosen type at each"},{reads:"Objects whose instance already exists",writes:"That instance moved to where the object is now"},{reads:"Instances whose object is gone from Rhino",writes:"That instance removed"},{reads:"Everything on other layers",writes:"Nothing"}],doc:`
56
+ `+Ci,run:Oi("ifc")},Ra={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},xi="rhino-to-revit",ka=`recipe:${xi}`;function Ma(s){const t=(s.attrs.Position??"").split(",").map(e=>Number(e.trim()));return t.length!==3||t.some(e=>!Number.isFinite(e))?null:[t[0],t[1],t[2]]}const Ri={name:xi,title:"Rhino to Revit",description:"Places in Revit an instance of a chosen type at each placed object of a Rhino layer.",to:"revit",inputs:["rhino-model"],source:{kind:"project-file",extensions:["frag"]},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",writes:"A new instance of the chosen type at each"},{reads:"Objects whose instance already exists",writes:"That instance moved to where the object is now"},{reads:"Instances whose object is gone from Rhino",writes:"That instance removed"},{reads:"Everything on other layers",writes:"Nothing"}],doc:`
57
57
  ## What it does
58
58
 
59
59
  It reads a model published from Rhino and places in Revit instances of one
@@ -80,5 +80,5 @@ it. What it made is remembered with the model's That Open data.
80
80
  Where an object becomes an instance, Revit decides the level: the nearest one
81
81
  at or below the point. For a level-based family the level wins over the
82
82
  point's height.
83
- `,async run(s){var L;const{picked:t,contents:e}=await ks(s,s.input),{layer:n,instanceType:r}=s.settings;if(!n||!r)throw new Error("Choose the layer and the Revit type.");const i=(L=e.metadata)==null?void 0:L.data,o=i==null?void 0:i.units,a=typeof o=="string"?Sa[o.trim().toLowerCase()]:void 0;if(!a)throw new Error(`"${t.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(`"${t.name}" declares its data as "${l}"; this recipe only converts Z up.`);const d=a*Ne,c=Rs(s),y=new xn({project:s.projectId,document:s.target.docId??"",baseCommit:s.target.version??0,author:_a});let O=0,b=0,B=0;const H=new Set,G=[];for(const I of e.items){if(!I.guid||Object.keys(I.attrs).length===0)continue;if((I.attrs.Layer??"")!==n){B++;continue}const j=Aa(I);if(!j)continue;H.add(I.guid);const st=[j[0]*d,j[1]*d,j[2]*d],Z=c.get(I.guid);Z?G.push({instance:Z,object:I.guid,position:st}):(y.add({CategoryId:r.categoryId,Family:r.family,Type:r.type},{position:st,source:I.guid}),O++)}for(const I of G)y.set(I.instance,{},{position:I.position,source:I.object}),b++;let F=0;for(const[I,j]of c)H.has(I)||(y.remove(j),F++);const D=O+b+F;if(D===0)throw new Ms(`Nothing to write: layer "${n}" of "${t.name}" has no placed object, and nothing of this recipe is left to remove.`);return{title:`From Rhino: ${[O?`${O} new`:"",b?`${b} moved`:"",F?`${F} gone`:""].filter(Boolean).join(", ")}`,verb:y.summary,targets:D,payload:new Blob([await y.build(s.opId)]),ruleTallies:[{read:O,written:O},{read:b,written:b},{read:F,written:F},{read:B,written:0}]}}},Oi=[Ai,Si,Ls];function Oa(s){for(const t of Oi)s.recipes.register(t)}const Ca={MAX_FIELDS:200,MAX_KEY_LENGTH:50,MAX_VALUE_LENGTH:50},$a={uuid:"a3f82c1d-5b74-4e9a-bc30-d7e12f894a61"},xa={uuid:"2c9f4e8d-3a1b-4c5e-9d7f-0a2b6c8e1d3f"},Ra={uuid:"b0b5e2a2-0b3a-4a6b-8b1c-0b1c4a6b8b1c"},ka={uuid:"d8f3a1c2-6b4e-4f9a-8c1d-2e7b5a9f3c60"},Na={uuid:"3f9c1a7e-6b2d-4e18-9a5c-7d0e2f4b6c81"},Ma={uuid:"2c4ae432-fc24-43e9-9783-0c960c674e96"},Fa={uuid:"6f3a9c2e-8b1d-4e6a-9c3f-1d7b5a8e2c4f"},La={uuid:"69af63aa-19ba-4fc7-b17b-75647bac1d76"},Pa={uuid:"234f1416-528d-452a-9cc9-a16c5239b2eb"};exports.CDEManager=$a;exports.ChannelClient=wi;exports.ChannelRoom=Fs;exports.ClashesManager=xa;exports.CollabRoom=mi;exports.DOCUMENT_FILE=bn;exports.DOCUMENT_SCHEMA=Qe;exports.DOCUMENT_TYPES=Os;exports.DocumentDrafts=ti;exports.EngineServicesClient=An;exports.ExternalRoom=gi;exports.FileList=Ra;exports.FlowDoc=ts;exports.GISManager=ka;exports.GitHistoryManager=Na;exports.HelloWorld=Ma;exports.METADATA_LIMITS=Ca;exports.OP_SCHEMA=$s;exports.OperationBuilder=xn;exports.PROJECT_RECIPE_SCHEMA=Ns;exports.PlatformClient=ys;exports.ProjectDocuments=Cs;exports.ProjectHistory=Ss;exports.ProjectManager=Fa;exports.ProjectRecipes=hi;exports.RECIPE_NAME=ci;exports.RecipeKit=ai;exports.Recipes=di;exports.RequestError=kn;exports.SELF_VIEWING_FORMATS=Kr;exports.STORAGE_BATCH_MAX=cs;exports.StaleHistoryError=Xn;exports.TopicsManager=La;exports.UIManager=Pa;exports.UpToDate=Ms;exports.builtinRecipes=Oi;exports.compileRecipe=as;exports.describeChanges=Zo;exports.documentTypeOf=ns;exports.fragToRevit=Ls;exports.ifcToRevit=Si;exports.latestVersions=fi;exports.mintGuid=As;exports.orderByGraph=_s;exports.readFrag=Rn;exports.registerBuiltinRecipes=Oa;exports.rhinoToRevit=Ai;exports.windowTransport=pi;
83
+ `,async run(s){var $;const{picked:t,contents:e}=await Ls(s,s.input),{layer:n,instanceType:r}=s.settings;if(!n||!r)throw new Error("Choose the layer and the Revit type.");const i=($=e.metadata)==null?void 0:$.data,o=i==null?void 0:i.units,a=typeof o=="string"?Ra[o.trim().toLowerCase()]:void 0;if(!a)throw new Error(`"${t.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(`"${t.name}" declares its data as "${l}"; this recipe only converts Z up.`);const d=a*Ne,c=Fs(s),m=new Nn({project:s.projectId,document:s.target.docId??"",baseCommit:s.target.version??0,author:ka});let w=0,v=0,I=0;const _=new Set,L=[];for(const E of e.items){if(!E.guid||Object.keys(E.attrs).length===0)continue;if((E.attrs.Layer??"")!==n){I++;continue}const N=Ma(E);if(!N)continue;_.add(E.guid);const z=[N[0]*d,N[1]*d,N[2]*d],ut=c.get(E.guid);ut?L.push({instance:ut,object:E.guid,position:z}):(m.add({CategoryId:r.categoryId,Family:r.family,Type:r.type},{position:z,source:E.guid}),w++)}for(const E of L)m.set(E.instance,{},{position:E.position,source:E.object}),v++;let C=0;for(const[E,N]of c)_.has(E)||(m.remove(N),C++);const O=w+v+C;if(O===0)throw new Bs(`Nothing to write: layer "${n}" of "${t.name}" has no placed object, and nothing of this recipe is left to remove.`);return{title:`From Rhino: ${[w?`${w} new`:"",v?`${v} moved`:"",C?`${C} gone`:""].filter(Boolean).join(", ")}`,verb:m.summary,targets:O,payload:new Blob([await m.build(s.opId)]),ruleTallies:[{read:w,written:w},{read:v,written:v},{read:C,written:C},{read:I,written:0}]}}},ki=[Ri,$i,Ds];function Na(s){for(const t of ki)s.recipes.register(t)}const Fa={MAX_FIELDS:200,MAX_KEY_LENGTH:50,MAX_VALUE_LENGTH:50},La={uuid:"a3f82c1d-5b74-4e9a-bc30-d7e12f894a61"},Pa={uuid:"2c9f4e8d-3a1b-4c5e-9d7f-0a2b6c8e1d3f"},Ba={uuid:"b0b5e2a2-0b3a-4a6b-8b1c-0b1c4a6b8b1c"},ja={uuid:"d8f3a1c2-6b4e-4f9a-8c1d-2e7b5a9f3c60"},Da={uuid:"3f9c1a7e-6b2d-4e18-9a5c-7d0e2f4b6c81"},Ua={uuid:"2c4ae432-fc24-43e9-9783-0c960c674e96"},qa={uuid:"6f3a9c2e-8b1d-4e6a-9c3f-1d7b5a8e2c4f"},Va={uuid:"69af63aa-19ba-4fc7-b17b-75647bac1d76"},Ga={uuid:"234f1416-528d-452a-9cc9-a16c5239b2eb"};exports.CDEManager=La;exports.ChannelClient=Ii;exports.ChannelRoom=js;exports.ClashesManager=Pa;exports.CollabRoom=bi;exports.DOCUMENT_FILE=In;exports.DOCUMENT_SCHEMA=en;exports.DOCUMENT_TYPES=Rs;exports.DocumentDrafts=oi;exports.EngineServicesClient=Rn;exports.ExternalRoom=Ti;exports.FileList=Ba;exports.FlowDoc=rs;exports.GISManager=ja;exports.GitHistoryManager=Da;exports.HelloWorld=Ua;exports.METADATA_LIMITS=Fa;exports.OP_SCHEMA=Ms;exports.OperationBuilder=Nn;exports.PROJECT_RECIPE_SCHEMA=Ps;exports.PlatformClient=Es;exports.ProjectDocuments=ks;exports.ProjectHistory=Cs;exports.ProjectManager=qa;exports.ProjectRecipes=gi;exports.RECIPE_NAME=pi;exports.RecipeKit=ui;exports.Recipes=yi;exports.RequestError=Ln;exports.SELF_VIEWING_FORMATS=ei;exports.STORAGE_BATCH_MAX=fs;exports.StaleHistoryError=es;exports.TopicsManager=Va;exports.UIManager=Ga;exports.UpToDate=Bs;exports.builtinRecipes=ki;exports.compileRecipe=ds;exports.describeChanges=ra;exports.documentTypeOf=os;exports.fragToRevit=Ds;exports.ifcToRevit=$i;exports.latestVersions=wi;exports.mintGuid=xs;exports.orderByGraph=$s;exports.readFrag=Fn;exports.registerBuiltinRecipes=Na;exports.rhinoToRevit=Ri;exports.windowTransport=vi;
84
84
  //# sourceMappingURL=index.cjs.js.map