@thatopen/services 0.34.3 → 0.34.5
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 +72 -2
- package/dist/cli.js.map +1 -1
- package/dist/core/client.d.ts +30 -9
- package/dist/index.cjs.js +5 -5
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.es.js +2306 -2242
- 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 Ya=Object.create;var gs=Object.defineProperty;var Ka=Object.getOwnPropertyDescriptor;var Xa=Object.getOwnPropertyNames;var Za=Object.getPrototypeOf,Qa=Object.prototype.hasOwnProperty;var So=s=>{throw TypeError(s)};var tc=(s,t,e)=>t in s?gs(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e;var ec=(s,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Xa(t))!Qa.call(s,i)&&i!==e&&gs(s,i,{get:()=>t[i],enumerable:!(n=Ka(t,i))||n.enumerable});return s};var Vn=(s,t,e)=>(e=s!=null?Ya(Za(s)):{},ec(t||!s||!s.__esModule?gs(e,"default",{value:s,enumerable:!0}):e,s));var he=(s,t,e)=>tc(s,typeof t!="symbol"?t+"":t,e),ys=(s,t,e)=>t.has(s)||So("Cannot "+e);var N=(s,t,e)=>(ys(s,t,"read from private field"),e?e.call(s):t.get(s)),qt=(s,t,e)=>t.has(s)?So("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(s):t.set(s,e),Xt=(s,t,e,n)=>(ys(s,t,"write to private field"),n?n.call(s,e):t.set(s,e),e),I=(s,t,e)=>(ys(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 Kn=Object.create(null);Object.keys(_e).forEach(s=>{Kn[_e[s]]=s});const xs={type:"error",data:"parser error"},Wo=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",Yo=typeof ArrayBuffer=="function",Ko=s=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(s):s&&s.buffer instanceof ArrayBuffer,ni=({type:s,data:t},e,n)=>Wo&&t instanceof Blob?e?n(t):xo(t,n):Yo&&(t instanceof ArrayBuffer||Ko(t))?e?n(t):xo(new Blob([t]),n):n(_e[s]+(t||"")),xo=(s,t)=>{const e=new FileReader;return e.onload=function(){const n=e.result.split(",")[1];t("b"+(n||""))},e.readAsDataURL(s)};function _o(s){return s instanceof Uint8Array?s:s instanceof ArrayBuffer?new Uint8Array(s):new Uint8Array(s.buffer,s.byteOffset,s.byteLength)}let ws;function nc(s,t){if(Wo&&s.data instanceof Blob)return s.data.arrayBuffer().then(_o).then(t);if(Yo&&(s.data instanceof ArrayBuffer||Ko(s.data)))return t(_o(s.data));ni(s,!1,e=>{ws||(ws=new TextEncoder),t(ws.encode(e))})}const Ao="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Tn=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let s=0;s<Ao.length;s++)Tn[Ao.charCodeAt(s)]=s;const sc=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=Tn[s.charCodeAt(n)],a=Tn[s.charCodeAt(n+1)],l=Tn[s.charCodeAt(n+2)],p=Tn[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},ic=typeof ArrayBuffer=="function",si=(s,t)=>{if(typeof s!="string")return{type:"message",data:Xo(s,t)};const e=s.charAt(0);return e==="b"?{type:"message",data:rc(s.substring(1),t)}:Kn[e]?s.length>1?{type:Kn[e],data:s.substring(1)}:{type:Kn[e]}:xs},rc=(s,t)=>{if(ic){const e=sc(s);return Xo(e,t)}else return{base64:!0,data:s}},Xo=(s,t)=>{switch(t){case"blob":return s instanceof Blob?s:new Blob([s]);case"arraybuffer":default:return s instanceof ArrayBuffer?s:s.buffer}},Zo="",oc=(s,t)=>{const e=s.length,n=new Array(e);let i=0;s.forEach((r,a)=>{ni(r,!1,l=>{n[a]=l,++i===e&&t(n.join(Zo))})})},ac=(s,t)=>{const e=s.split(Zo),n=[];for(let i=0;i<e.length;i++){const r=si(e[i],t);if(n.push(r),r.type==="error")break}return n};function cc(){return new TransformStream({transform(s,t){nc(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 bs;function zn(s){return s.reduce((t,e)=>t+e.length,0)}function Wn(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 lc(s,t){bs||(bs=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(zn(e)<1)break;const p=Wn(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(zn(e)<2)break;const p=Wn(e,2);i=new DataView(p.buffer,p.byteOffset,p.length).getUint16(0),n=3}else if(n===2){if(zn(e)<8)break;const p=Wn(e,8),d=new DataView(p.buffer,p.byteOffset,p.length),c=d.getUint32(0);if(c>Math.pow(2,21)-1){l.enqueue(xs);break}i=c*Math.pow(2,32)+d.getUint32(4),n=3}else{if(zn(e)<i)break;const p=Wn(e,i);l.enqueue(si(r?p:bs.decode(p),t)),n=0}if(i===0||i>s){l.enqueue(xs);break}}}})}const Qo=4;function oe(s){if(s)return hc(s)}function hc(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 ls=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")(),fc="arraybuffer";function ta(s,...t){return t.reduce((e,n)=>(s.hasOwnProperty(n)&&(e[n]=s[n]),e),{})}const dc=we.setTimeout,uc=we.clearTimeout;function hs(s,t){t.useNativeTimers?(s.setTimeoutFn=dc.bind(we),s.clearTimeoutFn=uc.bind(we)):(s.setTimeoutFn=we.setTimeout.bind(we),s.clearTimeoutFn=we.clearTimeout.bind(we))}const pc=1.33;function mc(s){return typeof s=="string"?gc(s):Math.ceil((s.byteLength||s.size)*pc)}function gc(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 ea(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function yc(s){let t="";for(let e in s)s.hasOwnProperty(e)&&(t.length&&(t+="&"),t+=encodeURIComponent(e)+"="+encodeURIComponent(s[e]));return t}function wc(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 bc extends Error{constructor(t,e,n){super(t),this.description=e,this.context=n,this.type="TransportError"}}class ii extends oe{constructor(t){super(),this.writable=!1,hs(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 bc(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=si(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=yc(t);return e.length?"?"+e:""}}class vc extends ii{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)};ac(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,oc(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]=ea()),!this.supportsBinary&&!e.sid&&(e.b64=1),this.createUri(t,e)}}let na=!1;try{na=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const Ec=na;function Tc(){}class Mc extends vc{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,hs(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=ta(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=Tc,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",Co);else if(typeof addEventListener=="function"){const s="onpagehide"in we?"pagehide":"unload";addEventListener(s,Co,!1)}}function Co(){for(let s in xe.requests)xe.requests.hasOwnProperty(s)&&xe.requests[s].abort()}const $c=function(){const s=sa({xdomain:!1});return s&&s.responseType!==null}();class Ic extends Mc{constructor(t){super(t);const e=t&&t.forceBase64;this.supportsBinary=$c&&!e}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new xe(sa,this.uri(),t)}}function sa(s){const t=s.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!t||Ec))return new XMLHttpRequest}catch{}if(!t)try{return new we[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const ia=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class Sc extends ii{get name(){return"websocket"}doOpen(){const t=this.uri(),e=this.opts.protocols,n=ia?{}:ta(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;ni(n,this.supportsBinary,r=>{try{this.doWrite(n,r)}catch{}i&&ls(()=>{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]=ea()),this.supportsBinary||(e.b64=1),this.createUri(t,e)}}const vs=we.WebSocket||we.MozWebSocket;class xc extends Sc{createSocket(t,e,n){return ia?new vs(t,e,n):e?new vs(t,e):new vs(t)}doWrite(t,e){this.ws.send(e)}}class _c extends ii{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=lc(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=t.readable.pipeThrough(e).getReader(),i=cc();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&&ls(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this._transport)===null||t===void 0||t.close()}}const Ac={websocket:xc,webtransport:_c,polling:Ic},Cc=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Rc=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function _s(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=Cc.exec(s||""),r={},a=14;for(;a--;)r[Rc[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=Oc(r,r.path),r.queryKey=kc(r,r.query),r}function Oc(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 kc(s,t){const e={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(n,i,r){i&&(e[i]=r)}),e}const As=typeof addEventListener=="function"&&typeof removeEventListener=="function",Xn=[];As&&addEventListener("offline",()=>{Xn.forEach(s=>s())},!1);class We extends oe{constructor(t,e){if(super(),this.binaryType=fc,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=_s(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=_s(e.host).host);hs(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=wc(this.opts.query)),As&&(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"})},Xn.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(t){const e=Object.assign({},this.opts.query);e.EIO=Qo,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+=mc(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,ls(()=>{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(),As&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const n=Xn.indexOf(this._offlineEventListener);n!==-1&&Xn.splice(n,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,e),this.writeBuffer=[],this._prevBufferLen=0}}}We.protocol=Qo;class Nc 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 Fc=class extends Nc{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=>Ac[r]).filter(r=>!!r)),super(n?i:t,i)}};function Pc(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=_s(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 Lc=typeof ArrayBuffer=="function",Bc=s=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(s):s.buffer instanceof ArrayBuffer,ra=Object.prototype.toString,jc=typeof Blob=="function"||typeof Blob<"u"&&ra.call(Blob)==="[object BlobConstructor]",Dc=typeof File=="function"||typeof File<"u"&&ra.call(File)==="[object FileConstructor]";function ri(s){return Lc&&(s instanceof ArrayBuffer||Bc(s))||jc&&s instanceof Blob||Dc&&s instanceof File}function Zn(s,t){if(!s||typeof s!="object")return!1;if(Array.isArray(s)){for(let e=0,n=s.length;e<n;e++)if(Zn(s[e]))return!0;return!1}if(ri(s))return!0;if(s.toJSON&&typeof s.toJSON=="function"&&arguments.length===1)return Zn(s.toJSON(),!0);for(const e in s)if(Object.prototype.hasOwnProperty.call(s,e)&&Zn(s[e]))return!0;return!1}function Uc(s){const t=[],e=s.data,n=s;return n.data=Cs(e,t),n.attachments=t.length,{packet:n,buffers:t}}function Cs(s,t){if(!s)return s;if(ri(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]=Cs(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]=Cs(s[n],t));return e}return s}function Jc(s,t){return s.data=Rs(s.data,t),delete s.attachments,s}function Rs(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]=Rs(s[e],t);else if(typeof s=="object")for(const e in s)Object.prototype.hasOwnProperty.call(s,e)&&(s[e]=Rs(s[e],t));return s}const qc=["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 Gc{constructor(t){this.replacer=t}encode(t){return(t.type===Vt.EVENT||t.type===Vt.ACK)&&Zn(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=Uc(t),n=this.encodeAsString(e.packet),i=e.buffers;return i.unshift(n),i}}class oi 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 Hc(e),e.attachments===0&&super.emitReserved("decoded",e)):super.emitReserved("decoded",e)}else if(ri(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(!Vc(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(oi.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 Ro(e);case Vt.DISCONNECT:return e===void 0;case Vt.CONNECT_ERROR:return typeof e=="string"||Ro(e);case Vt.EVENT:case Vt.BINARY_EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&qc.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 Hc{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=Jc(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const Vc=Number.isInteger||function(s){return typeof s=="number"&&isFinite(s)&&Math.floor(s)===s};function Ro(s){return Object.prototype.toString.call(s)==="[object Object]"}const zc=Object.freeze(Object.defineProperty({__proto__:null,Decoder:oi,Encoder:Gc,get PacketType(){return Vt}},Symbol.toStringTag,{value:"Module"}));function Ee(s,t,e){return s.on(t,e),function(){s.off(t,e)}}const Wc=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class oa 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(Wc.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 fn(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}fn.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};fn.prototype.reset=function(){this.attempts=0};fn.prototype.setMin=function(s){this.ms=s};fn.prototype.setMax=function(s){this.max=s};fn.prototype.setJitter=function(s){this.jitter=s};class Os 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,hs(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 fn({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||zc;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 Fc(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){ls(()=>{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 oa(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 gn={};function _n(s,t){typeof s=="object"&&(t=s,s=void 0),t=t||{};const e=Pc(s,t.path||"/socket.io"),n=e.source,i=e.id,r=e.path,a=gn[i]&&r in gn[i].nsps,l=t.forceNew||t["force new connection"]||t.multiplex===!1||a;let p;return l?p=new Os(n,t):(gn[i]||(gn[i]=new Os(n,t)),p=gn[i]),e.query&&!t.query&&(t.query=e.queryKey),p.socket(e.path,t)}Object.assign(_n,{Manager:Os,Socket:oa,io:_n,connect:_n});class ks 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 Oo="bimterop",Ns="revitflow_history.json",aa="revitflow_model.frag",ca="revitflow_",Yc="bimterop-locks-anchor",yn=new Map;function Kc(s,t){return s.filter(e=>String(e.parentId??"")===t)}function Xc(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,Rn,On,Fs;class ai{constructor(t,e){qt(this,On);qt(this,ve);qt(this,Ye,new Map);qt(this,ke);qt(this,Rn,0);this.client=t,this.projectId=e}async docs(){const t=await I(this,On,Fs).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===aa)??p.find(E=>E.endsWith(".frag")&&!E.startsWith(ca)),c=p.includes(Ns)||!!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 Ps(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 Ps(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,Rn)>3e4)&&(Xt(this,Rn,Date.now()),Xt(this,ke,this.client.listFolders({parentFolderId:t,projectId:this.projectId}).then(n=>Kc(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,On,Fs).call(this);if(e)return e;if(!t)return;const n=await this.client.createFolder(Oo,void 0,this.projectId);return Xt(this,ve,Ie(n)),N(this,ve)}}ve=new WeakMap,Ye=new WeakMap,ke=new WeakMap,Rn=new WeakMap,On=new WeakSet,Fs=async function(){if(N(this,ve))return N(this,ve);const e=(await this.client.listFolders({projectId:this.projectId})).find(n=>String(n.name??"")===Oo&&!n.parentId);return e&&Xt(this,ve,Ie(e)),N(this,ve)};var Me,Et,Re,tn,Ue,$e,kn,Ls,Qn,Je,la,ha,ts,fa,da,ua;class Ps{constructor(t,e,n,i,r){qt(this,Et);qt(this,Me);qt(this,$e);qt(this,kn,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,ts).call(this);return ci((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,Qn).call(this,Yc);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,ts).call(this)??{model:this.docId,commits:[]};const i=ko(n.commits);if(t.expectedLatestGuid!==void 0&&(i==null?void 0:i.guid)!==t.expectedLatestGuid)throw new ks(t.expectedLatestGuid,i==null?void 0:i.guid);const r={guid:li(),...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:Zc(t.changes)};if(t.model&&(await I(this,Et,ua).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=Xc(E)}const a=await I(this,Et,ts).call(this);if(a){n=a;const c=ko(n.commits);if(t.expectedLatestGuid!==void 0&&(c==null?void 0:c.guid)!==t.expectedLatestGuid)throw new ks(t.expectedLatestGuid,c==null?void 0:c.guid);c&&!r.parents&&(r.parents=[c.guid])}return n.commits.push(r),await I(this,Et,fa).call(this,e,Ns,n),r}}Me=new WeakMap,Et=new WeakSet,Re=function(){return new fi(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,kn=new WeakMap,Ls=async function(){return(!N(this,$e)||Date.now()-N(this,kn)>5e3)&&(Xt(this,kn,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:as(n)})):[]})()),N(this,$e).catch(()=>{Xt(this,$e,void 0)})),N(this,$e)},Qn=async function(t){try{return(await I(this,Et,Ls).call(this)).find(e=>e.name===t)}catch{return}},Je=async function(){try{const t=await I(this,Et,Ls).call(this);return t.find(e=>e.name===aa)??t.find(e=>e.name.endsWith(".frag")&&!e.name.startsWith(ca))}catch{return}},la=async function(t){const e=await I(this,Et,Qn).call(this,t);if(!e)return;const n=e.stamp?yn.get(e.id):void 0;if(n&&n.stamp===e.stamp)return structuredClone(await n.value);const i=I(this,Et,ha).call(this,e,t);return e.stamp&&(yn.set(e.id,{stamp:e.stamp,value:i}),i.catch(()=>{var r;((r=yn.get(e.id))==null?void 0:r.value)===i&&yn.delete(e.id)})),structuredClone(await i)},ha=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)},ts=function(){return I(this,Et,la).call(this,Ns)},fa=async function(t,e,n){const i=new Blob([JSON.stringify(n)],{type:"application/json"}),r=await I(this,Et,Qn).call(this,e);return r?(yn.delete(r.id),await this.client.updateFile(r.id,{file:i,versionTag:await this.client.nextVersionTag(r.id)}),r):await I(this,Et,da).call(this,t,e,n)},da=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}},ua=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 Zc(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 ci(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 ko(s){const t=ci(s);return t[t.length-1]}function li(){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 hi={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"}},Qc={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 Bs(s){var e;if(s.type&&s.type in hi)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?Qc[n.toLowerCase()]:void 0;if(i)return i}return"generic"}const Cn="thatopen/document@1",Mn="document.json",pa=["pdf","txt","md","json","csv","tsv","frag"];function be(s){return String(s._id??s.id??"")}const Ze=new Map;let No=!1;const as=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,ma,ga,js,ya,wa,ba,va,$n;class fi{constructor(t,e){qt(this,se);this.client=t,this.projectId=e}async list(t){const e=await I(this,se,ma).call(this),n=t==null?void 0:t.types;return n!=null&&n.length?e.filter(i=>n.includes(Bs(i.descriptor))):e}async fromFile(t,e){const n=await this.client.getFile(t),i=String(n.name??""),r=Es(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 W=await this.client.createFolder(d,p,this.projectId);if(c=be(W),!await I(this,se,$n).call(this,c))break}await this.client.updateFile(t,{parentFolderId:c});const E=[],b=await I(this,se,wa).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:Es(String(k.name??""),k.fileExtension)})}catch{}((e==null?void 0:e.selfView)??pa.includes(r))&&E.push({fileId:t,format:r});const P={schema:Cn,name:d,native:{fileId:t,format:r},views:E};return P.type=(e==null?void 0:e.type)??Bs(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 ai(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??Es(e.name,void 0)},changes:[]})}async descriptor(t){const e=await I(this,se,$n).call(this,t);return e?I(this,se,js).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:Cn,views:e.views??[]},i=new Blob([JSON.stringify(n)],{type:"application/json"}),r=await I(this,se,$n).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:Mn,versionTag:"v1",parentFolderId:t,projectId:this.projectId})}drafts(t){return new Ea(this.client,()=>I(this,se,$n).call(this,t))}}se=new WeakSet,ma=async function(){const t=await I(this,se,ga).call(this);if(t)return t;const n=(await this.client.listFiles({projectId:this.projectId})).filter(r=>String(r.name??"")===Mn);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,js).call(this,be(r),as(r));return p?{folderId:l,descriptor:p}:null}))).filter(r=>r!==null)},ga=async function(){if(No)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 No=!0,null;throw n}const e=[];for(const n of(t==null?void 0:t.documents)??[]){const i=Po(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},js=function(t,e){const n=e?Ze.get(t):void 0;if(n&&n.stamp===e)return n.value;const i=I(this,se,ya).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},ya=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 Po(i)},wa=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,va).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??"")===Mn).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,ba).call(this,d);if(c===void 0||c===be(t))return be(d)}},ba=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}},va=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{}},$n=async function(t){if(!t)return;const n=(await this.client.listFiles({folderId:t,versions:!0})).find(i=>String(i.name??"")===Mn);return n?{id:be(n),stamp:as(n)}:void 0};const Ds="draft:",en="TODRAFT1";var Se,In,Us;class Ea{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,In).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,In).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 nl(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=tl(e.userId),r=(await I(this,Se,In).call(this,n.id)).filter(p=>p.userId===e.userId),l=(await this.client.createHiddenFile(await el(t,e.meta??{}),n.id,i)).hiddenFileId;if(!l)throw new Error("The draft upload answered without a hiddenFileId.");return await I(this,Se,Us).call(this,r.map(p=>p.hiddenId)),{userId:e.userId,savedAt:Fo(l)}}async delete(t){const e=await this.holder();if(!e)return;const n=(await I(this,Se,In).call(this,e.id)).filter(i=>i.userId===t.userId);await I(this,Se,Us).call(this,n.map(i=>i.hiddenId))}}Se=new WeakSet,In=async function(t){return(await this.client.getHiddenFilesByParent(t)).filter(n=>typeof n.tag=="string"&&n.tag.startsWith(Ds)).map(n=>{const i=String(n._id);return{hiddenId:i,userId:n.tag.slice(Ds.length),savedAt:Fo(i)}})},Us=async function(t){for(const e of t)try{await this.client.deleteHiddenFile(e)}catch{}};function tl(s){const t=`${Ds}${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 Fo(s){const t=parseInt(s.slice(0,8),16);return new Date(Number.isFinite(t)?t*1e3:0)}async function el(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 nl(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 Es(s,t){const e=(t??"").replace(/^\./,"").toLowerCase();if(e)return e;const n=s.lastIndexOf(".");return n>0?s.slice(n+1).toLowerCase():""}function Po(s){if(!s||typeof s!="object")return null;const t=s;if(t.schema!==Cn||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 hi?t.type:void 0,a={...t};return delete a.type,delete a.native,{...a,schema:Cn,name:t.name,...r?{type:r}:{},...i?{native:{fileId:n.fileId,format:n.format}}:{},views:e}}const sl="flow:",il="flow:op",rl="flow:source",ol="flow:host",al="flow:print",di="revitflow/op@2",Lo="REVITFLOWCHANGE",Bo="REVITFLOWOPERATION";class fs{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:di,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 cl();return ll(this.flatbuffer(n,i,t,JSON.stringify(e)))}pack(t,e){const n={};for(const[i,r]of Object.entries(t??{}))i.startsWith(sl)&&i!==al||(n[i]=String(r));return e.position&&(n.Position=e.position.map(jo).join(",")),e.rotationDeg!==void 0&&(n.Rotation=jo(e.rotationDeg)),e.source&&(n[rl]=e.source),e.host&&(n[ol]=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()),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(i),st=new Set,pt=[];for(const rt of this.changes){const _t=[],ie={[il]: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(Lo));jt.push(c.createString(Bo));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(Lo),0)),X=p.createSpatialStructure(c,P,c.createString(Bo),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 cl(){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 jo(s){return Number.isFinite(s)?String(s):"0"}async function ll(s){const t=new Blob([s]).stream().pipeThrough(new CompressionStream("deflate"));return new Uint8Array(await new Response(t).arrayBuffer())}async function ds(s){const[t,e]=await hl(),n=e.Model.getRootAsModel(new t.ByteBuffer(await fl(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 hl(){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 fl(s){const t=new Blob([s]).stream().pipeThrough(new DecompressionStream("deflate"));return new Uint8Array(await new Response(t).arrayBuffer())}const Ta="Element",Ma="Carried",sn=1/.3048;function $a(s){const t=[];for(const e of s)for(const n of[Ta,Ma]){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 dl(s){const t=new Map;for(const[e,n]of ui(s))t.set(e,n.name);return t}function ui(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 Ia(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 pi(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 es(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 mi(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=Sa(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 ds(e),site:i,shapes:r}}function Sa(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,W=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:W*nt,angleDeg:V}}const gi="thatopen/recipe@1",Do="__project_data",Uo="recipes",ul=s=>`${s}.recipe.json`,xa={OperationBuilder:fs,OP_SCHEMA:di,readFrag:ds,readPickedFrag:mi,recordsOf:$a,innerJson:de,levelsOf:ui,levelNames:dl,stylesOf:Ia,printOf:es,siteLocationOf:Sa,whatItMadeBefore:pi,ELEMENT_FIELD:Ta,CARRIED_FIELD:Ma,FEET_PER_METRE:sn},_a=/^[a-z0-9][a-z0-9-]{1,62}$/;async function Aa(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===Do&&!d.parentId));if(!r){if(!e)return null;r=await s.createFolder(Do,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===Uo&&String(d.parentId)===a));if(!p){if(!e)return null;p=await s.createFolder(Uo,a,t)}return String(p._id)}const pl=s=>String(s._id??s.id??""),ml=s=>String(s.tag??s.versionTag??""),Js=s=>{var t;return Number(((t=/(\d+)/.exec(s))==null?void 0:t[1])??-1)};async function wn(s,t){const e=await Aa(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:pl(r)})}return i}async function Yn(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)!==gi||!((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 bn(s,t){return(await s.listVersions(t)).map(n=>({tag:ml(n),createdAt:String(n.createdAt??"")})).filter(n=>n.tag).sort((n,i)=>Js(n.tag)-Js(i.tag))}var Nn;class Ca{constructor(t,e){qt(this,Nn,new Map);this.client=t,this.builtinNames=e}async list(t){const e=await wn(this.client,t);return(await Promise.all([...e.entries()].map(async([,{id:i}])=>{var r;try{const a=await bn(this.client,i),l=(r=a[a.length-1])==null?void 0:r.tag,p=await Yn(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 wn(this.client,t)).get(e);if(!n)throw new Error(`The project has no recipe named "${e}".`);const i=await bn(this.client,n.id);return await Promise.all(i.map(async({tag:r,createdAt:a})=>{try{const l=await Yn(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 wn(this.client,t)).get(e);if(!i)throw new Error(`The project has no recipe named "${e}".`);const r=n??((a=(await bn(this.client,i.id)).pop())==null?void 0:a.tag);if(!r)throw new Error(`The recipe "${e}" has no saved version.`);return{...await Yn(this.client,i.id,r),version:r}}async save(t,e,n){const{manifest:i,code:r}=e;if(!_a.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 qs(i,r);const a={schema:gi,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 wn(this.client,t)).get(i.name);if(p){const c=await bn(this.client,p.id),E=`v${Math.max(0,...c.map(b=>Js(b.tag)))+1}`;return await this.client.createVersion(p.id,l,E),E}const d=await Aa(this.client,t,!0);return await this.client.createFile({file:l,name:ul(i.name),versionTag:"v1",projectId:t,parentFolderId:d}),"v1"}async load(t,e,n){var p;const i=(await wn(this.client,t)).get(e);if(!i)throw new Error(`The project has no recipe named "${e}".`);const r=n??((p=(await bn(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,Nn).get(a);if(!l){const d=await Yn(this.client,i.id,r);l=await qs(d.manifest,d.code),N(this,Nn).set(a,l)}return{recipe:l,version:r}}}Nn=new WeakMap;async function qs(s,t){var i;let e;try{e=await import(`data:text/javascript;base64,${gl(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:xa})}}function gl(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 yl(s){const t=s instanceof Uint8Array?s:new Uint8Array(await s.arrayBuffer()),{items:e,metadata:n}=await ds(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 yi extends Error{constructor(t){super(t),this.name="UpToDate"}}var Ne,Fn,Pn;class Ra{constructor(t){qt(this,Ne,new Map);qt(this,Fn,new Map);qt(this,Pn,new Map);he(this,"project");this.client=t,this.project=new Ca(t,()=>new Set(N(this,Ne).keys()))}provideImporter(t,e){N(this,Fn).set(t.toLowerCase(),e)}provideShapes(t,e){N(this,Pn).set(t.toLowerCase(),e)}shapesFor(t){return N(this,Pn).get(t.toLowerCase())}importerFor(t){return N(this,Fn).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 Oa(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??li(),input:e.input,settings:e.settings??{},progress:e.progress??(()=>{})})}}Ne=new WeakMap,Fn=new WeakMap,Pn=new WeakMap;async function Oa(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 Gs=100;function wl(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 bl(s){if(!s||typeof s!="object")return;const t=s.retryAfter;return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}class us extends Error{constructor(e,n,i,r){const a=wl(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??bl(a.details)}}const Te="item/folder",Lt="item",je="processor",vl="npm-registry",Ae="hidden",Ts="FILE",Ms="TOOL",$s="APP",El=500,Jo=3e4,Tl=2e3,Ml=15e3,$l=s=>/^\/?project\/permissions\/check/.test(s),Il=s=>/^\/?(item\/folder\/?$|item\/?$|item\/folder\/[^/]+\/items\/?$|project\/[^/]+\/data\/?$)/.test(s),vn=new Map,Sl=.25,xl=s=>new Promise(t=>setTimeout(t,s));function _l(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 Al(s){return s instanceof us?s.status===429||s.status>=500:!0}function Cl(s,t){const e=Math.min(El*2**t,Jo),n=e*Sl*Math.random(),i=s instanceof us&&s.retryAfter!=null?s.retryAfter*1e3:void 0;return i!=null?Math.min(i,Jo)+n:e+n}var Y,ns,vt,Hs,qe,Ln,Sn,ss,is,Vs,zs,Ws;const vi=class vi{constructor(t,e,n){qt(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");qt(this,Ln);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 vi(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:i,versions:r}=t||{};return e?await I(this,Y,vt).call(this,"GET",`${Te}/${e}/items`,{query:{itemType:Ts,archived:n,...r&&{showVersions:!0}}}):await I(this,Y,vt).call(this,"GET",`${Lt}`,{query:{itemType:Ts,archived:n,...i&&{projectId:i}}})}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,zs).call(this,t,e)}async createFile(t){return await I(this,Y,is).call(this,t,Ts)}async updateFile(t,e){return await I(this,Y,Vs).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,ss).call(this,t,e)}async getFileVersionMetadata(t,e,n){const{withDraft:i}=n||{};return await I(this,Y,vt).call(this,"GET",`${Lt}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/metadata`,{query:{...i&&{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,Sn).call(this,t,async i=>(await I(this,Y,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,Y,vt).call(this,"GET",Te,{query:{parentFolderId:n,archived:e,...i&&{projectId:i}}})}async getFolder(t){return await I(this,Y,vt).call(this,"GET",`${Te}/${t}`)}async getFoldersBatch(t){return await I(this,Y,Sn).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:i}=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},...i&&{projectId:i}}})}async getComponent(t,e){return await I(this,Y,zs).call(this,t,e)}async createComponent(t){const{componentProps:e}=t;return await I(this,Y,is).call(this,t,Ms,e)}async updateComponent(t,e){const{componentProps:n}=e;return await I(this,Y,Vs).call(this,t,e,n)}async downloadComponent(t,e){return await I(this,Y,ss).call(this,t,e)}async downloadComponentBundle(t,e){const{versionTag:n,withDraft:i}=e||{};return await I(this,Y,qe).call(this,`${Lt}/${t}/download/bundle`,{query:{...n&&{versionTag:n},...i&&{withDraft:i}}})}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 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,Y,vt).call(this,"GET",`${Te}/${e}/items`,{query:{itemType:$s,...n&&{ShowVersions:n}}}):await I(this,Y,vt).call(this,"GET",`${Lt}`,{query:{itemType:$s,...n&&{ShowVersions:n},...i&&{projectId:i}}})}async createApp(t){const{appProps:e}=t;return await I(this,Y,is).call(this,t,$s,e)}async downloadApp(t,e){return await I(this,Y,ss).call(this,t,e)}async downloadAppBundle(t,e){const{versionTag:n,withDraft:i}=e||{};return await I(this,Y,qe).call(this,`${Lt}/${t}/download/bundle`,{query:{...n&&{versionTag:n},...i&&{withDraft:i}}})}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",`${vl}/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,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 i=await n.text().catch(()=>"");throw new Error(`Local server request failed: ${n.status} - ${i}`)}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)}`:"",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,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 i=await n.text().catch(()=>"");throw new Error(`Local server request failed: ${n.status} - ${i}`)}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,i=await _n(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 fi(this,t)}history(t){return new ai(this,t)}get recipes(){return N(this,Ln)??Xt(this,Ln,new Ra(this)),N(this,Ln)}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,Y,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,Y,vt).call(this,"POST",`${Lt}/${Ae}/batch`,{body:i})}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,Sn).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,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,Y,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,Y,vt).call(this,"GET",`${Lt}/${encodeURIComponent(t)}/versions`,{query:e})}async listVersionsBatch(t,e={}){const{archived:n}=e;return await I(this,Y,Sn).call(this,t,async i=>(await I(this,Y,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,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,ns=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,Y,ns).call(this,e)}?${new URLSearchParams(I(this,Y,Ws).call(this,n==null?void 0:n.query)).toString()}`,r=Date.now(),a=vn.get(i);if(a&&(a.pending||r-a.at<(Il(e)?Ml:Tl)))return a.answer.then(p=>p===void 0?p:structuredClone(p));const l={at:r,pending:!0,answer:I(this,Y,Hs).call(this,t,e,n)};return vn.set(i,l),l.answer.then(()=>{l.pending=!1,l.at=Date.now()},()=>{vn.get(i)===l&&vn.delete(i)}),l.answer.then(p=>p===void 0?p:structuredClone(p))}return t!=="GET"&&!$l(e)&&vn.clear(),I(this,Y,Hs).call(this,t,e,n)},Hs=async function(t,e,n){const{body:i,query:r,contentType:a,retries:l,responseType:p,retryAttempt:d}=n||{},c=I(this,Y,ns).call(this,e),E=I(this,Y,Ws).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(W=>W).catch(()=>"");throw new us(P.status,P.statusText,k,_l(P))}return p==="blob"?await P.blob():P.json().then(k=>k).catch(()=>{})}catch(P){const k=l??this.retries;if(k>0&&Al(P)){const W=d??0;return await xl(Cl(P,W)),await I(this,Y,vt).call(this,t,e,{...n,retries:k-1,retryAttempt:W+1})}throw P}},qe=async function(t,e){const{query:n}=e||{},i=I(this,Y,ns).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}`}}})},Ln=new WeakMap,Sn=async function(t,e){if(!t.length)return[];const n=[];for(let r=0;r<t.length;r+=Gs)n.push(t.slice(r,r+Gs));return(await Promise.all(n.map(e))).flat()},ss=async function(t,e){const{versionTag:n,withDraft:i}=e||{},r=await I(this,Y,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},is=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,Y,vt).call(this,"POST",Lt,{body:c})},Vs=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,Y,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,Y,vt).call(this,"PUT",`${Lt}/${t}`,{body:b,contentType:"application/json"})}return{item:d,version:c}},zs=async function(t,e){const{showVersions:n=!1}=e||{};return await I(this,Y,vt).call(this,"GET",`${Lt}/${t}`,{query:{showVersions:n}})},Ws=function(t){return t&&Object.entries(t).filter(([,e])=>e!==void 0).reduce((e,[n,i])=>(e[n]=i,e),{})};let cs=vi;function ka(){if(typeof window>"u"||window.parent===window)throw new Error("client.channel only works inside a That Open app, which runs in an iframe of the platform.");return{post:s=>window.parent.postMessage(s,"*"),listen:s=>{const t=e=>{e.source===window.parent&&s(e.data)};return window.addEventListener("message",t),()=>window.removeEventListener("message",t)}}}const Ys="channel:",Rl=1e4;function rs(s){try{s()}catch(t){console.error("[channel] a listener threw:",t)}}var Fe,ge,ye,on,an,cn,ue,Ks,Xs,nn;class wi{constructor(t,e){qt(this,ue);qt(this,Fe,!1);qt(this,ge,[]);qt(this,ye,[]);qt(this,on,new Set);qt(this,an,new Set);qt(this,cn,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,Ks).call(this,"joined",this.controls.join)}leave(){return!N(this,Fe)&&!N(this,ye).some(t=>t.want==="joined")?Promise.resolve():I(this,ue,Ks).call(this,"left",this.controls.leave)}onChange(t){return N(this,on).add(t),()=>void N(this,on).delete(t)}onPeerJoined(t){return N(this,an).add(t),()=>void N(this,an).delete(t)}onPeerLeft(t){return N(this,cn).add(t),()=>void N(this,cn).delete(t)}applyJoined(){Xt(this,Fe,!0),I(this,ue,Xs).call(this,"joined"),I(this,ue,nn).call(this)}applyLeft(){Xt(this,Fe,!1),Xt(this,ge,[]),I(this,ue,Xs).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,an).forEach(e=>rs(()=>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,cn).forEach(n=>rs(()=>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,on=new WeakMap,an=new WeakMap,cn=new WeakMap,ue=new WeakSet,Ks=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.`))},Rl)};N(this,ye).push(r),this.transport.post({type:"APP_CHANNEL_CONTROL",...e})})},Xs=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,on).forEach(t=>rs(t))};var ln;class Na extends wi{constructor(e){super(e,{join:{action:"joinCollab"},leave:{action:"leaveCollab"}});qt(this,ln,new Map)}on(e,n){const i=N(this,ln).get(e)??new Set;return i.add(n),N(this,ln).set(e,i),()=>void i.delete(n)}send(e,n){if(e.startsWith(Ys))throw new Error(`Message types starting with '${Ys}' are reserved.`);this.joined&&this.post({type:"APP_CHANNEL_PUBLISH",message:{type:e,payload:n}})}accepts(e){return e===void 0||e==="collab"}async handle(e){const n=N(this,ln).get(e.type);if(!(n!=null&&n.size))return{handled:!1};const i=Pa(e);return n.forEach(r=>rs(()=>r(e.payload,i))),{handled:!0}}}ln=new WeakMap;var Ge;class Fa extends wi{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,Pa(e))}}catch(i){return{handled:!0,error:i instanceof Error?i.message:String(i)}}}}Ge=new WeakMap;function Pa(s){return{from:s.from,at:s.at,requestId:s.requestId,kind:s.kind}}function Ol(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,Bn,Pe,He,Ve,ce,Zs,os,Ba,ja,Da,Qs;class La{constructor(t){qt(this,ce);qt(this,Ke);qt(this,Bn);qt(this,Pe);qt(this,He,new Map);qt(this,Ve,new Set);Xt(this,Ke,t),Xt(this,Bn,t.listen(e=>void I(this,ce,Ba).call(this,e)))}collab(){return N(this,Pe)??Xt(this,Pe,new Na(N(this,Ke))),N(this,Pe)}external(t){const e=t??"";let n=N(this,He).get(e);return n||(n=new Fa(N(this,Ke),t),N(this,He).set(e,n)),n}dispose(){N(this,Bn).call(this)}}Ke=new WeakMap,Bn=new WeakMap,Pe=new WeakMap,He=new WeakMap,Ve=new WeakMap,ce=new WeakSet,Zs=function(){return[...N(this,Pe)?[N(this,Pe)]:[],...N(this,He).values()]},os=function(t,e){if(t==="collab")return N(this,Pe);if(t==="external")return N(this,He).get(typeof e=="string"?e:"")},Ba=async function(t){const e=Ol(t);if(e){if(e.type.startsWith(Ys)){I(this,ce,ja).call(this,e);return}await I(this,ce,Da).call(this,e)}},ja=function(t){var n,i,r;const e=t.payload??{};switch(t.type){case"channel:joined":(n=I(this,ce,os).call(this,e.scope,e.kind))==null||n.applyJoined();break;case"channel:left":(i=I(this,ce,os).call(this,e.scope,e.kind))==null||i.applyLeft();break;case"channel:peers":(r=I(this,ce,os).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,Zs).call(this).map(p=>p.failPending(a)).some(Boolean)||console.error("[channel] error:",t.payload);break}}},Da=async function(t){const e=I(this,ce,Zs).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,Qs).call(this,t.requestId,a))}t.requestId&&t.scope==="external"&&e.length>0&&!n&&I(this,ce,Qs).call(this,t.requestId,{handled:!0,error:`No handler for "${t.type}".`})},Qs=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",En="tokens",kl=6e4;var hn,jn,ze;const Ei=class Ei extends cs{constructor(e,n,i){super(typeof e=="string"?e:"",n,{...i,useBearer:!0});qt(this,hn);qt(this,jn);qt(this,ze,new Map);typeof e=="function"&&Xt(this,hn,e)}async resolveAccessToken(){return N(this,hn)?await N(this,hn).call(this):super.resolveAccessToken()}static fromPlatformContext(e){const n=(typeof window<"u"?window.__THATOPEN_CONTEXT__:null)||{appId:"",projectId:"",accessToken:"",apiUrl:""},i=new Ei(n.accessToken,n.apiUrl,e);return i.context=n,i}get channel(){return N(this,jn)??Xt(this,jn,new La(ka())),N(this,jn)}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<kl)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",En)}async getTokenSecret(e){return await(await this.request("GET",`${En}/${e}/token`,{responseType:"blob"})).text()}async createToken(e){return await this.request("POST",En,{body:JSON.stringify({urlRestrictions:[],...e}),contentType:"application/json"})}async updateToken(e,n){return await this.request("PUT",`${En}/${e}`,{body:JSON.stringify(n),contentType:"application/json"})}async revokeToken(e){return await this.request("DELETE",`${En}/${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=_n(`${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()}};hn=new WeakMap,jn=new WeakMap,ze=new WeakMap;let ti=Ei;const Ce=1/.3048,Nl={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"},Fl="OST_GenericModel",Pl=new Set(["IFCSPACE","IFCOPENINGELEMENT","IFCSITE","IFCANNOTATION","IFCGRID","IFCVIRTUALELEMENT","IFCBUILDING","IFCBUILDINGSTOREY"]),Oe=(s,t)=>Math.round(s/t)*t,Ll=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]]}),An=(s,t)=>s[0]*t[0]+s[1]*t[1]+s[2]*t[2],Is=s=>Math.sqrt(An(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 Bl(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)||Pl.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":Nl[b.ifcClass.toUpperCase()]??Fl,k=Ll(b.pieces[0].matrix),W=Is(k.x),V=Is(k.y),D=Is(k.z),f=k.z.map(U=>U/(D||1)),Tt=Math.abs(f[2]-1)<1e-6&&An(rn(k.x,k.y),k.z)>0&&Math.abs(W-V)<1e-6&&Math.abs(W-D)<1e-6,nt=An(rn(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(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=An(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?Ul(at[0]):null;if(pt){const U=Dl(pt),Z=U.key,B=`prism|${P}|${U.axis}|${Z}`;let ut=a.get(B);if(!ut){const le=qo(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:Go(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=qo(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:Go(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=ei(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=ei(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 qo(s){return(s.replace(/[\\:{}[\]|;<>?`~]/g,"-").replace(/\s+/g," ").trim()||"Shape").slice(0,120)}function Go(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 jl(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 ei(s,l.gid)){const E=c.pts;if(E.length<4)continue;const b=ql(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),W=k($)*k(P)*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(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 ${W.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 Dl(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 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)])}),i=b=>b.map(P=>{const k=P.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("|"),r=(b,$)=>{const P=Math.cos(-$),k=Math.sin(-$);return b.map(W=>W.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 W=new Set,V=.5*Math.atan2(2*P,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: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 Ul(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 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+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 Jl(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],W=c.verts[$*3+2];return[E[0]*P+E[4]*k+E[8]*W+E[12],E[1]*P+E[5]*k+E[9]*W+E[13],E[2]*P+E[6]*k+E[10]*W+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 ql(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]),W=Math.max(...P)-Math.min(...P),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 ei(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],W=E.verts[P+1],V=E.verts[P+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=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+=An($,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 Gl(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 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=[P(b.tris[k]),P(b.tris[k+1]),P(b.tris[k+2])],V=[];for(let nt=0;nt<3;nt++){const wt=W[nt],Pt=W[(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 Hl(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 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=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 Ss(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:W,allLoops:V}=P;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(i){const at=W.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!==W&&U.area>=.01&&U.pts.length<=200&&(U.area>=.1||!st(pt(U.pts),W))).map(U=>U.pts),Gt=Bt.filter(U=>!st(pt(U),W)),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=>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],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 Vl(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 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(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||(!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 xn(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 Ho(s){const t=xn(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 Vo=180/Math.PI;function zo(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 zl(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 Ua(s){return async t=>{var Ri,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;const{picked:e,contents:n,site:i,shapes:r}=await mi(t,t.input),a=$a(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 $=ui(a),P=Ia(a);if(typeof process<"u"&&((Ri=process.env)!=null&&Ri.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`,W=new Map,V=pi(t,W);t.progress("Writing the changes for Revit");const D=new fs({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=W.get(o),F=l?{...h,Frame:"shared",...p?{SharedAt:p}:{}}:h;return!m||m===es({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=es({attrs:m,placement:w??{}}),R=V.get(o);if(R){const O=W.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=es({attrs:l?{...w,Frame:"shared",...p?{SharedAt:p}:{}}:w,placement:{}}),F=(Oi=[...W].find(([R,O])=>O===m&&V.has(R)))==null?void 0:Oi[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=((Ni=(ki=h==null?void 0:h.run)==null?void 0:ki.line)==null?void 0:Ni.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=Gl(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"&&((Pi=(Fi=process.env)==null?void 0:Fi.RECIPE_WALL)!=null&&Pi.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"&&((Li=process.env)!=null&&Li.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"&&((ji=(Bi=process.env)==null?void 0:Bi.RECIPE_WALL)!=null&&ji.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,(Di=L.start)==null?void 0:Di[0]):null,v=h.params.wantedAtEnd==="square"?g(x,(Ui=L.end)==null?void 0:Ui[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"&&((Ji=process.env)!=null&&Ji.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"&&((qi=process.env)!=null&&qi.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"&&((Hi=(Gi=process.env)==null?void 0:Gi.RECIPE_WALL)!=null&&Hi.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:((Vi=xn(h))==null?void 0:Vi.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)?zl(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"&&((zi=process.env)!=null&&zi.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"&&((Wi=process.env)!=null&&Wi.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"&&((Yi=process.env)!=null&&Yi.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),mn=Ft(ee,Zt,ne),Io=Ft(ee,Zt,Ut);if((fe>1e-9&&Be<-1e-9||fe<-1e-9&&Be>1e-9)&&(mn>1e-9&&Io<-1e-9||mn<-1e-9&&Io>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"&&((Ki=process.env)!=null&&Ki.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"&&((Xi=process.env)!=null&&Xi.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?Vl(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"&&((Zi=process.env)!=null&&Zi.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 _=Ss(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));_=!((Qi=_.pieces)!=null&&Qi.length)&&(J.length||_.outline.length>4)?{..._,holes:J}:null,_&&typeof process<"u"&&((tr=process.env)!=null&&tr.RECIPE_TRACE)&&console.error(`[wall-outline] ${h.item.guid}: ${L.length} hosted, ${J.length} empty hole(s) kept`)}const g=_!=null&&_.outline?null:Ss(r,h.item.guid,u,x);if(g){typeof process<"u"&&((er=process.env)!=null&&er.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"&&((nr=process.env)!=null&&nr.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:Ss(r,h.item.guid,u,x,!0);if((sr=_==null?void 0:_.holes)!=null&&sr.length&&!((ir=_.pieces)!=null&&ir.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"&&((rr=process.env)!=null&&rr.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"&&((or=process.env)!=null&&or.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"&&((cr=(ar=process.env)==null?void 0:ar.RECIPE_WALL)!=null&&cr.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"&&((lr=process.env)!=null&&lr.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"&&((hr=process.env)!=null&&hr.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"&&((fr=process.env)!=null&&fr.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"&&((dr=process.env)!=null&&dr.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"&&((ur=process.env)!=null&&ur.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"&&((pr=process.env)!=null&&pr.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"&&((mr=process.env)!=null&&mr.RECIPE_TRACE)&&console.error(`[layer-extension] ${h.item.guid} ${A.Type}: top ${y}, base ${g}`)}}typeof process<"u"&&((yr=(gr=process.env)==null?void 0:gr.RECIPE_WALL)!=null&&yr.split(",").includes(h.item.guid??""))&&console.error(`[wall-attrs] ${JSON.stringify(A).slice(0,1500)} style ${JSON.stringify(((wr=P.get(q))==null?void 0:wr.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 Dn=0,Ti=0;const Mi=new Map;for(const o of a){if(o.kind!=="run"||o.params.of!=="curtainWall")continue;Ti++;const h=de(o,"run"),w=(Er=(vr=(br=h==null?void 0:h.run)==null?void 0:br.line)==null?void 0:vr.curves)==null?void 0:Er[0],m=$.get(String((h==null?void 0:h.level)??o.params.level??"")),F=o.params.lookRef,R=typeof F=="string"?(Tr=P.get(F))==null?void 0:Tr.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"&&((Mr=process.env)!=null&&Mr.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=!(($r=h.lines)!=null&&$r.along)&&It.length>0&&(It.length!==St.length||It.some((y,g)=>Math.abs(y-St[g])>.01));it&&typeof process<"u"&&((Ir=process.env)!=null&&Ir.RECIPE_TRACE)&&console.error(`[curtain-lines] ${o.item.guid}: ${It.length} from its bars, not the type's ${St.length}`);const ft=((Sr=h.lines)==null?void 0:Sr.along)??(it?It:St),mt=((xr=h.lines)==null?void 0:xr.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 Hl(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:((_r=xn(o))==null?void 0:_r.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,mn=Math.abs(fe)>Math.abs(Be)?gt:$t;return{p:[Ht[0]+fe*mn,Ht[1]+Be*mn],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=(Ar=y.panel)!=null&&Ar.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=Mi.get(L.Type);S===void 0?Mi.set(L.Type,v):S!==v&&(typeof process<"u"&&((Cr=process.env)!=null&&Cr.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)&&Dn++}let Un=0,$i=0;const Ii=(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;$i++;const h=de(o,"stair"),w=o.params.lookRef,m=typeof w=="string"?(Rr=P.get(w))==null?void 0:Rr.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):(kr=(Or=h.sketch)==null?void 0:Or.risers)!=null&&kr.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"&&((Nr=process.env)!=null&&Nr.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):Ii(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"&&((Fr=process.env)!=null&&Fr.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"&&((Pr=process.env)!=null&&Pr.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"&&((Lr=process.env)==null?void 0:Lr.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"&&((Br=process.env)==null?void 0:Br.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"&&((jr=process.env)!=null&&jr.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"&&((Dr=process.env)!=null&&Dr.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 ${Ii(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=(((Jr=(Ur=G==null?void 0:G.profile)==null?void 0:Ur.outline)==null?void 0:Jr.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:((qr=xn(o))==null?void 0:qr.type)??String(w),Level:F.name,Stairs:JSON.stringify(It)};typeof process<"u"&&(((Gr=process.env)==null?void 0:Gr.RECIPE_STAIR)===o.item.guid||((Hr=process.env)==null?void 0:Hr.RECIPE_STAIR)==="*")&&console.error(`[stair-spec] ${bt.Stairs} style ${JSON.stringify(m)}`),st(nt(o.id),bt)&&Un++}const Si=new Map,dn={floor:0,foundation:0,roof:0,ceiling:0},pe={floor:0,foundation:0,roof:0,ceiling:0},xi=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":Ho(o);if(w==="other"||r&&o.item.guid&&/^IFCRAMP(FLIGHT)?$/i.test(((Vr=r.elements.get(o.item.guid))==null?void 0:Vr.ifcClass)??""))continue;const m=de(o,"extrusion"),F=m==null?void 0:m.on;if(F&&(Math.abs(((zr=F.u)==null?void 0:zr[2])??0)>.001||Math.abs(((Wr=F.v)==null?void 0:Wr[2])??0)>.001))continue;if(w==="roof"&&!Bt(o)){const lt=m,bt=((Kr=(Yr=m==null?void 0:m.profile)==null?void 0:Yr.outline)==null?void 0:Kr.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"&&((Xr=process.env)!=null&&Xr.RECIPE_TRACE)&&console.error(`[roof-as-floor] ${o.item.guid} ${o.params.lookRef}: its low side a corner, a sloped floor`))}}dn[w]++,typeof process<"u"&&((Zr=process.env)==null?void 0:Zr.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((to=(Qr=m==null?void 0:m.profile)==null?void 0:Qr.outline)==null?void 0:to.curves);if(typeof q!="string"||!O||!x)continue;const gt=[x],$t=w==="roof"?Bt(o):null;for(const lt of((eo=m==null?void 0:m.profile)==null?void 0:eo.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 xi)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"&&((no=process.env)!=null&&no.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"&&((so=process.env)!=null&&so.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"&&((io=process.env)!=null&&io.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=xn(o))==null?void 0:ro.type)??q,Profile:JSON.stringify(gt),Level:O.name};let Ot=pt(q);if(w==="roof"&&r&&o.item.guid){const lt=(oo=r.elements.get(o.item.guid))==null?void 0:oo.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=Si.get(A.Type);lt===void 0?Si.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"&&((ao=process.env)!=null&&ao.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??((co=m==null?void 0:m.said)==null?void 0:co.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"&&((lo=process.env)!=null&&lo.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"&&((ho=process.env)!=null&&ho.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((fo=gt[0])==null?void 0:fo.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=((po=(uo=m==null?void 0:m.profile)==null?void 0:uo.outline)==null?void 0:po.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"&&((mo=process.env)!=null&&mo.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=((yo=(go=m==null?void 0:m.profile)==null?void 0:go.outline)==null?void 0:yo.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"&&((wo=process.env)!=null&&wo.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 Jn=0,_i=0;for(const o of a){if(o.kind!=="member"||o.params.of!=="column")continue;_i++;const h=de(o,"member"),w=h==null?void 0:h.start;if(!w||w.length!==3)continue;const m=c?zo(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)*Vo})&&Jn++}let qn=0,Ai=0,ps=0;for(const o of a){if(o.kind!=="familyInstance")continue;if(o.params.host){ps++;continue}if(Ai++,!E)continue;const h=de(o,"instance"),w=(bo=h==null?void 0:h.placement)==null?void 0:bo.at;if(!w||w.length!==3)continue;const m=zo(o.params.type);if(!m)continue;const F=(vo=h==null?void 0:h.placement)==null?void 0:vo.right,R=F?Math.atan2(F[1],F[0])*Vo:0;st(nt(o.id),{Family:m.family,Type:m.type},{position:[w[0]*f,w[1]*f,w[2]*f],rotationDeg:R})&&qn++}Pt.size&&typeof process<"u"&&((Eo=process.env)!=null&&Eo.RECIPE_TRACE)&&console.error(`[shaped-panels] ${Pt.size} curtain panel(s) made as families of their shape`);const un=r?Bl(r,wt,e.fileId,Pt).filter(o=>!xi.some(h=>h.guid&&o.key.includes(h.guid))):[];if(typeof process<"u"&&((To=process.env)!=null&&To.RECIPE_GID))for(const o of un.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 Gn=0;const Hn=new Map;for(const o of un){if(!o.attrs.Family||Hn.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&&Hn.set(o.attrs.Family,h)}const Ci=new Set;for(const o of un){const h=o.attrs.Family;!h||!Hn.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}:{}})&&Ci.add(h)}for(const o of un){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&&Ci.has(h)&&!(o.attrs.Shape||o.attrs.Prism)&&!Wt(o.key,m,w)?{...o.attrs,...Hn.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}:{}})&&Gn++}if(r)for(const o of jl(r,wt,e.fileId)){const h=(Mo=at.get(o.host))==null?void 0:Mo.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"&&(($o=process.env)!=null&&$o.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 Jl(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 ms=0;const za=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"&&!za.has(String(h))||o.kind==="extrusion"&&h==="slab"&&Ho(o)==="other"&&!/ Landing \d+$/.test(String(o.item.attrs.Name??""))||o.kind==="run"&&h!=="wall"&&h!=="curtainWall")&&ms++}te();let pn=0;for(const[o,h]of V)!o.startsWith(`${e.fileId}:`)||wt.has(o)||(D.remove(h),pn++);if(D.length===0)throw new yi(`Up to date: "${e.name}" holds ${tt} element(s) this recipe already made, ${ps+ms} waiting on the applier, and nothing is left to remove.`);const Wa=[Kt?`${Kt} level(s)`:"",Yt?`${Yt} wall(s)`:"",Dn?`${Dn} 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)`:"",Un?`${Un} stair(s)`:"",Jn?`${Jn} column(s)`:"",qn?`${qn} instance(s)`:"",Gn?`${Gn} family instance(s)`:"",ct?`${ct} changed`:"",pn?`${pn} gone`:""].filter(Boolean);return{title:`${s==="ifc"?"IFC":"Model"} to Revit: ${Wa.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:Ti,written:Dn},{read:dn.floor+dn.foundation,written:pe.floor+pe.foundation},{read:dn.roof,written:pe.roof},{read:dn.ceiling,written:pe.ceiling},{read:$i,written:Un},{read:_i,written:Jn},{read:Ai,written:qn},{read:un.length,written:Gn},{read:pn,written:pn},{read:ps+ms,written:0}]}}}const Wl={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}}},Yl=[{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"}],Ja=`
|
|
1
|
+
"use strict";var rc=Object.create;var Mn=Object.defineProperty;var oc=Object.getOwnPropertyDescriptor;var ac=Object.getOwnPropertyNames;var cc=Object.getPrototypeOf,lc=Object.prototype.hasOwnProperty;var No=n=>{throw TypeError(n)};var hc=(n,t,e)=>t in n?Mn(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e;var fc=(n,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of ac(t))!lc.call(n,i)&&i!==e&&Mn(n,i,{get:()=>t[i],enumerable:!(s=oc(t,i))||s.enumerable});return n};var Ks=(n,t,e)=>(e=n!=null?rc(cc(n)):{},fc(t||!n||!n.__esModule?Mn(e,"default",{value:n,enumerable:!0}):e,n));var he=(n,t,e)=>hc(n,typeof t!="symbol"?t+"":t,e),$n=(n,t,e)=>t.has(n)||No("Cannot "+e);var R=(n,t,e)=>($n(n,t,"read from private field"),e?e.call(n):t.get(n)),Lt=(n,t,e)=>t.has(n)?No("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(n):t.set(n,e),Vt=(n,t,e,s)=>($n(n,t,"write to private field"),s?s.call(n,e):t.set(n,e),e),I=(n,t,e)=>($n(n,t,"access private method"),e);var In=(n,t,e,s)=>({set _(i){Vt(n,t,i,e)},get _(){return R(n,t,s)}});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 tn=Object.create(null);Object.keys(_e).forEach(n=>{tn[_e[n]]=n});const Fn={type:"error",data:"parser error"},na=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",ia=typeof ArrayBuffer=="function",ra=n=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(n):n&&n.buffer instanceof ArrayBuffer,hi=({type:n,data:t},e,s)=>na&&t instanceof Blob?e?s(t):Fo(t,s):ia&&(t instanceof ArrayBuffer||ra(t))?e?s(t):Fo(new Blob([t]),s):s(_e[n]+(t||"")),Fo=(n,t)=>{const e=new FileReader;return e.onload=function(){const s=e.result.split(",")[1];t("b"+(s||""))},e.readAsDataURL(n)};function Po(n){return n instanceof Uint8Array?n:n instanceof ArrayBuffer?new Uint8Array(n):new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}let Sn;function dc(n,t){if(na&&n.data instanceof Blob)return n.data.arrayBuffer().then(Po).then(t);if(ia&&(n.data instanceof ArrayBuffer||ra(n.data)))return t(Po(n.data));hi(n,!1,e=>{Sn||(Sn=new TextEncoder),t(Sn.encode(e))})}const Lo="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Is=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let n=0;n<Lo.length;n++)Is[Lo.charCodeAt(n)]=n;const uc=n=>{let t=n.length*.75,e=n.length,s,i=0,r,a,l,p;n[n.length-1]==="="&&(t--,n[n.length-2]==="="&&t--);const d=new ArrayBuffer(t),c=new Uint8Array(d);for(s=0;s<e;s+=4)r=Is[n.charCodeAt(s)],a=Is[n.charCodeAt(s+1)],l=Is[n.charCodeAt(s+2)],p=Is[n.charCodeAt(s+3)],c[i++]=r<<2|a>>4,c[i++]=(a&15)<<4|l>>2,c[i++]=(l&3)<<6|p&63;return d},pc=typeof ArrayBuffer=="function",fi=(n,t)=>{if(typeof n!="string")return{type:"message",data:oa(n,t)};const e=n.charAt(0);return e==="b"?{type:"message",data:mc(n.substring(1),t)}:tn[e]?n.length>1?{type:tn[e],data:n.substring(1)}:{type:tn[e]}:Fn},mc=(n,t)=>{if(pc){const e=uc(n);return oa(e,t)}else return{base64:!0,data:n}},oa=(n,t)=>{switch(t){case"blob":return n instanceof Blob?n:new Blob([n]);case"arraybuffer":default:return n instanceof ArrayBuffer?n:n.buffer}},aa="",gc=(n,t)=>{const e=n.length,s=new Array(e);let i=0;n.forEach((r,a)=>{hi(r,!1,l=>{s[a]=l,++i===e&&t(s.join(aa))})})},yc=(n,t)=>{const e=n.split(aa),s=[];for(let i=0;i<e.length;i++){const r=fi(e[i],t);if(s.push(r),r.type==="error")break}return s};function wc(){return new TransformStream({transform(n,t){dc(n,e=>{const s=e.length;let i;if(s<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,s);else if(s<65536){i=new Uint8Array(3);const r=new DataView(i.buffer);r.setUint8(0,126),r.setUint16(1,s)}else{i=new Uint8Array(9);const r=new DataView(i.buffer);r.setUint8(0,127),r.setBigUint64(1,BigInt(s))}n.data&&typeof n.data!="string"&&(i[0]|=128),t.enqueue(i),t.enqueue(e)})}})}let xn;function Xs(n){return n.reduce((t,e)=>t+e.length,0)}function Zs(n,t){if(n[0].length===t)return n.shift();const e=new Uint8Array(t);let s=0;for(let i=0;i<t;i++)e[i]=n[0][s++],s===n[0].length&&(n.shift(),s=0);return n.length&&s<n[0].length&&(n[0]=n[0].slice(s)),e}function bc(n,t){xn||(xn=new TextDecoder);const e=[];let s=0,i=-1,r=!1;return new TransformStream({transform(a,l){for(e.push(a);;){if(s===0){if(Xs(e)<1)break;const p=Zs(e,1);r=(p[0]&128)===128,i=p[0]&127,i<126?s=3:i===126?s=1:s=2}else if(s===1){if(Xs(e)<2)break;const p=Zs(e,2);i=new DataView(p.buffer,p.byteOffset,p.length).getUint16(0),s=3}else if(s===2){if(Xs(e)<8)break;const p=Zs(e,8),d=new DataView(p.buffer,p.byteOffset,p.length),c=d.getUint32(0);if(c>Math.pow(2,21)-1){l.enqueue(Fn);break}i=c*Math.pow(2,32)+d.getUint32(4),s=3}else{if(Xs(e)<i)break;const p=Zs(e,i);l.enqueue(fi(r?p:xn.decode(p),t)),s=0}if(i===0||i>n){l.enqueue(Fn);break}}}})}const ca=4;function oe(n){if(n)return vc(n)}function vc(n){for(var t in oe.prototype)n[t]=oe.prototype[t];return n}oe.prototype.on=oe.prototype.addEventListener=function(n,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+n]=this._callbacks["$"+n]||[]).push(t),this};oe.prototype.once=function(n,t){function e(){this.off(n,e),t.apply(this,arguments)}return e.fn=t,this.on(n,e),this};oe.prototype.off=oe.prototype.removeListener=oe.prototype.removeAllListeners=oe.prototype.removeEventListener=function(n,t){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var e=this._callbacks["$"+n];if(!e)return this;if(arguments.length==1)return delete this._callbacks["$"+n],this;for(var s,i=0;i<e.length;i++)if(s=e[i],s===t||s.fn===t){e.splice(i,1);break}return e.length===0&&delete this._callbacks["$"+n],this};oe.prototype.emit=function(n){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),e=this._callbacks["$"+n],s=1;s<arguments.length;s++)t[s-1]=arguments[s];if(e){e=e.slice(0);for(var s=0,i=e.length;s<i;++s)e[s].apply(this,t)}return this};oe.prototype.emitReserved=oe.prototype.emit;oe.prototype.listeners=function(n){return this._callbacks=this._callbacks||{},this._callbacks["$"+n]||[]};oe.prototype.hasListeners=function(n){return!!this.listeners(n).length};const gn=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")(),Ec="arraybuffer";function la(n,...t){return t.reduce((e,s)=>(n.hasOwnProperty(s)&&(e[s]=n[s]),e),{})}const Tc=we.setTimeout,Mc=we.clearTimeout;function yn(n,t){t.useNativeTimers?(n.setTimeoutFn=Tc.bind(we),n.clearTimeoutFn=Mc.bind(we)):(n.setTimeoutFn=we.setTimeout.bind(we),n.clearTimeoutFn=we.clearTimeout.bind(we))}const $c=1.33;function Ic(n){return typeof n=="string"?Sc(n):Math.ceil((n.byteLength||n.size)*$c)}function Sc(n){let t=0,e=0;for(let s=0,i=n.length;s<i;s++)t=n.charCodeAt(s),t<128?e+=1:t<2048?e+=2:t<55296||t>=57344?e+=3:(s++,e+=4);return e}function ha(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function xc(n){let t="";for(let e in n)n.hasOwnProperty(e)&&(t.length&&(t+="&"),t+=encodeURIComponent(e)+"="+encodeURIComponent(n[e]));return t}function _c(n){let t={},e=n.split("&");for(let s=0,i=e.length;s<i;s++){let r=e[s].split("=");t[decodeURIComponent(r[0])]=decodeURIComponent(r[1])}return t}class Ac extends Error{constructor(t,e,s){super(t),this.description=e,this.context=s,this.type="TransportError"}}class di extends oe{constructor(t){super(),this.writable=!1,yn(this,t),this.opts=t,this.query=t.query,this.socket=t.socket,this.supportsBinary=!t.forceBase64}onError(t,e,s){return super.emitReserved("error",new Ac(t,e,s)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(t){this.readyState==="open"&&this.write(t)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(t){const e=fi(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=xc(t);return e.length?"?"+e:""}}class Cc extends di{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(t){this.readyState="pausing";const e=()=>{this.readyState="paused",t()};if(this._polling||!this.writable){let s=0;this._polling&&(s++,this.once("pollComplete",function(){--s||e()})),this.writable||(s++,this.once("drain",function(){--s||e()}))}else e()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){const e=s=>{if(this.readyState==="opening"&&s.type==="open"&&this.onOpen(),s.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(s)};yc(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,gc(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]=ha()),!this.supportsBinary&&!e.sid&&(e.b64=1),this.createUri(t,e)}}let fa=!1;try{fa=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const Rc=fa;function Oc(){}class kc extends Cc{constructor(t){if(super(t),typeof location<"u"){const e=location.protocol==="https:";let s=location.port;s||(s=e?"443":"80"),this.xd=typeof location<"u"&&t.hostname!==location.hostname||s!==t.port}}doWrite(t,e){const s=this.request({method:"POST",data:t});s.on("success",e),s.on("error",(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,s)=>{this.onError("xhr poll error",e,s)}),this.pollXhr=t}}class xe extends oe{constructor(t,e,s){super(),this.createRequest=t,yn(this,s),this._opts=s,this._method=s.method||"GET",this._uri=e,this._data=s.data!==void 0?s.data:null,this._create()}_create(){var t;const e=la(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");e.xdomain=!!this._opts.xd;const s=this._xhr=this.createRequest(e);try{s.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){s.setDisableHeaderCheck&&s.setDisableHeaderCheck(!0);for(let i in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(i)&&s.setRequestHeader(i,this._opts.extraHeaders[i])}}catch{}if(this._method==="POST")try{s.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{s.setRequestHeader("Accept","*/*")}catch{}(t=this._opts.cookieJar)===null||t===void 0||t.addCookies(s),"withCredentials"in s&&(s.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(s.timeout=this._opts.requestTimeout),s.onreadystatechange=()=>{var i;s.readyState===3&&((i=this._opts.cookieJar)===null||i===void 0||i.parseCookies(s.getResponseHeader("set-cookie"))),s.readyState===4&&(s.status===200||s.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof s.status=="number"?s.status:0)},0))},s.send(this._data)}catch(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=Oc,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",Bo);else if(typeof addEventListener=="function"){const n="onpagehide"in we?"pagehide":"unload";addEventListener(n,Bo,!1)}}function Bo(){for(let n in xe.requests)xe.requests.hasOwnProperty(n)&&xe.requests[n].abort()}const Nc=function(){const n=da({xdomain:!1});return n&&n.responseType!==null}();class Fc extends kc{constructor(t){super(t);const e=t&&t.forceBase64;this.supportsBinary=Nc&&!e}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new xe(da,this.uri(),t)}}function da(n){const t=n.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!t||Rc))return new XMLHttpRequest}catch{}if(!t)try{return new we[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const ua=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class Pc extends di{get name(){return"websocket"}doOpen(){const t=this.uri(),e=this.opts.protocols,s=ua?{}:la(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(s.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(t,e,s)}catch(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 s=t[e],i=e===t.length-1;hi(s,this.supportsBinary,r=>{try{this.doWrite(s,r)}catch{}i&&gn(()=>{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]=ha()),this.supportsBinary||(e.b64=1),this.createUri(t,e)}}const _n=we.WebSocket||we.MozWebSocket;class Lc extends Pc{createSocket(t,e,s){return ua?new _n(t,e,s):e?new _n(t,e):new _n(t)}doWrite(t,e){this.ws.send(e)}}class Bc extends di{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=bc(Number.MAX_SAFE_INTEGER,this.socket.binaryType),s=t.readable.pipeThrough(e).getReader(),i=wc();i.readable.pipeTo(t.writable),this._writer=i.writable.getWriter();const r=()=>{s.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 s=t[e],i=e===t.length-1;this._writer.write(s).then(()=>{i&&gn(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this._transport)===null||t===void 0||t.close()}}const jc={websocket:Lc,webtransport:Bc,polling:Fc},Dc=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Uc=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Pn(n){if(n.length>8e3)throw"URI too long";const t=n,e=n.indexOf("["),s=n.indexOf("]");e!=-1&&s!=-1&&(n=n.substring(0,e)+n.substring(e,s).replace(/:/g,";")+n.substring(s,n.length));let i=Dc.exec(n||""),r={},a=14;for(;a--;)r[Uc[a]]=i[a]||"";return e!=-1&&s!=-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=Jc(r,r.path),r.queryKey=qc(r,r.query),r}function Jc(n,t){const e=/\/{2,9}/g,s=t.replace(e,"/").split("/");return(t.slice(0,1)=="/"||t.length===0)&&s.splice(0,1),t.slice(-1)=="/"&&s.splice(s.length-1,1),s}function qc(n,t){const e={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(s,i,r){i&&(e[i]=r)}),e}const Ln=typeof addEventListener=="function"&&typeof removeEventListener=="function",en=[];Ln&&addEventListener("offline",()=>{en.forEach(n=>n())},!1);class We extends oe{constructor(t,e){if(super(),this.binaryType=Ec,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,t&&typeof t=="object"&&(e=t,t=null),t){const s=Pn(t);e.hostname=s.host,e.secure=s.protocol==="https"||s.protocol==="wss",e.port=s.port,s.query&&(e.query=s.query)}else e.host&&(e.hostname=Pn(e.host).host);yn(this,e),this.secure=e.secure!=null?e.secure:typeof location<"u"&&location.protocol==="https:",e.hostname&&!e.port&&(e.port=this.secure?"443":"80"),this.hostname=e.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=e.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},e.transports.forEach(s=>{const i=s.prototype.name;this.transports.push(i),this._transportsByName[i]=s}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},e),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=_c(this.opts.query)),Ln&&(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"})},en.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(t){const e=Object.assign({},this.opts.query);e.EIO=ca,e.transport=t,this.id&&(e.sid=this.id);const s=Object.assign({},this.opts,{query:e,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new this._transportsByName[t](s)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const t=this.opts.rememberUpgrade&&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 s=0;s<this.writeBuffer.length;s++){const i=this.writeBuffer[s].data;if(i&&(e+=Ic(i)),s>0&&e>this._maxPayload)return this.writeBuffer.slice(0,s);e+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const t=Date.now()>this._pingTimeoutTime;return t&&(this._pingTimeoutTime=0,gn(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),t}write(t,e,s){return this._sendPacket("message",t,e,s),this}send(t,e,s){return this._sendPacket("message",t,e,s),this}_sendPacket(t,e,s,i){if(typeof e=="function"&&(i=e,e=void 0),typeof s=="function"&&(i=s,s=null),this.readyState==="closing"||this.readyState==="closed")return;s=s||{},s.compress=s.compress!==!1;const r={type:t,data:e,options:s};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()},s=()=>{this.once("upgrade",e),this.once("upgradeError",e)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?s():t()}):this.upgrading?s():t()),this}_onError(t){if(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(),Ln&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const s=en.indexOf(this._offlineEventListener);s!==-1&&en.splice(s,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,e),this.writeBuffer=[],this._prevBufferLen=0}}}We.protocol=ca;class Hc 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),s=!1;We.priorWebsocketSuccess=!1;const i=()=>{s||(e.send([{type:"ping",data:"probe"}]),e.once("packet",E=>{if(!s)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(()=>{s||this.readyState!=="closed"&&(c(),this.setTransport(e),e.send([{type:"upgrade"}]),this.emitReserved("upgrade",e),e=null,this.upgrading=!1,this.flush())})}else{const b=new Error("probe error");b.transport=e.name,this.emitReserved("upgradeError",b)}}))};function r(){s||(s=!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(()=>{s||e.open()},200):e.open()}onHandshake(t){this._upgrades=this._filterUpgrades(t.upgrades),super.onHandshake(t)}_filterUpgrades(t){const e=[];for(let s=0;s<t.length;s++)~this.transports.indexOf(t[s])&&e.push(t[s]);return e}}let Gc=class extends Hc{constructor(t,e={}){const s=typeof t=="object",i=s?{...t}:{...e};(!i.transports||i.transports&&typeof i.transports[0]=="string")&&(i.transports=(i.transports||["polling","websocket","webtransport"]).map(r=>jc[r]).filter(r=>!!r)),super(s?i:t,i)}};function Vc(n,t="",e){let s=n;e=e||typeof location<"u"&&location,n==null&&(n=e.protocol+"//"+e.host),typeof n=="string"&&(n.charAt(0)==="/"&&(n.charAt(1)==="/"?n=e.protocol+n:n=e.host+n),/^(https?|wss?):\/\//.test(n)||(typeof e<"u"?n=e.protocol+"//"+n:n="https://"+n),s=Pn(n)),s.port||(/^(http|ws)$/.test(s.protocol)?s.port="80":/^(http|ws)s$/.test(s.protocol)&&(s.port="443")),s.path=s.path||"/";const r=s.host.indexOf(":")!==-1?"["+s.host+"]":s.host;return s.id=s.protocol+"://"+r+":"+s.port+t,s.href=s.protocol+"://"+r+(e&&e.port===s.port?"":":"+s.port),s}const zc=typeof ArrayBuffer=="function",Wc=n=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(n):n.buffer instanceof ArrayBuffer,pa=Object.prototype.toString,Yc=typeof Blob=="function"||typeof Blob<"u"&&pa.call(Blob)==="[object BlobConstructor]",Kc=typeof File=="function"||typeof File<"u"&&pa.call(File)==="[object FileConstructor]";function ui(n){return zc&&(n instanceof ArrayBuffer||Wc(n))||Yc&&n instanceof Blob||Kc&&n instanceof File}function sn(n,t){if(!n||typeof n!="object")return!1;if(Array.isArray(n)){for(let e=0,s=n.length;e<s;e++)if(sn(n[e]))return!0;return!1}if(ui(n))return!0;if(n.toJSON&&typeof n.toJSON=="function"&&arguments.length===1)return sn(n.toJSON(),!0);for(const e in n)if(Object.prototype.hasOwnProperty.call(n,e)&&sn(n[e]))return!0;return!1}function Xc(n){const t=[],e=n.data,s=n;return s.data=Bn(e,t),s.attachments=t.length,{packet:s,buffers:t}}function Bn(n,t){if(!n)return n;if(ui(n)){const e={_placeholder:!0,num:t.length};return t.push(n),e}else if(Array.isArray(n)){const e=new Array(n.length);for(let s=0;s<n.length;s++)e[s]=Bn(n[s],t);return e}else if(typeof n=="object"&&!(n instanceof Date)){const e={};for(const s in n)Object.prototype.hasOwnProperty.call(n,s)&&(e[s]=Bn(n[s],t));return e}return n}function Zc(n,t){return n.data=jn(n.data,t),delete n.attachments,n}function jn(n,t){if(!n)return n;if(n&&n._placeholder===!0){if(typeof n.num=="number"&&n.num>=0&&n.num<t.length)return t[n.num];throw new Error("illegal attachments")}else if(Array.isArray(n))for(let e=0;e<n.length;e++)n[e]=jn(n[e],t);else if(typeof n=="object")for(const e in n)Object.prototype.hasOwnProperty.call(n,e)&&(n[e]=jn(n[e],t));return n}const Qc=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var zt;(function(n){n[n.CONNECT=0]="CONNECT",n[n.DISCONNECT=1]="DISCONNECT",n[n.EVENT=2]="EVENT",n[n.ACK=3]="ACK",n[n.CONNECT_ERROR=4]="CONNECT_ERROR",n[n.BINARY_EVENT=5]="BINARY_EVENT",n[n.BINARY_ACK=6]="BINARY_ACK"})(zt||(zt={}));class tl{constructor(t){this.replacer=t}encode(t){return(t.type===zt.EVENT||t.type===zt.ACK)&&sn(t)?this.encodeAsBinary({type:t.type===zt.EVENT?zt.BINARY_EVENT:zt.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id}):[this.encodeAsString(t)]}encodeAsString(t){let e=""+t.type;return(t.type===zt.BINARY_EVENT||t.type===zt.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=Xc(t),s=this.encodeAsString(e.packet),i=e.buffers;return i.unshift(s),i}}class pi 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 s=e.type===zt.BINARY_EVENT;s||e.type===zt.BINARY_ACK?(e.type=s?zt.EVENT:zt.ACK,this.reconstructor=new el(e),e.attachments===0&&super.emitReserved("decoded",e)):super.emitReserved("decoded",e)}else if(ui(t)||t.base64)if(this.reconstructor)e=this.reconstructor.takeBinaryData(t),e&&(this.reconstructor=null,super.emitReserved("decoded",e));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+t)}decodeString(t){let e=0;const s={type:Number(t.charAt(0))};if(zt[s.type]===void 0)throw new Error("unknown packet type "+s.type);if(s.type===zt.BINARY_EVENT||s.type===zt.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(!sl(l)||l<0)throw new Error("Illegal attachments");if(l>this.opts.maxAttachments)throw new Error("too many attachments");s.attachments=l}if(t.charAt(e+1)==="/"){const r=e+1;for(;++e&&!(t.charAt(e)===","||e===t.length););s.nsp=t.substring(r,e)}else s.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}s.id=Number(t.substring(r,e+1))}if(t.charAt(++e)){const r=this.tryParse(t.substr(e));if(pi.isPayloadValid(s.type,r))s.data=r;else throw new Error("invalid payload")}return s}tryParse(t){try{return JSON.parse(t,this.opts.reviver)}catch{return!1}}static isPayloadValid(t,e){switch(t){case zt.CONNECT:return jo(e);case zt.DISCONNECT:return e===void 0;case zt.CONNECT_ERROR:return typeof e=="string"||jo(e);case zt.EVENT:case zt.BINARY_EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&Qc.indexOf(e[0])===-1);case zt.ACK:case zt.BINARY_ACK:return Array.isArray(e)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class el{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=Zc(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const sl=Number.isInteger||function(n){return typeof n=="number"&&isFinite(n)&&Math.floor(n)===n};function jo(n){return Object.prototype.toString.call(n)==="[object Object]"}const nl=Object.freeze(Object.defineProperty({__proto__:null,Decoder:pi,Encoder:tl,get PacketType(){return zt}},Symbol.toStringTag,{value:"Module"}));function Ee(n,t,e){return n.on(t,e),function(){n.off(t,e)}}const il=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class ma extends oe{constructor(t,e,s){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=t,this.nsp=e,s&&s.auth&&(this.auth=s.auth),this._opts=Object.assign({},s),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const t=this.io;this.subs=[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 s,i,r;if(il.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:zt.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=(s=this.io.engine)===null||s===void 0?void 0:s.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 s;const i=(s=this.flags.timeout)!==null&&s!==void 0?s: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((s,i)=>{const r=(a,l)=>a?i(a):s(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 s={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?s.tryCount>this._opts.retries&&(this._queue.shift(),e&&e(i)):(this._queue.shift(),e&&e(null,...r)),s.pending=!1,this._drainQueue())),this._queue.push(s),this._drainQueue()}_drainQueue(t=!1){if(!this.connected||this._queue.length===0)return;const e=this._queue[0];e.pending&&!t||(e.pending=!0,e.tryCount++,this.flags=e.flags,this.emit.apply(this,e.args))}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){typeof this.auth=="function"?this.auth(t=>{this._sendConnectPacket(t)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:zt.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,e){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,e),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(t=>{if(!this.sendBuffer.some(s=>String(s.id)===t)){const s=this.acks[t];delete this.acks[t],s.withError&&s.call(this,new Error("socket has been disconnected"))}})}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case zt.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 zt.EVENT:case zt.BINARY_EVENT:this.onevent(t);break;case zt.ACK:case zt.BINARY_ACK:this.onack(t);break;case zt.DISCONNECT:this.ondisconnect();break;case zt.CONNECT_ERROR:this.destroy();const s=new Error(t.data.message);s.data=t.data.data,this.emitReserved("connect_error",s);break}}onevent(t){const e=t.data||[];t.id!=null&&e.push(this.ack(t.id)),this.connected?this.emitEvent(e):this.receiveBuffer.push(Object.freeze(e))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){const e=this._anyListeners.slice();for(const s of e)s.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&typeof t[t.length-1]=="string"&&(this._lastOffset=t[t.length-1])}ack(t){const e=this;let s=!1;return function(...i){s||(s=!0,e.packet({type:zt.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:zt.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){const e=this._anyListeners;for(let s=0;s<e.length;s++)if(t===e[s])return e.splice(s,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(t),this}prependAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(t),this}offAnyOutgoing(t){if(!this._anyOutgoingListeners)return this;if(t){const e=this._anyOutgoingListeners;for(let s=0;s<e.length;s++)if(t===e[s])return e.splice(s,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(t){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const e=this._anyOutgoingListeners.slice();for(const s of e)s.apply(this,t.data)}}}function ps(n){n=n||{},this.ms=n.min||100,this.max=n.max||1e4,this.factor=n.factor||2,this.jitter=n.jitter>0&&n.jitter<=1?n.jitter:0,this.attempts=0}ps.prototype.duration=function(){var n=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),e=Math.floor(t*this.jitter*n);n=Math.floor(t*10)&1?n+e:n-e}return Math.min(n,this.max)|0};ps.prototype.reset=function(){this.attempts=0};ps.prototype.setMin=function(n){this.ms=n};ps.prototype.setMax=function(n){this.max=n};ps.prototype.setJitter=function(n){this.jitter=n};class Dn extends oe{constructor(t,e){var s;super(),this.nsps={},this.subs=[],t&&typeof t=="object"&&(e=t,t=void 0),e=e||{},e.path=e.path||"/socket.io",this.opts=e,yn(this,e),this.reconnection(e.reconnection!==!1),this.reconnectionAttempts(e.reconnectionAttempts||1/0),this.reconnectionDelay(e.reconnectionDelay||1e3),this.reconnectionDelayMax(e.reconnectionDelayMax||5e3),this.randomizationFactor((s=e.randomizationFactor)!==null&&s!==void 0?s:.5),this.backoff=new ps({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||nl;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 Gc(this.uri,this.opts);const e=this.engine,s=this;this._readyState="opening",this.skipReconnect=!1;const i=Ee(e,"open",function(){s.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){gn(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,e){let s=this.nsps[t];return s?this._autoConnect&&!s.active&&s.connect():(s=new ma(this,t,e),this.nsps[t]=s),s}_destroy(t){const e=Object.keys(this.nsps);for(const s of e)if(this.nsps[s].active)return;this._close()}_packet(t){const e=this.encoder.encode(t);for(let s=0;s<e.length;s++)this.engine.write(e[s],t.options)}cleanup(){this.subs.forEach(t=>t()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(t,e){var s;this.cleanup(),(s=this.engine)===null||s===void 0||s.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,e),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const e=this.backoff.duration();this._reconnecting=!0;const s=this.setTimeoutFn(()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),!t.skipReconnect&&t.open(i=>{i?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",i)):t.onreconnect()}))},e);this.opts.autoUnref&&s.unref(),this.subs.push(()=>{this.clearTimeoutFn(s)})}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const bs={};function Rs(n,t){typeof n=="object"&&(t=n,n=void 0),t=t||{};const e=Vc(n,t.path||"/socket.io"),s=e.source,i=e.id,r=e.path,a=bs[i]&&r in bs[i].nsps,l=t.forceNew||t["force new connection"]||t.multiplex===!1||a;let p;return l?p=new Dn(s,t):(bs[i]||(bs[i]=new Dn(s,t)),p=bs[i]),e.query&&!t.query&&(t.query=e.queryKey),p.socket(e.path,t)}Object.assign(Rs,{Manager:Dn,Socket:ma,io:Rs,connect:Rs});class Un 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 Do="bimterop",Jn="revitflow_history.json",ga="revitflow_model.frag",ya="revitflow_",rl="bimterop-locks-anchor",vs=new Map;function ol(n,t){return n.filter(e=>String(e.parentId??"")===t)}function al(n){const t=n==null?void 0:n.hiddenFileId;if(typeof t!="string"||!t)throw new Error("The hidden-file upload answered without a hiddenFileId.");return t}function Ie(n){return String(n._id??n.id??"")}var ve,Ye,ke,Ns,Fs,qn;class mi{constructor(t,e){Lt(this,Fs);Lt(this,ve);Lt(this,Ye,new Map);Lt(this,ke);Lt(this,Ns,0);this.client=t,this.projectId=e}async docs(){const t=await I(this,Fs,qn).call(this);if(!t)return[];const e=await this.childFolders(t,!0),s=[];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===ga)??p.find(E=>E.endsWith(".frag")&&!E.startsWith(ya)),c=p.includes(Jn)||!!d;s.push({source:r.slice(0,a),docId:r.slice(a+1),folderId:Ie(i),modelName:d,...c?{}:{empty:!0}})}return s}doc(t,e){const s=`${t}-${e}`;let i=R(this,Ye).get(s);return i||(i=new Hn(this.client,this,t,e),R(this,Ye).set(s,i)),i}document(t){const e=`platform-${t}`;let s=R(this,Ye).get(e);return s||(s=new Hn(this.client,this,"platform",t,t),R(this,Ye).set(e,s)),s}async childFolders(t,e=!1){return(e||!R(this,ke)||Date.now()-R(this,Ns)>3e4)&&(Vt(this,Ns,Date.now()),Vt(this,ke,this.client.listFolders({parentFolderId:t,projectId:this.projectId}).then(s=>ol(s,t))),R(this,ke).catch(()=>{Vt(this,ke,void 0)})),R(this,ke)}forgetFolders(){Vt(this,ke,void 0)}async rootFolderId(t=!1){if(R(this,ve))return R(this,ve);const e=await I(this,Fs,qn).call(this);if(e)return e;if(!t)return;const s=await this.client.createFolder(Do,void 0,this.projectId);return Vt(this,ve,Ie(s)),R(this,ve)}}ve=new WeakMap,Ye=new WeakMap,ke=new WeakMap,Ns=new WeakMap,Fs=new WeakSet,qn=async function(){if(R(this,ve))return R(this,ve);const e=(await this.client.listFolders({projectId:this.projectId})).find(s=>String(s.name??"")===Do&&!s.parentId);return e&&Vt(this,ve,Ie(e)),R(this,ve)};var Me,Et,Re,ss,Ue,$e,Ps,Gn,nn,Je,wa,ba,rn,va,Ea,Ta;class Hn{constructor(t,e,s,i,r){Lt(this,Et);Lt(this,Me);Lt(this,$e);Lt(this,Ps,0);this.client=t,this.project=e,this.source=s,this.docId=i,Vt(this,Me,r)}async timeline(){const t=await I(this,Et,rn).call(this);return gi((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 s=t==null?void 0:t.at,i=s?e.findIndex(c=>c.guid===s):e.length-1;if(i<0)throw new Error(`No version ${s} 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 R(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),s=await R(this,Et,Re).descriptor(e);if(s){for(const r of t){const a=s.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 R(this,Et,Re).descriptor(e)){await R(this,Et,Re).addView(e,t);return}const i=await I(this,Et,Je).call(this);await R(this,Et,Re).setDescriptor(e,{name:(i==null?void 0:i.name.replace(/\.frag$/,""))??R(this,Et,ss),views:[t]})}async ensureDescriptor(){const t=await I(this,Et,Ue).call(this,!1),e=await R(this,Et,Re).descriptor(t);if(e)return e;const s=await I(this,Et,Je).call(this);if(!s)return null;const i={name:s.name.replace(/\.frag$/,""),views:[{fileId:s.id,format:"frag"}]};return await R(this,Et,Re).setDescriptor(t,i),await R(this,Et,Re).descriptor(t)}async ownership(){const t=await I(this,Et,nn).call(this,rl);if(!t)return[];const e=await this.client.getHiddenFilesByParent(t.id),s=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 s)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 s=await I(this,Et,rn).call(this)??{model:this.docId,commits:[]};const i=Uo(s.commits);if(t.expectedLatestGuid!==void 0&&(i==null?void 0:i.guid)!==t.expectedLatestGuid)throw new Un(t.expectedLatestGuid,i==null?void 0:i.guid);const r={guid:yi(),...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:cl(t.changes)};if(t.model&&(await I(this,Et,Ta).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=al(E)}const a=await I(this,Et,rn).call(this);if(a){s=a;const c=Uo(s.commits);if(t.expectedLatestGuid!==void 0&&(c==null?void 0:c.guid)!==t.expectedLatestGuid)throw new Un(t.expectedLatestGuid,c==null?void 0:c.guid);c&&!r.parents&&(r.parents=[c.guid])}return s.commits.push(r),await I(this,Et,va).call(this,e,Jn,s),r}}Me=new WeakMap,Et=new WeakSet,Re=function(){return new bi(this.client,this.project.projectId)},ss=function(){return`${this.source}-${this.docId}`},Ue=async function(t){if(R(this,Me))return R(this,Me);const e=await this.project.rootFolderId(t);if(!e)throw new Error(`Project ${this.project.projectId} has no connected documents yet.`);const s=a=>a.find(l=>String(l.name??"")===R(this,Et,ss)),i=s(await this.project.childFolders(e))??s(await this.project.childFolders(e,!0));if(i)return Vt(this,Me,Ie(i)),R(this,Me);if(!t)throw new Error(`Document ${R(this,Et,ss)} does not exist in this project.`);const r=await this.client.createFolder(R(this,Et,ss),e,this.project.projectId);return this.project.forgetFolders(),Vt(this,Me,Ie(r)),R(this,Me)},$e=new WeakMap,Ps=new WeakMap,Gn=async function(){return(!R(this,$e)||Date.now()-R(this,Ps)>5e3)&&(Vt(this,Ps,Date.now()),Vt(this,$e,(async()=>{const t=await I(this,Et,Ue).call(this,!1);return t?(await this.client.listFiles({folderId:t,versions:!0})).map(s=>({id:Ie(s),name:String(s.name??""),stamp:un(s)})):[]})()),R(this,$e).catch(()=>{Vt(this,$e,void 0)})),R(this,$e)},nn=async function(t){try{return(await I(this,Et,Gn).call(this)).find(e=>e.name===t)}catch{return}},Je=async function(){try{const t=await I(this,Et,Gn).call(this);return t.find(e=>e.name===ga)??t.find(e=>e.name.endsWith(".frag")&&!e.name.startsWith(ya))}catch{return}},wa=async function(t){const e=await I(this,Et,nn).call(this,t);if(!e)return;const s=e.stamp?vs.get(e.id):void 0;if(s&&s.stamp===e.stamp)return structuredClone(await s.value);const i=I(this,Et,ba).call(this,e,t);return e.stamp&&(vs.set(e.id,{stamp:e.stamp,value:i}),i.catch(()=>{var r;((r=vs.get(e.id))==null?void 0:r.value)===i&&vs.delete(e.id)})),structuredClone(await i)},ba=async function(t,e){const s=await this.client.downloadFile(t.id);if(!s.ok)throw new Error(`Reading ${e} answered ${s.status}`);const i=await s.text();if(i.trim())return JSON.parse(i)},rn=function(){return I(this,Et,wa).call(this,Jn)},va=async function(t,e,s){const i=new Blob([JSON.stringify(s)],{type:"application/json"}),r=await I(this,Et,nn).call(this,e);return r?(vs.delete(r.id),await this.client.updateFile(r.id,{file:i,versionTag:await this.client.nextVersionTag(r.id)}),r):await I(this,Et,Ea).call(this,t,e,s)},Ea=async function(t,e,s){const i=new Blob([JSON.stringify(s)],{type:"application/json"}),r=await this.client.createFile({file:i,name:e,versionTag:"v1",parentFolderId:t,projectId:this.project.projectId});Vt(this,$e,void 0);const a=r.item;return{id:Ie(a??r),name:e}},Ta=async function(t,e){const s=await I(this,Et,Je).call(this);if(s)return await this.client.updateFile(s.id,{file:e,versionTag:await this.client.nextVersionTag(s.id)}),s;const i=`${R(this,Et,ss)}.frag`,r=await this.client.createFile({file:e,name:i,versionTag:"v1",parentFolderId:t,projectId:this.project.projectId});Vt(this,$e,void 0);const a=r.item;return{id:Ie(a??r),name:i}};function cl(n){const t={added:0,modified:0,removed:0};for(const e of n)e.type==="create"?t.added++:e.type==="delete"?t.removed++:t.modified++;return t}function gi(n){var p;if(n.length<=1)return n.forEach((d,c)=>d.ordinal=c),[...n];const t=new Map(n.map(d=>[d.guid,d])),e=new Map,s=[];for(const d of n){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 s.push(d)}const i=(d,c)=>String(d.timestamp).localeCompare(String(c.timestamp));s.sort(i);const r=[],a=[...s].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 n)l.has(d.guid)||r.push(d);return r.forEach((d,c)=>d.ordinal=c),r}function Uo(n){const t=gi(n);return t[t.length-1]}function yi(){const n=globalThis.crypto;return n!=null&&n.randomUUID?n.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 wi={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"}},ll={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 Vn(n){var e;if(n.type&&n.type in wi)return n.type;const t=[(e=n.native)==null?void 0:e.format,...n.views.map(s=>s.format)];for(const s of t){const i=s?ll[s.toLowerCase()]:void 0;if(i)return i}return"generic"}const ks="thatopen/document@1",Ss="document.json",Ma=["pdf","txt","md","json","csv","tsv","frag"];function be(n){return String(n._id??n.id??"")}const ts=new Map;let Jo=!1;const un=n=>{const t=n,e=[...t.versions??[]].sort((i,r)=>String(r.createdAt??"").localeCompare(String(i.createdAt??"")))[0],s=(e==null?void 0:e.tag)??t.versionTag;return s==null?void 0:String(s)};var ne,$a,Ia,zn,Sa,xa,_a,Aa,xs;class bi{constructor(t,e){Lt(this,ne);this.client=t,this.projectId=e}async list(t){const e=await I(this,ne,$a).call(this),s=t==null?void 0:t.types;return s!=null&&s.length?e.filter(i=>s.includes(Vn(i.descriptor))):e}async fromFile(t,e){const s=await this.client.getFile(t),i=String(s.name??""),r=An(i,s.fileExtension),a=(e==null?void 0:e.name)??i.replace(/\.[^.]+$/,"")??i,l=new Set((await this.list().catch(()=>[])).map(N=>String(N.descriptor.name??"").toLowerCase())),p=s.folderId?String(s.folderId):void 0;let d=a,c="";for(let N=1;N<100;N++){if(d=N===1?a:`${a} (${N})`,l.has(d.toLowerCase()))continue;const Y=await this.client.createFolder(d,p,this.projectId);if(c=be(Y),!await I(this,ne,xs).call(this,c))break}await this.client.updateFile(t,{parentFolderId:c});const E=[],b=await I(this,ne,xa).call(this,s);if(b)try{const N=await this.client.getFile(b);await this.client.updateFile(b,{parentFolderId:c}),E.push({fileId:b,format:An(String(N.name??""),N.fileExtension)})}catch{}((e==null?void 0:e.selfView)??Ma.includes(r))&&E.push({fileId:t,format:r});const P={schema:ks,name:d,native:{fileId:t,format:r},views:E};return P.type=(e==null?void 0:e.type)??Vn(P),await this.setDescriptor(c,P),await this.recordUpload(c,{fileId:t,name:i,format:r},(e==null?void 0:e.author)??String(s.createdBy??"")),{folderId:c,descriptor:P}}async recordUpload(t,e,s){const i=new mi(this.client,this.projectId).document(t),r=(await i.timeline()).length===0;await i.sync({author:s||"unknown",source:"platform",kind:"upload",message:r?"Uploaded to the platform":"New version uploaded",file:{...e,format:e.format??An(e.name,void 0)},changes:[]})}async descriptor(t){const e=await I(this,ne,xs).call(this,t);return e?I(this,ne,zn).call(this,e.id,e.stamp):null}async view(t,e){const s=await this.descriptor(t);if(!s)return null;for(const i of e){const r=s.views.find(a=>a.format===i);if(r)return r}return null}async addView(t,e){const s=await this.descriptor(t);if(!s)throw new Error("This folder has no document descriptor yet: call setDescriptor first.");s.views=[...s.views.filter(i=>i.format!==e.format),e],await this.setDescriptor(t,s)}async setType(t,e){const s=await this.descriptor(t);if(!s)throw new Error("This folder has no document descriptor yet: call setDescriptor first.");s.type!==e&&await this.setDescriptor(t,{...s,type:e})}async setDescriptor(t,e){const s={...e,schema:ks,views:e.views??[]},i=new Blob([JSON.stringify(s)],{type:"application/json"}),r=await I(this,ne,xs).call(this,t);if(r){ts.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:Ss,versionTag:"v1",parentFolderId:t,projectId:this.projectId})}drafts(t){return new Ca(this.client,()=>I(this,ne,xs).call(this,t))}}ne=new WeakSet,$a=async function(){const t=await I(this,ne,Ia).call(this);if(t)return t;const s=(await this.client.listFiles({projectId:this.projectId})).filter(r=>String(r.name??"")===Ss);return(await Promise.all(s.map(async r=>{const a=r,l=String(a.folderId??a.parentFolderId??"");if(!l)return null;const p=await I(this,ne,zn).call(this,be(r),un(r));return p?{folderId:l,descriptor:p}:null}))).filter(r=>r!==null)},Ia=async function(){if(Jo)return null;let t;try{t=await this.client.listDocumentDescriptors(this.projectId)}catch(s){const i=s.status;if(i===404||i===400||i===405)return Jo=!0,null;throw s}const e=[];for(const s of(t==null?void 0:t.documents)??[]){const i=Ho(s.descriptor);!i||!s.folderId||(s.fileId&&s.versionTag&&ts.set(s.fileId,{stamp:s.versionTag,value:Promise.resolve(i)}),e.push({folderId:String(s.folderId),descriptor:i}))}return e},zn=function(t,e){const s=e?ts.get(t):void 0;if(s&&s.stamp===e)return s.value;const i=I(this,ne,Sa).call(this,t);return e&&(ts.set(t,{stamp:e,value:i}),i.catch(()=>{var r;((r=ts.get(t))==null?void 0:r.value)===i&&ts.delete(t)})),i},Sa=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 s=await e.text();if(!s.trim())return null;let i;try{i=JSON.parse(s)}catch{return null}return Ho(i)},xa=async function(t){let e=t.versions??[],s;if(e.length===0){s=await this.client.listFiles({projectId:this.projectId}).catch(()=>[]);const d=s.find(c=>be(c)===be(t));e=(d==null?void 0:d.versions)??[]}const i=await I(this,ne,Aa).call(this,t,e);if(i)return i;const r=String(t.name??"").replace(/\.[^.]+$/,"").toLowerCase();if(!r)return;s??(s=await this.client.listFiles({projectId:this.projectId}).catch(()=>[]));const a=d=>String(d.folderId??d.parentFolderId??""),l=new Set(s.filter(d=>String(d.name??"")===Ss).map(a)),p=s.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,ne,_a).call(this,d);if(c===void 0||c===be(t))return be(d)}},_a=async function(t){const s=[...t.versions??[]].sort((i,r)=>String(r.createdAt??"").localeCompare(String(i.createdAt??"")))[0];if(s)try{const i=await this.client.getFileVersionMetadata(be(t),s.tag);return typeof(i==null?void 0:i.sourceIfcId)=="string"&&i.sourceIfcId?i.sourceIfcId:void 0}catch{return}},Aa=async function(t,e){const s=[...e].sort((i,r)=>String(r.createdAt??"").localeCompare(String(i.createdAt??"")));for(const i of s)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{}},xs=async function(t){if(!t)return;const s=(await this.client.listFiles({folderId:t,versions:!0})).find(i=>String(i.name??"")===Ss);return s?{id:be(s),stamp:un(s)}:void 0};const Wn="draft:",ns="TODRAFT1";var Se,_s,Yn;class Ca{constructor(t,e){Lt(this,Se);this.client=t,this.holder=e}async list(){const t=await this.holder();if(!t)return[];const e=new Map;for(const s of await I(this,Se,_s).call(this,t.id)){const i=e.get(s.userId);(!i||s.savedAt>i.savedAt)&&e.set(s.userId,{userId:s.userId,savedAt:s.savedAt})}return[...e.values()].sort((s,i)=>+i.savedAt-+s.savedAt)}async get(t){const e=await this.holder();if(!e)return null;const i=(await I(this,Se,_s).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 dl(await r.blob());return{userId:i.userId,savedAt:i.savedAt,meta:a,blob:l}}async put(t,e){const s=await this.holder();if(!s)throw new Error("This folder is not a document (no document.json): drafts need one.");const i=hl(e.userId),r=(await I(this,Se,_s).call(this,s.id)).filter(p=>p.userId===e.userId),l=(await this.client.createHiddenFile(await fl(t,e.meta??{}),s.id,i)).hiddenFileId;if(!l)throw new Error("The draft upload answered without a hiddenFileId.");return await I(this,Se,Yn).call(this,r.map(p=>p.hiddenId)),{userId:e.userId,savedAt:qo(l)}}async delete(t){const e=await this.holder();if(!e)return;const s=(await I(this,Se,_s).call(this,e.id)).filter(i=>i.userId===t.userId);await I(this,Se,Yn).call(this,s.map(i=>i.hiddenId))}}Se=new WeakSet,_s=async function(t){return(await this.client.getHiddenFilesByParent(t)).filter(s=>typeof s.tag=="string"&&s.tag.startsWith(Wn)).map(s=>{const i=String(s._id);return{hiddenId:i,userId:s.tag.slice(Wn.length),savedAt:qo(i)}})},Yn=async function(t){for(const e of t)try{await this.client.deleteHiddenFile(e)}catch{}};function hl(n){const t=`${Wn}${n}`;if(!/^[A-Za-z0-9][A-Za-z0-9:._-]{0,49}$/.test(t))throw new Error(`A draft cannot be tagged for user "${n}": ids must be letters, digits or :._- and short.`);return t}function qo(n){const t=parseInt(n.slice(0,8),16);return new Date(Number.isFinite(t)?t*1e3:0)}async function fl(n,t){const e=new TextEncoder().encode(JSON.stringify(t)),s=new Uint8Array(4);return new DataView(s.buffer).setUint32(0,e.length,!0),new Blob([new TextEncoder().encode(ns),s,e,n])}async function dl(n){const t=new Uint8Array(await n.slice(0,ns.length+4).arrayBuffer());if(new TextDecoder().decode(t.slice(0,ns.length))!==ns)return{meta:{},blob:n};const e=new DataView(t.buffer).getUint32(ns.length,!0),s=ns.length+4,i=await n.slice(s,s+e).text();let r={};try{r=JSON.parse(i)}catch{}return{meta:r,blob:n.slice(s+e)}}function An(n,t){const e=(t??"").replace(/^\./,"").toLowerCase();if(e)return e;const s=n.lastIndexOf(".");return s>0?n.slice(s+1).toLowerCase():""}function Ho(n){if(!n||typeof n!="object")return null;const t=n;if(t.schema!==ks||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"):[],s=t.native,i=!!s&&typeof s=="object"&&typeof s.fileId=="string"&&typeof s.format=="string",r=typeof t.type=="string"&&t.type in wi?t.type:void 0,a={...t};return delete a.type,delete a.native,{...a,schema:ks,name:t.name,...r?{type:r}:{},...i?{native:{fileId:s.fileId,format:s.format}}:{},views:e}}const ul="flow:",pl="flow:op",ml="flow:source",gl="flow:host",yl="flow:print",vi="revitflow/op@2",Go="REVITFLOWCHANGE",Vo="REVITFLOWOPERATION";class wn{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,s={}){return this.requireId(t,"set"),this.changes.push({op:"set",item:t,attrs:this.pack(e,s)}),this}remove(t){return this.requireId(t,"remove"),this.changes.push({op:"remove",item:t,attrs:{}}),this}get summary(){const t=new Set(this.changes.map(e=>e.op));return t.size===1?[...t][0]:"mixed"}async build(t){if(this.changes.length===0)throw new Error("An operation with no changes is not an operation. Add at least one.");const e={schema:vi,opId:t,batchId:this.batchId??t,targetProject:this.target.project,targetDocument:this.target.document,baseCommit:this.baseCommit,author:this.author,...this.userId?{userId:this.userId}:{},title:this.title,summary:this.summary},[s,i]=await wl();return bl(this.flatbuffer(s,i,t,JSON.stringify(e)))}pack(t,e){const s={};for(const[i,r]of Object.entries(t??{}))i.startsWith(ul)&&i!==yl||(s[i]=String(r));return e.position&&(s.Position=e.position.map(zo).join(",")),e.rotationDeg!==void 0&&(s.Rotation=zo(e.rotationDeg)),e.source&&(s[ml]=e.source),e.host&&(s[gl]=e.host),s}requireId(t,e){if(!t||!t.trim())throw new Error(`A '${e}' has to name the item it acts on.`)}flatbuffer(t,e,s,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=$++,N=rt=>(rt(c,0),c.endVector()),Y=a.createShellsVector(c,[]),z=a.createCircleExtrusionsVector(c,[]),D=N(a.startSamplesVector),f=N(a.startRepresentationsVector),Tt=N(a.startMaterialsVector),st=N(a.startLocalTransformsVector),wt=N(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,st),a.addMaterials(c,Tt),a.addCircleExtrusions(c,z),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 Yt=a.endMeshes(c),at=c.createString(i),nt=new Set,pt=[];for(const rt of this.changes){const _t=[],ie={[pl]:rt.op,...rt.attrs};for(const[Nt,le]of Object.entries(ie)){const me=JSON.stringify([Nt,le,"IFCTEXT"]);nt.add(me),_t.push(c.createString(me))}pt.push(r.createAttribute(c,r.createDataVector(c,_t)))}{const rt=JSON.stringify(["Name",s,"IFCLABEL"]);nt.add(rt);const _t=r.createDataVector(c,[c.createString(rt)]);pt.push(r.createAttribute(c,_t))}const jt=l.createAttributesVector(c,pt),Ht=l.createUniqueAttributesVector(c,[...nt].map(rt=>c.createString(rt))),Dt=this.changes.map(()=>c.createString(Go));Dt.push(c.createString(Vo));const Xt=l.createCategoriesVector(c,Dt),Kt=[],Wt=[];this.changes.forEach((rt,_t)=>{rt.item&&(Kt.push(c.createString(rt.item)),Wt.push(b[_t]))});const U=l.createGuidsVector(c,Kt),Z=l.createGuidsItemsVector(c,Wt),B=l.createLocalIdsVector(c,[...b,P]),ut=this.changes.map((rt,_t)=>p.createSpatialStructure(c,b[_t],c.createString(Go),0)),X=p.createSpatialStructure(c,P,c.createString(Vo),p.createChildrenVector(c,ut)),dt=c.createString(s);l.startModel(c),l.addMeshes(c,Yt),l.addMetadata(c,at),l.addAttributes(c,jt),l.addUniqueAttributes(c,Ht),l.addLocalIds(c,B),l.addCategories(c,Xt),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 wl(){try{return await Promise.all([import("flatbuffers"),import("@thatopen/fragments")])}catch(n){throw new Error(`OperationBuilder needs the optional peers \`flatbuffers\` and \`@thatopen/fragments\` installed — add them to the app that authors operations. (${n instanceof Error?n.message:String(n)})`)}}function zo(n){return Number.isFinite(n)?String(n):"0"}async function bl(n){const t=new Blob([n]).stream().pipeThrough(new CompressionStream("deflate"));return new Uint8Array(await new Response(t).arrayBuffer())}async function bn(n){const[t,e]=await vl(),s=e.Model.getRootAsModel(new t.ByteBuffer(await El(n)));let i={};try{i=JSON.parse(s.metadata()??"{}")}catch{}const r=new Map;for(let l=0;l<s.guidsLength();l++){const p=s.guidsItems(l),d=s.guids(l);p!==null&&d&&r.set(p,d)}const a=[];for(let l=0;l<s.attributesLength();l++){const p=s.localIds(l);if(p===null)continue;const d={},c=s.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:s.categories(l)??null,attrs:d})}return{metadata:i,items:a}}async function vl(){try{return await Promise.all([import("flatbuffers"),import("@thatopen/fragments")])}catch(n){throw new Error(`readFrag needs the optional peers \`flatbuffers\` and \`@thatopen/fragments\` resolvable (in Node, fragments also pulls its own imports, e.g. web-ifc). (${n instanceof Error?n.message:String(n)})`)}}async function El(n){const t=new Blob([n]).stream().pipeThrough(new DecompressionStream("deflate"));return new Uint8Array(await new Response(t).arrayBuffer())}const Ra="Element",Oa="Carried",rs=1/.3048;function ka(n){const t=[];for(const e of n)for(const s of[Ra,Oa]){const i=e.attrs[s];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(n,t){const e=n.params[t];if(typeof e!="string")return null;try{return JSON.parse(e)}catch{return null}}function Tl(n){const t=new Map;for(const[e,s]of Ei(n))t.set(e,s.name);return t}function Ei(n){const t=new Map;for(const e of n){if(e.kind!=="datum"||e.params.of!=="level")continue;const s=e.params.named,i=e.params.at;typeof s=="string"&&typeof i=="number"&&t.set(e.id,{name:s,at:i})}return t}function Na(n){const t=new Map;for(const e of n){if(!e.kind.endsWith("Style"))continue;const s=e.params.name;typeof s=="string"&&t.set(s,e)}return t}function Ti(n,t){const e=new Map;for(const[s,i]of n.made)e.set(s,i.id),i.print&&(t==null||t.set(s,i.print));return e}function on(n){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(n));let s=2166136261;for(let i=0;i<e.length;i++)s^=e.charCodeAt(i),s=Math.imul(s,16777619);return(s>>>0).toString(36)}async function Mi(n,t){var a,l;if(!(t!=null&&t.fileId))throw new Error("Choose the model file to read.");n.progress(`Downloading ${t.name}`);let e=new Uint8Array(await(await n.client.downloadFile(t.fileId,t.version?{versionTag:t.version}:void 0)).arrayBuffer());const s=((l=(a=/\.([^.]+)$/.exec(t.name))==null?void 0:a[1])==null?void 0:l.toLowerCase())??"frag";let i=null,r=null;if(s!=="frag"){const p=n.client.recipes.importerFor(s);if(!p)throw new Error(`This app cannot read .${s} files: it provides no importer for them.`);s==="ifc"&&(i=Fa(e));const d=n.client.recipes.shapesFor(s);d&&(n.progress(`Reading the shapes of ${t.name}`),r=await d(e,t.name)),n.progress(`Reading ${t.name}`),e=await p(e,t.name)}return{picked:t,contents:await bn(e),site:i,shapes:r}}function Fa(n){var wt;const t=new TextDecoder("latin1").decode(n),e=Pt=>new RegExp(`^${Pt}=\\s*([A-Z0-9_]+)\\((.*)\\);\\s*$`,"m").exec(t),s=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]=s(l[2]);if(p!=="$"||!d)return null;const c=e(d);if((c==null?void 0:c[1])!=="IFCAXIS2PLACEMENT3D")return null;const[E,,b]=s(c[2]),$=E&&E!=="$"?e(E):null;if(!$)return null;const[P=0,N=0,Y=0]=i($[2]);let z=0;const D=b&&b!=="$"?e(b):null;if(D){const[Pt=1,tt=0]=i(D[2]);z=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},st=f?f[2]?Tt[f[2].toUpperCase()]??1:1:/IFCCONVERSIONBASEDUNIT\([^)]*\.LENGTHUNIT\.[^)]*'FOOT'/i.test(t)?.3048:1;return{east:P*st,north:N*st,elevation:Y*st,angleDeg:z}}const $i="thatopen/recipe@1",Wo="__project_data",Yo="recipes",Ml=n=>`${n}.recipe.json`,Pa={OperationBuilder:wn,OP_SCHEMA:vi,readFrag:bn,readPickedFrag:Mi,recordsOf:ka,innerJson:de,levelsOf:Ei,levelNames:Tl,stylesOf:Na,printOf:on,siteLocationOf:Fa,whatItMadeBefore:Ti,ELEMENT_FIELD:Ra,CARRIED_FIELD:Oa,FEET_PER_METRE:rs},La=/^[a-z0-9][a-z0-9-]{1,62}$/;async function Ba(n,t,e){const s=d=>[...d].sort((c,E)=>String(c._id).localeCompare(String(E._id)))[0],i=await n.listFolders({projectId:t,archived:!1});let r=s(i.filter(d=>d.name===Wo&&!d.parentId));if(!r){if(!e)return null;r=await n.createFolder(Wo,void 0,t)}const a=String(r._id),l=await n.listFolders({parentFolderId:a,projectId:t,archived:!1});let p=s(l.filter(d=>d.name===Yo&&String(d.parentId)===a));if(!p){if(!e)return null;p=await n.createFolder(Yo,a,t)}return String(p._id)}const $l=n=>String(n._id??n.id??""),Il=n=>String(n.tag??n.versionTag??""),Kn=n=>{var t;return Number(((t=/(\d+)/.exec(n))==null?void 0:t[1])??-1)};async function Es(n,t){const e=await Ba(n,t,!1);if(!e)return new Map;const s=await n.listFiles({folderId:e}),i=new Map;for(const r of s){const a=String(r.name??"");a.endsWith(".recipe.json")&&i.set(a.slice(0,-12),{id:$l(r)})}return i}async function Qs(n,t,e){var r;const s=await n.downloadFile(t,e?{versionTag:e}:void 0),i=JSON.parse(await s.text());if((i==null?void 0:i.schema)!==$i||!((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 Ts(n,t){return(await n.listVersions(t)).map(s=>({tag:Il(s),createdAt:String(s.createdAt??"")})).filter(s=>s.tag).sort((s,i)=>Kn(s.tag)-Kn(i.tag))}var Ls;class ja{constructor(t,e){Lt(this,Ls,new Map);this.client=t,this.builtinNames=e}async list(t){const e=await Es(this.client,t);return(await Promise.all([...e.entries()].map(async([,{id:i}])=>{var r;try{const a=await Ts(this.client,i),l=(r=a[a.length-1])==null?void 0:r.tag,p=await Qs(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 s=(await Es(this.client,t)).get(e);if(!s)throw new Error(`The project has no recipe named "${e}".`);const i=await Ts(this.client,s.id);return await Promise.all(i.map(async({tag:r,createdAt:a})=>{try{const l=await Qs(this.client,s.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,s){var a;const i=(await Es(this.client,t)).get(e);if(!i)throw new Error(`The project has no recipe named "${e}".`);const r=s??((a=(await Ts(this.client,i.id)).pop())==null?void 0:a.tag);if(!r)throw new Error(`The recipe "${e}" has no saved version.`);return{...await Qs(this.client,i.id,r),version:r}}async save(t,e,s){const{manifest:i,code:r}=e;if(!La.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 Xn(i,r);const a={schema:$i,manifest:i,code:r,author:s.author,...s.note?{note:s.note}:{},savedAt:new Date().toISOString()},l=new Blob([JSON.stringify(a,null,2)],{type:"application/json"}),p=(await Es(this.client,t)).get(i.name);if(p){const c=await Ts(this.client,p.id),E=`v${Math.max(0,...c.map(b=>Kn(b.tag)))+1}`;return await this.client.createVersion(p.id,l,E),E}const d=await Ba(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,s){var p;const i=(await Es(this.client,t)).get(e);if(!i)throw new Error(`The project has no recipe named "${e}".`);const r=s??((p=(await Ts(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=R(this,Ls).get(a);if(!l){const d=await Qs(this.client,i.id,r);l=await Xn(d.manifest,d.code),R(this,Ls).set(a,l)}return{recipe:l,version:r}}}Ls=new WeakMap;async function Xn(n,t){var i;let e;try{e=await import(`data:text/javascript;base64,${Sl(t)}`)}catch(r){throw new Error(`The recipe's code does not load: ${r instanceof Error?r.message:String(r)}`)}const s=e.run??((i=e.default)==null?void 0:i.run);if(typeof s!="function")throw new Error("The recipe's code exports no `run(context)` function.");return{...n,run:r=>s({...r,kit:Pa})}}function Sl(n){const t=new TextEncoder().encode(n);let e="";for(let s=0;s<t.length;s+=32768)e+=String.fromCharCode(...t.subarray(s,s+32768));return btoa(e)}async function xl(n){const t=n instanceof Uint8Array?n:new Uint8Array(await n.arrayBuffer()),{items:e,metadata:s}=await bn(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:s??{},changes:i}}class Ii extends Error{constructor(t){super(t),this.name="UpToDate"}}var Ne,Bs,js;class Da{constructor(t){Lt(this,Ne,new Map);Lt(this,Bs,new Map);Lt(this,js,new Map);he(this,"project");this.client=t,this.project=new ja(t,()=>new Set(R(this,Ne).keys()))}provideImporter(t,e){R(this,Bs).set(t.toLowerCase(),e)}provideShapes(t,e){R(this,js).set(t.toLowerCase(),e)}shapesFor(t){return R(this,js).get(t.toLowerCase())}importerFor(t){return R(this,Bs).get(t.toLowerCase())}register(t){if(R(this,Ne).has(t.name))throw new Error(`A recipe named "${t.name}" is already registered.`);R(this,Ne).set(t.name,t)}list(t){return[...R(this,Ne).values()].filter(s=>(!(t!=null&&t.to)||s.to===t.to)&&(!(t!=null&&t.input)||s.inputs.includes(t.input)))}get(t){return R(this,Ne).get(t)}async catalog(t,e){const s=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[...s,...i.sort((r,a)=>r.manifest.name.localeCompare(a.manifest.name))]}async resolve(t,e,s){const i=R(this,Ne).get(t);return i?{recipe:i,origin:"builtin"}:{...await this.project.load(e,t,s),origin:"project"}}async choices(t,e){const{recipe:s}=await this.resolve(t,e),i=s.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 Ua(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:s}=await this.resolve(t,e.projectId,e.recipeVersion);if(s.to!==e.target.source)throw new Error(`Recipe "${t}" writes ${s.to}, but the target document belongs to ${e.target.source}.`);return await s.run({client:this.client,projectId:e.projectId,target:e.target,made:e.made??new Map,opId:e.opId??yi(),input:e.input,settings:e.settings??{},progress:e.progress??(()=>{})})}}Ne=new WeakMap,Bs=new WeakMap,js=new WeakMap;async function Ua(n,t){const e=new Map;if(t.length===0)return e;const s=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:s((d==null?void 0:d.tag)??(d==null?void 0:d.versionTag))-s((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 n.listVersions(r)))}catch{e.set(r,"v1")}})),e}const Zn=100;function _l(n){try{const t=JSON.parse(n);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 Al(n){if(!n||typeof n!="object")return;const t=n.retryAfter;return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}class vn extends Error{constructor(e,s,i,r){const a=_l(i);super(a.message??`${s||"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??Al(a.details)}}const Te="item/folder",Bt="item",Ko=12e3,je="processor",Cl="npm-registry",Ae="hidden",Cn="FILE",Rn="TOOL",On="APP",Rl=500,Xo=3e4,Ol=2e3,kl=15e3,Nl=n=>/^\/?project\/permissions\/check/.test(n),Fl=n=>/^\/?(item\/folder\/?$|item\/?$|item\/folder\/[^/]+\/items\/?$|project\/[^/]+\/data\/?$)/.test(n),Ms=new Map,Pl=.25,Ll=n=>new Promise(t=>setTimeout(t,n));function Bl(n){var i,r;const t=(r=(i=n.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 s=Date.parse(t);if(!Number.isNaN(s))return Math.max(0,(s-Date.now())/1e3)}function jl(n){return n instanceof vn?n.status===429||n.status>=500:!0}function Dl(n,t){const e=Math.min(Rl*2**t,Xo),s=e*Pl*Math.random(),i=n instanceof vn&&n.retryAfter!=null?n.retryAfter*1e3:void 0;return i!=null?Math.min(i,Xo)+s:e+s}var q,an,vt,Qn,qe,as,Ja,cs,mn,Ds,Ke,Xe,cn,Us,As,ln,hn,ti,ei,si;const _i=class _i{constructor(t,e,s){Lt(this,q);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");Lt(this,as,new Map);Lt(this,cs);Lt(this,mn,Date.now());Lt(this,Ds,!1);Lt(this,Ke,0);Lt(this,Xe,!1);Lt(this,Us);const{retries:i=0,useBearer:r=!1,localServerUrl:a}=s||{};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:""},s=new _i(e.accessToken,e.apiUrl,{...t,useBearer:!0});return s.context=e,s}setRetries(t){this.retries=t}setBuiltInGlobals(t){this.builtInGlobals=t}get socketOrigin(){return this.wsUrl.split("?")[0]}async resolveAccessToken(){return this.accessToken}async request(t,e,s){return I(this,q,vt).call(this,t,e,s)}async listFiles(t){const{folderId:e,archived:s,projectId:i,versions:r}=t||{};return e?await I(this,q,vt).call(this,"GET",`${Te}/${e}/items`,{query:{itemType:Cn,archived:s,...r&&{showVersions:!0}}}):await I(this,q,vt).call(this,"GET",`${Bt}`,{query:{itemType:Cn,archived:s,...i&&{projectId:i}}})}async listDocumentDescriptors(t){const e=R(this,as).get(t);if(e)return await e;const s=I(this,q,Ja).call(this,t);R(this,as).set(t,s);try{return await s}finally{R(this,as).delete(t)}}async exportProjectDocuments(t,e){return(e==null?void 0:e.format)==="csv"?(await(await I(this,q,vt).call(this,"GET",`${Bt}/export`,{query:{projectId:t,format:"csv"},responseType:"blob"})).text()).replace(/^/,""):await I(this,q,vt).call(this,"GET",`${Bt}/export`,{query:{projectId:t}})}async getFile(t,e){return await I(this,q,ei).call(this,t,e)}async createFile(t){return await I(this,q,hn).call(this,t,Cn)}async updateFile(t,e){return await I(this,q,ti).call(this,t,e)}async archiveFile(t){return await I(this,q,vt).call(this,"DELETE",`${Bt}/${t}`)}async recoverFile(t){return await I(this,q,vt).call(this,"PUT",`${Bt}/${t}/recover`)}async downloadFile(t,e){return await I(this,q,ln).call(this,t,e)}async getFileVersionMetadata(t,e,s){const{withDraft:i}=s||{};return await I(this,q,vt).call(this,"GET",`${Bt}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/metadata`,{query:{...i&&{withDraft:"true"}}})}async updateFileVersionMetadata(t,e,s){return await I(this,q,vt).call(this,"PUT",`${Bt}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/metadata`,{body:JSON.stringify({metadata:s}),contentType:"application/json"})}async deleteFileVersionMetadata(t,e){return await I(this,q,vt).call(this,"DELETE",`${Bt}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/metadata`)}async getFileVersionMetadataBatch(t,e){const{withDraft:s}=e||{};return await I(this,q,As).call(this,t,async i=>(await I(this,q,vt).call(this,"POST",`${Bt}/batch/version-metadata`,{body:JSON.stringify({entries:i,...s!==void 0&&{withDraft:s}}),contentType:"application/json"})).results)}async listFolders(t){const{archived:e,parentFolderId:s,projectId:i}=t||{};return await I(this,q,vt).call(this,"GET",Te,{query:{parentFolderId:s,archived:e,...i&&{projectId:i}}})}async getFolder(t){return await I(this,q,vt).call(this,"GET",`${Te}/${t}`)}async getFoldersBatch(t){return await I(this,q,As).call(this,t,async e=>(await I(this,q,vt).call(this,"POST",`${Bt}/batch/folders`,{body:JSON.stringify({folderIds:e}),contentType:"application/json"})).results)}async createFolder(t,e,s){return await I(this,q,vt).call(this,"POST",Te,{body:JSON.stringify({name:t,...e&&{parentId:e},...s&&{projectId:s}}),contentType:"application/json"})}async updateFolder(t,e){const{name:s}=e;return await I(this,q,vt).call(this,"PUT",`${Te}/${t}`,{body:JSON.stringify({name:s}),contentType:"application/json"})}async archiveFolder(t){return await I(this,q,vt).call(this,"DELETE",`${Te}/${t}`)}async recoverFolder(t){return await I(this,q,vt).call(this,"PUT",`${Te}/${t}/recover`)}async downloadFolder(t){return await I(this,q,qe).call(this,`${Te}/${t}/download`)}async listComponents(t){const{folderId:e,ShowVersions:s,projectId:i}=t||{};return e?await I(this,q,vt).call(this,"GET",`${Te}/${e}/items`,{query:{itemType:Rn,...s&&{ShowVersions:s}}}):await I(this,q,vt).call(this,"GET",`${Bt}`,{query:{itemType:Rn,...s&&{ShowVersions:s},...i&&{projectId:i}}})}async getComponent(t,e){return await I(this,q,ei).call(this,t,e)}async createComponent(t){const{componentProps:e}=t;return await I(this,q,hn).call(this,t,Rn,e)}async updateComponent(t,e){const{componentProps:s}=e;return await I(this,q,ti).call(this,t,e,s)}async downloadComponent(t,e){return await I(this,q,ln).call(this,t,e)}async downloadComponentBundle(t,e){const{versionTag:s,withDraft:i}=e||{};return await I(this,q,qe).call(this,`${Bt}/${t}/download/bundle`,{query:{...s&&{versionTag:s},...i&&{withDraft:i}}})}async archiveComponent(t){return await I(this,q,vt).call(this,"DELETE",`${Bt}/${t}`)}async recoverComponent(t){return await I(this,q,vt).call(this,"PUT",`${Bt}/${t}/recover`)}async getBuiltInComponent(t){return await(await I(this,q,qe).call(this,`built-in/${t}/bundle`)).text()}async initBuiltInComponent(t,e,s){const i=await this.getBuiltInComponent(t.uuid),r=s??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(s=>this.initBuiltInComponent(s,t)))}async setup(t,...e){const s=t.OBC,i=t.BUI;if(!(s!=null&&s.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 s.Components;if(i.Manager.init(),this.setBuiltInGlobals(t),await this.initBuiltInComponents(r,...e),r.init(),globalThis.__thatOpenShellSaysLoaded&&!R(this,cs)&&Vt(this,cs,this.holdAppLoaded()),Vt(this,Ds,!0),I(this,q,cn).call(this),!R(this,Xe)){const a=typeof performance<"u"?performance.now():Date.now()-R(this,mn);setTimeout(()=>{Vt(this,Ke,0),I(this,q,cn).call(this)},Math.max(0,Ko-a))}return{components:r}}holdAppLoaded(t=Ko){if(R(this,Xe))return()=>{};In(this,Ke)._++;let e=!1;const s=()=>{e||(e=!0,clearTimeout(i),In(this,Ke)._--,I(this,q,cn).call(this))},i=setTimeout(s,t);return s}appReady(){var t;(t=R(this,cs))==null||t.call(this)}throwError(t,e){var s,i;(i=(s=this.context.appEventOrchestrator)==null?void 0:s.appError)==null||i.call(s,t,e)}async listApps(t){const{folderId:e,ShowVersions:s,projectId:i}=t||{};return e?await I(this,q,vt).call(this,"GET",`${Te}/${e}/items`,{query:{itemType:On,...s&&{ShowVersions:s}}}):await I(this,q,vt).call(this,"GET",`${Bt}`,{query:{itemType:On,...s&&{ShowVersions:s},...i&&{projectId:i}}})}async createApp(t){const{appProps:e}=t;return await I(this,q,hn).call(this,t,On,e)}async downloadApp(t,e){return await I(this,q,ln).call(this,t,e)}async downloadAppBundle(t,e){const{versionTag:s,withDraft:i}=e||{};return await I(this,q,qe).call(this,`${Bt}/${t}/download/bundle`,{query:{...s&&{versionTag:s},...i&&{withDraft:i}}})}async archiveApp(t){return await I(this,q,vt).call(this,"DELETE",`${Bt}/${t}`)}async getNpmCredentials(){return await I(this,q,vt).call(this,"GET",`${Cl}/credentials`)}async executeComponent(t,e,s){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,q,vt).call(this,"POST",`${je}/${t}/execute`,{body:JSON.stringify(e),query:{...s&&{versionTag:s}},contentType:"application/json"})}async abortExecution(t){if(this.localServerUrl){const e=`${this.localServerUrl}/api/${je}/progress/${t}/abort`,s=await fetch(e,{method:"POST"});if(!s.ok){const i=await s.text().catch(()=>"");throw new Error(`Local server request failed: ${s.status} - ${i}`)}return await s.json()}return await I(this,q,vt).call(this,"POST",`${je}/progress/${t}/abort`)}async listExecutions(t,e){if(this.localServerUrl){const s=e?`?projectId=${encodeURIComponent(e)}`:"",i=`${this.localServerUrl}/api/${je}/${t}/progress${s}`,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,q,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}`,s=await fetch(e);if(!s.ok){const i=await s.text().catch(()=>"");throw new Error(`Local server request failed: ${s.status} - ${i}`)}return await s.json()}return await I(this,q,vt).call(this,"GET",`${je}/progress/${t}`)}async onExecutionProgress(t,e){const s=this.localServerUrl??this.wsUrl,i=await Rs(s,{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 bi(this,t)}history(t){return new mi(this,t)}get recipes(){return R(this,Us)??Vt(this,Us,new Da(this)),R(this,Us)}async createHiddenFile(t,e,s){const i=new FormData;return i.append("file",t),i.append("parentItemId",e),s!=null&&i.append("tag",s),await I(this,q,vt).call(this,"POST",`${Bt}/${Ae}`,{body:i})}async createHiddenFilesBatch(t,e,s){const i=new FormData;for(const r of t)i.append("files",r);return i.append("parentItemId",e),s!=null&&i.append("tag",s),await I(this,q,vt).call(this,"POST",`${Bt}/${Ae}/batch`,{body:i})}async deleteHiddenFile(t){return await I(this,q,vt).call(this,"DELETE",`${Bt}/${Ae}/${t}`)}async getHiddenFile(t){return await I(this,q,vt).call(this,"GET",`${Bt}/${Ae}/${t}`)}async downloadHiddenFile(t){return await I(this,q,qe).call(this,`${Bt}/${Ae}/${t}/download`)}async getHiddenFileSignedUrl(t,e){return await I(this,q,vt).call(this,"GET",`${Bt}/${Ae}/${t}/signed-url`,{...e!=null&&{query:{expiresIn:e}}})}async getHiddenFileSignedUrlsBatch(t,e){return await I(this,q,As).call(this,t,async s=>(await I(this,q,vt).call(this,"POST",`${Bt}/${Ae}/signed-url/batch`,{body:JSON.stringify({hiddenFileIds:s,...e!=null&&{expiresIn:e}}),contentType:"application/json"})).results)}async getHiddenFilesByParent(t,e){return await I(this,q,vt).call(this,"GET",`${Bt}/${t}/${Ae}`,{...e!=null&&{query:{tag:e}}})}async deleteHiddenFilesByParent(t){return await I(this,q,vt).call(this,"DELETE",`${Bt}/${t}/${Ae}`)}async uploadItemIcon(t,e){const s=new FormData;return s.append("icon",e),await I(this,q,vt).call(this,"PUT",`${Bt}/${t}/icon`,{body:s})}async getItemIcon(t){return await I(this,q,qe).call(this,`${Bt}/${t}/icon`)}async removeItemIcon(t){return await I(this,q,vt).call(this,"DELETE",`${Bt}/${t}/icon`)}async updateItem(t,e){return await I(this,q,vt).call(this,"PUT",`${Bt}/${t}`,{body:JSON.stringify(e),contentType:"application/json"})}async createVersion(t,e,s,i,r){const a=new FormData;a.append("file",e),a.append("versionTag",s),i&&a.append("extraProps",JSON.stringify(i));const l=await I(this,q,vt).call(this,"POST",`${Bt}/${t}/version`,{body:a});return r&&await this.updateFileVersionMetadata(t,(l==null?void 0:l.tag)??s,r),l}async nextVersionTag(t){if(!t)return"v1";let e=[];try{e=await this.listVersions(t)}catch{return`v-${Date.now()}`}let s=0;for(const i of e){const r=/^v(\d{1,6})$/.exec(String(i.tag??i.versionTag??""));r&&(s=Math.max(s,Number(r[1])))}return`v${Math.max(s,e.length)+1}`}async listVersions(t,e={}){return await I(this,q,vt).call(this,"GET",`${Bt}/${encodeURIComponent(t)}/versions`,{query:e})}async listVersionsBatch(t,e={}){const{archived:s}=e;return await I(this,q,As).call(this,t,async i=>(await I(this,q,vt).call(this,"POST",`${Bt}/batch/versions`,{body:JSON.stringify({itemIds:i,...s!==void 0&&{archived:s}}),contentType:"application/json"})).results)}async archiveVersion(t,e){return await I(this,q,vt).call(this,"PUT",`${Bt}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/archive`)}async recoverVersion(t,e){return await I(this,q,vt).call(this,"PUT",`${Bt}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/recover`)}async deleteVersion(t,e){return await I(this,q,vt).call(this,"DELETE",`${Bt}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}`)}};q=new WeakSet,an=function(t){return`${this.apiUrl}/${t}`},vt=async function(t,e,s){if(t==="GET"&&(s==null?void 0:s.responseType)!=="blob"&&!(s!=null&&s.retryAttempt)){const i=`${I(this,q,an).call(this,e)}?${new URLSearchParams(I(this,q,si).call(this,s==null?void 0:s.query)).toString()}`,r=Date.now(),a=Ms.get(i);if(a&&(a.pending||r-a.at<(Fl(e)?kl:Ol)))return a.answer.then(p=>p===void 0?p:structuredClone(p));const l={at:r,pending:!0,answer:I(this,q,Qn).call(this,t,e,s)};return Ms.set(i,l),l.answer.then(()=>{l.pending=!1,l.at=Date.now()},()=>{Ms.get(i)===l&&Ms.delete(i)}),l.answer.then(p=>p===void 0?p:structuredClone(p))}return t!=="GET"&&!Nl(e)&&Ms.clear(),I(this,q,Qn).call(this,t,e,s)},Qn=async function(t,e,s){const{body:i,query:r,contentType:a,retries:l,responseType:p,retryAttempt:d}=s||{},c=I(this,q,an).call(this,e),E=I(this,q,si).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 N=await P.text().then(Y=>Y).catch(()=>"");throw new vn(P.status,P.statusText,N,Bl(P))}return p==="blob"?await P.blob():P.json().then(N=>N).catch(()=>{})}catch(P){const N=l??this.retries;if(N>0&&jl(P)){const Y=d??0;return await Ll(Dl(P,Y)),await I(this,q,vt).call(this,t,e,{...s,retries:N-1,retryAttempt:Y+1})}throw P}},qe=async function(t,e){const{query:s}=e||{},i=I(this,q,an).call(this,t),r=await this.resolveAccessToken(),a={...s,...this.useBearer?{}:{accessToken:r}};return await fetch(i+"?"+new URLSearchParams(a).toString(),{method:"GET",...this.useBearer&&{headers:{Authorization:`Bearer ${r}`}}})},as=new WeakMap,Ja=async function(t){return await I(this,q,vt).call(this,"GET",`${Bt}/documents`,{query:{projectId:t}})},cs=new WeakMap,mn=new WeakMap,Ds=new WeakMap,Ke=new WeakMap,Xe=new WeakMap,cn=function(){var t,e;R(this,Xe)||!R(this,Ds)||R(this,Ke)>0||(Vt(this,Xe,!0),(e=(t=this.context.appEventOrchestrator)==null?void 0:t.appLoaded)==null||e.call(t))},Us=new WeakMap,As=async function(t,e){if(!t.length)return[];const s=[];for(let r=0;r<t.length;r+=Zn)s.push(t.slice(r,r+Zn));return(await Promise.all(s.map(e))).flat()},ln=async function(t,e){const{versionTag:s,withDraft:i}=e||{},r=await I(this,q,qe).call(this,`${Bt}/${t}/download`,{query:{...s&&{versionTag:s},...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},hn=async function(t,e,s){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),s&&c.append("extraProps",JSON.stringify(s)),d&&c.append("metadata",JSON.stringify(d)),await I(this,q,vt).call(this,"POST",Bt,{body:c})},ti=async function(t,e,s){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),s&&E.append("extraProps",JSON.stringify(s)),c=await I(this,q,vt).call(this,"POST",`${Bt}/${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,q,vt).call(this,"PUT",`${Bt}/${t}`,{body:b,contentType:"application/json"})}return{item:d,version:c}},ei=async function(t,e){const{showVersions:s=!1}=e||{};return await I(this,q,vt).call(this,"GET",`${Bt}/${t}`,{query:{showVersions:s}})},si=function(t){return t&&Object.entries(t).filter(([,e])=>e!==void 0).reduce((e,[s,i])=>(e[s]=i,e),{})};let pn=_i;function qa(){if(typeof window>"u"||window.parent===window)throw new Error("client.channel only works inside a That Open app, which runs in an iframe of the platform.");return{post:n=>window.parent.postMessage(n,"*"),listen:n=>{const t=e=>{e.source===window.parent&&n(e.data)};return window.addEventListener("message",t),()=>window.removeEventListener("message",t)}}}const ni="channel:",Ul=1e4;function fn(n){try{n()}catch(t){console.error("[channel] a listener threw:",t)}}var Fe,ge,ye,ls,hs,fs,ue,ii,ri,is;class Si{constructor(t,e){Lt(this,ue);Lt(this,Fe,!1);Lt(this,ge,[]);Lt(this,ye,[]);Lt(this,ls,new Set);Lt(this,hs,new Set);Lt(this,fs,new Set);this.transport=t,this.controls=e}get joined(){return R(this,Fe)}get peers(){return R(this,ge)}join(){return R(this,Fe)?Promise.resolve():I(this,ue,ii).call(this,"joined",this.controls.join)}leave(){return!R(this,Fe)&&!R(this,ye).some(t=>t.want==="joined")?Promise.resolve():I(this,ue,ii).call(this,"left",this.controls.leave)}onChange(t){return R(this,ls).add(t),()=>void R(this,ls).delete(t)}onPeerJoined(t){return R(this,hs).add(t),()=>void R(this,hs).delete(t)}onPeerLeft(t){return R(this,fs).add(t),()=>void R(this,fs).delete(t)}applyJoined(){Vt(this,Fe,!0),I(this,ue,ri).call(this,"joined"),I(this,ue,is).call(this)}applyLeft(){Vt(this,Fe,!1),Vt(this,ge,[]),I(this,ue,ri).call(this,"left"),I(this,ue,is).call(this)}applyPeers(t){Vt(this,ge,t),I(this,ue,is).call(this)}applyPeerJoined(t){!R(this,Fe)||R(this,ge).some(e=>e.from===t.from)||(Vt(this,ge,[...R(this,ge),t]),R(this,hs).forEach(e=>fn(()=>e(t))),I(this,ue,is).call(this))}applyPeerLeft(t){const e=R(this,ge).find(s=>s.from===t);e&&(Vt(this,ge,R(this,ge).filter(s=>s.from!==t)),R(this,fs).forEach(s=>fn(()=>s(e))),I(this,ue,is).call(this))}failPending(t){const e=R(this,ye);return Vt(this,ye,[]),e.forEach(s=>{clearTimeout(s.timer),s.reject(t)}),e.length>0}post(t){this.transport.post(t)}}Fe=new WeakMap,ge=new WeakMap,ye=new WeakMap,ls=new WeakMap,hs=new WeakMap,fs=new WeakMap,ue=new WeakSet,ii=function(t,e){return new Promise((s,i)=>{const r={want:t,resolve:s,reject:i,timer:setTimeout(()=>{Vt(this,ye,R(this,ye).filter(a=>a!==r)),i(new Error(`The platform did not confirm ${t==="joined"?"joining":"leaving"} in time.`))},Ul)};R(this,ye).push(r),this.transport.post({type:"APP_CHANNEL_CONTROL",...e})})},ri=function(t){const e=R(this,ye).filter(s=>s.want===t);Vt(this,ye,R(this,ye).filter(s=>s.want!==t)),e.forEach(s=>{clearTimeout(s.timer),s.resolve()})},is=function(){R(this,ls).forEach(t=>fn(t))};var ds;class Ha extends Si{constructor(e){super(e,{join:{action:"joinCollab"},leave:{action:"leaveCollab"}});Lt(this,ds,new Map)}on(e,s){const i=R(this,ds).get(e)??new Set;return i.add(s),R(this,ds).set(e,i),()=>void i.delete(s)}send(e,s){if(e.startsWith(ni))throw new Error(`Message types starting with '${ni}' are reserved.`);this.joined&&this.post({type:"APP_CHANNEL_PUBLISH",message:{type:e,payload:s}})}accepts(e){return e===void 0||e==="collab"}async handle(e){const s=R(this,ds).get(e.type);if(!(s!=null&&s.size))return{handled:!1};const i=Va(e);return s.forEach(r=>fn(()=>r(e.payload,i))),{handled:!0}}}ds=new WeakMap;var He;class Ga extends Si{constructor(e,s){super(e,{join:{action:"joinExternal",kind:s},leave:{action:"leaveExternal",kind:s}});Lt(this,He,new Map);this.kind=s}on(e,s){if(R(this,He).has(e))throw new Error(`"${e}" already has a handler in this room. Remove it first.`);return R(this,He).set(e,s),()=>void R(this,He).delete(e)}accepts(e,s){return e!==void 0&&e!=="external"?!1:this.kind===void 0||e===void 0||this.kind===s}get hasHandlers(){return R(this,He).size>0}async handle(e){const s=R(this,He).get(e.type);if(!s)return{handled:!1};try{return{handled:!0,value:await s(e.payload,Va(e))}}catch(i){return{handled:!0,error:i instanceof Error?i.message:String(i)}}}}He=new WeakMap;function Va(n){return{from:n.from,at:n.at,requestId:n.requestId,kind:n.kind}}function Jl(n){const t=n;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 Ze,Js,Pe,Ge,Ve,ce,oi,dn,Wa,Ya,Ka,ai;class za{constructor(t){Lt(this,ce);Lt(this,Ze);Lt(this,Js);Lt(this,Pe);Lt(this,Ge,new Map);Lt(this,Ve,new Set);Vt(this,Ze,t),Vt(this,Js,t.listen(e=>void I(this,ce,Wa).call(this,e)))}collab(){return R(this,Pe)??Vt(this,Pe,new Ha(R(this,Ze))),R(this,Pe)}external(t){const e=t??"";let s=R(this,Ge).get(e);return s||(s=new Ga(R(this,Ze),t),R(this,Ge).set(e,s)),s}dispose(){R(this,Js).call(this)}}Ze=new WeakMap,Js=new WeakMap,Pe=new WeakMap,Ge=new WeakMap,Ve=new WeakMap,ce=new WeakSet,oi=function(){return[...R(this,Pe)?[R(this,Pe)]:[],...R(this,Ge).values()]},dn=function(t,e){if(t==="collab")return R(this,Pe);if(t==="external")return R(this,Ge).get(typeof e=="string"?e:"")},Wa=async function(t){const e=Jl(t);if(e){if(e.type.startsWith(ni)){I(this,ce,Ya).call(this,e);return}await I(this,ce,Ka).call(this,e)}},Ya=function(t){var s,i,r;const e=t.payload??{};switch(t.type){case"channel:joined":(s=I(this,ce,dn).call(this,e.scope,e.kind))==null||s.applyJoined();break;case"channel:left":(i=I(this,ce,dn).call(this,e.scope,e.kind))==null||i.applyLeft();break;case"channel:peers":(r=I(this,ce,dn).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"?[R(this,Pe)]:[...R(this,Ge).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,oi).call(this).map(p=>p.failPending(a)).some(Boolean)||console.error("[channel] error:",t.payload);break}}},Ka=async function(t){const e=I(this,ce,oi).call(this).filter(r=>r.accepts(t.scope,t.kind));let s=!1;for(const r of e){const a=await r.handle(t);a.handled&&(s=!0,t.requestId&&I(this,ce,ai).call(this,t.requestId,a))}t.requestId&&t.scope==="external"&&e.length>0&&!s&&I(this,ce,ai).call(this,t.requestId,{handled:!0,error:`No handler for "${t.type}".`})},ai=function(t,e){R(this,Ve).has(t)||(R(this,Ve).add(t),R(this,Ve).size>500&&R(this,Ve).delete(R(this,Ve).values().next().value),R(this,Ze).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",es="notifications",$s="tokens",ql=6e4;var us,qs,ze;const Ai=class Ai extends pn{constructor(e,s,i){super(typeof e=="string"?e:"",s,{...i,useBearer:!0});Lt(this,us);Lt(this,qs);Lt(this,ze,new Map);typeof e=="function"&&Vt(this,us,e)}async resolveAccessToken(){return R(this,us)?await R(this,us).call(this):super.resolveAccessToken()}static fromPlatformContext(e){const s=(typeof window<"u"?window.__THATOPEN_CONTEXT__:null)||{appId:"",projectId:"",accessToken:"",apiUrl:""},i=new Ai(s.accessToken,s.apiUrl,e);return i.context=s,i}get channel(){return R(this,qs)??Vt(this,qs,new za(qa())),R(this,qs)}async listProjects(){return await this.request("GET",ae)}async getProject(e){return await this.request("GET",`${ae}/${e}`)}async getProjectData(e){const s=R(this,ze).get(e);if(s&&Date.now()-s.at<ql)return await s.data;const i=this.request("GET",`${ae}/${e}/data`);return R(this,ze).set(e,{at:Date.now(),data:i}),i.catch(()=>{var r;((r=R(this,ze).get(e))==null?void 0:r.data)===i&&R(this,ze).delete(e)}),await i}async request(e,s,i){return e.toUpperCase()!=="GET"&&R(this,ze).clear(),await super.request(e,s,i)}async listMembers(e){return await this.request("GET",`${ae}/${e}/users`)}async addMember(e,s,i){return await this.request("POST",`${ae}/${e}/user`,{body:JSON.stringify({accountId:s,...i&&{projectRoleId:i}}),contentType:"application/json"})}async setMemberRole(e,s,i){return await this.request("PUT",`${ae}/${e}/user/${s}`,{body:JSON.stringify({projectRoleId:i}),contentType:"application/json"})}async removeMember(e,s){return await this.request("DELETE",`${ae}/${e}/user/${s}`)}async inviteMember(e,s,i){return await this.request("POST",`${ae}/${e}/invite`,{body:JSON.stringify({email:s,...i&&{projectRoleId:i}}),contentType:"application/json"})}async listInvitations(e){return await this.request("GET",`${ae}/${e}/invites`)}async cancelInvitation(e,s){return await this.request("DELETE",`${ae}/${e}/invite/${s}`)}async listRoles(e){return await this.request("GET",`${ae}/${e}/roles`)}async createRole(e,s){return await this.request("POST",`${ae}/${e}/role`,{body:JSON.stringify(s),contentType:"application/json"})}async updateRole(e,s){return await this.request("PUT",`${ae}/role/${e}`,{body:JSON.stringify(s),contentType:"application/json"})}async deleteRole(e){return await this.request("DELETE",`${ae}/role/${e}`)}async getPermissionMatrix(e){const[s,i]=await Promise.all([this.listRoles(e),this.listMembers(e)]);return s.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",$s)}async getTokenSecret(e){return await(await this.request("GET",`${$s}/${e}/token`,{responseType:"blob"})).text()}async createToken(e){return await this.request("POST",$s,{body:JSON.stringify({urlRestrictions:[],...e}),contentType:"application/json"})}async updateToken(e,s){return await this.request("PUT",`${$s}/${e}`,{body:JSON.stringify(s),contentType:"application/json"})}async revokeToken(e){return await this.request("DELETE",`${$s}/${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",es,{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",`${es}/unread-count`)).count}async markNotificationsRead(e){return await this.request("POST",`${es}/mark-read`,{body:JSON.stringify({ids:e}),contentType:"application/json"})}async markAllNotificationsRead(){return await this.request("POST",`${es}/mark-all-read`)}async getNotificationSubscriptions(){return await this.request("GET",`${es}/subscriptions`)}async unsubscribeFromAutomation(e){return await this.request("DELETE",`${es}/subscriptions/${e}`)}async subscribeToAutomation(e,s,i){return await this.request("POST",`${ae}/${e}/events/hooks/${s}/subscription`,{body:JSON.stringify(i??{}),contentType:"application/json"})}async updateAutomationSubscription(e,s,i){return await this.request("PATCH",`${ae}/${e}/events/hooks/${s}/subscription`,{body:JSON.stringify(i),contentType:"application/json"})}async onNotification(e){const s=await this.resolveAccessToken(),i=Rs(`${this.socketOrigin}/notifications`,{auth:{accessToken:s},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()}};us=new WeakMap,qs=new WeakMap,ze=new WeakMap;let ci=Ai;const Ce=1/.3048,Hl={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"},Gl="OST_GenericModel",Vl=new Set(["IFCSPACE","IFCOPENINGELEMENT","IFCSITE","IFCANNOTATION","IFCGRID","IFCVIRTUALELEMENT","IFCBUILDING","IFCBUILDINGSTOREY"]),Oe=(n,t)=>Math.round(n/t)*t,zl=n=>({x:[n[0],n[1],n[2]],y:[n[4],n[5],n[6]],z:[n[8],n[9],n[10]],t:[n[12],n[13],n[14]]}),Os=(n,t)=>n[0]*t[0]+n[1]*t[1]+n[2]*t[2],kn=n=>Math.sqrt(Os(n,n)),os=(n,t)=>[n[1]*t[2]-n[2]*t[1],n[2]*t[0]-n[0]*t[2],n[0]*t[1]-n[1]*t[0]];function Wl(n,t,e,s){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 n.elements.values()){if(i.has(b.gid)||Vl.has(b.ifcClass.toUpperCase())||b.parent&&i.has(b.parent)&&!/^IFC(DOOR|WINDOW)$/i.test(b.ifcClass)&&!(s!=null&&s.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":Hl[b.ifcClass.toUpperCase()]??Gl,N=zl(b.pieces[0].matrix),Y=kn(N.x),z=kn(N.y),D=kn(N.z),f=N.z.map(U=>U/(D||1)),Tt=Math.abs(f[2]-1)<1e-6&&Os(os(N.x,N.y),N.z)>0&&Math.abs(Y-z)<1e-6&&Math.abs(Y-D)<1e-6,st=Os(os(N.x,N.y),N.z)>0&&Math.abs(Y-z)<1e-6&&Math.abs(Y-D)<1e-6,wt=[N.x,N.y,N.z].map(U=>U.map(Z=>Z/(Y||1))),Pt=st&&!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(N.x[1],N.x[0]):Pt?Math.atan2(Pt[1],Pt[0]):0,ct=Math.cos(-tt),ht=Math.sin(-tt),kt=[N.t[0],N.t[1],N.t[2]],te=/COLUMN/i.test(P),Yt=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=[],nt=[P];for(const U of b.pieces){const Z=n.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]],Qe=Yt(re);ut.push(Oe(Qe[0]*Ce,1e-5),Oe(Qe[1]*Ce,1e-5),Oe(Qe[2]*Ce,1e-5))}const X=Os(os([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=Yt([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]];nt.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?Xl(at[0]):null;if(pt){const U=Kl(pt),Z=U.key,B=`prism|${P}|${U.axis}|${Z}`;let ut=a.get(B);if(!ut){const le=Zo(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(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 jt=`${P}|${at.map(U=>`${U.v.map(Z=>Math.round(Z*304.8/2)).join(",")}/${U.t.join(",")}`).join("|")}`,Ht=nt.join("|");let Dt=a.get(Ht)??a.get(jt);if(Dt&&(a.set(Ht,Dt),a.set(jt,Dt)),!Dt){const U=Zo(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})`;Dt={family:B,type:B,first:!0,key:Qo(jt)},a.set(jt,Dt),a.set(Ht,Dt)}const Xt={ShapeCategory:P,Family:Dt.family,Type:Dt.type,ShapeKey:Dt.key,...te?{ColumnFree:"1"}:{}};Dt.first&&(Xt.Shape=JSON.stringify({pieces:at}),Dt.first=!1);const Kt=b.host?r.get(b.host):void 0,Wt=b.opening?n.elements.get(b.opening):void 0;if(Kt&&Wt){const U=[1/0,1/0,1/0],Z=[-1/0,-1/0,-1/0];for(const B of Wt.pieces){const ut=n.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=Yt([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=li(n,Wt.gid).flatMap(dt=>dt.pts).map(dt=>Yt(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&&(Xt.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])&&(Xt.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=li(n,Wt.gid).flatMap(X=>X.pts),ut=Qt(n,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&&(Xt.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:Xt,at:[kt[0],kt[1],kt[2]],rotationDeg:tt*180/Math.PI,...Kt?{host:Kt}:{}})}return p}function Zo(n){return(n.replace(/[\\:{}[\]|;<>?`~]/g,"-").replace(/\s+/g," ").trim()||"Shape").slice(0,120)}function Qo(n){let t=2166136261;for(let e=0;e<n.length;e++)t^=n.charCodeAt(e),t=Math.imul(t,16777619);return(t>>>0).toString(36)}function Yl(n,t,e){var r,a;const s=new Map;for(const l of t){const[,p,d]=l.split(":");p&&/^run/.test(d??"")&&!s.has(p)&&s.set(p,l)}const i=[];for(const l of n.elements.values()){if(l.ifcClass.toUpperCase()!=="IFCOPENINGELEMENT"||!l.host)continue;const p=s.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 li(n,l.gid)){const E=c.pts;if(E.length<4)continue;const b=Ql(Qt(n,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]),N=D=>Math.max(...D)-Math.min(...D),Y=N($)*N(P)*N(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)}: ${N($).toFixed(3)} along ${N(P).toFixed(3)} across ${N(E.map(D=>D[2])).toFixed(3)} up, axis ${JSON.stringify(b.u.map(D=>+D.toFixed(3)))})`);continue}const z=Qt(n,l.host).map(D=>-(D[0]-b.a[0])*b.u[1]+(D[1]-b.a[1])*b.u[0]);if(z.length&&(Math.min(...P)>Math.min(...z)+.005||Math.max(...P)<Math.max(...z)-.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(...z).toFixed(3)}..${Math.max(...z).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)}: ${N($).toFixed(3)} along ${N(P).toFixed(3)} across ${N(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 Kl(n){const t=n.loops.flat(),e=[t.reduce((b,$)=>b+$[0],0)/t.length,t.reduce((b,$)=>b+$[1],0)/t.length],s=n.loops.map(b=>{const $=b.map(([f,Tt])=>[f-e[0],Tt-e[1]]),P=$.map(([f,Tt])=>Math.hypot(f,Tt)),N=P.reduce((f,Tt)=>f+Tt,0)/P.length;if($.length<8||N<=0||P.some(f=>Math.abs(f-N)>.02*N))return $;const Y=2*Math.PI/$.length;for(let f=0;f<$.length;f++){const Tt=Math.atan2($[f][1],$[f][0]),st=Math.atan2($[(f+1)%$.length][1],$[(f+1)%$.length][0]),wt=Math.abs(Math.atan2(Math.sin(st-Tt),Math.cos(st-Tt)));if(Math.abs(wt-Y)>.1*Y)return $}const D=$.reduce((f,Tt,st)=>{const wt=$[(st+1)%$.length];return f+Tt[0]*wt[1]-wt[0]*Tt[1]},0)>=0?1:-1;return $.map((f,Tt)=>[N*Math.cos(D*2*Math.PI*Tt/$.length),N*Math.sin(D*2*Math.PI*Tt/$.length)])}),i=b=>b.map(P=>{const N=P.map(([z,D])=>`${Math.round(z*304.8)},${Math.round(D*304.8)}`);let Y=0;for(let z=1;z<N.length;z++)N[z]<N[Y]&&(Y=z);return[...N.slice(Y),...N.slice(0,Y)].join(";")}).sort().join("|"),r=(b,$)=>{const P=Math.cos(-$),N=Math.sin(-$);return b.map(Y=>Y.map(([z,D])=>[P*z-N*D,N*z+P*D]))},a=[];let l=n.axis,p=0,d=s;if(l===1&&(l=0,p=Math.PI/2,d=s.map(b=>b.map(([$,P])=>[-P,$]))),l===2){let b=0,$=0,P=0;const N=s.flat();for(const[st,wt]of N)b+=st*st,$+=wt*wt,P+=st*wt;const Y=new Set,z=.5*Math.atan2(2*P,b-$);for(let st=0;st<4;st++)Y.add(z+st*Math.PI/2);const D=N.map(([st,wt])=>Math.hypot(st,wt)),f=Math.max(...D),Tt=N.filter((st,wt)=>D[wt]>f-.003);if(Math.abs(b-$)<.001*(b+$)||Tt.length>4)for(const[st,wt]of Tt.slice(0,64))Y.add(Math.atan2(wt,st));for(const st of Y)a.push({loops:r(s,st),turn:st,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 Xl(n){const e=n.v.length/3;if(e<6)return null;const s=[0,1,2].map(i=>{let r=1/0,a=-1/0;for(let l=0;l<e;l++){const p=n.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)=>s[a]-s[r])){let r=1/0,a=-1/0;for(let tt=0;tt<e;tt++){const ct=n.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=n.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=[n.v[tt*3+p],n.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<n.t.length;tt+=3){const ct=[n.t[tt],n.t[tt+1],n.t[tt+2]];if(!ct.every(kt=>Math.abs(n.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]],Yt=te[0]*te[0]+te[1]*te[1],at=[];if(E.length<=3e3)for(let nt=0;nt<E.length;nt++){if(nt===tt||nt===ct)continue;const pt=((E[nt][0]-ht[0])*te[0]+(E[nt][1]-ht[1])*te[1])/Yt;if(pt<=1e-6||pt>=1-1e-6)continue;Math.abs((E[nt][0]-ht[0])*te[1]-(E[nt][1]-ht[1])*te[0])/Math.sqrt(Yt)<3e-4&&at.push({t:pt,id:nt})}return[tt,...at.sort((nt,pt)=>nt.t-pt.t).map(nt=>nt.id),ct]},N=[];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++)N.push([ht[kt],ht[kt+1]])}const Y=new Map;for(const[tt,ct]of N){const ht=tt<ct?`${tt},${ct}`:`${ct},${tt}`;Y.set(ht,(Y.get(ht)??0)+1)}const z=new Map;for(const[tt,ct]of N)Y.get(tt<ct?`${tt},${ct}`:`${ct},${tt}`)===1&&z.set(tt,[...z.get(tt)??[],ct]);if([...z.values()].some(tt=>tt.length!==1))continue;const D=[],f=new Set(z.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=z.get(ht)[0];while(ht!==tt&&kt++<1e5&&z.has(ht));if(ht!==tt||ct.length<3){D.length=0;break}const te=ct.filter((Yt,at)=>{const nt=ct[(at-1+ct.length)%ct.length],pt=ct[(at+1)%ct.length];return Math.abs((Yt[0]-nt[0])*(pt[1]-nt[1])-(Yt[1]-nt[1])*(pt[0]-nt[0]))>1e-7});D.push(te.map(([Yt,at])=>[Oe(Yt,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(n.v[ht*3+i]-tt)<=.001&&ct.add(`${Math.round(n.v[ht*3+p]*304.8)},${Math.round(n.v[ht*3+d]*304.8)}`);return ct},st=(tt,ct)=>{const[ht,kt]=ct.split(",").map(Number);for(let te=-1;te<=1;te++)for(let Yt=-1;Yt<=1;Yt++)if(tt.has(`${ht+te},${kt+Yt}`))return!0;return!1},wt=Tt(r),Pt=Tt(a);if(!(Pt.size<3||[...wt].some(tt=>!st(Pt,tt))||[...Pt].some(tt=>!st(wt,tt))))return{axis:i,from:r,length:a-r,loops:D}}return null}function Zl(n,t){const e=[];for(const s of n.elements.values()){if(s.ifcClass.toUpperCase()!=="IFCSPACE")continue;let i=1/0,r=-1/0;const a=[];for(const d of s.pieces){const c=n.geometries.get(d.geometry);if(!c)continue;const E=d.matrix,b=$=>{const P=c.verts[$*3],N=c.verts[$*3+1],Y=c.verts[$*3+2];return[E[0]*P+E[4]*N+E[8]*Y+E[12],E[1]*P+E[5]*N+E[9]*Y+E[13],E[2]*P+E[6]*N+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 N of P)i=Math.min(i,N[2]),r=Math.max(r,N[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}:${s.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:s.name??"",name:s.longName??s.name??""})}return e}function Ql(n){if(n.length<2)return;let t=n[0],e=n[0],s=0;for(const d of n){const c=Math.hypot(d[0]-n[0][0],d[1]-n[0][1]);c>s&&(s=c,e=d)}s=0;for(const d of n){const c=Math.hypot(d[0]-e[0],d[1]-e[1]);c>s&&(s=c,t=d)}if(s<.1)return;const i=[...new Map(n.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]),N=l.map(f=>-f[0]*$[1]+f[1]*$[0]),Y=Math.max(...P)-Math.min(...P),z=Math.max(...N)-Math.min(...N),D=Y*z;(!p||D<p.area-1e-9)&&(p={area:D,u:Y>=z?$:[-$[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])/s,(e[1]-t[1])/s]}}function li(n,t){const e=n.elements.get(t);if(!e)return[];const s=[],i=[],r=new Map;for(const c of e.pieces){const E=n.geometries.get(c.geometry);if(!E)continue;const b=c.matrix,$=[];for(let P=0;P<E.verts.length;P+=3){const N=E.verts[P],Y=E.verts[P+1],z=E.verts[P+2],D=[b[0]*N+b[4]*Y+b[8]*z+b[12],b[1]*N+b[5]*Y+b[9]*z+b[13],b[2]*N+b[6]*Y+b[10]*z+b[14]],f=D.map(st=>Math.round(st*1e4)).join(",");let Tt=r.get(f);Tt===void 0&&(Tt=s.length,r.set(f,Tt),s.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=s.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,N]=[s[i[c]],s[i[c+1]],s[i[c+2]]];b.volume+=Os($,os(P,N))/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=>s[b]),volume:c.volume,index:E,of:d.length}))}function th(n,t,e,s,i,r){const a=n.elements.get(t);if(!a)return null;const l=E=>(E[0]-e[0])*s[0]+(E[1]-e[1])*s[1],p=E=>-(E[0]-e[0])*s[1]+(E[1]-e[1])*s[0];let d=1/0,c=-1/0;for(const E of a.pieces){const b=n.geometries.get(E.geometry);if(!b)continue;const $=E.matrix,P=N=>{const Y=b.verts[N*3],z=b.verts[N*3+1],D=b.verts[N*3+2];return[$[0]*Y+$[4]*z+$[8]*D+$[12],$[1]*Y+$[5]*z+$[9]*D+$[13],$[2]*Y+$[6]*z+$[10]*D+$[14]]};for(let N=0;N+2<b.tris.length;N+=3){const Y=[P(b.tris[N]),P(b.tris[N+1]),P(b.tris[N+2])],z=[];for(let st=0;st<3;st++){const wt=Y[st],Pt=Y[(st+1)%3],tt=l(wt)-i,ct=l(Pt)-i;if(tt<0==ct<0||tt===ct)continue;const ht=tt/(tt-ct);z.push([p(wt)+ht*(p(Pt)-p(wt)),wt[2]+ht*(Pt[2]-wt[2])])}if(z.length!==2)continue;const[D,f]=z;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(n,t,e){const s=n.elements.get(t),i=[];if(!s)return i;for(const r of e===void 0?s.pieces:[s.pieces[e]]){const a=n.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 eh(n,t,e,s){var r;const i=[];for(const a of n.elements.values()){if(a.parent!==t||!/^IFC(PLATE|COVERING|BUILDINGELEMENTPROXY)$/i.test(a.ifcClass)||a.pieces.length===0)continue;const l=Qt(n,a.gid);if(l.length===0)continue;let p=0;for(const b of a.pieces)p+=(((r=n.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&&s){const b=n.geometries.get(a.pieces[0].geometry),$=a.pieces[0].matrix;let P=0,N=null;if(b)for(let Y=0;Y+2<b.tris.length;Y+=3){const z=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=z(b.tris[Y]),f=z(b.tris[Y+1]),Tt=z(b.tris[Y+2]),st=os([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(st[0],st[1],st[2]);wt>P&&(P=wt,N=st.map(Pt=>Pt/wt))}if(N&&Math.abs(N[0]*s[0]+N[1]*s[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 Nn(n,t,e,s,i=!1){const r=n.elements.get(t);if(!r)return null;const a=Math.hypot(s[0]-e[0],s[1]-e[1]);if(!(a>.1))return null;const l=[(s[0]-e[0])/a,(s[1]-e[1])/a],p=[-l[1],l[0]],d=[];for(const at of r.pieces){const nt=n.geometries.get(at.geometry);if(!nt)continue;const pt=at.matrix,jt=Ht=>{const Dt=nt.verts[Ht*3],Xt=nt.verts[Ht*3+1],Kt=nt.verts[Ht*3+2];return[pt[0]*Dt+pt[4]*Xt+pt[8]*Kt+pt[12],pt[1]*Dt+pt[5]*Xt+pt[9]*Kt+pt[13],pt[2]*Dt+pt[6]*Xt+pt[10]*Kt+pt[14]]};for(let Ht=0;Ht+2<nt.tris.length;Ht+=3){const Dt=jt(nt.tris[Ht]),Xt=jt(nt.tris[Ht+1]),Kt=jt(nt.tris[Ht+2]),Wt=os([Xt[0]-Dt[0],Xt[1]-Dt[1],Xt[2]-Dt[2]],[Kt[0]-Dt[0],Kt[1]-Dt[1],Kt[2]-Dt[2]]),U=Math.hypot(Wt[0],Wt[1],Wt[2]);if(U<1e-9||Math.abs((Wt[0]*p[0]+Wt[1]*p[1])/U)<.995)continue;const Z=((Dt[0]+Xt[0]+Kt[0])/3-e[0])*p[0]+((Dt[1]+Xt[1]+Kt[1])/3-e[1])*p[1];d.push({a:Dt,b:Xt,c:Kt,across:Z})}}if(d.length<2)return null;const c=at=>{const nt=(at[0]-e[0])*l[0]+(at[1]-e[1])*l[1];return`${Math.round(nt*1e3)},${Math.round(at[2]*1e3)}`},E=at=>at.split(",").map(nt=>Number(nt)/1e3),b=at=>{const nt=new Map,pt=(Wt,U)=>Wt<U?`${Wt}|${U}`:`${U}|${Wt}`;for(const Wt of at){const U=[c(Wt.a),c(Wt.b),c(Wt.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);nt.set(X,(nt.get(X)??0)+1)}}const jt=new Map;for(const[Wt,U]of nt){if(U!==1)continue;const[Z,B]=Wt.split("|");(jt.get(Z)??jt.set(Z,[]).get(Z)).push(B),(jt.get(B)??jt.set(B,[]).get(B)).push(Z)}if(jt.size<3||jt.size>4e3)return null;const Ht=new Set;let Dt=null,Xt=0;const Kt=[];for(const Wt of jt.keys()){if(Ht.has(Wt))continue;const U=[Wt];Ht.add(Wt);let Z="",B=Wt;for(let dt=0;dt<5e3;dt++){const Mt=(jt.get(B)??[]).find(rt=>rt!==Z&&!Ht.has(rt))??null;if(!Mt)break;U.push(Mt),Ht.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]}Kt.push({pts:ut,area:Math.abs(X)/2}),Math.abs(X)/2>Xt&&(Xt=Math.abs(X)/2,Dt=ut)}return Dt?{best:Dt,bestArea:Xt,allLoops:Kt}:null},$=Math.max(...d.map(at=>at.across));let P=b(d.filter(at=>at.across>$-.005));const N=[...new Set(d.map(at=>Math.round(at.across*200)))].map(at=>at/200);if(N.length>1&&N.length<=24)for(const at of N){if(Math.abs(at-$)<.005)continue;const nt=b(d.filter(pt=>Math.abs(pt.across-at)<.0025));nt&&P&&nt.bestArea>P.bestArea*1.2&&(P=nt)}if(!P)return null;const{best:Y,allLoops:z}=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])),st=Math.max(...Y.map(at=>at[1]));if(!(f-D>.1)||!(st-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])}),nt=(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],jt=z.filter(U=>U.pts!==Y&&U.area>=.01&&U.pts.length<=200&&(U.area>=.1||!nt(pt(U.pts),Y))).map(U=>U.pts),Ht=jt.filter(U=>!nt(pt(U),Y)),Dt=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},Xt=$-Math.min(...d.map(U=>U.across));let Kt=0;for(const U of r.pieces){const Z=n.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]);Kt+=(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 Wt=(Dt(at)-jt.filter(U=>!Ht.includes(U)).reduce((U,Z)=>U+Dt(Z),0)+Ht.reduce((U,Z)=>U+Dt(Z),0))*Xt;return Xt>.01&&Math.abs(Kt)>1e-6&&Math.abs(Wt-Math.abs(Kt))>.15*Math.abs(Kt)?null:Ht.length?{lo:D,hi:f,bottom:Tt,chain:[],outline:at,holes:jt.filter(U=>!Ht.includes(U)),pieces:Ht}:(at.length>4||jt.length)&&at.length<=200?{lo:D,hi:f,bottom:Tt,chain:[],outline:at,holes:jt}:null}const wt=at=>Y.map((nt,pt)=>({p:nt,i:pt})).filter(({p:nt})=>Math.abs(nt[0]-at)<.003).sort((nt,pt)=>pt.p[1]-nt.p[1])[0],Pt=wt(D),tt=wt(f);if(!Pt||!tt)return null;const ct=at=>{const nt=[];for(let pt=Pt.i,jt=0;jt<=Y.length;pt=(pt+at+Y.length)%Y.length,jt++)if(nt.push(Y[pt]),pt===tt.i)return nt;return null},ht=ct(1),kt=ct(-1),te=at=>at?at.reduce((nt,pt)=>nt+pt[1],0)/at.length:-1/0;let Yt=te(ht)>=te(kt)?ht:kt;if(!Yt||Yt.length<2||(Yt=Yt.filter((at,nt,pt)=>{if(nt===0||nt===pt.length-1)return!0;const jt=pt[nt-1],Ht=pt[nt+1];return Math.abs((Ht[0]-jt[0])*(at[1]-jt[1])-(Ht[1]-jt[1])*(at[0]-jt[0]))>1e-4*Math.hypot(Ht[0]-jt[0],Ht[1]-jt[1])}),Yt.every(at=>Math.abs(at[1]-st)<.005)))return null;for(let at=1;at<Yt.length;at++)if(Yt[at][0]<Yt[at-1][0]-.003)return null;return Yt.length>200?null:{lo:D,hi:f,bottom:Tt,chain:Yt}}function sh(n,t,e){const s=Qt(n,t);if(s.length<4||e.length===0)return;let i=s[0],r=s[0],a=0;for(const z of s){const D=Math.hypot(z[0]-s[0][0],z[1]-s[0][1]);D>a&&(a=D,r=z)}a=0;for(const z of s){const D=Math.hypot(z[0]-r[0],z[1]-r[1]);D>a&&(a=D,i=z)}if(a<.3)return;const l=(r[0]-i[0])/a,p=(r[1]-i[1])/a,d=z=>(z[0]-i[0])*l+(z[1]-i[1])*p,c=Math.max(...s.map(z=>z[2])),E=z=>Math.max(...s.filter(D=>Math.abs(d(D)-z)<.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,N=(i[1]+r[1])/2;let Y;for(const z of e){const D=Qt(n,z.gid);if(D.length===0)continue;const f=D.map(Pt=>Pt[0]),Tt=D.map(Pt=>Pt[1]),st=D.map(Pt=>Pt[2]);if(P<Math.min(...f)-.2||P>Math.max(...f)+.2||N<Math.min(...Tt)-.2||N>Math.max(...Tt)+.2)continue;const wt=Math.min(...st)-c;wt>1.5||Math.max(...st)<c-.05||(!Y||Math.abs(wt)<Math.abs(Y.gap))&&(Y={id:z.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 Cs(n){const t=n.item.attrs.Name;if(typeof t!="string")return null;const e=t.indexOf(":"),s=t.lastIndexOf(":");if(e<=0||s<=e)return null;const i=t.slice(e+1,s).trim();return i?{family:t.slice(0,e).trim(),type:i}:null}function ta(n){const t=Cs(n),e=n.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 ea=180/Math.PI;function sa(n){if(typeof n!="string")return null;const t=n.indexOf(":");return t<=0||t===n.length-1?null:{family:n.slice(0,t),type:n.slice(t+1)}}const Ct=n=>String(n);function nh(n){const t=n.slice(),e=(s,i,r)=>Math.abs((i[0]-s[0])*(r[1]-s[1])-(r[0]-s[0])*(i[1]-s[1]))/2;for(let s=!0;s&&t.length>3;){s=!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),s=!0,i--)}}return t}function Xa(n){return async t=>{var ji,Di,Ui,Ji,qi,Hi,Gi,Vi,zi,Wi,Yi,Ki,Xi,Zi,Qi,tr,er,sr,nr,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,Hr,Gr,Vr,zr,Wr,Yr,Kr,Xr,Zr,Qr,to,eo,so,no,io,ro,oo,ao,co,lo,ho,fo,uo,po,mo,go,yo,wo,bo,vo,Eo,To,Mo,$o,Io,So,xo,_o,Ao,Co,Ro,Oo;const{picked:e,contents:s,site:i,shapes:r}=await Mi(t,t.input),a=ka(s.items),l=/CoordinateBase:\s*(Coordenadas compartidas|Shared Coordinates|Shared)/i.test(JSON.stringify(s.metadata??{})),p=l&&i?[i.east*rs,i.north*rs,i.elevation*rs,i.angleDeg].map(o=>o.toFixed(6)).join(","):void 0;if(a.length===0)throw new Error(n==="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 $=Ei(a),P=Na(a);if(typeof process<"u"&&((ji=process.env)!=null&&ji.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 N=`recipe:${n}-to-revit`,Y=new Map,z=Ti(t,Y);t.progress("Writing the changes for Revit");const D=new wn({project:t.projectId,document:t.target.docId??"",baseCommit:t.target.version??0,author:N}),f=rs,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 st=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 O;if(!ht)return;const o=k=>k?k.split(":")[1]:void 0,h=new Set,w=k=>(k.LocationLine??"").split(";").map(H=>H.split(",").map(Number)).filter(H=>H.length>=2&&H.every(Number.isFinite)),m=k=>{h.has(k)||(h.add(k),F=!0)};let F=!0;kt.forEach((k,H)=>{ht.has(o(k.sourceKey)??"")&&m(H)});for(let k=0;F&&k<2;k++){F=!1;const H=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&&H.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))||k===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=(O=kt[$t].placement)==null?void 0:O.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((k,H)=>{/^[0-9A-Za-z_$]{22}$/.test(o(k.sourceKey)??"")||h.add(H)});for(const k of[...h].sort((H,u)=>H-u))D.add(kt[k].attrs,{...kt[k].placement,source:kt[k].sourceKey});typeof process<"u"&&console.error(`[focus] ${ht.size} asked, ${h.size} of ${kt.length} change(s) written`)},Yt=(o,h,w)=>{if(!z.has(o))return!1;const m=Y.get(o),F=l?{...h,Frame:"shared",...p?{SharedAt:p}:{}}:h;return!m||m===on({attrs:F,placement:w??{}})},at=new Map,nt=(o,h,w)=>{wt.add(o),at.set(o,h);const m=l?{...h,Frame:"shared",...p?{SharedAt:p}:{}}:h,F=on({attrs:m,placement:w??{}}),O=z.get(o);if(O){const k=Y.get(o);return!k||k===F?(tt++,!1):(D.remove(O),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},jt=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)??[],O=Array.isArray(m)?m.map(mt=>typeof mt=="number"):[],k=O.indexOf(!0);if(o.params.of!=="roof"||!w||F.length!==4||O.filter(Boolean).length!==2||k<0||k>1||!O[k+2])return null;const[H,u]=[F[k],F[k+2]],x=H.from,gt=H.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[k],m[k+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[k])||0),bt+(Number(K[k+2])||0)],V=(et-G+lt*A)/(Ot+lt);return{A:x,u:Rt,n:It,L:$t,W:A,si:Ot,sj:lt,ridge:V,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))}}},Ht=new Map(a.filter(o=>o.kind==="extrusion"&&o.params.of==="roof").map(o=>[o.id,o])),Dt=[...Ht.values()].filter(o=>o.item.guid).map(o=>({id:o.id,gid:o.item.guid}));let Xt=0;if(b)for(const[o,h]of $){const w={CategoryId:De.levels,Name:h.name,Elevation:Ct(h.at*f)},m=on({attrs:l?{...w,Frame:"shared",...p?{SharedAt:p}:{}}:w,placement:{}}),F=(Di=[...Y].find(([O,k])=>k===m&&z.has(O)))==null?void 0:Di[0];nt(F??st(o),w)&&Xt++}let Kt=0,Wt=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?[st(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=((Ji=(Ui=h==null?void 0:h.run)==null?void 0:Ui.line)==null?void 0:Ji.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){Wt++;continue}const O=(pt(m)??0)/f,k=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},H=w.map(k).filter(u=>u!==null);Wt+=w.length-H.length,H.forEach((u,x)=>X.push({record:o,i:x,width:O,from:u.from,to:u.to,..."arcMid"in u?{arcMid:u.arcMid}:{},joinStart:x===0&&String(o.params.meetsAtStart)==="true",joinEnd:x===H.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 O=((h.from[0]-o.from[0])*m[1]-(h.from[1]-o.from[1])*m[0])/F;return[o.from[0]+O*w[0],o.from[1]+O*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,O=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]+O*w),o[1]-(h.from[1]+O*m))},rt=(o,h)=>{const w=de(o.record,"run"),m=de(h.record,"run"),F=[w.base,w.base+w.height],O=[m.base,m.base+m.height],k=$.get(String((w==null?void 0:w.level)??o.record.params.level)).at,H=$.get(String((m==null?void 0:m.level)??h.record.params.level)).at;return Math.min(k+F[1],H+O[1])>Math.max(k+F[0],H+O[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 O=o[m];let k=null,H=1/0;for(const gt of X){if(gt===o||gt.arcMid||!rt(o,gt))continue;const $t=Mt(O,gt);$t<H&&(H=$t,k=gt)}if(!k||H>_t)continue;const u=dt(o,k);if(!u)continue;const x=Math.min(_t,2*Math.max(o.width,k.width)+.02);Math.hypot(u[0]-O[0],u[1]-O[1])>x||Mt(u,k)>k.width+.01||(w[m]=u,Nt.set(o,{...Nt.get(o),[m]:k.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 O=w.record.item.guid;if(!O||X.filter(x=>x.record===w.record).length!==1)return null;const{d:k}=o(w),H=Qt(r,O).map(x=>x[2]);if(!H.length)return null;const u=th(r,O,w.from,k,(m+F)/2,(Math.min(...H)+Math.max(...H))/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 O=o(F);if(O.L<.3||Math.abs(m.d[0]*O.d[1]-m.d[1]*O.d[0])>.02)continue;const k=Math.abs(-(F.from[0]-w.from[0])*m.d[1]+(F.from[1]-w.from[1])*m.d[0]);if(k>(w.width+F.width)/2-.01)continue;const H=[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(...H)),x=Math.min(m.L,Math.max(...H));if(x-u<.3)continue;const gt=h(w,u,x);typeof process<"u"&&((Hi=(qi=process.env)==null?void 0:qi.RECIPE_WALL)!=null&&Hi.split(",").includes(w.record.item.guid??""))&&console.error(`[cut-by?] ${w.record.item.guid} by ${F.record.item.guid}: off ${k.toFixed(3)}, along ${u.toFixed(2)}..${x.toFixed(2)}, shape ${gt}`),!(gt===null||gt>w.width-.01)&&(typeof process<"u"&&((Gi=process.env)!=null&&Gi.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 O of r.elements.values()){if(O.parent!==o||!/^IFCPLATE$/i.test(O.ifcClass)||O.pieces.length!==1)continue;const k=r.geometries.get(O.pieces[0].geometry);if(!k||k.tris.length/3>12)continue;const H=Qt(r,O.gid);if(H.length<4)continue;const u=H.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((O,k)=>O-k),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 k;if(!r||!o)return null;const w=[-h[1],h[0]],m=[],F=[];for(const H of r.elements.values()){if(H.parent!==o||!/^IFCMEMBER$/i.test(H.ifcClass))continue;const u=Qt(r,H.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((H,u)=>H-u),F.sort((H,u)=>H-u);const O={width:m[Math.floor(m.length/2)],depth:F[Math.floor(F.length/2)]};return typeof process<"u"&&((k=process.env)!=null&&k.RECIPE_TRACE)&&console.error(`[mullion] ${o}: ${m.length} member(s), median ${(O.width*1e3).toFixed(1)} × ${(O.depth*1e3).toFixed(1)} mm`),{width:O.width*f,depth:O.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"),O=$.get(String((F==null?void 0:F.level)??w.record.params.level??""));if(!F||!O)continue;const k=Qt(r,m);if(!k.length)continue;let H=1/0;for(const u of k)H=Math.min(H,u[2]);o.push(H-(O.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"&&((zi=(Vi=process.env)==null?void 0:Vi.RECIPE_WALL)!=null&&zi.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,O=m.height,k=$.get(String(m.level??h.params.level??"")),H=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 W=y[0]*j[0]+y[1]*j[1];return Math.abs(W)<.5?null:((J[0]-S[0])*j[0]+(J[1]-S[1])*j[1])/W},T=h.params.wantedAtStart==="square"?g(u,(Wi=L.start)==null?void 0:Wi[0]):null,v=h.params.wantedAtEnd==="square"?g(x,(Yi=L.end)==null?void 0:Yi[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"&&((Ki=process.env)!=null&&Ki.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"&&((Xi=process.env)!=null&&Xi.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} ${H}: start ${T==null?void 0:T.toFixed(3)} end ${v==null?void 0:v.toFixed(3)}`),typeof process<"u"&&((Qi=(Zi=process.env)==null?void 0:Zi.RECIPE_WALL)!=null&&Qi.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(W=>(W[0]-u[0])*y[0]+(W[1]-u[1])*y[1]),T=Math.min(...g),v=Math.max(...g),S=L.map(W=>-(W[0]-u[0])*y[1]+(W[1]-u[1])*y[0]),C=Math.max(...S)-Math.min(...S),J=W=>{const M=S.filter((ot,Q)=>Math.abs(g[Q]-W)<.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=(k.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:((tr=Cs(h))==null?void 0:tr.type)??H,LocationLine:yt,Level:k.name,BaseOffset:Ct(F*f),Height:Ct(O*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 _=`${st(L.record.id)}#${L.i}`,y=z.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((k.at+F+O-K.at)*f));const G=m.profile;let et=Array.isArray(G)?nh(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"&&((er=process.env)!=null&&er.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(H))==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=k.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),W=et.filter(M=>!J(M));et.filter(J).length===4&&(W.length===0||v.length&&W.every(j))&&(typeof process<"u"&&((sr=process.env)!=null&&sr.RECIPE_TRACE)&&console.error(`[layer-extension] ${h.item.guid} ${H}: its outline's ${W.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(se=>(se[0]-o.from[0])*_[0]+(se[1]-o.from[1])*_[1]):[],Ft=Q.length?Math.max(0,-Math.min(...Q))-g:1/0,Ut=Q.length?Math.max(0,Math.max(...Q)-L)-T:1/0,Gt=(M==null?void 0:M.from)??(Ft<.6?Ft:0),ee=(M==null?void 0:M.to)??(Ut<.6?Ut:0);Gt&<.includes("start")&&Ft>.005&&(g+=Math.min(Gt,Ft),ot.push("start")),ee&<.includes("end")&&Ut>.005&&(T+=Math.min(ee,Ut),ot.push("end"));const Zt=lt.filter(se=>!ot.includes(se));if(ot.length&&(Zt.length?A.JoinEnds=Zt.join(","):delete A.JoinEnds),ot.length&&A.Mitre){const se=A.Mitre.split(",").filter(Jt=>Zt.includes(Jt));se.length?A.Mitre=se.join(","):delete A.Mitre}ot.length&&typeof process<"u"&&((nr=process.env)!=null&&nr.RECIPE_TRACE)&&console.error(`[profile-face] ${h.item.guid} ${H}: ${ot.join(",")} to the far face`)}const C=(M,ot)=>et.map(([Q,Ft],Ut)=>{const Gt=Math.abs(Q)<1e-6,ee=Math.abs(Q-L)<1e-6;let Zt=Q,se=Ft;if(Gt||ee){Zt=Gt?-M:L+ot;const Jt=[et[(Ut-1+et.length)%et.length],et[(Ut+1)%et.length]].find(([fe])=>Math.abs(fe-Q)>1e-6);Jt&&(se=Ft+(Jt[1]-Ft)/(Jt[0]-Q)*(Zt-Q))}return[Zt,se]}),J=M=>{const ot=M.length,Q=M.map((Ut,Gt)=>[Ut,M[(Gt+1)%ot]]);if(Q.some(([Ut,Gt])=>Math.hypot(Gt[0]-Ut[0],Gt[1]-Ut[1])<.001))return!1;for(let Ut=0;Ut<ot;Ut++){const[Gt,ee]=Q[Ut],[,Zt]=Q[(Ut+1)%ot],se=[ee[0]-Gt[0],ee[1]-Gt[1]],Jt=[Zt[0]-ee[0],Zt[1]-ee[1]];if((se[0]*Jt[0]+se[1]*Jt[1])/(Math.hypot(...se)*Math.hypot(...Jt))<-.999)return!1}const Ft=(Ut,Gt,ee)=>(Gt[0]-Ut[0])*(ee[1]-Ut[1])-(Gt[1]-Ut[1])*(ee[0]-Ut[0]);for(let Ut=0;Ut<ot;Ut++)for(let Gt=Ut+1;Gt<ot;Gt++){if(Gt===Ut+1||Ut===0&&Gt===ot-1)continue;const[ee,Zt]=Q[Ut],[se,Jt]=Q[Gt],fe=Ft(se,Jt,ee),Be=Ft(se,Jt,Zt),ws=Ft(ee,Zt,se),ko=Ft(ee,Zt,Jt);if((fe>1e-9&&Be<-1e-9||fe<-1e-9&&Be>1e-9)&&(ws>1e-9&&ko<-1e-9||ws<-1e-9&&ko>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"&&((ir=process.env)!=null&&ir.RECIPE_TRACE)&&console.error(`[profile-folded] ${h.item.guid} ${H}: 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 W=M=>M.flatMap(([ot,Q])=>{const Ft=[o.from[0]+ot*_[0],o.from[1]+ot*_[1]];return[Ft[0]*f,Ft[1]*f,(k.at+F+Q)*f]});for(const M of W(j))y.push(M);if(A.Profile=JSON.stringify([y]),j.length===8){const M=j.map(([,Jt])=>Jt),ot=Math.max(...M),Q=Math.min(...M),Ft=j.map(([Jt])=>Jt),Ut=Math.min(...Ft),Gt=Math.max(...Ft),ee=j.filter(([Jt])=>Jt>Ut+.005&&Jt<Gt-.005),Zt=[...new Set(ee.map(([Jt])=>+Jt.toFixed(4)))].sort((Jt,fe)=>Jt-fe);if(j.filter(([Jt,fe])=>(Math.abs(Jt-Ut)<.005||Math.abs(Jt-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(([,Jt])=>Math.abs(Jt-Q)<.005)&&ee.every(([,Jt])=>Math.abs(Jt-Q)<.005||ot-Jt<.3)){const Jt=(fe,Be)=>[[fe,Q],[Be,Q],[Be,ot],[fe,ot]];A.Profile=JSON.stringify([W(Jt(Ut,Zt[0]))]),w=[JSON.stringify([W(Jt(Zt[1],Gt))])],typeof process<"u"&&((rr=process.env)!=null&&rr.RECIPE_TRACE)&&console.error(`[slit-split] ${h.item.guid} ${H}: 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&&Ht.has(St)?jt(Ht.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=k.at+F,S=[],C=(J,j)=>{const W=_(J);S.push(W[0]*f,W[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?sh(r,h.item.guid,Dt):void 0;if(mt&&!A.Profile){A.AttachTop=st(mt);const L=z.get(st(mt));L&&(A.AttachTopMade=L)}if(mt&&typeof St!="string"&&typeof process<"u"&&((or=process.env)!=null&&or.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 _=Nn(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 W=Qt(r,j.gid).map(M=>[(M[0]-u[0])*v[0]+(M[1]-u[1])*v[1],M[2]]);return W.length?[Math.min(...W.map(M=>M[0])),Math.max(...W.map(M=>M[0])),Math.min(...W.map(M=>M[1])),Math.max(...W.map(M=>M[1]))]:null}).filter(j=>j!==null),C=j=>{const W=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(W,Ft[0])>.01&&Math.min(Q,Ft[3])-Math.max(ot,Ft[2])>.01)},J=(_.holes??[]).filter(j=>!C(j));_=!((ar=_.pieces)!=null&&ar.length)&&(J.length||_.outline.length>4)?{..._,holes:J}:null,_&&typeof process<"u"&&((cr=process.env)!=null&&cr.RECIPE_TRACE)&&console.error(`[wall-outline] ${h.item.guid}: ${L.length} hosted, ${J.length} empty hole(s) kept`)}const g=_!=null&&_.outline?null:Nn(r,h.item.guid,u,x);if(g){typeof process<"u"&&((lr=process.env)!=null&&lr.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"&&((hr=process.env)!=null&&hr.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:Nn(r,h.item.guid,u,x,!0);if((fr=_==null?void 0:_.holes)!=null&&fr.length&&!((dr=_.pieces)!=null&&dr.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"&&((ur=process.env)!=null&&ur.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]),_=k.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,(_+O)*f,u[0]*f,u[1]*f,(_+O)*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 W=0;W<C.length;W++){const M=C[W],ot=C[(W+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=W=>(W[0]-C.through[0])*C.keep[0]+(W[1]-C.through[1])*C.keep[1]+(W[2]-C.through[2])*C.keep[2],j=[];for(let W=0;W<g.length;W++){const M=g[W],ot=g[(W+1)%g.length],Q=J(M),Ft=J(ot);if(Q>=0&&j.push(M),Q>=0!=Ft>=0){const Ut=Q/(Q-Ft);j.push([0,1,2].map(Gt=>M[Gt]+Ut*(ot[Gt]-M[Gt])))}}g=j}const S=g.length>=3?T(g):0;S>.05&&v-S>.05&&(typeof process<"u"&&((pr=process.env)!=null&&pr.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 W=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 W.length>=2?{c:(Math.max(...W)+Math.min(...W))/2,w:Math.max(...W)-Math.min(...W)}: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,W=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(...W)-Math.min(...W),ot=M<(v.w+S.w)/2+.01&&C.w>.5*Math.min(v.w,S.w);if(typeof process<"u"&&((gr=(mr=process.env)==null?void 0:mr.RECIPE_WALL)!=null&&gr.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"&&((yr=process.env)!=null&&yr.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(H);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 qt=h.item.guid?r==null?void 0:r.elements.get(h.item.guid):void 0;if(qt!=null&&qt.layers&&qt.layers.length>1)A["Type.Layers"]=JSON.stringify([...qt.layers].reverse().map(L=>[+Ct(L.thickness*f),L.material??"",L.function??""])),qt.layersFlipped&&(A.FlipLayers="1");else if(typeof process<"u"&&((wr=process.env)!=null&&wr.RECIPE_PIECE_LAYERS)&&qt&&qt.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=[];qt.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]),W=C.map(Q=>Q[2]);if(Math.max(...J)-Math.min(...J)<Math.min(.3,.5*L)||Math.max(...W)-Math.min(...W)<.5*O)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,W)=>{const M=ot=>+Ct(Math.round(ot*2e3)/2e3*f);W>0&&y[W-1][0]-j[1]>.003&&v.push([M(y[W-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"&&((br=process.env)!=null&&br.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"&&((vr=process.env)!=null&&vr.RECIPE_LAYER_EXT)){const L=(()=>{var y,g;try{return JSON.parse(String(((g=(y=P.get(H))==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 W=[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]<W[2]-.01&&W[0]<M.box[3]-.01&&M.box[1]<W[3]-.01&&W[1]<M.box[4]-.01&&M.box[2]<J-.01&&C<M.box[5]-.01).flatMap(M=>M.keys)},v=k.at+F+re,S=typeof process<"u"&&((Er=process.env)!=null&&Er.RECIPE_EXT_CUT)&&!A.Profile&&y>.001&&g<.001?T(v+O,v+O+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"&&((Tr=process.env)!=null&&Tr.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"&&((Mr=process.env)!=null&&Mr.RECIPE_TRACE)&&console.error(`[layer-extension] ${h.item.guid} ${A.Type}: top ${y}, base ${g}`)}}typeof process<"u"&&((Ir=($r=process.env)==null?void 0:$r.RECIPE_WALL)!=null&&Ir.split(",").includes(h.item.guid??""))&&console.error(`[wall-attrs] ${JSON.stringify(A).slice(0,1500)} style ${JSON.stringify(((Sr=P.get(H))==null?void 0:Sr.params)??null).slice(0,800)}`),nt(`${st(h.id)}#${o.i}`,A)&&Kt++,w.forEach((L,_)=>{nt(`${st(h.id)}#${o.i}p${_+1}`,{...A,Profile:L})&&Kt++})}const Qe=(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,O=[];for(let k=F;k<=o+1e-4;k+=h)k>1e-4&&k<o-1e-4&&O.push(k);return O};let Hs=0,Ci=0;const Ri=new Map;for(const o of a){if(o.kind!=="run"||o.params.of!=="curtainWall")continue;Ci++;const h=de(o,"run"),w=(Ar=(_r=(xr=h==null?void 0:h.run)==null?void 0:xr.line)==null?void 0:_r.curves)==null?void 0:Ar[0],m=$.get(String((h==null?void 0:h.level)??o.params.level??"")),F=o.params.lookRef,O=typeof F=="string"?(Cr=P.get(F))==null?void 0:Cr.params:void 0;if(!(w!=null&&w.from)||!w.to||typeof(h==null?void 0:h.height)!="number"||!m||!O)continue;const k=y=>typeof y=="number"?y:Number(y)||0,H=Math.hypot(w.to[0]-w.from[0],w.to[1]-w.from[1]),u=[(w.to[0]-w.from[0])/H,(w.to[1]-w.from[1])/H],x=k(O.uprightWidth)>0?null:Le(o.item.guid??void 0,u),gt=(k(O.uprightWidth)||(x?x.width/f:0))/2,$t=(k(O.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(W=>(W[0]-w.from[0])*u[0]+(W[1]-w.from[1])*u[1]),j=C.map(W=>W[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)),W=M=>M.t1-M.t0>M.z1-M.z0;Rt.bottom=!v.some(M=>W(M)&&Math.abs(M.z0-J)<.01),Rt.top=!v.some(M=>W(M)&&Math.abs(M.z1-j)<.01),Rt.start=!v.some(M=>!W(M)&&Math.abs(M.t0-S)<.01),Rt.end=!v.some(M=>!W(M)&&Math.abs(M.t1-C)<.01),It=[...new Set(v.filter(M=>!W(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"&&((Rr=process.env)!=null&&Rr.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,V=(m.at+G)*f,St=Qe(H,k(O.alongSpacing),O.alongJustify),it=!((Or=h.lines)!=null&&Or.along)&&It.length>0&&(It.length!==St.length||It.some((y,g)=>Math.abs(y-St[g])>.01));it&&typeof process<"u"&&((kr=process.env)!=null&&kr.RECIPE_TRACE)&&console.error(`[curtain-lines] ${o.item.guid}: ${It.length} from its bars, not the type's ${St.length}`);const ft=((Nr=h.lines)==null?void 0:Nr.along)??(it?It:St),mt=((Fr=h.lines)==null?void 0:Fr.up)??Qe(h.height,k(O.upSpacing),O.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=H+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 qt=(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 eh(r,o.item.guid,k(O.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>H+.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));qt.push({along:(v+yt)*f,up:(S+Ot)*f}),Pt.add(y.gid)}const L={CategoryId:De.walls,Type:((Pr=Cs(o))==null?void 0:Pr.type)??String(F),LocationLine:`${Ct(bt[0]*f)},${Ct(bt[1]*f)},${Ct(V)};${Ct(K[0]*f)},${Ct(K[1]*f)},${Ct(V)}`,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:qt,...xt?{noBorders:!0}:{},mullion:k(O.uprightWidth)>0?{width:k(O.uprightWidth)*f,depth:k(O.depth)*f}:x??{width:0,depth:k(O.depth)*f},panel:{thickness:me(o.item.guid??void 0,u)??k(O.panelDepth)*f,offset:-k(O.panelOffset)*f}})},_=h.profile;if(Array.isArray(_)&&_.length>=3){const g=_.reduce((C,J,j)=>{const W=_[(j+1)%_.length];return C+J[0]*W[1]-W[0]*J[1]},0)>0?1:-1,T=_.length,v=_.map((C,J)=>{const j=_[(J-1+T)%T],W=_[(J+1)%T],M=(Gt,ee)=>{const Zt=ee[0]-Gt[0],se=ee[1]-Gt[1],Jt=Math.hypot(Zt,se)||1,fe=g*se/Jt,Be=-g*Zt/Jt,ws=Math.abs(fe)>Math.abs(Be)?gt:$t;return{p:[Gt[0]+fe*ws,Gt[1]+Be*ws],d:[Zt,se]}},ot=M(j,C),Q=M(C,W),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 Ut=((Q.p[0]-ot.p[0])*Q.d[1]-(Q.p[1]-ot.p[1])*Q.d[0])/Ft;return[ot.p[0]+Ut*ot.d[0],ot.p[1]+Ut*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=(Lr=y.panel)!=null&&Lr.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=Ri.get(L.Type);S===void 0?Ri.set(L.Type,v):S!==v&&(typeof process<"u"&&((Br=process.env)!=null&&Br.RECIPE_TRACE)&&console.error(`[curtain-type] ${o.item.guid}: ${L.Type} first made with ${S}, this one ${v}`),L.Type=`${L.Type} · ${v}`)}nt(st(o.id),L)&&Hs++}let Gs=0,Oi=0;const ki=(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],O=[o,...[...r.elements.values()].filter(u=>u.parent===o).map(u=>u.gid)].flatMap(u=>Qt(r,u));if(O.length<4)return null;const k=O.map(u=>(u[0]-h[0])*F[0]+(u[1]-h[1])*F[1]),H=Math.max(...k)-Math.min(...k);return H>.3&&H<10?H:null};for(const o of a){if(o.kind!=="stair"||o.params.of!=="stair")continue;Oi++;const h=de(o,"stair"),w=o.params.lookRef,m=typeof w=="string"?(jr=P.get(w))==null?void 0:jr.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 O=K=>typeof K=="number"?K:Number(K)||0,k=Number(h.rise),H=O(m.maxRiser)>0?O(m.maxRiser):(Ur=(Dr=h.sketch)==null?void 0:Dr.risers)!=null&&Ur.length?k/(h.sketch.risers.length+1):.18,u=Math.max(1,Math.ceil(k/H-1e-6)),x=O(m.tread),gt=K=>[K[0]*f,K[1]*f];let $t=F.at+O(o.params.base),Rt=!1;if(r&&o.item.guid){const K=Qt(r,o.item.guid).map(V=>V[2]-re),G=k/u,et=K.length?Math.min(...K):$t;$t-et>.5*G&&$t-et<1.5*G&&(typeof process<"u"&&((Jr=process.env)!=null&&Jr.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,V)=>et<V.length-1||!/^\d+$/.test(G));return K.length>=3&&/^(stairs?|escaleras?|treppen?)$/i.test(K[0])?K[1]:K[0]})(),base:$t*f,height:k*f,risers:u,tread:x*f,width:(O(m.width)>0?O(m.width):ki(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(V=>V[2]))-re,et=F.at+O(o.params.base)+k;return et-G>.5*(k/u)&&et-G<1.5*(k/u)})(),sizes:{maxRiser:Math.ceil(k/u*1e3-1e-6)/1e3*f,minTread:x*f,waist:O(m.waist)*f,treadThickness:m.construction==="assembled"?O(m.treadThickness)*f:0,riserThickness:m.construction==="assembled"?O(m.riserThickness)*f:0,notchExtension:O(m.notchExtension)*f,notchThickness:O(m.notchThickness)*f,...m.nosing!==void 0&&Number.isFinite(Number(m.nosing))?{nosing:Number(m.nosing)*f}:{}}};typeof process<"u"&&((qr=process.env)!=null&&qr.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,V=yt.boundary,St=it=>V.some((ft,mt)=>{const At=V[(mt+1)%V.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),qt=K(ft),L=[xt[0]-qt[0],xt[1]-qt[1]];let _=null,y=1/0;for(let g=0;g<V.length;g++){const T=V[g],v=V[(g+1)%V.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"&&((Hr=process.env)!=null&&Hr.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])}),V=et>0?[...yt.boundary.slice(et),...yt.boundary.slice(0,et)]:yt.boundary;typeof process<"u"&&((Gr=process.env)==null?void 0:Gr.RECIPE_STAIR)===o.item.guid&&console.error(`[stair-sketch] boundary ${JSON.stringify(V)} (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<V.length;g++){const T=it([V[g],V[(g+1)%V.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<V.length;J++){const j=[V[(J+1)%V.length][0]-V[J][0],V[(J+1)%V.length][1]-V[J][1]],W=Math.hypot(j[0],j[1]);if(!(W>0)||Math.abs((j[0]*g[1]-j[1]*g[0])/(W*T))>.06)continue;const M=it([V[J],V[(J+1)%V.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)%V.length)v.push([gt(V[S]),gt(V[(S+1)%V.length])]);return v},qt=[...xt(1,mt),...xt((mt+1)%V.length,0)];typeof process<"u"&&((Vr=process.env)==null?void 0:Vr.RECIPE_STAIR)===o.item.guid&&console.error(`[stair-sketch] end edge ${mt} of ${V.length}`);const L=yt.risers.map(([g,T])=>[gt(g),gt(T)]);gt(V[mt]),gt(V[(mt+1)%V.length]);const _=L.map(([g,T])=>[(g[0]+T[0])/2,(g[1]+T[1])/2]);if(It.sketch={boundary:qt,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"&&((zr=process.env)!=null&&zr.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??""}: ${qt.length} sides (shortest ${(Math.min(...qt.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]],W=Math.hypot(J[0],J[1]),M=Math.hypot(j[0],j[1]);Math.abs((J[0]*j[1]-J[1]*j[0])/(W*M))>.001||(y=Math.min(y,Math.abs(((S[0]-T[0])*J[1]-(S[1]-T[1])*J[0])/W)))}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],V=Math.hypot(G,et);V>0&&(K=[K[0]-x*G/V,K[1]-x*et/V])}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"&&((Wr=process.env)!=null&&Wr.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 ${k}, ${u} risers, width ${O(m.width)}, measured ${ki(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,V=(((Kr=(Yr=G==null?void 0:G.profile)==null?void 0:Yr.outline)==null?void 0:Kr.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||!V.length||!St||!it)continue;const[ft,mt]=[Math.min(...V.map(S=>S[0])),Math.max(...V.map(S=>S[0]))],[At,xt]=[Math.min(...V.map(S=>S[1])),Math.max(...V.map(S=>S[1]))],qt=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]-qt[0])*_[0]+(y[1]-qt[1])*_[1]<0&&(_=[-_[0],-_[1]]);const T=St/f,v=(S,C)=>[(qt[0]+L[0]*S+_[0]*C)*f,(qt[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+O(K.params.base)+qt[2]+xt)*f,thickness:(xt-At)*f})}lt.length&&(It.landings=lt);const bt={CategoryId:De.stairs,Type:((Xr=Cs(o))==null?void 0:Xr.type)??String(w),Level:F.name,Stairs:JSON.stringify(It)};typeof process<"u"&&(((Zr=process.env)==null?void 0:Zr.RECIPE_STAIR)===o.item.guid||((Qr=process.env)==null?void 0:Qr.RECIPE_STAIR)==="*")&&console.error(`[stair-spec] ${bt.Stairs} style ${JSON.stringify(m)}`),nt(st(o.id),bt)&&Gs++}const Ni=new Map,ms={floor:0,foundation:0,roof:0,ceiling:0},pe={floor:0,foundation:0,roof:0,ceiling:0},Fi=a.flatMap(o=>{var O,k;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=(((k=(O=h==null?void 0:h.profile)==null?void 0:O.outline)==null?void 0:k.curves)??[]).flatMap(H=>H.from?[H.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":ta(o);if(w==="other"||r&&o.item.guid&&/^IFCRAMP(FLIGHT)?$/i.test(((to=r.elements.get(o.item.guid))==null?void 0:to.ifcClass)??""))continue;const m=de(o,"extrusion"),F=m==null?void 0:m.on;if(F&&(Math.abs(((eo=F.u)==null?void 0:eo[2])??0)>.001||Math.abs(((so=F.v)==null?void 0:so[2])??0)>.001))continue;if(w==="roof"&&!jt(o)){const lt=m,bt=((io=(no=m==null?void 0:m.profile)==null?void 0:no.outline)==null?void 0:io.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]),V=Math.min(...et);G.some((it,ft)=>Math.abs(et[ft]-V)<.01&&Math.abs(et[(ft+1)%G.length]-V)<.01)||(w="floor",typeof process<"u"&&((ro=process.env)!=null&&ro.RECIPE_TRACE)&&console.error(`[roof-as-floor] ${o.item.guid} ${o.params.lookRef}: its low side a corner, a sloped floor`))}}ms[w]++,typeof process<"u"&&((oo=process.env)==null?void 0:oo.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 O=typeof o.params.base=="number"?o.params.base:0,k=$.get(String((m==null?void 0:m.level)??o.params.level??"")),H=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,O*f)}return bt.length>=9?bt:null},x=u((co=(ao=m==null?void 0:m.profile)==null?void 0:ao.outline)==null?void 0:co.curves);if(typeof H!="string"||!k||!x)continue;const gt=[x],$t=w==="roof"?jt(o):null;for(const lt of((lo=m==null?void 0:m.profile)==null?void 0:lo.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=k.at+O,yt=It+(Number(o.params.depth)||0);for(const lt of Fi)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,W=x[3*S+1]/f;J>g!=W>g&&y<(j-C)*(g-J)/(W-J)+C&&(T=!T)}return T};if(!G.every(y=>et(y[0],y[1]))){typeof process<"u"&&((ho=process.env)!=null&&ho.RECIPE_TRACE)&&console.error(`[slab-cut] ${o.item.guid}: a cut across its edge, left`);continue}const V=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=V(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=V(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))}),qt=St(x),L=G.some(y=>qt.some((g,T)=>{const v=qt[(T+1)%qt.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"&&((fo=process.env)!=null&&fo.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]):O)*f]);gt.push(_),typeof process<"u"&&((uo=process.env)!=null&&uo.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:((po=Cs(o))==null?void 0:po.type)??H,Profile:JSON.stringify(gt),Level:k.name};let Ot=pt(H);if(w==="roof"&&r&&o.item.guid){const lt=(mo=r.elements.get(o.item.guid))==null?void 0:mo.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=Ni.get(A.Type);lt===void 0?Ni.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 V=[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=V[2]>bt[2]+.01&&V[2]<bt[5]-.01&&V[5]>bt[5]&<.some(At=>Math.abs(At[2]-V[2])<.005),it=V[0]<bt[3]-.01&&bt[0]<V[3]-.01&&V[1]<bt[4]-.01&&bt[1]<V[4]-.01;if(!St||!it)return[];const ft=`${st(G.record.id)}#${G.i}`,mt=z.get(ft);return mt?[ft,mt]:[ft]});K.length&&(A.CutBy=[...new Set(K)].join("|"),typeof process<"u"&&((go=process.env)!=null&&go.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(O*f);const lt=Number(o.params.drop??((yo=m==null?void 0:m.said)==null?void 0:yo.drop));if(w==="ceiling"&&Number.isFinite(lt)&&Ot){const V=[...$.values()].filter(St=>St.at>k.at+1e-6).sort((St,it)=>St.at-it.at)[0];V&&(A.BaseOffset=Ct((V.at-lt-Ot/f-k.at)*f))}const bt=m==null?void 0:m.slopes;if(w==="roof"&&Array.isArray(bt)&&bt.some(V=>typeof V=="number")){A.Slopes=JSON.stringify(bt.map(it=>typeof it=="number"?it:null));const V=Math.max(...bt.filter(it=>typeof it=="number").map(it=>Math.abs(it)));Ot&&V>0&&(A.BaseOffset=Ct(O*f-Ot*Math.sqrt(1+V*V)));const St=r&&o.item.guid?Qt(r,o.item.guid):[];if(Ot&&V>0&&St.length>=4){const it=St.map(qt=>qt[2]-re),ft=Math.min(...it),mt=k.at+O,At=mt-Ot/f*Math.sqrt(1+V*V),xt=mt-ft;if(ft-At>.01&&xt>.01){const qt=St.filter((W,M)=>it[M]<ft+.002),L=W=>[Math.min(...W.map(M=>M[0])),Math.min(...W.map(M=>M[1])),Math.max(...W.map(M=>M[0])),Math.max(...W.map(M=>M[1]))],[_,y,g,T]=L(St),[v,S,C,J]=L(qt),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+V*V):xt)*f)}typeof process<"u"&&((wo=process.env)!=null&&wo.RECIPE_TRACE)&&console.error(`[roof-eave] ${o.item.guid} ${H}: 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"&&((bo=process.env)!=null&&bo.RECIPE_TRACE)&&console.error(`[roof] ${o.item.guid} ${H}: slopes ${JSON.stringify(bt)} base ${O} width ${Ot} edges ${gt[0]?gt[0].length/3:0} profile ${JSON.stringify((vo=gt[0])==null?void 0:vo.map(it=>+it.toFixed(2)))}`)}const K=w==="roof"?jt(o):null;if(K){const{A:V,n:St,u:it,W:ft,ridge:mt,si:At,ti:xt,tj:qt,L}=K,_=(y,g)=>[(V[0]+St[0]*y)*f,(V[1]+St[1]*y)*f,g*f];A.Extrusion=JSON.stringify({profile:[_(0,xt),_(mt,xt+At*mt),_(ft,qt)],along:[it[0],it[1]],length:L*f}),delete A.Slopes}const G=m==null?void 0:m.slope,et=((To=(Eo=m==null?void 0:m.profile)==null?void 0:Eo.outline)==null?void 0:To.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 V=[Math.cos(G.toward),Math.sin(G.toward)],St=et.map(At=>At.from).filter(Boolean),it=St.map(At=>At[0]*V[0]+At[1]*V[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(O*f);const At=r&&o.item.guid?Qt(r,o.item.guid):[];if(At.length>=4){const xt=Math.min(...At.map(qt=>qt[2]))-re;k.at+O-xt>.5*Math.tan(Math.abs(G.by))*(Math.max(...it)-ft)&&(A.BaseOffset=Ct((xt-k.at)*f))}}typeof process<"u"&&((Mo=process.env)!=null&&Mo.RECIPE_TRACE)&&console.error(`[roof-plane] ${o.item.guid} ${H}: ${(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(O*f+Ot);const lt=m==null?void 0:m.slope,bt=((Io=($o=m==null?void 0:m.profile)==null?void 0:$o.outline)==null?void 0:Io.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]),V=Math.min(...et),St=Math.max(...et),it=G[et.indexOf(V)],ft=Math.tan(lt.by);if(St-V>.001){A.Slope=Ct(ft),A.SlopeArrow=JSON.stringify([it[0]*f,it[1]*f,(it[0]+K[0]*(St-V))*f,(it[1]+K[1]*(St-V))*f]),A.HeightOffset=Ct(O*f+Ot-ft*(St-V)*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-k.at)*f+Ot*Math.sqrt(1+ft*ft)),typeof process<"u"&&((So=process.env)!=null&&So.RECIPE_TRACE)&&console.error(`[slab-slope] ${o.item.guid} ${H}: lowest ${At.toFixed(3)} level ${k.at.toFixed(3)} base ${O.toFixed(3)} rise ${(ft*(St-V)).toFixed(3)}: top at its low corner ${(At+Ot*Math.sqrt(1+ft*ft)/f).toFixed(3)} (by base ${(k.at+O+Ot/f-ft*(St-V)).toFixed(3)})`)}}}}nt(st(o.id),A)&&pe[w]++}let Vs=0,Pi=0;for(const o of a){if(o.kind!=="member"||o.params.of!=="column")continue;Pi++;const h=de(o,"member"),w=h==null?void 0:h.start;if(!w||w.length!==3)continue;const m=c?sa(o.params.lookRef):null;if(c&&!m||!m&&!d)continue;const F=m??{family:d.family,type:d.type},O=$.get(String((h==null?void 0:h.level)??""));nt(st(o.id),{...d&&!m?{CategoryId:d.categoryId}:{},Family:F.family,Type:F.type,...O?{Level:O.name}:{}},{position:[w[0]*f,w[1]*f,w[2]*f],rotationDeg:(Number((h==null?void 0:h.roll)??0)||0)*ea})&&Vs++}let zs=0,Li=0,En=0;for(const o of a){if(o.kind!=="familyInstance")continue;if(o.params.host){En++;continue}if(Li++,!E)continue;const h=de(o,"instance"),w=(xo=h==null?void 0:h.placement)==null?void 0:xo.at;if(!w||w.length!==3)continue;const m=sa(o.params.type);if(!m)continue;const F=(_o=h==null?void 0:h.placement)==null?void 0:_o.right,O=F?Math.atan2(F[1],F[0])*ea:0;nt(st(o.id),{Family:m.family,Type:m.type},{position:[w[0]*f,w[1]*f,w[2]*f],rotationDeg:O})&&zs++}Pt.size&&typeof process<"u"&&((Ao=process.env)!=null&&Ao.RECIPE_TRACE)&&console.error(`[shaped-panels] ${Pt.size} curtain panel(s) made as families of their shape`);const gs=r?Wl(r,wt,e.fileId,Pt).filter(o=>!Fi.some(h=>h.guid&&o.key.includes(h.guid))):[];if(typeof process<"u"&&((Co=process.env)!=null&&Co.RECIPE_GID))for(const o of gs.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 Ws=0;const Ys=new Map;for(const o of gs){if(!o.attrs.Family||Ys.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&&Ys.set(o.attrs.Family,h)}const Bi=new Set;for(const o of gs){const h=o.attrs.Family;!h||!Ys.has(h)||!(o.attrs.Shape||o.attrs.Prism)||Yt(o.key,o.host&&z.get(o.host)?{...o.attrs,HostMade:z.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}:{}})&&Bi.add(h)}for(const o of gs){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&&z.get(o.host)?{...o.attrs,HostMade:z.get(o.host)}:o.attrs,F=h&&Bi.has(h)&&!(o.attrs.Shape||o.attrs.Prism)&&!Yt(o.key,m,w)?{...o.attrs,...Ys.get(h)}:o.attrs;nt(o.key,o.host&&z.get(o.host)?{...F,HostMade:z.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}:{}})&&Ws++}if(r)for(const o of Yl(r,wt,e.fileId)){const h=(Ro=at.get(o.host))==null?void 0:Ro.Profile;if(h)try{const w=JSON.parse(h),m=[];for(let H=0;H+2<o.box.length;H+=3)m.push([o.box[H]*f,o.box[H+1]*f,(o.box[H+2]-re)*f]);const F=(H,u)=>[Math.min(...H.map(x=>x[u])),Math.max(...H.map(x=>x[u]))],O=[0,1,2].map(H=>F(m,H));if(w.slice(1).some(H=>{const u=[];for(let x=0;x+2<H.length;x+=3)u.push([H[x],H[x+1],H[x+2]]);return u.length>=3&&[0,1,2].every(x=>{const gt=F(u,x);return gt[0]<O[x][1]+.03&&O[x][0]<gt[1]+.03})})){typeof process<"u"&&((Oo=process.env)!=null&&Oo.RECIPE_TRACE)&&console.error(`[opening] ${o.key}: its wall's outline has its holes`);continue}}catch{}nt(o.key,{WallOpening:o.box.map((w,m)=>Ct((m%3===2?w-re:w)*f)).join(","),...z.get(o.host)?{HostMade:z.get(o.host)}:{}},{host:o.host})}if(r)for(const o of Zl(r,e.fileId))nt(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 Tn=0;const nc=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"&&!nc.has(String(h))||o.kind==="extrusion"&&h==="slab"&&ta(o)==="other"&&!/ Landing \d+$/.test(String(o.item.attrs.Name??""))||o.kind==="run"&&h!=="wall"&&h!=="curtainWall")&&Tn++}te();let ys=0;for(const[o,h]of z)!o.startsWith(`${e.fileId}:`)||wt.has(o)||(D.remove(h),ys++);if(D.length===0)throw new Ii(`Up to date: "${e.name}" holds ${tt} element(s) this recipe already made, ${En+Tn} waiting on the applier, and nothing is left to remove.`);const ic=[Xt?`${Xt} level(s)`:"",Kt?`${Kt} wall(s)`:"",Hs?`${Hs} 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)`:"",Gs?`${Gs} stair(s)`:"",Vs?`${Vs} column(s)`:"",zs?`${zs} instance(s)`:"",Ws?`${Ws} family instance(s)`:"",ct?`${ct} changed`:"",ys?`${ys} gone`:""].filter(Boolean);return{title:`${n==="ifc"?"IFC":"Model"} to Revit: ${ic.join(", ")}`,verb:D.summary,targets:D.length,payload:new Blob([await D.build(t.opId)]),ruleTallies:[{read:$.size,written:Xt},{read:X.length+Wt,written:Kt},{read:Ci,written:Hs},{read:ms.floor+ms.foundation,written:pe.floor+pe.foundation},{read:ms.roof,written:pe.roof},{read:ms.ceiling,written:pe.ceiling},{read:Oi,written:Gs},{read:Pi,written:Vs},{read:Li,written:zs},{read:gs.length,written:Ws},{read:ys,written:ys},{read:En+Tn,written:0}]}}}const ih={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}}},rh=[{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"}],Za=`
|
|
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
|
+
`,xi={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:ih,rules:rh,doc:Za,run:Xa("frag")},Qa={...xi,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
|
+
`+Za,run:Xa("ifc")},oh={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},tc="rhino-to-revit",ah=`recipe:${tc}`;function ch(n){const t=(n.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 ec={name:tc,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(
|
|
83
|
+
`,async run(n){var Tt;const{picked:t,contents:e}=await Mi(n,n.input),{layer:s,instanceType:i}=n.settings;if(!s||!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"?oh[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*rs,c=Ti(n),E=new wn({project:n.projectId,document:n.target.docId??"",baseCommit:n.target.version??0,author:ah});let b=0,$=0,P=0;const N=new Set,Y=[];for(const st of e.items){if(!st.guid||Object.keys(st.attrs).length===0)continue;if((st.attrs.Layer??"")!==s){P++;continue}const wt=ch(st);if(!wt)continue;N.add(st.guid);const Pt=[wt[0]*d,wt[1]*d,wt[2]*d],tt=c.get(st.guid);tt?Y.push({instance:tt,object:st.guid,position:Pt}):(E.add({CategoryId:i.categoryId,Family:i.family,Type:i.type},{position:Pt,source:st.guid}),b++)}for(const st of Y)E.set(st.instance,{},{position:st.position,source:st.object}),$++;let z=0;for(const[st,wt]of c)N.has(st)||(E.remove(wt),z++);const D=b+$+z;if(D===0)throw new Ii(`Nothing to write: layer "${s}" of "${t.name}" has no placed object, and nothing of this recipe is left to remove.`);return{title:`From Rhino: ${[b?`${b} new`:"",$?`${$} moved`:"",z?`${z} gone`:""].filter(Boolean).join(", ")}`,verb:E.summary,targets:D,payload:new Blob([await E.build(n.opId)]),ruleTallies:[{read:b,written:b},{read:$,written:$},{read:z,written:z},{read:P,written:0}]}}},sc=[ec,Qa,xi];function lh(n){for(const t of sc)n.recipes.register(t)}const hh={MAX_FIELDS:200,MAX_KEY_LENGTH:50,MAX_VALUE_LENGTH:50},fh={uuid:"a3f82c1d-5b74-4e9a-bc30-d7e12f894a61"},dh={uuid:"2c9f4e8d-3a1b-4c5e-9d7f-0a2b6c8e1d3f"},uh={uuid:"b0b5e2a2-0b3a-4a6b-8b1c-0b1c4a6b8b1c"},ph={uuid:"d8f3a1c2-6b4e-4f9a-8c1d-2e7b5a9f3c60"},mh={uuid:"3f9c1a7e-6b2d-4e18-9a5c-7d0e2f4b6c81"},gh={uuid:"2c4ae432-fc24-43e9-9783-0c960c674e96"},yh={uuid:"6f3a9c2e-8b1d-4e6a-9c3f-1d7b5a8e2c4f"},wh={uuid:"69af63aa-19ba-4fc7-b17b-75647bac1d76"},bh={uuid:"234f1416-528d-452a-9cc9-a16c5239b2eb"};exports.CDEManager=fh;exports.ChannelClient=za;exports.ChannelRoom=Si;exports.ClashesManager=dh;exports.CollabRoom=Ha;exports.DOCUMENT_FILE=Ss;exports.DOCUMENT_SCHEMA=ks;exports.DOCUMENT_TYPES=wi;exports.DocumentDrafts=Ca;exports.EngineServicesClient=pn;exports.ExternalRoom=Ga;exports.FileList=uh;exports.FlowDoc=Hn;exports.GISManager=ph;exports.GitHistoryManager=mh;exports.HelloWorld=gh;exports.METADATA_LIMITS=hh;exports.OP_SCHEMA=vi;exports.OperationBuilder=wn;exports.PROJECT_RECIPE_SCHEMA=$i;exports.PlatformClient=ci;exports.ProjectDocuments=bi;exports.ProjectHistory=mi;exports.ProjectManager=yh;exports.ProjectRecipes=ja;exports.RECIPE_NAME=La;exports.RecipeKit=Pa;exports.Recipes=Da;exports.RequestError=vn;exports.SELF_VIEWING_FORMATS=Ma;exports.STORAGE_BATCH_MAX=Zn;exports.StaleHistoryError=Un;exports.TopicsManager=wh;exports.UIManager=bh;exports.UpToDate=Ii;exports.builtinRecipes=sc;exports.compileRecipe=Xn;exports.describeChanges=xl;exports.documentTypeOf=Vn;exports.fragToRevit=xi;exports.ifcToRevit=Qa;exports.latestVersions=Ua;exports.mintGuid=yi;exports.orderByGraph=gi;exports.readFrag=bn;exports.registerBuiltinRecipes=lh;exports.rhinoToRevit=ec;exports.stampOf=un;exports.windowTransport=qa;
|
|
84
84
|
//# sourceMappingURL=index.cjs.js.map
|