@thatopen/services 0.32.0 → 0.33.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs.js CHANGED
@@ -1,5 +1,5 @@
1
- "use strict";var Fi=Object.create;var jn=Object.defineProperty;var Li=Object.getOwnPropertyDescriptor;var Pi=Object.getOwnPropertyNames;var Bi=Object.getPrototypeOf,ji=Object.prototype.hasOwnProperty;var mr=s=>{throw TypeError(s)};var Di=(s,t,e)=>t in s?jn(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e;var Ui=(s,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Pi(t))!ji.call(s,r)&&r!==e&&jn(s,r,{get:()=>t[r],enumerable:!(n=Li(t,r))||n.enumerable});return s};var pn=(s,t,e)=>(e=s!=null?Fi(Bi(s)):{},Ui(t||!s||!s.__esModule?jn(e,"default",{value:s,enumerable:!0}):e,s));var kt=(s,t,e)=>Di(s,typeof t!="symbol"?t+"":t,e),Dn=(s,t,e)=>t.has(s)||mr("Cannot "+e);var g=(s,t,e)=>(Dn(s,t,"read from private field"),e?e.call(s):t.get(s)),K=(s,t,e)=>t.has(s)?mr("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(s):t.set(s,e),it=(s,t,e,n)=>(Dn(s,t,"write to private field"),n?n.call(s,e):t.set(s,e),e),p=(s,t,e)=>(Dn(s,t,"access private method"),e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ne=Object.create(null);ne.open="0";ne.close="1";ne.ping="2";ne.pong="3";ne.message="4";ne.upgrade="5";ne.noop="6";const wn=Object.create(null);Object.keys(ne).forEach(s=>{wn[ne[s]]=s});const Yn={type:"error",data:"parser error"},Lr=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",Pr=typeof ArrayBuffer=="function",Br=s=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(s):s&&s.buffer instanceof ArrayBuffer,Is=({type:s,data:t},e,n)=>Lr&&t instanceof Blob?e?n(t):gr(t,n):Pr&&(t instanceof ArrayBuffer||Br(t))?e?n(t):gr(new Blob([t]),n):n(ne[s]+(t||"")),gr=(s,t)=>{const e=new FileReader;return e.onload=function(){const n=e.result.split(",")[1];t("b"+(n||""))},e.readAsDataURL(s)};function yr(s){return s instanceof Uint8Array?s:s instanceof ArrayBuffer?new Uint8Array(s):new Uint8Array(s.buffer,s.byteOffset,s.byteLength)}let Un;function qi(s,t){if(Lr&&s.data instanceof Blob)return s.data.arrayBuffer().then(yr).then(t);if(Pr&&(s.data instanceof ArrayBuffer||Br(s.data)))return t(yr(s.data));Is(s,!1,e=>{Un||(Un=new TextEncoder),t(Un.encode(e))})}const wr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Ye=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let s=0;s<wr.length;s++)Ye[wr.charCodeAt(s)]=s;const Vi=s=>{let t=s.length*.75,e=s.length,n,r=0,i,o,a,l;s[s.length-1]==="="&&(t--,s[s.length-2]==="="&&t--);const d=new ArrayBuffer(t),c=new Uint8Array(d);for(n=0;n<e;n+=4)i=Ye[s.charCodeAt(n)],o=Ye[s.charCodeAt(n+1)],a=Ye[s.charCodeAt(n+2)],l=Ye[s.charCodeAt(n+3)],c[r++]=i<<2|o>>4,c[r++]=(o&15)<<4|a>>2,c[r++]=(a&3)<<6|l&63;return d},Gi=typeof ArrayBuffer=="function",Ss=(s,t)=>{if(typeof s!="string")return{type:"message",data:jr(s,t)};const e=s.charAt(0);return e==="b"?{type:"message",data:Hi(s.substring(1),t)}:wn[e]?s.length>1?{type:wn[e],data:s.substring(1)}:{type:wn[e]}:Yn},Hi=(s,t)=>{if(Gi){const e=Vi(s);return jr(e,t)}else return{base64:!0,data:s}},jr=(s,t)=>{switch(t){case"blob":return s instanceof Blob?s:new Blob([s]);case"arraybuffer":default:return s instanceof ArrayBuffer?s:s.buffer}},Dr="",Ji=(s,t)=>{const e=s.length,n=new Array(e);let r=0;s.forEach((i,o)=>{Is(i,!1,a=>{n[o]=a,++r===e&&t(n.join(Dr))})})},Wi=(s,t)=>{const e=s.split(Dr),n=[];for(let r=0;r<e.length;r++){const i=Ss(e[r],t);if(n.push(i),i.type==="error")break}return n};function zi(){return new TransformStream({transform(s,t){qi(s,e=>{const n=e.length;let r;if(n<126)r=new Uint8Array(1),new DataView(r.buffer).setUint8(0,n);else if(n<65536){r=new Uint8Array(3);const i=new DataView(r.buffer);i.setUint8(0,126),i.setUint16(1,n)}else{r=new Uint8Array(9);const i=new DataView(r.buffer);i.setUint8(0,127),i.setBigUint64(1,BigInt(n))}s.data&&typeof s.data!="string"&&(r[0]|=128),t.enqueue(r),t.enqueue(e)})}})}let qn;function mn(s){return s.reduce((t,e)=>t+e.length,0)}function gn(s,t){if(s[0].length===t)return s.shift();const e=new Uint8Array(t);let n=0;for(let r=0;r<t;r++)e[r]=s[0][n++],n===s[0].length&&(s.shift(),n=0);return s.length&&n<s[0].length&&(s[0]=s[0].slice(n)),e}function Yi(s,t){qn||(qn=new TextDecoder);const e=[];let n=0,r=-1,i=!1;return new TransformStream({transform(o,a){for(e.push(o);;){if(n===0){if(mn(e)<1)break;const l=gn(e,1);i=(l[0]&128)===128,r=l[0]&127,r<126?n=3:r===126?n=1:n=2}else if(n===1){if(mn(e)<2)break;const l=gn(e,2);r=new DataView(l.buffer,l.byteOffset,l.length).getUint16(0),n=3}else if(n===2){if(mn(e)<8)break;const l=gn(e,8),d=new DataView(l.buffer,l.byteOffset,l.length),c=d.getUint32(0);if(c>Math.pow(2,21)-1){a.enqueue(Yn);break}r=c*Math.pow(2,32)+d.getUint32(4),n=3}else{if(mn(e)<r)break;const l=gn(e,r);a.enqueue(Ss(i?l:qn.decode(l),t)),n=0}if(r===0||r>s){a.enqueue(Yn);break}}}})}const Ur=4;function _t(s){if(s)return Ki(s)}function Ki(s){for(var t in _t.prototype)s[t]=_t.prototype[t];return s}_t.prototype.on=_t.prototype.addEventListener=function(s,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+s]=this._callbacks["$"+s]||[]).push(t),this};_t.prototype.once=function(s,t){function e(){this.off(s,e),t.apply(this,arguments)}return e.fn=t,this.on(s,e),this};_t.prototype.off=_t.prototype.removeListener=_t.prototype.removeAllListeners=_t.prototype.removeEventListener=function(s,t){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var e=this._callbacks["$"+s];if(!e)return this;if(arguments.length==1)return delete this._callbacks["$"+s],this;for(var n,r=0;r<e.length;r++)if(n=e[r],n===t||n.fn===t){e.splice(r,1);break}return e.length===0&&delete this._callbacks["$"+s],this};_t.prototype.emit=function(s){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),e=this._callbacks["$"+s],n=1;n<arguments.length;n++)t[n-1]=arguments[n];if(e){e=e.slice(0);for(var n=0,r=e.length;n<r;++n)e[n].apply(this,t)}return this};_t.prototype.emitReserved=_t.prototype.emit;_t.prototype.listeners=function(s){return this._callbacks=this._callbacks||{},this._callbacks["$"+s]||[]};_t.prototype.hasListeners=function(s){return!!this.listeners(s).length};const kn=typeof Promise=="function"&&typeof Promise.resolve=="function"?t=>Promise.resolve().then(t):(t,e)=>e(t,0),qt=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),Xi="arraybuffer";function qr(s,...t){return t.reduce((e,n)=>(s.hasOwnProperty(n)&&(e[n]=s[n]),e),{})}const Qi=qt.setTimeout,Zi=qt.clearTimeout;function Mn(s,t){t.useNativeTimers?(s.setTimeoutFn=Qi.bind(qt),s.clearTimeoutFn=Zi.bind(qt)):(s.setTimeoutFn=qt.setTimeout.bind(qt),s.clearTimeoutFn=qt.clearTimeout.bind(qt))}const to=1.33;function eo(s){return typeof s=="string"?no(s):Math.ceil((s.byteLength||s.size)*to)}function no(s){let t=0,e=0;for(let n=0,r=s.length;n<r;n++)t=s.charCodeAt(n),t<128?e+=1:t<2048?e+=2:t<55296||t>=57344?e+=3:(n++,e+=4);return e}function Vr(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function so(s){let t="";for(let e in s)s.hasOwnProperty(e)&&(t.length&&(t+="&"),t+=encodeURIComponent(e)+"="+encodeURIComponent(s[e]));return t}function ro(s){let t={},e=s.split("&");for(let n=0,r=e.length;n<r;n++){let i=e[n].split("=");t[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return t}class io extends Error{constructor(t,e,n){super(t),this.description=e,this.context=n,this.type="TransportError"}}class _s extends _t{constructor(t){super(),this.writable=!1,Mn(this,t),this.opts=t,this.query=t.query,this.socket=t.socket,this.supportsBinary=!t.forceBase64}onError(t,e,n){return super.emitReserved("error",new io(t,e,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(t){this.readyState==="open"&&this.write(t)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(t){const e=Ss(t,this.socket.binaryType);this.onPacket(e)}onPacket(t){super.emitReserved("packet",t)}onClose(t){this.readyState="closed",super.emitReserved("close",t)}pause(t){}createUri(t,e={}){return t+"://"+this._hostname()+this._port()+this.opts.path+this._query(e)}_hostname(){const t=this.opts.hostname;return t.indexOf(":")===-1?t:"["+t+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(t){const e=so(t);return e.length?"?"+e:""}}class oo extends _s{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(t){this.readyState="pausing";const e=()=>{this.readyState="paused",t()};if(this._polling||!this.writable){let n=0;this._polling&&(n++,this.once("pollComplete",function(){--n||e()})),this.writable||(n++,this.once("drain",function(){--n||e()}))}else e()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){const e=n=>{if(this.readyState==="opening"&&n.type==="open"&&this.onOpen(),n.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(n)};Wi(t,this.socket.binaryType).forEach(e),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){const t=()=>{this.write([{type:"close"}])};this.readyState==="open"?t():this.once("open",t)}write(t){this.writable=!1,Ji(t,e=>{this.doWrite(e,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const t=this.opts.secure?"https":"http",e=this.query||{};return this.opts.timestampRequests!==!1&&(e[this.opts.timestampParam]=Vr()),!this.supportsBinary&&!e.sid&&(e.b64=1),this.createUri(t,e)}}let Gr=!1;try{Gr=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const ao=Gr;function co(){}class lo extends oo{constructor(t){if(super(t),typeof location<"u"){const e=location.protocol==="https:";let n=location.port;n||(n=e?"443":"80"),this.xd=typeof location<"u"&&t.hostname!==location.hostname||n!==t.port}}doWrite(t,e){const n=this.request({method:"POST",data:t});n.on("success",e),n.on("error",(r,i)=>{this.onError("xhr post error",r,i)})}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(e,n)=>{this.onError("xhr poll error",e,n)}),this.pollXhr=t}}class ee extends _t{constructor(t,e,n){super(),this.createRequest=t,Mn(this,n),this._opts=n,this._method=n.method||"GET",this._uri=e,this._data=n.data!==void 0?n.data:null,this._create()}_create(){var t;const e=qr(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");e.xdomain=!!this._opts.xd;const n=this._xhr=this.createRequest(e);try{n.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let r in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(r)&&n.setRequestHeader(r,this._opts.extraHeaders[r])}}catch{}if(this._method==="POST")try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{n.setRequestHeader("Accept","*/*")}catch{}(t=this._opts.cookieJar)===null||t===void 0||t.addCookies(n),"withCredentials"in n&&(n.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(n.timeout=this._opts.requestTimeout),n.onreadystatechange=()=>{var r;n.readyState===3&&((r=this._opts.cookieJar)===null||r===void 0||r.parseCookies(n.getResponseHeader("set-cookie"))),n.readyState===4&&(n.status===200||n.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof n.status=="number"?n.status:0)},0))},n.send(this._data)}catch(r){this.setTimeoutFn(()=>{this._onError(r)},0);return}typeof document<"u"&&(this._index=ee.requestsCount++,ee.requests[this._index]=this)}_onError(t){this.emitReserved("error",t,this._xhr),this._cleanup(!0)}_cleanup(t){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=co,t)try{this._xhr.abort()}catch{}typeof document<"u"&&delete ee.requests[this._index],this._xhr=null}}_onLoad(){const t=this._xhr.responseText;t!==null&&(this.emitReserved("data",t),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}ee.requestsCount=0;ee.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",vr);else if(typeof addEventListener=="function"){const s="onpagehide"in qt?"pagehide":"unload";addEventListener(s,vr,!1)}}function vr(){for(let s in ee.requests)ee.requests.hasOwnProperty(s)&&ee.requests[s].abort()}const ho=function(){const s=Hr({xdomain:!1});return s&&s.responseType!==null}();class fo extends lo{constructor(t){super(t);const e=t&&t.forceBase64;this.supportsBinary=ho&&!e}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new ee(Hr,this.uri(),t)}}function Hr(s){const t=s.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!t||ao))return new XMLHttpRequest}catch{}if(!t)try{return new qt[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const Jr=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class uo extends _s{get name(){return"websocket"}doOpen(){const t=this.uri(),e=this.opts.protocols,n=Jr?{}:qr(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(t,e,n)}catch(r){return this.emitReserved("error",r)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const n=t[e],r=e===t.length-1;Is(n,this.supportsBinary,i=>{try{this.doWrite(n,i)}catch{}r&&kn(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const t=this.opts.secure?"wss":"ws",e=this.query||{};return this.opts.timestampRequests&&(e[this.opts.timestampParam]=Vr()),this.supportsBinary||(e.b64=1),this.createUri(t,e)}}const Vn=qt.WebSocket||qt.MozWebSocket;class po extends uo{createSocket(t,e,n){return Jr?new Vn(t,e,n):e?new Vn(t,e):new Vn(t)}doWrite(t,e){this.ws.send(e)}}class mo extends _s{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(t){return this.emitReserved("error",t)}this._transport.closed.then(()=>{this.onClose()}).catch(t=>{this.onError("webtransport error",t)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(t=>{const e=Yi(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=t.readable.pipeThrough(e).getReader(),r=zi();r.readable.pipeTo(t.writable),this._writer=r.writable.getWriter();const i=()=>{n.read().then(({done:a,value:l})=>{a||(this.onPacket(l),i())}).catch(a=>{})};i();const o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this._writer.write(o).then(()=>this.onOpen())})})}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const n=t[e],r=e===t.length-1;this._writer.write(n).then(()=>{r&&kn(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this._transport)===null||t===void 0||t.close()}}const go={websocket:po,webtransport:mo,polling:fo},yo=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,wo=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Kn(s){if(s.length>8e3)throw"URI too long";const t=s,e=s.indexOf("["),n=s.indexOf("]");e!=-1&&n!=-1&&(s=s.substring(0,e)+s.substring(e,n).replace(/:/g,";")+s.substring(n,s.length));let r=yo.exec(s||""),i={},o=14;for(;o--;)i[wo[o]]=r[o]||"";return e!=-1&&n!=-1&&(i.source=t,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=vo(i,i.path),i.queryKey=bo(i,i.query),i}function vo(s,t){const e=/\/{2,9}/g,n=t.replace(e,"/").split("/");return(t.slice(0,1)=="/"||t.length===0)&&n.splice(0,1),t.slice(-1)=="/"&&n.splice(n.length-1,1),n}function bo(s,t){const e={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(n,r,i){r&&(e[r]=i)}),e}const Xn=typeof addEventListener=="function"&&typeof removeEventListener=="function",vn=[];Xn&&addEventListener("offline",()=>{vn.forEach(s=>s())},!1);class Se extends _t{constructor(t,e){if(super(),this.binaryType=Xi,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,t&&typeof t=="object"&&(e=t,t=null),t){const n=Kn(t);e.hostname=n.host,e.secure=n.protocol==="https"||n.protocol==="wss",e.port=n.port,n.query&&(e.query=n.query)}else e.host&&(e.hostname=Kn(e.host).host);Mn(this,e),this.secure=e.secure!=null?e.secure:typeof location<"u"&&location.protocol==="https:",e.hostname&&!e.port&&(e.port=this.secure?"443":"80"),this.hostname=e.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=e.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},e.transports.forEach(n=>{const r=n.prototype.name;this.transports.push(r),this._transportsByName[r]=n}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},e),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=ro(this.opts.query)),Xn&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},vn.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(t){const e=Object.assign({},this.opts.query);e.EIO=Ur,e.transport=t,this.id&&(e.sid=this.id);const n=Object.assign({},this.opts,{query:e,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new this._transportsByName[t](n)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const t=this.opts.rememberUpgrade&&Se.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const e=this.createTransport(t);e.open(),this.setTransport(e)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",e=>this._onClose("transport close",e))}onOpen(){this.readyState="open",Se.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",t),this.emitReserved("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const e=new Error("server error");e.code=t.data,this._onError(e);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data);break}}onHandshake(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this._pingInterval=t.pingInterval,this._pingTimeout=t.pingTimeout,this._maxPayload=t.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const t=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+t,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},t),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const t=this._getWritablePackets();this.transport.send(t),this._prevBufferLen=t.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let n=0;n<this.writeBuffer.length;n++){const r=this.writeBuffer[n].data;if(r&&(e+=eo(r)),n>0&&e>this._maxPayload)return this.writeBuffer.slice(0,n);e+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const t=Date.now()>this._pingTimeoutTime;return t&&(this._pingTimeoutTime=0,kn(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),t}write(t,e,n){return this._sendPacket("message",t,e,n),this}send(t,e,n){return this._sendPacket("message",t,e,n),this}_sendPacket(t,e,n,r){if(typeof e=="function"&&(r=e,e=void 0),typeof n=="function"&&(r=n,n=null),this.readyState==="closing"||this.readyState==="closed")return;n=n||{},n.compress=n.compress!==!1;const i={type:t,data:e,options:n};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),r&&this.once("flush",r),this.flush()}close(){const t=()=>{this._onClose("forced close"),this.transport.close()},e=()=>{this.off("upgrade",e),this.off("upgradeError",e),t()},n=()=>{this.once("upgrade",e),this.once("upgradeError",e)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?n():t()}):this.upgrading?n():t()),this}_onError(t){if(Se.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",t),this._onClose("transport error",t)}_onClose(t,e){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),Xn&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const n=vn.indexOf(this._offlineEventListener);n!==-1&&vn.splice(n,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,e),this.writeBuffer=[],this._prevBufferLen=0}}}Se.protocol=Ur;class To extends Se{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let t=0;t<this._upgrades.length;t++)this._probe(this._upgrades[t])}_probe(t){let e=this.createTransport(t),n=!1;Se.priorWebsocketSuccess=!1;const r=()=>{n||(e.send([{type:"ping",data:"probe"}]),e.once("packet",m=>{if(!n)if(m.type==="pong"&&m.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",e),!e)return;Se.priorWebsocketSuccess=e.name==="websocket",this.transport.pause(()=>{n||this.readyState!=="closed"&&(c(),this.setTransport(e),e.send([{type:"upgrade"}]),this.emitReserved("upgrade",e),e=null,this.upgrading=!1,this.flush())})}else{const w=new Error("probe error");w.transport=e.name,this.emitReserved("upgradeError",w)}}))};function i(){n||(n=!0,c(),e.close(),e=null)}const o=m=>{const w=new Error("probe error: "+m);w.transport=e.name,i(),this.emitReserved("upgradeError",w)};function a(){o("transport closed")}function l(){o("socket closed")}function d(m){e&&m.name!==e.name&&i()}const c=()=>{e.removeListener("open",r),e.removeListener("error",o),e.removeListener("close",a),this.off("close",l),this.off("upgrading",d)};e.once("open",r),e.once("error",o),e.once("close",a),this.once("close",l),this.once("upgrading",d),this._upgrades.indexOf("webtransport")!==-1&&t!=="webtransport"?this.setTimeoutFn(()=>{n||e.open()},200):e.open()}onHandshake(t){this._upgrades=this._filterUpgrades(t.upgrades),super.onHandshake(t)}_filterUpgrades(t){const e=[];for(let n=0;n<t.length;n++)~this.transports.indexOf(t[n])&&e.push(t[n]);return e}}let Eo=class extends To{constructor(t,e={}){const n=typeof t=="object",r=n?{...t}:{...e};(!r.transports||r.transports&&typeof r.transports[0]=="string")&&(r.transports=(r.transports||["polling","websocket","webtransport"]).map(i=>go[i]).filter(i=>!!i)),super(n?r:t,r)}};function Io(s,t="",e){let n=s;e=e||typeof location<"u"&&location,s==null&&(s=e.protocol+"//"+e.host),typeof s=="string"&&(s.charAt(0)==="/"&&(s.charAt(1)==="/"?s=e.protocol+s:s=e.host+s),/^(https?|wss?):\/\//.test(s)||(typeof e<"u"?s=e.protocol+"//"+s:s="https://"+s),n=Kn(s)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";const i=n.host.indexOf(":")!==-1?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+i+":"+n.port+t,n.href=n.protocol+"://"+i+(e&&e.port===n.port?"":":"+n.port),n}const So=typeof ArrayBuffer=="function",_o=s=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(s):s.buffer instanceof ArrayBuffer,Wr=Object.prototype.toString,Ao=typeof Blob=="function"||typeof Blob<"u"&&Wr.call(Blob)==="[object BlobConstructor]",Oo=typeof File=="function"||typeof File<"u"&&Wr.call(File)==="[object FileConstructor]";function As(s){return So&&(s instanceof ArrayBuffer||_o(s))||Ao&&s instanceof Blob||Oo&&s instanceof File}function bn(s,t){if(!s||typeof s!="object")return!1;if(Array.isArray(s)){for(let e=0,n=s.length;e<n;e++)if(bn(s[e]))return!0;return!1}if(As(s))return!0;if(s.toJSON&&typeof s.toJSON=="function"&&arguments.length===1)return bn(s.toJSON(),!0);for(const e in s)if(Object.prototype.hasOwnProperty.call(s,e)&&bn(s[e]))return!0;return!1}function Co(s){const t=[],e=s.data,n=s;return n.data=Qn(e,t),n.attachments=t.length,{packet:n,buffers:t}}function Qn(s,t){if(!s)return s;if(As(s)){const e={_placeholder:!0,num:t.length};return t.push(s),e}else if(Array.isArray(s)){const e=new Array(s.length);for(let n=0;n<s.length;n++)e[n]=Qn(s[n],t);return e}else if(typeof s=="object"&&!(s instanceof Date)){const e={};for(const n in s)Object.prototype.hasOwnProperty.call(s,n)&&(e[n]=Qn(s[n],t));return e}return s}function $o(s,t){return s.data=Zn(s.data,t),delete s.attachments,s}function Zn(s,t){if(!s)return s;if(s&&s._placeholder===!0){if(typeof s.num=="number"&&s.num>=0&&s.num<t.length)return t[s.num];throw new Error("illegal attachments")}else if(Array.isArray(s))for(let e=0;e<s.length;e++)s[e]=Zn(s[e],t);else if(typeof s=="object")for(const e in s)Object.prototype.hasOwnProperty.call(s,e)&&(s[e]=Zn(s[e],t));return s}const xo=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var X;(function(s){s[s.CONNECT=0]="CONNECT",s[s.DISCONNECT=1]="DISCONNECT",s[s.EVENT=2]="EVENT",s[s.ACK=3]="ACK",s[s.CONNECT_ERROR=4]="CONNECT_ERROR",s[s.BINARY_EVENT=5]="BINARY_EVENT",s[s.BINARY_ACK=6]="BINARY_ACK"})(X||(X={}));class Ro{constructor(t){this.replacer=t}encode(t){return(t.type===X.EVENT||t.type===X.ACK)&&bn(t)?this.encodeAsBinary({type:t.type===X.EVENT?X.BINARY_EVENT:X.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id}):[this.encodeAsString(t)]}encodeAsString(t){let e=""+t.type;return(t.type===X.BINARY_EVENT||t.type===X.BINARY_ACK)&&(e+=t.attachments+"-"),t.nsp&&t.nsp!=="/"&&(e+=t.nsp+","),t.id!=null&&(e+=t.id),t.data!=null&&(e+=JSON.stringify(t.data,this.replacer)),e}encodeAsBinary(t){const e=Co(t),n=this.encodeAsString(e.packet),r=e.buffers;return r.unshift(n),r}}class Os extends _t{constructor(t){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},typeof t=="function"?{reviver:t}:t)}add(t){let e;if(typeof t=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");e=this.decodeString(t);const n=e.type===X.BINARY_EVENT;n||e.type===X.BINARY_ACK?(e.type=n?X.EVENT:X.ACK,this.reconstructor=new ko(e),e.attachments===0&&super.emitReserved("decoded",e)):super.emitReserved("decoded",e)}else if(As(t)||t.base64)if(this.reconstructor)e=this.reconstructor.takeBinaryData(t),e&&(this.reconstructor=null,super.emitReserved("decoded",e));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+t)}decodeString(t){let e=0;const n={type:Number(t.charAt(0))};if(X[n.type]===void 0)throw new Error("unknown packet type "+n.type);if(n.type===X.BINARY_EVENT||n.type===X.BINARY_ACK){const i=e+1;for(;t.charAt(++e)!=="-"&&e!=t.length;);const o=t.substring(i,e);if(o!=Number(o)||t.charAt(e)!=="-")throw new Error("Illegal attachments");const a=Number(o);if(!Mo(a)||a<0)throw new Error("Illegal attachments");if(a>this.opts.maxAttachments)throw new Error("too many attachments");n.attachments=a}if(t.charAt(e+1)==="/"){const i=e+1;for(;++e&&!(t.charAt(e)===","||e===t.length););n.nsp=t.substring(i,e)}else n.nsp="/";const r=t.charAt(e+1);if(r!==""&&Number(r)==r){const i=e+1;for(;++e;){const o=t.charAt(e);if(o==null||Number(o)!=o){--e;break}if(e===t.length)break}n.id=Number(t.substring(i,e+1))}if(t.charAt(++e)){const i=this.tryParse(t.substr(e));if(Os.isPayloadValid(n.type,i))n.data=i;else throw new Error("invalid payload")}return n}tryParse(t){try{return JSON.parse(t,this.opts.reviver)}catch{return!1}}static isPayloadValid(t,e){switch(t){case X.CONNECT:return br(e);case X.DISCONNECT:return e===void 0;case X.CONNECT_ERROR:return typeof e=="string"||br(e);case X.EVENT:case X.BINARY_EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&xo.indexOf(e[0])===-1);case X.ACK:case X.BINARY_ACK:return Array.isArray(e)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class ko{constructor(t){this.packet=t,this.buffers=[],this.reconPack=t}takeBinaryData(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){const e=$o(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const Mo=Number.isInteger||function(s){return typeof s=="number"&&isFinite(s)&&Math.floor(s)===s};function br(s){return Object.prototype.toString.call(s)==="[object Object]"}const No=Object.freeze(Object.defineProperty({__proto__:null,Decoder:Os,Encoder:Ro,get PacketType(){return X}},Symbol.toStringTag,{value:"Module"}));function zt(s,t,e){return s.on(t,e),function(){s.off(t,e)}}const Fo=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class zr extends _t{constructor(t,e,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=t,this.nsp=e,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const t=this.io;this.subs=[zt(t,"open",this.onopen.bind(this)),zt(t,"packet",this.onpacket.bind(this)),zt(t,"error",this.onerror.bind(this)),zt(t,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...t){return t.unshift("message"),this.emit.apply(this,t),this}emit(t,...e){var n,r,i;if(Fo.hasOwnProperty(t))throw new Error('"'+t.toString()+'" is a reserved event name');if(e.unshift(t),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(e),this;const o={type:X.EVENT,data:e};if(o.options={},o.options.compress=this.flags.compress!==!1,typeof e[e.length-1]=="function"){const c=this.ids++,m=e.pop();this._registerAckCallback(c,m),o.id=c}const a=(r=(n=this.io.engine)===null||n===void 0?void 0:n.transport)===null||r===void 0?void 0:r.writable,l=this.connected&&!(!((i=this.io.engine)===null||i===void 0)&&i._hasPingExpired());return this.flags.volatile&&!a||(l?(this.notifyOutgoingListeners(o),this.packet(o)):this.sendBuffer.push(o)),this.flags={},this}_registerAckCallback(t,e){var n;const r=(n=this.flags.timeout)!==null&&n!==void 0?n:this._opts.ackTimeout;if(r===void 0){this.acks[t]=e;return}const i=this.io.setTimeoutFn(()=>{delete this.acks[t];for(let a=0;a<this.sendBuffer.length;a++)this.sendBuffer[a].id===t&&this.sendBuffer.splice(a,1);e.call(this,new Error("operation has timed out"))},r),o=(...a)=>{this.io.clearTimeoutFn(i),e.apply(this,a)};o.withError=!0,this.acks[t]=o}emitWithAck(t,...e){return new Promise((n,r)=>{const i=(o,a)=>o?r(o):n(a);i.withError=!0,e.push(i),this.emit(t,...e)})}_addToQueue(t){let e;typeof t[t.length-1]=="function"&&(e=t.pop());const n={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((r,...i)=>(this._queue[0],r!==null?n.tryCount>this._opts.retries&&(this._queue.shift(),e&&e(r)):(this._queue.shift(),e&&e(null,...i)),n.pending=!1,this._drainQueue())),this._queue.push(n),this._drainQueue()}_drainQueue(t=!1){if(!this.connected||this._queue.length===0)return;const e=this._queue[0];e.pending&&!t||(e.pending=!0,e.tryCount++,this.flags=e.flags,this.emit.apply(this,e.args))}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){typeof this.auth=="function"?this.auth(t=>{this._sendConnectPacket(t)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:X.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,e){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,e),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(t=>{if(!this.sendBuffer.some(n=>String(n.id)===t)){const n=this.acks[t];delete this.acks[t],n.withError&&n.call(this,new Error("socket has been disconnected"))}})}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case X.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case X.EVENT:case X.BINARY_EVENT:this.onevent(t);break;case X.ACK:case X.BINARY_ACK:this.onack(t);break;case X.DISCONNECT:this.ondisconnect();break;case X.CONNECT_ERROR:this.destroy();const n=new Error(t.data.message);n.data=t.data.data,this.emitReserved("connect_error",n);break}}onevent(t){const e=t.data||[];t.id!=null&&e.push(this.ack(t.id)),this.connected?this.emitEvent(e):this.receiveBuffer.push(Object.freeze(e))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){const e=this._anyListeners.slice();for(const n of e)n.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&typeof t[t.length-1]=="string"&&(this._lastOffset=t[t.length-1])}ack(t){const e=this;let n=!1;return function(...r){n||(n=!0,e.packet({type:X.ACK,id:t,data:r}))}}onack(t){const e=this.acks[t.id];typeof e=="function"&&(delete this.acks[t.id],e.withError&&t.data.unshift(null),e.apply(this,t.data))}onconnect(t,e){this.id=t,this.recovered=e&&this._pid===e,this._pid=e,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:X.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){const e=this._anyListeners;for(let n=0;n<e.length;n++)if(t===e[n])return e.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(t),this}prependAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(t),this}offAnyOutgoing(t){if(!this._anyOutgoingListeners)return this;if(t){const e=this._anyOutgoingListeners;for(let n=0;n<e.length;n++)if(t===e[n])return e.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(t){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const e=this._anyOutgoingListeners.slice();for(const n of e)n.apply(this,t.data)}}}function De(s){s=s||{},this.ms=s.min||100,this.max=s.max||1e4,this.factor=s.factor||2,this.jitter=s.jitter>0&&s.jitter<=1?s.jitter:0,this.attempts=0}De.prototype.duration=function(){var s=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),e=Math.floor(t*this.jitter*s);s=Math.floor(t*10)&1?s+e:s-e}return Math.min(s,this.max)|0};De.prototype.reset=function(){this.attempts=0};De.prototype.setMin=function(s){this.ms=s};De.prototype.setMax=function(s){this.max=s};De.prototype.setJitter=function(s){this.jitter=s};class ts extends _t{constructor(t,e){var n;super(),this.nsps={},this.subs=[],t&&typeof t=="object"&&(e=t,t=void 0),e=e||{},e.path=e.path||"/socket.io",this.opts=e,Mn(this,e),this.reconnection(e.reconnection!==!1),this.reconnectionAttempts(e.reconnectionAttempts||1/0),this.reconnectionDelay(e.reconnectionDelay||1e3),this.reconnectionDelayMax(e.reconnectionDelayMax||5e3),this.randomizationFactor((n=e.randomizationFactor)!==null&&n!==void 0?n:.5),this.backoff=new De({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(e.timeout==null?2e4:e.timeout),this._readyState="closed",this.uri=t;const r=e.parser||No;this.encoder=new r.Encoder,this.decoder=new r.Decoder,this._autoConnect=e.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,t||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(t){return t===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var e;return t===void 0?this._reconnectionDelay:(this._reconnectionDelay=t,(e=this.backoff)===null||e===void 0||e.setMin(t),this)}randomizationFactor(t){var e;return t===void 0?this._randomizationFactor:(this._randomizationFactor=t,(e=this.backoff)===null||e===void 0||e.setJitter(t),this)}reconnectionDelayMax(t){var e;return t===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,(e=this.backoff)===null||e===void 0||e.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(t){if(~this._readyState.indexOf("open"))return this;this.engine=new Eo(this.uri,this.opts);const e=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const r=zt(e,"open",function(){n.onopen(),t&&t()}),i=a=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",a),t?t(a):this.maybeReconnectOnOpen()},o=zt(e,"error",i);if(this._timeout!==!1){const a=this._timeout,l=this.setTimeoutFn(()=>{r(),i(new Error("timeout")),e.close()},a);this.opts.autoUnref&&l.unref(),this.subs.push(()=>{this.clearTimeoutFn(l)})}return this.subs.push(r),this.subs.push(o),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(zt(t,"ping",this.onping.bind(this)),zt(t,"data",this.ondata.bind(this)),zt(t,"error",this.onerror.bind(this)),zt(t,"close",this.onclose.bind(this)),zt(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(e){this.onclose("parse error",e)}}ondecoded(t){kn(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,e){let n=this.nsps[t];return n?this._autoConnect&&!n.active&&n.connect():(n=new zr(this,t,e),this.nsps[t]=n),n}_destroy(t){const e=Object.keys(this.nsps);for(const n of e)if(this.nsps[n].active)return;this._close()}_packet(t){const e=this.encoder.encode(t);for(let n=0;n<e.length;n++)this.engine.write(e[n],t.options)}cleanup(){this.subs.forEach(t=>t()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(t,e){var n;this.cleanup(),(n=this.engine)===null||n===void 0||n.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,e),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const e=this.backoff.duration();this._reconnecting=!0;const n=this.setTimeoutFn(()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),!t.skipReconnect&&t.open(r=>{r?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",r)):t.onreconnect()}))},e);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const Ge={};function Ze(s,t){typeof s=="object"&&(t=s,s=void 0),t=t||{};const e=Io(s,t.path||"/socket.io"),n=e.source,r=e.id,i=e.path,o=Ge[r]&&i in Ge[r].nsps,a=t.forceNew||t["force new connection"]||t.multiplex===!1||o;let l;return a?l=new ts(n,t):(Ge[r]||(Ge[r]=new ts(n,t)),l=Ge[r]),e.query&&!t.query&&(t.query=e.queryKey),l.socket(e.path,t)}Object.assign(Ze,{Manager:ts,Socket:zr,io:Ze,connect:Ze});class es extends Error{constructor(t,e){super(`The document history advanced while this version was being prepared: expected head ${t}, found ${e??"none"}. Read the timeline again and rebuild on the new head.`),this.expectedGuid=t,this.actualGuid=e,this.name="StaleHistoryError"}}const Tr="bimterop",ns="revitflow_history.json",Yr="revitflow_model.frag",Kr="revitflow_",Lo="bimterop-locks-anchor";function Po(s,t){return s.filter(e=>String(e.parentId??"")===t)}function Bo(s){const t=s==null?void 0:s.hiddenFileId;if(typeof t!="string"||!t)throw new Error("The hidden-file upload answered without a hiddenFileId.");return t}function Zt(s){return String(s._id??s.id??"")}var Wt,Ae,oe,sn,rn,ss;class Cs{constructor(t,e){K(this,rn);K(this,Wt);K(this,Ae,new Map);K(this,oe);K(this,sn,0);this.client=t,this.projectId=e}async docs(){const t=await p(this,rn,ss).call(this);if(!t)return[];const e=await this.childFolders(t,!0),n=[];for(const r of e){if(r.archived)continue;const i=String(r.name??""),o=i.indexOf("-");if(o<=0)continue;const l=(await this.client.listFiles({folderId:Zt(r)})).map(m=>String(m.name??"")),d=l.find(m=>m===Yr)??l.find(m=>m.endsWith(".frag")&&!m.startsWith(Kr)),c=l.includes(ns)||!!d;n.push({source:i.slice(0,o),docId:i.slice(o+1),folderId:Zt(r),modelName:d,...c?{}:{empty:!0}})}return n}doc(t,e){const n=`${t}-${e}`;let r=g(this,Ae).get(n);return r||(r=new rs(this.client,this,t,e),g(this,Ae).set(n,r)),r}document(t){const e=`platform-${t}`;let n=g(this,Ae).get(e);return n||(n=new rs(this.client,this,"platform",t,t),g(this,Ae).set(e,n)),n}async childFolders(t,e=!1){return(e||!g(this,oe)||Date.now()-g(this,sn)>3e4)&&(it(this,sn,Date.now()),it(this,oe,this.client.listFolders({parentFolderId:t,projectId:this.projectId}).then(n=>Po(n,t))),g(this,oe).catch(()=>{it(this,oe,void 0)})),g(this,oe)}forgetFolders(){it(this,oe,void 0)}async rootFolderId(t=!1){if(g(this,Wt))return g(this,Wt);const e=await p(this,rn,ss).call(this);if(e)return e;if(!t)return;const n=await this.client.createFolder(Tr,void 0,this.projectId);return it(this,Wt,Zt(n)),g(this,Wt)}}Wt=new WeakMap,Ae=new WeakMap,oe=new WeakMap,sn=new WeakMap,rn=new WeakSet,ss=async function(){if(g(this,Wt))return g(this,Wt);const e=(await this.client.listFolders({projectId:this.projectId})).find(n=>String(n.name??"")===Tr&&!n.parentId);return e&&it(this,Wt,Zt(e)),g(this,Wt)};var Xt,M,ie,Re,ye,Qt,on,is,Tn,we,Xr,En,Qr,Zr,ti;class rs{constructor(t,e,n,r,i){K(this,M);K(this,Xt);K(this,Qt);K(this,on,0);this.client=t,this.project=e,this.source=n,this.docId=r,it(this,Xt,i)}async timeline(){const t=await p(this,M,En).call(this);return $s((t==null?void 0:t.commits)??[])}async latest(){const t=await this.timeline();return t.length?t[t.length-1]:null}async delta(t){if(!t.deltaId)throw new Error(`Version ${t.guid} carries no delta: it is a full export — read model() instead.`);return await(await this.client.downloadHiddenFile(t.deltaId)).blob()}async model(){const t=await p(this,M,we).call(this);if(!t)throw new Error(`Document ${this.source}-${this.docId} has no model file yet.`);const e=await this.client.downloadFile(t.id);if(!e.ok)throw new Error(`Reading the model answered ${e.status}`);return await e.blob()}async modelParts(t){const e=await this.timeline();if(e.length===0)throw new Error(`Document ${this.source}-${this.docId} has no history yet.`);const n=t==null?void 0:t.at,r=n?e.findIndex(c=>c.guid===n):e.length-1;if(r<0)throw new Error(`No version ${n} in this document's timeline.`);let i=0;for(let c=r;c>=0;c--)if(e[c].full){i=c;break}const o=await p(this,M,we).call(this);if(!o)throw new Error(`Document ${this.source}-${this.docId} has no model file yet.`);const a=e[i],l=e.slice(r+1).some(c=>c.full),d=e.slice(i+1,r+1).map(c=>({guid:c.guid,...c.deltaId?{deltaId:c.deltaId}:{},...c.streamId?{streamId:c.streamId}:{},removedUniqueIds:c.changes.filter(m=>m.type==="delete").map(m=>m.uniqueId)}));return{baseline:{fileId:o.id,guid:a.guid,current:!l,...a.version!==void 0?{storageVersion:a.version}:{}},steps:d,at:e[r].guid}}async folderId(){return await p(this,M,ye).call(this,!1)}async descriptor(){return await g(this,M,ie).descriptor(await p(this,M,ye).call(this,!1))}async view(t){const e=await p(this,M,ye).call(this,!1),n=await g(this,M,ie).descriptor(e);if(n){for(const i of t){const o=n.views.find(a=>a.format===i);if(o)return o}return null}if(!t.includes("frag"))return null;const r=await p(this,M,we).call(this);return r?{fileId:r.id,format:"frag"}:null}async addView(t){const e=await p(this,M,ye).call(this,!0);if(await g(this,M,ie).descriptor(e)){await g(this,M,ie).addView(e,t);return}const r=await p(this,M,we).call(this);await g(this,M,ie).setDescriptor(e,{name:(r==null?void 0:r.name.replace(/\.frag$/,""))??g(this,M,Re),views:[t]})}async ensureDescriptor(){const t=await p(this,M,ye).call(this,!1),e=await g(this,M,ie).descriptor(t);if(e)return e;const n=await p(this,M,we).call(this);if(!n)return null;const r={name:n.name.replace(/\.frag$/,""),views:[{fileId:n.id,format:"frag"}]};return await g(this,M,ie).setDescriptor(t,r),await g(this,M,ie).descriptor(t)}async ownership(){const t=await p(this,M,Tn).call(this,Lo);if(!t)return[];const e=await this.client.getHiddenFilesByParent(t.id),n=await Promise.all(e.map(async o=>{try{const a=Zt(o),l=await this.client.downloadHiddenFile(a),d=JSON.parse(await l.text());return!d||typeof d!="object"||!("revitflowlock"in d)||!Array.isArray(d.keys)?null:{owner:String(d.user??""),keys:d.keys.filter(c=>typeof c=="string")}}catch{return null}})),r=new Set,i=new Map;for(const o of n)if(o)for(const a of o.keys){if(!a||r.has(a))continue;r.add(a);const l=i.get(o.owner)??[];l.push(a),i.set(o.owner,l)}return[...i.entries()].map(([o,a])=>({owner:o,elements:a}))}async sync(t){var a;const e=await p(this,M,ye).call(this,!0);let n=await p(this,M,En).call(this)??{model:this.docId,commits:[]};const r=Er(n.commits);if(t.expectedLatestGuid!==void 0&&(r==null?void 0:r.guid)!==t.expectedLatestGuid)throw new es(t.expectedLatestGuid,r==null?void 0:r.guid);const i={guid:xs(),...r?{parents:[r.guid]}:{},author:t.author,source:t.source,timestamp:new Date().toISOString(),...t.message?{message:t.message}:{},...t.userId?{userId:t.userId}:{},...t.kind?{kind:t.kind}:{},...t.file?{file:t.file}:{},...t.origin?{origin:t.origin}:{},...(a=t.origins)!=null&&a.length?{origins:t.origins}:{},changes:t.changes,counts:jo(t.changes)};if(t.model&&(await p(this,M,ti).call(this,e,t.model),i.full=!0),t.delta){const l=await p(this,M,we).call(this);if(!l)throw new Error("A delta needs the model file to hang from: sync a full model first.");const d=await this.client.createHiddenFile(t.delta,l.id);i.deltaId=Bo(d)}const o=await p(this,M,En).call(this);if(o){n=o;const l=Er(n.commits);if(t.expectedLatestGuid!==void 0&&(l==null?void 0:l.guid)!==t.expectedLatestGuid)throw new es(t.expectedLatestGuid,l==null?void 0:l.guid);l&&!i.parents&&(i.parents=[l.guid])}return n.commits.push(i),await p(this,M,Qr).call(this,e,ns,n),i}}Xt=new WeakMap,M=new WeakSet,ie=function(){return new ks(this.client,this.project.projectId)},Re=function(){return`${this.source}-${this.docId}`},ye=async function(t){if(g(this,Xt))return g(this,Xt);const e=await this.project.rootFolderId(t);if(!e)throw new Error(`Project ${this.project.projectId} has no connected documents yet.`);const n=o=>o.find(a=>String(a.name??"")===g(this,M,Re)),r=n(await this.project.childFolders(e))??n(await this.project.childFolders(e,!0));if(r)return it(this,Xt,Zt(r)),g(this,Xt);if(!t)throw new Error(`Document ${g(this,M,Re)} does not exist in this project.`);const i=await this.client.createFolder(g(this,M,Re),e,this.project.projectId);return this.project.forgetFolders(),it(this,Xt,Zt(i)),g(this,Xt)},Qt=new WeakMap,on=new WeakMap,is=async function(){return(!g(this,Qt)||Date.now()-g(this,on)>5e3)&&(it(this,on,Date.now()),it(this,Qt,(async()=>{const t=await p(this,M,ye).call(this,!1);return(await this.client.listFiles({projectId:this.project.projectId})).filter(n=>{const r=n;return String(r.folderId??r.parentFolderId??"")===t}).map(n=>({id:Zt(n),name:String(n.name??"")}))})()),g(this,Qt).catch(()=>{it(this,Qt,void 0)})),g(this,Qt)},Tn=async function(t){try{return(await p(this,M,is).call(this)).find(e=>e.name===t)}catch{return}},we=async function(){try{const t=await p(this,M,is).call(this);return t.find(e=>e.name===Yr)??t.find(e=>e.name.endsWith(".frag")&&!e.name.startsWith(Kr))}catch{return}},Xr=async function(t){const e=await p(this,M,Tn).call(this,t);if(!e)return;const n=await this.client.downloadFile(e.id);if(!n.ok)throw new Error(`Reading ${t} answered ${n.status}`);const r=await n.text();if(r.trim())return JSON.parse(r)},En=function(){return p(this,M,Xr).call(this,ns)},Qr=async function(t,e,n){const r=new Blob([JSON.stringify(n)],{type:"application/json"}),i=await p(this,M,Tn).call(this,e);return i?(await this.client.updateFile(i.id,{file:r,versionTag:await this.client.nextVersionTag(i.id)}),i):await p(this,M,Zr).call(this,t,e,n)},Zr=async function(t,e,n){const r=new Blob([JSON.stringify(n)],{type:"application/json"}),i=await this.client.createFile({file:r,name:e,versionTag:"v1",parentFolderId:t,projectId:this.project.projectId});it(this,Qt,void 0);const o=i.item;return{id:Zt(o??i),name:e}},ti=async function(t,e){const n=await p(this,M,we).call(this);if(n)return await this.client.updateFile(n.id,{file:e,versionTag:await this.client.nextVersionTag(n.id)}),n;const r=`${g(this,M,Re)}.frag`,i=await this.client.createFile({file:e,name:r,versionTag:"v1",parentFolderId:t,projectId:this.project.projectId});it(this,Qt,void 0);const o=i.item;return{id:Zt(o??i),name:r}};function jo(s){const t={added:0,modified:0,removed:0};for(const e of s)e.type==="create"?t.added++:e.type==="delete"?t.removed++:t.modified++;return t}function $s(s){var l;if(s.length<=1)return s.forEach((d,c)=>d.ordinal=c),[...s];const t=new Map(s.map(d=>[d.guid,d])),e=new Map,n=[];for(const d of s){const c=(l=d.parents)==null?void 0:l[0];if(c&&t.has(c)){const m=e.get(c)??[];m.push(d),e.set(c,m)}else n.push(d)}const r=(d,c)=>String(d.timestamp).localeCompare(String(c.timestamp));n.sort(r);const i=[],o=[...n].reverse(),a=new Set;for(;o.length;){const d=o.pop();if(a.has(d.guid))continue;a.add(d.guid),i.push(d);const c=(e.get(d.guid)??[]).sort(r);for(let m=c.length-1;m>=0;m--)o.push(c[m])}for(const d of s)a.has(d.guid)||i.push(d);return i.forEach((d,c)=>d.ordinal=c),i}function Er(s){const t=$s(s);return t[t.length-1]}function xs(){const s=globalThis.crypto;return s!=null&&s.randomUUID?s.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}const Rs={bim:{label:"BIM model",icon:"tabler:building"},drawings:{label:"Drawings",icon:"tabler:layout-board"},reality:{label:"Reality capture",icon:"tabler:3d-cube-sphere"},coordination:{label:"Coordination set",icon:"tabler:messages"},generic:{label:"Generic",icon:"tabler:file"}},Do={rvt:"bim",rfa:"bim",ifc:"bim",frag:"bim",tostrm:"bim","3dm":"bim",nwd:"bim",dgn:"bim",dwg:"drawings",dxf:"drawings",las:"reality",laz:"reality",e57:"reality",ply:"reality",potree:"reality",splat:"reality",spz:"reality",ksplat:"reality",bcf:"coordination",bcfzip:"coordination"};function os(s){var e;if(s.type&&s.type in Rs)return s.type;const t=[(e=s.native)==null?void 0:e.format,...s.views.map(n=>n.format)];for(const n of t){const r=n?Do[n.toLowerCase()]:void 0;if(r)return r}return"generic"}const en="thatopen/document@1",In="document.json",ei=["pdf","txt","md","json","csv","tsv","frag"];function se(s){return String(s._id??s.id??"")}const He=new Map,Ir=s=>{const t=s,e=[...t.versions??[]].sort((r,i)=>String(i.createdAt??"").localeCompare(String(r.createdAt??"")))[0],n=(e==null?void 0:e.tag)??t.versionTag;return n==null?void 0:String(n)};var Rt,ni,as,si,ri,ii,Sn;class ks{constructor(t,e){K(this,Rt);this.client=t,this.projectId=e}async list(t){const e=await p(this,Rt,ni).call(this),n=t==null?void 0:t.types;return n!=null&&n.length?e.filter(r=>n.includes(os(r.descriptor))):e}async fromFile(t,e){const n=await this.client.getFile(t),r=String(n.name??""),i=Gn(r,n.fileExtension),o=(e==null?void 0:e.name)??r.replace(/\.[^.]+$/,"")??r,a=await this.client.createFolder(o,n.folderId?String(n.folderId):void 0,this.projectId),l=se(a);await this.client.updateFile(t,{parentFolderId:l});const d=[],c=await p(this,Rt,ri).call(this,n);if(c)try{const v=await this.client.getFile(c);await this.client.updateFile(c,{parentFolderId:l}),d.push({fileId:c,format:Gn(String(v.name??""),v.fileExtension)})}catch{}((e==null?void 0:e.selfView)??ei.includes(i))&&d.push({fileId:t,format:i});const w={schema:en,name:o,native:{fileId:t,format:i},views:d};return w.type=(e==null?void 0:e.type)??os(w),await this.setDescriptor(l,w),await this.recordUpload(l,{fileId:t,name:r,format:i},(e==null?void 0:e.author)??String(n.createdBy??"")),{folderId:l,descriptor:w}}async recordUpload(t,e,n){const r=new Cs(this.client,this.projectId).document(t),i=(await r.timeline()).length===0;await r.sync({author:n||"unknown",source:"platform",kind:"upload",message:i?"Uploaded to the platform":"New version uploaded",file:{...e,format:e.format??Gn(e.name,void 0)},changes:[]})}async descriptor(t){const e=await p(this,Rt,Sn).call(this,t);return e?p(this,Rt,as).call(this,e.id,e.stamp):null}async view(t,e){const n=await this.descriptor(t);if(!n)return null;for(const r of e){const i=n.views.find(o=>o.format===r);if(i)return i}return null}async addView(t,e){const n=await this.descriptor(t);if(!n)throw new Error("This folder has no document descriptor yet: call setDescriptor first.");n.views=[...n.views.filter(r=>r.format!==e.format),e],await this.setDescriptor(t,n)}async setType(t,e){const n=await this.descriptor(t);if(!n)throw new Error("This folder has no document descriptor yet: call setDescriptor first.");n.type!==e&&await this.setDescriptor(t,{...n,type:e})}async setDescriptor(t,e){const n={...e,schema:en,views:e.views??[]},r=new Blob([JSON.stringify(n)],{type:"application/json"}),i=await p(this,Rt,Sn).call(this,t);if(i){He.delete(i.id),await this.client.updateFile(i.id,{file:r,versionTag:await this.client.nextVersionTag(i.id)});return}await this.client.createFile({file:r,name:In,versionTag:"v1",parentFolderId:t,projectId:this.projectId})}drafts(t){return new oi(this.client,()=>p(this,Rt,Sn).call(this,t))}}Rt=new WeakSet,ni=async function(){const e=(await this.client.listFiles({projectId:this.projectId})).filter(r=>String(r.name??"")===In);return(await Promise.all(e.map(async r=>{const i=r,o=String(i.folderId??i.parentFolderId??"");if(!o)return null;const a=await p(this,Rt,as).call(this,se(r),Ir(r));return a?{folderId:o,descriptor:a}:null}))).filter(r=>r!==null)},as=function(t,e){const n=e?He.get(t):void 0;if(n&&n.stamp===e)return n.value;const r=p(this,Rt,si).call(this,t);return e&&(He.set(t,{stamp:e,value:r}),r.catch(()=>{var i;((i=He.get(t))==null?void 0:i.value)===r&&He.delete(t)})),r},si=async function(t){const e=await this.client.downloadFile(t);if(!e.ok)throw new Error(`Reading a document's descriptor answered ${e.status}`);const n=await e.text();if(!n.trim())return null;let r;try{r=JSON.parse(n)}catch{return null}return Go(r)},ri=async function(t){let e=t.versions??[],n;if(e.length===0){n=await this.client.listFiles({projectId:this.projectId}).catch(()=>[]);const a=n.find(l=>se(l)===se(t));e=(a==null?void 0:a.versions)??[]}const r=await p(this,Rt,ii).call(this,t,e);if(r)return r;const i=String(t.name??"").replace(/\.[^.]+$/,"").toLowerCase();if(!i)return;n??(n=await this.client.listFiles({projectId:this.projectId}).catch(()=>[]));const o=n.find(a=>String(a.name??"").toLowerCase()===`${i}.frag`&&!a.archived&&se(a)!==se(t));return o?se(o):void 0},ii=async function(t,e){const n=[...e].sort((r,i)=>String(i.createdAt??"").localeCompare(String(r.createdAt??"")));for(const r of n)try{const i=await this.client.getFileVersionMetadata(se(t),r.tag),o=i==null?void 0:i.derivedFileId;if(typeof o=="string"&&o)return o}catch{}},Sn=async function(t){const n=(await this.client.listFiles({projectId:this.projectId})).filter(r=>{const i=r;return String(i.folderId??i.parentFolderId??"")===t}).find(r=>String(r.name??"")===In);return n?{id:se(n),stamp:Ir(n)}:void 0};const cs="draft:",ke="TODRAFT1";var te,Ke,ls;class oi{constructor(t,e){K(this,te);this.client=t,this.holder=e}async list(){const t=await this.holder();if(!t)return[];const e=new Map;for(const n of await p(this,te,Ke).call(this,t.id)){const r=e.get(n.userId);(!r||n.savedAt>r.savedAt)&&e.set(n.userId,{userId:n.userId,savedAt:n.savedAt})}return[...e.values()].sort((n,r)=>+r.savedAt-+n.savedAt)}async get(t){const e=await this.holder();if(!e)return null;const r=(await p(this,te,Ke).call(this,e.id)).filter(l=>!(t!=null&&t.userId)||l.userId===t.userId).sort((l,d)=>+d.savedAt-+l.savedAt)[0];if(!r)return null;const i=await this.client.downloadHiddenFile(r.hiddenId),{meta:o,blob:a}=await Vo(await i.blob());return{userId:r.userId,savedAt:r.savedAt,meta:o,blob:a}}async put(t,e){const n=await this.holder();if(!n)throw new Error("This folder is not a document (no document.json): drafts need one.");const r=Uo(e.userId),i=(await p(this,te,Ke).call(this,n.id)).filter(l=>l.userId===e.userId),a=(await this.client.createHiddenFile(await qo(t,e.meta??{}),n.id,r)).hiddenFileId;if(!a)throw new Error("The draft upload answered without a hiddenFileId.");return await p(this,te,ls).call(this,i.map(l=>l.hiddenId)),{userId:e.userId,savedAt:Sr(a)}}async delete(t){const e=await this.holder();if(!e)return;const n=(await p(this,te,Ke).call(this,e.id)).filter(r=>r.userId===t.userId);await p(this,te,ls).call(this,n.map(r=>r.hiddenId))}}te=new WeakSet,Ke=async function(t){return(await this.client.getHiddenFilesByParent(t)).filter(n=>typeof n.tag=="string"&&n.tag.startsWith(cs)).map(n=>{const r=String(n._id);return{hiddenId:r,userId:n.tag.slice(cs.length),savedAt:Sr(r)}})},ls=async function(t){for(const e of t)try{await this.client.deleteHiddenFile(e)}catch{}};function Uo(s){const t=`${cs}${s}`;if(!/^[A-Za-z0-9][A-Za-z0-9:._-]{0,49}$/.test(t))throw new Error(`A draft cannot be tagged for user "${s}": ids must be letters, digits or :._- and short.`);return t}function Sr(s){const t=parseInt(s.slice(0,8),16);return new Date(Number.isFinite(t)?t*1e3:0)}async function qo(s,t){const e=new TextEncoder().encode(JSON.stringify(t)),n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,e.length,!0),new Blob([new TextEncoder().encode(ke),n,e,s])}async function Vo(s){const t=new Uint8Array(await s.slice(0,ke.length+4).arrayBuffer());if(new TextDecoder().decode(t.slice(0,ke.length))!==ke)return{meta:{},blob:s};const e=new DataView(t.buffer).getUint32(ke.length,!0),n=ke.length+4,r=await s.slice(n,n+e).text();let i={};try{i=JSON.parse(r)}catch{}return{meta:i,blob:s.slice(n+e)}}function Gn(s,t){const e=(t??"").replace(/^\./,"").toLowerCase();if(e)return e;const n=s.lastIndexOf(".");return n>0?s.slice(n+1).toLowerCase():""}function Go(s){if(!s||typeof s!="object")return null;const t=s;if(t.schema!==en||typeof t.name!="string")return null;const e=Array.isArray(t.views)?t.views.filter(o=>!!o&&typeof o=="object"&&typeof o.fileId=="string"&&typeof o.format=="string"):[],n=t.native,r=!!n&&typeof n=="object"&&typeof n.fileId=="string"&&typeof n.format=="string",i=typeof t.type=="string"&&t.type in Rs?t.type:void 0;return{schema:en,name:t.name,...i?{type:i}:{},...r?{native:{fileId:n.fileId,format:n.format}}:{},views:e}}const Ho="flow:",Jo="flow:op",Wo="flow:source",zo="flow:host",Ms="revitflow/op@2",_r="REVITFLOWCHANGE",Ar="REVITFLOWOPERATION";class Nn{constructor(t){kt(this,"changes",[]);this.target=t}get length(){return this.changes.length}get batchId(){return this.target.batchId}get title(){return this.target.title??`${this.changes.length} change(s)`}get author(){return this.target.author??"app"}get userId(){return this.target.userId}get baseCommit(){return this.target.baseCommit}add(t,e={}){return this.changes.push({op:"add",attrs:this.pack(t,e)}),this}set(t,e,n={}){return this.requireId(t,"set"),this.changes.push({op:"set",item:t,attrs:this.pack(e,n)}),this}remove(t){return this.requireId(t,"remove"),this.changes.push({op:"remove",item:t,attrs:{}}),this}get summary(){const t=new Set(this.changes.map(e=>e.op));return t.size===1?[...t][0]:"mixed"}async build(t){if(this.changes.length===0)throw new Error("An operation with no changes is not an operation. Add at least one.");const e={schema:Ms,opId:t,batchId:this.batchId??t,targetProject:this.target.project,targetDocument:this.target.document,baseCommit:this.baseCommit,author:this.author,...this.userId?{userId:this.userId}:{},title:this.title,summary:this.summary},[n,r]=await Yo();return Ko(this.flatbuffer(n,r,t,JSON.stringify(e)))}pack(t,e){const n={};for(const[r,i]of Object.entries(t??{}))r.startsWith(Ho)||(n[r]=String(i));return e.position&&(n.Position=e.position.map(Or).join(",")),e.rotationDeg!==void 0&&(n.Rotation=Or(e.rotationDeg)),e.source&&(n[Wo]=e.source),e.host&&(n[zo]=e.host),n}requireId(t,e){if(!t||!t.trim())throw new Error(`A '${e}' has to name the item it acts on.`)}flatbuffer(t,e,n,r){const{Attribute:i,Meshes:o,Model:a,SpatialStructure:l,Transform:d}=e,c=new t.Builder(1024),m=this.changes.length,w=new Uint32Array(m);let v=1;for(let et=0;et<m;et++)w[et]=v++;const I=v++,_=et=>(et(c,0),c.endVector()),L=o.createShellsVector(c,[]),C=o.createCircleExtrusionsVector(c,[]),O=_(o.startSamplesVector),u=_(o.startRepresentationsVector),$=_(o.startMaterialsVector),E=_(o.startLocalTransformsVector),N=_(o.startGlobalTransformsVector),z=o.createMeshesItemsVector(c,[]),ut=o.createMaterialIdsVector(c,[]),wt=o.createRepresentationIdsVector(c,[]),Ot=o.createSampleIdsVector(c,[]),Vt=o.createLocalTransformIdsVector(c,[]),Mt=o.createGlobalTransformIdsVector(c,[]);o.startMeshes(c),o.addCoordinates(c,d.createTransform(c,0,0,0,1,0,0,0,1,0)),o.addGlobalTransforms(c,N),o.addShells(c,L),o.addRepresentations(c,u),o.addSamples(c,O),o.addLocalTransforms(c,E),o.addMaterials(c,$),o.addCircleExtrusions(c,C),o.addMeshesItems(c,z),o.addRepresentationIds(c,wt),o.addSampleIds(c,Ot),o.addMaterialIds(c,ut),o.addLocalTransformIds(c,Vt),o.addGlobalTransformIds(c,Mt);const he=o.endMeshes(c),Yt=c.createString(r),It=new Set,Gt=[];for(const et of this.changes){const At=[],Ht={[Jo]:et.op,...et.attrs};for(const[de,Ue]of Object.entries(Ht)){const $e=JSON.stringify([de,Ue,"IFCTEXT"]);It.add($e),At.push(c.createString($e))}Gt.push(i.createAttribute(c,i.createDataVector(c,At)))}{const et=JSON.stringify(["Name",n,"IFCLABEL"]);It.add(et);const At=i.createDataVector(c,[c.createString(et)]);Gt.push(i.createAttribute(c,At))}const Nt=a.createAttributesVector(c,Gt),Ce=a.createUniqueAttributesVector(c,[...It].map(et=>c.createString(et))),q=this.changes.map(()=>c.createString(_r));q.push(c.createString(Ar));const Z=a.createCategoriesVector(c,q),x=[],Tt=[];this.changes.forEach((et,At)=>{et.item&&(x.push(c.createString(et.item)),Tt.push(w[At]))});const Et=a.createGuidsVector(c,x),pt=a.createGuidsItemsVector(c,Tt),jt=a.createLocalIdsVector(c,[...w,I]),Ft=this.changes.map((et,At)=>l.createSpatialStructure(c,w[At],c.createString(_r),0)),Pt=l.createSpatialStructure(c,I,c.createString(Ar),l.createChildrenVector(c,Ft)),st=c.createString(n);a.startModel(c),a.addMeshes(c,he),a.addMetadata(c,Yt),a.addAttributes(c,Nt),a.addUniqueAttributes(c,Ce),a.addLocalIds(c,jt),a.addCategories(c,Z),a.addGuidsItems(c,pt),a.addGuids(c,Et),a.addGuid(c,st),a.addSpatialStructure(c,Pt),a.addMaxLocalId(c,v);const rt=a.endModel(c);return a.finishModelBuffer(c,rt),c.asUint8Array()}}async function Yo(){try{return await Promise.all([import("flatbuffers"),import("@thatopen/fragments")])}catch(s){throw new Error(`OperationBuilder needs the optional peers \`flatbuffers\` and \`@thatopen/fragments\` installed — add them to the app that authors operations. (${s instanceof Error?s.message:String(s)})`)}}function Or(s){return Number.isFinite(s)?String(s):"0"}async function Ko(s){const t=new Blob([s]).stream().pipeThrough(new CompressionStream("deflate"));return new Uint8Array(await new Response(t).arrayBuffer())}async function Fn(s){const[t,e]=await Xo(),n=e.Model.getRootAsModel(new t.ByteBuffer(await Qo(s)));let r={};try{r=JSON.parse(n.metadata()??"{}")}catch{}const i=new Map;for(let a=0;a<n.guidsLength();a++){const l=n.guidsItems(a),d=n.guids(a);l!==null&&d&&i.set(l,d)}const o=[];for(let a=0;a<n.attributesLength();a++){const l=n.localIds(a);if(l===null)continue;const d={},c=n.attributes(a);for(let m=0;m<((c==null?void 0:c.dataLength())??0);m++){const w=c.data(m);if(w)try{const[v,I]=JSON.parse(w);d[v]=I}catch{}}o.push({localId:l,guid:i.get(l)??null,category:n.categories(a)??null,attrs:d})}return{metadata:r,items:o}}async function Xo(){try{return await Promise.all([import("flatbuffers"),import("@thatopen/fragments")])}catch(s){throw new Error(`readFrag needs the optional peers \`flatbuffers\` and \`@thatopen/fragments\` resolvable (in Node, fragments also pulls its own imports, e.g. web-ifc). (${s instanceof Error?s.message:String(s)})`)}}async function Qo(s){const t=new Blob([s]).stream().pipeThrough(new DecompressionStream("deflate"));return new Uint8Array(await new Response(t).arrayBuffer())}const ai="Element",ci="Carried",Ne=1/.3048;function li(s){const t=[];for(const e of s)for(const n of[ai,ci]){const r=e.attrs[n];if(r)try{const i=JSON.parse(r);for(const o of Array.isArray(i)?i:[i]){const a=o;typeof(a==null?void 0:a.id)!="string"||typeof(a==null?void 0:a.kind)!="string"||t.push({id:a.id,kind:a.kind,params:a.params??{},item:e})}}catch{}}return t}function Bt(s,t){const e=s.params[t];if(typeof e!="string")return null;try{return JSON.parse(e)}catch{return null}}function Zo(s){const t=new Map;for(const[e,n]of Ns(s))t.set(e,n.name);return t}function Ns(s){const t=new Map;for(const e of s){if(e.kind!=="datum"||e.params.of!=="level")continue;const n=e.params.named,r=e.params.at;typeof n=="string"&&typeof r=="number"&&t.set(e.id,{name:n,at:r})}return t}function hi(s){const t=new Map;for(const e of s){if(!e.kind.endsWith("Style"))continue;const n=e.params.name;typeof n=="string"&&t.set(n,e)}return t}function Fs(s,t){const e=new Map;for(const[n,r]of s.made)e.set(n,r.id),r.print&&(t==null||t.set(n,r.print));return e}function di(s){const t=r=>Array.isArray(r)?r.map(t):r&&typeof r=="object"?Object.fromEntries(Object.keys(r).sort().map(i=>[i,t(r[i])])):r,e=JSON.stringify(t(s));let n=2166136261;for(let r=0;r<e.length;r++)n^=e.charCodeAt(r),n=Math.imul(n,16777619);return(n>>>0).toString(36)}async function Ls(s,t){var o,a;if(!(t!=null&&t.fileId))throw new Error("Choose the model file to read.");s.progress(`Downloading ${t.name}`);let e=new Uint8Array(await(await s.client.downloadFile(t.fileId,t.version?{versionTag:t.version}:void 0)).arrayBuffer());const n=((a=(o=/\.([^.]+)$/.exec(t.name))==null?void 0:o[1])==null?void 0:a.toLowerCase())??"frag";let r=null,i=null;if(n!=="frag"){const l=s.client.recipes.importerFor(n);if(!l)throw new Error(`This app cannot read .${n} files: it provides no importer for them.`);n==="ifc"&&(r=fi(e));const d=s.client.recipes.shapesFor(n);d&&(s.progress(`Reading the shapes of ${t.name}`),i=await d(e,t.name)),s.progress(`Reading ${t.name}`),e=await l(e,t.name)}return{picked:t,contents:await Fn(e),site:r,shapes:i}}function fi(s){var N;const t=new TextDecoder("latin1").decode(s),e=z=>new RegExp(`^${z}=\\s*([A-Z0-9_]+)\\((.*)\\);\\s*$`,"m").exec(t),n=z=>[...z.matchAll(/#\d+|\$/g)].map(ut=>ut[0]),r=z=>[...z.matchAll(/-?\d+(?:\.\d*)?(?:E[-+]?\d+)?/gi)].map(ut=>Number(ut[0])),i=/^(#\d+)=\s*IFCSITE\((.*)\);\s*$/m.exec(t);if(!i)return null;const o=(N=i[2].split(",")[5])==null?void 0:N.trim();if(!(o!=null&&o.startsWith("#")))return null;const a=e(o);if((a==null?void 0:a[1])!=="IFCLOCALPLACEMENT")return null;const[l,d]=n(a[2]);if(l!=="$"||!d)return null;const c=e(d);if((c==null?void 0:c[1])!=="IFCAXIS2PLACEMENT3D")return null;const[m,,w]=n(c[2]),v=m&&m!=="$"?e(m):null;if(!v)return null;const[I=0,_=0,L=0]=r(v[2]);let C=0;const O=w&&w!=="$"?e(w):null;if(O){const[z=1,ut=0]=r(O[2]);C=Math.atan2(ut,z)*180/Math.PI}const u=/IFCSIUNIT\([^)]*\.LENGTHUNIT\.\s*,\s*(\.([A-Z]+)\.|\$)\s*,\s*\.METRE\./i.exec(t),$={MILLI:.001,CENTI:.01,DECI:.1,KILO:1e3},E=u?u[2]?$[u[2].toUpperCase()]??1:1:/IFCCONVERSIONBASEDUNIT\([^)]*\.LENGTHUNIT\.[^)]*'FOOT'/i.test(t)?.3048:1;return{east:I*E,north:_*E,elevation:L*E,angleDeg:C}}const Ps="thatopen/recipe@1",Cr="__project_data",$r="recipes",ta=s=>`${s}.recipe.json`,ui={OperationBuilder:Nn,OP_SCHEMA:Ms,readFrag:Fn,readPickedFrag:Ls,recordsOf:li,innerJson:Bt,levelsOf:Ns,levelNames:Zo,stylesOf:hi,printOf:di,siteLocationOf:fi,whatItMadeBefore:Fs,ELEMENT_FIELD:ai,CARRIED_FIELD:ci,FEET_PER_METRE:Ne},pi=/^[a-z0-9][a-z0-9-]{1,62}$/;async function mi(s,t,e){const n=d=>[...d].sort((c,m)=>String(c._id).localeCompare(String(m._id)))[0],r=await s.listFolders({projectId:t,archived:!1});let i=n(r.filter(d=>d.name===Cr&&!d.parentId));if(!i){if(!e)return null;i=await s.createFolder(Cr,void 0,t)}const o=String(i._id),a=await s.listFolders({parentFolderId:o,projectId:t,archived:!1});let l=n(a.filter(d=>d.name===$r&&String(d.parentId)===o));if(!l){if(!e)return null;l=await s.createFolder($r,o,t)}return String(l._id)}const ea=s=>String(s._id??s.id??""),na=s=>String(s.tag??s.versionTag??""),hs=s=>{var t;return Number(((t=/(\d+)/.exec(s))==null?void 0:t[1])??-1)};async function Je(s,t){const e=await mi(s,t,!1);if(!e)return new Map;const n=await s.listFiles({folderId:e}),r=new Map;for(const i of n){const o=String(i.name??"");o.endsWith(".recipe.json")&&r.set(o.slice(0,-12),{id:ea(i)})}return r}async function yn(s,t,e){var i;const n=await s.downloadFile(t,e?{versionTag:e}:void 0),r=JSON.parse(await n.text());if((r==null?void 0:r.schema)!==Ps||!((i=r.manifest)!=null&&i.name)||typeof r.code!="string")throw new Error(`This is not a recipe this library can read (${String(r==null?void 0:r.schema)}).`);return r}async function We(s,t){return(await s.listVersions(t)).map(n=>({tag:na(n),createdAt:String(n.createdAt??"")})).filter(n=>n.tag).sort((n,r)=>hs(n.tag)-hs(r.tag))}var an;class gi{constructor(t,e){K(this,an,new Map);this.client=t,this.builtinNames=e}async list(t){const e=await Je(this.client,t);return(await Promise.all([...e.entries()].map(async([,{id:r}])=>{var i;try{const o=await We(this.client,r),a=(i=o[o.length-1])==null?void 0:i.tag,l=await yn(this.client,r,a);return{manifest:l.manifest,origin:"project",version:a,author:l.author,savedAt:l.savedAt}}catch{return null}}))).filter(r=>r!==null)}async versions(t,e){const n=(await Je(this.client,t)).get(e);if(!n)throw new Error(`The project has no recipe named "${e}".`);const r=await We(this.client,n.id);return await Promise.all(r.map(async({tag:i,createdAt:o})=>{try{const a=await yn(this.client,n.id,i);return{version:i,author:a.author,note:a.note,savedAt:a.savedAt??o}}catch{return{version:i,savedAt:o}}}))}async source(t,e,n){var o;const r=(await Je(this.client,t)).get(e);if(!r)throw new Error(`The project has no recipe named "${e}".`);const i=n??((o=(await We(this.client,r.id)).pop())==null?void 0:o.tag);if(!i)throw new Error(`The recipe "${e}" has no saved version.`);return{...await yn(this.client,r.id,i),version:i}}async save(t,e,n){const{manifest:r,code:i}=e;if(!pi.test((r==null?void 0:r.name)??""))throw new Error('A recipe name is lower case letters, digits and dashes, 2 to 63 of them: "walls-from-ifc".');if(this.builtinNames().has(r.name))throw new Error(`"${r.name}" is a built-in recipe. Give yours a name of its own.`);if(!r.to||!r.description||!Array.isArray(r.inputs))throw new Error("A recipe says what it writes (`to`), what it does (`description`) and what it reads (`inputs`).");await ds(r,i);const o={schema:Ps,manifest:r,code:i,author:n.author,...n.note?{note:n.note}:{},savedAt:new Date().toISOString()},a=new Blob([JSON.stringify(o,null,2)],{type:"application/json"}),l=(await Je(this.client,t)).get(r.name);if(l){const c=await We(this.client,l.id),m=`v${Math.max(0,...c.map(w=>hs(w.tag)))+1}`;return await this.client.createVersion(l.id,a,m),m}const d=await mi(this.client,t,!0);return await this.client.createFile({file:a,name:ta(r.name),versionTag:"v1",projectId:t,parentFolderId:d}),"v1"}async load(t,e,n){var l;const r=(await Je(this.client,t)).get(e);if(!r)throw new Error(`The project has no recipe named "${e}".`);const i=n??((l=(await We(this.client,r.id)).pop())==null?void 0:l.tag);if(!i)throw new Error(`The recipe "${e}" has no saved version.`);const o=`${r.id}@${i}`;let a=g(this,an).get(o);if(!a){const d=await yn(this.client,r.id,i);a=await ds(d.manifest,d.code),g(this,an).set(o,a)}return{recipe:a,version:i}}}an=new WeakMap;async function ds(s,t){var r;let e;try{e=await import(`data:text/javascript;base64,${sa(t)}`)}catch(i){throw new Error(`The recipe's code does not load: ${i instanceof Error?i.message:String(i)}`)}const n=e.run??((r=e.default)==null?void 0:r.run);if(typeof n!="function")throw new Error("The recipe's code exports no `run(context)` function.");return{...s,run:i=>n({...i,kit:ui})}}function sa(s){const t=new TextEncoder().encode(s);let e="";for(let n=0;n<t.length;n+=32768)e+=String.fromCharCode(...t.subarray(n,n+32768));return btoa(e)}async function ra(s){const t=s instanceof Uint8Array?s:new Uint8Array(await s.arrayBuffer()),{items:e,metadata:n}=await Fn(t),r=e.filter(i=>i.attrs["flow:op"]).map(i=>{const o={};for(const[a,l]of Object.entries(i.attrs))a.startsWith("flow:")||(o[a]=l);return{op:i.attrs["flow:op"],...i.guid?{target:i.guid}:{},...i.attrs["flow:source"]?{source:i.attrs["flow:source"]}:{},attrs:o}});return{envelope:n??{},changes:r}}class Bs extends Error{constructor(t){super(t),this.name="UpToDate"}}var ae,cn,ln;class yi{constructor(t){K(this,ae,new Map);K(this,cn,new Map);K(this,ln,new Map);kt(this,"project");this.client=t,this.project=new gi(t,()=>new Set(g(this,ae).keys()))}provideImporter(t,e){g(this,cn).set(t.toLowerCase(),e)}provideShapes(t,e){g(this,ln).set(t.toLowerCase(),e)}shapesFor(t){return g(this,ln).get(t.toLowerCase())}importerFor(t){return g(this,cn).get(t.toLowerCase())}register(t){if(g(this,ae).has(t.name))throw new Error(`A recipe named "${t.name}" is already registered.`);g(this,ae).set(t.name,t)}list(t){return[...g(this,ae).values()].filter(n=>(!(t!=null&&t.to)||n.to===t.to)&&(!(t!=null&&t.input)||n.inputs.includes(t.input)))}get(t){return g(this,ae).get(t)}async catalog(t,e){const n=this.list(e).map(i=>({manifest:i,origin:"builtin"}));let r=[];try{r=(await this.project.list(t)).filter(i=>!(e!=null&&e.to)||i.manifest.to===e.to)}catch{}return[...n,...r.sort((i,o)=>i.manifest.name.localeCompare(o.manifest.name))]}async resolve(t,e,n){const r=g(this,ae).get(t);return r?{recipe:r,origin:"builtin"}:{...await this.project.load(e,t,n),origin:"project"}}async choices(t,e){const{recipe:n}=await this.resolve(t,e),r=n.source;if((r==null?void 0:r.kind)!=="project-file")return[];const i=(r.extensions??[]).map(d=>d.toLowerCase()),a=(await this.client.documents(e).list()).filter(d=>d.descriptor.native&&(i.length===0||i.includes(d.descriptor.native.format.toLowerCase()))),l=await wi(this.client,a.map(d=>d.descriptor.native.fileId));return a.map(d=>{const c=d.descriptor.native;return{label:d.descriptor.name,fileId:c.fileId,name:`${d.descriptor.name}.${c.format}`,folderId:d.folderId,version:l.get(c.fileId)??"v1"}}).sort((d,c)=>d.label.localeCompare(c.label))}async run(t,e){const{recipe:n}=await this.resolve(t,e.projectId,e.recipeVersion);if(n.to!==e.target.source)throw new Error(`Recipe "${t}" writes ${n.to}, but the target document belongs to ${e.target.source}.`);return await n.run({client:this.client,projectId:e.projectId,target:e.target,made:e.made??new Map,opId:e.opId??xs(),input:e.input,settings:e.settings??{},progress:e.progress??(()=>{})})}}ae=new WeakMap,cn=new WeakMap,ln=new WeakMap;async function wi(s,t){const e=new Map;if(t.length===0)return e;const n=i=>{var o;return Number(((o=/(\d+)/.exec(String(i??"")))==null?void 0:o[1])??-1)},r=i=>{const a=i.slice().sort((l,d)=>{const c=l!=null&&l.createdAt?new Date(String(l.createdAt)).getTime():NaN,m=d!=null&&d.createdAt?new Date(String(d.createdAt)).getTime():NaN;return!Number.isNaN(c)&&!Number.isNaN(m)&&c!==m?m-c:n((d==null?void 0:d.tag)??(d==null?void 0:d.versionTag))-n((l==null?void 0:l.tag)??(l==null?void 0:l.versionTag))})[0];return a?String(a.tag??a.versionTag??"v1"):"v1"};return await Promise.all(t.map(async i=>{try{e.set(i,r(await s.listVersions(i)))}catch{e.set(i,"v1")}})),e}const fs=100;function ia(s){try{const t=JSON.parse(s);if(t&&typeof t=="object"){const e=t;return{message:typeof e.message=="string"?e.message:void 0,code:typeof e.code=="string"?e.code:void 0,details:e.details}}}catch{}return{}}function oa(s){if(!s||typeof s!="object")return;const t=s.retryAfter;return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}class Ln extends Error{constructor(e,n,r,i){const o=ia(r);super(o.message??`${n||"Request failed"} (${e})`);kt(this,"status");kt(this,"code");kt(this,"details");kt(this,"body");kt(this,"retryAfter");this.name="RequestError",this.status=e,this.code=o.code,this.details=o.details,this.body=r,this.retryAfter=i??oa(o.details)}}const Kt="item/folder",W="item",pe="processor",aa="npm-registry",re="hidden",Hn="FILE",Jn="TOOL",Wn="APP",ca=500,xr=3e4,la=2e3,ze=new Map,ha=.25,da=s=>new Promise(t=>setTimeout(t,s));function fa(s){var r,i;const t=(i=(r=s.headers)==null?void 0:r.get)==null?void 0:i.call(r,"Retry-After");if(!t)return;const e=Number(t);if(Number.isFinite(e))return Math.max(0,e);const n=Date.parse(t);if(!Number.isNaN(n))return Math.max(0,(n-Date.now())/1e3)}function ua(s){return s instanceof Ln?s.status===429||s.status>=500:!0}function pa(s,t){const e=Math.min(ca*2**t,xr),n=e*ha*Math.random(),r=s instanceof Ln&&s.retryAfter!=null?s.retryAfter*1e3:void 0;return r!=null?Math.min(r,xr)+n:e+n}var T,_n,F,us,ve,hn,Xe,An,On,ps,ms,gs;const Us=class Us{constructor(t,e,n){K(this,T);kt(this,"apiUrl");kt(this,"accessToken");kt(this,"wsUrl");kt(this,"retries");kt(this,"useBearer");kt(this,"builtInGlobals",null);kt(this,"localServerUrl",null);kt(this,"context");K(this,hn);const{retries:r=0,useBearer:i=!1,localServerUrl:o}=n||{};let a=e;if(a.charAt(a.length-1)==="/"&&(a=a.slice(0,-1)),this.apiUrl=`${a}/api`,this.accessToken=t,this.wsUrl=a,this.retries=r,this.useBearer=i,this.context={appId:"",projectId:"",accessToken:t,apiUrl:e},o){let l=o;l.charAt(l.length-1)==="/"&&(l=l.slice(0,-1)),this.localServerUrl=l}}static fromPlatformContext(t){const e=(typeof window<"u"?window.__THATOPEN_CONTEXT__:null)||{appId:"",projectId:"",accessToken:"",apiUrl:""},n=new Us(e.accessToken,e.apiUrl,{...t,useBearer:!0});return n.context=e,n}setRetries(t){this.retries=t}setBuiltInGlobals(t){this.builtInGlobals=t}get socketOrigin(){return this.wsUrl.split("?")[0]}async resolveAccessToken(){return this.accessToken}async request(t,e,n){return p(this,T,F).call(this,t,e,n)}async listFiles(t){const{folderId:e,archived:n,projectId:r}=t||{};return e?await p(this,T,F).call(this,"GET",`${Kt}/${e}/items`,{query:{itemType:Hn,archived:n}}):await p(this,T,F).call(this,"GET",`${W}`,{query:{itemType:Hn,archived:n,...r&&{projectId:r}}})}async getFile(t,e){return await p(this,T,ms).call(this,t,e)}async createFile(t){return await p(this,T,On).call(this,t,Hn)}async updateFile(t,e){return await p(this,T,ps).call(this,t,e)}async archiveFile(t){return await p(this,T,F).call(this,"DELETE",`${W}/${t}`)}async recoverFile(t){return await p(this,T,F).call(this,"PUT",`${W}/${t}/recover`)}async downloadFile(t,e){return await p(this,T,An).call(this,t,e)}async getFileVersionMetadata(t,e,n){const{withDraft:r}=n||{};return await p(this,T,F).call(this,"GET",`${W}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/metadata`,{query:{...r&&{withDraft:"true"}}})}async updateFileVersionMetadata(t,e,n){return await p(this,T,F).call(this,"PUT",`${W}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/metadata`,{body:JSON.stringify({metadata:n}),contentType:"application/json"})}async deleteFileVersionMetadata(t,e){return await p(this,T,F).call(this,"DELETE",`${W}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/metadata`)}async getFileVersionMetadataBatch(t,e){const{withDraft:n}=e||{};return await p(this,T,Xe).call(this,t,async r=>(await p(this,T,F).call(this,"POST",`${W}/batch/version-metadata`,{body:JSON.stringify({entries:r,...n!==void 0&&{withDraft:n}}),contentType:"application/json"})).results)}async listFolders(t){const{archived:e,parentFolderId:n,projectId:r}=t||{};return await p(this,T,F).call(this,"GET",Kt,{query:{parentFolderId:n,archived:e,...r&&{projectId:r}}})}async getFolder(t){return await p(this,T,F).call(this,"GET",`${Kt}/${t}`)}async getFoldersBatch(t){return await p(this,T,Xe).call(this,t,async e=>(await p(this,T,F).call(this,"POST",`${W}/batch/folders`,{body:JSON.stringify({folderIds:e}),contentType:"application/json"})).results)}async createFolder(t,e,n){return await p(this,T,F).call(this,"POST",Kt,{body:JSON.stringify({name:t,...e&&{parentId:e},...n&&{projectId:n}}),contentType:"application/json"})}async updateFolder(t,e){const{name:n}=e;return await p(this,T,F).call(this,"PUT",`${Kt}/${t}`,{body:JSON.stringify({name:n}),contentType:"application/json"})}async archiveFolder(t){return await p(this,T,F).call(this,"DELETE",`${Kt}/${t}`)}async recoverFolder(t){return await p(this,T,F).call(this,"PUT",`${Kt}/${t}/recover`)}async downloadFolder(t){return await p(this,T,ve).call(this,`${Kt}/${t}/download`)}async listComponents(t){const{folderId:e,ShowVersions:n,projectId:r}=t||{};return e?await p(this,T,F).call(this,"GET",`${Kt}/${e}/items`,{query:{itemType:Jn,...n&&{ShowVersions:n}}}):await p(this,T,F).call(this,"GET",`${W}`,{query:{itemType:Jn,...n&&{ShowVersions:n},...r&&{projectId:r}}})}async getComponent(t,e){return await p(this,T,ms).call(this,t,e)}async createComponent(t){const{componentProps:e}=t;return await p(this,T,On).call(this,t,Jn,e)}async updateComponent(t,e){const{componentProps:n}=e;return await p(this,T,ps).call(this,t,e,n)}async downloadComponent(t,e){return await p(this,T,An).call(this,t,e)}async downloadComponentBundle(t,e){const{versionTag:n,withDraft:r}=e||{};return await p(this,T,ve).call(this,`${W}/${t}/download/bundle`,{query:{...n&&{versionTag:n},...r&&{withDraft:r}}})}async archiveComponent(t){return await p(this,T,F).call(this,"DELETE",`${W}/${t}`)}async recoverComponent(t){return await p(this,T,F).call(this,"PUT",`${W}/${t}/recover`)}async getBuiltInComponent(t){return await(await p(this,T,ve).call(this,`built-in/${t}/bundle`)).text()}async initBuiltInComponent(t,e,n){const r=await this.getBuiltInComponent(t.uuid),i=n??this.builtInGlobals??(typeof window<"u"?window.ThatOpenCompany:{})??{},o=Object.keys(i),a=o.map(m=>i[m]),d=new Function(...o,`${r}
2
- return main;`)(...a),c=(d==null?void 0:d.componentDefinition)??d;e.get(c)}async initBuiltInComponents(t,...e){await Promise.all(e.map(n=>this.initBuiltInComponent(n,t)))}async setup(t,...e){var o,a;const n=t.OBC,r=t.BUI;if(!(n!=null&&n.Components))throw new Error("globals.OBC must include Components");if(!(r!=null&&r.Manager))throw new Error("globals.BUI must include Manager");const i=new n.Components;return r.Manager.init(),this.setBuiltInGlobals(t),await this.initBuiltInComponents(i,...e),i.init(),(a=(o=this.context.appEventOrchestrator)==null?void 0:o.appLoaded)==null||a.call(o),{components:i}}throwError(t,e){var n,r;(r=(n=this.context.appEventOrchestrator)==null?void 0:n.appError)==null||r.call(n,t,e)}async listApps(t){const{folderId:e,ShowVersions:n,projectId:r}=t||{};return e?await p(this,T,F).call(this,"GET",`${Kt}/${e}/items`,{query:{itemType:Wn,...n&&{ShowVersions:n}}}):await p(this,T,F).call(this,"GET",`${W}`,{query:{itemType:Wn,...n&&{ShowVersions:n},...r&&{projectId:r}}})}async createApp(t){const{appProps:e}=t;return await p(this,T,On).call(this,t,Wn,e)}async downloadApp(t,e){return await p(this,T,An).call(this,t,e)}async downloadAppBundle(t,e){const{versionTag:n,withDraft:r}=e||{};return await p(this,T,ve).call(this,`${W}/${t}/download/bundle`,{query:{...n&&{versionTag:n},...r&&{withDraft:r}}})}async archiveApp(t){return await p(this,T,F).call(this,"DELETE",`${W}/${t}`)}async getNpmCredentials(){return await p(this,T,F).call(this,"GET",`${aa}/credentials`)}async executeComponent(t,e,n){if(this.localServerUrl){const r=`${this.localServerUrl}/api/${pe}/${t}/execute`,i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!i.ok){const o=await i.text().catch(()=>"");throw new Error(`Local server request failed: ${i.status} - ${o}`)}return await i.json()}return await p(this,T,F).call(this,"POST",`${pe}/${t}/execute`,{body:JSON.stringify(e),query:{...n&&{versionTag:n}},contentType:"application/json"})}async abortExecution(t){if(this.localServerUrl){const e=`${this.localServerUrl}/api/${pe}/progress/${t}/abort`,n=await fetch(e,{method:"POST"});if(!n.ok){const r=await n.text().catch(()=>"");throw new Error(`Local server request failed: ${n.status} - ${r}`)}return await n.json()}return await p(this,T,F).call(this,"POST",`${pe}/progress/${t}/abort`)}async listExecutions(t,e){if(this.localServerUrl){const n=e?`?projectId=${encodeURIComponent(e)}`:"",r=`${this.localServerUrl}/api/${pe}/${t}/progress${n}`,i=await fetch(r);if(!i.ok){const o=await i.text().catch(()=>"");throw new Error(`Local server request failed: ${i.status} - ${o}`)}return await i.json()}return await p(this,T,F).call(this,"GET",`${pe}/${t}/progress`,{query:{...e&&{projectId:e}}})}async getExecution(t){if(this.localServerUrl){const e=`${this.localServerUrl}/api/${pe}/progress/${t}`,n=await fetch(e);if(!n.ok){const r=await n.text().catch(()=>"");throw new Error(`Local server request failed: ${n.status} - ${r}`)}return await n.json()}return await p(this,T,F).call(this,"GET",`${pe}/progress/${t}`)}async onExecutionProgress(t,e){const n=this.localServerUrl??this.wsUrl,r=await Ze(n,{auth:{accessToken:this.accessToken},transports:["websocket"]});r.on("connect",function(){r.emit("executionSubscription",JSON.stringify({executionId:t})),r.on("execution",i=>{e(i)})}),r.on("connect_error",function(i){console.log(i)})}documents(t){return new ks(this,t)}history(t){return new Cs(this,t)}get recipes(){return g(this,hn)??it(this,hn,new yi(this)),g(this,hn)}async createHiddenFile(t,e,n){const r=new FormData;return r.append("file",t),r.append("parentItemId",e),n!=null&&r.append("tag",n),await p(this,T,F).call(this,"POST",`${W}/${re}`,{body:r})}async createHiddenFilesBatch(t,e,n){const r=new FormData;for(const i of t)r.append("files",i);return r.append("parentItemId",e),n!=null&&r.append("tag",n),await p(this,T,F).call(this,"POST",`${W}/${re}/batch`,{body:r})}async deleteHiddenFile(t){return await p(this,T,F).call(this,"DELETE",`${W}/${re}/${t}`)}async getHiddenFile(t){return await p(this,T,F).call(this,"GET",`${W}/${re}/${t}`)}async downloadHiddenFile(t){return await p(this,T,ve).call(this,`${W}/${re}/${t}/download`)}async getHiddenFileSignedUrl(t,e){return await p(this,T,F).call(this,"GET",`${W}/${re}/${t}/signed-url`,{...e!=null&&{query:{expiresIn:e}}})}async getHiddenFileSignedUrlsBatch(t,e){return await p(this,T,Xe).call(this,t,async n=>(await p(this,T,F).call(this,"POST",`${W}/${re}/signed-url/batch`,{body:JSON.stringify({hiddenFileIds:n,...e!=null&&{expiresIn:e}}),contentType:"application/json"})).results)}async getHiddenFilesByParent(t,e){return await p(this,T,F).call(this,"GET",`${W}/${t}/${re}`,{...e!=null&&{query:{tag:e}}})}async deleteHiddenFilesByParent(t){return await p(this,T,F).call(this,"DELETE",`${W}/${t}/${re}`)}async uploadItemIcon(t,e){const n=new FormData;return n.append("icon",e),await p(this,T,F).call(this,"PUT",`${W}/${t}/icon`,{body:n})}async getItemIcon(t){return await p(this,T,ve).call(this,`${W}/${t}/icon`)}async removeItemIcon(t){return await p(this,T,F).call(this,"DELETE",`${W}/${t}/icon`)}async updateItem(t,e){return await p(this,T,F).call(this,"PUT",`${W}/${t}`,{body:JSON.stringify(e),contentType:"application/json"})}async createVersion(t,e,n,r,i){const o=new FormData;return o.append("file",e),o.append("versionTag",n),r&&o.append("extraProps",JSON.stringify(r)),i&&o.append("metadata",JSON.stringify(i)),await p(this,T,F).call(this,"POST",`${W}/${t}/version`,{body:o})}async nextVersionTag(t){if(!t)return"v1";let e=[];try{e=await this.listVersions(t)}catch{return`v-${Date.now()}`}let n=0;for(const r of e){const i=/^v(\d{1,6})$/.exec(String(r.tag??r.versionTag??""));i&&(n=Math.max(n,Number(i[1])))}return`v${Math.max(n,e.length)+1}`}async listVersions(t,e={}){return await p(this,T,F).call(this,"GET",`${W}/${encodeURIComponent(t)}/versions`,{query:e})}async listVersionsBatch(t,e={}){const{archived:n}=e;return await p(this,T,Xe).call(this,t,async r=>(await p(this,T,F).call(this,"POST",`${W}/batch/versions`,{body:JSON.stringify({itemIds:r,...n!==void 0&&{archived:n}}),contentType:"application/json"})).results)}async archiveVersion(t,e){return await p(this,T,F).call(this,"PUT",`${W}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/archive`)}async recoverVersion(t,e){return await p(this,T,F).call(this,"PUT",`${W}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/recover`)}async deleteVersion(t,e){return await p(this,T,F).call(this,"DELETE",`${W}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}`)}};T=new WeakSet,_n=function(t){return`${this.apiUrl}/${t}`},F=async function(t,e,n){if(t==="GET"&&(n==null?void 0:n.responseType)!=="blob"&&!(n!=null&&n.retryAttempt)){const r=`${p(this,T,_n).call(this,e)}?${new URLSearchParams(p(this,T,gs).call(this,n==null?void 0:n.query)).toString()}`,i=Date.now(),o=ze.get(r);if(o&&(o.pending||i-o.at<la))return o.answer.then(l=>l===void 0?l:structuredClone(l));const a={at:i,pending:!0,answer:p(this,T,us).call(this,t,e,n)};return ze.set(r,a),a.answer.then(()=>{a.pending=!1,a.at=Date.now()},()=>{ze.get(r)===a&&ze.delete(r)}),a.answer.then(l=>l===void 0?l:structuredClone(l))}return t!=="GET"&&ze.clear(),p(this,T,us).call(this,t,e,n)},us=async function(t,e,n){const{body:r,query:i,contentType:o,retries:a,responseType:l,retryAttempt:d}=n||{},c=p(this,T,_n).call(this,e),m=p(this,T,gs).call(this,i),w=await this.resolveAccessToken(),v={...m,...this.useBearer?{}:{accessToken:w}};try{const I=await fetch(c+"?"+new URLSearchParams(v).toString(),{method:t,headers:{Accept:"application/json",...o&&{"Content-Type":o},...this.useBearer&&{Authorization:`Bearer ${w}`}},...r&&{body:r}});if(!I.ok){const _=await I.text().then(L=>L).catch(()=>"");throw new Ln(I.status,I.statusText,_,fa(I))}return l==="blob"?await I.blob():I.json().then(_=>_).catch(()=>{})}catch(I){const _=a??this.retries;if(_>0&&ua(I)){const L=d??0;return await da(pa(I,L)),await p(this,T,F).call(this,t,e,{...n,retries:_-1,retryAttempt:L+1})}throw I}},ve=async function(t,e){const{query:n}=e||{},r=p(this,T,_n).call(this,t),i=await this.resolveAccessToken(),o={...n,...this.useBearer?{}:{accessToken:i}};return await fetch(r+"?"+new URLSearchParams(o).toString(),{method:"GET",...this.useBearer&&{headers:{Authorization:`Bearer ${i}`}}})},hn=new WeakMap,Xe=async function(t,e){if(!t.length)return[];const n=[];for(let i=0;i<t.length;i+=fs)n.push(t.slice(i,i+fs));return(await Promise.all(n.map(e))).flat()},An=async function(t,e){const{versionTag:n,withDraft:r}=e||{},i=await p(this,T,ve).call(this,`${W}/${t}/download`,{query:{...n&&{versionTag:n},...r&&{withDraft:r}}});if(i.status===429||i.status>=500)throw new Error(`Downloading ${t} answered ${i.status}${i.status===429?" (rate limited)":""}`);return i},On=async function(t,e,n){const{name:r,versionTag:i,parentFolderId:o,projectId:a,file:l,metadata:d}=t,c=new FormData;return c.append("file",l),c.append("name",r),c.append("versionTag",i),c.append("itemType",e),o&&c.append("folderId",o),a&&c.append("projectId",a),n&&c.append("extraProps",JSON.stringify(n)),d&&c.append("metadata",JSON.stringify(d)),await p(this,T,F).call(this,"POST",W,{body:c})},ps=async function(t,e,n){const{name:r,versionTag:i,parentFolderId:o,file:a,metadata:l}=e;let d,c;if(a){const m=new FormData;m.append("file",a),i&&m.append("versionTag",i),n&&m.append("extraProps",JSON.stringify(n)),l&&m.append("metadata",JSON.stringify(l)),c=await p(this,T,F).call(this,"POST",`${W}/${t}/version`,{body:m})}if(r||o){const m={...r&&{name:r},...o&&{folderId:o}},w=JSON.stringify(m);d=await p(this,T,F).call(this,"PUT",`${W}/${t}`,{body:w,contentType:"application/json"})}return{item:d,version:c}},ms=async function(t,e){const{showVersions:n=!1}=e||{};return await p(this,T,F).call(this,"GET",`${W}/${t}`,{query:{showVersions:n}})},gs=function(t){return t&&Object.entries(t).filter(([,e])=>e!==void 0).reduce((e,[n,r])=>(e[n]=r,e),{})};let Rn=Us;function vi(){if(typeof window>"u"||window.parent===window)throw new Error("client.channel only works inside a That Open app, which runs in an iframe of the platform.");return{post:s=>window.parent.postMessage(s,"*"),listen:s=>{const t=e=>{e.source===window.parent&&s(e.data)};return window.addEventListener("message",t),()=>window.removeEventListener("message",t)}}}const ys="channel:",ma=1e4;function Cn(s){try{s()}catch(t){console.error("[channel] a listener threw:",t)}}var ce,Dt,Ut,Fe,Le,Pe,Lt,ws,vs,Me;class js{constructor(t,e){K(this,Lt);K(this,ce,!1);K(this,Dt,[]);K(this,Ut,[]);K(this,Fe,new Set);K(this,Le,new Set);K(this,Pe,new Set);this.transport=t,this.controls=e}get joined(){return g(this,ce)}get peers(){return g(this,Dt)}join(){return g(this,ce)?Promise.resolve():p(this,Lt,ws).call(this,"joined",this.controls.join)}leave(){return!g(this,ce)&&!g(this,Ut).some(t=>t.want==="joined")?Promise.resolve():p(this,Lt,ws).call(this,"left",this.controls.leave)}onChange(t){return g(this,Fe).add(t),()=>void g(this,Fe).delete(t)}onPeerJoined(t){return g(this,Le).add(t),()=>void g(this,Le).delete(t)}onPeerLeft(t){return g(this,Pe).add(t),()=>void g(this,Pe).delete(t)}applyJoined(){it(this,ce,!0),p(this,Lt,vs).call(this,"joined"),p(this,Lt,Me).call(this)}applyLeft(){it(this,ce,!1),it(this,Dt,[]),p(this,Lt,vs).call(this,"left"),p(this,Lt,Me).call(this)}applyPeers(t){it(this,Dt,t),p(this,Lt,Me).call(this)}applyPeerJoined(t){!g(this,ce)||g(this,Dt).some(e=>e.from===t.from)||(it(this,Dt,[...g(this,Dt),t]),g(this,Le).forEach(e=>Cn(()=>e(t))),p(this,Lt,Me).call(this))}applyPeerLeft(t){const e=g(this,Dt).find(n=>n.from===t);e&&(it(this,Dt,g(this,Dt).filter(n=>n.from!==t)),g(this,Pe).forEach(n=>Cn(()=>n(e))),p(this,Lt,Me).call(this))}failPending(t){const e=g(this,Ut);return it(this,Ut,[]),e.forEach(n=>{clearTimeout(n.timer),n.reject(t)}),e.length>0}post(t){this.transport.post(t)}}ce=new WeakMap,Dt=new WeakMap,Ut=new WeakMap,Fe=new WeakMap,Le=new WeakMap,Pe=new WeakMap,Lt=new WeakSet,ws=function(t,e){return new Promise((n,r)=>{const i={want:t,resolve:n,reject:r,timer:setTimeout(()=>{it(this,Ut,g(this,Ut).filter(o=>o!==i)),r(new Error(`The platform did not confirm ${t==="joined"?"joining":"leaving"} in time.`))},ma)};g(this,Ut).push(i),this.transport.post({type:"APP_CHANNEL_CONTROL",...e})})},vs=function(t){const e=g(this,Ut).filter(n=>n.want===t);it(this,Ut,g(this,Ut).filter(n=>n.want!==t)),e.forEach(n=>{clearTimeout(n.timer),n.resolve()})},Me=function(){g(this,Fe).forEach(t=>Cn(t))};var Be;class bi extends js{constructor(e){super(e,{join:{action:"joinCollab"},leave:{action:"leaveCollab"}});K(this,Be,new Map)}on(e,n){const r=g(this,Be).get(e)??new Set;return r.add(n),g(this,Be).set(e,r),()=>void r.delete(n)}send(e,n){if(e.startsWith(ys))throw new Error(`Message types starting with '${ys}' are reserved.`);this.joined&&this.post({type:"APP_CHANNEL_PUBLISH",message:{type:e,payload:n}})}accepts(e){return e===void 0||e==="collab"}async handle(e){const n=g(this,Be).get(e.type);if(!(n!=null&&n.size))return{handled:!1};const r=Ei(e);return n.forEach(i=>Cn(()=>i(e.payload,r))),{handled:!0}}}Be=new WeakMap;var Te;class Ti extends js{constructor(e,n){super(e,{join:{action:"joinExternal",kind:n},leave:{action:"leaveExternal",kind:n}});K(this,Te,new Map);this.kind=n}on(e,n){if(g(this,Te).has(e))throw new Error(`"${e}" already has a handler in this room. Remove it first.`);return g(this,Te).set(e,n),()=>void g(this,Te).delete(e)}accepts(e,n){return e!==void 0&&e!=="external"?!1:this.kind===void 0||e===void 0||this.kind===n}get hasHandlers(){return g(this,Te).size>0}async handle(e){const n=g(this,Te).get(e.type);if(!n)return{handled:!1};try{return{handled:!0,value:await n(e.payload,Ei(e))}}catch(r){return{handled:!0,error:r instanceof Error?r.message:String(r)}}}}Te=new WeakMap;function Ei(s){return{from:s.from,at:s.at,requestId:s.requestId,kind:s.kind}}function ga(s){const t=s;if((t==null?void 0:t.type)!=="THATOPEN_CHANNEL_MESSAGE")return null;const e=t.message;return!e||typeof e.type!="string"?null:{type:e.type,requestId:typeof e.requestId=="string"?e.requestId:void 0,payload:e.payload,at:typeof e.at=="number"?e.at:Date.now(),from:typeof e.from=="string"?e.from:"",scope:e.scope==="collab"||e.scope==="external"?e.scope:void 0,kind:typeof e.kind=="string"?e.kind:void 0}}var Oe,dn,le,Ee,Ie,Ct,bs,$n,Si,_i,Ai,Ts;class Ii{constructor(t){K(this,Ct);K(this,Oe);K(this,dn);K(this,le);K(this,Ee,new Map);K(this,Ie,new Set);it(this,Oe,t),it(this,dn,t.listen(e=>void p(this,Ct,Si).call(this,e)))}collab(){return g(this,le)??it(this,le,new bi(g(this,Oe))),g(this,le)}external(t){const e=t??"";let n=g(this,Ee).get(e);return n||(n=new Ti(g(this,Oe),t),g(this,Ee).set(e,n)),n}dispose(){g(this,dn).call(this)}}Oe=new WeakMap,dn=new WeakMap,le=new WeakMap,Ee=new WeakMap,Ie=new WeakMap,Ct=new WeakSet,bs=function(){return[...g(this,le)?[g(this,le)]:[],...g(this,Ee).values()]},$n=function(t,e){if(t==="collab")return g(this,le);if(t==="external")return g(this,Ee).get(typeof e=="string"?e:"")},Si=async function(t){const e=ga(t);if(e){if(e.type.startsWith(ys)){p(this,Ct,_i).call(this,e);return}await p(this,Ct,Ai).call(this,e)}},_i=function(t){var n,r,i;const e=t.payload??{};switch(t.type){case"channel:joined":(n=p(this,Ct,$n).call(this,e.scope,e.kind))==null||n.applyJoined();break;case"channel:left":(r=p(this,Ct,$n).call(this,e.scope,e.kind))==null||r.applyLeft();break;case"channel:peers":(i=p(this,Ct,$n).call(this,e.scope,e.kind))==null||i.applyPeers(e.peers??[]);break;case"channel:peer-joined":case"channel:peer-left":{if(!e.from)break;const o=e.scope==="collab"?[g(this,le)]:[...g(this,Ee).values()].filter(a=>a.accepts("external",e.kind));for(const a of o)t.type==="channel:peer-joined"?a==null||a.applyPeerJoined({from:e.from,kind:e.kind}):a==null||a.applyPeerLeft(e.from);break}case"channel:error":{const o=new Error(String(t.payload));p(this,Ct,bs).call(this).map(l=>l.failPending(o)).some(Boolean)||console.error("[channel] error:",t.payload);break}}},Ai=async function(t){const e=p(this,Ct,bs).call(this).filter(i=>i.accepts(t.scope,t.kind));let n=!1;for(const i of e){const o=await i.handle(t);o.handled&&(n=!0,t.requestId&&p(this,Ct,Ts).call(this,t.requestId,o))}t.requestId&&t.scope==="external"&&e.length>0&&!n&&p(this,Ct,Ts).call(this,t.requestId,{handled:!0,error:`No handler for "${t.type}".`})},Ts=function(t,e){g(this,Ie).has(t)||(g(this,Ie).add(t),g(this,Ie).size>500&&g(this,Ie).delete(g(this,Ie).values().next().value),g(this,Oe).post({type:"APP_CHANNEL_PUBLISH",message:{type:e.error===void 0?"reply":"reply-error",requestId:t,payload:e.error===void 0?e.value:{error:e.error}}}))};const _e="project",xe="notifications";var je,fn;const qs=class qs extends Rn{constructor(e,n,r){super(typeof e=="string"?e:"",n,{...r,useBearer:!0});K(this,je);K(this,fn);typeof e=="function"&&it(this,je,e)}async resolveAccessToken(){return g(this,je)?await g(this,je).call(this):super.resolveAccessToken()}static fromPlatformContext(e){const n=(typeof window<"u"?window.__THATOPEN_CONTEXT__:null)||{appId:"",projectId:"",accessToken:"",apiUrl:""},r=new qs(n.accessToken,n.apiUrl,e);return r.context=n,r}get channel(){return g(this,fn)??it(this,fn,new Ii(vi())),g(this,fn)}async listProjects(){return await this.request("GET",_e)}async getProject(e){return await this.request("GET",`${_e}/${e}`)}async getProjectData(e){return await this.request("GET",`${_e}/${e}/data`)}async getAvatar(e){return await this.request("GET",`account/${e}/avatar`,{responseType:"blob"})}async checkPermission(e){return await this.request("GET",`${_e}/permissions/check`,{query:e})}async checkPermissionBatch(e){return(await this.request("POST",`${_e}/permissions/check/batch`,{body:JSON.stringify({checks:e}),contentType:"application/json"})).results}async getNotifications(e){return await this.request("GET",xe,{query:{...(e==null?void 0:e.cursor)!==void 0&&{cursor:e.cursor},...(e==null?void 0:e.limit)!==void 0&&{limit:String(e.limit)}}})}async getUnreadNotificationCount(){return(await this.request("GET",`${xe}/unread-count`)).count}async markNotificationsRead(e){return await this.request("POST",`${xe}/mark-read`,{body:JSON.stringify({ids:e}),contentType:"application/json"})}async markAllNotificationsRead(){return await this.request("POST",`${xe}/mark-all-read`)}async getNotificationSubscriptions(){return await this.request("GET",`${xe}/subscriptions`)}async unsubscribeFromAutomation(e){return await this.request("DELETE",`${xe}/subscriptions/${e}`)}async subscribeToAutomation(e,n,r){return await this.request("POST",`${_e}/${e}/events/hooks/${n}/subscription`,{body:JSON.stringify(r??{}),contentType:"application/json"})}async updateAutomationSubscription(e,n,r){return await this.request("PATCH",`${_e}/${e}/events/hooks/${n}/subscription`,{body:JSON.stringify(r),contentType:"application/json"})}async onNotification(e){const n=await this.resolveAccessToken(),r=Ze(`${this.socketOrigin}/notifications`,{auth:{accessToken:n},transports:["websocket"]});return r.on("notification.created",i=>e({type:"created",id:i==null?void 0:i.id})),r.on("notification.read",i=>e({type:"read",id:i==null?void 0:i.id})),r.on("notifications.allRead",i=>e({type:"allRead",batch:i==null?void 0:i.batch})),()=>r.disconnect()}};je=new WeakMap,fn=new WeakMap;let Es=qs;const me=1/.3048,ya={IFCDOOR:"OST_Doors",IFCWINDOW:"OST_Windows",IFCFURNITURE:"OST_Furniture",IFCFURNISHINGELEMENT:"OST_Furniture",IFCSYSTEMFURNITUREELEMENT:"OST_FurnitureSystems",IFCLIGHTFIXTURE:"OST_LightingFixtures",IFCSANITARYTERMINAL:"OST_PlumbingFixtures",IFCFLOWTERMINAL:"OST_PlumbingFixtures",IFCCOLUMN:"OST_Columns",IFCFOOTING:"OST_StructuralFoundation",IFCGEOGRAPHICELEMENT:"OST_Site",IFCELECTRICAPPLIANCE:"OST_ElectricalEquipment",IFCELECTRICDISTRIBUTIONBOARD:"OST_ElectricalEquipment",IFCUNITARYEQUIPMENT:"OST_MechanicalEquipment"},wa="OST_GenericModel",va=new Set(["IFCSPACE","IFCOPENINGELEMENT","IFCSITE","IFCANNOTATION","IFCGRID","IFCVIRTUALELEMENT","IFCBUILDING","IFCBUILDINGSTOREY"]),be=(s,t)=>Math.round(s/t)*t,ba=s=>({x:[s[0],s[1],s[2]],y:[s[4],s[5],s[6]],z:[s[8],s[9],s[10]],t:[s[12],s[13],s[14]]}),tn=(s,t)=>s[0]*t[0]+s[1]*t[1]+s[2]*t[2],zn=s=>Math.sqrt(tn(s,s)),xn=(s,t)=>[s[1]*t[2]-s[2]*t[1],s[2]*t[0]-s[0]*t[2],s[0]*t[1]-s[1]*t[0]];function Ta(s,t,e){const n=new Set,r=new Map;for(const l of t){const d=l.split(":")[1];d&&(n.add(d),r.has(d)||r.set(d,l))}const i=new Map,o=new Map,a=[];for(const l of s.elements.values()){if(n.has(l.gid)||va.has(l.ifcClass.toUpperCase())||l.parent&&n.has(l.parent)&&!/^IFC(DOOR|WINDOW)$/i.test(l.ifcClass)||l.pieces.length===0)continue;const c=/^IFCCOLUMN$/i.test(l.ifcClass)&&/structural|estructural|结构柱|tragend|tragwerk/i.test(`${l.typeName??""} ${l.objectType??""} ${l.name??""}`)?"OST_StructuralColumns":ya[l.ifcClass.toUpperCase()]??wa,m=ba(l.pieces[0].matrix),w=zn(m.x),v=zn(m.y),I=zn(m.z),_=m.z.map(q=>q/(I||1)),L=Math.abs(_[2]-1)<1e-6&&tn(xn(m.x,m.y),m.z)>0&&Math.abs(w-v)<1e-6&&Math.abs(w-I)<1e-6,C=tn(xn(m.x,m.y),m.z)>0&&Math.abs(w-v)<1e-6&&Math.abs(w-I)<1e-6,O=[m.x,m.y,m.z].map(q=>q.map(Z=>Z/(w||1))),u=C&&!L&&O.some(q=>Math.abs(Math.abs(q[2])-1)<1e-6)?O.find(q=>Math.abs(q[2])<1e-6):void 0,$=L?Math.atan2(m.x[1],m.x[0]):u?Math.atan2(u[1],u[0]):0,E=Math.cos(-$),N=Math.sin(-$),z=[m.t[0],m.t[1],m.t[2]],ut=/COLUMN/i.test(c),wt=q=>{const Z=q[0]-z[0],x=q[1]-z[1];return[E*Z-N*x,N*Z+E*x,q[2]-z[2]]},Ot=[],Vt=[c];for(const q of l.pieces){const Z=s.geometries.get(q.geometry);if(!Z)continue;const x=q.matrix,Tt=[];for(let st=0;st<Z.verts.length;st+=3){const rt=Z.verts[st],et=Z.verts[st+1],At=Z.verts[st+2],Ht=[x[0]*rt+x[4]*et+x[8]*At+x[12],x[1]*rt+x[5]*et+x[9]*At+x[13],x[2]*rt+x[6]*et+x[10]*At+x[14]],de=wt(Ht);Tt.push(be(de[0]*me,1e-5),be(de[1]*me,1e-5),be(de[2]*me,1e-5))}const Et=tn(xn([x[0],x[1],x[2]],[x[4],x[5],x[6]]),[x[8],x[9],x[10]])<0,pt=[];for(let st=0;st+2<Z.tris.length;st+=3)Et?pt.push(Z.tris[st],Z.tris[st+2],Z.tris[st+1]):pt.push(Z.tris[st],Z.tris[st+1],Z.tris[st+2]);pt.length&&Ot.push({v:Tt,t:pt});const jt=wt([x[12],x[13],x[14]]),Ft=[E*x[0]-N*x[1],N*x[0]+E*x[1],x[2]],Pt=[E*x[4]-N*x[5],N*x[4]+E*x[5],x[6]];Vt.push(`${q.geometry}@${[...jt,...Ft,...Pt].map(st=>be(st,1e-4).toFixed(4)).join(",")}`)}if(Ot.length===0)continue;const Mt=!l.host&&Ot.length===1?Sa(Ot[0]):null;if(Mt){const q=Ia(Mt),Z=q.key,x=`prism|${c}|${q.axis}|${Z}`;let Tt=i.get(x);if(!Tt){const et=Rr(l.typeName??l.objectType??l.name??l.ifcClass),At=(o.get(et)??0)+1;o.set(et,At);const Ht=At===1?et:`${et} (${At})`;Tt={family:Ht,type:Ht,first:!0,key:kr(x)},i.set(x,Tt)}const Et={ShapeCategory:c,Family:Tt.family,Type:Tt.type,ShapeKey:Tt.key,PrismLength:String(be(Mt.length,1e-5)),...ut?{ColumnFree:"1"}:{}};Tt.first&&(Et.Prism=JSON.stringify({axis:q.axis,loops:q.loops}),Tt.first=!1);const pt=[0,0,0];pt[Mt.axis]=(q.flipped?Mt.from+Mt.length:Mt.from)/me;const jt=(Mt.axis+1)%3,Ft=(Mt.axis+2)%3;pt[jt]+=q.centre[0]/me,pt[Ft]+=q.centre[1]/me;const Pt=Math.cos($),st=Math.sin($),rt=[z[0]+Pt*pt[0]-st*pt[1],z[1]+st*pt[0]+Pt*pt[1],z[2]+pt[2]];a.push({key:`${e}:${l.gid}:shape`,attrs:Et,at:rt,rotationDeg:($+q.turn)*180/Math.PI});continue}const he=`${c}|${Ot.map(q=>`${q.v.map(Z=>Math.round(Z*304.8/2)).join(",")}/${q.t.join(",")}`).join("|")}`,Yt=Vt.join("|");let It=i.get(Yt)??i.get(he);if(It&&(i.set(Yt,It),i.set(he,It)),!It){const q=Rr(l.typeName??l.objectType??l.name??l.ifcClass),Z=(o.get(q)??0)+1;o.set(q,Z);const x=Z===1?q:`${q} (${Z})`;It={family:x,type:x,first:!0,key:kr(he)},i.set(he,It),i.set(Yt,It)}const Gt={ShapeCategory:c,Family:It.family,Type:It.type,ShapeKey:It.key,...ut?{ColumnFree:"1"}:{}};It.first&&(Gt.Shape=JSON.stringify({pieces:Ot}),It.first=!1);const Nt=l.host?r.get(l.host):void 0,Ce=l.opening?s.elements.get(l.opening):void 0;if(Nt&&Ce){const q=[1/0,1/0,1/0],Z=[-1/0,-1/0,-1/0];for(const x of Ce.pieces){const Tt=s.geometries.get(x.geometry);if(!Tt)continue;const Et=x.matrix;for(let pt=0;pt<Tt.verts.length;pt+=3){const jt=Tt.verts[pt],Ft=Tt.verts[pt+1],Pt=Tt.verts[pt+2],st=wt([Et[0]*jt+Et[4]*Ft+Et[8]*Pt+Et[12],Et[1]*jt+Et[5]*Ft+Et[9]*Pt+Et[13],Et[2]*jt+Et[6]*Ft+Et[10]*Pt+Et[14]]);for(let rt=0;rt<3;rt++)q[rt]=Math.min(q[rt],st[rt]*me),Z[rt]=Math.max(Z[rt],st[rt]*me)}}Number.isFinite(q[0])&&(Gt.Opening=[...q,...Z].map(x=>be(x,1e-5)).join(","))}a.push({key:`${e}:${l.gid}:shape`,attrs:Gt,at:[z[0],z[1],z[2]],rotationDeg:$*180/Math.PI,...Nt?{host:Nt}:{}})}return a}function Rr(s){return(s.replace(/[\\:{}[\]|;<>?`~]/g,"-").replace(/\s+/g," ").trim()||"Shape").slice(0,120)}function kr(s){let t=2166136261;for(let e=0;e<s.length;e++)t^=s.charCodeAt(e),t=Math.imul(t,16777619);return(t>>>0).toString(36)}function Ea(s,t,e){const n=new Map;for(const i of t){const[,o,a]=i.split(":");o&&/^run/.test(a??"")&&!n.has(o)&&n.set(o,i)}const r=[];for(const i of s.elements.values()){if(i.ifcClass.toUpperCase()!=="IFCOPENINGELEMENT"||!i.host)continue;const o=n.get(i.host);if(o)for(const a of Oa(s,i.gid)){const l=a.pts;if(l.length<4)continue;const d=Aa(nn(s,i.host));if(!d)continue;const c=l.map(I=>(I[0]-d.a[0])*d.u[0]+(I[1]-d.a[1])*d.u[1]),m=l.map(I=>-(I[0]-d.a[0])*d.u[1]+(I[1]-d.a[1])*d.u[0]),w=I=>Math.max(...I)-Math.min(...I),v=w(c)*w(m)*w(l.map(I=>I[2]));!(v>0)||Math.abs(a.volume)<.75*v||r.push({key:`${e}:${i.gid}:opening${a.index===0&&a.of===1?"":`#${a.index}`}`,host:o,box:l.flat()})}}return r}function Ia(s){const t=s.loops.flat(),e=[t.reduce((w,v)=>w+v[0],0)/t.length,t.reduce((w,v)=>w+v[1],0)/t.length],n=s.loops.map(w=>{const v=w.map(([O,u])=>[O-e[0],u-e[1]]),I=v.map(([O,u])=>Math.hypot(O,u)),_=I.reduce((O,u)=>O+u,0)/I.length;if(v.length<8||_<=0||I.some(O=>Math.abs(O-_)>.02*_))return v;const C=v.reduce((O,u,$)=>{const E=v[($+1)%v.length];return O+u[0]*E[1]-E[0]*u[1]},0)>=0?1:-1;return v.map((O,u)=>[_*Math.cos(C*2*Math.PI*u/v.length),_*Math.sin(C*2*Math.PI*u/v.length)])}),r=w=>w.map(I=>{const _=I.map(([C,O])=>`${Math.round(C*304.8)},${Math.round(O*304.8)}`);let L=0;for(let C=1;C<_.length;C++)_[C]<_[L]&&(L=C);return[..._.slice(L),..._.slice(0,L)].join(";")}).sort().join("|"),i=(w,v)=>{const I=Math.cos(-v),_=Math.sin(-v);return w.map(L=>L.map(([C,O])=>[I*C-_*O,_*C+I*O]))},o=[];let a=s.axis,l=0,d=n;if(a===1&&(a=0,l=Math.PI/2,d=n.map(w=>w.map(([v,I])=>[-I,v]))),a===2){let w=0,v=0,I=0;const _=n.flat();for(const[E,N]of _)w+=E*E,v+=N*N,I+=E*N;const L=new Set,C=.5*Math.atan2(2*I,w-v);for(let E=0;E<4;E++)L.add(C+E*Math.PI/2);const O=_.map(([E,N])=>Math.hypot(E,N)),u=Math.max(...O),$=_.filter((E,N)=>O[N]>u-.003);if(Math.abs(w-v)<.001*(w+v)||$.length>4)for(const[E,N]of $.slice(0,64))L.add(Math.atan2(N,E));for(const E of L)o.push({loops:i(n,E),turn:E,flipped:!1})}else o.push({loops:d,turn:0,flipped:!1}),o.push({loops:d.map(w=>w.map(([v,I])=>[-v,I]).reverse()),turn:Math.PI,flipped:!0});let c=o[0],m=r(c.loops);for(const w of o.slice(1)){const v=r(w.loops);v<m&&(c=w,m=v)}return{axis:a,loops:c.loops,key:m,centre:e,turn:l+c.turn,flipped:c.flipped}}function Sa(s){const e=s.v.length/3;if(e<6)return null;const n=[0,1,2].map(r=>{let i=1/0,o=-1/0;for(let a=0;a<e;a++){const l=s.v[a*3+r];i=Math.min(i,l),o=Math.max(o,l)}return o-i});for(const r of[0,1,2].sort((i,o)=>n[o]-n[i])){let i=1/0,o=-1/0;for(let u=0;u<e;u++){const $=s.v[u*3+r];i=Math.min(i,$),o=Math.max(o,$)}if(o-i<.01)continue;let a=!0;for(let u=0;u<e&&a;u++){const $=s.v[u*3+r];Math.abs($-i)>.001&&Math.abs($-o)>.001&&(a=!1)}if(!a)continue;const l=(r+1)%3,d=(r+2)%3,c=new Map,m=[],w=u=>{const $=[s.v[u*3+l],s.v[u*3+d]],E=`${Math.round($[0]*3048)},${Math.round($[1]*3048)}`;return c.has(E)||(c.set(E,m.length),m.push($)),c.get(E)},v=new Map,I=[];for(let u=0;u+2<s.t.length;u+=3){const $=[s.t[u],s.t[u+1],s.t[u+2]];if(!$.every(N=>Math.abs(s.v[N*3+r]-i)<=.001))continue;const E=$.map(w);if(!(E[0]===E[1]||E[1]===E[2]||E[0]===E[2])){I.push(E);for(let N=0;N<3;N++){const z=E[N],ut=E[(N+1)%3],wt=z<ut?`${z},${ut}`:`${ut},${z}`;v.set(wt,(v.get(wt)??0)+1)}}}if(I.length===0)continue;const _=new Map;for(const u of I)for(let $=0;$<3;$++){const E=u[$],N=u[($+1)%3];v.get(E<N?`${E},${N}`:`${N},${E}`)===1&&_.set(E,[..._.get(E)??[],N])}if([..._.values()].some(u=>u.length!==1))continue;const L=[],C=new Set(_.keys());for(;C.size;){const u=C.values().next().value,$=[];let E=u,N=0;do $.push(m[E]),C.delete(E),E=_.get(E)[0];while(E!==u&&N++<1e5&&_.has(E));if(E!==u||$.length<3){L.length=0;break}const z=$.filter((ut,wt)=>{const Ot=$[(wt-1+$.length)%$.length],Vt=$[(wt+1)%$.length];return Math.abs((ut[0]-Ot[0])*(Vt[1]-Ot[1])-(ut[1]-Ot[1])*(Vt[0]-Ot[0]))>1e-7});L.push(z.map(([ut,wt])=>[be(ut,1e-5),be(wt,1e-5)]))}if(L.length===0||L.some(u=>u.length<3))continue;let O=0;for(let u=0;u<e;u++)Math.abs(s.v[u*3+r]-o)<=.001&&O++;if(!(O<3))return{axis:r,from:i,length:o-i,loops:L}}return null}function _a(s,t){const e=[];for(const n of s.elements.values()){if(n.ifcClass.toUpperCase()!=="IFCSPACE")continue;let r=1/0,i=-1/0;const o=[];for(const d of n.pieces){const c=s.geometries.get(d.geometry);if(!c)continue;const m=d.matrix,w=v=>{const I=c.verts[v*3],_=c.verts[v*3+1],L=c.verts[v*3+2];return[m[0]*I+m[4]*_+m[8]*L+m[12],m[1]*I+m[5]*_+m[9]*L+m[13],m[2]*I+m[6]*_+m[10]*L+m[14]]};for(let v=0;v+2<c.tris.length;v+=3){const I=[w(c.tris[v]),w(c.tris[v+1]),w(c.tris[v+2])];for(const _ of I)r=Math.min(r,_[2]),i=Math.max(i,_[2]);o.push(I)}}if(!Number.isFinite(r)||i-r<.1)continue;let a=null,l=0;for(const d of o){if(!d.every(m=>Math.abs(m[2]-r)<.001))continue;const c=Math.abs((d[1][0]-d[0][0])*(d[2][1]-d[0][1])-(d[2][0]-d[0][0])*(d[1][1]-d[0][1]))/2;c>l&&(l=c,a=d)}a&&e.push({key:`${t}:${n.gid}:room`,at:[(a[0][0]+a[1][0]+a[2][0])/3,(a[0][1]+a[1][1]+a[2][1])/3,r],height:i-r,number:n.name??"",name:n.longName??n.name??""})}return e}function Aa(s){if(s.length<2)return;let t=s[0],e=s[0],n=0;for(const r of s){const i=Math.hypot(r[0]-s[0][0],r[1]-s[0][1]);i>n&&(n=i,e=r)}n=0;for(const r of s){const i=Math.hypot(r[0]-e[0],r[1]-e[1]);i>n&&(n=i,t=r)}if(!(n<.1))return{a:t,u:[(e[0]-t[0])/n,(e[1]-t[1])/n]}}function Oa(s,t){const e=s.elements.get(t);if(!e)return[];const n=[],r=[],i=new Map;for(const c of e.pieces){const m=s.geometries.get(c.geometry);if(!m)continue;const w=c.matrix,v=[];for(let I=0;I<m.verts.length;I+=3){const _=m.verts[I],L=m.verts[I+1],C=m.verts[I+2],O=[w[0]*_+w[4]*L+w[8]*C+w[12],w[1]*_+w[5]*L+w[9]*C+w[13],w[2]*_+w[6]*L+w[10]*C+w[14]],u=O.map(E=>Math.round(E*1e4)).join(",");let $=i.get(u);$===void 0&&($=n.length,i.set(u,$),n.push(O)),v.push($)}for(let I=0;I+2<m.tris.length;I+=3)r.push(v[m.tris[I]],v[m.tris[I+1]],v[m.tris[I+2]])}const o=n.map((c,m)=>m),a=c=>{for(;o[c]!==c;)o[c]=o[o[c]],c=o[c];return c};for(let c=0;c<r.length;c+=3){const m=a(r[c]);o[a(r[c+1])]=m,o[a(r[c+2])]=m}const l=new Map;for(let c=0;c<r.length;c+=3){const m=a(r[c]);let w=l.get(m);w||(w={pts:new Set,volume:0},l.set(m,w));const[v,I,_]=[n[r[c]],n[r[c+1]],n[r[c+2]]];w.volume+=tn(v,xn(I,_))/6,w.pts.add(r[c]),w.pts.add(r[c+1]),w.pts.add(r[c+2])}const d=[...l.values()];return d.map((c,m)=>({pts:[...c.pts].map(w=>n[w]),volume:c.volume,index:m,of:d.length}))}function nn(s,t,e){const n=s.elements.get(t),r=[];if(!n)return r;for(const i of n.pieces){const o=s.geometries.get(i.geometry);if(!o)continue;const a=i.matrix;for(let l=0;l<o.verts.length;l+=3){const d=o.verts[l],c=o.verts[l+1],m=o.verts[l+2];r.push([a[0]*d+a[4]*c+a[8]*m+a[12],a[1]*d+a[5]*c+a[9]*m+a[13],a[2]*d+a[6]*c+a[10]*m+a[14]])}}return r}function Ca(s,t,e){const n=nn(s,t);if(n.length<4||e.length===0)return;let r=n[0],i=n[0],o=0;for(const C of n){const O=Math.hypot(C[0]-n[0][0],C[1]-n[0][1]);O>o&&(o=O,i=C)}o=0;for(const C of n){const O=Math.hypot(C[0]-i[0],C[1]-i[1]);O>o&&(o=O,r=C)}if(o<.3)return;const a=(i[0]-r[0])/o,l=(i[1]-r[1])/o,d=C=>(C[0]-r[0])*a+(C[1]-r[1])*l,c=Math.max(...n.map(C=>C[2])),m=C=>Math.max(...n.filter(O=>Math.abs(d(O)-C)<.05).map(O=>O[2]),-1/0),w=m(0),v=m(o);if(Math.abs(w-v)<.05&&c-Math.max(w,v)<.05)return;const I=(r[0]+i[0])/2,_=(r[1]+i[1])/2;let L;for(const C of e){const O=nn(s,C.gid);if(O.length===0)continue;const u=O.map(z=>z[0]),$=O.map(z=>z[1]),E=O.map(z=>z[2]);if(I<Math.min(...u)-.2||I>Math.max(...u)+.2||_<Math.min(...$)-.2||_>Math.max(...$)+.2)continue;const N=Math.min(...E)-c;N>1.5||Math.max(...E)<c-.05||(!L||Math.abs(N)<Math.abs(L.gap))&&(L={id:C.id,gap:N})}return L==null?void 0:L.id}const ge={levels:"-2000240",walls:"-2000011",floors:"-2000032",roofs:"-2000035",ceilings:"-2000038",structuralFoundations:"-2001300",stairs:"-2000120"};function Qe(s){const t=s.item.attrs.Name;if(typeof t!="string")return null;const e=t.indexOf(":"),n=t.lastIndexOf(":");if(e<=0||n<=e)return null;const r=t.slice(e+1,n).trim();return r?{family:t.slice(0,e).trim(),type:r}:null}function Mr(s){const t=Qe(s),e=s.item.attrs.PredefinedType;return t?/escalera|stair|landing|descansillo/i.test(t.family)||e==="LANDING"||/plataforma|^pad\b|building pad/i.test(t.family)?"other":/cubierta|roof/i.test(t.family)||e==="ROOF"?"roof":/cimentaci|foundation/i.test(t.family)||e==="BASESLAB"?"foundation":"floor":"floor"}const Nr=180/Math.PI;function Fr(s){if(typeof s!="string")return null;const t=s.indexOf(":");return t<=0||t===s.length-1?null:{family:s.slice(0,t),type:s.slice(t+1)}}const ft=s=>String(s);function Oi(s){return async t=>{var Gs,Hs,Js,Ws,zs,Ys,Ks,Xs,Qs,Zs,tr,er,nr,sr,rr,ir,or,ar,cr,lr,hr;const{picked:e,contents:n,site:r,shapes:i}=await Ls(t,t.input),o=li(n.items),a=/CoordinateBase:\s*(Coordenadas compartidas|Shared Coordinates|Shared)/i.test(JSON.stringify(n.metadata??{})),l=a&&r?[r.east*Ne,r.north*Ne,r.elevation*Ne,r.angleDeg].map(h=>h.toFixed(6)).join(","):void 0;if(o.length===0)throw new Error(s==="ifc"?`Nothing in "${e.name}" could be read as a building element (walls, floors, levels...).`:`"${e.name}" carries no platform records, so there is nothing semantic to convert.`);const{columnType:d,trustStyleNames:c,includeInstances:m}=t.settings,w=t.settings.createLevels!==!1;if(m&&!c)throw new Error("Free-standing instances can only be made by their style names: turn trustStyleNames on.");const v=Ns(o),I=hi(o),_=`recipe:${s}-to-revit`,L=new Map,C=Fs(t,L);t.progress("Writing the changes for Revit");const O=new Nn({project:t.projectId,document:t.target.docId??"",baseCommit:t.target.version??0,author:_}),u=Ne,$=new Map;{const h=new Map;for(const f of o){const y=f.item.guid;if(!y)continue;const b=`${y}:${f.kind}`,R=h.get(b)??0;h.set(b,R+1),$.set(f.id,`${e.fileId}:${b}${R?`:${R}`:""}`)}}const E=h=>$.get(h)??`${e.fileId}:${h}`,N=new Set;let z=0,ut=0;const wt=(h,f,y)=>{N.add(h);const b=a?{...f,Frame:"shared",...l?{SharedAt:l}:{}}:f,R=di({attrs:b,placement:y??{}}),S=C.get(h);if(S){const k=L.get(h);return!k||k===R?(z++,!1):(O.remove(S),O.add({...b,"flow:print":R},{...y,source:h}),ut++,!1)}return O.add({...b,"flow:print":R},{...y,source:h}),!0},Ot=h=>{const f=typeof h=="string"?I.get(h):void 0,y=f==null?void 0:f.params.thickness;return typeof y=="number"&&y>0?y*u:void 0},Vt=h=>{var D,at;const f=Bt(h,"extrusion"),y=v.get(String((f==null?void 0:f.level)??h.params.level??"")),b=f==null?void 0:f.slopes,R=((at=(D=f==null?void 0:f.profile)==null?void 0:D.outline)==null?void 0:at.curves)??[],S=Array.isArray(b)?b.map(H=>typeof H=="number"):[],k=S.indexOf(!0);if(h.params.of!=="roof"||!y||R.length!==4||S.filter(Boolean).length!==2||k<0||k>1||!S[k+2])return null;const[A,j]=[R[k],R[k+2]],nt=A.from,ht=A.to,Y=Math.hypot(ht[0]-nt[0],ht[1]-nt[1]),St=[(ht[0]-nt[0])/Y,(ht[1]-nt[1])/Y];let U=[-St[1],St[0]];const ot=(j.from[0]-nt[0])*U[0]+(j.from[1]-nt[1])*U[1];ot<0&&(U=[-U[0],-U[1]]);const yt=Math.abs(ot),[P,G]=[b[k],b[k+2]],lt=y.at+(typeof h.params.base=="number"?h.params.base:0),$t=(f==null?void 0:f.eaves)??[],[tt,vt]=[lt+(Number($t[k])||0),lt+(Number($t[k+2])||0)],mt=(vt-tt+G*yt)/(P+G);return{A:nt,u:St,n:U,L:Y,W:yt,si:P,sj:G,ridge:mt,top:lt,ti:tt,tj:vt,zAt:(H,B)=>{const V=(H-nt[0])*U[0]+(B-nt[1])*U[1];return Math.min(tt+P*V,vt+G*(yt-V))}}},Mt=new Map(o.filter(h=>h.kind==="extrusion"&&h.params.of==="roof").map(h=>[h.id,h])),he=[...Mt.values()].filter(h=>h.item.guid).map(h=>({id:h.id,gid:h.item.guid}));let Yt=0;if(w)for(const[h,f]of v)wt(E(h),{CategoryId:ge.levels,Name:f.name,Elevation:ft(f.at*u)})&&Yt++;let It=0,Gt=0;const Nt=[];for(const h of o){if(h.kind!=="run"||h.params.of!=="wall")continue;const f=Bt(h,"run"),y=((Hs=(Gs=f==null?void 0:f.run)==null?void 0:Gs.line)==null?void 0:Hs.curves)??[],b=h.params.lookRef,R=v.get(String((f==null?void 0:f.level)??h.params.level??""));if(typeof b!="string"||typeof(f==null?void 0:f.height)!="number"||!R){Gt++;continue}const S=(Ot(b)??0)/u,k=y.filter(A=>A.kind==="segment"&&A.from&&A.to);Gt+=y.length-k.length,k.forEach((A,j)=>Nt.push({record:h,i:j,width:S,from:[...A.from],to:[...A.to],joinStart:j===0&&String(h.params.meetsAtStart)==="true",joinEnd:j===k.length-1&&String(h.params.meetsAtEnd)==="true"}))}const Ce=(h,f)=>{const y=[h.to[0]-h.from[0],h.to[1]-h.from[1]],b=[f.to[0]-f.from[0],f.to[1]-f.from[1]],R=y[0]*b[1]-y[1]*b[0];if(Math.abs(R)<1e-9*Math.hypot(...y)*Math.hypot(...b)*1e3)return null;const S=((f.from[0]-h.from[0])*b[1]-(f.from[1]-h.from[1])*b[0])/R;return[h.from[0]+S*y[0],h.from[1]+S*y[1]]},q=(h,f)=>{const y=f.to[0]-f.from[0],b=f.to[1]-f.from[1],R=y*y+b*b||1,S=Math.max(0,Math.min(1,((h[0]-f.from[0])*y+(h[1]-f.from[1])*b)/R));return Math.hypot(h[0]-(f.from[0]+S*y),h[1]-(f.from[1]+S*b))},Z=(h,f)=>{const y=Bt(h.record,"run"),b=Bt(f.record,"run"),R=[y.base,y.base+y.height],S=[b.base,b.base+b.height],k=v.get(String((y==null?void 0:y.level)??h.record.params.level)).at,A=v.get(String((b==null?void 0:b.level)??f.record.params.level)).at;return Math.min(k+R[1],A+S[1])>Math.max(k+R[0],A+S[0])},x=1,Tt=new Map;for(const h of Nt){const f=[["from",h.joinStart],["to",h.joinEnd]],y={from:h.from,to:h.to};for(const[b,R]of f){if(!R)continue;const S=h[b];let k=null,A=1/0;for(const ht of Nt){if(ht===h||!Z(h,ht))continue;const Y=q(S,ht);Y<A&&(A=Y,k=ht)}if(!k||A>x)continue;const j=Ce(h,k);if(!j)continue;const nt=Math.min(x,2*Math.max(h.width,k.width)+.02);Math.hypot(j[0]-S[0],j[1]-S[1])>nt||q(j,k)>k.width+.01||(y[b]=j)}Tt.set(h,y)}for(const h of Nt){const{record:f}=h,y=Bt(f,"run"),b=typeof y.base=="number"?y.base:0,R=y.height,S=v.get(String(y.level??f.params.level??"")),k=f.params.lookRef;let{from:A,to:j}=Tt.get(h);const nt=new Set;if(i&&f.item.guid&&Nt.filter(D=>D.record===f).length===1?i.elements.get(f.item.guid):void 0){const D=nn(i,f.item.guid),at=Math.hypot(j[0]-A[0],j[1]-A[1]);if(D.length>=4&&at>.05){const H=[(j[0]-A[0])/at,(j[1]-A[1])/at],B=D.map(bt=>(bt[0]-A[0])*H[0]+(bt[1]-A[1])*H[1]),V=Math.min(...B),ct=Math.max(...B),dt=D.map(bt=>-(bt[0]-A[0])*H[1]+(bt[1]-A[1])*H[0]),xt=Math.max(...dt)-Math.min(...dt),Q=bt=>{const Jt=dt.filter((fe,ue)=>Math.abs(B[ue]-bt)<.002);return Jt.length>=2&&Math.max(...Jt)-Math.min(...Jt)>.9*xt},J=A;Q(V)&&(A=[J[0]+H[0]*V,J[1]+H[1]*V],nt.add("start")),Q(ct)&&(j=[J[0]+H[0]*ct,J[1]+H[1]*ct],nt.add("end"))}}const Y=(S.at+b)*u,St=`${ft(A[0]*u)},${ft(A[1]*u)},${ft(Y)};${ft(j[0]*u)},${ft(j[1]*u)},${ft(Y)}`,U={CategoryId:ge.walls,Type:((Js=Qe(f))==null?void 0:Js.type)??k,LocationLine:St,Level:S.name,BaseOffset:ft(b*u),Height:ft(R*u)},ot=[A!==h.from||h.joinStart?"start":"",j!==h.to||h.joinEnd?"end":""].filter(D=>!!D&&!nt.has(D));ot.length&&(U.JoinEnds=ot.join(","));const yt=ot.filter(D=>f.params[D==="start"?"wantedAtStart":"wantedAtEnd"]==="mitre");yt.length&&(U.Mitre=yt.join(","));const P=v.get(String(f.params.topLevel??""));P&&(U.TopLevel=P.name,U.TopOffset=ft((S.at+b+R-P.at)*u));const G=y.profile;if(Array.isArray(G)&&G.length>=3&&h.i===0&&!Nt.some(D=>D!==h&&D.record===f)){const D=Math.hypot(h.to[0]-h.from[0],h.to[1]-h.from[1]),at=[(h.to[0]-h.from[0])/D,(h.to[1]-h.from[1])/D],H=[],B=-((A[0]-h.from[0])*at[0]+(A[1]-h.from[1])*at[1]),V=(j[0]-h.to[0])*at[0]+(j[1]-h.to[1])*at[1];G.forEach(([ct,dt],xt)=>{const Q=Math.abs(ct)<1e-6,J=Math.abs(ct-D)<1e-6;let bt=ct,Jt=dt;if(Q||J){bt=Q?-B:D+V;const ue=[G[(xt-1+G.length)%G.length],G[(xt+1)%G.length]].find(([Ve])=>Math.abs(Ve-ct)>1e-6);ue&&(Jt=dt+(ue[1]-dt)/(ue[0]-ct)*(bt-ct))}const fe=[h.from[0]+bt*at[0],h.from[1]+bt*at[1]];H.push(fe[0]*u,fe[1]*u,(S.at+b+Jt)*u)}),U.Profile=JSON.stringify([H]),delete U.TopLevel,delete U.TopOffset}const lt=f.params.topAttachedTo,$t=f.params.topAttachedAt==="top"||y.topAttachedAt==="top",tt=typeof lt=="string"&&$t&&!U.Profile&&Mt.has(lt)?Vt(Mt.get(lt)):null;if(tt){const D=Math.hypot(j[0]-A[0],j[1]-A[1]),at=Q=>[A[0]+(j[0]-A[0])*Q/D,A[1]+(j[1]-A[1])*Q/D],H=(A[0]-tt.A[0])*tt.n[0]+(A[1]-tt.A[1])*tt.n[1],B=(j[0]-tt.A[0])*tt.n[0]+(j[1]-tt.A[1])*tt.n[1],V=[0,D];(H-tt.ridge)*(B-tt.ridge)<0&&V.splice(1,0,(tt.ridge-H)/(B-H)*D);const ct=S.at+b,dt=[],xt=(Q,J)=>{const bt=at(Q);dt.push(bt[0]*u,bt[1]*u,J*u)};xt(0,ct),xt(D,ct);for(const Q of[...V].reverse()){const J=at(Q);xt(Q,tt.zAt(J[0],J[1]))}U.Profile=JSON.stringify([dt]),delete U.TopLevel,delete U.TopOffset}const vt=typeof lt=="string"?lt:i&&f.item.guid?Ca(i,f.item.guid,he):void 0;vt&&!U.Profile&&(U.AttachTop=E(vt));const mt=Ot(k);mt&&(U["Type.Width"]=ft(mt));const gt=f.item.guid?i==null?void 0:i.elements.get(f.item.guid):void 0;gt!=null&&gt.layers&&gt.layers.length>1&&(U["Type.Layers"]=JSON.stringify([...gt.layers].reverse().map(D=>[+ft(D.thickness*u),D.material??"",D.function??""])),gt.layersFlipped&&(U.FlipLayers="1")),wt(`${E(f.id)}#${h.i}`,U)&&It++}const Et=(h,f,y)=>{if(!(f>0)||f>=h)return[];const b=h-Math.floor(h/f+1e-9)*f,R=y==="beginning"?0:y==="end"?b:y==="centreLine"?h/2%f:b/2,S=[];for(let k=R;k<=h+1e-4;k+=f)k>1e-4&&k<h-1e-4&&S.push(k);return S};let pt=0,jt=0;for(const h of o){if(h.kind!=="run"||h.params.of!=="curtainWall")continue;jt++;const f=Bt(h,"run"),y=(Ys=(zs=(Ws=f==null?void 0:f.run)==null?void 0:Ws.line)==null?void 0:zs.curves)==null?void 0:Ys[0],b=v.get(String((f==null?void 0:f.level)??h.params.level??"")),R=h.params.lookRef,S=typeof R=="string"?(Ks=I.get(R))==null?void 0:Ks.params:void 0;if(!(y!=null&&y.from)||!y.to||typeof(f==null?void 0:f.height)!="number"||!b||!S)continue;const k=mt=>typeof mt=="number"?mt:Number(mt)||0,A=k(S.uprightWidth)/2,j=k(S.horizontalWidth)/2,nt=Math.hypot(y.to[0]-y.from[0],y.to[1]-y.from[1]),ht=[(y.to[0]-y.from[0])/nt,(y.to[1]-y.from[1])/nt],Y=[y.from[0]-ht[0]*A,y.from[1]-ht[1]*A],St=[y.to[0]+ht[0]*A,y.to[1]+ht[1]*A],U=(typeof f.base=="number"?f.base:0)-j,ot=f.height+2*j,yt=(b.at+U)*u,P=((Xs=f.lines)==null?void 0:Xs.along)??Et(nt,k(S.alongSpacing),S.alongJustify),G=((Qs=f.lines)==null?void 0:Qs.up)??Et(f.height,k(S.upSpacing),S.upJustify),lt=(f.omitted??[]).flatMap(mt=>{const gt=/^(horizontal|vertical)@(-?[\d.]+):(-?[\d.]+)$/.exec(mt);if(!gt)return[];const D=gt[1]==="horizontal",at=Number(gt[2])/1e3+(D?j:A),H=Number(gt[3])/1e3+(D?A:j);return[{horizontal:D,at:at*u,from:H*u}]}),$t=(f.omitted??[]).flatMap(mt=>{const gt=/^panel@(-?[\d.]+),(-?[\d.]+)$/.exec(mt);return gt?[{along:(Number(gt[1])/1e3+A)*u,up:(Number(gt[2])/1e3+j)*u}]:[]}),tt={CategoryId:ge.walls,Type:((Zs=Qe(h))==null?void 0:Zs.type)??String(R),LocationLine:`${ft(Y[0]*u)},${ft(Y[1]*u)},${ft(yt)};${ft(St[0]*u)},${ft(St[1]*u)},${ft(yt)}`,Level:b.name,BaseOffset:ft(U*u),Height:ft(ot*u),Curtain:JSON.stringify({along:P.map(mt=>(mt+A)*u),up:G.map(mt=>(mt+j)*u),omit:lt,empty:$t,mullion:{width:k(S.uprightWidth)*u,depth:k(S.depth)*u},panel:{thickness:k(S.panelDepth)*u,offset:-k(S.panelOffset)*u}})},vt=f.profile;if(Array.isArray(vt)&&vt.length>=3){const gt=vt.reduce((B,V,ct)=>{const dt=vt[(ct+1)%vt.length];return B+V[0]*dt[1]-dt[0]*V[1]},0)>0?1:-1,D=vt.length,at=vt.map((B,V)=>{const ct=vt[(V-1+D)%D],dt=vt[(V+1)%D],xt=(fe,ue)=>{const Ve=ue[0]-fe[0],Bn=ue[1]-fe[1],dr=Math.hypot(Ve,Bn)||1,fr=gt*Bn/dr,ur=-gt*Ve/dr,pr=Math.abs(fr)>Math.abs(ur)?A:j;return{p:[fe[0]+fr*pr,fe[1]+ur*pr],d:[Ve,Bn]}},Q=xt(ct,B),J=xt(B,dt),bt=Q.d[0]*J.d[1]-Q.d[1]*J.d[0];if(Math.abs(bt)<1e-12)return[J.p[0],J.p[1]];const Jt=((J.p[0]-Q.p[0])*J.d[1]-(J.p[1]-Q.p[1])*J.d[0])/bt;return[Q.p[0]+Jt*Q.d[0],Q.p[1]+Jt*Q.d[1]]}),H=[];for(const[B,V]of at)H.push((y.from[0]+ht[0]*B)*u,(y.from[1]+ht[1]*B)*u,(b.at+U+j+V)*u);tt.Profile=JSON.stringify([H])}wt(E(h.id),tt)&&pt++}let Ft=0,Pt=0;for(const h of o){if(h.kind!=="stair"||h.params.of!=="stair")continue;Pt++;const f=Bt(h,"stair"),y=h.params.lookRef,b=typeof y=="string"?(tr=I.get(y))==null?void 0:tr.params:void 0,R=v.get(String((f==null?void 0:f.level)??h.params.level??""));if(!(f!=null&&f.start)||!f.end||!(Number(f.rise)>0)||!R||!b)continue;const S=P=>typeof P=="number"?P:Number(P)||0,k=Number(f.rise),A=Math.max(1,Math.ceil(k/S(b.maxRiser)-1e-6)),j=S(b.tread),nt=P=>[P[0]*u,P[1]*u],ht={family:String(y).split(":")[0],base:(R.at+S(h.params.base))*u,height:k*u,risers:A,tread:j*u,width:S(b.width)*u,sizes:{maxRiser:Math.ceil(k/A*1e3-1e-6)/1e3*u,minTread:j*u,waist:S(b.waist)*u,treadThickness:S(b.treadThickness)*u,riserThickness:S(b.riserThickness)*u,notchExtension:S(b.notchExtension)*u,notchThickness:S(b.notchThickness)*u}},Y=f.sketch;if(Y!=null&&Y.boundary&&Y.boundary.length>=4&&Y.risers&&Y.risers.length>=2){const P=Y.boundary,G=Y.risers[Y.risers.length-1],lt=B=>[(B[0][0]+B[1][0])/2,(B[0][1]+B[1][1])/2],$t=lt(G);let tt=1,vt=1/0;for(let B=1;B<P.length;B++){const V=lt([P[B],P[(B+1)%P.length]]),ct=Math.abs(Math.hypot(V[0]-$t[0],V[1]-$t[1])-j);ct<vt&&(vt=ct,tt=B)}const mt=(B,V)=>{const ct=[];for(let dt=B;dt!==V;dt=(dt+1)%P.length)ct.push([nt(P[dt]),nt(P[(dt+1)%P.length])]);return ct},gt=[...mt(1,tt),...mt((tt+1)%P.length,0)],D=Y.risers.map(([B,V])=>[nt(B),nt(V)]);nt(P[tt]),nt(P[(tt+1)%P.length]);const at=D.map(([B,V])=>[(B[0]+V[0])/2,(B[1]+V[1])/2]);ht.sketch={boundary:gt,risers:D,path:at};let H=1/0;for(let B=0;B+1<Y.risers.length;B++){const[V,ct]=Y.risers[B],[dt,xt]=Y.risers[B+1],Q=[ct[0]-V[0],ct[1]-V[1]],J=[xt[0]-dt[0],xt[1]-dt[1]],bt=Math.hypot(Q[0],Q[1]),Jt=Math.hypot(J[0],J[1]);Math.abs((Q[0]*J[1]-Q[1]*J[0])/(bt*Jt))>.001||(H=Math.min(H,Math.abs(((dt[0]-V[0])*Q[1]-(dt[1]-V[1])*Q[0])/bt)))}Number.isFinite(H)&&(ht.tread=H*u,ht.sizes.minTread=H*u)}else ht.path=[nt([f.start[0],f.start[1]]),nt([f.end[0],f.end[1]])];const St=String(h.item.attrs.Name??""),U=St.replace(/ Run \d+$/,""),ot=[];for(const P of o){if(P.kind!=="extrusion"||U===St||!new RegExp(`^${U.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")} Landing \\d+$`).test(String(P.item.attrs.Name??"")))continue;const G=Bt(P,"extrusion"),lt=G==null?void 0:G.on,$t=(((nr=(er=G==null?void 0:G.profile)==null?void 0:er.outline)==null?void 0:nr.curves)??[]).flatMap(J=>J.from?[J.from]:[]),tt=Ot(P.params.lookRef),vt=v.get(String((G==null?void 0:G.level)??P.params.level??""));if(!(lt!=null&&lt.origin)||!lt.u||!lt.v||Math.abs(lt.v[2]??0)<.99||!$t.length||!tt||!vt)continue;const[mt,gt]=[Math.min(...$t.map(J=>J[0])),Math.max(...$t.map(J=>J[0]))],[D,at]=[Math.min(...$t.map(J=>J[1])),Math.max(...$t.map(J=>J[1]))],H=lt.origin,B=lt.u;let V=[B[1],-B[0]];const ct=[(f.start[0]+f.end[0])/2,(f.start[1]+f.end[1])/2];(ct[0]-H[0])*V[0]+(ct[1]-H[1])*V[1]<0&&(V=[-V[0],-V[1]]);const xt=tt/u,Q=(J,bt)=>[(H[0]+B[0]*J+V[0]*bt)*u,(H[1]+B[1]*J+V[1]*bt)*u];ot.push({outline:[Q(mt,0),Q(gt,0),Q(gt,xt),Q(mt,xt)],top:(vt.at+S(P.params.base)+H[2]+at)*u,thickness:(at-D)*u})}ot.length&&(ht.landings=ot);const yt={CategoryId:ge.stairs,Type:((sr=Qe(h))==null?void 0:sr.type)??String(y),Level:R.name,Stairs:JSON.stringify(ht)};wt(E(h.id),yt)&&Ft++}const st={floor:0,foundation:0,roof:0,ceiling:0},rt={floor:0,foundation:0,roof:0,ceiling:0};for(const h of o){const f=h.params.of;if(h.kind!=="extrusion"||f!=="slab"&&f!=="roof"&&f!=="covering")continue;const y=f==="covering"?"ceiling":f==="roof"?"roof":Mr(h);if(y==="other")continue;st[y]++;const b=Bt(h,"extrusion"),R=typeof h.params.base=="number"?h.params.base:0,S=v.get(String((b==null?void 0:b.level)??h.params.level??"")),k=h.params.lookRef,A=U=>{if(!(U!=null&&U.length))return null;const ot=[];for(const yt of U){if(yt.kind!=="segment"||!yt.from)return null;ot.push(yt.from[0]*u,yt.from[1]*u,R*u)}return ot.length>=9?ot:null},j=A((ir=(rr=b==null?void 0:b.profile)==null?void 0:rr.outline)==null?void 0:ir.curves);if(typeof k!="string"||!S||!j)continue;const nt=[j],ht=y==="roof"?Vt(h):null;for(const U of((or=b==null?void 0:b.profile)==null?void 0:or.holes)??[]){const ot=A(U==null?void 0:U.curves);if(ot&&ht)for(let yt=0;yt+2<ot.length;yt+=3)ot[yt+2]=ht.zAt(ot[yt]/u,ot[yt+1]/u)*u;ot&&nt.push(ot)}const Y={CategoryId:y==="roof"?ge.roofs:y==="ceiling"?ge.ceilings:y==="foundation"?ge.structuralFoundations:ge.floors,Type:((ar=Qe(h))==null?void 0:ar.type)??k,Profile:JSON.stringify(nt),Level:S.name},St=Ot(k);if(St&&(Y["Type.Width"]=ft(St)),y==="roof"||y==="ceiling"){Y.BaseOffset=ft(R*u);const U=Number(h.params.drop??((cr=b==null?void 0:b.said)==null?void 0:cr.drop));if(y==="ceiling"&&Number.isFinite(U)&&St){const P=[...v.values()].filter(G=>G.at>S.at+1e-6).sort((G,lt)=>G.at-lt.at)[0];P&&(Y.BaseOffset=ft((P.at-U-St/u-S.at)*u))}const ot=b==null?void 0:b.slopes;if(y==="roof"&&Array.isArray(ot)&&ot.some(P=>typeof P=="number")){Y.Slopes=JSON.stringify(ot.map(G=>typeof G=="number"?G:null));const P=Math.max(...ot.filter(G=>typeof G=="number").map(G=>Math.abs(G)));St&&P>0&&(Y.BaseOffset=ft(R*u-St*Math.sqrt(1+P*P)))}const yt=y==="roof"?Vt(h):null;if(yt){const{A:P,n:G,u:lt,W:$t,ridge:tt,si:vt,ti:mt,tj:gt,L:D}=yt,at=(H,B)=>[(P[0]+G[0]*H)*u,(P[1]+G[1]*H)*u,B*u];Y.Extrusion=JSON.stringify({profile:[at(0,mt),at(tt,mt+vt*tt),at($t,gt)],along:[lt[0],lt[1]],length:D*u}),delete Y.Slopes}}else St&&(Y.HeightOffset=ft(R*u+St));wt(E(h.id),Y)&&rt[y]++}let et=0,At=0;for(const h of o){if(h.kind!=="member"||h.params.of!=="column")continue;At++;const f=Bt(h,"member"),y=f==null?void 0:f.start;if(!y||y.length!==3)continue;const b=c?Fr(h.params.lookRef):null;if(c&&!b||!b&&!d)continue;const R=b??{family:d.family,type:d.type},S=v.get(String((f==null?void 0:f.level)??""));wt(E(h.id),{...d&&!b?{CategoryId:d.categoryId}:{},Family:R.family,Type:R.type,...S?{Level:S.name}:{}},{position:[y[0]*u,y[1]*u,y[2]*u],rotationDeg:(Number((f==null?void 0:f.roll)??0)||0)*Nr})&&et++}let Ht=0,de=0,Ue=0;for(const h of o){if(h.kind!=="familyInstance")continue;if(h.params.host){Ue++;continue}if(de++,!m)continue;const f=Bt(h,"instance"),y=(lr=f==null?void 0:f.placement)==null?void 0:lr.at;if(!y||y.length!==3)continue;const b=Fr(h.params.type);if(!b)continue;const R=(hr=f==null?void 0:f.placement)==null?void 0:hr.right,S=R?Math.atan2(R[1],R[0])*Nr:0;wt(E(h.id),{Family:b.family,Type:b.type},{position:[y[0]*u,y[1]*u,y[2]*u],rotationDeg:S})&&Ht++}const $e=(()=>{if(!i)return 0;const h=[];for(const y of Nt){const b=y.record.item.guid;if(!b||!i.elements.has(b))continue;const R=Bt(y.record,"run"),S=v.get(String((R==null?void 0:R.level)??y.record.params.level??""));if(!R||!S)continue;const k=nn(i,b);if(!k.length)continue;let A=1/0;for(const j of k)A=Math.min(A,j[2]);h.push(A-(S.at+(typeof R.base=="number"?R.base:0)))}h.sort((y,b)=>y-b);const f=h.length?h[Math.floor(h.length/2)]:0;return Math.abs(f)>.5?f:0})(),Vs=i?Ta(i,N,e.fileId):[];let un=0;for(const h of Vs)wt(h.key,h.attrs,{position:[h.at[0]*u,h.at[1]*u,(h.at[2]-$e)*u],rotationDeg:h.rotationDeg,...h.host?{host:h.host}:{}})&&un++;if(i)for(const h of Ea(i,N,e.fileId))wt(h.key,{WallOpening:h.box.map((f,y)=>ft((y%3===2?f-$e:f)*u)).join(",")},{host:h.host});if(i)for(const h of _a(i,e.fileId))wt(h.key,{Room:"1",Name:h.name,Number:h.number,Height:ft(h.height*u)},{position:[h.at[0]*u,h.at[1]*u,(h.at[2]-$e)*u]});let Pn=0;const Mi=new Set(["slab","roof","covering"]);for(const h of o){const f=h.params.of;(h.kind==="footing"||h.kind==="ramp"||h.kind==="stair"&&f!=="stair"||h.kind==="extrusion"&&!Mi.has(String(f))||h.kind==="extrusion"&&f==="slab"&&Mr(h)==="other"&&!/ Landing \d+$/.test(String(h.item.attrs.Name??""))||h.kind==="run"&&f!=="wall"&&f!=="curtainWall")&&Pn++}let qe=0;for(const[h,f]of C)!h.startsWith(`${e.fileId}:`)||N.has(h)||(O.remove(f),qe++);if(O.length===0)throw new Bs(`Up to date: "${e.name}" holds ${z} element(s) this recipe already made, ${Ue+Pn} waiting on the applier, and nothing is left to remove.`);const Ni=[Yt?`${Yt} level(s)`:"",It?`${It} wall(s)`:"",pt?`${pt} curtain wall(s)`:"",rt.floor?`${rt.floor} floor(s)`:"",rt.foundation?`${rt.foundation} foundation slab(s)`:"",rt.roof?`${rt.roof} roof(s)`:"",rt.ceiling?`${rt.ceiling} ceiling(s)`:"",Ft?`${Ft} stair(s)`:"",et?`${et} column(s)`:"",Ht?`${Ht} instance(s)`:"",un?`${un} family instance(s)`:"",ut?`${ut} changed`:"",qe?`${qe} gone`:""].filter(Boolean);return{title:`${s==="ifc"?"IFC":"Model"} to Revit: ${Ni.join(", ")}`,verb:O.summary,targets:O.length,payload:new Blob([await O.build(t.opId)]),ruleTallies:[{read:v.size,written:Yt},{read:Nt.length+Gt,written:It},{read:jt,written:pt},{read:st.floor+st.foundation,written:rt.floor+rt.foundation},{read:st.roof,written:rt.roof},{read:st.ceiling,written:rt.ceiling},{read:Pt,written:Ft},{read:At,written:et},{read:de,written:Ht},{read:Vs.length,written:un},{read:qe,written:qe},{read:Ue+Pn,written:0}]}}}const $a={type:"object",properties:{columnType:{type:"object",title:"Column type","x-existing":{of:"family-type",from:"target",where:{CategoryId:"-2001330"}}},trustStyleNames:{type:"boolean",title:"Use the model's own style names as Family:Type",default:!1},includeInstances:{type:"boolean",title:"Also bring free-standing instances (needs style names)",default:!1},createLevels:{type:"boolean",title:"Carry the model's levels (ensured by name)",default:!0}}},xa=[{reads:"Levels (datums)",writes:"The same level in Revit, ensured by name"},{reads:"Wall runs, one per straight segment",writes:"A native wall: line, type (made from its width when missing), level, height, joins; its edited profile or its top on a roof"},{reads:"Curtain wall runs",writes:"Revit's curtain wall: its grid lines, mullions and panels"},{reads:"Slabs: floors and foundation slabs",writes:"A native floor or foundation slab from the profile, holes included"},{reads:"Roofs",writes:"A footprint roof with its sloping edges, or a roof by extrusion for a gable"},{reads:"Ceilings (coverings)",writes:"A native ceiling from the profile, hung at its drop"},{reads:"Stairs",writes:"A native stair: a straight or sketched run, with its landings"},{reads:"Column records (members)",writes:"A Revit column at each, on its level"},{reads:"Free-standing family instances",writes:"When turned on: a new instance of the same-named type, placed and turned"},{reads:"Everything else with a body: doors, windows, furniture, fixtures, proxies, columns, railings",writes:"A family made from the file's own shape, one per shape, placed where the file has it (doors and windows in their wall)"},{reads:"Things this recipe made whose record is gone",writes:"That element removed"},{reads:"Hosted doors/windows, footings, ramps, other bodies",writes:"Nothing yet - read and counted"}],Ci=`
1
+ "use strict";var Di=Object.create;var Un=Object.defineProperty;var Ui=Object.getOwnPropertyDescriptor;var qi=Object.getOwnPropertyNames;var Vi=Object.getPrototypeOf,Gi=Object.prototype.hasOwnProperty;var yr=s=>{throw TypeError(s)};var Hi=(s,t,e)=>t in s?Un(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e;var Ji=(s,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of qi(t))!Gi.call(s,r)&&r!==e&&Un(s,r,{get:()=>t[r],enumerable:!(n=Ui(t,r))||n.enumerable});return s};var mn=(s,t,e)=>(e=s!=null?Di(Vi(s)):{},Ji(t||!s||!s.__esModule?Un(e,"default",{value:s,enumerable:!0}):e,s));var kt=(s,t,e)=>Hi(s,typeof t!="symbol"?t+"":t,e),qn=(s,t,e)=>t.has(s)||yr("Cannot "+e);var g=(s,t,e)=>(qn(s,t,"read from private field"),e?e.call(s):t.get(s)),K=(s,t,e)=>t.has(s)?yr("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(s):t.set(s,e),it=(s,t,e,n)=>(qn(s,t,"write to private field"),n?n.call(s,e):t.set(s,e),e),p=(s,t,e)=>(qn(s,t,"access private method"),e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ne=Object.create(null);ne.open="0";ne.close="1";ne.ping="2";ne.pong="3";ne.message="4";ne.upgrade="5";ne.noop="6";const vn=Object.create(null);Object.keys(ne).forEach(s=>{vn[ne[s]]=s});const Xn={type:"error",data:"parser error"},jr=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",Dr=typeof ArrayBuffer=="function",Ur=s=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(s):s&&s.buffer instanceof ArrayBuffer,_s=({type:s,data:t},e,n)=>jr&&t instanceof Blob?e?n(t):wr(t,n):Dr&&(t instanceof ArrayBuffer||Ur(t))?e?n(t):wr(new Blob([t]),n):n(ne[s]+(t||"")),wr=(s,t)=>{const e=new FileReader;return e.onload=function(){const n=e.result.split(",")[1];t("b"+(n||""))},e.readAsDataURL(s)};function vr(s){return s instanceof Uint8Array?s:s instanceof ArrayBuffer?new Uint8Array(s):new Uint8Array(s.buffer,s.byteOffset,s.byteLength)}let Vn;function Wi(s,t){if(jr&&s.data instanceof Blob)return s.data.arrayBuffer().then(vr).then(t);if(Dr&&(s.data instanceof ArrayBuffer||Ur(s.data)))return t(vr(s.data));_s(s,!1,e=>{Vn||(Vn=new TextEncoder),t(Vn.encode(e))})}const br="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Ke=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let s=0;s<br.length;s++)Ke[br.charCodeAt(s)]=s;const zi=s=>{let t=s.length*.75,e=s.length,n,r=0,i,o,a,l;s[s.length-1]==="="&&(t--,s[s.length-2]==="="&&t--);const d=new ArrayBuffer(t),c=new Uint8Array(d);for(n=0;n<e;n+=4)i=Ke[s.charCodeAt(n)],o=Ke[s.charCodeAt(n+1)],a=Ke[s.charCodeAt(n+2)],l=Ke[s.charCodeAt(n+3)],c[r++]=i<<2|o>>4,c[r++]=(o&15)<<4|a>>2,c[r++]=(a&3)<<6|l&63;return d},Yi=typeof ArrayBuffer=="function",As=(s,t)=>{if(typeof s!="string")return{type:"message",data:qr(s,t)};const e=s.charAt(0);return e==="b"?{type:"message",data:Ki(s.substring(1),t)}:vn[e]?s.length>1?{type:vn[e],data:s.substring(1)}:{type:vn[e]}:Xn},Ki=(s,t)=>{if(Yi){const e=zi(s);return qr(e,t)}else return{base64:!0,data:s}},qr=(s,t)=>{switch(t){case"blob":return s instanceof Blob?s:new Blob([s]);case"arraybuffer":default:return s instanceof ArrayBuffer?s:s.buffer}},Vr="",Xi=(s,t)=>{const e=s.length,n=new Array(e);let r=0;s.forEach((i,o)=>{_s(i,!1,a=>{n[o]=a,++r===e&&t(n.join(Vr))})})},Qi=(s,t)=>{const e=s.split(Vr),n=[];for(let r=0;r<e.length;r++){const i=As(e[r],t);if(n.push(i),i.type==="error")break}return n};function Zi(){return new TransformStream({transform(s,t){Wi(s,e=>{const n=e.length;let r;if(n<126)r=new Uint8Array(1),new DataView(r.buffer).setUint8(0,n);else if(n<65536){r=new Uint8Array(3);const i=new DataView(r.buffer);i.setUint8(0,126),i.setUint16(1,n)}else{r=new Uint8Array(9);const i=new DataView(r.buffer);i.setUint8(0,127),i.setBigUint64(1,BigInt(n))}s.data&&typeof s.data!="string"&&(r[0]|=128),t.enqueue(r),t.enqueue(e)})}})}let Gn;function gn(s){return s.reduce((t,e)=>t+e.length,0)}function yn(s,t){if(s[0].length===t)return s.shift();const e=new Uint8Array(t);let n=0;for(let r=0;r<t;r++)e[r]=s[0][n++],n===s[0].length&&(s.shift(),n=0);return s.length&&n<s[0].length&&(s[0]=s[0].slice(n)),e}function to(s,t){Gn||(Gn=new TextDecoder);const e=[];let n=0,r=-1,i=!1;return new TransformStream({transform(o,a){for(e.push(o);;){if(n===0){if(gn(e)<1)break;const l=yn(e,1);i=(l[0]&128)===128,r=l[0]&127,r<126?n=3:r===126?n=1:n=2}else if(n===1){if(gn(e)<2)break;const l=yn(e,2);r=new DataView(l.buffer,l.byteOffset,l.length).getUint16(0),n=3}else if(n===2){if(gn(e)<8)break;const l=yn(e,8),d=new DataView(l.buffer,l.byteOffset,l.length),c=d.getUint32(0);if(c>Math.pow(2,21)-1){a.enqueue(Xn);break}r=c*Math.pow(2,32)+d.getUint32(4),n=3}else{if(gn(e)<r)break;const l=yn(e,r);a.enqueue(As(i?l:Gn.decode(l),t)),n=0}if(r===0||r>s){a.enqueue(Xn);break}}}})}const Gr=4;function _t(s){if(s)return eo(s)}function eo(s){for(var t in _t.prototype)s[t]=_t.prototype[t];return s}_t.prototype.on=_t.prototype.addEventListener=function(s,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+s]=this._callbacks["$"+s]||[]).push(t),this};_t.prototype.once=function(s,t){function e(){this.off(s,e),t.apply(this,arguments)}return e.fn=t,this.on(s,e),this};_t.prototype.off=_t.prototype.removeListener=_t.prototype.removeAllListeners=_t.prototype.removeEventListener=function(s,t){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var e=this._callbacks["$"+s];if(!e)return this;if(arguments.length==1)return delete this._callbacks["$"+s],this;for(var n,r=0;r<e.length;r++)if(n=e[r],n===t||n.fn===t){e.splice(r,1);break}return e.length===0&&delete this._callbacks["$"+s],this};_t.prototype.emit=function(s){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),e=this._callbacks["$"+s],n=1;n<arguments.length;n++)t[n-1]=arguments[n];if(e){e=e.slice(0);for(var n=0,r=e.length;n<r;++n)e[n].apply(this,t)}return this};_t.prototype.emitReserved=_t.prototype.emit;_t.prototype.listeners=function(s){return this._callbacks=this._callbacks||{},this._callbacks["$"+s]||[]};_t.prototype.hasListeners=function(s){return!!this.listeners(s).length};const Nn=typeof Promise=="function"&&typeof Promise.resolve=="function"?t=>Promise.resolve().then(t):(t,e)=>e(t,0),qt=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),no="arraybuffer";function Hr(s,...t){return t.reduce((e,n)=>(s.hasOwnProperty(n)&&(e[n]=s[n]),e),{})}const so=qt.setTimeout,ro=qt.clearTimeout;function Fn(s,t){t.useNativeTimers?(s.setTimeoutFn=so.bind(qt),s.clearTimeoutFn=ro.bind(qt)):(s.setTimeoutFn=qt.setTimeout.bind(qt),s.clearTimeoutFn=qt.clearTimeout.bind(qt))}const io=1.33;function oo(s){return typeof s=="string"?ao(s):Math.ceil((s.byteLength||s.size)*io)}function ao(s){let t=0,e=0;for(let n=0,r=s.length;n<r;n++)t=s.charCodeAt(n),t<128?e+=1:t<2048?e+=2:t<55296||t>=57344?e+=3:(n++,e+=4);return e}function Jr(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function co(s){let t="";for(let e in s)s.hasOwnProperty(e)&&(t.length&&(t+="&"),t+=encodeURIComponent(e)+"="+encodeURIComponent(s[e]));return t}function lo(s){let t={},e=s.split("&");for(let n=0,r=e.length;n<r;n++){let i=e[n].split("=");t[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return t}class ho extends Error{constructor(t,e,n){super(t),this.description=e,this.context=n,this.type="TransportError"}}class Os extends _t{constructor(t){super(),this.writable=!1,Fn(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 ho(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=As(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=co(t);return e.length?"?"+e:""}}class fo extends Os{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(t){this.readyState="pausing";const e=()=>{this.readyState="paused",t()};if(this._polling||!this.writable){let n=0;this._polling&&(n++,this.once("pollComplete",function(){--n||e()})),this.writable||(n++,this.once("drain",function(){--n||e()}))}else e()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){const e=n=>{if(this.readyState==="opening"&&n.type==="open"&&this.onOpen(),n.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(n)};Qi(t,this.socket.binaryType).forEach(e),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){const t=()=>{this.write([{type:"close"}])};this.readyState==="open"?t():this.once("open",t)}write(t){this.writable=!1,Xi(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]=Jr()),!this.supportsBinary&&!e.sid&&(e.b64=1),this.createUri(t,e)}}let Wr=!1;try{Wr=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const uo=Wr;function po(){}class mo extends fo{constructor(t){if(super(t),typeof location<"u"){const e=location.protocol==="https:";let n=location.port;n||(n=e?"443":"80"),this.xd=typeof location<"u"&&t.hostname!==location.hostname||n!==t.port}}doWrite(t,e){const n=this.request({method:"POST",data:t});n.on("success",e),n.on("error",(r,i)=>{this.onError("xhr post error",r,i)})}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(e,n)=>{this.onError("xhr poll error",e,n)}),this.pollXhr=t}}class ee extends _t{constructor(t,e,n){super(),this.createRequest=t,Fn(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=Hr(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");e.xdomain=!!this._opts.xd;const n=this._xhr=this.createRequest(e);try{n.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let r in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(r)&&n.setRequestHeader(r,this._opts.extraHeaders[r])}}catch{}if(this._method==="POST")try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{n.setRequestHeader("Accept","*/*")}catch{}(t=this._opts.cookieJar)===null||t===void 0||t.addCookies(n),"withCredentials"in n&&(n.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(n.timeout=this._opts.requestTimeout),n.onreadystatechange=()=>{var r;n.readyState===3&&((r=this._opts.cookieJar)===null||r===void 0||r.parseCookies(n.getResponseHeader("set-cookie"))),n.readyState===4&&(n.status===200||n.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof n.status=="number"?n.status:0)},0))},n.send(this._data)}catch(r){this.setTimeoutFn(()=>{this._onError(r)},0);return}typeof document<"u"&&(this._index=ee.requestsCount++,ee.requests[this._index]=this)}_onError(t){this.emitReserved("error",t,this._xhr),this._cleanup(!0)}_cleanup(t){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=po,t)try{this._xhr.abort()}catch{}typeof document<"u"&&delete ee.requests[this._index],this._xhr=null}}_onLoad(){const t=this._xhr.responseText;t!==null&&(this.emitReserved("data",t),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}ee.requestsCount=0;ee.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",Tr);else if(typeof addEventListener=="function"){const s="onpagehide"in qt?"pagehide":"unload";addEventListener(s,Tr,!1)}}function Tr(){for(let s in ee.requests)ee.requests.hasOwnProperty(s)&&ee.requests[s].abort()}const go=function(){const s=zr({xdomain:!1});return s&&s.responseType!==null}();class yo extends mo{constructor(t){super(t);const e=t&&t.forceBase64;this.supportsBinary=go&&!e}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new ee(zr,this.uri(),t)}}function zr(s){const t=s.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!t||uo))return new XMLHttpRequest}catch{}if(!t)try{return new qt[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const Yr=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class wo extends Os{get name(){return"websocket"}doOpen(){const t=this.uri(),e=this.opts.protocols,n=Yr?{}:Hr(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(t,e,n)}catch(r){return this.emitReserved("error",r)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const n=t[e],r=e===t.length-1;_s(n,this.supportsBinary,i=>{try{this.doWrite(n,i)}catch{}r&&Nn(()=>{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]=Jr()),this.supportsBinary||(e.b64=1),this.createUri(t,e)}}const Hn=qt.WebSocket||qt.MozWebSocket;class vo extends wo{createSocket(t,e,n){return Yr?new Hn(t,e,n):e?new Hn(t,e):new Hn(t)}doWrite(t,e){this.ws.send(e)}}class bo extends Os{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=to(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=t.readable.pipeThrough(e).getReader(),r=Zi();r.readable.pipeTo(t.writable),this._writer=r.writable.getWriter();const i=()=>{n.read().then(({done:a,value:l})=>{a||(this.onPacket(l),i())}).catch(a=>{})};i();const o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this._writer.write(o).then(()=>this.onOpen())})})}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const n=t[e],r=e===t.length-1;this._writer.write(n).then(()=>{r&&Nn(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this._transport)===null||t===void 0||t.close()}}const To={websocket:vo,webtransport:bo,polling:yo},Eo=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Io=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Qn(s){if(s.length>8e3)throw"URI too long";const t=s,e=s.indexOf("["),n=s.indexOf("]");e!=-1&&n!=-1&&(s=s.substring(0,e)+s.substring(e,n).replace(/:/g,";")+s.substring(n,s.length));let r=Eo.exec(s||""),i={},o=14;for(;o--;)i[Io[o]]=r[o]||"";return e!=-1&&n!=-1&&(i.source=t,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=So(i,i.path),i.queryKey=_o(i,i.query),i}function So(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 _o(s,t){const e={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(n,r,i){r&&(e[r]=i)}),e}const Zn=typeof addEventListener=="function"&&typeof removeEventListener=="function",bn=[];Zn&&addEventListener("offline",()=>{bn.forEach(s=>s())},!1);class Se extends _t{constructor(t,e){if(super(),this.binaryType=no,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=Qn(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=Qn(e.host).host);Fn(this,e),this.secure=e.secure!=null?e.secure:typeof location<"u"&&location.protocol==="https:",e.hostname&&!e.port&&(e.port=this.secure?"443":"80"),this.hostname=e.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=e.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},e.transports.forEach(n=>{const r=n.prototype.name;this.transports.push(r),this._transportsByName[r]=n}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},e),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=lo(this.opts.query)),Zn&&(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"})},bn.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(t){const e=Object.assign({},this.opts.query);e.EIO=Gr,e.transport=t,this.id&&(e.sid=this.id);const n=Object.assign({},this.opts,{query:e,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new this._transportsByName[t](n)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const t=this.opts.rememberUpgrade&&Se.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const e=this.createTransport(t);e.open(),this.setTransport(e)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",e=>this._onClose("transport close",e))}onOpen(){this.readyState="open",Se.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",t),this.emitReserved("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const e=new Error("server error");e.code=t.data,this._onError(e);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data);break}}onHandshake(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this._pingInterval=t.pingInterval,this._pingTimeout=t.pingTimeout,this._maxPayload=t.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const t=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+t,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},t),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const t=this._getWritablePackets();this.transport.send(t),this._prevBufferLen=t.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let n=0;n<this.writeBuffer.length;n++){const r=this.writeBuffer[n].data;if(r&&(e+=oo(r)),n>0&&e>this._maxPayload)return this.writeBuffer.slice(0,n);e+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const t=Date.now()>this._pingTimeoutTime;return t&&(this._pingTimeoutTime=0,Nn(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),t}write(t,e,n){return this._sendPacket("message",t,e,n),this}send(t,e,n){return this._sendPacket("message",t,e,n),this}_sendPacket(t,e,n,r){if(typeof e=="function"&&(r=e,e=void 0),typeof n=="function"&&(r=n,n=null),this.readyState==="closing"||this.readyState==="closed")return;n=n||{},n.compress=n.compress!==!1;const i={type:t,data:e,options:n};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),r&&this.once("flush",r),this.flush()}close(){const t=()=>{this._onClose("forced close"),this.transport.close()},e=()=>{this.off("upgrade",e),this.off("upgradeError",e),t()},n=()=>{this.once("upgrade",e),this.once("upgradeError",e)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?n():t()}):this.upgrading?n():t()),this}_onError(t){if(Se.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",t),this._onClose("transport error",t)}_onClose(t,e){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),Zn&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const n=bn.indexOf(this._offlineEventListener);n!==-1&&bn.splice(n,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,e),this.writeBuffer=[],this._prevBufferLen=0}}}Se.protocol=Gr;class Ao extends Se{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let t=0;t<this._upgrades.length;t++)this._probe(this._upgrades[t])}_probe(t){let e=this.createTransport(t),n=!1;Se.priorWebsocketSuccess=!1;const r=()=>{n||(e.send([{type:"ping",data:"probe"}]),e.once("packet",m=>{if(!n)if(m.type==="pong"&&m.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",e),!e)return;Se.priorWebsocketSuccess=e.name==="websocket",this.transport.pause(()=>{n||this.readyState!=="closed"&&(c(),this.setTransport(e),e.send([{type:"upgrade"}]),this.emitReserved("upgrade",e),e=null,this.upgrading=!1,this.flush())})}else{const w=new Error("probe error");w.transport=e.name,this.emitReserved("upgradeError",w)}}))};function i(){n||(n=!0,c(),e.close(),e=null)}const o=m=>{const w=new Error("probe error: "+m);w.transport=e.name,i(),this.emitReserved("upgradeError",w)};function a(){o("transport closed")}function l(){o("socket closed")}function d(m){e&&m.name!==e.name&&i()}const c=()=>{e.removeListener("open",r),e.removeListener("error",o),e.removeListener("close",a),this.off("close",l),this.off("upgrading",d)};e.once("open",r),e.once("error",o),e.once("close",a),this.once("close",l),this.once("upgrading",d),this._upgrades.indexOf("webtransport")!==-1&&t!=="webtransport"?this.setTimeoutFn(()=>{n||e.open()},200):e.open()}onHandshake(t){this._upgrades=this._filterUpgrades(t.upgrades),super.onHandshake(t)}_filterUpgrades(t){const e=[];for(let n=0;n<t.length;n++)~this.transports.indexOf(t[n])&&e.push(t[n]);return e}}let Oo=class extends Ao{constructor(t,e={}){const n=typeof t=="object",r=n?{...t}:{...e};(!r.transports||r.transports&&typeof r.transports[0]=="string")&&(r.transports=(r.transports||["polling","websocket","webtransport"]).map(i=>To[i]).filter(i=>!!i)),super(n?r:t,r)}};function Co(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=Qn(s)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";const i=n.host.indexOf(":")!==-1?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+i+":"+n.port+t,n.href=n.protocol+"://"+i+(e&&e.port===n.port?"":":"+n.port),n}const $o=typeof ArrayBuffer=="function",xo=s=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(s):s.buffer instanceof ArrayBuffer,Kr=Object.prototype.toString,Ro=typeof Blob=="function"||typeof Blob<"u"&&Kr.call(Blob)==="[object BlobConstructor]",ko=typeof File=="function"||typeof File<"u"&&Kr.call(File)==="[object FileConstructor]";function Cs(s){return $o&&(s instanceof ArrayBuffer||xo(s))||Ro&&s instanceof Blob||ko&&s instanceof File}function Tn(s,t){if(!s||typeof s!="object")return!1;if(Array.isArray(s)){for(let e=0,n=s.length;e<n;e++)if(Tn(s[e]))return!0;return!1}if(Cs(s))return!0;if(s.toJSON&&typeof s.toJSON=="function"&&arguments.length===1)return Tn(s.toJSON(),!0);for(const e in s)if(Object.prototype.hasOwnProperty.call(s,e)&&Tn(s[e]))return!0;return!1}function Mo(s){const t=[],e=s.data,n=s;return n.data=ts(e,t),n.attachments=t.length,{packet:n,buffers:t}}function ts(s,t){if(!s)return s;if(Cs(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]=ts(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]=ts(s[n],t));return e}return s}function No(s,t){return s.data=es(s.data,t),delete s.attachments,s}function es(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]=es(s[e],t);else if(typeof s=="object")for(const e in s)Object.prototype.hasOwnProperty.call(s,e)&&(s[e]=es(s[e],t));return s}const Fo=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var X;(function(s){s[s.CONNECT=0]="CONNECT",s[s.DISCONNECT=1]="DISCONNECT",s[s.EVENT=2]="EVENT",s[s.ACK=3]="ACK",s[s.CONNECT_ERROR=4]="CONNECT_ERROR",s[s.BINARY_EVENT=5]="BINARY_EVENT",s[s.BINARY_ACK=6]="BINARY_ACK"})(X||(X={}));class Lo{constructor(t){this.replacer=t}encode(t){return(t.type===X.EVENT||t.type===X.ACK)&&Tn(t)?this.encodeAsBinary({type:t.type===X.EVENT?X.BINARY_EVENT:X.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id}):[this.encodeAsString(t)]}encodeAsString(t){let e=""+t.type;return(t.type===X.BINARY_EVENT||t.type===X.BINARY_ACK)&&(e+=t.attachments+"-"),t.nsp&&t.nsp!=="/"&&(e+=t.nsp+","),t.id!=null&&(e+=t.id),t.data!=null&&(e+=JSON.stringify(t.data,this.replacer)),e}encodeAsBinary(t){const e=Mo(t),n=this.encodeAsString(e.packet),r=e.buffers;return r.unshift(n),r}}class $s extends _t{constructor(t){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},typeof t=="function"?{reviver:t}:t)}add(t){let e;if(typeof t=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");e=this.decodeString(t);const n=e.type===X.BINARY_EVENT;n||e.type===X.BINARY_ACK?(e.type=n?X.EVENT:X.ACK,this.reconstructor=new Po(e),e.attachments===0&&super.emitReserved("decoded",e)):super.emitReserved("decoded",e)}else if(Cs(t)||t.base64)if(this.reconstructor)e=this.reconstructor.takeBinaryData(t),e&&(this.reconstructor=null,super.emitReserved("decoded",e));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+t)}decodeString(t){let e=0;const n={type:Number(t.charAt(0))};if(X[n.type]===void 0)throw new Error("unknown packet type "+n.type);if(n.type===X.BINARY_EVENT||n.type===X.BINARY_ACK){const i=e+1;for(;t.charAt(++e)!=="-"&&e!=t.length;);const o=t.substring(i,e);if(o!=Number(o)||t.charAt(e)!=="-")throw new Error("Illegal attachments");const a=Number(o);if(!Bo(a)||a<0)throw new Error("Illegal attachments");if(a>this.opts.maxAttachments)throw new Error("too many attachments");n.attachments=a}if(t.charAt(e+1)==="/"){const i=e+1;for(;++e&&!(t.charAt(e)===","||e===t.length););n.nsp=t.substring(i,e)}else n.nsp="/";const r=t.charAt(e+1);if(r!==""&&Number(r)==r){const i=e+1;for(;++e;){const o=t.charAt(e);if(o==null||Number(o)!=o){--e;break}if(e===t.length)break}n.id=Number(t.substring(i,e+1))}if(t.charAt(++e)){const i=this.tryParse(t.substr(e));if($s.isPayloadValid(n.type,i))n.data=i;else throw new Error("invalid payload")}return n}tryParse(t){try{return JSON.parse(t,this.opts.reviver)}catch{return!1}}static isPayloadValid(t,e){switch(t){case X.CONNECT:return Er(e);case X.DISCONNECT:return e===void 0;case X.CONNECT_ERROR:return typeof e=="string"||Er(e);case X.EVENT:case X.BINARY_EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&Fo.indexOf(e[0])===-1);case X.ACK:case X.BINARY_ACK:return Array.isArray(e)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class Po{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=No(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const Bo=Number.isInteger||function(s){return typeof s=="number"&&isFinite(s)&&Math.floor(s)===s};function Er(s){return Object.prototype.toString.call(s)==="[object Object]"}const jo=Object.freeze(Object.defineProperty({__proto__:null,Decoder:$s,Encoder:Lo,get PacketType(){return X}},Symbol.toStringTag,{value:"Module"}));function zt(s,t,e){return s.on(t,e),function(){s.off(t,e)}}const Do=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Xr extends _t{constructor(t,e,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=t,this.nsp=e,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const t=this.io;this.subs=[zt(t,"open",this.onopen.bind(this)),zt(t,"packet",this.onpacket.bind(this)),zt(t,"error",this.onerror.bind(this)),zt(t,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...t){return t.unshift("message"),this.emit.apply(this,t),this}emit(t,...e){var n,r,i;if(Do.hasOwnProperty(t))throw new Error('"'+t.toString()+'" is a reserved event name');if(e.unshift(t),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(e),this;const o={type:X.EVENT,data:e};if(o.options={},o.options.compress=this.flags.compress!==!1,typeof e[e.length-1]=="function"){const c=this.ids++,m=e.pop();this._registerAckCallback(c,m),o.id=c}const a=(r=(n=this.io.engine)===null||n===void 0?void 0:n.transport)===null||r===void 0?void 0:r.writable,l=this.connected&&!(!((i=this.io.engine)===null||i===void 0)&&i._hasPingExpired());return this.flags.volatile&&!a||(l?(this.notifyOutgoingListeners(o),this.packet(o)):this.sendBuffer.push(o)),this.flags={},this}_registerAckCallback(t,e){var n;const r=(n=this.flags.timeout)!==null&&n!==void 0?n:this._opts.ackTimeout;if(r===void 0){this.acks[t]=e;return}const i=this.io.setTimeoutFn(()=>{delete this.acks[t];for(let a=0;a<this.sendBuffer.length;a++)this.sendBuffer[a].id===t&&this.sendBuffer.splice(a,1);e.call(this,new Error("operation has timed out"))},r),o=(...a)=>{this.io.clearTimeoutFn(i),e.apply(this,a)};o.withError=!0,this.acks[t]=o}emitWithAck(t,...e){return new Promise((n,r)=>{const i=(o,a)=>o?r(o):n(a);i.withError=!0,e.push(i),this.emit(t,...e)})}_addToQueue(t){let e;typeof t[t.length-1]=="function"&&(e=t.pop());const n={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((r,...i)=>(this._queue[0],r!==null?n.tryCount>this._opts.retries&&(this._queue.shift(),e&&e(r)):(this._queue.shift(),e&&e(null,...i)),n.pending=!1,this._drainQueue())),this._queue.push(n),this._drainQueue()}_drainQueue(t=!1){if(!this.connected||this._queue.length===0)return;const e=this._queue[0];e.pending&&!t||(e.pending=!0,e.tryCount++,this.flags=e.flags,this.emit.apply(this,e.args))}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){typeof this.auth=="function"?this.auth(t=>{this._sendConnectPacket(t)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:X.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,e){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,e),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(t=>{if(!this.sendBuffer.some(n=>String(n.id)===t)){const n=this.acks[t];delete this.acks[t],n.withError&&n.call(this,new Error("socket has been disconnected"))}})}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case X.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case X.EVENT:case X.BINARY_EVENT:this.onevent(t);break;case X.ACK:case X.BINARY_ACK:this.onack(t);break;case X.DISCONNECT:this.ondisconnect();break;case X.CONNECT_ERROR:this.destroy();const n=new Error(t.data.message);n.data=t.data.data,this.emitReserved("connect_error",n);break}}onevent(t){const e=t.data||[];t.id!=null&&e.push(this.ack(t.id)),this.connected?this.emitEvent(e):this.receiveBuffer.push(Object.freeze(e))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){const e=this._anyListeners.slice();for(const n of e)n.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&typeof t[t.length-1]=="string"&&(this._lastOffset=t[t.length-1])}ack(t){const e=this;let n=!1;return function(...r){n||(n=!0,e.packet({type:X.ACK,id:t,data:r}))}}onack(t){const e=this.acks[t.id];typeof e=="function"&&(delete this.acks[t.id],e.withError&&t.data.unshift(null),e.apply(this,t.data))}onconnect(t,e){this.id=t,this.recovered=e&&this._pid===e,this._pid=e,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:X.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){const e=this._anyListeners;for(let n=0;n<e.length;n++)if(t===e[n])return e.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(t),this}prependAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(t),this}offAnyOutgoing(t){if(!this._anyOutgoingListeners)return this;if(t){const e=this._anyOutgoingListeners;for(let n=0;n<e.length;n++)if(t===e[n])return e.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(t){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const e=this._anyOutgoingListeners.slice();for(const n of e)n.apply(this,t.data)}}}function Ue(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}Ue.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};Ue.prototype.reset=function(){this.attempts=0};Ue.prototype.setMin=function(s){this.ms=s};Ue.prototype.setMax=function(s){this.max=s};Ue.prototype.setJitter=function(s){this.jitter=s};class ns extends _t{constructor(t,e){var n;super(),this.nsps={},this.subs=[],t&&typeof t=="object"&&(e=t,t=void 0),e=e||{},e.path=e.path||"/socket.io",this.opts=e,Fn(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 Ue({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(e.timeout==null?2e4:e.timeout),this._readyState="closed",this.uri=t;const r=e.parser||jo;this.encoder=new r.Encoder,this.decoder=new r.Decoder,this._autoConnect=e.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,t||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(t){return t===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var e;return t===void 0?this._reconnectionDelay:(this._reconnectionDelay=t,(e=this.backoff)===null||e===void 0||e.setMin(t),this)}randomizationFactor(t){var e;return t===void 0?this._randomizationFactor:(this._randomizationFactor=t,(e=this.backoff)===null||e===void 0||e.setJitter(t),this)}reconnectionDelayMax(t){var e;return t===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,(e=this.backoff)===null||e===void 0||e.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(t){if(~this._readyState.indexOf("open"))return this;this.engine=new Oo(this.uri,this.opts);const e=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const r=zt(e,"open",function(){n.onopen(),t&&t()}),i=a=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",a),t?t(a):this.maybeReconnectOnOpen()},o=zt(e,"error",i);if(this._timeout!==!1){const a=this._timeout,l=this.setTimeoutFn(()=>{r(),i(new Error("timeout")),e.close()},a);this.opts.autoUnref&&l.unref(),this.subs.push(()=>{this.clearTimeoutFn(l)})}return this.subs.push(r),this.subs.push(o),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(zt(t,"ping",this.onping.bind(this)),zt(t,"data",this.ondata.bind(this)),zt(t,"error",this.onerror.bind(this)),zt(t,"close",this.onclose.bind(this)),zt(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(e){this.onclose("parse error",e)}}ondecoded(t){Nn(()=>{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 Xr(this,t,e),this.nsps[t]=n),n}_destroy(t){const e=Object.keys(this.nsps);for(const n of e)if(this.nsps[n].active)return;this._close()}_packet(t){const e=this.encoder.encode(t);for(let n=0;n<e.length;n++)this.engine.write(e[n],t.options)}cleanup(){this.subs.forEach(t=>t()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(t,e){var n;this.cleanup(),(n=this.engine)===null||n===void 0||n.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,e),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const e=this.backoff.duration();this._reconnecting=!0;const n=this.setTimeoutFn(()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),!t.skipReconnect&&t.open(r=>{r?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",r)):t.onreconnect()}))},e);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const He={};function tn(s,t){typeof s=="object"&&(t=s,s=void 0),t=t||{};const e=Co(s,t.path||"/socket.io"),n=e.source,r=e.id,i=e.path,o=He[r]&&i in He[r].nsps,a=t.forceNew||t["force new connection"]||t.multiplex===!1||o;let l;return a?l=new ns(n,t):(He[r]||(He[r]=new ns(n,t)),l=He[r]),e.query&&!t.query&&(t.query=e.queryKey),l.socket(e.path,t)}Object.assign(tn,{Manager:ns,Socket:Xr,io:tn,connect:tn});class ss 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 Ir="bimterop",rs="revitflow_history.json",Qr="revitflow_model.frag",Zr="revitflow_",Uo="bimterop-locks-anchor",Je=new Map;function qo(s,t){return s.filter(e=>String(e.parentId??"")===t)}function Vo(s){const t=s==null?void 0:s.hiddenFileId;if(typeof t!="string"||!t)throw new Error("The hidden-file upload answered without a hiddenFileId.");return t}function Zt(s){return String(s._id??s.id??"")}var Wt,Ae,oe,rn,on,is;class xs{constructor(t,e){K(this,on);K(this,Wt);K(this,Ae,new Map);K(this,oe);K(this,rn,0);this.client=t,this.projectId=e}async docs(){const t=await p(this,on,is).call(this);if(!t)return[];const e=await this.childFolders(t,!0),n=[];for(const r of e){if(r.archived)continue;const i=String(r.name??""),o=i.indexOf("-");if(o<=0)continue;const l=(await this.client.listFiles({folderId:Zt(r)})).map(m=>String(m.name??"")),d=l.find(m=>m===Qr)??l.find(m=>m.endsWith(".frag")&&!m.startsWith(Zr)),c=l.includes(rs)||!!d;n.push({source:i.slice(0,o),docId:i.slice(o+1),folderId:Zt(r),modelName:d,...c?{}:{empty:!0}})}return n}doc(t,e){const n=`${t}-${e}`;let r=g(this,Ae).get(n);return r||(r=new os(this.client,this,t,e),g(this,Ae).set(n,r)),r}document(t){const e=`platform-${t}`;let n=g(this,Ae).get(e);return n||(n=new os(this.client,this,"platform",t,t),g(this,Ae).set(e,n)),n}async childFolders(t,e=!1){return(e||!g(this,oe)||Date.now()-g(this,rn)>3e4)&&(it(this,rn,Date.now()),it(this,oe,this.client.listFolders({parentFolderId:t,projectId:this.projectId}).then(n=>qo(n,t))),g(this,oe).catch(()=>{it(this,oe,void 0)})),g(this,oe)}forgetFolders(){it(this,oe,void 0)}async rootFolderId(t=!1){if(g(this,Wt))return g(this,Wt);const e=await p(this,on,is).call(this);if(e)return e;if(!t)return;const n=await this.client.createFolder(Ir,void 0,this.projectId);return it(this,Wt,Zt(n)),g(this,Wt)}}Wt=new WeakMap,Ae=new WeakMap,oe=new WeakMap,rn=new WeakMap,on=new WeakSet,is=async function(){if(g(this,Wt))return g(this,Wt);const e=(await this.client.listFolders({projectId:this.projectId})).find(n=>String(n.name??"")===Ir&&!n.parentId);return e&&it(this,Wt,Zt(e)),g(this,Wt)};var Xt,M,ie,ke,ye,Qt,an,as,En,we,ti,ei,In,ni,si,ri;class os{constructor(t,e,n,r,i){K(this,M);K(this,Xt);K(this,Qt);K(this,an,0);this.client=t,this.project=e,this.source=n,this.docId=r,it(this,Xt,i)}async timeline(){const t=await p(this,M,In).call(this);return Rs((t==null?void 0:t.commits)??[])}async latest(){const t=await this.timeline();return t.length?t[t.length-1]:null}async delta(t){if(!t.deltaId)throw new Error(`Version ${t.guid} carries no delta: it is a full export — read model() instead.`);return await(await this.client.downloadHiddenFile(t.deltaId)).blob()}async model(){const t=await p(this,M,we).call(this);if(!t)throw new Error(`Document ${this.source}-${this.docId} has no model file yet.`);const e=await this.client.downloadFile(t.id);if(!e.ok)throw new Error(`Reading the model answered ${e.status}`);return await e.blob()}async modelParts(t){const e=await this.timeline();if(e.length===0)throw new Error(`Document ${this.source}-${this.docId} has no history yet.`);const n=t==null?void 0:t.at,r=n?e.findIndex(c=>c.guid===n):e.length-1;if(r<0)throw new Error(`No version ${n} in this document's timeline.`);let i=0;for(let c=r;c>=0;c--)if(e[c].full){i=c;break}const o=await p(this,M,we).call(this);if(!o)throw new Error(`Document ${this.source}-${this.docId} has no model file yet.`);const a=e[i],l=e.slice(r+1).some(c=>c.full),d=e.slice(i+1,r+1).map(c=>({guid:c.guid,...c.deltaId?{deltaId:c.deltaId}:{},...c.streamId?{streamId:c.streamId}:{},removedUniqueIds:c.changes.filter(m=>m.type==="delete").map(m=>m.uniqueId)}));return{baseline:{fileId:o.id,guid:a.guid,current:!l,...a.version!==void 0?{storageVersion:a.version}:{}},steps:d,at:e[r].guid}}async folderId(){return await p(this,M,ye).call(this,!1)}async descriptor(){return await g(this,M,ie).descriptor(await p(this,M,ye).call(this,!1))}async view(t){const e=await p(this,M,ye).call(this,!1),n=await g(this,M,ie).descriptor(e);if(n){for(const i of t){const o=n.views.find(a=>a.format===i);if(o)return o}return null}if(!t.includes("frag"))return null;const r=await p(this,M,we).call(this);return r?{fileId:r.id,format:"frag"}:null}async addView(t){const e=await p(this,M,ye).call(this,!0);if(await g(this,M,ie).descriptor(e)){await g(this,M,ie).addView(e,t);return}const r=await p(this,M,we).call(this);await g(this,M,ie).setDescriptor(e,{name:(r==null?void 0:r.name.replace(/\.frag$/,""))??g(this,M,ke),views:[t]})}async ensureDescriptor(){const t=await p(this,M,ye).call(this,!1),e=await g(this,M,ie).descriptor(t);if(e)return e;const n=await p(this,M,we).call(this);if(!n)return null;const r={name:n.name.replace(/\.frag$/,""),views:[{fileId:n.id,format:"frag"}]};return await g(this,M,ie).setDescriptor(t,r),await g(this,M,ie).descriptor(t)}async ownership(){const t=await p(this,M,En).call(this,Uo);if(!t)return[];const e=await this.client.getHiddenFilesByParent(t.id),n=await Promise.all(e.map(async o=>{try{const a=Zt(o),l=await this.client.downloadHiddenFile(a),d=JSON.parse(await l.text());return!d||typeof d!="object"||!("revitflowlock"in d)||!Array.isArray(d.keys)?null:{owner:String(d.user??""),keys:d.keys.filter(c=>typeof c=="string")}}catch{return null}})),r=new Set,i=new Map;for(const o of n)if(o)for(const a of o.keys){if(!a||r.has(a))continue;r.add(a);const l=i.get(o.owner)??[];l.push(a),i.set(o.owner,l)}return[...i.entries()].map(([o,a])=>({owner:o,elements:a}))}async sync(t){var a;const e=await p(this,M,ye).call(this,!0);let n=await p(this,M,In).call(this)??{model:this.docId,commits:[]};const r=Sr(n.commits);if(t.expectedLatestGuid!==void 0&&(r==null?void 0:r.guid)!==t.expectedLatestGuid)throw new ss(t.expectedLatestGuid,r==null?void 0:r.guid);const i={guid:ks(),...r?{parents:[r.guid]}:{},author:t.author,source:t.source,timestamp:new Date().toISOString(),...t.message?{message:t.message}:{},...t.userId?{userId:t.userId}:{},...t.kind?{kind:t.kind}:{},...t.file?{file:t.file}:{},...t.origin?{origin:t.origin}:{},...(a=t.origins)!=null&&a.length?{origins:t.origins}:{},changes:t.changes,counts:Go(t.changes)};if(t.model&&(await p(this,M,ri).call(this,e,t.model),i.full=!0),t.delta){const l=await p(this,M,we).call(this);if(!l)throw new Error("A delta needs the model file to hang from: sync a full model first.");const d=await this.client.createHiddenFile(t.delta,l.id);i.deltaId=Vo(d)}const o=await p(this,M,In).call(this);if(o){n=o;const l=Sr(n.commits);if(t.expectedLatestGuid!==void 0&&(l==null?void 0:l.guid)!==t.expectedLatestGuid)throw new ss(t.expectedLatestGuid,l==null?void 0:l.guid);l&&!i.parents&&(i.parents=[l.guid])}return n.commits.push(i),await p(this,M,ni).call(this,e,rs,n),i}}Xt=new WeakMap,M=new WeakSet,ie=function(){return new Ns(this.client,this.project.projectId)},ke=function(){return`${this.source}-${this.docId}`},ye=async function(t){if(g(this,Xt))return g(this,Xt);const e=await this.project.rootFolderId(t);if(!e)throw new Error(`Project ${this.project.projectId} has no connected documents yet.`);const n=o=>o.find(a=>String(a.name??"")===g(this,M,ke)),r=n(await this.project.childFolders(e))??n(await this.project.childFolders(e,!0));if(r)return it(this,Xt,Zt(r)),g(this,Xt);if(!t)throw new Error(`Document ${g(this,M,ke)} does not exist in this project.`);const i=await this.client.createFolder(g(this,M,ke),e,this.project.projectId);return this.project.forgetFolders(),it(this,Xt,Zt(i)),g(this,Xt)},Qt=new WeakMap,an=new WeakMap,as=async function(){return(!g(this,Qt)||Date.now()-g(this,an)>5e3)&&(it(this,an,Date.now()),it(this,Qt,(async()=>{const t=await p(this,M,ye).call(this,!1);return(await this.client.listFiles({projectId:this.project.projectId})).filter(n=>{const r=n;return String(r.folderId??r.parentFolderId??"")===t}).map(n=>({id:Zt(n),name:String(n.name??""),stamp:kn(n)}))})()),g(this,Qt).catch(()=>{it(this,Qt,void 0)})),g(this,Qt)},En=async function(t){try{return(await p(this,M,as).call(this)).find(e=>e.name===t)}catch{return}},we=async function(){try{const t=await p(this,M,as).call(this);return t.find(e=>e.name===Qr)??t.find(e=>e.name.endsWith(".frag")&&!e.name.startsWith(Zr))}catch{return}},ti=async function(t){const e=await p(this,M,En).call(this,t);if(!e)return;const n=e.stamp?Je.get(e.id):void 0;if(n&&n.stamp===e.stamp)return structuredClone(await n.value);const r=p(this,M,ei).call(this,e,t);return e.stamp&&(Je.set(e.id,{stamp:e.stamp,value:r}),r.catch(()=>{var i;((i=Je.get(e.id))==null?void 0:i.value)===r&&Je.delete(e.id)})),structuredClone(await r)},ei=async function(t,e){const n=await this.client.downloadFile(t.id);if(!n.ok)throw new Error(`Reading ${e} answered ${n.status}`);const r=await n.text();if(r.trim())return JSON.parse(r)},In=function(){return p(this,M,ti).call(this,rs)},ni=async function(t,e,n){const r=new Blob([JSON.stringify(n)],{type:"application/json"}),i=await p(this,M,En).call(this,e);return i?(Je.delete(i.id),await this.client.updateFile(i.id,{file:r,versionTag:await this.client.nextVersionTag(i.id)}),i):await p(this,M,si).call(this,t,e,n)},si=async function(t,e,n){const r=new Blob([JSON.stringify(n)],{type:"application/json"}),i=await this.client.createFile({file:r,name:e,versionTag:"v1",parentFolderId:t,projectId:this.project.projectId});it(this,Qt,void 0);const o=i.item;return{id:Zt(o??i),name:e}},ri=async function(t,e){const n=await p(this,M,we).call(this);if(n)return await this.client.updateFile(n.id,{file:e,versionTag:await this.client.nextVersionTag(n.id)}),n;const r=`${g(this,M,ke)}.frag`,i=await this.client.createFile({file:e,name:r,versionTag:"v1",parentFolderId:t,projectId:this.project.projectId});it(this,Qt,void 0);const o=i.item;return{id:Zt(o??i),name:r}};function Go(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 Rs(s){var l;if(s.length<=1)return s.forEach((d,c)=>d.ordinal=c),[...s];const t=new Map(s.map(d=>[d.guid,d])),e=new Map,n=[];for(const d of s){const c=(l=d.parents)==null?void 0:l[0];if(c&&t.has(c)){const m=e.get(c)??[];m.push(d),e.set(c,m)}else n.push(d)}const r=(d,c)=>String(d.timestamp).localeCompare(String(c.timestamp));n.sort(r);const i=[],o=[...n].reverse(),a=new Set;for(;o.length;){const d=o.pop();if(a.has(d.guid))continue;a.add(d.guid),i.push(d);const c=(e.get(d.guid)??[]).sort(r);for(let m=c.length-1;m>=0;m--)o.push(c[m])}for(const d of s)a.has(d.guid)||i.push(d);return i.forEach((d,c)=>d.ordinal=c),i}function Sr(s){const t=Rs(s);return t[t.length-1]}function ks(){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 Ms={bim:{label:"BIM model",icon:"tabler:building"},drawings:{label:"Drawings",icon:"tabler:layout-board"},reality:{label:"Reality capture",icon:"tabler:3d-cube-sphere"},coordination:{label:"Coordination set",icon:"tabler:messages"},generic:{label:"Generic",icon:"tabler:file"}},Ho={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 cs(s){var e;if(s.type&&s.type in Ms)return s.type;const t=[(e=s.native)==null?void 0:e.format,...s.views.map(n=>n.format)];for(const n of t){const r=n?Ho[n.toLowerCase()]:void 0;if(r)return r}return"generic"}const nn="thatopen/document@1",Sn="document.json",ii=["pdf","txt","md","json","csv","tsv","frag"];function se(s){return String(s._id??s.id??"")}const xe=new Map;let _r=!1;const kn=s=>{const t=s,e=[...t.versions??[]].sort((r,i)=>String(i.createdAt??"").localeCompare(String(r.createdAt??"")))[0],n=(e==null?void 0:e.tag)??t.versionTag;return n==null?void 0:String(n)};var Ot,oi,ai,ls,ci,li,hi,_n;class Ns{constructor(t,e){K(this,Ot);this.client=t,this.projectId=e}async list(t){const e=await p(this,Ot,oi).call(this),n=t==null?void 0:t.types;return n!=null&&n.length?e.filter(r=>n.includes(cs(r.descriptor))):e}async fromFile(t,e){const n=await this.client.getFile(t),r=String(n.name??""),i=Jn(r,n.fileExtension),o=(e==null?void 0:e.name)??r.replace(/\.[^.]+$/,"")??r,a=await this.client.createFolder(o,n.folderId?String(n.folderId):void 0,this.projectId),l=se(a);await this.client.updateFile(t,{parentFolderId:l});const d=[],c=await p(this,Ot,li).call(this,n);if(c)try{const v=await this.client.getFile(c);await this.client.updateFile(c,{parentFolderId:l}),d.push({fileId:c,format:Jn(String(v.name??""),v.fileExtension)})}catch{}((e==null?void 0:e.selfView)??ii.includes(i))&&d.push({fileId:t,format:i});const w={schema:nn,name:o,native:{fileId:t,format:i},views:d};return w.type=(e==null?void 0:e.type)??cs(w),await this.setDescriptor(l,w),await this.recordUpload(l,{fileId:t,name:r,format:i},(e==null?void 0:e.author)??String(n.createdBy??"")),{folderId:l,descriptor:w}}async recordUpload(t,e,n){const r=new xs(this.client,this.projectId).document(t),i=(await r.timeline()).length===0;await r.sync({author:n||"unknown",source:"platform",kind:"upload",message:i?"Uploaded to the platform":"New version uploaded",file:{...e,format:e.format??Jn(e.name,void 0)},changes:[]})}async descriptor(t){const e=await p(this,Ot,_n).call(this,t);return e?p(this,Ot,ls).call(this,e.id,e.stamp):null}async view(t,e){const n=await this.descriptor(t);if(!n)return null;for(const r of e){const i=n.views.find(o=>o.format===r);if(i)return i}return null}async addView(t,e){const n=await this.descriptor(t);if(!n)throw new Error("This folder has no document descriptor yet: call setDescriptor first.");n.views=[...n.views.filter(r=>r.format!==e.format),e],await this.setDescriptor(t,n)}async setType(t,e){const n=await this.descriptor(t);if(!n)throw new Error("This folder has no document descriptor yet: call setDescriptor first.");n.type!==e&&await this.setDescriptor(t,{...n,type:e})}async setDescriptor(t,e){const n={...e,schema:nn,views:e.views??[]},r=new Blob([JSON.stringify(n)],{type:"application/json"}),i=await p(this,Ot,_n).call(this,t);if(i){xe.delete(i.id),await this.client.updateFile(i.id,{file:r,versionTag:await this.client.nextVersionTag(i.id)});return}await this.client.createFile({file:r,name:Sn,versionTag:"v1",parentFolderId:t,projectId:this.projectId})}drafts(t){return new di(this.client,()=>p(this,Ot,_n).call(this,t))}}Ot=new WeakSet,oi=async function(){const t=await p(this,Ot,ai).call(this);if(t)return t;const n=(await this.client.listFiles({projectId:this.projectId})).filter(i=>String(i.name??"")===Sn);return(await Promise.all(n.map(async i=>{const o=i,a=String(o.folderId??o.parentFolderId??"");if(!a)return null;const l=await p(this,Ot,ls).call(this,se(i),kn(i));return l?{folderId:a,descriptor:l}:null}))).filter(i=>i!==null)},ai=async function(){if(_r)return null;let t;try{t=await this.client.listDocumentDescriptors(this.projectId)}catch(n){const r=n.status;if(r===404||r===400||r===405)return _r=!0,null;throw n}const e=[];for(const n of(t==null?void 0:t.documents)??[]){const r=Or(n.descriptor);!r||!n.folderId||(n.fileId&&n.versionTag&&xe.set(n.fileId,{stamp:n.versionTag,value:Promise.resolve(r)}),e.push({folderId:String(n.folderId),descriptor:r}))}return e},ls=function(t,e){const n=e?xe.get(t):void 0;if(n&&n.stamp===e)return n.value;const r=p(this,Ot,ci).call(this,t);return e&&(xe.set(t,{stamp:e,value:r}),r.catch(()=>{var i;((i=xe.get(t))==null?void 0:i.value)===r&&xe.delete(t)})),r},ci=async function(t){const e=await this.client.downloadFile(t);if(!e.ok)throw new Error(`Reading a document's descriptor answered ${e.status}`);const n=await e.text();if(!n.trim())return null;let r;try{r=JSON.parse(n)}catch{return null}return Or(r)},li=async function(t){let e=t.versions??[],n;if(e.length===0){n=await this.client.listFiles({projectId:this.projectId}).catch(()=>[]);const a=n.find(l=>se(l)===se(t));e=(a==null?void 0:a.versions)??[]}const r=await p(this,Ot,hi).call(this,t,e);if(r)return r;const i=String(t.name??"").replace(/\.[^.]+$/,"").toLowerCase();if(!i)return;n??(n=await this.client.listFiles({projectId:this.projectId}).catch(()=>[]));const o=n.find(a=>String(a.name??"").toLowerCase()===`${i}.frag`&&!a.archived&&se(a)!==se(t));return o?se(o):void 0},hi=async function(t,e){const n=[...e].sort((r,i)=>String(i.createdAt??"").localeCompare(String(r.createdAt??"")));for(const r of n)try{const i=await this.client.getFileVersionMetadata(se(t),r.tag),o=i==null?void 0:i.derivedFileId;if(typeof o=="string"&&o)return o}catch{}},_n=async function(t){const n=(await this.client.listFiles({projectId:this.projectId})).filter(r=>{const i=r;return String(i.folderId??i.parentFolderId??"")===t}).find(r=>String(r.name??"")===Sn);return n?{id:se(n),stamp:kn(n)}:void 0};const hs="draft:",Me="TODRAFT1";var te,Xe,ds;class di{constructor(t,e){K(this,te);this.client=t,this.holder=e}async list(){const t=await this.holder();if(!t)return[];const e=new Map;for(const n of await p(this,te,Xe).call(this,t.id)){const r=e.get(n.userId);(!r||n.savedAt>r.savedAt)&&e.set(n.userId,{userId:n.userId,savedAt:n.savedAt})}return[...e.values()].sort((n,r)=>+r.savedAt-+n.savedAt)}async get(t){const e=await this.holder();if(!e)return null;const r=(await p(this,te,Xe).call(this,e.id)).filter(l=>!(t!=null&&t.userId)||l.userId===t.userId).sort((l,d)=>+d.savedAt-+l.savedAt)[0];if(!r)return null;const i=await this.client.downloadHiddenFile(r.hiddenId),{meta:o,blob:a}=await zo(await i.blob());return{userId:r.userId,savedAt:r.savedAt,meta:o,blob:a}}async put(t,e){const n=await this.holder();if(!n)throw new Error("This folder is not a document (no document.json): drafts need one.");const r=Jo(e.userId),i=(await p(this,te,Xe).call(this,n.id)).filter(l=>l.userId===e.userId),a=(await this.client.createHiddenFile(await Wo(t,e.meta??{}),n.id,r)).hiddenFileId;if(!a)throw new Error("The draft upload answered without a hiddenFileId.");return await p(this,te,ds).call(this,i.map(l=>l.hiddenId)),{userId:e.userId,savedAt:Ar(a)}}async delete(t){const e=await this.holder();if(!e)return;const n=(await p(this,te,Xe).call(this,e.id)).filter(r=>r.userId===t.userId);await p(this,te,ds).call(this,n.map(r=>r.hiddenId))}}te=new WeakSet,Xe=async function(t){return(await this.client.getHiddenFilesByParent(t)).filter(n=>typeof n.tag=="string"&&n.tag.startsWith(hs)).map(n=>{const r=String(n._id);return{hiddenId:r,userId:n.tag.slice(hs.length),savedAt:Ar(r)}})},ds=async function(t){for(const e of t)try{await this.client.deleteHiddenFile(e)}catch{}};function Jo(s){const t=`${hs}${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 Ar(s){const t=parseInt(s.slice(0,8),16);return new Date(Number.isFinite(t)?t*1e3:0)}async function Wo(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(Me),n,e,s])}async function zo(s){const t=new Uint8Array(await s.slice(0,Me.length+4).arrayBuffer());if(new TextDecoder().decode(t.slice(0,Me.length))!==Me)return{meta:{},blob:s};const e=new DataView(t.buffer).getUint32(Me.length,!0),n=Me.length+4,r=await s.slice(n,n+e).text();let i={};try{i=JSON.parse(r)}catch{}return{meta:i,blob:s.slice(n+e)}}function Jn(s,t){const e=(t??"").replace(/^\./,"").toLowerCase();if(e)return e;const n=s.lastIndexOf(".");return n>0?s.slice(n+1).toLowerCase():""}function Or(s){if(!s||typeof s!="object")return null;const t=s;if(t.schema!==nn||typeof t.name!="string")return null;const e=Array.isArray(t.views)?t.views.filter(o=>!!o&&typeof o=="object"&&typeof o.fileId=="string"&&typeof o.format=="string"):[],n=t.native,r=!!n&&typeof n=="object"&&typeof n.fileId=="string"&&typeof n.format=="string",i=typeof t.type=="string"&&t.type in Ms?t.type:void 0;return{schema:nn,name:t.name,...i?{type:i}:{},...r?{native:{fileId:n.fileId,format:n.format}}:{},views:e}}const Yo="flow:",Ko="flow:op",Xo="flow:source",Qo="flow:host",Fs="revitflow/op@2",Cr="REVITFLOWCHANGE",$r="REVITFLOWOPERATION";class Ln{constructor(t){kt(this,"changes",[]);this.target=t}get length(){return this.changes.length}get batchId(){return this.target.batchId}get title(){return this.target.title??`${this.changes.length} change(s)`}get author(){return this.target.author??"app"}get userId(){return this.target.userId}get baseCommit(){return this.target.baseCommit}add(t,e={}){return this.changes.push({op:"add",attrs:this.pack(t,e)}),this}set(t,e,n={}){return this.requireId(t,"set"),this.changes.push({op:"set",item:t,attrs:this.pack(e,n)}),this}remove(t){return this.requireId(t,"remove"),this.changes.push({op:"remove",item:t,attrs:{}}),this}get summary(){const t=new Set(this.changes.map(e=>e.op));return t.size===1?[...t][0]:"mixed"}async build(t){if(this.changes.length===0)throw new Error("An operation with no changes is not an operation. Add at least one.");const e={schema:Fs,opId:t,batchId:this.batchId??t,targetProject:this.target.project,targetDocument:this.target.document,baseCommit:this.baseCommit,author:this.author,...this.userId?{userId:this.userId}:{},title:this.title,summary:this.summary},[n,r]=await Zo();return ta(this.flatbuffer(n,r,t,JSON.stringify(e)))}pack(t,e){const n={};for(const[r,i]of Object.entries(t??{}))r.startsWith(Yo)||(n[r]=String(i));return e.position&&(n.Position=e.position.map(xr).join(",")),e.rotationDeg!==void 0&&(n.Rotation=xr(e.rotationDeg)),e.source&&(n[Xo]=e.source),e.host&&(n[Qo]=e.host),n}requireId(t,e){if(!t||!t.trim())throw new Error(`A '${e}' has to name the item it acts on.`)}flatbuffer(t,e,n,r){const{Attribute:i,Meshes:o,Model:a,SpatialStructure:l,Transform:d}=e,c=new t.Builder(1024),m=this.changes.length,w=new Uint32Array(m);let v=1;for(let et=0;et<m;et++)w[et]=v++;const I=v++,_=et=>(et(c,0),c.endVector()),L=o.createShellsVector(c,[]),C=o.createCircleExtrusionsVector(c,[]),O=_(o.startSamplesVector),u=_(o.startRepresentationsVector),$=_(o.startMaterialsVector),E=_(o.startLocalTransformsVector),F=_(o.startGlobalTransformsVector),z=o.createMeshesItemsVector(c,[]),ut=o.createMaterialIdsVector(c,[]),wt=o.createRepresentationIdsVector(c,[]),Ct=o.createSampleIdsVector(c,[]),Vt=o.createLocalTransformIdsVector(c,[]),Mt=o.createGlobalTransformIdsVector(c,[]);o.startMeshes(c),o.addCoordinates(c,d.createTransform(c,0,0,0,1,0,0,0,1,0)),o.addGlobalTransforms(c,F),o.addShells(c,L),o.addRepresentations(c,u),o.addSamples(c,O),o.addLocalTransforms(c,E),o.addMaterials(c,$),o.addCircleExtrusions(c,C),o.addMeshesItems(c,z),o.addRepresentationIds(c,wt),o.addSampleIds(c,Ct),o.addMaterialIds(c,ut),o.addLocalTransformIds(c,Vt),o.addGlobalTransformIds(c,Mt);const he=o.endMeshes(c),Yt=c.createString(r),It=new Set,Gt=[];for(const et of this.changes){const At=[],Ht={[Ko]:et.op,...et.attrs};for(const[de,qe]of Object.entries(Ht)){const $e=JSON.stringify([de,qe,"IFCTEXT"]);It.add($e),At.push(c.createString($e))}Gt.push(i.createAttribute(c,i.createDataVector(c,At)))}{const et=JSON.stringify(["Name",n,"IFCLABEL"]);It.add(et);const At=i.createDataVector(c,[c.createString(et)]);Gt.push(i.createAttribute(c,At))}const Nt=a.createAttributesVector(c,Gt),Ce=a.createUniqueAttributesVector(c,[...It].map(et=>c.createString(et))),q=this.changes.map(()=>c.createString(Cr));q.push(c.createString($r));const Z=a.createCategoriesVector(c,q),x=[],Tt=[];this.changes.forEach((et,At)=>{et.item&&(x.push(c.createString(et.item)),Tt.push(w[At]))});const Et=a.createGuidsVector(c,x),pt=a.createGuidsItemsVector(c,Tt),jt=a.createLocalIdsVector(c,[...w,I]),Ft=this.changes.map((et,At)=>l.createSpatialStructure(c,w[At],c.createString(Cr),0)),Pt=l.createSpatialStructure(c,I,c.createString($r),l.createChildrenVector(c,Ft)),st=c.createString(n);a.startModel(c),a.addMeshes(c,he),a.addMetadata(c,Yt),a.addAttributes(c,Nt),a.addUniqueAttributes(c,Ce),a.addLocalIds(c,jt),a.addCategories(c,Z),a.addGuidsItems(c,pt),a.addGuids(c,Et),a.addGuid(c,st),a.addSpatialStructure(c,Pt),a.addMaxLocalId(c,v);const rt=a.endModel(c);return a.finishModelBuffer(c,rt),c.asUint8Array()}}async function Zo(){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 xr(s){return Number.isFinite(s)?String(s):"0"}async function ta(s){const t=new Blob([s]).stream().pipeThrough(new CompressionStream("deflate"));return new Uint8Array(await new Response(t).arrayBuffer())}async function Pn(s){const[t,e]=await ea(),n=e.Model.getRootAsModel(new t.ByteBuffer(await na(s)));let r={};try{r=JSON.parse(n.metadata()??"{}")}catch{}const i=new Map;for(let a=0;a<n.guidsLength();a++){const l=n.guidsItems(a),d=n.guids(a);l!==null&&d&&i.set(l,d)}const o=[];for(let a=0;a<n.attributesLength();a++){const l=n.localIds(a);if(l===null)continue;const d={},c=n.attributes(a);for(let m=0;m<((c==null?void 0:c.dataLength())??0);m++){const w=c.data(m);if(w)try{const[v,I]=JSON.parse(w);d[v]=I}catch{}}o.push({localId:l,guid:i.get(l)??null,category:n.categories(a)??null,attrs:d})}return{metadata:r,items:o}}async function ea(){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 na(s){const t=new Blob([s]).stream().pipeThrough(new DecompressionStream("deflate"));return new Uint8Array(await new Response(t).arrayBuffer())}const fi="Element",ui="Carried",Fe=1/.3048;function pi(s){const t=[];for(const e of s)for(const n of[fi,ui]){const r=e.attrs[n];if(r)try{const i=JSON.parse(r);for(const o of Array.isArray(i)?i:[i]){const a=o;typeof(a==null?void 0:a.id)!="string"||typeof(a==null?void 0:a.kind)!="string"||t.push({id:a.id,kind:a.kind,params:a.params??{},item:e})}}catch{}}return t}function Bt(s,t){const e=s.params[t];if(typeof e!="string")return null;try{return JSON.parse(e)}catch{return null}}function sa(s){const t=new Map;for(const[e,n]of Ls(s))t.set(e,n.name);return t}function Ls(s){const t=new Map;for(const e of s){if(e.kind!=="datum"||e.params.of!=="level")continue;const n=e.params.named,r=e.params.at;typeof n=="string"&&typeof r=="number"&&t.set(e.id,{name:n,at:r})}return t}function mi(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 Ps(s,t){const e=new Map;for(const[n,r]of s.made)e.set(n,r.id),r.print&&(t==null||t.set(n,r.print));return e}function gi(s){const t=r=>Array.isArray(r)?r.map(t):r&&typeof r=="object"?Object.fromEntries(Object.keys(r).sort().map(i=>[i,t(r[i])])):r,e=JSON.stringify(t(s));let n=2166136261;for(let r=0;r<e.length;r++)n^=e.charCodeAt(r),n=Math.imul(n,16777619);return(n>>>0).toString(36)}async function Bs(s,t){var o,a;if(!(t!=null&&t.fileId))throw new Error("Choose the model file to read.");s.progress(`Downloading ${t.name}`);let e=new Uint8Array(await(await s.client.downloadFile(t.fileId,t.version?{versionTag:t.version}:void 0)).arrayBuffer());const n=((a=(o=/\.([^.]+)$/.exec(t.name))==null?void 0:o[1])==null?void 0:a.toLowerCase())??"frag";let r=null,i=null;if(n!=="frag"){const l=s.client.recipes.importerFor(n);if(!l)throw new Error(`This app cannot read .${n} files: it provides no importer for them.`);n==="ifc"&&(r=yi(e));const d=s.client.recipes.shapesFor(n);d&&(s.progress(`Reading the shapes of ${t.name}`),i=await d(e,t.name)),s.progress(`Reading ${t.name}`),e=await l(e,t.name)}return{picked:t,contents:await Pn(e),site:r,shapes:i}}function yi(s){var F;const t=new TextDecoder("latin1").decode(s),e=z=>new RegExp(`^${z}=\\s*([A-Z0-9_]+)\\((.*)\\);\\s*$`,"m").exec(t),n=z=>[...z.matchAll(/#\d+|\$/g)].map(ut=>ut[0]),r=z=>[...z.matchAll(/-?\d+(?:\.\d*)?(?:E[-+]?\d+)?/gi)].map(ut=>Number(ut[0])),i=/^(#\d+)=\s*IFCSITE\((.*)\);\s*$/m.exec(t);if(!i)return null;const o=(F=i[2].split(",")[5])==null?void 0:F.trim();if(!(o!=null&&o.startsWith("#")))return null;const a=e(o);if((a==null?void 0:a[1])!=="IFCLOCALPLACEMENT")return null;const[l,d]=n(a[2]);if(l!=="$"||!d)return null;const c=e(d);if((c==null?void 0:c[1])!=="IFCAXIS2PLACEMENT3D")return null;const[m,,w]=n(c[2]),v=m&&m!=="$"?e(m):null;if(!v)return null;const[I=0,_=0,L=0]=r(v[2]);let C=0;const O=w&&w!=="$"?e(w):null;if(O){const[z=1,ut=0]=r(O[2]);C=Math.atan2(ut,z)*180/Math.PI}const u=/IFCSIUNIT\([^)]*\.LENGTHUNIT\.\s*,\s*(\.([A-Z]+)\.|\$)\s*,\s*\.METRE\./i.exec(t),$={MILLI:.001,CENTI:.01,DECI:.1,KILO:1e3},E=u?u[2]?$[u[2].toUpperCase()]??1:1:/IFCCONVERSIONBASEDUNIT\([^)]*\.LENGTHUNIT\.[^)]*'FOOT'/i.test(t)?.3048:1;return{east:I*E,north:_*E,elevation:L*E,angleDeg:C}}const js="thatopen/recipe@1",Rr="__project_data",kr="recipes",ra=s=>`${s}.recipe.json`,wi={OperationBuilder:Ln,OP_SCHEMA:Fs,readFrag:Pn,readPickedFrag:Bs,recordsOf:pi,innerJson:Bt,levelsOf:Ls,levelNames:sa,stylesOf:mi,printOf:gi,siteLocationOf:yi,whatItMadeBefore:Ps,ELEMENT_FIELD:fi,CARRIED_FIELD:ui,FEET_PER_METRE:Fe},vi=/^[a-z0-9][a-z0-9-]{1,62}$/;async function bi(s,t,e){const n=d=>[...d].sort((c,m)=>String(c._id).localeCompare(String(m._id)))[0],r=await s.listFolders({projectId:t,archived:!1});let i=n(r.filter(d=>d.name===Rr&&!d.parentId));if(!i){if(!e)return null;i=await s.createFolder(Rr,void 0,t)}const o=String(i._id),a=await s.listFolders({parentFolderId:o,projectId:t,archived:!1});let l=n(a.filter(d=>d.name===kr&&String(d.parentId)===o));if(!l){if(!e)return null;l=await s.createFolder(kr,o,t)}return String(l._id)}const ia=s=>String(s._id??s.id??""),oa=s=>String(s.tag??s.versionTag??""),fs=s=>{var t;return Number(((t=/(\d+)/.exec(s))==null?void 0:t[1])??-1)};async function We(s,t){const e=await bi(s,t,!1);if(!e)return new Map;const n=await s.listFiles({folderId:e}),r=new Map;for(const i of n){const o=String(i.name??"");o.endsWith(".recipe.json")&&r.set(o.slice(0,-12),{id:ia(i)})}return r}async function wn(s,t,e){var i;const n=await s.downloadFile(t,e?{versionTag:e}:void 0),r=JSON.parse(await n.text());if((r==null?void 0:r.schema)!==js||!((i=r.manifest)!=null&&i.name)||typeof r.code!="string")throw new Error(`This is not a recipe this library can read (${String(r==null?void 0:r.schema)}).`);return r}async function ze(s,t){return(await s.listVersions(t)).map(n=>({tag:oa(n),createdAt:String(n.createdAt??"")})).filter(n=>n.tag).sort((n,r)=>fs(n.tag)-fs(r.tag))}var cn;class Ti{constructor(t,e){K(this,cn,new Map);this.client=t,this.builtinNames=e}async list(t){const e=await We(this.client,t);return(await Promise.all([...e.entries()].map(async([,{id:r}])=>{var i;try{const o=await ze(this.client,r),a=(i=o[o.length-1])==null?void 0:i.tag,l=await wn(this.client,r,a);return{manifest:l.manifest,origin:"project",version:a,author:l.author,savedAt:l.savedAt}}catch{return null}}))).filter(r=>r!==null)}async versions(t,e){const n=(await We(this.client,t)).get(e);if(!n)throw new Error(`The project has no recipe named "${e}".`);const r=await ze(this.client,n.id);return await Promise.all(r.map(async({tag:i,createdAt:o})=>{try{const a=await wn(this.client,n.id,i);return{version:i,author:a.author,note:a.note,savedAt:a.savedAt??o}}catch{return{version:i,savedAt:o}}}))}async source(t,e,n){var o;const r=(await We(this.client,t)).get(e);if(!r)throw new Error(`The project has no recipe named "${e}".`);const i=n??((o=(await ze(this.client,r.id)).pop())==null?void 0:o.tag);if(!i)throw new Error(`The recipe "${e}" has no saved version.`);return{...await wn(this.client,r.id,i),version:i}}async save(t,e,n){const{manifest:r,code:i}=e;if(!vi.test((r==null?void 0:r.name)??""))throw new Error('A recipe name is lower case letters, digits and dashes, 2 to 63 of them: "walls-from-ifc".');if(this.builtinNames().has(r.name))throw new Error(`"${r.name}" is a built-in recipe. Give yours a name of its own.`);if(!r.to||!r.description||!Array.isArray(r.inputs))throw new Error("A recipe says what it writes (`to`), what it does (`description`) and what it reads (`inputs`).");await us(r,i);const o={schema:js,manifest:r,code:i,author:n.author,...n.note?{note:n.note}:{},savedAt:new Date().toISOString()},a=new Blob([JSON.stringify(o,null,2)],{type:"application/json"}),l=(await We(this.client,t)).get(r.name);if(l){const c=await ze(this.client,l.id),m=`v${Math.max(0,...c.map(w=>fs(w.tag)))+1}`;return await this.client.createVersion(l.id,a,m),m}const d=await bi(this.client,t,!0);return await this.client.createFile({file:a,name:ra(r.name),versionTag:"v1",projectId:t,parentFolderId:d}),"v1"}async load(t,e,n){var l;const r=(await We(this.client,t)).get(e);if(!r)throw new Error(`The project has no recipe named "${e}".`);const i=n??((l=(await ze(this.client,r.id)).pop())==null?void 0:l.tag);if(!i)throw new Error(`The recipe "${e}" has no saved version.`);const o=`${r.id}@${i}`;let a=g(this,cn).get(o);if(!a){const d=await wn(this.client,r.id,i);a=await us(d.manifest,d.code),g(this,cn).set(o,a)}return{recipe:a,version:i}}}cn=new WeakMap;async function us(s,t){var r;let e;try{e=await import(`data:text/javascript;base64,${aa(t)}`)}catch(i){throw new Error(`The recipe's code does not load: ${i instanceof Error?i.message:String(i)}`)}const n=e.run??((r=e.default)==null?void 0:r.run);if(typeof n!="function")throw new Error("The recipe's code exports no `run(context)` function.");return{...s,run:i=>n({...i,kit:wi})}}function aa(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 ca(s){const t=s instanceof Uint8Array?s:new Uint8Array(await s.arrayBuffer()),{items:e,metadata:n}=await Pn(t),r=e.filter(i=>i.attrs["flow:op"]).map(i=>{const o={};for(const[a,l]of Object.entries(i.attrs))a.startsWith("flow:")||(o[a]=l);return{op:i.attrs["flow:op"],...i.guid?{target:i.guid}:{},...i.attrs["flow:source"]?{source:i.attrs["flow:source"]}:{},attrs:o}});return{envelope:n??{},changes:r}}class Ds extends Error{constructor(t){super(t),this.name="UpToDate"}}var ae,ln,hn;class Ei{constructor(t){K(this,ae,new Map);K(this,ln,new Map);K(this,hn,new Map);kt(this,"project");this.client=t,this.project=new Ti(t,()=>new Set(g(this,ae).keys()))}provideImporter(t,e){g(this,ln).set(t.toLowerCase(),e)}provideShapes(t,e){g(this,hn).set(t.toLowerCase(),e)}shapesFor(t){return g(this,hn).get(t.toLowerCase())}importerFor(t){return g(this,ln).get(t.toLowerCase())}register(t){if(g(this,ae).has(t.name))throw new Error(`A recipe named "${t.name}" is already registered.`);g(this,ae).set(t.name,t)}list(t){return[...g(this,ae).values()].filter(n=>(!(t!=null&&t.to)||n.to===t.to)&&(!(t!=null&&t.input)||n.inputs.includes(t.input)))}get(t){return g(this,ae).get(t)}async catalog(t,e){const n=this.list(e).map(i=>({manifest:i,origin:"builtin"}));let r=[];try{r=(await this.project.list(t)).filter(i=>!(e!=null&&e.to)||i.manifest.to===e.to)}catch{}return[...n,...r.sort((i,o)=>i.manifest.name.localeCompare(o.manifest.name))]}async resolve(t,e,n){const r=g(this,ae).get(t);return r?{recipe:r,origin:"builtin"}:{...await this.project.load(e,t,n),origin:"project"}}async choices(t,e){const{recipe:n}=await this.resolve(t,e),r=n.source;if((r==null?void 0:r.kind)!=="project-file")return[];const i=(r.extensions??[]).map(d=>d.toLowerCase()),a=(await this.client.documents(e).list()).filter(d=>d.descriptor.native&&(i.length===0||i.includes(d.descriptor.native.format.toLowerCase()))),l=await Ii(this.client,a.map(d=>d.descriptor.native.fileId));return a.map(d=>{const c=d.descriptor.native;return{label:d.descriptor.name,fileId:c.fileId,name:`${d.descriptor.name}.${c.format}`,folderId:d.folderId,version:l.get(c.fileId)??"v1"}}).sort((d,c)=>d.label.localeCompare(c.label))}async run(t,e){const{recipe:n}=await this.resolve(t,e.projectId,e.recipeVersion);if(n.to!==e.target.source)throw new Error(`Recipe "${t}" writes ${n.to}, but the target document belongs to ${e.target.source}.`);return await n.run({client:this.client,projectId:e.projectId,target:e.target,made:e.made??new Map,opId:e.opId??ks(),input:e.input,settings:e.settings??{},progress:e.progress??(()=>{})})}}ae=new WeakMap,ln=new WeakMap,hn=new WeakMap;async function Ii(s,t){const e=new Map;if(t.length===0)return e;const n=i=>{var o;return Number(((o=/(\d+)/.exec(String(i??"")))==null?void 0:o[1])??-1)},r=i=>{const a=i.slice().sort((l,d)=>{const c=l!=null&&l.createdAt?new Date(String(l.createdAt)).getTime():NaN,m=d!=null&&d.createdAt?new Date(String(d.createdAt)).getTime():NaN;return!Number.isNaN(c)&&!Number.isNaN(m)&&c!==m?m-c:n((d==null?void 0:d.tag)??(d==null?void 0:d.versionTag))-n((l==null?void 0:l.tag)??(l==null?void 0:l.versionTag))})[0];return a?String(a.tag??a.versionTag??"v1"):"v1"};return await Promise.all(t.map(async i=>{try{e.set(i,r(await s.listVersions(i)))}catch{e.set(i,"v1")}})),e}const ps=100;function la(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 ha(s){if(!s||typeof s!="object")return;const t=s.retryAfter;return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}class Bn extends Error{constructor(e,n,r,i){const o=la(r);super(o.message??`${n||"Request failed"} (${e})`);kt(this,"status");kt(this,"code");kt(this,"details");kt(this,"body");kt(this,"retryAfter");this.name="RequestError",this.status=e,this.code=o.code,this.details=o.details,this.body=r,this.retryAfter=i??ha(o.details)}}const Kt="item/folder",H="item",pe="processor",da="npm-registry",re="hidden",Wn="FILE",zn="TOOL",Yn="APP",fa=500,Mr=3e4,ua=2e3,pa=15e3,ma=s=>/^\/?project\/permissions\/check/.test(s),ga=s=>/^\/?(item\/folder\/?$|item\/?$|item\/folder\/[^/]+\/items\/?$|project\/[^/]+\/data\/?$)/.test(s),Ye=new Map,ya=.25,wa=s=>new Promise(t=>setTimeout(t,s));function va(s){var r,i;const t=(i=(r=s.headers)==null?void 0:r.get)==null?void 0:i.call(r,"Retry-After");if(!t)return;const e=Number(t);if(Number.isFinite(e))return Math.max(0,e);const n=Date.parse(t);if(!Number.isNaN(n))return Math.max(0,(n-Date.now())/1e3)}function ba(s){return s instanceof Bn?s.status===429||s.status>=500:!0}function Ta(s,t){const e=Math.min(fa*2**t,Mr),n=e*ya*Math.random(),r=s instanceof Bn&&s.retryAfter!=null?s.retryAfter*1e3:void 0;return r!=null?Math.min(r,Mr)+n:e+n}var T,An,N,ms,ve,dn,Qe,On,Cn,gs,ys,ws;const Vs=class Vs{constructor(t,e,n){K(this,T);kt(this,"apiUrl");kt(this,"accessToken");kt(this,"wsUrl");kt(this,"retries");kt(this,"useBearer");kt(this,"builtInGlobals",null);kt(this,"localServerUrl",null);kt(this,"context");K(this,dn);const{retries:r=0,useBearer:i=!1,localServerUrl:o}=n||{};let a=e;if(a.charAt(a.length-1)==="/"&&(a=a.slice(0,-1)),this.apiUrl=`${a}/api`,this.accessToken=t,this.wsUrl=a,this.retries=r,this.useBearer=i,this.context={appId:"",projectId:"",accessToken:t,apiUrl:e},o){let l=o;l.charAt(l.length-1)==="/"&&(l=l.slice(0,-1)),this.localServerUrl=l}}static fromPlatformContext(t){const e=(typeof window<"u"?window.__THATOPEN_CONTEXT__:null)||{appId:"",projectId:"",accessToken:"",apiUrl:""},n=new Vs(e.accessToken,e.apiUrl,{...t,useBearer:!0});return n.context=e,n}setRetries(t){this.retries=t}setBuiltInGlobals(t){this.builtInGlobals=t}get socketOrigin(){return this.wsUrl.split("?")[0]}async resolveAccessToken(){return this.accessToken}async request(t,e,n){return p(this,T,N).call(this,t,e,n)}async listFiles(t){const{folderId:e,archived:n,projectId:r}=t||{};return e?await p(this,T,N).call(this,"GET",`${Kt}/${e}/items`,{query:{itemType:Wn,archived:n}}):await p(this,T,N).call(this,"GET",`${H}`,{query:{itemType:Wn,archived:n,...r&&{projectId:r}}})}async listDocumentDescriptors(t){return await p(this,T,N).call(this,"GET",`${H}/documents`,{query:{projectId:t}})}async getFile(t,e){return await p(this,T,ys).call(this,t,e)}async createFile(t){return await p(this,T,Cn).call(this,t,Wn)}async updateFile(t,e){return await p(this,T,gs).call(this,t,e)}async archiveFile(t){return await p(this,T,N).call(this,"DELETE",`${H}/${t}`)}async recoverFile(t){return await p(this,T,N).call(this,"PUT",`${H}/${t}/recover`)}async downloadFile(t,e){return await p(this,T,On).call(this,t,e)}async getFileVersionMetadata(t,e,n){const{withDraft:r}=n||{};return await p(this,T,N).call(this,"GET",`${H}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/metadata`,{query:{...r&&{withDraft:"true"}}})}async updateFileVersionMetadata(t,e,n){return await p(this,T,N).call(this,"PUT",`${H}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/metadata`,{body:JSON.stringify({metadata:n}),contentType:"application/json"})}async deleteFileVersionMetadata(t,e){return await p(this,T,N).call(this,"DELETE",`${H}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/metadata`)}async getFileVersionMetadataBatch(t,e){const{withDraft:n}=e||{};return await p(this,T,Qe).call(this,t,async r=>(await p(this,T,N).call(this,"POST",`${H}/batch/version-metadata`,{body:JSON.stringify({entries:r,...n!==void 0&&{withDraft:n}}),contentType:"application/json"})).results)}async listFolders(t){const{archived:e,parentFolderId:n,projectId:r}=t||{};return await p(this,T,N).call(this,"GET",Kt,{query:{parentFolderId:n,archived:e,...r&&{projectId:r}}})}async getFolder(t){return await p(this,T,N).call(this,"GET",`${Kt}/${t}`)}async getFoldersBatch(t){return await p(this,T,Qe).call(this,t,async e=>(await p(this,T,N).call(this,"POST",`${H}/batch/folders`,{body:JSON.stringify({folderIds:e}),contentType:"application/json"})).results)}async createFolder(t,e,n){return await p(this,T,N).call(this,"POST",Kt,{body:JSON.stringify({name:t,...e&&{parentId:e},...n&&{projectId:n}}),contentType:"application/json"})}async updateFolder(t,e){const{name:n}=e;return await p(this,T,N).call(this,"PUT",`${Kt}/${t}`,{body:JSON.stringify({name:n}),contentType:"application/json"})}async archiveFolder(t){return await p(this,T,N).call(this,"DELETE",`${Kt}/${t}`)}async recoverFolder(t){return await p(this,T,N).call(this,"PUT",`${Kt}/${t}/recover`)}async downloadFolder(t){return await p(this,T,ve).call(this,`${Kt}/${t}/download`)}async listComponents(t){const{folderId:e,ShowVersions:n,projectId:r}=t||{};return e?await p(this,T,N).call(this,"GET",`${Kt}/${e}/items`,{query:{itemType:zn,...n&&{ShowVersions:n}}}):await p(this,T,N).call(this,"GET",`${H}`,{query:{itemType:zn,...n&&{ShowVersions:n},...r&&{projectId:r}}})}async getComponent(t,e){return await p(this,T,ys).call(this,t,e)}async createComponent(t){const{componentProps:e}=t;return await p(this,T,Cn).call(this,t,zn,e)}async updateComponent(t,e){const{componentProps:n}=e;return await p(this,T,gs).call(this,t,e,n)}async downloadComponent(t,e){return await p(this,T,On).call(this,t,e)}async downloadComponentBundle(t,e){const{versionTag:n,withDraft:r}=e||{};return await p(this,T,ve).call(this,`${H}/${t}/download/bundle`,{query:{...n&&{versionTag:n},...r&&{withDraft:r}}})}async archiveComponent(t){return await p(this,T,N).call(this,"DELETE",`${H}/${t}`)}async recoverComponent(t){return await p(this,T,N).call(this,"PUT",`${H}/${t}/recover`)}async getBuiltInComponent(t){return await(await p(this,T,ve).call(this,`built-in/${t}/bundle`)).text()}async initBuiltInComponent(t,e,n){const r=await this.getBuiltInComponent(t.uuid),i=n??this.builtInGlobals??(typeof window<"u"?window.ThatOpenCompany:{})??{},o=Object.keys(i),a=o.map(m=>i[m]),d=new Function(...o,`${r}
2
+ return main;`)(...a),c=(d==null?void 0:d.componentDefinition)??d;e.get(c)}async initBuiltInComponents(t,...e){await Promise.all(e.map(n=>this.initBuiltInComponent(n,t)))}async setup(t,...e){var o,a;const n=t.OBC,r=t.BUI;if(!(n!=null&&n.Components))throw new Error("globals.OBC must include Components");if(!(r!=null&&r.Manager))throw new Error("globals.BUI must include Manager");const i=new n.Components;return r.Manager.init(),this.setBuiltInGlobals(t),await this.initBuiltInComponents(i,...e),i.init(),(a=(o=this.context.appEventOrchestrator)==null?void 0:o.appLoaded)==null||a.call(o),{components:i}}throwError(t,e){var n,r;(r=(n=this.context.appEventOrchestrator)==null?void 0:n.appError)==null||r.call(n,t,e)}async listApps(t){const{folderId:e,ShowVersions:n,projectId:r}=t||{};return e?await p(this,T,N).call(this,"GET",`${Kt}/${e}/items`,{query:{itemType:Yn,...n&&{ShowVersions:n}}}):await p(this,T,N).call(this,"GET",`${H}`,{query:{itemType:Yn,...n&&{ShowVersions:n},...r&&{projectId:r}}})}async createApp(t){const{appProps:e}=t;return await p(this,T,Cn).call(this,t,Yn,e)}async downloadApp(t,e){return await p(this,T,On).call(this,t,e)}async downloadAppBundle(t,e){const{versionTag:n,withDraft:r}=e||{};return await p(this,T,ve).call(this,`${H}/${t}/download/bundle`,{query:{...n&&{versionTag:n},...r&&{withDraft:r}}})}async archiveApp(t){return await p(this,T,N).call(this,"DELETE",`${H}/${t}`)}async getNpmCredentials(){return await p(this,T,N).call(this,"GET",`${da}/credentials`)}async executeComponent(t,e,n){if(this.localServerUrl){const r=`${this.localServerUrl}/api/${pe}/${t}/execute`,i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!i.ok){const o=await i.text().catch(()=>"");throw new Error(`Local server request failed: ${i.status} - ${o}`)}return await i.json()}return await p(this,T,N).call(this,"POST",`${pe}/${t}/execute`,{body:JSON.stringify(e),query:{...n&&{versionTag:n}},contentType:"application/json"})}async abortExecution(t){if(this.localServerUrl){const e=`${this.localServerUrl}/api/${pe}/progress/${t}/abort`,n=await fetch(e,{method:"POST"});if(!n.ok){const r=await n.text().catch(()=>"");throw new Error(`Local server request failed: ${n.status} - ${r}`)}return await n.json()}return await p(this,T,N).call(this,"POST",`${pe}/progress/${t}/abort`)}async listExecutions(t,e){if(this.localServerUrl){const n=e?`?projectId=${encodeURIComponent(e)}`:"",r=`${this.localServerUrl}/api/${pe}/${t}/progress${n}`,i=await fetch(r);if(!i.ok){const o=await i.text().catch(()=>"");throw new Error(`Local server request failed: ${i.status} - ${o}`)}return await i.json()}return await p(this,T,N).call(this,"GET",`${pe}/${t}/progress`,{query:{...e&&{projectId:e}}})}async getExecution(t){if(this.localServerUrl){const e=`${this.localServerUrl}/api/${pe}/progress/${t}`,n=await fetch(e);if(!n.ok){const r=await n.text().catch(()=>"");throw new Error(`Local server request failed: ${n.status} - ${r}`)}return await n.json()}return await p(this,T,N).call(this,"GET",`${pe}/progress/${t}`)}async onExecutionProgress(t,e){const n=this.localServerUrl??this.wsUrl,r=await tn(n,{auth:{accessToken:this.accessToken},transports:["websocket"]});r.on("connect",function(){r.emit("executionSubscription",JSON.stringify({executionId:t})),r.on("execution",i=>{e(i)})}),r.on("connect_error",function(i){console.log(i)})}documents(t){return new Ns(this,t)}history(t){return new xs(this,t)}get recipes(){return g(this,dn)??it(this,dn,new Ei(this)),g(this,dn)}async createHiddenFile(t,e,n){const r=new FormData;return r.append("file",t),r.append("parentItemId",e),n!=null&&r.append("tag",n),await p(this,T,N).call(this,"POST",`${H}/${re}`,{body:r})}async createHiddenFilesBatch(t,e,n){const r=new FormData;for(const i of t)r.append("files",i);return r.append("parentItemId",e),n!=null&&r.append("tag",n),await p(this,T,N).call(this,"POST",`${H}/${re}/batch`,{body:r})}async deleteHiddenFile(t){return await p(this,T,N).call(this,"DELETE",`${H}/${re}/${t}`)}async getHiddenFile(t){return await p(this,T,N).call(this,"GET",`${H}/${re}/${t}`)}async downloadHiddenFile(t){return await p(this,T,ve).call(this,`${H}/${re}/${t}/download`)}async getHiddenFileSignedUrl(t,e){return await p(this,T,N).call(this,"GET",`${H}/${re}/${t}/signed-url`,{...e!=null&&{query:{expiresIn:e}}})}async getHiddenFileSignedUrlsBatch(t,e){return await p(this,T,Qe).call(this,t,async n=>(await p(this,T,N).call(this,"POST",`${H}/${re}/signed-url/batch`,{body:JSON.stringify({hiddenFileIds:n,...e!=null&&{expiresIn:e}}),contentType:"application/json"})).results)}async getHiddenFilesByParent(t,e){return await p(this,T,N).call(this,"GET",`${H}/${t}/${re}`,{...e!=null&&{query:{tag:e}}})}async deleteHiddenFilesByParent(t){return await p(this,T,N).call(this,"DELETE",`${H}/${t}/${re}`)}async uploadItemIcon(t,e){const n=new FormData;return n.append("icon",e),await p(this,T,N).call(this,"PUT",`${H}/${t}/icon`,{body:n})}async getItemIcon(t){return await p(this,T,ve).call(this,`${H}/${t}/icon`)}async removeItemIcon(t){return await p(this,T,N).call(this,"DELETE",`${H}/${t}/icon`)}async updateItem(t,e){return await p(this,T,N).call(this,"PUT",`${H}/${t}`,{body:JSON.stringify(e),contentType:"application/json"})}async createVersion(t,e,n,r,i){const o=new FormData;return o.append("file",e),o.append("versionTag",n),r&&o.append("extraProps",JSON.stringify(r)),i&&o.append("metadata",JSON.stringify(i)),await p(this,T,N).call(this,"POST",`${H}/${t}/version`,{body:o})}async nextVersionTag(t){if(!t)return"v1";let e=[];try{e=await this.listVersions(t)}catch{return`v-${Date.now()}`}let n=0;for(const r of e){const i=/^v(\d{1,6})$/.exec(String(r.tag??r.versionTag??""));i&&(n=Math.max(n,Number(i[1])))}return`v${Math.max(n,e.length)+1}`}async listVersions(t,e={}){return await p(this,T,N).call(this,"GET",`${H}/${encodeURIComponent(t)}/versions`,{query:e})}async listVersionsBatch(t,e={}){const{archived:n}=e;return await p(this,T,Qe).call(this,t,async r=>(await p(this,T,N).call(this,"POST",`${H}/batch/versions`,{body:JSON.stringify({itemIds:r,...n!==void 0&&{archived:n}}),contentType:"application/json"})).results)}async archiveVersion(t,e){return await p(this,T,N).call(this,"PUT",`${H}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/archive`)}async recoverVersion(t,e){return await p(this,T,N).call(this,"PUT",`${H}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/recover`)}async deleteVersion(t,e){return await p(this,T,N).call(this,"DELETE",`${H}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}`)}};T=new WeakSet,An=function(t){return`${this.apiUrl}/${t}`},N=async function(t,e,n){if(t==="GET"&&(n==null?void 0:n.responseType)!=="blob"&&!(n!=null&&n.retryAttempt)){const r=`${p(this,T,An).call(this,e)}?${new URLSearchParams(p(this,T,ws).call(this,n==null?void 0:n.query)).toString()}`,i=Date.now(),o=Ye.get(r);if(o&&(o.pending||i-o.at<(ga(e)?pa:ua)))return o.answer.then(l=>l===void 0?l:structuredClone(l));const a={at:i,pending:!0,answer:p(this,T,ms).call(this,t,e,n)};return Ye.set(r,a),a.answer.then(()=>{a.pending=!1,a.at=Date.now()},()=>{Ye.get(r)===a&&Ye.delete(r)}),a.answer.then(l=>l===void 0?l:structuredClone(l))}return t!=="GET"&&!ma(e)&&Ye.clear(),p(this,T,ms).call(this,t,e,n)},ms=async function(t,e,n){const{body:r,query:i,contentType:o,retries:a,responseType:l,retryAttempt:d}=n||{},c=p(this,T,An).call(this,e),m=p(this,T,ws).call(this,i),w=await this.resolveAccessToken(),v={...m,...this.useBearer?{}:{accessToken:w}};try{const I=await fetch(c+"?"+new URLSearchParams(v).toString(),{method:t,headers:{Accept:"application/json",...o&&{"Content-Type":o},...this.useBearer&&{Authorization:`Bearer ${w}`}},...r&&{body:r}});if(!I.ok){const _=await I.text().then(L=>L).catch(()=>"");throw new Bn(I.status,I.statusText,_,va(I))}return l==="blob"?await I.blob():I.json().then(_=>_).catch(()=>{})}catch(I){const _=a??this.retries;if(_>0&&ba(I)){const L=d??0;return await wa(Ta(I,L)),await p(this,T,N).call(this,t,e,{...n,retries:_-1,retryAttempt:L+1})}throw I}},ve=async function(t,e){const{query:n}=e||{},r=p(this,T,An).call(this,t),i=await this.resolveAccessToken(),o={...n,...this.useBearer?{}:{accessToken:i}};return await fetch(r+"?"+new URLSearchParams(o).toString(),{method:"GET",...this.useBearer&&{headers:{Authorization:`Bearer ${i}`}}})},dn=new WeakMap,Qe=async function(t,e){if(!t.length)return[];const n=[];for(let i=0;i<t.length;i+=ps)n.push(t.slice(i,i+ps));return(await Promise.all(n.map(e))).flat()},On=async function(t,e){const{versionTag:n,withDraft:r}=e||{},i=await p(this,T,ve).call(this,`${H}/${t}/download`,{query:{...n&&{versionTag:n},...r&&{withDraft:r}}});if(i.status===429||i.status>=500)throw new Error(`Downloading ${t} answered ${i.status}${i.status===429?" (rate limited)":""}`);return i},Cn=async function(t,e,n){const{name:r,versionTag:i,parentFolderId:o,projectId:a,file:l,metadata:d}=t,c=new FormData;return c.append("file",l),c.append("name",r),c.append("versionTag",i),c.append("itemType",e),o&&c.append("folderId",o),a&&c.append("projectId",a),n&&c.append("extraProps",JSON.stringify(n)),d&&c.append("metadata",JSON.stringify(d)),await p(this,T,N).call(this,"POST",H,{body:c})},gs=async function(t,e,n){const{name:r,versionTag:i,parentFolderId:o,file:a,metadata:l}=e;let d,c;if(a){const m=new FormData;m.append("file",a),i&&m.append("versionTag",i),n&&m.append("extraProps",JSON.stringify(n)),l&&m.append("metadata",JSON.stringify(l)),c=await p(this,T,N).call(this,"POST",`${H}/${t}/version`,{body:m})}if(r||o){const m={...r&&{name:r},...o&&{folderId:o}},w=JSON.stringify(m);d=await p(this,T,N).call(this,"PUT",`${H}/${t}`,{body:w,contentType:"application/json"})}return{item:d,version:c}},ys=async function(t,e){const{showVersions:n=!1}=e||{};return await p(this,T,N).call(this,"GET",`${H}/${t}`,{query:{showVersions:n}})},ws=function(t){return t&&Object.entries(t).filter(([,e])=>e!==void 0).reduce((e,[n,r])=>(e[n]=r,e),{})};let Mn=Vs;function Si(){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 vs="channel:",Ea=1e4;function $n(s){try{s()}catch(t){console.error("[channel] a listener threw:",t)}}var ce,Dt,Ut,Le,Pe,Be,Lt,bs,Ts,Ne;class Us{constructor(t,e){K(this,Lt);K(this,ce,!1);K(this,Dt,[]);K(this,Ut,[]);K(this,Le,new Set);K(this,Pe,new Set);K(this,Be,new Set);this.transport=t,this.controls=e}get joined(){return g(this,ce)}get peers(){return g(this,Dt)}join(){return g(this,ce)?Promise.resolve():p(this,Lt,bs).call(this,"joined",this.controls.join)}leave(){return!g(this,ce)&&!g(this,Ut).some(t=>t.want==="joined")?Promise.resolve():p(this,Lt,bs).call(this,"left",this.controls.leave)}onChange(t){return g(this,Le).add(t),()=>void g(this,Le).delete(t)}onPeerJoined(t){return g(this,Pe).add(t),()=>void g(this,Pe).delete(t)}onPeerLeft(t){return g(this,Be).add(t),()=>void g(this,Be).delete(t)}applyJoined(){it(this,ce,!0),p(this,Lt,Ts).call(this,"joined"),p(this,Lt,Ne).call(this)}applyLeft(){it(this,ce,!1),it(this,Dt,[]),p(this,Lt,Ts).call(this,"left"),p(this,Lt,Ne).call(this)}applyPeers(t){it(this,Dt,t),p(this,Lt,Ne).call(this)}applyPeerJoined(t){!g(this,ce)||g(this,Dt).some(e=>e.from===t.from)||(it(this,Dt,[...g(this,Dt),t]),g(this,Pe).forEach(e=>$n(()=>e(t))),p(this,Lt,Ne).call(this))}applyPeerLeft(t){const e=g(this,Dt).find(n=>n.from===t);e&&(it(this,Dt,g(this,Dt).filter(n=>n.from!==t)),g(this,Be).forEach(n=>$n(()=>n(e))),p(this,Lt,Ne).call(this))}failPending(t){const e=g(this,Ut);return it(this,Ut,[]),e.forEach(n=>{clearTimeout(n.timer),n.reject(t)}),e.length>0}post(t){this.transport.post(t)}}ce=new WeakMap,Dt=new WeakMap,Ut=new WeakMap,Le=new WeakMap,Pe=new WeakMap,Be=new WeakMap,Lt=new WeakSet,bs=function(t,e){return new Promise((n,r)=>{const i={want:t,resolve:n,reject:r,timer:setTimeout(()=>{it(this,Ut,g(this,Ut).filter(o=>o!==i)),r(new Error(`The platform did not confirm ${t==="joined"?"joining":"leaving"} in time.`))},Ea)};g(this,Ut).push(i),this.transport.post({type:"APP_CHANNEL_CONTROL",...e})})},Ts=function(t){const e=g(this,Ut).filter(n=>n.want===t);it(this,Ut,g(this,Ut).filter(n=>n.want!==t)),e.forEach(n=>{clearTimeout(n.timer),n.resolve()})},Ne=function(){g(this,Le).forEach(t=>$n(t))};var je;class _i extends Us{constructor(e){super(e,{join:{action:"joinCollab"},leave:{action:"leaveCollab"}});K(this,je,new Map)}on(e,n){const r=g(this,je).get(e)??new Set;return r.add(n),g(this,je).set(e,r),()=>void r.delete(n)}send(e,n){if(e.startsWith(vs))throw new Error(`Message types starting with '${vs}' are reserved.`);this.joined&&this.post({type:"APP_CHANNEL_PUBLISH",message:{type:e,payload:n}})}accepts(e){return e===void 0||e==="collab"}async handle(e){const n=g(this,je).get(e.type);if(!(n!=null&&n.size))return{handled:!1};const r=Oi(e);return n.forEach(i=>$n(()=>i(e.payload,r))),{handled:!0}}}je=new WeakMap;var Te;class Ai extends Us{constructor(e,n){super(e,{join:{action:"joinExternal",kind:n},leave:{action:"leaveExternal",kind:n}});K(this,Te,new Map);this.kind=n}on(e,n){if(g(this,Te).has(e))throw new Error(`"${e}" already has a handler in this room. Remove it first.`);return g(this,Te).set(e,n),()=>void g(this,Te).delete(e)}accepts(e,n){return e!==void 0&&e!=="external"?!1:this.kind===void 0||e===void 0||this.kind===n}get hasHandlers(){return g(this,Te).size>0}async handle(e){const n=g(this,Te).get(e.type);if(!n)return{handled:!1};try{return{handled:!0,value:await n(e.payload,Oi(e))}}catch(r){return{handled:!0,error:r instanceof Error?r.message:String(r)}}}}Te=new WeakMap;function Oi(s){return{from:s.from,at:s.at,requestId:s.requestId,kind:s.kind}}function Ia(s){const t=s;if((t==null?void 0:t.type)!=="THATOPEN_CHANNEL_MESSAGE")return null;const e=t.message;return!e||typeof e.type!="string"?null:{type:e.type,requestId:typeof e.requestId=="string"?e.requestId:void 0,payload:e.payload,at:typeof e.at=="number"?e.at:Date.now(),from:typeof e.from=="string"?e.from:"",scope:e.scope==="collab"||e.scope==="external"?e.scope:void 0,kind:typeof e.kind=="string"?e.kind:void 0}}var Oe,fn,le,Ee,Ie,$t,Es,xn,$i,xi,Ri,Is;class Ci{constructor(t){K(this,$t);K(this,Oe);K(this,fn);K(this,le);K(this,Ee,new Map);K(this,Ie,new Set);it(this,Oe,t),it(this,fn,t.listen(e=>void p(this,$t,$i).call(this,e)))}collab(){return g(this,le)??it(this,le,new _i(g(this,Oe))),g(this,le)}external(t){const e=t??"";let n=g(this,Ee).get(e);return n||(n=new Ai(g(this,Oe),t),g(this,Ee).set(e,n)),n}dispose(){g(this,fn).call(this)}}Oe=new WeakMap,fn=new WeakMap,le=new WeakMap,Ee=new WeakMap,Ie=new WeakMap,$t=new WeakSet,Es=function(){return[...g(this,le)?[g(this,le)]:[],...g(this,Ee).values()]},xn=function(t,e){if(t==="collab")return g(this,le);if(t==="external")return g(this,Ee).get(typeof e=="string"?e:"")},$i=async function(t){const e=Ia(t);if(e){if(e.type.startsWith(vs)){p(this,$t,xi).call(this,e);return}await p(this,$t,Ri).call(this,e)}},xi=function(t){var n,r,i;const e=t.payload??{};switch(t.type){case"channel:joined":(n=p(this,$t,xn).call(this,e.scope,e.kind))==null||n.applyJoined();break;case"channel:left":(r=p(this,$t,xn).call(this,e.scope,e.kind))==null||r.applyLeft();break;case"channel:peers":(i=p(this,$t,xn).call(this,e.scope,e.kind))==null||i.applyPeers(e.peers??[]);break;case"channel:peer-joined":case"channel:peer-left":{if(!e.from)break;const o=e.scope==="collab"?[g(this,le)]:[...g(this,Ee).values()].filter(a=>a.accepts("external",e.kind));for(const a of o)t.type==="channel:peer-joined"?a==null||a.applyPeerJoined({from:e.from,kind:e.kind}):a==null||a.applyPeerLeft(e.from);break}case"channel:error":{const o=new Error(String(t.payload));p(this,$t,Es).call(this).map(l=>l.failPending(o)).some(Boolean)||console.error("[channel] error:",t.payload);break}}},Ri=async function(t){const e=p(this,$t,Es).call(this).filter(i=>i.accepts(t.scope,t.kind));let n=!1;for(const i of e){const o=await i.handle(t);o.handled&&(n=!0,t.requestId&&p(this,$t,Is).call(this,t.requestId,o))}t.requestId&&t.scope==="external"&&e.length>0&&!n&&p(this,$t,Is).call(this,t.requestId,{handled:!0,error:`No handler for "${t.type}".`})},Is=function(t,e){g(this,Ie).has(t)||(g(this,Ie).add(t),g(this,Ie).size>500&&g(this,Ie).delete(g(this,Ie).values().next().value),g(this,Oe).post({type:"APP_CHANNEL_PUBLISH",message:{type:e.error===void 0?"reply":"reply-error",requestId:t,payload:e.error===void 0?e.value:{error:e.error}}}))};const _e="project",Re="notifications";var De,un;const Gs=class Gs extends Mn{constructor(e,n,r){super(typeof e=="string"?e:"",n,{...r,useBearer:!0});K(this,De);K(this,un);typeof e=="function"&&it(this,De,e)}async resolveAccessToken(){return g(this,De)?await g(this,De).call(this):super.resolveAccessToken()}static fromPlatformContext(e){const n=(typeof window<"u"?window.__THATOPEN_CONTEXT__:null)||{appId:"",projectId:"",accessToken:"",apiUrl:""},r=new Gs(n.accessToken,n.apiUrl,e);return r.context=n,r}get channel(){return g(this,un)??it(this,un,new Ci(Si())),g(this,un)}async listProjects(){return await this.request("GET",_e)}async getProject(e){return await this.request("GET",`${_e}/${e}`)}async getProjectData(e){return await this.request("GET",`${_e}/${e}/data`)}async getAvatar(e){return await this.request("GET",`account/${e}/avatar`,{responseType:"blob"})}async checkPermission(e){return await this.request("GET",`${_e}/permissions/check`,{query:e})}async checkPermissionBatch(e){return(await this.request("POST",`${_e}/permissions/check/batch`,{body:JSON.stringify({checks:e}),contentType:"application/json"})).results}async getNotifications(e){return await this.request("GET",Re,{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",`${Re}/unread-count`)).count}async markNotificationsRead(e){return await this.request("POST",`${Re}/mark-read`,{body:JSON.stringify({ids:e}),contentType:"application/json"})}async markAllNotificationsRead(){return await this.request("POST",`${Re}/mark-all-read`)}async getNotificationSubscriptions(){return await this.request("GET",`${Re}/subscriptions`)}async unsubscribeFromAutomation(e){return await this.request("DELETE",`${Re}/subscriptions/${e}`)}async subscribeToAutomation(e,n,r){return await this.request("POST",`${_e}/${e}/events/hooks/${n}/subscription`,{body:JSON.stringify(r??{}),contentType:"application/json"})}async updateAutomationSubscription(e,n,r){return await this.request("PATCH",`${_e}/${e}/events/hooks/${n}/subscription`,{body:JSON.stringify(r),contentType:"application/json"})}async onNotification(e){const n=await this.resolveAccessToken(),r=tn(`${this.socketOrigin}/notifications`,{auth:{accessToken:n},transports:["websocket"]});return r.on("notification.created",i=>e({type:"created",id:i==null?void 0:i.id})),r.on("notification.read",i=>e({type:"read",id:i==null?void 0:i.id})),r.on("notifications.allRead",i=>e({type:"allRead",batch:i==null?void 0:i.batch})),()=>r.disconnect()}};De=new WeakMap,un=new WeakMap;let Ss=Gs;const me=1/.3048,Sa={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"},_a="OST_GenericModel",Aa=new Set(["IFCSPACE","IFCOPENINGELEMENT","IFCSITE","IFCANNOTATION","IFCGRID","IFCVIRTUALELEMENT","IFCBUILDING","IFCBUILDINGSTOREY"]),be=(s,t)=>Math.round(s/t)*t,Oa=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]]}),en=(s,t)=>s[0]*t[0]+s[1]*t[1]+s[2]*t[2],Kn=s=>Math.sqrt(en(s,s)),Rn=(s,t)=>[s[1]*t[2]-s[2]*t[1],s[2]*t[0]-s[0]*t[2],s[0]*t[1]-s[1]*t[0]];function Ca(s,t,e){const n=new Set,r=new Map;for(const l of t){const d=l.split(":")[1];d&&(n.add(d),r.has(d)||r.set(d,l))}const i=new Map,o=new Map,a=[];for(const l of s.elements.values()){if(n.has(l.gid)||Aa.has(l.ifcClass.toUpperCase())||l.parent&&n.has(l.parent)&&!/^IFC(DOOR|WINDOW)$/i.test(l.ifcClass)||l.pieces.length===0)continue;const c=/^IFCCOLUMN$/i.test(l.ifcClass)&&/structural|estructural|结构柱|tragend|tragwerk/i.test(`${l.typeName??""} ${l.objectType??""} ${l.name??""}`)?"OST_StructuralColumns":Sa[l.ifcClass.toUpperCase()]??_a,m=Oa(l.pieces[0].matrix),w=Kn(m.x),v=Kn(m.y),I=Kn(m.z),_=m.z.map(q=>q/(I||1)),L=Math.abs(_[2]-1)<1e-6&&en(Rn(m.x,m.y),m.z)>0&&Math.abs(w-v)<1e-6&&Math.abs(w-I)<1e-6,C=en(Rn(m.x,m.y),m.z)>0&&Math.abs(w-v)<1e-6&&Math.abs(w-I)<1e-6,O=[m.x,m.y,m.z].map(q=>q.map(Z=>Z/(w||1))),u=C&&!L&&O.some(q=>Math.abs(Math.abs(q[2])-1)<1e-6)?O.find(q=>Math.abs(q[2])<1e-6):void 0,$=L?Math.atan2(m.x[1],m.x[0]):u?Math.atan2(u[1],u[0]):0,E=Math.cos(-$),F=Math.sin(-$),z=[m.t[0],m.t[1],m.t[2]],ut=/COLUMN/i.test(c),wt=q=>{const Z=q[0]-z[0],x=q[1]-z[1];return[E*Z-F*x,F*Z+E*x,q[2]-z[2]]},Ct=[],Vt=[c];for(const q of l.pieces){const Z=s.geometries.get(q.geometry);if(!Z)continue;const x=q.matrix,Tt=[];for(let st=0;st<Z.verts.length;st+=3){const rt=Z.verts[st],et=Z.verts[st+1],At=Z.verts[st+2],Ht=[x[0]*rt+x[4]*et+x[8]*At+x[12],x[1]*rt+x[5]*et+x[9]*At+x[13],x[2]*rt+x[6]*et+x[10]*At+x[14]],de=wt(Ht);Tt.push(be(de[0]*me,1e-5),be(de[1]*me,1e-5),be(de[2]*me,1e-5))}const Et=en(Rn([x[0],x[1],x[2]],[x[4],x[5],x[6]]),[x[8],x[9],x[10]])<0,pt=[];for(let st=0;st+2<Z.tris.length;st+=3)Et?pt.push(Z.tris[st],Z.tris[st+2],Z.tris[st+1]):pt.push(Z.tris[st],Z.tris[st+1],Z.tris[st+2]);pt.length&&Ct.push({v:Tt,t:pt});const jt=wt([x[12],x[13],x[14]]),Ft=[E*x[0]-F*x[1],F*x[0]+E*x[1],x[2]],Pt=[E*x[4]-F*x[5],F*x[4]+E*x[5],x[6]];Vt.push(`${q.geometry}@${[...jt,...Ft,...Pt].map(st=>be(st,1e-4).toFixed(4)).join(",")}`)}if(Ct.length===0)continue;const Mt=!l.host&&Ct.length===1?Ra(Ct[0]):null;if(Mt){const q=xa(Mt),Z=q.key,x=`prism|${c}|${q.axis}|${Z}`;let Tt=i.get(x);if(!Tt){const et=Nr(l.typeName??l.objectType??l.name??l.ifcClass),At=(o.get(et)??0)+1;o.set(et,At);const Ht=At===1?et:`${et} (${At})`;Tt={family:Ht,type:Ht,first:!0,key:Fr(x)},i.set(x,Tt)}const Et={ShapeCategory:c,Family:Tt.family,Type:Tt.type,ShapeKey:Tt.key,PrismLength:String(be(Mt.length,1e-5)),...ut?{ColumnFree:"1"}:{}};Tt.first&&(Et.Prism=JSON.stringify({axis:q.axis,loops:q.loops}),Tt.first=!1);const pt=[0,0,0];pt[Mt.axis]=(q.flipped?Mt.from+Mt.length:Mt.from)/me;const jt=(Mt.axis+1)%3,Ft=(Mt.axis+2)%3;pt[jt]+=q.centre[0]/me,pt[Ft]+=q.centre[1]/me;const Pt=Math.cos($),st=Math.sin($),rt=[z[0]+Pt*pt[0]-st*pt[1],z[1]+st*pt[0]+Pt*pt[1],z[2]+pt[2]];a.push({key:`${e}:${l.gid}:shape`,attrs:Et,at:rt,rotationDeg:($+q.turn)*180/Math.PI});continue}const he=`${c}|${Ct.map(q=>`${q.v.map(Z=>Math.round(Z*304.8/2)).join(",")}/${q.t.join(",")}`).join("|")}`,Yt=Vt.join("|");let It=i.get(Yt)??i.get(he);if(It&&(i.set(Yt,It),i.set(he,It)),!It){const q=Nr(l.typeName??l.objectType??l.name??l.ifcClass),Z=(o.get(q)??0)+1;o.set(q,Z);const x=Z===1?q:`${q} (${Z})`;It={family:x,type:x,first:!0,key:Fr(he)},i.set(he,It),i.set(Yt,It)}const Gt={ShapeCategory:c,Family:It.family,Type:It.type,ShapeKey:It.key,...ut?{ColumnFree:"1"}:{}};It.first&&(Gt.Shape=JSON.stringify({pieces:Ct}),It.first=!1);const Nt=l.host?r.get(l.host):void 0,Ce=l.opening?s.elements.get(l.opening):void 0;if(Nt&&Ce){const q=[1/0,1/0,1/0],Z=[-1/0,-1/0,-1/0];for(const x of Ce.pieces){const Tt=s.geometries.get(x.geometry);if(!Tt)continue;const Et=x.matrix;for(let pt=0;pt<Tt.verts.length;pt+=3){const jt=Tt.verts[pt],Ft=Tt.verts[pt+1],Pt=Tt.verts[pt+2],st=wt([Et[0]*jt+Et[4]*Ft+Et[8]*Pt+Et[12],Et[1]*jt+Et[5]*Ft+Et[9]*Pt+Et[13],Et[2]*jt+Et[6]*Ft+Et[10]*Pt+Et[14]]);for(let rt=0;rt<3;rt++)q[rt]=Math.min(q[rt],st[rt]*me),Z[rt]=Math.max(Z[rt],st[rt]*me)}}Number.isFinite(q[0])&&(Gt.Opening=[...q,...Z].map(x=>be(x,1e-5)).join(","))}a.push({key:`${e}:${l.gid}:shape`,attrs:Gt,at:[z[0],z[1],z[2]],rotationDeg:$*180/Math.PI,...Nt?{host:Nt}:{}})}return a}function Nr(s){return(s.replace(/[\\:{}[\]|;<>?`~]/g,"-").replace(/\s+/g," ").trim()||"Shape").slice(0,120)}function Fr(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 $a(s,t,e){const n=new Map;for(const i of t){const[,o,a]=i.split(":");o&&/^run/.test(a??"")&&!n.has(o)&&n.set(o,i)}const r=[];for(const i of s.elements.values()){if(i.ifcClass.toUpperCase()!=="IFCOPENINGELEMENT"||!i.host)continue;const o=n.get(i.host);if(o)for(const a of Na(s,i.gid)){const l=a.pts;if(l.length<4)continue;const d=Ma(sn(s,i.host));if(!d)continue;const c=l.map(I=>(I[0]-d.a[0])*d.u[0]+(I[1]-d.a[1])*d.u[1]),m=l.map(I=>-(I[0]-d.a[0])*d.u[1]+(I[1]-d.a[1])*d.u[0]),w=I=>Math.max(...I)-Math.min(...I),v=w(c)*w(m)*w(l.map(I=>I[2]));!(v>0)||Math.abs(a.volume)<.75*v||r.push({key:`${e}:${i.gid}:opening${a.index===0&&a.of===1?"":`#${a.index}`}`,host:o,box:l.flat()})}}return r}function xa(s){const t=s.loops.flat(),e=[t.reduce((w,v)=>w+v[0],0)/t.length,t.reduce((w,v)=>w+v[1],0)/t.length],n=s.loops.map(w=>{const v=w.map(([O,u])=>[O-e[0],u-e[1]]),I=v.map(([O,u])=>Math.hypot(O,u)),_=I.reduce((O,u)=>O+u,0)/I.length;if(v.length<8||_<=0||I.some(O=>Math.abs(O-_)>.02*_))return v;const C=v.reduce((O,u,$)=>{const E=v[($+1)%v.length];return O+u[0]*E[1]-E[0]*u[1]},0)>=0?1:-1;return v.map((O,u)=>[_*Math.cos(C*2*Math.PI*u/v.length),_*Math.sin(C*2*Math.PI*u/v.length)])}),r=w=>w.map(I=>{const _=I.map(([C,O])=>`${Math.round(C*304.8)},${Math.round(O*304.8)}`);let L=0;for(let C=1;C<_.length;C++)_[C]<_[L]&&(L=C);return[..._.slice(L),..._.slice(0,L)].join(";")}).sort().join("|"),i=(w,v)=>{const I=Math.cos(-v),_=Math.sin(-v);return w.map(L=>L.map(([C,O])=>[I*C-_*O,_*C+I*O]))},o=[];let a=s.axis,l=0,d=n;if(a===1&&(a=0,l=Math.PI/2,d=n.map(w=>w.map(([v,I])=>[-I,v]))),a===2){let w=0,v=0,I=0;const _=n.flat();for(const[E,F]of _)w+=E*E,v+=F*F,I+=E*F;const L=new Set,C=.5*Math.atan2(2*I,w-v);for(let E=0;E<4;E++)L.add(C+E*Math.PI/2);const O=_.map(([E,F])=>Math.hypot(E,F)),u=Math.max(...O),$=_.filter((E,F)=>O[F]>u-.003);if(Math.abs(w-v)<.001*(w+v)||$.length>4)for(const[E,F]of $.slice(0,64))L.add(Math.atan2(F,E));for(const E of L)o.push({loops:i(n,E),turn:E,flipped:!1})}else o.push({loops:d,turn:0,flipped:!1}),o.push({loops:d.map(w=>w.map(([v,I])=>[-v,I]).reverse()),turn:Math.PI,flipped:!0});let c=o[0],m=r(c.loops);for(const w of o.slice(1)){const v=r(w.loops);v<m&&(c=w,m=v)}return{axis:a,loops:c.loops,key:m,centre:e,turn:l+c.turn,flipped:c.flipped}}function Ra(s){const e=s.v.length/3;if(e<6)return null;const n=[0,1,2].map(r=>{let i=1/0,o=-1/0;for(let a=0;a<e;a++){const l=s.v[a*3+r];i=Math.min(i,l),o=Math.max(o,l)}return o-i});for(const r of[0,1,2].sort((i,o)=>n[o]-n[i])){let i=1/0,o=-1/0;for(let u=0;u<e;u++){const $=s.v[u*3+r];i=Math.min(i,$),o=Math.max(o,$)}if(o-i<.01)continue;let a=!0;for(let u=0;u<e&&a;u++){const $=s.v[u*3+r];Math.abs($-i)>.001&&Math.abs($-o)>.001&&(a=!1)}if(!a)continue;const l=(r+1)%3,d=(r+2)%3,c=new Map,m=[],w=u=>{const $=[s.v[u*3+l],s.v[u*3+d]],E=`${Math.round($[0]*3048)},${Math.round($[1]*3048)}`;return c.has(E)||(c.set(E,m.length),m.push($)),c.get(E)},v=new Map,I=[];for(let u=0;u+2<s.t.length;u+=3){const $=[s.t[u],s.t[u+1],s.t[u+2]];if(!$.every(F=>Math.abs(s.v[F*3+r]-i)<=.001))continue;const E=$.map(w);if(!(E[0]===E[1]||E[1]===E[2]||E[0]===E[2])){I.push(E);for(let F=0;F<3;F++){const z=E[F],ut=E[(F+1)%3],wt=z<ut?`${z},${ut}`:`${ut},${z}`;v.set(wt,(v.get(wt)??0)+1)}}}if(I.length===0)continue;const _=new Map;for(const u of I)for(let $=0;$<3;$++){const E=u[$],F=u[($+1)%3];v.get(E<F?`${E},${F}`:`${F},${E}`)===1&&_.set(E,[..._.get(E)??[],F])}if([..._.values()].some(u=>u.length!==1))continue;const L=[],C=new Set(_.keys());for(;C.size;){const u=C.values().next().value,$=[];let E=u,F=0;do $.push(m[E]),C.delete(E),E=_.get(E)[0];while(E!==u&&F++<1e5&&_.has(E));if(E!==u||$.length<3){L.length=0;break}const z=$.filter((ut,wt)=>{const Ct=$[(wt-1+$.length)%$.length],Vt=$[(wt+1)%$.length];return Math.abs((ut[0]-Ct[0])*(Vt[1]-Ct[1])-(ut[1]-Ct[1])*(Vt[0]-Ct[0]))>1e-7});L.push(z.map(([ut,wt])=>[be(ut,1e-5),be(wt,1e-5)]))}if(L.length===0||L.some(u=>u.length<3))continue;let O=0;for(let u=0;u<e;u++)Math.abs(s.v[u*3+r]-o)<=.001&&O++;if(!(O<3))return{axis:r,from:i,length:o-i,loops:L}}return null}function ka(s,t){const e=[];for(const n of s.elements.values()){if(n.ifcClass.toUpperCase()!=="IFCSPACE")continue;let r=1/0,i=-1/0;const o=[];for(const d of n.pieces){const c=s.geometries.get(d.geometry);if(!c)continue;const m=d.matrix,w=v=>{const I=c.verts[v*3],_=c.verts[v*3+1],L=c.verts[v*3+2];return[m[0]*I+m[4]*_+m[8]*L+m[12],m[1]*I+m[5]*_+m[9]*L+m[13],m[2]*I+m[6]*_+m[10]*L+m[14]]};for(let v=0;v+2<c.tris.length;v+=3){const I=[w(c.tris[v]),w(c.tris[v+1]),w(c.tris[v+2])];for(const _ of I)r=Math.min(r,_[2]),i=Math.max(i,_[2]);o.push(I)}}if(!Number.isFinite(r)||i-r<.1)continue;let a=null,l=0;for(const d of o){if(!d.every(m=>Math.abs(m[2]-r)<.001))continue;const c=Math.abs((d[1][0]-d[0][0])*(d[2][1]-d[0][1])-(d[2][0]-d[0][0])*(d[1][1]-d[0][1]))/2;c>l&&(l=c,a=d)}a&&e.push({key:`${t}:${n.gid}:room`,at:[(a[0][0]+a[1][0]+a[2][0])/3,(a[0][1]+a[1][1]+a[2][1])/3,r],height:i-r,number:n.name??"",name:n.longName??n.name??""})}return e}function Ma(s){if(s.length<2)return;let t=s[0],e=s[0],n=0;for(const r of s){const i=Math.hypot(r[0]-s[0][0],r[1]-s[0][1]);i>n&&(n=i,e=r)}n=0;for(const r of s){const i=Math.hypot(r[0]-e[0],r[1]-e[1]);i>n&&(n=i,t=r)}if(!(n<.1))return{a:t,u:[(e[0]-t[0])/n,(e[1]-t[1])/n]}}function Na(s,t){const e=s.elements.get(t);if(!e)return[];const n=[],r=[],i=new Map;for(const c of e.pieces){const m=s.geometries.get(c.geometry);if(!m)continue;const w=c.matrix,v=[];for(let I=0;I<m.verts.length;I+=3){const _=m.verts[I],L=m.verts[I+1],C=m.verts[I+2],O=[w[0]*_+w[4]*L+w[8]*C+w[12],w[1]*_+w[5]*L+w[9]*C+w[13],w[2]*_+w[6]*L+w[10]*C+w[14]],u=O.map(E=>Math.round(E*1e4)).join(",");let $=i.get(u);$===void 0&&($=n.length,i.set(u,$),n.push(O)),v.push($)}for(let I=0;I+2<m.tris.length;I+=3)r.push(v[m.tris[I]],v[m.tris[I+1]],v[m.tris[I+2]])}const o=n.map((c,m)=>m),a=c=>{for(;o[c]!==c;)o[c]=o[o[c]],c=o[c];return c};for(let c=0;c<r.length;c+=3){const m=a(r[c]);o[a(r[c+1])]=m,o[a(r[c+2])]=m}const l=new Map;for(let c=0;c<r.length;c+=3){const m=a(r[c]);let w=l.get(m);w||(w={pts:new Set,volume:0},l.set(m,w));const[v,I,_]=[n[r[c]],n[r[c+1]],n[r[c+2]]];w.volume+=en(v,Rn(I,_))/6,w.pts.add(r[c]),w.pts.add(r[c+1]),w.pts.add(r[c+2])}const d=[...l.values()];return d.map((c,m)=>({pts:[...c.pts].map(w=>n[w]),volume:c.volume,index:m,of:d.length}))}function sn(s,t,e){const n=s.elements.get(t),r=[];if(!n)return r;for(const i of n.pieces){const o=s.geometries.get(i.geometry);if(!o)continue;const a=i.matrix;for(let l=0;l<o.verts.length;l+=3){const d=o.verts[l],c=o.verts[l+1],m=o.verts[l+2];r.push([a[0]*d+a[4]*c+a[8]*m+a[12],a[1]*d+a[5]*c+a[9]*m+a[13],a[2]*d+a[6]*c+a[10]*m+a[14]])}}return r}function Fa(s,t,e){const n=sn(s,t);if(n.length<4||e.length===0)return;let r=n[0],i=n[0],o=0;for(const C of n){const O=Math.hypot(C[0]-n[0][0],C[1]-n[0][1]);O>o&&(o=O,i=C)}o=0;for(const C of n){const O=Math.hypot(C[0]-i[0],C[1]-i[1]);O>o&&(o=O,r=C)}if(o<.3)return;const a=(i[0]-r[0])/o,l=(i[1]-r[1])/o,d=C=>(C[0]-r[0])*a+(C[1]-r[1])*l,c=Math.max(...n.map(C=>C[2])),m=C=>Math.max(...n.filter(O=>Math.abs(d(O)-C)<.05).map(O=>O[2]),-1/0),w=m(0),v=m(o);if(Math.abs(w-v)<.05&&c-Math.max(w,v)<.05)return;const I=(r[0]+i[0])/2,_=(r[1]+i[1])/2;let L;for(const C of e){const O=sn(s,C.gid);if(O.length===0)continue;const u=O.map(z=>z[0]),$=O.map(z=>z[1]),E=O.map(z=>z[2]);if(I<Math.min(...u)-.2||I>Math.max(...u)+.2||_<Math.min(...$)-.2||_>Math.max(...$)+.2)continue;const F=Math.min(...E)-c;F>1.5||Math.max(...E)<c-.05||(!L||Math.abs(F)<Math.abs(L.gap))&&(L={id:C.id,gap:F})}return L==null?void 0:L.id}const ge={levels:"-2000240",walls:"-2000011",floors:"-2000032",roofs:"-2000035",ceilings:"-2000038",structuralFoundations:"-2001300",stairs:"-2000120"};function Ze(s){const t=s.item.attrs.Name;if(typeof t!="string")return null;const e=t.indexOf(":"),n=t.lastIndexOf(":");if(e<=0||n<=e)return null;const r=t.slice(e+1,n).trim();return r?{family:t.slice(0,e).trim(),type:r}:null}function Lr(s){const t=Ze(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 Pr=180/Math.PI;function Br(s){if(typeof s!="string")return null;const t=s.indexOf(":");return t<=0||t===s.length-1?null:{family:s.slice(0,t),type:s.slice(t+1)}}const ft=s=>String(s);function ki(s){return async t=>{var Js,Ws,zs,Ys,Ks,Xs,Qs,Zs,tr,er,nr,sr,rr,ir,or,ar,cr,lr,hr,dr,fr;const{picked:e,contents:n,site:r,shapes:i}=await Bs(t,t.input),o=pi(n.items),a=/CoordinateBase:\s*(Coordenadas compartidas|Shared Coordinates|Shared)/i.test(JSON.stringify(n.metadata??{})),l=a&&r?[r.east*Fe,r.north*Fe,r.elevation*Fe,r.angleDeg].map(h=>h.toFixed(6)).join(","):void 0;if(o.length===0)throw new Error(s==="ifc"?`Nothing in "${e.name}" could be read as a building element (walls, floors, levels...).`:`"${e.name}" carries no platform records, so there is nothing semantic to convert.`);const{columnType:d,trustStyleNames:c,includeInstances:m}=t.settings,w=t.settings.createLevels!==!1;if(m&&!c)throw new Error("Free-standing instances can only be made by their style names: turn trustStyleNames on.");const v=Ls(o),I=mi(o),_=`recipe:${s}-to-revit`,L=new Map,C=Ps(t,L);t.progress("Writing the changes for Revit");const O=new Ln({project:t.projectId,document:t.target.docId??"",baseCommit:t.target.version??0,author:_}),u=Fe,$=new Map;{const h=new Map;for(const f of o){const y=f.item.guid;if(!y)continue;const b=`${y}:${f.kind}`,R=h.get(b)??0;h.set(b,R+1),$.set(f.id,`${e.fileId}:${b}${R?`:${R}`:""}`)}}const E=h=>$.get(h)??`${e.fileId}:${h}`,F=new Set;let z=0,ut=0;const wt=(h,f,y)=>{F.add(h);const b=a?{...f,Frame:"shared",...l?{SharedAt:l}:{}}:f,R=gi({attrs:b,placement:y??{}}),S=C.get(h);if(S){const k=L.get(h);return!k||k===R?(z++,!1):(O.remove(S),O.add({...b,"flow:print":R},{...y,source:h}),ut++,!1)}return O.add({...b,"flow:print":R},{...y,source:h}),!0},Ct=h=>{const f=typeof h=="string"?I.get(h):void 0,y=f==null?void 0:f.params.thickness;return typeof y=="number"&&y>0?y*u:void 0},Vt=h=>{var D,at;const f=Bt(h,"extrusion"),y=v.get(String((f==null?void 0:f.level)??h.params.level??"")),b=f==null?void 0:f.slopes,R=((at=(D=f==null?void 0:f.profile)==null?void 0:D.outline)==null?void 0:at.curves)??[],S=Array.isArray(b)?b.map(J=>typeof J=="number"):[],k=S.indexOf(!0);if(h.params.of!=="roof"||!y||R.length!==4||S.filter(Boolean).length!==2||k<0||k>1||!S[k+2])return null;const[A,j]=[R[k],R[k+2]],nt=A.from,ht=A.to,Y=Math.hypot(ht[0]-nt[0],ht[1]-nt[1]),St=[(ht[0]-nt[0])/Y,(ht[1]-nt[1])/Y];let U=[-St[1],St[0]];const ot=(j.from[0]-nt[0])*U[0]+(j.from[1]-nt[1])*U[1];ot<0&&(U=[-U[0],-U[1]]);const yt=Math.abs(ot),[P,G]=[b[k],b[k+2]],lt=y.at+(typeof h.params.base=="number"?h.params.base:0),xt=(f==null?void 0:f.eaves)??[],[tt,vt]=[lt+(Number(xt[k])||0),lt+(Number(xt[k+2])||0)],mt=(vt-tt+G*yt)/(P+G);return{A:nt,u:St,n:U,L:Y,W:yt,si:P,sj:G,ridge:mt,top:lt,ti:tt,tj:vt,zAt:(J,B)=>{const V=(J-nt[0])*U[0]+(B-nt[1])*U[1];return Math.min(tt+P*V,vt+G*(yt-V))}}},Mt=new Map(o.filter(h=>h.kind==="extrusion"&&h.params.of==="roof").map(h=>[h.id,h])),he=[...Mt.values()].filter(h=>h.item.guid).map(h=>({id:h.id,gid:h.item.guid}));let Yt=0;if(w)for(const[h,f]of v)wt(E(h),{CategoryId:ge.levels,Name:f.name,Elevation:ft(f.at*u)})&&Yt++;let It=0,Gt=0;const Nt=[];for(const h of o){if(h.kind!=="run"||h.params.of!=="wall")continue;const f=Bt(h,"run"),y=((Ws=(Js=f==null?void 0:f.run)==null?void 0:Js.line)==null?void 0:Ws.curves)??[],b=h.params.lookRef,R=v.get(String((f==null?void 0:f.level)??h.params.level??""));if(typeof b!="string"||typeof(f==null?void 0:f.height)!="number"||!R){Gt++;continue}const S=(Ct(b)??0)/u,k=y.filter(A=>A.kind==="segment"&&A.from&&A.to);Gt+=y.length-k.length,k.forEach((A,j)=>Nt.push({record:h,i:j,width:S,from:[...A.from],to:[...A.to],joinStart:j===0&&String(h.params.meetsAtStart)==="true",joinEnd:j===k.length-1&&String(h.params.meetsAtEnd)==="true"}))}const Ce=(h,f)=>{const y=[h.to[0]-h.from[0],h.to[1]-h.from[1]],b=[f.to[0]-f.from[0],f.to[1]-f.from[1]],R=y[0]*b[1]-y[1]*b[0];if(Math.abs(R)<1e-9*Math.hypot(...y)*Math.hypot(...b)*1e3)return null;const S=((f.from[0]-h.from[0])*b[1]-(f.from[1]-h.from[1])*b[0])/R;return[h.from[0]+S*y[0],h.from[1]+S*y[1]]},q=(h,f)=>{const y=f.to[0]-f.from[0],b=f.to[1]-f.from[1],R=y*y+b*b||1,S=Math.max(0,Math.min(1,((h[0]-f.from[0])*y+(h[1]-f.from[1])*b)/R));return Math.hypot(h[0]-(f.from[0]+S*y),h[1]-(f.from[1]+S*b))},Z=(h,f)=>{const y=Bt(h.record,"run"),b=Bt(f.record,"run"),R=[y.base,y.base+y.height],S=[b.base,b.base+b.height],k=v.get(String((y==null?void 0:y.level)??h.record.params.level)).at,A=v.get(String((b==null?void 0:b.level)??f.record.params.level)).at;return Math.min(k+R[1],A+S[1])>Math.max(k+R[0],A+S[0])},x=1,Tt=new Map;for(const h of Nt){const f=[["from",h.joinStart],["to",h.joinEnd]],y={from:h.from,to:h.to};for(const[b,R]of f){if(!R)continue;const S=h[b];let k=null,A=1/0;for(const ht of Nt){if(ht===h||!Z(h,ht))continue;const Y=q(S,ht);Y<A&&(A=Y,k=ht)}if(!k||A>x)continue;const j=Ce(h,k);if(!j)continue;const nt=Math.min(x,2*Math.max(h.width,k.width)+.02);Math.hypot(j[0]-S[0],j[1]-S[1])>nt||q(j,k)>k.width+.01||(y[b]=j)}Tt.set(h,y)}for(const h of Nt){const{record:f}=h,y=Bt(f,"run"),b=typeof y.base=="number"?y.base:0,R=y.height,S=v.get(String(y.level??f.params.level??"")),k=f.params.lookRef;let{from:A,to:j}=Tt.get(h);const nt=new Set;if(i&&f.item.guid&&Nt.filter(D=>D.record===f).length===1?i.elements.get(f.item.guid):void 0){const D=sn(i,f.item.guid),at=Math.hypot(j[0]-A[0],j[1]-A[1]);if(D.length>=4&&at>.05){const J=[(j[0]-A[0])/at,(j[1]-A[1])/at],B=D.map(bt=>(bt[0]-A[0])*J[0]+(bt[1]-A[1])*J[1]),V=Math.min(...B),ct=Math.max(...B),dt=D.map(bt=>-(bt[0]-A[0])*J[1]+(bt[1]-A[1])*J[0]),Rt=Math.max(...dt)-Math.min(...dt),Q=bt=>{const Jt=dt.filter((fe,ue)=>Math.abs(B[ue]-bt)<.002);return Jt.length>=2&&Math.max(...Jt)-Math.min(...Jt)>.9*Rt},W=A;Q(V)&&(A=[W[0]+J[0]*V,W[1]+J[1]*V],nt.add("start")),Q(ct)&&(j=[W[0]+J[0]*ct,W[1]+J[1]*ct],nt.add("end"))}}const Y=(S.at+b)*u,St=`${ft(A[0]*u)},${ft(A[1]*u)},${ft(Y)};${ft(j[0]*u)},${ft(j[1]*u)},${ft(Y)}`,U={CategoryId:ge.walls,Type:((zs=Ze(f))==null?void 0:zs.type)??k,LocationLine:St,Level:S.name,BaseOffset:ft(b*u),Height:ft(R*u)},ot=[A!==h.from||h.joinStart?"start":"",j!==h.to||h.joinEnd?"end":""].filter(D=>!!D&&!nt.has(D));ot.length&&(U.JoinEnds=ot.join(","));const yt=ot.filter(D=>f.params[D==="start"?"wantedAtStart":"wantedAtEnd"]==="mitre");yt.length&&(U.Mitre=yt.join(","));const P=v.get(String(f.params.topLevel??""));P&&(U.TopLevel=P.name,U.TopOffset=ft((S.at+b+R-P.at)*u));const G=y.profile;if(Array.isArray(G)&&G.length>=3&&h.i===0&&!Nt.some(D=>D!==h&&D.record===f)){const D=Math.hypot(h.to[0]-h.from[0],h.to[1]-h.from[1]),at=[(h.to[0]-h.from[0])/D,(h.to[1]-h.from[1])/D],J=[],B=-((A[0]-h.from[0])*at[0]+(A[1]-h.from[1])*at[1]),V=(j[0]-h.to[0])*at[0]+(j[1]-h.to[1])*at[1];G.forEach(([ct,dt],Rt)=>{const Q=Math.abs(ct)<1e-6,W=Math.abs(ct-D)<1e-6;let bt=ct,Jt=dt;if(Q||W){bt=Q?-B:D+V;const ue=[G[(Rt-1+G.length)%G.length],G[(Rt+1)%G.length]].find(([Ge])=>Math.abs(Ge-ct)>1e-6);ue&&(Jt=dt+(ue[1]-dt)/(ue[0]-ct)*(bt-ct))}const fe=[h.from[0]+bt*at[0],h.from[1]+bt*at[1]];J.push(fe[0]*u,fe[1]*u,(S.at+b+Jt)*u)}),U.Profile=JSON.stringify([J]),delete U.TopLevel,delete U.TopOffset}const lt=f.params.topAttachedTo,xt=f.params.topAttachedAt==="top"||y.topAttachedAt==="top",tt=typeof lt=="string"&&xt&&!U.Profile&&Mt.has(lt)?Vt(Mt.get(lt)):null;if(tt){const D=Math.hypot(j[0]-A[0],j[1]-A[1]),at=Q=>[A[0]+(j[0]-A[0])*Q/D,A[1]+(j[1]-A[1])*Q/D],J=(A[0]-tt.A[0])*tt.n[0]+(A[1]-tt.A[1])*tt.n[1],B=(j[0]-tt.A[0])*tt.n[0]+(j[1]-tt.A[1])*tt.n[1],V=[0,D];(J-tt.ridge)*(B-tt.ridge)<0&&V.splice(1,0,(tt.ridge-J)/(B-J)*D);const ct=S.at+b,dt=[],Rt=(Q,W)=>{const bt=at(Q);dt.push(bt[0]*u,bt[1]*u,W*u)};Rt(0,ct),Rt(D,ct);for(const Q of[...V].reverse()){const W=at(Q);Rt(Q,tt.zAt(W[0],W[1]))}U.Profile=JSON.stringify([dt]),delete U.TopLevel,delete U.TopOffset}const vt=typeof lt=="string"?lt:i&&f.item.guid?Fa(i,f.item.guid,he):void 0;vt&&!U.Profile&&(U.AttachTop=E(vt));const mt=Ct(k);mt&&(U["Type.Width"]=ft(mt));const gt=f.item.guid?i==null?void 0:i.elements.get(f.item.guid):void 0;gt!=null&&gt.layers&&gt.layers.length>1&&(U["Type.Layers"]=JSON.stringify([...gt.layers].reverse().map(D=>[+ft(D.thickness*u),D.material??"",D.function??""])),gt.layersFlipped&&(U.FlipLayers="1")),wt(`${E(f.id)}#${h.i}`,U)&&It++}const Et=(h,f,y)=>{if(!(f>0)||f>=h)return[];const b=h-Math.floor(h/f+1e-9)*f,R=y==="beginning"?0:y==="end"?b:y==="centreLine"?h/2%f:b/2,S=[];for(let k=R;k<=h+1e-4;k+=f)k>1e-4&&k<h-1e-4&&S.push(k);return S};let pt=0,jt=0;for(const h of o){if(h.kind!=="run"||h.params.of!=="curtainWall")continue;jt++;const f=Bt(h,"run"),y=(Xs=(Ks=(Ys=f==null?void 0:f.run)==null?void 0:Ys.line)==null?void 0:Ks.curves)==null?void 0:Xs[0],b=v.get(String((f==null?void 0:f.level)??h.params.level??"")),R=h.params.lookRef,S=typeof R=="string"?(Qs=I.get(R))==null?void 0:Qs.params:void 0;if(!(y!=null&&y.from)||!y.to||typeof(f==null?void 0:f.height)!="number"||!b||!S)continue;const k=mt=>typeof mt=="number"?mt:Number(mt)||0,A=k(S.uprightWidth)/2,j=k(S.horizontalWidth)/2,nt=Math.hypot(y.to[0]-y.from[0],y.to[1]-y.from[1]),ht=[(y.to[0]-y.from[0])/nt,(y.to[1]-y.from[1])/nt],Y=[y.from[0]-ht[0]*A,y.from[1]-ht[1]*A],St=[y.to[0]+ht[0]*A,y.to[1]+ht[1]*A],U=(typeof f.base=="number"?f.base:0)-j,ot=f.height+2*j,yt=(b.at+U)*u,P=((Zs=f.lines)==null?void 0:Zs.along)??Et(nt,k(S.alongSpacing),S.alongJustify),G=((tr=f.lines)==null?void 0:tr.up)??Et(f.height,k(S.upSpacing),S.upJustify),lt=(f.omitted??[]).flatMap(mt=>{const gt=/^(horizontal|vertical)@(-?[\d.]+):(-?[\d.]+)$/.exec(mt);if(!gt)return[];const D=gt[1]==="horizontal",at=Number(gt[2])/1e3+(D?j:A),J=Number(gt[3])/1e3+(D?A:j);return[{horizontal:D,at:at*u,from:J*u}]}),xt=(f.omitted??[]).flatMap(mt=>{const gt=/^panel@(-?[\d.]+),(-?[\d.]+)$/.exec(mt);return gt?[{along:(Number(gt[1])/1e3+A)*u,up:(Number(gt[2])/1e3+j)*u}]:[]}),tt={CategoryId:ge.walls,Type:((er=Ze(h))==null?void 0:er.type)??String(R),LocationLine:`${ft(Y[0]*u)},${ft(Y[1]*u)},${ft(yt)};${ft(St[0]*u)},${ft(St[1]*u)},${ft(yt)}`,Level:b.name,BaseOffset:ft(U*u),Height:ft(ot*u),Curtain:JSON.stringify({along:P.map(mt=>(mt+A)*u),up:G.map(mt=>(mt+j)*u),omit:lt,empty:xt,mullion:{width:k(S.uprightWidth)*u,depth:k(S.depth)*u},panel:{thickness:k(S.panelDepth)*u,offset:-k(S.panelOffset)*u}})},vt=f.profile;if(Array.isArray(vt)&&vt.length>=3){const gt=vt.reduce((B,V,ct)=>{const dt=vt[(ct+1)%vt.length];return B+V[0]*dt[1]-dt[0]*V[1]},0)>0?1:-1,D=vt.length,at=vt.map((B,V)=>{const ct=vt[(V-1+D)%D],dt=vt[(V+1)%D],Rt=(fe,ue)=>{const Ge=ue[0]-fe[0],Dn=ue[1]-fe[1],ur=Math.hypot(Ge,Dn)||1,pr=gt*Dn/ur,mr=-gt*Ge/ur,gr=Math.abs(pr)>Math.abs(mr)?A:j;return{p:[fe[0]+pr*gr,fe[1]+mr*gr],d:[Ge,Dn]}},Q=Rt(ct,B),W=Rt(B,dt),bt=Q.d[0]*W.d[1]-Q.d[1]*W.d[0];if(Math.abs(bt)<1e-12)return[W.p[0],W.p[1]];const Jt=((W.p[0]-Q.p[0])*W.d[1]-(W.p[1]-Q.p[1])*W.d[0])/bt;return[Q.p[0]+Jt*Q.d[0],Q.p[1]+Jt*Q.d[1]]}),J=[];for(const[B,V]of at)J.push((y.from[0]+ht[0]*B)*u,(y.from[1]+ht[1]*B)*u,(b.at+U+j+V)*u);tt.Profile=JSON.stringify([J])}wt(E(h.id),tt)&&pt++}let Ft=0,Pt=0;for(const h of o){if(h.kind!=="stair"||h.params.of!=="stair")continue;Pt++;const f=Bt(h,"stair"),y=h.params.lookRef,b=typeof y=="string"?(nr=I.get(y))==null?void 0:nr.params:void 0,R=v.get(String((f==null?void 0:f.level)??h.params.level??""));if(!(f!=null&&f.start)||!f.end||!(Number(f.rise)>0)||!R||!b)continue;const S=P=>typeof P=="number"?P:Number(P)||0,k=Number(f.rise),A=Math.max(1,Math.ceil(k/S(b.maxRiser)-1e-6)),j=S(b.tread),nt=P=>[P[0]*u,P[1]*u],ht={family:String(y).split(":")[0],base:(R.at+S(h.params.base))*u,height:k*u,risers:A,tread:j*u,width:S(b.width)*u,sizes:{maxRiser:Math.ceil(k/A*1e3-1e-6)/1e3*u,minTread:j*u,waist:S(b.waist)*u,treadThickness:S(b.treadThickness)*u,riserThickness:S(b.riserThickness)*u,notchExtension:S(b.notchExtension)*u,notchThickness:S(b.notchThickness)*u}},Y=f.sketch;if(Y!=null&&Y.boundary&&Y.boundary.length>=4&&Y.risers&&Y.risers.length>=2){const P=Y.boundary,G=Y.risers[Y.risers.length-1],lt=B=>[(B[0][0]+B[1][0])/2,(B[0][1]+B[1][1])/2],xt=lt(G);let tt=1,vt=1/0;for(let B=1;B<P.length;B++){const V=lt([P[B],P[(B+1)%P.length]]),ct=Math.abs(Math.hypot(V[0]-xt[0],V[1]-xt[1])-j);ct<vt&&(vt=ct,tt=B)}const mt=(B,V)=>{const ct=[];for(let dt=B;dt!==V;dt=(dt+1)%P.length)ct.push([nt(P[dt]),nt(P[(dt+1)%P.length])]);return ct},gt=[...mt(1,tt),...mt((tt+1)%P.length,0)],D=Y.risers.map(([B,V])=>[nt(B),nt(V)]);nt(P[tt]),nt(P[(tt+1)%P.length]);const at=D.map(([B,V])=>[(B[0]+V[0])/2,(B[1]+V[1])/2]);ht.sketch={boundary:gt,risers:D,path:at};let J=1/0;for(let B=0;B+1<Y.risers.length;B++){const[V,ct]=Y.risers[B],[dt,Rt]=Y.risers[B+1],Q=[ct[0]-V[0],ct[1]-V[1]],W=[Rt[0]-dt[0],Rt[1]-dt[1]],bt=Math.hypot(Q[0],Q[1]),Jt=Math.hypot(W[0],W[1]);Math.abs((Q[0]*W[1]-Q[1]*W[0])/(bt*Jt))>.001||(J=Math.min(J,Math.abs(((dt[0]-V[0])*Q[1]-(dt[1]-V[1])*Q[0])/bt)))}Number.isFinite(J)&&(ht.tread=J*u,ht.sizes.minTread=J*u)}else ht.path=[nt([f.start[0],f.start[1]]),nt([f.end[0],f.end[1]])];const St=String(h.item.attrs.Name??""),U=St.replace(/ Run \d+$/,""),ot=[];for(const P of o){if(P.kind!=="extrusion"||U===St||!new RegExp(`^${U.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")} Landing \\d+$`).test(String(P.item.attrs.Name??"")))continue;const G=Bt(P,"extrusion"),lt=G==null?void 0:G.on,xt=(((rr=(sr=G==null?void 0:G.profile)==null?void 0:sr.outline)==null?void 0:rr.curves)??[]).flatMap(W=>W.from?[W.from]:[]),tt=Ct(P.params.lookRef),vt=v.get(String((G==null?void 0:G.level)??P.params.level??""));if(!(lt!=null&&lt.origin)||!lt.u||!lt.v||Math.abs(lt.v[2]??0)<.99||!xt.length||!tt||!vt)continue;const[mt,gt]=[Math.min(...xt.map(W=>W[0])),Math.max(...xt.map(W=>W[0]))],[D,at]=[Math.min(...xt.map(W=>W[1])),Math.max(...xt.map(W=>W[1]))],J=lt.origin,B=lt.u;let V=[B[1],-B[0]];const ct=[(f.start[0]+f.end[0])/2,(f.start[1]+f.end[1])/2];(ct[0]-J[0])*V[0]+(ct[1]-J[1])*V[1]<0&&(V=[-V[0],-V[1]]);const Rt=tt/u,Q=(W,bt)=>[(J[0]+B[0]*W+V[0]*bt)*u,(J[1]+B[1]*W+V[1]*bt)*u];ot.push({outline:[Q(mt,0),Q(gt,0),Q(gt,Rt),Q(mt,Rt)],top:(vt.at+S(P.params.base)+J[2]+at)*u,thickness:(at-D)*u})}ot.length&&(ht.landings=ot);const yt={CategoryId:ge.stairs,Type:((ir=Ze(h))==null?void 0:ir.type)??String(y),Level:R.name,Stairs:JSON.stringify(ht)};wt(E(h.id),yt)&&Ft++}const st={floor:0,foundation:0,roof:0,ceiling:0},rt={floor:0,foundation:0,roof:0,ceiling:0};for(const h of o){const f=h.params.of;if(h.kind!=="extrusion"||f!=="slab"&&f!=="roof"&&f!=="covering")continue;const y=f==="covering"?"ceiling":f==="roof"?"roof":Lr(h);if(y==="other")continue;st[y]++;const b=Bt(h,"extrusion"),R=typeof h.params.base=="number"?h.params.base:0,S=v.get(String((b==null?void 0:b.level)??h.params.level??"")),k=h.params.lookRef,A=U=>{if(!(U!=null&&U.length))return null;const ot=[];for(const yt of U){if(yt.kind!=="segment"||!yt.from)return null;ot.push(yt.from[0]*u,yt.from[1]*u,R*u)}return ot.length>=9?ot:null},j=A((ar=(or=b==null?void 0:b.profile)==null?void 0:or.outline)==null?void 0:ar.curves);if(typeof k!="string"||!S||!j)continue;const nt=[j],ht=y==="roof"?Vt(h):null;for(const U of((cr=b==null?void 0:b.profile)==null?void 0:cr.holes)??[]){const ot=A(U==null?void 0:U.curves);if(ot&&ht)for(let yt=0;yt+2<ot.length;yt+=3)ot[yt+2]=ht.zAt(ot[yt]/u,ot[yt+1]/u)*u;ot&&nt.push(ot)}const Y={CategoryId:y==="roof"?ge.roofs:y==="ceiling"?ge.ceilings:y==="foundation"?ge.structuralFoundations:ge.floors,Type:((lr=Ze(h))==null?void 0:lr.type)??k,Profile:JSON.stringify(nt),Level:S.name},St=Ct(k);if(St&&(Y["Type.Width"]=ft(St)),y==="roof"||y==="ceiling"){Y.BaseOffset=ft(R*u);const U=Number(h.params.drop??((hr=b==null?void 0:b.said)==null?void 0:hr.drop));if(y==="ceiling"&&Number.isFinite(U)&&St){const P=[...v.values()].filter(G=>G.at>S.at+1e-6).sort((G,lt)=>G.at-lt.at)[0];P&&(Y.BaseOffset=ft((P.at-U-St/u-S.at)*u))}const ot=b==null?void 0:b.slopes;if(y==="roof"&&Array.isArray(ot)&&ot.some(P=>typeof P=="number")){Y.Slopes=JSON.stringify(ot.map(G=>typeof G=="number"?G:null));const P=Math.max(...ot.filter(G=>typeof G=="number").map(G=>Math.abs(G)));St&&P>0&&(Y.BaseOffset=ft(R*u-St*Math.sqrt(1+P*P)))}const yt=y==="roof"?Vt(h):null;if(yt){const{A:P,n:G,u:lt,W:xt,ridge:tt,si:vt,ti:mt,tj:gt,L:D}=yt,at=(J,B)=>[(P[0]+G[0]*J)*u,(P[1]+G[1]*J)*u,B*u];Y.Extrusion=JSON.stringify({profile:[at(0,mt),at(tt,mt+vt*tt),at(xt,gt)],along:[lt[0],lt[1]],length:D*u}),delete Y.Slopes}}else St&&(Y.HeightOffset=ft(R*u+St));wt(E(h.id),Y)&&rt[y]++}let et=0,At=0;for(const h of o){if(h.kind!=="member"||h.params.of!=="column")continue;At++;const f=Bt(h,"member"),y=f==null?void 0:f.start;if(!y||y.length!==3)continue;const b=c?Br(h.params.lookRef):null;if(c&&!b||!b&&!d)continue;const R=b??{family:d.family,type:d.type},S=v.get(String((f==null?void 0:f.level)??""));wt(E(h.id),{...d&&!b?{CategoryId:d.categoryId}:{},Family:R.family,Type:R.type,...S?{Level:S.name}:{}},{position:[y[0]*u,y[1]*u,y[2]*u],rotationDeg:(Number((f==null?void 0:f.roll)??0)||0)*Pr})&&et++}let Ht=0,de=0,qe=0;for(const h of o){if(h.kind!=="familyInstance")continue;if(h.params.host){qe++;continue}if(de++,!m)continue;const f=Bt(h,"instance"),y=(dr=f==null?void 0:f.placement)==null?void 0:dr.at;if(!y||y.length!==3)continue;const b=Br(h.params.type);if(!b)continue;const R=(fr=f==null?void 0:f.placement)==null?void 0:fr.right,S=R?Math.atan2(R[1],R[0])*Pr:0;wt(E(h.id),{Family:b.family,Type:b.type},{position:[y[0]*u,y[1]*u,y[2]*u],rotationDeg:S})&&Ht++}const $e=(()=>{if(!i)return 0;const h=[];for(const y of Nt){const b=y.record.item.guid;if(!b||!i.elements.has(b))continue;const R=Bt(y.record,"run"),S=v.get(String((R==null?void 0:R.level)??y.record.params.level??""));if(!R||!S)continue;const k=sn(i,b);if(!k.length)continue;let A=1/0;for(const j of k)A=Math.min(A,j[2]);h.push(A-(S.at+(typeof R.base=="number"?R.base:0)))}h.sort((y,b)=>y-b);const f=h.length?h[Math.floor(h.length/2)]:0;return Math.abs(f)>.5?f:0})(),Hs=i?Ca(i,F,e.fileId):[];let pn=0;for(const h of Hs)wt(h.key,h.attrs,{position:[h.at[0]*u,h.at[1]*u,(h.at[2]-$e)*u],rotationDeg:h.rotationDeg,...h.host?{host:h.host}:{}})&&pn++;if(i)for(const h of $a(i,F,e.fileId))wt(h.key,{WallOpening:h.box.map((f,y)=>ft((y%3===2?f-$e:f)*u)).join(",")},{host:h.host});if(i)for(const h of ka(i,e.fileId))wt(h.key,{Room:"1",Name:h.name,Number:h.number,Height:ft(h.height*u)},{position:[h.at[0]*u,h.at[1]*u,(h.at[2]-$e)*u]});let jn=0;const Bi=new Set(["slab","roof","covering"]);for(const h of o){const f=h.params.of;(h.kind==="footing"||h.kind==="ramp"||h.kind==="stair"&&f!=="stair"||h.kind==="extrusion"&&!Bi.has(String(f))||h.kind==="extrusion"&&f==="slab"&&Lr(h)==="other"&&!/ Landing \d+$/.test(String(h.item.attrs.Name??""))||h.kind==="run"&&f!=="wall"&&f!=="curtainWall")&&jn++}let Ve=0;for(const[h,f]of C)!h.startsWith(`${e.fileId}:`)||F.has(h)||(O.remove(f),Ve++);if(O.length===0)throw new Ds(`Up to date: "${e.name}" holds ${z} element(s) this recipe already made, ${qe+jn} waiting on the applier, and nothing is left to remove.`);const ji=[Yt?`${Yt} level(s)`:"",It?`${It} wall(s)`:"",pt?`${pt} curtain wall(s)`:"",rt.floor?`${rt.floor} floor(s)`:"",rt.foundation?`${rt.foundation} foundation slab(s)`:"",rt.roof?`${rt.roof} roof(s)`:"",rt.ceiling?`${rt.ceiling} ceiling(s)`:"",Ft?`${Ft} stair(s)`:"",et?`${et} column(s)`:"",Ht?`${Ht} instance(s)`:"",pn?`${pn} family instance(s)`:"",ut?`${ut} changed`:"",Ve?`${Ve} gone`:""].filter(Boolean);return{title:`${s==="ifc"?"IFC":"Model"} to Revit: ${ji.join(", ")}`,verb:O.summary,targets:O.length,payload:new Blob([await O.build(t.opId)]),ruleTallies:[{read:v.size,written:Yt},{read:Nt.length+Gt,written:It},{read:jt,written:pt},{read:st.floor+st.foundation,written:rt.floor+rt.foundation},{read:st.roof,written:rt.roof},{read:st.ceiling,written:rt.ceiling},{read:Pt,written:Ft},{read:At,written:et},{read:de,written:Ht},{read:Hs.length,written:pn},{read:Ve,written:Ve},{read:qe+jn,written:0}]}}}const La={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}}},Pa=[{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"}],Mi=`
3
3
  ## How to use it
4
4
 
5
5
  In Revit, with the That Open plugin: **That Open > Select recipe**, pick this
@@ -47,13 +47,13 @@ are read and counted, and their rule row says so.
47
47
  Records are metres and radians, Z up; Revit gets feet and degrees. Types are
48
48
  matched exactly by name; Revit refuses the whole apply when a loadable type is
49
49
  missing (system types are created from their width instead).
50
- `,Ds={name:"frag-to-revit",title:"Platform model to Revit",description:"Builds in Revit the platform records of a .frag: levels, walls, curtain walls, floors, roofs, ceilings, stairs, columns, instances.",to:"revit",inputs:["frag-model"],source:{kind:"project-file",extensions:["frag"]},settingsSchema:$a,rules:xa,doc:Ci,run:Oi("frag")},$i={...Ds,name:"ifc-to-revit",title:"IFC to Revit",description:"Builds an IFC of the project in Revit as native elements: levels, walls, floors, roofs, stairs, curtain walls, columns, instances.",inputs:["ifc-model"],source:{kind:"project-file",extensions:["ifc"]},doc:`
50
+ `,qs={name:"frag-to-revit",title:"Platform model to Revit",description:"Builds in Revit the platform records of a .frag: levels, walls, curtain walls, floors, roofs, ceilings, stairs, columns, instances.",to:"revit",inputs:["frag-model"],source:{kind:"project-file",extensions:["frag"]},settingsSchema:La,rules:Pa,doc:Mi,run:ki("frag")},Ni={...qs,name:"ifc-to-revit",title:"IFC to Revit",description:"Builds an IFC of the project in Revit as native elements: levels, walls, floors, roofs, stairs, curtain walls, columns, instances.",inputs:["ifc-model"],source:{kind:"project-file",extensions:["ifc"]},doc:`
51
51
  ## Point it at the IFC
52
52
 
53
53
  It reads the IFC file itself, the version uploaded last. Its first step
54
54
  converts it into the platform's records - what each element is, not only its
55
55
  shape - and Revit gets those. Nothing has to be prepared before.
56
- `+Ci,run:Oi("ifc")},Ra={millimeters:.001,millimetres:.001,mm:.001,centimeters:.01,centimetres:.01,cm:.01,meters:1,metres:1,m:1,inches:.0254,in:.0254,feet:.3048,ft:.3048},xi="rhino-to-revit",ka=`recipe:${xi}`;function Ma(s){const t=(s.attrs.Position??"").split(",").map(e=>Number(e.trim()));return t.length!==3||t.some(e=>!Number.isFinite(e))?null:[t[0],t[1],t[2]]}const Ri={name:xi,title:"Rhino to Revit",description:"Places in Revit an instance of a chosen type at each placed object of a Rhino layer.",to:"revit",inputs:["rhino-model"],source:{kind:"project-file",extensions:["frag"]},settingsSchema:{type:"object",properties:{layer:{type:"string",title:"Rhino layer","x-existing":{of:"layer",from:"source"}},instanceType:{type:"object",title:"Revit type","x-existing":{of:"family-type",from:"target"}}},required:["layer","instanceType"]},rules:[{reads:"Objects on the chosen layer with no instance yet",writes:"A new instance of the chosen type at each"},{reads:"Objects whose instance already exists",writes:"That instance moved to where the object is now"},{reads:"Instances whose object is gone from Rhino",writes:"That instance removed"},{reads:"Everything on other layers",writes:"Nothing"}],doc:`
56
+ `+Mi,run:ki("ifc")},Ba={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},Fi="rhino-to-revit",ja=`recipe:${Fi}`;function Da(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 Li={name:Fi,title:"Rhino to Revit",description:"Places in Revit an instance of a chosen type at each placed object of a Rhino layer.",to:"revit",inputs:["rhino-model"],source:{kind:"project-file",extensions:["frag"]},settingsSchema:{type:"object",properties:{layer:{type:"string",title:"Rhino layer","x-existing":{of:"layer",from:"source"}},instanceType:{type:"object",title:"Revit type","x-existing":{of:"family-type",from:"target"}}},required:["layer","instanceType"]},rules:[{reads:"Objects on the chosen layer with no instance yet",writes:"A new instance of the chosen type at each"},{reads:"Objects whose instance already exists",writes:"That instance moved to where the object is now"},{reads:"Instances whose object is gone from Rhino",writes:"That instance removed"},{reads:"Everything on other layers",writes:"Nothing"}],doc:`
57
57
  ## What it does
58
58
 
59
59
  It reads a model published from Rhino and places in Revit instances of one
@@ -80,5 +80,5 @@ it. What it made is remembered with the model's That Open data.
80
80
  Where an object becomes an instance, Revit decides the level: the nearest one
81
81
  at or below the point. For a level-based family the level wins over the
82
82
  point's height.
83
- `,async run(s){var $;const{picked:t,contents:e}=await Ls(s,s.input),{layer:n,instanceType:r}=s.settings;if(!n||!r)throw new Error("Choose the layer and the Revit type.");const i=($=e.metadata)==null?void 0:$.data,o=i==null?void 0:i.units,a=typeof o=="string"?Ra[o.trim().toLowerCase()]:void 0;if(!a)throw new Error(`"${t.name}" does not say what units its data is in${o?` ("${String(o)}" is not one this recipe knows)`:""}, so nothing can be converted from it.`);const l=String((i==null?void 0:i.axes)??"z-up").toLowerCase();if(l!=="z-up")throw new Error(`"${t.name}" declares its data as "${l}"; this recipe only converts Z up.`);const d=a*Ne,c=Fs(s),m=new Nn({project:s.projectId,document:s.target.docId??"",baseCommit:s.target.version??0,author:ka});let w=0,v=0,I=0;const _=new Set,L=[];for(const E of e.items){if(!E.guid||Object.keys(E.attrs).length===0)continue;if((E.attrs.Layer??"")!==n){I++;continue}const N=Ma(E);if(!N)continue;_.add(E.guid);const z=[N[0]*d,N[1]*d,N[2]*d],ut=c.get(E.guid);ut?L.push({instance:ut,object:E.guid,position:z}):(m.add({CategoryId:r.categoryId,Family:r.family,Type:r.type},{position:z,source:E.guid}),w++)}for(const E of L)m.set(E.instance,{},{position:E.position,source:E.object}),v++;let C=0;for(const[E,N]of c)_.has(E)||(m.remove(N),C++);const O=w+v+C;if(O===0)throw new Bs(`Nothing to write: layer "${n}" of "${t.name}" has no placed object, and nothing of this recipe is left to remove.`);return{title:`From Rhino: ${[w?`${w} new`:"",v?`${v} moved`:"",C?`${C} gone`:""].filter(Boolean).join(", ")}`,verb:m.summary,targets:O,payload:new Blob([await m.build(s.opId)]),ruleTallies:[{read:w,written:w},{read:v,written:v},{read:C,written:C},{read:I,written:0}]}}},ki=[Ri,$i,Ds];function Na(s){for(const t of ki)s.recipes.register(t)}const Fa={MAX_FIELDS:200,MAX_KEY_LENGTH:50,MAX_VALUE_LENGTH:50},La={uuid:"a3f82c1d-5b74-4e9a-bc30-d7e12f894a61"},Pa={uuid:"2c9f4e8d-3a1b-4c5e-9d7f-0a2b6c8e1d3f"},Ba={uuid:"b0b5e2a2-0b3a-4a6b-8b1c-0b1c4a6b8b1c"},ja={uuid:"d8f3a1c2-6b4e-4f9a-8c1d-2e7b5a9f3c60"},Da={uuid:"3f9c1a7e-6b2d-4e18-9a5c-7d0e2f4b6c81"},Ua={uuid:"2c4ae432-fc24-43e9-9783-0c960c674e96"},qa={uuid:"6f3a9c2e-8b1d-4e6a-9c3f-1d7b5a8e2c4f"},Va={uuid:"69af63aa-19ba-4fc7-b17b-75647bac1d76"},Ga={uuid:"234f1416-528d-452a-9cc9-a16c5239b2eb"};exports.CDEManager=La;exports.ChannelClient=Ii;exports.ChannelRoom=js;exports.ClashesManager=Pa;exports.CollabRoom=bi;exports.DOCUMENT_FILE=In;exports.DOCUMENT_SCHEMA=en;exports.DOCUMENT_TYPES=Rs;exports.DocumentDrafts=oi;exports.EngineServicesClient=Rn;exports.ExternalRoom=Ti;exports.FileList=Ba;exports.FlowDoc=rs;exports.GISManager=ja;exports.GitHistoryManager=Da;exports.HelloWorld=Ua;exports.METADATA_LIMITS=Fa;exports.OP_SCHEMA=Ms;exports.OperationBuilder=Nn;exports.PROJECT_RECIPE_SCHEMA=Ps;exports.PlatformClient=Es;exports.ProjectDocuments=ks;exports.ProjectHistory=Cs;exports.ProjectManager=qa;exports.ProjectRecipes=gi;exports.RECIPE_NAME=pi;exports.RecipeKit=ui;exports.Recipes=yi;exports.RequestError=Ln;exports.SELF_VIEWING_FORMATS=ei;exports.STORAGE_BATCH_MAX=fs;exports.StaleHistoryError=es;exports.TopicsManager=Va;exports.UIManager=Ga;exports.UpToDate=Bs;exports.builtinRecipes=ki;exports.compileRecipe=ds;exports.describeChanges=ra;exports.documentTypeOf=os;exports.fragToRevit=Ds;exports.ifcToRevit=$i;exports.latestVersions=wi;exports.mintGuid=xs;exports.orderByGraph=$s;exports.readFrag=Fn;exports.registerBuiltinRecipes=Na;exports.rhinoToRevit=Ri;exports.windowTransport=vi;
83
+ `,async run(s){var $;const{picked:t,contents:e}=await Bs(s,s.input),{layer:n,instanceType:r}=s.settings;if(!n||!r)throw new Error("Choose the layer and the Revit type.");const i=($=e.metadata)==null?void 0:$.data,o=i==null?void 0:i.units,a=typeof o=="string"?Ba[o.trim().toLowerCase()]:void 0;if(!a)throw new Error(`"${t.name}" does not say what units its data is in${o?` ("${String(o)}" is not one this recipe knows)`:""}, so nothing can be converted from it.`);const l=String((i==null?void 0:i.axes)??"z-up").toLowerCase();if(l!=="z-up")throw new Error(`"${t.name}" declares its data as "${l}"; this recipe only converts Z up.`);const d=a*Fe,c=Ps(s),m=new Ln({project:s.projectId,document:s.target.docId??"",baseCommit:s.target.version??0,author:ja});let w=0,v=0,I=0;const _=new Set,L=[];for(const E of e.items){if(!E.guid||Object.keys(E.attrs).length===0)continue;if((E.attrs.Layer??"")!==n){I++;continue}const F=Da(E);if(!F)continue;_.add(E.guid);const z=[F[0]*d,F[1]*d,F[2]*d],ut=c.get(E.guid);ut?L.push({instance:ut,object:E.guid,position:z}):(m.add({CategoryId:r.categoryId,Family:r.family,Type:r.type},{position:z,source:E.guid}),w++)}for(const E of L)m.set(E.instance,{},{position:E.position,source:E.object}),v++;let C=0;for(const[E,F]of c)_.has(E)||(m.remove(F),C++);const O=w+v+C;if(O===0)throw new Ds(`Nothing to write: layer "${n}" of "${t.name}" has no placed object, and nothing of this recipe is left to remove.`);return{title:`From Rhino: ${[w?`${w} new`:"",v?`${v} moved`:"",C?`${C} gone`:""].filter(Boolean).join(", ")}`,verb:m.summary,targets:O,payload:new Blob([await m.build(s.opId)]),ruleTallies:[{read:w,written:w},{read:v,written:v},{read:C,written:C},{read:I,written:0}]}}},Pi=[Li,Ni,qs];function Ua(s){for(const t of Pi)s.recipes.register(t)}const qa={MAX_FIELDS:200,MAX_KEY_LENGTH:50,MAX_VALUE_LENGTH:50},Va={uuid:"a3f82c1d-5b74-4e9a-bc30-d7e12f894a61"},Ga={uuid:"2c9f4e8d-3a1b-4c5e-9d7f-0a2b6c8e1d3f"},Ha={uuid:"b0b5e2a2-0b3a-4a6b-8b1c-0b1c4a6b8b1c"},Ja={uuid:"d8f3a1c2-6b4e-4f9a-8c1d-2e7b5a9f3c60"},Wa={uuid:"3f9c1a7e-6b2d-4e18-9a5c-7d0e2f4b6c81"},za={uuid:"2c4ae432-fc24-43e9-9783-0c960c674e96"},Ya={uuid:"6f3a9c2e-8b1d-4e6a-9c3f-1d7b5a8e2c4f"},Ka={uuid:"69af63aa-19ba-4fc7-b17b-75647bac1d76"},Xa={uuid:"234f1416-528d-452a-9cc9-a16c5239b2eb"};exports.CDEManager=Va;exports.ChannelClient=Ci;exports.ChannelRoom=Us;exports.ClashesManager=Ga;exports.CollabRoom=_i;exports.DOCUMENT_FILE=Sn;exports.DOCUMENT_SCHEMA=nn;exports.DOCUMENT_TYPES=Ms;exports.DocumentDrafts=di;exports.EngineServicesClient=Mn;exports.ExternalRoom=Ai;exports.FileList=Ha;exports.FlowDoc=os;exports.GISManager=Ja;exports.GitHistoryManager=Wa;exports.HelloWorld=za;exports.METADATA_LIMITS=qa;exports.OP_SCHEMA=Fs;exports.OperationBuilder=Ln;exports.PROJECT_RECIPE_SCHEMA=js;exports.PlatformClient=Ss;exports.ProjectDocuments=Ns;exports.ProjectHistory=xs;exports.ProjectManager=Ya;exports.ProjectRecipes=Ti;exports.RECIPE_NAME=vi;exports.RecipeKit=wi;exports.Recipes=Ei;exports.RequestError=Bn;exports.SELF_VIEWING_FORMATS=ii;exports.STORAGE_BATCH_MAX=ps;exports.StaleHistoryError=ss;exports.TopicsManager=Ka;exports.UIManager=Xa;exports.UpToDate=Ds;exports.builtinRecipes=Pi;exports.compileRecipe=us;exports.describeChanges=ca;exports.documentTypeOf=cs;exports.fragToRevit=qs;exports.ifcToRevit=Ni;exports.latestVersions=Ii;exports.mintGuid=ks;exports.orderByGraph=Rs;exports.readFrag=Pn;exports.registerBuiltinRecipes=Ua;exports.rhinoToRevit=Li;exports.stampOf=kn;exports.windowTransport=Si;
84
84
  //# sourceMappingURL=index.cjs.js.map