@thatopen/services 0.35.1 → 0.36.1
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/README.md +66 -66
- package/dist/built-in/index.d.ts +13 -13
- package/dist/cli/lib/browser-session.d.ts +17 -0
- package/dist/cli/lib/config.d.ts +6 -0
- package/dist/cli.js +334 -38
- package/dist/cli.js.map +1 -1
- package/dist/core/browser-sign-in.d.ts +50 -0
- package/dist/core/browser-sign-in.test.d.ts +1 -0
- package/dist/core/builtin-recipes/index.d.ts +2 -2
- package/dist/core/builtin-recipes/layer-to-native.d.ts +19 -0
- package/dist/core/builtin-recipes/records-to-native.d.ts +43 -0
- package/dist/core/builtin-recipes/shapes-to-families.d.ts +9 -4
- package/dist/core/builtin-recipes/shared.d.ts +8 -11
- package/dist/core/channel.d.ts +1 -1
- package/dist/core/client.d.ts +46 -2
- package/dist/core/frag-items.d.ts +1 -1
- package/dist/core/history.d.ts +9 -9
- package/dist/core/op-builder.d.ts +2 -2
- package/dist/core/platform-client.d.ts +6 -3
- package/dist/core/project-recipes.d.ts +1 -1
- package/dist/core/recipes.d.ts +31 -5
- package/dist/index.cjs.js +23 -20
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.es.js +4284 -3455
- package/dist/index.es.js.map +1 -1
- package/dist/vite-env.d.ts +1 -1
- package/docs/ai-quickstart.md +548 -548
- package/docs/builtin/paths.json +130 -130
- package/docs/cli/create.md +29 -29
- package/docs/cli/local-server.md +38 -38
- package/docs/cli/login.md +35 -32
- package/docs/cli/mcp.md +46 -46
- package/docs/cli/publish.md +31 -31
- package/docs/cli/run.md +26 -26
- package/docs/cli/serve.md +43 -43
- package/docs/cli/swap.md +30 -30
- package/docs/client/paths.json +2 -2
- package/docs/cloud/GaussianSplatConverter.md +43 -43
- package/docs/cloud/PointCloudConverter.md +53 -53
- package/docs/flow-architecture.md +393 -393
- package/docs/flow-plugin-guide.md +354 -354
- package/docs/platform-token.md +81 -81
- package/docs/rate-limits.md +133 -133
- package/docs/recipes-guide.md +243 -243
- package/docs/revit-collab-quickstart.md +445 -445
- package/docs/rhino-interop-quickstart.md +387 -387
- package/docs/sheet-sets-guide.md +69 -69
- package/package.json +1 -1
- package/resources/AGENTS.md +57 -57
- package/src/built-in/CDEManager/example.ts +214 -214
- package/src/built-in/CDEManager/examples/FileEditing/example.ts +226 -226
- package/src/built-in/CDEManager/examples/FileMoves/example.ts +186 -186
- package/src/built-in/CDEManager/examples/FileOperations/example.ts +295 -295
- package/src/built-in/CDEManager/examples/FileTransfers/example.ts +210 -210
- package/src/built-in/CDEManager/examples/FolderManagement/example.ts +230 -230
- package/src/built-in/CDEManager/examples/MetadataSchema/example.ts +230 -230
- package/src/built-in/CDEManager/examples/MetadataViews/example.ts +166 -166
- package/src/built-in/CDEManager/examples/ProjectConfig/example.ts +177 -177
- package/src/built-in/ClashesManager/example.ts +283 -283
- package/src/built-in/GISManager/example.ts +355 -355
- package/src/built-in/ProjectManager/example.ts +124 -124
- package/src/built-in/UIManager/src/app/example.ts +97 -97
- package/src/built-in/UIManager/src/app/examples/AppState/example.ts +140 -140
- package/src/built-in/UIManager/src/app/examples/Banner/example.ts +159 -159
- package/src/built-in/UIManager/src/app/examples/Contexts/example.ts +123 -123
- package/src/built-in/UIManager/src/app/examples/FileDrop/example.ts +124 -124
- package/src/built-in/UIManager/src/app/examples/FloatingLayout/example.ts +90 -90
- package/src/built-in/UIManager/src/app/examples/Modal/example.ts +163 -163
- package/src/built-in/UIManager/src/app/examples/Notifications/example.ts +133 -133
- package/src/built-in/UIManager/src/app/examples/ProjectFileStorage/example.ts +150 -150
- package/src/built-in/UIManager/src/app/examples/Sidebar/example.ts +105 -105
- package/src/built-in/UIManager/src/clashes-panel/example.ts +183 -183
- package/src/built-in/UIManager/src/gis-panel/example.ts +163 -163
- package/src/built-in/UIManager/src/gis-properties-panel/example.ts +168 -168
- package/src/built-in/UIManager/src/git-history-panel/example.ts +70 -70
- package/src/built-in/UIManager/src/map-panel/example.ts +189 -189
- package/src/built-in/UIManager/src/models-list/example.ts +181 -181
- package/src/built-in/UIManager/src/settings-panel/example.ts +303 -303
- package/src/built-in/UIManager/src/topics-panel/example.ts +170 -170
- package/src/built-in/UIManager/src/viewer/example.ts +182 -182
- package/src/built-in/UIManager/src/viewer-toolbar/example.ts +376 -376
- package/src/built-in/index.ts +2995 -2995
- package/src/cli/templates/app/README.md +250 -250
- package/src/cli/templates/app/index.html +35 -35
- package/src/cli/templates/app/package.json +32 -32
- package/src/cli/templates/app/src/app.ts +37 -37
- package/src/cli/templates/app/src/assets/tool-placeholder.ts +50 -50
- package/src/cli/templates/app/src/bim-components/CloudRunner/index.ts +95 -95
- package/src/cli/templates/app/src/bim-components/CloudRunner/src/index.ts +1 -1
- package/src/cli/templates/app/src/bim-components/CloudRunner/src/types.ts +5 -5
- package/src/cli/templates/app/src/bim-components/index.ts +1 -1
- package/src/cli/templates/app/src/globals.ts +1 -1
- package/src/cli/templates/app/src/main.history.ts +191 -191
- package/src/cli/templates/app/src/main.ts +226 -226
- package/src/cli/templates/app/src/setups/channel.ts +76 -76
- package/src/cli/templates/app/src/setups/reality-capture/lib/hidden-tiles-plugin.ts +88 -88
- package/src/cli/templates/app/src/setups/reality-capture/lib/point-tile-plugin.ts +166 -166
- package/src/cli/templates/app/src/setups/reality-capture/lib/render-frame.ts +31 -31
- package/src/cli/templates/app/src/setups/reality-capture/lib/splat-tile-plugin.ts +51 -51
- package/src/cli/templates/app/src/setups/reality-capture-viewer.ts +1383 -1383
- package/src/cli/templates/app/src/ui-components/app-info-section/index.ts +26 -26
- package/src/cli/templates/app/src/ui-components/app-info-section/src/index.ts +1 -1
- package/src/cli/templates/app/src/ui-components/app-info-section/src/types.ts +15 -15
- package/src/cli/templates/app/src/ui-components/cloud-runner-section/index.ts +37 -37
- package/src/cli/templates/app/src/ui-components/cloud-runner-section/src/index.ts +1 -1
- package/src/cli/templates/app/src/ui-components/cloud-runner-section/src/types.ts +14 -14
- package/src/cli/templates/app/src/ui-components/index.ts +2 -2
- package/src/cli/templates/app/tsconfig.json +16 -16
- package/src/cli/templates/app/vite.config.js +57 -57
- package/src/cli/templates/cloud-component/README.md +205 -205
- package/src/cli/templates/cloud-component/_thatopen +5 -5
- package/src/cli/templates/cloud-component/declarations.json +4 -4
- package/src/cli/templates/cloud-component/package.json +21 -21
- package/src/cli/templates/cloud-component/src/main.ts +70 -70
- package/src/cli/templates/cloud-component/tsconfig.json +16 -16
- package/src/cli/templates/cloud-component/vite.config.js +46 -46
- package/src/cli/templates/shared/AGENTS.md +8 -8
- package/src/cli/templates/shared/CLAUDE.md +1 -1
- package/src/cli/templates/shared/_gitignore +5 -5
- package/src/core/examples/.env.example +7 -7
- package/src/core/examples/apps.ts +67 -67
- package/src/core/examples/batch-reads.ts +99 -99
- package/src/core/examples/channel.ts +65 -65
- package/src/core/examples/components.ts +91 -91
- package/src/core/examples/execution.ts +75 -75
- package/src/core/examples/file-metadata.ts +94 -94
- package/src/core/examples/files.ts +81 -81
- package/src/core/examples/folders.ts +82 -82
- package/src/core/examples/hidden-files.ts +88 -88
- package/src/core/examples/history.ts +103 -103
- package/src/core/examples/icons.ts +68 -68
- package/src/core/examples/permissions.ts +87 -87
- package/dist/core/builtin-recipes/records-to-revit.d.ts +0 -28
- package/dist/core/builtin-recipes/rhino-to-revit.d.ts +0 -16
package/dist/index.cjs.js
CHANGED
|
@@ -1,17 +1,20 @@
|
|
|
1
|
-
"use strict";var cc=Object.create;var $s=Object.defineProperty;var lc=Object.getOwnPropertyDescriptor;var hc=Object.getOwnPropertyNames;var fc=Object.getPrototypeOf,dc=Object.prototype.hasOwnProperty;var Po=s=>{throw TypeError(s)};var uc=(s,t,e)=>t in s?$s(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e;var pc=(s,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of hc(t))!dc.call(s,i)&&i!==e&&$s(s,i,{get:()=>t[i],enumerable:!(n=lc(t,i))||n.enumerable});return s};var Zn=(s,t,e)=>(e=s!=null?cc(fc(s)):{},pc(t||!s||!s.__esModule?$s(e,"default",{value:s,enumerable:!0}):e,s));var le=(s,t,e)=>uc(s,typeof t!="symbol"?t+"":t,e),Is=(s,t,e)=>t.has(s)||Po("Cannot "+e);var R=(s,t,e)=>(Is(s,t,"read from private field"),e?e.call(s):t.get(s)),Lt=(s,t,e)=>t.has(s)?Po("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(s):t.set(s,e),Vt=(s,t,e,n)=>(Is(s,t,"write to private field"),n?n.call(s,e):t.set(s,e),e),I=(s,t,e)=>(Is(s,t,"access private method"),e);var Ss=(s,t,e,n)=>({set _(i){Vt(s,t,i,e)},get _(){return R(s,t,n)}});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 ns=Object.create(null);Object.keys(_e).forEach(s=>{ns[_e[s]]=s});const Ls={type:"error",data:"parser error"},ra=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",oa=typeof ArrayBuffer=="function",aa=s=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(s):s&&s.buffer instanceof ArrayBuffer,di=({type:s,data:t},e,n)=>ra&&t instanceof Blob?e?n(t):Lo(t,n):oa&&(t instanceof ArrayBuffer||aa(t))?e?n(t):Lo(new Blob([t]),n):n(_e[s]+(t||"")),Lo=(s,t)=>{const e=new FileReader;return e.onload=function(){const n=e.result.split(",")[1];t("b"+(n||""))},e.readAsDataURL(s)};function Bo(s){return s instanceof Uint8Array?s:s instanceof ArrayBuffer?new Uint8Array(s):new Uint8Array(s.buffer,s.byteOffset,s.byteLength)}let xs;function mc(s,t){if(ra&&s.data instanceof Blob)return s.data.arrayBuffer().then(Bo).then(t);if(oa&&(s.data instanceof ArrayBuffer||aa(s.data)))return t(Bo(s.data));di(s,!1,e=>{xs||(xs=new TextEncoder),t(xs.encode(e))})}const Do="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",xn=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let s=0;s<Do.length;s++)xn[Do.charCodeAt(s)]=s;const gc=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=xn[s.charCodeAt(n)],a=xn[s.charCodeAt(n+1)],l=xn[s.charCodeAt(n+2)],p=xn[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},yc=typeof ArrayBuffer=="function",ui=(s,t)=>{if(typeof s!="string")return{type:"message",data:ca(s,t)};const e=s.charAt(0);return e==="b"?{type:"message",data:wc(s.substring(1),t)}:ns[e]?s.length>1?{type:ns[e],data:s.substring(1)}:{type:ns[e]}:Ls},wc=(s,t)=>{if(yc){const e=gc(s);return ca(e,t)}else return{base64:!0,data:s}},ca=(s,t)=>{switch(t){case"blob":return s instanceof Blob?s:new Blob([s]);case"arraybuffer":default:return s instanceof ArrayBuffer?s:s.buffer}},la="",bc=(s,t)=>{const e=s.length,n=new Array(e);let i=0;s.forEach((r,a)=>{di(r,!1,l=>{n[a]=l,++i===e&&t(n.join(la))})})},vc=(s,t)=>{const e=s.split(la),n=[];for(let i=0;i<e.length;i++){const r=ui(e[i],t);if(n.push(r),r.type==="error")break}return n};function Ec(){return new TransformStream({transform(s,t){mc(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 _s;function Qn(s){return s.reduce((t,e)=>t+e.length,0)}function ts(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 Tc(s,t){_s||(_s=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(Qn(e)<1)break;const p=ts(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(Qn(e)<2)break;const p=ts(e,2);i=new DataView(p.buffer,p.byteOffset,p.length).getUint16(0),n=3}else if(n===2){if(Qn(e)<8)break;const p=ts(e,8),d=new DataView(p.buffer,p.byteOffset,p.length),c=d.getUint32(0);if(c>Math.pow(2,21)-1){l.enqueue(Ls);break}i=c*Math.pow(2,32)+d.getUint32(4),n=3}else{if(Qn(e)<i)break;const p=ts(e,i);l.enqueue(ui(r?p:_s.decode(p),t)),n=0}if(i===0||i>s){l.enqueue(Ls);break}}}})}const ha=4;function oe(s){if(s)return Mc(s)}function Mc(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 ys=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")(),$c="arraybuffer";function fa(s,...t){return t.reduce((e,n)=>(s.hasOwnProperty(n)&&(e[n]=s[n]),e),{})}const Ic=we.setTimeout,Sc=we.clearTimeout;function ws(s,t){t.useNativeTimers?(s.setTimeoutFn=Ic.bind(we),s.clearTimeoutFn=Sc.bind(we)):(s.setTimeoutFn=we.setTimeout.bind(we),s.clearTimeoutFn=we.clearTimeout.bind(we))}const xc=1.33;function _c(s){return typeof s=="string"?Ac(s):Math.ceil((s.byteLength||s.size)*xc)}function Ac(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 da(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function Cc(s){let t="";for(let e in s)s.hasOwnProperty(e)&&(t.length&&(t+="&"),t+=encodeURIComponent(e)+"="+encodeURIComponent(s[e]));return t}function Rc(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 Oc extends Error{constructor(t,e,n){super(t),this.description=e,this.context=n,this.type="TransportError"}}class pi extends oe{constructor(t){super(),this.writable=!1,ws(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 Oc(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=ui(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=Cc(t);return e.length?"?"+e:""}}class kc extends pi{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)};vc(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,bc(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]=da()),!this.supportsBinary&&!e.sid&&(e.b64=1),this.createUri(t,e)}}let ua=!1;try{ua=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const Nc=ua;function Fc(){}class Pc extends kc{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,ws(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=fa(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=Fc,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",jo);else if(typeof addEventListener=="function"){const s="onpagehide"in we?"pagehide":"unload";addEventListener(s,jo,!1)}}function jo(){for(let s in xe.requests)xe.requests.hasOwnProperty(s)&&xe.requests[s].abort()}const Lc=function(){const s=pa({xdomain:!1});return s&&s.responseType!==null}();class Bc extends Pc{constructor(t){super(t);const e=t&&t.forceBase64;this.supportsBinary=Lc&&!e}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new xe(pa,this.uri(),t)}}function pa(s){const t=s.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!t||Nc))return new XMLHttpRequest}catch{}if(!t)try{return new we[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const ma=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class Dc extends pi{get name(){return"websocket"}doOpen(){const t=this.uri(),e=this.opts.protocols,n=ma?{}:fa(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;di(n,this.supportsBinary,r=>{try{this.doWrite(n,r)}catch{}i&&ys(()=>{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]=da()),this.supportsBinary||(e.b64=1),this.createUri(t,e)}}const As=we.WebSocket||we.MozWebSocket;class jc extends Dc{createSocket(t,e,n){return ma?new As(t,e,n):e?new As(t,e):new As(t)}doWrite(t,e){this.ws.send(e)}}class Uc extends pi{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=Tc(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=t.readable.pipeThrough(e).getReader(),i=Ec();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&&ys(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this._transport)===null||t===void 0||t.close()}}const Jc={websocket:jc,webtransport:Uc,polling:Bc},qc=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Hc=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Bs(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=qc.exec(s||""),r={},a=14;for(;a--;)r[Hc[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=Gc(r,r.path),r.queryKey=Vc(r,r.query),r}function Gc(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 Vc(s,t){const e={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(n,i,r){i&&(e[i]=r)}),e}const Ds=typeof addEventListener=="function"&&typeof removeEventListener=="function",ss=[];Ds&&addEventListener("offline",()=>{ss.forEach(s=>s())},!1);class We extends oe{constructor(t,e){if(super(),this.binaryType=$c,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=Bs(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=Bs(e.host).host);ws(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=Rc(this.opts.query)),Ds&&(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"})},ss.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(t){const e=Object.assign({},this.opts.query);e.EIO=ha,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+=_c(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,ys(()=>{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(),Ds&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const n=ss.indexOf(this._offlineEventListener);n!==-1&&ss.splice(n,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,e),this.writeBuffer=[],this._prevBufferLen=0}}}We.protocol=ha;class zc 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 Wc=class extends zc{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=>Jc[r]).filter(r=>!!r)),super(n?i:t,i)}};function Yc(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=Bs(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 Kc=typeof ArrayBuffer=="function",Xc=s=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(s):s.buffer instanceof ArrayBuffer,ga=Object.prototype.toString,Zc=typeof Blob=="function"||typeof Blob<"u"&&ga.call(Blob)==="[object BlobConstructor]",Qc=typeof File=="function"||typeof File<"u"&&ga.call(File)==="[object FileConstructor]";function mi(s){return Kc&&(s instanceof ArrayBuffer||Xc(s))||Zc&&s instanceof Blob||Qc&&s instanceof File}function is(s,t){if(!s||typeof s!="object")return!1;if(Array.isArray(s)){for(let e=0,n=s.length;e<n;e++)if(is(s[e]))return!0;return!1}if(mi(s))return!0;if(s.toJSON&&typeof s.toJSON=="function"&&arguments.length===1)return is(s.toJSON(),!0);for(const e in s)if(Object.prototype.hasOwnProperty.call(s,e)&&is(s[e]))return!0;return!1}function tl(s){const t=[],e=s.data,n=s;return n.data=js(e,t),n.attachments=t.length,{packet:n,buffers:t}}function js(s,t){if(!s)return s;if(mi(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]=js(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]=js(s[n],t));return e}return s}function el(s,t){return s.data=Us(s.data,t),delete s.attachments,s}function Us(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]=Us(s[e],t);else if(typeof s=="object")for(const e in s)Object.prototype.hasOwnProperty.call(s,e)&&(s[e]=Us(s[e],t));return s}const nl=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var zt;(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"})(zt||(zt={}));class sl{constructor(t){this.replacer=t}encode(t){return(t.type===zt.EVENT||t.type===zt.ACK)&&is(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=tl(t),n=this.encodeAsString(e.packet),i=e.buffers;return i.unshift(n),i}}class gi 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===zt.BINARY_EVENT;n||e.type===zt.BINARY_ACK?(e.type=n?zt.EVENT:zt.ACK,this.reconstructor=new il(e),e.attachments===0&&super.emitReserved("decoded",e)):super.emitReserved("decoded",e)}else if(mi(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(zt[n.type]===void 0)throw new Error("unknown packet type "+n.type);if(n.type===zt.BINARY_EVENT||n.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(!rl(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(gi.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 zt.CONNECT:return Uo(e);case zt.DISCONNECT:return e===void 0;case zt.CONNECT_ERROR:return typeof e=="string"||Uo(e);case zt.EVENT:case zt.BINARY_EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&nl.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 il{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=el(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const rl=Number.isInteger||function(s){return typeof s=="number"&&isFinite(s)&&Math.floor(s)===s};function Uo(s){return Object.prototype.toString.call(s)==="[object Object]"}const ol=Object.freeze(Object.defineProperty({__proto__:null,Decoder:gi,Encoder:sl,get PacketType(){return zt}},Symbol.toStringTag,{value:"Module"}));function Ee(s,t,e){return s.on(t,e),function(){s.off(t,e)}}const al=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class ya 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(al.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=(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: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(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 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 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: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 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 gn(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}gn.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};gn.prototype.reset=function(){this.attempts=0};gn.prototype.setMin=function(s){this.ms=s};gn.prototype.setMax=function(s){this.max=s};gn.prototype.setJitter=function(s){this.jitter=s};class Js 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,ws(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 gn({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||ol;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 Wc(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){ys(()=>{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 ya(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 En={};function kn(s,t){typeof s=="object"&&(t=s,s=void 0),t=t||{};const e=Yc(s,t.path||"/socket.io"),n=e.source,i=e.id,r=e.path,a=En[i]&&r in En[i].nsps,l=t.forceNew||t["force new connection"]||t.multiplex===!1||a;let p;return l?p=new Js(n,t):(En[i]||(En[i]=new Js(n,t)),p=En[i]),e.query&&!t.query&&(t.query=e.queryKey),p.socket(e.path,t)}Object.assign(kn,{Manager:Js,Socket:ya,io:kn,connect:kn});class qs 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 Jo="bimterop",Hs="revitflow_history.json",wa="revitflow_model.frag",ba="revitflow_",cl="bimterop-locks-anchor",Tn=new Map;function ll(s,t){return s.filter(e=>String(e.parentId??"")===t)}function hl(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,Pn,Ln,Gs;class yi{constructor(t,e){Lt(this,Ln);Lt(this,ve);Lt(this,Ye,new Map);Lt(this,ke);Lt(this,Pn,0);this.client=t,this.projectId=e}async docs(){const t=await I(this,Ln,Gs).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===wa)??p.find(E=>E.endsWith(".frag")&&!E.startsWith(ba)),c=p.includes(Hs)||!!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=R(this,Ye).get(n);return i||(i=new Vs(this.client,this,t,e),R(this,Ye).set(n,i)),i}document(t){const e=`platform-${t}`;let n=R(this,Ye).get(e);return n||(n=new Vs(this.client,this,"platform",t,t),R(this,Ye).set(e,n)),n}async childFolders(t,e=!1){return(e||!R(this,ke)||Date.now()-R(this,Pn)>3e4)&&(Vt(this,Pn,Date.now()),Vt(this,ke,this.client.listFolders({parentFolderId:t,projectId:this.projectId}).then(n=>ll(n,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,Ln,Gs).call(this);if(e)return e;if(!t)return;const n=await this.client.createFolder(Jo,void 0,this.projectId);return Vt(this,ve,Ie(n)),R(this,ve)}}ve=new WeakMap,Ye=new WeakMap,ke=new WeakMap,Pn=new WeakMap,Ln=new WeakSet,Gs=async function(){if(R(this,ve))return R(this,ve);const e=(await this.client.listFolders({projectId:this.projectId})).find(n=>String(n.name??"")===Jo&&!n.parentId);return e&&Vt(this,ve,Ie(e)),R(this,ve)};var Me,Et,Re,nn,Ue,$e,Bn,zs,rs,Je,va,Ea,os,Ta,Ma,$a;class Vs{constructor(t,e,n,i,r){Lt(this,Et);Lt(this,Me);Lt(this,$e);Lt(this,Bn,0);this.client=t,this.project=e,this.source=n,this.docId=i,Vt(this,Me,r)}async timeline(){const t=await I(this,Et,os).call(this);return wi((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 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),n=await R(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 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,nn),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 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 R(this,Et,Re).setDescriptor(t,i),await R(this,Et,Re).descriptor(t)}async ownership(){const t=await I(this,Et,rs).call(this,cl);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,os).call(this)??{model:this.docId,commits:[]};const i=qo(n.commits);if(t.expectedLatestGuid!==void 0&&(i==null?void 0:i.guid)!==t.expectedLatestGuid)throw new qs(t.expectedLatestGuid,i==null?void 0:i.guid);const r={guid:bi(),...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:fl(t.changes)};if(t.model&&(await I(this,Et,$a).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=hl(E)}const a=await I(this,Et,os).call(this);if(a){n=a;const c=qo(n.commits);if(t.expectedLatestGuid!==void 0&&(c==null?void 0:c.guid)!==t.expectedLatestGuid)throw new qs(t.expectedLatestGuid,c==null?void 0:c.guid);c&&!r.parents&&(r.parents=[c.guid])}return n.commits.push(r),await I(this,Et,Ta).call(this,e,Hs,n),r}}Me=new WeakMap,Et=new WeakSet,Re=function(){return new Ei(this.client,this.project.projectId)},nn=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 n=a=>a.find(l=>String(l.name??"")===R(this,Et,nn)),i=n(await this.project.childFolders(e))??n(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,nn)} does not exist in this project.`);const r=await this.client.createFolder(R(this,Et,nn),e,this.project.projectId);return this.project.forgetFolders(),Vt(this,Me,Ie(r)),R(this,Me)},$e=new WeakMap,Bn=new WeakMap,zs=async function(){return(!R(this,$e)||Date.now()-R(this,Bn)>5e3)&&(Vt(this,Bn,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(n=>({id:Ie(n),name:String(n.name??""),stamp:ps(n)})):[]})()),R(this,$e).catch(()=>{Vt(this,$e,void 0)})),R(this,$e)},rs=async function(t){try{return(await I(this,Et,zs).call(this)).find(e=>e.name===t)}catch{return}},Je=async function(){try{const t=await I(this,Et,zs).call(this);return t.find(e=>e.name===wa)??t.find(e=>e.name.endsWith(".frag")&&!e.name.startsWith(ba))}catch{return}},va=async function(t){const e=await I(this,Et,rs).call(this,t);if(!e)return;const n=e.stamp?Tn.get(e.id):void 0;if(n&&n.stamp===e.stamp)return structuredClone(await n.value);const i=I(this,Et,Ea).call(this,e,t);return e.stamp&&(Tn.set(e.id,{stamp:e.stamp,value:i}),i.catch(()=>{var r;((r=Tn.get(e.id))==null?void 0:r.value)===i&&Tn.delete(e.id)})),structuredClone(await i)},Ea=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)},os=function(){return I(this,Et,va).call(this,Hs)},Ta=async function(t,e,n){const i=new Blob([JSON.stringify(n)],{type:"application/json"}),r=await I(this,Et,rs).call(this,e);return r?(Tn.delete(r.id),await this.client.updateFile(r.id,{file:i,versionTag:await this.client.nextVersionTag(r.id)}),r):await I(this,Et,Ma).call(this,t,e,n)},Ma=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});Vt(this,$e,void 0);const a=r.item;return{id:Ie(a??r),name:e}},$a=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=`${R(this,Et,nn)}.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 fl(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 wi(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 qo(s){const t=wi(s);return t[t.length-1]}function bi(){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 vi={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"}},dl={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 Ws(s){var e;if(s.type&&s.type in vi)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?dl[n.toLowerCase()]:void 0;if(i)return i}return"generic"}const Fn="thatopen/document@1",_n="document.json",Ia=["pdf","txt","md","json","csv","tsv","frag"];function be(s){return String(s._id??s.id??"")}const tn=new Map;let Ho=!1;const ps=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,Sa,xa,Ys,_a,Aa,Ca,Ra,An;class Ei{constructor(t,e){Lt(this,se);this.client=t,this.projectId=e}async list(t){const e=await I(this,se,Sa).call(this),n=t==null?void 0:t.types;return n!=null&&n.length?e.filter(i=>n.includes(Ws(i.descriptor))):e}async fromFile(t,e){const n=await this.client.getFile(t),i=String(n.name??""),r=Cs(i,n.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=n.folderId?String(n.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,se,An).call(this,c))break}await this.client.updateFile(t,{parentFolderId:c});const E=[],b=await I(this,se,Aa).call(this,n);if(b)try{const N=await this.client.getFile(b);await this.client.updateFile(b,{parentFolderId:c}),E.push({fileId:b,format:Cs(String(N.name??""),N.fileExtension)})}catch{}((e==null?void 0:e.selfView)??Ia.includes(r))&&E.push({fileId:t,format:r});const P={schema:Fn,name:d,native:{fileId:t,format:r},views:E};return P.type=(e==null?void 0:e.type)??Ws(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 yi(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??Cs(e.name,void 0)},changes:[]})}async descriptor(t){const e=await I(this,se,An).call(this,t);return e?I(this,se,Ys).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:Fn,views:e.views??[]},i=new Blob([JSON.stringify(n)],{type:"application/json"}),r=await I(this,se,An).call(this,t);if(r){tn.delete(r.id),await this.client.updateFile(r.id,{file:i,versionTag:await this.client.nextVersionTag(r.id)});return}await this.client.createFile({file:i,name:_n,versionTag:"v1",parentFolderId:t,projectId:this.projectId})}drafts(t){return new Oa(this.client,()=>I(this,se,An).call(this,t))}}se=new WeakSet,Sa=async function(){const t=await I(this,se,xa).call(this);if(t)return t;const n=(await this.client.listFiles({projectId:this.projectId})).filter(r=>String(r.name??"")===_n);return(await Promise.all(n.map(async r=>{const a=r,l=String(a.folderId??a.parentFolderId??"");if(!l)return null;const p=await I(this,se,Ys).call(this,be(r),ps(r));return p?{folderId:l,descriptor:p}:null}))).filter(r=>r!==null)},xa=async function(){if(Ho)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 Ho=!0,null;throw n}const e=[];for(const n of(t==null?void 0:t.documents)??[]){const i=Vo(n.descriptor);!i||!n.folderId||(n.fileId&&n.versionTag&&tn.set(n.fileId,{stamp:n.versionTag,value:Promise.resolve(i)}),e.push({folderId:String(n.folderId),descriptor:i}))}return e},Ys=function(t,e){const n=e?tn.get(t):void 0;if(n&&n.stamp===e)return n.value;const i=I(this,se,_a).call(this,t);return e&&(tn.set(t,{stamp:e,value:i}),i.catch(()=>{var r;((r=tn.get(t))==null?void 0:r.value)===i&&tn.delete(t)})),i},_a=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 Vo(i)},Aa=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,Ra).call(this,t,e);if(i)return i;const r=String(t.name??"").replace(/\.[^.]+$/,"").toLowerCase();if(!r)return;n??(n=await this.client.listFiles({projectId:this.projectId}).catch(()=>[]));const a=d=>String(d.folderId??d.parentFolderId??""),l=new Set(n.filter(d=>String(d.name??"")===_n).map(a)),p=n.filter(d=>String(d.name??"").toLowerCase()===`${r}.frag`&&!d.archived&&be(d)!==be(t)&&!l.has(a(d)));for(const d of p){const c=await I(this,se,Ca).call(this,d);if(c===void 0||c===be(t))return be(d)}},Ca=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}},Ra=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{}},An=async function(t){if(!t)return;const n=(await this.client.listFiles({folderId:t,versions:!0})).find(i=>String(i.name??"")===_n);return n?{id:be(n),stamp:ps(n)}:void 0};const Ks="draft:",sn="TODRAFT1";var Se,Cn,Xs;class Oa{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 n of await I(this,Se,Cn).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,Cn).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 ml(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=ul(e.userId),r=(await I(this,Se,Cn).call(this,n.id)).filter(p=>p.userId===e.userId),l=(await this.client.createHiddenFile(await pl(t,e.meta??{}),n.id,i)).hiddenFileId;if(!l)throw new Error("The draft upload answered without a hiddenFileId.");return await I(this,Se,Xs).call(this,r.map(p=>p.hiddenId)),{userId:e.userId,savedAt:Go(l)}}async delete(t){const e=await this.holder();if(!e)return;const n=(await I(this,Se,Cn).call(this,e.id)).filter(i=>i.userId===t.userId);await I(this,Se,Xs).call(this,n.map(i=>i.hiddenId))}}Se=new WeakSet,Cn=async function(t){return(await this.client.getHiddenFilesByParent(t)).filter(n=>typeof n.tag=="string"&&n.tag.startsWith(Ks)).map(n=>{const i=String(n._id);return{hiddenId:i,userId:n.tag.slice(Ks.length),savedAt:Go(i)}})},Xs=async function(t){for(const e of t)try{await this.client.deleteHiddenFile(e)}catch{}};function ul(s){const t=`${Ks}${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 Go(s){const t=parseInt(s.slice(0,8),16);return new Date(Number.isFinite(t)?t*1e3:0)}async function pl(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(sn),n,e,s])}async function ml(s){const t=new Uint8Array(await s.slice(0,sn.length+4).arrayBuffer());if(new TextDecoder().decode(t.slice(0,sn.length))!==sn)return{meta:{},blob:s};const e=new DataView(t.buffer).getUint32(sn.length,!0),n=sn.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 Cs(s,t){const e=(t??"").replace(/^\./,"").toLowerCase();if(e)return e;const n=s.lastIndexOf(".");return n>0?s.slice(n+1).toLowerCase():""}function Vo(s){if(!s||typeof s!="object")return null;const t=s;if(t.schema!==Fn||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 vi?t.type:void 0,a={...t};return delete a.type,delete a.native,{...a,schema:Fn,name:t.name,...r?{type:r}:{},...i?{native:{fileId:n.fileId,format:n.format}}:{},views:e}}const gl="flow:",yl="flow:op",wl="flow:source",bl="flow:host",vl="flow:print",Ti="revitflow/op@2",zo="REVITFLOWCHANGE",Wo="REVITFLOWOPERATION";class bs{constructor(t){le(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:Ti,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 El();return Tl(this.flatbuffer(n,i,t,JSON.stringify(e)))}pack(t,e){const n={};for(const[i,r]of Object.entries(t??{}))i.startsWith(gl)&&i!==vl||(n[i]=String(r));return e.position&&(n.Position=e.position.map(Yo).join(",")),e.rotationDeg!==void 0&&(n.Rotation=Yo(e.rotationDeg)),e.source&&(n[wl]=e.source),e.host&&(n[bl]=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=$++,N=rt=>(rt(c,0),c.endVector()),Y=a.createShellsVector(c,[]),z=a.createCircleExtrusionsVector(c,[]),j=N(a.startSamplesVector),f=N(a.startRepresentationsVector),Tt=N(a.startMaterialsVector),nt=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,j),a.addLocalTransforms(c,nt),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),st=new Set,pt=[];for(const rt of this.changes){const _t=[],ie={[yl]:rt.op,...rt.attrs};for(const[Nt,he]of Object.entries(ie)){const me=JSON.stringify([Nt,he,"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 Dt=l.createAttributesVector(c,pt),Ht=l.createUniqueAttributesVector(c,[...st].map(rt=>c.createString(rt))),jt=this.changes.map(()=>c.createString(zo));jt.push(c.createString(Wo));const Xt=l.createCategoriesVector(c,jt),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(zo),0)),X=p.createSpatialStructure(c,P,c.createString(Wo),p.createChildrenVector(c,ut)),dt=c.createString(n);l.startModel(c),l.addMeshes(c,Yt),l.addMetadata(c,at),l.addAttributes(c,Dt),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 El(){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 Yo(s){return Number.isFinite(s)?String(s):"0"}async function Tl(s){const t=new Blob([s]).stream().pipeThrough(new CompressionStream("deflate"));return new Uint8Array(await new Response(t).arrayBuffer())}async function vs(s){const[t,e]=await Ml(),n=e.Model.getRootAsModel(new t.ByteBuffer(await $l(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 Ml(){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 $l(s){const t=new Blob([s]).stream().pipeThrough(new DecompressionStream("deflate"));return new Uint8Array(await new Response(t).arrayBuffer())}const ka="Element",Na="Carried",on=1/.3048;function Fa(s){const t=[];for(const e of s)for(const n of[ka,Na]){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 Il(s){const t=new Map;for(const[e,n]of Mi(s))t.set(e,n.name);return t}function Mi(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 Pa(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 $i(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 as(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 Ii(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=La(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 vs(e),site:i,shapes:r}}function La(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,N=0,Y=0]=i($[2]);let z=0;const j=b&&b!=="$"?e(b):null;if(j){const[Pt=1,tt=0]=i(j[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},nt=f?f[2]?Tt[f[2].toUpperCase()]??1:1:/IFCCONVERSIONBASEDUNIT\([^)]*\.LENGTHUNIT\.[^)]*'FOOT'/i.test(t)?.3048:1;return{east:P*nt,north:N*nt,elevation:Y*nt,angleDeg:z}}const Si="thatopen/recipe@1",Ko="__project_data",Xo="recipes",Sl=s=>`${s}.recipe.json`,Ba={OperationBuilder:bs,OP_SCHEMA:Ti,readFrag:vs,readPickedFrag:Ii,recordsOf:Fa,innerJson:de,levelsOf:Mi,levelNames:Il,stylesOf:Pa,printOf:as,siteLocationOf:La,whatItMadeBefore:$i,ELEMENT_FIELD:ka,CARRIED_FIELD:Na,FEET_PER_METRE:on},Da=/^[a-z0-9][a-z0-9-]{1,62}$/;async function ja(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===Ko&&!d.parentId));if(!r){if(!e)return null;r=await s.createFolder(Ko,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===Xo&&String(d.parentId)===a));if(!p){if(!e)return null;p=await s.createFolder(Xo,a,t)}return String(p._id)}const xl=s=>String(s._id??s.id??""),_l=s=>String(s.tag??s.versionTag??""),Zs=s=>{var t;return Number(((t=/(\d+)/.exec(s))==null?void 0:t[1])??-1)};async function Mn(s,t){const e=await ja(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:xl(r)})}return i}async function es(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)!==Si||!((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 $n(s,t){return(await s.listVersions(t)).map(n=>({tag:_l(n),createdAt:String(n.createdAt??"")})).filter(n=>n.tag).sort((n,i)=>Zs(n.tag)-Zs(i.tag))}var Dn;class Ua{constructor(t,e){Lt(this,Dn,new Map);this.client=t,this.builtinNames=e}async list(t){const e=await Mn(this.client,t);return(await Promise.all([...e.entries()].map(async([,{id:i}])=>{var r;try{const a=await $n(this.client,i),l=(r=a[a.length-1])==null?void 0:r.tag,p=await es(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 Mn(this.client,t)).get(e);if(!n)throw new Error(`The project has no recipe named "${e}".`);const i=await $n(this.client,n.id);return await Promise.all(i.map(async({tag:r,createdAt:a})=>{try{const l=await es(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 Mn(this.client,t)).get(e);if(!i)throw new Error(`The project has no recipe named "${e}".`);const r=n??((a=(await $n(this.client,i.id)).pop())==null?void 0:a.tag);if(!r)throw new Error(`The recipe "${e}" has no saved version.`);return{...await es(this.client,i.id,r),version:r}}async save(t,e,n){const{manifest:i,code:r}=e;if(!Da.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:Si,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 Mn(this.client,t)).get(i.name);if(p){const c=await $n(this.client,p.id),E=`v${Math.max(0,...c.map(b=>Zs(b.tag)))+1}`;return await this.client.createVersion(p.id,l,E),E}const d=await ja(this.client,t,!0);return await this.client.createFile({file:l,name:Sl(i.name),versionTag:"v1",projectId:t,parentFolderId:d}),"v1"}async load(t,e,n){var p;const i=(await Mn(this.client,t)).get(e);if(!i)throw new Error(`The project has no recipe named "${e}".`);const r=n??((p=(await $n(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,Dn).get(a);if(!l){const d=await es(this.client,i.id,r);l=await Qs(d.manifest,d.code),R(this,Dn).set(a,l)}return{recipe:l,version:r}}}Dn=new WeakMap;async function Qs(s,t){var i;let e;try{e=await import(`data:text/javascript;base64,${Al(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:Ba})}}function Al(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 Cl(s){const t=s instanceof Uint8Array?s:new Uint8Array(await s.arrayBuffer()),{items:e,metadata:n}=await vs(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 xi extends Error{constructor(t){super(t),this.name="UpToDate"}}var Ne,jn,Un;class Ja{constructor(t){Lt(this,Ne,new Map);Lt(this,jn,new Map);Lt(this,Un,new Map);le(this,"project");this.client=t,this.project=new Ua(t,()=>new Set(R(this,Ne).keys()))}provideImporter(t,e){R(this,jn).set(t.toLowerCase(),e)}provideShapes(t,e){R(this,Un).set(t.toLowerCase(),e)}shapesFor(t){return R(this,Un).get(t.toLowerCase())}importerFor(t){return R(this,jn).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(n=>(!(t!=null&&t.to)||n.to===t.to)&&(!(t!=null&&t.input)||n.inputs.includes(t.input)))}get(t){return R(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=R(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 qa(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??bi(),input:e.input,settings:e.settings??{},progress:e.progress??(()=>{})})}}Ne=new WeakMap,jn=new WeakMap,Un=new WeakMap;async function qa(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 ti=100;function Rl(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 Ol(s){if(!s||typeof s!="object")return;const t=s.retryAfter;return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}class Es extends Error{constructor(e,n,i,r){const a=Rl(i);super(a.message??`${n||"Request failed"} (${e})`);le(this,"status");le(this,"code");le(this,"details");le(this,"body");le(this,"retryAfter");this.name="RequestError",this.status=e,this.code=a.code,this.details=a.details,this.body=i,this.retryAfter=r??Ol(a.details)}}const Rs=()=>{if(typeof window>"u")return null;const s=window.__THATOPEN_CONTEXT__;return s&&typeof s.cacheSet=="function"?s:null};var cn;class Ha{constructor(){Lt(this,cn,new Map)}get(t){var n;const e=Rs();return e?(n=e.cache)==null?void 0:n[t]:R(this,cn).get(t)}set(t,e){const n=Rs();n?n.cacheSet(t,e):R(this,cn).set(t,e)}delete(t){var n;const e=Rs();e?(n=e.cacheDelete)==null||n.call(e,t):R(this,cn).delete(t)}answer(t,e){const n=this.get(t);return n&&n.projectId===e?n:void 0}keepAnswer(t,e,n){try{this.set(t,{projectId:e,value:n,at:Date.now()})}catch{}}}cn=new WeakMap;const Te="item/folder",Bt="item",Zo=12e3,De="processor",kl="npm-registry",Ae="hidden",Os="FILE",ks="TOOL",Ns="APP",Nl=500,Qo=3e4,Fl=2e3,Pl=15e3,Ll=s=>/^\/?project\/permissions\/check/.test(s),Bl=s=>/^\/?(item\/folder\/?$|item\/?$|item\/folder\/[^/]+\/items\/?$|project\/[^/]+\/data\/?$)/.test(s),In=new Map,Dl=.25,jl=s=>new Promise(t=>setTimeout(t,s));function Ul(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 Jl(s){return s instanceof Es?s.status===429||s.status>=500:!0}function ql(s,t){const e=Math.min(Nl*2**t,Qo),n=e*Dl*Math.random(),i=s instanceof Es&&s.retryAfter!=null?s.retryAfter*1e3:void 0;return i!=null?Math.min(i,Qo)+n:e+n}var q,cs,vt,ei,qe,ln,Ga,hn,gs,Jn,Ke,Xe,ls,qn,Rn,hs,fs,ni,si,ii;const Ci=class Ci{constructor(t,e,n){Lt(this,q);le(this,"apiUrl");le(this,"accessToken");le(this,"wsUrl");le(this,"retries");le(this,"useBearer");le(this,"builtInGlobals",null);le(this,"localServerUrl",null);le(this,"context");le(this,"cache",new Ha);Lt(this,ln,new Map);Lt(this,hn);Lt(this,gs,Date.now());Lt(this,Jn,!1);Lt(this,Ke,0);Lt(this,Xe,!1);Lt(this,qn);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 Ci(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,q,vt).call(this,t,e,n)}async listFiles(t){const{folderId:e,archived:n,projectId:i,versions:r}=t||{};if(e)return await I(this,q,vt).call(this,"GET",`${Te}/${e}/items`,{query:{itemType:Os,archived:n,...r&&{showVersions:!0}}});const a=await I(this,q,vt).call(this,"GET",`${Bt}`,{query:{itemType:Os,archived:n,...i&&{projectId:i}}});return i&&!n&&this.cache.keepAnswer("files",i,a),a}async listDocumentDescriptors(t){const e=R(this,ln).get(t);if(e)return await e;const n=I(this,q,Ga).call(this,t);R(this,ln).set(t,n);try{return await n}finally{R(this,ln).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,si).call(this,t,e)}async createFile(t){return await I(this,q,fs).call(this,t,Os)}async updateFile(t,e){return await I(this,q,ni).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,hs).call(this,t,e)}async getFileVersionMetadata(t,e,n){const{withDraft:i}=n||{};return await I(this,q,vt).call(this,"GET",`${Bt}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/metadata`,{query:{...i&&{withDraft:"true"}}})}async updateFileVersionMetadata(t,e,n){return await I(this,q,vt).call(this,"PUT",`${Bt}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/metadata`,{body:JSON.stringify({metadata:n}),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:n}=e||{};return await I(this,q,Rn).call(this,t,async i=>(await I(this,q,vt).call(this,"POST",`${Bt}/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,q,vt).call(this,"GET",Te,{query:{parentFolderId:n,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,Rn).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,n){return await I(this,q,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,q,vt).call(this,"PUT",`${Te}/${t}`,{body:JSON.stringify({name:n}),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:n,projectId:i}=t||{};return e?await I(this,q,vt).call(this,"GET",`${Te}/${e}/items`,{query:{itemType:ks,...n&&{ShowVersions:n}}}):await I(this,q,vt).call(this,"GET",`${Bt}`,{query:{itemType:ks,...n&&{ShowVersions:n},...i&&{projectId:i}}})}async getComponent(t,e){return await I(this,q,si).call(this,t,e)}async createComponent(t){const{componentProps:e}=t;return await I(this,q,fs).call(this,t,ks,e)}async updateComponent(t,e){const{componentProps:n}=e;return await I(this,q,ni).call(this,t,e,n)}async downloadComponent(t,e){return await I(this,q,hs).call(this,t,e)}async downloadComponentBundle(t,e){const{versionTag:n,withDraft:i}=e||{};return await I(this,q,qe).call(this,`${Bt}/${t}/download/bundle`,{query:{...n&&{versionTag:n},...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,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){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;if(i.Manager.init(),this.setBuiltInGlobals(t),await this.initBuiltInComponents(r,...e),r.init(),globalThis.__thatOpenShellSaysLoaded&&!R(this,hn)&&Vt(this,hn,this.holdAppLoaded()),Vt(this,Jn,!0),I(this,q,ls).call(this),!R(this,Xe)){const a=typeof performance<"u"?performance.now():Date.now()-R(this,gs);setTimeout(()=>{Vt(this,Ke,0),I(this,q,ls).call(this)},Math.max(0,Zo-a))}return{components:r}}holdAppLoaded(t=Zo){if(R(this,Xe))return()=>{};Ss(this,Ke)._++;let e=!1;const n=()=>{e||(e=!0,clearTimeout(i),Ss(this,Ke)._--,I(this,q,ls).call(this))},i=setTimeout(n,t);return n}appReady(){var t;(t=R(this,hn))==null||t.call(this)}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,q,vt).call(this,"GET",`${Te}/${e}/items`,{query:{itemType:Ns,...n&&{ShowVersions:n}}}):await I(this,q,vt).call(this,"GET",`${Bt}`,{query:{itemType:Ns,...n&&{ShowVersions:n},...i&&{projectId:i}}})}async createApp(t){const{appProps:e}=t;return await I(this,q,fs).call(this,t,Ns,e)}async downloadApp(t,e){return await I(this,q,hs).call(this,t,e)}async downloadAppBundle(t,e){const{versionTag:n,withDraft:i}=e||{};return await I(this,q,qe).call(this,`${Bt}/${t}/download/bundle`,{query:{...n&&{versionTag:n},...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",`${kl}/credentials`)}async executeComponent(t,e,n){if(this.localServerUrl){const i=`${this.localServerUrl}/api/${De}/${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",`${De}/${t}/execute`,{body:JSON.stringify(e),query:{...n&&{versionTag:n}},contentType:"application/json"})}async abortExecution(t){if(this.localServerUrl){const e=`${this.localServerUrl}/api/${De}/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,q,vt).call(this,"POST",`${De}/progress/${t}/abort`)}async listExecutions(t,e){if(this.localServerUrl){const n=e?`?projectId=${encodeURIComponent(e)}`:"",i=`${this.localServerUrl}/api/${De}/${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,q,vt).call(this,"GET",`${De}/${t}/progress`,{query:{...e&&{projectId:e}}})}async getExecution(t){if(this.localServerUrl){const e=`${this.localServerUrl}/api/${De}/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,q,vt).call(this,"GET",`${De}/progress/${t}`)}async onExecutionProgress(t,e){const n=this.localServerUrl??this.wsUrl,i=await kn(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 Ei(this,t)}history(t){return new yi(this,t)}get recipes(){return R(this,qn)??Vt(this,qn,new Ja(this)),R(this,qn)}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,q,vt).call(this,"POST",`${Bt}/${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,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,Rn).call(this,t,async n=>(await I(this,q,vt).call(this,"POST",`${Bt}/${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,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 n=new FormData;return n.append("icon",e),await I(this,q,vt).call(this,"PUT",`${Bt}/${t}/icon`,{body:n})}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,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,q,vt).call(this,"POST",`${Bt}/${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,q,vt).call(this,"GET",`${Bt}/${encodeURIComponent(t)}/versions`,{query:e})}async listVersionsBatch(t,e={}){const{archived:n}=e;return await I(this,q,Rn).call(this,t,async i=>(await I(this,q,vt).call(this,"POST",`${Bt}/batch/versions`,{body:JSON.stringify({itemIds:i,...n!==void 0&&{archived:n}}),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,cs=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,q,cs).call(this,e)}?${new URLSearchParams(I(this,q,ii).call(this,n==null?void 0:n.query)).toString()}`,r=Date.now(),a=In.get(i);if(a&&(a.pending||r-a.at<(Bl(e)?Pl:Fl)))return a.answer.then(p=>p===void 0?p:structuredClone(p));const l={at:r,pending:!0,answer:I(this,q,ei).call(this,t,e,n)};return In.set(i,l),l.answer.then(()=>{l.pending=!1,l.at=Date.now()},()=>{In.get(i)===l&&In.delete(i)}),l.answer.then(p=>p===void 0?p:structuredClone(p))}return t!=="GET"&&!Ll(e)&&In.clear(),I(this,q,ei).call(this,t,e,n)},ei=async function(t,e,n){const{body:i,query:r,contentType:a,retries:l,responseType:p,retryAttempt:d}=n||{},c=I(this,q,cs).call(this,e),E=I(this,q,ii).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 Es(P.status,P.statusText,N,Ul(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 jl(ql(P,Y)),await I(this,q,vt).call(this,t,e,{...n,retries:N-1,retryAttempt:Y+1})}throw P}},qe=async function(t,e){const{query:n}=e||{},i=I(this,q,cs).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,Ga=async function(t){const e=await I(this,q,vt).call(this,"GET",`${Bt}/documents`,{query:{projectId:t}});return this.cache.keepAnswer("documents",t,e),e},hn=new WeakMap,gs=new WeakMap,Jn=new WeakMap,Ke=new WeakMap,Xe=new WeakMap,ls=function(){var t,e;R(this,Xe)||!R(this,Jn)||R(this,Ke)>0||(Vt(this,Xe,!0),(e=(t=this.context.appEventOrchestrator)==null?void 0:t.appLoaded)==null||e.call(t))},qn=new WeakMap,Rn=async function(t,e){if(!t.length)return[];const n=[];for(let r=0;r<t.length;r+=ti)n.push(t.slice(r,r+ti));return(await Promise.all(n.map(e))).flat()},hs=async function(t,e){const{versionTag:n,withDraft:i}=e||{},r=await I(this,q,qe).call(this,`${Bt}/${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},fs=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,q,vt).call(this,"POST",Bt,{body:c})},ni=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,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}},si=async function(t,e){const{showVersions:n=!1}=e||{};return await I(this,q,vt).call(this,"GET",`${Bt}/${t}`,{query:{showVersions:n}})},ii=function(t){return t&&Object.entries(t).filter(([,e])=>e!==void 0).reduce((e,[n,i])=>(e[n]=i,e),{})};let ms=Ci;function Va(){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 ri="channel:",Hl=1e4;function ds(s){try{s()}catch(t){console.error("[channel] a listener threw:",t)}}var Fe,ge,ye,fn,dn,un,ue,oi,ai,rn;class _i{constructor(t,e){Lt(this,ue);Lt(this,Fe,!1);Lt(this,ge,[]);Lt(this,ye,[]);Lt(this,fn,new Set);Lt(this,dn,new Set);Lt(this,un,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,oi).call(this,"joined",this.controls.join)}leave(){return!R(this,Fe)&&!R(this,ye).some(t=>t.want==="joined")?Promise.resolve():I(this,ue,oi).call(this,"left",this.controls.leave)}onChange(t){return R(this,fn).add(t),()=>void R(this,fn).delete(t)}onPeerJoined(t){return R(this,dn).add(t),()=>void R(this,dn).delete(t)}onPeerLeft(t){return R(this,un).add(t),()=>void R(this,un).delete(t)}applyJoined(){Vt(this,Fe,!0),I(this,ue,ai).call(this,"joined"),I(this,ue,rn).call(this)}applyLeft(){Vt(this,Fe,!1),Vt(this,ge,[]),I(this,ue,ai).call(this,"left"),I(this,ue,rn).call(this)}applyPeers(t){Vt(this,ge,t),I(this,ue,rn).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,dn).forEach(e=>ds(()=>e(t))),I(this,ue,rn).call(this))}applyPeerLeft(t){const e=R(this,ge).find(n=>n.from===t);e&&(Vt(this,ge,R(this,ge).filter(n=>n.from!==t)),R(this,un).forEach(n=>ds(()=>n(e))),I(this,ue,rn).call(this))}failPending(t){const e=R(this,ye);return Vt(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,fn=new WeakMap,dn=new WeakMap,un=new WeakMap,ue=new WeakSet,oi=function(t,e){return new Promise((n,i)=>{const r={want:t,resolve:n,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.`))},Hl)};R(this,ye).push(r),this.transport.post({type:"APP_CHANNEL_CONTROL",...e})})},ai=function(t){const e=R(this,ye).filter(n=>n.want===t);Vt(this,ye,R(this,ye).filter(n=>n.want!==t)),e.forEach(n=>{clearTimeout(n.timer),n.resolve()})},rn=function(){R(this,fn).forEach(t=>ds(t))};var pn;class za extends _i{constructor(e){super(e,{join:{action:"joinCollab"},leave:{action:"leaveCollab"}});Lt(this,pn,new Map)}on(e,n){const i=R(this,pn).get(e)??new Set;return i.add(n),R(this,pn).set(e,i),()=>void i.delete(n)}send(e,n){if(e.startsWith(ri))throw new Error(`Message types starting with '${ri}' 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=R(this,pn).get(e.type);if(!(n!=null&&n.size))return{handled:!1};const i=Ya(e);return n.forEach(r=>ds(()=>r(e.payload,i))),{handled:!0}}}pn=new WeakMap;var He;class Wa extends _i{constructor(e,n){super(e,{join:{action:"joinExternal",kind:n},leave:{action:"leaveExternal",kind:n}});Lt(this,He,new Map);this.kind=n}on(e,n){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,n),()=>void R(this,He).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 R(this,He).size>0}async handle(e){const n=R(this,He).get(e.type);if(!n)return{handled:!1};try{return{handled:!0,value:await n(e.payload,Ya(e))}}catch(i){return{handled:!0,error:i instanceof Error?i.message:String(i)}}}}He=new WeakMap;function Ya(s){return{from:s.from,at:s.at,requestId:s.requestId,kind:s.kind}}function Gl(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 Ze,Hn,Pe,Ge,Ve,ce,ci,us,Xa,Za,Qa,li;class Ka{constructor(t){Lt(this,ce);Lt(this,Ze);Lt(this,Hn);Lt(this,Pe);Lt(this,Ge,new Map);Lt(this,Ve,new Set);Vt(this,Ze,t),Vt(this,Hn,t.listen(e=>void I(this,ce,Xa).call(this,e)))}collab(){return R(this,Pe)??Vt(this,Pe,new za(R(this,Ze))),R(this,Pe)}external(t){const e=t??"";let n=R(this,Ge).get(e);return n||(n=new Wa(R(this,Ze),t),R(this,Ge).set(e,n)),n}dispose(){R(this,Hn).call(this)}}Ze=new WeakMap,Hn=new WeakMap,Pe=new WeakMap,Ge=new WeakMap,Ve=new WeakMap,ce=new WeakSet,ci=function(){return[...R(this,Pe)?[R(this,Pe)]:[],...R(this,Ge).values()]},us=function(t,e){if(t==="collab")return R(this,Pe);if(t==="external")return R(this,Ge).get(typeof e=="string"?e:"")},Xa=async function(t){const e=Gl(t);if(e){if(e.type.startsWith(ri)){I(this,ce,Za).call(this,e);return}await I(this,ce,Qa).call(this,e)}},Za=function(t){var n,i,r;const e=t.payload??{};switch(t.type){case"channel:joined":(n=I(this,ce,us).call(this,e.scope,e.kind))==null||n.applyJoined();break;case"channel:left":(i=I(this,ce,us).call(this,e.scope,e.kind))==null||i.applyLeft();break;case"channel:peers":(r=I(this,ce,us).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,ci).call(this).map(p=>p.failPending(a)).some(Boolean)||console.error("[channel] error:",t.payload);break}}},Qa=async function(t){const e=I(this,ce,ci).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,li).call(this,t.requestId,a))}t.requestId&&t.scope==="external"&&e.length>0&&!n&&I(this,ce,li).call(this,t.requestId,{handled:!0,error:`No handler for "${t.type}".`})},li=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",en="notifications",Sn="tokens",Vl=6e4;var mn,Gn,ze;const Ri=class Ri extends ms{constructor(e,n,i){super(typeof e=="string"?e:"",n,{...i,useBearer:!0});Lt(this,mn);Lt(this,Gn);Lt(this,ze,new Map);typeof e=="function"&&Vt(this,mn,e)}async resolveAccessToken(){return R(this,mn)?await R(this,mn).call(this):super.resolveAccessToken()}static fromPlatformContext(e){const n=(typeof window<"u"?window.__THATOPEN_CONTEXT__:null)||{appId:"",projectId:"",accessToken:"",apiUrl:""},i=new Ri(n.accessToken,n.apiUrl,e);return i.context=n,i}get channel(){return R(this,Gn)??Vt(this,Gn,new Ka(Va())),R(this,Gn)}async listProjects(){return await this.request("GET",ae)}async getProject(e){return await this.request("GET",`${ae}/${e}`)}async getProjectData(e){const n=R(this,ze).get(e);if(n&&Date.now()-n.at<Vl)return await n.data;const i=this.request("GET",`${ae}/${e}/data`);return R(this,ze).set(e,{at:Date.now(),data:i}),i.then(r=>this.cache.keepAnswer("projectData",e,r),()=>{}),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,n,i){return e.toUpperCase()!=="GET"&&R(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",Sn)}async getTokenSecret(e){return await(await this.request("GET",`${Sn}/${e}/token`,{responseType:"blob"})).text()}async createToken(e){return await this.request("POST",Sn,{body:JSON.stringify({urlRestrictions:[],...e}),contentType:"application/json"})}async updateToken(e,n){return await this.request("PUT",`${Sn}/${e}`,{body:JSON.stringify(n),contentType:"application/json"})}async revokeToken(e){return await this.request("DELETE",`${Sn}/${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",en,{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",`${en}/unread-count`)).count}async markNotificationsRead(e){return await this.request("POST",`${en}/mark-read`,{body:JSON.stringify({ids:e}),contentType:"application/json"})}async markAllNotificationsRead(){return await this.request("POST",`${en}/mark-all-read`)}async getNotificationSubscriptions(){return await this.request("GET",`${en}/subscriptions`)}async unsubscribeFromAutomation(e){return await this.request("DELETE",`${en}/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=kn(`${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()}};mn=new WeakMap,Gn=new WeakMap,ze=new WeakMap;let hi=Ri;const Ce=1/.3048,zl={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"},Wl="OST_GenericModel",Yl=new Set(["IFCSPACE","IFCOPENINGELEMENT","IFCSITE","IFCANNOTATION","IFCGRID","IFCVIRTUALELEMENT","IFCBUILDING","IFCBUILDINGSTOREY"]),Oe=(s,t)=>Math.round(s/t)*t,Kl=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]]}),Nn=(s,t)=>s[0]*t[0]+s[1]*t[1]+s[2]*t[2],Fs=s=>Math.sqrt(Nn(s,s)),an=(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 Xl(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)||Yl.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":zl[b.ifcClass.toUpperCase()]??Wl,N=Kl(b.pieces[0].matrix),Y=Fs(N.x),z=Fs(N.y),j=Fs(N.z),f=N.z.map(U=>U/(j||1)),Tt=Math.abs(f[2]-1)<1e-6&&Nn(an(N.x,N.y),N.z)>0&&Math.abs(Y-z)<1e-6&&Math.abs(Y-j)<1e-6,nt=Nn(an(N.x,N.y),N.z)>0&&Math.abs(Y-z)<1e-6&&Math.abs(Y-j)<1e-6,wt=[N.x,N.y,N.z].map(U=>U.map(Z=>Z/(Y||1))),Pt=nt&&!Tt&&wt.some(U=>Math.abs(Math.abs(U[2])-1)<1e-6)?wt.find(U=>Math.abs(U[2])<1e-6):void 0,tt=Tt?Math.atan2(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=[],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 he=Z.verts[Nt],me=Z.verts[Nt+1],Le=Z.verts[Nt+2],re=[B[0]*he+B[4]*me+B[8]*Le+B[12],B[1]*he+B[5]*me+B[9]*Le+B[13],B[2]*he+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=Nn(an([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]];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?th(at[0]):null;if(pt){const U=Ql(pt),Z=U.key,B=`prism|${P}|${U.axis}|${Z}`;let ut=a.get(B);if(!ut){const he=ta(b.typeName??b.objectType??b.name??b.ifcClass),me=(l.get(he.toLowerCase())??0)+1;l.set(he.toLowerCase(),me);const Le=me===1?he:`${he} (${me})`;ut={family:Le,type:Le,first:!0,key:ea(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 Dt=`${P}|${at.map(U=>`${U.v.map(Z=>Math.round(Z*304.8/2)).join(",")}/${U.t.join(",")}`).join("|")}`,Ht=st.join("|");let jt=a.get(Ht)??a.get(Dt);if(jt&&(a.set(Ht,jt),a.set(Dt,jt)),!jt){const U=ta(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:ea(Dt)},a.set(Dt,jt),a.set(Ht,jt)}const Xt={ShapeCategory:P,Family:jt.family,Type:jt.type,ShapeKey:jt.key,...te?{ColumnFree:"1"}:{}};jt.first&&(Xt.Shape=JSON.stringify({pieces:at}),jt.first=!1);const Kt=b.host?r.get(b.host):void 0,Wt=b.opening?s.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=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=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=fi(s,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(he=>Oe(he,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=fi(s,Wt.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&&(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 ta(s){return(s.replace(/[\\:{}[\]|;<>?`~]/g,"-").replace(/\s+/g," ").trim()||"Shape").slice(0,120)}function ea(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 Zl(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 fi(s,l.gid)){const E=c.pts;if(E.length<4)continue;const b=nh(Qt(s,l.host));if(!b)continue;const $=E.map(j=>(j[0]-b.a[0])*b.u[0]+(j[1]-b.a[1])*b.u[1]),P=E.map(j=>-(j[0]-b.a[0])*b.u[1]+(j[1]-b.a[1])*b.u[0]),N=j=>Math.max(...j)-Math.min(...j),Y=N($)*N(P)*N(E.map(j=>j[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(j=>j[2])).toFixed(3)} up, axis ${JSON.stringify(b.u.map(j=>+j.toFixed(3)))})`);continue}const z=Qt(s,l.host).map(j=>-(j[0]-b.a[0])*b.u[1]+(j[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(j=>j[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 Ql(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)),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]),nt=Math.atan2($[(f+1)%$.length][1],$[(f+1)%$.length][0]),wt=Math.abs(Math.atan2(Math.sin(nt-Tt),Math.cos(nt-Tt)));if(Math.abs(wt-Y)>.1*Y)return $}const j=$.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)=>[N*Math.cos(j*2*Math.PI*Tt/$.length),N*Math.sin(j*2*Math.PI*Tt/$.length)])}),i=b=>b.map(P=>{const N=P.map(([z,j])=>`${Math.round(z*304.8)},${Math.round(j*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,j])=>[P*z-N*j,N*z+P*j]))},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 N=n.flat();for(const[nt,wt]of N)b+=nt*nt,$+=wt*wt,P+=nt*wt;const Y=new Set,z=.5*Math.atan2(2*P,b-$);for(let nt=0;nt<4;nt++)Y.add(z+nt*Math.PI/2);const j=N.map(([nt,wt])=>Math.hypot(nt,wt)),f=Math.max(...j),Tt=N.filter((nt,wt)=>j[wt]>f-.003);if(Math.abs(b-$)<.001*(b+$)||Tt.length>4)for(const[nt,wt]of Tt.slice(0,64))Y.add(Math.atan2(wt,nt));for(const nt of Y)a.push({loops:r(n,nt),turn:nt,flipped:!1})}else a.push({loops:d,turn:0,flipped:!1}),a.push({loops:d.map(b=>b.map(([$,P])=>[-$,P]).reverse()),turn:Math.PI,flipped:!0});let c=a[0],E=i(c.loops);for(const b of a.slice(1)){const $=i(b.loops);$<E&&(c=b,E=$)}return{axis:l,loops:c.loops,key:E,centre:e,turn:p+c.turn,flipped:c.flipped}}function th(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]],Yt=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])/Yt;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(Yt)<3e-4&&at.push({t:pt,id:st})}return[tt,...at.sort((st,pt)=>st.t-pt.t).map(st=>st.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 j=[],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){j.length=0;break}const te=ct.filter((Yt,at)=>{const st=ct[(at-1+ct.length)%ct.length],pt=ct[(at+1)%ct.length];return Math.abs((Yt[0]-st[0])*(pt[1]-st[1])-(Yt[1]-st[1])*(pt[0]-st[0]))>1e-7});j.push(te.map(([Yt,at])=>[Oe(Yt,1e-5),Oe(at,1e-5)]))}if(j.length===0||j.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 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=>!nt(Pt,tt))||[...Pt].some(tt=>!nt(wt,tt))))return{axis:i,from:r,length:a-r,loops:j}}return null}function eh(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],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}:${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 nh(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]),N=l.map(f=>-f[0]*$[1]+f[1]*$[0]),Y=Math.max(...P)-Math.min(...P),z=Math.max(...N)-Math.min(...N),j=Y*z;(!p||j<p.area-1e-9)&&(p={area:j,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])/n,(e[1]-t[1])/n]}}function fi(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 N=E.verts[P],Y=E.verts[P+1],z=E.verts[P+2],j=[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=j.map(nt=>Math.round(nt*1e4)).join(",");let Tt=r.get(f);Tt===void 0&&(Tt=n.length,r.set(f,Tt),n.push(j)),$.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,N]=[n[i[c]],n[i[c+1]],n[i[c+2]]];b.volume+=Nn($,an(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=>n[b]),volume:c.volume,index:E,of:d.length}))}function sh(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=N=>{const Y=b.verts[N*3],z=b.verts[N*3+1],j=b.verts[N*3+2];return[$[0]*Y+$[4]*z+$[8]*j+$[12],$[1]*Y+$[5]*z+$[9]*j+$[13],$[2]*Y+$[6]*z+$[10]*j+$[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 nt=0;nt<3;nt++){const wt=Y[nt],Pt=Y[(nt+1)%3],tt=l(wt)-i,ct=l(Pt)-i;if(tt<0==ct<0||tt===ct)continue;const ht=tt/(tt-ct);z.push([p(wt)+ht*(p(Pt)-p(wt)),wt[2]+ht*(Pt[2]-wt[2])])}if(z.length!==2)continue;const[j,f]=z;if((j[1]-r)*(f[1]-r)>0||j[1]===f[1])continue;const Tt=j[0]+(r-j[1])/(f[1]-j[1])*(f[0]-j[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 ih(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,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]},j=z(b.tris[Y]),f=z(b.tris[Y+1]),Tt=z(b.tris[Y+2]),nt=an([f[0]-j[0],f[1]-j[1],f[2]-j[2]],[Tt[0]-j[0],Tt[1]-j[1],Tt[2]-j[2]]),wt=Math.hypot(nt[0],nt[1],nt[2]);wt>P&&(P=wt,N=nt.map(Pt=>Pt/wt))}if(N&&Math.abs(N[0]*n[0]+N[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 Ps(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,Dt=Ht=>{const jt=st.verts[Ht*3],Xt=st.verts[Ht*3+1],Kt=st.verts[Ht*3+2];return[pt[0]*jt+pt[4]*Xt+pt[8]*Kt+pt[12],pt[1]*jt+pt[5]*Xt+pt[9]*Kt+pt[13],pt[2]*jt+pt[6]*Xt+pt[10]*Kt+pt[14]]};for(let Ht=0;Ht+2<st.tris.length;Ht+=3){const jt=Dt(st.tris[Ht]),Xt=Dt(st.tris[Ht+1]),Kt=Dt(st.tris[Ht+2]),Wt=an([Xt[0]-jt[0],Xt[1]-jt[1],Xt[2]-jt[2]],[Kt[0]-jt[0],Kt[1]-jt[1],Kt[2]-jt[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=((jt[0]+Xt[0]+Kt[0])/3-e[0])*p[0]+((jt[1]+Xt[1]+Kt[1])/3-e[1])*p[1];d.push({a:jt,b:Xt,c:Kt,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=(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);st.set(X,(st.get(X)??0)+1)}}const Dt=new Map;for(const[Wt,U]of st){if(U!==1)continue;const[Z,B]=Wt.split("|");(Dt.get(Z)??Dt.set(Z,[]).get(Z)).push(B),(Dt.get(B)??Dt.set(B,[]).get(B)).push(Z)}if(Dt.size<3||Dt.size>4e3)return null;const Ht=new Set;let jt=null,Xt=0;const Kt=[];for(const Wt of Dt.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=(Dt.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,jt=ut)}return jt?{best:jt,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 st=b(d.filter(pt=>Math.abs(pt.across-at)<.0025));st&&P&&st.bestArea>P.bestArea*1.2&&(P=st)}if(!P)return null;const{best:Y,allLoops:z}=P;if(!Y||Y.length<3)return null;const j=Math.min(...Y.map(at=>at[0])),f=Math.max(...Y.map(at=>at[0])),Tt=Math.min(...Y.map(at=>at[1])),nt=Math.max(...Y.map(at=>at[1]));if(!(f-j>.1)||!(nt-Tt>.1))return null;if(i){const at=Y.filter((U,Z,B)=>{const ut=B[(Z-1+B.length)%B.length],X=B[(Z+1)%B.length];return Math.abs((X[0]-ut[0])*(U[1]-ut[1])-(X[1]-ut[1])*(U[0]-ut[0]))>1e-4*Math.hypot(X[0]-ut[0],X[1]-ut[1])}),st=(U,Z)=>{let B=!1;for(let ut=0,X=Z.length-1;ut<Z.length;X=ut++)Z[ut][1]>U[1]!=Z[X][1]>U[1]&&U[0]<(Z[X][0]-Z[ut][0])*(U[1]-Z[ut][1])/(Z[X][1]-Z[ut][1])+Z[ut][0]&&(B=!B);return B},pt=U=>[U.reduce((Z,B)=>Z+B[0],0)/U.length,U.reduce((Z,B)=>Z+B[1],0)/U.length],Dt=z.filter(U=>U.pts!==Y&&U.area>=.01&&U.pts.length<=200&&(U.area>=.1||!st(pt(U.pts),Y))).map(U=>U.pts),Ht=Dt.filter(U=>!st(pt(U),Y)),jt=U=>{let Z=0;for(let B=0;B<U.length;B++){const ut=U[B],X=U[(B+1)%U.length];Z+=ut[0]*X[1]-X[0]*ut[1]}return Math.abs(Z)/2},Xt=$-Math.min(...d.map(U=>U.across));let Kt=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]);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=(jt(at)-Dt.filter(U=>!Ht.includes(U)).reduce((U,Z)=>U+jt(Z),0)+Ht.reduce((U,Z)=>U+jt(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:j,hi:f,bottom:Tt,chain:[],outline:at,holes:Dt.filter(U=>!Ht.includes(U)),pieces:Ht}:(at.length>4||Dt.length)&&at.length<=200?{lo:j,hi:f,bottom:Tt,chain:[],outline:at,holes:Dt}:null}const wt=at=>Y.map((st,pt)=>({p:st,i:pt})).filter(({p:st})=>Math.abs(st[0]-at)<.003).sort((st,pt)=>pt.p[1]-st.p[1])[0],Pt=wt(j),tt=wt(f);if(!Pt||!tt)return null;const ct=at=>{const st=[];for(let pt=Pt.i,Dt=0;Dt<=Y.length;pt=(pt+at+Y.length)%Y.length,Dt++)if(st.push(Y[pt]),pt===tt.i)return st;return null},ht=ct(1),kt=ct(-1),te=at=>at?at.reduce((st,pt)=>st+pt[1],0)/at.length:-1/0;let Yt=te(ht)>=te(kt)?ht:kt;if(!Yt||Yt.length<2||(Yt=Yt.filter((at,st,pt)=>{if(st===0||st===pt.length-1)return!0;const Dt=pt[st-1],Ht=pt[st+1];return Math.abs((Ht[0]-Dt[0])*(at[1]-Dt[1])-(Ht[1]-Dt[1])*(at[0]-Dt[0]))>1e-4*Math.hypot(Ht[0]-Dt[0],Ht[1]-Dt[1])}),Yt.every(at=>Math.abs(at[1]-nt)<.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:j,hi:f,bottom:Tt,chain:Yt}}function rh(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 z of n){const j=Math.hypot(z[0]-n[0][0],z[1]-n[0][1]);j>a&&(a=j,r=z)}a=0;for(const z of n){const j=Math.hypot(z[0]-r[0],z[1]-r[1]);j>a&&(a=j,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(...n.map(z=>z[2])),E=z=>Math.max(...n.filter(j=>Math.abs(d(j)-z)<.05).map(j=>j[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 j=Qt(s,z.gid);if(j.length===0)continue;const f=j.map(Pt=>Pt[0]),Tt=j.map(Pt=>Pt[1]),nt=j.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(...nt)-c;wt>1.5||Math.max(...nt)<c-.05||(!Y||Math.abs(wt)<Math.abs(Y.gap))&&(Y={id:z.id,gap:wt})}return Y==null?void 0:Y.id}const je={levels:"-2000240",walls:"-2000011",floors:"-2000032",roofs:"-2000035",ceilings:"-2000038",structuralFoundations:"-2001300",stairs:"-2000120"};function On(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 na(s){const t=On(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 sa=180/Math.PI;function ia(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 oh(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 tc(s){return async t=>{var Ui,Ji,qi,Hi,Gi,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,Dr,jr,Ur,Jr,qr,Hr,Gr,Vr,zr,Wr,Yr,Kr,Xr,Zr,Qr,to,eo,no,so,io,ro,oo,ao,co,lo,ho,fo,uo,po,mo,go,yo,wo,bo,vo,Eo,To,Mo,$o,Io,So,xo,_o,Ao,Co,Ro,Oo,ko,No;const{picked:e,contents:n,site:i,shapes:r}=await Ii(t,t.input),a=Fa(n.items),l=/CoordinateBase:\s*(Coordenadas compartidas|Shared Coordinates|Shared)/i.test(JSON.stringify(n.metadata??{})),p=l&&i?[i.east*on,i.north*on,i.elevation*on,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 $=Mi(a),P=Pa(a);if(typeof process<"u"&&((Ui=process.env)!=null&&Ui.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:${s}-to-revit`,Y=new Map,z=$i(t,Y);t.progress("Writing the changes for Revit");const j=new bs({project:t.projectId,document:t.target.docId??"",baseCommit:t.target.version??0,author:N}),f=on,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 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))j.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===as({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=as({attrs:m,placement:w??{}}),O=z.get(o);if(O){const k=Y.get(o);return!k||k===F?(tt++,!1):(j.remove(O),j.add({...m,"flow:print":F},{...w,source:o}),ct++,!1)}return ht?(kt.push({sourceKey:o,attrs:{...m,"flow:print":F},placement:w}),!0):(j.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},Dt=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])),jt=[...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:je.levels,Name:h.name,Elevation:Ct(h.at*f)},m=as({attrs:l?{...w,Frame:"shared",...p?{SharedAt:p}:{}}:w,placement:{}}),F=(Ji=[...Y].find(([O,k])=>k===m&&z.has(O)))==null?void 0:Ji[0];st(F??nt(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?[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=((Hi=(qi=h==null?void 0:h.run)==null?void 0:qi.line)==null?void 0:Hi.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 he=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=sh(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"&&((Vi=(Gi=process.env)==null?void 0:Gi.RECIPE_WALL)!=null&&Vi.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"&&((zi=process.env)!=null&&zi.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`),he.set(w,[...he.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"&&((Yi=(Wi=process.env)==null?void 0:Wi.RECIPE_WALL)!=null&&Yi.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,D=C==null?void 0:C.keep;if(!J||!D)return null;const W=y[0]*D[0]+y[1]*D[1];return Math.abs(W)<.5?null:((J[0]-S[0])*D[0]+(J[1]-S[1])*D[1])/W},T=h.params.wantedAtStart==="square"?g(u,(Ki=L.start)==null?void 0:Ki[0]):null,v=h.params.wantedAtEnd==="square"?g(x,(Xi=L.end)==null?void 0:Xi[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"&&((Zi=process.env)!=null&&Zi.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} ${H}: start ${T==null?void 0:T.toFixed(3)} end ${v==null?void 0:v.toFixed(3)}`),typeof process<"u"&&((er=(tr=process.env)==null?void 0:tr.RECIPE_WALL)!=null&&er.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},D=u;J(T)&&(u=[D[0]+y[0]*T,D[1]+y[1]*T],$t.add("start")),J(v)&&(x=[D[0]+y[0]*v,D[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:je.walls,Type:((nr=On(h))==null?void 0:nr.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=he.get(o);Ot&&(A.CutBy=Ot.flatMap(L=>{const _=`${nt(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)?oh(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"&&((sr=process.env)!=null&&sr.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),D=([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(D))&&(typeof process<"u"&&((ir=process.env)!=null&&ir.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(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,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(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(Jt=>Zt.includes(Jt));ne.length?A.Mitre=ne.join(","):delete A.Mitre}ot.length&&typeof process<"u"&&((rr=process.env)!=null&&rr.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,ne=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&&(ne=Ft+(Jt[1]-Ft)/(Jt[0]-Q)*(Zt-Q))}return[Zt,ne]}),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],ne=[ee[0]-Gt[0],ee[1]-Gt[1]],Jt=[Zt[0]-ee[0],Zt[1]-ee[1]];if((ne[0]*Jt[0]+ne[1]*Jt[1])/(Math.hypot(...ne)*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],[ne,Jt]=Q[Gt],fe=Ft(ne,Jt,ee),Be=Ft(ne,Jt,Zt),vn=Ft(ee,Zt,ne),Fo=Ft(ee,Zt,Jt);if((fe>1e-9&&Be<-1e-9||fe<-1e-9&&Be>1e-9)&&(vn>1e-9&&Fo<-1e-9||vn<-1e-9&&Fo>1e-9))return!1}return!0};let D=C(g,T);if(!J(D)){const ot=[[v,S],[0,0]].find(([Q,Ft])=>J(C(Q,Ft)));typeof process<"u"&&((or=process.env)!=null&&or.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"}`),D=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(D))y.push(M);if(A.Profile=JSON.stringify([y]),D.length===8){const M=D.map(([,Jt])=>Jt),ot=Math.max(...M),Q=Math.min(...M),Ft=D.map(([Jt])=>Jt),Ut=Math.min(...Ft),Gt=Math.max(...Ft),ee=D.filter(([Jt])=>Jt>Ut+.005&&Jt<Gt-.005),Zt=[...new Set(ee.map(([Jt])=>+Jt.toFixed(4)))].sort((Jt,fe)=>Jt-fe);if(D.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"&&((ar=process.env)!=null&&ar.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)?Dt(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,D)=>{const W=_(J);S.push(W[0]*f,W[1]*f,D*f)};C(0,v),C(L,v);for(const J of[...T].reverse()){const D=_(J);C(J,ft.zAt(D[0],D[1]))}A.Profile=JSON.stringify([S]),delete A.TopLevel,delete A.TopOffset}const mt=typeof St=="string"?St:r&&h.item.guid?rh(r,h.item.guid,jt):void 0;if(mt&&!A.Profile){A.AttachTop=nt(mt);const L=z.get(nt(mt));L&&(A.AttachTopMade=L)}if(mt&&typeof St!="string"&&typeof process<"u"&&((cr=process.env)!=null&&cr.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 _=Ps(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(D=>{const W=Qt(r,D.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(D=>D!==null),C=D=>{const W=Math.min(...D.map(Ft=>Ft[0])),M=Math.max(...D.map(Ft=>Ft[0])),ot=Math.min(...D.map(Ft=>Ft[1])),Q=Math.max(...D.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(D=>!C(D));_=!((lr=_.pieces)!=null&&lr.length)&&(J.length||_.outline.length>4)?{..._,holes:J}:null,_&&typeof process<"u"&&((hr=process.env)!=null&&hr.RECIPE_TRACE)&&console.error(`[wall-outline] ${h.item.guid}: ${L.length} hosted, ${J.length} empty hole(s) kept`)}const g=_!=null&&_.outline?null:Ps(r,h.item.guid,u,x);if(g){typeof process<"u"&&((fr=process.env)!=null&&fr.RECIPE_TRACE)&&console.error(`[wall-top] ${h.item.guid} ${h.item.name??""}: ${g.chain.map(([J,D])=>`${J.toFixed(2)}/${D.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,D)=>{S.push((u[0]+J*v[0])*f,(u[1]+J*v[1])*f,D*f)};C(g.lo,g.bottom-re),C(g.hi,g.bottom-re);for(const[J,D]of[...g.chain].reverse())C(J,D-re);A.Profile=JSON.stringify([S]),delete A.TopLevel,delete A.TopOffset}if(_!=null&&_.outline){typeof process<"u"&&((dr=process.env)!=null&&dr.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,D])=>[(u[0]+J*v[0])*f,(u[1]+J*v[1])*f,(D-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:Ps(r,h.item.guid,u,x,!0);if((ur=_==null?void 0:_.holes)!=null&&ur.length&&!((pr=_.pieces)!=null&&pr.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"&&((mr=process.env)!=null&&mr.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 D=0;for(let W=0;W<C.length;W++){const M=C[W],ot=C[(W+1)%C.length];D+=(M[0]*J[0]+M[1]*J[1])*ot[2]-(ot[0]*J[0]+ot[1]*J[1])*M[2]}return Math.abs(D)/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],D=[];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&&D.push(M),Q>=0!=Ft>=0){const Ut=Q/(Q-Ft);D.push([0,1,2].map(Gt=>M[Gt]+Ut*(ot[Gt]-M[Gt])))}}g=D}const S=g.length>=3?T(g):0;S>.05&&v-S>.05&&(typeof process<"u"&&((gr=process.env)!=null&&gr.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,D)=>{const W=L.filter(M=>{const ot=(M[0]-u[0])*y[0]+(M[1]-u[1])*y[1];return ot>=J*_&&ot<=D*_}).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,D=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*D*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"&&((wr=(yr=process.env)==null?void 0:yr.RECIPE_WALL)!=null&&wr.split(",").includes(h.item.guid??""))&&console.error(`[arc-bands] ${JSON.stringify({b0:v,bm:C,b1:S,sag:D,spread:M})}`),ot&&Math.abs(D)>.02&&Math.abs(D)<_/2){const Q=[(u[0]+x[0])/2+g[0]*D,(u[1]+x[1])/2+g[1]*D];A.LocationArc=`${Ct(Q[0]*f)},${Ct(Q[1]*f)},${Ct(It)}`,typeof process<"u"&&((br=process.env)!=null&&br.RECIPE_TRACE)&&console.error(`[wall-arc] ${h.item.guid} ${h.item.name??""}: bows ${(D*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"&&((vr=process.env)!=null&&vr.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]),D=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(...D),ot=Math.max(...D);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((D,W)=>{const M=ot=>+Ct(Math.round(ot*2e3)/2e3*f);W>0&&y[W-1][0]-D[1]>.003&&v.push([M(y[W-1][0]-D[1]),"","air"]),v.push([M(D[1]-D[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"&&((Er=process.env)!=null&&Er.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"&&((Tr=process.env)!=null&&Tr.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 D=Qt(r,h.item.guid);if(D.length<4)return[];const W=[Math.min(...D.map(M=>M[0])),Math.min(...D.map(M=>M[1])),Math.max(...D.map(M=>M[0])),Math.max(...D.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"&&((Mr=process.env)!=null&&Mr.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"&&(($r=process.env)!=null&&$r.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"&&((Ir=process.env)!=null&&Ir.RECIPE_TRACE)&&console.error(`[layer-extension] ${h.item.guid} ${A.Type}: top ${y}, base ${g}`)}}typeof process<"u"&&((xr=(Sr=process.env)==null?void 0:Sr.RECIPE_WALL)!=null&&xr.split(",").includes(h.item.guid??""))&&console.error(`[wall-attrs] ${JSON.stringify(A).slice(0,1500)} style ${JSON.stringify(((_r=P.get(H))==null?void 0:_r.params)??null).slice(0,800)}`),st(`${nt(h.id)}#${o.i}`,A)&&Kt++,w.forEach((L,_)=>{st(`${nt(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 Vn=0,Oi=0;const ki=new Map;for(const o of a){if(o.kind!=="run"||o.params.of!=="curtainWall")continue;Oi++;const h=de(o,"run"),w=(Rr=(Cr=(Ar=h==null?void 0:h.run)==null?void 0:Ar.line)==null?void 0:Cr.curves)==null?void 0:Rr[0],m=$.get(String((h==null?void 0:h.level)??o.params.level??"")),F=o.params.lookRef,O=typeof F=="string"?(Or=P.get(F))==null?void 0:Or.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]),D=C.map(W=>W[2]);return{t0:Math.min(...J),t1:Math.max(...J),z0:Math.min(...D),z1:Math.max(...D)}},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)),D=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-D)<.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"&&((kr=process.env)!=null&&kr.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=!((Nr=h.lines)!=null&&Nr.along)&&It.length>0&&(It.length!==St.length||It.some((y,g)=>Math.abs(y-St[g])>.01));it&&typeof process<"u"&&((Fr=process.env)!=null&&Fr.RECIPE_TRACE)&&console.error(`[curtain-lines] ${o.item.guid}: ${It.length} from its bars, not the type's ${St.length}`);const ft=((Pr=h.lines)==null?void 0:Pr.along)??(it?It:St),mt=((Lr=h.lines)==null?void 0:Lr.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 ih(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:je.walls,Type:((Br=On(o))==null?void 0:Br.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,D)=>{const W=_[(D+1)%_.length];return C+J[0]*W[1]-W[0]*J[1]},0)>0?1:-1,T=_.length,v=_.map((C,J)=>{const D=_[(J-1+T)%T],W=_[(J+1)%T],M=(Gt,ee)=>{const Zt=ee[0]-Gt[0],ne=ee[1]-Gt[1],Jt=Math.hypot(Zt,ne)||1,fe=g*ne/Jt,Be=-g*Zt/Jt,vn=Math.abs(fe)>Math.abs(Be)?gt:$t;return{p:[Gt[0]+fe*vn,Gt[1]+Be*vn],d:[Zt,ne]}},ot=M(D,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=(Dr=y.panel)!=null&&Dr.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=ki.get(L.Type);S===void 0?ki.set(L.Type,v):S!==v&&(typeof process<"u"&&((jr=process.env)!=null&&jr.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)&&Vn++}let zn=0,Ni=0;const Fi=(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;Ni++;const h=de(o,"stair"),w=o.params.lookRef,m=typeof w=="string"?(Ur=P.get(w))==null?void 0:Ur.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):(qr=(Jr=h.sketch)==null?void 0:Jr.risers)!=null&&qr.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"&&((Hr=process.env)!=null&&Hr.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):Fi(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"&&((Gr=process.env)!=null&&Gr.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]),D=(J[0]-xt[0])*L[0]+(J[1]-xt[1])*L[1];D>1e-4&&D<y&&(y=D,_=[T,v])}_&&G.unshift(_)}G.length!==yt.risers.length&&typeof process<"u"&&((Vr=process.env)!=null&&Vr.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"&&((zr=process.env)==null?void 0:zr.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 D=[V[(J+1)%V.length][0]-V[J][0],V[(J+1)%V.length][1]-V[J][1]],W=Math.hypot(D[0],D[1]);if(!(W>0)||Math.abs((D[0]*g[1]-D[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"&&((Wr=process.env)==null?void 0:Wr.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"&&((Yr=process.env)!=null&&Yr.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]],D=[C[0]-S[0],C[1]-S[1]],W=Math.hypot(J[0],J[1]),M=Math.hypot(D[0],D[1]);Math.abs((J[0]*D[1]-J[1]*D[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"&&((Kr=process.env)!=null&&Kr.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 ${Fi(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=(((Zr=(Xr=G==null?void 0:G.profile)==null?void 0:Xr.outline)==null?void 0:Zr.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:je.stairs,Type:((Qr=On(o))==null?void 0:Qr.type)??String(w),Level:F.name,Stairs:JSON.stringify(It)};typeof process<"u"&&(((to=process.env)==null?void 0:to.RECIPE_STAIR)===o.item.guid||((eo=process.env)==null?void 0:eo.RECIPE_STAIR)==="*")&&console.error(`[stair-spec] ${bt.Stairs} style ${JSON.stringify(m)}`),st(nt(o.id),bt)&&zn++}const Pi=new Map,yn={floor:0,foundation:0,roof:0,ceiling:0},pe={floor:0,foundation:0,roof:0,ceiling:0},Li=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":na(o);if(w==="other"||r&&o.item.guid&&/^IFCRAMP(FLIGHT)?$/i.test(((no=r.elements.get(o.item.guid))==null?void 0:no.ifcClass)??""))continue;const m=de(o,"extrusion"),F=m==null?void 0:m.on;if(F&&(Math.abs(((so=F.u)==null?void 0:so[2])??0)>.001||Math.abs(((io=F.v)==null?void 0:io[2])??0)>.001))continue;if(w==="roof"&&!Dt(o)){const lt=m,bt=((oo=(ro=m==null?void 0:m.profile)==null?void 0:ro.outline)==null?void 0:oo.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"&&((ao=process.env)!=null&&ao.RECIPE_TRACE)&&console.error(`[roof-as-floor] ${o.item.guid} ${o.params.lookRef}: its low side a corner, a sloped floor`))}}yn[w]++,typeof process<"u"&&((co=process.env)==null?void 0:co.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((ho=(lo=m==null?void 0:m.profile)==null?void 0:lo.outline)==null?void 0:ho.curves);if(typeof H!="string"||!k||!x)continue;const gt=[x],$t=w==="roof"?Dt(o):null;for(const lt of((fo=m==null?void 0:m.profile)==null?void 0:fo.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 Li)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,D=x[3*S]/f,W=x[3*S+1]/f;J>g!=W>g&&y<(D-C)*(g-J)/(W-J)+C&&(T=!T)}return T};if(!G.every(y=>et(y[0],y[1]))){typeof process<"u"&&((uo=process.env)!=null&&uo.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,D=Math.max(0,Math.min(1,((y[0]-g[0])*S+(y[1]-g[1])*C)/J));return Math.hypot(y[0]-(g[0]+D*S),y[1]-(g[1]+D*C))<.01}));if(xt||L){typeof process<"u"&&((po=process.env)!=null&&po.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"&&((mo=process.env)!=null&&mo.RECIPE_TRACE)&&console.error(`[slab-cut] ${o.item.guid} ${o.item.name??""}: a hole of ${G.length} corners`)}const A={CategoryId:w==="roof"?je.roofs:w==="ceiling"?je.ceilings:w==="foundation"?je.structuralFoundations:je.floors,Type:((go=On(o))==null?void 0:go.type)??H,Profile:JSON.stringify(gt),Level:k.name};let Ot=pt(H);if(w==="roof"&&r&&o.item.guid){const lt=(yo=r.elements.get(o.item.guid))==null?void 0:yo.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=Pi.get(A.Type);lt===void 0?Pi.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=`${nt(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"&&((wo=process.env)!=null&&wo.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??((bo=m==null?void 0:m.said)==null?void 0:bo.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),D=v-_>.01&&S-y>.01&&g-C>.01&&T-J>.01;A.EaveCut=D?"TwoCutSquare":"TwoCutPlumb",A.FasciaDepth=Ct((D?xt*Math.sqrt(1+V*V):xt)*f)}typeof process<"u"&&((vo=process.env)!=null&&vo.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"&&((Eo=process.env)!=null&&Eo.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((To=gt[0])==null?void 0:To.map(it=>+it.toFixed(2)))}`)}const K=w==="roof"?Dt(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=(($o=(Mo=m==null?void 0:m.profile)==null?void 0:Mo.outline)==null?void 0:$o.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"&&((Io=process.env)!=null&&Io.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=((xo=(So=m==null?void 0:m.profile)==null?void 0:So.outline)==null?void 0:xo.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"&&((_o=process.env)!=null&&_o.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)})`)}}}}st(nt(o.id),A)&&pe[w]++}let Wn=0,Bi=0;for(const o of a){if(o.kind!=="member"||o.params.of!=="column")continue;Bi++;const h=de(o,"member"),w=h==null?void 0:h.start;if(!w||w.length!==3)continue;const m=c?ia(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)??""));st(nt(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)*sa})&&Wn++}let Yn=0,Di=0,Ts=0;for(const o of a){if(o.kind!=="familyInstance")continue;if(o.params.host){Ts++;continue}if(Di++,!E)continue;const h=de(o,"instance"),w=(Ao=h==null?void 0:h.placement)==null?void 0:Ao.at;if(!w||w.length!==3)continue;const m=ia(o.params.type);if(!m)continue;const F=(Co=h==null?void 0:h.placement)==null?void 0:Co.right,O=F?Math.atan2(F[1],F[0])*sa:0;st(nt(o.id),{Family:m.family,Type:m.type},{position:[w[0]*f,w[1]*f,w[2]*f],rotationDeg:O})&&Yn++}Pt.size&&typeof process<"u"&&((Ro=process.env)!=null&&Ro.RECIPE_TRACE)&&console.error(`[shaped-panels] ${Pt.size} curtain panel(s) made as families of their shape`);const wn=r?Xl(r,wt,e.fileId,Pt).filter(o=>!Li.some(h=>h.guid&&o.key.includes(h.guid))):[];if(typeof process<"u"&&((Oo=process.env)!=null&&Oo.RECIPE_GID))for(const o of wn.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 Kn=0;const Xn=new Map;for(const o of wn){if(!o.attrs.Family||Xn.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&&Xn.set(o.attrs.Family,h)}const ji=new Set;for(const o of wn){const h=o.attrs.Family;!h||!Xn.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}:{}})&&ji.add(h)}for(const o of wn){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&&ji.has(h)&&!(o.attrs.Shape||o.attrs.Prism)&&!Yt(o.key,m,w)?{...o.attrs,...Xn.get(h)}:o.attrs;st(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}:{}})&&Kn++}if(r)for(const o of Zl(r,wt,e.fileId)){const h=(ko=at.get(o.host))==null?void 0:ko.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"&&((No=process.env)!=null&&No.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(","),...z.get(o.host)?{HostMade:z.get(o.host)}:{}},{host:o.host})}if(r)for(const o of eh(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 oc=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"&&!oc.has(String(h))||o.kind==="extrusion"&&h==="slab"&&na(o)==="other"&&!/ Landing \d+$/.test(String(o.item.attrs.Name??""))||o.kind==="run"&&h!=="wall"&&h!=="curtainWall")&&Ms++}te();let bn=0;for(const[o,h]of z)!o.startsWith(`${e.fileId}:`)||wt.has(o)||(j.remove(h),bn++);if(j.length===0)throw new xi(`Up to date: "${e.name}" holds ${tt} element(s) this recipe already made, ${Ts+Ms} waiting on the applier, and nothing is left to remove.`);const ac=[Xt?`${Xt} level(s)`:"",Kt?`${Kt} wall(s)`:"",Vn?`${Vn} 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)`:"",zn?`${zn} stair(s)`:"",Wn?`${Wn} column(s)`:"",Yn?`${Yn} instance(s)`:"",Kn?`${Kn} family instance(s)`:"",ct?`${ct} changed`:"",bn?`${bn} gone`:""].filter(Boolean);return{title:`${s==="ifc"?"IFC":"Model"} to Revit: ${ac.join(", ")}`,verb:j.summary,targets:j.length,payload:new Blob([await j.build(t.opId)]),ruleTallies:[{read:$.size,written:Xt},{read:X.length+Wt,written:Kt},{read:Oi,written:Vn},{read:yn.floor+yn.foundation,written:pe.floor+pe.foundation},{read:yn.roof,written:pe.roof},{read:yn.ceiling,written:pe.ceiling},{read:Ni,written:zn},{read:Bi,written:Wn},{read:Di,written:Yn},{read:wn.length,written:Kn},{read:bn,written:bn},{read:Ts+Ms,written:0}]}}}const ah={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}}},ch=[{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"}],ec=`
|
|
1
|
+
"use strict";var Dl=Object.create;var po=Object.defineProperty;var jl=Object.getOwnPropertyDescriptor;var Ul=Object.getOwnPropertyNames;var zl=Object.getPrototypeOf,ql=Object.prototype.hasOwnProperty;var rc=s=>{throw TypeError(s)};var Jl=(s,t,e)=>t in s?po(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e;var Gl=(s,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ul(t))!ql.call(s,o)&&o!==e&&po(s,o,{get:()=>t[o],enumerable:!(n=jl(t,o))||n.enumerable});return s};var Os=(s,t,e)=>(e=s!=null?Dl(zl(s)):{},Gl(t||!s||!s.__esModule?po(e,"default",{value:s,enumerable:!0}):e,s));var we=(s,t,e)=>Jl(s,typeof t!="symbol"?t+"":t,e),mo=(s,t,e)=>t.has(s)||rc("Cannot "+e);var H=(s,t,e)=>(mo(s,t,"read from private field"),e?e.call(s):t.get(s)),Wt=(s,t,e)=>t.has(s)?rc("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(s):t.set(s,e),ie=(s,t,e,n)=>(mo(s,t,"write to private field"),n?n.call(s,e):t.set(s,e),e),N=(s,t,e)=>(mo(s,t,"access private method"),e);var go=(s,t,e,n)=>({set _(o){ie(s,t,o,e)},get _(){return H(s,t,n)}});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const _o="services-sdk",Co=async(s,t)=>{const e=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!e.ok){const n=await e.text().catch(()=>"");let o=n;try{o=JSON.parse(n).message??n}catch{}throw new Error(o||`The platform answered ${e.status}`)}return await e.json()},Hl=(s,t)=>new Promise((e,n)=>{const o=setTimeout(e,s);t==null||t.addEventListener("abort",()=>{clearTimeout(o),n(new Error("Sign-in cancelled"))},{once:!0})}),Oo=(s,t)=>`${s.replace(/\/$/,"")}/api/connectors/device/${t}`;async function Cc(s){const{apiUrl:t,application:e,machine:n,version:o,onVerification:r,signal:a}=s,f=await Co(Oo(t,"start"),{application:e,machine:n,connectorId:_o});await r({url:f.verification_uri_complete,userCode:f.user_code,manualUrl:f.verification_uri});const g=Date.now()+f.expires_in*1e3;for(;Date.now()<g;){await Hl(f.interval*1e3,a);const d=await Co(Oo(t,"claim"),{deviceCode:f.device_code,connectorId:_o,pluginVersion:o});if(d.status==="confirmed")return{apiUrl:t,accessToken:d.accessToken,expiresAt:Date.now()+d.expiresIn*1e3,installId:d.installId,refreshToken:d.refreshToken}}throw new Error("The code expired before it was confirmed. Try again.")}async function Oc(s){const t=await Co(Oo(s.apiUrl,"refresh"),{installId:s.installId,refreshToken:s.refreshToken});return{...s,accessToken:t.accessToken,expiresAt:Date.now()+t.expiresIn*1e3,refreshToken:t.refreshToken}}const We=Object.create(null);We.open="0";We.close="1";We.ping="2";We.pong="3";We.message="4";We.upgrade="5";We.noop="6";const Ns=Object.create(null);Object.keys(We).forEach(s=>{Ns[We[s]]=s});const Ao={type:"error",data:"parser error"},Ac=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",Rc=typeof ArrayBuffer=="function",kc=s=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(s):s&&s.buffer instanceof ArrayBuffer,ir=({type:s,data:t},e,n)=>Ac&&t instanceof Blob?e?n(t):ic(t,n):Rc&&(t instanceof ArrayBuffer||kc(t))?e?n(t):ic(new Blob([t]),n):n(We[s]+(t||"")),ic=(s,t)=>{const e=new FileReader;return e.onload=function(){const n=e.result.split(",")[1];t("b"+(n||""))},e.readAsDataURL(s)};function ac(s){return s instanceof Uint8Array?s:s instanceof ArrayBuffer?new Uint8Array(s):new Uint8Array(s.buffer,s.byteOffset,s.byteLength)}let yo;function Vl(s,t){if(Ac&&s.data instanceof Blob)return s.data.arrayBuffer().then(ac).then(t);if(Rc&&(s.data instanceof ArrayBuffer||kc(s.data)))return t(ac(s.data));ir(s,!1,e=>{yo||(yo=new TextEncoder),t(yo.encode(e))})}const cc="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",es=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let s=0;s<cc.length;s++)es[cc.charCodeAt(s)]=s;const Wl=s=>{let t=s.length*.75,e=s.length,n,o=0,r,a,f,g;s[s.length-1]==="="&&(t--,s[s.length-2]==="="&&t--);const d=new ArrayBuffer(t),h=new Uint8Array(d);for(n=0;n<e;n+=4)r=es[s.charCodeAt(n)],a=es[s.charCodeAt(n+1)],f=es[s.charCodeAt(n+2)],g=es[s.charCodeAt(n+3)],h[o++]=r<<2|a>>4,h[o++]=(a&15)<<4|f>>2,h[o++]=(f&3)<<6|g&63;return d},Yl=typeof ArrayBuffer=="function",ar=(s,t)=>{if(typeof s!="string")return{type:"message",data:Fc(s,t)};const e=s.charAt(0);return e==="b"?{type:"message",data:Kl(s.substring(1),t)}:Ns[e]?s.length>1?{type:Ns[e],data:s.substring(1)}:{type:Ns[e]}:Ao},Kl=(s,t)=>{if(Yl){const e=Wl(s);return Fc(e,t)}else return{base64:!0,data:s}},Fc=(s,t)=>{switch(t){case"blob":return s instanceof Blob?s:new Blob([s]);case"arraybuffer":default:return s instanceof ArrayBuffer?s:s.buffer}},Nc="",Xl=(s,t)=>{const e=s.length,n=new Array(e);let o=0;s.forEach((r,a)=>{ir(r,!1,f=>{n[a]=f,++o===e&&t(n.join(Nc))})})},Zl=(s,t)=>{const e=s.split(Nc),n=[];for(let o=0;o<e.length;o++){const r=ar(e[o],t);if(n.push(r),r.type==="error")break}return n};function Ql(){return new TransformStream({transform(s,t){Vl(s,e=>{const n=e.length;let o;if(n<126)o=new Uint8Array(1),new DataView(o.buffer).setUint8(0,n);else if(n<65536){o=new Uint8Array(3);const r=new DataView(o.buffer);r.setUint8(0,126),r.setUint16(1,n)}else{o=new Uint8Array(9);const r=new DataView(o.buffer);r.setUint8(0,127),r.setBigUint64(1,BigInt(n))}s.data&&typeof s.data!="string"&&(o[0]|=128),t.enqueue(o),t.enqueue(e)})}})}let wo;function As(s){return s.reduce((t,e)=>t+e.length,0)}function Rs(s,t){if(s[0].length===t)return s.shift();const e=new Uint8Array(t);let n=0;for(let o=0;o<t;o++)e[o]=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 th(s,t){wo||(wo=new TextDecoder);const e=[];let n=0,o=-1,r=!1;return new TransformStream({transform(a,f){for(e.push(a);;){if(n===0){if(As(e)<1)break;const g=Rs(e,1);r=(g[0]&128)===128,o=g[0]&127,o<126?n=3:o===126?n=1:n=2}else if(n===1){if(As(e)<2)break;const g=Rs(e,2);o=new DataView(g.buffer,g.byteOffset,g.length).getUint16(0),n=3}else if(n===2){if(As(e)<8)break;const g=Rs(e,8),d=new DataView(g.buffer,g.byteOffset,g.length),h=d.getUint32(0);if(h>Math.pow(2,21)-1){f.enqueue(Ao);break}o=h*Math.pow(2,32)+d.getUint32(4),n=3}else{if(As(e)<o)break;const g=Rs(e,o);f.enqueue(ar(r?g:wo.decode(g),t)),n=0}if(o===0||o>s){f.enqueue(Ao);break}}}})}const Pc=4;function ye(s){if(s)return eh(s)}function eh(s){for(var t in ye.prototype)s[t]=ye.prototype[t];return s}ye.prototype.on=ye.prototype.addEventListener=function(s,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+s]=this._callbacks["$"+s]||[]).push(t),this};ye.prototype.once=function(s,t){function e(){this.off(s,e),t.apply(this,arguments)}return e.fn=t,this.on(s,e),this};ye.prototype.off=ye.prototype.removeListener=ye.prototype.removeAllListeners=ye.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,o=0;o<e.length;o++)if(n=e[o],n===t||n.fn===t){e.splice(o,1);break}return e.length===0&&delete this._callbacks["$"+s],this};ye.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,o=e.length;n<o;++n)e[n].apply(this,t)}return this};ye.prototype.emitReserved=ye.prototype.emit;ye.prototype.listeners=function(s){return this._callbacks=this._callbacks||{},this._callbacks["$"+s]||[]};ye.prototype.hasListeners=function(s){return!!this.listeners(s).length};const Zs=typeof Promise=="function"&&typeof Promise.resolve=="function"?t=>Promise.resolve().then(t):(t,e)=>e(t,0),Ne=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),nh="arraybuffer";function Lc(s,...t){return t.reduce((e,n)=>(s.hasOwnProperty(n)&&(e[n]=s[n]),e),{})}const sh=Ne.setTimeout,oh=Ne.clearTimeout;function Qs(s,t){t.useNativeTimers?(s.setTimeoutFn=sh.bind(Ne),s.clearTimeoutFn=oh.bind(Ne)):(s.setTimeoutFn=Ne.setTimeout.bind(Ne),s.clearTimeoutFn=Ne.clearTimeout.bind(Ne))}const rh=1.33;function ih(s){return typeof s=="string"?ah(s):Math.ceil((s.byteLength||s.size)*rh)}function ah(s){let t=0,e=0;for(let n=0,o=s.length;n<o;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 Bc(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function ch(s){let t="";for(let e in s)s.hasOwnProperty(e)&&(t.length&&(t+="&"),t+=encodeURIComponent(e)+"="+encodeURIComponent(s[e]));return t}function lh(s){let t={},e=s.split("&");for(let n=0,o=e.length;n<o;n++){let r=e[n].split("=");t[decodeURIComponent(r[0])]=decodeURIComponent(r[1])}return t}class hh extends Error{constructor(t,e,n){super(t),this.description=e,this.context=n,this.type="TransportError"}}class cr extends ye{constructor(t){super(),this.writable=!1,Qs(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 hh(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=ar(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=ch(t);return e.length?"?"+e:""}}class fh extends cr{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)};Zl(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,Xl(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]=Bc()),!this.supportsBinary&&!e.sid&&(e.b64=1),this.createUri(t,e)}}let Dc=!1;try{Dc=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const dh=Dc;function uh(){}class ph extends fh{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",(o,r)=>{this.onError("xhr post error",o,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 Ve extends ye{constructor(t,e,n){super(),this.createRequest=t,Qs(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=Lc(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 o in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(o)&&n.setRequestHeader(o,this._opts.extraHeaders[o])}}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 o;n.readyState===3&&((o=this._opts.cookieJar)===null||o===void 0||o.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(o){this.setTimeoutFn(()=>{this._onError(o)},0);return}typeof document<"u"&&(this._index=Ve.requestsCount++,Ve.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=uh,t)try{this._xhr.abort()}catch{}typeof document<"u"&&delete Ve.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()}}Ve.requestsCount=0;Ve.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",lc);else if(typeof addEventListener=="function"){const s="onpagehide"in Ne?"pagehide":"unload";addEventListener(s,lc,!1)}}function lc(){for(let s in Ve.requests)Ve.requests.hasOwnProperty(s)&&Ve.requests[s].abort()}const mh=function(){const s=jc({xdomain:!1});return s&&s.responseType!==null}();class gh extends ph{constructor(t){super(t);const e=t&&t.forceBase64;this.supportsBinary=mh&&!e}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new Ve(jc,this.uri(),t)}}function jc(s){const t=s.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!t||dh))return new XMLHttpRequest}catch{}if(!t)try{return new Ne[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const Uc=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class yh extends cr{get name(){return"websocket"}doOpen(){const t=this.uri(),e=this.opts.protocols,n=Uc?{}:Lc(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(o){return this.emitReserved("error",o)}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],o=e===t.length-1;ir(n,this.supportsBinary,r=>{try{this.doWrite(n,r)}catch{}o&&Zs(()=>{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]=Bc()),this.supportsBinary||(e.b64=1),this.createUri(t,e)}}const bo=Ne.WebSocket||Ne.MozWebSocket;class wh extends yh{createSocket(t,e,n){return Uc?new bo(t,e,n):e?new bo(t,e):new bo(t)}doWrite(t,e){this.ws.send(e)}}class bh extends cr{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=th(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=t.readable.pipeThrough(e).getReader(),o=Ql();o.readable.pipeTo(t.writable),this._writer=o.writable.getWriter();const r=()=>{n.read().then(({done:f,value:g})=>{f||(this.onPacket(g),r())}).catch(f=>{})};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],o=e===t.length-1;this._writer.write(n).then(()=>{o&&Zs(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this._transport)===null||t===void 0||t.close()}}const Eh={websocket:wh,webtransport:bh,polling:gh},vh=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Mh=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Ro(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 o=vh.exec(s||""),r={},a=14;for(;a--;)r[Mh[a]]=o[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=Th(r,r.path),r.queryKey=$h(r,r.query),r}function Th(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 $h(s,t){const e={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(n,o,r){o&&(e[o]=r)}),e}const ko=typeof addEventListener=="function"&&typeof removeEventListener=="function",Ps=[];ko&&addEventListener("offline",()=>{Ps.forEach(s=>s())},!1);class mn extends ye{constructor(t,e){if(super(),this.binaryType=nh,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=Ro(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=Ro(e.host).host);Qs(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 o=n.prototype.name;this.transports.push(o),this._transportsByName[o]=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=lh(this.opts.query)),ko&&(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"})},Ps.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(t){const e=Object.assign({},this.opts.query);e.EIO=Pc,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&&mn.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",mn.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 o=this.writeBuffer[n].data;if(o&&(e+=ih(o)),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,Zs(()=>{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,o){if(typeof e=="function"&&(o=e,e=void 0),typeof n=="function"&&(o=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),o&&this.once("flush",o),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(mn.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(),ko&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const n=Ps.indexOf(this._offlineEventListener);n!==-1&&Ps.splice(n,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,e),this.writeBuffer=[],this._prevBufferLen=0}}}mn.protocol=Pc;class Sh extends mn{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;mn.priorWebsocketSuccess=!1;const o=()=>{n||(e.send([{type:"ping",data:"probe"}]),e.once("packet",b=>{if(!n)if(b.type==="pong"&&b.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",e),!e)return;mn.priorWebsocketSuccess=e.name==="websocket",this.transport.pause(()=>{n||this.readyState!=="closed"&&(h(),this.setTransport(e),e.send([{type:"upgrade"}]),this.emitReserved("upgrade",e),e=null,this.upgrading=!1,this.flush())})}else{const w=new Error("probe error");w.transport=e.name,this.emitReserved("upgradeError",w)}}))};function r(){n||(n=!0,h(),e.close(),e=null)}const a=b=>{const w=new Error("probe error: "+b);w.transport=e.name,r(),this.emitReserved("upgradeError",w)};function f(){a("transport closed")}function g(){a("socket closed")}function d(b){e&&b.name!==e.name&&r()}const h=()=>{e.removeListener("open",o),e.removeListener("error",a),e.removeListener("close",f),this.off("close",g),this.off("upgrading",d)};e.once("open",o),e.once("error",a),e.once("close",f),this.once("close",g),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 xh=class extends Sh{constructor(t,e={}){const n=typeof t=="object",o=n?{...t}:{...e};(!o.transports||o.transports&&typeof o.transports[0]=="string")&&(o.transports=(o.transports||["polling","websocket","webtransport"]).map(r=>Eh[r]).filter(r=>!!r)),super(n?o:t,o)}};function Ih(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=Ro(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 _h=typeof ArrayBuffer=="function",Ch=s=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(s):s.buffer instanceof ArrayBuffer,zc=Object.prototype.toString,Oh=typeof Blob=="function"||typeof Blob<"u"&&zc.call(Blob)==="[object BlobConstructor]",Ah=typeof File=="function"||typeof File<"u"&&zc.call(File)==="[object FileConstructor]";function lr(s){return _h&&(s instanceof ArrayBuffer||Ch(s))||Oh&&s instanceof Blob||Ah&&s instanceof File}function Ls(s,t){if(!s||typeof s!="object")return!1;if(Array.isArray(s)){for(let e=0,n=s.length;e<n;e++)if(Ls(s[e]))return!0;return!1}if(lr(s))return!0;if(s.toJSON&&typeof s.toJSON=="function"&&arguments.length===1)return Ls(s.toJSON(),!0);for(const e in s)if(Object.prototype.hasOwnProperty.call(s,e)&&Ls(s[e]))return!0;return!1}function Rh(s){const t=[],e=s.data,n=s;return n.data=Fo(e,t),n.attachments=t.length,{packet:n,buffers:t}}function Fo(s,t){if(!s)return s;if(lr(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]=Fo(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]=Fo(s[n],t));return e}return s}function kh(s,t){return s.data=No(s.data,t),delete s.attachments,s}function No(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]=No(s[e],t);else if(typeof s=="object")for(const e in s)Object.prototype.hasOwnProperty.call(s,e)&&(s[e]=No(s[e],t));return s}const Fh=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var ce;(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"})(ce||(ce={}));class Nh{constructor(t){this.replacer=t}encode(t){return(t.type===ce.EVENT||t.type===ce.ACK)&&Ls(t)?this.encodeAsBinary({type:t.type===ce.EVENT?ce.BINARY_EVENT:ce.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id}):[this.encodeAsString(t)]}encodeAsString(t){let e=""+t.type;return(t.type===ce.BINARY_EVENT||t.type===ce.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=Rh(t),n=this.encodeAsString(e.packet),o=e.buffers;return o.unshift(n),o}}class hr extends ye{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===ce.BINARY_EVENT;n||e.type===ce.BINARY_ACK?(e.type=n?ce.EVENT:ce.ACK,this.reconstructor=new Ph(e),e.attachments===0&&super.emitReserved("decoded",e)):super.emitReserved("decoded",e)}else if(lr(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(ce[n.type]===void 0)throw new Error("unknown packet type "+n.type);if(n.type===ce.BINARY_EVENT||n.type===ce.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 f=Number(a);if(!Lh(f)||f<0)throw new Error("Illegal attachments");if(f>this.opts.maxAttachments)throw new Error("too many attachments");n.attachments=f}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 o=t.charAt(e+1);if(o!==""&&Number(o)==o){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(hr.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 ce.CONNECT:return hc(e);case ce.DISCONNECT:return e===void 0;case ce.CONNECT_ERROR:return typeof e=="string"||hc(e);case ce.EVENT:case ce.BINARY_EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&Fh.indexOf(e[0])===-1);case ce.ACK:case ce.BINARY_ACK:return Array.isArray(e)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class Ph{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=kh(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const Lh=Number.isInteger||function(s){return typeof s=="number"&&isFinite(s)&&Math.floor(s)===s};function hc(s){return Object.prototype.toString.call(s)==="[object Object]"}const Bh=Object.freeze(Object.defineProperty({__proto__:null,Decoder:hr,Encoder:Nh,get PacketType(){return ce}},Symbol.toStringTag,{value:"Module"}));function De(s,t,e){return s.on(t,e),function(){s.off(t,e)}}const Dh=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class qc extends ye{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=[De(t,"open",this.onopen.bind(this)),De(t,"packet",this.onpacket.bind(this)),De(t,"error",this.onerror.bind(this)),De(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,o,r;if(Dh.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:ce.EVENT,data:e};if(a.options={},a.options.compress=this.flags.compress!==!1,typeof e[e.length-1]=="function"){const h=this.ids++,b=e.pop();this._registerAckCallback(h,b),a.id=h}const f=(o=(n=this.io.engine)===null||n===void 0?void 0:n.transport)===null||o===void 0?void 0:o.writable,g=this.connected&&!(!((r=this.io.engine)===null||r===void 0)&&r._hasPingExpired());return this.flags.volatile&&!f||(g?(this.notifyOutgoingListeners(a),this.packet(a)):this.sendBuffer.push(a)),this.flags={},this}_registerAckCallback(t,e){var n;const o=(n=this.flags.timeout)!==null&&n!==void 0?n:this._opts.ackTimeout;if(o===void 0){this.acks[t]=e;return}const r=this.io.setTimeoutFn(()=>{delete this.acks[t];for(let f=0;f<this.sendBuffer.length;f++)this.sendBuffer[f].id===t&&this.sendBuffer.splice(f,1);e.call(this,new Error("operation has timed out"))},o),a=(...f)=>{this.io.clearTimeoutFn(r),e.apply(this,f)};a.withError=!0,this.acks[t]=a}emitWithAck(t,...e){return new Promise((n,o)=>{const r=(a,f)=>a?o(a):n(f);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((o,...r)=>(this._queue[0],o!==null?n.tryCount>this._opts.retries&&(this._queue.shift(),e&&e(o)):(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:ce.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 ce.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 ce.EVENT:case ce.BINARY_EVENT:this.onevent(t);break;case ce.ACK:case ce.BINARY_ACK:this.onack(t);break;case ce.DISCONNECT:this.ondisconnect();break;case ce.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(...o){n||(n=!0,e.packet({type:ce.ACK,id:t,data:o}))}}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:ce.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 Bn(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}Bn.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};Bn.prototype.reset=function(){this.attempts=0};Bn.prototype.setMin=function(s){this.ms=s};Bn.prototype.setMax=function(s){this.max=s};Bn.prototype.setJitter=function(s){this.jitter=s};class Po extends ye{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,Qs(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 Bn({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(e.timeout==null?2e4:e.timeout),this._readyState="closed",this.uri=t;const o=e.parser||Bh;this.encoder=new o.Encoder,this.decoder=new o.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 xh(this.uri,this.opts);const e=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const o=De(e,"open",function(){n.onopen(),t&&t()}),r=f=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",f),t?t(f):this.maybeReconnectOnOpen()},a=De(e,"error",r);if(this._timeout!==!1){const f=this._timeout,g=this.setTimeoutFn(()=>{o(),r(new Error("timeout")),e.close()},f);this.opts.autoUnref&&g.unref(),this.subs.push(()=>{this.clearTimeoutFn(g)})}return this.subs.push(o),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(De(t,"ping",this.onping.bind(this)),De(t,"data",this.ondata.bind(this)),De(t,"error",this.onerror.bind(this)),De(t,"close",this.onclose.bind(this)),De(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){Zs(()=>{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 qc(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(o=>{o?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",o)):t.onreconnect()}))},e);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const Yn={};function is(s,t){typeof s=="object"&&(t=s,s=void 0),t=t||{};const e=Ih(s,t.path||"/socket.io"),n=e.source,o=e.id,r=e.path,a=Yn[o]&&r in Yn[o].nsps,f=t.forceNew||t["force new connection"]||t.multiplex===!1||a;let g;return f?g=new Po(n,t):(Yn[o]||(Yn[o]=new Po(n,t)),g=Yn[o]),e.query&&!t.query&&(t.query=e.queryKey),g.socket(e.path,t)}Object.assign(is,{Manager:Po,Socket:qc,io:is,connect:is});class Lo 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 fc="bimterop",Bo="revitflow_history.json",Jc="revitflow_model.frag",Gc="revitflow_",jh="bimterop-locks-anchor",Kn=new Map;function Uh(s,t){return s.filter(e=>String(e.parentId??"")===t)}function zh(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 Ge(s){return String(s._id??s.id??"")}var Be,yn,Qe,hs,fs,Do;class fr{constructor(t,e){Wt(this,fs);Wt(this,Be);Wt(this,yn,new Map);Wt(this,Qe);Wt(this,hs,0);this.client=t,this.projectId=e}async docs(){const t=await N(this,fs,Do).call(this);if(!t)return[];const e=await this.childFolders(t,!0),n=[];for(const o of e){if(o.archived)continue;const r=String(o.name??""),a=r.indexOf("-");if(a<=0)continue;const g=(await this.client.listFiles({folderId:Ge(o)})).map(b=>String(b.name??"")),d=g.find(b=>b===Jc)??g.find(b=>b.endsWith(".frag")&&!b.startsWith(Gc)),h=g.includes(Bo)||!!d;n.push({source:r.slice(0,a),docId:r.slice(a+1),folderId:Ge(o),modelName:d,...h?{}:{empty:!0}})}return n}doc(t,e){const n=`${t}-${e}`;let o=H(this,yn).get(n);return o||(o=new jo(this.client,this,t,e),H(this,yn).set(n,o)),o}document(t){const e=`platform-${t}`;let n=H(this,yn).get(e);return n||(n=new jo(this.client,this,"platform",t,t),H(this,yn).set(e,n)),n}async childFolders(t,e=!1){return(e||!H(this,Qe)||Date.now()-H(this,hs)>3e4)&&(ie(this,hs,Date.now()),ie(this,Qe,this.client.listFolders({parentFolderId:t,projectId:this.projectId}).then(n=>Uh(n,t))),H(this,Qe).catch(()=>{ie(this,Qe,void 0)})),H(this,Qe)}forgetFolders(){ie(this,Qe,void 0)}async rootFolderId(t=!1){if(H(this,Be))return H(this,Be);const e=await N(this,fs,Do).call(this);if(e)return e;if(!t)return;const n=await this.client.createFolder(fc,void 0,this.projectId);return ie(this,Be,Ge(n)),H(this,Be)}}Be=new WeakMap,yn=new WeakMap,Qe=new WeakMap,hs=new WeakMap,fs=new WeakSet,Do=async function(){if(H(this,Be))return H(this,Be);const e=(await this.client.listFolders({projectId:this.projectId})).find(n=>String(n.name??"")===fc&&!n.parentId);return e&&ie(this,Be,Ge(e)),H(this,Be)};var qe,Dt,Xe,xn,an,Je,ds,Uo,Bs,cn,Hc,Vc,Ds,Wc,Yc,Kc;class jo{constructor(t,e,n,o,r){Wt(this,Dt);Wt(this,qe);Wt(this,Je);Wt(this,ds,0);this.client=t,this.project=e,this.source=n,this.docId=o,ie(this,qe,r)}async timeline(){const t=await N(this,Dt,Ds).call(this);return dr((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 N(this,Dt,cn).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,o=n?e.findIndex(h=>h.guid===n):e.length-1;if(o<0)throw new Error(`No version ${n} in this document's timeline.`);let r=0;for(let h=o;h>=0;h--)if(e[h].full){r=h;break}const a=await N(this,Dt,cn).call(this);if(!a)throw new Error(`Document ${this.source}-${this.docId} has no model file yet.`);const f=e[r],g=e.slice(o+1).some(h=>h.full),d=e.slice(r+1,o+1).map(h=>({guid:h.guid,...h.deltaId?{deltaId:h.deltaId}:{},...h.streamId?{streamId:h.streamId}:{},removedUniqueIds:h.changes.filter(b=>b.type==="delete").map(b=>b.uniqueId)}));return{baseline:{fileId:a.id,guid:f.guid,current:!g,...f.version!==void 0?{storageVersion:f.version}:{}},steps:d,at:e[o].guid}}async folderId(){return await N(this,Dt,an).call(this,!1)}async descriptor(){return await H(this,Dt,Xe).descriptor(await N(this,Dt,an).call(this,!1))}async view(t){const e=await N(this,Dt,an).call(this,!1),n=await H(this,Dt,Xe).descriptor(e);if(n){for(const r of t){const a=n.views.find(f=>f.format===r);if(a)return a}return null}if(!t.includes("frag"))return null;const o=await N(this,Dt,cn).call(this);return o?{fileId:o.id,format:"frag"}:null}async addView(t){const e=await N(this,Dt,an).call(this,!0);if(await H(this,Dt,Xe).descriptor(e)){await H(this,Dt,Xe).addView(e,t);return}const o=await N(this,Dt,cn).call(this);await H(this,Dt,Xe).setDescriptor(e,{name:(o==null?void 0:o.name.replace(/\.frag$/,""))??H(this,Dt,xn),views:[t]})}async ensureDescriptor(){const t=await N(this,Dt,an).call(this,!1),e=await H(this,Dt,Xe).descriptor(t);if(e)return e;const n=await N(this,Dt,cn).call(this);if(!n)return null;const o={name:n.name.replace(/\.frag$/,""),views:[{fileId:n.id,format:"frag"}]};return await H(this,Dt,Xe).setDescriptor(t,o),await H(this,Dt,Xe).descriptor(t)}async ownership(){const t=await N(this,Dt,Bs).call(this,jh);if(!t)return[];const e=await this.client.getHiddenFilesByParent(t.id),n=await Promise.all(e.map(async a=>{try{const f=Ge(a),g=await this.client.downloadHiddenFile(f),d=JSON.parse(await g.text());return!d||typeof d!="object"||!("revitflowlock"in d)||!Array.isArray(d.keys)?null:{owner:String(d.user??""),keys:d.keys.filter(h=>typeof h=="string")}}catch{return null}})),o=new Set,r=new Map;for(const a of n)if(a)for(const f of a.keys){if(!f||o.has(f))continue;o.add(f);const g=r.get(a.owner)??[];g.push(f),r.set(a.owner,g)}return[...r.entries()].map(([a,f])=>({owner:a,elements:f}))}async sync(t){var f,g,d;const e=await N(this,Dt,an).call(this,!0);let n=await N(this,Dt,Ds).call(this)??{model:this.docId,commits:[]};const o=dc(n.commits);if(t.expectedLatestGuid!==void 0&&(o==null?void 0:o.guid)!==t.expectedLatestGuid)throw new Lo(t.expectedLatestGuid,o==null?void 0:o.guid);const r={guid:ur(),...o?{parents:[o.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}:{},...(f=t.origins)!=null&&f.length?{origins:t.origins}:{},changes:t.changes,counts:qh(t.changes)};if(t.model&&(await N(this,Dt,Kc).call(this,e,t.model),r.full=!0),t.delta){const h=((g=await N(this,Dt,cn).call(this))==null?void 0:g.id)??((d=t.file)==null?void 0:d.fileId)??void 0;if(!h)throw new Error("A delta needs the model file to hang from: sync a full model first.");const b=await this.client.createHiddenFile(t.delta,h);r.deltaId=zh(b)}const a=await N(this,Dt,Ds).call(this);if(a){n=a;const h=dc(n.commits);if(t.expectedLatestGuid!==void 0&&(h==null?void 0:h.guid)!==t.expectedLatestGuid)throw new Lo(t.expectedLatestGuid,h==null?void 0:h.guid);h&&!r.parents&&(r.parents=[h.guid])}return n.commits.push(r),await N(this,Dt,Wc).call(this,e,Bo,n),r}}qe=new WeakMap,Dt=new WeakSet,Xe=function(){return new mr(this.client,this.project.projectId)},xn=function(){return`${this.source}-${this.docId}`},an=async function(t){if(H(this,qe))return H(this,qe);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(f=>String(f.name??"")===H(this,Dt,xn)),o=n(await this.project.childFolders(e))??n(await this.project.childFolders(e,!0));if(o)return ie(this,qe,Ge(o)),H(this,qe);if(!t)throw new Error(`Document ${H(this,Dt,xn)} does not exist in this project.`);const r=await this.client.createFolder(H(this,Dt,xn),e,this.project.projectId);return this.project.forgetFolders(),ie(this,qe,Ge(r)),H(this,qe)},Je=new WeakMap,ds=new WeakMap,Uo=async function(){return(!H(this,Je)||Date.now()-H(this,ds)>5e3)&&(ie(this,ds,Date.now()),ie(this,Je,(async()=>{const t=await N(this,Dt,an).call(this,!1);return t?(await this.client.listFiles({folderId:t,versions:!0})).map(n=>({id:Ge(n),name:String(n.name??""),stamp:Vs(n)})):[]})()),H(this,Je).catch(()=>{ie(this,Je,void 0)})),H(this,Je)},Bs=async function(t){try{return(await N(this,Dt,Uo).call(this)).find(e=>e.name===t)}catch{return}},cn=async function(){try{const t=await N(this,Dt,Uo).call(this);return t.find(e=>e.name===Jc)??t.find(e=>e.name.endsWith(".frag")&&!e.name.startsWith(Gc))}catch{return}},Hc=async function(t){const e=await N(this,Dt,Bs).call(this,t);if(!e)return;const n=e.stamp?Kn.get(e.id):void 0;if(n&&n.stamp===e.stamp)return structuredClone(await n.value);const o=N(this,Dt,Vc).call(this,e,t);return e.stamp&&(Kn.set(e.id,{stamp:e.stamp,value:o}),o.catch(()=>{var r;((r=Kn.get(e.id))==null?void 0:r.value)===o&&Kn.delete(e.id)})),structuredClone(await o)},Vc=async function(t,e){const n=await this.client.downloadFile(t.id);if(!n.ok)throw new Error(`Reading ${e} answered ${n.status}`);const o=await n.text();if(o.trim())return JSON.parse(o)},Ds=function(){return N(this,Dt,Hc).call(this,Bo)},Wc=async function(t,e,n){const o=new Blob([JSON.stringify(n)],{type:"application/json"}),r=await N(this,Dt,Bs).call(this,e);return r?(Kn.delete(r.id),await this.client.updateFile(r.id,{file:o,versionTag:await this.client.nextVersionTag(r.id)}),r):await N(this,Dt,Yc).call(this,t,e,n)},Yc=async function(t,e,n){const o=new Blob([JSON.stringify(n)],{type:"application/json"}),r=await this.client.createFile({file:o,name:e,versionTag:"v1",parentFolderId:t,projectId:this.project.projectId});ie(this,Je,void 0);const a=r.item;return{id:Ge(a??r),name:e}},Kc=async function(t,e){const n=await N(this,Dt,cn).call(this);if(n)return await this.client.updateFile(n.id,{file:e,versionTag:await this.client.nextVersionTag(n.id)}),n;const o=`${H(this,Dt,xn)}.frag`,r=await this.client.createFile({file:e,name:o,versionTag:"v1",parentFolderId:t,projectId:this.project.projectId});ie(this,Je,void 0);const a=r.item;return{id:Ge(a??r),name:o}};function qh(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 dr(s){var g;if(s.length<=1)return s.forEach((d,h)=>d.ordinal=h),[...s];const t=new Map(s.map(d=>[d.guid,d])),e=new Map,n=[];for(const d of s){const h=(g=d.parents)==null?void 0:g[0];if(h&&t.has(h)){const b=e.get(h)??[];b.push(d),e.set(h,b)}else n.push(d)}const o=(d,h)=>String(d.timestamp).localeCompare(String(h.timestamp));n.sort(o);const r=[],a=[...n].reverse(),f=new Set;for(;a.length;){const d=a.pop();if(f.has(d.guid))continue;f.add(d.guid),r.push(d);const h=(e.get(d.guid)??[]).sort(o);for(let b=h.length-1;b>=0;b--)a.push(h[b])}for(const d of s)f.has(d.guid)||r.push(d);return r.forEach((d,h)=>d.ordinal=h),r}function dc(s){const t=dr(s);return t[t.length-1]}function ur(){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 pr={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"}},Jh={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 zo(s){var e;if(s.type&&s.type in pr)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 o=n?Jh[n.toLowerCase()]:void 0;if(o)return o}return"generic"}const ls="thatopen/document@1",ns="document.json",Xc=["pdf","txt","md","json","csv","tsv","frag"];function Le(s){return String(s._id??s.id??"")}const $n=new Map;let uc=!1;const Vs=s=>{const t=s,e=[...t.versions??[]].sort((o,r)=>String(r.createdAt??"").localeCompare(String(o.createdAt??"")))[0],n=(e==null?void 0:e.tag)??t.versionTag;return n==null?void 0:String(n)};var pe,Zc,Qc,qo,tl,el,nl,sl,ss;class mr{constructor(t,e){Wt(this,pe);this.client=t,this.projectId=e}async list(t){const e=await N(this,pe,Zc).call(this),n=t==null?void 0:t.types;return n!=null&&n.length?e.filter(o=>n.includes(zo(o.descriptor))):e}async fromFile(t,e){const n=await this.client.getFile(t),o=String(n.name??""),r=Eo(o,n.fileExtension),a=(e==null?void 0:e.name)??o.replace(/\.[^.]+$/,"")??o,f=new Set((await this.list().catch(()=>[])).map(S=>String(S.descriptor.name??"").toLowerCase())),g=n.folderId?String(n.folderId):void 0;let d=a,h="";for(let S=1;S<100;S++){if(d=S===1?a:`${a} (${S})`,f.has(d.toLowerCase()))continue;const M=await this.client.createFolder(d,g,this.projectId);if(h=Le(M),!await N(this,pe,ss).call(this,h))break}await this.client.updateFile(t,{parentFolderId:h});const b=[],w=await N(this,pe,el).call(this,n);if(w)try{const S=await this.client.getFile(w);await this.client.updateFile(w,{parentFolderId:h}),b.push({fileId:w,format:Eo(String(S.name??""),S.fileExtension)})}catch{}((e==null?void 0:e.selfView)??Xc.includes(r))&&b.push({fileId:t,format:r});const P={schema:ls,name:d,native:{fileId:t,format:r},views:b};return P.type=(e==null?void 0:e.type)??zo(P),await this.setDescriptor(h,P),await this.recordUpload(h,{fileId:t,name:o,format:r},(e==null?void 0:e.author)??String(n.createdBy??"")),{folderId:h,descriptor:P}}async recordUpload(t,e,n){const o=new fr(this.client,this.projectId).document(t),r=(await o.timeline()).length===0;await o.sync({author:n||"unknown",source:"platform",kind:"upload",message:r?"Uploaded to the platform":"New version uploaded",file:{...e,format:e.format??Eo(e.name,void 0)},changes:[]})}async descriptor(t){const e=await N(this,pe,ss).call(this,t);return e?N(this,pe,qo).call(this,e.id,e.stamp):null}async view(t,e){const n=await this.descriptor(t);if(!n)return null;for(const o of e){const r=n.views.find(a=>a.format===o);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(o=>o.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:ls,views:e.views??[]},o=new Blob([JSON.stringify(n)],{type:"application/json"}),r=await N(this,pe,ss).call(this,t);if(r){$n.delete(r.id),await this.client.updateFile(r.id,{file:o,versionTag:await this.client.nextVersionTag(r.id)});return}await this.client.createFile({file:o,name:ns,versionTag:"v1",parentFolderId:t,projectId:this.projectId})}drafts(t){return new ol(this.client,()=>N(this,pe,ss).call(this,t))}}pe=new WeakSet,Zc=async function(){const t=await N(this,pe,Qc).call(this);if(t)return t;const n=(await this.client.listFiles({projectId:this.projectId})).filter(r=>String(r.name??"")===ns);return(await Promise.all(n.map(async r=>{const a=r,f=String(a.folderId??a.parentFolderId??"");if(!f)return null;const g=await N(this,pe,qo).call(this,Le(r),Vs(r));return g?{folderId:f,descriptor:g}:null}))).filter(r=>r!==null)},Qc=async function(){if(uc)return null;let t;try{t=await this.client.listDocumentDescriptors(this.projectId)}catch(n){const o=n.status;if(o===404||o===400||o===405)return uc=!0,null;throw n}const e=[];for(const n of(t==null?void 0:t.documents)??[]){const o=mc(n.descriptor);!o||!n.folderId||(n.fileId&&n.versionTag&&$n.set(n.fileId,{stamp:n.versionTag,value:Promise.resolve(o)}),e.push({folderId:String(n.folderId),descriptor:o}))}return e},qo=function(t,e){const n=e?$n.get(t):void 0;if(n&&n.stamp===e)return n.value;const o=N(this,pe,tl).call(this,t);return e&&($n.set(t,{stamp:e,value:o}),o.catch(()=>{var r;((r=$n.get(t))==null?void 0:r.value)===o&&$n.delete(t)})),o},tl=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 o;try{o=JSON.parse(n)}catch{return null}return mc(o)},el=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(h=>Le(h)===Le(t));e=(d==null?void 0:d.versions)??[]}const o=await N(this,pe,sl).call(this,t,e);if(o)return o;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??""),f=new Set(n.filter(d=>String(d.name??"")===ns).map(a)),g=n.filter(d=>String(d.name??"").toLowerCase()===`${r}.frag`&&!d.archived&&Le(d)!==Le(t)&&!f.has(a(d)));for(const d of g){const h=await N(this,pe,nl).call(this,d);if(h===void 0||h===Le(t))return Le(d)}},nl=async function(t){const n=[...t.versions??[]].sort((o,r)=>String(r.createdAt??"").localeCompare(String(o.createdAt??"")))[0];if(n)try{const o=await this.client.getFileVersionMetadata(Le(t),n.tag);return typeof(o==null?void 0:o.sourceIfcId)=="string"&&o.sourceIfcId?o.sourceIfcId:void 0}catch{return}},sl=async function(t,e){const n=[...e].sort((o,r)=>String(r.createdAt??"").localeCompare(String(o.createdAt??"")));for(const o of n)try{const r=await this.client.getFileVersionMetadata(Le(t),o.tag),a=r==null?void 0:r.derivedFileId;if(typeof a=="string"&&a)return a}catch{}},ss=async function(t){if(!t)return;const n=(await this.client.listFiles({folderId:t,versions:!0})).find(o=>String(o.name??"")===ns);return n?{id:Le(n),stamp:Vs(n)}:void 0};const Jo="draft:",In="TODRAFT1";var He,os,Go;class ol{constructor(t,e){Wt(this,He);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 N(this,He,os).call(this,t.id)){const o=e.get(n.userId);(!o||n.savedAt>o.savedAt)&&e.set(n.userId,{userId:n.userId,savedAt:n.savedAt})}return[...e.values()].sort((n,o)=>+o.savedAt-+n.savedAt)}async get(t){const e=await this.holder();if(!e)return null;const o=(await N(this,He,os).call(this,e.id)).filter(g=>!(t!=null&&t.userId)||g.userId===t.userId).sort((g,d)=>+d.savedAt-+g.savedAt)[0];if(!o)return null;const r=await this.client.downloadHiddenFile(o.hiddenId),{meta:a,blob:f}=await Vh(await r.blob());return{userId:o.userId,savedAt:o.savedAt,meta:a,blob:f}}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 o=Gh(e.userId),r=(await N(this,He,os).call(this,n.id)).filter(g=>g.userId===e.userId),f=(await this.client.createHiddenFile(await Hh(t,e.meta??{}),n.id,o)).hiddenFileId;if(!f)throw new Error("The draft upload answered without a hiddenFileId.");return await N(this,He,Go).call(this,r.map(g=>g.hiddenId)),{userId:e.userId,savedAt:pc(f)}}async delete(t){const e=await this.holder();if(!e)return;const n=(await N(this,He,os).call(this,e.id)).filter(o=>o.userId===t.userId);await N(this,He,Go).call(this,n.map(o=>o.hiddenId))}}He=new WeakSet,os=async function(t){return(await this.client.getHiddenFilesByParent(t)).filter(n=>typeof n.tag=="string"&&n.tag.startsWith(Jo)).map(n=>{const o=String(n._id);return{hiddenId:o,userId:n.tag.slice(Jo.length),savedAt:pc(o)}})},Go=async function(t){for(const e of t)try{await this.client.deleteHiddenFile(e)}catch{}};function Gh(s){const t=`${Jo}${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 pc(s){const t=parseInt(s.slice(0,8),16);return new Date(Number.isFinite(t)?t*1e3:0)}async function Hh(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(In),n,e,s])}async function Vh(s){const t=new Uint8Array(await s.slice(0,In.length+4).arrayBuffer());if(new TextDecoder().decode(t.slice(0,In.length))!==In)return{meta:{},blob:s};const e=new DataView(t.buffer).getUint32(In.length,!0),n=In.length+4,o=await s.slice(n,n+e).text();let r={};try{r=JSON.parse(o)}catch{}return{meta:r,blob:s.slice(n+e)}}function Eo(s,t){const e=(t??"").replace(/^\./,"").toLowerCase();if(e)return e;const n=s.lastIndexOf(".");return n>0?s.slice(n+1).toLowerCase():""}function mc(s){if(!s||typeof s!="object")return null;const t=s;if(t.schema!==ls||typeof t.name!="string")return null;const e=Array.isArray(t.views)?t.views.filter(f=>!!f&&typeof f=="object"&&typeof f.fileId=="string"&&typeof f.format=="string"):[],n=t.native,o=!!n&&typeof n=="object"&&typeof n.fileId=="string"&&typeof n.format=="string",r=typeof t.type=="string"&&t.type in pr?t.type:void 0,a={...t};return delete a.type,delete a.native,{...a,schema:ls,name:t.name,...r?{type:r}:{},...o?{native:{fileId:n.fileId,format:n.format}}:{},views:e}}const Wh="flow:",Yh="flow:op",Kh="flow:source",Xh="flow:host",Zh="flow:print",gr="revitflow/op@2",gc="REVITFLOWCHANGE",yc="REVITFLOWOPERATION";class to{constructor(t){we(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:gr,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,o]=await Qh();return tf(this.flatbuffer(n,o,t,JSON.stringify(e)))}pack(t,e){const n={};for(const[o,r]of Object.entries(t??{}))o.startsWith(Wh)&&o!==Zh||(n[o]=String(r));return e.position&&(n.Position=e.position.map(wc).join(",")),e.rotationDeg!==void 0&&(n.Rotation=wc(e.rotationDeg)),e.source&&(n[Kh]=e.source),e.host&&(n[Xh]=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,o){const{Attribute:r,Meshes:a,Model:f,SpatialStructure:g,Transform:d}=e,h=new t.Builder(1024),b=this.changes.length,w=new Uint32Array(b);let F=1;for(let ht=0;ht<b;ht++)w[ht]=F++;const P=F++,S=ht=>(ht(h,0),h.endVector()),M=a.createShellsVector(h,[]),v=a.createCircleExtrusionsVector(h,[]),G=S(a.startSamplesVector),vt=S(a.startRepresentationsVector),Mt=S(a.startMaterialsVector),St=S(a.startLocalTransformsVector),l=S(a.startGlobalTransformsVector),Ht=a.createMeshesItemsVector(h,[]),it=a.createMaterialIdsVector(h,[]),Tt=a.createRepresentationIdsVector(h,[]),$t=a.createSampleIdsVector(h,[]),ne=a.createLocalTransformIdsVector(h,[]),ee=a.createGlobalTransformIdsVector(h,[]);a.startMeshes(h),a.addCoordinates(h,d.createTransform(h,0,0,0,1,0,0,0,1,0)),a.addGlobalTransforms(h,l),a.addShells(h,M),a.addRepresentations(h,vt),a.addSamples(h,G),a.addLocalTransforms(h,St),a.addMaterials(h,Mt),a.addCircleExtrusions(h,v),a.addMeshesItems(h,Ht),a.addRepresentationIds(h,Tt),a.addSampleIds(h,$t),a.addMaterialIds(h,it),a.addLocalTransformIds(h,ne),a.addGlobalTransformIds(h,ee);const xt=a.endMeshes(h),lt=h.createString(o),Et=new Set,Rt=[];for(const ht of this.changes){const Qt=[],Yt={[Yh]:ht.op,...ht.attrs};for(const[Zt,me]of Object.entries(Yt)){const Gt=JSON.stringify([Zt,me,"IFCTEXT"]);Et.add(Gt),Qt.push(h.createString(Gt))}Rt.push(r.createAttribute(h,r.createDataVector(h,Qt)))}{const ht=JSON.stringify(["Name",n,"IFCLABEL"]);Et.add(ht);const Qt=r.createDataVector(h,[h.createString(ht)]);Rt.push(r.createAttribute(h,Qt))}const Jt=f.createAttributesVector(h,Rt),It=f.createUniqueAttributesVector(h,[...Et].map(ht=>h.createString(ht))),re=this.changes.map(()=>h.createString(gc));re.push(h.createString(yc));const he=f.createCategoriesVector(h,re),se=[],le=[];this.changes.forEach((ht,Qt)=>{ht.item&&(se.push(h.createString(ht.item)),le.push(w[Qt]))});const Ct=f.createGuidsVector(h,se),kt=f.createGuidsItemsVector(h,le),mt=f.createLocalIdsVector(h,[...w,P]),_t=this.changes.map((ht,Qt)=>g.createSpatialStructure(h,w[Qt],h.createString(gc),0)),ct=g.createSpatialStructure(h,P,h.createString(yc),g.createChildrenVector(h,_t)),qt=h.createString(n);f.startModel(h),f.addMeshes(h,xt),f.addMetadata(h,lt),f.addAttributes(h,Jt),f.addUniqueAttributes(h,It),f.addLocalIds(h,mt),f.addCategories(h,he),f.addGuidsItems(h,kt),f.addGuids(h,Ct),f.addGuid(h,qt),f.addSpatialStructure(h,ct),f.addMaxLocalId(h,F);const At=f.endModel(h);return f.finishModelBuffer(h,At),h.asUint8Array()}}async function Qh(){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 wc(s){return Number.isFinite(s)?String(s):"0"}async function tf(s){const t=new Blob([s]).stream().pipeThrough(new CompressionStream("deflate"));return new Uint8Array(await new Response(t).arrayBuffer())}async function eo(s){const[t,e]=await ef(),n=e.Model.getRootAsModel(new t.ByteBuffer(await nf(s)));let o={};try{o=JSON.parse(n.metadata()??"{}")}catch{}const r=new Map;for(let f=0;f<n.guidsLength();f++){const g=n.guidsItems(f),d=n.guids(f);g!==null&&d&&r.set(g,d)}const a=[];for(let f=0;f<n.attributesLength();f++){const g=n.localIds(f);if(g===null)continue;const d={},h=n.attributes(f);for(let b=0;b<((h==null?void 0:h.dataLength())??0);b++){const w=h.data(b);if(w)try{const[F,P]=JSON.parse(w);d[F]=P}catch{}}a.push({localId:g,guid:r.get(g)??null,category:n.categories(f)??null,attrs:d})}return{metadata:o,items:a}}async function ef(){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 nf(s){const t=new Blob([s]).stream().pipeThrough(new DecompressionStream("deflate"));return new Uint8Array(await new Response(t).arrayBuffer())}const rl="Element",il="Carried",sn=1/.3048;function al(s){const t=[];for(const e of s)for(const n of[rl,il]){const o=e.attrs[n];if(o)try{const r=JSON.parse(o);for(const a of Array.isArray(r)?r:[r]){const f=a;typeof(f==null?void 0:f.id)!="string"||typeof(f==null?void 0:f.kind)!="string"||t.push({id:f.id,kind:f.kind,params:f.params??{},item:e})}}catch{}}return t}function Ee(s,t){const e=s.params[t];if(typeof e!="string")return null;try{return JSON.parse(e)}catch{return null}}function sf(s){const t=new Map;for(const[e,n]of yr(s))t.set(e,n.name);return t}function yr(s){const t=new Map;for(const e of s){if(e.kind!=="datum"||e.params.of!=="level")continue;const n=e.params.named,o=e.params.at;typeof n=="string"&&typeof o=="number"&&t.set(e.id,{name:n,at:o})}return t}function cl(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 Ws(s,t){const e=new Map;for(const[n,o]of s.made)e.set(n,o.id),o.print&&(t==null||t.set(n,o.print));return e}function js(s){const t=o=>Array.isArray(o)?o.map(t):o&&typeof o=="object"?Object.fromEntries(Object.keys(o).sort().map(r=>[r,t(o[r])])):o,e=JSON.stringify(t(s));let n=2166136261;for(let o=0;o<e.length;o++)n^=e.charCodeAt(o),n=Math.imul(n,16777619);return(n>>>0).toString(36)}async function of(s,t,e){var w;if(t[0]!==123)return null;let n;try{n=JSON.parse(new TextDecoder().decode(t))}catch{return null}if(!((w=n==null?void 0:n.entry)!=null&&w.object)||!n.parts)return null;const o=s.client.recipes.streamedReader();if(!o)throw new Error(`${e} is a streamed model, and this app cannot read those: it provides no reader for them.`);s.progress(`Downloading the pieces of ${e}`);const r=new Map,a=F=>{let P=r.get(F);return P||(P=(async()=>{const S=await s.client.downloadHiddenFile(F);if(!S.ok)throw new Error(`Reading a piece of ${e} answered ${S.status}`);return new Uint8Array(await S.arrayBuffer())})(),r.set(F,P)),P},f=async F=>{const P=await Promise.all((F??[]).map(async v=>(await a(v.object)).subarray(v.offset,v.offset+v.length))),S=new Uint8Array(P.reduce((v,G)=>v+G.length,0));let M=0;for(const v of P)S.set(v,M),M+=v.length;return S},[g,d,h,b]=await Promise.all([f([n.entry]),f(n.parts.container),f(n.parts.sidecar),f(n.parts.lod)]);return s.progress(`Reading ${e}`),await o({entry:g,container:d,sidecar:h,lod:b},e)}async function wr(s,t,e){var h,b,w,F;if(!(t!=null&&t.fileId))throw new Error("Choose the model file to read.");s.progress(`Downloading ${t.name}`);let n=new Uint8Array(await(await s.client.downloadFile(t.fileId,t.version?{versionTag:t.version}:void 0)).arrayBuffer());const o=((b=(h=/\.([^.]+)$/.exec(t.name))==null?void 0:h[1])==null?void 0:b.toLowerCase())??"frag";let r=null,a=null;if(o!=="frag"){const P=s.client.recipes.importerFor(o);if(!P)throw new Error(`This app cannot read .${o} files: it provides no importer for them.`);o==="ifc"&&(r=ll(n));const S=s.client.recipes.shapesFor(o);S&&(s.progress(`Reading the shapes of ${t.name}`),a=await S(n,t.name)),s.progress(`Reading ${t.name}`),n=await P(n,t.name)}const f=await of(s,n,t.name);if(o==="frag"&&(e!=null&&e.shapes)&&!f){const P=s.client.recipes.shapesFor("frag");P&&(s.progress(`Reading the shapes of ${t.name}`),a=await P(n,t.name))}const g=f??await eo(n),d=(F=(w=g.metadata)==null?void 0:w.thatOpenModelling)==null?void 0:F.origin;if(a&&Array.isArray(d)&&(d[0]||d[1])){const P=new Set;for(const S of a.elements.values())for(const M of S.pieces)P.has(M)||(P.add(M),M.matrix=M.matrix.map((v,G)=>G===12?v-(d[0]??0):G===13?v-(d[1]??0):v));for(const S of a.elements.values())S.rebar&&(S.rebar=bc(S.rebar,M=>[M[0]-(d[0]??0),M[1]-(d[1]??0),M[2]]))}if(a&&(r!=null&&r.elevation))for(const P of a.elements.values())P.rebar&&(P.rebar=bc(P.rebar,S=>[S[0],S[1],S[2]-r.elevation]));return{picked:t,contents:g,site:r,shapes:a}}const bc=(s,t)=>({...s,path:s.path.map(t),...s.paths?{paths:s.paths.map(e=>e.map(t))}:{}});function ll(s){var l;const t=new TextDecoder("latin1").decode(s),e=Ht=>new RegExp(`^${Ht}=\\s*([A-Z0-9_]+)\\((.*)\\);\\s*$`,"m").exec(t),n=Ht=>[...Ht.matchAll(/#\d+|\$/g)].map(it=>it[0]),o=Ht=>[...Ht.matchAll(/-?\d+(?:\.\d*)?(?:E[-+]?\d+)?/gi)].map(it=>Number(it[0])),r=/^(#\d+)=\s*IFCSITE\((.*)\);\s*$/m.exec(t);if(!r)return null;const a=(l=r[2].split(",")[5])==null?void 0:l.trim();if(!(a!=null&&a.startsWith("#")))return null;const f=e(a);if((f==null?void 0:f[1])!=="IFCLOCALPLACEMENT")return null;const[g,d]=n(f[2]);if(g!=="$"||!d)return null;const h=e(d);if((h==null?void 0:h[1])!=="IFCAXIS2PLACEMENT3D")return null;const[b,,w]=n(h[2]),F=b&&b!=="$"?e(b):null;if(!F)return null;const[P=0,S=0,M=0]=o(F[2]);let v=0;const G=w&&w!=="$"?e(w):null;if(G){const[Ht=1,it=0]=o(G[2]);v=Math.atan2(it,Ht)*180/Math.PI}const vt=/IFCSIUNIT\([^)]*\.LENGTHUNIT\.\s*,\s*(\.([A-Z]+)\.|\$)\s*,\s*\.METRE\./i.exec(t),Mt={MILLI:.001,CENTI:.01,DECI:.1,KILO:1e3},St=vt?vt[2]?Mt[vt[2].toUpperCase()]??1:1:/IFCCONVERSIONBASEDUNIT\([^)]*\.LENGTHUNIT\.[^)]*'FOOT'/i.test(t)?.3048:1;return{east:P*St,north:S*St,elevation:M*St,angleDeg:v}}const br="thatopen/recipe@1",Ec="__project_data",vc="recipes",rf=s=>`${s}.recipe.json`,hl={OperationBuilder:to,OP_SCHEMA:gr,readFrag:eo,readPickedFrag:wr,recordsOf:al,innerJson:Ee,levelsOf:yr,levelNames:sf,stylesOf:cl,printOf:js,siteLocationOf:ll,whatItMadeBefore:Ws,ELEMENT_FIELD:rl,CARRIED_FIELD:il,FEET_PER_METRE:sn},fl=/^[a-z0-9][a-z0-9-]{1,62}$/;async function dl(s,t,e){const n=d=>[...d].sort((h,b)=>String(h._id).localeCompare(String(b._id)))[0],o=await s.listFolders({projectId:t,archived:!1});let r=n(o.filter(d=>d.name===Ec&&!d.parentId));if(!r){if(!e)return null;r=await s.createFolder(Ec,void 0,t)}const a=String(r._id),f=await s.listFolders({parentFolderId:a,projectId:t,archived:!1});let g=n(f.filter(d=>d.name===vc&&String(d.parentId)===a));if(!g){if(!e)return null;g=await s.createFolder(vc,a,t)}return String(g._id)}const af=s=>String(s._id??s.id??""),cf=s=>String(s.tag??s.versionTag??""),Ho=s=>{var t;return Number(((t=/(\d+)/.exec(s))==null?void 0:t[1])??-1)};async function Xn(s,t){const e=await dl(s,t,!1);if(!e)return new Map;const n=await s.listFiles({folderId:e}),o=new Map;for(const r of n){const a=String(r.name??"");a.endsWith(".recipe.json")&&o.set(a.slice(0,-12),{id:af(r)})}return o}async function ks(s,t,e){var r;const n=await s.downloadFile(t,e?{versionTag:e}:void 0),o=JSON.parse(await n.text());if((o==null?void 0:o.schema)!==br||!((r=o.manifest)!=null&&r.name)||typeof o.code!="string")throw new Error(`This is not a recipe this library can read (${String(o==null?void 0:o.schema)}).`);return o}async function Zn(s,t){return(await s.listVersions(t)).map(n=>({tag:cf(n),createdAt:String(n.createdAt??"")})).filter(n=>n.tag).sort((n,o)=>Ho(n.tag)-Ho(o.tag))}var us;class ul{constructor(t,e){Wt(this,us,new Map);this.client=t,this.builtinNames=e}async list(t){const e=await Xn(this.client,t);return(await Promise.all([...e.entries()].map(async([,{id:o}])=>{var r;try{const a=await Zn(this.client,o),f=(r=a[a.length-1])==null?void 0:r.tag,g=await ks(this.client,o,f);return{manifest:g.manifest,origin:"project",version:f,author:g.author,savedAt:g.savedAt}}catch{return null}}))).filter(o=>o!==null)}async versions(t,e){const n=(await Xn(this.client,t)).get(e);if(!n)throw new Error(`The project has no recipe named "${e}".`);const o=await Zn(this.client,n.id);return await Promise.all(o.map(async({tag:r,createdAt:a})=>{try{const f=await ks(this.client,n.id,r);return{version:r,author:f.author,note:f.note,savedAt:f.savedAt??a}}catch{return{version:r,savedAt:a}}}))}async source(t,e,n){var a;const o=(await Xn(this.client,t)).get(e);if(!o)throw new Error(`The project has no recipe named "${e}".`);const r=n??((a=(await Zn(this.client,o.id)).pop())==null?void 0:a.tag);if(!r)throw new Error(`The recipe "${e}" has no saved version.`);return{...await ks(this.client,o.id,r),version:r}}async save(t,e,n){const{manifest:o,code:r}=e;if(!fl.test((o==null?void 0:o.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(o.name))throw new Error(`"${o.name}" is a built-in recipe. Give yours a name of its own.`);if(!o.to||!o.description||!Array.isArray(o.inputs))throw new Error("A recipe says what it writes (`to`), what it does (`description`) and what it reads (`inputs`).");await Vo(o,r);const a={schema:br,manifest:o,code:r,author:n.author,...n.note?{note:n.note}:{},savedAt:new Date().toISOString()},f=new Blob([JSON.stringify(a,null,2)],{type:"application/json"}),g=(await Xn(this.client,t)).get(o.name);if(g){const h=await Zn(this.client,g.id),b=`v${Math.max(0,...h.map(w=>Ho(w.tag)))+1}`;return await this.client.createVersion(g.id,f,b),b}const d=await dl(this.client,t,!0);return await this.client.createFile({file:f,name:rf(o.name),versionTag:"v1",projectId:t,parentFolderId:d}),"v1"}async load(t,e,n){var g;const o=(await Xn(this.client,t)).get(e);if(!o)throw new Error(`The project has no recipe named "${e}".`);const r=n??((g=(await Zn(this.client,o.id)).pop())==null?void 0:g.tag);if(!r)throw new Error(`The recipe "${e}" has no saved version.`);const a=`${o.id}@${r}`;let f=H(this,us).get(a);if(!f){const d=await ks(this.client,o.id,r);f=await Vo(d.manifest,d.code),H(this,us).set(a,f)}return{recipe:f,version:r}}}us=new WeakMap;async function Vo(s,t){var o;let e;try{e=await import(`data:text/javascript;base64,${lf(t)}`)}catch(r){throw new Error(`The recipe's code does not load: ${r instanceof Error?r.message:String(r)}`)}const n=e.run??((o=e.default)==null?void 0:o.run);if(typeof n!="function")throw new Error("The recipe's code exports no `run(context)` function.");return{...s,run:r=>n({...r,kit:hl})}}function lf(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 hf(s){const t=s instanceof Uint8Array?s:new Uint8Array(await s.arrayBuffer()),{items:e,metadata:n}=await eo(t),o=e.filter(r=>r.attrs["flow:op"]).map(r=>{const a={};for(const[f,g]of Object.entries(r.attrs))f.startsWith("flow:")||(a[f]=g);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:o}}class Er extends Error{constructor(t){super(t),this.name="UpToDate"}}var tn,ps,ms,gs;class pl{constructor(t){Wt(this,tn,new Map);Wt(this,ps,new Map);Wt(this,ms,new Map);we(this,"project");Wt(this,gs);this.client=t,this.project=new ul(t,()=>new Set(H(this,tn).keys()))}provideImporter(t,e){H(this,ps).set(t.toLowerCase(),e)}provideShapes(t,e){H(this,ms).set(t.toLowerCase(),e)}shapesFor(t){return H(this,ms).get(t.toLowerCase())}importerFor(t){return H(this,ps).get(t.toLowerCase())}provideStreamedReader(t){ie(this,gs,t)}streamedReader(){return H(this,gs)}register(t){if(H(this,tn).has(t.name))throw new Error(`A recipe named "${t.name}" is already registered.`);H(this,tn).set(t.name,t)}list(t){return[...H(this,tn).values()].filter(n=>(!(t!=null&&t.to)||n.to===t.to)&&(!(t!=null&&t.input)||n.inputs.includes(t.input)))}get(t){return H(this,tn).get(t)}async catalog(t,e){const n=this.list(e).map(r=>({manifest:r,origin:"builtin"}));let o=[];try{o=(await this.project.list(t)).filter(r=>!(e!=null&&e.to)||r.manifest.to===e.to)}catch{}return[...n,...o.sort((r,a)=>r.manifest.name.localeCompare(a.manifest.name))]}async resolve(t,e,n){const o=H(this,tn).get(t);return o?{recipe:o,origin:"builtin"}:{...await this.project.load(e,t,n),origin:"project"}}async choices(t,e){const{recipe:n}=await this.resolve(t,e),o=n.source;if((o==null?void 0:o.kind)!=="project-file")return[];const r=(o.extensions??[]).map(d=>d.toLowerCase()),f=(await this.client.documents(e).list()).filter(d=>d.descriptor.native&&(r.length===0||r.includes(d.descriptor.native.format.toLowerCase()))),g=await ml(this.client,f.map(d=>d.descriptor.native.fileId));return f.map(d=>{const h=d.descriptor.native;return{label:d.descriptor.name,fileId:h.fileId,name:`${d.descriptor.name}.${h.format}`,folderId:d.folderId,version:g.get(h.fileId)??"v1"}}).sort((d,h)=>d.label.localeCompare(h.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??ur(),input:e.input,settings:e.settings??{},progress:e.progress??(()=>{})})}}tn=new WeakMap,ps=new WeakMap,ms=new WeakMap,gs=new WeakMap;async function ml(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)},o=r=>{const f=r.slice().sort((g,d)=>{const h=g!=null&&g.createdAt?new Date(String(g.createdAt)).getTime():NaN,b=d!=null&&d.createdAt?new Date(String(d.createdAt)).getTime():NaN;return!Number.isNaN(h)&&!Number.isNaN(b)&&h!==b?b-h:n((d==null?void 0:d.tag)??(d==null?void 0:d.versionTag))-n((g==null?void 0:g.tag)??(g==null?void 0:g.versionTag))})[0];return f?String(f.tag??f.versionTag??"v1"):"v1"};return await Promise.all(t.map(async r=>{try{e.set(r,o(await s.listVersions(r)))}catch{e.set(r,"v1")}})),e}const Wo=100;function ff(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 df(s){if(!s||typeof s!="object")return;const t=s.retryAfter;return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}class no extends Error{constructor(e,n,o,r){const a=ff(o);super(a.message??`${n||"Request failed"} (${e})`);we(this,"status");we(this,"code");we(this,"details");we(this,"body");we(this,"retryAfter");this.name="RequestError",this.status=e,this.code=a.code,this.details=a.details,this.body=o,this.retryAfter=r??df(a.details)}}const vo=()=>{if(typeof window>"u")return null;const s=window.__THATOPEN_CONTEXT__;return s&&typeof s.cacheSet=="function"?s:null};var On;class gl{constructor(){Wt(this,On,new Map)}get(t){var n;const e=vo();return e?(n=e.cache)==null?void 0:n[t]:H(this,On).get(t)}set(t,e){const n=vo();n?n.cacheSet(t,e):H(this,On).set(t,e)}delete(t){var n;const e=vo();e?(n=e.cacheDelete)==null||n.call(e,t):H(this,On).delete(t)}answer(t,e){const n=this.get(t);return n&&n.projectId===e?n:void 0}keepAnswer(t,e,n){try{this.set(t,{projectId:e,value:n,at:Date.now()})}catch{}}}On=new WeakMap;const ze="item/folder",Xt="item",Mc=12e3,rn="processor",uf="npm-registry",Ye="hidden",Mo="FILE",To="TOOL",$o="APP",pf=500,Tc=3e4,mf=2e3,gf=15e3,yf=s=>/^\/?project\/permissions\/check/.test(s),wf=s=>/^\/?(item\/folder\/?$|item\/?$|item\/folder\/[^/]+\/items\/?$|project\/[^/]+\/data\/?$)/.test(s),Qn=new Map,bf=.25,Ef=s=>new Promise(t=>setTimeout(t,s));function vf(s){var o,r;const t=(r=(o=s.headers)==null?void 0:o.get)==null?void 0:r.call(o,"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 Mf(s){return s instanceof no?s.status===429||s.status>=500:!0}function Tf(s,t){const e=Math.min(pf*2**t,Tc),n=e*bf*Math.random(),o=s instanceof no&&s.retryAfter!=null?s.retryAfter*1e3:void 0;return o!=null?Math.min(o,Tc)+n:e+n}var rt,Us,Bt,Yo,ln,An,yl,Rn,Xs,ys,wn,bn,zs,ws,rs,qs,Js,Ko,Xo,Zo;const cs=class cs{constructor(t,e,n){Wt(this,rt);we(this,"apiUrl");we(this,"accessToken");we(this,"wsUrl");we(this,"retries");we(this,"useBearer");we(this,"builtInGlobals",null);we(this,"localServerUrl",null);we(this,"context");we(this,"cache",new gl);we(this,"renewal",null);Wt(this,An,new Map);Wt(this,Rn);Wt(this,Xs,Date.now());Wt(this,ys,!1);Wt(this,wn,0);Wt(this,bn,!1);Wt(this,ws);const{retries:o=0,useBearer:r=!1,localServerUrl:a}=n||{};let f=e;if(f.charAt(f.length-1)==="/"&&(f=f.slice(0,-1)),this.apiUrl=`${f}/api`,this.accessToken=t,this.wsUrl=f,this.retries=o,this.useBearer=r,this.context={appId:"",projectId:"",accessToken:t,apiUrl:e},a){let g=a;g.charAt(g.length-1)==="/"&&(g=g.slice(0,-1)),this.localServerUrl=g}}static fromPlatformContext(t){const e=(typeof window<"u"?window.__THATOPEN_CONTEXT__:null)||{appId:"",projectId:"",accessToken:"",apiUrl:""},n=new cs(e.accessToken,e.apiUrl,{...t,useBearer:!0});return n.context=e,n}static async signInWithBrowser(t){var n;const e=await Cc(t);return(n=t.onSession)==null||n.call(t,e),cs.fromBrowserSession(e,t)}static fromBrowserSession(t,e){const n=new cs(t.accessToken,t.apiUrl,{useBearer:!0});return n.renewFrom(t,e==null?void 0:e.onSession),n}renewFrom(t,e){var r,a;const o=Math.max(t.expiresAt-Date.now()-6e4,0);this.renewal=setTimeout(async()=>{try{const f=await Oc(t);this.setAccessToken(f.accessToken),e==null||e(f),this.renewFrom(f,e)}catch{this.renewFrom({...t,expiresAt:Date.now()+6e4+6e4},e)}},o),(a=(r=this.renewal).unref)==null||a.call(r)}stopRenewing(){this.renewal&&clearTimeout(this.renewal),this.renewal=null}setAccessToken(t){this.accessToken=t,this.context={...this.context,accessToken:t}}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 N(this,rt,Bt).call(this,t,e,n)}async listFiles(t){const{folderId:e,archived:n,projectId:o,versions:r}=t||{};if(e)return await N(this,rt,Bt).call(this,"GET",`${ze}/${e}/items`,{query:{itemType:Mo,archived:n,...r&&{showVersions:!0}}});const a=await N(this,rt,Bt).call(this,"GET",`${Xt}`,{query:{itemType:Mo,archived:n,...o&&{projectId:o}}});return o&&!n&&this.cache.keepAnswer("files",o,a),a}async listDocumentDescriptors(t){const e=H(this,An).get(t);if(e)return await e;const n=N(this,rt,yl).call(this,t);H(this,An).set(t,n);try{return await n}finally{H(this,An).delete(t)}}async exportProjectDocuments(t,e){return(e==null?void 0:e.format)==="csv"?(await(await N(this,rt,Bt).call(this,"GET",`${Xt}/export`,{query:{projectId:t,format:"csv"},responseType:"blob"})).text()).replace(/^/,""):await N(this,rt,Bt).call(this,"GET",`${Xt}/export`,{query:{projectId:t}})}async getFile(t,e){return await N(this,rt,Xo).call(this,t,e)}async createFile(t){return await N(this,rt,Js).call(this,t,Mo)}async updateFile(t,e){return await N(this,rt,Ko).call(this,t,e)}async archiveFile(t){return await N(this,rt,Bt).call(this,"DELETE",`${Xt}/${t}`)}async recoverFile(t){return await N(this,rt,Bt).call(this,"PUT",`${Xt}/${t}/recover`)}async downloadFile(t,e){return await N(this,rt,qs).call(this,t,e)}async getFileVersionMetadata(t,e,n){const{withDraft:o}=n||{};return await N(this,rt,Bt).call(this,"GET",`${Xt}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/metadata`,{query:{...o&&{withDraft:"true"}}})}async updateFileVersionMetadata(t,e,n){return await N(this,rt,Bt).call(this,"PUT",`${Xt}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/metadata`,{body:JSON.stringify({metadata:n}),contentType:"application/json"})}async deleteFileVersionMetadata(t,e){return await N(this,rt,Bt).call(this,"DELETE",`${Xt}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/metadata`)}async getFileVersionMetadataBatch(t,e){const{withDraft:n}=e||{};return await N(this,rt,rs).call(this,t,async o=>(await N(this,rt,Bt).call(this,"POST",`${Xt}/batch/version-metadata`,{body:JSON.stringify({entries:o,...n!==void 0&&{withDraft:n}}),contentType:"application/json"})).results)}async listFolders(t){const{archived:e,parentFolderId:n,projectId:o}=t||{};return await N(this,rt,Bt).call(this,"GET",ze,{query:{parentFolderId:n,archived:e,...o&&{projectId:o}}})}async getFolder(t){return await N(this,rt,Bt).call(this,"GET",`${ze}/${t}`)}async getFoldersBatch(t){return await N(this,rt,rs).call(this,t,async e=>(await N(this,rt,Bt).call(this,"POST",`${Xt}/batch/folders`,{body:JSON.stringify({folderIds:e}),contentType:"application/json"})).results)}async createFolder(t,e,n){return await N(this,rt,Bt).call(this,"POST",ze,{body:JSON.stringify({name:t,...e&&{parentId:e},...n&&{projectId:n}}),contentType:"application/json"})}async updateFolder(t,e){const{name:n}=e;return await N(this,rt,Bt).call(this,"PUT",`${ze}/${t}`,{body:JSON.stringify({name:n}),contentType:"application/json"})}async archiveFolder(t){return await N(this,rt,Bt).call(this,"DELETE",`${ze}/${t}`)}async recoverFolder(t){return await N(this,rt,Bt).call(this,"PUT",`${ze}/${t}/recover`)}async downloadFolder(t){return await N(this,rt,ln).call(this,`${ze}/${t}/download`)}async listComponents(t){const{folderId:e,ShowVersions:n,projectId:o}=t||{};return e?await N(this,rt,Bt).call(this,"GET",`${ze}/${e}/items`,{query:{itemType:To,...n&&{ShowVersions:n}}}):await N(this,rt,Bt).call(this,"GET",`${Xt}`,{query:{itemType:To,...n&&{ShowVersions:n},...o&&{projectId:o}}})}async getComponent(t,e){return await N(this,rt,Xo).call(this,t,e)}async createComponent(t){const{componentProps:e}=t;return await N(this,rt,Js).call(this,t,To,e)}async updateComponent(t,e){const{componentProps:n}=e;return await N(this,rt,Ko).call(this,t,e,n)}async downloadComponent(t,e){return await N(this,rt,qs).call(this,t,e)}async downloadComponentBundle(t,e){const{versionTag:n,withDraft:o}=e||{};return await N(this,rt,ln).call(this,`${Xt}/${t}/download/bundle`,{query:{...n&&{versionTag:n},...o&&{withDraft:o}}})}async archiveComponent(t){return await N(this,rt,Bt).call(this,"DELETE",`${Xt}/${t}`)}async recoverComponent(t){return await N(this,rt,Bt).call(this,"PUT",`${Xt}/${t}/recover`)}async getBuiltInComponent(t){return await(await N(this,rt,ln).call(this,`built-in/${t}/bundle`)).text()}async initBuiltInComponent(t,e,n){const o=await this.getBuiltInComponent(t.uuid),r=n??this.builtInGlobals??(typeof window<"u"?window.ThatOpenCompany:{})??{},a=Object.keys(r),f=a.map(b=>r[b]),d=new Function(...a,`${o}
|
|
2
|
+
return main;`)(...f),h=(d==null?void 0:d.componentDefinition)??d;e.get(h)}async initBuiltInComponents(t,...e){await Promise.all(e.map(n=>this.initBuiltInComponent(n,t)))}async setup(t,...e){const n=t.OBC,o=t.BUI;if(!(n!=null&&n.Components))throw new Error("globals.OBC must include Components");if(!(o!=null&&o.Manager))throw new Error("globals.BUI must include Manager");const r=new n.Components;if(o.Manager.init(),this.setBuiltInGlobals(t),await this.initBuiltInComponents(r,...e),r.init(),globalThis.__thatOpenShellSaysLoaded&&!H(this,Rn)&&ie(this,Rn,this.holdAppLoaded()),ie(this,ys,!0),N(this,rt,zs).call(this),!H(this,bn)){const a=typeof performance<"u"?performance.now():Date.now()-H(this,Xs);setTimeout(()=>{ie(this,wn,0),N(this,rt,zs).call(this)},Math.max(0,Mc-a))}return{components:r}}holdAppLoaded(t=Mc){if(H(this,bn))return()=>{};go(this,wn)._++;let e=!1;const n=()=>{e||(e=!0,clearTimeout(o),go(this,wn)._--,N(this,rt,zs).call(this))},o=setTimeout(n,t);return n}appReady(){var t;(t=H(this,Rn))==null||t.call(this)}throwError(t,e){var n,o;(o=(n=this.context.appEventOrchestrator)==null?void 0:n.appError)==null||o.call(n,t,e)}async listApps(t){const{folderId:e,ShowVersions:n,projectId:o}=t||{};return e?await N(this,rt,Bt).call(this,"GET",`${ze}/${e}/items`,{query:{itemType:$o,...n&&{ShowVersions:n}}}):await N(this,rt,Bt).call(this,"GET",`${Xt}`,{query:{itemType:$o,...n&&{ShowVersions:n},...o&&{projectId:o}}})}async createApp(t){const{appProps:e}=t;return await N(this,rt,Js).call(this,t,$o,e)}async downloadApp(t,e){return await N(this,rt,qs).call(this,t,e)}async downloadAppBundle(t,e){const{versionTag:n,withDraft:o}=e||{};return await N(this,rt,ln).call(this,`${Xt}/${t}/download/bundle`,{query:{...n&&{versionTag:n},...o&&{withDraft:o}}})}async archiveApp(t){return await N(this,rt,Bt).call(this,"DELETE",`${Xt}/${t}`)}async getNpmCredentials(){return await N(this,rt,Bt).call(this,"GET",`${uf}/credentials`)}async executeComponent(t,e,n){if(this.localServerUrl){const o=`${this.localServerUrl}/api/${rn}/${t}/execute`,r=await fetch(o,{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 N(this,rt,Bt).call(this,"POST",`${rn}/${t}/execute`,{body:JSON.stringify(e),query:{...n&&{versionTag:n}},contentType:"application/json"})}async abortExecution(t){if(this.localServerUrl){const e=`${this.localServerUrl}/api/${rn}/progress/${t}/abort`,n=await fetch(e,{method:"POST"});if(!n.ok){const o=await n.text().catch(()=>"");throw new Error(`Local server request failed: ${n.status} - ${o}`)}return await n.json()}return await N(this,rt,Bt).call(this,"POST",`${rn}/progress/${t}/abort`)}async listExecutions(t,e){if(this.localServerUrl){const n=e?`?projectId=${encodeURIComponent(e)}`:"",o=`${this.localServerUrl}/api/${rn}/${t}/progress${n}`,r=await fetch(o);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 N(this,rt,Bt).call(this,"GET",`${rn}/${t}/progress`,{query:{...e&&{projectId:e}}})}async getExecution(t){if(this.localServerUrl){const e=`${this.localServerUrl}/api/${rn}/progress/${t}`,n=await fetch(e);if(!n.ok){const o=await n.text().catch(()=>"");throw new Error(`Local server request failed: ${n.status} - ${o}`)}return await n.json()}return await N(this,rt,Bt).call(this,"GET",`${rn}/progress/${t}`)}async onExecutionProgress(t,e){const n=this.localServerUrl??this.wsUrl,o=await is(n,{auth:{accessToken:this.accessToken},transports:["websocket"]});o.on("connect",function(){o.emit("executionSubscription",JSON.stringify({executionId:t})),o.on("execution",r=>{e(r)})}),o.on("connect_error",function(r){console.log(r)})}documents(t){return new mr(this,t)}history(t){return new fr(this,t)}get recipes(){return H(this,ws)??ie(this,ws,new pl(this)),H(this,ws)}async createHiddenFile(t,e,n){const o=new FormData;return o.append("file",t),o.append("parentItemId",e),n!=null&&o.append("tag",n),await N(this,rt,Bt).call(this,"POST",`${Xt}/${Ye}`,{body:o})}async createHiddenFilesBatch(t,e,n){const o=new FormData;for(const r of t)o.append("files",r);return o.append("parentItemId",e),n!=null&&o.append("tag",n),await N(this,rt,Bt).call(this,"POST",`${Xt}/${Ye}/batch`,{body:o})}async deleteHiddenFile(t){return await N(this,rt,Bt).call(this,"DELETE",`${Xt}/${Ye}/${t}`)}async getHiddenFile(t){return await N(this,rt,Bt).call(this,"GET",`${Xt}/${Ye}/${t}`)}async downloadHiddenFile(t){return await N(this,rt,ln).call(this,`${Xt}/${Ye}/${t}/download`)}async getHiddenFileSignedUrl(t,e){return await N(this,rt,Bt).call(this,"GET",`${Xt}/${Ye}/${t}/signed-url`,{...e!=null&&{query:{expiresIn:e}}})}async getHiddenFileSignedUrlsBatch(t,e){return await N(this,rt,rs).call(this,t,async n=>(await N(this,rt,Bt).call(this,"POST",`${Xt}/${Ye}/signed-url/batch`,{body:JSON.stringify({hiddenFileIds:n,...e!=null&&{expiresIn:e}}),contentType:"application/json"})).results)}async getHiddenFilesByParent(t,e){return await N(this,rt,Bt).call(this,"GET",`${Xt}/${t}/${Ye}`,{...e!=null&&{query:{tag:e}}})}async deleteHiddenFilesByParent(t){return await N(this,rt,Bt).call(this,"DELETE",`${Xt}/${t}/${Ye}`)}async uploadItemIcon(t,e){const n=new FormData;return n.append("icon",e),await N(this,rt,Bt).call(this,"PUT",`${Xt}/${t}/icon`,{body:n})}async getItemIcon(t){return await N(this,rt,ln).call(this,`${Xt}/${t}/icon`)}async removeItemIcon(t){return await N(this,rt,Bt).call(this,"DELETE",`${Xt}/${t}/icon`)}async updateItem(t,e){return await N(this,rt,Bt).call(this,"PUT",`${Xt}/${t}`,{body:JSON.stringify(e),contentType:"application/json"})}async createVersion(t,e,n,o,r){const a=new FormData;a.append("file",e),a.append("versionTag",n),o&&a.append("extraProps",JSON.stringify(o));const f=await N(this,rt,Bt).call(this,"POST",`${Xt}/${t}/version`,{body:a});return r&&await this.updateFileVersionMetadata(t,(f==null?void 0:f.tag)??n,r),f}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 o of e){const r=/^v(\d{1,6})$/.exec(String(o.tag??o.versionTag??""));r&&(n=Math.max(n,Number(r[1])))}return`v${Math.max(n,e.length)+1}`}async listVersions(t,e={}){return await N(this,rt,Bt).call(this,"GET",`${Xt}/${encodeURIComponent(t)}/versions`,{query:e})}async listVersionsBatch(t,e={}){const{archived:n}=e;return await N(this,rt,rs).call(this,t,async o=>(await N(this,rt,Bt).call(this,"POST",`${Xt}/batch/versions`,{body:JSON.stringify({itemIds:o,...n!==void 0&&{archived:n}}),contentType:"application/json"})).results)}async archiveVersion(t,e){return await N(this,rt,Bt).call(this,"PUT",`${Xt}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/archive`)}async recoverVersion(t,e){return await N(this,rt,Bt).call(this,"PUT",`${Xt}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/recover`)}async deleteVersion(t,e){return await N(this,rt,Bt).call(this,"DELETE",`${Xt}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}`)}};rt=new WeakSet,Us=function(t){return`${this.apiUrl}/${t}`},Bt=async function(t,e,n){if(t==="GET"&&(n==null?void 0:n.responseType)!=="blob"&&!(n!=null&&n.retryAttempt)){const o=`${N(this,rt,Us).call(this,e)}?${new URLSearchParams(N(this,rt,Zo).call(this,n==null?void 0:n.query)).toString()}`,r=Date.now(),a=Qn.get(o);if(a&&(a.pending||r-a.at<(wf(e)?gf:mf)))return a.answer.then(g=>g===void 0?g:structuredClone(g));const f={at:r,pending:!0,answer:N(this,rt,Yo).call(this,t,e,n)};return Qn.set(o,f),f.answer.then(()=>{f.pending=!1,f.at=Date.now()},()=>{Qn.get(o)===f&&Qn.delete(o)}),f.answer.then(g=>g===void 0?g:structuredClone(g))}return t!=="GET"&&!yf(e)&&Qn.clear(),N(this,rt,Yo).call(this,t,e,n)},Yo=async function(t,e,n){const{body:o,query:r,contentType:a,retries:f,responseType:g,retryAttempt:d}=n||{},h=N(this,rt,Us).call(this,e),b=N(this,rt,Zo).call(this,r),w=await this.resolveAccessToken(),F={...b,...this.useBearer?{}:{accessToken:w}};try{const P=await fetch(h+"?"+new URLSearchParams(F).toString(),{method:t,headers:{Accept:"application/json",...a&&{"Content-Type":a},...this.useBearer&&{Authorization:`Bearer ${w}`}},...o&&{body:o}});if(!P.ok){const S=await P.text().then(M=>M).catch(()=>"");throw new no(P.status,P.statusText,S,vf(P))}return g==="blob"?await P.blob():P.json().then(S=>S).catch(()=>{})}catch(P){const S=f??this.retries;if(S>0&&Mf(P)){const M=d??0;return await Ef(Tf(P,M)),await N(this,rt,Bt).call(this,t,e,{...n,retries:S-1,retryAttempt:M+1})}throw P}},ln=async function(t,e){const{query:n}=e||{},o=N(this,rt,Us).call(this,t),r=await this.resolveAccessToken(),a={...n,...this.useBearer?{}:{accessToken:r}};return await fetch(o+"?"+new URLSearchParams(a).toString(),{method:"GET",...this.useBearer&&{headers:{Authorization:`Bearer ${r}`}}})},An=new WeakMap,yl=async function(t){const e=await N(this,rt,Bt).call(this,"GET",`${Xt}/documents`,{query:{projectId:t}});return this.cache.keepAnswer("documents",t,e),e},Rn=new WeakMap,Xs=new WeakMap,ys=new WeakMap,wn=new WeakMap,bn=new WeakMap,zs=function(){var t,e;H(this,bn)||!H(this,ys)||H(this,wn)>0||(ie(this,bn,!0),(e=(t=this.context.appEventOrchestrator)==null?void 0:t.appLoaded)==null||e.call(t))},ws=new WeakMap,rs=async function(t,e){if(!t.length)return[];const n=[];for(let r=0;r<t.length;r+=Wo)n.push(t.slice(r,r+Wo));return(await Promise.all(n.map(e))).flat()},qs=async function(t,e){const{versionTag:n,withDraft:o}=e||{},r=await N(this,rt,ln).call(this,`${Xt}/${t}/download`,{query:{...n&&{versionTag:n},...o&&{withDraft:o}}});if(r.status===429||r.status>=500)throw new Error(`Downloading ${t} answered ${r.status}${r.status===429?" (rate limited)":""}`);return r},Js=async function(t,e,n){const{name:o,versionTag:r,parentFolderId:a,projectId:f,file:g,metadata:d}=t,h=new FormData;return h.append("file",g),h.append("name",o),h.append("versionTag",r),h.append("itemType",e),a&&h.append("folderId",a),f&&h.append("projectId",f),n&&h.append("extraProps",JSON.stringify(n)),d&&h.append("metadata",JSON.stringify(d)),await N(this,rt,Bt).call(this,"POST",Xt,{body:h})},Ko=async function(t,e,n){const{name:o,versionTag:r,parentFolderId:a,file:f,metadata:g}=e;let d,h;if(f){const b=new FormData;b.append("file",f),r&&b.append("versionTag",r),n&&b.append("extraProps",JSON.stringify(n)),h=await N(this,rt,Bt).call(this,"POST",`${Xt}/${t}/version`,{body:b});const w=(h==null?void 0:h.tag)??r;g&&w&&await this.updateFileVersionMetadata(t,w,g)}if(o||a){const b={...o&&{name:o},...a&&{folderId:a}},w=JSON.stringify(b);d=await N(this,rt,Bt).call(this,"PUT",`${Xt}/${t}`,{body:w,contentType:"application/json"})}return{item:d,version:h}},Xo=async function(t,e){const{showVersions:n=!1}=e||{};return await N(this,rt,Bt).call(this,"GET",`${Xt}/${t}`,{query:{showVersions:n}})},Zo=function(t){return t&&Object.entries(t).filter(([,e])=>e!==void 0).reduce((e,[n,o])=>(e[n]=o,e),{})};let Ys=cs;function wl(){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 Qo="channel:",$f=1e4;function Gs(s){try{s()}catch(t){console.error("[channel] a listener threw:",t)}}var en,ke,Fe,kn,Fn,Nn,Ce,tr,er,_n;class vr{constructor(t,e){Wt(this,Ce);Wt(this,en,!1);Wt(this,ke,[]);Wt(this,Fe,[]);Wt(this,kn,new Set);Wt(this,Fn,new Set);Wt(this,Nn,new Set);this.transport=t,this.controls=e}get joined(){return H(this,en)}get peers(){return H(this,ke)}join(){return H(this,en)?Promise.resolve():N(this,Ce,tr).call(this,"joined",this.controls.join)}leave(){return!H(this,en)&&!H(this,Fe).some(t=>t.want==="joined")?Promise.resolve():N(this,Ce,tr).call(this,"left",this.controls.leave)}onChange(t){return H(this,kn).add(t),()=>void H(this,kn).delete(t)}onPeerJoined(t){return H(this,Fn).add(t),()=>void H(this,Fn).delete(t)}onPeerLeft(t){return H(this,Nn).add(t),()=>void H(this,Nn).delete(t)}applyJoined(){ie(this,en,!0),N(this,Ce,er).call(this,"joined"),N(this,Ce,_n).call(this)}applyLeft(){ie(this,en,!1),ie(this,ke,[]),N(this,Ce,er).call(this,"left"),N(this,Ce,_n).call(this)}applyPeers(t){ie(this,ke,t),N(this,Ce,_n).call(this)}applyPeerJoined(t){!H(this,en)||H(this,ke).some(e=>e.from===t.from)||(ie(this,ke,[...H(this,ke),t]),H(this,Fn).forEach(e=>Gs(()=>e(t))),N(this,Ce,_n).call(this))}applyPeerLeft(t){const e=H(this,ke).find(n=>n.from===t);e&&(ie(this,ke,H(this,ke).filter(n=>n.from!==t)),H(this,Nn).forEach(n=>Gs(()=>n(e))),N(this,Ce,_n).call(this))}failPending(t){const e=H(this,Fe);return ie(this,Fe,[]),e.forEach(n=>{clearTimeout(n.timer),n.reject(t)}),e.length>0}post(t){this.transport.post(t)}}en=new WeakMap,ke=new WeakMap,Fe=new WeakMap,kn=new WeakMap,Fn=new WeakMap,Nn=new WeakMap,Ce=new WeakSet,tr=function(t,e){return new Promise((n,o)=>{const r={want:t,resolve:n,reject:o,timer:setTimeout(()=>{ie(this,Fe,H(this,Fe).filter(a=>a!==r)),o(new Error(`The platform did not confirm ${t==="joined"?"joining":"leaving"} in time.`))},$f)};H(this,Fe).push(r),this.transport.post({type:"APP_CHANNEL_CONTROL",...e})})},er=function(t){const e=H(this,Fe).filter(n=>n.want===t);ie(this,Fe,H(this,Fe).filter(n=>n.want!==t)),e.forEach(n=>{clearTimeout(n.timer),n.resolve()})},_n=function(){H(this,kn).forEach(t=>Gs(t))};var Pn;class bl extends vr{constructor(e){super(e,{join:{action:"joinCollab"},leave:{action:"leaveCollab"}});Wt(this,Pn,new Map)}on(e,n){const o=H(this,Pn).get(e)??new Set;return o.add(n),H(this,Pn).set(e,o),()=>void o.delete(n)}send(e,n){if(e.startsWith(Qo))throw new Error(`Message types starting with '${Qo}' 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=H(this,Pn).get(e.type);if(!(n!=null&&n.size))return{handled:!1};const o=vl(e);return n.forEach(r=>Gs(()=>r(e.payload,o))),{handled:!0}}}Pn=new WeakMap;var fn;class El extends vr{constructor(e,n){super(e,{join:{action:"joinExternal",kind:n},leave:{action:"leaveExternal",kind:n}});Wt(this,fn,new Map);this.kind=n}on(e,n){if(H(this,fn).has(e))throw new Error(`"${e}" already has a handler in this room. Remove it first.`);return H(this,fn).set(e,n),()=>void H(this,fn).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 H(this,fn).size>0}async handle(e){const n=H(this,fn).get(e.type);if(!n)return{handled:!1};try{return{handled:!0,value:await n(e.payload,vl(e))}}catch(o){return{handled:!0,error:o instanceof Error?o.message:String(o)}}}}fn=new WeakMap;function vl(s){return{from:s.from,at:s.at,requestId:s.requestId,kind:s.kind}}function Sf(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 En,bs,nn,dn,un,ve,nr,Hs,Tl,$l,Sl,sr;class Ml{constructor(t){Wt(this,ve);Wt(this,En);Wt(this,bs);Wt(this,nn);Wt(this,dn,new Map);Wt(this,un,new Set);ie(this,En,t),ie(this,bs,t.listen(e=>void N(this,ve,Tl).call(this,e)))}collab(){return H(this,nn)??ie(this,nn,new bl(H(this,En))),H(this,nn)}external(t){const e=t??"";let n=H(this,dn).get(e);return n||(n=new El(H(this,En),t),H(this,dn).set(e,n)),n}dispose(){H(this,bs).call(this)}}En=new WeakMap,bs=new WeakMap,nn=new WeakMap,dn=new WeakMap,un=new WeakMap,ve=new WeakSet,nr=function(){return[...H(this,nn)?[H(this,nn)]:[],...H(this,dn).values()]},Hs=function(t,e){if(t==="collab")return H(this,nn);if(t==="external")return H(this,dn).get(typeof e=="string"?e:"")},Tl=async function(t){const e=Sf(t);if(e){if(e.type.startsWith(Qo)){N(this,ve,$l).call(this,e);return}await N(this,ve,Sl).call(this,e)}},$l=function(t){var n,o,r;const e=t.payload??{};switch(t.type){case"channel:joined":(n=N(this,ve,Hs).call(this,e.scope,e.kind))==null||n.applyJoined();break;case"channel:left":(o=N(this,ve,Hs).call(this,e.scope,e.kind))==null||o.applyLeft();break;case"channel:peers":(r=N(this,ve,Hs).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"?[H(this,nn)]:[...H(this,dn).values()].filter(f=>f.accepts("external",e.kind));for(const f of a)t.type==="channel:peer-joined"?f==null||f.applyPeerJoined({from:e.from,kind:e.kind}):f==null||f.applyPeerLeft(e.from);break}case"channel:error":{const a=new Error(String(t.payload));N(this,ve,nr).call(this).map(g=>g.failPending(a)).some(Boolean)||console.error("[channel] error:",t.payload);break}}},Sl=async function(t){const e=N(this,ve,nr).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&&N(this,ve,sr).call(this,t.requestId,a))}t.requestId&&t.scope==="external"&&e.length>0&&!n&&N(this,ve,sr).call(this,t.requestId,{handled:!0,error:`No handler for "${t.type}".`})},sr=function(t,e){H(this,un).has(t)||(H(this,un).add(t),H(this,un).size>500&&H(this,un).delete(H(this,un).values().next().value),H(this,En).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 be="project",Sn="notifications",ts="tokens",xf=6e4;var Ln,Es,pn;const Tr=class Tr extends Ys{constructor(e,n,o){super(typeof e=="string"?e:"",n,{...o,useBearer:!0});Wt(this,Ln);Wt(this,Es);Wt(this,pn,new Map);typeof e=="function"&&ie(this,Ln,e)}async resolveAccessToken(){return H(this,Ln)?await H(this,Ln).call(this):super.resolveAccessToken()}static fromPlatformContext(e){const n=(typeof window<"u"?window.__THATOPEN_CONTEXT__:null)||{appId:"",projectId:"",accessToken:"",apiUrl:""},o=new Tr(()=>n.accessToken??"",n.apiUrl,e);return o.context=n,o}get channel(){return H(this,Es)??ie(this,Es,new Ml(wl())),H(this,Es)}async listProjects(){return await this.request("GET",be)}async getProject(e){return await this.request("GET",`${be}/${e}`)}async getProjectData(e){const n=H(this,pn).get(e);if(n&&Date.now()-n.at<xf)return await n.data;const o=this.request("GET",`${be}/${e}/data`);return H(this,pn).set(e,{at:Date.now(),data:o}),o.then(r=>this.cache.keepAnswer("projectData",e,r),()=>{}),o.catch(()=>{var r;((r=H(this,pn).get(e))==null?void 0:r.data)===o&&H(this,pn).delete(e)}),await o}async request(e,n,o){return e.toUpperCase()!=="GET"&&H(this,pn).clear(),await super.request(e,n,o)}async listMembers(e){return await this.request("GET",`${be}/${e}/users`)}async addMember(e,n,o){return await this.request("POST",`${be}/${e}/user`,{body:JSON.stringify({accountId:n,...o&&{projectRoleId:o}}),contentType:"application/json"})}async setMemberRole(e,n,o){return await this.request("PUT",`${be}/${e}/user/${n}`,{body:JSON.stringify({projectRoleId:o}),contentType:"application/json"})}async removeMember(e,n){return await this.request("DELETE",`${be}/${e}/user/${n}`)}async inviteMember(e,n,o){return await this.request("POST",`${be}/${e}/invite`,{body:JSON.stringify({email:n,...o&&{projectRoleId:o}}),contentType:"application/json"})}async listInvitations(e){return await this.request("GET",`${be}/${e}/invites`)}async cancelInvitation(e,n){return await this.request("DELETE",`${be}/${e}/invite/${n}`)}async listRoles(e){return await this.request("GET",`${be}/${e}/roles`)}async createRole(e,n){return await this.request("POST",`${be}/${e}/role`,{body:JSON.stringify(n),contentType:"application/json"})}async updateRole(e,n){return await this.request("PUT",`${be}/role/${e}`,{body:JSON.stringify(n),contentType:"application/json"})}async deleteRole(e){return await this.request("DELETE",`${be}/role/${e}`)}async getPermissionMatrix(e){const[n,o]=await Promise.all([this.listRoles(e),this.listMembers(e)]);return n.map(r=>({role:r,permissions:r.permissions??[],members:o.filter(a=>{var f;return String((f=a.role)==null?void 0:f._id)===String(r._id)}).map(a=>a.user)}))}async listTokens(){return await this.request("GET",ts)}async getTokenSecret(e){return await(await this.request("GET",`${ts}/${e}/token`,{responseType:"blob"})).text()}async createToken(e){return await this.request("POST",ts,{body:JSON.stringify({urlRestrictions:[],...e}),contentType:"application/json"})}async updateToken(e,n){return await this.request("PUT",`${ts}/${e}`,{body:JSON.stringify(n),contentType:"application/json"})}async revokeToken(e){return await this.request("DELETE",`${ts}/${e}`)}async getAvatar(e){return await this.request("GET",`account/${e}/avatar`,{responseType:"blob"})}async checkPermission(e){return await this.request("GET",`${be}/permissions/check`,{query:e})}async checkPermissionBatch(e){return(await this.request("POST",`${be}/permissions/check/batch`,{body:JSON.stringify({checks:e}),contentType:"application/json"})).results}async getNotifications(e){return await this.request("GET",Sn,{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",`${Sn}/unread-count`)).count}async markNotificationsRead(e){return await this.request("POST",`${Sn}/mark-read`,{body:JSON.stringify({ids:e}),contentType:"application/json"})}async markAllNotificationsRead(){return await this.request("POST",`${Sn}/mark-all-read`)}async getNotificationSubscriptions(){return await this.request("GET",`${Sn}/subscriptions`)}async unsubscribeFromAutomation(e){return await this.request("DELETE",`${Sn}/subscriptions/${e}`)}async subscribeToAutomation(e,n,o){return await this.request("POST",`${be}/${e}/events/hooks/${n}/subscription`,{body:JSON.stringify(o??{}),contentType:"application/json"})}async updateAutomationSubscription(e,n,o){return await this.request("PATCH",`${be}/${e}/events/hooks/${n}/subscription`,{body:JSON.stringify(o),contentType:"application/json"})}async onNotification(e){const n=await this.resolveAccessToken(),o=is(`${this.socketOrigin}/notifications`,{auth:{accessToken:n},transports:["websocket"]});return o.on("notification.created",r=>e({type:"created",id:r==null?void 0:r.id})),o.on("notification.read",r=>e({type:"read",id:r==null?void 0:r.id})),o.on("notifications.allRead",r=>e({type:"allRead",batch:r==null?void 0:r.batch})),()=>o.disconnect()}};Ln=new WeakMap,Es=new WeakMap,pn=new WeakMap;let or=Tr;const Ke=1/.3048,If={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",IFCBEAM:"OST_StructuralFraming",IFCFOOTING:"OST_StructuralFoundation",IFCGEOGRAPHICELEMENT:"OST_Site",IFCELECTRICAPPLIANCE:"OST_ElectricalEquipment",IFCELECTRICDISTRIBUTIONBOARD:"OST_ElectricalEquipment",IFCUNITARYEQUIPMENT:"OST_MechanicalEquipment"},Fs="OST_GenericModel",_f={"structural foundations":"OST_StructuralFoundation","cimentación estructural":"OST_StructuralFoundation",tragwerksfundamente:"OST_StructuralFoundation",fondations:"OST_StructuralFoundation","structural framing":"OST_StructuralFraming","armazón estructural":"OST_StructuralFraming",tragwerk:"OST_StructuralFraming",ossature:"OST_StructuralFraming","structural columns":"OST_StructuralColumns","pilares estructurales":"OST_StructuralColumns",tragwerksstützen:"OST_StructuralColumns","poteaux porteurs":"OST_StructuralColumns","structural stiffeners":"OST_StructuralStiffener","rigidizadores estructurales":"OST_StructuralStiffener",columns:"OST_Columns",pilares:"OST_Columns",stützen:"OST_Columns",poteaux:"OST_Columns",furniture:"OST_Furniture",mobiliario:"OST_Furniture",möbel:"OST_Furniture",mobilier:"OST_Furniture",casework:"OST_Casework","mueble de obra":"OST_Casework","mobiliario fijo":"OST_Casework","plumbing fixtures":"OST_PlumbingFixtures","aparatos sanitarios":"OST_PlumbingFixtures",sanitärinstallationen:"OST_PlumbingFixtures","lighting fixtures":"OST_LightingFixtures",luminarias:"OST_LightingFixtures",leuchten:"OST_LightingFixtures","specialty equipment":"OST_SpecialityEquipment","equipos especializados":"OST_SpecialityEquipment","mechanical equipment":"OST_MechanicalEquipment","equipos mecánicos":"OST_MechanicalEquipment","electrical equipment":"OST_ElectricalEquipment","equipos eléctricos":"OST_ElectricalEquipment","electrical fixtures":"OST_ElectricalFixtures","aparatos eléctricos":"OST_ElectricalFixtures",planting:"OST_Planting",vegetación:"OST_Planting",entourage:"OST_Entourage",site:"OST_Site",emplazamiento:"OST_Site",parking:"OST_Parking",aparcamiento:"OST_Parking",doors:"OST_Doors",puertas:"OST_Doors",windows:"OST_Windows",ventanas:"OST_Windows","generic models":"OST_GenericModel","modelos genéricos":"OST_GenericModel"},Ks=s=>{if(!(!s||!/\s:\s/.test(s)))return _f[s.split(":")[0].trim().toLowerCase()]},Cf=[["G2050","OST_Planting"],["C10302","OST_SpecialityEquipment"],["C10304","OST_Casework"],["E2010","OST_Casework"],["E2020","OST_Furniture"],["E10","OST_SpecialityEquipment"],["D1010","OST_SpecialityEquipment"],["D2010","OST_PlumbingFixtures"],["D30","OST_MechanicalEquipment"],["D5010","OST_ElectricalEquipment"],["D5020","OST_LightingFixtures"]],Of=s=>{var e;if(!s)return;const t=s.trim().toUpperCase();return(e=Cf.filter(([n])=>t.startsWith(n)).sort((n,o)=>o[0].length-n[0].length)[0])==null?void 0:e[1]},Af=s=>Ks(s)!==void 0||/^(walls|muros|floors|suelos|roofs|cubiertas|stairs|escaleras|railings|barandillas|structural rebar|armadura estructural|ceilings|techos|curtain panels|paneles de muro cortina|curtain wall mullions|montantes de muro cortina)\s*:/i.test(s??""),Rf=new Set(["IFCSPACE","IFCOPENINGELEMENT","IFCSITE","IFCANNOTATION","IFCGRID","IFCVIRTUALELEMENT","IFCBUILDING","IFCBUILDINGSTOREY"]),Ze=(s,t)=>Math.round(s/t)*t,kf=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]]}),as=(s,t)=>s[0]*t[0]+s[1]*t[1]+s[2]*t[2],So=s=>Math.sqrt(as(s,s)),Cn=(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 xl(s,t,e,n){var d,h,b;const o=new Set,r=new Map;for(const w of t){const[,F,P]=w.split(":");F&&(/^datum/.test(P??"")||(o.add(F),r.has(F)||r.set(F,w)))}const a=new Map,f=new Map,g=[];for(const w of s.elements.values()){if(o.has(w.gid)||Rf.has(w.ifcClass.toUpperCase())||w.parent&&o.has(w.parent)&&!/^IFC(DOOR|WINDOW)$/i.test(w.ifcClass)&&!(n!=null&&n.has(w.gid))||w.pieces.length===0)continue;const F=/^IFCCOLUMN$/i.test(w.ifcClass)&&(w.loadBearing||/structural|estructural|结构柱|tragend|tragwerk/i.test(`${w.typeName??""} ${w.objectType??""} ${w.name??""}`)),P=Ks(w.name)??Ks(w.objectType),S=(P&&P!==Fs?P:void 0)??If[w.ifcClass.toUpperCase()]??Fs,M=F?"OST_StructuralColumns":S===Fs?Of(w.classification)??Fs:S,v=kf(w.pieces[0].matrix),G=So(v.x),vt=So(v.y),Mt=So(v.z),St=v.z.map(mt=>mt/(Mt||1)),l=Math.abs(St[2]-1)<1e-6&&as(Cn(v.x,v.y),v.z)>0&&Math.abs(G-vt)<1e-6&&Math.abs(G-Mt)<1e-6,Ht=as(Cn(v.x,v.y),v.z)>0&&Math.abs(G-vt)<1e-6&&Math.abs(G-Mt)<1e-6,it=[v.x,v.y,v.z].map(mt=>mt.map(_t=>_t/(G||1))),Tt=Ht&&!l&&it.some(mt=>Math.abs(Math.abs(mt[2])-1)<1e-6)?it.find(mt=>Math.abs(mt[2])<1e-6):void 0,$t=l?Math.atan2(v.x[1],v.x[0]):Tt?Math.atan2(Tt[1],Tt[0]):0,ne=Math.cos(-$t),ee=Math.sin(-$t),xt=[v.t[0],v.t[1],v.t[2]],lt=/COLUMN/i.test(M),Et=mt=>{const _t=mt[0]-xt[0],ct=mt[1]-xt[1];return[ne*_t-ee*ct,ee*_t+ne*ct,mt[2]-xt[2]]},Rt=[],Jt=[M];for(const mt of w.pieces){const _t=s.geometries.get(mt.geometry);if(!_t)continue;const ct=mt.matrix,qt=[];for(let Gt=0;Gt<_t.verts.length;Gt+=3){const Oe=_t.verts[Gt],je=_t.verts[Gt+1],Ue=_t.verts[Gt+2],Dn=[ct[0]*Oe+ct[4]*je+ct[8]*Ue+ct[12],ct[1]*Oe+ct[5]*je+ct[9]*Ue+ct[13],ct[2]*Oe+ct[6]*je+ct[10]*Ue+ct[14]],jn=Et(Dn);qt.push(Ze(jn[0]*Ke,1e-5),Ze(jn[1]*Ke,1e-5),Ze(jn[2]*Ke,1e-5))}const At=as(Cn([ct[0],ct[1],ct[2]],[ct[4],ct[5],ct[6]]),[ct[8],ct[9],ct[10]])<0,ht=[];for(let Gt=0;Gt+2<_t.tris.length;Gt+=3)At?ht.push(_t.tris[Gt],_t.tris[Gt+2],_t.tris[Gt+1]):ht.push(_t.tris[Gt],_t.tris[Gt+1],_t.tris[Gt+2]);ht.length&&Rt.push({v:qt,t:ht});const Qt=Et([ct[12],ct[13],ct[14]]),Yt=[ne*ct[0]-ee*ct[1],ee*ct[0]+ne*ct[1],ct[2]],Zt=[ne*ct[4]-ee*ct[5],ee*ct[4]+ne*ct[5],ct[6]],me=[ne*ct[8]-ee*ct[9],ee*ct[8]+ne*ct[9],ct[10]];Jt.push(`${mt.geometry}@${[...Qt,...Yt,...Zt,...me].map(Gt=>Ze(Gt,1e-4).toFixed(4)).join(",")}`)}if(Rt.length===0)continue;const It=!w.host&&Rt.length===1?Pf(Rt[0]):null;if(It){const mt=Nf(It),_t=mt.key,ct=`prism|${M}|${mt.axis}|${_t}`;let qt=a.get(ct);if(!qt){const Oe=$c(w.typeName??w.objectType??w.name??w.ifcClass),je=(f.get(Oe.toLowerCase())??0)+1;f.set(Oe.toLowerCase(),je);const Ue=je===1?Oe:`${Oe} (${je})`;qt={family:Ue,type:Ue,first:!0,key:Sc(ct)},a.set(ct,qt)}const At={ShapeCategory:M,Family:qt.family,Type:qt.type,ShapeKey:qt.key,PrismLength:String(Ze(It.length,1e-5)),...lt?{ColumnFree:"1"}:{}};qt.first&&(At.Prism=JSON.stringify({axis:mt.axis,loops:mt.loops}),qt.first=!1);const ht=[0,0,0];ht[It.axis]=(mt.flipped?It.from+It.length:It.from)/Ke;const Qt=(It.axis+1)%3,Yt=(It.axis+2)%3;ht[Qt]+=mt.centre[0]/Ke,ht[Yt]+=mt.centre[1]/Ke;const Zt=Math.cos($t),me=Math.sin($t),Gt=[xt[0]+Zt*ht[0]-me*ht[1],xt[1]+me*ht[0]+Zt*ht[1],xt[2]+ht[2]];g.push({key:`${e}:${w.gid}:shape`,attrs:At,at:Gt,rotationDeg:($t+mt.turn)*180/Math.PI});continue}const re=`${M}|${Rt.map(mt=>`${mt.v.map(_t=>Math.round(_t*304.8/2)).join(",")}/${mt.t.join(",")}`).join("|")}`,he=Jt.join("|");let se=a.get(he)??a.get(re);if(se&&(a.set(he,se),a.set(re,se)),!se){const mt=$c(w.typeName??w.objectType??w.name??w.ifcClass),_t=(f.get(mt.toLowerCase())??0)+1;f.set(mt.toLowerCase(),_t);const ct=_t===1?mt:`${mt} (${_t})`;se={family:ct,type:ct,first:!0,key:Sc(re)},a.set(re,se),a.set(he,se)}const le={ShapeCategory:M,Family:se.family,Type:se.type,ShapeKey:se.key,...lt?{ColumnFree:"1"}:{}};se.first&&(le.Shape=JSON.stringify({pieces:Rt}),se.first=!1);const Ct=w.host?r.get(w.host):void 0,kt=w.opening?s.elements.get(w.opening):void 0;if(Ct&&kt){const mt=[1/0,1/0,1/0],_t=[-1/0,-1/0,-1/0];for(const ct of kt.pieces){const qt=s.geometries.get(ct.geometry);if(!qt)continue;const At=ct.matrix;for(let ht=0;ht<qt.verts.length;ht+=3){const Qt=qt.verts[ht],Yt=qt.verts[ht+1],Zt=qt.verts[ht+2],me=Et([At[0]*Qt+At[4]*Yt+At[8]*Zt+At[12],At[1]*Qt+At[5]*Yt+At[9]*Zt+At[13],At[2]*Qt+At[6]*Yt+At[10]*Zt+At[14]]);for(let Gt=0;Gt<3;Gt++)mt[Gt]=Math.min(mt[Gt],me[Gt]*Ke),_t[Gt]=Math.max(_t[Gt],me[Gt]*Ke)}}{const ct=rr(s,kt.gid).flatMap(ht=>ht.pts).map(ht=>Et(ht).map(Qt=>Qt*Ke)),qt=new Map;for(const ht of ct){const Qt=Math.round(ht[1]*200);qt.set(Qt,[...qt.get(Qt)??[],ht])}let At=null;for(const ht of qt.values()){if(ht.length<4)continue;const Qt=[Math.min(...ht.map(Yt=>Yt[0])),Math.max(...ht.map(Yt=>Yt[0])),Math.min(...ht.map(Yt=>Yt[2])),Math.max(...ht.map(Yt=>Yt[2]))];Qt[1]-Qt[0]<.1||Qt[3]-Qt[2]<.1||(!At||(Qt[1]-Qt[0])*(Qt[3]-Qt[2])<(At[1]-At[0])*(At[3]-At[2])-1e-6)&&(At=Qt)}if(At&&qt.size>2&&(mt[0]=At[0],_t[0]=At[1],mt[2]=At[2],_t[2]=At[3]),At&&qt.size>2){const ht=[...qt.entries()].sort((Yt,Zt)=>Yt[0]-Zt[0]).map(([,Yt])=>({y:Yt[0][1],r:[Math.min(...Yt.map(Zt=>Zt[0])),Math.max(...Yt.map(Zt=>Zt[0])),Math.min(...Yt.map(Zt=>Zt[2])),Math.max(...Yt.map(Zt=>Zt[2]))]})),Qt=[];for(let Yt=0;Yt+1<ht.length;Yt++){const Zt=ht[Yt].r,me=ht[Yt+1].r,Gt=[Math.max(Zt[0],me[0]),Math.min(Zt[1],me[1]),Math.max(Zt[2],me[2]),Math.min(Zt[3],me[3])];Gt[1]-Gt[0]<.1||Gt[3]-Gt[2]<.1||ht[Yt+1].y-ht[Yt].y<.01||(Gt[0]<At[0]-.016||Gt[1]>At[1]+.016||Gt[2]<At[2]-.016||Gt[3]>At[3]+.016)&&Qt.push([Gt[0],ht[Yt].y,Gt[2],Gt[1],ht[Yt+1].y,Gt[3]].map(Oe=>Ze(Oe,1e-5)))}Qt.length&&(le.OpeningSteps=JSON.stringify(Qt)),typeof process<"u"&&((d=process.env)!=null&&d.RECIPE_TRACE)&&console.error(`[opening-steps] ${w.gid}: ${ht.length} planes, narrowest ${JSON.stringify(At.map(Yt=>+Yt.toFixed(3)))}, steps ${JSON.stringify(Qt)}`)}}if(Number.isFinite(mt[0])&&(le.Opening=[...mt,..._t].map(ct=>Ze(ct,1e-5)).join(",")),typeof process<"u"&&((h=process.env)!=null&&h.RECIPE_CUT_LOST)&&w.host&&Number.isFinite(mt[0])){const ct=rr(s,kt.gid).flatMap(At=>At.pts),qt=te(s,w.host);if(ct.length&&qt.length){const At=[0,1,2].map(Zt=>Math.min(...ct.map(me=>me[Zt]))-.01),ht=[0,1,2].map(Zt=>Math.max(...ct.map(me=>me[Zt]))+.01),Qt=Math.min(...qt.map(Zt=>Zt[2]))+.01,Yt=qt.filter(Zt=>Zt[0]>At[0]&&Zt[0]<ht[0]&&Zt[1]>At[1]&&Zt[1]<ht[1]&&Zt[2]>Math.max(At[2],Qt)&&Zt[2]<ht[2]).length;Yt>=4&&(le.CutIfLost="1"),(b=process.env)!=null&&b.RECIPE_TRACE&&console.error(`[cut-if-lost] ${w.gid}: ${Yt} of its wall's corners in its opening → ${Yt>=4?"cut":"not"}`)}}}g.push({key:`${e}:${w.gid}:shape`,attrs:le,at:[xt[0],xt[1],xt[2]],rotationDeg:$t*180/Math.PI,...Ct?{host:Ct}:{}})}return g}function $c(s){return(s.replace(/[\\:{}[\]|;<>?`~]/g,"-").replace(/\s+/g," ").trim()||"Shape").slice(0,120)}function Sc(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 Ff(s,t,e){var r,a;const n=new Map;for(const f of t){const[,g,d]=f.split(":");g&&/^run/.test(d??"")&&!n.has(g)&&n.set(g,f)}const o=[];for(const f of s.elements.values()){if(f.ifcClass.toUpperCase()!=="IFCOPENINGELEMENT"||!f.host)continue;const g=n.get(f.host),d=typeof process<"u"&&((r=process.env)==null?void 0:r.RECIPE_TRACE);if(!g){d&&console.error(`[opening] ${f.gid}: its wall ${f.host} not written as a run`);continue}for(const h of rr(s,f.gid)){const b=h.pts;if(b.length<4)continue;const w=Bf(te(s,f.host));if(!w)continue;const F=b.map(G=>(G[0]-w.a[0])*w.u[0]+(G[1]-w.a[1])*w.u[1]),P=b.map(G=>-(G[0]-w.a[0])*w.u[1]+(G[1]-w.a[1])*w.u[0]),S=G=>Math.max(...G)-Math.min(...G),M=S(F)*S(P)*S(b.map(G=>G[2]));if(!(M>0)||Math.abs(h.volume)<.75*M){d&&console.error(`[opening] ${f.gid}: not a box (${h.volume.toFixed(3)} of ${M.toFixed(3)}: ${S(F).toFixed(3)} along ${S(P).toFixed(3)} across ${S(b.map(G=>G[2])).toFixed(3)} up, axis ${JSON.stringify(w.u.map(G=>+G.toFixed(3)))})`);continue}const v=te(s,f.host).map(G=>-(G[0]-w.a[0])*w.u[1]+(G[1]-w.a[1])*w.u[0]);if(v.length&&(Math.min(...P)>Math.min(...v)+.005||Math.max(...P)<Math.max(...v)-.005)){d&&console.error(`[opening] ${f.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)===f.gid&&console.error(`[opening] ${f.gid} part ${h.index}/${h.of}: a box (${h.volume.toFixed(4)} of ${M.toFixed(4)}: ${S(F).toFixed(3)} along ${S(P).toFixed(3)} across ${S(b.map(G=>G[2])).toFixed(3)} up, ${b.length} points)`),o.push({key:`${e}:${f.gid}:opening${h.index===0&&h.of===1?"":`#${h.index}`}`,host:g,box:b.flat()})}}return o}function Nf(s){const t=s.loops.flat(),e=[t.reduce((w,F)=>w+F[0],0)/t.length,t.reduce((w,F)=>w+F[1],0)/t.length],n=s.loops.map(w=>{const F=w.map(([vt,Mt])=>[vt-e[0],Mt-e[1]]),P=F.map(([vt,Mt])=>Math.hypot(vt,Mt)),S=P.reduce((vt,Mt)=>vt+Mt,0)/P.length;if(F.length<8||S<=0||P.some(vt=>Math.abs(vt-S)>.02*S))return F;const M=2*Math.PI/F.length;for(let vt=0;vt<F.length;vt++){const Mt=Math.atan2(F[vt][1],F[vt][0]),St=Math.atan2(F[(vt+1)%F.length][1],F[(vt+1)%F.length][0]),l=Math.abs(Math.atan2(Math.sin(St-Mt),Math.cos(St-Mt)));if(Math.abs(l-M)>.1*M)return F}const G=F.reduce((vt,Mt,St)=>{const l=F[(St+1)%F.length];return vt+Mt[0]*l[1]-l[0]*Mt[1]},0)>=0?1:-1;return F.map((vt,Mt)=>[S*Math.cos(G*2*Math.PI*Mt/F.length),S*Math.sin(G*2*Math.PI*Mt/F.length)])}),o=w=>w.map(P=>{const S=P.map(([v,G])=>`${Math.round(v*304.8)},${Math.round(G*304.8)}`);let M=0;for(let v=1;v<S.length;v++)S[v]<S[M]&&(M=v);return[...S.slice(M),...S.slice(0,M)].join(";")}).sort().join("|"),r=(w,F)=>{const P=Math.cos(-F),S=Math.sin(-F);return w.map(M=>M.map(([v,G])=>[P*v-S*G,S*v+P*G]))},a=[];let f=s.axis,g=0,d=n;if(f===1&&(f=0,g=Math.PI/2,d=n.map(w=>w.map(([F,P])=>[-P,F]))),f===2){let w=0,F=0,P=0;const S=n.flat();for(const[St,l]of S)w+=St*St,F+=l*l,P+=St*l;const M=new Set,v=.5*Math.atan2(2*P,w-F);for(let St=0;St<4;St++)M.add(v+St*Math.PI/2);const G=S.map(([St,l])=>Math.hypot(St,l)),vt=Math.max(...G),Mt=S.filter((St,l)=>G[l]>vt-.003);if(Math.abs(w-F)<.001*(w+F)||Mt.length>4)for(const[St,l]of Mt.slice(0,64))M.add(Math.atan2(l,St));for(const St of M)a.push({loops:r(n,St),turn:St,flipped:!1})}else a.push({loops:d,turn:0,flipped:!1}),a.push({loops:d.map(w=>w.map(([F,P])=>[-F,P]).reverse()),turn:Math.PI,flipped:!0});let h=a[0],b=o(h.loops);for(const w of a.slice(1)){const F=o(w.loops);F<b&&(h=w,b=F)}return{axis:f,loops:h.loops,key:b,centre:e,turn:g+h.turn,flipped:h.flipped}}function Pf(s){const e=s.v.length/3;if(e<6)return null;const n=[0,1,2].map(o=>{let r=1/0,a=-1/0;for(let f=0;f<e;f++){const g=s.v[f*3+o];r=Math.min(r,g),a=Math.max(a,g)}return a-r});for(const o of[0,1,2].sort((r,a)=>n[a]-n[r])){let r=1/0,a=-1/0;for(let it=0;it<e;it++){const Tt=s.v[it*3+o];r=Math.min(r,Tt),a=Math.max(a,Tt)}if(a-r<.01)continue;let f=!0;for(let it=0;it<e&&f;it++){const Tt=s.v[it*3+o];Math.abs(Tt-r)>.001&&Math.abs(Tt-a)>.001&&(f=!1)}if(!f)continue;const g=(o+1)%3,d=(o+2)%3,h=new Map,b=[],w=it=>{const Tt=[s.v[it*3+g],s.v[it*3+d]],$t=`${Math.round(Tt[0]*3048)},${Math.round(Tt[1]*3048)}`;return h.has($t)||(h.set($t,b.length),b.push(Tt)),h.get($t)},F=[];for(let it=0;it+2<s.t.length;it+=3){const Tt=[s.t[it],s.t[it+1],s.t[it+2]];if(!Tt.every(ne=>Math.abs(s.v[ne*3+o]-r)<=.001))continue;const $t=Tt.map(w);$t[0]===$t[1]||$t[1]===$t[2]||$t[0]===$t[2]||F.push($t)}if(F.length===0)continue;const P=(it,Tt)=>{const[$t,ne]=[b[it],b[Tt]],ee=[ne[0]-$t[0],ne[1]-$t[1]],xt=ee[0]*ee[0]+ee[1]*ee[1],lt=[];if(b.length<=3e3)for(let Et=0;Et<b.length;Et++){if(Et===it||Et===Tt)continue;const Rt=((b[Et][0]-$t[0])*ee[0]+(b[Et][1]-$t[1])*ee[1])/xt;if(Rt<=1e-6||Rt>=1-1e-6)continue;Math.abs((b[Et][0]-$t[0])*ee[1]-(b[Et][1]-$t[1])*ee[0])/Math.sqrt(xt)<3e-4&<.push({t:Rt,id:Et})}return[it,...lt.sort((Et,Rt)=>Et.t-Rt.t).map(Et=>Et.id),Tt]},S=[];for(const it of F)for(let Tt=0;Tt<3;Tt++){const $t=P(it[Tt],it[(Tt+1)%3]);for(let ne=0;ne+1<$t.length;ne++)S.push([$t[ne],$t[ne+1]])}const M=new Map;for(const[it,Tt]of S){const $t=it<Tt?`${it},${Tt}`:`${Tt},${it}`;M.set($t,(M.get($t)??0)+1)}const v=new Map;for(const[it,Tt]of S)M.get(it<Tt?`${it},${Tt}`:`${Tt},${it}`)===1&&v.set(it,[...v.get(it)??[],Tt]);if([...v.values()].some(it=>it.length!==1))continue;const G=[],vt=new Set(v.keys());for(;vt.size;){const it=vt.values().next().value,Tt=[];let $t=it,ne=0;do Tt.push(b[$t]),vt.delete($t),$t=v.get($t)[0];while($t!==it&&ne++<1e5&&v.has($t));if($t!==it||Tt.length<3){G.length=0;break}const ee=Tt.filter((xt,lt)=>{const Et=Tt[(lt-1+Tt.length)%Tt.length],Rt=Tt[(lt+1)%Tt.length];return Math.abs((xt[0]-Et[0])*(Rt[1]-Et[1])-(xt[1]-Et[1])*(Rt[0]-Et[0]))>1e-7});G.push(ee.map(([xt,lt])=>[Ze(xt,1e-5),Ze(lt,1e-5)]))}if(G.length===0||G.some(it=>it.length<3))continue;const Mt=it=>{const Tt=new Set;for(let $t=0;$t<e;$t++)Math.abs(s.v[$t*3+o]-it)<=.001&&Tt.add(`${Math.round(s.v[$t*3+g]*304.8)},${Math.round(s.v[$t*3+d]*304.8)}`);return Tt},St=(it,Tt)=>{const[$t,ne]=Tt.split(",").map(Number);for(let ee=-1;ee<=1;ee++)for(let xt=-1;xt<=1;xt++)if(it.has(`${$t+ee},${ne+xt}`))return!0;return!1},l=Mt(r),Ht=Mt(a);if(!(Ht.size<3||[...l].some(it=>!St(Ht,it))||[...Ht].some(it=>!St(l,it))))return{axis:o,from:r,length:a-r,loops:G}}return null}function Lf(s,t){const e=[];for(const n of s.elements.values()){if(n.ifcClass.toUpperCase()!=="IFCSPACE")continue;let o=1/0,r=-1/0;const a=[];for(const d of n.pieces){const h=s.geometries.get(d.geometry);if(!h)continue;const b=d.matrix,w=F=>{const P=h.verts[F*3],S=h.verts[F*3+1],M=h.verts[F*3+2];return[b[0]*P+b[4]*S+b[8]*M+b[12],b[1]*P+b[5]*S+b[9]*M+b[13],b[2]*P+b[6]*S+b[10]*M+b[14]]};for(let F=0;F+2<h.tris.length;F+=3){const P=[w(h.tris[F]),w(h.tris[F+1]),w(h.tris[F+2])];for(const S of P)o=Math.min(o,S[2]),r=Math.max(r,S[2]);a.push(P)}}if(!Number.isFinite(o)||r-o<.1)continue;let f=null,g=0;for(const d of a){if(!d.every(b=>Math.abs(b[2]-o)<.001))continue;const h=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;h>g&&(g=h,f=d)}f&&e.push({key:`${t}:${n.gid}:room`,at:[(f[0][0]+f[1][0]+f[2][0])/3,(f[0][1]+f[1][1]+f[2][1])/3,o],height:r-o,number:n.name??"",name:n.longName??n.name??""})}return e}function Bf(s){if(s.length<2)return;let t=s[0],e=s[0],n=0;for(const d of s){const h=Math.hypot(d[0]-s[0][0],d[1]-s[0][1]);h>n&&(n=h,e=d)}n=0;for(const d of s){const h=Math.hypot(d[0]-e[0],d[1]-e[1]);h>n&&(n=h,t=d)}if(n<.1)return;const o=[...new Map(s.map(d=>[`${Math.round(d[0]*1e3)},${Math.round(d[1]*1e3)}`,[d[0],d[1]]])).values()].sort((d,h)=>d[0]-h[0]||d[1]-h[1]),r=(d,h,b)=>(h[0]-d[0])*(b[1]-d[1])-(h[1]-d[1])*(b[0]-d[0]),a=d=>{const h=[];for(const b of d){for(;h.length>=2&&r(h[h.length-2],h[h.length-1],b)<=0;)h.pop();h.push(b)}return h.pop(),h},f=o.length>=3?[...a(o),...a([...o].reverse())]:o;let g;for(let d=0;d<f.length;d++){const h=f[d],b=f[(d+1)%f.length],w=Math.hypot(b[0]-h[0],b[1]-h[1]);if(w<.001)continue;const F=[(b[0]-h[0])/w,(b[1]-h[1])/w],P=f.map(vt=>vt[0]*F[0]+vt[1]*F[1]),S=f.map(vt=>-vt[0]*F[1]+vt[1]*F[0]),M=Math.max(...P)-Math.min(...P),v=Math.max(...S)-Math.min(...S),G=M*v;(!g||G<g.area-1e-9)&&(g={area:G,u:M>=v?F:[-F[1],F[0]]})}if(g){const d=g.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 rr(s,t){const e=s.elements.get(t);if(!e)return[];const n=[],o=[],r=new Map;for(const h of e.pieces){const b=s.geometries.get(h.geometry);if(!b)continue;const w=h.matrix,F=[];for(let P=0;P<b.verts.length;P+=3){const S=b.verts[P],M=b.verts[P+1],v=b.verts[P+2],G=[w[0]*S+w[4]*M+w[8]*v+w[12],w[1]*S+w[5]*M+w[9]*v+w[13],w[2]*S+w[6]*M+w[10]*v+w[14]],vt=G.map(St=>Math.round(St*1e4)).join(",");let Mt=r.get(vt);Mt===void 0&&(Mt=n.length,r.set(vt,Mt),n.push(G)),F.push(Mt)}for(let P=0;P+2<b.tris.length;P+=3)o.push(F[b.tris[P]],F[b.tris[P+1]],F[b.tris[P+2]])}const a=n.map((h,b)=>b),f=h=>{for(;a[h]!==h;)a[h]=a[a[h]],h=a[h];return h};for(let h=0;h<o.length;h+=3){const b=f(o[h]);a[f(o[h+1])]=b,a[f(o[h+2])]=b}const g=new Map;for(let h=0;h<o.length;h+=3){const b=f(o[h]);let w=g.get(b);w||(w={pts:new Set,volume:0},g.set(b,w));const[F,P,S]=[n[o[h]],n[o[h+1]],n[o[h+2]]];w.volume+=as(F,Cn(P,S))/6,w.pts.add(o[h]),w.pts.add(o[h+1]),w.pts.add(o[h+2])}const d=[...g.values()];return d.map((h,b)=>({pts:[...h.pts].map(w=>n[w]),volume:h.volume,index:b,of:d.length}))}function Df(s,t,e,n,o,r){const a=s.elements.get(t);if(!a)return null;const f=b=>(b[0]-e[0])*n[0]+(b[1]-e[1])*n[1],g=b=>-(b[0]-e[0])*n[1]+(b[1]-e[1])*n[0];let d=1/0,h=-1/0;for(const b of a.pieces){const w=s.geometries.get(b.geometry);if(!w)continue;const F=b.matrix,P=S=>{const M=w.verts[S*3],v=w.verts[S*3+1],G=w.verts[S*3+2];return[F[0]*M+F[4]*v+F[8]*G+F[12],F[1]*M+F[5]*v+F[9]*G+F[13],F[2]*M+F[6]*v+F[10]*G+F[14]]};for(let S=0;S+2<w.tris.length;S+=3){const M=[P(w.tris[S]),P(w.tris[S+1]),P(w.tris[S+2])],v=[];for(let St=0;St<3;St++){const l=M[St],Ht=M[(St+1)%3],it=f(l)-o,Tt=f(Ht)-o;if(it<0==Tt<0||it===Tt)continue;const $t=it/(it-Tt);v.push([g(l)+$t*(g(Ht)-g(l)),l[2]+$t*(Ht[2]-l[2])])}if(v.length!==2)continue;const[G,vt]=v;if((G[1]-r)*(vt[1]-r)>0||G[1]===vt[1])continue;const Mt=G[0]+(r-G[1])/(vt[1]-G[1])*(vt[0]-G[0]);d=Math.min(d,Mt),h=Math.max(h,Mt)}}return Number.isFinite(d)?{lo:d,hi:h}:null}function te(s,t,e){const n=s.elements.get(t),o=[];if(!n)return o;for(const r of e===void 0?n.pieces:[n.pieces[e]]){const a=s.geometries.get(r.geometry);if(!a)continue;const f=r.matrix;for(let g=0;g<a.verts.length;g+=3){const d=a.verts[g],h=a.verts[g+1],b=a.verts[g+2];o.push([f[0]*d+f[4]*h+f[8]*b+f[12],f[1]*d+f[5]*h+f[9]*b+f[13],f[2]*d+f[6]*h+f[10]*b+f[14]])}}return o}function xc(s,t,e,n){var r,a,f;const o=[];for(const g of s.elements.values()){if(g.parent!==t||!/^IFC(PLATE|COVERING|BUILDINGELEMENTPROXY)$/i.test(g.ifcClass)||g.pieces.length===0)continue;const d=te(s,g.gid);if(d.length===0)continue;let h=0;for(const P of g.pieces)h+=(((r=s.geometries.get(P.geometry))==null?void 0:r.tris.length)??0)/3;const b=[1/0,1/0,1/0],w=[-1/0,-1/0,-1/0];for(const P of d)for(let S=0;S<3;S++)b[S]=Math.min(b[S],P[S]),w[S]=Math.max(w[S],P[S]);const F=g.pieces.length===1&&h<=12;if(F&&n){const P=s.geometries.get(g.pieces[0].geometry),S=g.pieces[0].matrix;let M=0,v=null;if(P)for(let G=0;G+2<P.tris.length;G+=3){const vt=Tt=>{const $t=P.verts[Tt*3],ne=P.verts[Tt*3+1],ee=P.verts[Tt*3+2];return[S[0]*$t+S[4]*ne+S[8]*ee,S[1]*$t+S[5]*ne+S[9]*ee,S[2]*$t+S[6]*ne+S[10]*ee]},Mt=vt(P.tris[G]),St=vt(P.tris[G+1]),l=vt(P.tris[G+2]),Ht=Cn([St[0]-Mt[0],St[1]-Mt[1],St[2]-Mt[2]],[l[0]-Mt[0],l[1]-Mt[1],l[2]-Mt[2]]),it=Math.hypot(Ht[0],Ht[1],Ht[2]);it>M&&(M=it,v=Ht.map(Tt=>Tt/it))}if(typeof process<"u"&&((a=process.env)!=null&&a.RECIPE_CW_DEBUG)&&t.includes(process.env.RECIPE_CW_DEBUG)&&console.error(`[tilt-debug] ${g.gid} n ${v==null?void 0:v.map(G=>G.toFixed(3))} wall ${n.map(G=>G.toFixed(3))}`),v&&Math.abs(v[0]*n[0]+v[1]*n[1])<.996){o.push({gid:g.gid,centre:[(b[0]+w[0])/2,(b[1]+w[1])/2,(b[2]+w[2])/2]});continue}}typeof process<"u"&&((f=process.env)!=null&&f.RECIPE_CW_DEBUG)&&t.includes(process.env.RECIPE_CW_DEBUG)&&console.error(`[panel-debug] ${g.gid} pieces ${g.pieces.length} tris ${h} plain ${F}`),!F&&o.push({gid:g.gid,centre:[(b[0]+w[0])/2,(b[1]+w[1])/2,(b[2]+w[2])/2]})}return o}function xo(s,t,e,n,o=!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 f=[(n[0]-e[0])/a,(n[1]-e[1])/a],g=[-f[1],f[0]],d=[];for(const lt of r.pieces){const Et=s.geometries.get(lt.geometry);if(!Et)continue;const Rt=lt.matrix,Jt=It=>{const re=Et.verts[It*3],he=Et.verts[It*3+1],se=Et.verts[It*3+2];return[Rt[0]*re+Rt[4]*he+Rt[8]*se+Rt[12],Rt[1]*re+Rt[5]*he+Rt[9]*se+Rt[13],Rt[2]*re+Rt[6]*he+Rt[10]*se+Rt[14]]};for(let It=0;It+2<Et.tris.length;It+=3){const re=Jt(Et.tris[It]),he=Jt(Et.tris[It+1]),se=Jt(Et.tris[It+2]),le=Cn([he[0]-re[0],he[1]-re[1],he[2]-re[2]],[se[0]-re[0],se[1]-re[1],se[2]-re[2]]),Ct=Math.hypot(le[0],le[1],le[2]);if(Ct<1e-9||Math.abs((le[0]*g[0]+le[1]*g[1])/Ct)<.995)continue;const kt=((re[0]+he[0]+se[0])/3-e[0])*g[0]+((re[1]+he[1]+se[1])/3-e[1])*g[1];d.push({a:re,b:he,c:se,across:kt})}}if(d.length<2)return null;const h=lt=>{const Et=(lt[0]-e[0])*f[0]+(lt[1]-e[1])*f[1];return`${Math.round(Et*1e3)},${Math.round(lt[2]*1e3)}`},b=lt=>lt.split(",").map(Et=>Number(Et)/1e3),w=lt=>{const Et=new Map,Rt=(le,Ct)=>le<Ct?`${le}|${Ct}`:`${Ct}|${le}`;for(const le of lt){const Ct=[h(le.a),h(le.b),h(le.c)];for(let kt=0;kt<3;kt++){const mt=Ct[kt],_t=Ct[(kt+1)%3];if(mt===_t)continue;const ct=Rt(mt,_t);Et.set(ct,(Et.get(ct)??0)+1)}}const Jt=new Map;for(const[le,Ct]of Et){if(Ct!==1)continue;const[kt,mt]=le.split("|");(Jt.get(kt)??Jt.set(kt,[]).get(kt)).push(mt),(Jt.get(mt)??Jt.set(mt,[]).get(mt)).push(kt)}if(Jt.size<3||Jt.size>4e3)return null;const It=new Set;let re=null,he=0;const se=[];for(const le of Jt.keys()){if(It.has(le))continue;const Ct=[le];It.add(le);let kt="",mt=le;for(let qt=0;qt<5e3;qt++){const At=(Jt.get(mt)??[]).find(ht=>ht!==kt&&!It.has(ht))??null;if(!At)break;Ct.push(At),It.add(At),kt=mt,mt=At}if(Ct.length<3)continue;const _t=Ct.map(b);let ct=0;for(let qt=0;qt<_t.length;qt++){const At=_t[qt],ht=_t[(qt+1)%_t.length];ct+=At[0]*ht[1]-ht[0]*At[1]}se.push({pts:_t,area:Math.abs(ct)/2}),Math.abs(ct)/2>he&&(he=Math.abs(ct)/2,re=_t)}return re?{best:re,bestArea:he,allLoops:se}:null},F=Math.max(...d.map(lt=>lt.across));let P=w(d.filter(lt=>lt.across>F-.005));const S=[...new Set(d.map(lt=>Math.round(lt.across*200)))].map(lt=>lt/200);if(S.length>1&&S.length<=24)for(const lt of S){if(Math.abs(lt-F)<.005)continue;const Et=w(d.filter(Rt=>Math.abs(Rt.across-lt)<.0025));Et&&P&&Et.bestArea>P.bestArea*1.2&&(P=Et)}if(!P)return null;const{best:M,allLoops:v}=P;if(!M||M.length<3)return null;const G=Math.min(...M.map(lt=>lt[0])),vt=Math.max(...M.map(lt=>lt[0])),Mt=Math.min(...M.map(lt=>lt[1])),St=Math.max(...M.map(lt=>lt[1]));if(!(vt-G>.1)||!(St-Mt>.1))return null;if(o){const lt=M.filter((Ct,kt,mt)=>{const _t=mt[(kt-1+mt.length)%mt.length],ct=mt[(kt+1)%mt.length];return Math.abs((ct[0]-_t[0])*(Ct[1]-_t[1])-(ct[1]-_t[1])*(Ct[0]-_t[0]))>1e-4*Math.hypot(ct[0]-_t[0],ct[1]-_t[1])}),Et=(Ct,kt)=>{let mt=!1;for(let _t=0,ct=kt.length-1;_t<kt.length;ct=_t++)kt[_t][1]>Ct[1]!=kt[ct][1]>Ct[1]&&Ct[0]<(kt[ct][0]-kt[_t][0])*(Ct[1]-kt[_t][1])/(kt[ct][1]-kt[_t][1])+kt[_t][0]&&(mt=!mt);return mt},Rt=Ct=>[Ct.reduce((kt,mt)=>kt+mt[0],0)/Ct.length,Ct.reduce((kt,mt)=>kt+mt[1],0)/Ct.length],Jt=v.filter(Ct=>Ct.pts!==M&&Ct.area>=.01&&Ct.pts.length<=200&&(Ct.area>=.1||!Et(Rt(Ct.pts),M))).map(Ct=>Ct.pts),It=Jt.filter(Ct=>!Et(Rt(Ct),M)),re=Ct=>{let kt=0;for(let mt=0;mt<Ct.length;mt++){const _t=Ct[mt],ct=Ct[(mt+1)%Ct.length];kt+=_t[0]*ct[1]-ct[0]*_t[1]}return Math.abs(kt)/2},he=F-Math.min(...d.map(Ct=>Ct.across));let se=0;for(const Ct of r.pieces){const kt=s.geometries.get(Ct.geometry);if(!kt)continue;const mt=Ct.matrix,_t=ct=>{const qt=kt.verts[ct*3],At=kt.verts[ct*3+1],ht=kt.verts[ct*3+2];return[mt[0]*qt+mt[4]*At+mt[8]*ht+mt[12],mt[1]*qt+mt[5]*At+mt[9]*ht+mt[13],mt[2]*qt+mt[6]*At+mt[10]*ht+mt[14]]};for(let ct=0;ct+2<kt.tris.length;ct+=3){const qt=_t(kt.tris[ct]),At=_t(kt.tris[ct+1]),ht=_t(kt.tris[ct+2]);se+=(qt[0]*(At[1]*ht[2]-At[2]*ht[1])-qt[1]*(At[0]*ht[2]-At[2]*ht[0])+qt[2]*(At[0]*ht[1]-At[1]*ht[0]))/6}}const le=(re(lt)-Jt.filter(Ct=>!It.includes(Ct)).reduce((Ct,kt)=>Ct+re(kt),0)+It.reduce((Ct,kt)=>Ct+re(kt),0))*he;return he>.01&&Math.abs(se)>1e-6&&Math.abs(le-Math.abs(se))>.15*Math.abs(se)?null:It.length?{lo:G,hi:vt,bottom:Mt,chain:[],outline:lt,holes:Jt.filter(Ct=>!It.includes(Ct)),pieces:It}:(lt.length>4||Jt.length)&<.length<=200?{lo:G,hi:vt,bottom:Mt,chain:[],outline:lt,holes:Jt}:null}const l=lt=>M.map((Et,Rt)=>({p:Et,i:Rt})).filter(({p:Et})=>Math.abs(Et[0]-lt)<.003).sort((Et,Rt)=>Rt.p[1]-Et.p[1])[0],Ht=l(G),it=l(vt);if(!Ht||!it)return null;const Tt=lt=>{const Et=[];for(let Rt=Ht.i,Jt=0;Jt<=M.length;Rt=(Rt+lt+M.length)%M.length,Jt++)if(Et.push(M[Rt]),Rt===it.i)return Et;return null},$t=Tt(1),ne=Tt(-1),ee=lt=>lt?lt.reduce((Et,Rt)=>Et+Rt[1],0)/lt.length:-1/0;let xt=ee($t)>=ee(ne)?$t:ne;if(!xt||xt.length<2||(xt=xt.filter((lt,Et,Rt)=>{if(Et===0||Et===Rt.length-1)return!0;const Jt=Rt[Et-1],It=Rt[Et+1];return Math.abs((It[0]-Jt[0])*(lt[1]-Jt[1])-(It[1]-Jt[1])*(lt[0]-Jt[0]))>1e-4*Math.hypot(It[0]-Jt[0],It[1]-Jt[1])}),xt.every(lt=>Math.abs(lt[1]-St)<.005)))return null;for(let lt=1;lt<xt.length;lt++)if(xt[lt][0]<xt[lt-1][0]-.003)return null;return xt.length>200?null:{lo:G,hi:vt,bottom:Mt,chain:xt}}function jf(s,t,e){const n=te(s,t);if(n.length<4||e.length===0)return;let o=n[0],r=n[0],a=0;for(const v of n){const G=Math.hypot(v[0]-n[0][0],v[1]-n[0][1]);G>a&&(a=G,r=v)}a=0;for(const v of n){const G=Math.hypot(v[0]-r[0],v[1]-r[1]);G>a&&(a=G,o=v)}if(a<.3)return;const f=(r[0]-o[0])/a,g=(r[1]-o[1])/a,d=v=>(v[0]-o[0])*f+(v[1]-o[1])*g,h=Math.max(...n.map(v=>v[2])),b=v=>Math.max(...n.filter(G=>Math.abs(d(G)-v)<.05).map(G=>G[2]),-1/0),w=b(0),F=b(a);if(Math.abs(w-F)<.05&&h-Math.max(w,F)<.05)return;const P=(o[0]+r[0])/2,S=(o[1]+r[1])/2;let M;for(const v of e){const G=te(s,v.gid);if(G.length===0)continue;const vt=G.map(Ht=>Ht[0]),Mt=G.map(Ht=>Ht[1]),St=G.map(Ht=>Ht[2]);if(P<Math.min(...vt)-.2||P>Math.max(...vt)+.2||S<Math.min(...Mt)-.2||S>Math.max(...Mt)+.2)continue;const l=Math.min(...St)-h;l>1.5||Math.max(...St)<h-.05||(!M||Math.abs(l)<Math.abs(M.gap))&&(M={id:v.id,gap:l})}return M==null?void 0:M.id}const Ae={levels:"-2000240",walls:"-2000011",floors:"-2000032",roofs:"-2000035",ceilings:"-2000038",structuralFoundations:"-2001300",stairs:"-2000120",railings:"-2000126",rebar:"-2009000"};function Uf(s){const t=d=>d.reduce((h,b,w)=>{const F=d[(w+1)%d.length];return h+b[0]*F[1]-F[0]*b[1]},0)/2,e=d=>`${Math.round(d[0]*1e4)}|${Math.round(d[1]*1e4)}`,n=s.filter(d=>d.length>=3).map(d=>t(d)<0?[...d].reverse():d),o=n.flat(),r=new Map;for(const d of n)for(let h=0;h<d.length;h++){const b=d[h],w=d[(h+1)%d.length],F=Math.hypot(w[0]-b[0],w[1]-b[1]);if(!(F>1e-6))continue;const P=[(w[0]-b[0])/F,(w[1]-b[1])/F],S=o.map(v=>({r:v,t:(v[0]-b[0])*P[0]+(v[1]-b[1])*P[1]})).filter(({r:v,t:G})=>G>1e-4&&G<F-1e-4&&Math.abs((v[0]-b[0])*P[1]-(v[1]-b[1])*P[0])<1e-4).sort((v,G)=>v.t-G.t).map(({r:v})=>v),M=[b,...S,w];for(let v=0;v+1<M.length;v++){const[G,vt]=[M[v],M[v+1]],[Mt,St]=[e(G),e(vt)];Mt!==St&&(r.has(`${St}>${Mt}`)?r.delete(`${St}>${Mt}`):r.set(`${Mt}>${St}`,[G,vt]))}}const a=new Map;for(const[d,h]of r.values())a.set(e(d),h);const f=[],g=new Set;for(const[d]of r.values()){if(g.has(e(d)))continue;const h=[];for(let w=d,F=0;w&&!g.has(e(w))&&F<1e5;F++)g.add(e(w)),h.push(w),w=a.get(e(w));const b=h.filter((w,F)=>{const P=h[(F-1+h.length)%h.length],S=h[(F+1)%h.length];return Math.abs((w[0]-P[0])*(S[1]-w[1])-(w[1]-P[1])*(S[0]-w[0]))>1e-9});b.length>=3&&f.push(b)}return f}function zf(s){const t=M=>Math.round(M/.005)*.005,e=[...new Set(s.flatMap(M=>[t(M[0]),t(M[2])]))].sort((M,v)=>M-v),n=[...new Set(s.flatMap(M=>[t(M[1]),t(M[3])]))].sort((M,v)=>M-v);if(e.length>400||n.length>400)return null;const o=e.length-1,r=n.length-1,a=(M,v)=>M>=0&&v>=0&&M<o&&v<r&&f[v*o+M],f=new Array(o*r).fill(!1);for(const M of s){const v=e.indexOf(t(M[0])),G=e.indexOf(t(M[2])),vt=n.indexOf(t(M[1])),Mt=n.indexOf(t(M[3]));for(let St=vt;St<Mt;St++)for(let l=v;l<G;l++)f[St*o+l]=!0}for(let M=0;M<r;M++)for(let v=0;v<o;v++)!f[M*o+v]&&e[v+1]-e[v]<.03&&a(v-1,M)&&a(v+1,M)&&(f[M*o+v]=!0);for(let M=0;M<r;M++)for(let v=0;v<o;v++)!f[M*o+v]&&n[M+1]-n[M]<.03&&a(v,M-1)&&a(v,M+1)&&(f[M*o+v]=!0);const g=new Map,d=(M,v)=>`${M},${v}`,h=(M,v)=>{const G=d(...M);g.set(G,[...g.get(G)??[],d(...v)])};let b=0;for(let M=0;M<r;M++)for(let v=0;v<o;v++)f[M*o+v]&&(a(v,M-1)||(h([v,M],[v+1,M]),b++),a(v+1,M)||(h([v+1,M],[v+1,M+1]),b++),a(v,M+1)||(h([v+1,M+1],[v,M+1]),b++),a(v-1,M)||(h([v,M+1],[v,M]),b++));if(!b)return null;const w=g.keys().next().value,F=[w];let P=w;for(let M=0;M<=b;M++){const v=g.get(P);if(!(v!=null&&v.length))return null;if(P=v.shift(),P===w)break;F.push(P)}if(F.length!==b||[...g.values()].some(M=>M.length))return null;const S=F.map(M=>{const[v,G]=M.split(",").map(Number);return[e[v],n[G]]});return S.filter((M,v)=>{const G=S[(v-1+S.length)%S.length],vt=S[(v+1)%S.length];return Math.abs((M[0]-G[0])*(vt[1]-M[1])-(M[1]-G[1])*(vt[0]-M[0]))>1e-9})}function hn(s){let t=s.item.attrs.Name;if(typeof t!="string")return null;if(Af(t)&&(t=t.slice(t.indexOf(":")+1),t.indexOf(":")===t.lastIndexOf(":")&&t.includes(":"))){const[r,a]=t.split(":").map(f=>f.trim());return r&&a?{family:r,type:a}:null}const e=t.indexOf(":"),n=t.lastIndexOf(":");if(e<=0||n<=e)return null;const o=t.slice(e+1,n).trim();return o?{family:t.slice(0,e).trim(),type:o}:null}function Ic(s){const t=hn(s),e=s.item.attrs.PredefinedType;return t?/escalera|stair|landing|descansillo/i.test(t.family)||e==="LANDING"||/pile|pilote|encepado|pfahl/i.test(t.family)||Ks(s.item.attrs.Name)==="OST_StructuralFoundation"&&!/slab|losa|platte|radier|dalle/i.test(t.family)||/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 _c=180/Math.PI;function Io(s){if(typeof s!="string")return null;const t=s.indexOf(":");return t<=0||t===s.length-1?null:{family:s.slice(0,t),type:s.slice(t+1)}}const Pt=s=>String(s);function qf(s){const t=s.slice(),e=(n,o,r)=>Math.abs((o[0]-n[0])*(r[1]-n[1])-(r[0]-n[0])*(o[1]-n[1]))/2;for(let n=!0;n&&t.length>3;){n=!1;for(let o=0;o<t.length&&t.length>3;o++){const r=t[(o-1+t.length)%t.length],a=t[o],f=t[(o+1)%t.length],g=Math.min(Math.hypot(a[0]-r[0],a[1]-r[1]),Math.hypot(f[0]-a[0],f[1]-a[1]))<.02;(e(r,a,f)<1e-8||g&&e(r,a,f)<2e-4)&&(t.splice(o,1),n=!0,o--)}}return t}function Il(s){return async t=>{var Fr,Nr,Pr,Lr,Br,Dr,jr,Ur,zr,qr,Jr,Gr,Hr,Vr,Wr,Yr,Kr,Xr,Zr,Qr,ti,ei,ni,si,oi,ri,ii,ai,ci,li,hi,fi,di,ui,pi,mi,gi,yi,wi,bi,Ei,vi,Mi,Ti,$i,Si,xi,Ii,_i,Ci,Oi,Ai,Ri,ki,Fi,Ni,Pi,Li,Bi,Di,ji,Ui,zi,qi,Ji,Gi,Hi,Vi,Wi,Yi,Ki,Xi,Zi,Qi,ta,ea,na,sa,oa,ra,ia,aa,ca,la,ha,fa,da,ua,pa,ma,ga,ya,wa,ba,Ea,va,Ma,Ta,$a,Sa,xa,Ia,_a,Ca,Oa,Aa,Ra,ka,Fa,Na,Pa,La,Ba,Da,ja,Ua,za,qa,Ja,Ga,Ha,Va,Wa;const{picked:e,contents:n,site:o,shapes:r}=await wr(t,t.input),a=al(n.items),f=/CoordinateBase:\s*(Coordenadas compartidas|Shared Coordinates|Shared)/i.test(JSON.stringify(n.metadata??{})),g=f&&o?[o.east*sn,o.north*sn,o.elevation*sn,o.angleDeg].map(i=>i.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,doorType:h,windowType:b,trustStyleNames:w,includeInstances:F}=t.settings,P=t.settings.createLevels!==!1;if(F&&!w)throw new Error("Free-standing instances can only be made by their style names: turn trustStyleNames on.");const S=yr(a),M=cl(a);if(typeof process<"u"&&((Fr=process.env)!=null&&Fr.RECIPE_STYLE))for(const[i,c]of M)i.includes(process.env.RECIPE_STYLE)&&console.error(`[style] ${i}: ${JSON.stringify(c).slice(0,1500)}`);const v=`recipe:${s}-to-revit`,G=typeof process<"u"?process.env:{},vt=new Map,Mt=Ws(t,vt);t.progress("Writing the changes for the modelling tool");const St=new to({project:t.projectId,document:t.target.docId??"",baseCommit:t.target.version??0,author:v}),l=sn,Ht=new Map;{const i=new Map;for(const c of a){const m=c.item.guid;if(!m)continue;const p=`${m}:${c.kind}`,W=i.get(p)??0;i.set(p,W+1),Ht.set(c.id,`${e.fileId}:${p}${W?`:${W}`:""}`)}}const it=i=>Ht.get(i)??`${e.fileId}:${i}`,Tt=new Set,$t=new Set;let ne=0,ee=0;const xt=Array.isArray(t.settings.focus)?new Set(t.settings.focus):null,lt=[],Et=()=>{var R;if(!xt)return;const i=L=>L?L.split(":")[1]:void 0,c=new Set,m=L=>(L.LocationLine??"").split(";").map(Y=>Y.split(",").map(Number)).filter(Y=>Y.length>=2&&Y.every(Number.isFinite)),p=L=>{c.has(L)||(c.add(L),W=!0)};let W=!0;lt.forEach((L,Y)=>{xt.has(i(L.sourceKey)??"")&&p(Y)});for(let L=0;W&&L<2;L++){W=!1;const Y=new Set([...c].map(Ot=>`${lt[Ot].attrs.CategoryId}|${lt[Ot].attrs.Type??""}`)),u=new Set([...c].map(Ot=>i(lt[Ot].sourceKey))),k=new Set([...c].map(Ot=>lt[Ot].sourceKey)),gt=[...c].flatMap(Ot=>m(lt[Ot].attrs));lt.forEach((Ot,ft)=>{var yt;if(c.has(ft))return;const ot=Ot.attrs;if(ot.Type&&Y.has(`${ot.CategoryId}|${ot.Type}`)||(yt=Ot.placement)!=null&&yt.host&&(k.has(Ot.placement.host)||u.has(i(Ot.placement.host)))||ot.AttachTop&&k.has(ot.AttachTop)||ot.CutBy&&ot.CutBy.split("|").some(q=>k.has(q))||L===0&&m(ot).some(q=>gt.some(oe=>Math.hypot(q[0]-oe[0],q[1]-oe[1])<1)))return p(ft)});for(const Ot of[...c]){const ft=(R=lt[Ot].placement)==null?void 0:R.host,ot=lt[Ot].attrs.AttachTop,yt=(lt[Ot].attrs.CutBy??"").split("|");lt.forEach((q,oe)=>{(q.sourceKey===ft||q.sourceKey===ot||yt.includes(q.sourceKey))&&p(oe)})}}lt.forEach((L,Y)=>{/^[0-9A-Za-z_$]{22}$/.test(i(L.sourceKey)??"")||c.add(Y)});for(const L of[...c].sort((Y,u)=>Y-u))St.add(lt[L].attrs,{...lt[L].placement,source:lt[L].sourceKey});typeof process<"u"&&console.error(`[focus] ${xt.size} asked, ${c.size} of ${lt.length} change(s) written`)},Rt=(i,c,m)=>{if(!Mt.has(i))return!1;const p=vt.get(i),W=f?{...c,Frame:"shared",...g?{SharedAt:g}:{}}:c;return!p||p===js({attrs:W,placement:m??{}})},Jt=new Map,It=(i,c,m)=>{Tt.add(i),Jt.set(i,c);const p=f?{...c,Frame:"shared",...g?{SharedAt:g}:{}}:c,W=js({attrs:p,placement:m??{}}),R=Mt.get(i);if(R){const L=vt.get(i);return!L||L===W?(ne++,!1):(St.remove(R),St.add({...p,"flow:print":W},{...m,source:i}),ee++,!1)}return xt?(lt.push({sourceKey:i,attrs:{...p,"flow:print":W},placement:m}),!0):(St.add({...p,"flow:print":W},{...m,source:i}),!0)},re=i=>{const c=typeof i=="string"?M.get(i):void 0,m=c==null?void 0:c.params.thickness;return typeof m=="number"&&m>0?m*l:void 0},he=i=>{var et,J;const c=Ee(i,"extrusion"),m=S.get(String((c==null?void 0:c.level)??i.params.level??"")),p=c==null?void 0:c.slopes,W=((J=(et=c==null?void 0:c.profile)==null?void 0:et.outline)==null?void 0:J.curves)??[],R=Array.isArray(p)?p.map(K=>typeof K=="number"):[],L=R.indexOf(!0);if(i.params.of!=="roof"||!m||W.length!==4||R.filter(Boolean).length!==2||L<0||L>1||!R[L+2])return null;const[Y,u]=[W[L],W[L+2]],k=Y.from,gt=Y.to,Ot=Math.hypot(gt[0]-k[0],gt[1]-k[1]),ft=[(gt[0]-k[0])/Ot,(gt[1]-k[1])/Ot];let ot=[-ft[1],ft[0]];const yt=(u.from[0]-k[0])*ot[0]+(u.from[1]-k[1])*ot[1];yt<0&&(ot=[-ot[0],-ot[1]]);const q=Math.abs(yt),[oe,bt]=[p[L],p[L+2]],pt=m.at+(typeof i.params.base=="number"?i.params.base:0),wt=(c==null?void 0:c.eaves)??[],[x,T]=[pt+(Number(wt[L])||0),pt+(Number(wt[L+2])||0)],Q=(T-x+bt*q)/(oe+bt);return{A:k,u:ft,n:ot,L:Ot,W:q,si:oe,sj:bt,ridge:Q,top:pt,ti:x,tj:T,zAt:(K,V)=>{const st=(K-k[0])*ot[0]+(V-k[1])*ot[1];return Math.min(x+oe*st,T+bt*(q-st))}}},se=new Map(a.filter(i=>i.kind==="extrusion"&&i.params.of==="roof").map(i=>[i.id,i])),le=[...se.values()].filter(i=>i.item.guid).map(i=>({id:i.id,gid:i.item.guid}));let Ct=0;if(P)for(const[i,c]of S){const m={CategoryId:Ae.levels,Name:c.name,Elevation:Pt(c.at*l)},p=js({attrs:f?{...m,Frame:"shared",...g?{SharedAt:g}:{}}:m,placement:{}}),W=(Nr=[...vt].find(([R,L])=>L===p&&Mt.has(R)))==null?void 0:Nr[0];It(W??it(i),m)&&Ct++}let kt=0,mt=0;const _t=new Map,ct=new Map;let qt=null;const At=()=>qt??(qt=r?[...r.elements.values()].filter(i=>/^IFC(SLAB|ROOF)/i.test(i.ifcClass)).flatMap(i=>{const c=te(r,i.gid);if(!c.length)return[];const m=a.find(p=>p.kind==="extrusion"&&p.item.guid===i.gid);return[{keys:[...m?[it(m.id)]:[],`${e.fileId}:${i.gid}:shape`],box:[0,1,2].map(p=>Math.min(...c.map(W=>W[p]))).concat([0,1,2].map(p=>Math.max(...c.map(W=>W[p]))))}]}):[]),ht=[];for(const i of a){if(i.kind!=="run"||i.params.of!=="wall")continue;const c=Ee(i,"run"),m=((Lr=(Pr=c==null?void 0:c.run)==null?void 0:Pr.line)==null?void 0:Lr.curves)??[],p=i.params.lookRef,W=S.get(String((c==null?void 0:c.level)??i.params.level??""));if(typeof p!="string"||typeof(c==null?void 0:c.height)!="number"||!W){mt++;continue}const R=(re(p)??0)/l,L=u=>{var k;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=Ot=>[u.centre[0]+u.radius*Math.cos(Ot),u.centre[1]+u.radius*Math.sin(Ot)];return typeof process<"u"&&((k=process.env)!=null&&k.RECIPE_TRACE)&&console.error(`[wall-arc] ${i.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},Y=m.map(L).filter(u=>u!==null);mt+=m.length-Y.length,Y.forEach((u,k)=>ht.push({record:i,i:k,width:R,from:u.from,to:u.to,..."arcMid"in u?{arcMid:u.arcMid}:{},joinStart:k===0&&String(i.params.meetsAtStart)==="true",joinEnd:k===Y.length-1&&String(i.params.meetsAtEnd)==="true"}))}const Qt=(i,c)=>{const m=[i.to[0]-i.from[0],i.to[1]-i.from[1]],p=[c.to[0]-c.from[0],c.to[1]-c.from[1]],W=m[0]*p[1]-m[1]*p[0];if(Math.abs(W)<1e-9*Math.hypot(...m)*Math.hypot(...p)*1e3)return null;const R=((c.from[0]-i.from[0])*p[1]-(c.from[1]-i.from[1])*p[0])/W;return[i.from[0]+R*m[0],i.from[1]+R*m[1]]},Yt=(i,c)=>{const m=c.to[0]-c.from[0],p=c.to[1]-c.from[1],W=m*m+p*p||1,R=Math.max(0,Math.min(1,((i[0]-c.from[0])*m+(i[1]-c.from[1])*p)/W));return Math.hypot(i[0]-(c.from[0]+R*m),i[1]-(c.from[1]+R*p))},Zt=new Map,me=i=>{let c=Zt.get(i);if(!c){const m=Ee(i,"run"),p=S.get(String((m==null?void 0:m.level)??i.params.level)).at;c=[p+m.base,p+m.base+m.height],Zt.set(i,c)}return c},Gt=(i,c)=>{const[m,p]=me(i.record),[W,R]=me(c.record);return Math.min(p,R)>Math.max(m,W)},Oe=1,je=new Map,Ue=new Map;for(const i of ht){const c=[["from",i.joinStart],["to",i.joinEnd]],m={from:i.from,to:i.to};for(const[p,W]of c){if(!W)continue;const R=i[p];let L=null,Y=1/0;for(const gt of ht){if(gt===i||gt.arcMid||!Gt(i,gt))continue;const Ot=Yt(R,gt);Ot<Y&&(Y=Ot,L=gt)}if(!L||Y>Oe)continue;const u=Qt(i,L);if(!u)continue;const k=Math.min(Oe,2*Math.max(i.width,L.width)+.02);Math.hypot(u[0]-R[0],u[1]-R[1])>k||Yt(u,L)>L.width+.01||(m[p]=u,Ue.set(i,{...Ue.get(i),[p]:L.width/2}))}je.set(i,m)}const Dn=new Map;if(r){const i=m=>{const p=Math.hypot(m.to[0]-m.from[0],m.to[1]-m.from[1]);return{L:p,d:[(m.to[0]-m.from[0])/p,(m.to[1]-m.from[1])/p]}},c=(m,p,W)=>{const R=m.record.item.guid;if(!R||ht.filter(k=>k.record===m.record).length!==1)return null;const{d:L}=i(m),Y=te(r,R).map(k=>k[2]);if(!Y.length)return null;const u=Df(r,R,m.from,L,(p+W)/2,(Math.min(...Y)+Math.max(...Y))/2);return u?u.hi-u.lo:null};for(const m of ht){if(m.arcMid||!(m.width>0))continue;const p=i(m);if(!(p.L<.3))for(const W of ht){if(W===m||W.arcMid||!(W.width>0)||!Gt(m,W))continue;const R=i(W);if(R.L<.3||Math.abs(p.d[0]*R.d[1]-p.d[1]*R.d[0])>.02)continue;const L=Math.abs(-(W.from[0]-m.from[0])*p.d[1]+(W.from[1]-m.from[1])*p.d[0]);if(L>(m.width+W.width)/2-.01)continue;const Y=[W.from,W.to].map(Ot=>(Ot[0]-m.from[0])*p.d[0]+(Ot[1]-m.from[1])*p.d[1]),u=Math.max(0,Math.min(...Y)),k=Math.min(p.L,Math.max(...Y));if(k-u<.3)continue;const gt=c(m,u,k);typeof process<"u"&&((Dr=(Br=process.env)==null?void 0:Br.RECIPE_WALL)!=null&&Dr.split(",").includes(m.record.item.guid??""))&&console.error(`[cut-by?] ${m.record.item.guid} by ${W.record.item.guid}: off ${L.toFixed(3)}, along ${u.toFixed(2)}..${k.toFixed(2)}, shape ${gt}`),!(gt===null||gt>m.width-.01)&&(typeof process<"u"&&((jr=process.env)!=null&&jr.RECIPE_TRACE)&&console.error(`[cut-by] ${m.record.item.guid} (${(m.width*1e3).toFixed(0)} mm, its shape ${(gt*1e3).toFixed(0)}) cut by ${W.record.item.guid} over ${(k-u).toFixed(2)} m`),Dn.set(m,[...Dn.get(m)??[],W]))}}}const jn=(i,c)=>{var W;if(!r||!i)return null;const m=[-c[1],c[0]],p=[];for(const R of r.elements.values()){if(R.parent!==i||!/^IFCPLATE$/i.test(R.ifcClass)||R.pieces.length!==1)continue;const L=r.geometries.get(R.pieces[0].geometry);if(!L||L.tris.length/3>12)continue;const Y=te(r,R.gid);if(Y.length<4)continue;const u=Y.map(gt=>gt[0]*m[0]+gt[1]*m[1]),k=Math.max(...u)-Math.min(...u);k>.002&&k<.2&&p.push(k)}return p.length?(p.sort((R,L)=>R-L),typeof process<"u"&&((W=process.env)!=null&&W.RECIPE_TRACE)&&console.error(`[glass] ${i}: ${p.length} panel(s), median ${(p[Math.floor(p.length/2)]*1e3).toFixed(1)} mm`),p[Math.floor(p.length/2)]*l):null},kl=(i,c)=>{var L;if(!r||!i)return null;const m=[-c[1],c[0]],p=[],W=[];for(const Y of r.elements.values()){if(Y.parent!==i||!/^IFCMEMBER$/i.test(Y.ifcClass))continue;const u=te(r,Y.gid);if(u.length<4)continue;const k=u.map(q=>q[0]*c[0]+q[1]*c[1]),gt=u.map(q=>q[0]*m[0]+q[1]*m[1]),Ot=u.map(q=>q[2]),ft=q=>Math.max(...q)-Math.min(...q),ot=Math.min(ft(k),ft(Ot)),yt=ft(gt);ot>.005&&ot<.5&&yt>.005&&yt<1&&(p.push(ot),W.push(yt))}if(!p.length)return null;p.sort((Y,u)=>Y-u),W.sort((Y,u)=>Y-u);const R={width:p[Math.floor(p.length/2)],depth:W[Math.floor(W.length/2)]};return typeof process<"u"&&((L=process.env)!=null&&L.RECIPE_TRACE)&&console.error(`[mullion] ${i}: ${p.length} member(s), median ${(R.width*1e3).toFixed(1)} × ${(R.depth*1e3).toFixed(1)} mm`),{width:R.width*l,depth:R.depth*l}},Fl=i=>{var oe;if(!r)return null;const c=[...r.elements.values()].filter(bt=>bt.parent===i&&/^IFC(PLATE|MEMBER)$/i.test(bt.ifcClass)),m=c.filter(bt=>/^IFCPLATE$/i.test(bt.ifcClass)),p=c.filter(bt=>/^IFCMEMBER$/i.test(bt.ifcClass));if(!m.length)return null;const W=c.flatMap(bt=>te(r,bt.gid));if(!W.length)return null;const R=Math.min(...W.map(bt=>bt[2])),L=bt=>[...bt].sort((pt,wt)=>pt-wt)[Math.floor(bt.length/2)]??0,Y=bt=>{const pt=[0,1,2].map(tt=>bt.reduce(($,O)=>$+O[tt],0)/bt.length),wt=[0,1,2].map(tt=>[0,1,2].map($=>bt.reduce((O,D)=>O+(D[tt]-pt[tt])*(D[$]-pt[$]),0)));let x=[1,1,1];for(let tt=0;tt<50;tt++){const $=[0,1,2].map(D=>wt[D][0]*x[0]+wt[D][1]*x[1]+wt[D][2]*x[2]),O=Math.hypot($[0],$[1],$[2])||1;x=$.map(D=>D/O)}let T=[x[1],-x[0],0];const Q=Math.hypot(T[0],T[1]);T=Q>1e-6?T.map(tt=>tt/Q):[1,0,0];const I=[x[1]*T[2]-x[2]*T[1],x[2]*T[0]-x[0]*T[2],x[0]*T[1]-x[1]*T[0]],et=tt=>bt.map($=>($[0]-pt[0])*tt[0]+($[1]-pt[1])*tt[1]+($[2]-pt[2])*tt[2]),J=tt=>{const $=et(tt);return Math.max(...$)-Math.min(...$)},K=J(x)/2,V=bt.map(tt=>[(tt[0]-pt[0])*T[0]+(tt[1]-pt[1])*T[1]+(tt[2]-pt[2])*T[2],(tt[0]-pt[0])*I[0]+(tt[1]-pt[1])*I[1]+(tt[2]-pt[2])*I[2]]);let st=[J(T),J(I)];for(let tt=0;tt<V.length;tt++)for(let $=tt+1;$<V.length;$++){const O=V[$][0]-V[tt][0],D=V[$][1]-V[tt][1],dt=Math.hypot(O,D);if(dt<1e-6)continue;const[j,E]=[O/dt,D/dt],B=V.map(U=>U[0]*j+U[1]*E),_=V.map(U=>-U[0]*E+U[1]*j),z=Math.max(...B)-Math.min(...B),C=Math.max(..._)-Math.min(..._);z*C<st[0]*st[1]-1e-12&&(st=[z,C])}return{from:pt.map((tt,$)=>tt-x[$]*K),to:pt.map((tt,$)=>tt+x[$]*K),sides:st.sort((tt,$)=>tt-$)}},u=[],k=[],gt=[];for(const bt of p){const pt=te(r,bt.gid);if(pt.length<4)continue;const wt=Y(pt);u.push([wt.from[0]*l,wt.from[1]*l,(wt.from[2]-R)*l,wt.to[0]*l,wt.to[1]*l,(wt.to[2]-R)*l]),k.push(wt.sides[0]),gt.push(wt.sides[1])}const Ot=m.map(bt=>te(r,bt.gid)).filter(bt=>bt.length>=4).map(bt=>Y(bt).sides[0]),ft=bt=>{const pt=[0,1,2].map(K=>bt.reduce((V,st)=>V+st[K],0)/bt.length),wt=[0,1,2].map(K=>[0,1,2].map(V=>bt.reduce((st,tt)=>st+(tt[K]-pt[K])*(tt[V]-pt[V]),0))),x=(K,V)=>{let st=V;for(let tt=0;tt<60;tt++){const $=[0,1,2].map(D=>K[D][0]*st[0]+K[D][1]*st[1]+K[D][2]*st[2]),O=Math.hypot($[0],$[1],$[2])||1;st=$.map(D=>D/O)}return st},T=x(wt,[1,.7,.3]),Q=[0,1,2].reduce((K,V)=>K+T[V]*[0,1,2].reduce((st,tt)=>st+wt[V][tt]*T[tt],0),0),I=x(wt.map((K,V)=>K.map((st,tt)=>st-Q*T[V]*T[tt])),[.3,1,.7]);let et=[T[1]*I[2]-T[2]*I[1],T[2]*I[0]-T[0]*I[2],T[0]*I[1]-T[1]*I[0]];const J=Math.hypot(et[0],et[1],et[2])||1;return et=et.map(K=>K/J),et[2]<0&&(et=et.map(K=>-K)),{c:pt,n:et}},ot=m.map(bt=>te(r,bt.gid)).filter(bt=>bt.length>=4).map(ft),yt=[];for(const bt of p){const pt=te(r,bt.gid);if(pt.length<4||!ot.length)continue;const wt=[0,1,2].map(T=>pt.reduce((Q,I)=>Q+I[T],0)/pt.length);let x=null;for(const T of ot){const Q=[wt[0]-T.c[0],wt[1]-T.c[1],wt[2]-T.c[2]],I=Q[0]*T.n[0]+Q[1]*T.n[1]+Q[2]*T.n[2],et=Math.hypot(Q[0]-I*T.n[0],Q[1]-I*T.n[1],Q[2]-I*T.n[2]);Math.abs(I)<.25&&(!x||et<x.along)&&(x={d:I,along:et})}x&&yt.push(x.d)}const q=yt.length?L(yt):0;return typeof process<"u"&&((oe=process.env)!=null&&oe.RECIPE_TRACE)&&console.error(`[glazing] ${i}: bars ${(q*1e3).toFixed(1)} mm off the glass's middle (${yt.length} of ${p.length})`),{bars:u,panels:m.length,mullion:{width:L(k)*l,depth:L(gt)*l,...Math.abs(q)>5e-4?{offset:q*l}:{}},panel:{thickness:(L(Ot)||.01)*l}}},ue=(()=>{if(!r)return 0;const i=[];for(const m of ht){const p=m.record.item.guid;if(!p||!r.elements.has(p))continue;const W=Ee(m.record,"run"),R=S.get(String((W==null?void 0:W.level)??m.record.params.level??""));if(!W||!R)continue;const L=te(r,p);if(!L.length)continue;let Y=1/0;for(const u of L)Y=Math.min(Y,u[2]);i.push(Y-(R.at+(typeof W.base=="number"?W.base:0)))}i.sort((m,p)=>m-p);const c=i.length?i[Math.floor(i.length/2)]:0;return Math.abs(c)>.5?c:0})();for(const i of ht){const{record:c}=i;let m=[];const p=Ee(c,"run");typeof process<"u"&&((zr=(Ur=process.env)==null?void 0:Ur.RECIPE_WALL)!=null&&zr.split(",").includes(c.item.guid??""))&&console.error(`[wall] ${c.item.guid}: params ${JSON.stringify(c.params).slice(0,800)} seg ${JSON.stringify({from:i.from,to:i.to,i:i.i})}`);const W=typeof p.base=="number"?p.base:0,R=p.height,L=S.get(String(p.level??c.params.level??"")),Y=c.params.lookRef;let{from:u,to:k}=i.arcMid?{from:i.from,to:i.to}:je.get(i);Math.hypot(k[0]-u[0],k[1]-u[1])<.01&&({from:u,to:k}=i);const gt=new Set;if(!i.arcMid&&ht.filter($=>$.record===c).length===1){const $=p.asCut,O=Math.hypot(k[0]-u[0],k[1]-u[1]);if($&&O>.05){const D=[(k[0]-u[0])/O,(k[1]-u[1])/O],dt=(B,_)=>{const z=_==null?void 0:_.through,C=_==null?void 0:_.keep;if(!z||!C)return null;const U=D[0]*C[0]+D[1]*C[1];return Math.abs(U)<.5?null:((z[0]-B[0])*C[0]+(z[1]-B[1])*C[1])/U},j=c.params.wantedAtStart==="square"?dt(u,(qr=$.start)==null?void 0:qr[0]):null,E=c.params.wantedAtEnd==="square"?dt(k,(Jr=$.end)==null?void 0:Jr[0]):null;j!==null&&j>.005&&j<Math.min(1,O/2)&&(u=[u[0]+D[0]*j,u[1]+D[1]*j],gt.add("start")),E!==null&&E<-.005&&E>-Math.min(1,O/2)&&(k=[k[0]+D[0]*E,k[1]+D[1]*E],gt.add("end")),typeof process<"u"&&((Gr=process.env)!=null&&Gr.RECIPE_CUT_OUT)&&(j!==null&&j<-.005&&j>-1&&(u=[u[0]+D[0]*j,u[1]+D[1]*j],gt.add("start")),E!==null&&E>.005&&E<1&&(k=[k[0]+D[0]*E,k[1]+D[1]*E],gt.add("end"))),typeof process<"u"&&((Hr=process.env)!=null&&Hr.RECIPE_TRACE)&&(j!==null&&Math.abs(j)>.005&&Math.abs(j)<1||E!==null&&Math.abs(E)>.005&&Math.abs(E)<1)&&console.error(`[wall-to-cut] ${c.item.guid} ${Y}: start ${j==null?void 0:j.toFixed(3)} end ${E==null?void 0:E.toFixed(3)}`),typeof process<"u"&&((Wr=(Vr=process.env)==null?void 0:Vr.RECIPE_WALL)!=null&&Wr.split(",").includes(c.item.guid??""))&&console.error(`[wall-cut] ${c.item.guid}: start ${j==null?void 0:j.toFixed(3)} end ${E==null?void 0:E.toFixed(3)}`)}}const Ot=new Set(gt),ft=!i.arcMid&&r&&c.item.guid&&ht.filter($=>$.record===c).length===1?r.elements.get(c.item.guid):void 0;if(ft){const $=te(r,c.item.guid),O=Math.hypot(k[0]-u[0],k[1]-u[1]);if($.length>=4&&O>.05){const D=[(k[0]-u[0])/O,(k[1]-u[1])/O],dt=$.map(U=>(U[0]-u[0])*D[0]+(U[1]-u[1])*D[1]),j=Math.min(...dt),E=Math.max(...dt),B=$.map(U=>-(U[0]-u[0])*D[1]+(U[1]-u[1])*D[0]),_=Math.max(...B)-Math.min(...B),z=U=>{var X;const A=B.filter((Z,at)=>Math.abs(dt[at]-U)<.002);return A.length>=2&&Math.max(...A)-Math.min(...A)>(typeof process<"u"&&((X=process.env)!=null&&X.RECIPE_END_STEP)?.25:.9)*_},C=u;z(j)&&(u=[C[0]+D[0]*j,C[1]+D[1]*j],Ot.add("start")),z(E)&&(k=[C[0]+D[0]*E,C[1]+D[1]*E],Ot.add("end"))}}const ot=(L.at+W)*l,yt=`${Pt(u[0]*l)},${Pt(u[1]*l)},${Pt(ot)};${Pt(k[0]*l)},${Pt(k[1]*l)},${Pt(ot)}`,q={CategoryId:Ae.walls,Type:((Yr=hn(c))==null?void 0:Yr.type)??Y,LocationLine:yt,Level:L.name,BaseOffset:Pt(W*l),Height:Pt(R*l),...i.arcMid?{LocationArc:`${Pt(i.arcMid[0]*l)},${Pt(i.arcMid[1]*l)},${Pt(ot)}`}:{}},oe=Dn.get(i);oe&&(q.CutBy=oe.flatMap($=>{const O=`${it($.record.id)}#${$.i}`,D=Mt.get(O);return D?[O,D]:[O]}).join("|"));const bt=i.arcMid?[]:[u!==i.from||i.joinStart?"start":"",k!==i.to||i.joinEnd?"end":""].filter($=>!!$&&!Ot.has($));bt.length&&(q.JoinEnds=bt.join(","));const pt=bt.filter($=>c.params[$==="start"?"wantedAtStart":"wantedAtEnd"]==="mitre");pt.length&&(q.Mitre=pt.join(","));const wt=S.get(String(c.params.topLevel??""));wt&&(q.TopLevel=wt.name,q.TopOffset=Pt((L.at+W+R-wt.at)*l));const x=p.profile;let T=Array.isArray(x)?qf(x):x;if((c.params.wantedAtStart==="mitre"||c.params.wantedAtEnd==="mitre")&&Array.isArray(T)&&T.length===4){const $=Math.hypot(i.to[0]-i.from[0],i.to[1]-i.from[1]),O=p.height,D=(j,E)=>Math.abs(j)<1e-4?"lo":Math.abs(j-E)<.001?"hi":null,dt=T.map(([j,E])=>[D(j,$),D(E,O)]);dt.every(([j,E])=>j&&E)&&new Set(dt.map(([j,E])=>`${j}${E}`)).size===4&&(T=void 0)}if(typeof process<"u"&&((Kr=process.env)!=null&&Kr.RECIPE_LAYER_EXT)&&Array.isArray(T)&&T.length>=4&&r&&c.item.guid&&typeof p.height=="number"){const $=(()=>{var O,D;try{return JSON.parse(String(((D=(O=M.get(Y))==null?void 0:O.params)==null?void 0:D.definition)??"null"))}catch{return null}})();if((($==null?void 0:$.layers)??[]).some(O=>(O.topExtension??0)>.001||(O.baseExtension??0)>.001)){const O=Math.hypot(i.to[0]-i.from[0],i.to[1]-i.from[1]),D=p.height,dt=[(i.to[0]-i.from[0])/O,(i.to[1]-i.from[1])/O],j=L.at+W+ue,E=[...r.elements.values()].filter(A=>A.host===c.item.guid&&!/^IFCOPENINGELEMENT$/i.test(A.ifcClass)).map(A=>{const X=te(r,A.gid).map(Z=>[(Z[0]-i.from[0])*dt[0]+(Z[1]-i.from[1])*dt[1],Z[2]-j]);return X.length?[Math.min(...X.map(Z=>Z[0])),Math.max(...X.map(Z=>Z[0])),Math.min(...X.map(Z=>Z[1])),Math.max(...X.map(Z=>Z[1]))]:null}).filter(A=>A!==null),B=Math.min(...T.map(([A])=>A)),_=Math.max(...T.map(([A])=>A)),z=([A,X])=>(Math.abs(A-B)<.005||Math.abs(A-_)<.005)&&(Math.abs(X)<.005||Math.abs(X-D)<.005),C=([A,X])=>E.some(Z=>A>=Z[0]-.03&&A<=Z[1]+.03&&X>=Z[2]-.15&&X<=Z[3]+.03),U=T.filter(A=>!z(A));T.filter(z).length===4&&(U.length===0||E.length&&U.every(C))&&(typeof process<"u"&&((Xr=process.env)!=null&&Xr.RECIPE_TRACE)&&console.error(`[layer-extension] ${c.item.guid} ${Y}: its outline's ${U.length} notch corner(s) filled by what it hosts → a plain wall`),T=void 0)}}if(!i.arcMid&&Array.isArray(T)&&T.length>=3&&i.i===0&&!ht.some($=>$!==i&&$.record===c)){const $=Math.hypot(i.to[0]-i.from[0],i.to[1]-i.from[1]),O=[(i.to[0]-i.from[0])/$,(i.to[1]-i.from[1])/$],D=[];let dt=-((u[0]-i.from[0])*O[0]+(u[1]-i.from[1])*O[1]),j=(k[0]-i.to[0])*O[0]+(k[1]-i.to[1])*O[1];const E=dt,B=j;{const A=Ue.get(i),X=[],Z=r&&c.item.guid?te(r,c.item.guid).map(nt=>(nt[0]-i.from[0])*O[0]+(nt[1]-i.from[1])*O[1]):[],at=Z.length?Math.max(0,-Math.min(...Z))-dt:1/0,Lt=Z.length?Math.max(0,Math.max(...Z)-$)-j:1/0,Ft=(A==null?void 0:A.from)??(at<.6?at:0),jt=(A==null?void 0:A.to)??(Lt<.6?Lt:0);Ft&&bt.includes("start")&&at>.005&&(dt+=Math.min(Ft,at),X.push("start")),jt&&bt.includes("end")&&Lt>.005&&(j+=Math.min(jt,Lt),X.push("end"));const Kt=bt.filter(nt=>!X.includes(nt));if(X.length&&(Kt.length?q.JoinEnds=Kt.join(","):delete q.JoinEnds),X.length&&q.Mitre){const nt=q.Mitre.split(",").filter(Ut=>Kt.includes(Ut));nt.length?q.Mitre=nt.join(","):delete q.Mitre}X.length&&typeof process<"u"&&((Zr=process.env)!=null&&Zr.RECIPE_TRACE)&&console.error(`[profile-face] ${c.item.guid} ${Y}: ${X.join(",")} to the far face`)}const _=(A,X)=>T.map(([Z,at],Lt)=>{const Ft=Math.abs(Z)<1e-6,jt=Math.abs(Z-$)<1e-6;let Kt=Z,nt=at;if(Ft||jt){Kt=Ft?-A:$+X;const Ut=[T[(Lt-1+T.length)%T.length],T[(Lt+1)%T.length]].find(([Vt])=>Math.abs(Vt-Z)>1e-6);Ut&&(nt=at+(Ut[1]-at)/(Ut[0]-Z)*(Kt-Z))}return[Kt,nt]}),z=A=>{const X=A.length,Z=A.map((Lt,Ft)=>[Lt,A[(Ft+1)%X]]);if(Z.some(([Lt,Ft])=>Math.hypot(Ft[0]-Lt[0],Ft[1]-Lt[1])<.001))return!1;for(let Lt=0;Lt<X;Lt++){const[Ft,jt]=Z[Lt],[,Kt]=Z[(Lt+1)%X],nt=[jt[0]-Ft[0],jt[1]-Ft[1]],Ut=[Kt[0]-jt[0],Kt[1]-jt[1]];if((nt[0]*Ut[0]+nt[1]*Ut[1])/(Math.hypot(...nt)*Math.hypot(...Ut))<-.999)return!1}const at=(Lt,Ft,jt)=>(Ft[0]-Lt[0])*(jt[1]-Lt[1])-(Ft[1]-Lt[1])*(jt[0]-Lt[0]);for(let Lt=0;Lt<X;Lt++)for(let Ft=Lt+1;Ft<X;Ft++){if(Ft===Lt+1||Lt===0&&Ft===X-1)continue;const[jt,Kt]=Z[Lt],[nt,Ut]=Z[Ft],Vt=at(nt,Ut,jt),fe=at(nt,Ut,Kt),Me=at(jt,Kt,nt),Se=at(jt,Kt,Ut);if((Vt>1e-9&&fe<-1e-9||Vt<-1e-9&&fe>1e-9)&&(Me>1e-9&&Se<-1e-9||Me<-1e-9&&Se>1e-9))return!1}return!0};let C=_(dt,j);if(!z(C)){const X=[[E,B],[0,0]].find(([Z,at])=>z(_(Z,at)));typeof process<"u"&&((Qr=process.env)!=null&&Qr.RECIPE_TRACE)&&console.error(`[profile-folded] ${c.item.guid} ${Y}: ends ${dt.toFixed(3)}/${j.toFixed(3)} fold it → ${X?X.map(Z=>Z.toFixed(3)).join("/"):"as given"}`),C=X?_(...X):T.map(([Z,at])=>[Z,at])}const U=A=>A.flatMap(([X,Z])=>{const at=[i.from[0]+X*O[0],i.from[1]+X*O[1]];return[at[0]*l,at[1]*l,(L.at+W+Z)*l]});for(const A of U(C))D.push(A);if(q.Profile=JSON.stringify([D]),C.length===8){const A=C.map(([,Ut])=>Ut),X=Math.max(...A),Z=Math.min(...A),at=C.map(([Ut])=>Ut),Lt=Math.min(...at),Ft=Math.max(...at),jt=C.filter(([Ut])=>Ut>Lt+.005&&Ut<Ft-.005),Kt=[...new Set(jt.map(([Ut])=>+Ut.toFixed(4)))].sort((Ut,Vt)=>Ut-Vt);if(C.filter(([Ut,Vt])=>(Math.abs(Ut-Lt)<.005||Math.abs(Ut-Ft)<.005)&&(Math.abs(Vt-X)<.005||Math.abs(Vt-Z)<.005)).length===4&&jt.length===4&&Kt.length===2&&Kt[1]-Kt[0]<.3&&jt.some(([,Ut])=>Math.abs(Ut-Z)<.005)&&jt.every(([,Ut])=>Math.abs(Ut-Z)<.005||X-Ut<.3)){const Ut=(Vt,fe)=>[[Vt,Z],[fe,Z],[fe,X],[Vt,X]];q.Profile=JSON.stringify([U(Ut(Lt,Kt[0]))]),m=[JSON.stringify([U(Ut(Kt[1],Ft))])],typeof process<"u"&&((ti=process.env)!=null&&ti.RECIPE_TRACE)&&console.error(`[slit-split] ${c.item.guid} ${Y}: a slit ${((Kt[1]-Kt[0])*100).toFixed(0)} cm wide at ${Kt[0].toFixed(2)}, two walls`)}}delete q.TopLevel,delete q.TopOffset}const I=c.params.topAttachedTo,et=c.params.topAttachedAt==="top"||p.topAttachedAt==="top",J=!i.arcMid&&typeof I=="string"&&et&&!q.Profile&&se.has(I)?he(se.get(I)):null;if(J){const $=Math.hypot(k[0]-u[0],k[1]-u[1]),O=z=>[u[0]+(k[0]-u[0])*z/$,u[1]+(k[1]-u[1])*z/$],D=(u[0]-J.A[0])*J.n[0]+(u[1]-J.A[1])*J.n[1],dt=(k[0]-J.A[0])*J.n[0]+(k[1]-J.A[1])*J.n[1],j=[0,$];(D-J.ridge)*(dt-J.ridge)<0&&j.splice(1,0,(J.ridge-D)/(dt-D)*$);const E=L.at+W,B=[],_=(z,C)=>{const U=O(z);B.push(U[0]*l,U[1]*l,C*l)};_(0,E),_($,E);for(const z of[...j].reverse()){const C=O(z);_(z,J.zAt(C[0],C[1]))}q.Profile=JSON.stringify([B]),delete q.TopLevel,delete q.TopOffset}const K=typeof I=="string"?I:r&&c.item.guid?jf(r,c.item.guid,le):void 0;if(K&&!q.Profile){q.AttachTop=it(K);const $=Mt.get(it(K));$&&(q.AttachTopMade=$)}if(K&&typeof I!="string"&&typeof process<"u"&&((ei=process.env)!=null&&ei.RECIPE_TRACE)&&console.error(`[attach] ${c.item.guid} ${c.item.name??""} → ${K}`),!q.Profile&&!q.AttachTop&&ft){const $=[...r.elements.values()].filter(j=>j.host===c.item.guid&&!/^IFCOPENINGELEMENT$/i.test(j.ifcClass));let O=xo(r,c.item.guid,u,k,!0);const D=j=>{const E=[];for(const B of j)(!E.length||Math.hypot(B[0]-E[E.length-1][0],B[1]-E[E.length-1][1])>=.02)&&E.push(B);for(;E.length>1&&Math.hypot(E[0][0]-E[E.length-1][0],E[0][1]-E[E.length-1][1])<.02;)E.pop();return E};if(O!=null&&O.outline){const j=D(O.outline);O=j.length>=3?{...O,outline:j,holes:(O.holes??[]).map(D).filter(E=>E.length>=3)}:null}if($.length&&(O!=null&&O.outline)){const j=Math.hypot(k[0]-u[0],k[1]-u[1]),E=[(k[0]-u[0])/j,(k[1]-u[1])/j],B=$.map(C=>{const U=te(r,C.gid).map(A=>[(A[0]-u[0])*E[0]+(A[1]-u[1])*E[1],A[2]]);return U.length?[Math.min(...U.map(A=>A[0])),Math.max(...U.map(A=>A[0])),Math.min(...U.map(A=>A[1])),Math.max(...U.map(A=>A[1]))]:null}).filter(C=>C!==null),_=C=>{const U=Math.min(...C.map(at=>at[0])),A=Math.max(...C.map(at=>at[0])),X=Math.min(...C.map(at=>at[1])),Z=Math.max(...C.map(at=>at[1]));return B.some(at=>Math.min(A,at[1])-Math.max(U,at[0])>.01&&Math.min(Z,at[3])-Math.max(X,at[2])>.01)},z=(O.holes??[]).filter(C=>!_(C));O=!((ni=O.pieces)!=null&&ni.length)&&(z.length||O.outline.length>4)?{...O,holes:z}:null,O&&typeof process<"u"&&((si=process.env)!=null&&si.RECIPE_TRACE)&&console.error(`[wall-outline] ${c.item.guid}: ${$.length} hosted, ${z.length} empty hole(s) kept`)}const dt=O!=null&&O.outline?null:xo(r,c.item.guid,u,k);if(dt){typeof process<"u"&&((oi=process.env)!=null&&oi.RECIPE_TRACE)&&console.error(`[wall-top] ${c.item.guid} ${c.item.name??""}: ${dt.chain.map(([z,C])=>`${z.toFixed(2)}/${C.toFixed(2)}`).join(" ")}`);const j=Math.hypot(k[0]-u[0],k[1]-u[1]),E=[(k[0]-u[0])/j,(k[1]-u[1])/j],B=[],_=(z,C)=>{B.push((u[0]+z*E[0])*l,(u[1]+z*E[1])*l,C*l)};_(dt.lo,dt.bottom-ue),_(dt.hi,dt.bottom-ue);for(const[z,C]of[...dt.chain].reverse())_(z,C-ue);q.Profile=JSON.stringify([B]),delete q.TopLevel,delete q.TopOffset}if(O!=null&&O.outline){typeof process<"u"&&((ri=process.env)!=null&&ri.RECIPE_TRACE)&&console.error(`[wall-outline] ${c.item.guid} ${c.item.name??""}: ${O.outline.length} corners`);const j=Math.hypot(k[0]-u[0],k[1]-u[1]),E=[(k[0]-u[0])/j,(k[1]-u[1])/j],B=_=>_.flatMap(([z,C])=>[(u[0]+z*E[0])*l,(u[1]+z*E[1])*l,(C-ue)*l]);q.Profile=JSON.stringify([B(O.outline),...(O.holes??[]).map(B)]),delete q.TopLevel,delete q.TopOffset,m=(O.pieces??[]).map(_=>JSON.stringify([B(_)]))}}else if(q.Profile&&ft&&!q.AttachTop){const O=[...r.elements.values()].some(D=>D.host===c.item.guid&&!/^IFCOPENINGELEMENT$/i.test(D.ifcClass))?null:xo(r,c.item.guid,u,k,!0);if((ii=O==null?void 0:O.holes)!=null&&ii.length&&!((ai=O.pieces)!=null&&ai.length)){const D=Math.hypot(k[0]-u[0],k[1]-u[1]),dt=[(k[0]-u[0])/D,(k[1]-u[1])/D],j=E=>E.flatMap(([B,_])=>[(u[0]+B*dt[0])*l,(u[1]+B*dt[1])*l,(_-ue)*l]);try{const E=JSON.parse(q.Profile);q.Profile=JSON.stringify([...E,...O.holes.map(j)]),typeof process<"u"&&((ci=process.env)!=null&&ci.RECIPE_TRACE)&&console.error(`[wall-holes] ${c.item.guid} ${c.item.name??""}: ${O.holes.length} hole(s) added to the converter's profile`)}catch{}}}const V=(p.clippedBy??[]).filter($=>Array.isArray($.through)&&Array.isArray($.keep)&&Math.abs($.keep[2])>.05);if(!i.arcMid&&V.length&&!q.AttachTop)try{const $=Math.hypot(k[0]-u[0],k[1]-u[1]),O=L.at+W,D=q.Profile?JSON.parse(q.Profile):[[u[0]*l,u[1]*l,O*l,k[0]*l,k[1]*l,O*l,k[0]*l,k[1]*l,(O+R)*l,u[0]*l,u[1]*l,(O+R)*l]];let dt=[];for(let _=0;_+2<D[0].length;_+=3)dt.push([D[0][_]/l,D[0][_+1]/l,D[0][_+2]/l]);const j=_=>{const z=[(k[0]-u[0])/$,(k[1]-u[1])/$];let C=0;for(let U=0;U<_.length;U++){const A=_[U],X=_[(U+1)%_.length];C+=(A[0]*z[0]+A[1]*z[1])*X[2]-(X[0]*z[0]+X[1]*z[1])*A[2]}return Math.abs(C)/2},E=j(dt);for(const _ of V){const z=U=>(U[0]-_.through[0])*_.keep[0]+(U[1]-_.through[1])*_.keep[1]+(U[2]-_.through[2])*_.keep[2],C=[];for(let U=0;U<dt.length;U++){const A=dt[U],X=dt[(U+1)%dt.length],Z=z(A),at=z(X);if(Z>=0&&C.push(A),Z>=0!=at>=0){const Lt=Z/(Z-at);C.push([0,1,2].map(Ft=>A[Ft]+Lt*(X[Ft]-A[Ft])))}}dt=C}const B=dt.length>=3?j(dt):0;B>.05&&E-B>.05&&(typeof process<"u"&&((li=process.env)!=null&&li.RECIPE_TRACE)&&console.error(`[wall-clip] ${c.item.guid} ${c.item.name??""}: ${V.length} plane(s), ${E.toFixed(2)} → ${B.toFixed(2)} m²`),q.Profile=JSON.stringify([dt.flatMap(_=>[_[0]*l,_[1]*l,_[2]*l]),...D.slice(1)]),delete q.TopLevel,delete q.TopOffset)}catch{}if(!q.Profile&&ft){const $=te(r,c.item.guid),O=Math.hypot(k[0]-u[0],k[1]-u[1]);if($.length>=8&&O>.5){const D=[(k[0]-u[0])/O,(k[1]-u[1])/O],dt=[-D[1],D[0]],j=(z,C)=>{const U=$.filter(A=>{const X=(A[0]-u[0])*D[0]+(A[1]-u[1])*D[1];return X>=z*O&&X<=C*O}).map(A=>(A[0]-u[0])*dt[0]+(A[1]-u[1])*dt[1]);return U.length>=2?{c:(Math.max(...U)+Math.min(...U))/2,w:Math.max(...U)-Math.min(...U)}:null},E=j(-.02,.06),B=j(.94,1.02),_=j(.45,.55);if(E&&B&&_){const z=(E.c+B.c)/2,C=_.c-z,U=$.map(Z=>{const at=Math.min(Math.max(((Z[0]-u[0])*D[0]+(Z[1]-u[1])*D[1])/O,0),1);return(Z[0]-u[0])*dt[0]+(Z[1]-u[1])*dt[1]-z-4*C*at*(1-at)}),A=Math.max(...U)-Math.min(...U),X=A<(E.w+B.w)/2+.01&&_.w>.5*Math.min(E.w,B.w);if(typeof process<"u"&&((fi=(hi=process.env)==null?void 0:hi.RECIPE_WALL)!=null&&fi.split(",").includes(c.item.guid??""))&&console.error(`[arc-bands] ${JSON.stringify({b0:E,bm:_,b1:B,sag:C,spread:A})}`),X&&Math.abs(C)>.02&&Math.abs(C)<O/2){const Z=[(u[0]+k[0])/2+dt[0]*C,(u[1]+k[1])/2+dt[1]*C];q.LocationArc=`${Pt(Z[0]*l)},${Pt(Z[1]*l)},${Pt(ot)}`,typeof process<"u"&&((di=process.env)!=null&&di.RECIPE_TRACE)&&console.error(`[wall-arc] ${c.item.guid} ${c.item.name??""}: bows ${(C*100).toFixed(1)} cm over ${O.toFixed(2)} m`)}}}}const st=re(Y);if(st&&(q["Type.Width"]=Pt(st)),st){const $=_t.get(q.Type);$===void 0?_t.set(q.Type,st):Math.abs($-st)>.001&&(q.Type=`${q.Type} · ${Math.round(st/l*1e3)} mm`)}const tt=c.item.guid?r==null?void 0:r.elements.get(c.item.guid):void 0;if(tt!=null&&tt.layers&&tt.layers.length>1)q["Type.Layers"]=JSON.stringify([...tt.layers].reverse().map($=>[+Pt($.thickness*l),$.material??"",$.function??""])),tt.layersFlipped&&(q.FlipLayers="1");else if(typeof process<"u"&&((ui=process.env)!=null&&ui.RECIPE_PIECE_LAYERS)&&tt&&tt.pieces.length>=2&&st&&c.item.guid){const $=Math.hypot(k[0]-u[0],k[1]-u[1]),O=[(k[0]-u[0])/$,(k[1]-u[1])/$],D=[];tt.pieces.forEach((E,B)=>{const _=te(r,c.item.guid,B);if(_.length<4)return;const z=_.map(Z=>(Z[0]-u[0])*O[0]+(Z[1]-u[1])*O[1]),C=_.map(Z=>-(Z[0]-u[0])*O[1]+(Z[1]-u[1])*O[0]),U=_.map(Z=>Z[2]);if(Math.max(...z)-Math.min(...z)<Math.min(.3,.5*$)||Math.max(...U)-Math.min(...U)<.5*R)return;const A=Math.min(...C),X=Math.max(...C);D.some(Z=>Math.abs(Z[0]-A)<.002&&Math.abs(Z[1]-X)<.002)||D.push([A,X])}),D.sort((E,B)=>B[1]-E[1]);const dt=D.length?D[0][1]-D[D.length-1][0]:0,j=D.every((E,B)=>B===0||E[1]<=D[B-1][0]+.002);if(D.length>=2&&j&&Math.abs(dt-st/l)<.01){const E=[];D.forEach((C,U)=>{const A=X=>+Pt(Math.round(X*2e3)/2e3*l);U>0&&D[U-1][0]-C[1]>.003&&E.push([A(D[U-1][0]-C[1]),"","air"]),E.push([A(C[1]-C[0]),"",""])});const B=JSON.stringify(E),_=JSON.stringify([...E].reverse()),z=ct.get(q.Type);z===void 0&&ct.set(q.Type,B),z===void 0||z===B?q["Type.Layers"]=B:z===_&&(q["Type.Layers"]=z,q.FlipLayers="1"),typeof process<"u"&&((pi=process.env)!=null&&pi.RECIPE_TRACE)&&console.error(`[piece-layers] ${c.item.guid} ${q.Type}: ${B}${z&&z!==B?z===_?" (flipped)":" (the type stacks otherwise: kept)":""}`)}}if(!q["Type.Layers"]&&typeof process<"u"&&((mi=process.env)!=null&&mi.RECIPE_LAYER_EXT)){const $=(()=>{var D,dt;try{return JSON.parse(String(((dt=(D=M.get(Y))==null?void 0:D.params)==null?void 0:dt.definition)??"null"))}catch{return null}})(),O=($==null?void 0:$.layers)??[];if(O.length>1&&O.some(D=>(D.topExtension??0)>.001||(D.baseExtension??0)>.001)){q["Type.Layers"]=JSON.stringify(O.map(_=>[+Pt((_.thickness??0)*l),_.material??"",_.function??"",+Pt((_.topExtension??0)*l),+Pt((_.baseExtension??0)*l)]));const D=Math.max(...O.map(_=>_.topExtension??0)),dt=Math.max(...O.map(_=>_.baseExtension??0)),j=(_,z)=>{if(!r||!c.item.guid)return[];const C=te(r,c.item.guid);if(C.length<4)return[];const U=[Math.min(...C.map(A=>A[0])),Math.min(...C.map(A=>A[1])),Math.max(...C.map(A=>A[0])),Math.max(...C.map(A=>A[1]))];return At().filter(A=>A.box[0]<U[2]-.01&&U[0]<A.box[3]-.01&&A.box[1]<U[3]-.01&&U[1]<A.box[4]-.01&&A.box[2]<z-.01&&_<A.box[5]-.01).flatMap(A=>A.keys)},E=L.at+W+ue,B=typeof process<"u"&&((gi=process.env)!=null&&gi.RECIPE_EXT_CUT)&&!q.Profile&&D>.001&&dt<.001?j(E+R,E+R+D):[];B.length&&(q.Height||q.TopOffset)?(q["Type.Layers"]=JSON.stringify(O.map(_=>[+Pt((_.thickness??0)*l),_.material??"",_.function??""])),q.TopOffset?q.TopOffset=Pt(Number(q.TopOffset)+D*l):q.Height=Pt(Number(q.Height)+D*l),q.CutBy=[...q.CutBy?q.CutBy.split("|"):[],...B].join("|"),typeof process<"u"&&((yi=process.env)!=null&&yi.RECIPE_TRACE)&&console.error(`[layer-extension] ${c.item.guid} ${q.Type}: up ${D} to its finish's top, cut by ${B.length} slab(s)`)):(D>.001&&(q.TopExtension=Pt(D*l)),dt>.001&&(q.BaseExtension=Pt(dt*l))),typeof process<"u"&&((wi=process.env)!=null&&wi.RECIPE_TRACE)&&console.error(`[layer-extension] ${c.item.guid} ${q.Type}: top ${D}, base ${dt}`)}}typeof process<"u"&&((Ei=(bi=process.env)==null?void 0:bi.RECIPE_WALL)!=null&&Ei.split(",").includes(c.item.guid??""))&&console.error(`[wall-attrs] ${JSON.stringify(q).slice(0,1500)} style ${JSON.stringify(((vi=M.get(Y))==null?void 0:vi.params)??null).slice(0,800)}`),It(`${it(c.id)}#${i.i}`,q)&&kt++,m.forEach(($,O)=>{It(`${it(c.id)}#${i.i}p${O+1}`,{...q,Profile:$})&&kt++})}const $r=(i,c,m)=>{if(!(c>0)||c>=i)return[];const p=i-Math.floor(i/c+1e-9)*c,W=m==="beginning"?0:m==="end"?p:m==="centreLine"?i/2%c:p/2,R=[];for(let L=W;L<=i+1e-4;L+=c)L>1e-4&&L<i-1e-4&&R.push(L);return R};let Un=0,so=0;const vs=new Map;for(const i of a){if(i.kind!=="run"||i.params.of!=="curtainWall")continue;so++;const c=Ee(i,"run"),m=($i=(Ti=(Mi=c==null?void 0:c.run)==null?void 0:Mi.line)==null?void 0:Ti.curves)==null?void 0:$i[0],p=S.get(String((c==null?void 0:c.level)??i.params.level??"")),W=i.params.lookRef,R=typeof W=="string"?(Si=M.get(W))==null?void 0:Si.params:void 0;if(!(m!=null&&m.from)||!m.to||typeof(c==null?void 0:c.height)!="number"||!p||!R)continue;const L=z=>typeof z=="number"?z:Number(z)||0,Y=Math.hypot(m.to[0]-m.from[0],m.to[1]-m.from[1]),u=[(m.to[0]-m.from[0])/Y,(m.to[1]-m.from[1])/Y],k=L(R.uprightWidth)>0?null:kl(i.item.guid??void 0,u),gt=(L(R.uprightWidth)||(k?k.width/l:0))/2,Ot=(L(R.horizontalWidth)||(k?k.width/l:0))/2,ft={start:!1,end:!1,bottom:!1,top:!1};let ot=[];const yt={};if(r&&i.item.guid&&!Array.isArray(c.profile)){const z=[...r.elements.values()].filter(X=>X.parent===i.item.guid),C=X=>{const Z=te(r,X);if(!Z.length)return null;const at=Z.map(jt=>(jt[0]-m.from[0])*u[0]+(jt[1]-m.from[1])*u[1]),Lt=Z.map(jt=>jt[2]),Ft=Z.map(jt=>(jt[0]-m.from[0])*-u[1]+(jt[1]-m.from[1])*u[0]);return{t0:Math.min(...at),t1:Math.max(...at),z0:Math.min(...Lt),z1:Math.max(...Lt),a0:Math.min(...Ft),a1:Math.max(...Ft)}},U=z.map(X=>C(X.gid)).filter(X=>X!==null),A=z.filter(X=>/^IFCMEMBER$/i.test(X.ifcClass)).map(X=>C(X.gid)).filter(X=>X!==null);if(A.length&&U.length){const X=Math.min(...U.map(nt=>nt.t0)),Z=Math.max(...U.map(nt=>nt.t1)),at=Math.min(...U.map(nt=>nt.z0)),Lt=Math.max(...U.map(nt=>nt.z1)),Ft=nt=>nt.t1-nt.t0>nt.z1-nt.z0;ft.bottom=!A.some(nt=>Ft(nt)&&Math.abs(nt.z0-at)<.01),ft.top=!A.some(nt=>Ft(nt)&&Math.abs(nt.z1-Lt)<.01),ft.start=!A.some(nt=>!Ft(nt)&&Math.abs(nt.t0-X)<.01),ft.end=!A.some(nt=>!Ft(nt)&&Math.abs(nt.t1-Z)<.01);const jt=A.filter(nt=>!Ft(nt)&&nt.t0>X+.01&&nt.t1<Z-.01).map(nt=>nt.t1-nt.t0).sort((nt,Ut)=>nt-Ut),Kt=jt[Math.floor(jt.length/2)]??gt*2;for(const nt of["start","end"]){const Ut=A.filter(fe=>!Ft(fe)&&(nt==="start"?Math.abs(fe.t0-X)<.01:Math.abs(fe.t1-Z)<.01)),Vt=Ut.filter(fe=>fe.t1-fe.t0>2*Kt&&fe.a1-fe.a0>2*Kt);if(Vt.length&&Vt.length>=Ut.length/2){const fe=Vt[0],Me=nt==="start"?X:Z;yt[nt]={along:(fe.t1-fe.t0)*l,across:(fe.a1-fe.a0)*l,at:[(m.from[0]+u[0]*Me)*l,(m.from[1]+u[1]*Me)*l]},typeof process<"u"&&((xi=process.env)!=null&&xi.RECIPE_TRACE)&&console.error(`[curtain-corner] ${i.item.guid}: its ${nt} a corner bar, ${((fe.t1-fe.t0)*1e3).toFixed(0)} x ${((fe.a1-fe.a0)*1e3).toFixed(0)} mm`)}}ot=[...new Set(A.filter(nt=>!Ft(nt)&&nt.t0>X+.01&&nt.t1<Z-.01).map(nt=>+((nt.t0+nt.t1)/2).toFixed(4)))].sort((nt,Ut)=>nt-Ut),Object.values(ft).some(Boolean)&&typeof process<"u"&&((Ii=process.env)!=null&&Ii.RECIPE_TRACE)&&console.error(`[curtain-bare] ${i.item.guid}: no bar at its ${Object.entries(ft).filter(([,nt])=>nt).map(([nt])=>nt).join(", ")}`)}}const q=ft.start?0:gt,oe=ft.end?0:gt,bt=ft.bottom?0:Ot,pt=ft.top?0:Ot,wt=[m.from[0]-u[0]*q,m.from[1]-u[1]*q],x=[m.to[0]+u[0]*oe,m.to[1]+u[1]*oe],T=(typeof c.base=="number"?c.base:0)-bt,Q=c.height+bt+pt,I=(p.at+T)*l,et=$r(Y,L(R.alongSpacing),R.alongJustify),J=!((_i=c.lines)!=null&&_i.along)&&ot.length>0&&(ot.length!==et.length||ot.some((z,C)=>Math.abs(z-et[C])>.01));J&&typeof process<"u"&&((Ci=process.env)!=null&&Ci.RECIPE_TRACE)&&console.error(`[curtain-lines] ${i.item.guid}: ${ot.length} from its bars, not the type's ${et.length}`);const K=((Oi=c.lines)==null?void 0:Oi.along)??(J?ot:et),V=((Ai=c.lines)==null?void 0:Ai.up)??$r(c.height,L(R.upSpacing),R.upJustify),st=z=>{const C=/^(horizontal|vertical|upright)@(-?[\d.]+):(-?[\d.]+)$/.exec(z);if(!C)return[];const U=C[1]==="horizontal",A=Number(C[2])/1e3+(U?bt:q),X=Number(C[3])/1e3+(U?q:bt);return[{horizontal:U,at:A*l,from:X*l}]},tt=(c.omitted??[]).flatMap(st),$=(c.merged??[]).flatMap(st),O=ft.start&&ft.end&&ft.bottom&&ft.top;if(!O){const z=[0,...K.map(A=>A+q)],C=[0,...V.map(A=>A+bt)],U=Y+q+oe;if(ft.bottom)for(const A of z)tt.push({horizontal:!0,at:0,from:A*l});if(ft.top)for(const A of z)tt.push({horizontal:!0,at:Q*l,from:A*l});if(ft.start)for(const A of C)tt.push({horizontal:!1,at:0,from:A*l});if(ft.end)for(const A of C)tt.push({horizontal:!1,at:U*l,from:A*l})}const D=(c.omitted??[]).flatMap(z=>{const C=/^panel@(-?[\d.]+),(-?[\d.]+)$/.exec(z);return C?[{along:(Number(C[1])/1e3+q)*l,up:(Number(C[2])/1e3+bt)*l}]:[]});if(r&&i.item.guid)for(const z of xc(r,i.item.guid,L(R.panelDepth),[-u[1],u[0]])){const C=(z.centre[0]-m.from[0])*u[0]+(z.centre[1]-m.from[1])*u[1],U=z.centre[2]-ue-(p.at+(typeof c.base=="number"?c.base:0));if(C<-.01||C>Y+.01||U<-.01||U>c.height+.01)continue;const A=Math.max(0,...K.filter(Z=>Z<=C+1e-6)),X=Math.max(0,...V.filter(Z=>Z<=U+1e-6));D.push({along:(A+q)*l,up:(X+bt)*l}),$t.add(z.gid)}let dt=-L(R.panelOffset)*l;const j=typeof process<"u"?process.env:{},E=[];if(r&&i.item.guid){const z=[-u[1],u[0]],C=[...r.elements.values()].filter(U=>U.parent===i.item.guid&&/^IFCPLATE$/i.test(U.ifcClass)&&!$t.has(U.gid)).flatMap(U=>{const A=te(r,U.gid);if(A.length<4)return[];const X=A.map(Ft=>(Ft[0]-m.from[0])*z[0]+(Ft[1]-m.from[1])*z[1]),Z=Math.min(...X),at=Math.max(...X),Lt=[0,1,2].map(Ft=>A.reduce((jt,Kt)=>jt+Kt[Ft],0)/A.length);return[{el:U,thickness:at-Z,mid:(Z+at)/2,a:(Lt[0]-m.from[0])*u[0]+(Lt[1]-m.from[1])*u[1],u:Lt[2]-ue-(p.at+(typeof c.base=="number"?c.base:0))}]});if(C.length>1){const U=at=>[...at].sort((Lt,Ft)=>Lt-Ft)[Math.floor(at.length/2)],A=U(C.map(at=>at.thickness)),X=U(C.map(at=>at.mid)),Z=Number(j.RECIPE_PANEL_ACROSS_SIGN??1);Math.abs(L(R.panelOffset))<1e-6&&Math.abs(X)>.003&&(dt=Z*X*l,j.RECIPE_TRACE&&console.error(`[curtain-panel] ${i.item.guid}: its panels ${(X*1e3).toFixed(0)} mm off its line, by the file`));for(const at of C){if(Math.abs(at.thickness-A)<.005&&Math.abs(at.mid-X)<.005||at.a<-.01||at.a>Y+.01||at.u<-.01||at.u>c.height+.01)continue;const Lt=Math.max(0,...K.filter(jt=>jt<=at.a+1e-6)),Ft=Math.max(0,...V.filter(jt=>jt<=at.u+1e-6));E.push({along:(Lt+q)*l,up:(Ft+bt)*l,name:(at.el.typeName??at.el.name??"panel").replace(/:\d+$/,""),thickness:at.thickness*l,offset:dt+Z*(at.mid-X)*l})}E.length&&j.RECIPE_TRACE&&console.error(`[curtain-others] ${i.item.guid}: ${E.length} panel(s) of another sheet (${[...new Set(E.map(at=>`${at.name} ${(at.thickness/l*1e3).toFixed(0)} mm`))].join(", ")})`)}}const B={CategoryId:Ae.walls,Type:((Ri=hn(i))==null?void 0:Ri.type)??String(W),LocationLine:`${Pt(wt[0]*l)},${Pt(wt[1]*l)},${Pt(I)};${Pt(x[0]*l)},${Pt(x[1]*l)},${Pt(I)}`,Level:p.name,BaseOffset:Pt(T*l),Height:Pt(Q*l),Curtain:JSON.stringify({...E.length?{others:E}:{},along:K.map(z=>(z+q)*l),up:V.map(z=>(z+bt)*l),omit:tt,...$.length?{merge:$}:{},...yt.start||yt.end?{corners:yt}:{},empty:D,...O?{noBorders:!0}:{},mullion:L(R.uprightWidth)>0?{width:L(R.uprightWidth)*l,depth:L(R.depth)*l}:k??{width:0,depth:L(R.depth)*l},panel:{thickness:jn(i.item.guid??void 0,u)??L(R.panelDepth)*l,offset:dt}})},_=c.profile;if(Array.isArray(_)&&_.length>=3){const C=_.reduce((Z,at,Lt)=>{const Ft=_[(Lt+1)%_.length];return Z+at[0]*Ft[1]-Ft[0]*at[1]},0)>0?1:-1,U=_.length,A=_.map((Z,at)=>{const Lt=_[(at-1+U)%U],Ft=_[(at+1)%U],jt=(fe,Me)=>{const Se=Me[0]-fe[0],on=Me[1]-fe[1],xe=Math.hypot(Se,on)||1,Ie=C*on/xe,_s=-C*Se/xe,Cs=Math.abs(Ie)>Math.abs(_s)?gt:Ot;return{p:[fe[0]+Ie*Cs,fe[1]+_s*Cs],d:[Se,on]}},Kt=jt(Lt,Z),nt=jt(Z,Ft),Ut=Kt.d[0]*nt.d[1]-Kt.d[1]*nt.d[0];if(Math.abs(Ut)<1e-12)return[nt.p[0],nt.p[1]];const Vt=((nt.p[0]-Kt.p[0])*nt.d[1]-(nt.p[1]-Kt.p[1])*nt.d[0])/Ut;return[Kt.p[0]+Vt*Kt.d[0],Kt.p[1]+Vt*Kt.d[1]]}),X=[];for(const[Z,at]of A)X.push((m.from[0]+u[0]*Z)*l,(m.from[1]+u[1]*Z)*l,(p.at+T+Ot+at)*l);B.Profile=JSON.stringify([X])}{const z=JSON.parse(B.Curtain),C=z.mullion,U=(ki=z.panel)!=null&&ki.thickness?`, ${Math.round(z.panel.thickness/l*1e3)} mm glass`:"",A=`${Math.round(C.width/l*1e3)} x ${Math.round(C.depth/l*1e3)}${U}${z.noBorders?", no borders":""}`,X=vs.get(B.Type);X===void 0?vs.set(B.Type,A):X!==A&&(typeof process<"u"&&((Fi=process.env)!=null&&Fi.RECIPE_TRACE)&&console.error(`[curtain-type] ${i.item.guid}: ${B.Type} first made with ${X}, this one ${A}`),B.Type=`${B.Type} · ${A}`)}It(it(i.id),B)&&Un++}if(r){const i=typeof process<"u"?process.env:{},c=new Set(a.filter(R=>R.kind==="run"&&R.params.of==="curtainWall").map(R=>R.item.guid)),m=[...S.values()].sort((R,L)=>R.at-L.at),p=new Map;for(const R of r.elements.values())R.parent&&p.set(R.parent,[...p.get(R.parent)??[],R]);const W=new Set(a.filter(R=>{var L;return R.kind!=="assembly"&&((L=R.item)==null?void 0:L.guid)}).map(R=>R.item.guid));for(const[R,L]of p){if(c.has(R)||W.has(R)||r.elements.has(R)||!L.some(y=>/^IFCPLATE$/i.test(y.ifcClass))||!L.every(y=>/^IFC(PLATE|MEMBER|DOOR|WINDOW)$/i.test(y.ifcClass)))continue;const Y={gid:R,typeName:null},u=[...r.elements.values()].filter(y=>y.parent===Y.gid),k=u.filter(y=>/^IFCPLATE$/i.test(y.ifcClass)),gt=u.filter(y=>/^IFCMEMBER$/i.test(y.ifcClass));if(!k.length)continue;const Ot=[...k,...gt].flatMap(y=>te(r,y.gid));if(Ot.length<8)continue;const ft=Ot.reduce((y,ut)=>y+ut[0],0)/Ot.length,ot=Ot.reduce((y,ut)=>y+ut[1],0)/Ot.length;let yt=0,q=0,oe=0;for(const y of Ot)yt+=(y[0]-ft)**2,q+=(y[1]-ot)**2,oe+=(y[0]-ft)*(y[1]-ot);const bt=.5*Math.atan2(2*oe,yt-q),pt=[Math.cos(bt),Math.sin(bt)],wt=[-pt[1],pt[0]],x=y=>{const ut=te(r,y);if(!ut.length)return null;const zt=ut.map(Pe=>(Pe[0]-ft)*pt[0]+(Pe[1]-ot)*pt[1]),Nt=ut.map(Pe=>(Pe[0]-ft)*wt[0]+(Pe[1]-ot)*wt[1]),de=ut.map(Pe=>Pe[2]-ue),ae=Math.min(...zt),ge=Math.max(...zt),Vn=Pe=>Math.min(...de.filter((Wn,Bl)=>Math.abs(zt[Bl]-Pe)<.02));return{t0:ae,t1:ge,a0:Math.min(...Nt),a1:Math.max(...Nt),z0:Math.min(...de),z1:Math.max(...de),rise:Math.abs(Vn(ge)-Vn(ae))}},T=k.map(y=>({gid:y.gid,b:x(y.gid)})).filter(y=>!!y.b),Q=Math.min(...T.map(y=>y.b.t0)),I=Math.max(...T.map(y=>y.b.t1)),et=Math.min(...T.map(y=>y.b.z0)),J=Math.max(...T.map(y=>y.b.z1)),K=[],V=gt.flatMap(y=>{const ut=x(y.gid);return ut?ut.t1>Q-.08&&ut.t0<I+.08&&ut.z1>et-.08&&ut.z0<J+.08?[ut]:(K.push(y.gid),[]):[]}),st=[...T.map(y=>y.b),...V],tt=Math.min(...st.map(y=>y.t0)),$=Math.max(...st.map(y=>y.t1)),O=Math.min(...st.map(y=>y.z0)),D=Math.max(...st.map(y=>y.z1)),dt=Math.min(...st.map(y=>y.a0)),j=Math.max(...st.map(y=>y.a1)),E=Math.max(...st.map(y=>y.a1-y.a0));if(j-dt>Math.max(.1,1.6*E)||$-tt<.2||D-O<.2||T.some(y=>y.b.a1-y.b.a0>.12))continue;const B=y=>y.t1-y.t0>y.z1-y.z0,_=V.filter(y=>!B(y)),z=V.filter(y=>B(y)),C=y=>y.length?[...y].sort((ut,zt)=>ut-zt)[Math.floor(y.length/2)]:0,U=C(_.map(y=>y.t1-y.t0)),A=C(z.map(y=>y.z1-y.z0)),X=C(V.map(y=>y.a1-y.a0)),Z=_.some(y=>Math.abs(y.t0-tt)<.01),at=_.some(y=>Math.abs(y.t1-$)<.01),Lt=z.some(y=>Math.abs(y.z0-O)<.01),Ft=z.some(y=>Math.abs(y.z1-D)<.01),jt=V.length?C(V.map(y=>(y.a0+y.a1)/2)):C(T.map(y=>(y.b.a0+y.b.a1)/2)),Kt=i.RECIPE_CW_SPAN==="middles"?1:0,nt=tt+(Z?Kt*U/2:0),Ut=$-(at?Kt*U/2:0),Vt=O+(Lt?Kt*A/2:0),fe=D-(Ft?Kt*A/2:0),Me=Ut-nt,Se=fe-Vt,on=(y,ut)=>y.some(zt=>Math.abs(zt-ut)<.02),xe=[],Ie=[],_s=y=>Z&&Math.abs(y.t0-tt)<.01||at&&Math.abs(y.t1-$)<.01,Cs=y=>Lt&&Math.abs(y.z0-O)<.01||Ft&&Math.abs(y.z1-D)<.01,Ya=y=>{const ut=[...y].sort((de,ae)=>de[0]-ae[0]),zt=[];let Nt=null;for(const de of ut)Nt&&de[0]<=Nt[1]+.005?Nt[1]=Math.max(Nt[1],de[1]):(Nt&&zt.push((Nt[0]+Nt[1])/2),Nt=[de[0],de[1]]);return Nt&&zt.push((Nt[0]+Nt[1])/2),zt};for(const y of Ya(_.filter(ut=>!_s(ut)).map(ut=>[ut.t0,ut.t1]))){const ut=y-nt;ut>.02&&ut<Me-.02&&!on(xe,ut)&&xe.push(ut)}for(const y of Ya(z.filter(ut=>!Cs(ut)).map(ut=>[ut.z0,ut.z1]))){const ut=y-Vt;ut>.02&&ut<Se-.02&&!on(Ie,ut)&&Ie.push(ut)}for(const y of T)for(const ut of T)if(y!==ut){if(Math.abs(ut.b.z0-y.b.z1)<.06&&Math.min(y.b.t1,ut.b.t1)-Math.max(y.b.t0,ut.b.t0)>.05){const zt=(y.b.z1+ut.b.z0)/2-Vt;zt>.02&&zt<Se-.02&&!on(Ie,zt)&&Ie.push(zt)}if(Math.abs(ut.b.t0-y.b.t1)<.06&&Math.min(y.b.z1,ut.b.z1)-Math.max(y.b.z0,ut.b.z0)>.05){const zt=(y.b.t1+ut.b.t0)/2-nt;zt>.02&&zt<Me-.02&&!on(xe,zt)&&xe.push(zt)}}xe.sort((y,ut)=>y-ut),Ie.sort((y,ut)=>y-ut);const Ka=(y,ut,zt)=>{const Nt=[];for(const de of y)de<zt||de>ut-zt||(Nt.length&&de-Nt[Nt.length-1]<zt?Nt[Nt.length-1]=(Nt[Nt.length-1]+de)/2:Nt.push(de));return Nt},Xa=Math.max(.03,.5*Math.max(U,A));xe.splice(0,xe.length,...Ka(xe,Me,Xa)),Ie.splice(0,Ie.length,...Ka(Ie,Se,Xa));const Te=[0,...xe,Me],$e=[0,...Ie,Se],Gn=[],Hn=[];for(let y=0;y<Te.length;y++)for(let ut=0;ut+1<$e.length;ut++){const zt=Te[y],Nt=Vt+($e[ut]+$e[ut+1])/2;if(_.some(ae=>Math.abs((ae.t0+ae.t1)/2-nt-zt)<Math.max(.02,U)&&ae.z0<=Nt&&ae.z1>=Nt))continue;(y>0&&y<Te.length-1&&T.some(ae=>ae.b.t0<nt+zt-.05&&ae.b.t1>nt+zt+.05&&ae.b.z0<=Nt&&ae.b.z1>=Nt)?Hn:Gn).push({horizontal:!1,at:zt*l,from:$e[ut]*l})}for(let y=0;y<$e.length;y++)for(let ut=0;ut+1<Te.length;ut++){const zt=$e[y],Nt=nt+(Te[ut]+Te[ut+1])/2;if(z.some(ae=>Math.abs((ae.z0+ae.z1)/2-Vt-zt)<Math.max(.02,A)&&ae.t0<=Nt&&ae.t1>=Nt))continue;(y>0&&y<$e.length-1&&T.some(ae=>ae.b.z0<Vt+zt-.05&&ae.b.z1>Vt+zt+.05&&ae.b.t0<=Nt&&ae.b.t1>=Nt)?Hn:Gn).push({horizontal:!0,at:zt*l,from:Te[ut]*l})}const Za=!Z&&!at&&!Lt&&!Ft,Ll=U||A,Qa=V.flatMap(y=>{const ut=B(y)?y.z1-y.z0:y.t1-y.t0,zt=y.a1-y.a0;return Math.abs(ut-Ll)<.003&&Math.abs(zt-X)<.003?[]:B(y)&&y.rise>.005?[]:[{horizontal:B(y),along:((y.t0+y.t1)/2-nt)*l,up:((y.z0+y.z1)/2-Vt)*l,width:ut*l,depth:zt*l}]}),Tn=new Set(xc(r,Y.gid,X||.02,wt).map(y=>y.gid)),lo=[];let tc=!1;for(let y=0;y+1<Te.length;y++)for(let ut=0;ut+1<$e.length;ut++){const zt=nt+Te[y],Nt=nt+Te[y+1],de=Vt+$e[ut],ae=Vt+$e[ut+1],ge=(Nt-zt)*(ae-de),Vn=Math.min(ge,st.reduce((Pe,Wn)=>Pe+Math.max(0,Math.min(Nt,Wn.t1)-Math.max(zt,Wn.t0))*Math.max(0,Math.min(ae,Wn.z1)-Math.max(de,Wn.z0)),0));ge>0&&Vn>.15*ge&&Vn<.95*ge&&(tc=!0)}let Re=null;if(tc){if(Re=zf(st.map(Nt=>[Nt.t0,Nt.z0,Nt.t1,Nt.z1])),!Re){i.RECIPE_TRACE&&console.error(`[curtain-pieces] ${Y.gid}: a cell filled in part and no one outline, kept as its pieces`);continue}const y=(Nt,de)=>{for(const ae of de)if(Math.abs(Nt-ae)<.01)return ae;return Nt},ut=[nt,Ut,...xe.map(Nt=>nt+Nt)],zt=[Vt,fe,...Ie.map(Nt=>Vt+Nt)];Re=Re.map(([Nt,de])=>[y(Nt,ut),y(de,zt)]),Re=Re.filter((Nt,de)=>{const ae=Re[(de+Re.length-1)%Re.length];return Math.abs(Nt[0]-ae[0])>1e-6||Math.abs(Nt[1]-ae[1])>1e-6})}for(let y=0;y+1<Te.length;y++)for(let ut=0;ut+1<$e.length;ut++){const zt=nt+(Te[y]+Te[y+1])/2,Nt=Vt+($e[ut]+$e[ut+1])/2,de=T.filter(ge=>ge.b.t0<=zt&&ge.b.t1>=zt&&ge.b.z0<=Nt&&ge.b.z1>=Nt),ae=T.some(ge=>ge.b.t0<nt+Te[y+1]-.01&&ge.b.t1>nt+Te[y]+.01&&ge.b.z0<Vt+$e[ut+1]-.01&&ge.b.z1>Vt+$e[ut]+.01&&!Tn.has(ge.gid));(Re?!ae:!de.length||de.every(ge=>Tn.has(ge.gid)))&&lo.push({along:Te[y]*l,up:$e[ut]*l})}for(const y of Tn)$t.add(y);for(const y of K)$t.add(y);const ho=C(T.filter(y=>!Tn.has(y.gid)).map(y=>y.b.a1-y.b.a0).filter(y=>y>.002&&y<.2)),ec=C(T.filter(y=>!Tn.has(y.gid)).map(y=>(y.b.a0+y.b.a1)/2)),fo=[...m].reverse().find(y=>y.at<=Vt+.001)??m[0];if(!fo)continue;const nc=[ft+pt[0]*nt+wt[0]*jt,ot+pt[1]*nt+wt[1]*jt],sc=[ft+pt[0]*Ut+wt[0]*jt,ot+pt[1]*Ut+wt[1]*jt],oc=Vt*l,uo=hn({item:{attrs:{Name:/^IFCMEMBER$/i.test(((Ni=gt[0])==null?void 0:Ni.ifcClass)??"")?gt[0].name??"":""}}}),gn={CategoryId:Ae.walls,Type:(uo==null?void 0:uo.type)??Y.typeName??"Curtain wall",LocationLine:`${Pt(nc[0]*l)},${Pt(nc[1]*l)},${Pt(oc)};${Pt(sc[0]*l)},${Pt(sc[1]*l)},${Pt(oc)}`,Level:fo.name,BaseOffset:Pt((Vt-fo.at)*l),Height:Pt(Se*l),Curtain:JSON.stringify({along:xe.map(y=>y*l),up:Ie.map(y=>y*l),omit:Za?Gn.filter(y=>y.at>1e-6&&Math.abs(y.at-(y.horizontal?Se:Me)*l)>1e-6):Gn,...Hn.length?{merge:Hn}:{},empty:lo,...Za?{noBorders:!0}:{},...Qa.length?{bars:Qa}:{},mullion:{width:(U||A)*l,depth:(X||ho)*l},panel:{thickness:(ho||.02)*l,offset:(i.RECIPE_CW_OFFSET_SIGN==="-1"?-1:1)*(ec-jt)*l}})};{const y=JSON.parse(gn.Curtain),ut=`${Math.round(y.mullion.width/l*1e3)} x ${Math.round(y.mullion.depth/l*1e3)}${(Pi=y.panel)!=null&&Pi.thickness?`, ${Math.round(y.panel.thickness/l*1e3)} mm glass`:""}${y.noBorders?", no borders":""}`,zt=vs.get(gn.Type);zt===void 0?vs.set(gn.Type,ut):zt!==ut&&(gn.Type=`${gn.Type} · ${ut}`)}Re&&(gn.Profile=JSON.stringify([Re.flatMap(([y,ut])=>[(ft+pt[0]*y+wt[0]*jt)*l,(ot+pt[1]*y+wt[1]*jt)*l,ut*l])])),i.RECIPE_CW_DEBUG&&Y.gid.includes(i.RECIPE_CW_DEBUG)&&console.error(`[cw-debug] t0 ${nt.toFixed(3)} z0 ${Vt.toFixed(3)} L ${Me.toFixed(3)} H ${Se.toFixed(3)}
|
|
3
|
+
plates ${T.map(y=>`${(y.b.t0-nt).toFixed(2)}..${(y.b.t1-nt).toFixed(2)}/${(y.b.z0-Vt).toFixed(2)}..${(y.b.z1-Vt).toFixed(2)}`).join(" ")}
|
|
4
|
+
uprights ${_.map(y=>`${(y.t0-nt).toFixed(2)}..${(y.t1-nt).toFixed(2)}/${(y.z0-Vt).toFixed(2)}..${(y.z1-Vt).toFixed(2)}`).join(" ")}
|
|
5
|
+
rails ${z.map(y=>`${(y.t0-nt).toFixed(2)}..${(y.t1-nt).toFixed(2)}/${(y.z0-Vt).toFixed(2)}..${(y.z1-Vt).toFixed(2)}`).join(" ")}`),i.RECIPE_TRACE&&console.error(`[curtain-pieces] ${Y.gid}: ${Me.toFixed(2)} x ${Se.toFixed(2)} m, ${xe.length} + ${Ie.length} lines, ${Gn.length} out, ${Hn.length} merged, ${lo.length} empty (${Tn.size} shaped), bars ${(U*1e3).toFixed(0)}/${(A*1e3).toFixed(0)} x ${(X*1e3).toFixed(0)} mm, glass ${(ho*1e3).toFixed(0)} mm off ${((ec-jt)*1e3).toFixed(0)} mm`),It(`${e.fileId}:${Y.gid}:curtainPieces`,gn)&&Un++,so++}}let zn=0,Sr=0;const oo=i=>{var p;const c=i&&r?(p=r.elements.get(i))==null?void 0:p.parent:null;if(!c||!r)return null;const m=r.elements.get(c);return!m||/^IFCSTAIR$/i.test(m.ifcClass)?c:null},Ms=new Map;for(const i of a)if(i.kind==="stair"&&i.params.of==="stair"){const c=oo(i.item.guid??void 0);c&&Ms.set(c,(Ms.get(c)??0)+1)}const Ts=new Map,xr=(i,c,m)=>{if(!r||!i)return null;const p=Math.hypot(m[0]-c[0],m[1]-c[1]);if(!(p>0))return null;const W=[-(m[1]-c[1])/p,(m[0]-c[0])/p],R=[i,...[...r.elements.values()].filter(u=>u.parent===i).map(u=>u.gid)].flatMap(u=>te(r,u));if(R.length<4)return null;const L=R.map(u=>(u[0]-c[0])*W[0]+(u[1]-c[1])*W[1]),Y=Math.max(...L)-Math.min(...L);return Y>.3&&Y<10?Y:null};for(const i of a){if(i.kind!=="stair"||i.params.of!=="stair")continue;Sr++;const c=Ee(i,"stair"),m=i.params.lookRef,p=typeof m=="string"?(Li=M.get(m))==null?void 0:Li.params:void 0,W=S.get(String((c==null?void 0:c.level)??i.params.level??""));if(!(c!=null&&c.start)||!c.end||!(Number(c.rise)>0)||!W||!p)continue;const R=x=>typeof x=="number"?x:Number(x)||0,L=Number(c.rise),Y=R(p.maxRiser)>0?R(p.maxRiser):(Di=(Bi=c.sketch)==null?void 0:Bi.risers)!=null&&Di.length?L/(c.sketch.risers.length+1):.18,u=Math.max(1,Math.ceil(L/Y-1e-6)),k=R(p.tread),gt=x=>[x[0]*l,x[1]*l];let Ot=W.at+R(i.params.base),ft=!1;if(r&&i.item.guid){const x=te(r,i.item.guid).map(I=>I[2]-ue),T=L/u,Q=x.length?Math.min(...x):Ot;Ot-Q>.5*T&&Ot-Q<1.5*T&&(typeof process<"u"&&((ji=process.env)!=null&&ji.RECIPE_TRACE)&&console.error(`[stair-base] ${i.item.guid} ${i.item.name??""}: base ${Ot.toFixed(3)} → its shape's ${Q.toFixed(3)}`),Ot=Q,ft=!0)}const ot={family:(()=>{const x=String(m).split(":").map(T=>T.trim()).filter((T,Q,I)=>Q<I.length-1||!/^\d+$/.test(T));return x.length>=3&&/^(stairs?|escaleras?|treppen?)$/i.test(x[0])?x[1]:x[0]})(),base:Ot*l,height:L*l,risers:u,tread:k*l,width:(R(p.width)>0?R(p.width):xr(i.item.guid??void 0,c.start,c.end)??0)*l,endsWithRiser:(()=>{if(!r||!i.item.guid)return!1;const x=te(r,i.item.guid);if(x.length<4)return!1;const T=Math.max(...x.map(I=>I[2]))-ue,Q=W.at+R(i.params.base)+L;return Q-T>.5*(L/u)&&Q-T<1.5*(L/u)})(),sizes:{maxRiser:Math.ceil(L/u*1e3-1e-6)/1e3*l,minTread:k*l,waist:R(p.waist)*l,treadThickness:p.construction==="assembled"?R(p.treadThickness)*l:0,riserThickness:p.construction==="assembled"?R(p.riserThickness)*l:0,notchExtension:R(p.notchExtension)*l,notchThickness:R(p.notchThickness)*l,...p.nosing!==void 0&&Number.isFinite(Number(p.nosing))?{nosing:Number(p.nosing)*l}:{}}};typeof process<"u"&&((Ui=process.env)!=null&&Ui.RECIPE_TRACE)&&console.error(`[stair-end] ${i.item.guid} ${i.item.name??""}: ${u} risers, ends with riser ${ot.endsWithRiser}`);const yt=c.sketch;if(yt!=null&&yt.boundary&&yt.risers&&yt.risers.length>=2){const x=J=>[(J[0][0]+J[1][0])/2,(J[0][1]+J[1][1])/2],T=yt.risers.filter((J,K,V)=>K===0||Math.hypot(x(J)[0]-x(V[K-1])[0],x(J)[1]-x(V[K-1])[1])>.01),Q=(J,K)=>Math.hypot(J[0]-K[0],J[1]-K[1])<.01,I=yt.boundary,et=J=>I.some((K,V)=>{const st=I[(V+1)%I.length];return Q(K,J[0])&&Q(st,J[1])||Q(K,J[1])&&Q(st,J[0])});if(T.length>=2&&!et(T[0])){const[J,K]=[T[0],T[1]],V=[J[1][0]-J[0][0],J[1][1]-J[0][1]],st=Math.hypot(V[0],V[1]),tt=x(J),$=x(K),O=[tt[0]-$[0],tt[1]-$[1]];let D=null,dt=1/0;for(let j=0;j<I.length;j++){const E=I[j],B=I[(j+1)%I.length],_=[B[0]-E[0],B[1]-E[1]],z=Math.hypot(_[0],_[1]);if(!(z>0)||Math.abs((_[0]*V[1]-_[1]*V[0])/(z*st))>.02)continue;const C=x([E,B]),U=(C[0]-tt[0])*O[0]+(C[1]-tt[1])*O[1];U>1e-4&&U<dt&&(dt=U,D=[E,B])}D&&T.unshift(D)}T.length!==yt.risers.length&&typeof process<"u"&&((zi=process.env)!=null&&zi.RECIPE_TRACE)&&console.error(`[stair-sketch] ${i.item.guid}: riser lines ${yt.risers.length} → ${T.length}`),yt.risers=T}if(yt!=null&&yt.boundary&&yt.boundary.length>=4&&yt.risers&&yt.risers.length>=2){const x=yt.risers[0],T=(j,E)=>Math.hypot(j[0]-E[0],j[1]-E[1])<.01,Q=yt.boundary.findIndex((j,E,B)=>{const _=B[(E+1)%B.length];return T(j,x[0])&&T(_,x[1])||T(j,x[1])&&T(_,x[0])}),I=Q>0?[...yt.boundary.slice(Q),...yt.boundary.slice(0,Q)]:yt.boundary;typeof process<"u"&&((qi=process.env)==null?void 0:qi.RECIPE_STAIR)===i.item.guid&&console.error(`[stair-sketch] boundary ${JSON.stringify(I)} (turned by ${Q}) risers ${JSON.stringify(yt.risers)} tread ${k}`);const et=yt.risers[yt.risers.length-1],J=j=>[(j[0][0]+j[1][0])/2,(j[0][1]+j[1][1])/2],K=J(et);let V=1,st=1/0;for(let j=1;j<I.length;j++){const E=J([I[j],I[(j+1)%I.length]]),B=Math.abs(Math.hypot(E[0]-K[0],E[1]-K[1])-k);B<st&&(st=B,V=j)}{const j=[et[1][0]-et[0][0],et[1][1]-et[0][1]],E=Math.hypot(j[0],j[1]),B=J(yt.risers[0]);let _=-1/0,z=-1;for(let C=1;C<I.length;C++){const U=[I[(C+1)%I.length][0]-I[C][0],I[(C+1)%I.length][1]-I[C][1]],A=Math.hypot(U[0],U[1]);if(!(A>0)||Math.abs((U[0]*j[1]-U[1]*j[0])/(A*E))>.06)continue;const X=J([I[C],I[(C+1)%I.length]]),Z=Math.hypot(X[0]-B[0],X[1]-B[1]);Z>_+1e-6&&(_=Z,z=C)}z>0&&(V=z)}const tt=(j,E)=>{const B=[];for(let _=j;_!==E;_=(_+1)%I.length)B.push([gt(I[_]),gt(I[(_+1)%I.length])]);return B},$=[...tt(1,V),...tt((V+1)%I.length,0)];typeof process<"u"&&((Ji=process.env)==null?void 0:Ji.RECIPE_STAIR)===i.item.guid&&console.error(`[stair-sketch] end edge ${V} of ${I.length}`);const O=yt.risers.map(([j,E])=>[gt(j),gt(E)]);gt(I[V]),gt(I[(V+1)%I.length]);const D=O.map(([j,E])=>[(j[0]+E[0])/2,(j[1]+E[1])/2]);if(ot.sketch={boundary:$,risers:O,path:D},ot.path=[D[0],D[D.length-1]],ot.width||(ot.width=Math.hypot(O[0][1][0]-O[0][0][0],O[0][1][1]-O[0][0][1])),typeof process<"u"&&((Gi=process.env)!=null&&Gi.RECIPE_TRACE)){const j=E=>Math.hypot(E[1][0]-E[0][0],E[1][1]-E[0][1])/l;console.error(`[stair] ${i.item.guid} ${i.item.name??""}: ${$.length} sides (shortest ${(Math.min(...$.map(j))*1e3).toFixed(2)} mm), ${O.length} risers (shortest ${(Math.min(...O.map(j))*1e3).toFixed(2)} mm), walk ${D.length} points (shortest step ${(Math.min(...D.slice(1).map((E,B)=>j([D[B],E])))*1e3).toFixed(2)} mm)`)}let dt=1/0;for(let j=0;j+1<yt.risers.length;j++){const[E,B]=yt.risers[j],[_,z]=yt.risers[j+1],C=[B[0]-E[0],B[1]-E[1]],U=[z[0]-_[0],z[1]-_[1]],A=Math.hypot(C[0],C[1]),X=Math.hypot(U[0],U[1]);Math.abs((C[0]*U[1]-C[1]*U[0])/(A*X))>.001||(dt=Math.min(dt,Math.abs(((_[0]-E[0])*C[1]-(_[1]-E[1])*C[0])/A)))}if(Number.isFinite(dt)&&(ot.tread=dt*l,ot.sizes.minTread=dt*l,ft)){const j=ot.path,E=Math.hypot(j[1][0]-j[0][0],j[1][1]-j[0][1]);E>0&&(ot.path=[[j[0][0]-(j[1][0]-j[0][0])/E*dt*l,j[0][1]-(j[1][1]-j[0][1])/E*dt*l],j[1]])}}else{let x=[c.start[0],c.start[1]];if(ft&&k>0){const T=c.end[0]-c.start[0],Q=c.end[1]-c.start[1],I=Math.hypot(T,Q);I>0&&(x=[x[0]-k*T/I,x[1]-k*Q/I])}if(ot.path=[gt(x),gt([c.end[0],c.end[1]])],!(k>0)){const T=Math.hypot(c.end[0]-c.start[0],c.end[1]-c.start[1])/u;ot.tread=T*l,ot.sizes.minTread=T*l}typeof process<"u"&&((Hi=process.env)!=null&&Hi.RECIPE_TRACE)&&console.error(`[stair] ${i.item.guid} ${i.item.name??""}: straight, ${Math.hypot(c.end[0]-c.start[0],c.end[1]-c.start[1]).toFixed(3)} m, rise ${L}, ${u} risers, width ${R(p.width)}, measured ${xr(i.item.guid??void 0,c.start,c.end)}`)}const q=String(i.item.attrs.Name??""),oe=q.replace(/ Run \d+$/,""),bt=[];for(const x of a){if(x.kind!=="extrusion"||oe===q||!new RegExp(`^${oe.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")} Landing \\d+$`).test(String(x.item.attrs.Name??"")))continue;const T=Ee(x,"extrusion"),Q=T==null?void 0:T.on,I=(((Wi=(Vi=T==null?void 0:T.profile)==null?void 0:Vi.outline)==null?void 0:Wi.curves)??[]).flatMap(_=>_.from?[_.from]:[]),et=re(x.params.lookRef),J=S.get(String((T==null?void 0:T.level)??x.params.level??""));if(!(Q!=null&&Q.origin)||!Q.u||!Q.v||Math.abs(Q.v[2]??0)<.99||!I.length||!et||!J)continue;const[K,V]=[Math.min(...I.map(_=>_[0])),Math.max(...I.map(_=>_[0]))],[st,tt]=[Math.min(...I.map(_=>_[1])),Math.max(...I.map(_=>_[1]))],$=Q.origin,O=Q.u;let D=[O[1],-O[0]];const dt=[(c.start[0]+c.end[0])/2,(c.start[1]+c.end[1])/2];(dt[0]-$[0])*D[0]+(dt[1]-$[1])*D[1]<0&&(D=[-D[0],-D[1]]);const E=et/l,B=(_,z)=>[($[0]+O[0]*_+D[0]*z)*l,($[1]+O[1]*_+D[1]*z)*l];bt.push({outline:[B(K,0),B(V,0),B(V,E),B(K,E)],top:(J.at+R(x.params.base)+$[2]+tt)*l,thickness:(tt-st)*l})}bt.length&&(ot.landings=bt);const pt={CategoryId:Ae.stairs,Type:((Yi=hn(i))==null?void 0:Yi.type)??String(m),Level:W.name,Stairs:JSON.stringify(ot)};typeof process<"u"&&(((Ki=process.env)==null?void 0:Ki.RECIPE_STAIR)===i.item.guid||((Xi=process.env)==null?void 0:Xi.RECIPE_STAIR)==="*")&&console.error(`[stair-spec] ${pt.Stairs} style ${JSON.stringify(p)}`);const wt=oo(i.item.guid??void 0);if(wt&&(Ms.get(wt)??0)>1){Ts.has(wt)||Ts.set(wt,[]),Ts.get(wt).push({record:i,spec:ot,level:W.name,type:pt.Type});continue}It(it(i.id),pt)&&zn++}for(const[i,c]of Ts){const m=c.map(ft=>ft.spec).sort((ft,ot)=>Number(ft.base)-Number(ot.base)),p=Number(m[0].base),W=Math.max(...m.map(ft=>Number(ft.base)+Number(ft.height))),R=r?[...r.elements.values()].filter(ft=>ft.parent===i&&/^IFCSLAB/i.test(ft.ifcClass)).flatMap(ft=>{const ot=te(r,ft.gid);if(ot.length<4)return[];const[yt,q,oe,bt]=[Math.min(...ot.map(x=>x[0])),Math.max(...ot.map(x=>x[0])),Math.min(...ot.map(x=>x[1])),Math.max(...ot.map(x=>x[1]))],[pt,wt]=[Math.min(...ot.map(x=>x[2]))-ue,Math.max(...ot.map(x=>x[2]))-ue];return[{outline:[[yt*l,oe*l],[q*l,oe*l],[q*l,bt*l],[yt*l,bt*l]],top:wt*l,thickness:(wt-pt)*l}]}):[],L=ft=>r?[...r.elements.values()].filter(ot=>ot.parent===i&&ft.test(ot.ifcClass)):[],Y=ft=>{const ot=ft.flatMap(yt=>te(r,yt.gid));return ot.length?[Math.min(...ot.map(yt=>yt[0])),Math.max(...ot.map(yt=>yt[0])),Math.min(...ot.map(yt=>yt[1])),Math.max(...ot.map(yt=>yt[1]))]:null},u=L(/^IFCMEMBER/i);let k=null;if(u.length){const ft=Y(L(/^IFCSTAIRFLIGHT/i)),ot=Y(u),yt=ft&&ot?[ft[0]-ot[0],ot[1]-ft[1],ft[2]-ot[2],ot[3]-ft[3]].filter(I=>I>.005):[],q=[];for(const I of u){const et=new Map;for(const J of te(r,I.gid)){const K=`${Math.round(J[0]/.02)}|${Math.round(J[1]/.02)}`,V=et.get(K)??[1/0,-1/0];et.set(K,[Math.min(V[0],J[2]),Math.max(V[1],J[2])])}for(const[J,K]of et.values())K-J>.05&&q.push(K-J)}const oe=new Map;for(const I of q){const et=Math.round(I*100);oe.set(et,(oe.get(et)??0)+1)}const bt=m[0],pt=bt.tread&&bt.height&&bt.risers?Math.atan(bt.height/bt.risers/bt.tread):0,wt=u.map(I=>{const et=te(r,I.gid);if(et.length<4)return 1/0;const J=Math.max(...et.map($=>$[0]))-Math.min(...et.map($=>$[0])),K=Math.max(...et.map($=>$[1]))-Math.min(...et.map($=>$[1])),V=et.map($=>J>=K?$[0]:$[1]),st=et.map($=>$[2]),tt=$=>{const O=et.map((D,dt)=>-Math.sin($)*V[dt]+Math.cos($)*st[dt]);return Math.max(...O)-Math.min(...O)};return Math.min(tt(pt),tt(-pt),tt(0))}).filter(I=>I>.05&&I<2),x=q.length?[...oe].sort((I,et)=>et[1]-I[1]||et[0]-I[0])[0][0]/100:0,T=wt.length?Math.min(...wt):0,Q=Math.round((T>0&&T<.6?T:x)*1e3)/1e3;yt.length&&Q>0&&(k={width:Math.min(...yt)*l,depth:Q*l}),typeof process<"u"&&((Zi=process.env)!=null&&Zi.RECIPE_TRACE)&&console.error(`[stair-stringers] ${i}: ${u.length} member(s), out ${yt.map(I=>I.toFixed(3)).join("/")}, depth ${Q.toFixed(3)} of ${[...oe].sort((I,et)=>et[1]-I[1]).map(([I,et])=>`${I}cm×${et}`).join(" ")}`)}const gt={...m[0],...k?{sizes:{...m[0].sizes??{},stringerWidth:k.width,stringerDepth:k.depth}}:{},base:p,height:W-p,risers:m.reduce((ft,ot)=>ft+Number(ot.risers),0),runs:m.map(ft=>({path:ft.path,risers:ft.risers,tread:ft.tread,width:ft.width,endsWithRiser:ft.endsWithRiser,base:ft.base,height:ft.height,sketch:ft.sketch})),...R.length?{landings:R}:{}};delete gt.sketch;const Ot={CategoryId:Ae.stairs,Type:c[0].type,Level:c[0].level,Stairs:JSON.stringify(gt)};typeof process<"u"&&((Qi=process.env)!=null&&Qi.RECIPE_TRACE)&&console.error(`[stair-group] ${i}: ${m.length} flight(s), ${R.length} landing(s), ${gt.risers} risers, ${(W-p)/l} m`),It(`${e.fileId}:${i}:stair`,Ot)&&zn++}const ro=new Map;for(const i of a){if(i.kind!=="stair"||i.params.of!=="stair")continue;const c=oo(i.item.guid??void 0);c&&!ro.has(c)&&ro.set(c,(Ms.get(c)??0)>1?`${e.fileId}:${c}:stair`:it(i.id))}let Ir=0,_r=0;for(const i of a){if(i.kind!=="run"||i.params.of!=="railing")continue;_r++;const c=Ee(i,"run"),m=((ea=(ta=c==null?void 0:c.run)==null?void 0:ta.line)==null?void 0:ea.curves)??[],p=S.get(String((c==null?void 0:c.level)??i.params.level??""));if(!m.length||!p||m.some(gt=>gt.kind!=="segment"||!gt.from||!gt.to))continue;const W=[m[0].from,...m.map(gt=>gt.to)].map(gt=>[gt[0]*l,gt[1]*l]),R=String(i.params.lookRef??i.params.type??""),L=((na=hn(i))==null?void 0:na.type)??R.split(":").pop()??R,Y=i.item.guid&&r?(sa=r.elements.get(i.item.guid))==null?void 0:sa.parent:null,u=Y?ro.get(Y):void 0,k={CategoryId:Ae.railings,Type:L,Level:p.name,Railing:JSON.stringify({path:W,base:(p.at+(Number((c==null?void 0:c.base)??i.params.base)||0))*l,height:(Number((c==null?void 0:c.height)??i.params.height)||0)*l,...u?{stair:u}:{}})};It(it(i.id),k)&&Ir++}typeof process<"u"&&((oa=process.env)!=null&&oa.RECIPE_TRACE)&&console.error(`[railings] ${Ir} of ${_r}`);const Cr=new Map,vn={floor:0,foundation:0,roof:0,ceiling:0},_e={floor:0,foundation:0,roof:0,ceiling:0},Or=a.flatMap(i=>{var R,L;if(i.kind!=="extrusion"||i.params.of!=="form")return[];const c=Ee(i,"extrusion"),m=S.get(String((c==null?void 0:c.level)??i.params.level??"")),p=(((L=(R=c==null?void 0:c.profile)==null?void 0:R.outline)==null?void 0:L.curves)??[]).flatMap(Y=>Y.from?[Y.from]:[]);if(!(c!=null&&c.void)||!m||p.length<3)return[];const W=m.at+(Number(i.params.base)||0);return[{guid:i.item.guid,outline:p,from:W,to:W+(Number(c.depth??i.params.depth)||0)}]});for(const i of a){const c=i.params.of;if(i.kind!=="extrusion"||c!=="slab"&&c!=="roof"&&c!=="covering")continue;let m=c==="covering"?"ceiling":c==="roof"?"roof":Ic(i);if(m==="other"||r&&i.item.guid&&/^IFCRAMP(FLIGHT)?$/i.test(((ra=r.elements.get(i.item.guid))==null?void 0:ra.ifcClass)??""))continue;const p=Ee(i,"extrusion"),W=p==null?void 0:p.on,R=p==null?void 0:p.extruded;if(m==="roof"&&W&&((aa=(ia=R==null?void 0:R.line)==null?void 0:ia.curves)!=null&&aa.length)&&typeof R.from=="number"&&typeof R.to=="number"){const x=S.get(String((p==null?void 0:p.level)??i.params.level??"")),T=W.u??[1,0,0],Q=W.origin??[0,0,0],I=[T[1],-T[0]],et=[R.line.curves[0].from,...R.line.curves.map(K=>K.to)].filter(Boolean),J=(K,V,st)=>[(Q[0]+T[0]*K+I[0]*st)*l,(Q[1]+T[1]*K+I[1]*st)*l,(((x==null?void 0:x.at)??0)+V)*l];if(x&&et.length>=2&&typeof i.params.lookRef=="string"){const K=et.map($=>J($[0],$[1],R.from)),V=[J(et[0][0],0,R.from),J(et[et.length-1][0],0,R.from),J(et[et.length-1][0],0,R.to),J(et[0][0],0,R.from===R.to?R.to+1:R.to)].flat(),st={CategoryId:Ae.roofs,Type:((ca=hn(i))==null?void 0:ca.type)??String(i.params.lookRef),Profile:JSON.stringify([V]),Level:x.name,Extrusion:JSON.stringify({profile:K,along:I,length:(R.to-R.from)*l})},tt=re(String(i.params.lookRef));tt&&(st["Type.Width"]=Pt(tt)),vn.roof++,It(it(i.id),st)&&_e.roof++,typeof process<"u"&&((la=process.env)!=null&&la.RECIPE_TRACE)&&console.error(`[roof-extruded] ${i.item.guid} ${i.params.lookRef}: ${et.length} corner(s), ${(R.to-R.from).toFixed(3)} m along`);continue}}if(W&&(Math.abs(((ha=W.u)==null?void 0:ha[2])??0)>.001||Math.abs(((fa=W.v)==null?void 0:fa[2])??0)>.001))continue;if(m==="roof"&&!he(i)){const x=p,T=((ua=(da=p==null?void 0:p.profile)==null?void 0:da.outline)==null?void 0:ua.curves)??[];if(x!=null&&x.slope&&typeof x.slope.by=="number"&&Math.abs(x.slope.by)>.001&&typeof x.slope.toward=="number"&&!(Array.isArray(x.slopes)&&x.slopes.some(Q=>typeof Q=="number"))&&T.length>=3){const Q=[Math.cos(x.slope.toward),Math.sin(x.slope.toward)],I=T.map(V=>V.from).filter(Boolean),et=I.map(V=>V[0]*Q[0]+V[1]*Q[1]),J=Math.min(...et);I.some((V,st)=>Math.abs(et[st]-J)<.01&&Math.abs(et[(st+1)%I.length]-J)<.01)||(m="floor",typeof process<"u"&&((pa=process.env)!=null&&pa.RECIPE_TRACE)&&console.error(`[roof-as-floor] ${i.item.guid} ${i.params.lookRef}: its low side a corner, a sloped floor`))}}vn[m]++,typeof process<"u"&&((ma=process.env)==null?void 0:ma.RECIPE_SLAB)===i.item.guid&&console.error(`[slab] ${i.item.guid}: params ${JSON.stringify(i.params).slice(0,600)} body ${JSON.stringify(p).slice(0,1500)}`);const L=typeof i.params.base=="number"?i.params.base:0,Y=S.get(String((p==null?void 0:p.level)??i.params.level??"")),u=i.params.lookRef,k=x=>{if(!(x!=null&&x.length))return null;const T=[];for(const Q of x){if(Q.kind!=="segment"||!Q.from)return null;T.push(Q.from[0]*l,Q.from[1]*l,L*l)}return T.length>=9?T:null};let gt=k((ya=(ga=p==null?void 0:p.profile)==null?void 0:ga.outline)==null?void 0:ya.curves);if(typeof u!="string"||!Y||!gt)continue;const Ot=(p==null?void 0:p.regions)??[],ft=[];if(Ot.length>0){const x=K=>{const V=[];for(let st=0;st+2<K.length;st+=3)V.push([K[st]/l,K[st+1]/l]);return V},T=K=>K.flatMap(V=>[V[0]*l,V[1]*l,L*l]),Q=[gt,...Ot.map(K=>{var V;return k((V=K.outline)==null?void 0:V.curves)}).filter(K=>!!K)].map(x),I=Uf(Q),et=K=>K.reduce((V,st,tt)=>{const $=K[(tt+1)%K.length];return V+st[0]*$[1]-$[0]*st[1]},0)/2,J=I.filter(K=>et(K)>0).sort((K,V)=>et(V)-et(K));if(J.length>0){gt=T(J[0]);for(const K of[...J.slice(1),...I.filter(V=>et(V)<0)])ft.push(T(K));for(const K of Ot)for(const V of K.holes??[]){const st=k(V.curves);st&&ft.push(st)}typeof process<"u"&&((wa=process.env)!=null&&wa.RECIPE_TRACE)&&console.error(`[slab-regions] ${i.item.guid} ${i.item.name??""}: ${Q.length} pieces → ${J.length} outline(s), ${I.length-J.length} hole(s)`)}}const ot=[gt,...ft],yt=m==="roof"?he(i):null;for(const x of((ba=p==null?void 0:p.profile)==null?void 0:ba.holes)??[]){const T=k(x==null?void 0:x.curves);if(T&&yt)for(let Q=0;Q+2<T.length;Q+=3)T[Q+2]=yt.zAt(T[Q]/l,T[Q+1]/l)*l;T&&ot.push(T)}const q=[...(p==null?void 0:p.cuts)??[]],oe=Y.at+L,bt=oe+(Number(i.params.depth)||0);for(const x of Or)x.from<bt-.001&&oe<x.to-.001&&q.push({outline:x.outline,through:[0,0,x.to-x.from]});for(const x of q){const T=x.through,Q=x.outline;if(!Array.isArray(Q)||Q.length<3||!Array.isArray(T)||Math.abs(T[2])<.99*Math.hypot(T[0],T[1],T[2]))continue;const I=Q.filter((E,B)=>B===0||Math.hypot(E[0]-Q[B-1][0],E[1]-Q[B-1][1])>1e-4);if(I.length>3&&Math.hypot(I[0][0]-I[I.length-1][0],I[0][1]-I[I.length-1][1])<1e-4&&I.pop(),I.length<3)continue;const et=(E,B)=>{let _=!1;for(let z=0,C=gt.length/3-1;z<gt.length/3;C=z++){const U=gt[3*z]/l,A=gt[3*z+1]/l,X=gt[3*C]/l,Z=gt[3*C+1]/l;A>B!=Z>B&&E<(X-U)*(B-A)/(Z-A)+U&&(_=!_)}return _};if(!I.every(E=>et(E[0],E[1]))){typeof process<"u"&&((Ea=process.env)!=null&&Ea.RECIPE_TRACE)&&console.error(`[slab-cut] ${i.item.guid}: a cut across its edge, left`);continue}const J=E=>[Math.min(...E.map(B=>B[0])),Math.min(...E.map(B=>B[1])),Math.max(...E.map(B=>B[0])),Math.max(...E.map(B=>B[1]))],K=E=>{const B=[];for(let _=0;_+2<E.length;_+=3)B.push([E[_]/l,E[_+1]/l]);return B},V=J(I),st=(E,B,_)=>{let z=!1;for(let C=0,U=E.length-1;C<E.length;U=C++)E[C][1]>_!=E[U][1]>_&&B<(E[U][0]-E[C][0])*(_-E[C][1])/(E[U][1]-E[C][1])+E[C][0]&&(z=!z);return z},tt=(E,B,_)=>{const z=_[0]-B[0],C=_[1]-B[1],U=Math.max(0,Math.min(1,((E[0]-B[0])*z+(E[1]-B[1])*C)/(z*z+C*C||1)));return Math.hypot(E[0]-(B[0]+U*z),E[1]-(B[1]+U*C))},$=(E,B)=>E.some(_=>st(B,_[0],_[1])||B.some((z,C)=>tt(_,z,B[(C+1)%B.length])<.01)),O=ot.slice(1).some(E=>{const B=K(E),_=J(B);return V[0]<_[2]+.01&&_[0]<V[2]+.01&&V[1]<_[3]+.01&&_[1]<V[3]+.01&&($(I,B)||$(B,I))}),D=K(gt),dt=I.some(E=>D.some((B,_)=>{const z=D[(_+1)%D.length],C=z[0]-B[0],U=z[1]-B[1],A=C*C+U*U||1,X=Math.max(0,Math.min(1,((E[0]-B[0])*C+(E[1]-B[1])*U)/A));return Math.hypot(E[0]-(B[0]+X*C),E[1]-(B[1]+X*U))<.01}));if(O||dt){typeof process<"u"&&((va=process.env)!=null&&va.RECIPE_TRACE)&&console.error(`[slab-cut] ${i.item.guid}: a cut ${O?"over another hole":"at its edge"}, left`);continue}const j=I.flatMap(E=>[E[0]*l,E[1]*l,(yt?yt.zAt(E[0],E[1]):L)*l]);ot.push(j),typeof process<"u"&&((Ma=process.env)!=null&&Ma.RECIPE_TRACE)&&console.error(`[slab-cut] ${i.item.guid} ${i.item.name??""}: a hole of ${I.length} corners`)}const pt={CategoryId:m==="roof"?Ae.roofs:m==="ceiling"?Ae.ceilings:m==="foundation"?Ae.structuralFoundations:Ae.floors,Type:((Ta=hn(i))==null?void 0:Ta.type)??u,Profile:JSON.stringify(ot),Level:Y.name};let wt=re(u);if(m==="roof"&&r&&i.item.guid){const x=($a=r.elements.get(i.item.guid))==null?void 0:$a.layers,T=(x==null?void 0:x.reduce((I,et)=>I+(et.thickness>0?et.thickness:0),0))??0;T>0&&(!wt||Math.abs(T*l-wt)>.2*wt)&&(wt=T*l);const Q=p==null?void 0:p.slopes;if(!(Array.isArray(Q)&&Q.some(I=>typeof I=="number"))){const I=te(r,i.item.guid);if(I.length){const et=(Math.max(...I.map(J=>J[2]))-Math.min(...I.map(J=>J[2])))*l;wt&&et>wt*1.05&&et<wt*3&&(wt=et)}}}if(m==="roof"&&r&&i.item.guid){const x=Fl(i.item.guid);x&&(pt.Glazing=JSON.stringify(x),typeof process<"u"&&((Sa=process.env)!=null&&Sa.RECIPE_TRACE)&&console.error(`[glazing] ${i.item.guid} ${i.item.name??""}: ${x.bars.length} bar(s), ${x.panels} panel(s), bar ${(x.mullion.width/l*1e3).toFixed(0)} x ${(x.mullion.depth/l*1e3).toFixed(0)} mm`))}if(wt&&(pt["Type.Width"]=Pt(wt)),wt){const x=Cr.get(pt.Type);x===void 0?Cr.set(pt.Type,wt):Math.abs(x-wt)>.001&&(pt.Type=`${pt.Type} · ${Math.round(wt/l*1e3)} mm`)}if(m==="floor"&&r&&i.item.guid){const x=te(r,i.item.guid);if(x.length){const T=[0,1,2].map(I=>Math.min(...x.map(et=>et[I]))).concat([0,1,2].map(I=>Math.max(...x.map(et=>et[I])))),Q=ht.flatMap(I=>{const et=I.record.item.guid?te(r,I.record.item.guid):[];if(et.length<4)return[];const J=[0,1,2].map($=>Math.min(...et.map(O=>O[$]))).concat([0,1,2].map($=>Math.max(...et.map(O=>O[$])))),K=J[2]>T[2]+.01&&J[2]<T[5]-.01&&J[5]>T[5]&&x.some($=>Math.abs($[2]-J[2])<.005),V=J[0]<T[3]-.01&&T[0]<J[3]-.01&&J[1]<T[4]-.01&&T[1]<J[4]-.01;if(!K||!V)return[];const st=`${it(I.record.id)}#${I.i}`,tt=Mt.get(st);return tt?[st,tt]:[st]});Q.length&&(pt.CutBy=[...new Set(Q)].join("|"),typeof process<"u"&&((xa=process.env)!=null&&xa.RECIPE_TRACE)&&console.error(`[floor-cut] ${i.item.guid} ${i.item.name??""}: cut by ${Q.length} wall(s)`))}}if(m==="roof"||m==="ceiling"){pt.BaseOffset=Pt(L*l);const x=Number(i.params.drop??((Ia=p==null?void 0:p.said)==null?void 0:Ia.drop));if(m==="ceiling"&&Number.isFinite(x)&&wt){const J=[...S.values()].filter(K=>K.at>Y.at+1e-6).sort((K,V)=>K.at-V.at)[0];J&&(pt.BaseOffset=Pt((J.at-x-wt/l-Y.at)*l))}const T=p==null?void 0:p.slopes;if(m==="roof"&&Array.isArray(T)&&T.some(J=>typeof J=="number")){pt.Slopes=JSON.stringify(T.map(V=>typeof V=="number"?V:null));const J=Math.max(...T.filter(V=>typeof V=="number").map(V=>Math.abs(V)));wt&&J>0&&(pt.BaseOffset=Pt(L*l-wt*Math.sqrt(1+J*J)));const K=r&&i.item.guid?te(r,i.item.guid):[];if(wt&&J>0&&K.length>=4){const V=K.map(D=>D[2]-ue),st=Math.min(...V),tt=Y.at+L,$=tt-wt/l*Math.sqrt(1+J*J),O=tt-st;if(st-$>.01&&O>.01){const D=K.filter((Z,at)=>V[at]<st+.002),dt=Z=>[Math.min(...Z.map(at=>at[0])),Math.min(...Z.map(at=>at[1])),Math.max(...Z.map(at=>at[0])),Math.max(...Z.map(at=>at[1]))],[j,E,B,_]=dt(K),[z,C,U,A]=dt(D),X=z-j>.01&&C-E>.01&&B-U>.01&&_-A>.01;pt.EaveCut=X?"TwoCutSquare":"TwoCutPlumb",pt.FasciaDepth=Pt((X?O*Math.sqrt(1+J*J):O)*l)}typeof process<"u"&&((_a=process.env)!=null&&_a.RECIPE_TRACE)&&console.error(`[roof-eave] ${i.item.guid} ${u}: plumb low ${$.toFixed(3)}, its lowest ${st.toFixed(3)} → ${pt.EaveCut??"plumb"}${pt.FasciaDepth?`, fascia ${(Number(pt.FasciaDepth)/l).toFixed(3)}`:""}`)}typeof process<"u"&&((Ca=process.env)!=null&&Ca.RECIPE_TRACE)&&console.error(`[roof] ${i.item.guid} ${u}: slopes ${JSON.stringify(T)} base ${L} width ${wt} edges ${ot[0]?ot[0].length/3:0} profile ${JSON.stringify((Oa=ot[0])==null?void 0:Oa.map(V=>+V.toFixed(2)))}`)}const Q=m==="roof"?he(i):null;if(Q){const{A:J,n:K,u:V,W:st,ridge:tt,si:$,ti:O,tj:D,L:dt}=Q,j=(E,B)=>[(J[0]+K[0]*E)*l,(J[1]+K[1]*E)*l,B*l];pt.Extrusion=JSON.stringify({profile:[j(0,O),j(tt,O+$*tt),j(st,D)],along:[V[0],V[1]],length:dt*l}),delete pt.Slopes}const I=p==null?void 0:p.slope,et=((Ra=(Aa=p==null?void 0:p.profile)==null?void 0:Aa.outline)==null?void 0:Ra.curves)??[];if(m==="roof"&&!Q&&!pt.Slopes&&I&&typeof I.by=="number"&&Math.abs(I.by)>.001&&typeof I.toward=="number"&&et.length>=3){const J=[Math.cos(I.toward),Math.sin(I.toward)],K=et.map($=>$.from).filter(Boolean),V=K.map($=>$[0]*J[0]+$[1]*J[1]),st=Math.min(...V),tt=K.map(($,O)=>Math.abs(V[O]-st)<.01&&Math.abs(V[(O+1)%K.length]-st)<.01);if(K.length===et.length&&tt.some(Boolean)){pt.Slopes=JSON.stringify(tt.map(O=>O?Math.tan(Math.abs(I.by)):null)),pt.BaseOffset=Pt(L*l);const $=r&&i.item.guid?te(r,i.item.guid):[];if($.length>=4){const O=Math.min(...$.map(D=>D[2]))-ue;Y.at+L-O>.5*Math.tan(Math.abs(I.by))*(Math.max(...V)-st)&&(pt.BaseOffset=Pt((O-Y.at)*l))}}typeof process<"u"&&((ka=process.env)!=null&&ka.RECIPE_TRACE)&&console.error(`[roof-plane] ${i.item.guid} ${u}: ${(I.by*180/Math.PI).toFixed(1)}° toward ${(I.toward*180/Math.PI).toFixed(1)}°, eaves ${JSON.stringify(tt)}`)}}else if(wt){pt.HeightOffset=Pt(L*l+wt);const x=p==null?void 0:p.slope,T=((Na=(Fa=p==null?void 0:p.profile)==null?void 0:Fa.outline)==null?void 0:Na.curves)??[];if(x&&typeof x.by=="number"&&Math.abs(x.by)>1e-4&&typeof x.toward=="number"&&T.length>=3){const Q=[Math.cos(x.toward),Math.sin(x.toward)],I=T.map(tt=>tt.from).filter(Boolean),et=I.map(tt=>tt[0]*Q[0]+tt[1]*Q[1]),J=Math.min(...et),K=Math.max(...et),V=I[et.indexOf(J)],st=Math.tan(x.by);if(K-J>.001){pt.Slope=Pt(st),pt.SlopeArrow=JSON.stringify([V[0]*l,V[1]*l,(V[0]+Q[0]*(K-J))*l,(V[1]+Q[1]*(K-J))*l]),pt.HeightOffset=Pt(L*l+wt-st*(K-J)*l);const tt=r&&i.item.guid?te(r,i.item.guid):[];if(tt.length>=4){const $=Math.min(...tt.map(O=>O[2]))-ue;pt.HeightOffset=Pt(($-Y.at)*l+wt*Math.sqrt(1+st*st)),typeof process<"u"&&((Pa=process.env)!=null&&Pa.RECIPE_TRACE)&&console.error(`[slab-slope] ${i.item.guid} ${u}: lowest ${$.toFixed(3)} level ${Y.at.toFixed(3)} base ${L.toFixed(3)} rise ${(st*(K-J)).toFixed(3)}: top at its low corner ${($+wt*Math.sqrt(1+st*st)/l).toFixed(3)} (by base ${(Y.at+L+wt/l-st*(K-J)).toFixed(3)})`)}}}}It(it(i.id),pt)&&_e[m]++}let $s=0,Ar=0;for(const i of a){if(i.kind!=="member"||i.params.of!=="column")continue;Ar++;const c=Ee(i,"member"),m=c==null?void 0:c.start;if(!m||m.length!==3)continue;const p=w?Io(i.params.lookRef):null;if(w&&!p||!p&&!d)continue;const W=p??{family:d.family,type:d.type},R=S.get(String((c==null?void 0:c.level)??""));It(it(i.id),{...d&&!p?{CategoryId:d.categoryId}:{},Family:W.family,Type:W.type,...R?{Level:R.name}:{}},{position:[m[0]*l,m[1]*l,m[2]*l],rotationDeg:(Number((c==null?void 0:c.roll)??0)||0)*_c})&&$s++}let Ss=0,Rr=0,io=0,qn=0;for(const i of a){if(i.kind!=="familyInstance")continue;if(i.params.host||(La=Ee(i,"instance"))!=null&&La.host){const L=Ee(i,"instance"),Y=String(i.params.host??(L==null?void 0:L.host)??""),u=L!=null&&L.hole?a.find(pt=>pt.id===L.hole):void 0,k=a.find(pt=>pt.id===Y);let gt=(Ba=L==null?void 0:L.placement)==null?void 0:Ba.at,Ot=it(Y);if(u&&k){const pt=Number(u.params.along),wt=Number(u.params.width??0),x=ht.filter(Q=>Q.record===k);let T=pt+wt/2;for(const Q of x){const I=Math.hypot(Q.to[0]-Q.from[0],Q.to[1]-Q.from[1]);if(T<=I+1e-9||Q===x[x.length-1]){const et=I>0?Math.min(1,Math.max(0,T/I)):0,J=S.get(String(((Da=Ee(k,"run"))==null?void 0:Da.level)??""));gt=[Q.from[0]+(Q.to[0]-Q.from[0])*et,Q.from[1]+(Q.to[1]-Q.from[1])*et,((J==null?void 0:J.at)??0)+Number(u.params.sill??0)],Ot=`${it(Y)}#${Q.i}`;break}T-=I}}const ft=`${String(i.params.type??"")} ${i.item.category??""} ${i.item.name??""}`,ot=/window|ventana/i.test(ft)&&!/door|puerta/i.test(ft),yt=w?Io(i.params.lookRef??i.params.type):null,q=ot?b:h;if(!Y||!gt||gt.length!==3||!yt&&!q){io++;continue}const oe=a.find(pt=>pt.id===Y),bt=oe?S.get(String(((ja=Ee(oe,"run"))==null?void 0:ja.level)??"")):void 0;It(it(i.id),{CategoryId:yt?ot?"-2000014":"-2000023":q.categoryId,Family:yt?yt.family:q.family,Type:yt?yt.type:q.type,...bt?{Level:bt.name}:{}},{position:[gt[0]*l,gt[1]*l,gt[2]*l],host:Ot})&&qn++;continue}if(Rr++,!F)continue;const c=Ee(i,"instance"),m=(Ua=c==null?void 0:c.placement)==null?void 0:Ua.at;if(!m||m.length!==3)continue;const p=Io(i.params.type);if(!p)continue;const W=(za=c==null?void 0:c.placement)==null?void 0:za.right,R=W?Math.atan2(W[1],W[0])*_c:0;It(it(i.id),{Family:p.family,Type:p.type},{position:[m[0]*l,m[1]*l,m[2]*l],rotationDeg:R})&&Ss++}let ao=0;if(r&&G.RECIPE_REBAR!=="0")for(const i of r.elements.values()){if(!i.rebar||i.rebar.path.length<2)continue;const c={CategoryId:Ae.rebar,Type:(i.typeName??i.objectType??i.name??"Rebar").replace(/^.*?:\s*/,"").trim()||"Rebar",Rebar:JSON.stringify({diameter:2*i.rebar.radius*l,path:i.rebar.path.map(m=>[m[0]*l,m[1]*l,m[2]*l]),...(((qa=i.rebar.paths)==null?void 0:qa.length)??0)>1?{others:i.rebar.paths.slice(1).map(m=>m.map(p=>[p[0]*l,p[1]*l,p[2]*l]))}:{}})};It(`${e.fileId}:${i.gid}:rebar`,c)&&ao++}ao&&G.RECIPE_TRACE&&console.error(`[rebar] ${ao} bar(s) as rebar`),$t.size&&typeof process<"u"&&((Ja=process.env)!=null&&Ja.RECIPE_TRACE)&&console.error(`[shaped-panels] ${$t.size} curtain panel(s) made as families of their shape`);const Mn=r?xl(r,Tt,e.fileId,$t).filter(i=>!Or.some(c=>c.guid&&i.key.includes(c.guid))):[];if(typeof process<"u"&&((Ga=process.env)!=null&&Ga.RECIPE_TRACE)){const i={};for(const c of Mn)i[c.attrs.ShapeCategory]=(i[c.attrs.ShapeCategory]??0)+1;console.error(`[shaped-categories] ${JSON.stringify(i)}`)}if(typeof process<"u"&&((Ha=process.env)!=null&&Ha.RECIPE_GID))for(const i of Mn.filter(c=>c.key.includes(process.env.RECIPE_GID)))console.error(`[shaped] ${i.key} at ${i.at} turn ${i.rotationDeg} host ${i.host} ${JSON.stringify({...i.attrs,Shape:i.attrs.Shape?"…":void 0})}`);let xs=0;const Is=new Map;for(const i of Mn){if(!i.attrs.Family||Is.has(i.attrs.Family))continue;const c={};for(const m of["Shape","Prism"])i.attrs[m]&&(c[m]=i.attrs[m]);Object.keys(c).length&&Is.set(i.attrs.Family,c)}const kr=new Set;for(const i of Mn){const c=i.attrs.Family;!c||!Is.has(c)||!(i.attrs.Shape||i.attrs.Prism)||Rt(i.key,i.host&&Mt.get(i.host)?{...i.attrs,HostMade:Mt.get(i.host)}:i.attrs,{position:[i.at[0]*l,i.at[1]*l,(i.at[2]-ue)*l],rotationDeg:i.rotationDeg,...i.host?{host:i.host}:{}})&&kr.add(c)}for(const i of Mn){const c=i.attrs.Family,m={position:[i.at[0]*l,i.at[1]*l,(i.at[2]-ue)*l],rotationDeg:i.rotationDeg,...i.host?{host:i.host}:{}},p=i.host&&Mt.get(i.host)?{...i.attrs,HostMade:Mt.get(i.host)}:i.attrs,W=c&&kr.has(c)&&!(i.attrs.Shape||i.attrs.Prism)&&!Rt(i.key,p,m)?{...i.attrs,...Is.get(c)}:i.attrs;It(i.key,i.host&&Mt.get(i.host)?{...W,HostMade:Mt.get(i.host)}:W,{position:[i.at[0]*l,i.at[1]*l,(i.at[2]-ue)*l],rotationDeg:i.rotationDeg,...i.host?{host:i.host}:{}})&&xs++}if(r)for(const i of Ff(r,Tt,e.fileId)){const c=(Va=Jt.get(i.host))==null?void 0:Va.Profile;if(c)try{const m=JSON.parse(c),p=[];for(let Y=0;Y+2<i.box.length;Y+=3)p.push([i.box[Y]*l,i.box[Y+1]*l,(i.box[Y+2]-ue)*l]);const W=(Y,u)=>[Math.min(...Y.map(k=>k[u])),Math.max(...Y.map(k=>k[u]))],R=[0,1,2].map(Y=>W(p,Y));if(m.slice(1).some(Y=>{const u=[];for(let k=0;k+2<Y.length;k+=3)u.push([Y[k],Y[k+1],Y[k+2]]);return u.length>=3&&[0,1,2].every(k=>{const gt=W(u,k);return gt[0]<R[k][1]+.03&&R[k][0]<gt[1]+.03})})){typeof process<"u"&&((Wa=process.env)!=null&&Wa.RECIPE_TRACE)&&console.error(`[opening] ${i.key}: its wall's outline has its holes`);continue}}catch{}It(i.key,{WallOpening:i.box.map((m,p)=>Pt((p%3===2?m-ue:m)*l)).join(","),...Mt.get(i.host)?{HostMade:Mt.get(i.host)}:{}},{host:i.host})}if(r)for(const i of Lf(r,e.fileId))It(i.key,{Room:"1",Name:i.name,Number:i.number,Height:Pt(i.height*l)},{position:[i.at[0]*l,i.at[1]*l,(i.at[2]-ue)*l]});let co=0;const Nl=new Set(["slab","roof","covering"]);for(const i of a){const c=i.params.of;(i.kind==="footing"||i.kind==="ramp"||i.kind==="stair"&&c!=="stair"||i.kind==="extrusion"&&!Nl.has(String(c))||i.kind==="extrusion"&&c==="slab"&&Ic(i)==="other"&&!/ Landing \d+$/.test(String(i.item.attrs.Name??""))||i.kind==="run"&&c!=="wall"&&c!=="curtainWall")&&co++}Et();let Jn=0;for(const[i,c]of Mt)!i.startsWith(`${e.fileId}:`)||Tt.has(i)||(St.remove(c),Jn++);if(St.length===0)throw new Er(`Up to date: "${e.name}" holds ${ne} element(s) this recipe already made, ${io+co} waiting on the applier, and nothing is left to remove.`);const Pl=[Ct?`${Ct} level(s)`:"",kt?`${kt} wall(s)`:"",Un?`${Un} curtain wall(s)`:"",_e.floor?`${_e.floor} floor(s)`:"",_e.foundation?`${_e.foundation} foundation slab(s)`:"",_e.roof?`${_e.roof} roof(s)`:"",_e.ceiling?`${_e.ceiling} ceiling(s)`:"",zn?`${zn} stair(s)`:"",$s?`${$s} column(s)`:"",Ss?`${Ss} instance(s)`:"",qn?`${qn} door(s) and window(s)`:"",xs?`${xs} family instance(s)`:"",ee?`${ee} changed`:"",Jn?`${Jn} gone`:""].filter(Boolean);return{title:`${s==="ifc"?"IFC":"Model"} to native model: ${Pl.join(", ")}`,verb:St.summary,targets:St.length,payload:new Blob([await St.build(t.opId)]),ruleTallies:[{read:S.size,written:Ct},{read:ht.length+mt,written:kt},{read:so,written:Un},{read:vn.floor+vn.foundation,written:_e.floor+_e.foundation},{read:vn.roof,written:_e.roof},{read:vn.ceiling,written:_e.ceiling},{read:Sr,written:zn},{read:Ar,written:$s},{read:Rr+qn,written:Ss+qn},{read:Mn.length,written:xs},{read:Jn,written:Jn},{read:io+co,written:0}]}}}const Jf={type:"object",properties:{columnType:{type:"object",title:"Column type","x-existing":{of:"family-type",from:"target",where:{CategoryId:"-2001330"}}},doorType:{type:"object",title:"Door type","x-existing":{of:"family-type",from:"target",where:{CategoryId:"-2000023"}}},windowType:{type:"object",title:"Window type","x-existing":{of:"family-type",from:"target",where:{CategoryId:"-2000014"}}},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}}},Gf=[{reads:"Levels (datums)",writes:"The same level in the modelling tool, 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:"The modelling tool'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 native 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 with no type to give them, footings, ramps, other bodies",writes:"Nothing yet - read and counted (hosted doors and windows go in their wall as the Door/Window type chosen)"}],_l=`
|
|
3
6
|
## How to use it
|
|
4
7
|
|
|
5
|
-
In
|
|
8
|
+
In the modelling tool, with the That Open plugin: **That Open > Select recipe**, pick this
|
|
6
9
|
one and its source, then **Update**. It runs there and then: the model
|
|
7
|
-
is read, and
|
|
10
|
+
is read, and the modelling tool gets the building in one transaction (Ctrl+Z undoes all of
|
|
8
11
|
it). Apply it again whenever the source changes: only the difference is
|
|
9
12
|
written. Publish to That Open as usual, and the document's history shows the
|
|
10
13
|
step, with the recipe and the version of the source it read.
|
|
11
14
|
|
|
12
15
|
## What it does
|
|
13
16
|
|
|
14
|
-
It reads the platform's records and builds in
|
|
17
|
+
It reads the platform's records and builds in the modelling tool the building they
|
|
15
18
|
describe - levels, walls, curtain walls, floors, roofs, ceilings, stairs,
|
|
16
19
|
columns and (opting in) free-standing instances, levels first. Everything is
|
|
17
20
|
made NATIVELY: real walls on real levels, never imported meshes.
|
|
@@ -21,7 +24,7 @@ made NATIVELY: real walls on real levels, never imported meshes.
|
|
|
21
24
|
Walls: the location line per straight segment, the type by its exact name
|
|
22
25
|
(with its width, so a missing type is created by duplication), the level by
|
|
23
26
|
name, base offset, height and which ends join; an edited profile, or a top
|
|
24
|
-
attached to a roof. Curtain walls:
|
|
27
|
+
attached to a roof. Curtain walls: the modelling tool's own system, its grid lines,
|
|
25
28
|
mullions and panels. Floors, foundation slabs and ceilings: the boundary
|
|
26
29
|
loops, holes included. Roofs: by footprint with their sloping edges, or by
|
|
27
30
|
extrusion for a gable. Stairs: a straight or sketched run, with its landings.
|
|
@@ -33,7 +36,7 @@ elevation - ENSURED, so a level the model already has is simply used.
|
|
|
33
36
|
Apply it again and it writes only the difference: new records are made, a
|
|
34
37
|
changed one is made again from its new version, and one that is gone has its
|
|
35
38
|
element removed. It only ever touches what it made itself; elements a person
|
|
36
|
-
made in
|
|
39
|
+
made in the modelling tool are invisible to it. What it made is remembered with the
|
|
37
40
|
model's That Open data.
|
|
38
41
|
|
|
39
42
|
## What still waits
|
|
@@ -44,41 +47,41 @@ are read and counted, and their rule row says so.
|
|
|
44
47
|
|
|
45
48
|
## Units and axes
|
|
46
49
|
|
|
47
|
-
Records are metres and radians, Z up;
|
|
48
|
-
matched exactly by name;
|
|
50
|
+
Records are metres and radians, Z up; the modelling tool gets feet and degrees. Types are
|
|
51
|
+
matched exactly by name; the modelling tool refuses the whole apply when a loadable type is
|
|
49
52
|
missing (system types are created from their width instead).
|
|
50
|
-
`,
|
|
53
|
+
`,Mr={name:"frag-to-revit",title:"Platform model to native model",description:"Builds in the modelling tool 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:Jf,rules:Gf,doc:_l,run:Il("frag")},Cl={...Mr,name:"ifc-to-revit",title:"IFC to native model",description:"Builds an IFC of the project in the modelling tool as native elements: levels, walls, floors, roofs, stairs, curtain walls, columns, instances.",inputs:["ifc-model"],source:{kind:"project-file",extensions:["ifc"]},doc:`
|
|
51
54
|
## Point it at the IFC
|
|
52
55
|
|
|
53
56
|
It reads the IFC file itself, the version uploaded last. Its first step
|
|
54
57
|
converts it into the platform's records - what each element is, not only its
|
|
55
|
-
shape - and
|
|
56
|
-
`+
|
|
58
|
+
shape - and the modelling tool gets those. Nothing has to be prepared before.
|
|
59
|
+
`+_l,run:Il("ifc")},Hf={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},Ol="rhino-to-revit",Vf=`recipe:${Ol}`;function Wf(s){const t=(s.attrs.Position??"").split(",").map(e=>Number(e.trim()));return t.length!==3||t.some(e=>!Number.isFinite(e))?null:[t[0],t[1],t[2]]}const Al={name:Ol,title:"Layer to native model",description:"Places in the modelling tool an instance of a chosen type at each placed object of a layer.",to:"revit",inputs:["rhino-model"],source:{kind:"project-file",extensions:["frag"]},settingsSchema:{type:"object",properties:{layer:{type:"string",title:"Layer","x-existing":{of:"layer",from:"source"}},instanceType:{type:"object",title:"Type","x-existing":{of:"family-type",from:"target"}}},required:["layer"]},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 the source",writes:"That instance removed"},{reads:"Everything on other layers",writes:"Nothing"}],doc:`
|
|
57
60
|
## What it does
|
|
58
61
|
|
|
59
|
-
It reads a model published from
|
|
62
|
+
It reads a model published from a shape modeller and places in the modelling tool instances of one
|
|
60
63
|
type: one where each placed object of a layer stands. It never touches the
|
|
61
|
-
|
|
64
|
+
the shape modeller model. In the modelling tool: That Open > Select recipe, then Update.
|
|
62
65
|
|
|
63
66
|
## It reconciles, it does not push
|
|
64
67
|
|
|
65
|
-
Apply it again after the
|
|
68
|
+
Apply it again after the source model changed and it writes only the
|
|
66
69
|
difference: new objects become new instances, moved objects move theirs, and
|
|
67
70
|
an object that is gone has its instance removed. It only ever removes an
|
|
68
|
-
instance it made itself - elements a person made in
|
|
71
|
+
instance it made itself - elements a person made in the modelling tool are invisible to
|
|
69
72
|
it. What it made is remembered with the model's That Open data.
|
|
70
73
|
|
|
71
74
|
## What it assumes
|
|
72
75
|
|
|
73
|
-
- The
|
|
76
|
+
- The shape modeller model declares its units. One that does not is refused, not guessed.
|
|
74
77
|
- Both models are Z up. A different axis convention is refused.
|
|
75
|
-
- The
|
|
78
|
+
- The modelling tool type exists in the target. the modelling tool matches a type exactly and
|
|
76
79
|
refuses the whole apply when one is missing.
|
|
77
80
|
|
|
78
81
|
## What it does not know
|
|
79
82
|
|
|
80
|
-
Where an object becomes an instance,
|
|
83
|
+
Where an object becomes an instance, the modelling tool decides the level: the nearest one
|
|
81
84
|
at or below the point. For a level-based family the level wins over the
|
|
82
85
|
point's height.
|
|
83
|
-
`,async run(s){var
|
|
86
|
+
`,async run(s){var St;const{layer:t,instanceType:e}=s.settings;if(!t)throw new Error("Choose the layer.");const{picked:n,contents:o,shapes:r}=await wr(s,s.input,{shapes:!e});if(!e&&!r)throw new Error("Choose the type: this app cannot read the shapes of the source model to make its own families.");const a=(St=o.metadata)==null?void 0:St.data,f=a==null?void 0:a.units,g=typeof f=="string"?Hf[f.trim().toLowerCase()]:void 0;if(!g)throw new Error(`"${n.name}" does not say what units its data is in${f?` ("${String(f)}" is not one this recipe knows)`:""}, so nothing can be converted from it.`);const d=String((a==null?void 0:a.axes)??"z-up").toLowerCase();if(d!=="z-up")throw new Error(`"${n.name}" declares its data as "${d}"; this recipe only converts Z up.`);const h=g*sn,b=Ws(s),w=new to({project:s.projectId,document:s.target.docId??"",baseCommit:s.target.version??0,author:Vf});let F=0,P=0,S=0;const M=new Set,v=[];if(!e&&r){const l=new Set(o.items.filter(xt=>xt.guid&&(xt.attrs.Layer??"")===t).map(xt=>xt.guid));S=o.items.filter(xt=>xt.guid&&Object.keys(xt.attrs).length&&(xt.attrs.Layer??"")!==t).length;const Ht={geometries:r.geometries,elements:new Map([...r.elements].filter(([xt])=>l.has(xt)))},it=new Map;Ws(s,it);const Tt=(xt,lt,Et)=>{const Rt=JSON.stringify({a:Object.fromEntries(Object.entries(xt).filter(([It])=>It!=="Shape"&&It!=="Prism").sort()),p:lt.map(It=>Math.round(It*1e4)/1e4),r:Math.round(Et*1e3)/1e3});let Jt=2166136261;for(let It=0;It<Rt.length;It++)Jt^=Rt.charCodeAt(It),Jt=Math.imul(Jt,16777619);return(Jt>>>0).toString(36)},$t=xl(Ht,new Set,n.fileId),ne=new Map;for(const xt of $t){const lt={};for(const Et of["Shape","Prism"])xt.attrs[Et]&&(lt[Et]=xt.attrs[Et]);xt.attrs.Family&&Object.keys(lt).length&&!ne.has(xt.attrs.Family)&&ne.set(xt.attrs.Family,lt)}const ee=new Set;for(const xt of $t){const lt=xt.key.split(":")[1]??xt.key;M.add(lt);const Et=[xt.at[0]*sn,xt.at[1]*sn,xt.at[2]*sn],Rt=Tt(xt.attrs,Et,xt.rotationDeg),Jt=b.get(lt);if(Jt&&it.get(lt)===Rt)continue;Jt&&(w.remove(Jt),P++);const It=xt.attrs.Family,re=It&&!ee.has(It)?{...xt.attrs,...ne.get(It)??{}}:Object.fromEntries(Object.entries(xt.attrs).filter(([he])=>he!=="Shape"&&he!=="Prism"));It&&ee.add(It),w.add({...re,"flow:print":Rt},{position:Et,rotationDeg:xt.rotationDeg,source:lt}),F++}}else for(const l of o.items){if(!l.guid||Object.keys(l.attrs).length===0)continue;if((l.attrs.Layer??"")!==t){S++;continue}const Ht=Wf(l);if(!Ht)continue;M.add(l.guid);const it=[Ht[0]*h,Ht[1]*h,Ht[2]*h],Tt=b.get(l.guid);Tt?v.push({instance:Tt,object:l.guid,position:it}):(w.add({CategoryId:e.categoryId,Family:e.family,Type:e.type},{position:it,source:l.guid}),F++)}for(const l of v)w.set(l.instance,{},{position:l.position,source:l.object}),P++;let G=0;for(const[l,Ht]of b)M.has(l)||(w.remove(Ht),G++);const vt=F+P+G;if(vt===0)throw new Er(`Nothing to write: layer "${t}" of "${n.name}" has no placed object, and nothing of this recipe is left to remove.`);return{title:`From the source: ${[F?`${F} new`:"",P?`${P} moved`:"",G?`${G} gone`:""].filter(Boolean).join(", ")}`,verb:w.summary,targets:vt,payload:new Blob([await w.build(s.opId)]),ruleTallies:[{read:F,written:F},{read:P,written:P},{read:G,written:G},{read:S,written:0}]}}},Rl=[Al,Cl,Mr];function Yf(s){for(const t of Rl)s.recipes.register(t)}const Kf={MAX_FIELDS:200,MAX_KEY_LENGTH:50,MAX_VALUE_LENGTH:50},Xf={uuid:"a3f82c1d-5b74-4e9a-bc30-d7e12f894a61"},Zf={uuid:"2c9f4e8d-3a1b-4c5e-9d7f-0a2b6c8e1d3f"},Qf={uuid:"b0b5e2a2-0b3a-4a6b-8b1c-0b1c4a6b8b1c"},td={uuid:"d8f3a1c2-6b4e-4f9a-8c1d-2e7b5a9f3c60"},ed={uuid:"3f9c1a7e-6b2d-4e18-9a5c-7d0e2f4b6c81"},nd={uuid:"2c4ae432-fc24-43e9-9783-0c960c674e96"},sd={uuid:"6f3a9c2e-8b1d-4e6a-9c3f-1d7b5a8e2c4f"},od={uuid:"69af63aa-19ba-4fc7-b17b-75647bac1d76"},rd={uuid:"234f1416-528d-452a-9cc9-a16c5239b2eb"};exports.AppCache=gl;exports.CDEManager=Xf;exports.ChannelClient=Ml;exports.ChannelRoom=vr;exports.ClashesManager=Zf;exports.CollabRoom=bl;exports.DOCUMENT_FILE=ns;exports.DOCUMENT_SCHEMA=ls;exports.DOCUMENT_TYPES=pr;exports.DocumentDrafts=ol;exports.EngineServicesClient=Ys;exports.ExternalRoom=El;exports.FileList=Qf;exports.FlowDoc=jo;exports.GISManager=td;exports.GitHistoryManager=ed;exports.HelloWorld=nd;exports.METADATA_LIMITS=Kf;exports.OP_SCHEMA=gr;exports.OperationBuilder=to;exports.PROJECT_RECIPE_SCHEMA=br;exports.PlatformClient=or;exports.ProjectDocuments=mr;exports.ProjectHistory=fr;exports.ProjectManager=sd;exports.ProjectRecipes=ul;exports.RECIPE_NAME=fl;exports.RecipeKit=hl;exports.Recipes=pl;exports.RequestError=no;exports.SELF_VIEWING_FORMATS=Xc;exports.SERVICES_SDK_CONNECTOR_ID=_o;exports.STORAGE_BATCH_MAX=Wo;exports.StaleHistoryError=Lo;exports.TopicsManager=od;exports.UIManager=rd;exports.UpToDate=Er;exports.builtinRecipes=Rl;exports.compileRecipe=Vo;exports.describeChanges=hf;exports.documentTypeOf=zo;exports.ifcToNative=Cl;exports.latestVersions=ml;exports.layerToNative=Al;exports.mintGuid=ur;exports.orderByGraph=dr;exports.platformModelToNative=Mr;exports.readFrag=eo;exports.refreshBrowserSession=Oc;exports.registerBuiltinRecipes=Yf;exports.signInWithBrowser=Cc;exports.stampOf=Vs;exports.windowTransport=wl;
|
|
84
87
|
//# sourceMappingURL=index.cjs.js.map
|