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