@thatopen/services 0.32.0 → 0.34.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs.js CHANGED
@@ -1,5 +1,5 @@
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=`
1
+ "use strict";var Wa=Object.create;var ms=Object.defineProperty;var Ya=Object.getOwnPropertyDescriptor;var Ka=Object.getOwnPropertyNames;var Xa=Object.getPrototypeOf,Za=Object.prototype.hasOwnProperty;var Io=s=>{throw TypeError(s)};var Qa=(s,t,e)=>t in s?ms(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e;var tc=(s,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Ka(t))!Za.call(s,r)&&r!==e&&ms(s,r,{get:()=>t[r],enumerable:!(n=Ya(t,r))||n.enumerable});return s};var Hn=(s,t,e)=>(e=s!=null?Wa(Xa(s)):{},tc(t||!s||!s.__esModule?ms(e,"default",{value:s,enumerable:!0}):e,s));var he=(s,t,e)=>Qa(s,typeof t!="symbol"?t+"":t,e),gs=(s,t,e)=>t.has(s)||Io("Cannot "+e);var j=(s,t,e)=>(gs(s,t,"read from private field"),e?e.call(s):t.get(s)),Ht=(s,t,e)=>t.has(s)?Io("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(s):t.set(s,e),Xt=(s,t,e,n)=>(gs(s,t,"write to private field"),n?n.call(s,e):t.set(s,e),e),I=(s,t,e)=>(gs(s,t,"access private method"),e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const _e=Object.create(null);_e.open="0";_e.close="1";_e.ping="2";_e.pong="3";_e.message="4";_e.upgrade="5";_e.noop="6";const Yn=Object.create(null);Object.keys(_e).forEach(s=>{Yn[_e[s]]=s});const Ss={type:"error",data:"parser error"},zo=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",Wo=typeof ArrayBuffer=="function",Yo=s=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(s):s&&s.buffer instanceof ArrayBuffer,er=({type:s,data:t},e,n)=>zo&&t instanceof Blob?e?n(t):So(t,n):Wo&&(t instanceof ArrayBuffer||Yo(t))?e?n(t):So(new Blob([t]),n):n(_e[s]+(t||"")),So=(s,t)=>{const e=new FileReader;return e.onload=function(){const n=e.result.split(",")[1];t("b"+(n||""))},e.readAsDataURL(s)};function xo(s){return s instanceof Uint8Array?s:s instanceof ArrayBuffer?new Uint8Array(s):new Uint8Array(s.buffer,s.byteOffset,s.byteLength)}let ys;function ec(s,t){if(zo&&s.data instanceof Blob)return s.data.arrayBuffer().then(xo).then(t);if(Wo&&(s.data instanceof ArrayBuffer||Yo(s.data)))return t(xo(s.data));er(s,!1,e=>{ys||(ys=new TextEncoder),t(ys.encode(e))})}const _o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",En=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let s=0;s<_o.length;s++)En[_o.charCodeAt(s)]=s;const nc=s=>{let t=s.length*.75,e=s.length,n,r=0,i,a,l,p;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=En[s.charCodeAt(n)],a=En[s.charCodeAt(n+1)],l=En[s.charCodeAt(n+2)],p=En[s.charCodeAt(n+3)],c[r++]=i<<2|a>>4,c[r++]=(a&15)<<4|l>>2,c[r++]=(l&3)<<6|p&63;return d},sc=typeof ArrayBuffer=="function",nr=(s,t)=>{if(typeof s!="string")return{type:"message",data:Ko(s,t)};const e=s.charAt(0);return e==="b"?{type:"message",data:rc(s.substring(1),t)}:Yn[e]?s.length>1?{type:Yn[e],data:s.substring(1)}:{type:Yn[e]}:Ss},rc=(s,t)=>{if(sc){const e=nc(s);return Ko(e,t)}else return{base64:!0,data:s}},Ko=(s,t)=>{switch(t){case"blob":return s instanceof Blob?s:new Blob([s]);case"arraybuffer":default:return s instanceof ArrayBuffer?s:s.buffer}},Xo="",ic=(s,t)=>{const e=s.length,n=new Array(e);let r=0;s.forEach((i,a)=>{er(i,!1,l=>{n[a]=l,++r===e&&t(n.join(Xo))})})},oc=(s,t)=>{const e=s.split(Xo),n=[];for(let r=0;r<e.length;r++){const i=nr(e[r],t);if(n.push(i),i.type==="error")break}return n};function ac(){return new TransformStream({transform(s,t){ec(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 ws;function Vn(s){return s.reduce((t,e)=>t+e.length,0)}function zn(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 cc(s,t){ws||(ws=new TextDecoder);const e=[];let n=0,r=-1,i=!1;return new TransformStream({transform(a,l){for(e.push(a);;){if(n===0){if(Vn(e)<1)break;const p=zn(e,1);i=(p[0]&128)===128,r=p[0]&127,r<126?n=3:r===126?n=1:n=2}else if(n===1){if(Vn(e)<2)break;const p=zn(e,2);r=new DataView(p.buffer,p.byteOffset,p.length).getUint16(0),n=3}else if(n===2){if(Vn(e)<8)break;const p=zn(e,8),d=new DataView(p.buffer,p.byteOffset,p.length),c=d.getUint32(0);if(c>Math.pow(2,21)-1){l.enqueue(Ss);break}r=c*Math.pow(2,32)+d.getUint32(4),n=3}else{if(Vn(e)<r)break;const p=zn(e,r);l.enqueue(nr(i?p:ws.decode(p),t)),n=0}if(r===0||r>s){l.enqueue(Ss);break}}}})}const Zo=4;function oe(s){if(s)return lc(s)}function lc(s){for(var t in oe.prototype)s[t]=oe.prototype[t];return s}oe.prototype.on=oe.prototype.addEventListener=function(s,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+s]=this._callbacks["$"+s]||[]).push(t),this};oe.prototype.once=function(s,t){function e(){this.off(s,e),t.apply(this,arguments)}return e.fn=t,this.on(s,e),this};oe.prototype.off=oe.prototype.removeListener=oe.prototype.removeAllListeners=oe.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};oe.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};oe.prototype.emitReserved=oe.prototype.emit;oe.prototype.listeners=function(s){return this._callbacks=this._callbacks||{},this._callbacks["$"+s]||[]};oe.prototype.hasListeners=function(s){return!!this.listeners(s).length};const cs=typeof Promise=="function"&&typeof Promise.resolve=="function"?t=>Promise.resolve().then(t):(t,e)=>e(t,0),we=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),hc="arraybuffer";function Qo(s,...t){return t.reduce((e,n)=>(s.hasOwnProperty(n)&&(e[n]=s[n]),e),{})}const fc=we.setTimeout,dc=we.clearTimeout;function ls(s,t){t.useNativeTimers?(s.setTimeoutFn=fc.bind(we),s.clearTimeoutFn=dc.bind(we)):(s.setTimeoutFn=we.setTimeout.bind(we),s.clearTimeoutFn=we.clearTimeout.bind(we))}const uc=1.33;function pc(s){return typeof s=="string"?mc(s):Math.ceil((s.byteLength||s.size)*uc)}function mc(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 ta(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function gc(s){let t="";for(let e in s)s.hasOwnProperty(e)&&(t.length&&(t+="&"),t+=encodeURIComponent(e)+"="+encodeURIComponent(s[e]));return t}function yc(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 wc extends Error{constructor(t,e,n){super(t),this.description=e,this.context=n,this.type="TransportError"}}class sr extends oe{constructor(t){super(),this.writable=!1,ls(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 wc(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=nr(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=gc(t);return e.length?"?"+e:""}}class bc extends sr{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)};oc(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,ic(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]=ta()),!this.supportsBinary&&!e.sid&&(e.b64=1),this.createUri(t,e)}}let ea=!1;try{ea=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const vc=ea;function Ec(){}class Tc extends bc{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 xe extends oe{constructor(t,e,n){super(),this.createRequest=t,ls(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=Qo(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=xe.requestsCount++,xe.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=Ec,t)try{this._xhr.abort()}catch{}typeof document<"u"&&delete xe.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()}}xe.requestsCount=0;xe.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",Ao);else if(typeof addEventListener=="function"){const s="onpagehide"in we?"pagehide":"unload";addEventListener(s,Ao,!1)}}function Ao(){for(let s in xe.requests)xe.requests.hasOwnProperty(s)&&xe.requests[s].abort()}const Mc=function(){const s=na({xdomain:!1});return s&&s.responseType!==null}();class $c extends Tc{constructor(t){super(t);const e=t&&t.forceBase64;this.supportsBinary=Mc&&!e}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new xe(na,this.uri(),t)}}function na(s){const t=s.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!t||vc))return new XMLHttpRequest}catch{}if(!t)try{return new we[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const sa=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class Ic extends sr{get name(){return"websocket"}doOpen(){const t=this.uri(),e=this.opts.protocols,n=sa?{}:Qo(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;er(n,this.supportsBinary,i=>{try{this.doWrite(n,i)}catch{}r&&cs(()=>{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]=ta()),this.supportsBinary||(e.b64=1),this.createUri(t,e)}}const bs=we.WebSocket||we.MozWebSocket;class Sc extends Ic{createSocket(t,e,n){return sa?new bs(t,e,n):e?new bs(t,e):new bs(t)}doWrite(t,e){this.ws.send(e)}}class xc extends sr{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=cc(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=t.readable.pipeThrough(e).getReader(),r=ac();r.readable.pipeTo(t.writable),this._writer=r.writable.getWriter();const i=()=>{n.read().then(({done:l,value:p})=>{l||(this.onPacket(p),i())}).catch(l=>{})};i();const a={type:"open"};this.query.sid&&(a.data=`{"sid":"${this.query.sid}"}`),this._writer.write(a).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&&cs(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this._transport)===null||t===void 0||t.close()}}const _c={websocket:Sc,webtransport:xc,polling:$c},Ac=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Cc=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function xs(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=Ac.exec(s||""),i={},a=14;for(;a--;)i[Cc[a]]=r[a]||"";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=Rc(i,i.path),i.queryKey=Oc(i,i.query),i}function Rc(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 Oc(s,t){const e={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(n,r,i){r&&(e[r]=i)}),e}const _s=typeof addEventListener=="function"&&typeof removeEventListener=="function",Kn=[];_s&&addEventListener("offline",()=>{Kn.forEach(s=>s())},!1);class ze extends oe{constructor(t,e){if(super(),this.binaryType=hc,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=xs(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=xs(e.host).host);ls(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=yc(this.opts.query)),_s&&(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"})},Kn.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(t){const e=Object.assign({},this.opts.query);e.EIO=Zo,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&&ze.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",ze.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+=pc(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,cs(()=>{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(ze.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(),_s&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const n=Kn.indexOf(this._offlineEventListener);n!==-1&&Kn.splice(n,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,e),this.writeBuffer=[],this._prevBufferLen=0}}}ze.protocol=Zo;class kc extends ze{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;ze.priorWebsocketSuccess=!1;const r=()=>{n||(e.send([{type:"ping",data:"probe"}]),e.once("packet",E=>{if(!n)if(E.type==="pong"&&E.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",e),!e)return;ze.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 b=new Error("probe error");b.transport=e.name,this.emitReserved("upgradeError",b)}}))};function i(){n||(n=!0,c(),e.close(),e=null)}const a=E=>{const b=new Error("probe error: "+E);b.transport=e.name,i(),this.emitReserved("upgradeError",b)};function l(){a("transport closed")}function p(){a("socket closed")}function d(E){e&&E.name!==e.name&&i()}const c=()=>{e.removeListener("open",r),e.removeListener("error",a),e.removeListener("close",l),this.off("close",p),this.off("upgrading",d)};e.once("open",r),e.once("error",a),e.once("close",l),this.once("close",p),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 Nc=class extends kc{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=>_c[i]).filter(i=>!!i)),super(n?r:t,r)}};function Fc(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=xs(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 Pc=typeof ArrayBuffer=="function",Lc=s=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(s):s.buffer instanceof ArrayBuffer,ra=Object.prototype.toString,Bc=typeof Blob=="function"||typeof Blob<"u"&&ra.call(Blob)==="[object BlobConstructor]",jc=typeof File=="function"||typeof File<"u"&&ra.call(File)==="[object FileConstructor]";function rr(s){return Pc&&(s instanceof ArrayBuffer||Lc(s))||Bc&&s instanceof Blob||jc&&s instanceof File}function Xn(s,t){if(!s||typeof s!="object")return!1;if(Array.isArray(s)){for(let e=0,n=s.length;e<n;e++)if(Xn(s[e]))return!0;return!1}if(rr(s))return!0;if(s.toJSON&&typeof s.toJSON=="function"&&arguments.length===1)return Xn(s.toJSON(),!0);for(const e in s)if(Object.prototype.hasOwnProperty.call(s,e)&&Xn(s[e]))return!0;return!1}function Dc(s){const t=[],e=s.data,n=s;return n.data=As(e,t),n.attachments=t.length,{packet:n,buffers:t}}function As(s,t){if(!s)return s;if(rr(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]=As(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]=As(s[n],t));return e}return s}function Uc(s,t){return s.data=Cs(s.data,t),delete s.attachments,s}function Cs(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]=Cs(s[e],t);else if(typeof s=="object")for(const e in s)Object.prototype.hasOwnProperty.call(s,e)&&(s[e]=Cs(s[e],t));return s}const Jc=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var Vt;(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"})(Vt||(Vt={}));class qc{constructor(t){this.replacer=t}encode(t){return(t.type===Vt.EVENT||t.type===Vt.ACK)&&Xn(t)?this.encodeAsBinary({type:t.type===Vt.EVENT?Vt.BINARY_EVENT:Vt.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id}):[this.encodeAsString(t)]}encodeAsString(t){let e=""+t.type;return(t.type===Vt.BINARY_EVENT||t.type===Vt.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=Dc(t),n=this.encodeAsString(e.packet),r=e.buffers;return r.unshift(n),r}}class ir extends oe{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===Vt.BINARY_EVENT;n||e.type===Vt.BINARY_ACK?(e.type=n?Vt.EVENT:Vt.ACK,this.reconstructor=new Gc(e),e.attachments===0&&super.emitReserved("decoded",e)):super.emitReserved("decoded",e)}else if(rr(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(Vt[n.type]===void 0)throw new Error("unknown packet type "+n.type);if(n.type===Vt.BINARY_EVENT||n.type===Vt.BINARY_ACK){const i=e+1;for(;t.charAt(++e)!=="-"&&e!=t.length;);const a=t.substring(i,e);if(a!=Number(a)||t.charAt(e)!=="-")throw new Error("Illegal attachments");const l=Number(a);if(!Hc(l)||l<0)throw new Error("Illegal attachments");if(l>this.opts.maxAttachments)throw new Error("too many attachments");n.attachments=l}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 a=t.charAt(e);if(a==null||Number(a)!=a){--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(ir.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 Vt.CONNECT:return Co(e);case Vt.DISCONNECT:return e===void 0;case Vt.CONNECT_ERROR:return typeof e=="string"||Co(e);case Vt.EVENT:case Vt.BINARY_EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&Jc.indexOf(e[0])===-1);case Vt.ACK:case Vt.BINARY_ACK:return Array.isArray(e)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class Gc{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=Uc(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const Hc=Number.isInteger||function(s){return typeof s=="number"&&isFinite(s)&&Math.floor(s)===s};function Co(s){return Object.prototype.toString.call(s)==="[object Object]"}const Vc=Object.freeze(Object.defineProperty({__proto__:null,Decoder:ir,Encoder:qc,get PacketType(){return Vt}},Symbol.toStringTag,{value:"Module"}));function Ee(s,t,e){return s.on(t,e),function(){s.off(t,e)}}const zc=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class ia extends oe{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=[Ee(t,"open",this.onopen.bind(this)),Ee(t,"packet",this.onpacket.bind(this)),Ee(t,"error",this.onerror.bind(this)),Ee(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(zc.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 a={type:Vt.EVENT,data:e};if(a.options={},a.options.compress=this.flags.compress!==!1,typeof e[e.length-1]=="function"){const c=this.ids++,E=e.pop();this._registerAckCallback(c,E),a.id=c}const l=(r=(n=this.io.engine)===null||n===void 0?void 0:n.transport)===null||r===void 0?void 0:r.writable,p=this.connected&&!(!((i=this.io.engine)===null||i===void 0)&&i._hasPingExpired());return this.flags.volatile&&!l||(p?(this.notifyOutgoingListeners(a),this.packet(a)):this.sendBuffer.push(a)),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 l=0;l<this.sendBuffer.length;l++)this.sendBuffer[l].id===t&&this.sendBuffer.splice(l,1);e.call(this,new Error("operation has timed out"))},r),a=(...l)=>{this.io.clearTimeoutFn(i),e.apply(this,l)};a.withError=!0,this.acks[t]=a}emitWithAck(t,...e){return new Promise((n,r)=>{const i=(a,l)=>a?r(a):n(l);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:Vt.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 Vt.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 Vt.EVENT:case Vt.BINARY_EVENT:this.onevent(t);break;case Vt.ACK:case Vt.BINARY_ACK:this.onack(t);break;case Vt.DISCONNECT:this.ondisconnect();break;case Vt.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:Vt.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:Vt.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 hn(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}hn.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};hn.prototype.reset=function(){this.attempts=0};hn.prototype.setMin=function(s){this.ms=s};hn.prototype.setMax=function(s){this.max=s};hn.prototype.setJitter=function(s){this.jitter=s};class Rs extends oe{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,ls(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 hn({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||Vc;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 Nc(this.uri,this.opts);const e=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const r=Ee(e,"open",function(){n.onopen(),t&&t()}),i=l=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",l),t?t(l):this.maybeReconnectOnOpen()},a=Ee(e,"error",i);if(this._timeout!==!1){const l=this._timeout,p=this.setTimeoutFn(()=>{r(),i(new Error("timeout")),e.close()},l);this.opts.autoUnref&&p.unref(),this.subs.push(()=>{this.clearTimeoutFn(p)})}return this.subs.push(r),this.subs.push(a),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(Ee(t,"ping",this.onping.bind(this)),Ee(t,"data",this.ondata.bind(this)),Ee(t,"error",this.onerror.bind(this)),Ee(t,"close",this.onclose.bind(this)),Ee(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){cs(()=>{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 ia(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 mn={};function xn(s,t){typeof s=="object"&&(t=s,s=void 0),t=t||{};const e=Fc(s,t.path||"/socket.io"),n=e.source,r=e.id,i=e.path,a=mn[r]&&i in mn[r].nsps,l=t.forceNew||t["force new connection"]||t.multiplex===!1||a;let p;return l?p=new Rs(n,t):(mn[r]||(mn[r]=new Rs(n,t)),p=mn[r]),e.query&&!t.query&&(t.query=e.queryKey),p.socket(e.path,t)}Object.assign(xn,{Manager:Rs,Socket:ia,io:xn,connect:xn});class Os 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 Ro="bimterop",ks="revitflow_history.json",oa="revitflow_model.frag",aa="revitflow_",Wc="bimterop-locks-anchor",gn=new Map;function Yc(s,t){return s.filter(e=>String(e.parentId??"")===t)}function Kc(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 Ie(s){return String(s._id??s.id??"")}var ve,We,ke,Cn,Rn,Ns;class or{constructor(t,e){Ht(this,Rn);Ht(this,ve);Ht(this,We,new Map);Ht(this,ke);Ht(this,Cn,0);this.client=t,this.projectId=e}async docs(){const t=await I(this,Rn,Ns).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??""),a=i.indexOf("-");if(a<=0)continue;const p=(await this.client.listFiles({folderId:Ie(r)})).map(E=>String(E.name??"")),d=p.find(E=>E===oa)??p.find(E=>E.endsWith(".frag")&&!E.startsWith(aa)),c=p.includes(ks)||!!d;n.push({source:i.slice(0,a),docId:i.slice(a+1),folderId:Ie(r),modelName:d,...c?{}:{empty:!0}})}return n}doc(t,e){const n=`${t}-${e}`;let r=j(this,We).get(n);return r||(r=new Fs(this.client,this,t,e),j(this,We).set(n,r)),r}document(t){const e=`platform-${t}`;let n=j(this,We).get(e);return n||(n=new Fs(this.client,this,"platform",t,t),j(this,We).set(e,n)),n}async childFolders(t,e=!1){return(e||!j(this,ke)||Date.now()-j(this,Cn)>3e4)&&(Xt(this,Cn,Date.now()),Xt(this,ke,this.client.listFolders({parentFolderId:t,projectId:this.projectId}).then(n=>Yc(n,t))),j(this,ke).catch(()=>{Xt(this,ke,void 0)})),j(this,ke)}forgetFolders(){Xt(this,ke,void 0)}async rootFolderId(t=!1){if(j(this,ve))return j(this,ve);const e=await I(this,Rn,Ns).call(this);if(e)return e;if(!t)return;const n=await this.client.createFolder(Ro,void 0,this.projectId);return Xt(this,ve,Ie(n)),j(this,ve)}}ve=new WeakMap,We=new WeakMap,ke=new WeakMap,Cn=new WeakMap,Rn=new WeakSet,Ns=async function(){if(j(this,ve))return j(this,ve);const e=(await this.client.listFolders({projectId:this.projectId})).find(n=>String(n.name??"")===Ro&&!n.parentId);return e&&Xt(this,ve,Ie(e)),j(this,ve)};var Me,Et,Re,Qe,Ue,$e,On,Ps,Zn,Je,ca,la,Qn,ha,fa,da;class Fs{constructor(t,e,n,r,i){Ht(this,Et);Ht(this,Me);Ht(this,$e);Ht(this,On,0);this.client=t,this.project=e,this.source=n,this.docId=r,Xt(this,Me,i)}async timeline(){const t=await I(this,Et,Qn).call(this);return ar((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 I(this,Et,Je).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 a=await I(this,Et,Je).call(this);if(!a)throw new Error(`Document ${this.source}-${this.docId} has no model file yet.`);const l=e[i],p=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(E=>E.type==="delete").map(E=>E.uniqueId)}));return{baseline:{fileId:a.id,guid:l.guid,current:!p,...l.version!==void 0?{storageVersion:l.version}:{}},steps:d,at:e[r].guid}}async folderId(){return await I(this,Et,Ue).call(this,!1)}async descriptor(){return await j(this,Et,Re).descriptor(await I(this,Et,Ue).call(this,!1))}async view(t){const e=await I(this,Et,Ue).call(this,!1),n=await j(this,Et,Re).descriptor(e);if(n){for(const i of t){const a=n.views.find(l=>l.format===i);if(a)return a}return null}if(!t.includes("frag"))return null;const r=await I(this,Et,Je).call(this);return r?{fileId:r.id,format:"frag"}:null}async addView(t){const e=await I(this,Et,Ue).call(this,!0);if(await j(this,Et,Re).descriptor(e)){await j(this,Et,Re).addView(e,t);return}const r=await I(this,Et,Je).call(this);await j(this,Et,Re).setDescriptor(e,{name:(r==null?void 0:r.name.replace(/\.frag$/,""))??j(this,Et,Qe),views:[t]})}async ensureDescriptor(){const t=await I(this,Et,Ue).call(this,!1),e=await j(this,Et,Re).descriptor(t);if(e)return e;const n=await I(this,Et,Je).call(this);if(!n)return null;const r={name:n.name.replace(/\.frag$/,""),views:[{fileId:n.id,format:"frag"}]};return await j(this,Et,Re).setDescriptor(t,r),await j(this,Et,Re).descriptor(t)}async ownership(){const t=await I(this,Et,Zn).call(this,Wc);if(!t)return[];const e=await this.client.getHiddenFilesByParent(t.id),n=await Promise.all(e.map(async a=>{try{const l=Ie(a),p=await this.client.downloadHiddenFile(l),d=JSON.parse(await p.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 a of n)if(a)for(const l of a.keys){if(!l||r.has(l))continue;r.add(l);const p=i.get(a.owner)??[];p.push(l),i.set(a.owner,p)}return[...i.entries()].map(([a,l])=>({owner:a,elements:l}))}async sync(t){var l,p,d;const e=await I(this,Et,Ue).call(this,!0);let n=await I(this,Et,Qn).call(this)??{model:this.docId,commits:[]};const r=Oo(n.commits);if(t.expectedLatestGuid!==void 0&&(r==null?void 0:r.guid)!==t.expectedLatestGuid)throw new Os(t.expectedLatestGuid,r==null?void 0:r.guid);const i={guid:cr(),...r?{parents:[r.guid]}:{},author:t.author,source:t.source,timestamp:t.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}:{},...(l=t.origins)!=null&&l.length?{origins:t.origins}:{},changes:t.changes,counts:Xc(t.changes)};if(t.model&&(await I(this,Et,da).call(this,e,t.model),i.full=!0),t.delta){const c=((p=await I(this,Et,Je).call(this))==null?void 0:p.id)??((d=t.file)==null?void 0:d.fileId)??void 0;if(!c)throw new Error("A delta needs the model file to hang from: sync a full model first.");const E=await this.client.createHiddenFile(t.delta,c);i.deltaId=Kc(E)}const a=await I(this,Et,Qn).call(this);if(a){n=a;const c=Oo(n.commits);if(t.expectedLatestGuid!==void 0&&(c==null?void 0:c.guid)!==t.expectedLatestGuid)throw new Os(t.expectedLatestGuid,c==null?void 0:c.guid);c&&!i.parents&&(i.parents=[c.guid])}return n.commits.push(i),await I(this,Et,ha).call(this,e,ks,n),i}}Me=new WeakMap,Et=new WeakSet,Re=function(){return new hr(this.client,this.project.projectId)},Qe=function(){return`${this.source}-${this.docId}`},Ue=async function(t){if(j(this,Me))return j(this,Me);const e=await this.project.rootFolderId(t);if(!e)throw new Error(`Project ${this.project.projectId} has no connected documents yet.`);const n=a=>a.find(l=>String(l.name??"")===j(this,Et,Qe)),r=n(await this.project.childFolders(e))??n(await this.project.childFolders(e,!0));if(r)return Xt(this,Me,Ie(r)),j(this,Me);if(!t)throw new Error(`Document ${j(this,Et,Qe)} does not exist in this project.`);const i=await this.client.createFolder(j(this,Et,Qe),e,this.project.projectId);return this.project.forgetFolders(),Xt(this,Me,Ie(i)),j(this,Me)},$e=new WeakMap,On=new WeakMap,Ps=async function(){return(!j(this,$e)||Date.now()-j(this,On)>5e3)&&(Xt(this,On,Date.now()),Xt(this,$e,(async()=>{const t=await I(this,Et,Ue).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:Ie(n),name:String(n.name??""),stamp:os(n)}))})()),j(this,$e).catch(()=>{Xt(this,$e,void 0)})),j(this,$e)},Zn=async function(t){try{return(await I(this,Et,Ps).call(this)).find(e=>e.name===t)}catch{return}},Je=async function(){try{const t=await I(this,Et,Ps).call(this);return t.find(e=>e.name===oa)??t.find(e=>e.name.endsWith(".frag")&&!e.name.startsWith(aa))}catch{return}},ca=async function(t){const e=await I(this,Et,Zn).call(this,t);if(!e)return;const n=e.stamp?gn.get(e.id):void 0;if(n&&n.stamp===e.stamp)return structuredClone(await n.value);const r=I(this,Et,la).call(this,e,t);return e.stamp&&(gn.set(e.id,{stamp:e.stamp,value:r}),r.catch(()=>{var i;((i=gn.get(e.id))==null?void 0:i.value)===r&&gn.delete(e.id)})),structuredClone(await r)},la=async function(t,e){const n=await this.client.downloadFile(t.id);if(!n.ok)throw new Error(`Reading ${e} answered ${n.status}`);const r=await n.text();if(r.trim())return JSON.parse(r)},Qn=function(){return I(this,Et,ca).call(this,ks)},ha=async function(t,e,n){const r=new Blob([JSON.stringify(n)],{type:"application/json"}),i=await I(this,Et,Zn).call(this,e);return i?(gn.delete(i.id),await this.client.updateFile(i.id,{file:r,versionTag:await this.client.nextVersionTag(i.id)}),i):await I(this,Et,fa).call(this,t,e,n)},fa=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});Xt(this,$e,void 0);const a=i.item;return{id:Ie(a??i),name:e}},da=async function(t,e){const n=await I(this,Et,Je).call(this);if(n)return await this.client.updateFile(n.id,{file:e,versionTag:await this.client.nextVersionTag(n.id)}),n;const r=`${j(this,Et,Qe)}.frag`,i=await this.client.createFile({file:e,name:r,versionTag:"v1",parentFolderId:t,projectId:this.project.projectId});Xt(this,$e,void 0);const a=i.item;return{id:Ie(a??i),name:r}};function Xc(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 ar(s){var p;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=(p=d.parents)==null?void 0:p[0];if(c&&t.has(c)){const E=e.get(c)??[];E.push(d),e.set(c,E)}else n.push(d)}const r=(d,c)=>String(d.timestamp).localeCompare(String(c.timestamp));n.sort(r);const i=[],a=[...n].reverse(),l=new Set;for(;a.length;){const d=a.pop();if(l.has(d.guid))continue;l.add(d.guid),i.push(d);const c=(e.get(d.guid)??[]).sort(r);for(let E=c.length-1;E>=0;E--)a.push(c[E])}for(const d of s)l.has(d.guid)||i.push(d);return i.forEach((d,c)=>d.ordinal=c),i}function Oo(s){const t=ar(s);return t[t.length-1]}function cr(){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 lr={bim:{label:"BIM model",icon:"tabler:building"},drawings:{label:"Drawing set",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"}},Zc={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 Ls(s){var e;if(s.type&&s.type in lr)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?Zc[n.toLowerCase()]:void 0;if(r)return r}return"generic"}const An="thatopen/document@1",Tn="document.json",ua=["pdf","txt","md","json","csv","tsv","frag"];function be(s){return String(s._id??s.id??"")}const Xe=new Map;let ko=!1;const os=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 se,pa,ma,Bs,ga,ya,wa,ba,Mn;class hr{constructor(t,e){Ht(this,se);this.client=t,this.projectId=e}async list(t){const e=await I(this,se,pa).call(this),n=t==null?void 0:t.types;return n!=null&&n.length?e.filter(r=>n.includes(Ls(r.descriptor))):e}async fromFile(t,e){const n=await this.client.getFile(t),r=String(n.name??""),i=vs(r,n.fileExtension),a=(e==null?void 0:e.name)??r.replace(/\.[^.]+$/,"")??r,l=new Set((await this.list().catch(()=>[])).map(k=>String(k.descriptor.name??"").toLowerCase())),p=n.folderId?String(n.folderId):void 0;let d=a,c="";for(let k=1;k<100;k++){if(d=k===1?a:`${a} (${k})`,l.has(d.toLowerCase()))continue;const W=await this.client.createFolder(d,p,this.projectId);if(c=be(W),!await I(this,se,Mn).call(this,c))break}await this.client.updateFile(t,{parentFolderId:c});const E=[],b=await I(this,se,ya).call(this,n);if(b)try{const k=await this.client.getFile(b);await this.client.updateFile(b,{parentFolderId:c}),E.push({fileId:b,format:vs(String(k.name??""),k.fileExtension)})}catch{}((e==null?void 0:e.selfView)??ua.includes(i))&&E.push({fileId:t,format:i});const F={schema:An,name:d,native:{fileId:t,format:i},views:E};return F.type=(e==null?void 0:e.type)??Ls(F),await this.setDescriptor(c,F),await this.recordUpload(c,{fileId:t,name:r,format:i},(e==null?void 0:e.author)??String(n.createdBy??"")),{folderId:c,descriptor:F}}async recordUpload(t,e,n){const r=new or(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??vs(e.name,void 0)},changes:[]})}async descriptor(t){const e=await I(this,se,Mn).call(this,t);return e?I(this,se,Bs).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(a=>a.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:An,views:e.views??[]},r=new Blob([JSON.stringify(n)],{type:"application/json"}),i=await I(this,se,Mn).call(this,t);if(i){Xe.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:Tn,versionTag:"v1",parentFolderId:t,projectId:this.projectId})}drafts(t){return new va(this.client,()=>I(this,se,Mn).call(this,t))}}se=new WeakSet,pa=async function(){const t=await I(this,se,ma).call(this);if(t)return t;const n=(await this.client.listFiles({projectId:this.projectId})).filter(i=>String(i.name??"")===Tn);return(await Promise.all(n.map(async i=>{const a=i,l=String(a.folderId??a.parentFolderId??"");if(!l)return null;const p=await I(this,se,Bs).call(this,be(i),os(i));return p?{folderId:l,descriptor:p}:null}))).filter(i=>i!==null)},ma=async function(){if(ko)return null;let t;try{t=await this.client.listDocumentDescriptors(this.projectId)}catch(n){const r=n.status;if(r===404||r===400||r===405)return ko=!0,null;throw n}const e=[];for(const n of(t==null?void 0:t.documents)??[]){const r=Fo(n.descriptor);!r||!n.folderId||(n.fileId&&n.versionTag&&Xe.set(n.fileId,{stamp:n.versionTag,value:Promise.resolve(r)}),e.push({folderId:String(n.folderId),descriptor:r}))}return e},Bs=function(t,e){const n=e?Xe.get(t):void 0;if(n&&n.stamp===e)return n.value;const r=I(this,se,ga).call(this,t);return e&&(Xe.set(t,{stamp:e,value:r}),r.catch(()=>{var i;((i=Xe.get(t))==null?void 0:i.value)===r&&Xe.delete(t)})),r},ga=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 Fo(r)},ya=async function(t){let e=t.versions??[],n;if(e.length===0){n=await this.client.listFiles({projectId:this.projectId}).catch(()=>[]);const d=n.find(c=>be(c)===be(t));e=(d==null?void 0:d.versions)??[]}const r=await I(this,se,ba).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 a=d=>String(d.folderId??d.parentFolderId??""),l=new Set(n.filter(d=>String(d.name??"")===Tn).map(a)),p=n.filter(d=>String(d.name??"").toLowerCase()===`${i}.frag`&&!d.archived&&be(d)!==be(t)&&!l.has(a(d)));for(const d of p){const c=await I(this,se,wa).call(this,d);if(c===void 0||c===be(t))return be(d)}},wa=async function(t){const n=[...t.versions??[]].sort((r,i)=>String(i.createdAt??"").localeCompare(String(r.createdAt??"")))[0];if(n)try{const r=await this.client.getFileVersionMetadata(be(t),n.tag);return typeof(r==null?void 0:r.sourceIfcId)=="string"&&r.sourceIfcId?r.sourceIfcId:void 0}catch{return}},ba=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(be(t),r.tag),a=i==null?void 0:i.derivedFileId;if(typeof a=="string"&&a)return a}catch{}},Mn=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??"")===Tn);return n?{id:be(n),stamp:os(n)}:void 0};const js="draft:",tn="TODRAFT1";var Se,$n,Ds;class va{constructor(t,e){Ht(this,Se);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 I(this,Se,$n).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 I(this,Se,$n).call(this,e.id)).filter(p=>!(t!=null&&t.userId)||p.userId===t.userId).sort((p,d)=>+d.savedAt-+p.savedAt)[0];if(!r)return null;const i=await this.client.downloadHiddenFile(r.hiddenId),{meta:a,blob:l}=await el(await i.blob());return{userId:r.userId,savedAt:r.savedAt,meta:a,blob:l}}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=Qc(e.userId),i=(await I(this,Se,$n).call(this,n.id)).filter(p=>p.userId===e.userId),l=(await this.client.createHiddenFile(await tl(t,e.meta??{}),n.id,r)).hiddenFileId;if(!l)throw new Error("The draft upload answered without a hiddenFileId.");return await I(this,Se,Ds).call(this,i.map(p=>p.hiddenId)),{userId:e.userId,savedAt:No(l)}}async delete(t){const e=await this.holder();if(!e)return;const n=(await I(this,Se,$n).call(this,e.id)).filter(r=>r.userId===t.userId);await I(this,Se,Ds).call(this,n.map(r=>r.hiddenId))}}Se=new WeakSet,$n=async function(t){return(await this.client.getHiddenFilesByParent(t)).filter(n=>typeof n.tag=="string"&&n.tag.startsWith(js)).map(n=>{const r=String(n._id);return{hiddenId:r,userId:n.tag.slice(js.length),savedAt:No(r)}})},Ds=async function(t){for(const e of t)try{await this.client.deleteHiddenFile(e)}catch{}};function Qc(s){const t=`${js}${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 No(s){const t=parseInt(s.slice(0,8),16);return new Date(Number.isFinite(t)?t*1e3:0)}async function tl(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(tn),n,e,s])}async function el(s){const t=new Uint8Array(await s.slice(0,tn.length+4).arrayBuffer());if(new TextDecoder().decode(t.slice(0,tn.length))!==tn)return{meta:{},blob:s};const e=new DataView(t.buffer).getUint32(tn.length,!0),n=tn.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 vs(s,t){const e=(t??"").replace(/^\./,"").toLowerCase();if(e)return e;const n=s.lastIndexOf(".");return n>0?s.slice(n+1).toLowerCase():""}function Fo(s){if(!s||typeof s!="object")return null;const t=s;if(t.schema!==An||typeof t.name!="string")return null;const e=Array.isArray(t.views)?t.views.filter(l=>!!l&&typeof l=="object"&&typeof l.fileId=="string"&&typeof l.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 lr?t.type:void 0,a={...t};return delete a.type,delete a.native,{...a,schema:An,name:t.name,...i?{type:i}:{},...r?{native:{fileId:n.fileId,format:n.format}}:{},views:e}}const nl="flow:",sl="flow:op",rl="flow:source",il="flow:host",ol="flow:print",fr="revitflow/op@2",Po="REVITFLOWCHANGE",Lo="REVITFLOWOPERATION";class hs{constructor(t){he(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:fr,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 al();return cl(this.flatbuffer(n,r,t,JSON.stringify(e)))}pack(t,e){const n={};for(const[r,i]of Object.entries(t??{}))r.startsWith(nl)&&r!==ol||(n[r]=String(i));return e.position&&(n.Position=e.position.map(Bo).join(",")),e.rotationDeg!==void 0&&(n.Rotation=Bo(e.rotationDeg)),e.source&&(n[rl]=e.source),e.host&&(n[il]=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:a,Model:l,SpatialStructure:p,Transform:d}=e,c=new t.Builder(1024),E=this.changes.length,b=new Uint32Array(E);let $=1;for(let it=0;it<E;it++)b[it]=$++;const F=$++,k=it=>(it(c,0),c.endVector()),W=a.createShellsVector(c,[]),V=a.createCircleExtrusionsVector(c,[]),D=k(a.startSamplesVector),f=k(a.startRepresentationsVector),Tt=k(a.startMaterialsVector),nt=k(a.startLocalTransformsVector),wt=k(a.startGlobalTransformsVector),Pt=a.createMeshesItemsVector(c,[]),tt=a.createMaterialIdsVector(c,[]),ct=a.createRepresentationIdsVector(c,[]),ht=a.createSampleIdsVector(c,[]),kt=a.createLocalTransformIdsVector(c,[]),te=a.createGlobalTransformIdsVector(c,[]);a.startMeshes(c),a.addCoordinates(c,d.createTransform(c,0,0,0,1,0,0,0,1,0)),a.addGlobalTransforms(c,wt),a.addShells(c,W),a.addRepresentations(c,f),a.addSamples(c,D),a.addLocalTransforms(c,nt),a.addMaterials(c,Tt),a.addCircleExtrusions(c,V),a.addMeshesItems(c,Pt),a.addRepresentationIds(c,ct),a.addSampleIds(c,ht),a.addMaterialIds(c,tt),a.addLocalTransformIds(c,kt),a.addGlobalTransformIds(c,te);const Wt=a.endMeshes(c),at=c.createString(r),st=new Set,pt=[];for(const it of this.changes){const _t=[],re={[sl]:it.op,...it.attrs};for(const[Nt,le]of Object.entries(re)){const me=JSON.stringify([Nt,le,"IFCTEXT"]);st.add(me),_t.push(c.createString(me))}pt.push(i.createAttribute(c,i.createDataVector(c,_t)))}{const it=JSON.stringify(["Name",n,"IFCLABEL"]);st.add(it);const _t=i.createDataVector(c,[c.createString(it)]);pt.push(i.createAttribute(c,_t))}const Bt=l.createAttributesVector(c,pt),qt=l.createUniqueAttributesVector(c,[...st].map(it=>c.createString(it))),jt=this.changes.map(()=>c.createString(Po));jt.push(c.createString(Lo));const Kt=l.createCategoriesVector(c,jt),Yt=[],zt=[];this.changes.forEach((it,_t)=>{it.item&&(Yt.push(c.createString(it.item)),zt.push(b[_t]))});const U=l.createGuidsVector(c,Yt),Z=l.createGuidsItemsVector(c,zt),L=l.createLocalIdsVector(c,[...b,F]),ut=this.changes.map((it,_t)=>p.createSpatialStructure(c,b[_t],c.createString(Po),0)),X=p.createSpatialStructure(c,F,c.createString(Lo),p.createChildrenVector(c,ut)),dt=c.createString(n);l.startModel(c),l.addMeshes(c,Wt),l.addMetadata(c,at),l.addAttributes(c,Bt),l.addUniqueAttributes(c,qt),l.addLocalIds(c,L),l.addCategories(c,Kt),l.addGuidsItems(c,Z),l.addGuids(c,U),l.addGuid(c,dt),l.addSpatialStructure(c,X),l.addMaxLocalId(c,$);const Mt=l.endModel(c);return l.finishModelBuffer(c,Mt),c.asUint8Array()}}async function al(){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 Bo(s){return Number.isFinite(s)?String(s):"0"}async function cl(s){const t=new Blob([s]).stream().pipeThrough(new CompressionStream("deflate"));return new Uint8Array(await new Response(t).arrayBuffer())}async function fs(s){const[t,e]=await ll(),n=e.Model.getRootAsModel(new t.ByteBuffer(await hl(s)));let r={};try{r=JSON.parse(n.metadata()??"{}")}catch{}const i=new Map;for(let l=0;l<n.guidsLength();l++){const p=n.guidsItems(l),d=n.guids(l);p!==null&&d&&i.set(p,d)}const a=[];for(let l=0;l<n.attributesLength();l++){const p=n.localIds(l);if(p===null)continue;const d={},c=n.attributes(l);for(let E=0;E<((c==null?void 0:c.dataLength())??0);E++){const b=c.data(E);if(b)try{const[$,F]=JSON.parse(b);d[$]=F}catch{}}a.push({localId:p,guid:i.get(p)??null,category:n.categories(l)??null,attrs:d})}return{metadata:r,items:a}}async function ll(){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 hl(s){const t=new Blob([s]).stream().pipeThrough(new DecompressionStream("deflate"));return new Uint8Array(await new Response(t).arrayBuffer())}const Ea="Element",Ta="Carried",nn=1/.3048;function Ma(s){const t=[];for(const e of s)for(const n of[Ea,Ta]){const r=e.attrs[n];if(r)try{const i=JSON.parse(r);for(const a of Array.isArray(i)?i:[i]){const l=a;typeof(l==null?void 0:l.id)!="string"||typeof(l==null?void 0:l.kind)!="string"||t.push({id:l.id,kind:l.kind,params:l.params??{},item:e})}}catch{}}return t}function de(s,t){const e=s.params[t];if(typeof e!="string")return null;try{return JSON.parse(e)}catch{return null}}function fl(s){const t=new Map;for(const[e,n]of dr(s))t.set(e,n.name);return t}function dr(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 $a(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 ur(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 ts(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 pr(s,t){var a,l;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=((l=(a=/\.([^.]+)$/.exec(t.name))==null?void 0:a[1])==null?void 0:l.toLowerCase())??"frag";let r=null,i=null;if(n!=="frag"){const p=s.client.recipes.importerFor(n);if(!p)throw new Error(`This app cannot read .${n} files: it provides no importer for them.`);n==="ifc"&&(r=Ia(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 p(e,t.name)}return{picked:t,contents:await fs(e),site:r,shapes:i}}function Ia(s){var wt;const t=new TextDecoder("latin1").decode(s),e=Pt=>new RegExp(`^${Pt}=\\s*([A-Z0-9_]+)\\((.*)\\);\\s*$`,"m").exec(t),n=Pt=>[...Pt.matchAll(/#\d+|\$/g)].map(tt=>tt[0]),r=Pt=>[...Pt.matchAll(/-?\d+(?:\.\d*)?(?:E[-+]?\d+)?/gi)].map(tt=>Number(tt[0])),i=/^(#\d+)=\s*IFCSITE\((.*)\);\s*$/m.exec(t);if(!i)return null;const a=(wt=i[2].split(",")[5])==null?void 0:wt.trim();if(!(a!=null&&a.startsWith("#")))return null;const l=e(a);if((l==null?void 0:l[1])!=="IFCLOCALPLACEMENT")return null;const[p,d]=n(l[2]);if(p!=="$"||!d)return null;const c=e(d);if((c==null?void 0:c[1])!=="IFCAXIS2PLACEMENT3D")return null;const[E,,b]=n(c[2]),$=E&&E!=="$"?e(E):null;if(!$)return null;const[F=0,k=0,W=0]=r($[2]);let V=0;const D=b&&b!=="$"?e(b):null;if(D){const[Pt=1,tt=0]=r(D[2]);V=Math.atan2(tt,Pt)*180/Math.PI}const f=/IFCSIUNIT\([^)]*\.LENGTHUNIT\.\s*,\s*(\.([A-Z]+)\.|\$)\s*,\s*\.METRE\./i.exec(t),Tt={MILLI:.001,CENTI:.01,DECI:.1,KILO:1e3},nt=f?f[2]?Tt[f[2].toUpperCase()]??1:1:/IFCCONVERSIONBASEDUNIT\([^)]*\.LENGTHUNIT\.[^)]*'FOOT'/i.test(t)?.3048:1;return{east:F*nt,north:k*nt,elevation:W*nt,angleDeg:V}}const mr="thatopen/recipe@1",jo="__project_data",Do="recipes",dl=s=>`${s}.recipe.json`,Sa={OperationBuilder:hs,OP_SCHEMA:fr,readFrag:fs,readPickedFrag:pr,recordsOf:Ma,innerJson:de,levelsOf:dr,levelNames:fl,stylesOf:$a,printOf:ts,siteLocationOf:Ia,whatItMadeBefore:ur,ELEMENT_FIELD:Ea,CARRIED_FIELD:Ta,FEET_PER_METRE:nn},xa=/^[a-z0-9][a-z0-9-]{1,62}$/;async function _a(s,t,e){const n=d=>[...d].sort((c,E)=>String(c._id).localeCompare(String(E._id)))[0],r=await s.listFolders({projectId:t,archived:!1});let i=n(r.filter(d=>d.name===jo&&!d.parentId));if(!i){if(!e)return null;i=await s.createFolder(jo,void 0,t)}const a=String(i._id),l=await s.listFolders({parentFolderId:a,projectId:t,archived:!1});let p=n(l.filter(d=>d.name===Do&&String(d.parentId)===a));if(!p){if(!e)return null;p=await s.createFolder(Do,a,t)}return String(p._id)}const ul=s=>String(s._id??s.id??""),pl=s=>String(s.tag??s.versionTag??""),Us=s=>{var t;return Number(((t=/(\d+)/.exec(s))==null?void 0:t[1])??-1)};async function yn(s,t){const e=await _a(s,t,!1);if(!e)return new Map;const n=await s.listFiles({folderId:e}),r=new Map;for(const i of n){const a=String(i.name??"");a.endsWith(".recipe.json")&&r.set(a.slice(0,-12),{id:ul(i)})}return r}async function Wn(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)!==mr||!((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 wn(s,t){return(await s.listVersions(t)).map(n=>({tag:pl(n),createdAt:String(n.createdAt??"")})).filter(n=>n.tag).sort((n,r)=>Us(n.tag)-Us(r.tag))}var kn;class Aa{constructor(t,e){Ht(this,kn,new Map);this.client=t,this.builtinNames=e}async list(t){const e=await yn(this.client,t);return(await Promise.all([...e.entries()].map(async([,{id:r}])=>{var i;try{const a=await wn(this.client,r),l=(i=a[a.length-1])==null?void 0:i.tag,p=await Wn(this.client,r,l);return{manifest:p.manifest,origin:"project",version:l,author:p.author,savedAt:p.savedAt}}catch{return null}}))).filter(r=>r!==null)}async versions(t,e){const n=(await yn(this.client,t)).get(e);if(!n)throw new Error(`The project has no recipe named "${e}".`);const r=await wn(this.client,n.id);return await Promise.all(r.map(async({tag:i,createdAt:a})=>{try{const l=await Wn(this.client,n.id,i);return{version:i,author:l.author,note:l.note,savedAt:l.savedAt??a}}catch{return{version:i,savedAt:a}}}))}async source(t,e,n){var a;const r=(await yn(this.client,t)).get(e);if(!r)throw new Error(`The project has no recipe named "${e}".`);const i=n??((a=(await wn(this.client,r.id)).pop())==null?void 0:a.tag);if(!i)throw new Error(`The recipe "${e}" has no saved version.`);return{...await Wn(this.client,r.id,i),version:i}}async save(t,e,n){const{manifest:r,code:i}=e;if(!xa.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 Js(r,i);const a={schema:mr,manifest:r,code:i,author:n.author,...n.note?{note:n.note}:{},savedAt:new Date().toISOString()},l=new Blob([JSON.stringify(a,null,2)],{type:"application/json"}),p=(await yn(this.client,t)).get(r.name);if(p){const c=await wn(this.client,p.id),E=`v${Math.max(0,...c.map(b=>Us(b.tag)))+1}`;return await this.client.createVersion(p.id,l,E),E}const d=await _a(this.client,t,!0);return await this.client.createFile({file:l,name:dl(r.name),versionTag:"v1",projectId:t,parentFolderId:d}),"v1"}async load(t,e,n){var p;const r=(await yn(this.client,t)).get(e);if(!r)throw new Error(`The project has no recipe named "${e}".`);const i=n??((p=(await wn(this.client,r.id)).pop())==null?void 0:p.tag);if(!i)throw new Error(`The recipe "${e}" has no saved version.`);const a=`${r.id}@${i}`;let l=j(this,kn).get(a);if(!l){const d=await Wn(this.client,r.id,i);l=await Js(d.manifest,d.code),j(this,kn).set(a,l)}return{recipe:l,version:i}}}kn=new WeakMap;async function Js(s,t){var r;let e;try{e=await import(`data:text/javascript;base64,${ml(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:Sa})}}function ml(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 gl(s){const t=s instanceof Uint8Array?s:new Uint8Array(await s.arrayBuffer()),{items:e,metadata:n}=await fs(t),r=e.filter(i=>i.attrs["flow:op"]).map(i=>{const a={};for(const[l,p]of Object.entries(i.attrs))l.startsWith("flow:")||(a[l]=p);return{op:i.attrs["flow:op"],...i.guid?{target:i.guid}:{},...i.attrs["flow:source"]?{source:i.attrs["flow:source"]}:{},attrs:a}});return{envelope:n??{},changes:r}}class gr extends Error{constructor(t){super(t),this.name="UpToDate"}}var Ne,Nn,Fn;class Ca{constructor(t){Ht(this,Ne,new Map);Ht(this,Nn,new Map);Ht(this,Fn,new Map);he(this,"project");this.client=t,this.project=new Aa(t,()=>new Set(j(this,Ne).keys()))}provideImporter(t,e){j(this,Nn).set(t.toLowerCase(),e)}provideShapes(t,e){j(this,Fn).set(t.toLowerCase(),e)}shapesFor(t){return j(this,Fn).get(t.toLowerCase())}importerFor(t){return j(this,Nn).get(t.toLowerCase())}register(t){if(j(this,Ne).has(t.name))throw new Error(`A recipe named "${t.name}" is already registered.`);j(this,Ne).set(t.name,t)}list(t){return[...j(this,Ne).values()].filter(n=>(!(t!=null&&t.to)||n.to===t.to)&&(!(t!=null&&t.input)||n.inputs.includes(t.input)))}get(t){return j(this,Ne).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,a)=>i.manifest.name.localeCompare(a.manifest.name))]}async resolve(t,e,n){const r=j(this,Ne).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()),l=(await this.client.documents(e).list()).filter(d=>d.descriptor.native&&(i.length===0||i.includes(d.descriptor.native.format.toLowerCase()))),p=await Ra(this.client,l.map(d=>d.descriptor.native.fileId));return l.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:p.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??cr(),input:e.input,settings:e.settings??{},progress:e.progress??(()=>{})})}}Ne=new WeakMap,Nn=new WeakMap,Fn=new WeakMap;async function Ra(s,t){const e=new Map;if(t.length===0)return e;const n=i=>{var a;return Number(((a=/(\d+)/.exec(String(i??"")))==null?void 0:a[1])??-1)},r=i=>{const l=i.slice().sort((p,d)=>{const c=p!=null&&p.createdAt?new Date(String(p.createdAt)).getTime():NaN,E=d!=null&&d.createdAt?new Date(String(d.createdAt)).getTime():NaN;return!Number.isNaN(c)&&!Number.isNaN(E)&&c!==E?E-c:n((d==null?void 0:d.tag)??(d==null?void 0:d.versionTag))-n((p==null?void 0:p.tag)??(p==null?void 0:p.versionTag))})[0];return l?String(l.tag??l.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 qs=100;function yl(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 wl(s){if(!s||typeof s!="object")return;const t=s.retryAfter;return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}class ds extends Error{constructor(e,n,r,i){const a=yl(r);super(a.message??`${n||"Request failed"} (${e})`);he(this,"status");he(this,"code");he(this,"details");he(this,"body");he(this,"retryAfter");this.name="RequestError",this.status=e,this.code=a.code,this.details=a.details,this.body=r,this.retryAfter=i??wl(a.details)}}const Te="item/folder",Lt="item",je="processor",bl="npm-registry",Ae="hidden",Es="FILE",Ts="TOOL",Ms="APP",vl=500,Uo=3e4,El=2e3,Tl=15e3,Ml=s=>/^\/?project\/permissions\/check/.test(s),$l=s=>/^\/?(item\/folder\/?$|item\/?$|item\/folder\/[^/]+\/items\/?$|project\/[^/]+\/data\/?$)/.test(s),bn=new Map,Il=.25,Sl=s=>new Promise(t=>setTimeout(t,s));function xl(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 _l(s){return s instanceof ds?s.status===429||s.status>=500:!0}function Al(s,t){const e=Math.min(vl*2**t,Uo),n=e*Il*Math.random(),r=s instanceof ds&&s.retryAfter!=null?s.retryAfter*1e3:void 0;return r!=null?Math.min(r,Uo)+n:e+n}var Y,es,vt,Gs,qe,Pn,In,ns,ss,Hs,Vs,zs;const br=class br{constructor(t,e,n){Ht(this,Y);he(this,"apiUrl");he(this,"accessToken");he(this,"wsUrl");he(this,"retries");he(this,"useBearer");he(this,"builtInGlobals",null);he(this,"localServerUrl",null);he(this,"context");Ht(this,Pn);const{retries:r=0,useBearer:i=!1,localServerUrl:a}=n||{};let l=e;if(l.charAt(l.length-1)==="/"&&(l=l.slice(0,-1)),this.apiUrl=`${l}/api`,this.accessToken=t,this.wsUrl=l,this.retries=r,this.useBearer=i,this.context={appId:"",projectId:"",accessToken:t,apiUrl:e},a){let p=a;p.charAt(p.length-1)==="/"&&(p=p.slice(0,-1)),this.localServerUrl=p}}static fromPlatformContext(t){const e=(typeof window<"u"?window.__THATOPEN_CONTEXT__:null)||{appId:"",projectId:"",accessToken:"",apiUrl:""},n=new br(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 I(this,Y,vt).call(this,t,e,n)}async listFiles(t){const{folderId:e,archived:n,projectId:r}=t||{};return e?await I(this,Y,vt).call(this,"GET",`${Te}/${e}/items`,{query:{itemType:Es,archived:n}}):await I(this,Y,vt).call(this,"GET",`${Lt}`,{query:{itemType:Es,archived:n,...r&&{projectId:r}}})}async listDocumentDescriptors(t){return await I(this,Y,vt).call(this,"GET",`${Lt}/documents`,{query:{projectId:t}})}async exportProjectDocuments(t,e){return(e==null?void 0:e.format)==="csv"?(await(await I(this,Y,vt).call(this,"GET",`${Lt}/export`,{query:{projectId:t,format:"csv"},responseType:"blob"})).text()).replace(/^/,""):await I(this,Y,vt).call(this,"GET",`${Lt}/export`,{query:{projectId:t}})}async getFile(t,e){return await I(this,Y,Vs).call(this,t,e)}async createFile(t){return await I(this,Y,ss).call(this,t,Es)}async updateFile(t,e){return await I(this,Y,Hs).call(this,t,e)}async archiveFile(t){return await I(this,Y,vt).call(this,"DELETE",`${Lt}/${t}`)}async recoverFile(t){return await I(this,Y,vt).call(this,"PUT",`${Lt}/${t}/recover`)}async downloadFile(t,e){return await I(this,Y,ns).call(this,t,e)}async getFileVersionMetadata(t,e,n){const{withDraft:r}=n||{};return await I(this,Y,vt).call(this,"GET",`${Lt}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/metadata`,{query:{...r&&{withDraft:"true"}}})}async updateFileVersionMetadata(t,e,n){return await I(this,Y,vt).call(this,"PUT",`${Lt}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/metadata`,{body:JSON.stringify({metadata:n}),contentType:"application/json"})}async deleteFileVersionMetadata(t,e){return await I(this,Y,vt).call(this,"DELETE",`${Lt}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/metadata`)}async getFileVersionMetadataBatch(t,e){const{withDraft:n}=e||{};return await I(this,Y,In).call(this,t,async r=>(await I(this,Y,vt).call(this,"POST",`${Lt}/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 I(this,Y,vt).call(this,"GET",Te,{query:{parentFolderId:n,archived:e,...r&&{projectId:r}}})}async getFolder(t){return await I(this,Y,vt).call(this,"GET",`${Te}/${t}`)}async getFoldersBatch(t){return await I(this,Y,In).call(this,t,async e=>(await I(this,Y,vt).call(this,"POST",`${Lt}/batch/folders`,{body:JSON.stringify({folderIds:e}),contentType:"application/json"})).results)}async createFolder(t,e,n){return await I(this,Y,vt).call(this,"POST",Te,{body:JSON.stringify({name:t,...e&&{parentId:e},...n&&{projectId:n}}),contentType:"application/json"})}async updateFolder(t,e){const{name:n}=e;return await I(this,Y,vt).call(this,"PUT",`${Te}/${t}`,{body:JSON.stringify({name:n}),contentType:"application/json"})}async archiveFolder(t){return await I(this,Y,vt).call(this,"DELETE",`${Te}/${t}`)}async recoverFolder(t){return await I(this,Y,vt).call(this,"PUT",`${Te}/${t}/recover`)}async downloadFolder(t){return await I(this,Y,qe).call(this,`${Te}/${t}/download`)}async listComponents(t){const{folderId:e,ShowVersions:n,projectId:r}=t||{};return e?await I(this,Y,vt).call(this,"GET",`${Te}/${e}/items`,{query:{itemType:Ts,...n&&{ShowVersions:n}}}):await I(this,Y,vt).call(this,"GET",`${Lt}`,{query:{itemType:Ts,...n&&{ShowVersions:n},...r&&{projectId:r}}})}async getComponent(t,e){return await I(this,Y,Vs).call(this,t,e)}async createComponent(t){const{componentProps:e}=t;return await I(this,Y,ss).call(this,t,Ts,e)}async updateComponent(t,e){const{componentProps:n}=e;return await I(this,Y,Hs).call(this,t,e,n)}async downloadComponent(t,e){return await I(this,Y,ns).call(this,t,e)}async downloadComponentBundle(t,e){const{versionTag:n,withDraft:r}=e||{};return await I(this,Y,qe).call(this,`${Lt}/${t}/download/bundle`,{query:{...n&&{versionTag:n},...r&&{withDraft:r}}})}async archiveComponent(t){return await I(this,Y,vt).call(this,"DELETE",`${Lt}/${t}`)}async recoverComponent(t){return await I(this,Y,vt).call(this,"PUT",`${Lt}/${t}/recover`)}async getBuiltInComponent(t){return await(await I(this,Y,qe).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:{})??{},a=Object.keys(i),l=a.map(E=>i[E]),d=new Function(...a,`${r}
2
+ return main;`)(...l),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 a,l;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(),(l=(a=this.context.appEventOrchestrator)==null?void 0:a.appLoaded)==null||l.call(a),{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 I(this,Y,vt).call(this,"GET",`${Te}/${e}/items`,{query:{itemType:Ms,...n&&{ShowVersions:n}}}):await I(this,Y,vt).call(this,"GET",`${Lt}`,{query:{itemType:Ms,...n&&{ShowVersions:n},...r&&{projectId:r}}})}async createApp(t){const{appProps:e}=t;return await I(this,Y,ss).call(this,t,Ms,e)}async downloadApp(t,e){return await I(this,Y,ns).call(this,t,e)}async downloadAppBundle(t,e){const{versionTag:n,withDraft:r}=e||{};return await I(this,Y,qe).call(this,`${Lt}/${t}/download/bundle`,{query:{...n&&{versionTag:n},...r&&{withDraft:r}}})}async archiveApp(t){return await I(this,Y,vt).call(this,"DELETE",`${Lt}/${t}`)}async getNpmCredentials(){return await I(this,Y,vt).call(this,"GET",`${bl}/credentials`)}async executeComponent(t,e,n){if(this.localServerUrl){const r=`${this.localServerUrl}/api/${je}/${t}/execute`,i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!i.ok){const a=await i.text().catch(()=>"");throw new Error(`Local server request failed: ${i.status} - ${a}`)}return await i.json()}return await I(this,Y,vt).call(this,"POST",`${je}/${t}/execute`,{body:JSON.stringify(e),query:{...n&&{versionTag:n}},contentType:"application/json"})}async abortExecution(t){if(this.localServerUrl){const e=`${this.localServerUrl}/api/${je}/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 I(this,Y,vt).call(this,"POST",`${je}/progress/${t}/abort`)}async listExecutions(t,e){if(this.localServerUrl){const n=e?`?projectId=${encodeURIComponent(e)}`:"",r=`${this.localServerUrl}/api/${je}/${t}/progress${n}`,i=await fetch(r);if(!i.ok){const a=await i.text().catch(()=>"");throw new Error(`Local server request failed: ${i.status} - ${a}`)}return await i.json()}return await I(this,Y,vt).call(this,"GET",`${je}/${t}/progress`,{query:{...e&&{projectId:e}}})}async getExecution(t){if(this.localServerUrl){const e=`${this.localServerUrl}/api/${je}/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 I(this,Y,vt).call(this,"GET",`${je}/progress/${t}`)}async onExecutionProgress(t,e){const n=this.localServerUrl??this.wsUrl,r=await xn(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 hr(this,t)}history(t){return new or(this,t)}get recipes(){return j(this,Pn)??Xt(this,Pn,new Ca(this)),j(this,Pn)}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 I(this,Y,vt).call(this,"POST",`${Lt}/${Ae}`,{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 I(this,Y,vt).call(this,"POST",`${Lt}/${Ae}/batch`,{body:r})}async deleteHiddenFile(t){return await I(this,Y,vt).call(this,"DELETE",`${Lt}/${Ae}/${t}`)}async getHiddenFile(t){return await I(this,Y,vt).call(this,"GET",`${Lt}/${Ae}/${t}`)}async downloadHiddenFile(t){return await I(this,Y,qe).call(this,`${Lt}/${Ae}/${t}/download`)}async getHiddenFileSignedUrl(t,e){return await I(this,Y,vt).call(this,"GET",`${Lt}/${Ae}/${t}/signed-url`,{...e!=null&&{query:{expiresIn:e}}})}async getHiddenFileSignedUrlsBatch(t,e){return await I(this,Y,In).call(this,t,async n=>(await I(this,Y,vt).call(this,"POST",`${Lt}/${Ae}/signed-url/batch`,{body:JSON.stringify({hiddenFileIds:n,...e!=null&&{expiresIn:e}}),contentType:"application/json"})).results)}async getHiddenFilesByParent(t,e){return await I(this,Y,vt).call(this,"GET",`${Lt}/${t}/${Ae}`,{...e!=null&&{query:{tag:e}}})}async deleteHiddenFilesByParent(t){return await I(this,Y,vt).call(this,"DELETE",`${Lt}/${t}/${Ae}`)}async uploadItemIcon(t,e){const n=new FormData;return n.append("icon",e),await I(this,Y,vt).call(this,"PUT",`${Lt}/${t}/icon`,{body:n})}async getItemIcon(t){return await I(this,Y,qe).call(this,`${Lt}/${t}/icon`)}async removeItemIcon(t){return await I(this,Y,vt).call(this,"DELETE",`${Lt}/${t}/icon`)}async updateItem(t,e){return await I(this,Y,vt).call(this,"PUT",`${Lt}/${t}`,{body:JSON.stringify(e),contentType:"application/json"})}async createVersion(t,e,n,r,i){const a=new FormData;a.append("file",e),a.append("versionTag",n),r&&a.append("extraProps",JSON.stringify(r));const l=await I(this,Y,vt).call(this,"POST",`${Lt}/${t}/version`,{body:a});return i&&await this.updateFileVersionMetadata(t,(l==null?void 0:l.tag)??n,i),l}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 I(this,Y,vt).call(this,"GET",`${Lt}/${encodeURIComponent(t)}/versions`,{query:e})}async listVersionsBatch(t,e={}){const{archived:n}=e;return await I(this,Y,In).call(this,t,async r=>(await I(this,Y,vt).call(this,"POST",`${Lt}/batch/versions`,{body:JSON.stringify({itemIds:r,...n!==void 0&&{archived:n}}),contentType:"application/json"})).results)}async archiveVersion(t,e){return await I(this,Y,vt).call(this,"PUT",`${Lt}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/archive`)}async recoverVersion(t,e){return await I(this,Y,vt).call(this,"PUT",`${Lt}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/recover`)}async deleteVersion(t,e){return await I(this,Y,vt).call(this,"DELETE",`${Lt}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}`)}};Y=new WeakSet,es=function(t){return`${this.apiUrl}/${t}`},vt=async function(t,e,n){if(t==="GET"&&(n==null?void 0:n.responseType)!=="blob"&&!(n!=null&&n.retryAttempt)){const r=`${I(this,Y,es).call(this,e)}?${new URLSearchParams(I(this,Y,zs).call(this,n==null?void 0:n.query)).toString()}`,i=Date.now(),a=bn.get(r);if(a&&(a.pending||i-a.at<($l(e)?Tl:El)))return a.answer.then(p=>p===void 0?p:structuredClone(p));const l={at:i,pending:!0,answer:I(this,Y,Gs).call(this,t,e,n)};return bn.set(r,l),l.answer.then(()=>{l.pending=!1,l.at=Date.now()},()=>{bn.get(r)===l&&bn.delete(r)}),l.answer.then(p=>p===void 0?p:structuredClone(p))}return t!=="GET"&&!Ml(e)&&bn.clear(),I(this,Y,Gs).call(this,t,e,n)},Gs=async function(t,e,n){const{body:r,query:i,contentType:a,retries:l,responseType:p,retryAttempt:d}=n||{},c=I(this,Y,es).call(this,e),E=I(this,Y,zs).call(this,i),b=await this.resolveAccessToken(),$={...E,...this.useBearer?{}:{accessToken:b}};try{const F=await fetch(c+"?"+new URLSearchParams($).toString(),{method:t,headers:{Accept:"application/json",...a&&{"Content-Type":a},...this.useBearer&&{Authorization:`Bearer ${b}`}},...r&&{body:r}});if(!F.ok){const k=await F.text().then(W=>W).catch(()=>"");throw new ds(F.status,F.statusText,k,xl(F))}return p==="blob"?await F.blob():F.json().then(k=>k).catch(()=>{})}catch(F){const k=l??this.retries;if(k>0&&_l(F)){const W=d??0;return await Sl(Al(F,W)),await I(this,Y,vt).call(this,t,e,{...n,retries:k-1,retryAttempt:W+1})}throw F}},qe=async function(t,e){const{query:n}=e||{},r=I(this,Y,es).call(this,t),i=await this.resolveAccessToken(),a={...n,...this.useBearer?{}:{accessToken:i}};return await fetch(r+"?"+new URLSearchParams(a).toString(),{method:"GET",...this.useBearer&&{headers:{Authorization:`Bearer ${i}`}}})},Pn=new WeakMap,In=async function(t,e){if(!t.length)return[];const n=[];for(let i=0;i<t.length;i+=qs)n.push(t.slice(i,i+qs));return(await Promise.all(n.map(e))).flat()},ns=async function(t,e){const{versionTag:n,withDraft:r}=e||{},i=await I(this,Y,qe).call(this,`${Lt}/${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},ss=async function(t,e,n){const{name:r,versionTag:i,parentFolderId:a,projectId:l,file:p,metadata:d}=t,c=new FormData;return c.append("file",p),c.append("name",r),c.append("versionTag",i),c.append("itemType",e),a&&c.append("folderId",a),l&&c.append("projectId",l),n&&c.append("extraProps",JSON.stringify(n)),d&&c.append("metadata",JSON.stringify(d)),await I(this,Y,vt).call(this,"POST",Lt,{body:c})},Hs=async function(t,e,n){const{name:r,versionTag:i,parentFolderId:a,file:l,metadata:p}=e;let d,c;if(l){const E=new FormData;E.append("file",l),i&&E.append("versionTag",i),n&&E.append("extraProps",JSON.stringify(n)),c=await I(this,Y,vt).call(this,"POST",`${Lt}/${t}/version`,{body:E});const b=(c==null?void 0:c.tag)??i;p&&b&&await this.updateFileVersionMetadata(t,b,p)}if(r||a){const E={...r&&{name:r},...a&&{folderId:a}},b=JSON.stringify(E);d=await I(this,Y,vt).call(this,"PUT",`${Lt}/${t}`,{body:b,contentType:"application/json"})}return{item:d,version:c}},Vs=async function(t,e){const{showVersions:n=!1}=e||{};return await I(this,Y,vt).call(this,"GET",`${Lt}/${t}`,{query:{showVersions:n}})},zs=function(t){return t&&Object.entries(t).filter(([,e])=>e!==void 0).reduce((e,[n,r])=>(e[n]=r,e),{})};let as=br;function Oa(){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 Ws="channel:",Cl=1e4;function rs(s){try{s()}catch(t){console.error("[channel] a listener threw:",t)}}var Fe,ge,ye,rn,on,an,ue,Ys,Ks,en;class yr{constructor(t,e){Ht(this,ue);Ht(this,Fe,!1);Ht(this,ge,[]);Ht(this,ye,[]);Ht(this,rn,new Set);Ht(this,on,new Set);Ht(this,an,new Set);this.transport=t,this.controls=e}get joined(){return j(this,Fe)}get peers(){return j(this,ge)}join(){return j(this,Fe)?Promise.resolve():I(this,ue,Ys).call(this,"joined",this.controls.join)}leave(){return!j(this,Fe)&&!j(this,ye).some(t=>t.want==="joined")?Promise.resolve():I(this,ue,Ys).call(this,"left",this.controls.leave)}onChange(t){return j(this,rn).add(t),()=>void j(this,rn).delete(t)}onPeerJoined(t){return j(this,on).add(t),()=>void j(this,on).delete(t)}onPeerLeft(t){return j(this,an).add(t),()=>void j(this,an).delete(t)}applyJoined(){Xt(this,Fe,!0),I(this,ue,Ks).call(this,"joined"),I(this,ue,en).call(this)}applyLeft(){Xt(this,Fe,!1),Xt(this,ge,[]),I(this,ue,Ks).call(this,"left"),I(this,ue,en).call(this)}applyPeers(t){Xt(this,ge,t),I(this,ue,en).call(this)}applyPeerJoined(t){!j(this,Fe)||j(this,ge).some(e=>e.from===t.from)||(Xt(this,ge,[...j(this,ge),t]),j(this,on).forEach(e=>rs(()=>e(t))),I(this,ue,en).call(this))}applyPeerLeft(t){const e=j(this,ge).find(n=>n.from===t);e&&(Xt(this,ge,j(this,ge).filter(n=>n.from!==t)),j(this,an).forEach(n=>rs(()=>n(e))),I(this,ue,en).call(this))}failPending(t){const e=j(this,ye);return Xt(this,ye,[]),e.forEach(n=>{clearTimeout(n.timer),n.reject(t)}),e.length>0}post(t){this.transport.post(t)}}Fe=new WeakMap,ge=new WeakMap,ye=new WeakMap,rn=new WeakMap,on=new WeakMap,an=new WeakMap,ue=new WeakSet,Ys=function(t,e){return new Promise((n,r)=>{const i={want:t,resolve:n,reject:r,timer:setTimeout(()=>{Xt(this,ye,j(this,ye).filter(a=>a!==i)),r(new Error(`The platform did not confirm ${t==="joined"?"joining":"leaving"} in time.`))},Cl)};j(this,ye).push(i),this.transport.post({type:"APP_CHANNEL_CONTROL",...e})})},Ks=function(t){const e=j(this,ye).filter(n=>n.want===t);Xt(this,ye,j(this,ye).filter(n=>n.want!==t)),e.forEach(n=>{clearTimeout(n.timer),n.resolve()})},en=function(){j(this,rn).forEach(t=>rs(t))};var cn;class ka extends yr{constructor(e){super(e,{join:{action:"joinCollab"},leave:{action:"leaveCollab"}});Ht(this,cn,new Map)}on(e,n){const r=j(this,cn).get(e)??new Set;return r.add(n),j(this,cn).set(e,r),()=>void r.delete(n)}send(e,n){if(e.startsWith(Ws))throw new Error(`Message types starting with '${Ws}' 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=j(this,cn).get(e.type);if(!(n!=null&&n.size))return{handled:!1};const r=Fa(e);return n.forEach(i=>rs(()=>i(e.payload,r))),{handled:!0}}}cn=new WeakMap;var Ge;class Na extends yr{constructor(e,n){super(e,{join:{action:"joinExternal",kind:n},leave:{action:"leaveExternal",kind:n}});Ht(this,Ge,new Map);this.kind=n}on(e,n){if(j(this,Ge).has(e))throw new Error(`"${e}" already has a handler in this room. Remove it first.`);return j(this,Ge).set(e,n),()=>void j(this,Ge).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 j(this,Ge).size>0}async handle(e){const n=j(this,Ge).get(e.type);if(!n)return{handled:!1};try{return{handled:!0,value:await n(e.payload,Fa(e))}}catch(r){return{handled:!0,error:r instanceof Error?r.message:String(r)}}}}Ge=new WeakMap;function Fa(s){return{from:s.from,at:s.at,requestId:s.requestId,kind:s.kind}}function Rl(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 Ye,Ln,Pe,He,Ve,ce,Xs,is,La,Ba,ja,Zs;class Pa{constructor(t){Ht(this,ce);Ht(this,Ye);Ht(this,Ln);Ht(this,Pe);Ht(this,He,new Map);Ht(this,Ve,new Set);Xt(this,Ye,t),Xt(this,Ln,t.listen(e=>void I(this,ce,La).call(this,e)))}collab(){return j(this,Pe)??Xt(this,Pe,new ka(j(this,Ye))),j(this,Pe)}external(t){const e=t??"";let n=j(this,He).get(e);return n||(n=new Na(j(this,Ye),t),j(this,He).set(e,n)),n}dispose(){j(this,Ln).call(this)}}Ye=new WeakMap,Ln=new WeakMap,Pe=new WeakMap,He=new WeakMap,Ve=new WeakMap,ce=new WeakSet,Xs=function(){return[...j(this,Pe)?[j(this,Pe)]:[],...j(this,He).values()]},is=function(t,e){if(t==="collab")return j(this,Pe);if(t==="external")return j(this,He).get(typeof e=="string"?e:"")},La=async function(t){const e=Rl(t);if(e){if(e.type.startsWith(Ws)){I(this,ce,Ba).call(this,e);return}await I(this,ce,ja).call(this,e)}},Ba=function(t){var n,r,i;const e=t.payload??{};switch(t.type){case"channel:joined":(n=I(this,ce,is).call(this,e.scope,e.kind))==null||n.applyJoined();break;case"channel:left":(r=I(this,ce,is).call(this,e.scope,e.kind))==null||r.applyLeft();break;case"channel:peers":(i=I(this,ce,is).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 a=e.scope==="collab"?[j(this,Pe)]:[...j(this,He).values()].filter(l=>l.accepts("external",e.kind));for(const l of a)t.type==="channel:peer-joined"?l==null||l.applyPeerJoined({from:e.from,kind:e.kind}):l==null||l.applyPeerLeft(e.from);break}case"channel:error":{const a=new Error(String(t.payload));I(this,ce,Xs).call(this).map(p=>p.failPending(a)).some(Boolean)||console.error("[channel] error:",t.payload);break}}},ja=async function(t){const e=I(this,ce,Xs).call(this).filter(i=>i.accepts(t.scope,t.kind));let n=!1;for(const i of e){const a=await i.handle(t);a.handled&&(n=!0,t.requestId&&I(this,ce,Zs).call(this,t.requestId,a))}t.requestId&&t.scope==="external"&&e.length>0&&!n&&I(this,ce,Zs).call(this,t.requestId,{handled:!0,error:`No handler for "${t.type}".`})},Zs=function(t,e){j(this,Ve).has(t)||(j(this,Ve).add(t),j(this,Ve).size>500&&j(this,Ve).delete(j(this,Ve).values().next().value),j(this,Ye).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 ae="project",Ze="notifications",vn="tokens";var ln,Bn;const vr=class vr extends as{constructor(e,n,r){super(typeof e=="string"?e:"",n,{...r,useBearer:!0});Ht(this,ln);Ht(this,Bn);typeof e=="function"&&Xt(this,ln,e)}async resolveAccessToken(){return j(this,ln)?await j(this,ln).call(this):super.resolveAccessToken()}static fromPlatformContext(e){const n=(typeof window<"u"?window.__THATOPEN_CONTEXT__:null)||{appId:"",projectId:"",accessToken:"",apiUrl:""},r=new vr(n.accessToken,n.apiUrl,e);return r.context=n,r}get channel(){return j(this,Bn)??Xt(this,Bn,new Pa(Oa())),j(this,Bn)}async listProjects(){return await this.request("GET",ae)}async getProject(e){return await this.request("GET",`${ae}/${e}`)}async getProjectData(e){return await this.request("GET",`${ae}/${e}/data`)}async listMembers(e){return await this.request("GET",`${ae}/${e}/users`)}async addMember(e,n,r){return await this.request("POST",`${ae}/${e}/user`,{body:JSON.stringify({accountId:n,...r&&{projectRoleId:r}}),contentType:"application/json"})}async setMemberRole(e,n,r){return await this.request("PUT",`${ae}/${e}/user/${n}`,{body:JSON.stringify({projectRoleId:r}),contentType:"application/json"})}async removeMember(e,n){return await this.request("DELETE",`${ae}/${e}/user/${n}`)}async inviteMember(e,n,r){return await this.request("POST",`${ae}/${e}/invite`,{body:JSON.stringify({email:n,...r&&{projectRoleId:r}}),contentType:"application/json"})}async listInvitations(e){return await this.request("GET",`${ae}/${e}/invites`)}async cancelInvitation(e,n){return await this.request("DELETE",`${ae}/${e}/invite/${n}`)}async listRoles(e){return await this.request("GET",`${ae}/${e}/roles`)}async createRole(e,n){return await this.request("POST",`${ae}/${e}/role`,{body:JSON.stringify(n),contentType:"application/json"})}async updateRole(e,n){return await this.request("PUT",`${ae}/role/${e}`,{body:JSON.stringify(n),contentType:"application/json"})}async deleteRole(e){return await this.request("DELETE",`${ae}/role/${e}`)}async getPermissionMatrix(e){const[n,r]=await Promise.all([this.listRoles(e),this.listMembers(e)]);return n.map(i=>({role:i,permissions:i.permissions??[],members:r.filter(a=>{var l;return String((l=a.role)==null?void 0:l._id)===String(i._id)}).map(a=>a.user)}))}async listTokens(){return await this.request("GET",vn)}async getTokenSecret(e){return await(await this.request("GET",`${vn}/${e}/token`,{responseType:"blob"})).text()}async createToken(e){return await this.request("POST",vn,{body:JSON.stringify({urlRestrictions:[],...e}),contentType:"application/json"})}async updateToken(e,n){return await this.request("PUT",`${vn}/${e}`,{body:JSON.stringify(n),contentType:"application/json"})}async revokeToken(e){return await this.request("DELETE",`${vn}/${e}`)}async getAvatar(e){return await this.request("GET",`account/${e}/avatar`,{responseType:"blob"})}async checkPermission(e){return await this.request("GET",`${ae}/permissions/check`,{query:e})}async checkPermissionBatch(e){return(await this.request("POST",`${ae}/permissions/check/batch`,{body:JSON.stringify({checks:e}),contentType:"application/json"})).results}async getNotifications(e){return await this.request("GET",Ze,{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",`${Ze}/unread-count`)).count}async markNotificationsRead(e){return await this.request("POST",`${Ze}/mark-read`,{body:JSON.stringify({ids:e}),contentType:"application/json"})}async markAllNotificationsRead(){return await this.request("POST",`${Ze}/mark-all-read`)}async getNotificationSubscriptions(){return await this.request("GET",`${Ze}/subscriptions`)}async unsubscribeFromAutomation(e){return await this.request("DELETE",`${Ze}/subscriptions/${e}`)}async subscribeToAutomation(e,n,r){return await this.request("POST",`${ae}/${e}/events/hooks/${n}/subscription`,{body:JSON.stringify(r??{}),contentType:"application/json"})}async updateAutomationSubscription(e,n,r){return await this.request("PATCH",`${ae}/${e}/events/hooks/${n}/subscription`,{body:JSON.stringify(r),contentType:"application/json"})}async onNotification(e){const n=await this.resolveAccessToken(),r=xn(`${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()}};ln=new WeakMap,Bn=new WeakMap;let Qs=vr;const Ce=1/.3048,Ol={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"},kl="OST_GenericModel",Nl=new Set(["IFCSPACE","IFCOPENINGELEMENT","IFCSITE","IFCANNOTATION","IFCGRID","IFCVIRTUALELEMENT","IFCBUILDING","IFCBUILDINGSTOREY"]),Oe=(s,t)=>Math.round(s/t)*t,Fl=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]]}),_n=(s,t)=>s[0]*t[0]+s[1]*t[1]+s[2]*t[2],$s=s=>Math.sqrt(_n(s,s)),sn=(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 Pl(s,t,e,n){var d,c,E;const r=new Set,i=new Map;for(const b of t){const[,$,F]=b.split(":");$&&(/^datum/.test(F??"")||(r.add($),i.has($)||i.set($,b)))}const a=new Map,l=new Map,p=[];for(const b of s.elements.values()){if(r.has(b.gid)||Nl.has(b.ifcClass.toUpperCase())||b.parent&&r.has(b.parent)&&!/^IFC(DOOR|WINDOW)$/i.test(b.ifcClass)&&!(n!=null&&n.has(b.gid))||b.pieces.length===0)continue;const F=/^IFCCOLUMN$/i.test(b.ifcClass)&&(b.loadBearing||/structural|estructural|结构柱|tragend|tragwerk/i.test(`${b.typeName??""} ${b.objectType??""} ${b.name??""}`))?"OST_StructuralColumns":Ol[b.ifcClass.toUpperCase()]??kl,k=Fl(b.pieces[0].matrix),W=$s(k.x),V=$s(k.y),D=$s(k.z),f=k.z.map(U=>U/(D||1)),Tt=Math.abs(f[2]-1)<1e-6&&_n(sn(k.x,k.y),k.z)>0&&Math.abs(W-V)<1e-6&&Math.abs(W-D)<1e-6,nt=_n(sn(k.x,k.y),k.z)>0&&Math.abs(W-V)<1e-6&&Math.abs(W-D)<1e-6,wt=[k.x,k.y,k.z].map(U=>U.map(Z=>Z/(W||1))),Pt=nt&&!Tt&&wt.some(U=>Math.abs(Math.abs(U[2])-1)<1e-6)?wt.find(U=>Math.abs(U[2])<1e-6):void 0,tt=Tt?Math.atan2(k.x[1],k.x[0]):Pt?Math.atan2(Pt[1],Pt[0]):0,ct=Math.cos(-tt),ht=Math.sin(-tt),kt=[k.t[0],k.t[1],k.t[2]],te=/COLUMN/i.test(F),Wt=U=>{const Z=U[0]-kt[0],L=U[1]-kt[1];return[ct*Z-ht*L,ht*Z+ct*L,U[2]-kt[2]]},at=[],st=[F];for(const U of b.pieces){const Z=s.geometries.get(U.geometry);if(!Z)continue;const L=U.matrix,ut=[];for(let Nt=0;Nt<Z.verts.length;Nt+=3){const le=Z.verts[Nt],me=Z.verts[Nt+1],Le=Z.verts[Nt+2],ie=[L[0]*le+L[4]*me+L[8]*Le+L[12],L[1]*le+L[5]*me+L[9]*Le+L[13],L[2]*le+L[6]*me+L[10]*Le+L[14]],Ke=Wt(ie);ut.push(Oe(Ke[0]*Ce,1e-5),Oe(Ke[1]*Ce,1e-5),Oe(Ke[2]*Ce,1e-5))}const X=_n(sn([L[0],L[1],L[2]],[L[4],L[5],L[6]]),[L[8],L[9],L[10]])<0,dt=[];for(let Nt=0;Nt+2<Z.tris.length;Nt+=3)X?dt.push(Z.tris[Nt],Z.tris[Nt+2],Z.tris[Nt+1]):dt.push(Z.tris[Nt],Z.tris[Nt+1],Z.tris[Nt+2]);dt.length&&at.push({v:ut,t:dt});const Mt=Wt([L[12],L[13],L[14]]),it=[ct*L[0]-ht*L[1],ht*L[0]+ct*L[1],L[2]],_t=[ct*L[4]-ht*L[5],ht*L[4]+ct*L[5],L[6]],re=[ct*L[8]-ht*L[9],ht*L[8]+ct*L[9],L[10]];st.push(`${U.geometry}@${[...Mt,...it,..._t,...re].map(Nt=>Oe(Nt,1e-4).toFixed(4)).join(",")}`)}if(at.length===0)continue;const pt=!b.host&&at.length===1?jl(at[0]):null;if(pt){const U=Bl(pt),Z=U.key,L=`prism|${F}|${U.axis}|${Z}`;let ut=a.get(L);if(!ut){const le=Jo(b.typeName??b.objectType??b.name??b.ifcClass),me=(l.get(le.toLowerCase())??0)+1;l.set(le.toLowerCase(),me);const Le=me===1?le:`${le} (${me})`;ut={family:Le,type:Le,first:!0,key:qo(L)},a.set(L,ut)}const X={ShapeCategory:F,Family:ut.family,Type:ut.type,ShapeKey:ut.key,PrismLength:String(Oe(pt.length,1e-5)),...te?{ColumnFree:"1"}:{}};ut.first&&(X.Prism=JSON.stringify({axis:U.axis,loops:U.loops}),ut.first=!1);const dt=[0,0,0];dt[pt.axis]=(U.flipped?pt.from+pt.length:pt.from)/Ce;const Mt=(pt.axis+1)%3,it=(pt.axis+2)%3;dt[Mt]+=U.centre[0]/Ce,dt[it]+=U.centre[1]/Ce;const _t=Math.cos(tt),re=Math.sin(tt),Nt=[kt[0]+_t*dt[0]-re*dt[1],kt[1]+re*dt[0]+_t*dt[1],kt[2]+dt[2]];p.push({key:`${e}:${b.gid}:shape`,attrs:X,at:Nt,rotationDeg:(tt+U.turn)*180/Math.PI});continue}const Bt=`${F}|${at.map(U=>`${U.v.map(Z=>Math.round(Z*304.8/2)).join(",")}/${U.t.join(",")}`).join("|")}`,qt=st.join("|");let jt=a.get(qt)??a.get(Bt);if(jt&&(a.set(qt,jt),a.set(Bt,jt)),!jt){const U=Jo(b.typeName??b.objectType??b.name??b.ifcClass),Z=(l.get(U.toLowerCase())??0)+1;l.set(U.toLowerCase(),Z);const L=Z===1?U:`${U} (${Z})`;jt={family:L,type:L,first:!0,key:qo(Bt)},a.set(Bt,jt),a.set(qt,jt)}const Kt={ShapeCategory:F,Family:jt.family,Type:jt.type,ShapeKey:jt.key,...te?{ColumnFree:"1"}:{}};jt.first&&(Kt.Shape=JSON.stringify({pieces:at}),jt.first=!1);const Yt=b.host?i.get(b.host):void 0,zt=b.opening?s.elements.get(b.opening):void 0;if(Yt&&zt){const U=[1/0,1/0,1/0],Z=[-1/0,-1/0,-1/0];for(const L of zt.pieces){const ut=s.geometries.get(L.geometry);if(!ut)continue;const X=L.matrix;for(let dt=0;dt<ut.verts.length;dt+=3){const Mt=ut.verts[dt],it=ut.verts[dt+1],_t=ut.verts[dt+2],re=Wt([X[0]*Mt+X[4]*it+X[8]*_t+X[12],X[1]*Mt+X[5]*it+X[9]*_t+X[13],X[2]*Mt+X[6]*it+X[10]*_t+X[14]]);for(let Nt=0;Nt<3;Nt++)U[Nt]=Math.min(U[Nt],re[Nt]*Ce),Z[Nt]=Math.max(Z[Nt],re[Nt]*Ce)}}{const L=tr(s,zt.gid).flatMap(dt=>dt.pts).map(dt=>Wt(dt).map(Mt=>Mt*Ce)),ut=new Map;for(const dt of L){const Mt=Math.round(dt[1]*200);ut.set(Mt,[...ut.get(Mt)??[],dt])}let X=null;for(const dt of ut.values()){if(dt.length<4)continue;const Mt=[Math.min(...dt.map(it=>it[0])),Math.max(...dt.map(it=>it[0])),Math.min(...dt.map(it=>it[2])),Math.max(...dt.map(it=>it[2]))];Mt[1]-Mt[0]<.1||Mt[3]-Mt[2]<.1||(!X||(Mt[1]-Mt[0])*(Mt[3]-Mt[2])<(X[1]-X[0])*(X[3]-X[2])-1e-6)&&(X=Mt)}if(X&&ut.size>2&&(U[0]=X[0],Z[0]=X[1],U[2]=X[2],Z[2]=X[3]),X&&ut.size>2){const dt=[...ut.entries()].sort((it,_t)=>it[0]-_t[0]).map(([,it])=>({y:it[0][1],r:[Math.min(...it.map(_t=>_t[0])),Math.max(...it.map(_t=>_t[0])),Math.min(...it.map(_t=>_t[2])),Math.max(...it.map(_t=>_t[2]))]})),Mt=[];for(let it=0;it+1<dt.length;it++){const _t=dt[it].r,re=dt[it+1].r,Nt=[Math.max(_t[0],re[0]),Math.min(_t[1],re[1]),Math.max(_t[2],re[2]),Math.min(_t[3],re[3])];Nt[1]-Nt[0]<.1||Nt[3]-Nt[2]<.1||dt[it+1].y-dt[it].y<.01||(Nt[0]<X[0]-.016||Nt[1]>X[1]+.016||Nt[2]<X[2]-.016||Nt[3]>X[3]+.016)&&Mt.push([Nt[0],dt[it].y,Nt[2],Nt[1],dt[it+1].y,Nt[3]].map(le=>Oe(le,1e-5)))}Mt.length&&(Kt.OpeningSteps=JSON.stringify(Mt)),typeof process<"u"&&((d=process.env)!=null&&d.RECIPE_TRACE)&&console.error(`[opening-steps] ${b.gid}: ${dt.length} planes, narrowest ${JSON.stringify(X.map(it=>+it.toFixed(3)))}, steps ${JSON.stringify(Mt)}`)}}if(Number.isFinite(U[0])&&(Kt.Opening=[...U,...Z].map(L=>Oe(L,1e-5)).join(",")),typeof process<"u"&&((c=process.env)!=null&&c.RECIPE_CUT_LOST)&&b.host&&Number.isFinite(U[0])){const L=tr(s,zt.gid).flatMap(X=>X.pts),ut=Qt(s,b.host);if(L.length&&ut.length){const X=[0,1,2].map(_t=>Math.min(...L.map(re=>re[_t]))-.01),dt=[0,1,2].map(_t=>Math.max(...L.map(re=>re[_t]))+.01),Mt=Math.min(...ut.map(_t=>_t[2]))+.01,it=ut.filter(_t=>_t[0]>X[0]&&_t[0]<dt[0]&&_t[1]>X[1]&&_t[1]<dt[1]&&_t[2]>Math.max(X[2],Mt)&&_t[2]<dt[2]).length;it>=4&&(Kt.CutIfLost="1"),(E=process.env)!=null&&E.RECIPE_TRACE&&console.error(`[cut-if-lost] ${b.gid}: ${it} of its wall's corners in its opening → ${it>=4?"cut":"not"}`)}}}p.push({key:`${e}:${b.gid}:shape`,attrs:Kt,at:[kt[0],kt[1],kt[2]],rotationDeg:tt*180/Math.PI,...Yt?{host:Yt}:{}})}return p}function Jo(s){return(s.replace(/[\\:{}[\]|;<>?`~]/g,"-").replace(/\s+/g," ").trim()||"Shape").slice(0,120)}function qo(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 Ll(s,t,e){var i,a;const n=new Map;for(const l of t){const[,p,d]=l.split(":");p&&/^run/.test(d??"")&&!n.has(p)&&n.set(p,l)}const r=[];for(const l of s.elements.values()){if(l.ifcClass.toUpperCase()!=="IFCOPENINGELEMENT"||!l.host)continue;const p=n.get(l.host),d=typeof process<"u"&&((i=process.env)==null?void 0:i.RECIPE_TRACE);if(!p){d&&console.error(`[opening] ${l.gid}: its wall ${l.host} not written as a run`);continue}for(const c of tr(s,l.gid)){const E=c.pts;if(E.length<4)continue;const b=Ul(Qt(s,l.host));if(!b)continue;const $=E.map(D=>(D[0]-b.a[0])*b.u[0]+(D[1]-b.a[1])*b.u[1]),F=E.map(D=>-(D[0]-b.a[0])*b.u[1]+(D[1]-b.a[1])*b.u[0]),k=D=>Math.max(...D)-Math.min(...D),W=k($)*k(F)*k(E.map(D=>D[2]));if(!(W>0)||Math.abs(c.volume)<.75*W){d&&console.error(`[opening] ${l.gid}: not a box (${c.volume.toFixed(3)} of ${W.toFixed(3)}: ${k($).toFixed(3)} along ${k(F).toFixed(3)} across ${k(E.map(D=>D[2])).toFixed(3)} up, axis ${JSON.stringify(b.u.map(D=>+D.toFixed(3)))})`);continue}const V=Qt(s,l.host).map(D=>-(D[0]-b.a[0])*b.u[1]+(D[1]-b.a[1])*b.u[0]);if(V.length&&(Math.min(...F)>Math.min(...V)+.005||Math.max(...F)<Math.max(...V)-.005)){d&&console.error(`[opening] ${l.gid}: not through its wall (across ${Math.min(...F).toFixed(3)}..${Math.max(...F).toFixed(3)}, its wall ${Math.min(...V).toFixed(3)}..${Math.max(...V).toFixed(3)})`);continue}d&&((a=process.env)==null?void 0:a.RECIPE_GID)===l.gid&&console.error(`[opening] ${l.gid} part ${c.index}/${c.of}: a box (${c.volume.toFixed(4)} of ${W.toFixed(4)}: ${k($).toFixed(3)} along ${k(F).toFixed(3)} across ${k(E.map(D=>D[2])).toFixed(3)} up, ${E.length} points)`),r.push({key:`${e}:${l.gid}:opening${c.index===0&&c.of===1?"":`#${c.index}`}`,host:p,box:E.flat()})}}return r}function Bl(s){const t=s.loops.flat(),e=[t.reduce((b,$)=>b+$[0],0)/t.length,t.reduce((b,$)=>b+$[1],0)/t.length],n=s.loops.map(b=>{const $=b.map(([f,Tt])=>[f-e[0],Tt-e[1]]),F=$.map(([f,Tt])=>Math.hypot(f,Tt)),k=F.reduce((f,Tt)=>f+Tt,0)/F.length;if($.length<8||k<=0||F.some(f=>Math.abs(f-k)>.02*k))return $;const W=2*Math.PI/$.length;for(let f=0;f<$.length;f++){const Tt=Math.atan2($[f][1],$[f][0]),nt=Math.atan2($[(f+1)%$.length][1],$[(f+1)%$.length][0]),wt=Math.abs(Math.atan2(Math.sin(nt-Tt),Math.cos(nt-Tt)));if(Math.abs(wt-W)>.1*W)return $}const D=$.reduce((f,Tt,nt)=>{const wt=$[(nt+1)%$.length];return f+Tt[0]*wt[1]-wt[0]*Tt[1]},0)>=0?1:-1;return $.map((f,Tt)=>[k*Math.cos(D*2*Math.PI*Tt/$.length),k*Math.sin(D*2*Math.PI*Tt/$.length)])}),r=b=>b.map(F=>{const k=F.map(([V,D])=>`${Math.round(V*304.8)},${Math.round(D*304.8)}`);let W=0;for(let V=1;V<k.length;V++)k[V]<k[W]&&(W=V);return[...k.slice(W),...k.slice(0,W)].join(";")}).sort().join("|"),i=(b,$)=>{const F=Math.cos(-$),k=Math.sin(-$);return b.map(W=>W.map(([V,D])=>[F*V-k*D,k*V+F*D]))},a=[];let l=s.axis,p=0,d=n;if(l===1&&(l=0,p=Math.PI/2,d=n.map(b=>b.map(([$,F])=>[-F,$]))),l===2){let b=0,$=0,F=0;const k=n.flat();for(const[nt,wt]of k)b+=nt*nt,$+=wt*wt,F+=nt*wt;const W=new Set,V=.5*Math.atan2(2*F,b-$);for(let nt=0;nt<4;nt++)W.add(V+nt*Math.PI/2);const D=k.map(([nt,wt])=>Math.hypot(nt,wt)),f=Math.max(...D),Tt=k.filter((nt,wt)=>D[wt]>f-.003);if(Math.abs(b-$)<.001*(b+$)||Tt.length>4)for(const[nt,wt]of Tt.slice(0,64))W.add(Math.atan2(wt,nt));for(const nt of W)a.push({loops:i(n,nt),turn:nt,flipped:!1})}else a.push({loops:d,turn:0,flipped:!1}),a.push({loops:d.map(b=>b.map(([$,F])=>[-$,F]).reverse()),turn:Math.PI,flipped:!0});let c=a[0],E=r(c.loops);for(const b of a.slice(1)){const $=r(b.loops);$<E&&(c=b,E=$)}return{axis:l,loops:c.loops,key:E,centre:e,turn:p+c.turn,flipped:c.flipped}}function jl(s){const e=s.v.length/3;if(e<6)return null;const n=[0,1,2].map(r=>{let i=1/0,a=-1/0;for(let l=0;l<e;l++){const p=s.v[l*3+r];i=Math.min(i,p),a=Math.max(a,p)}return a-i});for(const r of[0,1,2].sort((i,a)=>n[a]-n[i])){let i=1/0,a=-1/0;for(let tt=0;tt<e;tt++){const ct=s.v[tt*3+r];i=Math.min(i,ct),a=Math.max(a,ct)}if(a-i<.01)continue;let l=!0;for(let tt=0;tt<e&&l;tt++){const ct=s.v[tt*3+r];Math.abs(ct-i)>.001&&Math.abs(ct-a)>.001&&(l=!1)}if(!l)continue;const p=(r+1)%3,d=(r+2)%3,c=new Map,E=[],b=tt=>{const ct=[s.v[tt*3+p],s.v[tt*3+d]],ht=`${Math.round(ct[0]*3048)},${Math.round(ct[1]*3048)}`;return c.has(ht)||(c.set(ht,E.length),E.push(ct)),c.get(ht)},$=[];for(let tt=0;tt+2<s.t.length;tt+=3){const ct=[s.t[tt],s.t[tt+1],s.t[tt+2]];if(!ct.every(kt=>Math.abs(s.v[kt*3+r]-i)<=.001))continue;const ht=ct.map(b);ht[0]===ht[1]||ht[1]===ht[2]||ht[0]===ht[2]||$.push(ht)}if($.length===0)continue;const F=(tt,ct)=>{const[ht,kt]=[E[tt],E[ct]],te=[kt[0]-ht[0],kt[1]-ht[1]],Wt=te[0]*te[0]+te[1]*te[1],at=[];if(E.length<=3e3)for(let st=0;st<E.length;st++){if(st===tt||st===ct)continue;const pt=((E[st][0]-ht[0])*te[0]+(E[st][1]-ht[1])*te[1])/Wt;if(pt<=1e-6||pt>=1-1e-6)continue;Math.abs((E[st][0]-ht[0])*te[1]-(E[st][1]-ht[1])*te[0])/Math.sqrt(Wt)<3e-4&&at.push({t:pt,id:st})}return[tt,...at.sort((st,pt)=>st.t-pt.t).map(st=>st.id),ct]},k=[];for(const tt of $)for(let ct=0;ct<3;ct++){const ht=F(tt[ct],tt[(ct+1)%3]);for(let kt=0;kt+1<ht.length;kt++)k.push([ht[kt],ht[kt+1]])}const W=new Map;for(const[tt,ct]of k){const ht=tt<ct?`${tt},${ct}`:`${ct},${tt}`;W.set(ht,(W.get(ht)??0)+1)}const V=new Map;for(const[tt,ct]of k)W.get(tt<ct?`${tt},${ct}`:`${ct},${tt}`)===1&&V.set(tt,[...V.get(tt)??[],ct]);if([...V.values()].some(tt=>tt.length!==1))continue;const D=[],f=new Set(V.keys());for(;f.size;){const tt=f.values().next().value,ct=[];let ht=tt,kt=0;do ct.push(E[ht]),f.delete(ht),ht=V.get(ht)[0];while(ht!==tt&&kt++<1e5&&V.has(ht));if(ht!==tt||ct.length<3){D.length=0;break}const te=ct.filter((Wt,at)=>{const st=ct[(at-1+ct.length)%ct.length],pt=ct[(at+1)%ct.length];return Math.abs((Wt[0]-st[0])*(pt[1]-st[1])-(Wt[1]-st[1])*(pt[0]-st[0]))>1e-7});D.push(te.map(([Wt,at])=>[Oe(Wt,1e-5),Oe(at,1e-5)]))}if(D.length===0||D.some(tt=>tt.length<3))continue;const Tt=tt=>{const ct=new Set;for(let ht=0;ht<e;ht++)Math.abs(s.v[ht*3+r]-tt)<=.001&&ct.add(`${Math.round(s.v[ht*3+p]*304.8)},${Math.round(s.v[ht*3+d]*304.8)}`);return ct},nt=(tt,ct)=>{const[ht,kt]=ct.split(",").map(Number);for(let te=-1;te<=1;te++)for(let Wt=-1;Wt<=1;Wt++)if(tt.has(`${ht+te},${kt+Wt}`))return!0;return!1},wt=Tt(i),Pt=Tt(a);if(!(Pt.size<3||[...wt].some(tt=>!nt(Pt,tt))||[...Pt].some(tt=>!nt(wt,tt))))return{axis:r,from:i,length:a-i,loops:D}}return null}function Dl(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 a=[];for(const d of n.pieces){const c=s.geometries.get(d.geometry);if(!c)continue;const E=d.matrix,b=$=>{const F=c.verts[$*3],k=c.verts[$*3+1],W=c.verts[$*3+2];return[E[0]*F+E[4]*k+E[8]*W+E[12],E[1]*F+E[5]*k+E[9]*W+E[13],E[2]*F+E[6]*k+E[10]*W+E[14]]};for(let $=0;$+2<c.tris.length;$+=3){const F=[b(c.tris[$]),b(c.tris[$+1]),b(c.tris[$+2])];for(const k of F)r=Math.min(r,k[2]),i=Math.max(i,k[2]);a.push(F)}}if(!Number.isFinite(r)||i-r<.1)continue;let l=null,p=0;for(const d of a){if(!d.every(E=>Math.abs(E[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>p&&(p=c,l=d)}l&&e.push({key:`${t}:${n.gid}:room`,at:[(l[0][0]+l[1][0]+l[2][0])/3,(l[0][1]+l[1][1]+l[2][1])/3,r],height:i-r,number:n.name??"",name:n.longName??n.name??""})}return e}function Ul(s){if(s.length<2)return;let t=s[0],e=s[0],n=0;for(const d of s){const c=Math.hypot(d[0]-s[0][0],d[1]-s[0][1]);c>n&&(n=c,e=d)}n=0;for(const d of s){const c=Math.hypot(d[0]-e[0],d[1]-e[1]);c>n&&(n=c,t=d)}if(n<.1)return;const r=[...new Map(s.map(d=>[`${Math.round(d[0]*1e3)},${Math.round(d[1]*1e3)}`,[d[0],d[1]]])).values()].sort((d,c)=>d[0]-c[0]||d[1]-c[1]),i=(d,c,E)=>(c[0]-d[0])*(E[1]-d[1])-(c[1]-d[1])*(E[0]-d[0]),a=d=>{const c=[];for(const E of d){for(;c.length>=2&&i(c[c.length-2],c[c.length-1],E)<=0;)c.pop();c.push(E)}return c.pop(),c},l=r.length>=3?[...a(r),...a([...r].reverse())]:r;let p;for(let d=0;d<l.length;d++){const c=l[d],E=l[(d+1)%l.length],b=Math.hypot(E[0]-c[0],E[1]-c[1]);if(b<.001)continue;const $=[(E[0]-c[0])/b,(E[1]-c[1])/b],F=l.map(f=>f[0]*$[0]+f[1]*$[1]),k=l.map(f=>-f[0]*$[1]+f[1]*$[0]),W=Math.max(...F)-Math.min(...F),V=Math.max(...k)-Math.min(...k),D=W*V;(!p||D<p.area-1e-9)&&(p={area:D,u:W>=V?$:[-$[1],$[0]]})}if(p){const d=p.u;return d[0]*(e[0]-t[0])+d[1]*(e[1]-t[1])<0&&(d[0]=-d[0],d[1]=-d[1]),{a:t,u:d}}return{a:t,u:[(e[0]-t[0])/n,(e[1]-t[1])/n]}}function tr(s,t){const e=s.elements.get(t);if(!e)return[];const n=[],r=[],i=new Map;for(const c of e.pieces){const E=s.geometries.get(c.geometry);if(!E)continue;const b=c.matrix,$=[];for(let F=0;F<E.verts.length;F+=3){const k=E.verts[F],W=E.verts[F+1],V=E.verts[F+2],D=[b[0]*k+b[4]*W+b[8]*V+b[12],b[1]*k+b[5]*W+b[9]*V+b[13],b[2]*k+b[6]*W+b[10]*V+b[14]],f=D.map(nt=>Math.round(nt*1e4)).join(",");let Tt=i.get(f);Tt===void 0&&(Tt=n.length,i.set(f,Tt),n.push(D)),$.push(Tt)}for(let F=0;F+2<E.tris.length;F+=3)r.push($[E.tris[F]],$[E.tris[F+1]],$[E.tris[F+2]])}const a=n.map((c,E)=>E),l=c=>{for(;a[c]!==c;)a[c]=a[a[c]],c=a[c];return c};for(let c=0;c<r.length;c+=3){const E=l(r[c]);a[l(r[c+1])]=E,a[l(r[c+2])]=E}const p=new Map;for(let c=0;c<r.length;c+=3){const E=l(r[c]);let b=p.get(E);b||(b={pts:new Set,volume:0},p.set(E,b));const[$,F,k]=[n[r[c]],n[r[c+1]],n[r[c+2]]];b.volume+=_n($,sn(F,k))/6,b.pts.add(r[c]),b.pts.add(r[c+1]),b.pts.add(r[c+2])}const d=[...p.values()];return d.map((c,E)=>({pts:[...c.pts].map(b=>n[b]),volume:c.volume,index:E,of:d.length}))}function Jl(s,t,e,n,r,i){const a=s.elements.get(t);if(!a)return null;const l=E=>(E[0]-e[0])*n[0]+(E[1]-e[1])*n[1],p=E=>-(E[0]-e[0])*n[1]+(E[1]-e[1])*n[0];let d=1/0,c=-1/0;for(const E of a.pieces){const b=s.geometries.get(E.geometry);if(!b)continue;const $=E.matrix,F=k=>{const W=b.verts[k*3],V=b.verts[k*3+1],D=b.verts[k*3+2];return[$[0]*W+$[4]*V+$[8]*D+$[12],$[1]*W+$[5]*V+$[9]*D+$[13],$[2]*W+$[6]*V+$[10]*D+$[14]]};for(let k=0;k+2<b.tris.length;k+=3){const W=[F(b.tris[k]),F(b.tris[k+1]),F(b.tris[k+2])],V=[];for(let nt=0;nt<3;nt++){const wt=W[nt],Pt=W[(nt+1)%3],tt=l(wt)-r,ct=l(Pt)-r;if(tt<0==ct<0||tt===ct)continue;const ht=tt/(tt-ct);V.push([p(wt)+ht*(p(Pt)-p(wt)),wt[2]+ht*(Pt[2]-wt[2])])}if(V.length!==2)continue;const[D,f]=V;if((D[1]-i)*(f[1]-i)>0||D[1]===f[1])continue;const Tt=D[0]+(i-D[1])/(f[1]-D[1])*(f[0]-D[0]);d=Math.min(d,Tt),c=Math.max(c,Tt)}}return Number.isFinite(d)?{lo:d,hi:c}:null}function Qt(s,t,e){const n=s.elements.get(t),r=[];if(!n)return r;for(const i of e===void 0?n.pieces:[n.pieces[e]]){const a=s.geometries.get(i.geometry);if(!a)continue;const l=i.matrix;for(let p=0;p<a.verts.length;p+=3){const d=a.verts[p],c=a.verts[p+1],E=a.verts[p+2];r.push([l[0]*d+l[4]*c+l[8]*E+l[12],l[1]*d+l[5]*c+l[9]*E+l[13],l[2]*d+l[6]*c+l[10]*E+l[14]])}}return r}function ql(s,t,e,n){var i;const r=[];for(const a of s.elements.values()){if(a.parent!==t||!/^IFC(PLATE|COVERING|BUILDINGELEMENTPROXY)$/i.test(a.ifcClass)||a.pieces.length===0)continue;const l=Qt(s,a.gid);if(l.length===0)continue;let p=0;for(const b of a.pieces)p+=(((i=s.geometries.get(b.geometry))==null?void 0:i.tris.length)??0)/3;const d=[1/0,1/0,1/0],c=[-1/0,-1/0,-1/0];for(const b of l)for(let $=0;$<3;$++)d[$]=Math.min(d[$],b[$]),c[$]=Math.max(c[$],b[$]);const E=a.pieces.length===1&&p<=12;if(E&&n){const b=s.geometries.get(a.pieces[0].geometry),$=a.pieces[0].matrix;let F=0,k=null;if(b)for(let W=0;W+2<b.tris.length;W+=3){const V=Pt=>{const tt=b.verts[Pt*3],ct=b.verts[Pt*3+1],ht=b.verts[Pt*3+2];return[$[0]*tt+$[4]*ct+$[8]*ht,$[1]*tt+$[5]*ct+$[9]*ht,$[2]*tt+$[6]*ct+$[10]*ht]},D=V(b.tris[W]),f=V(b.tris[W+1]),Tt=V(b.tris[W+2]),nt=sn([f[0]-D[0],f[1]-D[1],f[2]-D[2]],[Tt[0]-D[0],Tt[1]-D[1],Tt[2]-D[2]]),wt=Math.hypot(nt[0],nt[1],nt[2]);wt>F&&(F=wt,k=nt.map(Pt=>Pt/wt))}if(k&&Math.abs(k[0]*n[0]+k[1]*n[1])<.996){r.push({gid:a.gid,centre:[(d[0]+c[0])/2,(d[1]+c[1])/2,(d[2]+c[2])/2]});continue}}E||r.push({gid:a.gid,centre:[(d[0]+c[0])/2,(d[1]+c[1])/2,(d[2]+c[2])/2]})}return r}function Is(s,t,e,n,r=!1){const i=s.elements.get(t);if(!i)return null;const a=Math.hypot(n[0]-e[0],n[1]-e[1]);if(!(a>.1))return null;const l=[(n[0]-e[0])/a,(n[1]-e[1])/a],p=[-l[1],l[0]],d=[];for(const at of i.pieces){const st=s.geometries.get(at.geometry);if(!st)continue;const pt=at.matrix,Bt=qt=>{const jt=st.verts[qt*3],Kt=st.verts[qt*3+1],Yt=st.verts[qt*3+2];return[pt[0]*jt+pt[4]*Kt+pt[8]*Yt+pt[12],pt[1]*jt+pt[5]*Kt+pt[9]*Yt+pt[13],pt[2]*jt+pt[6]*Kt+pt[10]*Yt+pt[14]]};for(let qt=0;qt+2<st.tris.length;qt+=3){const jt=Bt(st.tris[qt]),Kt=Bt(st.tris[qt+1]),Yt=Bt(st.tris[qt+2]),zt=sn([Kt[0]-jt[0],Kt[1]-jt[1],Kt[2]-jt[2]],[Yt[0]-jt[0],Yt[1]-jt[1],Yt[2]-jt[2]]),U=Math.hypot(zt[0],zt[1],zt[2]);if(U<1e-9||Math.abs((zt[0]*p[0]+zt[1]*p[1])/U)<.995)continue;const Z=((jt[0]+Kt[0]+Yt[0])/3-e[0])*p[0]+((jt[1]+Kt[1]+Yt[1])/3-e[1])*p[1];d.push({a:jt,b:Kt,c:Yt,across:Z})}}if(d.length<2)return null;const c=at=>{const st=(at[0]-e[0])*l[0]+(at[1]-e[1])*l[1];return`${Math.round(st*1e3)},${Math.round(at[2]*1e3)}`},E=at=>at.split(",").map(st=>Number(st)/1e3),b=at=>{const st=new Map,pt=(zt,U)=>zt<U?`${zt}|${U}`:`${U}|${zt}`;for(const zt of at){const U=[c(zt.a),c(zt.b),c(zt.c)];for(let Z=0;Z<3;Z++){const L=U[Z],ut=U[(Z+1)%3];if(L===ut)continue;const X=pt(L,ut);st.set(X,(st.get(X)??0)+1)}}const Bt=new Map;for(const[zt,U]of st){if(U!==1)continue;const[Z,L]=zt.split("|");(Bt.get(Z)??Bt.set(Z,[]).get(Z)).push(L),(Bt.get(L)??Bt.set(L,[]).get(L)).push(Z)}if(Bt.size<3||Bt.size>4e3)return null;const qt=new Set;let jt=null,Kt=0;const Yt=[];for(const zt of Bt.keys()){if(qt.has(zt))continue;const U=[zt];qt.add(zt);let Z="",L=zt;for(let dt=0;dt<5e3;dt++){const Mt=(Bt.get(L)??[]).find(it=>it!==Z&&!qt.has(it))??null;if(!Mt)break;U.push(Mt),qt.add(Mt),Z=L,L=Mt}if(U.length<3)continue;const ut=U.map(E);let X=0;for(let dt=0;dt<ut.length;dt++){const Mt=ut[dt],it=ut[(dt+1)%ut.length];X+=Mt[0]*it[1]-it[0]*Mt[1]}Yt.push({pts:ut,area:Math.abs(X)/2}),Math.abs(X)/2>Kt&&(Kt=Math.abs(X)/2,jt=ut)}return jt?{best:jt,bestArea:Kt,allLoops:Yt}:null},$=Math.max(...d.map(at=>at.across));let F=b(d.filter(at=>at.across>$-.005));const k=[...new Set(d.map(at=>Math.round(at.across*200)))].map(at=>at/200);if(k.length>1&&k.length<=24)for(const at of k){if(Math.abs(at-$)<.005)continue;const st=b(d.filter(pt=>Math.abs(pt.across-at)<.0025));st&&F&&st.bestArea>F.bestArea*1.2&&(F=st)}if(!F)return null;const{best:W,allLoops:V}=F;if(!W||W.length<3)return null;const D=Math.min(...W.map(at=>at[0])),f=Math.max(...W.map(at=>at[0])),Tt=Math.min(...W.map(at=>at[1])),nt=Math.max(...W.map(at=>at[1]));if(!(f-D>.1)||!(nt-Tt>.1))return null;if(r){const at=W.filter((U,Z,L)=>{const ut=L[(Z-1+L.length)%L.length],X=L[(Z+1)%L.length];return Math.abs((X[0]-ut[0])*(U[1]-ut[1])-(X[1]-ut[1])*(U[0]-ut[0]))>1e-4*Math.hypot(X[0]-ut[0],X[1]-ut[1])}),st=(U,Z)=>{let L=!1;for(let ut=0,X=Z.length-1;ut<Z.length;X=ut++)Z[ut][1]>U[1]!=Z[X][1]>U[1]&&U[0]<(Z[X][0]-Z[ut][0])*(U[1]-Z[ut][1])/(Z[X][1]-Z[ut][1])+Z[ut][0]&&(L=!L);return L},pt=U=>[U.reduce((Z,L)=>Z+L[0],0)/U.length,U.reduce((Z,L)=>Z+L[1],0)/U.length],Bt=V.filter(U=>U.pts!==W&&U.area>=.01&&U.pts.length<=200&&(U.area>=.1||!st(pt(U.pts),W))).map(U=>U.pts),qt=Bt.filter(U=>!st(pt(U),W)),jt=U=>{let Z=0;for(let L=0;L<U.length;L++){const ut=U[L],X=U[(L+1)%U.length];Z+=ut[0]*X[1]-X[0]*ut[1]}return Math.abs(Z)/2},Kt=$-Math.min(...d.map(U=>U.across));let Yt=0;for(const U of i.pieces){const Z=s.geometries.get(U.geometry);if(!Z)continue;const L=U.matrix,ut=X=>{const dt=Z.verts[X*3],Mt=Z.verts[X*3+1],it=Z.verts[X*3+2];return[L[0]*dt+L[4]*Mt+L[8]*it+L[12],L[1]*dt+L[5]*Mt+L[9]*it+L[13],L[2]*dt+L[6]*Mt+L[10]*it+L[14]]};for(let X=0;X+2<Z.tris.length;X+=3){const dt=ut(Z.tris[X]),Mt=ut(Z.tris[X+1]),it=ut(Z.tris[X+2]);Yt+=(dt[0]*(Mt[1]*it[2]-Mt[2]*it[1])-dt[1]*(Mt[0]*it[2]-Mt[2]*it[0])+dt[2]*(Mt[0]*it[1]-Mt[1]*it[0]))/6}}const zt=(jt(at)-Bt.filter(U=>!qt.includes(U)).reduce((U,Z)=>U+jt(Z),0)+qt.reduce((U,Z)=>U+jt(Z),0))*Kt;return Kt>.01&&Math.abs(Yt)>1e-6&&Math.abs(zt-Math.abs(Yt))>.15*Math.abs(Yt)?null:qt.length?{lo:D,hi:f,bottom:Tt,chain:[],outline:at,holes:Bt.filter(U=>!qt.includes(U)),pieces:qt}:(at.length>4||Bt.length)&&at.length<=200?{lo:D,hi:f,bottom:Tt,chain:[],outline:at,holes:Bt}:null}const wt=at=>W.map((st,pt)=>({p:st,i:pt})).filter(({p:st})=>Math.abs(st[0]-at)<.003).sort((st,pt)=>pt.p[1]-st.p[1])[0],Pt=wt(D),tt=wt(f);if(!Pt||!tt)return null;const ct=at=>{const st=[];for(let pt=Pt.i,Bt=0;Bt<=W.length;pt=(pt+at+W.length)%W.length,Bt++)if(st.push(W[pt]),pt===tt.i)return st;return null},ht=ct(1),kt=ct(-1),te=at=>at?at.reduce((st,pt)=>st+pt[1],0)/at.length:-1/0;let Wt=te(ht)>=te(kt)?ht:kt;if(!Wt||Wt.length<2||(Wt=Wt.filter((at,st,pt)=>{if(st===0||st===pt.length-1)return!0;const Bt=pt[st-1],qt=pt[st+1];return Math.abs((qt[0]-Bt[0])*(at[1]-Bt[1])-(qt[1]-Bt[1])*(at[0]-Bt[0]))>1e-4*Math.hypot(qt[0]-Bt[0],qt[1]-Bt[1])}),Wt.every(at=>Math.abs(at[1]-nt)<.005)))return null;for(let at=1;at<Wt.length;at++)if(Wt[at][0]<Wt[at-1][0]-.003)return null;return Wt.length>200?null:{lo:D,hi:f,bottom:Tt,chain:Wt}}function Gl(s,t,e){const n=Qt(s,t);if(n.length<4||e.length===0)return;let r=n[0],i=n[0],a=0;for(const V of n){const D=Math.hypot(V[0]-n[0][0],V[1]-n[0][1]);D>a&&(a=D,i=V)}a=0;for(const V of n){const D=Math.hypot(V[0]-i[0],V[1]-i[1]);D>a&&(a=D,r=V)}if(a<.3)return;const l=(i[0]-r[0])/a,p=(i[1]-r[1])/a,d=V=>(V[0]-r[0])*l+(V[1]-r[1])*p,c=Math.max(...n.map(V=>V[2])),E=V=>Math.max(...n.filter(D=>Math.abs(d(D)-V)<.05).map(D=>D[2]),-1/0),b=E(0),$=E(a);if(Math.abs(b-$)<.05&&c-Math.max(b,$)<.05)return;const F=(r[0]+i[0])/2,k=(r[1]+i[1])/2;let W;for(const V of e){const D=Qt(s,V.gid);if(D.length===0)continue;const f=D.map(Pt=>Pt[0]),Tt=D.map(Pt=>Pt[1]),nt=D.map(Pt=>Pt[2]);if(F<Math.min(...f)-.2||F>Math.max(...f)+.2||k<Math.min(...Tt)-.2||k>Math.max(...Tt)+.2)continue;const wt=Math.min(...nt)-c;wt>1.5||Math.max(...nt)<c-.05||(!W||Math.abs(wt)<Math.abs(W.gap))&&(W={id:V.id,gap:wt})}return W==null?void 0:W.id}const De={levels:"-2000240",walls:"-2000011",floors:"-2000032",roofs:"-2000035",ceilings:"-2000038",structuralFoundations:"-2001300",stairs:"-2000120"};function Sn(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 Go(s){const t=Sn(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 Ho=180/Math.PI;function Vo(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 Ct=s=>String(s);function Hl(s){const t=s.slice(),e=(n,r,i)=>Math.abs((r[0]-n[0])*(i[1]-n[1])-(i[0]-n[0])*(r[1]-n[1]))/2;for(let n=!0;n&&t.length>3;){n=!1;for(let r=0;r<t.length&&t.length>3;r++){const i=t[(r-1+t.length)%t.length],a=t[r],l=t[(r+1)%t.length],p=Math.min(Math.hypot(a[0]-i[0],a[1]-i[1]),Math.hypot(l[0]-a[0],l[1]-a[1]))<.02;(e(i,a,l)<1e-8||p&&e(i,a,l)<2e-4)&&(t.splice(r,1),n=!0,r--)}}return t}function Da(s){return async t=>{var Cr,Rr,Or,kr,Nr,Fr,Pr,Lr,Br,jr,Dr,Ur,Jr,qr,Gr,Hr,Vr,zr,Wr,Yr,Kr,Xr,Zr,Qr,ti,ei,ni,si,ri,ii,oi,ai,ci,li,hi,fi,di,ui,pi,mi,gi,yi,wi,bi,vi,Ei,Ti,Mi,$i,Ii,Si,xi,_i,Ai,Ci,Ri,Oi,ki,Ni,Fi,Pi,Li,Bi,ji,Di,Ui,Ji,qi,Gi,Hi,Vi,zi,Wi,Yi,Ki,Xi,Zi,Qi,to,eo,no,so,ro,io,oo,ao,co,lo,ho,fo,uo,po,mo,go,yo,wo,bo,vo,Eo,To,Mo;const{picked:e,contents:n,site:r,shapes:i}=await pr(t,t.input),a=Ma(n.items),l=/CoordinateBase:\s*(Coordenadas compartidas|Shared Coordinates|Shared)/i.test(JSON.stringify(n.metadata??{})),p=l&&r?[r.east*nn,r.north*nn,r.elevation*nn,r.angleDeg].map(o=>o.toFixed(6)).join(","):void 0;if(a.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:E}=t.settings,b=t.settings.createLevels!==!1;if(E&&!c)throw new Error("Free-standing instances can only be made by their style names: turn trustStyleNames on.");const $=dr(a),F=$a(a);if(typeof process<"u"&&((Cr=process.env)!=null&&Cr.RECIPE_STYLE))for(const[o,h]of F)o.includes(process.env.RECIPE_STYLE)&&console.error(`[style] ${o}: ${JSON.stringify(h).slice(0,1500)}`);const k=`recipe:${s}-to-revit`,W=new Map,V=ur(t,W);t.progress("Writing the changes for Revit");const D=new hs({project:t.projectId,document:t.target.docId??"",baseCommit:t.target.version??0,author:k}),f=nn,Tt=new Map;{const o=new Map;for(const h of a){const w=h.item.guid;if(!w)continue;const m=`${w}:${h.kind}`,N=o.get(m)??0;o.set(m,N+1),Tt.set(h.id,`${e.fileId}:${m}${N?`:${N}`:""}`)}}const nt=o=>Tt.get(o)??`${e.fileId}:${o}`,wt=new Set,Pt=new Set;let tt=0,ct=0;const ht=Array.isArray(t.settings.focus)?new Set(t.settings.focus):null,kt=[],te=()=>{var R;if(!ht)return;const o=O=>O?O.split(":")[1]:void 0,h=new Set,w=O=>(O.LocationLine??"").split(";").map(q=>q.split(",").map(Number)).filter(q=>q.length>=2&&q.every(Number.isFinite)),m=O=>{h.has(O)||(h.add(O),N=!0)};let N=!0;kt.forEach((O,q)=>{ht.has(o(O.sourceKey)??"")&&m(q)});for(let O=0;N&&O<2;O++){N=!1;const q=new Set([...h].map($t=>`${kt[$t].attrs.CategoryId}|${kt[$t].attrs.Type??""}`)),u=new Set([...h].map($t=>o(kt[$t].sourceKey))),x=new Set([...h].map($t=>kt[$t].sourceKey)),gt=[...h].flatMap($t=>w(kt[$t].attrs));kt.forEach(($t,Rt)=>{var yt;if(h.has(Rt))return;const It=$t.attrs;if(It.Type&&q.has(`${It.CategoryId}|${It.Type}`)||(yt=$t.placement)!=null&&yt.host&&(x.has($t.placement.host)||u.has(o($t.placement.host)))||It.AttachTop&&x.has(It.AttachTop)||It.CutBy&&It.CutBy.split("|").some(A=>x.has(A))||O===0&&w(It).some(A=>gt.some(Ot=>Math.hypot(A[0]-Ot[0],A[1]-Ot[1])<1)))return m(Rt)});for(const $t of[...h]){const Rt=(R=kt[$t].placement)==null?void 0:R.host,It=kt[$t].attrs.AttachTop,yt=(kt[$t].attrs.CutBy??"").split("|");kt.forEach((A,Ot)=>{(A.sourceKey===Rt||A.sourceKey===It||yt.includes(A.sourceKey))&&m(Ot)})}}kt.forEach((O,q)=>{/^[0-9A-Za-z_$]{22}$/.test(o(O.sourceKey)??"")||h.add(q)});for(const O of[...h].sort((q,u)=>q-u))D.add(kt[O].attrs,{...kt[O].placement,source:kt[O].sourceKey});typeof process<"u"&&console.error(`[focus] ${ht.size} asked, ${h.size} of ${kt.length} change(s) written`)},Wt=(o,h,w)=>{if(!V.has(o))return!1;const m=W.get(o),N=l?{...h,Frame:"shared",...p?{SharedAt:p}:{}}:h;return!m||m===ts({attrs:N,placement:w??{}})},at=new Map,st=(o,h,w)=>{wt.add(o),at.set(o,h);const m=l?{...h,Frame:"shared",...p?{SharedAt:p}:{}}:h,N=ts({attrs:m,placement:w??{}}),R=V.get(o);if(R){const O=W.get(o);return!O||O===N?(tt++,!1):(D.remove(R),D.add({...m,"flow:print":N},{...w,source:o}),ct++,!1)}return ht?(kt.push({sourceKey:o,attrs:{...m,"flow:print":N},placement:w}),!0):(D.add({...m,"flow:print":N},{...w,source:o}),!0)},pt=o=>{const h=typeof o=="string"?F.get(o):void 0,w=h==null?void 0:h.params.thickness;return typeof w=="number"&&w>0?w*f:void 0},Bt=o=>{var rt,ft;const h=de(o,"extrusion"),w=$.get(String((h==null?void 0:h.level)??o.params.level??"")),m=h==null?void 0:h.slopes,N=((ft=(rt=h==null?void 0:h.profile)==null?void 0:rt.outline)==null?void 0:ft.curves)??[],R=Array.isArray(m)?m.map(mt=>typeof mt=="number"):[],O=R.indexOf(!0);if(o.params.of!=="roof"||!w||N.length!==4||R.filter(Boolean).length!==2||O<0||O>1||!R[O+2])return null;const[q,u]=[N[O],N[O+2]],x=q.from,gt=q.to,$t=Math.hypot(gt[0]-x[0],gt[1]-x[1]),Rt=[(gt[0]-x[0])/$t,(gt[1]-x[1])/$t];let It=[-Rt[1],Rt[0]];const yt=(u.from[0]-x[0])*It[0]+(u.from[1]-x[1])*It[1];yt<0&&(It=[-It[0],-It[1]]);const A=Math.abs(yt),[Ot,lt]=[m[O],m[O+2]],bt=w.at+(typeof o.params.base=="number"?o.params.base:0),K=(h==null?void 0:h.eaves)??[],[G,et]=[bt+(Number(K[O])||0),bt+(Number(K[O+2])||0)],H=(et-G+lt*A)/(Ot+lt);return{A:x,u:Rt,n:It,L:$t,W:A,si:Ot,sj:lt,ridge:H,top:bt,ti:G,tj:et,zAt:(mt,At)=>{const xt=(mt-x[0])*It[0]+(At-x[1])*It[1];return Math.min(G+Ot*xt,et+lt*(A-xt))}}},qt=new Map(a.filter(o=>o.kind==="extrusion"&&o.params.of==="roof").map(o=>[o.id,o])),jt=[...qt.values()].filter(o=>o.item.guid).map(o=>({id:o.id,gid:o.item.guid}));let Kt=0;if(b)for(const[o,h]of $){const w={CategoryId:De.levels,Name:h.name,Elevation:Ct(h.at*f)},m=ts({attrs:l?{...w,Frame:"shared",...p?{SharedAt:p}:{}}:w,placement:{}}),N=(Rr=[...W].find(([R,O])=>O===m&&V.has(R)))==null?void 0:Rr[0];st(N??nt(o),w)&&Kt++}let Yt=0,zt=0;const U=new Map,Z=new Map;let L=null;const ut=()=>L??(L=i?[...i.elements.values()].filter(o=>/^IFC(SLAB|ROOF)/i.test(o.ifcClass)).flatMap(o=>{const h=Qt(i,o.gid);if(!h.length)return[];const w=a.find(m=>m.kind==="extrusion"&&m.item.guid===o.gid);return[{keys:[...w?[nt(w.id)]:[],`${e.fileId}:${o.gid}:shape`],box:[0,1,2].map(m=>Math.min(...h.map(N=>N[m]))).concat([0,1,2].map(m=>Math.max(...h.map(N=>N[m]))))}]}):[]),X=[];for(const o of a){if(o.kind!=="run"||o.params.of!=="wall")continue;const h=de(o,"run"),w=((kr=(Or=h==null?void 0:h.run)==null?void 0:Or.line)==null?void 0:kr.curves)??[],m=o.params.lookRef,N=$.get(String((h==null?void 0:h.level)??o.params.level??""));if(typeof m!="string"||typeof(h==null?void 0:h.height)!="number"||!N){zt++;continue}const R=(pt(m)??0)/f,O=u=>{var x;if(u.kind==="segment"&&Array.isArray(u.from)&&u.to)return{from:[...u.from],to:[...u.to]};if(u.kind==="arc"&&u.centre&&typeof u.radius=="number"&&typeof u.from=="number"&&typeof u.sweep=="number"){const gt=$t=>[u.centre[0]+u.radius*Math.cos($t),u.centre[1]+u.radius*Math.sin($t)];return typeof process<"u"&&((x=process.env)!=null&&x.RECIPE_TRACE)&&console.error(`[wall-arc] ${o.item.guid}: radius ${u.radius.toFixed(2)}, sweep ${(u.sweep*180/Math.PI).toFixed(1)}°`),{from:gt(u.from),to:gt(u.from+u.sweep),arcMid:gt(u.from+u.sweep/2)}}return null},q=w.map(O).filter(u=>u!==null);zt+=w.length-q.length,q.forEach((u,x)=>X.push({record:o,i:x,width:R,from:u.from,to:u.to,..."arcMid"in u?{arcMid:u.arcMid}:{},joinStart:x===0&&String(o.params.meetsAtStart)==="true",joinEnd:x===q.length-1&&String(o.params.meetsAtEnd)==="true"}))}const dt=(o,h)=>{const w=[o.to[0]-o.from[0],o.to[1]-o.from[1]],m=[h.to[0]-h.from[0],h.to[1]-h.from[1]],N=w[0]*m[1]-w[1]*m[0];if(Math.abs(N)<1e-9*Math.hypot(...w)*Math.hypot(...m)*1e3)return null;const R=((h.from[0]-o.from[0])*m[1]-(h.from[1]-o.from[1])*m[0])/N;return[o.from[0]+R*w[0],o.from[1]+R*w[1]]},Mt=(o,h)=>{const w=h.to[0]-h.from[0],m=h.to[1]-h.from[1],N=w*w+m*m||1,R=Math.max(0,Math.min(1,((o[0]-h.from[0])*w+(o[1]-h.from[1])*m)/N));return Math.hypot(o[0]-(h.from[0]+R*w),o[1]-(h.from[1]+R*m))},it=(o,h)=>{const w=de(o.record,"run"),m=de(h.record,"run"),N=[w.base,w.base+w.height],R=[m.base,m.base+m.height],O=$.get(String((w==null?void 0:w.level)??o.record.params.level)).at,q=$.get(String((m==null?void 0:m.level)??h.record.params.level)).at;return Math.min(O+N[1],q+R[1])>Math.max(O+N[0],q+R[0])},_t=1,re=new Map,Nt=new Map;for(const o of X){const h=[["from",o.joinStart],["to",o.joinEnd]],w={from:o.from,to:o.to};for(const[m,N]of h){if(!N)continue;const R=o[m];let O=null,q=1/0;for(const gt of X){if(gt===o||gt.arcMid||!it(o,gt))continue;const $t=Mt(R,gt);$t<q&&(q=$t,O=gt)}if(!O||q>_t)continue;const u=dt(o,O);if(!u)continue;const x=Math.min(_t,2*Math.max(o.width,O.width)+.02);Math.hypot(u[0]-R[0],u[1]-R[1])>x||Mt(u,O)>O.width+.01||(w[m]=u,Nt.set(o,{...Nt.get(o),[m]:O.width/2}))}re.set(o,w)}const le=new Map;if(i){const o=w=>{const m=Math.hypot(w.to[0]-w.from[0],w.to[1]-w.from[1]);return{L:m,d:[(w.to[0]-w.from[0])/m,(w.to[1]-w.from[1])/m]}},h=(w,m,N)=>{const R=w.record.item.guid;if(!R||X.filter(x=>x.record===w.record).length!==1)return null;const{d:O}=o(w),q=Qt(i,R).map(x=>x[2]);if(!q.length)return null;const u=Jl(i,R,w.from,O,(m+N)/2,(Math.min(...q)+Math.max(...q))/2);return u?u.hi-u.lo:null};for(const w of X){if(w.arcMid||!(w.width>0))continue;const m=o(w);if(!(m.L<.3))for(const N of X){if(N===w||N.arcMid||!(N.width>0)||!it(w,N))continue;const R=o(N);if(R.L<.3||Math.abs(m.d[0]*R.d[1]-m.d[1]*R.d[0])>.02)continue;const O=Math.abs(-(N.from[0]-w.from[0])*m.d[1]+(N.from[1]-w.from[1])*m.d[0]);if(O>(w.width+N.width)/2-.01)continue;const q=[N.from,N.to].map($t=>($t[0]-w.from[0])*m.d[0]+($t[1]-w.from[1])*m.d[1]),u=Math.max(0,Math.min(...q)),x=Math.min(m.L,Math.max(...q));if(x-u<.3)continue;const gt=h(w,u,x);typeof process<"u"&&((Fr=(Nr=process.env)==null?void 0:Nr.RECIPE_WALL)!=null&&Fr.split(",").includes(w.record.item.guid??""))&&console.error(`[cut-by?] ${w.record.item.guid} by ${N.record.item.guid}: off ${O.toFixed(3)}, along ${u.toFixed(2)}..${x.toFixed(2)}, shape ${gt}`),!(gt===null||gt>w.width-.01)&&(typeof process<"u"&&((Pr=process.env)!=null&&Pr.RECIPE_TRACE)&&console.error(`[cut-by] ${w.record.item.guid} (${(w.width*1e3).toFixed(0)} mm, its shape ${(gt*1e3).toFixed(0)}) cut by ${N.record.item.guid} over ${(x-u).toFixed(2)} m`),le.set(w,[...le.get(w)??[],N]))}}}const me=(o,h)=>{var N;if(!i||!o)return null;const w=[-h[1],h[0]],m=[];for(const R of i.elements.values()){if(R.parent!==o||!/^IFCPLATE$/i.test(R.ifcClass)||R.pieces.length!==1)continue;const O=i.geometries.get(R.pieces[0].geometry);if(!O||O.tris.length/3>12)continue;const q=Qt(i,R.gid);if(q.length<4)continue;const u=q.map(gt=>gt[0]*w[0]+gt[1]*w[1]),x=Math.max(...u)-Math.min(...u);x>.002&&x<.2&&m.push(x)}return m.length?(m.sort((R,O)=>R-O),typeof process<"u"&&((N=process.env)!=null&&N.RECIPE_TRACE)&&console.error(`[glass] ${o}: ${m.length} panel(s), median ${(m[Math.floor(m.length/2)]*1e3).toFixed(1)} mm`),m[Math.floor(m.length/2)]*f):null},Le=(o,h)=>{var O;if(!i||!o)return null;const w=[-h[1],h[0]],m=[],N=[];for(const q of i.elements.values()){if(q.parent!==o||!/^IFCMEMBER$/i.test(q.ifcClass))continue;const u=Qt(i,q.gid);if(u.length<4)continue;const x=u.map(A=>A[0]*h[0]+A[1]*h[1]),gt=u.map(A=>A[0]*w[0]+A[1]*w[1]),$t=u.map(A=>A[2]),Rt=A=>Math.max(...A)-Math.min(...A),It=Math.min(Rt(x),Rt($t)),yt=Rt(gt);It>.005&&It<.5&&yt>.005&&yt<1&&(m.push(It),N.push(yt))}if(!m.length)return null;m.sort((q,u)=>q-u),N.sort((q,u)=>q-u);const R={width:m[Math.floor(m.length/2)],depth:N[Math.floor(N.length/2)]};return typeof process<"u"&&((O=process.env)!=null&&O.RECIPE_TRACE)&&console.error(`[mullion] ${o}: ${m.length} member(s), median ${(R.width*1e3).toFixed(1)} × ${(R.depth*1e3).toFixed(1)} mm`),{width:R.width*f,depth:R.depth*f}},ie=(()=>{if(!i)return 0;const o=[];for(const w of X){const m=w.record.item.guid;if(!m||!i.elements.has(m))continue;const N=de(w.record,"run"),R=$.get(String((N==null?void 0:N.level)??w.record.params.level??""));if(!N||!R)continue;const O=Qt(i,m);if(!O.length)continue;let q=1/0;for(const u of O)q=Math.min(q,u[2]);o.push(q-(R.at+(typeof N.base=="number"?N.base:0)))}o.sort((w,m)=>w-m);const h=o.length?o[Math.floor(o.length/2)]:0;return Math.abs(h)>.5?h:0})();for(const o of X){const{record:h}=o;let w=[];const m=de(h,"run");typeof process<"u"&&((Br=(Lr=process.env)==null?void 0:Lr.RECIPE_WALL)!=null&&Br.split(",").includes(h.item.guid??""))&&console.error(`[wall] ${h.item.guid}: params ${JSON.stringify(h.params).slice(0,800)} seg ${JSON.stringify({from:o.from,to:o.to,i:o.i})}`);const N=typeof m.base=="number"?m.base:0,R=m.height,O=$.get(String(m.level??h.params.level??"")),q=h.params.lookRef;let{from:u,to:x}=o.arcMid?{from:o.from,to:o.to}:re.get(o);Math.hypot(x[0]-u[0],x[1]-u[1])<.01&&({from:u,to:x}=o);const gt=new Set;if(!o.arcMid&&X.filter(P=>P.record===h).length===1){const P=m.asCut,_=Math.hypot(x[0]-u[0],x[1]-u[1]);if(P&&_>.05){const y=[(x[0]-u[0])/_,(x[1]-u[1])/_],g=(S,C)=>{const J=C==null?void 0:C.through,B=C==null?void 0:C.keep;if(!J||!B)return null;const z=y[0]*B[0]+y[1]*B[1];return Math.abs(z)<.5?null:((J[0]-S[0])*B[0]+(J[1]-S[1])*B[1])/z},T=h.params.wantedAtStart==="square"?g(u,(jr=P.start)==null?void 0:jr[0]):null,v=h.params.wantedAtEnd==="square"?g(x,(Dr=P.end)==null?void 0:Dr[0]):null;T!==null&&T>.005&&T<Math.min(1,_/2)&&(u=[u[0]+y[0]*T,u[1]+y[1]*T],gt.add("start")),v!==null&&v<-.005&&v>-Math.min(1,_/2)&&(x=[x[0]+y[0]*v,x[1]+y[1]*v],gt.add("end")),typeof process<"u"&&((Ur=process.env)!=null&&Ur.RECIPE_CUT_OUT)&&(T!==null&&T<-.005&&T>-1&&(u=[u[0]+y[0]*T,u[1]+y[1]*T],gt.add("start")),v!==null&&v>.005&&v<1&&(x=[x[0]+y[0]*v,x[1]+y[1]*v],gt.add("end"))),typeof process<"u"&&((Jr=process.env)!=null&&Jr.RECIPE_TRACE)&&(T!==null&&Math.abs(T)>.005&&Math.abs(T)<1||v!==null&&Math.abs(v)>.005&&Math.abs(v)<1)&&console.error(`[wall-to-cut] ${h.item.guid} ${q}: start ${T==null?void 0:T.toFixed(3)} end ${v==null?void 0:v.toFixed(3)}`),typeof process<"u"&&((Gr=(qr=process.env)==null?void 0:qr.RECIPE_WALL)!=null&&Gr.split(",").includes(h.item.guid??""))&&console.error(`[wall-cut] ${h.item.guid}: start ${T==null?void 0:T.toFixed(3)} end ${v==null?void 0:v.toFixed(3)}`)}}const $t=new Set(gt),Rt=!o.arcMid&&i&&h.item.guid&&X.filter(P=>P.record===h).length===1?i.elements.get(h.item.guid):void 0;if(Rt){const P=Qt(i,h.item.guid),_=Math.hypot(x[0]-u[0],x[1]-u[1]);if(P.length>=4&&_>.05){const y=[(x[0]-u[0])/_,(x[1]-u[1])/_],g=P.map(z=>(z[0]-u[0])*y[0]+(z[1]-u[1])*y[1]),T=Math.min(...g),v=Math.max(...g),S=P.map(z=>-(z[0]-u[0])*y[1]+(z[1]-u[1])*y[0]),C=Math.max(...S)-Math.min(...S),J=z=>{const M=S.filter((ot,Q)=>Math.abs(g[Q]-z)<.002);return M.length>=2&&Math.max(...M)-Math.min(...M)>.9*C},B=u;J(T)&&(u=[B[0]+y[0]*T,B[1]+y[1]*T],$t.add("start")),J(v)&&(x=[B[0]+y[0]*v,B[1]+y[1]*v],$t.add("end"))}}const It=(O.at+N)*f,yt=`${Ct(u[0]*f)},${Ct(u[1]*f)},${Ct(It)};${Ct(x[0]*f)},${Ct(x[1]*f)},${Ct(It)}`,A={CategoryId:De.walls,Type:((Hr=Sn(h))==null?void 0:Hr.type)??q,LocationLine:yt,Level:O.name,BaseOffset:Ct(N*f),Height:Ct(R*f),...o.arcMid?{LocationArc:`${Ct(o.arcMid[0]*f)},${Ct(o.arcMid[1]*f)},${Ct(It)}`}:{}},Ot=le.get(o);Ot&&(A.CutBy=Ot.flatMap(P=>{const _=`${nt(P.record.id)}#${P.i}`,y=V.get(_);return y?[_,y]:[_]}).join("|"));const lt=o.arcMid?[]:[u!==o.from||o.joinStart?"start":"",x!==o.to||o.joinEnd?"end":""].filter(P=>!!P&&!$t.has(P));lt.length&&(A.JoinEnds=lt.join(","));const bt=lt.filter(P=>h.params[P==="start"?"wantedAtStart":"wantedAtEnd"]==="mitre");bt.length&&(A.Mitre=bt.join(","));const K=$.get(String(h.params.topLevel??""));K&&(A.TopLevel=K.name,A.TopOffset=Ct((O.at+N+R-K.at)*f));const G=m.profile;let et=Array.isArray(G)?Hl(G):G;if((h.params.wantedAtStart==="mitre"||h.params.wantedAtEnd==="mitre")&&Array.isArray(et)&&et.length===4){const P=Math.hypot(o.to[0]-o.from[0],o.to[1]-o.from[1]),_=m.height,y=(T,v)=>Math.abs(T)<1e-4?"lo":Math.abs(T-v)<.001?"hi":null,g=et.map(([T,v])=>[y(T,P),y(v,_)]);g.every(([T,v])=>T&&v)&&new Set(g.map(([T,v])=>`${T}${v}`)).size===4&&(et=void 0)}if(typeof process<"u"&&((Vr=process.env)!=null&&Vr.RECIPE_LAYER_EXT)&&Array.isArray(et)&&et.length>=4&&i&&h.item.guid&&typeof m.height=="number"){const P=(()=>{var _,y;try{return JSON.parse(String(((y=(_=F.get(q))==null?void 0:_.params)==null?void 0:y.definition)??"null"))}catch{return null}})();if(((P==null?void 0:P.layers)??[]).some(_=>(_.topExtension??0)>.001||(_.baseExtension??0)>.001)){const _=Math.hypot(o.to[0]-o.from[0],o.to[1]-o.from[1]),y=m.height,g=[(o.to[0]-o.from[0])/_,(o.to[1]-o.from[1])/_],T=O.at+N+ie,v=[...i.elements.values()].filter(M=>M.host===h.item.guid&&!/^IFCOPENINGELEMENT$/i.test(M.ifcClass)).map(M=>{const ot=Qt(i,M.gid).map(Q=>[(Q[0]-o.from[0])*g[0]+(Q[1]-o.from[1])*g[1],Q[2]-T]);return ot.length?[Math.min(...ot.map(Q=>Q[0])),Math.max(...ot.map(Q=>Q[0])),Math.min(...ot.map(Q=>Q[1])),Math.max(...ot.map(Q=>Q[1]))]:null}).filter(M=>M!==null),S=Math.min(...et.map(([M])=>M)),C=Math.max(...et.map(([M])=>M)),J=([M,ot])=>(Math.abs(M-S)<.005||Math.abs(M-C)<.005)&&(Math.abs(ot)<.005||Math.abs(ot-y)<.005),B=([M,ot])=>v.some(Q=>M>=Q[0]-.03&&M<=Q[1]+.03&&ot>=Q[2]-.15&&ot<=Q[3]+.03),z=et.filter(M=>!J(M));et.filter(J).length===4&&(z.length===0||v.length&&z.every(B))&&(typeof process<"u"&&((zr=process.env)!=null&&zr.RECIPE_TRACE)&&console.error(`[layer-extension] ${h.item.guid} ${q}: its outline's ${z.length} notch corner(s) filled by what it hosts → a plain wall`),et=void 0)}}if(!o.arcMid&&Array.isArray(et)&&et.length>=3&&o.i===0&&!X.some(P=>P!==o&&P.record===h)){const P=Math.hypot(o.to[0]-o.from[0],o.to[1]-o.from[1]),_=[(o.to[0]-o.from[0])/P,(o.to[1]-o.from[1])/P],y=[];let g=-((u[0]-o.from[0])*_[0]+(u[1]-o.from[1])*_[1]),T=(x[0]-o.to[0])*_[0]+(x[1]-o.to[1])*_[1];const v=g,S=T;{const M=Nt.get(o),ot=[],Q=i&&h.item.guid?Qt(i,h.item.guid).map(ne=>(ne[0]-o.from[0])*_[0]+(ne[1]-o.from[1])*_[1]):[],Ft=Q.length?Math.max(0,-Math.min(...Q))-g:1/0,Dt=Q.length?Math.max(0,Math.max(...Q)-P)-T:1/0,Gt=(M==null?void 0:M.from)??(Ft<.6?Ft:0),ee=(M==null?void 0:M.to)??(Dt<.6?Dt:0);Gt&&lt.includes("start")&&Ft>.005&&(g+=Math.min(Gt,Ft),ot.push("start")),ee&&lt.includes("end")&&Dt>.005&&(T+=Math.min(ee,Dt),ot.push("end"));const Zt=lt.filter(ne=>!ot.includes(ne));if(ot.length&&(Zt.length?A.JoinEnds=Zt.join(","):delete A.JoinEnds),ot.length&&A.Mitre){const ne=A.Mitre.split(",").filter(Ut=>Zt.includes(Ut));ne.length?A.Mitre=ne.join(","):delete A.Mitre}ot.length&&typeof process<"u"&&((Wr=process.env)!=null&&Wr.RECIPE_TRACE)&&console.error(`[profile-face] ${h.item.guid} ${q}: ${ot.join(",")} to the far face`)}const C=(M,ot)=>et.map(([Q,Ft],Dt)=>{const Gt=Math.abs(Q)<1e-6,ee=Math.abs(Q-P)<1e-6;let Zt=Q,ne=Ft;if(Gt||ee){Zt=Gt?-M:P+ot;const Ut=[et[(Dt-1+et.length)%et.length],et[(Dt+1)%et.length]].find(([fe])=>Math.abs(fe-Q)>1e-6);Ut&&(ne=Ft+(Ut[1]-Ft)/(Ut[0]-Q)*(Zt-Q))}return[Zt,ne]}),J=M=>{const ot=M.length,Q=M.map((Dt,Gt)=>[Dt,M[(Gt+1)%ot]]);if(Q.some(([Dt,Gt])=>Math.hypot(Gt[0]-Dt[0],Gt[1]-Dt[1])<.001))return!1;for(let Dt=0;Dt<ot;Dt++){const[Gt,ee]=Q[Dt],[,Zt]=Q[(Dt+1)%ot],ne=[ee[0]-Gt[0],ee[1]-Gt[1]],Ut=[Zt[0]-ee[0],Zt[1]-ee[1]];if((ne[0]*Ut[0]+ne[1]*Ut[1])/(Math.hypot(...ne)*Math.hypot(...Ut))<-.999)return!1}const Ft=(Dt,Gt,ee)=>(Gt[0]-Dt[0])*(ee[1]-Dt[1])-(Gt[1]-Dt[1])*(ee[0]-Dt[0]);for(let Dt=0;Dt<ot;Dt++)for(let Gt=Dt+1;Gt<ot;Gt++){if(Gt===Dt+1||Dt===0&&Gt===ot-1)continue;const[ee,Zt]=Q[Dt],[ne,Ut]=Q[Gt],fe=Ft(ne,Ut,ee),Be=Ft(ne,Ut,Zt),pn=Ft(ee,Zt,ne),$o=Ft(ee,Zt,Ut);if((fe>1e-9&&Be<-1e-9||fe<-1e-9&&Be>1e-9)&&(pn>1e-9&&$o<-1e-9||pn<-1e-9&&$o>1e-9))return!1}return!0};let B=C(g,T);if(!J(B)){const ot=[[v,S],[0,0]].find(([Q,Ft])=>J(C(Q,Ft)));typeof process<"u"&&((Yr=process.env)!=null&&Yr.RECIPE_TRACE)&&console.error(`[profile-folded] ${h.item.guid} ${q}: ends ${g.toFixed(3)}/${T.toFixed(3)} fold it → ${ot?ot.map(Q=>Q.toFixed(3)).join("/"):"as given"}`),B=ot?C(...ot):et.map(([Q,Ft])=>[Q,Ft])}const z=M=>M.flatMap(([ot,Q])=>{const Ft=[o.from[0]+ot*_[0],o.from[1]+ot*_[1]];return[Ft[0]*f,Ft[1]*f,(O.at+N+Q)*f]});for(const M of z(B))y.push(M);if(A.Profile=JSON.stringify([y]),B.length===8){const M=B.map(([,Ut])=>Ut),ot=Math.max(...M),Q=Math.min(...M),Ft=B.map(([Ut])=>Ut),Dt=Math.min(...Ft),Gt=Math.max(...Ft),ee=B.filter(([Ut])=>Ut>Dt+.005&&Ut<Gt-.005),Zt=[...new Set(ee.map(([Ut])=>+Ut.toFixed(4)))].sort((Ut,fe)=>Ut-fe);if(B.filter(([Ut,fe])=>(Math.abs(Ut-Dt)<.005||Math.abs(Ut-Gt)<.005)&&(Math.abs(fe-ot)<.005||Math.abs(fe-Q)<.005)).length===4&&ee.length===4&&Zt.length===2&&Zt[1]-Zt[0]<.3&&ee.some(([,Ut])=>Math.abs(Ut-Q)<.005)&&ee.every(([,Ut])=>Math.abs(Ut-Q)<.005||ot-Ut<.3)){const Ut=(fe,Be)=>[[fe,Q],[Be,Q],[Be,ot],[fe,ot]];A.Profile=JSON.stringify([z(Ut(Dt,Zt[0]))]),w=[JSON.stringify([z(Ut(Zt[1],Gt))])],typeof process<"u"&&((Kr=process.env)!=null&&Kr.RECIPE_TRACE)&&console.error(`[slit-split] ${h.item.guid} ${q}: a slit ${((Zt[1]-Zt[0])*100).toFixed(0)} cm wide at ${Zt[0].toFixed(2)}, two walls`)}}delete A.TopLevel,delete A.TopOffset}const St=h.params.topAttachedTo,rt=h.params.topAttachedAt==="top"||m.topAttachedAt==="top",ft=!o.arcMid&&typeof St=="string"&&rt&&!A.Profile&&qt.has(St)?Bt(qt.get(St)):null;if(ft){const P=Math.hypot(x[0]-u[0],x[1]-u[1]),_=J=>[u[0]+(x[0]-u[0])*J/P,u[1]+(x[1]-u[1])*J/P],y=(u[0]-ft.A[0])*ft.n[0]+(u[1]-ft.A[1])*ft.n[1],g=(x[0]-ft.A[0])*ft.n[0]+(x[1]-ft.A[1])*ft.n[1],T=[0,P];(y-ft.ridge)*(g-ft.ridge)<0&&T.splice(1,0,(ft.ridge-y)/(g-y)*P);const v=O.at+N,S=[],C=(J,B)=>{const z=_(J);S.push(z[0]*f,z[1]*f,B*f)};C(0,v),C(P,v);for(const J of[...T].reverse()){const B=_(J);C(J,ft.zAt(B[0],B[1]))}A.Profile=JSON.stringify([S]),delete A.TopLevel,delete A.TopOffset}const mt=typeof St=="string"?St:i&&h.item.guid?Gl(i,h.item.guid,jt):void 0;if(mt&&!A.Profile){A.AttachTop=nt(mt);const P=V.get(nt(mt));P&&(A.AttachTopMade=P)}if(mt&&typeof St!="string"&&typeof process<"u"&&((Xr=process.env)!=null&&Xr.RECIPE_TRACE)&&console.error(`[attach] ${h.item.guid} ${h.item.name??""} → ${mt}`),!A.Profile&&!A.AttachTop&&Rt){const P=[...i.elements.values()].filter(T=>T.host===h.item.guid&&!/^IFCOPENINGELEMENT$/i.test(T.ifcClass));let _=Is(i,h.item.guid,u,x,!0);const y=T=>{const v=[];for(const S of T)(!v.length||Math.hypot(S[0]-v[v.length-1][0],S[1]-v[v.length-1][1])>=.02)&&v.push(S);for(;v.length>1&&Math.hypot(v[0][0]-v[v.length-1][0],v[0][1]-v[v.length-1][1])<.02;)v.pop();return v};if(_!=null&&_.outline){const T=y(_.outline);_=T.length>=3?{..._,outline:T,holes:(_.holes??[]).map(y).filter(v=>v.length>=3)}:null}if(P.length&&(_!=null&&_.outline)){const T=Math.hypot(x[0]-u[0],x[1]-u[1]),v=[(x[0]-u[0])/T,(x[1]-u[1])/T],S=P.map(B=>{const z=Qt(i,B.gid).map(M=>[(M[0]-u[0])*v[0]+(M[1]-u[1])*v[1],M[2]]);return z.length?[Math.min(...z.map(M=>M[0])),Math.max(...z.map(M=>M[0])),Math.min(...z.map(M=>M[1])),Math.max(...z.map(M=>M[1]))]:null}).filter(B=>B!==null),C=B=>{const z=Math.min(...B.map(Ft=>Ft[0])),M=Math.max(...B.map(Ft=>Ft[0])),ot=Math.min(...B.map(Ft=>Ft[1])),Q=Math.max(...B.map(Ft=>Ft[1]));return S.some(Ft=>Math.min(M,Ft[1])-Math.max(z,Ft[0])>.01&&Math.min(Q,Ft[3])-Math.max(ot,Ft[2])>.01)},J=(_.holes??[]).filter(B=>!C(B));_=!((Zr=_.pieces)!=null&&Zr.length)&&(J.length||_.outline.length>4)?{..._,holes:J}:null,_&&typeof process<"u"&&((Qr=process.env)!=null&&Qr.RECIPE_TRACE)&&console.error(`[wall-outline] ${h.item.guid}: ${P.length} hosted, ${J.length} empty hole(s) kept`)}const g=_!=null&&_.outline?null:Is(i,h.item.guid,u,x);if(g){typeof process<"u"&&((ti=process.env)!=null&&ti.RECIPE_TRACE)&&console.error(`[wall-top] ${h.item.guid} ${h.item.name??""}: ${g.chain.map(([J,B])=>`${J.toFixed(2)}/${B.toFixed(2)}`).join(" ")}`);const T=Math.hypot(x[0]-u[0],x[1]-u[1]),v=[(x[0]-u[0])/T,(x[1]-u[1])/T],S=[],C=(J,B)=>{S.push((u[0]+J*v[0])*f,(u[1]+J*v[1])*f,B*f)};C(g.lo,g.bottom-ie),C(g.hi,g.bottom-ie);for(const[J,B]of[...g.chain].reverse())C(J,B-ie);A.Profile=JSON.stringify([S]),delete A.TopLevel,delete A.TopOffset}if(_!=null&&_.outline){typeof process<"u"&&((ei=process.env)!=null&&ei.RECIPE_TRACE)&&console.error(`[wall-outline] ${h.item.guid} ${h.item.name??""}: ${_.outline.length} corners`);const T=Math.hypot(x[0]-u[0],x[1]-u[1]),v=[(x[0]-u[0])/T,(x[1]-u[1])/T],S=C=>C.flatMap(([J,B])=>[(u[0]+J*v[0])*f,(u[1]+J*v[1])*f,(B-ie)*f]);A.Profile=JSON.stringify([S(_.outline),...(_.holes??[]).map(S)]),delete A.TopLevel,delete A.TopOffset,w=(_.pieces??[]).map(C=>JSON.stringify([S(C)]))}}else if(A.Profile&&Rt&&!A.AttachTop){const _=[...i.elements.values()].some(y=>y.host===h.item.guid&&!/^IFCOPENINGELEMENT$/i.test(y.ifcClass))?null:Is(i,h.item.guid,u,x,!0);if((ni=_==null?void 0:_.holes)!=null&&ni.length&&!((si=_.pieces)!=null&&si.length)){const y=Math.hypot(x[0]-u[0],x[1]-u[1]),g=[(x[0]-u[0])/y,(x[1]-u[1])/y],T=v=>v.flatMap(([S,C])=>[(u[0]+S*g[0])*f,(u[1]+S*g[1])*f,(C-ie)*f]);try{const v=JSON.parse(A.Profile);A.Profile=JSON.stringify([...v,..._.holes.map(T)]),typeof process<"u"&&((ri=process.env)!=null&&ri.RECIPE_TRACE)&&console.error(`[wall-holes] ${h.item.guid} ${h.item.name??""}: ${_.holes.length} hole(s) added to the converter's profile`)}catch{}}}const At=(m.clippedBy??[]).filter(P=>Array.isArray(P.through)&&Array.isArray(P.keep)&&Math.abs(P.keep[2])>.05);if(!o.arcMid&&At.length&&!A.AttachTop)try{const P=Math.hypot(x[0]-u[0],x[1]-u[1]),_=O.at+N,y=A.Profile?JSON.parse(A.Profile):[[u[0]*f,u[1]*f,_*f,x[0]*f,x[1]*f,_*f,x[0]*f,x[1]*f,(_+R)*f,u[0]*f,u[1]*f,(_+R)*f]];let g=[];for(let C=0;C+2<y[0].length;C+=3)g.push([y[0][C]/f,y[0][C+1]/f,y[0][C+2]/f]);const T=C=>{const J=[(x[0]-u[0])/P,(x[1]-u[1])/P];let B=0;for(let z=0;z<C.length;z++){const M=C[z],ot=C[(z+1)%C.length];B+=(M[0]*J[0]+M[1]*J[1])*ot[2]-(ot[0]*J[0]+ot[1]*J[1])*M[2]}return Math.abs(B)/2},v=T(g);for(const C of At){const J=z=>(z[0]-C.through[0])*C.keep[0]+(z[1]-C.through[1])*C.keep[1]+(z[2]-C.through[2])*C.keep[2],B=[];for(let z=0;z<g.length;z++){const M=g[z],ot=g[(z+1)%g.length],Q=J(M),Ft=J(ot);if(Q>=0&&B.push(M),Q>=0!=Ft>=0){const Dt=Q/(Q-Ft);B.push([0,1,2].map(Gt=>M[Gt]+Dt*(ot[Gt]-M[Gt])))}}g=B}const S=g.length>=3?T(g):0;S>.05&&v-S>.05&&(typeof process<"u"&&((ii=process.env)!=null&&ii.RECIPE_TRACE)&&console.error(`[wall-clip] ${h.item.guid} ${h.item.name??""}: ${At.length} plane(s), ${v.toFixed(2)} → ${S.toFixed(2)} m²`),A.Profile=JSON.stringify([g.flatMap(C=>[C[0]*f,C[1]*f,C[2]*f]),...y.slice(1)]),delete A.TopLevel,delete A.TopOffset)}catch{}if(!A.Profile&&Rt){const P=Qt(i,h.item.guid),_=Math.hypot(x[0]-u[0],x[1]-u[1]);if(P.length>=8&&_>.5){const y=[(x[0]-u[0])/_,(x[1]-u[1])/_],g=[-y[1],y[0]],T=(J,B)=>{const z=P.filter(M=>{const ot=(M[0]-u[0])*y[0]+(M[1]-u[1])*y[1];return ot>=J*_&&ot<=B*_}).map(M=>(M[0]-u[0])*g[0]+(M[1]-u[1])*g[1]);return z.length>=2?{c:(Math.max(...z)+Math.min(...z))/2,w:Math.max(...z)-Math.min(...z)}:null},v=T(-.02,.06),S=T(.94,1.02),C=T(.45,.55);if(v&&S&&C){const J=(v.c+S.c)/2,B=C.c-J,z=P.map(Q=>{const Ft=Math.min(Math.max(((Q[0]-u[0])*y[0]+(Q[1]-u[1])*y[1])/_,0),1);return(Q[0]-u[0])*g[0]+(Q[1]-u[1])*g[1]-J-4*B*Ft*(1-Ft)}),M=Math.max(...z)-Math.min(...z),ot=M<(v.w+S.w)/2+.01&&C.w>.5*Math.min(v.w,S.w);if(typeof process<"u"&&((ai=(oi=process.env)==null?void 0:oi.RECIPE_WALL)!=null&&ai.split(",").includes(h.item.guid??""))&&console.error(`[arc-bands] ${JSON.stringify({b0:v,bm:C,b1:S,sag:B,spread:M})}`),ot&&Math.abs(B)>.02&&Math.abs(B)<_/2){const Q=[(u[0]+x[0])/2+g[0]*B,(u[1]+x[1])/2+g[1]*B];A.LocationArc=`${Ct(Q[0]*f)},${Ct(Q[1]*f)},${Ct(It)}`,typeof process<"u"&&((ci=process.env)!=null&&ci.RECIPE_TRACE)&&console.error(`[wall-arc] ${h.item.guid} ${h.item.name??""}: bows ${(B*100).toFixed(1)} cm over ${_.toFixed(2)} m`)}}}}const xt=pt(q);if(xt&&(A["Type.Width"]=Ct(xt)),xt){const P=U.get(A.Type);P===void 0?U.set(A.Type,xt):Math.abs(P-xt)>.001&&(A.Type=`${A.Type} · ${Math.round(xt/f*1e3)} mm`)}const Jt=h.item.guid?i==null?void 0:i.elements.get(h.item.guid):void 0;if(Jt!=null&&Jt.layers&&Jt.layers.length>1)A["Type.Layers"]=JSON.stringify([...Jt.layers].reverse().map(P=>[+Ct(P.thickness*f),P.material??"",P.function??""])),Jt.layersFlipped&&(A.FlipLayers="1");else if(typeof process<"u"&&((li=process.env)!=null&&li.RECIPE_PIECE_LAYERS)&&Jt&&Jt.pieces.length>=2&&xt&&h.item.guid){const P=Math.hypot(x[0]-u[0],x[1]-u[1]),_=[(x[0]-u[0])/P,(x[1]-u[1])/P],y=[];Jt.pieces.forEach((v,S)=>{const C=Qt(i,h.item.guid,S);if(C.length<4)return;const J=C.map(Q=>(Q[0]-u[0])*_[0]+(Q[1]-u[1])*_[1]),B=C.map(Q=>-(Q[0]-u[0])*_[1]+(Q[1]-u[1])*_[0]),z=C.map(Q=>Q[2]);if(Math.max(...J)-Math.min(...J)<Math.min(.3,.5*P)||Math.max(...z)-Math.min(...z)<.5*R)return;const M=Math.min(...B),ot=Math.max(...B);y.some(Q=>Math.abs(Q[0]-M)<.002&&Math.abs(Q[1]-ot)<.002)||y.push([M,ot])}),y.sort((v,S)=>S[1]-v[1]);const g=y.length?y[0][1]-y[y.length-1][0]:0,T=y.every((v,S)=>S===0||v[1]<=y[S-1][0]+.002);if(y.length>=2&&T&&Math.abs(g-xt/f)<.01){const v=[];y.forEach((B,z)=>{const M=ot=>+Ct(Math.round(ot*2e3)/2e3*f);z>0&&y[z-1][0]-B[1]>.003&&v.push([M(y[z-1][0]-B[1]),"","air"]),v.push([M(B[1]-B[0]),"",""])});const S=JSON.stringify(v),C=JSON.stringify([...v].reverse()),J=Z.get(A.Type);J===void 0&&Z.set(A.Type,S),J===void 0||J===S?A["Type.Layers"]=S:J===C&&(A["Type.Layers"]=J,A.FlipLayers="1"),typeof process<"u"&&((hi=process.env)!=null&&hi.RECIPE_TRACE)&&console.error(`[piece-layers] ${h.item.guid} ${A.Type}: ${S}${J&&J!==S?J===C?" (flipped)":" (the type stacks otherwise: kept)":""}`)}}if(!A["Type.Layers"]&&typeof process<"u"&&((fi=process.env)!=null&&fi.RECIPE_LAYER_EXT)){const P=(()=>{var y,g;try{return JSON.parse(String(((g=(y=F.get(q))==null?void 0:y.params)==null?void 0:g.definition)??"null"))}catch{return null}})(),_=(P==null?void 0:P.layers)??[];if(_.length>1&&_.some(y=>(y.topExtension??0)>.001||(y.baseExtension??0)>.001)){A["Type.Layers"]=JSON.stringify(_.map(C=>[+Ct((C.thickness??0)*f),C.material??"",C.function??"",+Ct((C.topExtension??0)*f),+Ct((C.baseExtension??0)*f)]));const y=Math.max(..._.map(C=>C.topExtension??0)),g=Math.max(..._.map(C=>C.baseExtension??0)),T=(C,J)=>{if(!i||!h.item.guid)return[];const B=Qt(i,h.item.guid);if(B.length<4)return[];const z=[Math.min(...B.map(M=>M[0])),Math.min(...B.map(M=>M[1])),Math.max(...B.map(M=>M[0])),Math.max(...B.map(M=>M[1]))];return ut().filter(M=>M.box[0]<z[2]-.01&&z[0]<M.box[3]-.01&&M.box[1]<z[3]-.01&&z[1]<M.box[4]-.01&&M.box[2]<J-.01&&C<M.box[5]-.01).flatMap(M=>M.keys)},v=O.at+N+ie,S=typeof process<"u"&&((di=process.env)!=null&&di.RECIPE_EXT_CUT)&&!A.Profile&&y>.001&&g<.001?T(v+R,v+R+y):[];S.length&&(A.Height||A.TopOffset)?(A["Type.Layers"]=JSON.stringify(_.map(C=>[+Ct((C.thickness??0)*f),C.material??"",C.function??""])),A.TopOffset?A.TopOffset=Ct(Number(A.TopOffset)+y*f):A.Height=Ct(Number(A.Height)+y*f),A.CutBy=[...A.CutBy?A.CutBy.split("|"):[],...S].join("|"),typeof process<"u"&&((ui=process.env)!=null&&ui.RECIPE_TRACE)&&console.error(`[layer-extension] ${h.item.guid} ${A.Type}: up ${y} to its finish's top, cut by ${S.length} slab(s)`)):(y>.001&&(A.TopExtension=Ct(y*f)),g>.001&&(A.BaseExtension=Ct(g*f))),typeof process<"u"&&((pi=process.env)!=null&&pi.RECIPE_TRACE)&&console.error(`[layer-extension] ${h.item.guid} ${A.Type}: top ${y}, base ${g}`)}}typeof process<"u"&&((gi=(mi=process.env)==null?void 0:mi.RECIPE_WALL)!=null&&gi.split(",").includes(h.item.guid??""))&&console.error(`[wall-attrs] ${JSON.stringify(A).slice(0,1500)} style ${JSON.stringify(((yi=F.get(q))==null?void 0:yi.params)??null).slice(0,800)}`),st(`${nt(h.id)}#${o.i}`,A)&&Yt++,w.forEach((P,_)=>{st(`${nt(h.id)}#${o.i}p${_+1}`,{...A,Profile:P})&&Yt++})}const Ke=(o,h,w)=>{if(!(h>0)||h>=o)return[];const m=o-Math.floor(o/h+1e-9)*h,N=w==="beginning"?0:w==="end"?m:w==="centreLine"?o/2%h:m/2,R=[];for(let O=N;O<=o+1e-4;O+=h)O>1e-4&&O<o-1e-4&&R.push(O);return R};let jn=0,Er=0;const Tr=new Map;for(const o of a){if(o.kind!=="run"||o.params.of!=="curtainWall")continue;Er++;const h=de(o,"run"),w=(vi=(bi=(wi=h==null?void 0:h.run)==null?void 0:wi.line)==null?void 0:bi.curves)==null?void 0:vi[0],m=$.get(String((h==null?void 0:h.level)??o.params.level??"")),N=o.params.lookRef,R=typeof N=="string"?(Ei=F.get(N))==null?void 0:Ei.params:void 0;if(!(w!=null&&w.from)||!w.to||typeof(h==null?void 0:h.height)!="number"||!m||!R)continue;const O=y=>typeof y=="number"?y:Number(y)||0,q=Math.hypot(w.to[0]-w.from[0],w.to[1]-w.from[1]),u=[(w.to[0]-w.from[0])/q,(w.to[1]-w.from[1])/q],x=O(R.uprightWidth)>0?null:Le(o.item.guid??void 0,u),gt=(O(R.uprightWidth)||(x?x.width/f:0))/2,$t=(O(R.horizontalWidth)||(x?x.width/f:0))/2,Rt={start:!1,end:!1,bottom:!1,top:!1};let It=[];if(i&&o.item.guid&&!Array.isArray(h.profile)){const y=[...i.elements.values()].filter(S=>S.parent===o.item.guid),g=S=>{const C=Qt(i,S);if(!C.length)return null;const J=C.map(z=>(z[0]-w.from[0])*u[0]+(z[1]-w.from[1])*u[1]),B=C.map(z=>z[2]);return{t0:Math.min(...J),t1:Math.max(...J),z0:Math.min(...B),z1:Math.max(...B)}},T=y.map(S=>g(S.gid)).filter(S=>S!==null),v=y.filter(S=>/^IFCMEMBER$/i.test(S.ifcClass)).map(S=>g(S.gid)).filter(S=>S!==null);if(v.length&&T.length){const S=Math.min(...T.map(M=>M.t0)),C=Math.max(...T.map(M=>M.t1)),J=Math.min(...T.map(M=>M.z0)),B=Math.max(...T.map(M=>M.z1)),z=M=>M.t1-M.t0>M.z1-M.z0;Rt.bottom=!v.some(M=>z(M)&&Math.abs(M.z0-J)<.01),Rt.top=!v.some(M=>z(M)&&Math.abs(M.z1-B)<.01),Rt.start=!v.some(M=>!z(M)&&Math.abs(M.t0-S)<.01),Rt.end=!v.some(M=>!z(M)&&Math.abs(M.t1-C)<.01),It=[...new Set(v.filter(M=>!z(M)&&M.t0>S+.01&&M.t1<C-.01).map(M=>+((M.t0+M.t1)/2).toFixed(4)))].sort((M,ot)=>M-ot),Object.values(Rt).some(Boolean)&&typeof process<"u"&&((Ti=process.env)!=null&&Ti.RECIPE_TRACE)&&console.error(`[curtain-bare] ${o.item.guid}: no bar at its ${Object.entries(Rt).filter(([,M])=>M).map(([M])=>M).join(", ")}`)}}const yt=Rt.start?0:gt,A=Rt.end?0:gt,Ot=Rt.bottom?0:$t,lt=Rt.top?0:$t,bt=[w.from[0]-u[0]*yt,w.from[1]-u[1]*yt],K=[w.to[0]+u[0]*A,w.to[1]+u[1]*A],G=(typeof h.base=="number"?h.base:0)-Ot,et=h.height+Ot+lt,H=(m.at+G)*f,St=Ke(q,O(R.alongSpacing),R.alongJustify),rt=!((Mi=h.lines)!=null&&Mi.along)&&It.length>0&&(It.length!==St.length||It.some((y,g)=>Math.abs(y-St[g])>.01));rt&&typeof process<"u"&&(($i=process.env)!=null&&$i.RECIPE_TRACE)&&console.error(`[curtain-lines] ${o.item.guid}: ${It.length} from its bars, not the type's ${St.length}`);const ft=((Ii=h.lines)==null?void 0:Ii.along)??(rt?It:St),mt=((Si=h.lines)==null?void 0:Si.up)??Ke(h.height,O(R.upSpacing),R.upJustify),At=(h.omitted??[]).flatMap(y=>{const g=/^(horizontal|vertical)@(-?[\d.]+):(-?[\d.]+)$/.exec(y);if(!g)return[];const T=g[1]==="horizontal",v=Number(g[2])/1e3+(T?Ot:yt),S=Number(g[3])/1e3+(T?yt:Ot);return[{horizontal:T,at:v*f,from:S*f}]}),xt=Rt.start&&Rt.end&&Rt.bottom&&Rt.top;if(!xt){const y=[0,...ft.map(v=>v+yt)],g=[0,...mt.map(v=>v+Ot)],T=q+yt+A;if(Rt.bottom)for(const v of y)At.push({horizontal:!0,at:0,from:v*f});if(Rt.top)for(const v of y)At.push({horizontal:!0,at:et*f,from:v*f});if(Rt.start)for(const v of g)At.push({horizontal:!1,at:0,from:v*f});if(Rt.end)for(const v of g)At.push({horizontal:!1,at:T*f,from:v*f})}const Jt=(h.omitted??[]).flatMap(y=>{const g=/^panel@(-?[\d.]+),(-?[\d.]+)$/.exec(y);return g?[{along:(Number(g[1])/1e3+yt)*f,up:(Number(g[2])/1e3+Ot)*f}]:[]});if(i&&o.item.guid)for(const y of ql(i,o.item.guid,O(R.panelDepth),[-u[1],u[0]])){const g=(y.centre[0]-w.from[0])*u[0]+(y.centre[1]-w.from[1])*u[1],T=y.centre[2]-ie-(m.at+(typeof h.base=="number"?h.base:0));if(g<-.01||g>q+.01||T<-.01||T>h.height+.01)continue;const v=Math.max(0,...ft.filter(C=>C<=g+1e-6)),S=Math.max(0,...mt.filter(C=>C<=T+1e-6));Jt.push({along:(v+yt)*f,up:(S+Ot)*f}),Pt.add(y.gid)}const P={CategoryId:De.walls,Type:((xi=Sn(o))==null?void 0:xi.type)??String(N),LocationLine:`${Ct(bt[0]*f)},${Ct(bt[1]*f)},${Ct(H)};${Ct(K[0]*f)},${Ct(K[1]*f)},${Ct(H)}`,Level:m.name,BaseOffset:Ct(G*f),Height:Ct(et*f),Curtain:JSON.stringify({along:ft.map(y=>(y+yt)*f),up:mt.map(y=>(y+Ot)*f),omit:At,empty:Jt,...xt?{noBorders:!0}:{},mullion:O(R.uprightWidth)>0?{width:O(R.uprightWidth)*f,depth:O(R.depth)*f}:x??{width:0,depth:O(R.depth)*f},panel:{thickness:me(o.item.guid??void 0,u)??O(R.panelDepth)*f,offset:-O(R.panelOffset)*f}})},_=h.profile;if(Array.isArray(_)&&_.length>=3){const g=_.reduce((C,J,B)=>{const z=_[(B+1)%_.length];return C+J[0]*z[1]-z[0]*J[1]},0)>0?1:-1,T=_.length,v=_.map((C,J)=>{const B=_[(J-1+T)%T],z=_[(J+1)%T],M=(Gt,ee)=>{const Zt=ee[0]-Gt[0],ne=ee[1]-Gt[1],Ut=Math.hypot(Zt,ne)||1,fe=g*ne/Ut,Be=-g*Zt/Ut,pn=Math.abs(fe)>Math.abs(Be)?gt:$t;return{p:[Gt[0]+fe*pn,Gt[1]+Be*pn],d:[Zt,ne]}},ot=M(B,C),Q=M(C,z),Ft=ot.d[0]*Q.d[1]-ot.d[1]*Q.d[0];if(Math.abs(Ft)<1e-12)return[Q.p[0],Q.p[1]];const Dt=((Q.p[0]-ot.p[0])*Q.d[1]-(Q.p[1]-ot.p[1])*Q.d[0])/Ft;return[ot.p[0]+Dt*ot.d[0],ot.p[1]+Dt*ot.d[1]]}),S=[];for(const[C,J]of v)S.push((w.from[0]+u[0]*C)*f,(w.from[1]+u[1]*C)*f,(m.at+G+$t+J)*f);P.Profile=JSON.stringify([S])}{const y=JSON.parse(P.Curtain),g=y.mullion,T=(_i=y.panel)!=null&&_i.thickness?`, ${Math.round(y.panel.thickness/f*1e3)} mm glass`:"",v=`${Math.round(g.width/f*1e3)} x ${Math.round(g.depth/f*1e3)}${T}${y.noBorders?", no borders":""}`,S=Tr.get(P.Type);S===void 0?Tr.set(P.Type,v):S!==v&&(typeof process<"u"&&((Ai=process.env)!=null&&Ai.RECIPE_TRACE)&&console.error(`[curtain-type] ${o.item.guid}: ${P.Type} first made with ${S}, this one ${v}`),P.Type=`${P.Type} · ${v}`)}st(nt(o.id),P)&&jn++}let Dn=0,Mr=0;const $r=(o,h,w)=>{if(!i||!o)return null;const m=Math.hypot(w[0]-h[0],w[1]-h[1]);if(!(m>0))return null;const N=[-(w[1]-h[1])/m,(w[0]-h[0])/m],R=[o,...[...i.elements.values()].filter(u=>u.parent===o).map(u=>u.gid)].flatMap(u=>Qt(i,u));if(R.length<4)return null;const O=R.map(u=>(u[0]-h[0])*N[0]+(u[1]-h[1])*N[1]),q=Math.max(...O)-Math.min(...O);return q>.3&&q<10?q:null};for(const o of a){if(o.kind!=="stair"||o.params.of!=="stair")continue;Mr++;const h=de(o,"stair"),w=o.params.lookRef,m=typeof w=="string"?(Ci=F.get(w))==null?void 0:Ci.params:void 0,N=$.get(String((h==null?void 0:h.level)??o.params.level??""));if(!(h!=null&&h.start)||!h.end||!(Number(h.rise)>0)||!N||!m)continue;const R=K=>typeof K=="number"?K:Number(K)||0,O=Number(h.rise),q=R(m.maxRiser)>0?R(m.maxRiser):(Oi=(Ri=h.sketch)==null?void 0:Ri.risers)!=null&&Oi.length?O/(h.sketch.risers.length+1):.18,u=Math.max(1,Math.ceil(O/q-1e-6)),x=R(m.tread),gt=K=>[K[0]*f,K[1]*f];let $t=N.at+R(o.params.base),Rt=!1;if(i&&o.item.guid){const K=Qt(i,o.item.guid).map(H=>H[2]-ie),G=O/u,et=K.length?Math.min(...K):$t;$t-et>.5*G&&$t-et<1.5*G&&(typeof process<"u"&&((ki=process.env)!=null&&ki.RECIPE_TRACE)&&console.error(`[stair-base] ${o.item.guid} ${o.item.name??""}: base ${$t.toFixed(3)} → its shape's ${et.toFixed(3)}`),$t=et,Rt=!0)}const It={family:(()=>{const K=String(w).split(":").map(G=>G.trim()).filter((G,et,H)=>et<H.length-1||!/^\d+$/.test(G));return K.length>=3&&/^(stairs?|escaleras?|treppen?)$/i.test(K[0])?K[1]:K[0]})(),base:$t*f,height:O*f,risers:u,tread:x*f,width:(R(m.width)>0?R(m.width):$r(o.item.guid??void 0,h.start,h.end)??0)*f,endsWithRiser:(()=>{if(!i||!o.item.guid)return!1;const K=Qt(i,o.item.guid);if(K.length<4)return!1;const G=Math.max(...K.map(H=>H[2]))-ie,et=N.at+R(o.params.base)+O;return et-G>.5*(O/u)&&et-G<1.5*(O/u)})(),sizes:{maxRiser:Math.ceil(O/u*1e3-1e-6)/1e3*f,minTread:x*f,waist:R(m.waist)*f,treadThickness:m.construction==="assembled"?R(m.treadThickness)*f:0,riserThickness:m.construction==="assembled"?R(m.riserThickness)*f:0,notchExtension:R(m.notchExtension)*f,notchThickness:R(m.notchThickness)*f,...m.nosing!==void 0&&Number.isFinite(Number(m.nosing))?{nosing:Number(m.nosing)*f}:{}}};typeof process<"u"&&((Ni=process.env)!=null&&Ni.RECIPE_TRACE)&&console.error(`[stair-end] ${o.item.guid} ${o.item.name??""}: ${u} risers, ends with riser ${It.endsWithRiser}`);const yt=h.sketch;if(yt!=null&&yt.boundary&&yt.risers&&yt.risers.length>=2){const K=rt=>[(rt[0][0]+rt[1][0])/2,(rt[0][1]+rt[1][1])/2],G=yt.risers.filter((rt,ft,mt)=>ft===0||Math.hypot(K(rt)[0]-K(mt[ft-1])[0],K(rt)[1]-K(mt[ft-1])[1])>.01),et=(rt,ft)=>Math.hypot(rt[0]-ft[0],rt[1]-ft[1])<.01,H=yt.boundary,St=rt=>H.some((ft,mt)=>{const At=H[(mt+1)%H.length];return et(ft,rt[0])&&et(At,rt[1])||et(ft,rt[1])&&et(At,rt[0])});if(G.length>=2&&!St(G[0])){const[rt,ft]=[G[0],G[1]],mt=[rt[1][0]-rt[0][0],rt[1][1]-rt[0][1]],At=Math.hypot(mt[0],mt[1]),xt=K(rt),Jt=K(ft),P=[xt[0]-Jt[0],xt[1]-Jt[1]];let _=null,y=1/0;for(let g=0;g<H.length;g++){const T=H[g],v=H[(g+1)%H.length],S=[v[0]-T[0],v[1]-T[1]],C=Math.hypot(S[0],S[1]);if(!(C>0)||Math.abs((S[0]*mt[1]-S[1]*mt[0])/(C*At))>.02)continue;const J=K([T,v]),B=(J[0]-xt[0])*P[0]+(J[1]-xt[1])*P[1];B>1e-4&&B<y&&(y=B,_=[T,v])}_&&G.unshift(_)}G.length!==yt.risers.length&&typeof process<"u"&&((Fi=process.env)!=null&&Fi.RECIPE_TRACE)&&console.error(`[stair-sketch] ${o.item.guid}: riser lines ${yt.risers.length} → ${G.length}`),yt.risers=G}if(yt!=null&&yt.boundary&&yt.boundary.length>=4&&yt.risers&&yt.risers.length>=2){const K=yt.risers[0],G=(g,T)=>Math.hypot(g[0]-T[0],g[1]-T[1])<.01,et=yt.boundary.findIndex((g,T,v)=>{const S=v[(T+1)%v.length];return G(g,K[0])&&G(S,K[1])||G(g,K[1])&&G(S,K[0])}),H=et>0?[...yt.boundary.slice(et),...yt.boundary.slice(0,et)]:yt.boundary;typeof process<"u"&&((Pi=process.env)==null?void 0:Pi.RECIPE_STAIR)===o.item.guid&&console.error(`[stair-sketch] boundary ${JSON.stringify(H)} (turned by ${et}) risers ${JSON.stringify(yt.risers)} tread ${x}`);const St=yt.risers[yt.risers.length-1],rt=g=>[(g[0][0]+g[1][0])/2,(g[0][1]+g[1][1])/2],ft=rt(St);let mt=1,At=1/0;for(let g=1;g<H.length;g++){const T=rt([H[g],H[(g+1)%H.length]]),v=Math.abs(Math.hypot(T[0]-ft[0],T[1]-ft[1])-x);v<At&&(At=v,mt=g)}{const g=[St[1][0]-St[0][0],St[1][1]-St[0][1]],T=Math.hypot(g[0],g[1]),v=rt(yt.risers[0]);let S=-1/0,C=-1;for(let J=1;J<H.length;J++){const B=[H[(J+1)%H.length][0]-H[J][0],H[(J+1)%H.length][1]-H[J][1]],z=Math.hypot(B[0],B[1]);if(!(z>0)||Math.abs((B[0]*g[1]-B[1]*g[0])/(z*T))>.06)continue;const M=rt([H[J],H[(J+1)%H.length]]),ot=Math.hypot(M[0]-v[0],M[1]-v[1]);ot>S+1e-6&&(S=ot,C=J)}C>0&&(mt=C)}const xt=(g,T)=>{const v=[];for(let S=g;S!==T;S=(S+1)%H.length)v.push([gt(H[S]),gt(H[(S+1)%H.length])]);return v},Jt=[...xt(1,mt),...xt((mt+1)%H.length,0)];typeof process<"u"&&((Li=process.env)==null?void 0:Li.RECIPE_STAIR)===o.item.guid&&console.error(`[stair-sketch] end edge ${mt} of ${H.length}`);const P=yt.risers.map(([g,T])=>[gt(g),gt(T)]);gt(H[mt]),gt(H[(mt+1)%H.length]);const _=P.map(([g,T])=>[(g[0]+T[0])/2,(g[1]+T[1])/2]);if(It.sketch={boundary:Jt,risers:P,path:_},It.path=[_[0],_[_.length-1]],It.width||(It.width=Math.hypot(P[0][1][0]-P[0][0][0],P[0][1][1]-P[0][0][1])),typeof process<"u"&&((Bi=process.env)!=null&&Bi.RECIPE_TRACE)){const g=T=>Math.hypot(T[1][0]-T[0][0],T[1][1]-T[0][1])/f;console.error(`[stair] ${o.item.guid} ${o.item.name??""}: ${Jt.length} sides (shortest ${(Math.min(...Jt.map(g))*1e3).toFixed(2)} mm), ${P.length} risers (shortest ${(Math.min(...P.map(g))*1e3).toFixed(2)} mm), walk ${_.length} points (shortest step ${(Math.min(..._.slice(1).map((T,v)=>g([_[v],T])))*1e3).toFixed(2)} mm)`)}let y=1/0;for(let g=0;g+1<yt.risers.length;g++){const[T,v]=yt.risers[g],[S,C]=yt.risers[g+1],J=[v[0]-T[0],v[1]-T[1]],B=[C[0]-S[0],C[1]-S[1]],z=Math.hypot(J[0],J[1]),M=Math.hypot(B[0],B[1]);Math.abs((J[0]*B[1]-J[1]*B[0])/(z*M))>.001||(y=Math.min(y,Math.abs(((S[0]-T[0])*J[1]-(S[1]-T[1])*J[0])/z)))}if(Number.isFinite(y)&&(It.tread=y*f,It.sizes.minTread=y*f,Rt)){const g=It.path,T=Math.hypot(g[1][0]-g[0][0],g[1][1]-g[0][1]);T>0&&(It.path=[[g[0][0]-(g[1][0]-g[0][0])/T*y*f,g[0][1]-(g[1][1]-g[0][1])/T*y*f],g[1]])}}else{let K=[h.start[0],h.start[1]];if(Rt&&x>0){const G=h.end[0]-h.start[0],et=h.end[1]-h.start[1],H=Math.hypot(G,et);H>0&&(K=[K[0]-x*G/H,K[1]-x*et/H])}if(It.path=[gt(K),gt([h.end[0],h.end[1]])],!(x>0)){const G=Math.hypot(h.end[0]-h.start[0],h.end[1]-h.start[1])/u;It.tread=G*f,It.sizes.minTread=G*f}typeof process<"u"&&((ji=process.env)!=null&&ji.RECIPE_TRACE)&&console.error(`[stair] ${o.item.guid} ${o.item.name??""}: straight, ${Math.hypot(h.end[0]-h.start[0],h.end[1]-h.start[1]).toFixed(3)} m, rise ${O}, ${u} risers, width ${R(m.width)}, measured ${$r(o.item.guid??void 0,h.start,h.end)}`)}const A=String(o.item.attrs.Name??""),Ot=A.replace(/ Run \d+$/,""),lt=[];for(const K of a){if(K.kind!=="extrusion"||Ot===A||!new RegExp(`^${Ot.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")} Landing \\d+$`).test(String(K.item.attrs.Name??"")))continue;const G=de(K,"extrusion"),et=G==null?void 0:G.on,H=(((Ui=(Di=G==null?void 0:G.profile)==null?void 0:Di.outline)==null?void 0:Ui.curves)??[]).flatMap(S=>S.from?[S.from]:[]),St=pt(K.params.lookRef),rt=$.get(String((G==null?void 0:G.level)??K.params.level??""));if(!(et!=null&&et.origin)||!et.u||!et.v||Math.abs(et.v[2]??0)<.99||!H.length||!St||!rt)continue;const[ft,mt]=[Math.min(...H.map(S=>S[0])),Math.max(...H.map(S=>S[0]))],[At,xt]=[Math.min(...H.map(S=>S[1])),Math.max(...H.map(S=>S[1]))],Jt=et.origin,P=et.u;let _=[P[1],-P[0]];const y=[(h.start[0]+h.end[0])/2,(h.start[1]+h.end[1])/2];(y[0]-Jt[0])*_[0]+(y[1]-Jt[1])*_[1]<0&&(_=[-_[0],-_[1]]);const T=St/f,v=(S,C)=>[(Jt[0]+P[0]*S+_[0]*C)*f,(Jt[1]+P[1]*S+_[1]*C)*f];lt.push({outline:[v(ft,0),v(mt,0),v(mt,T),v(ft,T)],top:(rt.at+R(K.params.base)+Jt[2]+xt)*f,thickness:(xt-At)*f})}lt.length&&(It.landings=lt);const bt={CategoryId:De.stairs,Type:((Ji=Sn(o))==null?void 0:Ji.type)??String(w),Level:N.name,Stairs:JSON.stringify(It)};typeof process<"u"&&(((qi=process.env)==null?void 0:qi.RECIPE_STAIR)===o.item.guid||((Gi=process.env)==null?void 0:Gi.RECIPE_STAIR)==="*")&&console.error(`[stair-spec] ${bt.Stairs} style ${JSON.stringify(m)}`),st(nt(o.id),bt)&&Dn++}const Ir=new Map,fn={floor:0,foundation:0,roof:0,ceiling:0},pe={floor:0,foundation:0,roof:0,ceiling:0},Sr=a.flatMap(o=>{var R,O;if(o.kind!=="extrusion"||o.params.of!=="form")return[];const h=de(o,"extrusion"),w=$.get(String((h==null?void 0:h.level)??o.params.level??"")),m=(((O=(R=h==null?void 0:h.profile)==null?void 0:R.outline)==null?void 0:O.curves)??[]).flatMap(q=>q.from?[q.from]:[]);if(!(h!=null&&h.void)||!w||m.length<3)return[];const N=w.at+(Number(o.params.base)||0);return[{guid:o.item.guid,outline:m,from:N,to:N+(Number(h.depth??o.params.depth)||0)}]});for(const o of a){const h=o.params.of;if(o.kind!=="extrusion"||h!=="slab"&&h!=="roof"&&h!=="covering")continue;let w=h==="covering"?"ceiling":h==="roof"?"roof":Go(o);if(w==="other"||i&&o.item.guid&&/^IFCRAMP(FLIGHT)?$/i.test(((Hi=i.elements.get(o.item.guid))==null?void 0:Hi.ifcClass)??""))continue;const m=de(o,"extrusion"),N=m==null?void 0:m.on;if(N&&(Math.abs(((Vi=N.u)==null?void 0:Vi[2])??0)>.001||Math.abs(((zi=N.v)==null?void 0:zi[2])??0)>.001))continue;if(w==="roof"&&!Bt(o)){const lt=m,bt=((Yi=(Wi=m==null?void 0:m.profile)==null?void 0:Wi.outline)==null?void 0:Yi.curves)??[];if(lt!=null&&lt.slope&&typeof lt.slope.by=="number"&&Math.abs(lt.slope.by)>.001&&typeof lt.slope.toward=="number"&&!(Array.isArray(lt.slopes)&&lt.slopes.some(K=>typeof K=="number"))&&bt.length>=3){const K=[Math.cos(lt.slope.toward),Math.sin(lt.slope.toward)],G=bt.map(rt=>rt.from).filter(Boolean),et=G.map(rt=>rt[0]*K[0]+rt[1]*K[1]),H=Math.min(...et);G.some((rt,ft)=>Math.abs(et[ft]-H)<.01&&Math.abs(et[(ft+1)%G.length]-H)<.01)||(w="floor",typeof process<"u"&&((Ki=process.env)!=null&&Ki.RECIPE_TRACE)&&console.error(`[roof-as-floor] ${o.item.guid} ${o.params.lookRef}: its low side a corner, a sloped floor`))}}fn[w]++,typeof process<"u"&&((Xi=process.env)==null?void 0:Xi.RECIPE_SLAB)===o.item.guid&&console.error(`[slab] ${o.item.guid}: params ${JSON.stringify(o.params).slice(0,600)} body ${JSON.stringify(m).slice(0,1500)}`);const R=typeof o.params.base=="number"?o.params.base:0,O=$.get(String((m==null?void 0:m.level)??o.params.level??"")),q=o.params.lookRef,u=lt=>{if(!(lt!=null&&lt.length))return null;const bt=[];for(const K of lt){if(K.kind!=="segment"||!K.from)return null;bt.push(K.from[0]*f,K.from[1]*f,R*f)}return bt.length>=9?bt:null},x=u((Qi=(Zi=m==null?void 0:m.profile)==null?void 0:Zi.outline)==null?void 0:Qi.curves);if(typeof q!="string"||!O||!x)continue;const gt=[x],$t=w==="roof"?Bt(o):null;for(const lt of((to=m==null?void 0:m.profile)==null?void 0:to.holes)??[]){const bt=u(lt==null?void 0:lt.curves);if(bt&&$t)for(let K=0;K+2<bt.length;K+=3)bt[K+2]=$t.zAt(bt[K]/f,bt[K+1]/f)*f;bt&&gt.push(bt)}const Rt=[...(m==null?void 0:m.cuts)??[]],It=O.at+R,yt=It+(Number(o.params.depth)||0);for(const lt of Sr)lt.from<yt-.001&&It<lt.to-.001&&Rt.push({outline:lt.outline,through:[0,0,lt.to-lt.from]});for(const lt of Rt){const bt=lt.through,K=lt.outline;if(!Array.isArray(K)||K.length<3||!Array.isArray(bt)||Math.abs(bt[2])<.99*Math.hypot(bt[0],bt[1],bt[2]))continue;const G=K.filter((y,g)=>g===0||Math.hypot(y[0]-K[g-1][0],y[1]-K[g-1][1])>1e-4);if(G.length>3&&Math.hypot(G[0][0]-G[G.length-1][0],G[0][1]-G[G.length-1][1])<1e-4&&G.pop(),G.length<3)continue;const et=(y,g)=>{let T=!1;for(let v=0,S=x.length/3-1;v<x.length/3;S=v++){const C=x[3*v]/f,J=x[3*v+1]/f,B=x[3*S]/f,z=x[3*S+1]/f;J>g!=z>g&&y<(B-C)*(g-J)/(z-J)+C&&(T=!T)}return T};if(!G.every(y=>et(y[0],y[1]))){typeof process<"u"&&((eo=process.env)!=null&&eo.RECIPE_TRACE)&&console.error(`[slab-cut] ${o.item.guid}: a cut across its edge, left`);continue}const H=y=>[Math.min(...y.map(g=>g[0])),Math.min(...y.map(g=>g[1])),Math.max(...y.map(g=>g[0])),Math.max(...y.map(g=>g[1]))],St=y=>{const g=[];for(let T=0;T+2<y.length;T+=3)g.push([y[T]/f,y[T+1]/f]);return g},rt=H(G),ft=(y,g,T)=>{let v=!1;for(let S=0,C=y.length-1;S<y.length;C=S++)y[S][1]>T!=y[C][1]>T&&g<(y[C][0]-y[S][0])*(T-y[S][1])/(y[C][1]-y[S][1])+y[S][0]&&(v=!v);return v},mt=(y,g,T)=>{const v=T[0]-g[0],S=T[1]-g[1],C=Math.max(0,Math.min(1,((y[0]-g[0])*v+(y[1]-g[1])*S)/(v*v+S*S||1)));return Math.hypot(y[0]-(g[0]+C*v),y[1]-(g[1]+C*S))},At=(y,g)=>y.some(T=>ft(g,T[0],T[1])||g.some((v,S)=>mt(T,v,g[(S+1)%g.length])<.01)),xt=gt.slice(1).some(y=>{const g=St(y),T=H(g);return rt[0]<T[2]+.01&&T[0]<rt[2]+.01&&rt[1]<T[3]+.01&&T[1]<rt[3]+.01&&(At(G,g)||At(g,G))}),Jt=St(x),P=G.some(y=>Jt.some((g,T)=>{const v=Jt[(T+1)%Jt.length],S=v[0]-g[0],C=v[1]-g[1],J=S*S+C*C||1,B=Math.max(0,Math.min(1,((y[0]-g[0])*S+(y[1]-g[1])*C)/J));return Math.hypot(y[0]-(g[0]+B*S),y[1]-(g[1]+B*C))<.01}));if(xt||P){typeof process<"u"&&((no=process.env)!=null&&no.RECIPE_TRACE)&&console.error(`[slab-cut] ${o.item.guid}: a cut ${xt?"over another hole":"at its edge"}, left`);continue}const _=G.flatMap(y=>[y[0]*f,y[1]*f,($t?$t.zAt(y[0],y[1]):R)*f]);gt.push(_),typeof process<"u"&&((so=process.env)!=null&&so.RECIPE_TRACE)&&console.error(`[slab-cut] ${o.item.guid} ${o.item.name??""}: a hole of ${G.length} corners`)}const A={CategoryId:w==="roof"?De.roofs:w==="ceiling"?De.ceilings:w==="foundation"?De.structuralFoundations:De.floors,Type:((ro=Sn(o))==null?void 0:ro.type)??q,Profile:JSON.stringify(gt),Level:O.name};let Ot=pt(q);if(w==="roof"&&i&&o.item.guid){const lt=(io=i.elements.get(o.item.guid))==null?void 0:io.layers,bt=(lt==null?void 0:lt.reduce((K,G)=>K+(G.thickness>0?G.thickness:0),0))??0;bt>0&&(!Ot||Math.abs(bt*f-Ot)>.2*Ot)&&(Ot=bt*f)}if(Ot&&(A["Type.Width"]=Ct(Ot)),Ot){const lt=Ir.get(A.Type);lt===void 0?Ir.set(A.Type,Ot):Math.abs(lt-Ot)>.001&&(A.Type=`${A.Type} · ${Math.round(Ot/f*1e3)} mm`)}if(w==="floor"&&i&&o.item.guid){const lt=Qt(i,o.item.guid);if(lt.length){const bt=[0,1,2].map(G=>Math.min(...lt.map(et=>et[G]))).concat([0,1,2].map(G=>Math.max(...lt.map(et=>et[G])))),K=X.flatMap(G=>{const et=G.record.item.guid?Qt(i,G.record.item.guid):[];if(et.length<4)return[];const H=[0,1,2].map(At=>Math.min(...et.map(xt=>xt[At]))).concat([0,1,2].map(At=>Math.max(...et.map(xt=>xt[At])))),St=H[2]>bt[2]+.01&&H[2]<bt[5]-.01&&H[5]>bt[5]&&lt.some(At=>Math.abs(At[2]-H[2])<.005),rt=H[0]<bt[3]-.01&&bt[0]<H[3]-.01&&H[1]<bt[4]-.01&&bt[1]<H[4]-.01;if(!St||!rt)return[];const ft=`${nt(G.record.id)}#${G.i}`,mt=V.get(ft);return mt?[ft,mt]:[ft]});K.length&&(A.CutBy=[...new Set(K)].join("|"),typeof process<"u"&&((oo=process.env)!=null&&oo.RECIPE_TRACE)&&console.error(`[floor-cut] ${o.item.guid} ${o.item.name??""}: cut by ${K.length} wall(s)`))}}if(w==="roof"||w==="ceiling"){A.BaseOffset=Ct(R*f);const lt=Number(o.params.drop??((ao=m==null?void 0:m.said)==null?void 0:ao.drop));if(w==="ceiling"&&Number.isFinite(lt)&&Ot){const H=[...$.values()].filter(St=>St.at>O.at+1e-6).sort((St,rt)=>St.at-rt.at)[0];H&&(A.BaseOffset=Ct((H.at-lt-Ot/f-O.at)*f))}const bt=m==null?void 0:m.slopes;if(w==="roof"&&Array.isArray(bt)&&bt.some(H=>typeof H=="number")){A.Slopes=JSON.stringify(bt.map(rt=>typeof rt=="number"?rt:null));const H=Math.max(...bt.filter(rt=>typeof rt=="number").map(rt=>Math.abs(rt)));Ot&&H>0&&(A.BaseOffset=Ct(R*f-Ot*Math.sqrt(1+H*H)));const St=i&&o.item.guid?Qt(i,o.item.guid):[];if(Ot&&H>0&&St.length>=4){const rt=St.map(Jt=>Jt[2]-ie),ft=Math.min(...rt),mt=O.at+R,At=mt-Ot/f*Math.sqrt(1+H*H),xt=mt-ft;if(ft-At>.01&&xt>.01){const Jt=St.filter((z,M)=>rt[M]<ft+.002),P=z=>[Math.min(...z.map(M=>M[0])),Math.min(...z.map(M=>M[1])),Math.max(...z.map(M=>M[0])),Math.max(...z.map(M=>M[1]))],[_,y,g,T]=P(St),[v,S,C,J]=P(Jt),B=v-_>.01&&S-y>.01&&g-C>.01&&T-J>.01;A.EaveCut=B?"TwoCutSquare":"TwoCutPlumb",A.FasciaDepth=Ct((B?xt*Math.sqrt(1+H*H):xt)*f)}typeof process<"u"&&((co=process.env)!=null&&co.RECIPE_TRACE)&&console.error(`[roof-eave] ${o.item.guid} ${q}: plumb low ${At.toFixed(3)}, its lowest ${ft.toFixed(3)} → ${A.EaveCut??"plumb"}${A.FasciaDepth?`, fascia ${(Number(A.FasciaDepth)/f).toFixed(3)}`:""}`)}typeof process<"u"&&((lo=process.env)!=null&&lo.RECIPE_TRACE)&&console.error(`[roof] ${o.item.guid} ${q}: slopes ${JSON.stringify(bt)} base ${R} width ${Ot} edges ${gt[0]?gt[0].length/3:0} profile ${JSON.stringify((ho=gt[0])==null?void 0:ho.map(rt=>+rt.toFixed(2)))}`)}const K=w==="roof"?Bt(o):null;if(K){const{A:H,n:St,u:rt,W:ft,ridge:mt,si:At,ti:xt,tj:Jt,L:P}=K,_=(y,g)=>[(H[0]+St[0]*y)*f,(H[1]+St[1]*y)*f,g*f];A.Extrusion=JSON.stringify({profile:[_(0,xt),_(mt,xt+At*mt),_(ft,Jt)],along:[rt[0],rt[1]],length:P*f}),delete A.Slopes}const G=m==null?void 0:m.slope,et=((uo=(fo=m==null?void 0:m.profile)==null?void 0:fo.outline)==null?void 0:uo.curves)??[];if(w==="roof"&&!K&&!A.Slopes&&G&&typeof G.by=="number"&&Math.abs(G.by)>.001&&typeof G.toward=="number"&&et.length>=3){const H=[Math.cos(G.toward),Math.sin(G.toward)],St=et.map(At=>At.from).filter(Boolean),rt=St.map(At=>At[0]*H[0]+At[1]*H[1]),ft=Math.min(...rt),mt=St.map((At,xt)=>Math.abs(rt[xt]-ft)<.01&&Math.abs(rt[(xt+1)%St.length]-ft)<.01);if(St.length===et.length&&mt.some(Boolean)){A.Slopes=JSON.stringify(mt.map(xt=>xt?Math.tan(Math.abs(G.by)):null)),A.BaseOffset=Ct(R*f);const At=i&&o.item.guid?Qt(i,o.item.guid):[];if(At.length>=4){const xt=Math.min(...At.map(Jt=>Jt[2]))-ie;O.at+R-xt>.5*Math.tan(Math.abs(G.by))*(Math.max(...rt)-ft)&&(A.BaseOffset=Ct((xt-O.at)*f))}}typeof process<"u"&&((po=process.env)!=null&&po.RECIPE_TRACE)&&console.error(`[roof-plane] ${o.item.guid} ${q}: ${(G.by*180/Math.PI).toFixed(1)}° toward ${(G.toward*180/Math.PI).toFixed(1)}°, eaves ${JSON.stringify(mt)}`)}}else if(Ot){A.HeightOffset=Ct(R*f+Ot);const lt=m==null?void 0:m.slope,bt=((go=(mo=m==null?void 0:m.profile)==null?void 0:mo.outline)==null?void 0:go.curves)??[];if(lt&&typeof lt.by=="number"&&Math.abs(lt.by)>1e-4&&typeof lt.toward=="number"&&bt.length>=3){const K=[Math.cos(lt.toward),Math.sin(lt.toward)],G=bt.map(mt=>mt.from).filter(Boolean),et=G.map(mt=>mt[0]*K[0]+mt[1]*K[1]),H=Math.min(...et),St=Math.max(...et),rt=G[et.indexOf(H)],ft=Math.tan(lt.by);if(St-H>.001){A.Slope=Ct(ft),A.SlopeArrow=JSON.stringify([rt[0]*f,rt[1]*f,(rt[0]+K[0]*(St-H))*f,(rt[1]+K[1]*(St-H))*f]),A.HeightOffset=Ct(R*f+Ot-ft*(St-H)*f);const mt=i&&o.item.guid?Qt(i,o.item.guid):[];if(mt.length>=4){const At=Math.min(...mt.map(xt=>xt[2]))-ie;A.HeightOffset=Ct((At-O.at)*f+Ot*Math.sqrt(1+ft*ft)),typeof process<"u"&&((yo=process.env)!=null&&yo.RECIPE_TRACE)&&console.error(`[slab-slope] ${o.item.guid} ${q}: lowest ${At.toFixed(3)} level ${O.at.toFixed(3)} base ${R.toFixed(3)} rise ${(ft*(St-H)).toFixed(3)}: top at its low corner ${(At+Ot*Math.sqrt(1+ft*ft)/f).toFixed(3)} (by base ${(O.at+R+Ot/f-ft*(St-H)).toFixed(3)})`)}}}}st(nt(o.id),A)&&pe[w]++}let Un=0,xr=0;for(const o of a){if(o.kind!=="member"||o.params.of!=="column")continue;xr++;const h=de(o,"member"),w=h==null?void 0:h.start;if(!w||w.length!==3)continue;const m=c?Vo(o.params.lookRef):null;if(c&&!m||!m&&!d)continue;const N=m??{family:d.family,type:d.type},R=$.get(String((h==null?void 0:h.level)??""));st(nt(o.id),{...d&&!m?{CategoryId:d.categoryId}:{},Family:N.family,Type:N.type,...R?{Level:R.name}:{}},{position:[w[0]*f,w[1]*f,w[2]*f],rotationDeg:(Number((h==null?void 0:h.roll)??0)||0)*Ho})&&Un++}let Jn=0,_r=0,us=0;for(const o of a){if(o.kind!=="familyInstance")continue;if(o.params.host){us++;continue}if(_r++,!E)continue;const h=de(o,"instance"),w=(wo=h==null?void 0:h.placement)==null?void 0:wo.at;if(!w||w.length!==3)continue;const m=Vo(o.params.type);if(!m)continue;const N=(bo=h==null?void 0:h.placement)==null?void 0:bo.right,R=N?Math.atan2(N[1],N[0])*Ho:0;st(nt(o.id),{Family:m.family,Type:m.type},{position:[w[0]*f,w[1]*f,w[2]*f],rotationDeg:R})&&Jn++}Pt.size&&typeof process<"u"&&((vo=process.env)!=null&&vo.RECIPE_TRACE)&&console.error(`[shaped-panels] ${Pt.size} curtain panel(s) made as families of their shape`);const dn=i?Pl(i,wt,e.fileId,Pt).filter(o=>!Sr.some(h=>h.guid&&o.key.includes(h.guid))):[];if(typeof process<"u"&&((Eo=process.env)!=null&&Eo.RECIPE_GID))for(const o of dn.filter(h=>h.key.includes(process.env.RECIPE_GID)))console.error(`[shaped] ${o.key} at ${o.at} turn ${o.rotationDeg} host ${o.host} ${JSON.stringify({...o.attrs,Shape:o.attrs.Shape?"…":void 0})}`);let qn=0;const Gn=new Map;for(const o of dn){if(!o.attrs.Family||Gn.has(o.attrs.Family))continue;const h={};for(const w of["Shape","Prism"])o.attrs[w]&&(h[w]=o.attrs[w]);Object.keys(h).length&&Gn.set(o.attrs.Family,h)}const Ar=new Set;for(const o of dn){const h=o.attrs.Family;!h||!Gn.has(h)||!(o.attrs.Shape||o.attrs.Prism)||Wt(o.key,o.host&&V.get(o.host)?{...o.attrs,HostMade:V.get(o.host)}:o.attrs,{position:[o.at[0]*f,o.at[1]*f,(o.at[2]-ie)*f],rotationDeg:o.rotationDeg,...o.host?{host:o.host}:{}})&&Ar.add(h)}for(const o of dn){const h=o.attrs.Family,w={position:[o.at[0]*f,o.at[1]*f,(o.at[2]-ie)*f],rotationDeg:o.rotationDeg,...o.host?{host:o.host}:{}},m=o.host&&V.get(o.host)?{...o.attrs,HostMade:V.get(o.host)}:o.attrs,N=h&&Ar.has(h)&&!(o.attrs.Shape||o.attrs.Prism)&&!Wt(o.key,m,w)?{...o.attrs,...Gn.get(h)}:o.attrs;st(o.key,o.host&&V.get(o.host)?{...N,HostMade:V.get(o.host)}:N,{position:[o.at[0]*f,o.at[1]*f,(o.at[2]-ie)*f],rotationDeg:o.rotationDeg,...o.host?{host:o.host}:{}})&&qn++}if(i)for(const o of Ll(i,wt,e.fileId)){const h=(To=at.get(o.host))==null?void 0:To.Profile;if(h)try{const w=JSON.parse(h),m=[];for(let q=0;q+2<o.box.length;q+=3)m.push([o.box[q]*f,o.box[q+1]*f,(o.box[q+2]-ie)*f]);const N=(q,u)=>[Math.min(...q.map(x=>x[u])),Math.max(...q.map(x=>x[u]))],R=[0,1,2].map(q=>N(m,q));if(w.slice(1).some(q=>{const u=[];for(let x=0;x+2<q.length;x+=3)u.push([q[x],q[x+1],q[x+2]]);return u.length>=3&&[0,1,2].every(x=>{const gt=N(u,x);return gt[0]<R[x][1]+.03&&R[x][0]<gt[1]+.03})})){typeof process<"u"&&((Mo=process.env)!=null&&Mo.RECIPE_TRACE)&&console.error(`[opening] ${o.key}: its wall's outline has its holes`);continue}}catch{}st(o.key,{WallOpening:o.box.map((w,m)=>Ct((m%3===2?w-ie:w)*f)).join(","),...V.get(o.host)?{HostMade:V.get(o.host)}:{}},{host:o.host})}if(i)for(const o of Dl(i,e.fileId))st(o.key,{Room:"1",Name:o.name,Number:o.number,Height:Ct(o.height*f)},{position:[o.at[0]*f,o.at[1]*f,(o.at[2]-ie)*f]});let ps=0;const Va=new Set(["slab","roof","covering"]);for(const o of a){const h=o.params.of;(o.kind==="footing"||o.kind==="ramp"||o.kind==="stair"&&h!=="stair"||o.kind==="extrusion"&&!Va.has(String(h))||o.kind==="extrusion"&&h==="slab"&&Go(o)==="other"&&!/ Landing \d+$/.test(String(o.item.attrs.Name??""))||o.kind==="run"&&h!=="wall"&&h!=="curtainWall")&&ps++}te();let un=0;for(const[o,h]of V)!o.startsWith(`${e.fileId}:`)||wt.has(o)||(D.remove(h),un++);if(D.length===0)throw new gr(`Up to date: "${e.name}" holds ${tt} element(s) this recipe already made, ${us+ps} waiting on the applier, and nothing is left to remove.`);const za=[Kt?`${Kt} level(s)`:"",Yt?`${Yt} wall(s)`:"",jn?`${jn} curtain wall(s)`:"",pe.floor?`${pe.floor} floor(s)`:"",pe.foundation?`${pe.foundation} foundation slab(s)`:"",pe.roof?`${pe.roof} roof(s)`:"",pe.ceiling?`${pe.ceiling} ceiling(s)`:"",Dn?`${Dn} stair(s)`:"",Un?`${Un} column(s)`:"",Jn?`${Jn} instance(s)`:"",qn?`${qn} family instance(s)`:"",ct?`${ct} changed`:"",un?`${un} gone`:""].filter(Boolean);return{title:`${s==="ifc"?"IFC":"Model"} to Revit: ${za.join(", ")}`,verb:D.summary,targets:D.length,payload:new Blob([await D.build(t.opId)]),ruleTallies:[{read:$.size,written:Kt},{read:X.length+zt,written:Yt},{read:Er,written:jn},{read:fn.floor+fn.foundation,written:pe.floor+pe.foundation},{read:fn.roof,written:pe.roof},{read:fn.ceiling,written:pe.ceiling},{read:Mr,written:Dn},{read:xr,written:Un},{read:_r,written:Jn},{read:dn.length,written:qn},{read:un,written:un},{read:us+ps,written:0}]}}}const Vl={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}}},zl=[{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"}],Ua=`
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
- `,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:`
50
+ `,wr={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:Vl,rules:zl,doc:Ua,run:Da("frag")},Ja={...wr,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
- `+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:`
56
+ `+Ua,run:Da("ifc")},Wl={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},qa="rhino-to-revit",Yl=`recipe:${qa}`;function Kl(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 Ga={name:qa,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 $;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;
83
+ `,async run(s){var Tt;const{picked:t,contents:e}=await pr(s,s.input),{layer:n,instanceType:r}=s.settings;if(!n||!r)throw new Error("Choose the layer and the Revit type.");const i=(Tt=e.metadata)==null?void 0:Tt.data,a=i==null?void 0:i.units,l=typeof a=="string"?Wl[a.trim().toLowerCase()]:void 0;if(!l)throw new Error(`"${t.name}" does not say what units its data is in${a?` ("${String(a)}" is not one this recipe knows)`:""}, so nothing can be converted from it.`);const p=String((i==null?void 0:i.axes)??"z-up").toLowerCase();if(p!=="z-up")throw new Error(`"${t.name}" declares its data as "${p}"; this recipe only converts Z up.`);const d=l*nn,c=ur(s),E=new hs({project:s.projectId,document:s.target.docId??"",baseCommit:s.target.version??0,author:Yl});let b=0,$=0,F=0;const k=new Set,W=[];for(const nt of e.items){if(!nt.guid||Object.keys(nt.attrs).length===0)continue;if((nt.attrs.Layer??"")!==n){F++;continue}const wt=Kl(nt);if(!wt)continue;k.add(nt.guid);const Pt=[wt[0]*d,wt[1]*d,wt[2]*d],tt=c.get(nt.guid);tt?W.push({instance:tt,object:nt.guid,position:Pt}):(E.add({CategoryId:r.categoryId,Family:r.family,Type:r.type},{position:Pt,source:nt.guid}),b++)}for(const nt of W)E.set(nt.instance,{},{position:nt.position,source:nt.object}),$++;let V=0;for(const[nt,wt]of c)k.has(nt)||(E.remove(wt),V++);const D=b+$+V;if(D===0)throw new gr(`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: ${[b?`${b} new`:"",$?`${$} moved`:"",V?`${V} gone`:""].filter(Boolean).join(", ")}`,verb:E.summary,targets:D,payload:new Blob([await E.build(s.opId)]),ruleTallies:[{read:b,written:b},{read:$,written:$},{read:V,written:V},{read:F,written:0}]}}},Ha=[Ga,Ja,wr];function Xl(s){for(const t of Ha)s.recipes.register(t)}const Zl={MAX_FIELDS:200,MAX_KEY_LENGTH:50,MAX_VALUE_LENGTH:50},Ql={uuid:"a3f82c1d-5b74-4e9a-bc30-d7e12f894a61"},th={uuid:"2c9f4e8d-3a1b-4c5e-9d7f-0a2b6c8e1d3f"},eh={uuid:"b0b5e2a2-0b3a-4a6b-8b1c-0b1c4a6b8b1c"},nh={uuid:"d8f3a1c2-6b4e-4f9a-8c1d-2e7b5a9f3c60"},sh={uuid:"3f9c1a7e-6b2d-4e18-9a5c-7d0e2f4b6c81"},rh={uuid:"2c4ae432-fc24-43e9-9783-0c960c674e96"},ih={uuid:"6f3a9c2e-8b1d-4e6a-9c3f-1d7b5a8e2c4f"},oh={uuid:"69af63aa-19ba-4fc7-b17b-75647bac1d76"},ah={uuid:"234f1416-528d-452a-9cc9-a16c5239b2eb"};exports.CDEManager=Ql;exports.ChannelClient=Pa;exports.ChannelRoom=yr;exports.ClashesManager=th;exports.CollabRoom=ka;exports.DOCUMENT_FILE=Tn;exports.DOCUMENT_SCHEMA=An;exports.DOCUMENT_TYPES=lr;exports.DocumentDrafts=va;exports.EngineServicesClient=as;exports.ExternalRoom=Na;exports.FileList=eh;exports.FlowDoc=Fs;exports.GISManager=nh;exports.GitHistoryManager=sh;exports.HelloWorld=rh;exports.METADATA_LIMITS=Zl;exports.OP_SCHEMA=fr;exports.OperationBuilder=hs;exports.PROJECT_RECIPE_SCHEMA=mr;exports.PlatformClient=Qs;exports.ProjectDocuments=hr;exports.ProjectHistory=or;exports.ProjectManager=ih;exports.ProjectRecipes=Aa;exports.RECIPE_NAME=xa;exports.RecipeKit=Sa;exports.Recipes=Ca;exports.RequestError=ds;exports.SELF_VIEWING_FORMATS=ua;exports.STORAGE_BATCH_MAX=qs;exports.StaleHistoryError=Os;exports.TopicsManager=oh;exports.UIManager=ah;exports.UpToDate=gr;exports.builtinRecipes=Ha;exports.compileRecipe=Js;exports.describeChanges=gl;exports.documentTypeOf=Ls;exports.fragToRevit=wr;exports.ifcToRevit=Ja;exports.latestVersions=Ra;exports.mintGuid=cr;exports.orderByGraph=ar;exports.readFrag=fs;exports.registerBuiltinRecipes=Xl;exports.rhinoToRevit=Ga;exports.stampOf=os;exports.windowTransport=Oa;
84
84
  //# sourceMappingURL=index.cjs.js.map