@thatopen/services 0.31.2 → 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 $i=Object.create;var Ln=Object.defineProperty;var Ri=Object.getOwnPropertyDescriptor;var ki=Object.getOwnPropertyNames;var Ni=Object.getPrototypeOf,Mi=Object.prototype.hasOwnProperty;var dr=s=>{throw TypeError(s)};var Fi=(s,t,e)=>t in s?Ln(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e;var Li=(s,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of ki(t))!Mi.call(s,r)&&r!==e&&Ln(s,r,{get:()=>t[r],enumerable:!(n=Ri(t,r))||n.enumerable});return s};var fn=(s,t,e)=>(e=s!=null?$i(Ni(s)):{},Li(t||!s||!s.__esModule?Ln(e,"default",{value:s,enumerable:!0}):e,s));var Rt=(s,t,e)=>Fi(s,typeof t!="symbol"?t+"":t,e),Pn=(s,t,e)=>t.has(s)||dr("Cannot "+e);var g=(s,t,e)=>(Pn(s,t,"read from private field"),e?e.call(s):t.get(s)),K=(s,t,e)=>t.has(s)?dr("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(s):t.set(s,e),it=(s,t,e,n)=>(Pn(s,t,"write to private field"),n?n.call(s,e):t.set(s,e),e),m=(s,t,e)=>(Pn(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 gn=Object.create(null);Object.keys(ne).forEach(s=>{gn[ne[s]]=s});const Jn={type:"error",data:"parser error"},Rr=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",kr=typeof ArrayBuffer=="function",Nr=s=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(s):s&&s.buffer instanceof ArrayBuffer,vs=({type:s,data:t},e,n)=>Rr&&t instanceof Blob?e?n(t):fr(t,n):kr&&(t instanceof ArrayBuffer||Nr(t))?e?n(t):fr(new Blob([t]),n):n(ne[s]+(t||"")),fr=(s,t)=>{const e=new FileReader;return e.onload=function(){const n=e.result.split(",")[1];t("b"+(n||""))},e.readAsDataURL(s)};function ur(s){return s instanceof Uint8Array?s:s instanceof ArrayBuffer?new Uint8Array(s):new Uint8Array(s.buffer,s.byteOffset,s.byteLength)}let Bn;function Pi(s,t){if(Rr&&s.data instanceof Blob)return s.data.arrayBuffer().then(ur).then(t);if(kr&&(s.data instanceof ArrayBuffer||Nr(s.data)))return t(ur(s.data));vs(s,!1,e=>{Bn||(Bn=new TextEncoder),t(Bn.encode(e))})}const pr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",We=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let s=0;s<pr.length;s++)We[pr.charCodeAt(s)]=s;const Bi=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=We[s.charCodeAt(n)],o=We[s.charCodeAt(n+1)],a=We[s.charCodeAt(n+2)],l=We[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},Di=typeof ArrayBuffer=="function",bs=(s,t)=>{if(typeof s!="string")return{type:"message",data:Mr(s,t)};const e=s.charAt(0);return e==="b"?{type:"message",data:ji(s.substring(1),t)}:gn[e]?s.length>1?{type:gn[e],data:s.substring(1)}:{type:gn[e]}:Jn},ji=(s,t)=>{if(Di){const e=Bi(s);return Mr(e,t)}else return{base64:!0,data:s}},Mr=(s,t)=>{switch(t){case"blob":return s instanceof Blob?s:new Blob([s]);case"arraybuffer":default:return s instanceof ArrayBuffer?s:s.buffer}},Fr="",Ui=(s,t)=>{const e=s.length,n=new Array(e);let r=0;s.forEach((i,o)=>{vs(i,!1,a=>{n[o]=a,++r===e&&t(n.join(Fr))})})},qi=(s,t)=>{const e=s.split(Fr),n=[];for(let r=0;r<e.length;r++){const i=bs(e[r],t);if(n.push(i),i.type==="error")break}return n};function Vi(){return new TransformStream({transform(s,t){Pi(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 Dn;function un(s){return s.reduce((t,e)=>t+e.length,0)}function pn(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 Gi(s,t){Dn||(Dn=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(un(e)<1)break;const l=pn(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(un(e)<2)break;const l=pn(e,2);r=new DataView(l.buffer,l.byteOffset,l.length).getUint16(0),n=3}else if(n===2){if(un(e)<8)break;const l=pn(e,8),d=new DataView(l.buffer,l.byteOffset,l.length),c=d.getUint32(0);if(c>Math.pow(2,21)-1){a.enqueue(Jn);break}r=c*Math.pow(2,32)+d.getUint32(4),n=3}else{if(un(e)<r)break;const l=pn(e,r);a.enqueue(bs(i?l:Dn.decode(l),t)),n=0}if(r===0||r>s){a.enqueue(Jn);break}}}})}const Lr=4;function _t(s){if(s)return Hi(s)}function Hi(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 xn=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")(),Ji="arraybuffer";function Pr(s,...t){return t.reduce((e,n)=>(s.hasOwnProperty(n)&&(e[n]=s[n]),e),{})}const Wi=qt.setTimeout,zi=qt.clearTimeout;function $n(s,t){t.useNativeTimers?(s.setTimeoutFn=Wi.bind(qt),s.clearTimeoutFn=zi.bind(qt)):(s.setTimeoutFn=qt.setTimeout.bind(qt),s.clearTimeoutFn=qt.clearTimeout.bind(qt))}const Yi=1.33;function Ki(s){return typeof s=="string"?Xi(s):Math.ceil((s.byteLength||s.size)*Yi)}function Xi(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 Br(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function Qi(s){let t="";for(let e in s)s.hasOwnProperty(e)&&(t.length&&(t+="&"),t+=encodeURIComponent(e)+"="+encodeURIComponent(s[e]));return t}function Zi(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 to extends Error{constructor(t,e,n){super(t),this.description=e,this.context=n,this.type="TransportError"}}class Ts extends _t{constructor(t){super(),this.writable=!1,$n(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 to(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=bs(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=Qi(t);return e.length?"?"+e:""}}class eo extends Ts{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,Ui(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]=Br()),!this.supportsBinary&&!e.sid&&(e.b64=1),this.createUri(t,e)}}let Dr=!1;try{Dr=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const no=Dr;function so(){}class ro extends eo{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,$n(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=Pr(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=so,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",mr);else if(typeof addEventListener=="function"){const s="onpagehide"in qt?"pagehide":"unload";addEventListener(s,mr,!1)}}function mr(){for(let s in ee.requests)ee.requests.hasOwnProperty(s)&&ee.requests[s].abort()}const io=function(){const s=jr({xdomain:!1});return s&&s.responseType!==null}();class oo extends ro{constructor(t){super(t);const e=t&&t.forceBase64;this.supportsBinary=io&&!e}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new ee(jr,this.uri(),t)}}function jr(s){const t=s.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!t||no))return new XMLHttpRequest}catch{}if(!t)try{return new qt[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const Ur=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class ao extends Ts{get name(){return"websocket"}doOpen(){const t=this.uri(),e=this.opts.protocols,n=Ur?{}:Pr(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;vs(n,this.supportsBinary,i=>{try{this.doWrite(n,i)}catch{}r&&xn(()=>{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]=Br()),this.supportsBinary||(e.b64=1),this.createUri(t,e)}}const jn=qt.WebSocket||qt.MozWebSocket;class co extends ao{createSocket(t,e,n){return Ur?new jn(t,e,n):e?new jn(t,e):new jn(t)}doWrite(t,e){this.ws.send(e)}}class lo extends Ts{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=Gi(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=t.readable.pipeThrough(e).getReader(),r=Vi();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&&xn(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this._transport)===null||t===void 0||t.close()}}const ho={websocket:co,webtransport:lo,polling:oo},fo=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,uo=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Wn(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=fo.exec(s||""),i={},o=14;for(;o--;)i[uo[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=po(i,i.path),i.queryKey=mo(i,i.query),i}function po(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 mo(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",yn=[];zn&&addEventListener("offline",()=>{yn.forEach(s=>s())},!1);class Se extends _t{constructor(t,e){if(super(),this.binaryType=Ji,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=Wn(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=Wn(e.host).host);$n(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=Zi(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"})},yn.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(t){const e=Object.assign({},this.opts.query);e.EIO=Lr,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+=Ki(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,xn(()=>{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=yn.indexOf(this._offlineEventListener);n!==-1&&yn.splice(n,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,e),this.writeBuffer=[],this._prevBufferLen=0}}}Se.protocol=Lr;class go 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",p=>{if(!n)if(p.type==="pong"&&p.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=p=>{const w=new Error("probe error: "+p);w.transport=e.name,i(),this.emitReserved("upgradeError",w)};function a(){o("transport closed")}function l(){o("socket closed")}function d(p){e&&p.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 yo=class extends go{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=>ho[i]).filter(i=>!!i)),super(n?r:t,r)}};function wo(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=Wn(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 vo=typeof ArrayBuffer=="function",bo=s=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(s):s.buffer instanceof ArrayBuffer,qr=Object.prototype.toString,To=typeof Blob=="function"||typeof Blob<"u"&&qr.call(Blob)==="[object BlobConstructor]",Eo=typeof File=="function"||typeof File<"u"&&qr.call(File)==="[object FileConstructor]";function Es(s){return vo&&(s instanceof ArrayBuffer||bo(s))||To&&s instanceof Blob||Eo&&s instanceof File}function wn(s,t){if(!s||typeof s!="object")return!1;if(Array.isArray(s)){for(let e=0,n=s.length;e<n;e++)if(wn(s[e]))return!0;return!1}if(Es(s))return!0;if(s.toJSON&&typeof s.toJSON=="function"&&arguments.length===1)return wn(s.toJSON(),!0);for(const e in s)if(Object.prototype.hasOwnProperty.call(s,e)&&wn(s[e]))return!0;return!1}function Io(s){const t=[],e=s.data,n=s;return n.data=Yn(e,t),n.attachments=t.length,{packet:n,buffers:t}}function Yn(s,t){if(!s)return s;if(Es(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]=Yn(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]=Yn(s[n],t));return e}return s}function So(s,t){return s.data=Kn(s.data,t),delete s.attachments,s}function Kn(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]=Kn(s[e],t);else if(typeof s=="object")for(const e in s)Object.prototype.hasOwnProperty.call(s,e)&&(s[e]=Kn(s[e],t));return s}const _o=["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 Ao{constructor(t){this.replacer=t}encode(t){return(t.type===X.EVENT||t.type===X.ACK)&&wn(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=Io(t),n=this.encodeAsString(e.packet),r=e.buffers;return r.unshift(n),r}}class Is 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 Oo(e),e.attachments===0&&super.emitReserved("decoded",e)):super.emitReserved("decoded",e)}else if(Es(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(!Co(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(Is.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 gr(e);case X.DISCONNECT:return e===void 0;case X.CONNECT_ERROR:return typeof e=="string"||gr(e);case X.EVENT:case X.BINARY_EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&_o.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 Oo{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=So(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const Co=Number.isInteger||function(s){return typeof s=="number"&&isFinite(s)&&Math.floor(s)===s};function gr(s){return Object.prototype.toString.call(s)==="[object Object]"}const xo=Object.freeze(Object.defineProperty({__proto__:null,Decoder:Is,Encoder:Ao,get PacketType(){return X}},Symbol.toStringTag,{value:"Module"}));function zt(s,t,e){return s.on(t,e),function(){s.off(t,e)}}const $o=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Vr 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($o.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++,p=e.pop();this._registerAckCallback(c,p),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 je(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}je.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};je.prototype.reset=function(){this.attempts=0};je.prototype.setMin=function(s){this.ms=s};je.prototype.setMax=function(s){this.max=s};je.prototype.setJitter=function(s){this.jitter=s};class Xn 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,$n(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 je({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||xo;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 yo(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){xn(()=>{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 Vr(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 Xe(s,t){typeof s=="object"&&(t=s,s=void 0),t=t||{};const e=wo(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 Xn(n,t):(Ge[r]||(Ge[r]=new Xn(n,t)),l=Ge[r]),e.query&&!t.query&&(t.query=e.queryKey),l.socket(e.path,t)}Object.assign(Xe,{Manager:Xn,Socket:Vr,io:Xe,connect:Xe});class Qn 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 yr="bimterop",Zn="revitflow_history.json",Gr="revitflow_model.frag",Hr="revitflow_",Ro="bimterop-locks-anchor";function ko(s,t){return s.filter(e=>String(e.parentId??"")===t)}function No(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,en,nn,ts;class Ss{constructor(t,e){K(this,nn);K(this,Wt);K(this,Ae,new Map);K(this,oe);K(this,en,0);this.client=t,this.projectId=e}async docs(){const t=await m(this,nn,ts).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(p=>String(p.name??"")),d=l.find(p=>p===Gr)??l.find(p=>p.endsWith(".frag")&&!p.startsWith(Hr)),c=l.includes(Zn)||!!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 es(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 es(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,en)>3e4)&&(it(this,en,Date.now()),it(this,oe,this.client.listFolders({parentFolderId:t,projectId:this.projectId}).then(n=>ko(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 m(this,nn,ts).call(this);if(e)return e;if(!t)return;const n=await this.client.createFolder(yr,void 0,this.projectId);return it(this,Wt,Zt(n)),g(this,Wt)}}Wt=new WeakMap,Ae=new WeakMap,oe=new WeakMap,en=new WeakMap,nn=new WeakSet,ts=async function(){if(g(this,Wt))return g(this,Wt);const e=(await this.client.listFolders({projectId:this.projectId})).find(n=>String(n.name??"")===yr&&!n.parentId);return e&&it(this,Wt,Zt(e)),g(this,Wt)};var Xt,N,ie,Re,ye,Qt,sn,ns,vn,we,Jr,bn,Wr,zr,Yr;class es{constructor(t,e,n,r,i){K(this,N);K(this,Xt);K(this,Qt);K(this,sn,0);this.client=t,this.project=e,this.source=n,this.docId=r,it(this,Xt,i)}async timeline(){const t=await m(this,N,bn).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 m(this,N,we).call(this);if(!t)throw new Error(`Document ${this.source}-${this.docId} has no model file yet.`);return await(await this.client.downloadFile(t.id)).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 m(this,N,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(p=>p.type==="delete").map(p=>p.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 m(this,N,ye).call(this,!1)}async descriptor(){return await g(this,N,ie).descriptor(await m(this,N,ye).call(this,!1))}async view(t){const e=await m(this,N,ye).call(this,!1),n=await g(this,N,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 m(this,N,we).call(this);return r?{fileId:r.id,format:"frag"}:null}async addView(t){const e=await m(this,N,ye).call(this,!0);if(await g(this,N,ie).descriptor(e)){await g(this,N,ie).addView(e,t);return}const r=await m(this,N,we).call(this);await g(this,N,ie).setDescriptor(e,{name:(r==null?void 0:r.name.replace(/\.frag$/,""))??g(this,N,Re),views:[t]})}async ensureDescriptor(){const t=await m(this,N,ye).call(this,!1),e=await g(this,N,ie).descriptor(t);if(e)return e;const n=await m(this,N,we).call(this);if(!n)return null;const r={name:n.name.replace(/\.frag$/,""),views:[{fileId:n.id,format:"frag"}]};return await g(this,N,ie).setDescriptor(t,r),await g(this,N,ie).descriptor(t)}async ownership(){const t=await m(this,N,vn).call(this,Ro);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 m(this,N,ye).call(this,!0);let n=await m(this,N,bn).call(this)??{model:this.docId,commits:[]};const r=wr(n.commits);if(t.expectedLatestGuid!==void 0&&(r==null?void 0:r.guid)!==t.expectedLatestGuid)throw new Qn(t.expectedLatestGuid,r==null?void 0:r.guid);const i={guid:As(),...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:Mo(t.changes)};if(t.model&&(await m(this,N,Yr).call(this,e,t.model),i.full=!0),t.delta){const l=await m(this,N,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=No(d)}const o=await m(this,N,bn).call(this);if(o){n=o;const l=wr(n.commits);if(t.expectedLatestGuid!==void 0&&(l==null?void 0:l.guid)!==t.expectedLatestGuid)throw new Qn(t.expectedLatestGuid,l==null?void 0:l.guid);l&&!i.parents&&(i.parents=[l.guid])}return n.commits.push(i),await m(this,N,Wr).call(this,e,Zn,n),i}}Xt=new WeakMap,N=new WeakSet,ie=function(){return new Cs(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,N,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,N,Re)} does not exist in this project.`);const i=await this.client.createFolder(g(this,N,Re),e,this.project.projectId);return this.project.forgetFolders(),it(this,Xt,Zt(i)),g(this,Xt)},Qt=new WeakMap,sn=new WeakMap,ns=async function(){return(!g(this,Qt)||Date.now()-g(this,sn)>5e3)&&(it(this,sn,Date.now()),it(this,Qt,(async()=>{const t=await m(this,N,ye).call(this,!1);return(await this.client.listFiles({folderId:t})).map(n=>({id:Zt(n),name:String(n.name??"")}))})()),g(this,Qt).catch(()=>{it(this,Qt,void 0)})),g(this,Qt)},vn=async function(t){try{return(await m(this,N,ns).call(this)).find(e=>e.name===t)}catch{return}},we=async function(){try{const t=await m(this,N,ns).call(this);return t.find(e=>e.name===Gr)??t.find(e=>e.name.endsWith(".frag")&&!e.name.startsWith(Hr))}catch{return}},Jr=async function(t){const e=await m(this,N,vn).call(this,t);if(!e)return;const r=await(await this.client.downloadFile(e.id)).text();if(r.trim())return JSON.parse(r)},bn=function(){return m(this,N,Jr).call(this,Zn)},Wr=async function(t,e,n){const r=new Blob([JSON.stringify(n)],{type:"application/json"}),i=await m(this,N,vn).call(this,e);return i?(await this.client.updateFile(i.id,{file:r,versionTag:await this.client.nextVersionTag(i.id)}),i):await m(this,N,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}},Yr=async function(t,e){const n=await m(this,N,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,N,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 Mo(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 p=e.get(c)??[];p.push(d),e.set(c,p)}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 p=c.length-1;p>=0;p--)o.push(c[p])}for(const d of s)a.has(d.guid)||i.push(d);return i.forEach((d,c)=>d.ordinal=c),i}function wr(s){const t=_s(s);return t[t.length-1]}function As(){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 Os={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"}},Fo={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 ss(s){var e;if(s.type&&s.type in Os)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?Fo[n.toLowerCase()]:void 0;if(r)return r}return"generic"}const Ze="thatopen/document@1",Tn="document.json",Kr=["pdf","txt","md","json","csv","tsv","frag"];function se(s){return String(s._id??s.id??"")}var Nt,Xr,rs,Qr,Zr,En;class Cs{constructor(t,e){K(this,Nt);this.client=t,this.projectId=e}async list(t){const e=await m(this,Nt,Xr).call(this),n=t==null?void 0:t.types;return n!=null&&n.length?e.filter(r=>n.includes(ss(r.descriptor))):e}async fromFile(t,e){const n=await this.client.getFile(t),r=String(n.name??""),i=Un(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 m(this,Nt,Qr).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:Un(String(v.name??""),v.fileExtension)})}catch{}((e==null?void 0:e.selfView)??Kr.includes(i))&&d.push({fileId:t,format:i});const w={schema:Ze,name:o,native:{fileId:t,format:i},views:d};return w.type=(e==null?void 0:e.type)??ss(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 Ss(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??Un(e.name,void 0)},changes:[]})}async descriptor(t){const e=await m(this,Nt,En).call(this,t);return e?m(this,Nt,rs).call(this,e.id):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:Ze,views:e.views??[]},r=new Blob([JSON.stringify(n)],{type:"application/json"}),i=await m(this,Nt,En).call(this,t);if(i){await this.client.updateFile(i.id,{file:r,versionTag:await this.client.nextVersionTag(i.id)});return}await this.client.createFile({file:r,name:Tn,versionTag:"v1",parentFolderId:t,projectId:this.projectId})}drafts(t){return new ti(this.client,()=>m(this,Nt,En).call(this,t))}}Nt=new WeakSet,Xr=async function(){const e=(await this.client.listFiles({projectId:this.projectId})).filter(r=>String(r.name??"")===Tn);return(await Promise.all(e.map(async r=>{const i=r,o=String(i.folderId??i.parentFolderId??"");if(!o)return null;const a=await m(this,Nt,rs).call(this,se(r));return a?{folderId:o,descriptor:a}:null}))).filter(r=>r!==null)},rs=async function(t){const n=await(await this.client.downloadFile(t)).text();if(!n.trim())return null;let r;try{r=JSON.parse(n)}catch{return null}return Do(r)},Qr=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 m(this,Nt,Zr).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},Zr=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{}},En=async function(t){const n=(await this.client.listFiles({folderId:t})).find(r=>String(r.name??"")===Tn);return n?{id:se(n)}:void 0};const is="draft:",ke="TODRAFT1";var te,ze,os;class ti{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 m(this,te,ze).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 m(this,te,ze).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 Bo(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=Lo(e.userId),i=(await m(this,te,ze).call(this,n.id)).filter(l=>l.userId===e.userId),a=(await this.client.createHiddenFile(await Po(t,e.meta??{}),n.id,r)).hiddenFileId;if(!a)throw new Error("The draft upload answered without a hiddenFileId.");return await m(this,te,os).call(this,i.map(l=>l.hiddenId)),{userId:e.userId,savedAt:vr(a)}}async delete(t){const e=await this.holder();if(!e)return;const n=(await m(this,te,ze).call(this,e.id)).filter(r=>r.userId===t.userId);await m(this,te,os).call(this,n.map(r=>r.hiddenId))}}te=new WeakSet,ze=async function(t){return(await this.client.getHiddenFilesByParent(t)).filter(n=>typeof n.tag=="string"&&n.tag.startsWith(is)).map(n=>{const r=String(n._id);return{hiddenId:r,userId:n.tag.slice(is.length),savedAt:vr(r)}})},os=async function(t){for(const e of t)try{await this.client.deleteHiddenFile(e)}catch{}};function Lo(s){const t=`${is}${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 vr(s){const t=parseInt(s.slice(0,8),16);return new Date(Number.isFinite(t)?t*1e3:0)}async function Po(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 Bo(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 Un(s,t){const e=(t??"").replace(/^\./,"").toLowerCase();if(e)return e;const n=s.lastIndexOf(".");return n>0?s.slice(n+1).toLowerCase():""}function Do(s){if(!s||typeof s!="object")return null;const t=s;if(t.schema!==Ze||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 Os?t.type:void 0;return{schema:Ze,name:t.name,...i?{type:i}:{},...r?{native:{fileId:n.fileId,format:n.format}}:{},views:e}}const jo="flow:",Uo="flow:op",qo="flow:source",Vo="flow:host",xs="revitflow/op@2",br="REVITFLOWCHANGE",Tr="REVITFLOWOPERATION";class Rn{constructor(t){Rt(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:xs,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 Go();return Ho(this.flatbuffer(n,r,t,JSON.stringify(e)))}pack(t,e){const n={};for(const[r,i]of Object.entries(t??{}))r.startsWith(jo)||(n[r]=String(i));return e.position&&(n.Position=e.position.map(Er).join(",")),e.rotationDeg!==void 0&&(n.Rotation=Er(e.rotationDeg)),e.source&&(n[qo]=e.source),e.host&&(n[Vo]=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),p=this.changes.length,w=new Uint32Array(p);let v=1;for(let et=0;et<p;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),x=_(o.startMaterialsVector),T=_(o.startLocalTransformsVector),M=_(o.startGlobalTransformsVector),z=o.createMeshesItemsVector(c,[]),ut=o.createMaterialIdsVector(c,[]),wt=o.createRepresentationIdsVector(c,[]),Ot=o.createSampleIdsVector(c,[]),Vt=o.createLocalTransformIdsVector(c,[]),kt=o.createGlobalTransformIdsVector(c,[]);o.startMeshes(c),o.addCoordinates(c,d.createTransform(c,0,0,0,1,0,0,0,1,0)),o.addGlobalTransforms(c,M),o.addShells(c,L),o.addRepresentations(c,u),o.addSamples(c,O),o.addLocalTransforms(c,T),o.addMaterials(c,x),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,kt);const he=o.endMeshes(c),Yt=c.createString(r),It=new Set,Gt=[];for(const et of this.changes){const At=[],Ht={[Uo]:et.op,...et.attrs};for(const[de,Ue]of Object.entries(Ht)){const xe=JSON.stringify([de,Ue,"IFCTEXT"]);It.add(xe),At.push(c.createString(xe))}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 Mt=a.createAttributesVector(c,Gt),Ce=a.createUniqueAttributesVector(c,[...It].map(et=>c.createString(et))),q=this.changes.map(()=>c.createString(br));q.push(c.createString(Tr));const Z=a.createCategoriesVector(c,q),$=[],Tt=[];this.changes.forEach((et,At)=>{et.item&&($.push(c.createString(et.item)),Tt.push(w[At]))});const Et=a.createGuidsVector(c,$),pt=a.createGuidsItemsVector(c,Tt),Dt=a.createLocalIdsVector(c,[...w,I]),Ft=this.changes.map((et,At)=>l.createSpatialStructure(c,w[At],c.createString(br),0)),Pt=l.createSpatialStructure(c,I,c.createString(Tr),l.createChildrenVector(c,Ft)),st=c.createString(n);a.startModel(c),a.addMeshes(c,he),a.addMetadata(c,Yt),a.addAttributes(c,Mt),a.addUniqueAttributes(c,Ce),a.addLocalIds(c,Dt),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 Go(){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 Er(s){return Number.isFinite(s)?String(s):"0"}async function Ho(s){const t=new Blob([s]).stream().pipeThrough(new CompressionStream("deflate"));return new Uint8Array(await new Response(t).arrayBuffer())}async function kn(s){const[t,e]=await Jo(),n=e.Model.getRootAsModel(new t.ByteBuffer(await Wo(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 p=0;p<((c==null?void 0:c.dataLength())??0);p++){const w=c.data(p);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 Jo(){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 Wo(s){const t=new Blob([s]).stream().pipeThrough(new DecompressionStream("deflate"));return new Uint8Array(await new Response(t).arrayBuffer())}const ei="Element",ni="Carried",Me=1/.3048;function si(s){const t=[];for(const e of s)for(const n of[ei,ni]){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 $s(s))t.set(e,n.name);return t}function $s(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 ri(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 Rs(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 ii(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 ks(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=oi(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 kn(e),site:r,shapes:i}}function oi(s){var M;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=(M=i[2].split(",")[5])==null?void 0:M.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[p,,w]=n(c[2]),v=p&&p!=="$"?e(p):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),x={MILLI:.001,CENTI:.01,DECI:.1,KILO:1e3},T=u?u[2]?x[u[2].toUpperCase()]??1:1:/IFCCONVERSIONBASEDUNIT\([^)]*\.LENGTHUNIT\.[^)]*'FOOT'/i.test(t)?.3048:1;return{east:I*T,north:_*T,elevation:L*T,angleDeg:C}}const Ns="thatopen/recipe@1",Ir="__project_data",Sr="recipes",Yo=s=>`${s}.recipe.json`,ai={OperationBuilder:Rn,OP_SCHEMA:xs,readFrag:kn,readPickedFrag:ks,recordsOf:si,innerJson:Bt,levelsOf:$s,levelNames:zo,stylesOf:ri,printOf:ii,siteLocationOf:oi,whatItMadeBefore:Rs,ELEMENT_FIELD:ei,CARRIED_FIELD:ni,FEET_PER_METRE:Me},ci=/^[a-z0-9][a-z0-9-]{1,62}$/;async function li(s,t,e){const n=d=>[...d].sort((c,p)=>String(c._id).localeCompare(String(p._id)))[0],r=await s.listFolders({projectId:t,archived:!1});let i=n(r.filter(d=>d.name===Ir&&!d.parentId));if(!i){if(!e)return null;i=await s.createFolder(Ir,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===Sr&&String(d.parentId)===o));if(!l){if(!e)return null;l=await s.createFolder(Sr,o,t)}return String(l._id)}const Ko=s=>String(s._id??s.id??""),Xo=s=>String(s.tag??s.versionTag??""),as=s=>{var t;return Number(((t=/(\d+)/.exec(s))==null?void 0:t[1])??-1)};async function He(s,t){const e=await li(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:Ko(i)})}return r}async function mn(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)!==Ns||!((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 Je(s,t){return(await s.listVersions(t)).map(n=>({tag:Xo(n),createdAt:String(n.createdAt??"")})).filter(n=>n.tag).sort((n,r)=>as(n.tag)-as(r.tag))}var rn;class hi{constructor(t,e){K(this,rn,new Map);this.client=t,this.builtinNames=e}async list(t){const e=await He(this.client,t);return(await Promise.all([...e.entries()].map(async([,{id:r}])=>{var i;try{const o=await Je(this.client,r),a=(i=o[o.length-1])==null?void 0:i.tag,l=await mn(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 He(this.client,t)).get(e);if(!n)throw new Error(`The project has no recipe named "${e}".`);const r=await Je(this.client,n.id);return await Promise.all(r.map(async({tag:i,createdAt:o})=>{try{const a=await mn(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 He(this.client,t)).get(e);if(!r)throw new Error(`The project has no recipe named "${e}".`);const i=n??((o=(await Je(this.client,r.id)).pop())==null?void 0:o.tag);if(!i)throw new Error(`The recipe "${e}" has no saved version.`);return{...await mn(this.client,r.id,i),version:i}}async save(t,e,n){const{manifest:r,code:i}=e;if(!ci.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 cs(r,i);const o={schema:Ns,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 He(this.client,t)).get(r.name);if(l){const c=await Je(this.client,l.id),p=`v${Math.max(0,...c.map(w=>as(w.tag)))+1}`;return await this.client.createVersion(l.id,a,p),p}const d=await li(this.client,t,!0);return await this.client.createFile({file:a,name:Yo(r.name),versionTag:"v1",projectId:t,parentFolderId:d}),"v1"}async load(t,e,n){var l;const r=(await He(this.client,t)).get(e);if(!r)throw new Error(`The project has no recipe named "${e}".`);const i=n??((l=(await Je(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,rn).get(o);if(!a){const d=await mn(this.client,r.id,i);a=await cs(d.manifest,d.code),g(this,rn).set(o,a)}return{recipe:a,version:i}}}rn=new WeakMap;async function cs(s,t){var r;let e;try{e=await import(`data:text/javascript;base64,${Qo(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:ai})}}function Qo(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 Zo(s){const t=s instanceof Uint8Array?s:new Uint8Array(await s.arrayBuffer()),{items:e,metadata:n}=await kn(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 Ms extends Error{constructor(t){super(t),this.name="UpToDate"}}var ae,on,an;class di{constructor(t){K(this,ae,new Map);K(this,on,new Map);K(this,an,new Map);Rt(this,"project");this.client=t,this.project=new hi(t,()=>new Set(g(this,ae).keys()))}provideImporter(t,e){g(this,on).set(t.toLowerCase(),e)}provideShapes(t,e){g(this,an).set(t.toLowerCase(),e)}shapesFor(t){return g(this,an).get(t.toLowerCase())}importerFor(t){return g(this,on).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 fi(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??As(),input:e.input,settings:e.settings??{},progress:e.progress??(()=>{})})}}ae=new WeakMap,on=new WeakMap,an=new WeakMap;async function fi(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,p=d!=null&&d.createdAt?new Date(String(d.createdAt)).getTime():NaN;return!Number.isNaN(c)&&!Number.isNaN(p)&&c!==p?p-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 ls=100;function ta(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 ea(s){if(!s||typeof s!="object")return;const t=s.retryAfter;return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}class Nn extends Error{constructor(e,n,r,i){const o=ta(r);super(o.message??`${n||"Request failed"} (${e})`);Rt(this,"status");Rt(this,"code");Rt(this,"details");Rt(this,"body");Rt(this,"retryAfter");this.name="RequestError",this.status=e,this.code=o.code,this.details=o.details,this.body=r,this.retryAfter=i??ea(o.details)}}const Kt="item/folder",W="item",pe="processor",na="npm-registry",re="hidden",qn="FILE",Vn="TOOL",Gn="APP",sa=500,_r=3e4,ra=.25,ia=s=>new Promise(t=>setTimeout(t,s));function oa(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 aa(s){return s instanceof Nn?s.status===429||s.status>=500:!0}function ca(s,t){const e=Math.min(sa*2**t,_r),n=e*ra*Math.random(),r=s instanceof Nn&&s.retryAfter!=null?s.retryAfter*1e3:void 0;return r!=null?Math.min(r,_r)+n:e+n}var E,hs,F,ve,cn,Ye,In,Sn,ds,fs,ui;const Ps=class Ps{constructor(t,e,n){K(this,E);Rt(this,"apiUrl");Rt(this,"accessToken");Rt(this,"wsUrl");Rt(this,"retries");Rt(this,"useBearer");Rt(this,"builtInGlobals",null);Rt(this,"localServerUrl",null);Rt(this,"context");K(this,cn);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 Ps(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 m(this,E,F).call(this,t,e,n)}async listFiles(t){const{folderId:e,archived:n,projectId:r}=t||{};return e?await m(this,E,F).call(this,"GET",`${Kt}/${e}/items`,{query:{itemType:qn,archived:n}}):await m(this,E,F).call(this,"GET",`${W}`,{query:{itemType:qn,archived:n,...r&&{projectId:r}}})}async getFile(t,e){return await m(this,E,fs).call(this,t,e)}async createFile(t){return await m(this,E,Sn).call(this,t,qn)}async updateFile(t,e){return await m(this,E,ds).call(this,t,e)}async archiveFile(t){return await m(this,E,F).call(this,"DELETE",`${W}/${t}`)}async recoverFile(t){return await m(this,E,F).call(this,"PUT",`${W}/${t}/recover`)}async downloadFile(t,e){return await m(this,E,In).call(this,t,e)}async getFileVersionMetadata(t,e,n){const{withDraft:r}=n||{};return await m(this,E,F).call(this,"GET",`${W}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/metadata`,{query:{...r&&{withDraft:"true"}}})}async updateFileVersionMetadata(t,e,n){return await m(this,E,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 m(this,E,F).call(this,"DELETE",`${W}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/metadata`)}async getFileVersionMetadataBatch(t,e){const{withDraft:n}=e||{};return await m(this,E,Ye).call(this,t,async r=>(await m(this,E,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 m(this,E,F).call(this,"GET",Kt,{query:{parentFolderId:n,archived:e,...r&&{projectId:r}}})}async getFolder(t){return await m(this,E,F).call(this,"GET",`${Kt}/${t}`)}async getFoldersBatch(t){return await m(this,E,Ye).call(this,t,async e=>(await m(this,E,F).call(this,"POST",`${W}/batch/folders`,{body:JSON.stringify({folderIds:e}),contentType:"application/json"})).results)}async createFolder(t,e,n){return await m(this,E,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 m(this,E,F).call(this,"PUT",`${Kt}/${t}`,{body:JSON.stringify({name:n}),contentType:"application/json"})}async archiveFolder(t){return await m(this,E,F).call(this,"DELETE",`${Kt}/${t}`)}async recoverFolder(t){return await m(this,E,F).call(this,"PUT",`${Kt}/${t}/recover`)}async downloadFolder(t){return await m(this,E,ve).call(this,`${Kt}/${t}/download`)}async listComponents(t){const{folderId:e,ShowVersions:n,projectId:r}=t||{};return e?await m(this,E,F).call(this,"GET",`${Kt}/${e}/items`,{query:{itemType:Vn,...n&&{ShowVersions:n}}}):await m(this,E,F).call(this,"GET",`${W}`,{query:{itemType:Vn,...n&&{ShowVersions:n},...r&&{projectId:r}}})}async getComponent(t,e){return await m(this,E,fs).call(this,t,e)}async createComponent(t){const{componentProps:e}=t;return await m(this,E,Sn).call(this,t,Vn,e)}async updateComponent(t,e){const{componentProps:n}=e;return await m(this,E,ds).call(this,t,e,n)}async downloadComponent(t,e){return await m(this,E,In).call(this,t,e)}async downloadComponentBundle(t,e){const{versionTag:n,withDraft:r}=e||{};return await m(this,E,ve).call(this,`${W}/${t}/download/bundle`,{query:{...n&&{versionTag:n},...r&&{withDraft:r}}})}async archiveComponent(t){return await m(this,E,F).call(this,"DELETE",`${W}/${t}`)}async recoverComponent(t){return await m(this,E,F).call(this,"PUT",`${W}/${t}/recover`)}async getBuiltInComponent(t){return await(await m(this,E,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(p=>i[p]),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 m(this,E,F).call(this,"GET",`${Kt}/${e}/items`,{query:{itemType:Gn,...n&&{ShowVersions:n}}}):await m(this,E,F).call(this,"GET",`${W}`,{query:{itemType:Gn,...n&&{ShowVersions:n},...r&&{projectId:r}}})}async createApp(t){const{appProps:e}=t;return await m(this,E,Sn).call(this,t,Gn,e)}async downloadApp(t,e){return await m(this,E,In).call(this,t,e)}async downloadAppBundle(t,e){const{versionTag:n,withDraft:r}=e||{};return await m(this,E,ve).call(this,`${W}/${t}/download/bundle`,{query:{...n&&{versionTag:n},...r&&{withDraft:r}}})}async archiveApp(t){return await m(this,E,F).call(this,"DELETE",`${W}/${t}`)}async getNpmCredentials(){return await m(this,E,F).call(this,"GET",`${na}/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 m(this,E,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 m(this,E,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 m(this,E,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 m(this,E,F).call(this,"GET",`${pe}/progress/${t}`)}async onExecutionProgress(t,e){const n=this.localServerUrl??this.wsUrl,r=await Xe(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 Cs(this,t)}history(t){return new Ss(this,t)}get recipes(){return g(this,cn)??it(this,cn,new di(this)),g(this,cn)}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 m(this,E,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 m(this,E,F).call(this,"POST",`${W}/${re}/batch`,{body:r})}async deleteHiddenFile(t){return await m(this,E,F).call(this,"DELETE",`${W}/${re}/${t}`)}async getHiddenFile(t){return await m(this,E,F).call(this,"GET",`${W}/${re}/${t}`)}async downloadHiddenFile(t){return await m(this,E,ve).call(this,`${W}/${re}/${t}/download`)}async getHiddenFileSignedUrl(t,e){return await m(this,E,F).call(this,"GET",`${W}/${re}/${t}/signed-url`,{...e!=null&&{query:{expiresIn:e}}})}async getHiddenFileSignedUrlsBatch(t,e){return await m(this,E,Ye).call(this,t,async n=>(await m(this,E,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 m(this,E,F).call(this,"GET",`${W}/${t}/${re}`,{...e!=null&&{query:{tag:e}}})}async deleteHiddenFilesByParent(t){return await m(this,E,F).call(this,"DELETE",`${W}/${t}/${re}`)}async uploadItemIcon(t,e){const n=new FormData;return n.append("icon",e),await m(this,E,F).call(this,"PUT",`${W}/${t}/icon`,{body:n})}async getItemIcon(t){return await m(this,E,ve).call(this,`${W}/${t}/icon`)}async removeItemIcon(t){return await m(this,E,F).call(this,"DELETE",`${W}/${t}/icon`)}async updateItem(t,e){return await m(this,E,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 m(this,E,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 m(this,E,F).call(this,"GET",`${W}/${encodeURIComponent(t)}/versions`,{query:e})}async listVersionsBatch(t,e={}){const{archived:n}=e;return await m(this,E,Ye).call(this,t,async r=>(await m(this,E,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 m(this,E,F).call(this,"PUT",`${W}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/archive`)}async recoverVersion(t,e){return await m(this,E,F).call(this,"PUT",`${W}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}/recover`)}async deleteVersion(t,e){return await m(this,E,F).call(this,"DELETE",`${W}/${encodeURIComponent(t)}/version/${encodeURIComponent(e)}`)}};E=new WeakSet,hs=function(t){return`${this.apiUrl}/${t}`},F=async function(t,e,n){const{body:r,query:i,contentType:o,retries:a,responseType:l,retryAttempt:d}=n||{},c=m(this,E,hs).call(this,e),p=m(this,E,ui).call(this,i),w=await this.resolveAccessToken(),v={...p,...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 Nn(I.status,I.statusText,_,oa(I))}return l==="blob"?await I.blob():I.json().then(_=>_).catch(()=>{})}catch(I){const _=a??this.retries;if(_>0&&aa(I)){const L=d??0;return await ia(ca(I,L)),await m(this,E,F).call(this,t,e,{...n,retries:_-1,retryAttempt:L+1})}throw I}},ve=async function(t,e){const{query:n}=e||{},r=m(this,E,hs).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}`}}})},cn=new WeakMap,Ye=async function(t,e){if(!t.length)return[];const n=[];for(let i=0;i<t.length;i+=ls)n.push(t.slice(i,i+ls));return(await Promise.all(n.map(e))).flat()},In=async function(t,e){const{versionTag:n,withDraft:r}=e||{};return await m(this,E,ve).call(this,`${W}/${t}/download`,{query:{...n&&{versionTag:n},...r&&{withDraft:r}}})},Sn=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 m(this,E,F).call(this,"POST",W,{body:c})},ds=async function(t,e,n){const{name:r,versionTag:i,parentFolderId:o,file:a,metadata:l}=e;let d,c;if(a){const p=new FormData;p.append("file",a),i&&p.append("versionTag",i),n&&p.append("extraProps",JSON.stringify(n)),l&&p.append("metadata",JSON.stringify(l)),c=await m(this,E,F).call(this,"POST",`${W}/${t}/version`,{body:p})}if(r||o){const p={...r&&{name:r},...o&&{folderId:o}},w=JSON.stringify(p);d=await m(this,E,F).call(this,"PUT",`${W}/${t}`,{body:w,contentType:"application/json"})}return{item:d,version:c}},fs=async function(t,e){const{showVersions:n=!1}=e||{};return await m(this,E,F).call(this,"GET",`${W}/${t}`,{query:{showVersions:n}})},ui=function(t){return t&&Object.entries(t).filter(([,e])=>e!==void 0).reduce((e,[n,r])=>(e[n]=r,e),{})};let Cn=Ps;function pi(){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 us="channel:",la=1e4;function _n(s){try{s()}catch(t){console.error("[channel] a listener threw:",t)}}var ce,jt,Ut,Fe,Le,Pe,Lt,ps,ms,Ne;class Fs{constructor(t,e){K(this,Lt);K(this,ce,!1);K(this,jt,[]);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,jt)}join(){return g(this,ce)?Promise.resolve():m(this,Lt,ps).call(this,"joined",this.controls.join)}leave(){return!g(this,ce)&&!g(this,Ut).some(t=>t.want==="joined")?Promise.resolve():m(this,Lt,ps).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),m(this,Lt,ms).call(this,"joined"),m(this,Lt,Ne).call(this)}applyLeft(){it(this,ce,!1),it(this,jt,[]),m(this,Lt,ms).call(this,"left"),m(this,Lt,Ne).call(this)}applyPeers(t){it(this,jt,t),m(this,Lt,Ne).call(this)}applyPeerJoined(t){!g(this,ce)||g(this,jt).some(e=>e.from===t.from)||(it(this,jt,[...g(this,jt),t]),g(this,Le).forEach(e=>_n(()=>e(t))),m(this,Lt,Ne).call(this))}applyPeerLeft(t){const e=g(this,jt).find(n=>n.from===t);e&&(it(this,jt,g(this,jt).filter(n=>n.from!==t)),g(this,Pe).forEach(n=>_n(()=>n(e))),m(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,jt=new WeakMap,Ut=new WeakMap,Fe=new WeakMap,Le=new WeakMap,Pe=new WeakMap,Lt=new WeakSet,ps=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.`))},la)};g(this,Ut).push(i),this.transport.post({type:"APP_CHANNEL_CONTROL",...e})})},ms=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,Fe).forEach(t=>_n(t))};var Be;class mi extends Fs{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(us))throw new Error(`Message types starting with '${us}' 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=yi(e);return n.forEach(i=>_n(()=>i(e.payload,r))),{handled:!0}}}Be=new WeakMap;var Te;class gi extends Fs{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,yi(e))}}catch(r){return{handled:!0,error:r instanceof Error?r.message:String(r)}}}}Te=new WeakMap;function yi(s){return{from:s.from,at:s.at,requestId:s.requestId,kind:s.kind}}function ha(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,ln,le,Ee,Ie,Ct,gs,An,vi,bi,Ti,ys;class wi{constructor(t){K(this,Ct);K(this,Oe);K(this,ln);K(this,le);K(this,Ee,new Map);K(this,Ie,new Set);it(this,Oe,t),it(this,ln,t.listen(e=>void m(this,Ct,vi).call(this,e)))}collab(){return g(this,le)??it(this,le,new mi(g(this,Oe))),g(this,le)}external(t){const e=t??"";let n=g(this,Ee).get(e);return n||(n=new gi(g(this,Oe),t),g(this,Ee).set(e,n)),n}dispose(){g(this,ln).call(this)}}Oe=new WeakMap,ln=new WeakMap,le=new WeakMap,Ee=new WeakMap,Ie=new WeakMap,Ct=new WeakSet,gs=function(){return[...g(this,le)?[g(this,le)]:[],...g(this,Ee).values()]},An=function(t,e){if(t==="collab")return g(this,le);if(t==="external")return g(this,Ee).get(typeof e=="string"?e:"")},vi=async function(t){const e=ha(t);if(e){if(e.type.startsWith(us)){m(this,Ct,bi).call(this,e);return}await m(this,Ct,Ti).call(this,e)}},bi=function(t){var n,r,i;const e=t.payload??{};switch(t.type){case"channel:joined":(n=m(this,Ct,An).call(this,e.scope,e.kind))==null||n.applyJoined();break;case"channel:left":(r=m(this,Ct,An).call(this,e.scope,e.kind))==null||r.applyLeft();break;case"channel:peers":(i=m(this,Ct,An).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));m(this,Ct,gs).call(this).map(l=>l.failPending(o)).some(Boolean)||console.error("[channel] error:",t.payload);break}}},Ti=async function(t){const e=m(this,Ct,gs).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&&m(this,Ct,ys).call(this,t.requestId,o))}t.requestId&&t.scope==="external"&&e.length>0&&!n&&m(this,Ct,ys).call(this,t.requestId,{handled:!0,error:`No handler for "${t.type}".`})},ys=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",$e="notifications";var De,hn;const Bs=class Bs extends Cn{constructor(e,n,r){super(typeof e=="string"?e:"",n,{...r,useBearer:!0});K(this,De);K(this,hn);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 Bs(n.accessToken,n.apiUrl,e);return r.context=n,r}get channel(){return g(this,hn)??it(this,hn,new wi(pi())),g(this,hn)}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",$e,{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",`${$e}/unread-count`)).count}async markNotificationsRead(e){return await this.request("POST",`${$e}/mark-read`,{body:JSON.stringify({ids:e}),contentType:"application/json"})}async markAllNotificationsRead(){return await this.request("POST",`${$e}/mark-all-read`)}async getNotificationSubscriptions(){return await this.request("GET",`${$e}/subscriptions`)}async unsubscribeFromAutomation(e){return await this.request("DELETE",`${$e}/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=Xe(`${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,hn=new WeakMap;let ws=Bs;const me=1/.3048,da={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"},fa="OST_GenericModel",ua=new Set(["IFCSPACE","IFCOPENINGELEMENT","IFCSITE","IFCANNOTATION","IFCGRID","IFCVIRTUALELEMENT","IFCBUILDING","IFCBUILDINGSTOREY"]),be=(s,t)=>Math.round(s/t)*t,pa=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]]}),Qe=(s,t)=>s[0]*t[0]+s[1]*t[1]+s[2]*t[2],Hn=s=>Math.sqrt(Qe(s,s)),On=(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 ma(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)||ua.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":da[l.ifcClass.toUpperCase()]??fa,p=pa(l.pieces[0].matrix),w=Hn(p.x),v=Hn(p.y),I=Hn(p.z),_=p.z.map(q=>q/(I||1)),L=Math.abs(_[2]-1)<1e-6&&Qe(On(p.x,p.y),p.z)>0&&Math.abs(w-v)<1e-6&&Math.abs(w-I)<1e-6,C=Qe(On(p.x,p.y),p.z)>0&&Math.abs(w-v)<1e-6&&Math.abs(w-I)<1e-6,O=[p.x,p.y,p.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,x=L?Math.atan2(p.x[1],p.x[0]):u?Math.atan2(u[1],u[0]):0,T=Math.cos(-x),M=Math.sin(-x),z=[p.t[0],p.t[1],p.t[2]],ut=/COLUMN/i.test(c),wt=q=>{const Z=q[0]-z[0],$=q[1]-z[1];return[T*Z-M*$,M*Z+T*$,q[2]-z[2]]},Ot=[],Vt=[c];for(const q of l.pieces){const Z=s.geometries.get(q.geometry);if(!Z)continue;const $=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=[$[0]*rt+$[4]*et+$[8]*At+$[12],$[1]*rt+$[5]*et+$[9]*At+$[13],$[2]*rt+$[6]*et+$[10]*At+$[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=Qe(On([$[0],$[1],$[2]],[$[4],$[5],$[6]]),[$[8],$[9],$[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 Dt=wt([$[12],$[13],$[14]]),Ft=[T*$[0]-M*$[1],M*$[0]+T*$[1],$[2]],Pt=[T*$[4]-M*$[5],M*$[4]+T*$[5],$[6]];Vt.push(`${q.geometry}@${[...Dt,...Ft,...Pt].map(st=>be(st,1e-4).toFixed(4)).join(",")}`)}if(Ot.length===0)continue;const kt=!l.host&&Ot.length===1?wa(Ot[0]):null;if(kt){const q=ya(kt),Z=q.key,$=`prism|${c}|${q.axis}|${Z}`;let Tt=i.get($);if(!Tt){const et=Ar(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:Or($)},i.set($,Tt)}const Et={ShapeCategory:c,Family:Tt.family,Type:Tt.type,ShapeKey:Tt.key,PrismLength:String(be(kt.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[kt.axis]=(q.flipped?kt.from+kt.length:kt.from)/me;const Dt=(kt.axis+1)%3,Ft=(kt.axis+2)%3;pt[Dt]+=q.centre[0]/me,pt[Ft]+=q.centre[1]/me;const Pt=Math.cos(x),st=Math.sin(x),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:(x+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=Ar(l.typeName??l.objectType??l.name??l.ifcClass),Z=(o.get(q)??0)+1;o.set(q,Z);const $=Z===1?q:`${q} (${Z})`;It={family:$,type:$,first:!0,key:Or(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 Mt=l.host?r.get(l.host):void 0,Ce=l.opening?s.elements.get(l.opening):void 0;if(Mt&&Ce){const q=[1/0,1/0,1/0],Z=[-1/0,-1/0,-1/0];for(const $ of Ce.pieces){const Tt=s.geometries.get($.geometry);if(!Tt)continue;const Et=$.matrix;for(let pt=0;pt<Tt.verts.length;pt+=3){const Dt=Tt.verts[pt],Ft=Tt.verts[pt+1],Pt=Tt.verts[pt+2],st=wt([Et[0]*Dt+Et[4]*Ft+Et[8]*Pt+Et[12],Et[1]*Dt+Et[5]*Ft+Et[9]*Pt+Et[13],Et[2]*Dt+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($=>be($,1e-5)).join(","))}a.push({key:`${e}:${l.gid}:shape`,attrs:Gt,at:[z[0],z[1],z[2]],rotationDeg:x*180/Math.PI,...Mt?{host:Mt}:{}})}return a}function Ar(s){return(s.replace(/[\\:{}[\]|;<>?`~]/g,"-").replace(/\s+/g," ").trim()||"Shape").slice(0,120)}function Or(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 ga(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 Ta(s,i.gid)){const l=a.pts;if(l.length<4)continue;const d=ba(tn(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]),p=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(p)*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 ya(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,x)=>{const T=v[(x+1)%v.length];return O+u[0]*T[1]-T[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[T,M]of _)w+=T*T,v+=M*M,I+=T*M;const L=new Set,C=.5*Math.atan2(2*I,w-v);for(let T=0;T<4;T++)L.add(C+T*Math.PI/2);const O=_.map(([T,M])=>Math.hypot(T,M)),u=Math.max(...O),x=_.filter((T,M)=>O[M]>u-.003);if(Math.abs(w-v)<.001*(w+v)||x.length>4)for(const[T,M]of x.slice(0,64))L.add(Math.atan2(M,T));for(const T of L)o.push({loops:i(n,T),turn:T,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],p=r(c.loops);for(const w of o.slice(1)){const v=r(w.loops);v<p&&(c=w,p=v)}return{axis:a,loops:c.loops,key:p,centre:e,turn:l+c.turn,flipped:c.flipped}}function wa(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 x=s.v[u*3+r];i=Math.min(i,x),o=Math.max(o,x)}if(o-i<.01)continue;let a=!0;for(let u=0;u<e&&a;u++){const x=s.v[u*3+r];Math.abs(x-i)>.001&&Math.abs(x-o)>.001&&(a=!1)}if(!a)continue;const l=(r+1)%3,d=(r+2)%3,c=new Map,p=[],w=u=>{const x=[s.v[u*3+l],s.v[u*3+d]],T=`${Math.round(x[0]*3048)},${Math.round(x[1]*3048)}`;return c.has(T)||(c.set(T,p.length),p.push(x)),c.get(T)},v=new Map,I=[];for(let u=0;u+2<s.t.length;u+=3){const x=[s.t[u],s.t[u+1],s.t[u+2]];if(!x.every(M=>Math.abs(s.v[M*3+r]-i)<=.001))continue;const T=x.map(w);if(!(T[0]===T[1]||T[1]===T[2]||T[0]===T[2])){I.push(T);for(let M=0;M<3;M++){const z=T[M],ut=T[(M+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 x=0;x<3;x++){const T=u[x],M=u[(x+1)%3];v.get(T<M?`${T},${M}`:`${M},${T}`)===1&&_.set(T,[..._.get(T)??[],M])}if([..._.values()].some(u=>u.length!==1))continue;const L=[],C=new Set(_.keys());for(;C.size;){const u=C.values().next().value,x=[];let T=u,M=0;do x.push(p[T]),C.delete(T),T=_.get(T)[0];while(T!==u&&M++<1e5&&_.has(T));if(T!==u||x.length<3){L.length=0;break}const z=x.filter((ut,wt)=>{const Ot=x[(wt-1+x.length)%x.length],Vt=x[(wt+1)%x.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 va(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 p=d.matrix,w=v=>{const I=c.verts[v*3],_=c.verts[v*3+1],L=c.verts[v*3+2];return[p[0]*I+p[4]*_+p[8]*L+p[12],p[1]*I+p[5]*_+p[9]*L+p[13],p[2]*I+p[6]*_+p[10]*L+p[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(p=>Math.abs(p[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 ba(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 Ta(s,t){const e=s.elements.get(t);if(!e)return[];const n=[],r=[],i=new Map;for(const c of e.pieces){const p=s.geometries.get(c.geometry);if(!p)continue;const w=c.matrix,v=[];for(let I=0;I<p.verts.length;I+=3){const _=p.verts[I],L=p.verts[I+1],C=p.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(T=>Math.round(T*1e4)).join(",");let x=i.get(u);x===void 0&&(x=n.length,i.set(u,x),n.push(O)),v.push(x)}for(let I=0;I+2<p.tris.length;I+=3)r.push(v[p.tris[I]],v[p.tris[I+1]],v[p.tris[I+2]])}const o=n.map((c,p)=>p),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 p=a(r[c]);o[a(r[c+1])]=p,o[a(r[c+2])]=p}const l=new Map;for(let c=0;c<r.length;c+=3){const p=a(r[c]);let w=l.get(p);w||(w={pts:new Set,volume:0},l.set(p,w));const[v,I,_]=[n[r[c]],n[r[c+1]],n[r[c+2]]];w.volume+=Qe(v,On(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,p)=>({pts:[...c.pts].map(w=>n[w]),volume:c.volume,index:p,of:d.length}))}function tn(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],p=o.verts[l+2];r.push([a[0]*d+a[4]*c+a[8]*p+a[12],a[1]*d+a[5]*c+a[9]*p+a[13],a[2]*d+a[6]*c+a[10]*p+a[14]])}}return r}function Ea(s,t,e){const n=tn(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])),p=C=>Math.max(...n.filter(O=>Math.abs(d(O)-C)<.05).map(O=>O[2]),-1/0),w=p(0),v=p(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=tn(s,C.gid);if(O.length===0)continue;const u=O.map(z=>z[0]),x=O.map(z=>z[1]),T=O.map(z=>z[2]);if(I<Math.min(...u)-.2||I>Math.max(...u)+.2||_<Math.min(...x)-.2||_>Math.max(...x)+.2)continue;const M=Math.min(...T)-c;M>1.5||Math.max(...T)<c-.05||(!L||Math.abs(M)<Math.abs(L.gap))&&(L={id:C.id,gap:M})}return L==null?void 0:L.id}const ge={levels:"-2000240",walls:"-2000011",floors:"-2000032",roofs:"-2000035",ceilings:"-2000038",structuralFoundations:"-2001300",stairs:"-2000120"};function Ke(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 Cr(s){const t=Ke(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 xr=180/Math.PI;function $r(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 Ei(s){return async t=>{var js,Us,qs,Vs,Gs,Hs,Js,Ws,zs,Ys,Ks,Xs,Qs,Zs,tr,er,nr,sr,rr,ir,or;const{picked:e,contents:n,site:r,shapes:i}=await ks(t,t.input),o=si(n.items),a=/CoordinateBase:\s*(Coordenadas compartidas|Shared Coordinates|Shared)/i.test(JSON.stringify(n.metadata??{})),l=a&&r?[r.east*Me,r.north*Me,r.elevation*Me,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:p}=t.settings,w=t.settings.createLevels!==!1;if(p&&!c)throw new Error("Free-standing instances can only be made by their style names: turn trustStyleNames on.");const v=$s(o),I=ri(o),_=`recipe:${s}-to-revit`,L=new Map,C=Rs(t,L);t.progress("Writing the changes for Revit");const O=new Rn({project:t.projectId,document:t.target.docId??"",baseCommit:t.target.version??0,author:_}),u=Me,x=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),x.set(f.id,`${e.fileId}:${b}${R?`:${R}`:""}`)}}const T=h=>x.get(h)??`${e.fileId}:${h}`,M=new Set;let z=0,ut=0;const wt=(h,f,y)=>{M.add(h);const b=a?{...f,Frame:"shared",...l?{SharedAt:l}:{}}:f,R=ii({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 j,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=(j=f==null?void 0:f.profile)==null?void 0:j.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,D]=[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=(D.from[0]-nt[0])*U[0]+(D.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:(H,B)=>{const V=(H-nt[0])*U[0]+(B-nt[1])*U[1];return Math.min(tt+P*V,vt+G*(yt-V))}}},kt=new Map(o.filter(h=>h.kind==="extrusion"&&h.params.of==="roof").map(h=>[h.id,h])),he=[...kt.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(T(h),{CategoryId:ge.levels,Name:f.name,Elevation:ft(f.at*u)})&&Yt++;let It=0,Gt=0;const Mt=[];for(const h of o){if(h.kind!=="run"||h.params.of!=="wall")continue;const f=Bt(h,"run"),y=((Us=(js=f==null?void 0:f.run)==null?void 0:js.line)==null?void 0:Us.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,D)=>Mt.push({record:h,i:D,width:S,from:[...A.from],to:[...A.to],joinStart:D===0&&String(h.params.meetsAtStart)==="true",joinEnd:D===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])},$=1,Tt=new Map;for(const h of Mt){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 Mt){if(ht===h||!Z(h,ht))continue;const Y=q(S,ht);Y<A&&(A=Y,k=ht)}if(!k||A>$)continue;const D=Ce(h,k);if(!D)continue;const nt=Math.min($,2*Math.max(h.width,k.width)+.02);Math.hypot(D[0]-S[0],D[1]-S[1])>nt||q(D,k)>k.width+.01||(y[b]=D)}Tt.set(h,y)}for(const h of Mt){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:D}=Tt.get(h);const nt=new Set;if(i&&f.item.guid&&Mt.filter(j=>j.record===f).length===1?i.elements.get(f.item.guid):void 0){const j=tn(i,f.item.guid),at=Math.hypot(D[0]-A[0],D[1]-A[1]);if(j.length>=4&&at>.05){const H=[(D[0]-A[0])/at,(D[1]-A[1])/at],B=j.map(bt=>(bt[0]-A[0])*H[0]+(bt[1]-A[1])*H[1]),V=Math.min(...B),ct=Math.max(...B),dt=j.map(bt=>-(bt[0]-A[0])*H[1]+(bt[1]-A[1])*H[0]),$t=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*$t},J=A;Q(V)&&(A=[J[0]+H[0]*V,J[1]+H[1]*V],nt.add("start")),Q(ct)&&(D=[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(D[0]*u)},${ft(D[1]*u)},${ft(Y)}`,U={CategoryId:ge.walls,Type:((qs=Ke(f))==null?void 0:qs.type)??k,LocationLine:St,Level:S.name,BaseOffset:ft(b*u),Height:ft(R*u)},ot=[A!==h.from||h.joinStart?"start":"",D!==h.to||h.joinEnd?"end":""].filter(j=>!!j&&!nt.has(j));ot.length&&(U.JoinEnds=ot.join(","));const yt=ot.filter(j=>f.params[j==="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&&!Mt.some(j=>j!==h&&j.record===f)){const j=Math.hypot(h.to[0]-h.from[0],h.to[1]-h.from[1]),at=[(h.to[0]-h.from[0])/j,(h.to[1]-h.from[1])/j],H=[],B=-((A[0]-h.from[0])*at[0]+(A[1]-h.from[1])*at[1]),V=(D[0]-h.to[0])*at[0]+(D[1]-h.to[1])*at[1];G.forEach(([ct,dt],$t)=>{const Q=Math.abs(ct)<1e-6,J=Math.abs(ct-j)<1e-6;let bt=ct,Jt=dt;if(Q||J){bt=Q?-B:j+V;const ue=[G[($t-1+G.length)%G.length],G[($t+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,xt=f.params.topAttachedAt==="top"||y.topAttachedAt==="top",tt=typeof lt=="string"&&xt&&!U.Profile&&kt.has(lt)?Vt(kt.get(lt)):null;if(tt){const j=Math.hypot(D[0]-A[0],D[1]-A[1]),at=Q=>[A[0]+(D[0]-A[0])*Q/j,A[1]+(D[1]-A[1])*Q/j],H=(A[0]-tt.A[0])*tt.n[0]+(A[1]-tt.A[1])*tt.n[1],B=(D[0]-tt.A[0])*tt.n[0]+(D[1]-tt.A[1])*tt.n[1],V=[0,j];(H-tt.ridge)*(B-tt.ridge)<0&&V.splice(1,0,(tt.ridge-H)/(B-H)*j);const ct=S.at+b,dt=[],$t=(Q,J)=>{const bt=at(Q);dt.push(bt[0]*u,bt[1]*u,J*u)};$t(0,ct),$t(j,ct);for(const Q of[...V].reverse()){const J=at(Q);$t(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?Ea(i,f.item.guid,he):void 0;vt&&!U.Profile&&(U.AttachTop=T(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(j=>[+ft(j.thickness*u),j.material??"",j.function??""])),gt.layersFlipped&&(U.FlipLayers="1")),wt(`${T(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,Dt=0;for(const h of o){if(h.kind!=="run"||h.params.of!=="curtainWall")continue;Dt++;const f=Bt(h,"run"),y=(Hs=(Gs=(Vs=f==null?void 0:f.run)==null?void 0:Vs.line)==null?void 0:Gs.curves)==null?void 0:Hs[0],b=v.get(String((f==null?void 0:f.level)??h.params.level??"")),R=h.params.lookRef,S=typeof R=="string"?(Js=I.get(R))==null?void 0:Js.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,D=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)-D,ot=f.height+2*D,yt=(b.at+U)*u,P=((Ws=f.lines)==null?void 0:Ws.along)??Et(nt,k(S.alongSpacing),S.alongJustify),G=((zs=f.lines)==null?void 0:zs.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 j=gt[1]==="horizontal",at=Number(gt[2])/1e3+(j?D:A),H=Number(gt[3])/1e3+(j?A:D);return[{horizontal:j,at:at*u,from:H*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+D)*u}]:[]}),tt={CategoryId:ge.walls,Type:((Ys=Ke(h))==null?void 0:Ys.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+D)*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,j=vt.length,at=vt.map((B,V)=>{const ct=vt[(V-1+j)%j],dt=vt[(V+1)%j],$t=(fe,ue)=>{const Ve=ue[0]-fe[0],Fn=ue[1]-fe[1],ar=Math.hypot(Ve,Fn)||1,cr=gt*Fn/ar,lr=-gt*Ve/ar,hr=Math.abs(cr)>Math.abs(lr)?A:D;return{p:[fe[0]+cr*hr,fe[1]+lr*hr],d:[Ve,Fn]}},Q=$t(ct,B),J=$t(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+D+V)*u);tt.Profile=JSON.stringify([H])}wt(T(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"?(Ks=I.get(y))==null?void 0:Ks.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)),D=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:D*u,width:S(b.width)*u,sizes:{maxRiser:Math.ceil(k/A*1e3-1e-6)/1e3*u,minTread:D*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])-D);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)],j=Y.risers.map(([B,V])=>[nt(B),nt(V)]);nt(P[tt]),nt(P[(tt+1)%P.length]);const at=j.map(([B,V])=>[(B[0]+V[0])/2,(B[1]+V[1])/2]);ht.sketch={boundary:gt,risers:j,path:at};let H=1/0;for(let B=0;B+1<Y.risers.length;B++){const[V,ct]=Y.risers[B],[dt,$t]=Y.risers[B+1],Q=[ct[0]-V[0],ct[1]-V[1]],J=[$t[0]-dt[0],$t[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,xt=(((Qs=(Xs=G==null?void 0:G.profile)==null?void 0:Xs.outline)==null?void 0:Qs.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||!xt.length||!tt||!vt)continue;const[mt,gt]=[Math.min(...xt.map(J=>J[0])),Math.max(...xt.map(J=>J[0]))],[j,at]=[Math.min(...xt.map(J=>J[1])),Math.max(...xt.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 $t=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,$t),Q(mt,$t)],top:(vt.at+S(P.params.base)+H[2]+at)*u,thickness:(at-j)*u})}ot.length&&(ht.landings=ot);const yt={CategoryId:ge.stairs,Type:((Zs=Ke(h))==null?void 0:Zs.type)??String(y),Level:R.name,Stairs:JSON.stringify(ht)};wt(T(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":Cr(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},D=A((er=(tr=b==null?void 0:b.profile)==null?void 0:tr.outline)==null?void 0:er.curves);if(typeof k!="string"||!S||!D)continue;const nt=[D],ht=y==="roof"?Vt(h):null;for(const U of((nr=b==null?void 0:b.profile)==null?void 0:nr.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:((sr=Ke(h))==null?void 0:sr.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??((rr=b==null?void 0:b.said)==null?void 0:rr.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:j}=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(xt,gt)],along:[lt[0],lt[1]],length:j*u}),delete Y.Slopes}}else St&&(Y.HeightOffset=ft(R*u+St));wt(T(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?$r(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(T(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)*xr})&&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++,!p)continue;const f=Bt(h,"instance"),y=(ir=f==null?void 0:f.placement)==null?void 0:ir.at;if(!y||y.length!==3)continue;const b=$r(h.params.type);if(!b)continue;const R=(or=f==null?void 0:f.placement)==null?void 0:or.right,S=R?Math.atan2(R[1],R[0])*xr:0;wt(T(h.id),{Family:b.family,Type:b.type},{position:[y[0]*u,y[1]*u,y[2]*u],rotationDeg:S})&&Ht++}const xe=(()=>{if(!i)return 0;const h=[];for(const y of Mt){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=tn(i,b);if(!k.length)continue;let A=1/0;for(const D of k)A=Math.min(A,D[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})(),Ds=i?ma(i,M,e.fileId):[];let dn=0;for(const h of Ds)wt(h.key,h.attrs,{position:[h.at[0]*u,h.at[1]*u,(h.at[2]-xe)*u],rotationDeg:h.rotationDeg,...h.host?{host:h.host}:{}})&&dn++;if(i)for(const h of ga(i,M,e.fileId))wt(h.key,{WallOpening:h.box.map((f,y)=>ft((y%3===2?f-xe:f)*u)).join(",")},{host:h.host});if(i)for(const h of va(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]-xe)*u]});let Mn=0;const Ci=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"&&!Ci.has(String(f))||h.kind==="extrusion"&&f==="slab"&&Cr(h)==="other"&&!/ Landing \d+$/.test(String(h.item.attrs.Name??""))||h.kind==="run"&&f!=="wall"&&f!=="curtainWall")&&Mn++}let qe=0;for(const[h,f]of C)!h.startsWith(`${e.fileId}:`)||M.has(h)||(O.remove(f),qe++);if(O.length===0)throw new Ms(`Up to date: "${e.name}" holds ${z} element(s) this recipe already made, ${Ue+Mn} waiting on the applier, and nothing is left to remove.`);const xi=[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)`:"",dn?`${dn} family instance(s)`:"",ut?`${ut} changed`:"",qe?`${qe} gone`:""].filter(Boolean);return{title:`${s==="ifc"?"IFC":"Model"} to Revit: ${xi.join(", ")}`,verb:O.summary,targets:O.length,payload:new Blob([await O.build(t.opId)]),ruleTallies:[{read:v.size,written:Yt},{read:Mt.length+Gt,written:It},{read:Dt,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:Ds.length,written:dn},{read:qe,written:qe},{read:Ue+Mn,written:0}]}}}const Ia={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}}},Sa=[{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"}],Ii=`
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
- `,Ls={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:Ia,rules:Sa,doc:Ii,run:Ei("frag")},Si={...Ls,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
- `+Ii,run:Ei("ifc")},_a={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},_i="rhino-to-revit",Aa=`recipe:${_i}`;function Oa(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 Ai={name:_i,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 x;const{picked:t,contents:e}=await ks(s,s.input),{layer:n,instanceType:r}=s.settings;if(!n||!r)throw new Error("Choose the layer and the Revit type.");const i=(x=e.metadata)==null?void 0:x.data,o=i==null?void 0:i.units,a=typeof o=="string"?_a[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*Me,c=Rs(s),p=new Rn({project:s.projectId,document:s.target.docId??"",baseCommit:s.target.version??0,author:Aa});let w=0,v=0,I=0;const _=new Set,L=[];for(const T of e.items){if(!T.guid||Object.keys(T.attrs).length===0)continue;if((T.attrs.Layer??"")!==n){I++;continue}const M=Oa(T);if(!M)continue;_.add(T.guid);const z=[M[0]*d,M[1]*d,M[2]*d],ut=c.get(T.guid);ut?L.push({instance:ut,object:T.guid,position:z}):(p.add({CategoryId:r.categoryId,Family:r.family,Type:r.type},{position:z,source:T.guid}),w++)}for(const T of L)p.set(T.instance,{},{position:T.position,source:T.object}),v++;let C=0;for(const[T,M]of c)_.has(T)||(p.remove(M),C++);const O=w+v+C;if(O===0)throw new Ms(`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:p.summary,targets:O,payload:new Blob([await p.build(s.opId)]),ruleTallies:[{read:w,written:w},{read:v,written:v},{read:C,written:C},{read:I,written:0}]}}},Oi=[Ai,Si,Ls];function Ca(s){for(const t of Oi)s.recipes.register(t)}const xa={MAX_FIELDS:200,MAX_KEY_LENGTH:50,MAX_VALUE_LENGTH:50},$a={uuid:"a3f82c1d-5b74-4e9a-bc30-d7e12f894a61"},Ra={uuid:"2c9f4e8d-3a1b-4c5e-9d7f-0a2b6c8e1d3f"},ka={uuid:"b0b5e2a2-0b3a-4a6b-8b1c-0b1c4a6b8b1c"},Na={uuid:"d8f3a1c2-6b4e-4f9a-8c1d-2e7b5a9f3c60"},Ma={uuid:"3f9c1a7e-6b2d-4e18-9a5c-7d0e2f4b6c81"},Fa={uuid:"2c4ae432-fc24-43e9-9783-0c960c674e96"},La={uuid:"6f3a9c2e-8b1d-4e6a-9c3f-1d7b5a8e2c4f"},Pa={uuid:"69af63aa-19ba-4fc7-b17b-75647bac1d76"},Ba={uuid:"234f1416-528d-452a-9cc9-a16c5239b2eb"};exports.CDEManager=$a;exports.ChannelClient=wi;exports.ChannelRoom=Fs;exports.ClashesManager=Ra;exports.CollabRoom=mi;exports.DOCUMENT_FILE=Tn;exports.DOCUMENT_SCHEMA=Ze;exports.DOCUMENT_TYPES=Os;exports.DocumentDrafts=ti;exports.EngineServicesClient=Cn;exports.ExternalRoom=gi;exports.FileList=ka;exports.FlowDoc=es;exports.GISManager=Na;exports.GitHistoryManager=Ma;exports.HelloWorld=Fa;exports.METADATA_LIMITS=xa;exports.OP_SCHEMA=xs;exports.OperationBuilder=Rn;exports.PROJECT_RECIPE_SCHEMA=Ns;exports.PlatformClient=ws;exports.ProjectDocuments=Cs;exports.ProjectHistory=Ss;exports.ProjectManager=La;exports.ProjectRecipes=hi;exports.RECIPE_NAME=ci;exports.RecipeKit=ai;exports.Recipes=di;exports.RequestError=Nn;exports.SELF_VIEWING_FORMATS=Kr;exports.STORAGE_BATCH_MAX=ls;exports.StaleHistoryError=Qn;exports.TopicsManager=Pa;exports.UIManager=Ba;exports.UpToDate=Ms;exports.builtinRecipes=Oi;exports.compileRecipe=cs;exports.describeChanges=Zo;exports.documentTypeOf=ss;exports.fragToRevit=Ls;exports.ifcToRevit=Si;exports.latestVersions=fi;exports.mintGuid=As;exports.orderByGraph=_s;exports.readFrag=kn;exports.registerBuiltinRecipes=Ca;exports.rhinoToRevit=Ai;exports.windowTransport=pi;
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