${this.label||n.title}
@@ -4338,7 +4338,7 @@ globalThis.__HOUSEPLAN_BUILD_FINGERPRINT__="3d7cafaabdfd8cbcf261f9dccec794dd7c42
}
.markeractions:empty { display: none; }
.markersaveactions { margin-left: auto; }
-`],Ye=new Set(["hacs","sun","backup","hassio","met","telegram_bot","mobile_app","systemmonitor","better_thermostat","adaptive_lighting","yandex_pogoda","upnp_serial_number"]),Je=[{pattern:"протечк|leak|water sensor",icon:"mdi:water-alert"},{pattern:"клапан|valve",icon:"mdi:pipe-valve"},{pattern:"дым|smoke",icon:"mdi:smoke-detector"},{pattern:"термоголов|trv|radiator",icon:"mdi:radiator"},{pattern:"чайник|kettle|термопот",icon:"mdi:kettle"},{pattern:"сауна|sauna|harvia|парная|парилк",icon:"mdi:hot-tub"},{pattern:"температ|temperature|thermometer|climate sensor",icon:"mdi:thermometer"},{pattern:"qingping|air monitor|молекул|air quality",icon:"mdi:air-filter"},{pattern:"штор|curtain|blind|shade",icon:"mdi:roller-shade"},{pattern:"розетк|plug|socket|outlet",icon:"mdi:power-socket-de"},{pattern:"выключат|switch",icon:"mdi:light-switch"},{pattern:"лампа|лампочк|bulb|gx53|светильник|rgb|lamp|light strip",icon:"mdi:lightbulb"},{pattern:"камер|camera",icon:"mdi:cctv"},{pattern:"замок|ttlock|lock|sn609|sn9161",icon:"mdi:lock"},{pattern:"ворота|garage|gate",icon:"mdi:garage-variant"},{pattern:"калитк|door|открыт|contact",icon:"mdi:door"},{pattern:"счётчик|счетчик|kws|meter",icon:"mdi:meter-electric"},{pattern:"вводный автомат|breaker|wifimcbn",icon:"mdi:electric-switch"},{pattern:"myheat|котёл|котел|boiler|отоплен|heating",icon:"mdi:water-boiler"},{pattern:"холодильник|fridge",icon:"mdi:fridge"},{pattern:"стиральн|washer|washing",icon:"mdi:washing-machine"},{pattern:"сушилк|dryer",icon:"mdi:tumble-dryer"},{pattern:"пылесос|vacuum|dreame|roborock",icon:"mdi:robot-vacuum"},{pattern:"soundbar",icon:"mdi:soundbar"},{pattern:"колонк|станц|speaker|яндекс|yandex|алиса|alice",icon:"mdi:speaker"},{pattern:"tv|телевизор|hyundaitv|mitv|television",icon:"mdi:television"},{pattern:"keenetic|роутер|router|mesh|access point",icon:"mdi:router-wireless"},{pattern:"ибп|ups|kirpich",icon:"mdi:battery-charging-high"},{pattern:"slzb|координат|zigbee|coordinator",icon:"mdi:zigbee"},{pattern:"motion|движен|presence|присутств",icon:"mdi:motion-sensor"},{pattern:"humidity|влажн",icon:"mdi:water-percent"}];function Xe(e){const t=[];for(const i of e)if(i&&"string"==typeof i.pattern&&i.icon)try{t.push({re:new RegExp(i.pattern,"i"),icon:i.icon})}catch{}return t}const Ze=Xe(Je),Qe={temperature:"mdi:thermometer",humidity:"mdi:water-percent",motion:"mdi:motion-sensor",occupancy:"mdi:motion-sensor",presence:"mdi:motion-sensor",door:"mdi:door",window:"mdi:window-closed",garage_door:"mdi:garage-variant",smoke:"mdi:smoke-detector",moisture:"mdi:water-alert",gas:"mdi:gas-cylinder",power:"mdi:meter-electric",energy:"mdi:meter-electric",illuminance:"mdi:brightness-5",co2:"mdi:molecule-co2",pm25:"mdi:air-filter",battery:"mdi:battery"},et="mdi:chip";function tt(e,t,i){const s=((e||"")+" "+(t||"")).toLowerCase();for(const{re:e,icon:t}of i??Ze)if(e.test(s))return t;return et}const it=["light","switch","cover","valve","lock","climate","fan","media_player","camera","vacuum","humidifier","water_heater","alarm_control_panel","sensor","binary_sensor","event","button","number","select","update"];var st=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,nt=Math.ceil,ot=Math.floor,at="[BigNumber Error] ",rt=at+"Number primitive has more than 15 significant digits: ",lt=1e14,ct=14,ht=9007199254740991,dt=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],pt=1e7,ut=1e9;function _t(e){var t=0|e;return e>0||e===t?t:t-1}function mt(e){for(var t,i,s=1,n=e.length,o=e[0]+"";s
c^i?1:-1;for(r=(l=n.length)<(c=o.length)?l:c,a=0;ao[a]^i?1:-1;return l==c?0:l>c^i?1:-1}function ft(e,t,i,s){if(ei||e!==ot(e))throw Error(at+(s||"Argument")+("number"==typeof e?ei?" out of range: ":" not an integer: ":" not a primitive number: ")+String(e))}function vt(e){var t=e.c.length-1;return _t(e.e/ct)==t&&e.c[t]%2!=0}function yt(e,t){return(e.length>1?e.charAt(0)+"."+e.slice(1):e)+(t<0?"e":"e+")+t}function bt(e,t,i){var s,n;if(t<0){for(n=i+".";++t;n+=i);e=n+e}else if(++t>(s=e.length)){for(n=i,t-=s;--t;n+=i);e+=n}else ty?p.c=p.e=null:e.e=10;l/=10,r++);return void(r>y?p.c=p.e=null:(p.e=r,p.c=[e]))}d=String(e)}else{if(!st.test(d=String(e)))return n(p,d,c);p.s=45==d.charCodeAt(0)?(d=d.slice(1),-1):1}(r=d.indexOf("."))>-1&&(d=d.replace(".","")),(l=d.search(/e/i))>0?(r<0&&(r=l),r+=+d.slice(l+1),d=d.substring(0,l)):r<0&&(r=d.length)}else{if(ft(t,2,$.length,"Base"),10==t&&S)return T(p=new M(e),_+p.e+1,m);if(d=String(e),c="number"==typeof e){if(0*e!=0)return n(p,d,c,t);if(p.s=1/e<0?(d=d.slice(1),-1):1,M.DEBUG&&d.replace(/^0\.0*|\./,"").length>15)throw Error(rt+e)}else p.s=45===d.charCodeAt(0)?(d=d.slice(1),-1):1;for(i=$.slice(0,t),r=l=0,h=d.length;lr){r=h;continue}}else if(!a&&(d==d.toUpperCase()&&(d=d.toLowerCase())||d==d.toLowerCase()&&(d=d.toUpperCase()))){a=!0,l=-1,r=0;continue}return n(p,String(e),c,t)}c=!1,(r=(d=s(d,t,10,p.s)).indexOf("."))>-1?d=d.replace(".",""):r=d.length}for(l=0;48===d.charCodeAt(l);l++);for(h=d.length;48===d.charCodeAt(--h););if(d=d.slice(l,++h)){if(h-=l,c&&M.DEBUG&&h>15&&(e>ht||e!==ot(e)))throw Error(rt+p.s*e);if((r=r-l-1)>y)p.c=p.e=null;else if(r=f)?yt(l,a):bt(l,a,"0");else if(o=(e=T(new M(e),t,i)).e,r=(l=mt(e.c)).length,1==s||2==s&&(t<=o||o<=g)){for(;ra),l=bt(l,o,"0"),o+1>r){if(--t>0)for(l+=".";t--;l+="0");}else if((t+=o-r)>0)for(o+1==r&&(l+=".");t--;l+="0");return e.s<0&&n?"-"+l:l}function D(e,t){for(var i,s,n=1,o=new M(e[0]);n=10;n/=10,s++);return(i=s+i*ct-1)>y?e.c=e.e=null:i=10;r/=10,n++);if((o=t-n)<0)o+=ct,a=t,l=d[c=0],h=ot(l/p[n-a-1]%10);else if((c=nt((o+1)/ct))>=d.length){if(!s)break e;for(;d.length<=c;d.push(0));l=h=0,n=1,a=(o%=ct)-ct+1}else{for(l=r=d[c],n=1;r>=10;r/=10,n++);h=(a=(o%=ct)-ct+n)<0?0:ot(l/p[n-a-1]%10)}if(s=s||t<0||null!=d[c+1]||(a<0?l:l%p[n-a-1]),s=i<4?(h||s)&&(0==i||i==(e.s<0?3:2)):h>5||5==h&&(4==i||s||6==i&&(o>0?a>0?l/p[n-a]:0:d[c-1])%10&1||i==(e.s<0?8:7)),t<1||!d[0])return d.length=0,s?(t-=e.e+1,d[0]=p[(ct-t%ct)%ct],e.e=-t||0):d[0]=e.e=0,e;if(0==o?(d.length=c,r=1,c--):(d.length=c+1,r=p[ct-o],d[c]=a>0?ot(l/p[n-a]%p[a])*r:0),s)for(;;){if(0==c){for(o=1,a=d[0];a>=10;a/=10,o++);for(a=d[0]+=r,r=1;a>=10;a/=10,r++);o!=r&&(e.e++,d[0]==lt&&(d[0]=1));break}if(d[c]+=r,d[c]!=lt)break;d[c--]=0,r=1}for(o=d.length;0===d[--o];d.pop());}e.e>y?e.c=e.e=null:e.e=f?yt(t,i):bt(t,i,"0"),e.s<0?"-"+t:t)}return M.clone=e,M.ROUND_UP=0,M.ROUND_DOWN=1,M.ROUND_CEIL=2,M.ROUND_FLOOR=3,M.ROUND_HALF_UP=4,M.ROUND_HALF_DOWN=5,M.ROUND_HALF_EVEN=6,M.ROUND_HALF_CEIL=7,M.ROUND_HALF_FLOOR=8,M.EUCLID=9,M.config=M.set=function(e){var t,i;if(null!=e){if("object"!=typeof e)throw Error(at+"Object expected: "+e);if(e.hasOwnProperty(t="DECIMAL_PLACES")&&(ft(i=e[t],0,ut,t),_=i),e.hasOwnProperty(t="ROUNDING_MODE")&&(ft(i=e[t],0,8,t),m=i),e.hasOwnProperty(t="EXPONENTIAL_AT")&&((i=e[t])&&i.pop?(ft(i[0],-ut,0,t),ft(i[1],0,ut,t),g=i[0],f=i[1]):(ft(i,-ut,ut,t),g=-(f=i<0?-i:i))),e.hasOwnProperty(t="RANGE"))if((i=e[t])&&i.pop)ft(i[0],-ut,-1,t),ft(i[1],1,ut,t),v=i[0],y=i[1];else{if(ft(i,-ut,ut,t),!i)throw Error(at+t+" cannot be zero: "+i);v=-(y=i<0?-i:i)}if(e.hasOwnProperty(t="CRYPTO")){if((i=e[t])!==!!i)throw Error(at+t+" not true or false: "+i);if(i){if("undefined"==typeof crypto||!crypto||!crypto.getRandomValues&&!crypto.randomBytes)throw b=!i,Error(at+"crypto unavailable");b=i}else b=i}if(e.hasOwnProperty(t="MODULO_MODE")&&(ft(i=e[t],0,9,t),w=i),e.hasOwnProperty(t="POW_PRECISION")&&(ft(i=e[t],0,ut,t),k=i),e.hasOwnProperty(t="FORMAT")){if("object"!=typeof(i=e[t]))throw Error(at+t+" not an object: "+i);x=i}if(e.hasOwnProperty(t="ALPHABET")){if("string"!=typeof(i=e[t])||/^.?$|[+\-.\s]|(.).*\1/.test(i))throw Error(at+t+" invalid: "+i);S="0123456789"==i.slice(0,10),$=i}}return{DECIMAL_PLACES:_,ROUNDING_MODE:m,EXPONENTIAL_AT:[g,f],RANGE:[v,y],CRYPTO:b,MODULO_MODE:w,POW_PRECISION:k,FORMAT:x,ALPHABET:$}},M.isBigNumber=function(e){if(!e||!0!==e._isBigNumber)return!1;if(!M.DEBUG)return!0;var t,i,s=e.c,n=e.e,o=e.s;e:if("[object Array]"=={}.toString.call(s)){if((1===o||-1===o)&&n>=-ut&&n<=ut&&n===ot(n)){if(0===s[0]){if(0===n&&1===s.length)return!0;break e}if((t=(n+1)%ct)<1&&(t+=ct),String(s[0]).length==t){for(t=0;t=lt||i!==ot(i))break e;if(0!==i)return!0}}}else if(null===s&&null===n&&(null===o||1===o||-1===o))return!0;throw Error(at+"Invalid BigNumber: "+e)},M.maximum=M.max=function(){return D(arguments,-1)},M.minimum=M.min=function(){return D(arguments,1)},M.random=(o=9007199254740992,a=Math.random()*o&2097151?function(){return ot(Math.random()*o)}:function(){return 8388608*(1073741824*Math.random()|0)+(8388608*Math.random()|0)},function(e){var t,i,s,n,o,r=0,l=[],c=new M(u);if(null==e?e=_:ft(e,0,ut),n=nt(e/ct),b)if(crypto.getRandomValues){for(t=crypto.getRandomValues(new Uint32Array(n*=2));r>>11))>=9e15?(i=crypto.getRandomValues(new Uint32Array(2)),t[r]=i[0],t[r+1]=i[1]):(l.push(o%1e14),r+=2);r=n/2}else{if(!crypto.randomBytes)throw b=!1,Error(at+"crypto unavailable");for(t=crypto.randomBytes(n*=7);r=9e15?crypto.randomBytes(7).copy(t,r):(l.push(o%1e14),r+=7);r=n/7}if(!b)for(;r=10;o/=10,r++);ri-1&&(null==a[n+1]&&(a[n+1]=0),a[n+1]+=a[n]/i|0,a[n]%=i)}return a.reverse()}return function(s,n,o,a,r){var l,c,h,d,p,u,g,f,v=s.indexOf("."),y=_,b=m;for(v>=0&&(d=k,k=0,s=s.replace(".",""),u=(f=new M(n)).pow(s.length-v),k=d,f.c=t(bt(mt(u.c),u.e,"0"),10,o,e),f.e=f.c.length),h=d=(g=t(s,n,o,r?(l=$,e):(l=e,$))).length;0==g[--d];g.pop());if(!g[0])return l.charAt(0);if(v<0?--h:(u.c=g,u.e=h,u.s=a,g=(u=i(u,f,y,b,o)).c,p=u.r,h=u.e),v=g[c=h+y+1],d=o/2,p=p||c<0||null!=g[c+1],p=b<4?(null!=v||p)&&(0==b||b==(u.s<0?3:2)):v>d||v==d&&(4==b||p||6==b&&1&g[c-1]||b==(u.s<0?8:7)),c<1||!g[0])s=p?bt(l.charAt(1),-y,l.charAt(0)):l.charAt(0);else{if(g.length=c,p)for(--o;++g[--c]>o;)g[c]=0,c||(++h,g=[1].concat(g));for(d=g.length;!g[--d];);for(v=0,s="";v<=d;s+=l.charAt(g[v++]));s=bt(s,h,l.charAt(0))}return s}}(),i=function(){function e(e,t,i){var s,n,o,a,r=0,l=e.length,c=t%pt,h=t/pt|0;for(e=e.slice();l--;)r=((n=c*(o=e[l]%pt)+(s=h*o+(a=e[l]/pt|0)*c)%pt*pt+r)/i|0)+(s/pt|0)+h*a,e[l]=n%i;return r&&(e=[r].concat(e)),e}function t(e,t,i,s){var n,o;if(i!=s)o=i>s?1:-1;else for(n=o=0;nt[n]?1:-1;break}return o}function i(e,t,i,s){for(var n=0;i--;)e[i]-=n,n=e[i]1;e.splice(0,1));}return function(s,n,o,a,r){var l,c,h,d,p,u,_,m,g,f,v,y,b,w,k,x,$,S=s.s==n.s?1:-1,C=s.c,D=n.c;if(!(C&&C[0]&&D&&D[0]))return new M(s.s&&n.s&&(C?!D||C[0]!=D[0]:D)?C&&0==C[0]||!D?0*S:S/0:NaN);for(g=(m=new M(S)).c=[],S=o+(c=s.e-n.e)+1,r||(r=lt,c=_t(s.e/ct)-_t(n.e/ct),S=S/ct|0),h=0;D[h]==(C[h]||0);h++);if(D[h]>(C[h]||0)&&c--,S<0)g.push(1),d=!0;else{for(w=C.length,x=D.length,h=0,S+=2,(p=ot(r/(D[0]+1)))>1&&(D=e(D,p,r),C=e(C,p,r),x=D.length,w=C.length),b=x,v=(f=C.slice(0,x)).length;v=r/2&&k++;do{if(p=0,(l=t(D,f,x,v))<0){if(y=f[0],x!=v&&(y=y*r+(f[1]||0)),(p=ot(y/k))>1)for(p>=r&&(p=r-1),_=(u=e(D,p,r)).length,v=f.length;1==t(u,f,_,v);)p--,i(u,x<_?$:D,_,r),_=u.length,l=1;else 0==p&&(l=p=1),_=(u=D.slice()).length;if(_=10;S/=10,h++);T(m,o+(m.e=h+c*ct-1)+1,a,d)}else m.e=c,m.r=+d;return m}}(),r=/^(-?)0([xbo])(?=\w[\w.]*$)/i,l=/^([^.]+)\.$/,c=/^\.([^.]+)$/,h=/^-?(Infinity|NaN)$/,d=/^\s*\+(?=[\w.])|^\s+|\s+$/g,n=function(e,t,i,s){var n,o=i?t:t.replace(d,"");if(h.test(o))e.s=isNaN(o)?null:o<0?-1:1;else{if(!i&&(o=o.replace(r,function(e,t,i){return n="x"==(i=i.toLowerCase())?16:"b"==i?2:8,s&&s!=n?e:t}),s&&(n=s,o=o.replace(l,"$1").replace(c,"0.$1")),t!=o))return new M(o,n);if(M.DEBUG)throw Error(at+"Not a"+(s?" base "+s:"")+" number: "+t);e.s=null}e.c=e.e=null},p.absoluteValue=p.abs=function(){var e=new M(this);return e.s<0&&(e.s=1),e},p.comparedTo=function(e,t){return gt(this,new M(e,t))},p.decimalPlaces=p.dp=function(e,t){var i,s,n,o=this;if(null!=e)return ft(e,0,ut),null==t?t=m:ft(t,0,8),T(new M(o),e+o.e+1,t);if(!(i=o.c))return null;if(s=((n=i.length-1)-_t(this.e/ct))*ct,n=i[n])for(;n%10==0;n/=10,s--);return s<0&&(s=0),s},p.dividedBy=p.div=function(e,t){return i(this,new M(e,t),_,m)},p.dividedToIntegerBy=p.idiv=function(e,t){return i(this,new M(e,t),0,1)},p.exponentiatedBy=p.pow=function(e,t){var i,s,n,o,a,r,l,c,h=this;if((e=new M(e)).c&&!e.isInteger())throw Error(at+"Exponent not an integer: "+I(e));if(null!=t&&(t=new M(t)),a=e.e>14,!h.c||!h.c[0]||1==h.c[0]&&!h.e&&1==h.c.length||!e.c||!e.c[0])return c=new M(Math.pow(+I(h),a?e.s*(2-vt(e)):+I(e))),t?c.mod(t):c;if(r=e.s<0,t){if(t.c?!t.c[0]:!t.s)return new M(NaN);(s=!r&&h.isInteger()&&t.isInteger())&&(h=h.mod(t))}else{if(e.e>9&&(h.e>0||h.e<-1||(0==h.e?h.c[0]>1||a&&h.c[1]>=24e7:h.c[0]<8e13||a&&h.c[0]<=9999975e7)))return o=h.s<0&&vt(e)?-0:0,h.e>-1&&(o=1/o),new M(r?1/o:o);k&&(o=nt(k/ct+2))}for(a?(i=new M(.5),r&&(e.s=1),l=vt(e)):l=(n=Math.abs(+I(e)))%2,c=new M(u);;){if(l){if(!(c=c.times(h)).c)break;o?c.c.length>o&&(c.c.length=o):s&&(c=c.mod(t))}if(n){if(0===(n=ot(n/2)))break;l=n%2}else if(T(e=e.times(i),e.e+1,1),e.e>14)l=vt(e);else{if(0===(n=+I(e)))break;l=n%2}h=h.times(h),o?h.c&&h.c.length>o&&(h.c.length=o):s&&(h=h.mod(t))}return s?c:(r&&(c=u.div(c)),t?c.mod(t):o?T(c,k,m,void 0):c)},p.integerValue=function(e){var t=new M(this);return null==e?e=m:ft(e,0,8),T(t,t.e+1,e)},p.isEqualTo=p.eq=function(e,t){return 0===gt(this,new M(e,t))},p.isFinite=function(){return!!this.c},p.isGreaterThan=p.gt=function(e,t){return gt(this,new M(e,t))>0},p.isGreaterThanOrEqualTo=p.gte=function(e,t){return 1===(t=gt(this,new M(e,t)))||0===t},p.isInteger=function(){return!!this.c&&_t(this.e/ct)>this.c.length-2},p.isLessThan=p.lt=function(e,t){return gt(this,new M(e,t))<0},p.isLessThanOrEqualTo=p.lte=function(e,t){return-1===(t=gt(this,new M(e,t)))||0===t},p.isNaN=function(){return!this.s},p.isNegative=function(){return this.s<0},p.isPositive=function(){return this.s>0},p.isZero=function(){return!!this.c&&0==this.c[0]},p.minus=function(e,t){var i,s,n,o,a=this,r=a.s;if(t=(e=new M(e,t)).s,!r||!t)return new M(NaN);if(r!=t)return e.s=-t,a.plus(e);var l=a.e/ct,c=e.e/ct,h=a.c,d=e.c;if(!l||!c){if(!h||!d)return h?(e.s=-t,e):new M(d?a:NaN);if(!h[0]||!d[0])return d[0]?(e.s=-t,e):new M(h[0]?a:3==m?-0:0)}if(l=_t(l),c=_t(c),h=h.slice(),r=l-c){for((o=r<0)?(r=-r,n=h):(c=l,n=d),n.reverse(),t=r;t--;n.push(0));n.reverse()}else for(s=(o=(r=h.length)<(t=d.length))?r:t,r=t=0;t0)for(;t--;h[i++]=0);for(t=lt-1;s>r;){if(h[--s]=0;){for(i=0,p=y[n]%g,u=y[n]/g|0,o=n+(a=l);o>n;)i=((c=p*(c=v[--a]%g)+(r=u*c+(h=v[a]/g|0)*p)%g*g+_[o]+i)/m|0)+(r/g|0)+u*h,_[o--]=c%m;_[o]=i}return i?++s:_.splice(0,1),P(e,_,s)},p.negated=function(){var e=new M(this);return e.s=-e.s||null,e},p.plus=function(e,t){var i,s=this,n=s.s;if(t=(e=new M(e,t)).s,!n||!t)return new M(NaN);if(n!=t)return e.s=-t,s.minus(e);var o=s.e/ct,a=e.e/ct,r=s.c,l=e.c;if(!o||!a){if(!r||!l)return new M(n/0);if(!r[0]||!l[0])return l[0]?e:new M(r[0]?s:0*n)}if(o=_t(o),a=_t(a),r=r.slice(),n=o-a){for(n>0?(a=o,i=l):(n=-n,i=r),i.reverse();n--;i.push(0));i.reverse()}for((n=r.length)-(t=l.length)<0&&(i=l,l=r,r=i,t=n),n=0;t;)n=(r[--t]=r[t]+l[t]+n)/lt|0,r[t]=lt===r[t]?0:r[t]%lt;return n&&(r=[n].concat(r),++a),P(e,r,a)},p.precision=p.sd=function(e,t){var i,s,n,o=this;if(null!=e&&e!==!!e)return ft(e,1,ut),null==t?t=m:ft(t,0,8),T(new M(o),e,t);if(!(i=o.c))return null;if(s=(n=i.length-1)*ct+1,n=i[n]){for(;n%10==0;n/=10,s--);for(n=i[0];n>=10;n/=10,s++);}return e&&o.e+1>s&&(s=o.e+1),s},p.shiftedBy=function(e){return ft(e,-9007199254740991,ht),this.times("1e"+e)},p.squareRoot=p.sqrt=function(){var e,t,s,n,o,a=this,r=a.c,l=a.s,c=a.e,h=_+4,d=new M("0.5");if(1!==l||!r||!r[0])return new M(!l||l<0&&(!r||r[0])?NaN:r?a:1/0);if(0==(l=Math.sqrt(+I(a)))||l==1/0?(((t=mt(r)).length+c)%2==0&&(t+="0"),l=Math.sqrt(+t),c=_t((c+1)/2)-(c<0||c%2),s=new M(t=l==1/0?"5e"+c:(t=l.toExponential()).slice(0,t.indexOf("e")+1)+c)):s=new M(l+""),s.c[0])for((l=(c=s.e)+h)<3&&(l=0);;)if(o=s,s=d.times(o.plus(i(a,o,h,1))),mt(o.c).slice(0,l)===(t=mt(s.c)).slice(0,l)){if(s.e0&&_>0){for(o=_%r||r,h=u.substr(0,o);o<_;o+=r)h+=c+u.substr(o,r);l>0&&(h+=c+u.slice(o)),p&&(h="-"+h)}s=d?h+(i.decimalSeparator||"")+((l=+i.fractionGroupSize)?d.replace(new RegExp("\\d{"+l+"}\\B","g"),"$&"+(i.fractionGroupSeparator||"")):d):h}return(i.prefix||"")+s+(i.suffix||"")},p.toFraction=function(e){var t,s,n,o,a,r,l,c,h,d,p,_,g=this,f=g.c;if(null!=e&&(!(l=new M(e)).isInteger()&&(l.c||1!==l.s)||l.lt(u)))throw Error(at+"Argument "+(l.isInteger()?"out of range: ":"not an integer: ")+I(l));if(!f)return new M(g);for(t=new M(u),h=s=new M(u),n=c=new M(u),_=mt(f),a=t.e=_.length-g.e-1,t.c[0]=dt[(r=a%ct)<0?ct+r:r],e=!e||l.comparedTo(t)>0?a>0?t:h:l,r=y,y=1/0,l=new M(_),c.c[0]=0;d=i(l,t,0,1),1!=(o=s.plus(d.times(n))).comparedTo(e);)s=n,n=o,h=c.plus(d.times(o=h)),c=o,t=l.minus(d.times(o=t)),l=o;return o=i(e.minus(s),n,0,1),c=c.plus(o.times(h)),s=s.plus(o.times(n)),c.s=h.s=g.s,p=i(h,n,a*=2,m).minus(g).abs().comparedTo(i(c,s,a,m).minus(g).abs())<1?[h,n]:[c,s],y=r,p},p.toNumber=function(){return+I(this)},p.toPrecision=function(e,t){return null!=e&&ft(e,1,ut),C(this,e,t,2)},p.toString=function(e){var t,i=this,n=i.s,o=i.e;return null===o?n?(t="Infinity",n<0&&(t="-"+t)):t="NaN":(null==e?t=o<=g||o>=f?yt(mt(i.c),o):bt(mt(i.c),o,"0"):10===e&&S?t=bt(mt((i=T(new M(i),_+o+1,m)).c),i.e,"0"):(ft(e,2,$.length,"Base"),t=s(bt(mt(i.c),o,"0"),10,e,n,!0)),n<0&&i.c[0]&&(t="-"+t)),t},p.valueOf=p.toJSON=function(){return I(this)},p._isBigNumber=!0,p[Symbol.toStringTag]="BigNumber",p[Symbol.for("nodejs.util.inspect.custom")]=p.valueOf,null!=t&&M.set(t),M}(),kt=class{key;left=null;right=null;constructor(e){this.key=e}},xt=class extends kt{constructor(e){super(e)}},$t=class{size=0;modificationCount=0;splayCount=0;splay(e){const t=this.root;if(null==t)return this.compare(e,e),-1;let i=null,s=null,n=null,o=null,a=t;const r=this.compare;let l;for(;;)if(l=r(a.key,e),l>0){let t=a.left;if(null==t)break;if(l=r(t.key,e),l>0&&(a.left=t.right,t.right=a,a=t,t=a.left,null==t))break;null==i?s=a:i.left=a,i=a,a=t}else{if(!(l<0))break;{let t=a.right;if(null==t)break;if(l=r(t.key,e),l<0&&(a.right=t.left,t.left=a,a=t,t=a.right,null==t))break;null==n?o=a:n.right=a,n=a,a=t}}return null!=n&&(n.right=a.left,a.left=o),null!=i&&(i.left=a.right,a.right=s),this.root!==a&&(this.root=a,this.splayCount++),l}splayMin(e){let t=e,i=t.left;for(;null!=i;){const e=i;t.left=e.right,e.right=t,t=e,i=t.left}return t}splayMax(e){let t=e,i=t.right;for(;null!=i;){const e=i;t.right=e.left,e.left=t,t=e,i=t.right}return t}_delete(e){if(null==this.root)return null;if(0!=this.splay(e))return null;let t=this.root;const i=t,s=t.left;if(this.size--,null==s)this.root=t.right;else{const e=t.right;t=this.splayMax(s),t.right=e,this.root=t}return this.modificationCount++,i}addNewRoot(e,t){this.size++,this.modificationCount++;const i=this.root;null!=i?(t<0?(e.left=i,e.right=i.right,i.right=null):(e.right=i,e.left=i.left,i.left=null),this.root=e):this.root=e}_first(){const e=this.root;return null==e?null:(this.root=this.splayMin(e),this.root)}_last(){const e=this.root;return null==e?null:(this.root=this.splayMax(e),this.root)}clear(){this.root=null,this.size=0,this.modificationCount++}has(e){return this.validKey(e)&&0==this.splay(e)}defaultCompare(){return(e,t)=>et?1:0}wrap(){return{getRoot:()=>this.root,setRoot:e=>{this.root=e},getSize:()=>this.size,getModificationCount:()=>this.modificationCount,getSplayCount:()=>this.splayCount,setSplayCount:e=>{this.splayCount=e},splay:e=>this.splay(e),has:e=>this.has(e)}}},St=class e extends $t{root=null;compare;validKey;constructor(e,t){super(),this.compare=e??this.defaultCompare(),this.validKey=t??(e=>null!=e&&null!=e)}delete(e){return!!this.validKey(e)&&null!=this._delete(e)}deleteAll(e){for(const t of e)this.delete(t)}forEach(e){const t=this[Symbol.iterator]();let i;for(;i=t.next(),!i.done;)e(i.value,i.value,this)}add(e){const t=this.splay(e);return 0!=t&&this.addNewRoot(new xt(e),t),this}addAndReturn(e){const t=this.splay(e);return 0!=t&&this.addNewRoot(new xt(e),t),this.root.key}addAll(e){for(const t of e)this.add(t)}isEmpty(){return null==this.root}isNotEmpty(){return null!=this.root}single(){if(0==this.size)throw"Bad state: No element";if(this.size>1)throw"Bad state: Too many element";return this.root.key}first(){if(0==this.size)throw"Bad state: No element";return this._first().key}last(){if(0==this.size)throw"Bad state: No element";return this._last().key}lastBefore(e){if(null==e)throw"Invalid arguments(s)";if(null==this.root)return null;if(this.splay(e)<0)return this.root.key;let t=this.root.left;if(null==t)return null;let i=t.right;for(;null!=i;)t=i,i=t.right;return t.key}firstAfter(e){if(null==e)throw"Invalid arguments(s)";if(null==this.root)return null;if(this.splay(e)>0)return this.root.key;let t=this.root.right;if(null==t)return null;let i=t.left;for(;null!=i;)t=i,i=t.left;return t.key}retainAll(t){const i=new e(this.compare,this.validKey),s=this.modificationCount;for(const e of t){if(s!=this.modificationCount)throw"Concurrent modification during iteration.";this.validKey(e)&&0==this.splay(e)&&i.add(this.root.key)}i.size!=this.size&&(this.root=i.root,this.size=i.size,this.modificationCount++)}lookup(e){if(!this.validKey(e))return null;return 0!=this.splay(e)?null:this.root.key}intersection(t){const i=new e(this.compare,this.validKey);for(const e of this)t.has(e)&&i.add(e);return i}difference(t){const i=new e(this.compare,this.validKey);for(const e of this)t.has(e)||i.add(e);return i}union(e){const t=this.clone();return t.addAll(e),t}clone(){const t=new e(this.compare,this.validKey);return t.size=this.size,t.root=this.copyNode(this.root),t}copyNode(e){if(null==e)return null;const t=new xt(e.key);return function e(t,i){let s,n;do{if(s=t.left,n=t.right,null!=s){const t=new xt(s.key);i.left=t,e(s,t)}if(null!=n){const e=new xt(n.key);i.right=e,t=n,i=e}}while(null!=n)}(e,t),t}toSet(){return this.clone()}entries(){return new Dt(this.wrap())}keys(){return this[Symbol.iterator]()}values(){return this[Symbol.iterator]()}[Symbol.iterator](){return new Ct(this.wrap())}[Symbol.toStringTag]="[object Set]"},Mt=class{tree;path=new Array;modificationCount=null;splayCount;constructor(e){this.tree=e,this.splayCount=e.getSplayCount()}[Symbol.iterator](){return this}next(){return this.moveNext()?{done:!1,value:this.current()}:{done:!0,value:null}}current(){if(!this.path.length)return null;const e=this.path[this.path.length-1];return this.getValue(e)}rebuildPath(e){this.path.splice(0,this.path.length),this.tree.splay(e),this.path.push(this.tree.getRoot()),this.splayCount=this.tree.getSplayCount()}findLeftMostDescendent(e){for(;null!=e;)this.path.push(e),e=e.left}moveNext(){if(this.modificationCount!=this.tree.getModificationCount()){if(null==this.modificationCount){this.modificationCount=this.tree.getModificationCount();let e=this.tree.getRoot();for(;null!=e;)this.path.push(e),e=e.left;return this.path.length>0}throw"Concurrent modification during iteration."}if(!this.path.length)return!1;this.splayCount!=this.tree.getSplayCount()&&this.rebuildPath(this.path[this.path.length-1].key);let e=this.path[this.path.length-1],t=e.right;if(null!=t){for(;null!=t;)this.path.push(t),t=t.left;return!0}for(this.path.pop();this.path.length&&this.path[this.path.length-1].right===e;)e=this.path.pop();return this.path.length>0}},Ct=class extends Mt{getValue(e){return e.key}},Dt=class extends Mt{getValue(e){return[e.key,e.key]}},Pt=e=>()=>e,Tt=e=>{const t=e?(t,i)=>i.minus(t).abs().isLessThanOrEqualTo(e):Pt(!1);return(e,i)=>t(e,i)?0:e.comparedTo(i)};function It(e){const t=e?(t,i,s,n,o)=>t.exponentiatedBy(2).isLessThanOrEqualTo(n.minus(i).exponentiatedBy(2).plus(o.minus(s).exponentiatedBy(2)).times(e)):Pt(!1);return(e,i,s)=>{const n=e.x,o=e.y,a=s.x,r=s.y,l=o.minus(r).times(i.x.minus(a)).minus(n.minus(a).times(i.y.minus(r)));return t(l,n,o,a,r)?0:l.comparedTo(0)}}var Rt=e=>e,At=e=>{if(e){const t=new St(Tt(e)),i=new St(Tt(e)),s=(e,t)=>t.addAndReturn(e),n=e=>({x:s(e.x,t),y:s(e.y,i)});return n({x:new wt(0),y:new wt(0)}),n}return Rt},zt=e=>({set:e=>{Ft=zt(e)},reset:()=>zt(e),compare:Tt(e),snap:At(e),orient:It(e)}),Ft=zt(),Et=(e,t)=>e.ll.x.isLessThanOrEqualTo(t.x)&&t.x.isLessThanOrEqualTo(e.ur.x)&&e.ll.y.isLessThanOrEqualTo(t.y)&&t.y.isLessThanOrEqualTo(e.ur.y),Nt=(e,t)=>{if(t.ur.x.isLessThan(e.ll.x)||e.ur.x.isLessThan(t.ll.x)||t.ur.y.isLessThan(e.ll.y)||e.ur.y.isLessThan(t.ll.y))return null;const i=e.ll.x.isLessThan(t.ll.x)?t.ll.x:e.ll.x,s=e.ur.x.isLessThan(t.ur.x)?e.ur.x:t.ur.x;return{ll:{x:i,y:e.ll.y.isLessThan(t.ll.y)?t.ll.y:e.ll.y},ur:{x:s,y:e.ur.y.isLessThan(t.ur.y)?e.ur.y:t.ur.y}}},Ot=(e,t)=>e.x.times(t.y).minus(e.y.times(t.x)),Lt=(e,t)=>e.x.times(t.x).plus(e.y.times(t.y)),Ht=e=>Lt(e,e).sqrt(),Bt=(e,t,i)=>{const s={x:t.x.minus(e.x),y:t.y.minus(e.y)},n={x:i.x.minus(e.x),y:i.y.minus(e.y)};return Ot(n,s).div(Ht(n)).div(Ht(s))},qt=(e,t,i)=>{const s={x:t.x.minus(e.x),y:t.y.minus(e.y)},n={x:i.x.minus(e.x),y:i.y.minus(e.y)};return Lt(n,s).div(Ht(n)).div(Ht(s))},Wt=(e,t,i)=>t.y.isZero()?null:{x:e.x.plus(t.x.div(t.y).times(i.minus(e.y))),y:i},jt=(e,t,i)=>t.x.isZero()?null:{x:i,y:e.y.plus(t.y.div(t.x).times(i.minus(e.x)))},Ut=class e{point;isLeft;segment;otherSE;consumedBy;static compare(t,i){const s=e.comparePoints(t.point,i.point);return 0!==s?s:(t.point!==i.point&&t.link(i),t.isLeft!==i.isLeft?t.isLeft?1:-1:Qt.compare(t.segment,i.segment))}static comparePoints(e,t){return e.x.isLessThan(t.x)?-1:e.x.isGreaterThan(t.x)?1:e.y.isLessThan(t.y)?-1:e.y.isGreaterThan(t.y)?1:0}constructor(e,t){void 0===e.events?e.events=[this]:e.events.push(this),this.point=e,this.isLeft=t}link(e){if(e.point===this.point)throw new Error("Tried to link already linked events");const t=e.point.events;for(let e=0,i=t.length;e{const s=i.otherSE;t.set(i,{sine:Bt(this.point,e.point,s.point),cosine:qt(this.point,e.point,s.point)})};return(e,s)=>{t.has(e)||i(e),t.has(s)||i(s);const{sine:n,cosine:o}=t.get(e),{sine:a,cosine:r}=t.get(s);return n.isGreaterThanOrEqualTo(0)&&a.isGreaterThanOrEqualTo(0)?o.isLessThan(r)?1:o.isGreaterThan(r)?-1:0:n.isLessThan(0)&&a.isLessThan(0)?o.isLessThan(r)?-1:o.isGreaterThan(r)?1:0:a.isLessThan(n)?-1:a.isGreaterThan(n)?1:0}}},Gt=class e{events;poly;_isExteriorRing;_enclosingRing;static factory(t){const i=[];for(let s=0,n=t.length;s0&&(e=i)}let t=e.segment.prevInResult(),i=t?t.prevInResult():null;for(;;){if(!t)return null;if(!i)return t.ringOut;if(i.ringOut!==t.ringOut)return i.ringOut?.enclosingRing()!==t.ringOut?t.ringOut:t.ringOut?.enclosingRing();t=i.prevInResult(),i=t?t.prevInResult():null}}},Vt=class{exteriorRing;interiorRings;constructor(e){this.exteriorRing=e,e.poly=this,this.interiorRings=[]}addInterior(e){this.interiorRings.push(e),e.poly=this}getGeom(){const e=this.exteriorRing.getGeom();if(null===e)return null;const t=[e];for(let e=0,i=this.interiorRings.length;e0?(this.tree.delete(t),i.push(e)):(this.segments.push(t),t.prev=s)}else{if(s&&n){const e=s.getIntersection(n);if(null!==e){if(!s.isAnEndpoint(e)){const t=this._splitSafely(s,e);for(let e=0,s=t.length;e0)return-1;const s=t.comparePoint(e.rightSE.point);return 0!==s?s:-1}if(i.isGreaterThan(s)){if(a.isLessThan(r)&&a.isLessThan(c))return-1;if(a.isGreaterThan(r)&&a.isGreaterThan(c))return 1;const i=t.comparePoint(e.leftSE.point);if(0!==i)return i;const s=e.comparePoint(t.rightSE.point);return s<0?1:s>0?-1:1}if(a.isLessThan(r))return-1;if(a.isGreaterThan(r))return 1;if(n.isLessThan(o)){const i=t.comparePoint(e.rightSE.point);if(0!==i)return i}if(n.isGreaterThan(o)){const i=e.comparePoint(t.rightSE.point);if(i<0)return 1;if(i>0)return-1}if(!n.eq(o)){const e=l.minus(a),t=n.minus(i),h=c.minus(r),d=o.minus(s);if(e.isGreaterThan(t)&&h.isLessThan(d))return 1;if(e.isLessThan(t)&&h.isGreaterThan(d))return-1}return n.isGreaterThan(o)?1:n.isLessThan(o)||l.isLessThan(c)?-1:l.isGreaterThan(c)?1:e.idt.id?1:0}constructor(e,t,i,s){this.id=++Zt,this.leftSE=e,e.segment=this,e.otherSE=t,this.rightSE=t,t.segment=this,t.otherSE=e,this.rings=i,this.windings=s}static fromRing(t,i,s){let n,o,a;const r=Ut.comparePoints(t,i);if(r<0)n=t,o=i,a=1;else{if(!(r>0))throw new Error(`Tried to create degenerate segment at [${t.x}, ${t.y}]`);n=i,o=t,a=-1}const l=new Ut(n,!0),c=new Ut(o,!1);return new e(l,c,[s],[a])}replaceRightSE(e){this.rightSE=e,this.rightSE.segment=this,this.rightSE.otherSE=this.leftSE,this.leftSE.otherSE=this.rightSE}bbox(){const e=this.leftSE.point.y,t=this.rightSE.point.y;return{ll:{x:this.leftSE.point.x,y:e.isLessThan(t)?e:t},ur:{x:this.rightSE.point.x,y:e.isGreaterThan(t)?e:t}}}vector(){return{x:this.rightSE.point.x.minus(this.leftSE.point.x),y:this.rightSE.point.y.minus(this.leftSE.point.y)}}isAnEndpoint(e){return e.x.eq(this.leftSE.point.x)&&e.y.eq(this.leftSE.point.y)||e.x.eq(this.rightSE.point.x)&&e.y.eq(this.rightSE.point.y)}comparePoint(e){return Ft.orient(this.leftSE.point,e,this.rightSE.point)}getIntersection(e){const t=this.bbox(),i=e.bbox(),s=Nt(t,i);if(null===s)return null;const n=this.leftSE.point,o=this.rightSE.point,a=e.leftSE.point,r=e.rightSE.point,l=Et(t,a)&&0===this.comparePoint(a),c=Et(i,n)&&0===e.comparePoint(n),h=Et(t,r)&&0===this.comparePoint(r),d=Et(i,o)&&0===e.comparePoint(o);if(c&&l)return d&&!h?o:!d&&h?r:null;if(c)return h&&n.x.eq(r.x)&&n.y.eq(r.y)?null:n;if(l)return d&&o.x.eq(a.x)&&o.y.eq(a.y)?null:a;if(d&&h)return null;if(d)return o;if(h)return r;const p=((e,t,i,s)=>{if(t.x.isZero())return jt(i,s,e.x);if(s.x.isZero())return jt(e,t,i.x);if(t.y.isZero())return Wt(i,s,e.y);if(s.y.isZero())return Wt(e,t,i.y);const n=Ot(t,s);if(n.isZero())return null;const o={x:i.x.minus(e.x),y:i.y.minus(e.y)},a=Ot(o,t).div(n),r=Ot(o,s).div(n),l=e.x.plus(r.times(t.x)),c=i.x.plus(a.times(s.x)),h=e.y.plus(r.times(t.y)),d=i.y.plus(a.times(s.y));return{x:l.plus(c).div(2),y:h.plus(d).div(2)}})(n,this.vector(),a,e.vector());return null===p?null:Et(s,p)?Ft.snap(p):null}split(t){const i=[],s=void 0!==t.events,n=new Ut(t,!0),o=new Ut(t,!1),a=this.rightSE;this.replaceRightSE(o),i.push(o),i.push(n);const r=new e(n,a,this.rings.slice(),this.windings.slice());return Ut.comparePoints(r.leftSE.point,r.rightSE.point)>0&&r.swapEvents(),Ut.comparePoints(this.leftSE.point,this.rightSE.point)>0&&this.swapEvents(),s&&(n.checkForConsuming(),o.checkForConsuming()),i}swapEvents(){const e=this.rightSE;this.rightSE=this.leftSE,this.leftSE=e,this.leftSE.isLeft=!0,this.rightSE.isLeft=!1;for(let e=0,t=this.windings.length;e0){const e=i;i=s,s=e}if(i.prev===s){const e=i;i=s,s=e}for(let e=0,t=s.rings.length;e1===e.length&&e[0].isSubject;this._isInResult=i(e)!==i(t);break}}return this._isInResult}},ei=class{poly;isExterior;segments;bbox;constructor(e,t,i){if(!Array.isArray(e)||0===e.length)throw new Error("Input geometry is not a valid Polygon or MultiPolygon");if(this.poly=t,this.isExterior=i,this.segments=[],"number"!=typeof e[0][0]||"number"!=typeof e[0][1])throw new Error("Input geometry is not a valid Polygon or MultiPolygon");const s=Ft.snap({x:new wt(e[0][0]),y:new wt(e[0][1])});this.bbox={ll:{x:s.x,y:s.y},ur:{x:s.x,y:s.y}};let n=s;for(let t=1,i=e.length;tXt.run("union",e,t),ni=(e,...t)=>Xt.run("intersection",e,t),oi=(e,...t)=>Xt.run("difference",e,t);function ai(e){const t=Math.max(0,Math.min(120,(e-40)/140*120));return`hsl(${Math.round(t)}, 85%, 55%)`}function ri(e,t){if(!(Number.isFinite(e)&&t>0))return e;const i=Math.round(e/t)*t;return Math.abs(i-e)<=1e-9*t?e:i}function li(e,t){if(t){const t=e/2.54;let i=Math.floor(t/12),s=Math.round(t-12*i);return 12===s&&(i+=1,s=0),`${i}′ ${s}″`}return`${(e/100).toFixed(2)} m`}function ci(e,t,i=1){const s=e[0].toFixed(i),n=e[1].toFixed(i),o=t[0].toFixed(i),a=t[1].toFixed(i),r=s=3?e.poly:e&&null!=e.x&&null!=e.y&&null!=e.w&&null!=e.h?[[e.x,e.y],[e.x+e.w,e.y],[e.x+e.w,e.y+e.h],[e.x,e.y+e.h]]:null}function di(e){const t=[];for(const i of e||[])i?.poly?.length>=3?t.push({poly:i.poly.map(e=>e.join(",")).join(" ")}):i&&null!=i.x&&null!=i.y&&null!=i.w&&null!=i.h&&t.push({rect:{x:i.x,y:i.y,w:i.w,h:i.h,rx:.03*Math.min(i.w,i.h)}});return t}function pi(e){const t=[],i=new Set;for(const s of e||[]){const e=hi(s);if(e)for(let s=0;s=90?e-=180:e<-90&&(e+=180),s.step&&s.step>0){const i=Math.sqrt(d),o=Math.min(Math.max(s.length||0,0)/2,i/2);let r=Math.round(p*i/s.step)*s.step;Math.abs(p*i-i/2)<=s.step/2&&(r=i/2),r=Math.max(o,Math.min(i-o,r));const l=r/i;n={x:t+l*c,y:a+l*h,angle:e}}else n={x:u[0],y:u[1],angle:e}}}return n}function _i(e,t,i,s,n,o=1){const a=t*Math.PI/180,r=[Math.cos(a),Math.sin(a)];let l=null,c=o;for(const t of pi(s)){const i=[[t[0],t[1]],[t[2],t[3]]],s=t=>Math.abs(r[0]*(t[1]-e[1])-r[1]*(t[0]-e[0]));if(s(i[0])>o||s(i[1])>o)continue;const n=(i[0][0]-e[0])*r[0]+(i[0][1]-e[1])*r[1],a=(i[1][0]-e[0])*r[0]+(i[1][1]-e[1])*r[1],h=Math.min(n,a),d=Math.max(n,a),p=h>0?h:d<0?-d:0;p[e[0]+r[0]*t,e[1]+r[1]*t],g=(h+d)/2;return{wallA:m(h),wallB:m(d),sideA:u,sideB:_,midA:m((h-p)/2),midB:m((p+d)/2),wallCenter:m(g),centered:Math.abs(g)<=n}}function mi(e,t,i=!1){if("passage"===e)return 1;if(null==t||"unavailable"===t||"unknown"===t)return"window"===e?0:1;const s=function(e){return["on","open","home","detected","playing","cleaning"].includes(String(e))}(t)!==!!i;return s?1:0}function gi(e){return"passage"===e.type?[]:[e.contact,e.lock].filter(e=>"string"==typeof e&&e.length>0)}function fi(e,t,i=.001){return Math.abs(e[0]-t[0])e[1]!=l>e[1]&&e[0]<(r-o)*(e[1]-a)/(l-a)+o&&(i=!i)}return i}function yi(e,t,i){const s=i[0]-t[0],n=i[1]-t[1],o=s*s+n*n;let a=o?((e[0]-t[0])*s+(e[1]-t[1])*n)/o:0;return a=Math.max(0,Math.min(1,a)),Math.hypot(e[0]-(t[0]+a*s),e[1]-(t[1]+a*n))}function bi(e,t,i=1e-6){if(!t||t.length<2)return!1;for(let s=0;sn&&a<-n||o<-n&&a>n)&&(r>n&&l<-n||r<-n&&l>n)}function $i(e,t=24){const i=e.map(e=>e[0]),s=e.map(e=>e[1]),n=Math.min(...i),o=Math.max(...i),a=Math.min(...s),r=Math.max(...s),l=Math.max(o-n,r-a)||1;let c=0,h=0,d=0;for(let t=0;t1e-9?[h/(3*c),d/(3*c)]:[(n+o)/2,(a+r)/2],u=(t,i)=>{const s=((t,i)=>{if(!vi([t,i],e))return-1/0;let s=1/0;for(let n=0;nm&&(m=c,_=[s,l])}if(_){const[e,i]=_,s=(o-n)/t,l=(r-a)/t;for(let t=-4;t<=4;t++)for(let n=-4;n<=4;n++){const o=e+s*t/4,a=i+l*n/4,r=u(o,a);r>m&&(m=r,_=[o,a])}}return _||Si(e)||e[0]}function Si(e,t=1e-6){if(!e||e.length<3)return null;const i=e.length,s=[e.reduce((e,t)=>e+t[0],0)/i,e.reduce((e,t)=>e+t[1],0)/i];if(wi(s,e,t))return s;for(let s=0;sCi(e,t,i));return s.filter(e=>!s.some(t=>t!==e&&Ci(t,e,i)))}function Ti(e){if(!e||e.length<3)return 0;let t=0;for(let i=0;i[e[0],e[1]]),[e[0][0],e[0][1]]]]}function Ri(e,t,i){for(let s=0;s1&&fi(i[0],i[i.length-1],t)&&i.pop(),i}function zi(e,t,i=1e-6){if(!e||e.length<3||!t||t.length<2)return null;const s=t[0],n=t[t.length-1];if(fi(s,n,i))return null;const o=Ri(e,s,i),a=Ri(e,n,i);if(o<0||a<0)return null;const r=t.slice(1,-1);for(const t of r)if(!wi(t,e,i))return null;for(let i=0;i{const a=[t];let r=(s+1)%e.length;for(let t=0;t<=e.length&&(a.push(e[r]),r!==o);t++)r=(r+1)%e.length;return a.push(n),Ai(a,i)};let c,h;if(o===a){const a=Ai([...t],i);if(a.length<3||Ti(a)<=i)return null;const r=[];for(let i=0;i=0?t:[...t].reverse();for(const e of i)r.push(e)}c=Ai(r,i),h=a}else c=Ai([...l(s,o,n,a),...[...r].reverse()],i),h=Ai([...l(n,a,s,o),...r],i);return c.length<3||h.length<3||Ti(c)<=i||Ti(h)<=i||Math.abs(Ti(c)+Ti(h)-Ti(e))>Math.max(i,1e-6*Ti(e))?null:[c,h]}function Fi(e,t,i){const[s,n]=e.split(":");return"device"===s?n:"entity"===s?"lg_"+n:t&&t.startsWith("v_")?t:i()}function Ei(e){return e.length?Math.round(e.reduce((e,t)=>e+t,0)/e.length):null}function Ni(e,t){if(t>e[2]/e[3]){const i=e[3],s=e[3]*t;return{x:e[0]-(s-e[2])/2,y:e[1],w:s,h:i}}const i=e[2],s=e[2]/t;return{x:e[0],y:e[1]-(s-e[3])/2,w:i,h:s}}function Oi(e,t,i,s){if(e.length<2)return;const n=t.x+s,o=t.x+t.w-s,a=t.y+s,r=t.y+t.h-s;for(let t=0;t<60;t++){let t=!1;for(let s=0;s=0)i=t.slice(0,n).trim(),s=t.slice(n+1).trim();else{const e=t.split(".");e.length>2&&(i=e.slice(0,2).join("."),s=e.slice(2).join("."))}return/^[a-z0-9_]+\.[a-z0-9_]+$/.test(i)?n>=0&&!s||s&&!/^[a-zA-Z0-9_.-]+$/.test(s)?null:s?{entity:i,attr:s}:{entity:i}:null}function Ji(e,t){const i=String(e??"").trim(),s=String(t??"").trim(),n=Yi(s?`${i}:${s}`:i);return n?`{${n.entity}${n.attr?`:${n.attr}`:""}}`:""}function Xi(e,t,i){const s=String(t??"").trim();if(!s)return null;const n=e?.states?.[s];if(!n)return null;const o=String(i??"").trim(),a=e=>e.slice(0,60);if(o){const t=function(e){if(null==e)return null;if(Array.isArray(e)){const t=e.map(e=>null==e?"":String(e)).join(", ");return t?t.slice(0,60):null}if("object"==typeof e)return null;const t=String(e);return""===t?null:t.slice(0,60)}(n.attributes?.[o]);if(null===t)return null;const i=e?.formatEntityAttributeValue;if("function"==typeof i)try{const t=i.call(e,n,o);if("string"==typeof t&&""!==t)return{text:a(t),formatted:!0}}catch{}return{text:t,formatted:!1}}const r=n.state;if(null==r||""===r)return null;const l=e?.formatEntityState;if("function"==typeof l)try{const t=l.call(e,n);if("string"==typeof t&&""!==t)return{text:a(t),formatted:!0}}catch{}return{text:a(String(r)),formatted:!1}}function Zi(e,t,i){const s=String(t??"").trim(),n=String(i??"").trim()||s;if(!n)return e.text;const o=e.formatted&&s?function(e,t){if(!t)return e;const i=e.replace(/\s+$/,"");return i.endsWith(t)?i.slice(0,i.length-t.length).replace(/\s+$/,""):e}(e.text,s):e.text;return`${o} ${n}`}function Qi(e,t){const i=(t?.entity||"").trim();if(!i)return"";const s=e?.states?.[i],n=s?.state;if(!s||null==n||""===n||"unavailable"===n||"unknown"===n)return Vi;const o=(t?.attr||"").trim(),a=Xi(e,i,o||null);if(null===a)return Vi;return Zi(a,o?"":String(s.attributes?.unit_of_measurement??"").trim(),t?.unit)}function es(e,t,i,s=()=>!0){const n=e??"";let o=!1;const a=n.replace(/\{([^{}\r\n]+)\}/g,(e,t)=>{const n=Yi(t);return n?(o=!0,s(n.entity||"")?Qi(i,n):Vi):e});if(o)return a;const r=(t?.entity||"").trim();if(!r)return n;if(!s(r)){const e=n.indexOf(Ki);return e>=0?n.slice(0,e)+Vi+n.slice(e+2):n?`${n} ${Vi}`:Vi}const l=Qi(i,t),c=n.indexOf(Ki);return c>=0?n.slice(0,c)+l+n.slice(c+2):n?`${n} ${l}`:l}const ts=20;function is(e){const t=Number(e?.scale);if(Number.isFinite(t)&&t>0)return Math.min(20,Math.max(.15,t));return{s:.7,m:1,l:1.5}[String(e?.size??"")]??1}function ss(e,t){if(!t)return e;let i=e;for(const[e,s]of Object.entries(t))i=i.split("{"+e+"}").join(String(s));return i}const ns="#55606c",os=.55,as={c:"#607d8b",a:.18};function rs(e,t=as){const i=e&&"object"==typeof e?e:null,s=i?.a;return{c:Ie(i?.c,t.c),a:"number"==typeof s&&Number.isFinite(s)?Math.min(1,Math.max(0,s)):t.a}}function ls(e,t){const i=rs(e),s=t?.settings?.custom_fill;return s&&"object"==typeof s?rs(s,i):i}function cs(e){const t=e?.settings||{},i=!e?.plan_url,s="glow"===t.fill_mode;return{showBorders:t.show_borders??i,showNames:t.show_names??i,color:Ie(t.room_color,ns),opacity:"number"==typeof t.room_opacity?Math.min(1,Math.max(0,t.room_opacity)):os,fill:["lqi","light","temp","custom"].includes(t.fill_mode)?t.fill_mode:"none",customFill:rs(t.custom_fill),glow:"boolean"==typeof t.glow_enabled?t.glow_enabled:s,tempMin:"number"==typeof t.temp_min?t.temp_min:20,tempMax:"number"==typeof t.temp_max?t.temp_max:25,showLqi:"boolean"==typeof t.show_lqi?t.show_lqi:null,cardFontScale:"number"==typeof t.card_font_scale&&t.card_font_scale>0?Math.min(3,Math.max(.5,t.card_font_scale)):1,labelTemp:!0===t.label_temp,labelHum:!0===t.label_hum,labelLqi:!0===t.label_lqi,labelLight:!0===t.label_light,bgColor:Ie(t.bg_color,null),hideDecor:!0===t.hide_decor,hideOpenings:!0===t.hide_openings}}function hs(e,t){if(t.bgColor)return t.bgColor;const i=e?.bg_color;return Ie(i,"")}const ds={light_on:{c:"#ffd45c",a:.18},light_off:{c:"#9aa0a6",a:.14},light_none:{c:"#6b7480",a:0},temp_cold:{c:"#4fc3f7",a:.18},temp_ok:{c:"#66d17a",a:.18},temp_hot:{c:"#ffd45c",a:.18},lqi_low:{c:"#f25a4a",a:.18},lqi_high:{c:"#4bd28f",a:.18},glow_base:{c:"#0d1b2a",a:.5},glow_light:{c:"#ffd9a0",a:.85},wall_fill:{c:"#ffffff",a:1}};function ps(e){const t={},i=e?.fill_colors||{};for(const e of Object.keys(ds)){const s=ds[e],n=i[e];t[e]={c:Ie(n?.c,s.c),a:n&&"number"==typeof n.a?Math.min(1,Math.max(0,n.a)):s.a}}return t}function us(e,t,i){const s=Math.min(1,Math.max(0,i)),n=[1,3,5].map(t=>parseInt(e.slice(t,t+2),16)),o=[1,3,5].map(e=>parseInt(t.slice(e,e+2),16)),a=n.map((e,t)=>Math.round(e+(o[t]-e)*s));return"#"+a.map(e=>e.toString(16).padStart(2,"0")).join("")}function _s(e,t,i,s,n,o,a,r=as){const l=function(e,t,i,s,n,o,a,r=as){if("custom"===e)return rs(r);if("lqi"===e){if(null==t)return null;const e=(t-40)/140;return{c:us(a.lqi_low.c,a.lqi_high.c,e),a:a.lqi_low.a+(a.lqi_high.a-a.lqi_low.a)*Math.min(1,Math.max(0,e))}}if("light"===e)return"none"===i?a.light_none.a>0?a.light_none:null:"on"===i?a.light_on:a.light_off;if("temp"===e){if(null==s)return null;const e=Math.min(n,o),t=Math.max(n,o);return st?a.temp_hot:a.temp_ok}return null}(e,t,i,s,n,o,a,r);return l?{color:l.c,opacity:l.a,mode:e}:null}const ms={blind:["mdi:blinds","mdi:blinds-open"],shade:["mdi:blinds","mdi:blinds-open"],shutter:["mdi:window-shutter","mdi:window-shutter-open"],curtain:["mdi:curtains-closed","mdi:curtains"],window:["mdi:window-closed","mdi:window-open"],awning:["mdi:awning-outline","mdi:awning"],door:["mdi:door-closed","mdi:door-open"],garage:["mdi:garage","mdi:garage-open"],gate:["mdi:gate","mdi:gate-open"],damper:["mdi:circle-slice-8","mdi:circle-outline"]},gs=[["mdi:roller-shade-closed","mdi:roller-shade"],["mdi:blinds-horizontal-closed","mdi:blinds-horizontal"],["mdi:garage-variant","mdi:garage-open-variant"],["mdi:door","mdi:door-open"]];function fs(e){for(const t of[...Object.values(ms),...gs])if(e===t[0]||e===t[1])return t;return null}function vs(e,t,i,s,n){if(!s||"unavailable"===s||"unknown"===s)return e;if(n){const i="cover"===t?fs(e):null;return i?"closed"===s?i[0]:i[1]:e}if("binary_sensor"===t){if("door"===i)return"on"===s?"mdi:door-open":"mdi:door-closed";if("window"===i)return"on"===s?"mdi:window-open":"mdi:window-closed";if("garage_door"===i)return"on"===s?"mdi:garage-open-variant":"mdi:garage-variant"}if("cover"===t){const t=ms[String(i||"")];if(t)return"closed"===s?t[0]:t[1];const n=fs(e);return n?"closed"===s?n[0]:n[1]:e}return"lock"===t?"locked"===s?"mdi:lock":"mdi:lock-open-variant":"light"===t&&"mdi:lightbulb"===e&&"on"===s?"mdi:lightbulb-on":e}function ys(e){const t=Math.min(4e4,Math.max(1e3,e))/100,i=t<=66?255:329.698727446*Math.pow(t-60,-.1332047592),s=t<=66?99.4708025861*Math.log(t)-161.1195681661:288.1221695283*Math.pow(t-60,-.0755148492),n=t>=66?255:t<=19?0:138.5177312231*Math.log(t-10)-305.0447927307,o=e=>Math.round(Math.min(255,Math.max(0,e)));return[o(i),o(s),o(n)]}const bs=1/2.2;function ws(e){const t=/^rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/.exec(e);return t?"#"+t.slice(1).map(e=>Math.min(255,Number(e)).toString(16).padStart(2,"0")).join(""):null}function ks(e){if(!e||"object"!=typeof e||Array.isArray(e))return null;const t=e;if(Object.keys(t).some(e=>"c"!==e&&"bri"!==e))return null;const i=Ie(t.c,null);return i?void 0===t.bri||null===t.bri?{c:i}:"number"!=typeof t.bri||!Number.isFinite(t.bri)||t.bri<.01||t.bri>1?null:{c:i,bri:t.bri}:null}function xs(e,t,i){const s=ks(t),n=e?.attributes||{},o=s?.bri??function(e){const t=e?.attributes?.brightness,i="number"==typeof t?t:"string"==typeof t&&""!==t.trim()?Number(t):Number.NaN;return Number.isFinite(i)?Math.max(0,Math.min(1,i/255)):1}(e);if(s)return{c:s.c,bri:o};const a=ze(n.rgb_color);if(a)return{c:ws(a)||Ie(i,"#ffd9a0"),bri:o};const r=Number(n.color_temp_kelvin)||(Number(n.color_temp)>0?1e6/Number(n.color_temp):NaN);return Number.isFinite(r)&&r>0?{c:(l=ys(r),"#"+l.slice(0,3).map(e=>Math.min(255,Math.max(0,Math.round(Number(e)||0))).toString(16).padStart(2,"0")).join("")),bri:o}:{c:Ie(i,"#ffd9a0"),bri:o};var l}function $s(e,t,i){return"on"===e?.state?xs(e,t,i):null}function Ss(e,t=1){const i=Math.max(0,Math.min(1,Number.isFinite(e)?e:1)),s=.7*Math.max(0,Math.min(1,Number.isFinite(t)?t:1))*(.4+.6*Math.pow(i,bs));return Math.max(0,Math.min(1,s))}function Ms(e){return e.startsWith("light.")||e.startsWith("switch.")}function Cs(e,t,i=1e-6){const s=[];if(!e||!t||e.length<3||t.length<3)return s;for(let n=0;np||l>p)continue;const u=(n[0]-o[0])*h+(n[1]-o[1])*d,_=(a[0]-o[0])*h+(a[1]-o[1])*d,m=Math.max(0,Math.min(u,_)),g=Math.min(c,Math.max(u,_));g-m>i&&s.push([o[0]+h*m,o[1]+d*m,o[0]+h*g,o[1]+d*g])}}return s}function Ds(e,t,i=1e-6){const s=[];for(const n of e){const e=[n[0],n[1]],o=[n[2],n[3]],a=o[0]-e[0],r=o[1]-e[1],l=Math.hypot(a,r);if(lo||n>o)continue;const a=(s[0]-e[0])*c+(s[1]-e[1])*h,r=(s[2]-e[0])*c+(s[3]-e[1])*h,p=Math.max(0,Math.min(a,r)),u=Math.min(l,Math.max(a,r));u-p>i&&d.push([p,u])}if(!d.length){s.push([e[0],e[1],o[0],o[1]]);continue}d.sort((e,t)=>e[0]-t[0]);let p=0;for(const[t,n]of d)t-p>i&&s.push([e[0]+c*p,e[1]+h*p,e[0]+c*t,e[1]+h*t]),p=Math.max(p,n);l-p>i&&s.push([e[0]+c*p,e[1]+h*p,o[0],o[1]])}return s}function Ps(e,t,i=1e-6){const s=[];for(let t=0;t{if("string"!=typeof e||!e)return;const i=As(e);i.startsWith("/api/houseplan/content/")&&t.add(i)};for(const t of e?.spaces||[]){i(t?.plan_url);for(const e of t?.markers||[])for(const t of e?.pdfs||[])i(t?.url)}for(const t of e?.markers||[])for(const e of t?.pdfs||[])i(e?.url);return t}function As(e){return e?e.startsWith("/houseplan_files/plans/")?"/api/houseplan/content/plans/_/"+e.slice(23):e.startsWith("/houseplan_files/files/")?"/api/houseplan/content/files/"+e.slice(23):e:""}function zs(e,t){const i=t?.settings?.fill_mode;return"none"===i||"lqi"===i||"light"===i||"temp"===i||"custom"===i?i:e}function Fs(e,t){const i=t?.settings;return"boolean"==typeof i?.glow?i.glow:"glow"===i?.fill_mode||e}function Es(e,t=1){const i=Number(e);return Number.isFinite(i)&&i>0?Math.min(3,Math.max(.5,i)):t}function Ns(e,t){let i=180*Math.atan2(t[1]-e[1],t[0]-e[0])/Math.PI;return i<0&&(i+=360),i}function Os(e,t=.5){const i=(e%45+45)%45;return i<=t||45-i<=t}function Ls(e,t){const i=t[2]-t[0],s=t[3]-t[1],n=i*i+s*s;if(!n)return Math.hypot(e[0]-t[0],e[1]-t[1]);let o=((e[0]-t[0])*i+(e[1]-t[1])*s)/n;return o=Math.max(0,Math.min(1,o)),Math.hypot(e[0]-(t[0]+o*i),e[1]-(t[1]+o*s))}const Hs=new Set(["smoke","gas","carbon_monoxide","moisture","safety","tamper","problem"]);function Bs(e,t){return"alarm_control_panel"===e||"siren"===e||"binary_sensor"===e&&!!t&&Hs.has(t)}function qs(e){if(!e)return null;const t=e.indexOf("#");if(t<=0)return null;const i=e.slice(0,t),s=e.slice(t+1);if(!s)return null;if(s.startsWith("@")){const e=s.slice(1);return e?{space:i,area:null,roomId:e}:null}return{space:i,area:s,roomId:null}}const Ws={availability:"available",status:"alarm",activity:"none"},js=new Set(["motion","vibration","sound"]),Us=new Set(["occupancy","presence"]),Gs=new Set(["door","window","garage_door","opening"]),Vs=new Set(["running","power"]),Ks=new Set(["smoke","gas","carbon_monoxide","moisture","safety","tamper","problem"]);const Ys=new Set(["running","working","washing","rinsing","spinning","drying","heating","cooling","cleaning","cooking","playing","recording","pumping","irrigating","humidifying","dehumidifying","fan","preheating","defrosting"]),Js=new Set([...Ys,"start","started","run","active","in_progress","wash","rinse","spin","dry"]),Xs=new Set(["off","idle","paused","standby","docked","finished","complete","completed","stopped","ready","sleeping","stop","end","done","inactive"]),Zs=new Set(["heat","cool","heat_cool","auto","dry","fan_only"]),Qs=e=>""===e||"unknown"===e||"unavailable"===e||"__missing__"===e,en=e=>String(e??"").trim().toLowerCase(),tn=e=>en(e).replace(/[\s-]+/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,""),sn=new Map([["run_state",0],["job_state",0],["operation_state",0],["activity_state",0],["machine_state",1],["running_state",1],["status",2],["device_status",2],["machine_status",2]]),nn=new Set(["wifi","connection","signal","battery"]);function on(e,t){const i=e?.entities?.[t]||{};if("config"===i.entity_category)return null;const s=String(t||"").split(".").slice(1).join("."),n=[i.translation_key,i.original_name,i.name],o=[...n,s];n.some(e=>en(e))||o.push(e?.states?.[t]?.attributes?.friendly_name);const a=o.map(tn).filter(Boolean);if(a.some(e=>e.split("_").some(e=>nn.has(e))))return null;let r=null;for(const e of a)for(const[t,i]of sn)(e===t||e.endsWith(`_${t}`))&&(r=null==r?i:Math.min(r,i));return r}const an=(e,t)=>null!=on(e,t);function rn(e,t){if(!t.startsWith("switch."))return!1;const i=e?.entities?.[t]||{},s=e?.states?.[t],n=t.slice(7).toLowerCase();if(/(?:^|_)(?:main_)?power$/.test(n))return!0;if([i.translation_key,i.original_name,i.name].map(en).some(e=>["power","main power","power switch","питание"].includes(e)))return!0;const o=en(s?.attributes?.friendly_name);return/(?:^|[\s._-])(?:main[\s._-]+)?power$/.test(o)||/(?:^|[\s._-])питание$/.test(o)}function ln(e){for(const t of["hvac_action","action","current_operation","run_state","job_state","operation","activity"]){const i=en(e?.[t]);if(Ys.has(i)||Xs.has(i))return i}return""}function cn(e,t){const i=e?.states?.[t],s=i?en(i.state):"__missing__",n=String(t||"").split(".")[0],o=en(i?.attributes?.device_class),a={eid:t,state:s,availability:Qs(s)?"unavailable":"available",status:"neutral",activity:"none",edge:"none"};if("unavailable"===a.availability)return a;if(function(e,t,i){return"alarm_control_panel"===e?"triggered"===i:"on"===i&&Bs(e,t)}(n,o,s))return{...a,status:"alarm"};if("binary_sensor"===n)return js.has(o)?{...a,edge:"rising"}:Us.has(o)?{...a,activity:"on"===s?"presence":"none"}:Gs.has(o)?{...a,status:"on"===s?"open":"neutral",edge:"rising"}:"moving"===o?{...a,activity:"on"===s?"transition":"none"}:Vs.has(o)&&"on"===s?{...a,status:"working",activity:"running"}:a;if("cover"===n)return{...a,activity:"opening"===s||"closing"===s?"transition":"none",edge:"terminal_transition"};if("lock"===n)return{...a,status:"unlocked"===s||"open"===s?"open":"neutral",activity:"locking"===s||"unlocking"===s?"transition":"none",edge:"terminal_transition"};if("valve"===n)return{...a,status:["open","opening","closing"].includes(s)?"open":"neutral",activity:"opening"===s||"closing"===s?"transition":"none",edge:"terminal_transition"};if("climate"===n){const e=ln(i.attributes),t=Array.isArray(i.attributes?.hvac_modes)?i.attributes.hvac_modes.map(en):[],n=!Xs.has(s)&&(Zs.has(s)||Ys.has(s)||t.includes(s));return(e?Ys.has(e):n)?{...a,status:"working",activity:"running"}:a}if(["light","switch","fan","humidifier"].includes(n))return"on"===s?{...a,status:"working",activity:"running"}:a;if("media_player"===n)return"off"===s?{...a,availability:"unavailable"}:a;if("vacuum"===n)return"cleaning"===s?{...a,status:"working",activity:"running"}:"returning"===s?{...a,status:"working",activity:"transition"}:a;if("script"===n)return"on"===s?{...a,status:"working",activity:"running"}:a;if("automation"===n)return a;if("button"===n||"event"===n)return{...a,edge:"change"};const r=ln(i.attributes);return Ys.has(r)||Ys.has(s)&&!Xs.has(s)?{...a,status:"working",activity:"running"}:a}function hn(e,t,i){const s=i.filter(t=>t.startsWith("switch.")&&!e?.entities?.[t]?.entity_category),n=t.find(t=>rn(e,t));if(!(s.length>1&&!!n))return t.map(t=>cn(e,t));const o=t.find(t=>t!==n&&an(e,t)),a=cn(e,n);return"unavailable"===a.availability||"off"===a.state?t.map(t=>({eid:t,state:e?.states?.[t]?en(e.states[t].state):"__missing__",availability:"unavailable",status:"neutral",activity:"none",edge:"none"})):t.map(t=>{if(t===o)return function(e,t){const i=e?.states?.[t],s=i?en(i.state):"__missing__",n={eid:t,state:s,availability:Qs(s)?"unavailable":"available",status:"neutral",activity:"none",edge:"none"};if("unavailable"===n.availability)return n;const o=ln(i?.attributes);return Ys.has(o)||Js.has(s)&&!Xs.has(s)?{...n,status:"working",activity:"running"}:n}(e,t);return{...t===n?a:cn(e,t),status:"neutral",activity:"none",edge:"none"}})}function dn(e){if(!e.length)return{availability:"available",status:"neutral",activity:"none"};const t=e.filter(e=>"available"===e.availability);if(!t.length)return{availability:"unavailable",status:"neutral",activity:"none"};if(t.some(e=>"alarm"===e.status))return Ws;const i=t.some(e=>"working"===e.status)?"working":t.some(e=>"open"===e.status)?"open":"neutral",s=t.some(e=>"transition"===e.activity)?"transition":t.some(e=>"presence"===e.activity)?"presence":t.some(e=>"running"===e.activity)?"running":"none";return{availability:"available",status:i,activity:s}}function pn(e,t){if(!(e=>!!e&&!Qs(e))(e)||"unavailable"===t.availability||e===t.state)return null;if("rising"===t.edge)return"off"===e&&"on"===t.state?"event":null;if("change"===t.edge)return"event";if("terminal_transition"===t.edge){const i=new Set([e,t.state]);if(i.has("closed")&&i.has("open")||i.has("locked")&&i.has("unlocked"))return"transition"}return null}const un=(e,t=0)=>{const i=Number(e);return Number.isInteger(i)&&i>=0?i:t},_n=(e,t)=>{const i={rev:0,configRev:un(t),off:new Set};if(null==e)return{snapshot:i,valid:!1};const s=e.off;return!Number.isInteger(e.rev)||Number(e.rev)<0||!Number.isInteger(e.config_rev)||Number(e.config_rev)<0||!Array.isArray(s)||s.some(e=>"string"!=typeof e||!e)?{snapshot:i,valid:!1}:{snapshot:{rev:Number(e.rev),configRev:Number(e.config_rev),off:new Set(s)},valid:!0}};function mn(e,t=0){return _n(e,t).snapshot}function gn(e,t,i,s){const n=_n(t,i);return s&&n.valid&&n.snapshot.configRev===i?e.configRev===i&&n.snapshot.rev{try{const[i,s]=await Promise.all([e.callWS({type:"config/device_registry/list"}),e.callWS({type:"config/entity_registry/list"})]),n=Dn(i,"id"),o=Dn(s,"entity_id");if(!n||!o)throw new Error("invalid_registry_response");t.devices=n,t.entities=o,t.authoritative=!0,t.access="full",t.lastSuccess=Date.now(),t.error=void 0}catch(e){t.authoritative=!1,t.access="limited",t.error=function(e){if(e&&"object"==typeof e){const t=e;return String(t.message||t.code||t.error||"registry_unavailable")}return String(e||"registry_unavailable")}(e)}finally{t.revision++,t.loading=void 0,function(e){for(const t of[...e.listeners])try{t()}catch{}}(t)}})()),t.loading}function Tn(e,t){void 0===t.reloadTimer&&(t.reloadTimer=globalThis.setTimeout(()=>{t.reloadTimer=void 0,Pn(e,t)},80))}async function In(e,t){if(t.subscribing||t.unsubDevice&&t.unsubEntity)return t.subscribing;const i=e?.connection?.subscribeEvents;return"function"==typeof i?(t.subscribing=(async()=>{try{t.unsubDevice||(t.unsubDevice=await i.call(e.connection,()=>Tn(e,t),"device_registry_updated")),t.unsubEntity||(t.unsubEntity=await i.call(e.connection,()=>Tn(e,t),"entity_registry_updated"))}catch{}finally{0===t.refs&&(t.unsubDevice?.(),t.unsubEntity?.(),t.unsubDevice=void 0,t.unsubEntity=void 0),t.subscribing=void 0}})(),t.subscribing):void 0}function Rn(e,t){const i=Cn(e);if(!i)return()=>{};const s=0===i.refs;i.refs++,i.listeners.add(t),("pending"===i.access||s)&&Pn(e,i),In(e,i);let n=!1;return()=>{n||(n=!0,i.listeners.delete(t),i.refs=Math.max(0,i.refs-1),i.refs>0||(i.unsubDevice?.(),i.unsubEntity?.(),i.unsubDevice=void 0,i.unsubEntity=void 0,void 0!==i.reloadTimer&&globalThis.clearTimeout(i.reloadTimer),i.reloadTimer=void 0))}}function An(e){const t=Cn(e);if(!t)return{revision:0,authoritative:!1,access:"limited",devices:e?.devices||{},entities:e?.entities||{},lastSuccess:0,error:"registry_unavailable"};let i=e?.devices||{},s=e?.entities||{};if(t.authoritative){const n=t.liveDevices!==i||t.liveEntities!==s,o=void 0!==t.liveDevices||void 0!==t.liveEntities;if(n&&(t.liveDevices=i,t.liveEntities=s,t.projectedRevision=void 0,o&&Tn(e,t)),t.projectedRevision!==t.revision||!t.projectedDevices||!t.projectedEntities){const e={...t.devices},n={...t.entities};for(const[t,s]of Object.entries(i))Object.prototype.hasOwnProperty.call(e,t)||(e[t]=s);for(const[e,t]of Object.entries(s))Object.prototype.hasOwnProperty.call(n,e)||(n[e]=t);t.projectedDevices=e,t.projectedEntities=n,t.projectedRevision=t.revision}i=t.projectedDevices,s=t.projectedEntities}return{revision:t.revision,authoritative:t.authoritative,access:t.access,devices:i,entities:s,lastSuccess:t.lastSuccess,error:t.error}}function zn(e){if(!e||"object"!=typeof e&&"function"!=typeof e)return 0;let t=xn.get(e);return t||(t=$n++,xn.set(e,t)),t}function Fn(e,t=An(e)){return[t.revision,t.access,zn(t.devices),zn(t.entities)].join(":")}function En(e){return!!e&&null==e.disabled_by}function Nn(e,t=An(e)){const i={},s={},n={};for(const[e,s]of Object.entries(t.devices||{}))En(s)&&(i[e]=s);for(const[e,i]of Object.entries(t.entities||{})){if(!En(i))continue;const n=i.device_id?t.devices?.[i.device_id]:null;t.authoritative&&i.device_id&&!n||(n&&!En(n)||(s[e]=i))}for(const[i,s]of Object.entries(e?.states||{})){const e=t.entities?.[i];if(e&&!En(e))continue;const o=e?.device_id?t.devices?.[e.device_id]:null;t.authoritative&&e?.device_id&&!o||(o&&!En(o)||(n[i]=s))}return{...e,devices:i,entities:s,states:n}}function On(e,t=An(e)){return{...e,devices:t.devices||{},entities:t.entities||{}}}function Ln(e,t){const i=[];for(const[s,n]of Object.entries(e||{}))n?.device_id===t&&i.push(s);return i}function Hn(){if(Mn)return Mn;if("undefined"==typeof localStorage)return{};try{const e=JSON.parse(localStorage.getItem(Sn)||"{}");if(!e||"object"!=typeof e||Array.isArray(e))return{};const t=Date.now(),i={};for(const[s,n]of Object.entries(e))!n||"active"!==n.kind&&"ha_disabled"!==n.kind||!Number.isFinite(n.ts)||t-n.ts>7776e6||(i[s]=n);return Mn=i,Mn}catch{return{}}}function Bn(e,t,i=An(e)){if(!t||"virtual"===t)return{kind:"active",enabledEntityIds:[],allEntityIds:[]};const s=t.indexOf(":");if(s<1)return{kind:"unverified",reason:"registry_unavailable",enabledEntityIds:[],allEntityIds:[]};const n=t.slice(0,s),o=t.slice(s+1);if("device"!==n&&"entity"!==n||!o)return{kind:"unverified",reason:"registry_unavailable",enabledEntityIds:[],allEntityIds:[]};const a=i.devices||{},r=i.entities||{};if(i.authoritative){if("device"===n){const e=a[o];if(!e)return{kind:"orphaned",reason:"device_missing",enabledEntityIds:[],allEntityIds:[]};const t=Ln(r,o);if(!En(e))return{kind:"ha_disabled",reason:"device",enabledEntityIds:[],allEntityIds:t};const i=t.filter(e=>En(r[e]));return t.length&&!i.length?{kind:"ha_disabled",reason:"all_entities",enabledEntityIds:[],allEntityIds:t}:{kind:"active",enabledEntityIds:i,allEntityIds:t}}const t=r[o];return t&&!En(t)?{kind:"ha_disabled",reason:"entity",enabledEntityIds:[],allEntityIds:[o]}:t?.device_id&&!a[t.device_id]?{kind:"orphaned",reason:"device_missing",enabledEntityIds:[],allEntityIds:[o]}:t?.device_id&&!En(a[t.device_id])?{kind:"ha_disabled",reason:"device",enabledEntityIds:[],allEntityIds:[o]}:t||e?.states?.[o]?{kind:"active",enabledEntityIds:[o],allEntityIds:[o]}:{kind:"orphaned",reason:"entity_missing",enabledEntityIds:[],allEntityIds:[]}}const l=function(e){return Hn()[e]||null}(t);if("device"===n){const t=a[o],i=Ln(r,o);if(null!=t?.disabled_by)return{kind:"ha_disabled",reason:"device",enabledEntityIds:[],allEntityIds:i};const s=i.filter(e=>{const t=r[e];return null==t?.disabled_by&&(!t.device_id||null==a[t.device_id]?.disabled_by)});if(i.length&&!s.length&&i.every(e=>null!=r[e]?.disabled_by))return{kind:"ha_disabled",reason:"all_entities",enabledEntityIds:[],allEntityIds:i};if("ha_disabled"===l?.kind)return{kind:"ha_disabled",reason:l.reason||"device",enabledEntityIds:[],allEntityIds:i};if(t||s.some(t=>!!e?.states?.[t]))return{kind:"active",enabledEntityIds:s,allEntityIds:i}}else{const t=r[o];if(null!=t?.disabled_by)return{kind:"ha_disabled",reason:"entity",enabledEntityIds:[],allEntityIds:[o]};if(t?.device_id&&null!=a[t.device_id]?.disabled_by)return{kind:"ha_disabled",reason:"device",enabledEntityIds:[],allEntityIds:[o]};if("ha_disabled"===l?.kind)return{kind:"ha_disabled",reason:l.reason||"entity",enabledEntityIds:[],allEntityIds:[o]};if(t||e?.states?.[o])return{kind:"active",enabledEntityIds:[o],allEntityIds:[o]}}return{kind:"unverified",reason:"registry_unavailable",enabledEntityIds:[],allEntityIds:[]}}function qn(e){const t={};for(const[i,s]of Object.entries(e.entities)){if(!s?.device_id||!En(s))continue;const n=e.devices?.[s.device_id];n&&!En(n)||(t[s.device_id]=t[s.device_id]||[]).push(i)}return t}function Wn(e,t){const i=new Map;for(const s of e){if(!0===s?.removed)continue;const e=s?.binding||"";if(!e.startsWith("entity:"))continue;const n=e.slice(7);if(!n)continue;const o=t?.entities?.[n]?.device_id;if(!o)continue;const a=i.get(o)||new Set;a.add(n),i.set(o,a)}return{byDevice:i}}function jn(e,t,i,s){const n=s.byDevice.get(t);return n?.size?{partial:!0,entityIds:i.filter(t=>!n.has(t)&&!e?.entities?.[t]?.hidden)}:{partial:!1,entityIds:[...i]}}function Un(e,t,i){if(t.identifiers?.[0]?.[0])return t.identifiers[0][0];for(const t of i){const i=e.entities[t]?.platform;if(i)return i}return""}function Gn(e,t){if(/_device_temperature$/.test(t))return!1;if(e.entities?.[t]?.entity_category)return!1;const i=e.states[t];if(!i)return/_temperature$/.test(t);const s=i.attributes||{};return"temperature"===s.device_class||/°C|°F/.test(s.unit_of_measurement||"")||/_temperature$/.test(t)}const Vn=["vacuum","lawn_mower","climate","media_player","light","cover","lock","valve","alarm_control_panel","water_heater","fan","humidifier","siren","camera","remote"],Kn=e=>[...e.filter(e=>!e.reg?.hidden),...e.filter(e=>!!e.reg?.hidden)];function Yn(e,t){const i=t.map(t=>({eid:t,reg:e?.entities?.[t]})).filter(e=>!!e.reg);if(!i.length)return[];const s=i.filter(e=>!e.reg.entity_category),n=s.length?s:i;for(const e of Vn){const t=n.filter(t=>t.eid.startsWith(e+"."));if(t.length)return Kn(t).map(e=>e.eid)}const o=n.filter(t=>function(e,t){if(!t.startsWith("binary_sensor."))return!1;const i=en(e?.states?.[t]?.attributes?.device_class||e?.entities?.[t]?.device_class||e?.entities?.[t]?.original_device_class);return js.has(i)||Us.has(i)||Gs.has(i)||Vs.has(i)||"moving"===i||Ks.has(i)}(e,t.eid));if(o.length)return Kn(o).map(e=>e.eid);const a=n.filter(e=>e.eid.startsWith("switch."));if(a.length){const t=Kn(a),s=t.find(t=>rn(e,t.eid));if(a.length>1&&s){const t=i.filter(t=>t.eid!==s.eid&&"config"!==t.reg?.entity_category&&null!=on(e,t.eid)),n=t.filter(e=>!e.reg?.entity_category),o=n.length?n:t;for(const t of[0,1,2]){const i=Kn(o.filter(i=>on(e,i.eid)===t));if(i.length)return[i[0].eid,s.eid]}}return[(s||t[0]).eid]}const r=[];for(const e of it)r.push(...Kn(n.filter(t=>t.eid.startsWith(e+"."))));return r.push(...Kn(n.filter(e=>!it.includes(e.eid.split(".")[0])))),r.map(e=>e.eid)}function Jn(e,t,i){const s=t.map(t=>({eid:t,reg:e.entities[t],st:e.states[t]})).filter(e=>e.reg),n=[s.filter(e=>!e.reg.hidden&&!e.reg.entity_category),s.filter(e=>!e.reg.entity_category),s.filter(e=>!e.reg.hidden),s];if("mdi:thermometer"===i||"mdi:air-filter"===i)for(const t of n){const i=t.find(t=>Gn(e,t.eid));if(i)return i.eid}const o=Yn(e,t);return o.find(Ms)||o[0]}function Xn(e,t,i=[]){return[...new Set(Zn(e,t,i))].filter(e=>Ms(e))}function Zn(e,t,i=[]){const s=e?.startsWith("entity:")?new Set([e.slice(7)]):new Set(i);return(t||[]).filter(e=>"string"==typeof e&&!s.has(e))}function Qn(e,t){if("string"==typeof t)return e.area===t;const i=e.marker?.room_id;return i?!!t.id&&i===t.id:!!t.area&&e.area===t.area}function eo(e){const t=e.marker?.binding?.startsWith("entity:")?e.marker.binding.slice(7):null,i=e.entities.filter(Ms),s=e.primary&&Ms(e.primary)?e.primary:null;return[...new Set([t,s,...i].filter(e=>!!e&&Ms(e)))]}function to(e){const t=eo(e),i=e.marker?.light_entity;return i&&t.includes(i)?i:t[0]||null}function io(e,t){if(!1===t.marker?.is_light)return[];if(!0===t.marker?.is_light){return[{eid:to(t),via:"forced"}]}const i=t.primary||Yn(e,t.entities)[0];return i&&!i.startsWith("light.")?[]:t.entities.filter(t=>t.startsWith("light.")&&!!e.states?.[t]).map(e=>({eid:e,via:"light"}))}const so=new WeakMap,no=new WeakMap;function oo(e){return e.map(e=>[e.id||"",!0===e.hidden?1:0,e.primary||"",[...e.entities].join(","),void 0===e.controls?"":[...e.controls].join(","),e.marker?.id||"",e.marker?.binding||"",e.marker?.is_light,e.marker?.tap_action||"",!0===e.marker?.removed?1:0,e.marker?.light_entity||"",null==e.marker?.controls?"":[...e.marker.controls].join(",")].join("")).join("")}function ao(e){const t=oo(e),i=so.get(e);if(i?.fingerprint===t)return i;const s=e.filter(e=>!e.hidden),n=new Map,o=new Map;for(const t of e){o.set(t,Zn(t.marker?.binding,t.marker?.controls??t.controls,t.entities));const e=t.hidden||!0!==t.marker?.is_light?null:t.marker?.id||t.id;e&&n.set(String(e),t)}const a=new Map;for(const t of e){const e=o.get(t)||[],i=new Set(void 0===t.controls?e.filter(Ms):t.controls.filter(Ms)),s=to(t),r=i.size?[...i]:s?[s]:[];for(const i of e){if(!i.startsWith("marker:"))continue;const e=i.slice(7);if(!e||e===String(t.marker?.id||t.id||""))continue;if(!n.has(e))continue;const s=a.get(e)||{markerId:e,controllers:[],driverEids:[]};s.controllers.push({device:t,driverEids:[...r]}),s.driverEids=[...new Set([...s.driverEids,...r])],a.set(e,s)}}const r={fingerprint:t,visible:s,markerById:n,persistedByDevice:o,incomingByMarker:a};return so.set(e,r),r}function ro(e){return ao(e).incomingByMarker}function lo(e,t){const i=Xn(t.marker?.binding,t.controls??t.marker?.controls,t.entities),s=Zn(t.marker?.binding,t.marker?.controls??t.controls,t.entities);return(null!=t.marker?.is_light||!i.length&&!s.some(e=>e.startsWith("marker:")))&&io(e,t).length>0}function co(e,t){const i=Xn(t.marker?.binding,t.controls??t.marker?.controls,t.entities).map(e=>({eid:e,via:"controls"})),s=lo(e,t)?io(e,t):[];for(const e of s)e.eid&&i.some(t=>t.eid===e.eid)||i.push(e);return i}function ho(e,t,i,s){if(null!=i)return ho(e,t,null,s).filter(e=>Qn(e.device,i));const n=oo(t),o=function(e,t){const i=new Set;for(const e of t){for(const t of e.entities)i.add(t);for(const t of e.controls||e.marker?.controls||[])"string"!=typeof t||t.startsWith("marker:")||i.add(t)}return[...i].sort().map(t=>`${t}:${e?.states?.[t]?.state??""}`).join("|")}(e,t),a=vn(s),r=no.get(t);if(r?.graphFingerprint===n&&r.stateFingerprint===o&&r.virtualLightFingerprint===a&&r.registry===e?.entities)return r.sources;const{visible:l,markerById:c,persistedByDevice:h,incomingByMarker:d}=ao(t),p=null==i?l:l.filter(e=>Qn(e,i)),u=new Map,_=new Map;for(const t of p){const i=co(e,t).filter(e=>"controls"!==e.via);for(const s of i){const i=!0===t.marker?.is_light?String(t.marker?.id||t.id||""):"",n=i?`marker:${i}`:`entity:${s.eid}`,o=s.eid?[s.eid]:[],a={key:n,eid:s.eid||"",stateEids:o,serviceEids:o,device:t,via:s.via,castsGlow:!0,passive:!s.eid,on:!s.eid||"on"===e.states?.[s.eid]?.state};u.set(t,[...u.get(t)||[],a]),s.eid&&_.set(s.eid,a)}}const m=new Map;for(const e of t){const t=h.get(e)||[],i=new Set(void 0===e.controls?t.filter(Ms):e.controls);m.set(e,i)}for(const t of u.values())for(const i of t){if(!i.passive)continue;const t=i.key.slice(7),n=d.get(t);i.on=!n||n.driverEids.some(t=>"on"===e.states?.[t]?.state),!n&&yn(i.device.marker)&&(i.on=bn(i.device.marker,s))}const g=new Map,f=e=>{const t=g.get(e.key);(!t||e.castsGlow&&!t.castsGlow)&&g.set(e.key,e)};for(const t of l){const s=h.get(t)||[],n=null==i||Qn(t,i);for(const i of s){if(i.startsWith("marker:")){const e=c.get(i.slice(7)),t=e?u.get(e):null;if(t)for(const e of t)f(e);continue}if(!Ms(i)||!m.get(t)?.has(i))continue;const s=_.get(i);s?f(s):n&&f({key:`entity:${i}`,eid:i,stateEids:[i],serviceEids:[i],device:t,via:"controls",castsGlow:!1,passive:!1,on:"on"===e.states?.[i]?.state})}for(const e of u.get(t)||[])f(e)}const v=[...g.values()];return no.set(t,{graphFingerprint:n,stateFingerprint:o,virtualLightFingerprint:a,registry:e?.entities,sources:v}),v}function po(e){const t=e.filter(e=>e.castsGlow);return t.find(e=>e.on)||t[0]||null}function uo(e){return e.length?e.some(e=>e.on)?"on":"off":"none"}function _o(e,t){const i=[];for(const s of t){const t=e.states[s];if(!t)continue;const n=(t.attributes?.unit_of_measurement||"").toLowerCase();if(/_(linkquality|lqi)$/.test(s)||"lqi"===n){const e=parseFloat(t.state);isNaN(e)||i.push(e);continue}const o=t.attributes?.linkquality??t.attributes?.lqi;if(null!=o){const e=parseFloat(o);isNaN(e)||i.push(e)}}return Ei(i)}function mo(e,t){for(const i of t){if(!Gn(e,i))continue;const t=e.states[i];if(!t)continue;const s=parseFloat(t.state);if(!isNaN(s))return Math.round(10*s)/10}return null}function go(e,t){for(const i of t){if(!i.startsWith("climate."))continue;const t=e.states[i];if(!t||"unavailable"===t.state||"unknown"===t.state)continue;const s=parseFloat(t.attributes?.current_temperature);if(Number.isFinite(s))return Math.round(10*s)/10}return null}function fo(e,t){if(e.entities?.[t]?.entity_category)return!1;const i=e.states[t];if(!i)return/_humidity$/.test(t);const s=i.attributes||{};return"humidity"===s.device_class||"%"===s.unit_of_measurement&&/_humidity$/.test(t)||/_humidity$/.test(t)}function vo(e,t){for(const i of t){if(!fo(e,i))continue;const t=e.states[i];if(!t)continue;const s=parseFloat(t.state);if(!isNaN(s))return Math.round(s)}return null}function yo(e,t){if(!t)return[];const i=[];for(const[t,s]of Object.entries(e.entities)){if(!t.startsWith("light.")||s.hidden||!En(s))continue;let n=null;if("group"===s.platform)n=s.area_id||null;else{if(!s.device_id)continue;{const t=e.devices[s.device_id];if(!En(t))continue;if("Group"!==t?.model)continue;n=t.area_id||s.area_id||null}}if(!n)continue;const o=e.states[t];i.push({eid:t,name:s.name||o?.attributes?.friendly_name||t,area:n})}return i}function bo(e,t,i,s,n){const o=tt(t,i,n);if(o!==et)return o;const a=[];for(const t of s){const i=e.states[t]?.attributes?.device_class;i&&a.push(i)}return function(e){for(const t of e){const e=Qe[t];if(e)return e}return null}(a)??et}function wo(e){const t=new Set,i=new Set,s=new Set;for(const n of e||[]){const e=String(n.binding||"").indexOf(":");if(e<1)continue;const o=n.binding.slice(0,e),a=n.binding.slice(e+1);a&&(!0===n?.removed?"device"===o?t.add(a):"entity"===o&&i.add(a):"entity"===o&&s.add(a))}return{devices:t,entities:i,liveEntities:s}}function ko(e,t,i){if(i.liveEntities.has(t))return!1;if(i.entities.has(t))return!0;const s=e?.entities?.[t]?.device_id;return!!s&&i.devices.has(s)}function xo(e,t,i,s,n){const o=Xn(t.binding,t.controls,e.entities).filter(e=>!ko(i,e,s)).filter(e=>"active"===Bn(i,"entity:"+e,n).kind);e.marker=t,e.controls=o,e.userHidden=!0===t.hidden,e.hidden=e.userHidden||"ha_disabled"===e.bindingStatus?.kind,t.name&&(e.name=t.name),t.icon&&(e.icon=t.icon),null!=t.model&&(e.model=t.model),e.link=t.link??null,e.description=t.description??null,e.pdfs=t.pdfs||[],e.tapAction=t.tap_action??null}function $o(e,t,i,s){if("string"==typeof e.room_id&&e.room_id.length>0&&null===e.area)return{area:"",space:e.space||s};const n=e.area||t||"";return{area:n,space:n&&i[n]||e.space||s}}function So(e){const t=e.hass,i=e.registry||An(t),s=Nn(t,i),n=On(t,i),{areaToSpace:o,markers:a,settings:r,excluded:l,showAll:c,firstSpaceId:h,loc:d,iconRules:p}=e,u=!1!==r.group_lights,_=wo(a),m=yo(s,u).filter(e=>!ko(s,e.eid,_)),g=new Set(m.map(e=>e.area)),f=qn(s),v=function(e){const t={};for(const[i,s]of Object.entries(e.entities||{}))s?.device_id&&(t[s.device_id]=t[s.device_id]||[]).push(i);return t}(n),y=Wn(a,n),b=new Set;for(const e of a){const[t,i]=e.binding.split(":");"device"!==t&&"entity"!==t||!i||b.add(e.binding)}const w=(e,t)=>a.find(i=>i.binding===e+":"+t),k={},x=[];for(const e of Object.values(s.devices)){const n=e.area_id;if(!n||!o[n])continue;if("service"===e.entry_type)continue;if(b.has("device:"+e.id))continue;const a=Bn(t,"device:"+e.id,i);if("active"!==a.kind)continue;const h=w("device",e.id);if(h&&h.hidden&&!r.filter_seeded)continue;const _=jn(s,e.id,f[e.id]||[],y);if(_.partial&&!_.entityIds.length)continue;const m=_.entityIds,v=_.partial?{kind:"active",enabledEntityIds:m,allEntityIds:m}:a,$=Un(s,e,m),S=!r.filter_seeded;if(S&&!c){if(l.has($))continue;if("Group"===e.model)continue;if(/scene/i.test(e.model||""))continue;if(/bridge/i.test((e.model||"")+(e.name||"")))continue;if("myheat"===$&&e.via_device_id)continue}const M=(e.name_by_user||e.name||d("device.unnamed")).trim(),C=M+"|"+n;let D=bo(s,M,e.model,m,p);if(m.some(e=>e.startsWith("lock."))&&(D="mdi:lock"),S&&!c&&u&&"mdi:lightbulb"===D&&g.has(n))continue;k[C]=(k[C]||0)+1;const P=k[C]>1?M+" "+k[C]:M,T={id:e.id,name:P,model:e.model||"",area:n,space:o[n],icon:D,entities:m,allEntities:v.allEntityIds,bindingStatus:v,bindingKind:"device",bindingRef:e.id,pdfs:[]};T.primary=Jn(s,m,D),"mdi:thermometer"!==D&&"mdi:air-filter"!==D||(T.temp=mo(s,m)),T.primary&&fo(s,T.primary)&&(T.hum=vo(s,m)),x.push(T)}for(const e of m)o[e.area]&&(b.has("entity:"+e.eid)||x.push({id:"lg_"+e.eid,name:e.name,model:d("device.light_group"),area:e.area,space:o[e.area],icon:"mdi:lightbulb-group",entities:[e.eid],allEntities:[e.eid],bindingStatus:{kind:"active",enabledEntityIds:[e.eid],allEntityIds:[e.eid]},primary:e.eid,bindingKind:"entity",bindingRef:e.eid,pdfs:[]}));for(const e of a){if(e.removed)continue;const[a,l]=e.binding.split(":"),c="device"===a||"entity"===a?Bn(t,e.binding,i):null;if(!e.hidden||r.filter_seeded||"ha_disabled"===c?.kind)if("device"===a){const t=c;if("unverified"===t.kind)continue;const a=n.devices[l],{area:r,space:u}=$o(e,a?.area_id,o,h),m="active"===t.kind?t.enabledEntityIds:[];let g=a?bo(s,a.name_by_user||a.name||"",a.model,m,p):"mdi:help-circle";m.some(e=>e.startsWith("lock."))&&(g="mdi:lock");const f={id:e.id,name:a?.name_by_user||a?.name||d("device.fallback"),model:a?.model||"",area:r,space:u,icon:g,entities:m,allEntities:t.allEntityIds.length?t.allEntityIds:a&&v[a.id]||[],bindingStatus:t,bindingKind:"device",bindingRef:l};f.primary=Jn(s,m,g),"mdi:thermometer"!==g&&"mdi:air-filter"!==g||(f.temp=mo(s,m)),f.primary&&fo(s,f.primary)&&(f.hum=vo(s,m)),xo(f,e,n,_,i),x.push(f)}else if("entity"===a){if(ko(n,l,_))continue;const t=c;if("unverified"===t.kind)continue;const a=n.entities[l],r=a?.area_id||a?.device_id&&n.devices[a.device_id]?.area_id||"",{area:d,space:u}=$o(e,r,o,h),m=s.states[l],g=a?.name||m?.attributes?.friendly_name||l;let f=bo(s,g,"",[l],p);l.startsWith("lock.")&&(f="mdi:lock");const v={id:e.id,name:g,model:"",area:d,space:u,icon:f,entities:"active"===t.kind?[l]:[],allEntities:[l],bindingStatus:t,primary:"active"===t.kind?l:void 0,bindingKind:"entity",bindingRef:l};"mdi:thermometer"!==f&&"mdi:air-filter"!==f||!v.entities.length||(v.temp=mo(s,v.entities)),v.entities.length&&fo(s,l)&&(v.hum=vo(s,v.entities)),xo(v,e,n,_,i),x.push(v)}else{const t=e.area||"",s=e.space||t&&o[t]||h,a={id:e.id,name:e.name||d("device.virtual"),model:e.model||"",area:t,space:s,icon:e.icon||"mdi:map-marker",entities:[],allEntities:[],bindingStatus:{kind:"active",enabledEntityIds:[],allEntityIds:[]},bindingKind:"virtual",virtual:!0};xo(a,e,n,_,i),x.push(a)}}return x}function Mo(e,t,i,s){if(!t)return null;if(function(e,t,i){if(!t)return!1;const s=t.indexOf(":");if(s<1)return!1;const n=t.slice(0,s),o=t.slice(s+1),a=wo(i);return"device"===n?a.devices.has(o):"entity"===n&&ko(e,o,a)}(e,t,s))return null;const n=t.indexOf(":");if(n<0)return null;const o=t.slice(0,n),a=t.slice(n+1);if(!a)return null;if("entity"===o){const t=parseFloat(e.states[a]?.state);return Number.isFinite(t)?"temp"===i?Math.round(10*t)/10:Math.round(t):null}if("device"===o){const t=Object.entries(e.entities).filter(([,e])=>e.device_id===a).map(([e])=>e);return"temp"===i?mo(e,t):vo(e,t)}return null}const Co=new RegExp(["water","voda","coolant","flow_?temp","return_?temp","target","setpoint","chip","cpu","processor","board","core_temp","device_temp","batter","akkum","freezer","fridge","oven","kettle","boiler"].join("|"),"i");function Do(e,t,i){const s=[];for(const n of t){if(n.area!==i||n.virtual)continue;const t=_o(e,n.entities);null!=t&&s.push(t)}return Ei(s)}function Po(e,t,i){const s=[];for(const n of t){if(n.area!==i)continue;if("mdi:thermometer"!==n.icon&&"mdi:air-filter"!==n.icon)continue;const t=mo(e,n.entities);null!=t&&s.push(t)}return s.length?Math.round(s.reduce((e,t)=>e+t,0)/s.length*10)/10:null}const To={climate:["current_temperature","temperature","current_humidity","humidity"],water_heater:["current_temperature","temperature"],cover:["current_position"],valve:["current_position"],fan:["percentage"],humidifier:["current_humidity","humidity"],light:["brightness"],media_player:["volume_level"],vacuum:["battery_level","fan_speed"],lawn_mower:["battery_level","fan_speed"]};function Io(e){return e?e.sourceLabel?`${e.sourceLabel}: ${e.fullText}`:e.fullText:""}const Ro=new WeakMap;function Ao(e){return e?"entity_state"===e.kind?`state:${e.entity_id}`:"entity_attribute"===e.kind?`attr:${e.entity_id}:${e.attribute}`:"derived_marker_state"===e.kind?`marker:${e.ref}`:"derived:lqi":""}function zo(e){if("derived:lqi"===e)return{kind:"derived_lqi"};if(e.startsWith("state:"))return{kind:"entity_state",entity_id:e.slice(6)};if(e.startsWith("attr:")){const t=e.slice(5),i=t.lastIndexOf(":");if(i>0)return{kind:"entity_attribute",entity_id:t.slice(0,i),attribute:t.slice(i+1)}}return e.startsWith("marker:marker:")?{kind:"derived_marker_state",ref:e.slice(7)}:null}function Fo(e,t){const i=e?.entities?.[t],s=e?.states?.[t];return String(i?.name||i?.original_name||s?.attributes?.friendly_name||t)}function Eo(e){return e.replaceAll("_"," ")}function No(e,t=1){const i=Number(e);return Number.isFinite(i)?`${Math.round(i*t)} %`:null}function Oo(e){if("derived_lqi"===e.kind)return"lqi";if("entity_attribute"===e.kind){if(e.attribute.includes("temperature"))return"temperature";if(e.attribute.includes("humidity"))return"humidity"}return"default"}function Lo(e,t,i,s=[]){let n=null,o="",a="available";if("entity_state"===i.kind){o=Fo(e,i.entity_id);const t=e?.states?.[i.entity_id];if(t)if(Bo(e,i.entity_id))if(["unknown","unavailable"].includes(String(t.state).toLowerCase()))a="unavailable";else{const s=Xi(e,i.entity_id);n=s?Zi(s,String(t.attributes?.unit_of_measurement||"")):null,n||(a="unavailable")}else a="unavailable";else a="missing"}else if("entity_attribute"===i.kind){o=`${Eo(i.attribute)} · ${Fo(e,i.entity_id)}`;const t=e?.states?.[i.entity_id];t?Bo(e,i.entity_id)?(n=function(e,t,i){const s=e?.states?.[t];if(!s||!(i in(s.attributes||{})))return null;const n=Xi(e,t,i);if(n?.formatted)return n.text;const o=s.attributes?.[i];if("brightness"===i)return No(o,100/255);if("volume_level"===i)return No(o,100);if(["current_position","percentage","current_humidity","humidity","battery_level"].includes(i))return No(o);if("current_temperature"===i||"temperature"===i){const t=Number(o);if(!Number.isFinite(t))return null;const i=String(e?.config?.unit_system?.temperature||"°C");return`${Math.round(10*t)/10} ${i}`}return n?.text||(["string","number","boolean"].includes(typeof o)?String(o):null)}(e,i.entity_id,i.attribute),null==n&&(a="unavailable")):a="unavailable":a="missing"}else if("derived_lqi"===i.kind){o="LQI";const i=_o(e,t.entities);null==i?a="unavailable":n=String(i)}else{o="Light state";const t=s.find(e=>e.ref===i.ref);if(t){const i=t.on?"on":"off",s=e?.localize?.(`state.default.${i}`);n="string"==typeof s&&s?s:i,o=t.name||o}else a="missing"}const r=e?.localize?.("state.default.unavailable")||"Unavailable";return{source:i,sourceLabel:o,text:n??"—",fullText:n??r,availability:a,isLqi:"derived_lqi"===i.kind,tone:Oo(i)}}function Ho(e,t){if(!0===t.marker?.use_climate_temp){const i=t.entities.find(t=>t.startsWith("climate.")&&Number.isFinite(Number(e?.states?.[t]?.attributes?.current_temperature)));return i?{kind:"entity_attribute",entity_id:i,attribute:"current_temperature"}:null}if("mdi:thermometer"===t.icon||"mdi:air-filter"===t.icon){const i=t.entities.find(t=>Gn(e,t)&&Number.isFinite(Number(e?.states?.[t]?.state)));if(i)return{kind:"entity_state",entity_id:i}}return t.primary&&fo(e,t.primary)&&Number.isFinite(Number(e?.states?.[t.primary]?.state))?{kind:"entity_state",entity_id:t.primary}:null}function Bo(e,t){const i=e?.entities?.[t];if(i&&!En(i))return!1;const s=i?.device_id?e?.devices?.[i.device_id]:null;return!s||En(s)}function qo(e,t){return Bo(e,t)&&!!e?.states?.[t]}function Wo(e,t,i=[t]){const s=function(e,t){const i=e=>[e.id,e.primary,e.hidden?1:0,e.userHidden?1:0,e.entities.join(","),(e.controls||[]).join(","),e.marker?.binding||"",!0===e.marker?.is_light?1:0,e.marker?.light_entity||"",(e.marker?.controls||[]).join(",")].join("|");return`${i(e)}\n${t.map(i).join("\n")}`}(t,i),n=Ro.get(t);if(n&&n.states===(e?.states||null)&&n.entities===(e?.entities||null)&&n.devices===(e?.devices||null)&&n.signature===s)return n.result;const o=new Set(t.entities);for(const e of t.controls||[])e.startsWith("marker:")||o.add(e);const a=[],r=ho(e,i),l=r.filter(e=>e.key.startsWith("marker:")).map(e=>({ref:e.key,on:e.on,name:e.device?.name||e.key})),c=i=>{const s=Ao(i);if(a.some(e=>e.key===s))return;const n=Lo(e,t,i,l),o="entity_attribute"===i.kind?`${i.entity_id} · ${i.attribute}`:"entity_state"===i.kind?i.entity_id:"derived_marker_state"===i.kind?i.ref:"LQI";a.push({key:s,source:i,label:n.sourceLabel,technical:o,value:n.text,available:"available"===n.availability})};for(const t of[...o].sort()){if(!qo(e,t))continue;const i=t.split(".")[0],s=e?.entities?.[t];if("button"===i||"event"===i||"config"===s?.entity_category)continue;c({kind:"entity_state",entity_id:t});const n=e?.states?.[t];for(const e of To[i]||[])e in(n?.attributes||{})&&c({kind:"entity_attribute",entity_id:t,attribute:e})}const h=new Set((t.marker?.controls||t.controls||[]).filter(e=>e.startsWith("marker:")));!0===t.marker?.is_light&&t.marker.id&&h.add(`marker:${t.marker.id}`);const d=new Set(r.map(e=>e.key));for(const e of[...h].sort())d.has(e)&&c({kind:"derived_marker_state",ref:e});return t.virtual||null==_o(e,t.entities)||c({kind:"derived_lqi"}),Ro.set(t,{states:e?.states||null,entities:e?.entities||null,devices:e?.devices||null,signature:s,result:a}),a}function jo(e,t,i){const s=Ho(e,t);if(s&&i.some(e=>e.key===Ao(s)))return s;const n=t.primary&&i.find(e=>e.key===`state:${t.primary}`);if(n)return n.source;const o=[e=>e.technical.includes("temperature"),e=>e.technical.includes("humidity"),e=>e.technical.includes("battery")];for(const e of o){const t=i.find(e);if(t)return t.source}return i.find(e=>"derived_lqi"!==e.source.kind)?.source||i[0]?.source||null}function Uo(e){return"boolean"==typeof e?.themes?.darkMode?e.themes.darkMode?"theme-dark":"theme-light":""}function Go(e){const t=[];if(1!==e.scale&&t.push(`--dev-scale:${e.scale}`),"none"!==e.pulse.kind){t.push(`--ripple-scale:${e.pulse.diameterScale}`);const n=(i=e.pulse.color,s=null,"string"==typeof i&&(Te.test(i)||Ae.test(i))?i:s);n&&t.push(`--ripple-color:${n}`)}var i,s;return t}function Vo(e){const t=[...String(e)].reduce((e,t)=>/\s/.test(t)?e+.35:e+(t.codePointAt(0)>255?1:.62),0);return t<=8?.45:Math.max(.25,Math.round(3.6/t*1e3)/1e3)}function Ko(e,t){const i=e.pulse,s=i.generation%2==0,n=function(e){const t=e.valueBadge;if(!t||!1!==t.configured)return[];const i=[];return null!=e.tempText&&"temperature"!==t.tone&&i.push({kind:"temperature",text:e.tempText,suffix:"°"}),null!=e.humText&&"humidity"!==t.tone&&i.push({kind:"humidity",text:e.humText,suffix:"%"}),i}(e),o=e.valueBadge,a=o?.position||"right",r=!!o||n.length>0,l=["device-shell",null!=e.valueText?"text-shell":"",r?`with-values pos-${a}`:"",n.length?"with-legacy":""].filter(Boolean).join(" ");return W`
+`],Ye=new Set(["hacs","sun","backup","hassio","met","telegram_bot","mobile_app","systemmonitor","better_thermostat","adaptive_lighting","yandex_pogoda","upnp_serial_number"]),Je=[{pattern:"протечк|leak|water sensor",icon:"mdi:water-alert"},{pattern:"клапан|valve",icon:"mdi:pipe-valve"},{pattern:"дым|smoke",icon:"mdi:smoke-detector"},{pattern:"термоголов|trv|radiator",icon:"mdi:radiator"},{pattern:"чайник|kettle|термопот",icon:"mdi:kettle"},{pattern:"сауна|sauna|harvia|парная|парилк",icon:"mdi:hot-tub"},{pattern:"температ|temperature|thermometer|climate sensor",icon:"mdi:thermometer"},{pattern:"qingping|air monitor|молекул|air quality",icon:"mdi:air-filter"},{pattern:"штор|curtain|blind|shade",icon:"mdi:roller-shade"},{pattern:"розетк|plug|socket|outlet",icon:"mdi:power-socket-de"},{pattern:"выключат|switch",icon:"mdi:light-switch"},{pattern:"лампа|лампочк|bulb|gx53|светильник|rgb|lamp|light strip",icon:"mdi:lightbulb"},{pattern:"камер|camera",icon:"mdi:cctv"},{pattern:"замок|ttlock|lock|sn609|sn9161",icon:"mdi:lock"},{pattern:"ворота|garage|gate",icon:"mdi:garage-variant"},{pattern:"калитк|door|открыт|contact",icon:"mdi:door"},{pattern:"счётчик|счетчик|kws|meter",icon:"mdi:meter-electric"},{pattern:"вводный автомат|breaker|wifimcbn",icon:"mdi:electric-switch"},{pattern:"myheat|котёл|котел|boiler|отоплен|heating",icon:"mdi:water-boiler"},{pattern:"холодильник|fridge",icon:"mdi:fridge"},{pattern:"стиральн|washer|washing",icon:"mdi:washing-machine"},{pattern:"сушилк|dryer",icon:"mdi:tumble-dryer"},{pattern:"пылесос|vacuum|dreame|roborock",icon:"mdi:robot-vacuum"},{pattern:"soundbar",icon:"mdi:soundbar"},{pattern:"колонк|станц|speaker|яндекс|yandex|алиса|alice",icon:"mdi:speaker"},{pattern:"tv|телевизор|hyundaitv|mitv|television",icon:"mdi:television"},{pattern:"keenetic|роутер|router|mesh|access point",icon:"mdi:router-wireless"},{pattern:"ибп|ups|kirpich",icon:"mdi:battery-charging-high"},{pattern:"slzb|координат|zigbee|coordinator",icon:"mdi:zigbee"},{pattern:"motion|движен|presence|присутств",icon:"mdi:motion-sensor"},{pattern:"humidity|влажн",icon:"mdi:water-percent"}];function Xe(e){const t=[];for(const i of e)if(i&&"string"==typeof i.pattern&&i.icon)try{t.push({re:new RegExp(i.pattern,"i"),icon:i.icon})}catch{}return t}const Ze=Xe(Je),Qe={temperature:"mdi:thermometer",humidity:"mdi:water-percent",motion:"mdi:motion-sensor",occupancy:"mdi:motion-sensor",presence:"mdi:motion-sensor",door:"mdi:door",window:"mdi:window-closed",garage_door:"mdi:garage-variant",smoke:"mdi:smoke-detector",moisture:"mdi:water-alert",gas:"mdi:gas-cylinder",power:"mdi:meter-electric",energy:"mdi:meter-electric",illuminance:"mdi:brightness-5",co2:"mdi:molecule-co2",pm25:"mdi:air-filter",battery:"mdi:battery"},et="mdi:chip";function tt(e,t,i){const s=((e||"")+" "+(t||"")).toLowerCase();for(const{re:e,icon:t}of i??Ze)if(e.test(s))return t;return et}const it=["light","switch","cover","valve","lock","climate","fan","media_player","camera","vacuum","humidifier","water_heater","alarm_control_panel","sensor","binary_sensor","event","button","number","select","update"];var st=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,nt=Math.ceil,ot=Math.floor,at="[BigNumber Error] ",rt=at+"Number primitive has more than 15 significant digits: ",lt=1e14,ct=14,ht=9007199254740991,dt=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],pt=1e7,ut=1e9;function _t(e){var t=0|e;return e>0||e===t?t:t-1}function mt(e){for(var t,i,s=1,n=e.length,o=e[0]+"";sc^i?1:-1;for(r=(l=n.length)<(c=o.length)?l:c,a=0;ao[a]^i?1:-1;return l==c?0:l>c^i?1:-1}function ft(e,t,i,s){if(ei||e!==ot(e))throw Error(at+(s||"Argument")+("number"==typeof e?ei?" out of range: ":" not an integer: ":" not a primitive number: ")+String(e))}function vt(e){var t=e.c.length-1;return _t(e.e/ct)==t&&e.c[t]%2!=0}function yt(e,t){return(e.length>1?e.charAt(0)+"."+e.slice(1):e)+(t<0?"e":"e+")+t}function bt(e,t,i){var s,n;if(t<0){for(n=i+".";++t;n+=i);e=n+e}else if(++t>(s=e.length)){for(n=i,t-=s;--t;n+=i);e+=n}else ty?p.c=p.e=null:e.e=10;l/=10,r++);return void(r>y?p.c=p.e=null:(p.e=r,p.c=[e]))}d=String(e)}else{if(!st.test(d=String(e)))return n(p,d,c);p.s=45==d.charCodeAt(0)?(d=d.slice(1),-1):1}(r=d.indexOf("."))>-1&&(d=d.replace(".","")),(l=d.search(/e/i))>0?(r<0&&(r=l),r+=+d.slice(l+1),d=d.substring(0,l)):r<0&&(r=d.length)}else{if(ft(t,2,$.length,"Base"),10==t&&S)return T(p=new M(e),_+p.e+1,m);if(d=String(e),c="number"==typeof e){if(0*e!=0)return n(p,d,c,t);if(p.s=1/e<0?(d=d.slice(1),-1):1,M.DEBUG&&d.replace(/^0\.0*|\./,"").length>15)throw Error(rt+e)}else p.s=45===d.charCodeAt(0)?(d=d.slice(1),-1):1;for(i=$.slice(0,t),r=l=0,h=d.length;lr){r=h;continue}}else if(!a&&(d==d.toUpperCase()&&(d=d.toLowerCase())||d==d.toLowerCase()&&(d=d.toUpperCase()))){a=!0,l=-1,r=0;continue}return n(p,String(e),c,t)}c=!1,(r=(d=s(d,t,10,p.s)).indexOf("."))>-1?d=d.replace(".",""):r=d.length}for(l=0;48===d.charCodeAt(l);l++);for(h=d.length;48===d.charCodeAt(--h););if(d=d.slice(l,++h)){if(h-=l,c&&M.DEBUG&&h>15&&(e>ht||e!==ot(e)))throw Error(rt+p.s*e);if((r=r-l-1)>y)p.c=p.e=null;else if(r=f)?yt(l,a):bt(l,a,"0");else if(o=(e=T(new M(e),t,i)).e,r=(l=mt(e.c)).length,1==s||2==s&&(t<=o||o<=g)){for(;ra),l=bt(l,o,"0"),o+1>r){if(--t>0)for(l+=".";t--;l+="0");}else if((t+=o-r)>0)for(o+1==r&&(l+=".");t--;l+="0");return e.s<0&&n?"-"+l:l}function D(e,t){for(var i,s,n=1,o=new M(e[0]);n=10;n/=10,s++);return(i=s+i*ct-1)>y?e.c=e.e=null:i=10;r/=10,n++);if((o=t-n)<0)o+=ct,a=t,l=d[c=0],h=ot(l/p[n-a-1]%10);else if((c=nt((o+1)/ct))>=d.length){if(!s)break e;for(;d.length<=c;d.push(0));l=h=0,n=1,a=(o%=ct)-ct+1}else{for(l=r=d[c],n=1;r>=10;r/=10,n++);h=(a=(o%=ct)-ct+n)<0?0:ot(l/p[n-a-1]%10)}if(s=s||t<0||null!=d[c+1]||(a<0?l:l%p[n-a-1]),s=i<4?(h||s)&&(0==i||i==(e.s<0?3:2)):h>5||5==h&&(4==i||s||6==i&&(o>0?a>0?l/p[n-a]:0:d[c-1])%10&1||i==(e.s<0?8:7)),t<1||!d[0])return d.length=0,s?(t-=e.e+1,d[0]=p[(ct-t%ct)%ct],e.e=-t||0):d[0]=e.e=0,e;if(0==o?(d.length=c,r=1,c--):(d.length=c+1,r=p[ct-o],d[c]=a>0?ot(l/p[n-a]%p[a])*r:0),s)for(;;){if(0==c){for(o=1,a=d[0];a>=10;a/=10,o++);for(a=d[0]+=r,r=1;a>=10;a/=10,r++);o!=r&&(e.e++,d[0]==lt&&(d[0]=1));break}if(d[c]+=r,d[c]!=lt)break;d[c--]=0,r=1}for(o=d.length;0===d[--o];d.pop());}e.e>y?e.c=e.e=null:e.e=f?yt(t,i):bt(t,i,"0"),e.s<0?"-"+t:t)}return M.clone=e,M.ROUND_UP=0,M.ROUND_DOWN=1,M.ROUND_CEIL=2,M.ROUND_FLOOR=3,M.ROUND_HALF_UP=4,M.ROUND_HALF_DOWN=5,M.ROUND_HALF_EVEN=6,M.ROUND_HALF_CEIL=7,M.ROUND_HALF_FLOOR=8,M.EUCLID=9,M.config=M.set=function(e){var t,i;if(null!=e){if("object"!=typeof e)throw Error(at+"Object expected: "+e);if(e.hasOwnProperty(t="DECIMAL_PLACES")&&(ft(i=e[t],0,ut,t),_=i),e.hasOwnProperty(t="ROUNDING_MODE")&&(ft(i=e[t],0,8,t),m=i),e.hasOwnProperty(t="EXPONENTIAL_AT")&&((i=e[t])&&i.pop?(ft(i[0],-ut,0,t),ft(i[1],0,ut,t),g=i[0],f=i[1]):(ft(i,-ut,ut,t),g=-(f=i<0?-i:i))),e.hasOwnProperty(t="RANGE"))if((i=e[t])&&i.pop)ft(i[0],-ut,-1,t),ft(i[1],1,ut,t),v=i[0],y=i[1];else{if(ft(i,-ut,ut,t),!i)throw Error(at+t+" cannot be zero: "+i);v=-(y=i<0?-i:i)}if(e.hasOwnProperty(t="CRYPTO")){if((i=e[t])!==!!i)throw Error(at+t+" not true or false: "+i);if(i){if("undefined"==typeof crypto||!crypto||!crypto.getRandomValues&&!crypto.randomBytes)throw b=!i,Error(at+"crypto unavailable");b=i}else b=i}if(e.hasOwnProperty(t="MODULO_MODE")&&(ft(i=e[t],0,9,t),w=i),e.hasOwnProperty(t="POW_PRECISION")&&(ft(i=e[t],0,ut,t),k=i),e.hasOwnProperty(t="FORMAT")){if("object"!=typeof(i=e[t]))throw Error(at+t+" not an object: "+i);x=i}if(e.hasOwnProperty(t="ALPHABET")){if("string"!=typeof(i=e[t])||/^.?$|[+\-.\s]|(.).*\1/.test(i))throw Error(at+t+" invalid: "+i);S="0123456789"==i.slice(0,10),$=i}}return{DECIMAL_PLACES:_,ROUNDING_MODE:m,EXPONENTIAL_AT:[g,f],RANGE:[v,y],CRYPTO:b,MODULO_MODE:w,POW_PRECISION:k,FORMAT:x,ALPHABET:$}},M.isBigNumber=function(e){if(!e||!0!==e._isBigNumber)return!1;if(!M.DEBUG)return!0;var t,i,s=e.c,n=e.e,o=e.s;e:if("[object Array]"=={}.toString.call(s)){if((1===o||-1===o)&&n>=-ut&&n<=ut&&n===ot(n)){if(0===s[0]){if(0===n&&1===s.length)return!0;break e}if((t=(n+1)%ct)<1&&(t+=ct),String(s[0]).length==t){for(t=0;t=lt||i!==ot(i))break e;if(0!==i)return!0}}}else if(null===s&&null===n&&(null===o||1===o||-1===o))return!0;throw Error(at+"Invalid BigNumber: "+e)},M.maximum=M.max=function(){return D(arguments,-1)},M.minimum=M.min=function(){return D(arguments,1)},M.random=(o=9007199254740992,a=Math.random()*o&2097151?function(){return ot(Math.random()*o)}:function(){return 8388608*(1073741824*Math.random()|0)+(8388608*Math.random()|0)},function(e){var t,i,s,n,o,r=0,l=[],c=new M(u);if(null==e?e=_:ft(e,0,ut),n=nt(e/ct),b)if(crypto.getRandomValues){for(t=crypto.getRandomValues(new Uint32Array(n*=2));r>>11))>=9e15?(i=crypto.getRandomValues(new Uint32Array(2)),t[r]=i[0],t[r+1]=i[1]):(l.push(o%1e14),r+=2);r=n/2}else{if(!crypto.randomBytes)throw b=!1,Error(at+"crypto unavailable");for(t=crypto.randomBytes(n*=7);r=9e15?crypto.randomBytes(7).copy(t,r):(l.push(o%1e14),r+=7);r=n/7}if(!b)for(;r=10;o/=10,r++);ri-1&&(null==a[n+1]&&(a[n+1]=0),a[n+1]+=a[n]/i|0,a[n]%=i)}return a.reverse()}return function(s,n,o,a,r){var l,c,h,d,p,u,g,f,v=s.indexOf("."),y=_,b=m;for(v>=0&&(d=k,k=0,s=s.replace(".",""),u=(f=new M(n)).pow(s.length-v),k=d,f.c=t(bt(mt(u.c),u.e,"0"),10,o,e),f.e=f.c.length),h=d=(g=t(s,n,o,r?(l=$,e):(l=e,$))).length;0==g[--d];g.pop());if(!g[0])return l.charAt(0);if(v<0?--h:(u.c=g,u.e=h,u.s=a,g=(u=i(u,f,y,b,o)).c,p=u.r,h=u.e),v=g[c=h+y+1],d=o/2,p=p||c<0||null!=g[c+1],p=b<4?(null!=v||p)&&(0==b||b==(u.s<0?3:2)):v>d||v==d&&(4==b||p||6==b&&1&g[c-1]||b==(u.s<0?8:7)),c<1||!g[0])s=p?bt(l.charAt(1),-y,l.charAt(0)):l.charAt(0);else{if(g.length=c,p)for(--o;++g[--c]>o;)g[c]=0,c||(++h,g=[1].concat(g));for(d=g.length;!g[--d];);for(v=0,s="";v<=d;s+=l.charAt(g[v++]));s=bt(s,h,l.charAt(0))}return s}}(),i=function(){function e(e,t,i){var s,n,o,a,r=0,l=e.length,c=t%pt,h=t/pt|0;for(e=e.slice();l--;)r=((n=c*(o=e[l]%pt)+(s=h*o+(a=e[l]/pt|0)*c)%pt*pt+r)/i|0)+(s/pt|0)+h*a,e[l]=n%i;return r&&(e=[r].concat(e)),e}function t(e,t,i,s){var n,o;if(i!=s)o=i>s?1:-1;else for(n=o=0;nt[n]?1:-1;break}return o}function i(e,t,i,s){for(var n=0;i--;)e[i]-=n,n=e[i]1;e.splice(0,1));}return function(s,n,o,a,r){var l,c,h,d,p,u,_,m,g,f,v,y,b,w,k,x,$,S=s.s==n.s?1:-1,C=s.c,D=n.c;if(!(C&&C[0]&&D&&D[0]))return new M(s.s&&n.s&&(C?!D||C[0]!=D[0]:D)?C&&0==C[0]||!D?0*S:S/0:NaN);for(g=(m=new M(S)).c=[],S=o+(c=s.e-n.e)+1,r||(r=lt,c=_t(s.e/ct)-_t(n.e/ct),S=S/ct|0),h=0;D[h]==(C[h]||0);h++);if(D[h]>(C[h]||0)&&c--,S<0)g.push(1),d=!0;else{for(w=C.length,x=D.length,h=0,S+=2,(p=ot(r/(D[0]+1)))>1&&(D=e(D,p,r),C=e(C,p,r),x=D.length,w=C.length),b=x,v=(f=C.slice(0,x)).length;v=r/2&&k++;do{if(p=0,(l=t(D,f,x,v))<0){if(y=f[0],x!=v&&(y=y*r+(f[1]||0)),(p=ot(y/k))>1)for(p>=r&&(p=r-1),_=(u=e(D,p,r)).length,v=f.length;1==t(u,f,_,v);)p--,i(u,x<_?$:D,_,r),_=u.length,l=1;else 0==p&&(l=p=1),_=(u=D.slice()).length;if(_=10;S/=10,h++);T(m,o+(m.e=h+c*ct-1)+1,a,d)}else m.e=c,m.r=+d;return m}}(),r=/^(-?)0([xbo])(?=\w[\w.]*$)/i,l=/^([^.]+)\.$/,c=/^\.([^.]+)$/,h=/^-?(Infinity|NaN)$/,d=/^\s*\+(?=[\w.])|^\s+|\s+$/g,n=function(e,t,i,s){var n,o=i?t:t.replace(d,"");if(h.test(o))e.s=isNaN(o)?null:o<0?-1:1;else{if(!i&&(o=o.replace(r,function(e,t,i){return n="x"==(i=i.toLowerCase())?16:"b"==i?2:8,s&&s!=n?e:t}),s&&(n=s,o=o.replace(l,"$1").replace(c,"0.$1")),t!=o))return new M(o,n);if(M.DEBUG)throw Error(at+"Not a"+(s?" base "+s:"")+" number: "+t);e.s=null}e.c=e.e=null},p.absoluteValue=p.abs=function(){var e=new M(this);return e.s<0&&(e.s=1),e},p.comparedTo=function(e,t){return gt(this,new M(e,t))},p.decimalPlaces=p.dp=function(e,t){var i,s,n,o=this;if(null!=e)return ft(e,0,ut),null==t?t=m:ft(t,0,8),T(new M(o),e+o.e+1,t);if(!(i=o.c))return null;if(s=((n=i.length-1)-_t(this.e/ct))*ct,n=i[n])for(;n%10==0;n/=10,s--);return s<0&&(s=0),s},p.dividedBy=p.div=function(e,t){return i(this,new M(e,t),_,m)},p.dividedToIntegerBy=p.idiv=function(e,t){return i(this,new M(e,t),0,1)},p.exponentiatedBy=p.pow=function(e,t){var i,s,n,o,a,r,l,c,h=this;if((e=new M(e)).c&&!e.isInteger())throw Error(at+"Exponent not an integer: "+I(e));if(null!=t&&(t=new M(t)),a=e.e>14,!h.c||!h.c[0]||1==h.c[0]&&!h.e&&1==h.c.length||!e.c||!e.c[0])return c=new M(Math.pow(+I(h),a?e.s*(2-vt(e)):+I(e))),t?c.mod(t):c;if(r=e.s<0,t){if(t.c?!t.c[0]:!t.s)return new M(NaN);(s=!r&&h.isInteger()&&t.isInteger())&&(h=h.mod(t))}else{if(e.e>9&&(h.e>0||h.e<-1||(0==h.e?h.c[0]>1||a&&h.c[1]>=24e7:h.c[0]<8e13||a&&h.c[0]<=9999975e7)))return o=h.s<0&&vt(e)?-0:0,h.e>-1&&(o=1/o),new M(r?1/o:o);k&&(o=nt(k/ct+2))}for(a?(i=new M(.5),r&&(e.s=1),l=vt(e)):l=(n=Math.abs(+I(e)))%2,c=new M(u);;){if(l){if(!(c=c.times(h)).c)break;o?c.c.length>o&&(c.c.length=o):s&&(c=c.mod(t))}if(n){if(0===(n=ot(n/2)))break;l=n%2}else if(T(e=e.times(i),e.e+1,1),e.e>14)l=vt(e);else{if(0===(n=+I(e)))break;l=n%2}h=h.times(h),o?h.c&&h.c.length>o&&(h.c.length=o):s&&(h=h.mod(t))}return s?c:(r&&(c=u.div(c)),t?c.mod(t):o?T(c,k,m,void 0):c)},p.integerValue=function(e){var t=new M(this);return null==e?e=m:ft(e,0,8),T(t,t.e+1,e)},p.isEqualTo=p.eq=function(e,t){return 0===gt(this,new M(e,t))},p.isFinite=function(){return!!this.c},p.isGreaterThan=p.gt=function(e,t){return gt(this,new M(e,t))>0},p.isGreaterThanOrEqualTo=p.gte=function(e,t){return 1===(t=gt(this,new M(e,t)))||0===t},p.isInteger=function(){return!!this.c&&_t(this.e/ct)>this.c.length-2},p.isLessThan=p.lt=function(e,t){return gt(this,new M(e,t))<0},p.isLessThanOrEqualTo=p.lte=function(e,t){return-1===(t=gt(this,new M(e,t)))||0===t},p.isNaN=function(){return!this.s},p.isNegative=function(){return this.s<0},p.isPositive=function(){return this.s>0},p.isZero=function(){return!!this.c&&0==this.c[0]},p.minus=function(e,t){var i,s,n,o,a=this,r=a.s;if(t=(e=new M(e,t)).s,!r||!t)return new M(NaN);if(r!=t)return e.s=-t,a.plus(e);var l=a.e/ct,c=e.e/ct,h=a.c,d=e.c;if(!l||!c){if(!h||!d)return h?(e.s=-t,e):new M(d?a:NaN);if(!h[0]||!d[0])return d[0]?(e.s=-t,e):new M(h[0]?a:3==m?-0:0)}if(l=_t(l),c=_t(c),h=h.slice(),r=l-c){for((o=r<0)?(r=-r,n=h):(c=l,n=d),n.reverse(),t=r;t--;n.push(0));n.reverse()}else for(s=(o=(r=h.length)<(t=d.length))?r:t,r=t=0;t0)for(;t--;h[i++]=0);for(t=lt-1;s>r;){if(h[--s]=0;){for(i=0,p=y[n]%g,u=y[n]/g|0,o=n+(a=l);o>n;)i=((c=p*(c=v[--a]%g)+(r=u*c+(h=v[a]/g|0)*p)%g*g+_[o]+i)/m|0)+(r/g|0)+u*h,_[o--]=c%m;_[o]=i}return i?++s:_.splice(0,1),P(e,_,s)},p.negated=function(){var e=new M(this);return e.s=-e.s||null,e},p.plus=function(e,t){var i,s=this,n=s.s;if(t=(e=new M(e,t)).s,!n||!t)return new M(NaN);if(n!=t)return e.s=-t,s.minus(e);var o=s.e/ct,a=e.e/ct,r=s.c,l=e.c;if(!o||!a){if(!r||!l)return new M(n/0);if(!r[0]||!l[0])return l[0]?e:new M(r[0]?s:0*n)}if(o=_t(o),a=_t(a),r=r.slice(),n=o-a){for(n>0?(a=o,i=l):(n=-n,i=r),i.reverse();n--;i.push(0));i.reverse()}for((n=r.length)-(t=l.length)<0&&(i=l,l=r,r=i,t=n),n=0;t;)n=(r[--t]=r[t]+l[t]+n)/lt|0,r[t]=lt===r[t]?0:r[t]%lt;return n&&(r=[n].concat(r),++a),P(e,r,a)},p.precision=p.sd=function(e,t){var i,s,n,o=this;if(null!=e&&e!==!!e)return ft(e,1,ut),null==t?t=m:ft(t,0,8),T(new M(o),e,t);if(!(i=o.c))return null;if(s=(n=i.length-1)*ct+1,n=i[n]){for(;n%10==0;n/=10,s--);for(n=i[0];n>=10;n/=10,s++);}return e&&o.e+1>s&&(s=o.e+1),s},p.shiftedBy=function(e){return ft(e,-9007199254740991,ht),this.times("1e"+e)},p.squareRoot=p.sqrt=function(){var e,t,s,n,o,a=this,r=a.c,l=a.s,c=a.e,h=_+4,d=new M("0.5");if(1!==l||!r||!r[0])return new M(!l||l<0&&(!r||r[0])?NaN:r?a:1/0);if(0==(l=Math.sqrt(+I(a)))||l==1/0?(((t=mt(r)).length+c)%2==0&&(t+="0"),l=Math.sqrt(+t),c=_t((c+1)/2)-(c<0||c%2),s=new M(t=l==1/0?"5e"+c:(t=l.toExponential()).slice(0,t.indexOf("e")+1)+c)):s=new M(l+""),s.c[0])for((l=(c=s.e)+h)<3&&(l=0);;)if(o=s,s=d.times(o.plus(i(a,o,h,1))),mt(o.c).slice(0,l)===(t=mt(s.c)).slice(0,l)){if(s.e0&&_>0){for(o=_%r||r,h=u.substr(0,o);o<_;o+=r)h+=c+u.substr(o,r);l>0&&(h+=c+u.slice(o)),p&&(h="-"+h)}s=d?h+(i.decimalSeparator||"")+((l=+i.fractionGroupSize)?d.replace(new RegExp("\\d{"+l+"}\\B","g"),"$&"+(i.fractionGroupSeparator||"")):d):h}return(i.prefix||"")+s+(i.suffix||"")},p.toFraction=function(e){var t,s,n,o,a,r,l,c,h,d,p,_,g=this,f=g.c;if(null!=e&&(!(l=new M(e)).isInteger()&&(l.c||1!==l.s)||l.lt(u)))throw Error(at+"Argument "+(l.isInteger()?"out of range: ":"not an integer: ")+I(l));if(!f)return new M(g);for(t=new M(u),h=s=new M(u),n=c=new M(u),_=mt(f),a=t.e=_.length-g.e-1,t.c[0]=dt[(r=a%ct)<0?ct+r:r],e=!e||l.comparedTo(t)>0?a>0?t:h:l,r=y,y=1/0,l=new M(_),c.c[0]=0;d=i(l,t,0,1),1!=(o=s.plus(d.times(n))).comparedTo(e);)s=n,n=o,h=c.plus(d.times(o=h)),c=o,t=l.minus(d.times(o=t)),l=o;return o=i(e.minus(s),n,0,1),c=c.plus(o.times(h)),s=s.plus(o.times(n)),c.s=h.s=g.s,p=i(h,n,a*=2,m).minus(g).abs().comparedTo(i(c,s,a,m).minus(g).abs())<1?[h,n]:[c,s],y=r,p},p.toNumber=function(){return+I(this)},p.toPrecision=function(e,t){return null!=e&&ft(e,1,ut),C(this,e,t,2)},p.toString=function(e){var t,i=this,n=i.s,o=i.e;return null===o?n?(t="Infinity",n<0&&(t="-"+t)):t="NaN":(null==e?t=o<=g||o>=f?yt(mt(i.c),o):bt(mt(i.c),o,"0"):10===e&&S?t=bt(mt((i=T(new M(i),_+o+1,m)).c),i.e,"0"):(ft(e,2,$.length,"Base"),t=s(bt(mt(i.c),o,"0"),10,e,n,!0)),n<0&&i.c[0]&&(t="-"+t)),t},p.valueOf=p.toJSON=function(){return I(this)},p._isBigNumber=!0,p[Symbol.toStringTag]="BigNumber",p[Symbol.for("nodejs.util.inspect.custom")]=p.valueOf,null!=t&&M.set(t),M}(),kt=class{key;left=null;right=null;constructor(e){this.key=e}},xt=class extends kt{constructor(e){super(e)}},$t=class{size=0;modificationCount=0;splayCount=0;splay(e){const t=this.root;if(null==t)return this.compare(e,e),-1;let i=null,s=null,n=null,o=null,a=t;const r=this.compare;let l;for(;;)if(l=r(a.key,e),l>0){let t=a.left;if(null==t)break;if(l=r(t.key,e),l>0&&(a.left=t.right,t.right=a,a=t,t=a.left,null==t))break;null==i?s=a:i.left=a,i=a,a=t}else{if(!(l<0))break;{let t=a.right;if(null==t)break;if(l=r(t.key,e),l<0&&(a.right=t.left,t.left=a,a=t,t=a.right,null==t))break;null==n?o=a:n.right=a,n=a,a=t}}return null!=n&&(n.right=a.left,a.left=o),null!=i&&(i.left=a.right,a.right=s),this.root!==a&&(this.root=a,this.splayCount++),l}splayMin(e){let t=e,i=t.left;for(;null!=i;){const e=i;t.left=e.right,e.right=t,t=e,i=t.left}return t}splayMax(e){let t=e,i=t.right;for(;null!=i;){const e=i;t.right=e.left,e.left=t,t=e,i=t.right}return t}_delete(e){if(null==this.root)return null;if(0!=this.splay(e))return null;let t=this.root;const i=t,s=t.left;if(this.size--,null==s)this.root=t.right;else{const e=t.right;t=this.splayMax(s),t.right=e,this.root=t}return this.modificationCount++,i}addNewRoot(e,t){this.size++,this.modificationCount++;const i=this.root;null!=i?(t<0?(e.left=i,e.right=i.right,i.right=null):(e.right=i,e.left=i.left,i.left=null),this.root=e):this.root=e}_first(){const e=this.root;return null==e?null:(this.root=this.splayMin(e),this.root)}_last(){const e=this.root;return null==e?null:(this.root=this.splayMax(e),this.root)}clear(){this.root=null,this.size=0,this.modificationCount++}has(e){return this.validKey(e)&&0==this.splay(e)}defaultCompare(){return(e,t)=>et?1:0}wrap(){return{getRoot:()=>this.root,setRoot:e=>{this.root=e},getSize:()=>this.size,getModificationCount:()=>this.modificationCount,getSplayCount:()=>this.splayCount,setSplayCount:e=>{this.splayCount=e},splay:e=>this.splay(e),has:e=>this.has(e)}}},St=class e extends $t{root=null;compare;validKey;constructor(e,t){super(),this.compare=e??this.defaultCompare(),this.validKey=t??(e=>null!=e&&null!=e)}delete(e){return!!this.validKey(e)&&null!=this._delete(e)}deleteAll(e){for(const t of e)this.delete(t)}forEach(e){const t=this[Symbol.iterator]();let i;for(;i=t.next(),!i.done;)e(i.value,i.value,this)}add(e){const t=this.splay(e);return 0!=t&&this.addNewRoot(new xt(e),t),this}addAndReturn(e){const t=this.splay(e);return 0!=t&&this.addNewRoot(new xt(e),t),this.root.key}addAll(e){for(const t of e)this.add(t)}isEmpty(){return null==this.root}isNotEmpty(){return null!=this.root}single(){if(0==this.size)throw"Bad state: No element";if(this.size>1)throw"Bad state: Too many element";return this.root.key}first(){if(0==this.size)throw"Bad state: No element";return this._first().key}last(){if(0==this.size)throw"Bad state: No element";return this._last().key}lastBefore(e){if(null==e)throw"Invalid arguments(s)";if(null==this.root)return null;if(this.splay(e)<0)return this.root.key;let t=this.root.left;if(null==t)return null;let i=t.right;for(;null!=i;)t=i,i=t.right;return t.key}firstAfter(e){if(null==e)throw"Invalid arguments(s)";if(null==this.root)return null;if(this.splay(e)>0)return this.root.key;let t=this.root.right;if(null==t)return null;let i=t.left;for(;null!=i;)t=i,i=t.left;return t.key}retainAll(t){const i=new e(this.compare,this.validKey),s=this.modificationCount;for(const e of t){if(s!=this.modificationCount)throw"Concurrent modification during iteration.";this.validKey(e)&&0==this.splay(e)&&i.add(this.root.key)}i.size!=this.size&&(this.root=i.root,this.size=i.size,this.modificationCount++)}lookup(e){if(!this.validKey(e))return null;return 0!=this.splay(e)?null:this.root.key}intersection(t){const i=new e(this.compare,this.validKey);for(const e of this)t.has(e)&&i.add(e);return i}difference(t){const i=new e(this.compare,this.validKey);for(const e of this)t.has(e)||i.add(e);return i}union(e){const t=this.clone();return t.addAll(e),t}clone(){const t=new e(this.compare,this.validKey);return t.size=this.size,t.root=this.copyNode(this.root),t}copyNode(e){if(null==e)return null;const t=new xt(e.key);return function e(t,i){let s,n;do{if(s=t.left,n=t.right,null!=s){const t=new xt(s.key);i.left=t,e(s,t)}if(null!=n){const e=new xt(n.key);i.right=e,t=n,i=e}}while(null!=n)}(e,t),t}toSet(){return this.clone()}entries(){return new Dt(this.wrap())}keys(){return this[Symbol.iterator]()}values(){return this[Symbol.iterator]()}[Symbol.iterator](){return new Ct(this.wrap())}[Symbol.toStringTag]="[object Set]"},Mt=class{tree;path=new Array;modificationCount=null;splayCount;constructor(e){this.tree=e,this.splayCount=e.getSplayCount()}[Symbol.iterator](){return this}next(){return this.moveNext()?{done:!1,value:this.current()}:{done:!0,value:null}}current(){if(!this.path.length)return null;const e=this.path[this.path.length-1];return this.getValue(e)}rebuildPath(e){this.path.splice(0,this.path.length),this.tree.splay(e),this.path.push(this.tree.getRoot()),this.splayCount=this.tree.getSplayCount()}findLeftMostDescendent(e){for(;null!=e;)this.path.push(e),e=e.left}moveNext(){if(this.modificationCount!=this.tree.getModificationCount()){if(null==this.modificationCount){this.modificationCount=this.tree.getModificationCount();let e=this.tree.getRoot();for(;null!=e;)this.path.push(e),e=e.left;return this.path.length>0}throw"Concurrent modification during iteration."}if(!this.path.length)return!1;this.splayCount!=this.tree.getSplayCount()&&this.rebuildPath(this.path[this.path.length-1].key);let e=this.path[this.path.length-1],t=e.right;if(null!=t){for(;null!=t;)this.path.push(t),t=t.left;return!0}for(this.path.pop();this.path.length&&this.path[this.path.length-1].right===e;)e=this.path.pop();return this.path.length>0}},Ct=class extends Mt{getValue(e){return e.key}},Dt=class extends Mt{getValue(e){return[e.key,e.key]}},Pt=e=>()=>e,Tt=e=>{const t=e?(t,i)=>i.minus(t).abs().isLessThanOrEqualTo(e):Pt(!1);return(e,i)=>t(e,i)?0:e.comparedTo(i)};function It(e){const t=e?(t,i,s,n,o)=>t.exponentiatedBy(2).isLessThanOrEqualTo(n.minus(i).exponentiatedBy(2).plus(o.minus(s).exponentiatedBy(2)).times(e)):Pt(!1);return(e,i,s)=>{const n=e.x,o=e.y,a=s.x,r=s.y,l=o.minus(r).times(i.x.minus(a)).minus(n.minus(a).times(i.y.minus(r)));return t(l,n,o,a,r)?0:l.comparedTo(0)}}var Rt=e=>e,At=e=>{if(e){const t=new St(Tt(e)),i=new St(Tt(e)),s=(e,t)=>t.addAndReturn(e),n=e=>({x:s(e.x,t),y:s(e.y,i)});return n({x:new wt(0),y:new wt(0)}),n}return Rt},zt=e=>({set:e=>{Ft=zt(e)},reset:()=>zt(e),compare:Tt(e),snap:At(e),orient:It(e)}),Ft=zt(),Et=(e,t)=>e.ll.x.isLessThanOrEqualTo(t.x)&&t.x.isLessThanOrEqualTo(e.ur.x)&&e.ll.y.isLessThanOrEqualTo(t.y)&&t.y.isLessThanOrEqualTo(e.ur.y),Nt=(e,t)=>{if(t.ur.x.isLessThan(e.ll.x)||e.ur.x.isLessThan(t.ll.x)||t.ur.y.isLessThan(e.ll.y)||e.ur.y.isLessThan(t.ll.y))return null;const i=e.ll.x.isLessThan(t.ll.x)?t.ll.x:e.ll.x,s=e.ur.x.isLessThan(t.ur.x)?e.ur.x:t.ur.x;return{ll:{x:i,y:e.ll.y.isLessThan(t.ll.y)?t.ll.y:e.ll.y},ur:{x:s,y:e.ur.y.isLessThan(t.ur.y)?e.ur.y:t.ur.y}}},Ot=(e,t)=>e.x.times(t.y).minus(e.y.times(t.x)),Ht=(e,t)=>e.x.times(t.x).plus(e.y.times(t.y)),Lt=e=>Ht(e,e).sqrt(),Bt=(e,t,i)=>{const s={x:t.x.minus(e.x),y:t.y.minus(e.y)},n={x:i.x.minus(e.x),y:i.y.minus(e.y)};return Ot(n,s).div(Lt(n)).div(Lt(s))},qt=(e,t,i)=>{const s={x:t.x.minus(e.x),y:t.y.minus(e.y)},n={x:i.x.minus(e.x),y:i.y.minus(e.y)};return Ht(n,s).div(Lt(n)).div(Lt(s))},Wt=(e,t,i)=>t.y.isZero()?null:{x:e.x.plus(t.x.div(t.y).times(i.minus(e.y))),y:i},jt=(e,t,i)=>t.x.isZero()?null:{x:i,y:e.y.plus(t.y.div(t.x).times(i.minus(e.x)))},Ut=class e{point;isLeft;segment;otherSE;consumedBy;static compare(t,i){const s=e.comparePoints(t.point,i.point);return 0!==s?s:(t.point!==i.point&&t.link(i),t.isLeft!==i.isLeft?t.isLeft?1:-1:Qt.compare(t.segment,i.segment))}static comparePoints(e,t){return e.x.isLessThan(t.x)?-1:e.x.isGreaterThan(t.x)?1:e.y.isLessThan(t.y)?-1:e.y.isGreaterThan(t.y)?1:0}constructor(e,t){void 0===e.events?e.events=[this]:e.events.push(this),this.point=e,this.isLeft=t}link(e){if(e.point===this.point)throw new Error("Tried to link already linked events");const t=e.point.events;for(let e=0,i=t.length;e{const s=i.otherSE;t.set(i,{sine:Bt(this.point,e.point,s.point),cosine:qt(this.point,e.point,s.point)})};return(e,s)=>{t.has(e)||i(e),t.has(s)||i(s);const{sine:n,cosine:o}=t.get(e),{sine:a,cosine:r}=t.get(s);return n.isGreaterThanOrEqualTo(0)&&a.isGreaterThanOrEqualTo(0)?o.isLessThan(r)?1:o.isGreaterThan(r)?-1:0:n.isLessThan(0)&&a.isLessThan(0)?o.isLessThan(r)?-1:o.isGreaterThan(r)?1:0:a.isLessThan(n)?-1:a.isGreaterThan(n)?1:0}}},Gt=class e{events;poly;_isExteriorRing;_enclosingRing;static factory(t){const i=[];for(let s=0,n=t.length;s0&&(e=i)}let t=e.segment.prevInResult(),i=t?t.prevInResult():null;for(;;){if(!t)return null;if(!i)return t.ringOut;if(i.ringOut!==t.ringOut)return i.ringOut?.enclosingRing()!==t.ringOut?t.ringOut:t.ringOut?.enclosingRing();t=i.prevInResult(),i=t?t.prevInResult():null}}},Vt=class{exteriorRing;interiorRings;constructor(e){this.exteriorRing=e,e.poly=this,this.interiorRings=[]}addInterior(e){this.interiorRings.push(e),e.poly=this}getGeom(){const e=this.exteriorRing.getGeom();if(null===e)return null;const t=[e];for(let e=0,i=this.interiorRings.length;e0?(this.tree.delete(t),i.push(e)):(this.segments.push(t),t.prev=s)}else{if(s&&n){const e=s.getIntersection(n);if(null!==e){if(!s.isAnEndpoint(e)){const t=this._splitSafely(s,e);for(let e=0,s=t.length;e0)return-1;const s=t.comparePoint(e.rightSE.point);return 0!==s?s:-1}if(i.isGreaterThan(s)){if(a.isLessThan(r)&&a.isLessThan(c))return-1;if(a.isGreaterThan(r)&&a.isGreaterThan(c))return 1;const i=t.comparePoint(e.leftSE.point);if(0!==i)return i;const s=e.comparePoint(t.rightSE.point);return s<0?1:s>0?-1:1}if(a.isLessThan(r))return-1;if(a.isGreaterThan(r))return 1;if(n.isLessThan(o)){const i=t.comparePoint(e.rightSE.point);if(0!==i)return i}if(n.isGreaterThan(o)){const i=e.comparePoint(t.rightSE.point);if(i<0)return 1;if(i>0)return-1}if(!n.eq(o)){const e=l.minus(a),t=n.minus(i),h=c.minus(r),d=o.minus(s);if(e.isGreaterThan(t)&&h.isLessThan(d))return 1;if(e.isLessThan(t)&&h.isGreaterThan(d))return-1}return n.isGreaterThan(o)?1:n.isLessThan(o)||l.isLessThan(c)?-1:l.isGreaterThan(c)?1:e.idt.id?1:0}constructor(e,t,i,s){this.id=++Zt,this.leftSE=e,e.segment=this,e.otherSE=t,this.rightSE=t,t.segment=this,t.otherSE=e,this.rings=i,this.windings=s}static fromRing(t,i,s){let n,o,a;const r=Ut.comparePoints(t,i);if(r<0)n=t,o=i,a=1;else{if(!(r>0))throw new Error(`Tried to create degenerate segment at [${t.x}, ${t.y}]`);n=i,o=t,a=-1}const l=new Ut(n,!0),c=new Ut(o,!1);return new e(l,c,[s],[a])}replaceRightSE(e){this.rightSE=e,this.rightSE.segment=this,this.rightSE.otherSE=this.leftSE,this.leftSE.otherSE=this.rightSE}bbox(){const e=this.leftSE.point.y,t=this.rightSE.point.y;return{ll:{x:this.leftSE.point.x,y:e.isLessThan(t)?e:t},ur:{x:this.rightSE.point.x,y:e.isGreaterThan(t)?e:t}}}vector(){return{x:this.rightSE.point.x.minus(this.leftSE.point.x),y:this.rightSE.point.y.minus(this.leftSE.point.y)}}isAnEndpoint(e){return e.x.eq(this.leftSE.point.x)&&e.y.eq(this.leftSE.point.y)||e.x.eq(this.rightSE.point.x)&&e.y.eq(this.rightSE.point.y)}comparePoint(e){return Ft.orient(this.leftSE.point,e,this.rightSE.point)}getIntersection(e){const t=this.bbox(),i=e.bbox(),s=Nt(t,i);if(null===s)return null;const n=this.leftSE.point,o=this.rightSE.point,a=e.leftSE.point,r=e.rightSE.point,l=Et(t,a)&&0===this.comparePoint(a),c=Et(i,n)&&0===e.comparePoint(n),h=Et(t,r)&&0===this.comparePoint(r),d=Et(i,o)&&0===e.comparePoint(o);if(c&&l)return d&&!h?o:!d&&h?r:null;if(c)return h&&n.x.eq(r.x)&&n.y.eq(r.y)?null:n;if(l)return d&&o.x.eq(a.x)&&o.y.eq(a.y)?null:a;if(d&&h)return null;if(d)return o;if(h)return r;const p=((e,t,i,s)=>{if(t.x.isZero())return jt(i,s,e.x);if(s.x.isZero())return jt(e,t,i.x);if(t.y.isZero())return Wt(i,s,e.y);if(s.y.isZero())return Wt(e,t,i.y);const n=Ot(t,s);if(n.isZero())return null;const o={x:i.x.minus(e.x),y:i.y.minus(e.y)},a=Ot(o,t).div(n),r=Ot(o,s).div(n),l=e.x.plus(r.times(t.x)),c=i.x.plus(a.times(s.x)),h=e.y.plus(r.times(t.y)),d=i.y.plus(a.times(s.y));return{x:l.plus(c).div(2),y:h.plus(d).div(2)}})(n,this.vector(),a,e.vector());return null===p?null:Et(s,p)?Ft.snap(p):null}split(t){const i=[],s=void 0!==t.events,n=new Ut(t,!0),o=new Ut(t,!1),a=this.rightSE;this.replaceRightSE(o),i.push(o),i.push(n);const r=new e(n,a,this.rings.slice(),this.windings.slice());return Ut.comparePoints(r.leftSE.point,r.rightSE.point)>0&&r.swapEvents(),Ut.comparePoints(this.leftSE.point,this.rightSE.point)>0&&this.swapEvents(),s&&(n.checkForConsuming(),o.checkForConsuming()),i}swapEvents(){const e=this.rightSE;this.rightSE=this.leftSE,this.leftSE=e,this.leftSE.isLeft=!0,this.rightSE.isLeft=!1;for(let e=0,t=this.windings.length;e0){const e=i;i=s,s=e}if(i.prev===s){const e=i;i=s,s=e}for(let e=0,t=s.rings.length;e1===e.length&&e[0].isSubject;this._isInResult=i(e)!==i(t);break}}return this._isInResult}},ei=class{poly;isExterior;segments;bbox;constructor(e,t,i){if(!Array.isArray(e)||0===e.length)throw new Error("Input geometry is not a valid Polygon or MultiPolygon");if(this.poly=t,this.isExterior=i,this.segments=[],"number"!=typeof e[0][0]||"number"!=typeof e[0][1])throw new Error("Input geometry is not a valid Polygon or MultiPolygon");const s=Ft.snap({x:new wt(e[0][0]),y:new wt(e[0][1])});this.bbox={ll:{x:s.x,y:s.y},ur:{x:s.x,y:s.y}};let n=s;for(let t=1,i=e.length;tXt.run("union",e,t),ni=(e,...t)=>Xt.run("intersection",e,t),oi=(e,...t)=>Xt.run("difference",e,t);function ai(e){const t=Math.max(0,Math.min(120,(e-40)/140*120));return`hsl(${Math.round(t)}, 85%, 55%)`}function ri(e,t){if(!(Number.isFinite(e)&&t>0))return e;const i=Math.round(e/t)*t;return Math.abs(i-e)<=1e-9*t?e:i}function li(e,t){if(t){const t=e/2.54;let i=Math.floor(t/12),s=Math.round(t-12*i);return 12===s&&(i+=1,s=0),`${i}′ ${s}″`}return`${(e/100).toFixed(2)} m`}function ci(e,t,i=1){const s=e[0].toFixed(i),n=e[1].toFixed(i),o=t[0].toFixed(i),a=t[1].toFixed(i),r=s=3?e.poly:e&&null!=e.x&&null!=e.y&&null!=e.w&&null!=e.h?[[e.x,e.y],[e.x+e.w,e.y],[e.x+e.w,e.y+e.h],[e.x,e.y+e.h]]:null}function di(e){const t=[];for(const i of e||[])i?.poly?.length>=3?t.push({poly:i.poly.map(e=>e.join(",")).join(" ")}):i&&null!=i.x&&null!=i.y&&null!=i.w&&null!=i.h&&t.push({rect:{x:i.x,y:i.y,w:i.w,h:i.h,rx:.03*Math.min(i.w,i.h)}});return t}function pi(e){const t=[],i=new Set;for(const s of e||[]){const e=hi(s);if(e)for(let s=0;s=90?e-=180:e<-90&&(e+=180),s.step&&s.step>0){const i=Math.sqrt(d),o=Math.min(Math.max(s.length||0,0)/2,i/2);let r=Math.round(p*i/s.step)*s.step;Math.abs(p*i-i/2)<=s.step/2&&(r=i/2),r=Math.max(o,Math.min(i-o,r));const l=r/i;n={x:t+l*c,y:a+l*h,angle:e}}else n={x:u[0],y:u[1],angle:e}}}return n}function _i(e,t,i,s,n,o=1){const a=t*Math.PI/180,r=[Math.cos(a),Math.sin(a)];let l=null,c=o;for(const t of pi(s)){const i=[[t[0],t[1]],[t[2],t[3]]],s=t=>Math.abs(r[0]*(t[1]-e[1])-r[1]*(t[0]-e[0]));if(s(i[0])>o||s(i[1])>o)continue;const n=(i[0][0]-e[0])*r[0]+(i[0][1]-e[1])*r[1],a=(i[1][0]-e[0])*r[0]+(i[1][1]-e[1])*r[1],h=Math.min(n,a),d=Math.max(n,a),p=h>0?h:d<0?-d:0;p[e[0]+r[0]*t,e[1]+r[1]*t],g=(h+d)/2;return{wallA:m(h),wallB:m(d),sideA:u,sideB:_,midA:m((h-p)/2),midB:m((p+d)/2),wallCenter:m(g),centered:Math.abs(g)<=n}}function mi(e,t,i=!1){if("passage"===e)return 1;if(null==t||"unavailable"===t||"unknown"===t)return"window"===e?0:1;const s=function(e){return["on","open","home","detected","playing","cleaning"].includes(String(e))}(t)!==!!i;return s?1:0}function gi(e){return"passage"===e.type?[]:[e.contact,e.lock].filter(e=>"string"==typeof e&&e.length>0)}function fi(e,t,i=.001){return Math.abs(e[0]-t[0])e[1]!=l>e[1]&&e[0]<(r-o)*(e[1]-a)/(l-a)+o&&(i=!i)}return i}function yi(e,t,i){const s=i[0]-t[0],n=i[1]-t[1],o=s*s+n*n;let a=o?((e[0]-t[0])*s+(e[1]-t[1])*n)/o:0;return a=Math.max(0,Math.min(1,a)),Math.hypot(e[0]-(t[0]+a*s),e[1]-(t[1]+a*n))}function bi(e,t,i=1e-6){if(!t||t.length<2)return!1;for(let s=0;sn&&a<-n||o<-n&&a>n)&&(r>n&&l<-n||r<-n&&l>n)}function $i(e,t=24){const i=e.map(e=>e[0]),s=e.map(e=>e[1]),n=Math.min(...i),o=Math.max(...i),a=Math.min(...s),r=Math.max(...s),l=Math.max(o-n,r-a)||1;let c=0,h=0,d=0;for(let t=0;t1e-9?[h/(3*c),d/(3*c)]:[(n+o)/2,(a+r)/2],u=(t,i)=>{const s=((t,i)=>{if(!vi([t,i],e))return-1/0;let s=1/0;for(let n=0;nm&&(m=c,_=[s,l])}if(_){const[e,i]=_,s=(o-n)/t,l=(r-a)/t;for(let t=-4;t<=4;t++)for(let n=-4;n<=4;n++){const o=e+s*t/4,a=i+l*n/4,r=u(o,a);r>m&&(m=r,_=[o,a])}}return _||Si(e)||e[0]}function Si(e,t=1e-6){if(!e||e.length<3)return null;const i=e.length,s=[e.reduce((e,t)=>e+t[0],0)/i,e.reduce((e,t)=>e+t[1],0)/i];if(wi(s,e,t))return s;for(let s=0;sCi(e,t,i));return s.filter(e=>!s.some(t=>t!==e&&Ci(t,e,i)))}function Ti(e){if(!e||e.length<3)return 0;let t=0;for(let i=0;i[e[0],e[1]]),[e[0][0],e[0][1]]]]}function Ri(e,t,i){for(let s=0;s1&&fi(i[0],i[i.length-1],t)&&i.pop(),i}function zi(e,t,i=1e-6){if(!e||e.length<3||!t||t.length<2)return null;const s=t[0],n=t[t.length-1];if(fi(s,n,i))return null;const o=Ri(e,s,i),a=Ri(e,n,i);if(o<0||a<0)return null;const r=t.slice(1,-1);for(const t of r)if(!wi(t,e,i))return null;for(let i=0;i{const a=[t];let r=(s+1)%e.length;for(let t=0;t<=e.length&&(a.push(e[r]),r!==o);t++)r=(r+1)%e.length;return a.push(n),Ai(a,i)};let c,h;if(o===a){const a=Ai([...t],i);if(a.length<3||Ti(a)<=i)return null;const r=[];for(let i=0;i=0?t:[...t].reverse();for(const e of i)r.push(e)}c=Ai(r,i),h=a}else c=Ai([...l(s,o,n,a),...[...r].reverse()],i),h=Ai([...l(n,a,s,o),...r],i);return c.length<3||h.length<3||Ti(c)<=i||Ti(h)<=i||Math.abs(Ti(c)+Ti(h)-Ti(e))>Math.max(i,1e-6*Ti(e))?null:[c,h]}function Fi(e,t,i){const[s,n]=e.split(":");return"device"===s?n:"entity"===s?"lg_"+n:t&&t.startsWith("v_")?t:i()}function Ei(e){return e.length?Math.round(e.reduce((e,t)=>e+t,0)/e.length):null}function Ni(e,t){if(t>e[2]/e[3]){const i=e[3],s=e[3]*t;return{x:e[0]-(s-e[2])/2,y:e[1],w:s,h:i}}const i=e[2],s=e[2]/t;return{x:e[0],y:e[1]-(s-e[3])/2,w:i,h:s}}function Oi(e,t,i,s){if(e.length<2)return;const n=t.x+s,o=t.x+t.w-s,a=t.y+s,r=t.y+t.h-s;for(let t=0;t<60;t++){let t=!1;for(let s=0;s=0)i=t.slice(0,n).trim(),s=t.slice(n+1).trim();else{const e=t.split(".");e.length>2&&(i=e.slice(0,2).join("."),s=e.slice(2).join("."))}return/^[a-z0-9_]+\.[a-z0-9_]+$/.test(i)?n>=0&&!s||s&&!/^[a-zA-Z0-9_.-]+$/.test(s)?null:s?{entity:i,attr:s}:{entity:i}:null}function Ji(e,t){const i=String(e??"").trim(),s=String(t??"").trim(),n=Yi(s?`${i}:${s}`:i);return n?`{${n.entity}${n.attr?`:${n.attr}`:""}}`:""}function Xi(e,t,i){const s=String(t??"").trim();if(!s)return null;const n=e?.states?.[s];if(!n)return null;const o=String(i??"").trim(),a=e=>e.slice(0,60);if(o){const t=function(e){if(null==e)return null;if(Array.isArray(e)){const t=e.map(e=>null==e?"":String(e)).join(", ");return t?t.slice(0,60):null}if("object"==typeof e)return null;const t=String(e);return""===t?null:t.slice(0,60)}(n.attributes?.[o]);if(null===t)return null;const i=e?.formatEntityAttributeValue;if("function"==typeof i)try{const t=i.call(e,n,o);if("string"==typeof t&&""!==t)return{text:a(t),formatted:!0}}catch{}return{text:t,formatted:!1}}const r=n.state;if(null==r||""===r)return null;const l=e?.formatEntityState;if("function"==typeof l)try{const t=l.call(e,n);if("string"==typeof t&&""!==t)return{text:a(t),formatted:!0}}catch{}return{text:a(String(r)),formatted:!1}}function Zi(e,t,i){const s=String(t??"").trim(),n=String(i??"").trim()||s;if(!n)return e.text;const o=e.formatted&&s?function(e,t){if(!t)return e;const i=e.replace(/\s+$/,"");return i.endsWith(t)?i.slice(0,i.length-t.length).replace(/\s+$/,""):e}(e.text,s):e.text;return`${o} ${n}`}function Qi(e,t){const i=(t?.entity||"").trim();if(!i)return"";const s=e?.states?.[i],n=s?.state;if(!s||null==n||""===n||"unavailable"===n||"unknown"===n)return Vi;const o=(t?.attr||"").trim(),a=Xi(e,i,o||null);if(null===a)return Vi;return Zi(a,o?"":String(s.attributes?.unit_of_measurement??"").trim(),t?.unit)}function es(e,t,i,s=()=>!0){const n=e??"";let o=!1;const a=n.replace(/\{([^{}\r\n]+)\}/g,(e,t)=>{const n=Yi(t);return n?(o=!0,s(n.entity||"")?Qi(i,n):Vi):e});if(o)return a;const r=(t?.entity||"").trim();if(!r)return n;if(!s(r)){const e=n.indexOf(Ki);return e>=0?n.slice(0,e)+Vi+n.slice(e+2):n?`${n} ${Vi}`:Vi}const l=Qi(i,t),c=n.indexOf(Ki);return c>=0?n.slice(0,c)+l+n.slice(c+2):n?`${n} ${l}`:l}const ts=20;function is(e){const t=Number(e?.scale);if(Number.isFinite(t)&&t>0)return Math.min(20,Math.max(.15,t));return{s:.7,m:1,l:1.5}[String(e?.size??"")]??1}function ss(e,t){if(!t)return e;let i=e;for(const[e,s]of Object.entries(t))i=i.split("{"+e+"}").join(String(s));return i}const ns="#55606c",os=.55,as={c:"#607d8b",a:.18};function rs(e,t=as){const i=e&&"object"==typeof e?e:null,s=i?.a;return{c:Ie(i?.c,t.c),a:"number"==typeof s&&Number.isFinite(s)?Math.min(1,Math.max(0,s)):t.a}}function ls(e,t){const i=rs(e),s=t?.settings?.custom_fill;return s&&"object"==typeof s?rs(s,i):i}function cs(e){const t=e?.settings||{},i=!e?.plan_url,s="glow"===t.fill_mode;return{showBorders:t.show_borders??i,showNames:t.show_names??i,color:Ie(t.room_color,ns),opacity:"number"==typeof t.room_opacity?Math.min(1,Math.max(0,t.room_opacity)):os,fill:["lqi","light","temp","custom"].includes(t.fill_mode)?t.fill_mode:"none",customFill:rs(t.custom_fill),glow:"boolean"==typeof t.glow_enabled?t.glow_enabled:s,tempMin:"number"==typeof t.temp_min?t.temp_min:20,tempMax:"number"==typeof t.temp_max?t.temp_max:25,showLqi:"boolean"==typeof t.show_lqi?t.show_lqi:null,cardFontScale:"number"==typeof t.card_font_scale&&t.card_font_scale>0?Math.min(3,Math.max(.5,t.card_font_scale)):1,labelTemp:!0===t.label_temp,labelHum:!0===t.label_hum,labelLqi:!0===t.label_lqi,labelLight:!0===t.label_light,bgColor:Ie(t.bg_color,null),hideDecor:!0===t.hide_decor,hideOpenings:!0===t.hide_openings}}function hs(e,t){if(t.bgColor)return t.bgColor;const i=e?.bg_color;return Ie(i,"")}const ds={light_on:{c:"#ffd45c",a:.18},light_off:{c:"#9aa0a6",a:.14},light_none:{c:"#6b7480",a:0},temp_cold:{c:"#4fc3f7",a:.18},temp_ok:{c:"#66d17a",a:.18},temp_hot:{c:"#ffd45c",a:.18},lqi_low:{c:"#f25a4a",a:.18},lqi_high:{c:"#4bd28f",a:.18},glow_base:{c:"#0d1b2a",a:.5},glow_light:{c:"#ffd9a0",a:.85},wall_fill:{c:"#ffffff",a:1}};function ps(e){const t={},i=e?.fill_colors||{};for(const e of Object.keys(ds)){const s=ds[e],n=i[e];t[e]={c:Ie(n?.c,s.c),a:n&&"number"==typeof n.a?Math.min(1,Math.max(0,n.a)):s.a}}return t}function us(e,t,i){const s=Math.min(1,Math.max(0,i)),n=[1,3,5].map(t=>parseInt(e.slice(t,t+2),16)),o=[1,3,5].map(e=>parseInt(t.slice(e,e+2),16)),a=n.map((e,t)=>Math.round(e+(o[t]-e)*s));return"#"+a.map(e=>e.toString(16).padStart(2,"0")).join("")}function _s(e,t,i,s,n,o,a,r=as){const l=function(e,t,i,s,n,o,a,r=as){if("custom"===e)return rs(r);if("lqi"===e){if(null==t)return null;const e=(t-40)/140;return{c:us(a.lqi_low.c,a.lqi_high.c,e),a:a.lqi_low.a+(a.lqi_high.a-a.lqi_low.a)*Math.min(1,Math.max(0,e))}}if("light"===e)return"none"===i?a.light_none.a>0?a.light_none:null:"on"===i?a.light_on:a.light_off;if("temp"===e){if(null==s)return null;const e=Math.min(n,o),t=Math.max(n,o);return st?a.temp_hot:a.temp_ok}return null}(e,t,i,s,n,o,a,r);return l?{color:l.c,opacity:l.a,mode:e}:null}const ms={blind:["mdi:blinds","mdi:blinds-open"],shade:["mdi:blinds","mdi:blinds-open"],shutter:["mdi:window-shutter","mdi:window-shutter-open"],curtain:["mdi:curtains-closed","mdi:curtains"],window:["mdi:window-closed","mdi:window-open"],awning:["mdi:awning-outline","mdi:awning"],door:["mdi:door-closed","mdi:door-open"],garage:["mdi:garage","mdi:garage-open"],gate:["mdi:gate","mdi:gate-open"],damper:["mdi:circle-slice-8","mdi:circle-outline"]},gs=[["mdi:roller-shade-closed","mdi:roller-shade"],["mdi:blinds-horizontal-closed","mdi:blinds-horizontal"],["mdi:garage-variant","mdi:garage-open-variant"],["mdi:door","mdi:door-open"]];function fs(e){for(const t of[...Object.values(ms),...gs])if(e===t[0]||e===t[1])return t;return null}function vs(e,t,i,s,n){if(!s||"unavailable"===s||"unknown"===s)return e;if(n){const i="cover"===t?fs(e):null;return i?"closed"===s?i[0]:i[1]:e}if("binary_sensor"===t){if("door"===i)return"on"===s?"mdi:door-open":"mdi:door-closed";if("window"===i)return"on"===s?"mdi:window-open":"mdi:window-closed";if("garage_door"===i)return"on"===s?"mdi:garage-open-variant":"mdi:garage-variant"}if("cover"===t){const t=ms[String(i||"")];if(t)return"closed"===s?t[0]:t[1];const n=fs(e);return n?"closed"===s?n[0]:n[1]:e}return"lock"===t?"locked"===s?"mdi:lock":"mdi:lock-open-variant":"light"===t&&"mdi:lightbulb"===e&&"on"===s?"mdi:lightbulb-on":e}function ys(e){const t=Math.min(4e4,Math.max(1e3,e))/100,i=t<=66?255:329.698727446*Math.pow(t-60,-.1332047592),s=t<=66?99.4708025861*Math.log(t)-161.1195681661:288.1221695283*Math.pow(t-60,-.0755148492),n=t>=66?255:t<=19?0:138.5177312231*Math.log(t-10)-305.0447927307,o=e=>Math.round(Math.min(255,Math.max(0,e)));return[o(i),o(s),o(n)]}const bs=1/2.2;function ws(e){const t=/^rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/.exec(e);return t?"#"+t.slice(1).map(e=>Math.min(255,Number(e)).toString(16).padStart(2,"0")).join(""):null}function ks(e){if(!e||"object"!=typeof e||Array.isArray(e))return null;const t=e;if(Object.keys(t).some(e=>"c"!==e&&"bri"!==e))return null;const i=Ie(t.c,null);return i?void 0===t.bri||null===t.bri?{c:i}:"number"!=typeof t.bri||!Number.isFinite(t.bri)||t.bri<.01||t.bri>1?null:{c:i,bri:t.bri}:null}function xs(e,t,i){const s=ks(t),n=e?.attributes||{},o=s?.bri??function(e){const t=e?.attributes?.brightness,i="number"==typeof t?t:"string"==typeof t&&""!==t.trim()?Number(t):Number.NaN;return Number.isFinite(i)?Math.max(0,Math.min(1,i/255)):1}(e);if(s)return{c:s.c,bri:o};const a=ze(n.rgb_color);if(a)return{c:ws(a)||Ie(i,"#ffd9a0"),bri:o};const r=Number(n.color_temp_kelvin)||(Number(n.color_temp)>0?1e6/Number(n.color_temp):NaN);return Number.isFinite(r)&&r>0?{c:(l=ys(r),"#"+l.slice(0,3).map(e=>Math.min(255,Math.max(0,Math.round(Number(e)||0))).toString(16).padStart(2,"0")).join("")),bri:o}:{c:Ie(i,"#ffd9a0"),bri:o};var l}function $s(e,t,i){return"on"===e?.state?xs(e,t,i):null}function Ss(e,t=1){const i=Math.max(0,Math.min(1,Number.isFinite(e)?e:1)),s=.7*Math.max(0,Math.min(1,Number.isFinite(t)?t:1))*(.4+.6*Math.pow(i,bs));return Math.max(0,Math.min(1,s))}function Ms(e){return e.startsWith("light.")||e.startsWith("switch.")}function Cs(e,t,i=1e-6){const s=[];if(!e||!t||e.length<3||t.length<3)return s;for(let n=0;np||l>p)continue;const u=(n[0]-o[0])*h+(n[1]-o[1])*d,_=(a[0]-o[0])*h+(a[1]-o[1])*d,m=Math.max(0,Math.min(u,_)),g=Math.min(c,Math.max(u,_));g-m>i&&s.push([o[0]+h*m,o[1]+d*m,o[0]+h*g,o[1]+d*g])}}return s}function Ds(e,t,i=1e-6){const s=[];for(const n of e){const e=[n[0],n[1]],o=[n[2],n[3]],a=o[0]-e[0],r=o[1]-e[1],l=Math.hypot(a,r);if(lo||n>o)continue;const a=(s[0]-e[0])*c+(s[1]-e[1])*h,r=(s[2]-e[0])*c+(s[3]-e[1])*h,p=Math.max(0,Math.min(a,r)),u=Math.min(l,Math.max(a,r));u-p>i&&d.push([p,u])}if(!d.length){s.push([e[0],e[1],o[0],o[1]]);continue}d.sort((e,t)=>e[0]-t[0]);let p=0;for(const[t,n]of d)t-p>i&&s.push([e[0]+c*p,e[1]+h*p,e[0]+c*t,e[1]+h*t]),p=Math.max(p,n);l-p>i&&s.push([e[0]+c*p,e[1]+h*p,o[0],o[1]])}return s}function Ps(e,t,i=1e-6){const s=[];for(let t=0;t{if("string"!=typeof e||!e)return;const i=As(e);i.startsWith("/api/houseplan/content/")&&t.add(i)};for(const t of e?.spaces||[]){i(t?.plan_url);for(const e of t?.markers||[])for(const t of e?.pdfs||[])i(t?.url)}for(const t of e?.markers||[])for(const e of t?.pdfs||[])i(e?.url);return t}function As(e){return e?e.startsWith("/houseplan_files/plans/")?"/api/houseplan/content/plans/_/"+e.slice(23):e.startsWith("/houseplan_files/files/")?"/api/houseplan/content/files/"+e.slice(23):e:""}function zs(e,t){const i=t?.settings?.fill_mode;return"none"===i||"lqi"===i||"light"===i||"temp"===i||"custom"===i?i:e}function Fs(e,t){const i=t?.settings;return"boolean"==typeof i?.glow?i.glow:"glow"===i?.fill_mode||e}function Es(e,t=1){const i=Number(e);return Number.isFinite(i)&&i>0?Math.min(3,Math.max(.5,i)):t}function Ns(e,t){let i=180*Math.atan2(t[1]-e[1],t[0]-e[0])/Math.PI;return i<0&&(i+=360),i}function Os(e,t=.5){const i=(e%45+45)%45;return i<=t||45-i<=t}function Hs(e,t){const i=t[2]-t[0],s=t[3]-t[1],n=i*i+s*s;if(!n)return Math.hypot(e[0]-t[0],e[1]-t[1]);let o=((e[0]-t[0])*i+(e[1]-t[1])*s)/n;return o=Math.max(0,Math.min(1,o)),Math.hypot(e[0]-(t[0]+o*i),e[1]-(t[1]+o*s))}const Ls=new Set(["smoke","gas","carbon_monoxide","moisture","safety","tamper","problem"]);function Bs(e,t){return"alarm_control_panel"===e||"siren"===e||"binary_sensor"===e&&!!t&&Ls.has(t)}function qs(e){if(!e)return null;const t=e.indexOf("#");if(t<=0)return null;const i=e.slice(0,t),s=e.slice(t+1);if(!s)return null;if(s.startsWith("@")){const e=s.slice(1);return e?{space:i,area:null,roomId:e}:null}return{space:i,area:s,roomId:null}}const Ws={availability:"available",status:"alarm",activity:"none"},js=new Set(["motion","vibration","sound"]),Us=new Set(["occupancy","presence"]),Gs=new Set(["door","window","garage_door","opening"]),Vs=new Set(["running","power"]),Ks=new Set(["smoke","gas","carbon_monoxide","moisture","safety","tamper","problem"]);const Ys=new Set(["running","working","washing","rinsing","spinning","drying","heating","cooling","cleaning","cooking","playing","recording","pumping","irrigating","humidifying","dehumidifying","fan","preheating","defrosting"]),Js=new Set([...Ys,"start","started","run","active","in_progress","wash","rinse","spin","dry"]),Xs=new Set(["off","idle","paused","standby","docked","finished","complete","completed","stopped","ready","sleeping","stop","end","done","inactive"]),Zs=new Set(["heat","cool","heat_cool","auto","dry","fan_only"]),Qs=e=>""===e||"unknown"===e||"unavailable"===e||"__missing__"===e,en=e=>String(e??"").trim().toLowerCase(),tn=e=>en(e).replace(/[\s-]+/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,""),sn=new Map([["run_state",0],["job_state",0],["operation_state",0],["activity_state",0],["machine_state",1],["running_state",1],["status",2],["device_status",2],["machine_status",2]]),nn=new Set(["wifi","connection","signal","battery"]);function on(e,t){const i=e?.entities?.[t]||{};if("config"===i.entity_category)return null;const s=String(t||"").split(".").slice(1).join("."),n=[i.translation_key,i.original_name,i.name],o=[...n,s];n.some(e=>en(e))||o.push(e?.states?.[t]?.attributes?.friendly_name);const a=o.map(tn).filter(Boolean);if(a.some(e=>e.split("_").some(e=>nn.has(e))))return null;let r=null;for(const e of a)for(const[t,i]of sn)(e===t||e.endsWith(`_${t}`))&&(r=null==r?i:Math.min(r,i));return r}const an=(e,t)=>null!=on(e,t);function rn(e,t){if(!t.startsWith("switch."))return!1;const i=e?.entities?.[t]||{},s=e?.states?.[t],n=t.slice(7).toLowerCase();if(/(?:^|_)(?:main_)?power$/.test(n))return!0;if([i.translation_key,i.original_name,i.name].map(en).some(e=>["power","main power","power switch","питание"].includes(e)))return!0;const o=en(s?.attributes?.friendly_name);return/(?:^|[\s._-])(?:main[\s._-]+)?power$/.test(o)||/(?:^|[\s._-])питание$/.test(o)}function ln(e){for(const t of["hvac_action","action","current_operation","run_state","job_state","operation","activity"]){const i=en(e?.[t]);if(Ys.has(i)||Xs.has(i))return i}return""}function cn(e,t){const i=e?.states?.[t],s=i?en(i.state):"__missing__",n=String(t||"").split(".")[0],o=en(i?.attributes?.device_class),a={eid:t,state:s,availability:Qs(s)?"unavailable":"available",status:"neutral",activity:"none",edge:"none"};if("unavailable"===a.availability)return a;if(function(e,t,i){return"alarm_control_panel"===e?"triggered"===i:"on"===i&&Bs(e,t)}(n,o,s))return{...a,status:"alarm"};if("binary_sensor"===n)return js.has(o)?{...a,edge:"rising"}:Us.has(o)?{...a,activity:"on"===s?"presence":"none"}:Gs.has(o)?{...a,status:"on"===s?"open":"neutral",edge:"rising"}:"moving"===o?{...a,activity:"on"===s?"transition":"none"}:Vs.has(o)&&"on"===s?{...a,status:"working",activity:"running"}:a;if("cover"===n)return{...a,activity:"opening"===s||"closing"===s?"transition":"none",edge:"terminal_transition"};if("lock"===n)return{...a,status:"unlocked"===s||"open"===s?"open":"neutral",activity:"locking"===s||"unlocking"===s?"transition":"none",edge:"terminal_transition"};if("valve"===n)return{...a,status:["open","opening","closing"].includes(s)?"open":"neutral",activity:"opening"===s||"closing"===s?"transition":"none",edge:"terminal_transition"};if("climate"===n){const e=ln(i.attributes),t=Array.isArray(i.attributes?.hvac_modes)?i.attributes.hvac_modes.map(en):[],n=!Xs.has(s)&&(Zs.has(s)||Ys.has(s)||t.includes(s));return(e?Ys.has(e):n)?{...a,status:"working",activity:"running"}:a}if(["light","switch","fan","humidifier"].includes(n))return"on"===s?{...a,status:"working",activity:"running"}:a;if("media_player"===n)return"off"===s?{...a,availability:"unavailable"}:a;if("vacuum"===n)return"cleaning"===s?{...a,status:"working",activity:"running"}:"returning"===s?{...a,status:"working",activity:"transition"}:a;if("script"===n)return"on"===s?{...a,status:"working",activity:"running"}:a;if("automation"===n)return a;if("button"===n||"event"===n)return{...a,edge:"change"};const r=ln(i.attributes);return Ys.has(r)||Ys.has(s)&&!Xs.has(s)?{...a,status:"working",activity:"running"}:a}function hn(e,t,i){const s=i.filter(t=>t.startsWith("switch.")&&!e?.entities?.[t]?.entity_category),n=t.find(t=>rn(e,t));if(!(s.length>1&&!!n))return t.map(t=>cn(e,t));const o=t.find(t=>t!==n&&an(e,t)),a=cn(e,n);return"unavailable"===a.availability||"off"===a.state?t.map(t=>({eid:t,state:e?.states?.[t]?en(e.states[t].state):"__missing__",availability:"unavailable",status:"neutral",activity:"none",edge:"none"})):t.map(t=>{if(t===o)return function(e,t){const i=e?.states?.[t],s=i?en(i.state):"__missing__",n={eid:t,state:s,availability:Qs(s)?"unavailable":"available",status:"neutral",activity:"none",edge:"none"};if("unavailable"===n.availability)return n;const o=ln(i?.attributes);return Ys.has(o)||Js.has(s)&&!Xs.has(s)?{...n,status:"working",activity:"running"}:n}(e,t);return{...t===n?a:cn(e,t),status:"neutral",activity:"none",edge:"none"}})}function dn(e){if(!e.length)return{availability:"available",status:"neutral",activity:"none"};const t=e.filter(e=>"available"===e.availability);if(!t.length)return{availability:"unavailable",status:"neutral",activity:"none"};if(t.some(e=>"alarm"===e.status))return Ws;const i=t.some(e=>"working"===e.status)?"working":t.some(e=>"open"===e.status)?"open":"neutral",s=t.some(e=>"transition"===e.activity)?"transition":t.some(e=>"presence"===e.activity)?"presence":t.some(e=>"running"===e.activity)?"running":"none";return{availability:"available",status:i,activity:s}}function pn(e,t){if(!(e=>!!e&&!Qs(e))(e)||"unavailable"===t.availability||e===t.state)return null;if("rising"===t.edge)return"off"===e&&"on"===t.state?"event":null;if("change"===t.edge)return"event";if("terminal_transition"===t.edge){const i=new Set([e,t.state]);if(i.has("closed")&&i.has("open")||i.has("locked")&&i.has("unlocked"))return"transition"}return null}const un=(e,t=0)=>{const i=Number(e);return Number.isInteger(i)&&i>=0?i:t},_n=(e,t)=>{const i={rev:0,configRev:un(t),off:new Set};if(null==e)return{snapshot:i,valid:!1};const s=e.off;return!Number.isInteger(e.rev)||Number(e.rev)<0||!Number.isInteger(e.config_rev)||Number(e.config_rev)<0||!Array.isArray(s)||s.some(e=>"string"!=typeof e||!e)?{snapshot:i,valid:!1}:{snapshot:{rev:Number(e.rev),configRev:Number(e.config_rev),off:new Set(s)},valid:!0}};function mn(e,t=0){return _n(e,t).snapshot}function gn(e,t,i,s){const n=_n(t,i);return s&&n.valid&&n.snapshot.configRev===i?e.configRev===i&&n.snapshot.rev{try{const[i,s]=await Promise.all([e.callWS({type:"config/device_registry/list"}),e.callWS({type:"config/entity_registry/list"})]),n=Dn(i,"id"),o=Dn(s,"entity_id");if(!n||!o)throw new Error("invalid_registry_response");t.devices=n,t.entities=o,t.authoritative=!0,t.access="full",t.lastSuccess=Date.now(),t.error=void 0}catch(e){t.authoritative=!1,t.access="limited",t.error=function(e){if(e&&"object"==typeof e){const t=e;return String(t.message||t.code||t.error||"registry_unavailable")}return String(e||"registry_unavailable")}(e)}finally{t.revision++,t.loading=void 0,function(e){for(const t of[...e.listeners])try{t()}catch{}}(t)}})()),t.loading}function Tn(e,t){void 0===t.reloadTimer&&(t.reloadTimer=globalThis.setTimeout(()=>{t.reloadTimer=void 0,Pn(e,t)},80))}async function In(e,t){if(t.subscribing||t.unsubDevice&&t.unsubEntity)return t.subscribing;const i=e?.connection?.subscribeEvents;return"function"==typeof i?(t.subscribing=(async()=>{try{t.unsubDevice||(t.unsubDevice=await i.call(e.connection,()=>Tn(e,t),"device_registry_updated")),t.unsubEntity||(t.unsubEntity=await i.call(e.connection,()=>Tn(e,t),"entity_registry_updated"))}catch{}finally{0===t.refs&&(t.unsubDevice?.(),t.unsubEntity?.(),t.unsubDevice=void 0,t.unsubEntity=void 0),t.subscribing=void 0}})(),t.subscribing):void 0}function Rn(e,t){const i=Cn(e);if(!i)return()=>{};const s=0===i.refs;i.refs++,i.listeners.add(t),("pending"===i.access||s)&&Pn(e,i),In(e,i);let n=!1;return()=>{n||(n=!0,i.listeners.delete(t),i.refs=Math.max(0,i.refs-1),i.refs>0||(i.unsubDevice?.(),i.unsubEntity?.(),i.unsubDevice=void 0,i.unsubEntity=void 0,void 0!==i.reloadTimer&&globalThis.clearTimeout(i.reloadTimer),i.reloadTimer=void 0))}}function An(e){const t=Cn(e);if(!t)return{revision:0,authoritative:!1,access:"limited",devices:e?.devices||{},entities:e?.entities||{},lastSuccess:0,error:"registry_unavailable"};let i=e?.devices||{},s=e?.entities||{};if(t.authoritative){const n=t.liveDevices!==i||t.liveEntities!==s,o=void 0!==t.liveDevices||void 0!==t.liveEntities;if(n&&(t.liveDevices=i,t.liveEntities=s,t.projectedRevision=void 0,o&&Tn(e,t)),t.projectedRevision!==t.revision||!t.projectedDevices||!t.projectedEntities){const e={...t.devices},n={...t.entities};for(const[t,s]of Object.entries(i))Object.prototype.hasOwnProperty.call(e,t)||(e[t]=s);for(const[e,t]of Object.entries(s))Object.prototype.hasOwnProperty.call(n,e)||(n[e]=t);t.projectedDevices=e,t.projectedEntities=n,t.projectedRevision=t.revision}i=t.projectedDevices,s=t.projectedEntities}return{revision:t.revision,authoritative:t.authoritative,access:t.access,devices:i,entities:s,lastSuccess:t.lastSuccess,error:t.error}}function zn(e){if(!e||"object"!=typeof e&&"function"!=typeof e)return 0;let t=xn.get(e);return t||(t=$n++,xn.set(e,t)),t}function Fn(e,t=An(e)){return[t.revision,t.access,zn(t.devices),zn(t.entities)].join(":")}function En(e){return!!e&&null==e.disabled_by}function Nn(e,t=An(e)){const i={},s={},n={};for(const[e,s]of Object.entries(t.devices||{}))En(s)&&(i[e]=s);for(const[e,i]of Object.entries(t.entities||{})){if(!En(i))continue;const n=i.device_id?t.devices?.[i.device_id]:null;t.authoritative&&i.device_id&&!n||(n&&!En(n)||(s[e]=i))}for(const[i,s]of Object.entries(e?.states||{})){const e=t.entities?.[i];if(e&&!En(e))continue;const o=e?.device_id?t.devices?.[e.device_id]:null;t.authoritative&&e?.device_id&&!o||(o&&!En(o)||(n[i]=s))}return{...e,devices:i,entities:s,states:n}}function On(e,t=An(e)){return{...e,devices:t.devices||{},entities:t.entities||{}}}function Hn(e,t){const i=[];for(const[s,n]of Object.entries(e||{}))n?.device_id===t&&i.push(s);return i}function Ln(){if(Mn)return Mn;if("undefined"==typeof localStorage)return{};try{const e=JSON.parse(localStorage.getItem(Sn)||"{}");if(!e||"object"!=typeof e||Array.isArray(e))return{};const t=Date.now(),i={};for(const[s,n]of Object.entries(e))!n||"active"!==n.kind&&"ha_disabled"!==n.kind||!Number.isFinite(n.ts)||t-n.ts>7776e6||(i[s]=n);return Mn=i,Mn}catch{return{}}}function Bn(e,t,i=An(e)){if(!t||"virtual"===t)return{kind:"active",enabledEntityIds:[],allEntityIds:[]};const s=t.indexOf(":");if(s<1)return{kind:"unverified",reason:"registry_unavailable",enabledEntityIds:[],allEntityIds:[]};const n=t.slice(0,s),o=t.slice(s+1);if("device"!==n&&"entity"!==n||!o)return{kind:"unverified",reason:"registry_unavailable",enabledEntityIds:[],allEntityIds:[]};const a=i.devices||{},r=i.entities||{};if(i.authoritative){if("device"===n){const e=a[o];if(!e)return{kind:"orphaned",reason:"device_missing",enabledEntityIds:[],allEntityIds:[]};const t=Hn(r,o);if(!En(e))return{kind:"ha_disabled",reason:"device",enabledEntityIds:[],allEntityIds:t};const i=t.filter(e=>En(r[e]));return t.length&&!i.length?{kind:"ha_disabled",reason:"all_entities",enabledEntityIds:[],allEntityIds:t}:{kind:"active",enabledEntityIds:i,allEntityIds:t}}const t=r[o];return t&&!En(t)?{kind:"ha_disabled",reason:"entity",enabledEntityIds:[],allEntityIds:[o]}:t?.device_id&&!a[t.device_id]?{kind:"orphaned",reason:"device_missing",enabledEntityIds:[],allEntityIds:[o]}:t?.device_id&&!En(a[t.device_id])?{kind:"ha_disabled",reason:"device",enabledEntityIds:[],allEntityIds:[o]}:t||e?.states?.[o]?{kind:"active",enabledEntityIds:[o],allEntityIds:[o]}:{kind:"orphaned",reason:"entity_missing",enabledEntityIds:[],allEntityIds:[]}}const l=function(e){return Ln()[e]||null}(t);if("device"===n){const t=a[o],i=Hn(r,o);if(null!=t?.disabled_by)return{kind:"ha_disabled",reason:"device",enabledEntityIds:[],allEntityIds:i};const s=i.filter(e=>{const t=r[e];return null==t?.disabled_by&&(!t.device_id||null==a[t.device_id]?.disabled_by)});if(i.length&&!s.length&&i.every(e=>null!=r[e]?.disabled_by))return{kind:"ha_disabled",reason:"all_entities",enabledEntityIds:[],allEntityIds:i};if("ha_disabled"===l?.kind)return{kind:"ha_disabled",reason:l.reason||"device",enabledEntityIds:[],allEntityIds:i};if(t||s.some(t=>!!e?.states?.[t]))return{kind:"active",enabledEntityIds:s,allEntityIds:i}}else{const t=r[o];if(null!=t?.disabled_by)return{kind:"ha_disabled",reason:"entity",enabledEntityIds:[],allEntityIds:[o]};if(t?.device_id&&null!=a[t.device_id]?.disabled_by)return{kind:"ha_disabled",reason:"device",enabledEntityIds:[],allEntityIds:[o]};if("ha_disabled"===l?.kind)return{kind:"ha_disabled",reason:l.reason||"entity",enabledEntityIds:[],allEntityIds:[o]};if(t||e?.states?.[o])return{kind:"active",enabledEntityIds:[o],allEntityIds:[o]}}return{kind:"unverified",reason:"registry_unavailable",enabledEntityIds:[],allEntityIds:[]}}function qn(e){const t={};for(const[i,s]of Object.entries(e.entities)){if(!s?.device_id||!En(s))continue;const n=e.devices?.[s.device_id];n&&!En(n)||(t[s.device_id]=t[s.device_id]||[]).push(i)}return t}function Wn(e,t){const i=new Map;for(const s of e){if(!0===s?.removed)continue;const e=s?.binding||"";if(!e.startsWith("entity:"))continue;const n=e.slice(7);if(!n)continue;const o=t?.entities?.[n]?.device_id;if(!o)continue;const a=i.get(o)||new Set;a.add(n),i.set(o,a)}return{byDevice:i}}function jn(e,t,i,s){const n=s.byDevice.get(t);return n?.size?{partial:!0,entityIds:i.filter(t=>!n.has(t)&&!e?.entities?.[t]?.hidden)}:{partial:!1,entityIds:[...i]}}function Un(e,t,i){if(t.identifiers?.[0]?.[0])return t.identifiers[0][0];for(const t of i){const i=e.entities[t]?.platform;if(i)return i}return""}function Gn(e,t){if(/_device_temperature$/.test(t))return!1;if(e.entities?.[t]?.entity_category)return!1;const i=e.states[t];if(!i)return/_temperature$/.test(t);const s=i.attributes||{};return"temperature"===s.device_class||/°C|°F/.test(s.unit_of_measurement||"")||/_temperature$/.test(t)}const Vn=["vacuum","lawn_mower","climate","media_player","light","cover","lock","valve","alarm_control_panel","water_heater","fan","humidifier","siren","camera","remote"],Kn=e=>[...e.filter(e=>!e.reg?.hidden),...e.filter(e=>!!e.reg?.hidden)];function Yn(e,t){const i=t.map(t=>({eid:t,reg:e?.entities?.[t]})).filter(e=>!!e.reg);if(!i.length)return[];const s=i.filter(e=>!e.reg.entity_category),n=s.length?s:i;for(const e of Vn){const t=n.filter(t=>t.eid.startsWith(e+"."));if(t.length)return Kn(t).map(e=>e.eid)}const o=n.filter(t=>function(e,t){if(!t.startsWith("binary_sensor."))return!1;const i=en(e?.states?.[t]?.attributes?.device_class||e?.entities?.[t]?.device_class||e?.entities?.[t]?.original_device_class);return js.has(i)||Us.has(i)||Gs.has(i)||Vs.has(i)||"moving"===i||Ks.has(i)}(e,t.eid));if(o.length)return Kn(o).map(e=>e.eid);const a=n.filter(e=>e.eid.startsWith("switch."));if(a.length){const t=Kn(a),s=t.find(t=>rn(e,t.eid));if(a.length>1&&s){const t=i.filter(t=>t.eid!==s.eid&&"config"!==t.reg?.entity_category&&null!=on(e,t.eid)),n=t.filter(e=>!e.reg?.entity_category),o=n.length?n:t;for(const t of[0,1,2]){const i=Kn(o.filter(i=>on(e,i.eid)===t));if(i.length)return[i[0].eid,s.eid]}}return[(s||t[0]).eid]}const r=[];for(const e of it)r.push(...Kn(n.filter(t=>t.eid.startsWith(e+"."))));return r.push(...Kn(n.filter(e=>!it.includes(e.eid.split(".")[0])))),r.map(e=>e.eid)}function Jn(e,t,i){const s=t.map(t=>({eid:t,reg:e.entities[t],st:e.states[t]})).filter(e=>e.reg),n=[s.filter(e=>!e.reg.hidden&&!e.reg.entity_category),s.filter(e=>!e.reg.entity_category),s.filter(e=>!e.reg.hidden),s];if("mdi:thermometer"===i||"mdi:air-filter"===i)for(const t of n){const i=t.find(t=>Gn(e,t.eid));if(i)return i.eid}const o=Yn(e,t);return o.find(Ms)||o[0]}function Xn(e,t,i=[]){return[...new Set(Zn(e,t,i))].filter(e=>Ms(e))}function Zn(e,t,i=[]){const s=e?.startsWith("entity:")?new Set([e.slice(7)]):new Set(i);return(t||[]).filter(e=>"string"==typeof e&&!s.has(e))}function Qn(e,t){if("string"==typeof t)return e.area===t;const i=e.marker?.room_id;return i?!!t.id&&i===t.id:!!t.area&&e.area===t.area}function eo(e){const t=e.marker?.binding?.startsWith("entity:")?e.marker.binding.slice(7):null,i=e.entities.filter(Ms),s=e.primary&&Ms(e.primary)?e.primary:null;return[...new Set([t,s,...i].filter(e=>!!e&&Ms(e)))]}function to(e){const t=eo(e),i=e.marker?.light_entity;return i&&t.includes(i)?i:t[0]||null}function io(e,t){if(!1===t.marker?.is_light)return[];if(!0===t.marker?.is_light){return[{eid:to(t),via:"forced"}]}const i=t.primary||Yn(e,t.entities)[0];return i&&!i.startsWith("light.")?[]:t.entities.filter(t=>t.startsWith("light.")&&!!e.states?.[t]).map(e=>({eid:e,via:"light"}))}const so=new WeakMap,no=new WeakMap;function oo(e){return e.map(e=>[e.id||"",!0===e.hidden?1:0,e.primary||"",[...e.entities].join(","),void 0===e.controls?"":[...e.controls].join(","),e.marker?.id||"",e.marker?.binding||"",e.marker?.is_light,e.marker?.tap_action||"",!0===e.marker?.removed?1:0,e.marker?.light_entity||"",null==e.marker?.controls?"":[...e.marker.controls].join(",")].join("")).join("")}function ao(e){const t=oo(e),i=so.get(e);if(i?.fingerprint===t)return i;const s=e.filter(e=>!e.hidden),n=new Map,o=new Map;for(const t of e){o.set(t,Zn(t.marker?.binding,t.marker?.controls??t.controls,t.entities));const e=t.hidden||!0!==t.marker?.is_light?null:t.marker?.id||t.id;e&&n.set(String(e),t)}const a=new Map;for(const t of e){const e=o.get(t)||[],i=new Set(void 0===t.controls?e.filter(Ms):t.controls.filter(Ms)),s=to(t),r=i.size?[...i]:s?[s]:[];for(const i of e){if(!i.startsWith("marker:"))continue;const e=i.slice(7);if(!e||e===String(t.marker?.id||t.id||""))continue;if(!n.has(e))continue;const s=a.get(e)||{markerId:e,controllers:[],driverEids:[]};s.controllers.push({device:t,driverEids:[...r]}),s.driverEids=[...new Set([...s.driverEids,...r])],a.set(e,s)}}const r={fingerprint:t,visible:s,markerById:n,persistedByDevice:o,incomingByMarker:a};return so.set(e,r),r}function ro(e){return ao(e).incomingByMarker}function lo(e,t){const i=Xn(t.marker?.binding,t.controls??t.marker?.controls,t.entities),s=Zn(t.marker?.binding,t.marker?.controls??t.controls,t.entities);return(null!=t.marker?.is_light||!i.length&&!s.some(e=>e.startsWith("marker:")))&&io(e,t).length>0}function co(e,t){const i=Xn(t.marker?.binding,t.controls??t.marker?.controls,t.entities).map(e=>({eid:e,via:"controls"})),s=lo(e,t)?io(e,t):[];for(const e of s)e.eid&&i.some(t=>t.eid===e.eid)||i.push(e);return i}function ho(e,t,i,s){if(null!=i)return ho(e,t,null,s).filter(e=>Qn(e.device,i));const n=oo(t),o=function(e,t){const i=new Set;for(const e of t){for(const t of e.entities)i.add(t);for(const t of e.controls||e.marker?.controls||[])"string"!=typeof t||t.startsWith("marker:")||i.add(t)}return[...i].sort().map(t=>`${t}:${e?.states?.[t]?.state??""}`).join("|")}(e,t),a=vn(s),r=no.get(t);if(r?.graphFingerprint===n&&r.stateFingerprint===o&&r.virtualLightFingerprint===a&&r.registry===e?.entities)return r.sources;const{visible:l,markerById:c,persistedByDevice:h,incomingByMarker:d}=ao(t),p=null==i?l:l.filter(e=>Qn(e,i)),u=new Map,_=new Map;for(const t of p){const i=co(e,t).filter(e=>"controls"!==e.via);for(const s of i){const i=!0===t.marker?.is_light?String(t.marker?.id||t.id||""):"",n=i?`marker:${i}`:`entity:${s.eid}`,o=s.eid?[s.eid]:[],a={key:n,eid:s.eid||"",stateEids:o,serviceEids:o,device:t,via:s.via,castsGlow:!0,passive:!s.eid,on:!s.eid||"on"===e.states?.[s.eid]?.state};u.set(t,[...u.get(t)||[],a]),s.eid&&_.set(s.eid,a)}}const m=new Map;for(const e of t){const t=h.get(e)||[],i=new Set(void 0===e.controls?t.filter(Ms):e.controls);m.set(e,i)}for(const t of u.values())for(const i of t){if(!i.passive)continue;const t=i.key.slice(7),n=d.get(t);i.on=!n||n.driverEids.some(t=>"on"===e.states?.[t]?.state),!n&&yn(i.device.marker)&&(i.on=bn(i.device.marker,s))}const g=new Map,f=e=>{const t=g.get(e.key);(!t||e.castsGlow&&!t.castsGlow)&&g.set(e.key,e)};for(const t of l){const s=h.get(t)||[],n=null==i||Qn(t,i);for(const i of s){if(i.startsWith("marker:")){const e=c.get(i.slice(7)),t=e?u.get(e):null;if(t)for(const e of t)f(e);continue}if(!Ms(i)||!m.get(t)?.has(i))continue;const s=_.get(i);s?f(s):n&&f({key:`entity:${i}`,eid:i,stateEids:[i],serviceEids:[i],device:t,via:"controls",castsGlow:!1,passive:!1,on:"on"===e.states?.[i]?.state})}for(const e of u.get(t)||[])f(e)}const v=[...g.values()];return no.set(t,{graphFingerprint:n,stateFingerprint:o,virtualLightFingerprint:a,registry:e?.entities,sources:v}),v}function po(e){const t=e.filter(e=>e.castsGlow);return t.find(e=>e.on)||t[0]||null}function uo(e){return e.length?e.some(e=>e.on)?"on":"off":"none"}function _o(e,t){const i=[];for(const s of t){const t=e.states[s];if(!t)continue;const n=(t.attributes?.unit_of_measurement||"").toLowerCase();if(/_(linkquality|lqi)$/.test(s)||"lqi"===n){const e=parseFloat(t.state);isNaN(e)||i.push(e);continue}const o=t.attributes?.linkquality??t.attributes?.lqi;if(null!=o){const e=parseFloat(o);isNaN(e)||i.push(e)}}return Ei(i)}function mo(e,t){for(const i of t){if(!Gn(e,i))continue;const t=e.states[i];if(!t)continue;const s=parseFloat(t.state);if(!isNaN(s))return Math.round(10*s)/10}return null}function go(e,t){for(const i of t){if(!i.startsWith("climate."))continue;const t=e.states[i];if(!t||"unavailable"===t.state||"unknown"===t.state)continue;const s=parseFloat(t.attributes?.current_temperature);if(Number.isFinite(s))return Math.round(10*s)/10}return null}function fo(e,t){if(e.entities?.[t]?.entity_category)return!1;const i=e.states[t];if(!i)return/_humidity$/.test(t);const s=i.attributes||{};return"humidity"===s.device_class||"%"===s.unit_of_measurement&&/_humidity$/.test(t)||/_humidity$/.test(t)}function vo(e,t){for(const i of t){if(!fo(e,i))continue;const t=e.states[i];if(!t)continue;const s=parseFloat(t.state);if(!isNaN(s))return Math.round(s)}return null}function yo(e,t){if(!t)return[];const i=[];for(const[t,s]of Object.entries(e.entities)){if(!t.startsWith("light.")||s.hidden||!En(s))continue;let n=null;if("group"===s.platform)n=s.area_id||null;else{if(!s.device_id)continue;{const t=e.devices[s.device_id];if(!En(t))continue;if("Group"!==t?.model)continue;n=t.area_id||s.area_id||null}}if(!n)continue;const o=e.states[t];i.push({eid:t,name:s.name||o?.attributes?.friendly_name||t,area:n})}return i}function bo(e,t,i,s,n){const o=tt(t,i,n);if(o!==et)return o;const a=[];for(const t of s){const i=e.states[t]?.attributes?.device_class;i&&a.push(i)}return function(e){for(const t of e){const e=Qe[t];if(e)return e}return null}(a)??et}function wo(e){const t=new Set,i=new Set,s=new Set;for(const n of e||[]){const e=String(n.binding||"").indexOf(":");if(e<1)continue;const o=n.binding.slice(0,e),a=n.binding.slice(e+1);a&&(!0===n?.removed?"device"===o?t.add(a):"entity"===o&&i.add(a):"entity"===o&&s.add(a))}return{devices:t,entities:i,liveEntities:s}}function ko(e,t,i){if(i.liveEntities.has(t))return!1;if(i.entities.has(t))return!0;const s=e?.entities?.[t]?.device_id;return!!s&&i.devices.has(s)}function xo(e,t,i,s,n){const o=Xn(t.binding,t.controls,e.entities).filter(e=>!ko(i,e,s)).filter(e=>"active"===Bn(i,"entity:"+e,n).kind);e.marker=t,e.controls=o,e.userHidden=!0===t.hidden,e.hidden=e.userHidden||"ha_disabled"===e.bindingStatus?.kind,t.name&&(e.name=t.name),t.icon&&(e.icon=t.icon),null!=t.model&&(e.model=t.model),e.link=t.link??null,e.description=t.description??null,e.pdfs=t.pdfs||[],e.tapAction=t.tap_action??null}function $o(e,t,i,s){if("string"==typeof e.room_id&&e.room_id.length>0&&null===e.area)return{area:"",space:e.space||s};const n=e.area||t||"";return{area:n,space:n&&i[n]||e.space||s}}function So(e){const t=e.hass,i=e.registry||An(t),s=Nn(t,i),n=On(t,i),{areaToSpace:o,markers:a,settings:r,excluded:l,showAll:c,firstSpaceId:h,loc:d,iconRules:p}=e,u=!1!==r.group_lights,_=wo(a),m=yo(s,u).filter(e=>!ko(s,e.eid,_)),g=new Set(m.map(e=>e.area)),f=qn(s),v=function(e){const t={};for(const[i,s]of Object.entries(e.entities||{}))s?.device_id&&(t[s.device_id]=t[s.device_id]||[]).push(i);return t}(n),y=Wn(a,n),b=new Set;for(const e of a){const[t,i]=e.binding.split(":");"device"!==t&&"entity"!==t||!i||b.add(e.binding)}const w=(e,t)=>a.find(i=>i.binding===e+":"+t),k={},x=[];for(const e of Object.values(s.devices)){const n=e.area_id;if(!n||!o[n])continue;if("service"===e.entry_type)continue;if(b.has("device:"+e.id))continue;const a=Bn(t,"device:"+e.id,i);if("active"!==a.kind)continue;const h=w("device",e.id);if(h&&h.hidden&&!r.filter_seeded)continue;const _=jn(s,e.id,f[e.id]||[],y);if(_.partial&&!_.entityIds.length)continue;const m=_.entityIds,v=_.partial?{kind:"active",enabledEntityIds:m,allEntityIds:m}:a,$=Un(s,e,m),S=!r.filter_seeded;if(S&&!c){if(l.has($))continue;if("Group"===e.model)continue;if(/scene/i.test(e.model||""))continue;if(/bridge/i.test((e.model||"")+(e.name||"")))continue;if("myheat"===$&&e.via_device_id)continue}const M=(e.name_by_user||e.name||d("device.unnamed")).trim(),C=M+"|"+n;let D=bo(s,M,e.model,m,p);if(m.some(e=>e.startsWith("lock."))&&(D="mdi:lock"),S&&!c&&u&&"mdi:lightbulb"===D&&g.has(n))continue;k[C]=(k[C]||0)+1;const P=k[C]>1?M+" "+k[C]:M,T={id:e.id,name:P,model:e.model||"",area:n,space:o[n],icon:D,entities:m,allEntities:v.allEntityIds,bindingStatus:v,bindingKind:"device",bindingRef:e.id,pdfs:[]};T.primary=Jn(s,m,D),"mdi:thermometer"!==D&&"mdi:air-filter"!==D||(T.temp=mo(s,m)),T.primary&&fo(s,T.primary)&&(T.hum=vo(s,m)),x.push(T)}for(const e of m)o[e.area]&&(b.has("entity:"+e.eid)||x.push({id:"lg_"+e.eid,name:e.name,model:d("device.light_group"),area:e.area,space:o[e.area],icon:"mdi:lightbulb-group",entities:[e.eid],allEntities:[e.eid],bindingStatus:{kind:"active",enabledEntityIds:[e.eid],allEntityIds:[e.eid]},primary:e.eid,bindingKind:"entity",bindingRef:e.eid,pdfs:[]}));for(const e of a){if(e.removed)continue;const[a,l]=e.binding.split(":"),c="device"===a||"entity"===a?Bn(t,e.binding,i):null;if(!e.hidden||r.filter_seeded||"ha_disabled"===c?.kind)if("device"===a){const t=c;if("unverified"===t.kind)continue;const a=n.devices[l],{area:r,space:u}=$o(e,a?.area_id,o,h),m="active"===t.kind?t.enabledEntityIds:[];let g=a?bo(s,a.name_by_user||a.name||"",a.model,m,p):"mdi:help-circle";m.some(e=>e.startsWith("lock."))&&(g="mdi:lock");const f={id:e.id,name:a?.name_by_user||a?.name||d("device.fallback"),model:a?.model||"",area:r,space:u,icon:g,entities:m,allEntities:t.allEntityIds.length?t.allEntityIds:a&&v[a.id]||[],bindingStatus:t,bindingKind:"device",bindingRef:l};f.primary=Jn(s,m,g),"mdi:thermometer"!==g&&"mdi:air-filter"!==g||(f.temp=mo(s,m)),f.primary&&fo(s,f.primary)&&(f.hum=vo(s,m)),xo(f,e,n,_,i),x.push(f)}else if("entity"===a){if(ko(n,l,_))continue;const t=c;if("unverified"===t.kind)continue;const a=n.entities[l],r=a?.area_id||a?.device_id&&n.devices[a.device_id]?.area_id||"",{area:d,space:u}=$o(e,r,o,h),m=s.states[l],g=a?.name||m?.attributes?.friendly_name||l;let f=bo(s,g,"",[l],p);l.startsWith("lock.")&&(f="mdi:lock");const v={id:e.id,name:g,model:"",area:d,space:u,icon:f,entities:"active"===t.kind?[l]:[],allEntities:[l],bindingStatus:t,primary:"active"===t.kind?l:void 0,bindingKind:"entity",bindingRef:l};"mdi:thermometer"!==f&&"mdi:air-filter"!==f||!v.entities.length||(v.temp=mo(s,v.entities)),v.entities.length&&fo(s,l)&&(v.hum=vo(s,v.entities)),xo(v,e,n,_,i),x.push(v)}else{const t=e.area||"",s=e.space||t&&o[t]||h,a={id:e.id,name:e.name||d("device.virtual"),model:e.model||"",area:t,space:s,icon:e.icon||"mdi:map-marker",entities:[],allEntities:[],bindingStatus:{kind:"active",enabledEntityIds:[],allEntityIds:[]},bindingKind:"virtual",virtual:!0};xo(a,e,n,_,i),x.push(a)}}return x}function Mo(e,t,i,s){if(!t)return null;if(function(e,t,i){if(!t)return!1;const s=t.indexOf(":");if(s<1)return!1;const n=t.slice(0,s),o=t.slice(s+1),a=wo(i);return"device"===n?a.devices.has(o):"entity"===n&&ko(e,o,a)}(e,t,s))return null;const n=t.indexOf(":");if(n<0)return null;const o=t.slice(0,n),a=t.slice(n+1);if(!a)return null;if("entity"===o){const t=parseFloat(e.states[a]?.state);return Number.isFinite(t)?"temp"===i?Math.round(10*t)/10:Math.round(t):null}if("device"===o){const t=Object.entries(e.entities).filter(([,e])=>e.device_id===a).map(([e])=>e);return"temp"===i?mo(e,t):vo(e,t)}return null}const Co=new RegExp(["water","voda","coolant","flow_?temp","return_?temp","target","setpoint","chip","cpu","processor","board","core_temp","device_temp","batter","akkum","freezer","fridge","oven","kettle","boiler"].join("|"),"i");function Do(e,t,i){const s=[];for(const n of t){if(n.area!==i||n.virtual)continue;const t=_o(e,n.entities);null!=t&&s.push(t)}return Ei(s)}function Po(e,t,i){const s=[];for(const n of t){if(n.area!==i)continue;if("mdi:thermometer"!==n.icon&&"mdi:air-filter"!==n.icon)continue;const t=mo(e,n.entities);null!=t&&s.push(t)}return s.length?Math.round(s.reduce((e,t)=>e+t,0)/s.length*10)/10:null}const To={climate:["current_temperature","temperature","current_humidity","humidity"],water_heater:["current_temperature","temperature"],cover:["current_position"],valve:["current_position"],fan:["percentage"],humidifier:["current_humidity","humidity"],light:["brightness"],media_player:["volume_level"],vacuum:["battery_level","fan_speed"],lawn_mower:["battery_level","fan_speed"]};function Io(e){return e?e.sourceLabel?`${e.sourceLabel}: ${e.fullText}`:e.fullText:""}const Ro=new WeakMap;function Ao(e){return e?"entity_state"===e.kind?`state:${e.entity_id}`:"entity_attribute"===e.kind?`attr:${e.entity_id}:${e.attribute}`:"derived_marker_state"===e.kind?`marker:${e.ref}`:"derived:lqi":""}function zo(e){if("derived:lqi"===e)return{kind:"derived_lqi"};if(e.startsWith("state:"))return{kind:"entity_state",entity_id:e.slice(6)};if(e.startsWith("attr:")){const t=e.slice(5),i=t.lastIndexOf(":");if(i>0)return{kind:"entity_attribute",entity_id:t.slice(0,i),attribute:t.slice(i+1)}}return e.startsWith("marker:marker:")?{kind:"derived_marker_state",ref:e.slice(7)}:null}function Fo(e,t){const i=e?.entities?.[t],s=e?.states?.[t];return String(i?.name||i?.original_name||s?.attributes?.friendly_name||t)}function Eo(e){return e.replaceAll("_"," ")}function No(e,t=1){const i=Number(e);return Number.isFinite(i)?`${Math.round(i*t)} %`:null}function Oo(e){if("derived_lqi"===e.kind)return"lqi";if("entity_attribute"===e.kind){if(e.attribute.includes("temperature"))return"temperature";if(e.attribute.includes("humidity"))return"humidity"}return"default"}function Ho(e,t,i,s=[]){let n=null,o="",a="available";if("entity_state"===i.kind){o=Fo(e,i.entity_id);const t=e?.states?.[i.entity_id];if(t)if(Bo(e,i.entity_id))if(["unknown","unavailable"].includes(String(t.state).toLowerCase()))a="unavailable";else{const s=Xi(e,i.entity_id);n=s?Zi(s,String(t.attributes?.unit_of_measurement||"")):null,n||(a="unavailable")}else a="unavailable";else a="missing"}else if("entity_attribute"===i.kind){o=`${Eo(i.attribute)} · ${Fo(e,i.entity_id)}`;const t=e?.states?.[i.entity_id];t?Bo(e,i.entity_id)?(n=function(e,t,i){const s=e?.states?.[t];if(!s||!(i in(s.attributes||{})))return null;const n=Xi(e,t,i);if(n?.formatted)return n.text;const o=s.attributes?.[i];if("brightness"===i)return No(o,100/255);if("volume_level"===i)return No(o,100);if(["current_position","percentage","current_humidity","humidity","battery_level"].includes(i))return No(o);if("current_temperature"===i||"temperature"===i){const t=Number(o);if(!Number.isFinite(t))return null;const i=String(e?.config?.unit_system?.temperature||"°C");return`${Math.round(10*t)/10} ${i}`}return n?.text||(["string","number","boolean"].includes(typeof o)?String(o):null)}(e,i.entity_id,i.attribute),null==n&&(a="unavailable")):a="unavailable":a="missing"}else if("derived_lqi"===i.kind){o="LQI";const i=_o(e,t.entities);null==i?a="unavailable":n=String(i)}else{o="Light state";const t=s.find(e=>e.ref===i.ref);if(t){const i=t.on?"on":"off",s=e?.localize?.(`state.default.${i}`);n="string"==typeof s&&s?s:i,o=t.name||o}else a="missing"}const r=e?.localize?.("state.default.unavailable")||"Unavailable";return{source:i,sourceLabel:o,text:n??"—",fullText:n??r,availability:a,isLqi:"derived_lqi"===i.kind,tone:Oo(i)}}function Lo(e,t){if(!0===t.marker?.use_climate_temp){const i=t.entities.find(t=>t.startsWith("climate.")&&Number.isFinite(Number(e?.states?.[t]?.attributes?.current_temperature)));return i?{kind:"entity_attribute",entity_id:i,attribute:"current_temperature"}:null}if("mdi:thermometer"===t.icon||"mdi:air-filter"===t.icon){const i=t.entities.find(t=>Gn(e,t)&&Number.isFinite(Number(e?.states?.[t]?.state)));if(i)return{kind:"entity_state",entity_id:i}}return t.primary&&fo(e,t.primary)&&Number.isFinite(Number(e?.states?.[t.primary]?.state))?{kind:"entity_state",entity_id:t.primary}:null}function Bo(e,t){const i=e?.entities?.[t];if(i&&!En(i))return!1;const s=i?.device_id?e?.devices?.[i.device_id]:null;return!s||En(s)}function qo(e,t){return Bo(e,t)&&!!e?.states?.[t]}function Wo(e,t,i=[t]){const s=function(e,t){const i=e=>[e.id,e.primary,e.hidden?1:0,e.userHidden?1:0,e.entities.join(","),(e.controls||[]).join(","),e.marker?.binding||"",!0===e.marker?.is_light?1:0,e.marker?.light_entity||"",(e.marker?.controls||[]).join(",")].join("|");return`${i(e)}\n${t.map(i).join("\n")}`}(t,i),n=Ro.get(t);if(n&&n.states===(e?.states||null)&&n.entities===(e?.entities||null)&&n.devices===(e?.devices||null)&&n.signature===s)return n.result;const o=new Set(t.entities);for(const e of t.controls||[])e.startsWith("marker:")||o.add(e);const a=[],r=ho(e,i),l=r.filter(e=>e.key.startsWith("marker:")).map(e=>({ref:e.key,on:e.on,name:e.device?.name||e.key})),c=i=>{const s=Ao(i);if(a.some(e=>e.key===s))return;const n=Ho(e,t,i,l),o="entity_attribute"===i.kind?`${i.entity_id} · ${i.attribute}`:"entity_state"===i.kind?i.entity_id:"derived_marker_state"===i.kind?i.ref:"LQI";a.push({key:s,source:i,label:n.sourceLabel,technical:o,value:n.text,available:"available"===n.availability})};for(const t of[...o].sort()){if(!qo(e,t))continue;const i=t.split(".")[0],s=e?.entities?.[t];if("button"===i||"event"===i||"config"===s?.entity_category)continue;c({kind:"entity_state",entity_id:t});const n=e?.states?.[t];for(const e of To[i]||[])e in(n?.attributes||{})&&c({kind:"entity_attribute",entity_id:t,attribute:e})}const h=new Set((t.marker?.controls||t.controls||[]).filter(e=>e.startsWith("marker:")));!0===t.marker?.is_light&&t.marker.id&&h.add(`marker:${t.marker.id}`);const d=new Set(r.map(e=>e.key));for(const e of[...h].sort())d.has(e)&&c({kind:"derived_marker_state",ref:e});return t.virtual||null==_o(e,t.entities)||c({kind:"derived_lqi"}),Ro.set(t,{states:e?.states||null,entities:e?.entities||null,devices:e?.devices||null,signature:s,result:a}),a}function jo(e,t,i){const s=Lo(e,t);if(s&&i.some(e=>e.key===Ao(s)))return s;const n=t.primary&&i.find(e=>e.key===`state:${t.primary}`);if(n)return n.source;const o=[e=>e.technical.includes("temperature"),e=>e.technical.includes("humidity"),e=>e.technical.includes("battery")];for(const e of o){const t=i.find(e);if(t)return t.source}return i.find(e=>"derived_lqi"!==e.source.kind)?.source||i[0]?.source||null}function Uo(e){return"boolean"==typeof e?.themes?.darkMode?e.themes.darkMode?"theme-dark":"theme-light":""}function Go(e){const t=[];if(1!==e.scale&&t.push(`--dev-scale:${e.scale}`),"none"!==e.pulse.kind){t.push(`--ripple-scale:${e.pulse.diameterScale}`);const n=(i=e.pulse.color,s=null,"string"==typeof i&&(Te.test(i)||Ae.test(i))?i:s);n&&t.push(`--ripple-color:${n}`)}var i,s;return t}function Vo(e){const t=[...String(e)].reduce((e,t)=>/\s/.test(t)?e+.35:e+(t.codePointAt(0)>255?1:.62),0);return t<=8?.45:Math.max(.25,Math.round(3.6/t*1e3)/1e3)}function Ko(e,t){const i=e.pulse,s=i.generation%2==0,n=function(e){const t=e.valueBadge;if(!t||!1!==t.configured)return[];const i=[];return null!=e.tempText&&"temperature"!==t.tone&&i.push({kind:"temperature",text:e.tempText,suffix:"°"}),null!=e.humText&&"humidity"!==t.tone&&i.push({kind:"humidity",text:e.humText,suffix:"%"}),i}(e),o=e.valueBadge,a=o?.position||"right",r=!!o||n.length>0,l=["device-shell",null!=e.valueText?"text-shell":"",r?`with-values pos-${a}`:"",n.length?"with-legacy":""].filter(Boolean).join(" ");return W`
${"none"!==i.kind&&"dot"!==i.reducedMotionIndicator?W``:G}
${"dot"===i.reducedMotionIndicator?W``:G}
@@ -4487,14 +4487,14 @@ globalThis.__HOUSEPLAN_BUILD_FINGERPRINT__="3d7cafaabdfd8cbcf261f9dccec794dd7c42
.previewstage { min-height: 142px; }
.previewfacts > div { grid-template-columns: minmax(0, 1fr); gap: 2px; }
}
- `],customElements.get("hp-device-preview")||customElements.define("hp-device-preview",ha);const da=Math.tan(.25*Math.PI/180);function pa(e,t){const i=Math.abs(Number(t[0])-Number(e[0])),s=Math.abs(Number(t[1])-Number(e[1]));if(!([i,s].every(Number.isFinite)&&i>0&&s>0))return null;const n=i>=s?"horizontal":"vertical",o=Math.max(i,s),a=Math.min(i,s);return a/o>da?null:{axis:n,major:o,minor:a,angleDegrees:180*Math.atan2(a,o)/Math.PI}}function ua(e,t){const i=pa(e,t);return i?"horizontal"===i.axis?[Number(t[0]),Number(e[1])]:[Number(e[0]),Number(t[1])]:[Number(t[0]),Number(t[1])]}const _a=e=>`${e[0]},${e[1]}`,ma=(e,t)=>e[0]===t[0]&&e[1]===t[1],ga=(e,t)=>{const i=_a(e),s=_a(t);return i{let t=0;for(let i=0;i{if(e.length<3)return!1;for(let t=0;t1e-12},ya=e=>{for(let t=0;t+1ma(e,t.from)?[...t.to]:[...e],wa=(e,t)=>e.map(e=>Array.isArray(e?.poly)?{...e,poly:e.poly.map(e=>ba(e,t))}:e),ka=(e,t,i)=>{const s=e.flatMap((e,t)=>hi(e)?.some(e=>ma(e,i.from))?[t]:[]);if(!s.length)return!1;for(const i of s){const s=hi(e[i]),n=hi(t[i]);if(!s||!n)continue;if(!va(n))return!1;const o=Math.sign(fa(s)),a=Math.sign(fa(n));if(o&&a&&o!==a)return!1}const n=new Set;for(const e of s){const i=hi(t[e]);if(i)for(let s=0;s{let i=0;for(const s of e){const e=hi(s);if(e)for(let s=0;s{const{a:i,b:s,axis:n}=e,o="horizontal"===n?{from:s,to:[s[0],i[1]]}:{from:s,to:[i[0],s[1]]},a="horizontal"===n?{from:i,to:[i[0],s[1]]}:{from:i,to:[s[0],i[1]]};return[{move:o,preservedDegree:xa(t,i)},{move:a,preservedDegree:xa(t,s)}].sort((e,t)=>t.preservedDegree-e.preservedDegree||_a(e.move.to).localeCompare(_a(t.move.to))||_a(e.move.from).localeCompare(_a(t.move.from))).map(e=>e.move)};const Sa=(e,t)=>[e[0]-t[0],e[1]-t[1]],Ma=(e,t)=>[e[0]+t[0],e[1]+t[1]],Ca=(e,t)=>e[0]*t[0]+e[1]*t[1],Da=e=>Math.hypot(e[0],e[1]);function Pa(e){let t=0;for(let i=0;ie[1]!=l>e[1]&&e[0]<(r-o)*(e[1]-a)/(l-a)+o&&(i=!i)}return i}([r[0]+a[0]*l,r[1]+a[1]*l],e)&&(a=[-a[0],-a[1]]),a}function Ra(e){const t=e.length;if(t<3)return!1;for(let i=0;i(e[0]-n[0])*r[1]-(e[1]-n[1])*r[0],c=e=>(e[0]-n[0])*r[0]+(e[1]-n[1])*r[1],h=i,d=a-i;for(const t of e){const e=Math.abs(l(t));if(e<=i)continue;const n=c(t);n<=h||n>=d||eMath.abs(a+(e-p)/g*(r-a));s=Math.min(s,f(_),f(m))}}return s}function za(e,t,i){if(Di(e,t,i))return!0;if(Ci(e,t,i)||Ci(t,e,i))return!1;let s=0;try{const i=ni([[...e.map(e=>[e[0],e[1]]),[e[0][0],e[0][1]]]],[[...t.map(e=>[e[0],e[1]]),[t[0][0],t[0][1]]]]);for(const e of i)e?.[0]&&(s+=Ti(e[0]))}catch{return!1}return s>Math.max(1e-7,i*i)}function Fa(e,t,i){for(const s of t)for(let t=0;ti)continue;const c=(e.x-n[0])*l[0]+(e.y-n[1])*l[1];if(c-e.length/2>=-i&&c+e.length/2<=r+i)return!0}return!1}function Ea(e,t,i){const s=Math.abs(t[0]-e[0]),n=Math.abs(t[1]-e[1]);return s<=i&&n>i?"v":n<=i&&s>i?"h":null}function Na(e,t,i){return Math.abs(e[0]-t[0])<=i&&Math.abs(e[1]-t[1])<=i}function Oa(e,t,i,s,n){return Na(e,i,n)&&Na(t,s,n)||Na(e,s,n)&&Na(t,i,n)}function La(e,t,i,s,n){const o=Ea(e,t,n);return o&&Ea(i,s,n)===o?"h"===o?Math.abs(e[1]-i[1])>n||Math.abs(e[1]-s[1])>n?0:Math.max(0,Math.min(Math.max(e[0],t[0]),Math.max(i[0],s[0]))-Math.max(Math.min(e[0],t[0]),Math.min(i[0],s[0]))):Math.abs(e[0]-i[0])>n||Math.abs(e[0]-s[0])>n?0:Math.max(0,Math.min(Math.max(e[1],t[1]),Math.max(i[1],s[1]))-Math.max(Math.min(e[1],t[1]),Math.min(i[1],s[1]))):0}function Ha(e,t,i,s){const n=e.length,o=Ea(e[(t-1+n)%n],e[t],s),a=Ea(e[(t+1)%n],e[(t+2)%n],s),r="h"===i?"v":"h";return o===r&&a===r}function Ba(e){let t=1/0,i=1/0,s=-1/0,n=-1/0;for(const o of e)t=Math.min(t,o[0]),i=Math.min(i,o[1]),s=Math.max(s,o[0]),n=Math.max(n,o[1]);return[t,i,s,n]}function qa(e,t,i){const s=Ba(e),n=Ba(t);return s[2]n}const ja=(e,t)=>"h"===t?e[0]:e[1],Ua=(e,t)=>"h"===t?e[1]:e[0];function Ga(e,t,i,s,n){const o=e.find(e=>e.id===t);if(!o)return null;const a=o.poly[i],r=o.poly[(i+1)%o.poly.length],l=Ea(a,r,n);if(!l)return null;const c=0===s?r:a,h=0===s?a:r,d=ja(c,l),p=ja(h,l),u=Ua(c,l),_=function(e,t,i,s){const n=[];for(const o of e)for(let e=0;es||Math.abs(Ua(r,t)-i)>s)continue;const l=ja(a,t),c=ja(r,t),h=Math.min(l,c),d=Math.max(l,c);d-h>s&&n.push({roomId:o.id,edge:e,lo:h,hi:d})}return n.sort((e,t)=>e.lo-t.lo||e.hi-t.hi||e.roomId.localeCompare(t.roomId)||e.edge-t.edge)}(e,l,u,n),m=function(e,t,i,s){const n=[t,i];for(const o of e){const e=Math.max(t,o.lo),a=Math.min(i,o.hi);a-e>s&&n.push(e,a)}const o=[...new Set(n)].sort((e,t)=>e-t),a=[];for(let t=0;t+1r>e.lo-s&&re.roomId))].sort();a.push({lo:i,hi:n,owners:l})}return a}(_,Math.min(d,p),Math.max(d,p),n);return!m.length||m.some(e=>e.owners.length<1||e.owners.length>2)?null:{roomId:t,edge:i,movedEndpoint:s,axis:l,line:u,fixed:d,moving:p,intervals:_,baseline:m}}function Va(e,t,i){const s=[];for(const n of e.intervals){const o=t.polys[n.roomId];if(!o){s.push(n);continue}if(n.edge<0||n.edge>=o.length)continue;const a=o[n.edge],r=o[(n.edge+1)%o.length];if(Ea(a,r,i)!==e.axis||Math.abs(Ua(a,e.axis)-e.line)>i||Math.abs(Ua(r,e.axis)-e.line)>i)continue;const l=ja(a,e.axis),c=ja(r,e.axis),h=Math.min(l,c),d=Math.max(l,c);d-h>i&&s.push({...n,lo:h,hi:d})}return s}function Ka(e,t,i){return new Set(e.filter(e=>t>e.lo-i&&te.roomId)).size}function Ya(e,t,i){for(const s of t.sideOwnership){const t=e.polys[s.roomId];if(!t)return!1;const n=t[s.edge],o=t[(s.edge+1)%t.length];if(Ea(n,o,i)!==s.axis)return!1;const a=ja(0===s.movedEndpoint?n:o,s.axis),r=Va(s,e,i),l=(s.moving>=s.fixed?s.baseline[s.baseline.length-1]:s.baseline[0]).owners.length;if(l<1||l>2)return!1;const c=Math.min(s.fixed,s.moving,a),h=Math.max(s.fixed,s.moving,a),d=[c,h,s.fixed,s.moving,a];for(const e of s.intervals)d.push(e.lo,e.hi);for(const e of r)d.push(e.lo,e.hi);const p=[...new Set(d.filter(e=>e>=c&&e<=h))].sort((e,t)=>e-t),u=Math.min(s.fixed,s.moving),_=Math.max(s.fixed,s.moving),m=Math.min(s.fixed,a),g=Math.max(s.fixed,a);for(let e=0;e+1u-i&&o<_+i,c=o>m-i&&o2||d>2)return!1;if(a&&c){if(h!==d)return!1}else if(!a&&c){if(d!==l||h>0&&h!==d)return!1}else if(2===h?2!==d:d>1)return!1}}return!0}function Ja(e,t,i,s){const n=[i.n[0]*s,i.n[1]*s],o={polys:{},openings:{},movedSpans:{}};for(const t of i.roomIds){const s=e.find(e=>e.id===t),a=i.edgeByRoom[t];if(!s||null==a)continue;const r=(a+1)%s.poly.length;o.polys[t]=s.poly.map((e,t)=>t===a||t===r?Ma(e,n):[...e]),o.movedSpans[t]=[[Ma(s.poly[a],n),Ma(s.poly[r],n)]]}for(const e of t)i.movingOpeningIds.includes(e.id)&&(o.openings[e.id]=[e.x+n[0],e.y+n[1]]);return o}function Xa(e,t,i,s,n,o,a,r){if(!function(e,t,i,s){if(Ta([e.x,e.y],t,i)>2*s)return!1;const n=Da(Sa(i,t));if(n<=s)return!1;const o=[(i[0]-t[0])/n,(i[1]-t[1])/n],a=(e.x-t[0])*o[0]+(e.y-t[1])*o[1];return a>=-s&&a<=n+s}(e,t,i,r))return!0;if(Ta([e.x,e.y],s,n)>2*r)return!1;const l=0===o?s:n;return Da(Sa([e.x,e.y],l))>=e.length/2+a-r}function Za(e,t,i,s){const n=s.movingHalf||0;return"circle"===e.kind?Ta(e.center,t,i)2)return!1;const r=Ja(e,t,i,s);if(Object.keys(r.polys).length!==i.roomIds.length)return!1;if(!Ya(r,i,o))return!1;const l=new Set(i.roomIds),c=e=>r.polys[e.id]||e.poly;for(const s of i.roomIds){const l=e.find(e=>e.id===s),c=r.polys[s],h=i.edgeByRoom[s];if(!l||!c||c.length!==i.topology[s]||c.length!==l.poly.length||!Ra(c))return!1;const d=l.poly.length,p=(h-1+d)%d,u=[p,h,(h+1)%d];for(const e of u)if(pa(c[e],c[(e+1)%d]))return!1;const _=Pa(l.poly),m=Pa(c);if(Math.abs(m)e.id===t),s=r.polys[t];for(const n of e){if(n.id===t||l.has(n.id))continue;const e=c(n);if(!qa(i.poly,n.poly,o)||!qa(s,e,o))if(Ci(i.poly,n.poly,o)){if(!Ci(s,e,o))return!1}else if(Ci(n.poly,i.poly,o)){if(!Ci(e,s,o))return!1}else if(Ci(s,e,o)||Ci(e,s,o)||za(s,e,o))return!1}}e.find(e=>e.id===i.roomId);const h=r.polys[i.roomId],d=i.edgeByRoom[i.roomId],p=h[d],u=h[(d+1)%h.length];if(Math.abs(s)>o)for(const e of n.obstacles||[])if(Za(e,p,u,n))return!1;for(const e of t){if(!i.movingOpeningIds.includes(e.id))continue;const t=r.openings[e.id];if(!t||e.hosted)return!1;if(!Fa({...e,x:t[0],y:t[1]},[h],2*o))return!1}return!0}const er=new WeakMap;function tr(e,t,i){const s=i/t;return Ti(e)*s*s/1e4}function ir(e,t){return t?`${Math.round(10.7639*e)} ft²`:`${(Math.round(10*e)/10).toFixed(1)} m²`}const sr=e=>"number"==typeof e&&Number.isFinite(e),nr=(e,t)=>{const i=new Map;for(const s of e||[])!sr(s?.cm)||!t&&s.cm<=0||i.set(s.cm,(i.get(s.cm)||0)+1);return i},or=e=>[String(e),"см"].join(" ");function ar(e,t,i={}){if(i.allowClear)return[];const s=!0===i.exactMultiplicity,n=nr(e,s),o=nr(t,s),a=[];for(const[e,t]of n){const i=o.get(e)||0;0===i?a.push({invariant:"wall_records",kind:"lost",owner:or(e),reference:`было ${t}`,detail:"записи этой толщины исчезли целиком"}):s&&i!==t&&a.push({invariant:"wall_records",kind:"count",owner:or(e),reference:`было ${t}, стало ${i}`,detail:"изменилось число записей этой толщины"})}if(s)for(const[e,t]of o)n.has(e)||a.push({invariant:"wall_records",kind:"count",owner:or(e),reference:`было 0, стало ${t}`,detail:"появились записи новой толщины"});return a}class rr{constructor(){this._selectedRoomId=null,this._session=null,this._eligibility=null}get dragging(){return null!==this._session}ownsPointer(e){return this._session?.pointerId===e}get selectedRoomId(){return this._selectedRoomId}get snapshotIdentity(){return this._session?.snapshotIdentity||null}get activePointerId(){return this._session?.pointerId??null}get moved(){return!0===this._session?.moved}get delta(){return this._session?.delta||0}get rooms(){return this._session?.rooms||null}get openings(){return this._session?.openings||null}get plan(){return this._session?.plan||null}get preview(){return this._session?.accepted?.preview||null}get liveLabels(){return this._session?.accepted?.labels||null}selectRoom(e){this._selectedRoomId=e}restoreSelection(e){this._selectedRoomId=e}escapeIdle(){return this._selectedRoomId?(this._selectedRoomId=null,"selection-cleared"):"exit-tool"}resolve(e,t,i){this._eligibility&&this._eligibility.context===e||(this._eligibility={context:e,values:new Map});const s=this._eligibility.values.get(t);if(s)return s;const n=i();return this._eligibility.values.set(t,n),n}begin(e){return!this._session&&(this._session={pointerId:e.pointerId,start:[...e.start],roomId:e.roomId,plan:e.plan,options:e.options,rooms:e.rooms,openings:e.openings,snapshotIdentity:e.snapshotIdentity,before:e.before,moved:!1,delta:0,changedRoomIds:[...e.plan.roomIds],rejectionNotified:!1,wallUnionBefore:e.wallUnionBefore,accepted:null},!0)}move(e){const t=this._session;if(!t||t.pointerId!==e.pointerId)return{kind:"no-op"};const i=(s=t.start,n=e.point,o=t.plan.n,[s?.[0],s?.[1],n?.[0],n?.[1],o?.[0],o?.[1]].every(Number.isFinite)?(n[0]-s[0])*o[0]+(n[1]-s[1])*o[1]:0);var s,n,o;const a=e.snap([t.plan.a[0]+t.plan.n[0]*i,t.plan.a[1]+t.plan.n[1]*i]),r=(a[0]-t.plan.a[0])*t.plan.n[0]+(a[1]-t.plan.a[1])*t.plan.n[1],l=function(e,t,i,s,n,o){if(!Number.isFinite(s)||Math.abs(s)<1e-9)return 0;const a=Math.sign(s),r=Math.abs(s),l=Math.max(Math.abs(n),1e-6);let c=er.get(i);c&&c.opts===o||(c={opts:o,values:new Map},er.set(i,c));const h=c.values;let d=0;for(let s=Math.min(l,r),n=0;n<4096&&s<=r+1e-9;n++,s=Math.min(r,s+l)){const n=a*s,c=`${n.toFixed(9)}|${l.toFixed(9)}`;let p=h.get(c);if(void 0===p&&(p=Qa(e,t,i,n,o),h.size<4096&&h.set(c,p)),!p)break;if(d=n,Math.abs(s-r)<=1e-9)break}return d}(t.rooms,t.openings,t.plan,r,e.step,t.options);if(t.moved&&l===t.delta)return{kind:"no-op"};const c=Ja(t.rooms,t.openings,t.plan,l);let h;try{if(h=e.project(t.snapshotIdentity,c.polys,c.openings,t.changedRoomIds,t.rooms),!h.ok)return this._projectionRejected(t);if(ar(h.value.beforeWalls,h.value.afterWalls,{exactMultiplicity:!0}).length)return this._projectionRejected(t)}catch{return this._projectionRejected(t)}const d=t.accepted,p={preview:h.value.preview,labels:null,artifact:h.value.artifact,beforeWalls:h.value.beforeWalls,afterWalls:h.value.afterWalls};t.accepted=p;try{e.publish(p.preview,p.artifact),p.labels=e.measure(c,t.plan)}catch{t.accepted=d;try{e.publish(d?.preview||null,d?.artifact||null)}catch{}return this._projectionRejected(t)}return t.moved=!0,t.delta=l,{kind:"accepted",preview:h.value.preview,labels:p.labels,artifact:h.value.artifact}}finish(e){const t=this._session;if(!t||t.pointerId!==e.pointerId)return{kind:"no-op"};const i=t.accepted;let s;if(t.moved&&Math.abs(t.delta)>1e-9&&i)if(e.currentSnapshotIdentity!==t.snapshotIdentity)s={kind:"rejected",reason:"stale-snapshot"};else if(Qa(t.rooms,t.openings,t.plan,t.delta,t.options))if(ar(i.beforeWalls,i.afterWalls,{exactMultiplicity:!0}).length)s={kind:"rejected",reason:"wall-records"};else{let n=!1;try{n=e.validatePreview(i.preview)}catch{n=!1}s=n?{kind:"commit",preview:i.preview,before:t.before}:{kind:"rejected",reason:"invalid-candidate"}}else s={kind:"rejected",reason:"invalid-topology"};else s={kind:"no-op"};return this._session=null,"commit"===s.kind&&(this._eligibility=null),s}cancel(e,t){const i=this._session;return!i||void 0!==t&&i.pointerId!==t?{kind:"no-op"}:(this._session=null,this._eligibility=null,{kind:"cancelled",restoreWallUnion:e===i.snapshotIdentity?i.wallUnionBefore:null})}reset(){this._selectedRoomId=null,this._session=null,this._eligibility=null}_projectionRejected(e){const t=!e.rejectionNotified;return e.rejectionNotified=!0,{kind:"rejected",notify:t}}}const lr=(e,t)=>[(e[0]-t.x)/Math.max(1e-9,t.w)*t.stageWidth,(e[1]-t.y)/Math.max(1e-9,t.h)*t.stageHeight];function cr(e){const{poly:t,edge:i,text:s,view:n}=e,o=t[i],a=t[(i+1)%t.length],r=[(o[0]+a[0])/2,(o[1]+a[1])/2],l=function(e,t){const i=e[t],s=e[(t+1)%e.length],n=s[0]-i[0],o=s[1]-i[1],a=Math.hypot(n,o)||1;return(e=>{let t=0;for(let i=0;i=0?[-o/a,n/a]:[o/a,-n/a]}(t,i),c=Math.hypot(a[0]-o[0],a[1]-o[1])||1,h=[(a[0]-o[0])/c,(a[1]-o[1])/c],d=lr(r,n),p=lr(e.gearCenter,n),u=Math.max(34,7.2*s.length+12),_=Math.abs(l[0])>=Math.abs(l[1])?Math.max(28,u/2+4):Math.max(28,13),m=d[0]+l[0]*_,g=d[1]+l[1]*_,f=t=>{return i=m+h[0]*t,s=g+h[1]*t,n=u,o=18,a=p[0],r=p[1],l=e.gearWidthPx,c=e.gearHeightPx,2*Math.abs(i-a)=Math.abs(h[1])?h[0]:h[1])>0?-1:1,t=Math.max(n.stageWidth,n.stageHeight,64);for(let i=4;i<=t;i+=4){const t=i*e;if(!f(t)){v=t;break}const s=-t;if(!f(s)){v=s;break}}}const y=l[0]*_+h[0]*v,b=l[1]*_+h[1]*v,w=Math.hypot(y,b)||1,k=b/w*12,x=[r[0]+y/w*12*n.w/Math.max(1,n.stageWidth),r[1]+k*n.h/Math.max(1,n.stageHeight)];return{anchor:r,offsetXPx:y,offsetYPx:b,tangentOffsetPx:v,side:Math.abs(l[0])>=Math.abs(l[1])?l[0]<0?"left":"right":l[1]<0?"above":"below",leader:{a:r,b:x}}}function hr(e){const t=e%360;return t<0?t+360:t}function dr(e,t){const i=function(e,t){return hr(e+t)}(e,t)*Math.PI/180;return[Math.sin(i),-Math.cos(i)]}const pr=Object.freeze({dawn:Object.freeze({top:"#aabdd1",bottom:"#e8c8b7",horizon:"rgba(255,201,156,.56)",sun:"rgba(255,188,125,.78)",vignette:"rgba(65,72,99,.21)",outlineNear:"rgba(74,57,61,.25)",outlineMid:"rgba(255,238,224,.40)",outlineFar:"rgba(255,224,202,.18)"}),day:Object.freeze({top:"#dce9ef",bottom:"#cbdce3",horizon:"rgba(255,245,220,.45)",sun:"rgba(255,239,190,.72)",vignette:"rgba(65,91,105,.16)",outlineNear:"rgba(45,62,71,.28)",outlineMid:"rgba(255,255,255,.42)",outlineFar:"rgba(255,255,255,.20)"}),dusk:Object.freeze({top:"#48536c",bottom:"#9a7380",horizon:"rgba(242,156,114,.34)",sun:"rgba(255,167,113,.55)",vignette:"rgba(20,26,44,.39)",outlineNear:"rgba(238,219,225,.40)",outlineMid:"rgba(229,207,218,.26)",outlineFar:"rgba(215,190,205,.12)"}),night:Object.freeze({top:"#111a27",bottom:"#1f2f3e",horizon:"rgba(79,120,151,.16)",sun:"rgba(169,208,231,0)",vignette:"rgba(3,8,14,.58)",outlineNear:"rgba(218,238,249,.56)",outlineMid:"rgba(174,215,238,.30)",outlineFar:"rgba(136,194,226,.14)"})}),ur=e=>"number"==typeof e&&Number.isFinite(e),_r=(e,t,i)=>Math.min(i,Math.max(t,e));function mr(e){return e.elevation<=-6?"night":e.elevation>=6?"day":e.rising?"dawn":"dusk"}function gr(e){const t=(Math.floor(Number(e)||0)%1440+1440)%1440;return t>=300&&t<480?"dawn":t>=480&&t<1080?"day":t>=1080&&t<1260?"dusk":"night"}function fr(e){const t=mr(e),i=e.azimuth*Math.PI/180;return{sunX:50-42*Math.sin(i),sunY:78-_r(e.elevation,0,90)/90*64,sunOpacity:"night"===t?0:_r((e.elevation+6)/12,0,1)}}function vr(e){const t=(Math.floor(Number(e)||0)%1440+1440)%1440;if(t<300||t>=1260)return{sunX:50,sunY:78,sunOpacity:0};const i=(t-300)/960,s=(t-300)/120,n=(1260-t)/120;return{sunX:8+84*i,sunY:78-64*Math.sin(i*Math.PI),sunOpacity:Math.max(.18,Math.min(s,n,1))}}function yr(e,t=new Date){const i=function(e){const t=e?.states?.["sun.sun"]?.attributes;return t&&ur(t.azimuth)&&ur(t.elevation)&&"boolean"==typeof t.rising?{azimuth:hr(t.azimuth),elevation:t.elevation,rising:t.rising}:null}(e);if(i)return{phase:mr(i),source:"sun",...fr(i)};const s="number"==typeof t?t:function(e=new Date){return 60*e.getHours()+e.getMinutes()}(t);return{phase:gr(s),source:"clock",...vr(s)}}function br(e){return`${e.source}|${e.phase}|${e.sunX.toFixed(2)}|${e.sunY.toFixed(2)}|`+e.sunOpacity.toFixed(3)}const wr=[[-90,"#070c14"],[-12,"#070c14"],[-4,"#131a28"],[0,"#4a3527"],[10,"#e8ddcf"],[30,"#ffffff"],[90,"#ffffff"]],kr=e=>Math.min(1,Math.max(0,e));function xr(e,t,i=6){const s=e.angle*Math.PI/180,n=[Math.sin(s),-Math.cos(s)],o=s=>{const o=[e.x+n[0]*i*s,e.y+n[1]*i*s];return t.find(e=>e.poly.length>=3&&vi(o,e.poly))||null},a=o(1),r=o(-1);return a&&r?null:a||r?a?{normal:[-n[0],-n[1]],roomId:a.id}:{normal:n,roomId:r.id}:null}function $r(e,t,i){return i>0&&e[0]*t[0]+e[1]*t[1]>.05}function Sr(e,t,i,s){return[[e[0],e[1]],[t[0],t[1]],[t[0]+i[0]*s,t[1]+i[1]*s],[e[0]+i[0]*s,e[1]+i[1]*s]]}function Mr(e,t){try{const i=ni([[...e.map(e=>[e[0],e[1]]),[e[0][0],e[0][1]]]],[[...t.map(e=>[e[0],e[1]]),[t[0][0],t[0][1]]]]),s=[];for(const e of i){const t=e?.[0];!Array.isArray(t)||t.length<4||s.push(t.slice(0,t.length-1).map(e=>[e[0],e[1]]))}return s}catch{return[]}}function Cr(e,t,i,s,n,o,a){if(!(s>0))return[];const r=dr(i,n),l=[-r[0],-r[1]],c=function(e){const t=Math.min(90,Math.max(0,e));return.7*(.8+1.7*Math.pow(1-t/90,1.6))}(s),h=[];for(const i of t){if(!(i.length>0))continue;const t=xr(i,e);if(!t||!$r(t.normal,r,s))continue;const n=e.find(e=>e.id===t.roomId);if(!n)continue;const d=o&&o[t.roomId]||n.poly,p=i.angle*Math.PI/180,u=i.length/2,_=[-t.normal[0],-t.normal[1]],m=Math.max(0,a?.[i.id]||0),g=i.x+_[0]*m/2,f=i.y+_[1]*m/2,v=Math.cos(p)*u,y=Math.sin(p)*u,b=[g-v,f-y],w=[g+v,f+y],k=c*i.length,x=Mr(Sr(b,w,l,k),d);if(!x.length)continue;const $=l[0]*_[0]+l[1]*_[1];h.push({openingId:i.id,roomId:t.roomId,polys:x,a:b,b:w,dir:l,len:k,normal:_,depth:k*$})}return h}const Dr=e=>"number"==typeof e&&Number.isInteger(e)&&e>=0&&e<=359?e:null;function Pr(e,t){const i=Dr(t?.north_deg);return null!==i?i:Dr(e?.north_deg)}function Tr(e,t){const i=e=>"static"===e||"daynight"===e?e:null;return i(t?.bg_mode)??i(e?.bg_mode)??"static"}function Ir(e,t){const i=t?.sun_rays;return"boolean"==typeof i?i:!0===e?.sun_rays}function Rr(e){const t=e?.states?.["sun.sun"]?.attributes,i=Number(t?.azimuth),s=Number(t?.elevation);return Number.isFinite(i)&&Number.isFinite(s)?{azimuth:i,elevation:s}:null}const Ar=["dawn","day","dusk","night"];function zr(e){if(!e)return"";const t=pr[e.phase];return[`--hp-day-cycle-outline-near:${t.outlineNear}`,`--hp-day-cycle-outline-mid:${t.outlineMid}`,`--hp-day-cycle-outline-far:${t.outlineFar}`].join(";")}function Fr(e,t=1){if(!e)return G;const i=[`--hp-day-cycle-sun-x:${e.sunX.toFixed(2)}%`,`--hp-day-cycle-sun-y:${e.sunY.toFixed(2)}%`,`--hp-day-cycle-sun-opacity:${e.sunOpacity.toFixed(3)}`,`opacity:${Math.min(1,Math.max(0,t)).toFixed(4)}`].join(";");return W`0&&s>0))return null;const n=i>=s?"horizontal":"vertical",o=Math.max(i,s),a=Math.min(i,s);return a/o>da?null:{axis:n,major:o,minor:a,angleDegrees:180*Math.atan2(a,o)/Math.PI}}function ua(e,t){const i=pa(e,t);return i?"horizontal"===i.axis?[Number(t[0]),Number(e[1])]:[Number(e[0]),Number(t[1])]:[Number(t[0]),Number(t[1])]}const _a=e=>`${e[0]},${e[1]}`,ma=(e,t)=>e[0]===t[0]&&e[1]===t[1],ga=(e,t)=>{const i=_a(e),s=_a(t);return i
{let t=0;for(let i=0;i{if(e.length<3)return!1;for(let t=0;t1e-12},ya=e=>{for(let t=0;t+1ma(e,t.from)?[...t.to]:[...e],wa=(e,t)=>e.map(e=>Array.isArray(e?.poly)?{...e,poly:e.poly.map(e=>ba(e,t))}:e),ka=(e,t,i)=>{const s=e.flatMap((e,t)=>hi(e)?.some(e=>ma(e,i.from))?[t]:[]);if(!s.length)return!1;for(const i of s){const s=hi(e[i]),n=hi(t[i]);if(!s||!n)continue;if(!va(n))return!1;const o=Math.sign(fa(s)),a=Math.sign(fa(n));if(o&&a&&o!==a)return!1}const n=new Set;for(const e of s){const i=hi(t[e]);if(i)for(let s=0;s{let i=0;for(const s of e){const e=hi(s);if(e)for(let s=0;s{const{a:i,b:s,axis:n}=e,o="horizontal"===n?{from:s,to:[s[0],i[1]]}:{from:s,to:[i[0],s[1]]},a="horizontal"===n?{from:i,to:[i[0],s[1]]}:{from:i,to:[s[0],i[1]]};return[{move:o,preservedDegree:xa(t,i)},{move:a,preservedDegree:xa(t,s)}].sort((e,t)=>t.preservedDegree-e.preservedDegree||_a(e.move.to).localeCompare(_a(t.move.to))||_a(e.move.from).localeCompare(_a(t.move.from))).map(e=>e.move)};const Sa=(e,t)=>[e[0]-t[0],e[1]-t[1]],Ma=(e,t)=>[e[0]+t[0],e[1]+t[1]],Ca=(e,t)=>e[0]*t[0]+e[1]*t[1],Da=e=>Math.hypot(e[0],e[1]);function Pa(e){let t=0;for(let i=0;ie[1]!=l>e[1]&&e[0]<(r-o)*(e[1]-a)/(l-a)+o&&(i=!i)}return i}([r[0]+a[0]*l,r[1]+a[1]*l],e)&&(a=[-a[0],-a[1]]),a}function Ra(e){const t=e.length;if(t<3)return!1;for(let i=0;i(e[0]-n[0])*r[1]-(e[1]-n[1])*r[0],c=e=>(e[0]-n[0])*r[0]+(e[1]-n[1])*r[1],h=i,d=a-i;for(const t of e){const e=Math.abs(l(t));if(e<=i)continue;const n=c(t);n<=h||n>=d||eMath.abs(a+(e-p)/g*(r-a));s=Math.min(s,f(_),f(m))}}return s}function za(e,t,i){if(Di(e,t,i))return!0;if(Ci(e,t,i)||Ci(t,e,i))return!1;let s=0;try{const i=ni([[...e.map(e=>[e[0],e[1]]),[e[0][0],e[0][1]]]],[[...t.map(e=>[e[0],e[1]]),[t[0][0],t[0][1]]]]);for(const e of i)e?.[0]&&(s+=Ti(e[0]))}catch{return!1}return s>Math.max(1e-7,i*i)}function Fa(e,t,i){for(const s of t)for(let t=0;ti)continue;const c=(e.x-n[0])*l[0]+(e.y-n[1])*l[1];if(c-e.length/2>=-i&&c+e.length/2<=r+i)return!0}return!1}function Ea(e,t,i){const s=Math.abs(t[0]-e[0]),n=Math.abs(t[1]-e[1]);return s<=i&&n>i?"v":n<=i&&s>i?"h":null}function Na(e,t,i){return Math.abs(e[0]-t[0])<=i&&Math.abs(e[1]-t[1])<=i}function Oa(e,t,i,s,n){return Na(e,i,n)&&Na(t,s,n)||Na(e,s,n)&&Na(t,i,n)}function Ha(e,t,i,s,n){const o=Ea(e,t,n);return o&&Ea(i,s,n)===o?"h"===o?Math.abs(e[1]-i[1])>n||Math.abs(e[1]-s[1])>n?0:Math.max(0,Math.min(Math.max(e[0],t[0]),Math.max(i[0],s[0]))-Math.max(Math.min(e[0],t[0]),Math.min(i[0],s[0]))):Math.abs(e[0]-i[0])>n||Math.abs(e[0]-s[0])>n?0:Math.max(0,Math.min(Math.max(e[1],t[1]),Math.max(i[1],s[1]))-Math.max(Math.min(e[1],t[1]),Math.min(i[1],s[1]))):0}function La(e,t,i,s){const n=e.length,o=Ea(e[(t-1+n)%n],e[t],s),a=Ea(e[(t+1)%n],e[(t+2)%n],s),r="h"===i?"v":"h";return o===r&&a===r}function Ba(e){let t=1/0,i=1/0,s=-1/0,n=-1/0;for(const o of e)t=Math.min(t,o[0]),i=Math.min(i,o[1]),s=Math.max(s,o[0]),n=Math.max(n,o[1]);return[t,i,s,n]}function qa(e,t,i){const s=Ba(e),n=Ba(t);return s[2]n}const ja=(e,t)=>"h"===t?e[0]:e[1],Ua=(e,t)=>"h"===t?e[1]:e[0];function Ga(e,t,i,s,n){const o=e.find(e=>e.id===t);if(!o)return null;const a=o.poly[i],r=o.poly[(i+1)%o.poly.length],l=Ea(a,r,n);if(!l)return null;const c=0===s?r:a,h=0===s?a:r,d=ja(c,l),p=ja(h,l),u=Ua(c,l),_=function(e,t,i,s){const n=[];for(const o of e)for(let e=0;es||Math.abs(Ua(r,t)-i)>s)continue;const l=ja(a,t),c=ja(r,t),h=Math.min(l,c),d=Math.max(l,c);d-h>s&&n.push({roomId:o.id,edge:e,lo:h,hi:d})}return n.sort((e,t)=>e.lo-t.lo||e.hi-t.hi||e.roomId.localeCompare(t.roomId)||e.edge-t.edge)}(e,l,u,n),m=function(e,t,i,s){const n=[t,i];for(const o of e){const e=Math.max(t,o.lo),a=Math.min(i,o.hi);a-e>s&&n.push(e,a)}const o=[...new Set(n)].sort((e,t)=>e-t),a=[];for(let t=0;t+1r>e.lo-s&&re.roomId))].sort();a.push({lo:i,hi:n,owners:l})}return a}(_,Math.min(d,p),Math.max(d,p),n);return!m.length||m.some(e=>e.owners.length<1||e.owners.length>2)?null:{roomId:t,edge:i,movedEndpoint:s,axis:l,line:u,fixed:d,moving:p,intervals:_,baseline:m}}function Va(e,t,i){const s=[];for(const n of e.intervals){const o=t.polys[n.roomId];if(!o){s.push(n);continue}if(n.edge<0||n.edge>=o.length)continue;const a=o[n.edge],r=o[(n.edge+1)%o.length];if(Ea(a,r,i)!==e.axis||Math.abs(Ua(a,e.axis)-e.line)>i||Math.abs(Ua(r,e.axis)-e.line)>i)continue;const l=ja(a,e.axis),c=ja(r,e.axis),h=Math.min(l,c),d=Math.max(l,c);d-h>i&&s.push({...n,lo:h,hi:d})}return s}function Ka(e,t,i){return new Set(e.filter(e=>t>e.lo-i&&te.roomId)).size}function Ya(e,t,i){for(const s of t.sideOwnership){const t=e.polys[s.roomId];if(!t)return!1;const n=t[s.edge],o=t[(s.edge+1)%t.length];if(Ea(n,o,i)!==s.axis)return!1;const a=ja(0===s.movedEndpoint?n:o,s.axis),r=Va(s,e,i),l=(s.moving>=s.fixed?s.baseline[s.baseline.length-1]:s.baseline[0]).owners.length;if(l<1||l>2)return!1;const c=Math.min(s.fixed,s.moving,a),h=Math.max(s.fixed,s.moving,a),d=[c,h,s.fixed,s.moving,a];for(const e of s.intervals)d.push(e.lo,e.hi);for(const e of r)d.push(e.lo,e.hi);const p=[...new Set(d.filter(e=>e>=c&&e<=h))].sort((e,t)=>e-t),u=Math.min(s.fixed,s.moving),_=Math.max(s.fixed,s.moving),m=Math.min(s.fixed,a),g=Math.max(s.fixed,a);for(let e=0;e+1u-i&&o<_+i,c=o>m-i&&o2||d>2)return!1;if(a&&c){if(h!==d)return!1}else if(!a&&c){if(d!==l||h>0&&h!==d)return!1}else if(2===h?2!==d:d>1)return!1}}return!0}function Ja(e,t,i,s){const n=[i.n[0]*s,i.n[1]*s],o={polys:{},openings:{},movedSpans:{}};for(const t of i.roomIds){const s=e.find(e=>e.id===t),a=i.edgeByRoom[t];if(!s||null==a)continue;const r=(a+1)%s.poly.length;o.polys[t]=s.poly.map((e,t)=>t===a||t===r?Ma(e,n):[...e]),o.movedSpans[t]=[[Ma(s.poly[a],n),Ma(s.poly[r],n)]]}for(const e of t)i.movingOpeningIds.includes(e.id)&&(o.openings[e.id]=[e.x+n[0],e.y+n[1]]);return o}function Xa(e,t,i,s,n,o,a,r){if(!function(e,t,i,s){if(Ta([e.x,e.y],t,i)>2*s)return!1;const n=Da(Sa(i,t));if(n<=s)return!1;const o=[(i[0]-t[0])/n,(i[1]-t[1])/n],a=(e.x-t[0])*o[0]+(e.y-t[1])*o[1];return a>=-s&&a<=n+s}(e,t,i,r))return!0;if(Ta([e.x,e.y],s,n)>2*r)return!1;const l=0===o?s:n;return Da(Sa([e.x,e.y],l))>=e.length/2+a-r}function Za(e,t,i,s){const n=s.movingHalf||0;return"circle"===e.kind?Ta(e.center,t,i)2)return!1;const r=Ja(e,t,i,s);if(Object.keys(r.polys).length!==i.roomIds.length)return!1;if(!Ya(r,i,o))return!1;const l=new Set(i.roomIds),c=e=>r.polys[e.id]||e.poly;for(const s of i.roomIds){const l=e.find(e=>e.id===s),c=r.polys[s],h=i.edgeByRoom[s];if(!l||!c||c.length!==i.topology[s]||c.length!==l.poly.length||!Ra(c))return!1;const d=l.poly.length,p=(h-1+d)%d,u=[p,h,(h+1)%d];for(const e of u)if(pa(c[e],c[(e+1)%d]))return!1;const _=Pa(l.poly),m=Pa(c);if(Math.abs(m)e.id===t),s=r.polys[t];for(const n of e){if(n.id===t||l.has(n.id))continue;const e=c(n);if(!qa(i.poly,n.poly,o)||!qa(s,e,o))if(Ci(i.poly,n.poly,o)){if(!Ci(s,e,o))return!1}else if(Ci(n.poly,i.poly,o)){if(!Ci(e,s,o))return!1}else if(Ci(s,e,o)||Ci(e,s,o)||za(s,e,o))return!1}}e.find(e=>e.id===i.roomId);const h=r.polys[i.roomId],d=i.edgeByRoom[i.roomId],p=h[d],u=h[(d+1)%h.length];if(Math.abs(s)>o)for(const e of n.obstacles||[])if(Za(e,p,u,n))return!1;for(const e of t){if(!i.movingOpeningIds.includes(e.id))continue;const t=r.openings[e.id];if(!t||e.hosted)return!1;if(!Fa({...e,x:t[0],y:t[1]},[h],2*o))return!1}return!0}const er=new WeakMap;function tr(e,t,i){const s=i/t;return Ti(e)*s*s/1e4}function ir(e,t){return t?`${Math.round(10.7639*e)} ft²`:`${(Math.round(10*e)/10).toFixed(1)} m²`}const sr=e=>"number"==typeof e&&Number.isFinite(e),nr=(e,t)=>{const i=new Map;for(const s of e||[])!sr(s?.cm)||!t&&s.cm<=0||i.set(s.cm,(i.get(s.cm)||0)+1);return i},or=e=>[String(e),"см"].join(" ");function ar(e,t,i={}){if(i.allowClear)return[];const s=!0===i.exactMultiplicity,n=nr(e,s),o=nr(t,s),a=[];for(const[e,t]of n){const i=o.get(e)||0;0===i?a.push({invariant:"wall_records",kind:"lost",owner:or(e),reference:`было ${t}`,detail:"записи этой толщины исчезли целиком"}):s&&i!==t&&a.push({invariant:"wall_records",kind:"count",owner:or(e),reference:`было ${t}, стало ${i}`,detail:"изменилось число записей этой толщины"})}if(s)for(const[e,t]of o)n.has(e)||a.push({invariant:"wall_records",kind:"count",owner:or(e),reference:`было 0, стало ${t}`,detail:"появились записи новой толщины"});return a}class rr{constructor(){this._selectedRoomId=null,this._session=null,this._eligibility=null}get dragging(){return null!==this._session}ownsPointer(e){return this._session?.pointerId===e}get selectedRoomId(){return this._selectedRoomId}get snapshotIdentity(){return this._session?.snapshotIdentity||null}get activePointerId(){return this._session?.pointerId??null}get moved(){return!0===this._session?.moved}get delta(){return this._session?.delta||0}get rooms(){return this._session?.rooms||null}get openings(){return this._session?.openings||null}get plan(){return this._session?.plan||null}get preview(){return this._session?.accepted?.preview||null}get liveLabels(){return this._session?.accepted?.labels||null}selectRoom(e){this._selectedRoomId=e}restoreSelection(e){this._selectedRoomId=e}escapeIdle(){return this._selectedRoomId?(this._selectedRoomId=null,"selection-cleared"):"exit-tool"}resolve(e,t,i){this._eligibility&&this._eligibility.context===e||(this._eligibility={context:e,values:new Map});const s=this._eligibility.values.get(t);if(s)return s;const n=i();return this._eligibility.values.set(t,n),n}begin(e){return!this._session&&(this._session={pointerId:e.pointerId,start:[...e.start],roomId:e.roomId,plan:e.plan,options:e.options,rooms:e.rooms,openings:e.openings,snapshotIdentity:e.snapshotIdentity,before:e.before,moved:!1,delta:0,changedRoomIds:[...e.plan.roomIds],rejectionNotified:!1,wallUnionBefore:e.wallUnionBefore,accepted:null},!0)}move(e){const t=this._session;if(!t||t.pointerId!==e.pointerId)return{kind:"no-op"};const i=(s=t.start,n=e.point,o=t.plan.n,[s?.[0],s?.[1],n?.[0],n?.[1],o?.[0],o?.[1]].every(Number.isFinite)?(n[0]-s[0])*o[0]+(n[1]-s[1])*o[1]:0);var s,n,o;const a=e.snap([t.plan.a[0]+t.plan.n[0]*i,t.plan.a[1]+t.plan.n[1]*i]),r=(a[0]-t.plan.a[0])*t.plan.n[0]+(a[1]-t.plan.a[1])*t.plan.n[1],l=function(e,t,i,s,n,o){if(!Number.isFinite(s)||Math.abs(s)<1e-9)return 0;const a=Math.sign(s),r=Math.abs(s),l=Math.max(Math.abs(n),1e-6);let c=er.get(i);c&&c.opts===o||(c={opts:o,values:new Map},er.set(i,c));const h=c.values;let d=0;for(let s=Math.min(l,r),n=0;n<4096&&s<=r+1e-9;n++,s=Math.min(r,s+l)){const n=a*s,c=`${n.toFixed(9)}|${l.toFixed(9)}`;let p=h.get(c);if(void 0===p&&(p=Qa(e,t,i,n,o),h.size<4096&&h.set(c,p)),!p)break;if(d=n,Math.abs(s-r)<=1e-9)break}return d}(t.rooms,t.openings,t.plan,r,e.step,t.options);if(t.moved&&l===t.delta)return{kind:"no-op"};const c=Ja(t.rooms,t.openings,t.plan,l);let h;try{if(h=e.project(t.snapshotIdentity,c.polys,c.openings,t.changedRoomIds,t.rooms),!h.ok)return this._projectionRejected(t);if(ar(h.value.beforeWalls,h.value.afterWalls,{exactMultiplicity:!0}).length)return this._projectionRejected(t)}catch{return this._projectionRejected(t)}const d=t.accepted,p={preview:h.value.preview,labels:null,artifact:h.value.artifact,beforeWalls:h.value.beforeWalls,afterWalls:h.value.afterWalls};t.accepted=p;try{e.publish(p.preview,p.artifact),p.labels=e.measure(c,t.plan)}catch{t.accepted=d;try{e.publish(d?.preview||null,d?.artifact||null)}catch{}return this._projectionRejected(t)}return t.moved=!0,t.delta=l,{kind:"accepted",preview:h.value.preview,labels:p.labels,artifact:h.value.artifact}}finish(e){const t=this._session;if(!t||t.pointerId!==e.pointerId)return{kind:"no-op"};const i=t.accepted;let s;if(t.moved&&Math.abs(t.delta)>1e-9&&i)if(e.currentSnapshotIdentity!==t.snapshotIdentity)s={kind:"rejected",reason:"stale-snapshot"};else if(Qa(t.rooms,t.openings,t.plan,t.delta,t.options))if(ar(i.beforeWalls,i.afterWalls,{exactMultiplicity:!0}).length)s={kind:"rejected",reason:"wall-records"};else{let n=!1;try{n=e.validatePreview(i.preview)}catch{n=!1}s=n?{kind:"commit",preview:i.preview,before:t.before}:{kind:"rejected",reason:"invalid-candidate"}}else s={kind:"rejected",reason:"invalid-topology"};else s={kind:"no-op"};return this._session=null,"commit"===s.kind&&(this._eligibility=null),s}cancel(e,t){const i=this._session;return!i||void 0!==t&&i.pointerId!==t?{kind:"no-op"}:(this._session=null,this._eligibility=null,{kind:"cancelled",restoreWallUnion:e===i.snapshotIdentity?i.wallUnionBefore:null})}reset(){this._selectedRoomId=null,this._session=null,this._eligibility=null}_projectionRejected(e){const t=!e.rejectionNotified;return e.rejectionNotified=!0,{kind:"rejected",notify:t}}}const lr=(e,t)=>[(e[0]-t.x)/Math.max(1e-9,t.w)*t.stageWidth,(e[1]-t.y)/Math.max(1e-9,t.h)*t.stageHeight];function cr(e){const{poly:t,edge:i,text:s,view:n}=e,o=t[i],a=t[(i+1)%t.length],r=[(o[0]+a[0])/2,(o[1]+a[1])/2],l=function(e,t){const i=e[t],s=e[(t+1)%e.length],n=s[0]-i[0],o=s[1]-i[1],a=Math.hypot(n,o)||1;return(e=>{let t=0;for(let i=0;i=0?[-o/a,n/a]:[o/a,-n/a]}(t,i),c=Math.hypot(a[0]-o[0],a[1]-o[1])||1,h=[(a[0]-o[0])/c,(a[1]-o[1])/c],d=lr(r,n),p=lr(e.gearCenter,n),u=Math.max(34,7.2*s.length+12),_=Math.abs(l[0])>=Math.abs(l[1])?Math.max(28,u/2+4):Math.max(28,13),m=d[0]+l[0]*_,g=d[1]+l[1]*_,f=t=>{return i=m+h[0]*t,s=g+h[1]*t,n=u,o=18,a=p[0],r=p[1],l=e.gearWidthPx,c=e.gearHeightPx,2*Math.abs(i-a)=Math.abs(h[1])?h[0]:h[1])>0?-1:1,t=Math.max(n.stageWidth,n.stageHeight,64);for(let i=4;i<=t;i+=4){const t=i*e;if(!f(t)){v=t;break}const s=-t;if(!f(s)){v=s;break}}}const y=l[0]*_+h[0]*v,b=l[1]*_+h[1]*v,w=Math.hypot(y,b)||1,k=b/w*12,x=[r[0]+y/w*12*n.w/Math.max(1,n.stageWidth),r[1]+k*n.h/Math.max(1,n.stageHeight)];return{anchor:r,offsetXPx:y,offsetYPx:b,tangentOffsetPx:v,side:Math.abs(l[0])>=Math.abs(l[1])?l[0]<0?"left":"right":l[1]<0?"above":"below",leader:{a:r,b:x}}}function hr(e){const t=e%360;return t<0?t+360:t}function dr(e,t){const i=function(e,t){return hr(e+t)}(e,t)*Math.PI/180;return[Math.sin(i),-Math.cos(i)]}const pr=Object.freeze({dawn:Object.freeze({top:"#aabdd1",bottom:"#e8c8b7",horizon:"rgba(255,201,156,.56)",sun:"rgba(255,188,125,.78)",vignette:"rgba(65,72,99,.21)",outlineNear:"rgba(74,57,61,.25)",outlineMid:"rgba(255,238,224,.40)",outlineFar:"rgba(255,224,202,.18)"}),day:Object.freeze({top:"#dce9ef",bottom:"#cbdce3",horizon:"rgba(255,245,220,.45)",sun:"rgba(255,239,190,.72)",vignette:"rgba(65,91,105,.16)",outlineNear:"rgba(45,62,71,.28)",outlineMid:"rgba(255,255,255,.42)",outlineFar:"rgba(255,255,255,.20)"}),dusk:Object.freeze({top:"#48536c",bottom:"#9a7380",horizon:"rgba(242,156,114,.34)",sun:"rgba(255,167,113,.55)",vignette:"rgba(20,26,44,.39)",outlineNear:"rgba(238,219,225,.40)",outlineMid:"rgba(229,207,218,.26)",outlineFar:"rgba(215,190,205,.12)"}),night:Object.freeze({top:"#111a27",bottom:"#1f2f3e",horizon:"rgba(79,120,151,.16)",sun:"rgba(169,208,231,0)",vignette:"rgba(3,8,14,.58)",outlineNear:"rgba(218,238,249,.56)",outlineMid:"rgba(174,215,238,.30)",outlineFar:"rgba(136,194,226,.14)"})}),ur=e=>"number"==typeof e&&Number.isFinite(e),_r=(e,t,i)=>Math.min(i,Math.max(t,e));function mr(e){return e.elevation<=-6?"night":e.elevation>=6?"day":e.rising?"dawn":"dusk"}function gr(e){const t=(Math.floor(Number(e)||0)%1440+1440)%1440;return t>=300&&t<480?"dawn":t>=480&&t<1080?"day":t>=1080&&t<1260?"dusk":"night"}function fr(e){const t=mr(e),i=e.azimuth*Math.PI/180;return{sunX:50-42*Math.sin(i),sunY:78-_r(e.elevation,0,90)/90*64,sunOpacity:"night"===t?0:_r((e.elevation+6)/12,0,1)}}function vr(e){const t=(Math.floor(Number(e)||0)%1440+1440)%1440;if(t<300||t>=1260)return{sunX:50,sunY:78,sunOpacity:0};const i=(t-300)/960,s=(t-300)/120,n=(1260-t)/120;return{sunX:8+84*i,sunY:78-64*Math.sin(i*Math.PI),sunOpacity:Math.max(.18,Math.min(s,n,1))}}function yr(e,t=new Date){const i=function(e){const t=e?.states?.["sun.sun"]?.attributes;return t&&ur(t.azimuth)&&ur(t.elevation)&&"boolean"==typeof t.rising?{azimuth:hr(t.azimuth),elevation:t.elevation,rising:t.rising}:null}(e);if(i)return{phase:mr(i),source:"sun",...fr(i)};const s="number"==typeof t?t:function(e=new Date){return 60*e.getHours()+e.getMinutes()}(t);return{phase:gr(s),source:"clock",...vr(s)}}function br(e){return`${e.source}|${e.phase}|${e.sunX.toFixed(2)}|${e.sunY.toFixed(2)}|`+e.sunOpacity.toFixed(3)}const wr=[[-90,"#070c14"],[-12,"#070c14"],[-4,"#131a28"],[0,"#4a3527"],[10,"#e8ddcf"],[30,"#ffffff"],[90,"#ffffff"]],kr=e=>Math.min(1,Math.max(0,e));function xr(e,t,i=6){const s=e.angle*Math.PI/180,n=[Math.sin(s),-Math.cos(s)],o=s=>{const o=[e.x+n[0]*i*s,e.y+n[1]*i*s];return t.find(e=>e.poly.length>=3&&vi(o,e.poly))||null},a=o(1),r=o(-1);return a&&r?null:a||r?a?{normal:[-n[0],-n[1]],roomId:a.id}:{normal:n,roomId:r.id}:null}function $r(e,t,i){return i>0&&e[0]*t[0]+e[1]*t[1]>.05}function Sr(e,t,i,s){return[[e[0],e[1]],[t[0],t[1]],[t[0]+i[0]*s,t[1]+i[1]*s],[e[0]+i[0]*s,e[1]+i[1]*s]]}function Mr(e,t){try{const i=ni([[...e.map(e=>[e[0],e[1]]),[e[0][0],e[0][1]]]],[[...t.map(e=>[e[0],e[1]]),[t[0][0],t[0][1]]]]),s=[];for(const e of i){const t=e?.[0];!Array.isArray(t)||t.length<4||s.push(t.slice(0,t.length-1).map(e=>[e[0],e[1]]))}return s}catch{return[]}}function Cr(e,t,i,s,n,o,a){if(!(s>0))return[];const r=dr(i,n),l=[-r[0],-r[1]],c=function(e){const t=Math.min(90,Math.max(0,e));return.7*(.8+1.7*Math.pow(1-t/90,1.6))}(s),h=[];for(const i of t){if(!(i.length>0))continue;const t=xr(i,e);if(!t||!$r(t.normal,r,s))continue;const n=e.find(e=>e.id===t.roomId);if(!n)continue;const d=o&&o[t.roomId]||n.poly,p=i.angle*Math.PI/180,u=i.length/2,_=[-t.normal[0],-t.normal[1]],m=Math.max(0,a?.[i.id]||0),g=i.x+_[0]*m/2,f=i.y+_[1]*m/2,v=Math.cos(p)*u,y=Math.sin(p)*u,b=[g-v,f-y],w=[g+v,f+y],k=c*i.length,x=Mr(Sr(b,w,l,k),d);if(!x.length)continue;const $=l[0]*_[0]+l[1]*_[1];h.push({openingId:i.id,roomId:t.roomId,polys:x,a:b,b:w,dir:l,len:k,normal:_,depth:k*$})}return h}const Dr=e=>"number"==typeof e&&Number.isInteger(e)&&e>=0&&e<=359?e:null;function Pr(e,t){const i=Dr(t?.north_deg);return null!==i?i:Dr(e?.north_deg)}function Tr(e,t){const i=e=>"static"===e||"daynight"===e?e:null;return i(t?.bg_mode)??i(e?.bg_mode)??"static"}function Ir(e,t){const i=t?.sun_rays;return"boolean"==typeof i?i:!0===e?.sun_rays}function Rr(e){const t=e?.states?.["sun.sun"]?.attributes,i=Number(t?.azimuth),s=Number(t?.elevation);return Number.isFinite(i)&&Number.isFinite(s)?{azimuth:i,elevation:s}:null}const Ar=["dawn","day","dusk","night"];function zr(e){if(!e)return"";const t=pr[e.phase];return[`--hp-day-cycle-outline-near:${t.outlineNear}`,`--hp-day-cycle-outline-mid:${t.outlineMid}`,`--hp-day-cycle-outline-far:${t.outlineFar}`].join(";")}function Fr(e,t=1){if(!e)return G;const i=[`--hp-day-cycle-sun-x:${e.sunX.toFixed(2)}%`,`--hp-day-cycle-sun-y:${e.sunY.toFixed(2)}%`,`--hp-day-cycle-sun-opacity:${e.sunOpacity.toFixed(3)}`,`opacity:${Math.min(1,Math.max(0,t)).toFixed(4)}`].join(";");return W`
${Ar.map(t=>{const i=pr[t],s=`background:radial-gradient(ellipse at 50% 88%, ${i.horizon} 0%, transparent 54%),linear-gradient(180deg, ${i.top} 0%, ${i.bottom} 100%);box-shadow:inset 0 0 90px ${i.vignette}`;return W`
`})}
-
`}const Er={color:"#607d8b",opacity:1,widthCm:3.6,fill:!1,fillColor:"#607d8b",fillOpacity:.25},Nr=(e,t=1)=>{const i=Number(e);return Number.isFinite(i)?Math.min(1,Math.max(0,i)):t},Or=e=>{let t=Number(e);return Number.isFinite(t)?(t=(t%360+360)%360,t>180?t-360:t):0};function Lr(e,t,i){return Or(t)?[e.x,e.y]:i([e.x,e.y])}const Hr=(e,t,i)=>{const s=Number(e),n=Number.isFinite(t)&&t>0?t:5;return Number.isFinite(s)&&s>0?s/n*i:0},Br=(e,t,i)=>{const s=Number(e),n=Number.isFinite(t)&&t>0?t:5;return Number.isFinite(s)&&i>0?s/i*n:0},qr=(e,t,i,s=Er.widthCm)=>{const n=Number(e?.width_cm);if(Number.isFinite(n)&&n>0)return n;const o=Number(e?.width);return Number.isFinite(o)&&o>0?Br(o,t,i):s};function Wr(e,t){return{color:e.color,opacity:Nr(e.opacity),width_cm:Math.max(.1,Math.min(100,Number(e.widthCm)||.1)),...t?{fill:e.fill,fill_color:e.fillColor,fill_opacity:Nr(e.fillOpacity,.25)}:{}}}function jr(e){const t=e.x+e.w/2,i=e.y+e.h/2,s=Or(e.angle)*Math.PI/180,n=Math.cos(s),o=Math.sin(s),a=(e,s)=>{const a=e-t,r=s-i;return[t+a*n-r*o,i+a*o+r*n]};return[a(e.x,e.y),a(e.x+e.w,e.y),a(e.x+e.w,e.y+e.h),a(e.x,e.y+e.h)]}function Ur(e){const t=jr(e),i=(e,t)=>[(e[0]+t[0])/2,(e[1]+t[1])/2],s=[(t[0][0]+t[2][0])/2,(t[0][1]+t[2][1])/2];return{points:[...t,i(t[0],t[1]),i(t[1],t[2]),i(t[2],t[3]),i(t[3],t[0]),s],segments:t.map((e,i)=>({a:e,b:t[(i+1)%4]}))}}function Gr(e,t,i,s,n,o,a,r){const l=Or(e.angle)*Math.PI/180,c=Math.cos(l),h=Math.sin(l),d=-Math.sin(l),p=Math.cos(l),u=e.x+e.w/2,_=e.y+e.h/2,m=t>0?-e.w/2:e.w/2,g=i>0?-e.h/2:e.h/2,f=u+m*c+g*d,v=_+m*h+g*p,y=s-f,b=n-v;let w=(y*c+b*h)*(t>0?1:-1),k=(y*d+b*p)*(i>0?1:-1),x=null;if(o){const t=w/Math.max(e.w,r),i=k/Math.max(e.h,r);x=Math.max(r/Math.max(e.w,r),r/Math.max(e.h,r),t,i),w=e.w*x,k=e.h*x}if(a>0)if(o){const t=Math.max(1,Math.round(e.w/a)),i=Math.max(1,Math.round(e.h/a));if(Math.abs(e.w-t*a)<1e-6&&Math.abs(e.h-i*a)<1e-6){const s=(e,t)=>{let i=Math.abs(e),s=Math.abs(t);for(;s;)[i,s]=[s,i%s];return Math.max(1,i)},n=1/s(t,i),o=Math.max(r/e.w,r/e.h),a=Math.max(o,Math.round((x??1)/n)*n);w=e.w*a,k=e.h*a}else{e.w>=e.h?(w=Math.round(w/a)*a,k=w*(e.h/Math.max(e.w,r))):(k=Math.round(k/a)*a,w=k*(e.w/Math.max(e.h,r)))}}else w=Math.round(w/a)*a,k=Math.round(k/a)*a;w=Math.max(r,w),k=Math.max(r,k);return{x:f+(t>0?w/2:-w/2)*c+(i>0?k/2:-k/2)*d-w/2,y:v+(t>0?w/2:-w/2)*h+(i>0?k/2:-k/2)*p-k/2,w:w,h:k,angle:Or(e.angle)||void 0}}const Vr=(e,t,i)=>{const s=i[0]-t[0],n=i[1]-t[1],o=s*s+n*n;if(o<1e-12)return[...t];const a=Math.max(0,Math.min(1,((e[0]-t[0])*s+(e[1]-t[1])*n)/o));return[t[0]+s*a,t[1]+n*a]};const Kr=10**9,Yr=240,Jr=1e-4;function Xr(e){if(Array.isArray(e))return e.map(e=>Xr(e));if(null!==e&&"object"==typeof e){const t={};for(const[i,s]of Object.entries(e))t[i]=Xr(s);return t}return e}function Zr(e){if("number"!=typeof e||!Number.isFinite(e))return e;const t=(e<0||Object.is(e,-0)?-1:1)*(Math.floor(Math.abs(e)*Kr+.5)/Kr);return 0===t?0:t}function Qr(e){if("number"!=typeof e||!Number.isFinite(e))return e;const t=e*Yr,i=Math.round(t);if(Math.abs(t-i)null!==tl(e)):[]}function sl(e,t){for(const i of t)Object.prototype.hasOwnProperty.call(e,i)&&(e[i]=Zr(e[i]))}function nl(e,t){for(const i of t)Object.prototype.hasOwnProperty.call(e,i)&&(e[i]=Qr(e[i]))}function ol(e){if(Array.isArray(e))for(let t=0;t{for(const n of s){const s=t[n];"number"==typeof s&&Number.isFinite(s)&&i(s,e)}},s=t=>{if(Array.isArray(t))for(let s=0;s{if(Array.isArray(e))for(const t of e)s(t)};for(const i of il(e.rooms))t(i,["x","y","w","h"]),n(i.poly);for(const t of il(e.walls))s(t.a),s(t.b);for(const t of il(e.wall_segments))s(t.a),s(t.b);for(const i of il(e.openings))t(i,["x","y"]);for(const i of il(e.decor))"line"===i.kind?t(i,["x1","y1","x2","y2"]):"rect"===i.kind||"ellipse"===i.kind||"furniture"===i.kind?t(i,["x","y","w","h"]):"text"===i.kind&&t(i,["x","y"]);for(const t of il(e.room_drafts))n(t.points);for(const t of il(e.partitions))s(t.a),s(t.b);for(const t of il(e.wall_columns))s(t.center);for(const t of il(e.open_spans))s(t.a),s(t.b)}const n=tl(t);if(!n)return;const o=new Map;if(s)for(const e of il(s.spaces))null!=e.id&&o.set(String(e.id),e);for(const e of Object.values(n)){const t=tl(e);if(!t)continue;const s=null!=t.s&&o.get(String(t.s))||null;for(const e of["x","y"]){const n=t[e];"number"==typeof n&&Number.isFinite(n)&&i(n,s)}}}function ll(e){const t=Number(e?.cell_cm);return t>0?t:5}function cl(e,t={}){const i={canonicalized:0,far:0,maxShift:0,maxShiftCm:0,spaces:[],bySpace:new Map},s=il(tl(e)?.spaces);let n=5;for(const e of s)n=Math.max(n,ll(e));rl(e,t,(e,t)=>{const s=e*Yr,o=Math.abs(s-Math.round(s)),a=Qr(e),r=o>0&&o=Jr))return;const l=r&&"number"==typeof a?Math.abs(a-e):0;if(r?i.canonicalized++:i.far++,i.maxShift=Math.max(i.maxShift,l),i.maxShiftCm=Math.max(i.maxShiftCm,l*Yr*(t?ll(t):n)),!t?.id||!r)return;const c=String(t.id);let h=i.bySpace.get(c);h||(h={spaceId:c,space:String(t.title||c),canonicalized:0,far:0,maxShift:0,maxShiftCm:0},i.bySpace.set(c,h)),h.canonicalized++,h.maxShift=Math.max(h.maxShift,l),h.maxShiftCm=Math.max(h.maxShiftCm,l*Yr*ll(t))}),i.bySpace.size&&rl(e,t,(e,t)=>{if(!t?.id)return;const s=i.bySpace.get(String(t.id));if(!s)return;const n=e*Yr;Math.abs(n-Math.round(n))>=Jr&&s.far++}),i.spaces=[...i.bySpace.values()];const{bySpace:o,...a}=i;return a}function hl(e){return function(e){const t=e,i=tl(t);i&&nl(i,["x","y"]);return t}(Xr(e))}function dl(e){const t=e,i=tl(t);if(!i)return t;for(const e of Object.values(i)){const t=tl(e);t&&nl(t,["x","y"])}return t}function pl(e){const t=e,i=tl(t);if(!i)return t;for(const e of il(i.spaces)){sl(e,["plan_x","plan_y","plan_scale","plan_scale_x","plan_scale_y","plan_angle"]);for(const t of il(e.rooms))nl(t,["x","y","w","h"]),al(t.poly);for(const t of il(e.walls))ol(t.a),ol(t.b);for(const t of il(e.wall_segments))ol(t.a),ol(t.b);for(const t of il(e.openings)){nl(t,["x","y"]),sl(t,["angle","length"]);const e=tl(t.host);e&&sl(e,["t"])}for(const t of il(e.decor))"line"===t.kind?nl(t,["x1","y1","x2","y2"]):"rect"===t.kind||"ellipse"===t.kind||"furniture"===t.kind?(nl(t,["x","y","w","h"]),sl(t,["angle"])):"text"===t.kind&&(nl(t,["x","y"]),sl(t,["scale","angle"]));for(const t of il(e.room_drafts))al(t.points);for(const t of il(e.partitions))ol(t.a),ol(t.b);for(const t of il(e.wall_columns))ol(t.center),"square"===t.shape&&sl(t,["angle"]);for(const t of il(e.open_spans))ol(t.a),ol(t.b)}for(const e of il(i.markers))sl(e,["angle"]);return t}const ul=15;function _l(e,t,i,s,n){const o=i[0]-e[0],a=i[1]-e[1],r=Math.hypot(o,a);if(!(r>0)||r<=n+1e-9)return null;const l=o/r,c=a/r,h=t=>{const s=(t[0]-e[0])*l+(t[1]-e[1])*c,o=(n-s)/(r-s);return!Number.isFinite(o)||o<-1e-9||o>1+1e-9?null:[t[0]+(i[0]-t[0])*o,t[1]+(i[1]-t[1])*o]},d=h(t),p=h(s);return d&&p?[[e[0],e[1]],t,d,p,s]:null}const ml=Math.sin(.25*Math.PI/180);function gl(e,t){return Number.isFinite(e)&&e>0&&Number.isFinite(t)&&t>0&&e*t<3}function fl(e){const t=Number(e)>0?Number(e):5;if(5===t)return 8;const i=5/t*8;return Math.min(80,Math.max(.5,i))}function vl(e,t){return Number.isFinite(e)&&e>0&&Number.isFinite(t)&&t>0&&e*t<2}function yl(e){return Number.isFinite(e)?Math.max(1,Math.min(100,e)):1}function bl(e,t){return!Number.isFinite(e)||e<0?"":String(t?Math.round(e/2.54*100)/100:Math.round(100*e)/100)}function wl(e,t,i){if(!Number.isFinite(e)||e<=0)return 0;const s=Number(t)>0?Number(t):5;return yl(e)/s*i}function kl(e,t){return t>0&&Number.isFinite(e)?Math.round(e/t)*t:e}function xl(e){return Math.max(1e-6*Math.abs(e),1e-9)}function $l(e,t){if(!(t>0&&Number.isFinite(e)))return e;const i=kl(e,t);return Math.abs(i-e)<=xl(t)?i:e}function Sl(e,t){let i=t[0]-e[0],s=t[1]-e[1];const n=Math.hypot(i,s);return n<1e-12?[1,0]:(i/=n,s/=n,(i<-1e-12||Math.abs(i)<=1e-12&&s<0)&&(i=-i,s=-s),[i,s])}function Ml(e,t,i){const s=[$l(e[0],i),$l(e[1],i)],n=[$l(t[0],i),$l(t[1],i)],o=kl((s[0]+n[0])/2,i),a=kl((s[1]+n[1])/2,i),[r,l]=Sl(s,n);let c=Math.atan2(l,r);c<0&&(c+=Math.PI);const h=Math.round(1800*c)/1800,d=i>0&&i<.01?6:i<1?4:2;return`${o.toFixed(d)},${a.toFixed(d)}@${h.toFixed(4)}`}function Cl(e,t,i,s){return 1===s?Ml(e,t,i):Ml([e[0]/s,e[1]/s],[t[0]/s,t[1]/s],i)}function Dl(e,t){if(!Array.isArray(e.a)||!Array.isArray(e.b)||e.a.length<2||e.b.length<2)return null;const i=[Number(e.a[0]),Number(e.a[1]),Number(e.b[0]),Number(e.b[1])];if(!i.every(Number.isFinite))return null;const s=t>0?t:1;return[[i[0]*s,i[1]*s],[i[2]*s,i[3]*s]]}function Pl(e,t,i,s,n){const o=n>0?n:1;return{key:Cl(e,t,s,o),cm:yl(i),a:[e[0]/o,e[1]/o],b:[t[0]/o,t[1]/o]}}function Tl(e,t){const i=t>0?t:1,s=[];for(const t of e){const e=t.key.lastIndexOf("@");if(e<0)continue;const[n,o]=t.key.slice(0,e).split(",").map(Number),a=Number(t.key.slice(e+1));[n,o,a].every(Number.isFinite)&&s.push({w:t,x:n*i,y:o*i,ang:a})}return s}function Il(e,t){const[i,s]=Sl(e,t);let n=Math.atan2(s,i);return n<0&&(n+=Math.PI),n}function Rl(e,t){let i=Math.abs(e-t);return i>Math.PI/2&&(i=Math.PI-i),i<.02}function Al(e,t,i,s,n=1){if(!e?.length)return null;const o=Cl(t,i,s,n),a=e.find(e=>e.key===o);if(a)return a;const r=n>0?n:1,l=xl(s)*r,c=(e,t)=>Math.abs(e[0]-t[0])<=l&&Math.abs(e[1]-t[1])<=l;for(const s of e){const e=Dl(s,r);if(e&&(c(e[0],t)&&c(e[1],i)||c(e[0],i)&&c(e[1],t)))return s}const h=(t[0]+i[0])/2,d=(t[1]+i[1])/2,p=Il(t,i),u=Math.max(.5*s,1e-9)*r;for(const t of Tl(e,r))if(Rl(t.ang,p)&&Math.hypot(t.x-h,t.y-d)<=u)return t.w;return null}function zl(e,t,i,s,n=1){const o=Al(e,t,i,s,n);if(o&&o.cm>0)return yl(o.cm);const a=function(e,t,i,s,n){if(!e?.length)return null;const o=n>0?n:1,a=Math.hypot(i[0]-t[0],i[1]-t[1]);if(a<1e-12)return null;const r=Il(t,i),l=Math.max(.5*s,1e-9)*o;let c=null;for(const s of e){if(!(s.cm>0))continue;const e=Dl(s,o);if(!e)continue;const n=Math.hypot(e[1][0]-e[0][0],e[1][1]-e[0][1]);if(n<1e-12||!Rl(Il(e[0],e[1]),r))continue;if(bc(t[0],t[1],e[0][0],e[0][1],e[1][0],e[1][1])>l||bc(i[0],i[1],e[0][0],e[0][1],e[1][0],e[1][1])>l)continue;if(n+l(o.has(e.key)||(e=>{const t=Dl(e,s);if(!t)return!1;const[i,o]=t,r=o[0]-i[0],c=o[1]-i[1],h=Math.hypot(r,c);if(h<=l)return!1;if(!a.some(e=>{const t=[e[0],e[1]],s=[e[2],e[3]];return Rl(Il(i,o),Il(t,s))&&bc(i[0],i[1],t[0],t[1],s[0],s[1])<=l&&bc(o[0],o[1],t[0],t[1],s[0],s[1])<=l}))return!1;const d=(n||[]).some(e=>{const t=[e[0],e[1]],s=[e[2],e[3]];if(!Rl(Il(i,o),Il(t,s)))return!1;const n=e=>Math.abs((e[0]-i[0])*c-(e[1]-i[1])*r)/h;if(n(t)>l||n(s)>l)return!1;const a=h*h,d=((t[0]-i[0])*r+(t[1]-i[1])*c)/a,p=((s[0]-i[0])*r+(s[1]-i[1])*c)/a;return Math.min(1,Math.max(d,p))-Math.max(0,Math.min(d,p))>l/h});return!d})(e))&&e.cm>=1&&e.cm<=100)}function El(e,t,i,s=8){const[n,o]=Sl(e,t);let a=Math.atan2(o,n);a<0&&(a+=Math.PI);let r=i*Math.PI/180%Math.PI;r<0&&(r+=Math.PI);let l=Math.abs(a-r);return l>Math.PI/2&&(l=Math.PI-l),l<=s*Math.PI/180}function Nl(e,t,i,s,n=1,o="affine",a){if(!e?.length)return[];if(t.length!==i.length)return"fixed-topology"===o&&a?.(),e.slice();const r=n>0?n:1,l=Math.max(.5*s,1e-9)*r,c=Math.max(s*r*1e-6,1e-9),h=[],d=new Map,p=new Map,u=(e,t,i)=>{const s=e.get(t)||new Set;s.add(i),e.set(t,s)};for(let e=0;e[e[0]+(t[0]-e[0])*i,e[1]+(t[1]-e[1])*i],m=(e,t)=>Math.hypot(e[0]-t[0],e[1]-t[1])<=c,g=(e,t)=>{if("fixed-topology"===o){const i=t.na[0]-t.oa[0],s=t.na[1]-t.oa[1],n=t.nb[0]-t.ob[0],o=t.nb[1]-t.ob[1];return Math.hypot(i-n,s-o)<=c?[e[0]+i,e[1]+s]:m(e,t.oa)?[...t.na]:m(e,t.ob)?[...t.nb]:[...e]}const i=Math.max(0,Math.min(1,((e[0]-t.oa[0])*t.dx+(e[1]-t.oa[1])*t.dy)/t.len2));return _(t.na,t.nb,i)},f=(e,t)=>{const[i,s]=Sl(e,t);return(t[0]-e[0])*i+(t[1]-e[1])*s>=0?[[...e],[...t]]:[[...t],[...e]]},v=[],y=[],b=(e,t,i)=>{if(Math.hypot(t[0]-e[0],t[1]-e[1])<=c)return;const[n,o]=f(e,t),a=yl(i);if(y.some(e=>e.entry.cm===a&&m(e.span[0],n)&&m(e.span[1],o)))return;const l=Pl(n,o,a,s,r);v.push(l),y.push({entry:l,span:[n,o]})};for(const t of e){const e=Dl(t,r);if(e){const[i,s]=f(e[0],e[1]),n=s[0]-i[0],a=s[1]-i[1],r=n*n+a*a,d=Math.sqrt(r);if(d<=c){v.push({...t,cm:yl(t.cm)});continue}const p=[];for(const e of h){if(!Rl(Il(i,s),Il(e.oa,e.ob)))continue;const t=e=>Math.abs((e[0]-i[0])*a-(e[1]-i[1])*n)/d;if(t(e.oa)>l||t(e.ob)>l)continue;const o=((e.oa[0]-i[0])*n+(e.oa[1]-i[1])*a)/r,h=((e.ob[0]-i[0])*n+(e.ob[1]-i[1])*a)/r,u=Math.max(0,Math.min(o,h)),_=Math.min(1,Math.max(o,h));(_-u)*d>c&&p.push({lo:u,hi:_,move:e})}if(!p.length){"fixed-topology"===o?v.push({...t}):b(i,s,t.cm);continue}const u=[0,1,...p.flatMap(({lo:e,hi:t})=>[e,t])].sort((e,t)=>e-t).filter((e,t,i)=>0===t||Math.abs(e-i[t-1])*d>c),y=[];for(let e=0;e+1r>=e.lo-1e-12&&r<=e.hi+1e-12);if(!l.length){y.push([o,a]);continue}const h=[g(o,l[0].move),g(a,l[0].move)],f=l.slice(1).some(e=>{const t=g(o,e.move),i=g(a,e.move);return!m(h[0],t)||!m(h[1],i)});y.push(f?[o,a]:h)}const w=(e,t)=>{const i=e[1][0]-e[0][0],s=e[1][1]-e[0][1],n=t[1][0]-t[0][0],o=t[1][1]-t[0][1],a=Math.hypot(i,s);return!(a<=c||i*n+s*o<=0)&&Math.abs(i*o-s*n)/a<=c},k=[];for(const e of y){const t=k[k.length-1];t&&m(t[1],e[0])&&w(t,e)?t[1]=e[1]:k.push([[...e[0]],[...e[1]]])}if("fixed-topology"===o&&1===k.length){const[i,s]=k[0];if(m(i,e[0])&&m(s,e[1])||m(i,e[1])&&m(s,e[0])){v.push({...t});continue}}for(const[e,i]of k)b(e,i,t.cm);continue}if("fixed-topology"===o){const e=p.get(t.key);if(1===e?.size){const i=[...e][0];v.push(i===t.key?{...t}:{...t,key:i});continue}const i=[Tl([t],r)[0]];1!==r&&i.push(Tl([t],1)[0]);const s=i.filter(Boolean).some(e=>h.some(t=>{if(!Rl(e.ang,Il(t.oa,t.ob)))return!1;const i=((e.x-t.oa[0])*t.dx+(e.y-t.oa[1])*t.dy)/t.len2;return i>=-1e-6&&i<=1.000001&&bc(e.x,e.y,t.oa[0],t.oa[1],t.ob[0],t.ob[1])<=l}));((e?.size||0)>1||s)&&a?.(),v.push({...t});continue}let i="";const n=d.get(t.key);if(1===n?.size&&(i=[...n][0]),!i){const e=Tl([t],r)[0];if(e){const t=new Set;for(const i of h){if(!Rl(e.ang,Il(i.oa,i.ob)))continue;const n=((e.x-i.oa[0])*i.dx+(e.y-i.oa[1])*i.dy)/i.len2;if(n<-1e-6||n>1.000001)continue;if(bc(e.x,e.y,i.oa[0],i.oa[1],i.ob[0],i.ob[1])>l)continue;const o=g([e.x,e.y],i),[a,c]=Sl(i.na,i.nb),h=Math.max(s*r,1e-6);t.add(Cl([o[0]-a*h,o[1]-c*h],[o[0]+a*h,o[1]+c*h],s,r))}1===t.size&&(i=[...t][0])}}v.push({...t,key:i||t.key,cm:yl(t.cm)})}return v}function Ol(e,t,i,s,n=1,o="affine"){return Nl(e,t,i,s,n,o)}function Ll(e,t,i,s=1,n=[]){const o=s>0?s:1,a=Math.abs(i),r=Math.max(a*o*Jr,1e-9),l=(n||[]).flatMap(e=>{const t=Dl(e,o);return t?t.map(e=>[...e]):[]}),c=e=>e.every((e,t)=>(e=>{if(!(a>0))return!0;const t=e/o/a;return Math.abs(t-Math.round(t))Math.abs(e-i[t])<=r)),h=[],d=e=>JSON.stringify([e.key,e.cm,e.a,e.b]);for(const i of e||[]){const e=Dl(i,o);if(!e)continue;const[s,n]=e;if(![s[0],s[1],n[0],n[1]].every(Number.isFinite)||!c(s)||!c(n)){h.push(d(i));continue}const a=n[0]-s[0],l=n[1]-s[1],p=Math.hypot(a,l);if(p<=r){h.push(d(i));continue}const u=a/p,_=l/p,m=[];for(const e of t){const[t,i]=e;if(![t?.[0],t?.[1],i?.[0],i?.[1]].every(Number.isFinite))continue;const n=e=>Math.abs((e[0]-s[0])*_-(e[1]-s[1])*u);if(n(t)>r||n(i)>r)continue;const o=(t[0]-s[0])*u+(t[1]-s[1])*_,a=(i[0]-s[0])*u+(i[1]-s[1])*_,l=Math.max(0,Math.min(o,a)),c=Math.min(p,Math.max(o,a));c-l>r&&m.push([l,c])}m.sort((e,t)=>e[0]-t[0]||e[1]-t[1]);let g=0;for(const[e,t]of m){if(e>g+r)break;if(g=Math.max(g,t),g>=p-r)break}ge.key!==a);return null==s||s<1?r:[...r,Pl(t,i,s,n,o)]}function Bl(e,t,i,s,n,o=[],a=1){let r=e?e.slice():[];for(const e of function(e,t,i,s,n=1,o=[]){const a=ac(e,t,i,s,n,o);if(!a)return[];const r=[];for(let e=0;e0||(c=Hl(c,t,i,s,n,a)))}return c}function Wl(e){const{a:t,b:i,halfDepth:s}=e;if(!Array.isArray(t)||!Array.isArray(i)||t.length<2||i.length<2||![t[0],t[1],i[0],i[1]].every(Number.isFinite))return null;const n=i[0]-t[0],o=i[1]-t[1],a=Math.hypot(n,o);if(!(a>1e-9&&s>0&&Number.isFinite(s)))return null;const r=-o/a*s,l=n/a*s;return[[t[0]+r,t[1]+l],[i[0]+r,i[1]+l],[i[0]-r,i[1]-l],[t[0]-r,t[1]-l]]}function jl(e,t,i){return Math.hypot(e[0]-t[0],e[1]-t[1])<=i}function Ul(e,t,i){const s=t.b[0]-t.a[0],n=t.b[1]-t.a[1],o=s*s+n*n;if(!(o>i*i))return!1;const a=((e[0]-t.a[0])*s+(e[1]-t.a[1])*n)/o;if(!(a>0&&a<1))return!1;const r=[t.a[0]+s*a,t.a[1]+n*a];return Math.hypot(e[0]-r[0],e[1]-r[1])<=i}function Gl(e,t,i,s){const n=Math.hypot(t,i);if(!(n>1e-9&&s>0))return;const o=[t/n,i/n],a=e.find(e=>Math.abs(e.u[0]*o[1]-e.u[1]*o[0])<1e-9&&e.u[0]*o[0]+e.u[1]*o[1]>1-1e-9);a?a.halfDepth=Math.max(a.halfDepth,s):e.push({u:o,halfDepth:s})}function Vl(e,t){try{const i=oi(xc(e),xc(t));let s=null,n=0;for(const e of i||[]){const t=e?.[0]||[],i=Math.abs(Ql(t));t.length>=4&&i>n&&(n=i,s=t.slice(0,-1).map(e=>[e[0],e[1]]))}return s}catch{return null}}function Kl(e,t=1e-6){const i=(e||[]).map((e,t)=>({segment:e,index:t})).filter(({segment:e})=>e&&Array.isArray(e.a)&&Array.isArray(e.b)&&e.a.length>=2&&e.b.length>=2&&e.a.every(Number.isFinite)&&e.b.every(Number.isFinite)&&Number.isFinite(e.halfDepth)&&e.halfDepth>0&&Math.hypot(e.b[0]-e.a[0],e.b[1]-e.a[1])>1e-9);if(i.length<2)return[];const s=Math.max(Number.isFinite(t)?t:0,1e-9),n=i.flatMap(({segment:e})=>[e.a,e.b]).map(e=>[e[0],e[1]]).sort((e,t)=>e[0]-t[0]||e[1]-t[1]),o=[];for(const e of n)o.some(t=>jl(t,e,s))||o.push(e);const a=[];for(const e of o){const t=[];let n=!1;for(const{segment:o,index:a}of i){const i=Math.hypot(o.b[0]-o.a[0],o.b[1]-o.a[1]);jl(e,o.a,s)?t.push({u:[(o.b[0]-o.a[0])/i,(o.b[1]-o.a[1])/i],halfDepth:o.halfDepth,length:i,index:a}):jl(e,o.b,s)?t.push({u:[(o.a[0]-o.b[0])/i,(o.a[1]-o.b[1])/i],halfDepth:o.halfDepth,length:i,index:a}):Ul(e,o,s)&&(n=!0)}if(n||2!==t.length)continue;const[o,r]=t,l=o.u[0]*r.u[1]-o.u[1]*r.u[0];if(Math.abs(l)<1e-9)continue;const c=l<0?1:-1,h=[-o.u[1],o.u[0]],d=[-r.u[1],r.u[0]],p=[e[0]+h[0]*o.halfDepth*c,e[1]+h[1]*o.halfDepth*c],u=[e[0]-d[0]*r.halfDepth*c,e[1]-d[1]*r.halfDepth*c];if(!ic(p,o.u,u,r.u))continue;const _=[[o,r,u,[d[0]*-c,d[1]*-c]],[r,o,p,[h[0]*c,h[1]*c]]];for(const[t,,i,n]of _){const o=Math.min(2*t.halfDepth,t.length),r=[-t.u[1]*t.halfDepth,t.u[0]*t.halfDepth],l=[[e[0]+r[0],e[1]+r[1]],[e[0]+t.u[0]*o+r[0],e[1]+t.u[1]*o+r[1]],[e[0]+t.u[0]*o-r[0],e[1]+t.u[1]*o-r[1]],[e[0]-r[0],e[1]-r[1]]],c=e=>(e[0]-i[0])*n[0]+(e[1]-i[1])*n[1],h=[];for(let e=0;e=-1e-12&&h.push(t),s>1e-12&&n<-1e-12||s<-1e-12&&n>1e-12){const e=s/(s-n);h.push([t[0]+(i[0]-t[0])*e,t[1]+(i[1]-t[1])*e])}}h.length>=3&&Math.abs(Ql(h))>s*s&&a.push({segmentIndex:t.index,wedge:h})}}return a}function Yl(e,t=1e-6){const i=(e||[]).filter(e=>e&&Array.isArray(e.a)&&Array.isArray(e.b)&&e.a.length>=2&&e.b.length>=2&&e.a.every(Number.isFinite)&&e.b.every(Number.isFinite)&&Number.isFinite(e.halfDepth)&&e.halfDepth>0&&Math.hypot(e.b[0]-e.a[0],e.b[1]-e.a[1])>1e-9);if(i.length<2)return[];const s=Math.max(Number.isFinite(t)?t:0,1e-9),n=i.flatMap(e=>[e.a,e.b]).map(e=>[e[0],e[1]]).sort((e,t)=>e[0]-t[0]||e[1]-t[1]),o=[];for(const e of n)o.some(t=>jl(t,e,s))||o.push(e);const a=[],r=i.map((e,t)=>({roomId:"",a:[e.a[0],e.a[1]],b:[e.b[0],e.b[1]],key:`join-${t}`,kind:"outer",cm:0,open:!1,half:e.halfDepth})),l=dc(r,s);for(const e of pc(l).fans)a.push(e);const c=e=>!!uc(l,e);for(const e of o){if(c(e))continue;const t=[];for(const n of i)jl(e,n.a,s)?Gl(t,n.b[0]-n.a[0],n.b[1]-n.a[1],n.halfDepth):jl(e,n.b,s)?Gl(t,n.a[0]-n.b[0],n.a[1]-n.b[1],n.halfDepth):Ul(e,n,s)&&(Gl(t,n.a[0]-e[0],n.a[1]-e[1],n.halfDepth),Gl(t,n.b[0]-e[0],n.b[1]-e[1],n.halfDepth));if(!(t.length<2)){t.sort((e,t)=>Math.atan2(e.u[1],e.u[0])-Math.atan2(t.u[1],t.u[0])||e.halfDepth-t.halfDepth);for(let i=0;is*s&&a.push(m)}}}return a}function Jl(e,t,i,s){if(!(t>0)||!e||e.length<2)return"";if(i&&e.length>=3){let i=e;const n=e[e.length-1];if(e.length>=4&&Math.hypot(e[0][0]-n[0],e[0][1]-n[1])<1e-9&&(i=e.slice(0,-1)),i.length>=3){const e=i.map((e,i)=>s?.[i]||t),n=Hc(i,e),o=sc(i,e);if(n&&o)return`${nc(n)} ${nc(oc(o))}`}}const n=[];for(let i=0;i=1e-9&&r>0&&n.push({a:o,b:a,halfDepth:r})}const o=n.map(Wl);for(const{segmentIndex:e,wedge:t}of Kl(n)){const i=o[e];if(!i)continue;const s=Vl(i,t);s&&(o[e]=s)}const a=[...o.filter(e=>!!e),...Yl(n)],r=function(e){let t=null;try{for(const i of e){if(i.length<3)continue;const e=xc(i);t=t?si(t,e):[e]}return t}catch{return null}}(a);return r?Fc(r):a.map(e=>nc(e)).join(" ")}function Xl(e,t,i,s,n=1){if(!i.length)return!1;const o=Zl(s,n),a=(e[0]+t[0])/2,r=(e[1]+t[1])/2,[l,c]=Sl(e,t);for(const e of i){const[t,i]=Sl([e[0],e[1]],[e[2],e[3]]);if(!(Math.abs(l*i-c*t)>.05)&&bc(a,r,e[0],e[1],e[2],e[3])<=o)return!0}return!1}function Zl(e,t){return Math.max(e*(t>0?t:1)*.04,1e-9)}function Ql(e){let t=0;for(let i=0;ie[1]!=l>e[1]&&e[0]<(r-o)*(e[1]-a)/(l-a+0)+o&&(i=!i)}return i}([c[0]+.001*r,c[1]+.001*l],e)||(r=-r,l=-l),[r,l]}function tc(e,t){const i=e[0]*t[1]-e[1]*t[0],s=e[0]*t[0]+e[1]*t[1];return Math.abs(i)<1e-9&&s>0}function ic(e,t,i,s){const n=t[0]*s[1]-t[1]*s[0];if(Math.abs(n)<1e-12)return null;const o=[i[0]-e[0],i[1]-e[1]],a=(o[0]*s[1]-o[1]*s[0])/n;return[e[0]+a*t[0],e[1]+a*t[1]]}function sc(e,t,i){const s=e?.length||0;if(s<3||t.length!==s)return null;if(t.every(e=>!(e>0)))return e.map(e=>[e[0],e[1]]);const n=[];for(let o=0;o0||p>0)){n.push([e[o][0],e[o][1]]);continue}if(d>0!=p>0){const t=e[o],i=d>0?[t[0]+u*d,t[1]+_*d]:[t[0],t[1]],s=p>0?[t[0]+m*p,t[1]+g*p]:[t[0],t[1]];n.push(i),Math.hypot(s[0]-i[0],s[1]-i[1])>1e-9&&n.push(s);continue}if(tc(w,k)){const t=e[o],i=[t[0]+u*d,t[1]+_*d],s=[t[0]+m*p,t[1]+g*p];n.push(i),Math.hypot(s[0]-i[0],s[1]-i[1])>1e-9&&n.push(s);continue}const S=ic(x,w,$,k),M=Math.max(d,p,1e-9),C=uc(i,e[o])?.limit??4*M;if(S){const t=Math.hypot(S[0]-e[o][0],S[1]-e[o][1]);if(Number.isFinite(t)&&t<=C){n.push(S);continue}}d>0&&n.push([e[o][0]+u*d,e[o][1]+_*d]),p>0&&n.push([e[o][0]+m*p,e[o][1]+g*p]),d>0||p>0||n.push([e[o][0],e[o][1]])}return n.length>=3?n:null}function nc(e,t=!0){if(!e.length)return"";let i=`M ${e[0][0]} ${e[0][1]}`;for(let t=1;te?.id===t),r=hi(a);if(!r||r.length<3)return null;const l=Zl(s,n),c=[];for(const i of e||[]){if(!i||i.id===t)continue;const e=hi(i);if(e)for(const t of Cs(r,e,l))c.push([t[0],t[1]],[t[2],t[3]])}for(const e of i||[])c.push([e[0],e[1]],[e[2],e[3]]);for(const e of o||[]){const t=Dl(e,n);t&&c.push(t[0],t[1])}const h=[],d=[];for(let e=0;el)continue;const a=((e[0]-t[0])*(i[0]-t[0])+(e[1]-t[1])*(i[1]-t[1]))/(s*s);a<=n||a>=1-n||(o.some(e=>Math.abs(e-a)*s<=2*l)||o.push(a))}o.sort((e,t)=>e-t);for(const s of o)h.push([t[0]+(i[0]-t[0])*s,t[1]+(i[1]-t[1])*s]),d.push(e)}return{poly:h,parent:d,orig:r}}function rc(e,t,i,s){const n=t.poly.length,o=new Array(n).fill(0);if(!e?.length)return o;const a=new Set,r=[];for(let l=0;l0?(o[l]=yl(c.cm),a.add(c.key)):r.push(l)}if(!r.length)return o;const l=s>0?s:1,c=Math.max(.5*i,1e-9)*l,h=Tl(e,l).filter(e=>e.w.cm>0);for(let e=r.length-1;e>=0;e--){const i=r[e],s=t.poly[i],a=t.poly[(i+1)%n],d=Il(s,a);let p=null;for(const e of h){const t=Dl(e.w,l);if(!t||!Rl(Il(t[0],t[1]),d))continue;if(bc(s[0],s[1],t[0][0],t[0][1],t[1][0],t[1][1])>c||bc(a[0],a[1],t[0][0],t[0][1],t[1][0],t[1][1])>c)continue;const i=Math.hypot(a[0]-s[0],a[1]-s[1]),n=Math.hypot(t[1][0]-t[0][0],t[1][1]-t[0][1]),o=Math.max(0,n-i);(!p||oc||bc(n[0],n[1],t[0][0],t[0][1],t[1][0],t[1][1])>c)continue;i=!0,o=Math.max(0,Math.hypot(t[1][0]-t[0][0],t[1][1]-t[0][1])-_)}else{if(bc(e.x,e.y,s[0],s[1],n[0],n[1])>c)continue;o=Math.hypot(e.x-d,e.y-p)}(!u||i&&!u.exact||i===u.exact&&o0?i:1,o=(e||[]).filter(e=>e&&!e.open&&null!==e.kind&&Number.isFinite(e.half)&&e.half>0&&Array.isArray(e.a)&&Array.isArray(e.b)&&e.a.length>=2&&e.b.length>=2&&[e.a[0],e.a[1],e.b[0],e.b[1]].every(Number.isFinite)&&Math.hypot(e.b[0]-e.a[0],e.b[1]-e.a[1])>s).sort((e,t)=>e.key.localeCompare(t.key)||e.a[0]-t.a[0]||e.a[1]-t.a[1]||e.b[0]-t.b[0]||e.b[1]-t.b[1]||e.half-t.half),a=new Map;for(const e of o){const t=a.get(e.key);t?e.half>t.half&&a.set(e.key,{...t,half:e.half}):a.set(e.key,e)}const r=[...a.values()].flatMap(e=>[{point:[e.a[0],e.a[1]],other:e.b,halfDepth:e.half,kind:e.kind,key:e.key},{point:[e.b[0],e.b[1]],other:e.a,halfDepth:e.half,kind:e.kind,key:e.key}]).sort((e,t)=>e.point[0]-t.point[0]||e.point[1]-t.point[1]||e.other[0]-t.other[0]||e.other[1]-t.other[1]||e.halfDepth-t.halfDepth),l=new Map;for(const e of r){const[t,i]=lc(e.point,s),n=cc(t,i),o=l.get(n)||[];o.push(e),l.set(n,o)}const c=[],h=new Map;for(const e of r){const t=hc(h,e.point,s).filter(t=>Math.hypot(t.point[0]-e.point[0],t.point[1]-e.point[1])<=s).sort((t,i)=>Math.hypot(t.point[0]-e.point[0],t.point[1]-e.point[1])-Math.hypot(i.point[0]-e.point[0],i.point[1]-e.point[1])||t.point[0]-i.point[0]||t.point[1]-i.point[1]);let i=t[0];if(!i){i={point:[...e.point],rays:[]},c.push(i);const[t,n]=lc(i.point,s),o=cc(t,n),a=h.get(o)||[];a.push(i),h.set(o,a)}const n=e.other[0]-e.point[0],o=e.other[1]-e.point[1],a=Math.hypot(n,o);if(!(a>s))continue;const r=[n/a,o/a];let l=Math.atan2(r[1],r[0]);l<0&&(l+=2*Math.PI),i.rays.push({u:r,halfDepth:e.halfDepth,length:a,angle:l})}const d=[],p=e=>{const t=1e-9*Math.max(1,n),i=e.filter(e=>Number.isFinite(e.halfDepth)&&e.halfDepth>0&&Number.isFinite(e.length)&&e.length>s);return i.filter((e,s)=>!i.some((i,n)=>n!==s&&i.halfDepth>=e.halfDepth-t&&i.length>=e.length-t&&(i.halfDepth>e.halfDepth+t||i.length>e.length+t||ne.length-t.length||e.halfDepth-t.halfDepth).map(e=>({...e}))};for(const e of c){const t=e.rays.sort((e,t)=>e.angle-t.angle||e.length-t.length||e.halfDepth-t.halfDepth),i=[];for(const e of t){const t=i[i.length-1];t&&Math.abs(e.angle-t.angle)<=1e-9?t.supports.push({halfDepth:e.halfDepth,length:e.length}):i.push({u:[...e.u],angle:e.angle,supports:[{halfDepth:e.halfDepth,length:e.length}]})}if(i.length>1&&2*Math.PI-i[i.length-1].angle+i[0].angle<=1e-9){const e=i.pop();i[0].supports.push(...e.supports)}if(i.length<3)continue;const n=i.map(t=>{const i=p(t.supports),n=new Set,o=[];for(const a of i){const i=[e.point[0]+t.u[0]*a.length,e.point[1]+t.u[1]*a.length];for(const t of hc(l,i,s)){if("shared"!==t.kind||Math.hypot(t.point[0]-i[0],t.point[1]-i[1])>s)continue;const a=t.other[0]-t.point[0],r=t.other[1]-t.point[1],l=Math.hypot(a,r);if(!(l>s))continue;const c=a/l,h=r/l;if(Math.hypot(t.other[0]-e.point[0],t.other[1]-e.point[1])<=s)continue;const d=`${t.key}|${t.point[0]}|${t.point[1]}|${t.other[0]}|${t.other[1]}|${t.halfDepth}`;n.has(d)||(n.add(d),o.push({start:[t.point[0],t.point[1]],u:[c,h],length:l,halfDepth:t.halfDepth}))}}return o.sort((e,t)=>e.start[0]-t.start[0]||e.start[1]-t.start[1]||e.u[0]-t.u[0]||e.u[1]-t.u[1]||e.length-t.length||e.halfDepth-t.halfDepth),{u:[...t.u],halfDepth:Math.max(...i.map(e=>e.halfDepth)),length:Math.max(...i.map(e=>e.length)),supports:i,continuations:o}}).filter(e=>Number.isFinite(e.halfDepth)&&e.halfDepth>0&&Number.isFinite(e.length)&&e.length>s);if(n.length<3)continue;const o=Math.max(...n.map(e=>e.halfDepth));o>0&&Number.isFinite(o)&&d.push({point:[...e.point],rays:n,halfDepth:o,limit:1.25*o})}d.sort((e,t)=>e.point[0]-t.point[0]||e.point[1]-t.point[1]);const u=new Map;for(const e of d){const[t,i]=lc(e.point,s),n=cc(t,i),o=u.get(n)||[];o.push(e),u.set(n,o)}return{epsilon:s,coordinateScale:n,nodes:d,index:u}}function pc(e){const t={fans:[],supports:[]};if(!e?.nodes?.length)return t;const i=Math.max(e.epsilon,1e-9)**2;for(const s of e.nodes){const e=s.rays.filter(e=>Number.isFinite(e.halfDepth)&&e.halfDepth>0).map(e=>({...e,thickLength:Math.max(...e.supports.filter(t=>t.halfDepth>=e.halfDepth-1e-12).map(e=>e.length),0),angle:(()=>{const t=Math.atan2(e.u[1],e.u[0]);return t<0?t+2*Math.PI:t})()})).sort((e,t)=>e.angle-t.angle);if(e.length<2)continue;const n=s.point;for(const i of e)for(const e of i.supports){if(!(e.halfDepth>0&&e.length>0))continue;const s=-i.u[1]*e.halfDepth,o=i.u[0]*e.halfDepth,a=[n[0]+i.u[0]*e.length,n[1]+i.u[1]*e.length];t.supports.push([[n[0]+s,n[1]+o],[a[0]+s,a[1]+o],[a[0]-s,a[1]-o],[n[0]-s,n[1]-o]])}for(let s=0;s{const e=a.angle-o.angle;return e>0?e:e+2*Math.PI})();if(r<1e-9)continue;const l=r>Math.PI+1e-9,c=4*Math.max(o.halfDepth,a.halfDepth),h=[n[0]-o.u[1]*o.halfDepth,n[1]+o.u[0]*o.halfDepth],d=[n[0]+a.u[1]*a.halfDepth,n[1]-a.u[0]*a.halfDepth],p=o.u[0]*a.u[1]-o.u[1]*a.u[0],u=e=>{let t=Math.atan2(e[1]-n[1],e[0]-n[0])-o.angle;for(;t<0;)t+=2*Math.PI;return t<=r+1e-9};let _=null;if(Math.abs(p)>1e-9){const e=((d[0]-h[0])*a.u[1]-(d[1]-h[1])*a.u[0])/p,t=((d[0]-h[0])*o.u[1]-(d[1]-h[1])*o.u[0])/p,i=[h[0]+o.u[0]*e,h[1]+o.u[1]*e];(l?e<=1e-9&&t<=1e-9:e>1e-9&&e<=o.thickLength&&t<=a.thickLength)&&Math.hypot(i[0]-n[0],i[1]-n[1])<=c&&u(i)&&(_=i)}const m=e=>{Math.abs(Ql(e))>i&&t.fans.push(e)};if(_){const e=1.5*Math.max(o.halfDepth,a.halfDepth);m(_l([n[0],n[1]],h,_,d,e)??[[n[0],n[1]],h,_,d]);continue}if(l){m([[n[0],n[1]],h,d]);continue}const g=(e,t)=>Math.min(t,Math.sqrt(Math.max(c**2-e**2,0)),2*Math.max(o.halfDepth,a.halfDepth)),f=[h[0]+o.u[0]*g(o.halfDepth,o.thickLength),h[1]+o.u[1]*g(o.halfDepth,o.thickLength)],v=[d[0]+a.u[0]*g(a.halfDepth,a.thickLength),d[1]+a.u[1]*g(a.halfDepth,a.thickLength)];m([[n[0],n[1]],h,f,v,d])}}return t}function uc(e,t){return!e||!Array.isArray(t)||t.length<2||!t.slice(0,2).every(Number.isFinite)?null:hc(e.index,t,e.epsilon).filter(i=>Math.hypot(i.point[0]-t[0],i.point[1]-t[1])<=e.epsilon).sort((e,i)=>Math.hypot(e.point[0]-t[0],e.point[1]-t[1])-Math.hypot(i.point[0]-t[0],i.point[1]-t[1])||e.point[0]-i.point[0]||e.point[1]-i.point[1])[0]||null}function _c(e,t,i,s,n,o,a){return dc(gc(e,t,i,s,n,o,a),4*Zl(s,a),a)}function mc(e,t,i,s,n,o,a,r=1){const l=ac(e,t,s,n,r,i);if(!l)return null;const c=function(e,t,i){const s=(e||[]).find(e=>e?.id===t),n=hi(s);if(!n)return[];const o=[];for(const s of e||[]){if(!s||s.id===t)continue;const e=hi(s);if(e)for(const t of Cs(n,e,i))o.push(t)}return o}(e,t,Zl(n,r)),h=function(e,t,i,s,n){const o=Zl(s,n),a=[];for(let r=0;rbc(h,d,e[0],e[1],e[2],e[3])<=o);a.push(p?"shared":"outer")}return a}(l.poly,c,s,n,r),d=rc(i,l,n,r),p=d.map((e,t)=>h[t]&&e>0?wl(e,o,a)/2:0);return{...l,kinds:h,cms:d,offsets:p}}function gc(e,t,i,s,n,o,a=1){const r=[];for(const l of e||[]){if(!l?.id)continue;const c=mc(e,l.id,t,i,s,n,o,a);if(c)for(let e=0;e0&&(r=Hl(r,e.a,e.b,e.cm,s,a));return r}function vc(e,t,i,s,n,o,a=1){if(!t?.length)return[];const r=gc(e,t,i,s,n,o,a),l=new Map;for(const e of r){if(e.open||!e.kind||!e.roomId)continue;const t=l.get(e.key)||new Set;t.add(e.roomId),l.set(e.key,t)}const c=e=>{const t=[...l.get(e)||[]].sort();return 1!==t.length&&2!==t.length?`ambiguous:${e}`:`${1===t.length?"outer":"shared"}:${t.join("|")}`},h=[],d=new Set;for(const e of r)!e.open&&e.cm>0&&!d.has(e.key)&&(d.add(e.key),h.push({...e,ownerSignature:c(e.key)}));const p=[];for(const r of e||[]){if(!r?.id)continue;const l=mc(e,r.id,t,i,s,n,o,a);if(l)for(let e=0;e0)||null===l.kinds[i]){e++;continue}const o=c(Cl(l.poly[i],l.poly[(i+1)%l.poly.length],s,a));let r=e;for(;r+10&&p.push({a:[d[0],d[1]],b:[u[0],u[1]],key:Cl(d,u,s,a),cm:n,len:_,ownerSignature:o}),e=r+1}}}p.sort((e,t)=>t.len-e.len||e.key.localeCompare(t.key));const u=[],_=new Set,m=new Set,g=4*Zl(s,a);for(const e of p){const t=h.filter(t=>!m.has(t.key)&&t.cm===e.cm&&t.ownerSignature===e.ownerSignature&&Rl(Il(t.a,t.b),Il(e.a,e.b))&&bc(t.a[0],t.a[1],e.a[0],e.a[1],e.b[0],e.b[1])<=g&&bc(t.b[0],t.b[1],e.a[0],e.a[1],e.b[0],e.b[1])<=g);if(t.length){for(const e of t)m.add(e.key);_.has(e.key)||(_.add(e.key),u.push(Pl(e.a,e.b,e.cm,s,a)))}}for(const e of h)m.has(e.key)||_.has(e.key)||(_.add(e.key),u.push(Pl(e.a,e.b,e.cm,s,a)));return u}function yc(e,t,i,s,n,o,a,r=1){const l=Zl(n,r),c=(s[0]+s[2])/2,h=(s[1]+s[3])/2,d=Il([s[0],s[1]],[s[2],s[3]]);let p=null;for(const s of gc(e,t,i,n,o,a,r)){if(!Rl(Il(s.a,s.b),d))continue;const e=bc(c,h,s.a[0],s.a[1],s.b[0],s.b[1]);e>4*l||(!p||e[e[0],e[1]]),o=Math.abs(Ql(n));n.length>=3&&o>i&&(t=n,i=o)}return t}function kc(e,t,i,s,n,o,a,r=1,l,c){const h=(e||[]).find(e=>e?.id===t),d=hi(h);if(!d||d.length<3)return null;if(!i?.length)return d.map(e=>[e[0],e[1]]);const p=mc(e,t,i,s,n,o,a,r);if(!p||!p.offsets.some(e=>e>0))return d.map(e=>[e[0],e[1]]);const u=c||_c(e,i,s,n,o,a,r),_=sc(p.poly,p.offsets,u);if(!_)return d.map(e=>[e[0],e[1]]);if(!u.nodes.length)return _;const m=void 0===l?Ec(e,i,s,[],n,o,a,r):null,g=l??("ok"===m?.status||"degraded-extra"===m?.status?m.roomGeom:void 0);if(g)try{const e=wc(oi(xc(p.poly),g));if(e)return e}catch{}return function(e,t){try{return wc(ni(xc(e),xc(t)))}catch{return null}}(_,p.poly)||d.map(e=>[e[0],e[1]])}function xc(e){const t=e.map(e=>[e[0],e[1]]);return t.push([e[0][0],e[0][1]]),[t]}function $c(e){return!(!Array.isArray(e)||!e.length)&&e.every(e=>Array.isArray(e)&&e.length&&e.every(e=>Array.isArray(e)&&e.length>=4&&e.every(e=>Array.isArray(e)&&e.length>=2&&Number.isFinite(e[0])&&Number.isFinite(e[1])))&&Math.abs(Ti(e[0]))>1e-9)}function Sc(e,t,i,s){const n=s?new Set(s):null;let o=null;for(let s=0;st.epsilon))continue;const l=Tc([[e.point[0]+r[0]*s.halfDepth,e.point[1]+r[1]*s.halfDepth],[e.point[0]+a.u[0]*n+r[0]*s.halfDepth,e.point[1]+a.u[1]*n+r[1]*s.halfDepth],[e.point[0]+a.u[0]*n-r[0]*s.halfDepth,e.point[1]+a.u[1]*n-r[1]*s.halfDepth],[e.point[0]-r[0]*s.halfDepth,e.point[1]-r[1]*s.halfDepth]],t.coordinateScale);if(!l)continue;const c=xc(l);o=o?si(o,c):c}}return o}function Mc(e,t,i){let s=null;for(const n of e.rays)for(const e of n.continuations){const n=[-e.u[1],e.u[0]],o=[e.start[0]+e.u[0]*e.length,e.start[1]+e.u[1]*e.length],a=Tc([[e.start[0]+n[0]*e.halfDepth,e.start[1]+n[1]*e.halfDepth],[o[0]+n[0]*e.halfDepth,o[1]+n[1]*e.halfDepth],[o[0]-n[0]*e.halfDepth,o[1]-n[1]*e.halfDepth],[e.start[0]-n[0]*e.halfDepth,e.start[1]-n[1]*e.halfDepth]],t.coordinateScale);if(!a)continue;const r=ni(xc(a),i);Array.isArray(r)&&0!==r.length&&(s=s?si(s,r):r)}return s}function Cc(e,t,i=2*(4*e.halfDepth+2*t.epsilon)){const s=function(e,t=ml){const i=new Set,s=Number.isFinite(t)&&t>=0?t:ml;for(let t=0;te-t)}(e);return s.length?Sc(e,t,i,s):null}function Dc(e,t,i,s,n){const o=function(e){let t=null;for(const i of e){const e=xc(i);try{t=t?si(t,e):e}catch{}}return t}(function(e,t,i=!1){if(!e)return[];const s=[];for(const n of e.nodes)for(let o=0;o1e-9)||h>=Math.PI-1e-9)continue;const d=[-a.u[1],a.u[0]],p=[-r.u[1],r.u[0]],u=[n.point[0]+d[0]*a.halfDepth,n.point[1]+d[1]*a.halfDepth],_=[n.point[0]-p[0]*r.halfDepth,n.point[1]-p[1]*r.halfDepth],m=ic(u,a.u,_,r.u);if(!m)continue;const g=Math.hypot(m[0]-n.point[0],m[1]-n.point[1]);if(!Number.isFinite(g)||g<=n.limit)continue;const f=t?Math.sqrt(Math.max(0,n.limit*n.limit-a.halfDepth*a.halfDepth)):0,v=t?Math.sqrt(Math.max(0,n.limit*n.limit-r.halfDepth*r.halfDepth)):0,y=Tc([[u[0]+a.u[0]*f,u[1]+a.u[1]*f],[_[0]+r.u[0]*v,_[1]+r.u[1]*v],m],e.coordinateScale);if(y&&s.push(y),i){const t=m[0]-n.point[0],i=m[1]-n.point[1],o=Math.hypot(t,i),a=g-n.limit;if(o>e.epsilon&&a>e.epsilon){const r=Math.min(Math.max(8*e.epsilon,.05*n.halfDepth),.25*a),l=t/o,c=i/o,h=-c,d=l,p=Tc([[m[0]-l*r+h*r,m[1]-c*r+d*r],[m[0]-l*r-h*r,m[1]-c*r-d*r],[m[0]+l*r,m[1]+c*r]],e.coordinateScale);p&&s.push(p)}}}return s}({...t,nodes:[e]},i,s));return o&&n?oi(o,n):o}function Pc(e,t,i,s){if(!e||!t.nodes.length)return e;let n=null;try{n=function(e){let t=null;for(const i of e.nodes){const s=Cc(i,e);s&&(t=t?si(t,s):s)}return t}(t)}catch{return e}let o=e;for(const e of t.nodes){const a=4*e.halfDepth+2*t.epsilon,r=2*a,l=[[e.point[0]-a,e.point[1]-a],[e.point[0]+a,e.point[1]-a],[e.point[0]+a,e.point[1]+a],[e.point[0]-a,e.point[1]+a]];try{let a=o;const c=Dc(e,t,!1,!0,n);c&&(a=oi(a,c));let h=Sc(e,t,r);const d=Dc(e,t,!0,!0,n);d&&(h=oi(h,d)),n&&(h=si(h,n));const p=.02*Math.min(...e.rays.map(e=>e.halfDepth));if(h=si(h,xc([[e.point[0]-p,e.point[1]-p],[e.point[0]+p,e.point[1]-p],[e.point[0]+p,e.point[1]+p],[e.point[0]-p,e.point[1]+p]])),!h)continue;let u=ni(h,xc(l));s?u=ni(u,s):i&&(u=ni(u,i));const _=xc(l),m=oi(a,_),g=i?oi(ni(a,_),i):null,f=Mc(e,t,_);o=si(m,...g?[g]:[],...f?[f]:[],u)}catch{}}if(n)try{let e=n;s?e=ni(e,s):i&&(e=ni(e,i)),o=si(o,e)}catch{}return o}function Tc(e,t=1){if(!Array.isArray(e)||e.length<3)return null;const i=Number.isFinite(t)&&t>0?t:1,s=1e-12*Math.max(1,i),n=[];for(const t of e){if(!Array.isArray(t)||t.length<2)return null;const e=Number(t[0]),i=Number(t[1]);if(!Number.isFinite(e)||!Number.isFinite(i))return null;const o=Math.round(e/s)*s,a=Math.round(i/s)*s;if(!Number.isFinite(o)||!Number.isFinite(a))return null;n.push([Object.is(o,-0)?0:o,Object.is(a,-0)?0:a])}return Math.abs(Ql(n))>s*s?n:null}function Ic(e,t,i,s){if(bc(e[0],e[1],t[0],t[1],i[0],i[1])>s)return!1;const n=i[0]-t[0],o=i[1]-t[1],a=(e[0]-t[0])*n+(e[1]-t[1])*o,r=n*n+o*o,l=s*Math.sqrt(r);return a>=-l&&a<=r+l}function Rc(e,t,i){const s=[],n=[];for(let o=0;oi*i))continue;const d=i/Math.sqrt(h),p=[0,1];for(const e of t)for(const t of[e.a,e.b]){if(!Ic(t,a,r,i))continue;const e=((t[0]-a[0])*l+(t[1]-a[1])*c)/h;e>d&&e<1-d&&p.push(e)}p.sort((e,t)=>e-t);const u=p.filter((e,t)=>0===t||Math.abs(e-p[t-1])>d);for(let e=0;e=3&&n.length===s.length?{poly:s,offsets:n}:null}function Ac(e,t,i,s,n,o,a,r){const l=(e||[]).map(hi).filter(e=>!!e&&e.length>=3);if(!l.length)return null;let c=si(xc(l[0]));for(let e=1;e"outer"===e.kind&&e.half>0),p=4*Zl(s,a),u=r||dc(h,p,a);let _=null;for(const e of function(e){const t=[];for(const i of Array.isArray(e)?e:[])if(Array.isArray(i))for(const e of i){if(!Array.isArray(e)||e.length<4)continue;const i=e.slice(0,-1).map(e=>[e[0],e[1]]);i.length>=3&&t.push(i)}return t}(c)){const t=Rc(e,d,p);if(!t||!t.offsets.some(e=>e>0))continue;const i=Hc(t.poly,t.offsets,u),s=sc(t.poly,t.offsets,u);if(!i||!s)continue;const n=oi(xc(i),xc(s));_=_?si(_,n):n}return{centre:c,shell:_||[]}}function zc(e,t,i,s,n,o,a=1){try{const r=Ac(e,t,i,s,n,o,a,_c(e,t,i,s,n,o,a));if(!r)return[];return r.shell?.length?si(r.centre,r.shell):r.centre}catch{return null}}function Fc(e){if(!e)return"";let t="";for(const i of e)if(Array.isArray(i))for(const e of i){if(!Array.isArray(e)||e.length<4)continue;const i=e.slice(0,e.length-1);i.length<3||(t+=(t?" ":"")+nc(i.map(e=>[e[0],e[1]])))}return t}function Ec(e,t,i,s=[],n,o,a,r=1,l=[],c={}){if(!t?.length&&!l.length)return{status:"not-applicable",geom:[],components:[],roomGeom:[],paperGeom:[],roomComponents:[],depthUnits:0,openingIndex:null,multiWallNodes:null,degradedExtraCount:0};const h=[],d=_c(e,t,i,n,o,a,r);let p=0;for(const s of e||[]){if(!s?.id)continue;const l=mc(e,s.id,t,i,n,o,a,r);if(!l||l.poly.length<3||!l.offsets.some(e=>e>0))continue;for(const e of l.offsets)e>0&&(p=Math.max(p,2*e));const c=Hc(l.poly,l.offsets,d),u=sc(l.poly,l.offsets,d);c&&h.push({outset:c,inset:u})}for(const e of l){const t=e.map(e=>e[0]),i=e.map(e=>e[1]);if(t.length){const s=Math.min(Math.max(...t)-Math.min(...t),Math.max(...i)-Math.min(...i)),n=Math.min(...e.map((t,i)=>{const s=e[(i+1)%e.length];return Math.hypot(s[0]-t[0],s[1]-t[1])}));p=Math.max(p,e.length>16?s:n)}}const u=function(e,t,i,s,n,o,a,r){if(!t?.length||!i?.length)return[];const l=4*Zl(s,a),c=new Map;for(const r of gc(e,t,i,s,n,o,a))!r.open&&r.half>0&&!c.has(r.key)&&c.set(r.key,r);const h=[...c.values()];if(h.length<2)return[];const d=r||dc(h,l),p=[];for(const e of i)for(const t of[[e[0],e[1]],[e[2],e[3]]])p.some(e=>Math.hypot(e[0]-t[0],e[1]-t[1])<=l)||p.push(t);const u=[],_=(e,t)=>{let i=0,s=0;if(Math.hypot(e.a[0]-t[0],e.a[1]-t[1])<=l)i=e.b[0]-e.a[0],s=e.b[1]-e.a[1];else{if(!(Math.hypot(e.b[0]-t[0],e.b[1]-t[1])<=l))return null;i=e.a[0]-e.b[0],s=e.a[1]-e.b[1]}const n=Math.hypot(i,s);return n>l?[i/n,s/n]:null};for(const e of p){const t=h.map(t=>({iv:t,u:_(t,e)})).filter(e=>!!e.u);for(let i=0;i0?[e.slice(),p,m,_]:[e.slice(),_,m,p];else{if(!f)continue;{const t=[-n.u[1],n.u[0]],i=[-o.u[1],o.u[0]],s=a<0?1:-1,r=[e[0]+t[0]*n.iv.half*s,e[1]+t[1]*n.iv.half*s],l=[e[0]-i[0]*o.iv.half*s,e[1]-i[1]*o.iv.half*s];y=a>0?[e.slice(),r,l]:[e.slice(),l,r]}}Math.abs(Ql(y))>l*l&&u.push(y)}}return u}(e,t,i,n,o,a,r,d),_=s.length?Bc(e,t,i,n,o,a,r):null;let m="exterior";try{const v=Ac(e,t,i,n,o,a,r,d);m="paper";const y=v?v.shell?.length?si(v.centre,v.shell):v.centre:[],b=e=>{const t=xc(e.outset);return e.inset?oi(t,xc(e.inset)):t};m="room-rings";let w=null;for(const e of h)try{const t=b(e);w=w?si(w,t):t}catch{}if(m="edge-bodies",v)for(const s of Lc(e,t,i,n,o,a,r))try{const e=ni(xc(s.quad),v.centre);w=w?si(w,e):e}catch{}m="junctions",w=function(e,t,i=1,s=si){let n=e;for(const e of t||[]){const t=Tc(e,i);if(t)try{const e=xc(t);n=n?s(n,e):e}catch{}}return n}(w,u,r),m="facade-clip",w&&v&&(w=ni(w,v.centre)),m="exterior-shell";const k=[];let x=0;if(v?.shell?.length)if(w)try{const e=si(w,v.shell);if(!$c(e))throw new Error("invalid shell union");w=e}catch{if(!$c(w)||!$c(v.shell))throw new Error("invalid shell");k.push({id:"exterior-shell",geom:v.shell}),x++}else w=v.shell;if(m="multi-wall-trim",w&&d.nodes.length){const e=e=>e.rays.some(e=>e.supports.some(e=>e.length<2*e.halfDepth)),t=d.nodes.filter(e);if(t.length){w=Pc(w,{...d,nodes:t},v?.centre,y)}}if(m="junction-corners",d.nodes.length){const s=pc(d),l=function(e,t,i,s,n,o,a,r){try{const l=Ac(e,t,i,s,n,o,a,{epsilon:r.epsilon,coordinateScale:r.coordinateScale,nodes:[],index:new Map});return l?l.shell?.length?si(l.centre,l.shell):l.centre:null}catch{return null}}(e,t,i,n,o,a,r,d);for(const e of s.fans)try{let t=[xc(e)];if(l&&(t=ni(t,l)),!t?.length)continue;w=w?si(w,t):t}catch{}g=w,f=Math.max(d.epsilon,1e-9)**2,w=Array.isArray(g)?g.map(e=>{if(!Array.isArray(e)||!e.length)return e;const[t,...i]=e;return Math.abs(Ql(t||[]))<=f?null:[t,...i.filter(e=>Math.abs(Ql(e||[]))>f)]}).filter(e=>!!e):g}const $=w||[],S=[...$c($)?[{id:"room-primary",geom:$}]:[],...k.map((e,t)=>({id:`room-isolated-${t}`,geom:e.geom}))];m="openings";for(const e of s){if(!(e.length>0))continue;const t=jc(_,e,!0);if(!t.negative&&!t.positive)continue;const i=e.angle*Math.PI/180,s=Math.cos(i),o=Math.sin(i),a=-o,l=s,c=e.length/2,h=1.25*Math.max(p,n*r),d=[[e.x-s*c-a*h,e.y-o*c-l*h],[e.x+s*c-a*h,e.y+o*c-l*h],[e.x+s*c+a*h,e.y+o*c+l*h],[e.x-s*c+a*h,e.y-o*c+l*h]];w&&(w=oi(w,xc(d)));for(const e of k)e.geom=oi(e.geom,xc(d))}m="extras";const M=[];let C=0;const D=c.mergeExtra||((e,t)=>e?si(e,t):t);for(let e=0;ee.length>=2&&Number.isFinite(e[0])&&Number.isFinite(e[1]))||Math.abs(Ti(t))<=1e-9){C++;continue}const i=[xc(t)];try{const t=D(w,i,e);if(!$c(t))throw new Error("invalid extra union");w=t}catch{C++,$c(i)&&M.push({id:`extra-${e}`,geom:i})}}M.push(...k),M.sort((e,t)=>Fc(e.geom).localeCompare(Fc(t.geom)));const P=w||[];return{status:C||x?"degraded-extra":"ok",geom:P,components:[...$c(P)?[{id:"primary",geom:P}]:[],...M.map((e,t)=>({...e,id:`isolated-${t}`}))],roomGeom:$,roomComponents:S,paperGeom:y,depthUnits:p,openingPadUnits:1.25*Math.max(p,n*r),openingIndex:_,multiWallNodes:d,degradedExtraCount:C+x}}catch{return c.onCoreFailure?.(m),{status:"failed-core",geom:[],components:[],roomGeom:[],paperGeom:[],roomComponents:[],depthUnits:p,openingIndex:null,multiWallNodes:d,degradedExtraCount:0}}var g,f}function Nc(e,t,i,s=[],n,o,a,r=1,l=[],c={}){if(!t?.length&&!l.length)return null;return Oc(Ec(e,t,i,s,n,o,a,r,l,c))}function Oc(e){if("failed-core"===e.status||"not-applicable"===e.status)return null;const t=e.components.map(e=>({id:e.id,d:Fc(e.geom),fillRule:"evenodd"})).filter(e=>!!e.d),i=t[0]?.d||"",s=Fc(e.paperGeom);if(t.length){const n={status:e.status,d:i,paths:t,components:e.components,roomGeom:e.roomGeom,multiWallNodes:e.multiWallNodes,paperD:s,depthUnits:e.depthUnits,fillRule:"evenodd"};return Object.defineProperties(n,{roomComponents:{value:e.roomComponents||[],enumerable:!1},openingIndex:{value:e.openingIndex,enumerable:!1},openingPadUnits:{value:e.openingPadUnits,enumerable:!1}}),n}return null}function Lc(e,t,i,s,n,o,a=1){if(!t?.length)return[];const r=new Set,l=[];for(const c of e||[]){if(!c?.id)continue;const h=mc(e,c.id,t,i,s,n,o,a);if(!h)continue;const d=h.poly;for(let e=0;e0))continue;const u=Cl(t,i,s,a);if(r.has(u))continue;r.add(u);const _=wl(p,n,o),[m,g]=ec(d,e),f=-m,v=-g,y=_/2,b=[[t[0]+f*y,t[1]+v*y],[i[0]+f*y,i[1]+v*y],[i[0]+m*y,i[1]+g*y],[t[0]+m*y,t[1]+g*y]];l.push({key:u,kind:c,cm:p,quad:b,a:[t[0],t[1]],b:[i[0],i[1]],depthUnits:_})}}return l}function Hc(e,t,i){const s=e?.length||0;if(s<3||t.length!==s)return null;if(t.every(e=>!(e>0)))return e.map(e=>[e[0],e[1]]);oc(e),t.slice().reverse();const n=[];for(let o=0;o0||l>0)){n.push([e[o][0],e[o][1]]);continue}if(r>0!=l>0){const t=e[o],i=r>0?[t[0]-c*r,t[1]-h*r]:[t[0],t[1]],s=l>0?[t[0]-d*l,t[1]-p*l]:[t[0],t[1]];n.push(i),Math.hypot(s[0]-i[0],s[1]-i[1])>1e-9&&n.push(s);continue}if(tc(w,k)){const t=e[o],i=[t[0]-c*r,t[1]-h*r],s=[t[0]-d*l,t[1]-p*l];n.push(i),Math.hypot(s[0]-i[0],s[1]-i[1])>1e-9&&n.push(s);continue}const S=ic(x,w,$,k),M=Math.max(r,l,1e-9),C=uc(i,e[o])?.limit??4*M;if(S){const t=Math.hypot(S[0]-e[o][0],S[1]-e[o][1]);if(Number.isFinite(t)&&t<=C){n.push(S);continue}}r>0&&n.push([e[o][0]-c*r,e[o][1]-h*r]),l>0&&n.push([e[o][0]-d*l,e[o][1]-p*l])}return n.length>=3?n:null}function Bc(e,t,i,s,n,o,a=1){const r=[];for(const l of e||[]){if(!l?.id)continue;const c=mc(e,l.id,t,i,s,n,o,a);if(!c)continue;const h=Math.abs(Ti(c.poly));for(let e=0;e[Math.max(t,e.x0),Math.min(i,e.x1)]).filter(e=>e[1]-e[0]>s).sort((e,t)=>e[0]-t[0]||e[1]-t[1]);if(!n.length)return{coverage:0,full:!1};let o=n[0][0],a=n[0][1],r=0,l=o<=t+s;for(let e=1;e=i-s,{coverage:r,full:l}}function Wc(e,t){return Number(t.full)-Number(e.full)||e.faceDistance-t.faceDistance||e.area-t.area||e.roomId.localeCompare(t.roomId)}function jc(e,t,i=!1){const s=Number(t?.x),n=Number(t?.y),o=Number(t?.angle),a=Number(t?.length);if(!([s,n,o,a].every(Number.isFinite)&&a>0))return{negative:null,positive:null};const r=o*Math.PI/180,l=Math.cos(r),c=Math.sin(r),h=-c,d=l,p=a/2,u=Math.max(1e-9,e.adjacencyEps),_=new Map;let m=0;for(const t of e.edges){if(i&&!(t.half>0))continue;if(!El(t.a,t.b,o))continue;const[e,a]=Sl(t.a,t.b);if(Math.abs((s-t.a[0])*a-(n-t.a[1])*e)>u)continue;const r=(t.a[0]-s)*l+(t.a[1]-n)*c,g=(t.b[0]-s)*l+(t.b[1]-n)*c,f=Math.max(-p,Math.min(r,g)),v=Math.min(p,Math.max(r,g));if(v-f<=u)continue;const y=t.inward[0]*h+t.inward[1]*d>=0?1:-1,b=((t.a[0]+t.b[0])/2-s)*h+((t.a[1]+t.b[1])/2-n)*d,w=Math.abs(b+y*t.half),k=`${y}|${t.roomId}`,x={x0:f,x1:v,half:t.half,cm:t.cm,key:t.key,axis:[e,a]},$=_.get(k);$?($.pieces.push(x),$.faceDistance=Math.min($.faceDistance,w)):_.set(k,{roomId:t.roomId,side:y,order:m++,pieces:[x],faceDistance:w,area:t.area,coverage:0,full:!1})}for(const e of _.values()){const t=qc(e.pieces,-p,p,u);e.coverage=t.coverage,e.full=t.full}const g=e=>{const t=[..._.values()].filter(t=>t.side===e&&t.coverage>u);return t.sort(Wc),t[0]||null};return{negative:g(-1),positive:g(1)}}function Uc(e,t){const i=jc(e,t),s=[i.negative,i.positive].filter(e=>!!e);if(!s.length)return{ox:0,oy:0,cm:0,side:-1};const n=i.negative&&i.positive?-1:s[0].side,o=t.flip_v?-n:n,a=(-1===o?i.negative:i.positive)||s[0],r=[...a.pieces].sort((e,t)=>(e.x0<=0&&e.x1>=0?0:Math.min(Math.abs(e.x0),Math.abs(e.x1)))-(t.x0<=0&&t.x1>=0?0:Math.min(Math.abs(t.x0),Math.abs(t.x1)))||t.x1-t.x0-(e.x1-e.x0)||e.key.localeCompare(t.key))[0];if(!(r.half>0&&r.cm>0))return{ox:0,oy:0,cm:0,side:o};const l=t.angle*Math.PI/180,c=-Math.sin(l),h=Math.cos(l);return{ox:c*o*r.half,oy:h*o*r.half,cm:r.cm,side:o}}function Gc(e,t){const i=1e-9,s=t.filter(e=>Number.isFinite(e.x0)&&Number.isFinite(e.x1)&&Number.isFinite(e.half)&&e.x1>e.x0&&e.half>0);if(!s.length)return"";const n=s.flatMap(e=>[e.x0,e.x1]).sort((e,t)=>e-t),o=[];for(const e of n){const t=o[o.length-1];(void 0===t||e>t+i)&&o.push(e)}const a=[];for(let e=0;e+1t+i))continue;const r=(t+n)/2,l=s.reduce((e,t)=>r>=t.x0-i&&r<=t.x1+i?Math.max(e,t.half):e,0);if(!(l>0))continue;const c=a[a.length-1];c&&t<=c.x1+i&&Math.abs(l-c.half)<=i?c.x1=n:a.push({x0:t,x1:n,half:l})}const r=[];for(const e of a){const t=r[r.length-1],s=t?.[t.length-1];s&&e.x0<=s.x1+i?(e.x0=s.x1,t.push(e)):r.push([e])}return r.map(t=>{const i=t[0],s=t[t.length-1],n=Math.min(.25*Math.min(...t.map(e=>e.half)),.75),o=-e*n,a=[];if(1===e){a.push(`M ${i.x0} ${o} L ${s.x1} ${o}`);for(let e=t.length-1;e>=0;e--){const i=t[e];a.push(`L ${i.x1} ${i.half} L ${i.x0} ${i.half}`)}}else{a.push(`M ${s.x1} ${o} L ${i.x0} ${o}`);for(const e of t)a.push(`L ${e.x0} ${-e.half} L ${e.x1} ${-e.half}`)}return a.push("Z"),a.join(" ")}).join(" ")}function Vc(e,t,i,s){if(!s)return i;const n=e.angle*Math.PI/180,o=Math.cos(n),a=Math.sin(n),r=[],l=1e-9;for(const n of i){const[i,c]=n.axis,h=o*i+a*c;if(Math.abs(h)<=l)continue;const d=e.x*i+e.y*c,p=d+h*n.x0,u=d+h*n.x1,_=Math.min(p,u),m=Math.max(p,u),g=`${n.key}|${t}`,f=s.get(g)||[];let v=[[_,m]];for(const[e,t]of f){const i=[];for(const[s,n]of v)t<=s+l||e>=n-l?i.push([s,n]):(e>s+l&&i.push([s,Math.min(n,e)]),te[0]-t[0]||e[1]-t[1]),b=[];for(const e of y){const t=b[b.length-1];t&&e[0]<=t[1]+l?t[1]=Math.max(t[1],e[1]):b.push([e[0],e[1]])}s.set(g,b)}return r}function Kc(e,t){const i=new Map;return t.map(t=>function(e,t,i){const s=jc(e,t,!0),n=s.negative,o=s.positive;if(!n&&!o)return null;let a;if(n&&o)a=[{candidate:n,side:-1},{candidate:o,side:1}];else{const e=n||o;a=[{candidate:e,side:-1},{candidate:e,side:1}]}const r=a.map(({candidate:e,side:s})=>({candidate:e,side:s,pieces:Vc(t,s,e.pieces,i)})),l=r.map(({candidate:e,side:t,pieces:i})=>({side:t,roomId:e.roomId,d:Gc(t,i)})),c=r.flatMap(({pieces:e})=>e);if(!c.length)return null;const h=Math.max(...c.map(e=>e.half));return{faces:l,minY:-h,maxY:h,wallKey:[...new Set(c.map(e=>e.key))].sort().join("|")}}(e,t,i))}const Yc=150,Jc=1e-6;function Xc(e){return Number.isFinite(e)?Math.max(1,Math.min(Yc,e)):1}function Zc(e){return((Number.isFinite(Number(e))?Number(e):0)%90+90)%90}const Qc=e=>{const t=e.map(e=>[e[0],e[1]]);return!t.length||t[0][0]===t[t.length-1][0]&&t[0][1]===t[t.length-1][1]||t.push([...t[0]]),[t]},eh=(e,t)=>e[0]===t[0]&&e[1]===t[1];function th(e,t=1e-6){const i=Number.isFinite(t)&&t>0?t:Jc,s=[];for(const t of e||[]){if(!Array.isArray(t)||t.length<2)return null;const e=Number(t[0]),n=Number(t[1]);if(!Number.isFinite(e)||!Number.isFinite(n))return null;const o=Math.round(e/i)*i,a=Math.round(n/i)*i;if(!Number.isFinite(o)||!Number.isFinite(a))return null;const r=[Object.is(o,-0)?0:o,Object.is(a,-0)?0:a];s.length&&eh(s[s.length-1],r)||s.push(r)}return s.length>1&&eh(s[0],s[s.length-1])&&s.pop(),s.length<3||new Set(s.map(e=>`${e[0]},${e[1]}`)).size<3?null:Ti(s)>i*i?s:null}function ih(e){const t=[];for(const i of e||[])for(const e of i||[]){const i=(e||[]).filter(e=>Array.isArray(e)&&e.length>=2);i.length<4||t.push(`M ${i.slice(0,-1).map(e=>`${e[0]} ${e[1]}`).join(" L ")} Z`)}return t.join(" ")}function sh(e,t,i,s,n){return Wl({a:e,b:t,halfDepth:wl(i,s,n)/2})}function nh(e,t,i){const s=Number(t)>0?Number(t):5,n=Xc(e.cm)/s*i,o=e.center[0],a=e.center[1];if("circle"===e.shape){const e=n/2;return Array.from({length:96},(t,i)=>{const s=i/96*Math.PI*2;return[o+Math.cos(s)*e,a+Math.sin(s)*e]})}const r=n/2,l=Zc(e.angle)*Math.PI/180,c=Math.cos(l),h=Math.sin(l);return[[-r,-r],[r,-r],[r,r],[-r,r]].map(([e,t])=>[o+e*c-t*h,a+e*h+t*c])}function oh(e,t,i=1e-9){if(!t.length)return[e];let s=[Qc(e)];try{for(const e of t){const t=e.b[0]-e.a[0],n=e.b[1]-e.a[1],o=Math.hypot(t,n);if(!(o>i))continue;const a=t/o,r=n/o,l=-r,c=a,h=1.25*Math.max(Number(e.depth)||0,4*i),d=Math.max(2*i,1e-9*o),p=[[e.a[0]-a*d-l*h,e.a[1]-r*d-c*h],[e.b[0]+a*d-l*h,e.b[1]+r*d-c*h],[e.b[0]+a*d+l*h,e.b[1]+r*d+c*h],[e.a[0]-a*d+l*h,e.a[1]-r*d+c*h]];s=oi(s,Qc(p))}return mh(s)}catch{return[e]}}function ah(e,t){try{const i=oi([[...e.map(e=>[e[0],e[1]]),[e[0][0],e[0][1]]]],[[...t.map(e=>[e[0],e[1]]),[t[0][0],t[0][1]]]]);let s=null,n=0;for(const e of i||[]){const t=e?.[0]||[],i=Math.abs(Ti(t));t.length>=4&&i>n&&(n=i,s=t.slice(0,-1).map(e=>[e[0],e[1]]))}return s}catch{return null}}function rh(e,t,i,s=Math.max(2e-4*i,1e-9),n=[]){const o=[],a=[],r=new Map;for(const e of n){const t=r.get(e.hostId)||[];t.push(e),r.set(e.hostId,t)}const l=[],c=[],h=[];for(const s of e.room_drafts||[])for(let e=0;e+10))continue;const r={a:s.points[e],b:s.points[e+1],halfDepth:a},c=Wl(r);c&&(o.push(r),l.push(c))}const d=[];for(const s of e.partitions||[]){const e={a:s.a,b:s.b,halfDepth:wl(s.cm,t,i)/2};if(!(e.halfDepth>0))continue;const n=Wl(e);n&&(a.push(e),c.push(n),d.push({id:s.id,body:n}))}const p=[...o,...a];for(const{segmentIndex:e,wedge:t}of Kl(p,s)){const i=e=o.length&&(d[i.at].body=s))}for(const e of d)h.push(...oh(e.body,r.get(e.id)||[],s));const u=(e.wall_columns||[]).map(e=>nh(e,t,i)),_=Yl([...o,...a],s).flatMap(e=>oh(e,n,s));return{drafts:l,partitions:c,columns:u,patches:_,all:[...l,...h,..._,...u]}}function lh(e){try{const t=e.map(e=>th(e)).filter(e=>!!e).map(e=>Qc(e));return t.length?si(t[0],...t.slice(1)):null}catch{return null}}const ch=e=>`M ${e.map(e=>`${e[0]} ${e[1]}`).join(" L ")} Z`;function hh(e){const t=[];for(const i of e||[]){if(uh([i])<=1e-6)continue;const e=[];for(const t of i||[]){const i=(t||[]).filter(e=>Array.isArray(e)&&e.length>=2);i.length<4||e.push(ch(i.slice(0,-1)))}e.length&&t.push(e.join(" "))}return t}function dh(e,t,i={}){const s=lh(e.filter(e=>e.length>=3)),n=t.some(e=>!th(e))?null:lh(t);if(!s)return[];if(n)try{return hh(ni(s,n))}catch{}return function(e,t,i){let s=null;for(let n=0;n=4&&t.push(e.slice(0,-1).map(e=>[e[0],e[1]]));return t}function mh(e){const t=[];for(const i of e||[]){const e=i?.[0];e?.length>=4&&t.push(e.slice(0,-1).map(e=>[e[0],e[1]]))}return t}function gh(e,t){let i=!1;for(let s=0,n=t.length-1;se[1]!=l>e[1]&&e[0]<(r-o)*(e[1]-a)/(l-a||1e-12)+o&&(i=!i)}return i}function fh(e,t,i){return function(e,t){for(const i of t||[]){const t=i?.[0];if(!t?.length||!gh(e,t))continue;let s=!1;for(let t=1;tgh(e,t))}function vh(e,t,i){if(Math.hypot(e.center[0]-t.center[0],e.center[1]-t.center[1])>i)return!1;if(Math.abs(Xc(e.cm)-Xc(t.cm))>1e-6)return!1;if(e.shape!==t.shape)return!0;if("circle"===e.shape||"circle"===t.shape)return!0;const s=Math.abs(Zc(e.angle)-Zc(t.angle));return Math.min(s,90-s)<=1e-6}const yh=2.54;function bh(e){const t="number"==typeof e?e:NaN;return!Number.isFinite(t)||t<=0||5===t?1:5/t}function wh(e,t){return e*bh(t)}function kh(e){return e?yh:1}function xh(e,t){if(!t)return String(e);const i=e/yh;return String(Math.round(1e6*i)/1e6)}const $h=1e3;function Sh(e,t){const i=Number(e),s=Number.isFinite(i)&&i>0?i:1,n=s>=1?t:t*s,o=s>=1?t/s:t;return{x:(t-n)/2,y:(t-o)/2,w:n,h:o}}const Mh=.01,Ch=100;function Dh(e,t=1e3){const i=Sh(e?.plan_aspect,t),s=Number(e?.plan_scale),n=Number.isFinite(s)&&s>0?Math.min(Ch,Math.max(Mh,s)):1,o=Number(e?.plan_scale_x),a=Number(e?.plan_scale_y),r=Number.isFinite(o)&&o>0?Math.min(Ch,Math.max(Mh,o)):n,l=Number.isFinite(a)&&a>0?Math.min(Ch,Math.max(Mh,a)):n,c=Number(e?.plan_x),h=Number(e?.plan_y),d=Or(e?.plan_angle);return{x:i.x+(Number.isFinite(c)?Lh(c):0)*t,y:i.y+(Number.isFinite(h)?Lh(h):0)*t,w:i.w*r,h:i.h*l,...d?{angle:d}:{}}}function Ph(e){if(null==e.x||null==e.y)return{x:e.x,y:e.y,w:e.w,h:e.h};const t=Number(e.w)||0,i=Number(e.h)||0;return{x:t<0?e.x+t:e.x,y:i<0?e.y+i:e.y,w:Math.abs(t),h:Math.abs(i)}}function Th(e){return e&&Array.isArray(e.spaces)?e.spaces.map(e=>{const t=$h,i=function(e){return Array.isArray(e)&&4===e.length&&e.every(e=>Number.isFinite(e))&&e[2]>1e-6&&e[3]>1e-6?e:[0,0,1,1]}(e.view_box);return{id:e.id,title:e.title,cellCm:Number.isFinite(Number(e.cell_cm))&&Number(e.cell_cm)>0?Number(e.cell_cm):5,vb:[i[0]*$h,i[1]*t,i[2]*$h,i[3]*t],bg:e.plan_url?{href:As(e.plan_url),...Dh(e,$h)}:null,rooms:(e.rooms||[]).map(e=>{const i={...e,...Ph(e)};return{id:i.id,name:i.name,area:i.area??null,open_to:i.open_to||void 0,settings:i.settings||void 0,x:null!=i.x?i.x*$h:void 0,y:null!=i.y?i.y*t:void 0,w:null!=i.w?i.w*$h:void 0,h:null!=i.h?i.h*t:void 0,poly:i.poly?i.poly.map(e=>[e[0]*$h,e[1]*t]):void 0,wall_ids:Array.isArray(i.wall_ids)?[...i.wall_ids]:void 0}}),wall_segments:(e.wall_segments||[]).map(e=>({...e,id:String(e.id),a:[Number(e.a?.[0])*$h,Number(e.a?.[1])*t],b:[Number(e.b?.[0])*$h,Number(e.b?.[1])*t],cm:Number(e.cm)})),room_drafts:(e.room_drafts||[]).map(e=>({id:e.id,points:(e.points||[]).map(e=>[e[0]*$h,e[1]*t]),segments:(e.segments||[]).map(e=>({..."string"==typeof e.id&&e.id?{id:e.id}:{},cm:Number(e.cm)}))})),partitions:(e.partitions||[]).map(e=>({id:e.id,a:[e.a[0]*$h,e.a[1]*t],b:[e.b[0]*$h,e.b[1]*t],cm:Number(e.cm)})),wall_columns:(e.wall_columns||[]).map(e=>({id:e.id,shape:"circle"===e.shape?"circle":"square",center:[e.center[0]*$h,e.center[1]*t],cm:Number(e.cm),..."circle"===e.shape?{}:{angle:Zc(e.angle)}}))}}):[]}const Ih=5e3,Rh=Ih*$h,Ah=240,zh=$h/Ah,Fh=1/Ah;function Eh(e){if(!Number.isFinite(e))return e;const t=Math.round(e*Ah/$h)*$h/Ah;return Math.abs(t-e)<=1e-9*zh?e:t}function Nh(e){return{x:Eh(e.x),y:Eh(e.y)}}function Oh(e){return Number.isFinite(e)?Math.min(Rh,Math.max(-Rh,e)):0}function Lh(e){return Number.isFinite(e)?Math.min(Ih,Math.max(-Ih,e)):0}const Hh=1/3,Bh=200;function qh(e){let t=1/0,i=1/0,s=-1/0,n=-1/0;for(const o of e){const e=Number(o[0]),a=Number(o[1]);Number.isFinite(e)&&Number.isFinite(a)&&(es&&(s=e),a>n&&(n=a))}return t>s?null:{minX:t,minY:i,maxX:s,maxY:n}}function Wh(e){return e.poly&&e.poly.length?qh(e.poly):null==e.x||null==e.y?null:qh([[e.x,e.y],[e.x+(e.w||0),e.y+(e.h||0)]])}function jh(e,t){const i=[];for(const t of e.rooms||[]){const e=Wh(t);e&&i.push(e)}if(e.bg){const t=qh(jr(e.bg));t&&i.push(t)}for(const e of t||[])if(Array.isArray(e)){const t=qh([e]);t&&i.push(t)}else i.push(e);return i}const Uh=e=>{if(!e.length)return 0;const t=[...e].sort((e,t)=>e-t),i=t.length>>1;return t.length%2?t[i]:(t[i-1]+t[i])/2},Gh=e=>{let t=1/0,i=1/0,s=-1/0,n=-1/0;for(const o of e)o.minXs&&(s=o.maxX),o.maxY>n&&(n=o.maxY);return t>s||i>n?null:{x:t,y:i,w:s-t,h:n-i}};function Vh(e,t){let{x:i,y:s,w:n,h:o}=e;n<30&&(i=i+n/2-100,n=Bh),o<30&&(s=s+o/2-100,o=Bh);const a=Math.max(n,o)*t;return{x:i-a,y:s-a,w:n+2*a,h:o+2*a}}function Kh(e,t={}){const i=t.pad??.05,s=t.k??10,n=t.minSpread??50,o=e.filter(e=>Number.isFinite(e.minX)&&Number.isFinite(e.minY)&&Number.isFinite(e.maxX)&&Number.isFinite(e.maxY)&&Math.abs(e.minX)<=Rh&&Math.abs(e.maxX)<=Rh&&Math.abs(e.minY)<=Rh&&Math.abs(e.maxY)<=Rh);if(!o.length)return{core:null,all:null,outliers:0};const a=Gh(o);if(o.length<4){const e=Vh(a,i);return{core:e,all:e,outliers:0}}const r=o.map(e=>(e.minX+e.maxX)/2),l=o.map(e=>(e.minY+e.maxY)/2),c=Uh(r),h=Uh(l),d=o.map((e,t)=>Math.max(Math.abs(r[t]-c),Math.abs(l[t]-h))),p=Math.max(((e,t)=>e.length?e[Math.min(e.length-1,Math.max(0,Math.round(t*(e.length-1))))]:0)([...d].sort((e,t)=>e-t),.75),n),u=d.map(e=>e>s*p),_=u.filter(Boolean).length,m=_&&_<=o.length*Hh?o.filter((e,t)=>!u[t]):o;return{core:Vh(Gh(m)||a,i),all:Vh(a,i),outliers:m===o?0:_}}function Yh(e,t,i=.05){const s=Kh(jh(e,t),{pad:i});if(s.core)return s.core;const n=e.vb&&4===e.vb.length&&e.vb[2]>0&&e.vb[3]>0?e.vb:[0,0,$h,$h];return{x:n[0],y:n[1],w:n[2],h:n[3]}}function Jh(e){const t=Yh(e);return{x:t.x+t.w/2,y:t.y+t.h/2}}function Xh(e){const t=[];for(const i of e.rooms||[]){const e=Wh(i);e&&t.push(e)}const i=Kh(t,{pad:0}).core,s=$h*bh(e.cellCm??5);return i?Math.max(s,Math.min(Rh,Math.max(i.w,i.h))):s}function Zh(e,t,i,s=1){const n=Number(i),o=Number.isFinite(s)&&s>0?s:1;return!Number.isFinite(n)||n<=0?e*o:e*Xh(t)*o/n}const Qh=[1,2,5,10,20,50,100,200,500,1e3];function ed(e){if(e.poly&&e.poly.length){const t=e.poly.map(e=>e[0]),i=e.poly.map(e=>e[1]),s=Math.min(...t),n=Math.min(...i);return{x:s,y:n,w:Math.max(...t)-s,h:Math.max(...i)-n}}return{x:e.x??0,y:e.y??0,w:e.w??0,h:e.h??0}}function td(e,t,i,s){const n=i["rl_"+(e.id||"")];if(n&&n.s===t)return{x:n.x*$h,y:n.y*$h};const o=function(e){if(e.poly){const t=e.poly.length;return[e.poly.reduce((e,t)=>e+t[0],0)/t,e.poly.reduce((e,t)=>e+t[1],0)/t]}return[e.x+e.w/2,e.y+.1*Math.min(e.w,e.h)]}(e);return Nh({x:o[0],y:o[1]})}const id=["furniture","appliance","sanitary","other"],sd=[{id:"sofa",group:"furniture",w:220,h:90,g:[["r",0,0,1,1],["l",.09,.26,.91,.26],["l",.09,.26,.09,1],["l",.91,.26,.91,1],["l",.5,.26,.5,1]]},{id:"armchair",group:"furniture",w:90,h:85,g:[["r",0,0,1,1],["l",.14,.28,.86,.28],["l",.14,.28,.14,1],["l",.86,.28,.86,1]]},{id:"coffee_table",group:"furniture",w:110,h:60,g:[["r",0,0,1,1],["r",.08,.14,.84,.72]]},{id:"table_dining",group:"furniture",w:140,h:80,g:[["r",0,0,1,1],["r",.06,.11,.88,.78]]},{id:"table_round",group:"furniture",w:120,h:120,g:[["e",.5,.5,.5,.5],["e",.5,.5,.41,.41]]},{id:"chair",group:"furniture",w:45,h:45,g:[["r",0,0,1,.18],["r",.06,.18,.88,.8]]},{id:"desk",group:"furniture",w:120,h:60,g:[["r",0,0,1,1],["r",.63,.07,.31,.86],["l",.63,.5,.94,.5]]},{id:"bed_double",group:"furniture",w:160,h:200,g:[["r",0,0,1,1],["r",0,0,1,.07],["r",.06,.1,.4,.15],["r",.54,.1,.4,.15],["l",0,.33,1,.33]]},{id:"bed_single",group:"furniture",w:90,h:200,g:[["r",0,0,1,1],["r",0,0,1,.07],["r",.15,.1,.7,.15],["l",0,.33,1,.33]]},{id:"nightstand",group:"furniture",w:45,h:40,g:[["r",0,0,1,1],["r",.12,.14,.76,.33],["r",.12,.53,.76,.33]]},{id:"wardrobe",group:"furniture",w:100,h:60,g:[["r",0,0,1,1],["l",0,.72,1,.72],["l",.5,.72,.5,1]]},{id:"bookshelf",group:"furniture",w:80,h:30,g:[["r",0,0,1,1],["l",.34,0,.34,1],["l",.67,0,.67,1]]},{id:"fridge",group:"appliance",w:60,h:65,g:[["r",0,0,1,1],["l",0,.36,1,.36],["l",.83,.44,.83,.64]]},{id:"stove",group:"appliance",w:60,h:60,g:[["r",0,0,1,1],["e",.29,.31,.15,.15],["e",.71,.31,.15,.15],["e",.29,.71,.15,.15],["e",.71,.71,.15,.15]]},{id:"dishwasher",group:"appliance",w:60,h:60,g:[["r",0,0,1,1],["r",.1,.12,.8,.76],["e",.5,.5,.27,.27],["e",.5,.5,.13,.13]]},{id:"washer",group:"appliance",w:60,h:60,g:[["r",0,0,1,1],["l",.08,.17,.92,.17],["e",.5,.57,.3,.3],["e",.5,.57,.14,.14]]},{id:"dryer",group:"appliance",w:60,h:60,g:[["r",0,0,1,1],["l",.08,.17,.92,.17],["e",.5,.57,.3,.3],["p",.36,.5,.5,.64,.64,.5]]},{id:"tv",group:"appliance",w:120,h:30,g:[["r",0,0,1,.42],["l",.5,.42,.5,.72],["l",.3,.72,.7,.72]]},{id:"ac",group:"appliance",w:90,h:25,g:[["r",0,0,1,1],["l",.05,.55,.95,.55],["l",.05,.79,.95,.79]]},{id:"water_heater",group:"appliance",w:45,h:45,g:[["e",.5,.5,.5,.5],["e",.5,.5,.31,.31]]},{id:"toilet",group:"sanitary",w:40,h:70,g:[["r",.06,0,.88,.2],["e",.5,.58,.37,.35],["e",.5,.58,.22,.2]]},{id:"bathtub",group:"sanitary",w:170,h:75,g:[["r",0,0,1,1],["r",.05,.11,.77,.78],["e",.89,.5,.045,.1]]},{id:"shower",group:"sanitary",w:90,h:90,g:[["r",0,0,1,1],["l",0,0,1,1],["l",1,0,0,1],["e",.5,.5,.08,.08]]},{id:"sink",group:"sanitary",w:60,h:45,g:[["r",0,0,1,1],["e",.5,.6,.34,.3],["e",.5,.15,.07,.07]]},{id:"kitchen_sink",group:"sanitary",w:80,h:60,g:[["r",0,0,1,1],["r",.06,.24,.44,.64],["r",.54,.24,.4,.64],["e",.5,.12,.06,.06]]},{id:"bidet",group:"sanitary",w:40,h:55,g:[["e",.5,.5,.44,.5],["e",.5,.5,.26,.3]]},{id:"stairs",group:"other",w:100,h:280,g:[["r",0,0,1,1],["l",0,.111,1,.111],["l",0,.222,1,.222],["l",0,.333,1,.333],["l",0,.444,1,.444],["l",0,.556,1,.556],["l",0,.667,1,.667],["l",0,.778,1,.778],["l",0,.889,1,.889],["l",.5,.93,.5,.06],["p",.38,.16,.5,.06,.62,.16]]},{id:"fireplace",group:"other",w:120,h:40,g:[["r",0,0,1,1],["p",.22,1,.22,.42,.78,.42,.78,1]]},{id:"plant",group:"other",w:40,h:40,g:[["e",.5,.5,.22,.22],["l",.5,.28,.5,.02],["l",.5,.72,.5,.98],["l",.28,.5,.02,.5],["l",.72,.5,.98,.5],["l",.34,.34,.13,.13],["l",.66,.66,.87,.87],["l",.66,.34,.87,.13],["l",.34,.66,.13,.87]]},{id:"rug",group:"other",w:200,h:140,g:[["r",0,0,1,1],["r",.06,.09,.88,.82]]}],nd=new Map(sd.map(e=>[e.id,e]));function od(e){return e&&nd.get(e)||null}function ad(e){return sd.filter(t=>t.group===e)}function rd(e,t,i=zh,s=1e3){const n=Number(t)>0?Number(t):5;return(Number(e)||0)/n*i/s}const ld=5e-4,cd=Ih;function hd(e){return Number.isFinite(e)?Math.max(ld,Math.min(cd,e)):ld}const dd=e=>{const t=Math.round(1e3*e)/1e3;return Object.is(t,-0)?"0":String(t)};function pd(e,t,i){const s=od(e);if(!(s&&t>0&&i>0))return"";const n=e=>dd(e*t),o=e=>dd(e*i),a=[];for(const e of s.g)if("r"===e[0]){const[,t,i,s,r]=e;a.push(`M${n(t)} ${o(i)}H${n(t+s)}V${o(i+r)}H${n(t)}Z`)}else if("l"===e[0]){const[,t,i,s,r]=e;a.push(`M${n(t)} ${o(i)}L${n(s)} ${o(r)}`)}else if("e"===e[0]){const[,s,r,l,c]=e;a.push(`M${n(s-l)} ${o(r)}A${dd(l*t)} ${dd(c*i)} 0 0 1 ${n(s+l)} ${o(r)}A${dd(l*t)} ${dd(c*i)} 0 0 1 ${n(s-l)} ${o(r)}Z`)}else{const t=e.slice(1);if(t.length<4)continue;let i=`M${n(t[0])} ${o(t[1])}`;for(let e=2;e+1{let t=(e%360+360)%360;return t>180&&(t-=360),t};function _d(e,t,i,s,n,o=0){let a=null,r=n;for(const n of s){const[s,l,c,h]=n,d=c-s,p=h-l,u=d*d+p*p;if(!u)continue;const _=Math.sqrt(u);let m=((e-s)*d+(t-l)*p)/u;m=Math.max(0,Math.min(1,m));let g=s+m*d,f=l+m*p;const v=Math.hypot(e-g,t-f);if(!(v0){const e=Math.round(m*_/o)*o;g=s+e/_*d,f=l+e/_*p}a={cx:g+y*(i/2),cy:f+b*(i/2),angle:ud(180*Math.atan2(-y,b)/Math.PI),dist:v}}return a}function md(e,t,i){const s=i>0?i:1;return{a:[e[0]/s,e[1]/s],b:[t[0]/s,t[1]/s]}}function gd(e,t){const i=t>0?t:1;return[e.a[0]*i,e.a[1]*i,e.b[0]*i,e.b[1]*i]}function fd(e){return Array.isArray(e)&&e.length>=2&&Number.isFinite(Number(e[0]))&&Number.isFinite(Number(e[1]))}function vd(e){if(!Array.isArray(e))return[];const t=[];for(const i of e){if(!i||"object"!=typeof i)continue;const e=i;if(!fd(e.a)||!fd(e.b))continue;const s=[Number(e.a[0]),Number(e.a[1])],n=[Number(e.b[0]),Number(e.b[1])];Math.hypot(n[0]-s[0],n[1]-s[1])<.001||t.push({a:s,b:n})}return t}function yd(e,t,i,s,n=!0){const o=(e||[]).filter(e=>e?.id),a=vd(t);if(a.length)return function(e,t,i,s){const n=vd(e);if(!n.length)return[];const o=function(e,t){const i=[],s=(e||[]).filter(e=>e?.id);for(let e=0;e4*s||o>4*s)continue;const a=(e[0]-n)*p+(e[1]-l)*u,c=(e[2]-n)*p+(e[3]-l)*u,h=Math.max(0,Math.min(a,c)),m=Math.min(d,Math.max(a,c));if(m-he.lo-t.lo||e.hi-t.hi);const i=[];for(const e of t){const t=i[i.length-1];t&&e.lo<=t.hi+r?t.hi=Math.max(t.hi,e.hi):i.push({...e})}for(const t of i){const i=[n+p*t.lo,l+u*t.lo],s=[n+p*t.hi,l+u*t.hi];Math.hypot(s[0]-i[0],s[1]-i[1])i.pair===e&&Math.abs(i.ux*a-i.uy*o)<=1e-6&&Math.abs((t[0]-i.origin[0])*i.uy-(t[1]-i.origin[1])*i.ux)<=c&&Math.abs((t[2]-i.origin[0])*i.uy-(t[3]-i.origin[1])*i.ux)<=c);h||(h={pair:e,origin:[t[0],t[1]],ux:o,uy:a,ranges:[]},l.push(h));const d=(t[0]-h.origin[0])*h.ux+(t[1]-h.origin[1])*h.uy,p=(t[2]-h.origin[0])*h.ux+(t[3]-h.origin[1])*h.uy;h.ranges.push({lo:Math.min(d,p),hi:Math.max(d,p)})}const h=[];for(const e of l){e.ranges.sort((e,t)=>e.lo-t.lo||e.hi-t.hi);const t=[];for(const i of e.ranges){const e=t[t.length-1];e&&i.lo<=e.hi+r?e.hi=Math.max(e.hi,i.hi):t.push({...i})}for(const s of t){const t=[e.origin[0]+e.ux*s.lo,e.origin[1]+e.uy*s.lo],n=[e.origin[0]+e.ux*s.hi,e.origin[1]+e.uy*s.hi];Math.hypot(n[0]-t[0],n[1]-t[1])>=r&&h.push(md(t,n,i))}}return h}(a,e,i,s).map(e=>gd(e,i));if(!n)return[];const r=[],l=(e,t)=>(e.open_to||[]).includes(t.id)||(t.open_to||[]).includes(e.id);for(let e=0;e{const t=kd.get(e);if(!t)return;const i=Date.now();if("hidden"===e.visibilityState){t.hiddenAt||(t.hiddenAt=i);const e={kind:"hidden",token:t.token,at:i,hiddenFor:0,long:!1};for(const i of[...t.subscribers])i(e);return}const s=t.hiddenAt?Math.max(0,i-t.hiddenAt):0;t.hiddenAt=0,t.token++;const n={kind:"visible",token:t.token,at:i,hiddenFor:s,long:s>=bd};for(const e of[...t.subscribers])e(n)},onPageShow:t=>{const i=kd.get(e);if(!i)return;const s=Date.now();i.token++;const n={kind:"pageshow",token:i.token,at:s,hiddenFor:0,long:!!t.persisted,persisted:!!t.persisted};for(const e of[...i.subscribers])e(n)}},kd.set(e,i),e.addEventListener("visibilitychange",i.onVisibility),e.defaultView?.addEventListener("pageshow",i.onPageShow)}return i.subscribers.add(t),()=>{const i=kd.get(e);i&&(i.subscribers.delete(t),i.subscribers.size||(e.removeEventListener("visibilitychange",i.onVisibility),e.defaultView?.removeEventListener("pageshow",i.onPageShow),kd.delete(e)))}}const $d={now:()=>Date.now(),setTimeout:(e,t)=>window.setTimeout(e,t),clearTimeout:e=>window.clearTimeout(e),requestAnimationFrame:e=>window.requestAnimationFrame(e),cancelAnimationFrame:e=>window.cancelAnimationFrame(e)};class Sd{constructor(e,t=$d){this.onChange=e,this.clock=t,this._state="steady",this._token=0,this._frameFingerprint="",this._hasCompleteFrame=!1,this._overlayPhase="none",this._recoveryReason=null,this._overlayTimer=0,this._overlayRaf=0,this._overlayOpaqueAt=0,this._barrierRafs=new Set,this._trace=[],this._disposed=!1}get state(){return this._state}get token(){return this._token}get frameFingerprint(){return this._frameFingerprint}get hasCompleteFrame(){return this._hasCompleteFrame}get overlayPhase(){return this._overlayPhase}get overlayVisible(){return"none"!==this._overlayPhase}get overlayBlocksInteraction(){return this.overlayVisible}get recoveryReason(){return this._recoveryReason}get trace(){return this._trace.map(e=>({...e,...e.stage?{stage:[...e.stage]}:{}}))}note(e,t={}){this.record(e,void 0,t)}record(e,t,i={}){this._trace.push({at:this.clock.now(),token:this._token,event:e,state:this._state,...t?{reason:t}:{},...i}),this._trace.length>80&&this._trace.splice(0,this._trace.length-80)}changed(){this._disposed||this.onChange()}adoptCompleteFrame(e){e&&(this._hasCompleteFrame=!0,this._frameFingerprint=e,this._state="steady",this._recoveryReason=null,this.clearOverlay(),this.record("frame-adopted"),this.changed())}markCompleteFrame(e){e&&(this._hasCompleteFrame=!0,this._frameFingerprint=e,this._state="steady",this._recoveryReason=null,this.clearOverlay(),this.record("frame-complete"),this.changed())}refreshCompleteFrame(e){!this._disposed&&this._hasCompleteFrame&&"steady"===this._state&&e&&e!==this._frameFingerprint&&(this._frameFingerprint=e,this.record("frame-refreshed"))}visibility(e){return"hidden"===e.kind?(this.record("visibility-hidden"),this._token):e.long||"visible"!==e.kind&&"pageshow"!==e.kind?this.beginCandidate("pageshow"===e.kind?"pageshow":"long-resume"):(this.record("pageshow"===e.kind?"pageshow-noop":"visibility-visible-quick"),this._token)}beginCandidate(e,t="plan"){return this._token++,this._recoveryReason=t,this._hasCompleteFrame?(this._state="connection"===t?"offline-stale":"holding",this.clearOverlay()):this.overlayVisible?this._state="overlay-visible":(this._state="overlay-pending",this.scheduleOverlay(t)),this.record("candidate-start",e),this.changed(),this._token}connectionLost(){return this.beginCandidate("connection-lost","connection")}candidateReady(e){return!this._disposed&&e===this._token&&(this._state="candidate-ready",this.record("candidate-ready"),this.changed(),!0)}async commitAfterPaint(e,t){if(this._disposed||e!==this._token)return!1;let i=!0;const s=(async()=>{for(await t.updateComplete();i&&!this._disposed&&e===this._token;)if(t.stageValid()&&t.assetsReady()){if(await this.nextFrame(),e!==this._token||!t.stageValid()||!t.assetsReady())continue;if(await this.nextFrame(),e===this._token&&t.stageValid()&&t.assetsReady())return!0}else await this.nextFrame();return!1})();let n=0;const o=new Promise(e=>{n=this.clock.setTimeout(()=>e({ready:!1,timedOut:!0}),wd)}),a=await Promise.race([s.then(e=>({ready:e,timedOut:!1})),o]);return i=!1,this.clock.clearTimeout(n),!this._disposed&&e===this._token&&(!(!a.ready&&!a.timedOut)&&(a.ready?(this._hasCompleteFrame=!0,this._frameFingerprint=t.frameFingerprint(),this.record("paint-barrier"),this.finishOverlayAfterCommit(),!0):(this.record("paint-barrier-timeout"),this._hasCompleteFrame?(this._state="connection"===this._recoveryReason?"offline-stale":"steady",this.clearOverlay()):(this._state="recovery-error","opaque"!==this._overlayPhase&&this.showOverlayNow()),this.changed(),!1)))}retry(e=this._recoveryReason||"plan"){return this.beginCandidate("retry",e)}nextFrame(){return new Promise(e=>{const t=this.clock.requestAnimationFrame(()=>{this._barrierRafs.delete(t),e()});this._barrierRafs.add(t)})}scheduleOverlay(e){this.clearOverlayTimer(),this._recoveryReason=e,this._overlayTimer=this.clock.setTimeout(()=>{this._overlayTimer=0,this._hasCompleteFrame||"overlay-pending"!==this._state&&"candidate-ready"!==this._state||(this._state="overlay-visible",this._overlayPhase="entering",this.record("overlay-enter"),this.changed(),this._overlayRaf=this.clock.requestAnimationFrame(()=>{this._overlayRaf=0,"entering"===this._overlayPhase&&(this._overlayPhase="fading-in",this.changed(),this._overlayTimer=this.clock.setTimeout(()=>{this._overlayTimer=0,"fading-in"===this._overlayPhase&&(this._overlayPhase="opaque",this._overlayOpaqueAt=this.clock.now(),this.record("overlay-opaque"),this.changed())},150))}))},150)}showOverlayNow(){this.clearOverlayTimer(),this._overlayPhase="opaque",this._overlayOpaqueAt=this.clock.now(),this.record("overlay-error")}finishOverlayAfterCommit(){if(this.clearOverlayTimer(),"none"===this._overlayPhase||"entering"===this._overlayPhase||"fading-in"===this._overlayPhase)return this.clearOverlay(),this._state="steady",this._recoveryReason=null,this.record("candidate-committed"),void this.changed();const e=Math.max(0,this._overlayOpaqueAt+250-this.clock.now());this._overlayTimer=this.clock.setTimeout(()=>{this._overlayTimer=0,this._overlayPhase="leaving",this.record("overlay-leave"),this.changed(),this._overlayTimer=this.clock.setTimeout(()=>{this._overlayTimer=0,this._overlayPhase="none",this._state="steady",this._recoveryReason=null,this.record("candidate-committed"),this.changed()},180)},e)}clearOverlayTimer(){this._overlayTimer&&this.clock.clearTimeout(this._overlayTimer),this._overlayTimer=0}clearOverlay(){this.clearOverlayTimer(),this._overlayRaf&&this.clock.cancelAnimationFrame(this._overlayRaf),this._overlayRaf=0,this._overlayPhase="none",this._overlayOpaqueAt=0}dispose(){this._disposed=!0,this._token++,this.clearOverlay();for(const e of this._barrierRafs)this.clock.cancelAnimationFrame(e);this._barrierRafs.clear()}}function Md(e){let t=2166136261,i=2654435769;const s=new WeakSet,n=e=>{for(let s=0;s>>0)+(i>>>2)}},o=e=>{if(null===e)return void n("n");const t=typeof e;if("string"===t)return void n(`s${e.length}:${e}`);if("number"===t)return void n(`d${Number.isNaN(e)?"NaN":String(e)}`);if("boolean"===t)return void n(e?"t":"f");if("undefined"===t)return void n("u");if("object"!==t)return void n(`${t}:${String(e)}`);const i=e;if(s.has(i))n("[cycle]");else{if(s.add(i),Array.isArray(e)){n("[");for(const t of e)o(t);return n("]"),void s.delete(i)}n("{");for(const t of Object.keys(e).sort())n(t),o(e[t]);n("}"),s.delete(i)}};return o(e),`${(t>>>0).toString(16).padStart(8,"0")}${(i>>>0).toString(16).padStart(8,"0")}`}function Cd(e){return Md(e)}const Dd=new WeakMap;class Pd{constructor(e,t=()=>Date.now()){this.onUpdate=e,this.now=t,this.fallbackAuthority={},this.referenceOwner={},this.referenced=new Set,this.queued=new Set,this.disposed=!1,this.sharedUpdate=()=>{this.disposed||this.onUpdate()}}bind(e){const t=((e,t)=>{const i=e?.connection||e?.callWS||t;return!i||"object"!=typeof i&&"function"!=typeof i?t:i})(e,this.fallbackAuthority);return this.shared&&this.authority===t||(this.shared&&(this.shared.listeners.delete(this.sharedUpdate),this.shared.references.delete(this.referenceOwner)),this.authority=t,this.shared=(e=>{let t=Dd.get(e);return t||(t={signed:{},queued:new Set,inFlight:new Map,retry:new Map,listeners:new Set,settlers:new Set,references:new Map},Dd.set(e,t)),t})(t),this.disposed||(this.shared.listeners.add(this.sharedUpdate),this.shared.references.set(this.referenceOwner,new Set(this.referenced)))),this.shared}start(e,t){this.disposed=!1,this.referenced=new Set(t());const i=this.bind(e());i.listeners.add(this.sharedUpdate),i.references.set(this.referenceOwner,new Set(this.referenced)),this.stopTimer(),this.resignTimer=setInterval(()=>this.resign(e(),t()),288e5)}dispose(){if(this.disposed=!0,this.stopTimer(),clearTimeout(this.batchTimer),this.shared){this.shared.listeners.delete(this.sharedUpdate),this.shared.references.delete(this.referenceOwner);for(const e of this.queued)this.shared.queued.delete(e)}this.queued.clear()}invalidate(e){const t=this.bind(e);clearTimeout(this.batchTimer),this.queued.clear(),t.queued.clear(),t.inFlight.clear(),t.retry.clear(),t.signed={}}stopTimer(){void 0!==this.resignTimer&&clearInterval(this.resignTimer),this.resignTimer=void 0}display(e,t){const i=As(t);if(!i.startsWith("/api/houseplan/content/"))return i;const s=this.bind(e);this.referenced.add(i),s.references.set(this.referenceOwner,new Set(this.referenced));const n=s.signed[i],o=n?this.now()-n.at:1/0;return o{const t=[...this.queued];this.queued.clear();for(const e of t)i.queued.delete(e);this.sign(e,t)},30))}sign(e,t){if(!t.length||!e?.callWS)return;const i=this.bind(e);for(const s of function(e,t){const i=Math.max(1,Math.floor(t)),s=[];for(let t=0;t{const s=i.inFlight.get(e);return!(void 0!==s&&t-s<15e3)&&(i.inFlight.set(e,t),!0)});n.length&&e.callWS({type:"houseplan/content/sign",paths:n}).then(e=>{const t=this.now();let s=0,o=!1;for(const a of n){const n=e?.urls?.[a];if("string"==typeof n&&n){const e=i.signed[a];e?.loaded&&e.url!==n?(e.pending={url:n,at:t},this.preloadReplacement(i,a,n,t)):(i.signed[a]={url:n,at:t,loaded:e?.url===n&&!!e.loaded},o=!0),i.retry.delete(a),s++}else this.backOff(i,a)}if(s&&(this.trimShared(i),o))for(const e of[...i.listeners])e()}).catch(()=>{for(const e of n)this.backOff(i,e)}).finally(()=>{for(const e of n)i.inFlight.get(e)===t&&i.inFlight.delete(e);for(const e of[...i.settlers])e()})}}preloadReplacement(e,t,i,s){const n=()=>{const n=e.signed[t];if(n?.pending?.url===i){e.signed[t]={url:i,at:s,loaded:!0},e.retry.delete(t),this.trimShared(e);for(const t of[...e.listeners])t()}},o=()=>{const s=e.signed[t];s?.pending?.url===i&&(delete s.pending,this.backOff(e,t))};if("undefined"==typeof Image)return void n();const a=new Image;a.onload=()=>{("function"==typeof a.decode?a.decode():Promise.resolve()).then(n).catch(o)},a.onerror=o,a.src=i}preloadCurrentImage(e,t,i){if(i.loaded)return Promise.resolve(!0);if(i.preload)return i.preload;if("undefined"==typeof Image)return i.loaded=!0,Promise.resolve(!0);const s=i.url;return i.preload=new Promise(n=>{const o=new Image;let a=!1;const r=o=>{if(a)return;a=!0,clearTimeout(l);const r=e.signed[t];if(r===i&&delete r.preload,o&&r===i&&r.url===s){r.loaded=!0;for(const t of[...e.listeners])t();n(!0)}else o||r!==i||this.backOff(e,t),n(!1)};o.onload=()=>{("function"==typeof o.decode?o.decode():Promise.resolve()).then(()=>r(!0)).catch(()=>r(!1))},o.onerror=()=>r(!1);const l=setTimeout(()=>r(!1),wd);o.src=s}),i.preload}prepareImage(e,t){const i=As(t);if(!i.startsWith("/api/houseplan/content/"))return Promise.resolve(!0);const s=this.bind(e),n=()=>{const t=s.signed[i];if(t&&this.now()-t.atthis.now()&&!s.inFlight.has(i)&&!s.queued.has(i)?Promise.resolve(!1):null},o=n();return o?(a=o,new Promise(e=>{let t=!1;const i=i=>{t||(t=!0,clearTimeout(s),e(i))},s=setTimeout(()=>i(!1),wd);a.then(i).catch(()=>i(!1))})):new Promise(e=>{let t=!1,i=null;const o=i=>{t||(t=!0,clearTimeout(r),s.settlers.delete(a),e(i))},a=()=>{t||i||(i=n(),i&&i.then(o).catch(()=>o(!1)))},r=setTimeout(()=>o(!1),wd);s.settlers.add(a),a()});var a}backOff(e,t){const i=e.retry.get(t)?.delay||0,s=Math.min(6e4,i?2*i:2e3);e.retry.set(t,{notBefore:this.now()+s,delay:s})}trimShared(e){const t=Object.entries(e.signed);if(t.length<=512)return;const i=new Set(e.inFlight.keys());for(const t of e.references.values())for(const e of t)i.add(e);for(const[e,s]of t)(s.pending||s.preload)&&i.add(e);t.sort((e,t)=>t[1].at-e[1].at);const s=t.filter(([e])=>i.has(e));for(const e of t){if(s.length>=512)break;i.has(e[0])||s.push(e)}e.signed=Object.fromEntries(s)}resign(e,t){const i=this.bind(e);this.referenced=new Set(t),i.references.set(this.referenceOwner,new Set(this.referenced));const s=this.now(),n=new Set;for(const e of i.references.values())for(const t of e)n.add(t);const o={};for(const[e,t]of Object.entries(i.signed))n.has(e)&&s-t.at!!o[e]&&!o[e].pending))}markLoaded(e,t,i){const s=As(t);if(!s.startsWith("/api/houseplan/content/"))return;const n=this.bind(e).signed[s];if(n&&(!i||n.url===i)&&!n.loaded){n.loaded=!0;for(const t of[...this.bind(e).listeners])t()}}isReady(e,t){const i=As(t);if(!i.startsWith("/api/houseplan/content/"))return!0;const s=this.bind(e).signed[i];return!!s&&this.now()-s.ate.id===t)}function Id(e="file"){const t="draw"===e;return{source:e,showBorders:t,showNames:t,displayTouched:!1}}function Rd(e,t){if(e.displayTouched)return{...e,source:t};const i="draw"===t;return{...e,source:t,showBorders:i,showNames:i}}function Ad(e,t,i){return{...e,[t]:i,displayTouched:!0}}function zd(e,t,i){return[e[0]*t+e[1]*i+e[2],e[3]*t+e[4]*i+e[5]]}function Fd(e,t){let i=0;for(const[s,n]of t){const t=zd(e,s[0],s[1]);i=Math.max(i,Math.hypot(t[0]-n[0],t[1]-n[1]))}return i}const Ed=e=>{if(null==e||""===e)return null;const t=Number(e);return Number.isFinite(t)?t:null},Nd=e=>{const t=e,i=Ed(Array.isArray(t)?t[0]:t?.x),s=Ed(Array.isArray(t)?t[1]:t?.y);return null==i||null==s?null:[i,s]};function Od(e){if(!Array.isArray(e))return null;const t=[];for(const i of e){const e=Nd(i);if(!e)return null;t.push(e)}if(t.length>1){const e=t[0],i=t[t.length-1];e[0]===i[0]&&e[1]===i[1]&&t.pop()}if(t.length<3)return null;let i=0,s=0,n=0;for(let e=0;ee+t[0],0)/t.length,t.reduce((e,t)=>e+t[1],0)/t.length]:[s/(3*i),n/(3*i)]}function Ld(e){if(!Array.isArray(e))return null;const t=[];for(const i of e){const e=Nd(i);if(!e)return null;t.push(e)}if(t.length>1){const e=t[0],i=t[t.length-1];e[0]===i[0]&&e[1]===i[1]&&t.pop()}const i=Od(t);if(!i)return null;const s=t.map(e=>e[0]),n=t.map(e=>e[1]);return{centroid:i,bbox:[Math.min(...s),Math.min(...n),Math.max(...s),Math.max(...n)]}}function Hd(e){let t=e;if(t&&"object"==typeof t&&!Array.isArray(t)){const e=t;t=e.path??e.points??t}if(!Array.isArray(t)||!t.length)return[];let i=(t.some(e=>(e=>Array.isArray(e)?e.length>=2&&!Array.isArray(e[0])&&("object"!=typeof e[0]||null==e[0]):!!e&&"object"==typeof e&&("x"in e||"y"in e))(e))?[t]:t.filter(Array.isArray)).map(e=>e.map(Nd).filter(e=>null!=e)).filter(e=>e.length>=2);i.length>64&&(i=i.slice(-64));const s=i.reduce((e,t)=>e+t.length,0);if(s<=4e3)return i.map(e=>e.slice());const n=4e3-2*i.length,o=i.map(e=>e.length-2),a=o.reduce((e,t)=>e+t,0),r=o.map(e=>n*e/a),l=r.map(Math.floor);let c=n-l.reduce((e,t)=>e+t,0);const h=r.map((e,t)=>({index:t,fraction:e-Math.floor(e)})).sort((e,t)=>t.fraction-e.fraction||e.index-t.index);for(let e=0;efunction(e,t){if(t>=e.length)return e.slice();if(t<=2)return[e[0],e[e.length-1]];const i=[];for(let s=0;se.slice()),i=t[t.length-1];return i?(i.length>2?i.pop():t.pop(),t):[]}function Wd(e){if(!e)return null;const t=e.vacuum_position||e.robot_position||null,i=t&&null!=Ed(t.x)&&null!=Ed(t.y)?{x:Ed(t.x),y:Ed(t.y),a:Ed(t.a??t.angle??t.theta)}:null,s=Hd(e.path?.path??e.path?.points??e.path),n=[],o=e.rooms,a=Array.isArray(o)?o.map((e,t)=>[String(e?.id??t),e]):o&&"object"==typeof o?Object.entries(o):[];for(const[e,t]of a){if(!t||"object"!=typeof t)continue;const i=String(t.name??t.label??"").trim(),s=[[Ed(t.cx),Ed(t.cy)],[Ed(t.center?.x),Ed(t.center?.y)],[Ed(t.x),Ed(t.y)]].find(([e,t])=>null!=e&&null!=t);let o=s?.[0]??null,a=s?.[1]??null;const r=Ld(t.outline),l=Ed(t.x0),c=Ed(t.y0),h=Ed(t.x1),d=Ed(t.y1),p=(null!=l&&null!=c&&null!=h&&null!=d?[Math.min(l,h),Math.min(c,d),Math.max(l,h),Math.max(c,d)]:null)||r?.bbox||null;if(null!=o&&null!=a||!r||([o,a]=r.centroid),null!=o&&null!=a||!p||(o=(p[0]+p[2])/2,a=(p[1]+p[3])/2),i&&null!=o&&null!=a){const t={id:e,name:i,cx:o,cy:a};p&&([t.x0,t.y0,t.x1,t.y1]=p),n.push(t)}}const r=function(e){return String(e.map_name??e.current_map??e.map_index??e.selected_map??"default")}(e);return i||n.length||s.length?{pos:i,path:s,rooms:n,mapId:r}:null}function jd(e,t,i){if(!e||!t)return null;const s=t.attributes||{},n=e.split(".")[0]||"",o=null!=i?.platform?String(i.platform):null,a=!!Nd(s.vacuum_position??s.robot_position),r=!(!s.rooms||"object"!=typeof s.rooms),l=Hd(s.path?.path??s.path?.points??s.path).length>0,c=[s.map_name,s.current_map,s.map_index,s.selected_map].some(e=>null!=e),h="xiaomi_cloud_map_extractor"===o,d=r||l||c;let p=null;if(a?p="compatible":h?p="known_xcme_incomplete":d?p="partial":"camera"===n&&(p="camera"),!p)return null;const u=a?"camera"===n?300:200:h?100:d?50:0;return{entityId:e,name:String(s.friendly_name||e),platform:o,category:p,hasPosition:a,hasRooms:r,hasPath:l,hasMapId:c,score:u}}const Ud=e=>e.toLowerCase().replace(/[\s_\-.,]+/g,"");function Gd(e,t){const i=new Map(t.map(e=>[Ud(e.name),e])),s=[],n=[];for(const t of e){const e=i.get(Ud(t.name));e&&(s.push([[t.cx,t.cy],[e.cx,e.cy]]),n.push(t.name))}if(s.length<3)return null;const o=function(e){if(e.length<3)return null;let t=0,i=0,s=0,n=0,o=0,a=0,r=0,l=0,c=0,h=0,d=0,p=0;for(const[[u,_],[m,g]]of e){if(![u,_,m,g].every(Number.isFinite))return null;t+=u*u,i+=u*_,s+=u,n+=_*_,o+=_,a+=1,r+=u*m,l+=_*m,c+=m,h+=u*g,d+=_*g,p+=g}const u=[t,i,s,i,n,o,s,o,a],_=e=>{const[t,i,s,n,o,a,r,l,c]=u,h=t*(o*c-a*l)-i*(n*c-a*r)+s*(n*l-o*r);if(!Number.isFinite(h)||Math.abs(h)<1e-9)return null;const d=[(o*c-a*l)/h,(s*l-i*c)/h,(i*a-s*o)/h,(a*r-n*c)/h,(t*c-s*r)/h,(s*n-t*a)/h,(n*l-o*r)/h,(i*r-t*l)/h,(t*o-i*n)/h];return[d[0]*e[0]+d[1]*e[1]+d[2]*e[2],d[3]*e[0]+d[4]*e[1]+d[5]*e[2],d[6]*e[0]+d[7]*e[1]+d[8]*e[2]]},m=_([r,l,c]),g=_([h,d,p]);if(!m||!g)return null;const f=[m[0],m[1],m[2],g[0],g[1],g[2]];return f.every(Number.isFinite)?f:null}(s);return o?{matrix:o,matched:n,residual:Fd(o,s)}:null}function Vd(e,t,i){const s=e[e.length-1];if(s&&s[0]===t[0]&&s[1]===t[1])return e;if(e.push(t),e.length<=600)return e;let n=function(e,t){if(e.length<3)return e.slice();const i=new Uint8Array(e.length);i[0]=i[e.length-1]=1;const s=[[0,e.length-1]];for(;s.length;){const[n,o]=s.pop(),[a,r]=e[n],[l,c]=e[o],h=l-a,d=c-r,p=Math.hypot(h,d)||1e-9;let u=0,_=-1;for(let t=n+1;tu&&(u=i,_=t)}_>0&&u>t&&(i[_]=1,s.push([n,_],[_,o]))}const n=[];for(let t=0;t600&&(n=n.filter((e,t)=>t%2==0||t===n.length-1)),n}function Kd(e){return"cleaning"===e||"returning"===e||"on"===e}const Yd={0:[1,0],90:[0,1],180:[-1,0],270:[0,-1]};function Jd(e){const[t,i]=Yd[e.rot]||[1,0],s=e.mir?-1:1;return[e.s*t*s,-e.s*i,e.ox,e.s*i*s,e.s*t,e.oy]}function Xd(e){const t=e[0]*e[4]-e[1]*e[3];if(!Number.isFinite(t)||Math.abs(t)<1e-12)return null;const i=t<0,s=Math.sqrt(Math.abs(t));let n=180*Math.atan2(-e[1],e[4])/Math.PI;return n=(90*Math.round(n/90)%360+360)%360,{ox:e[2],oy:e[5],s:s,rot:n,mir:i}}function Zd(e,t,i,s){const[n,o]=zd(Jd(t),i,s),a=Jd({...e,ox:0,oy:0}),[r,l]=zd(a,i,s);return{...e,ox:n-r,oy:o-l}}function Qd(e){const t=e?.trail_mode;return"never"===t||"cleaning"===t||"always"===t?t:!1===e?.trail?"never":"cleaning"}const ep={offStates:["off"],unknownUsesToggle:!0},tp={light:ep,switch:ep,fan:ep,humidifier:ep,input_boolean:ep,automation:ep,remote:ep,group:ep,climate:{...ep,featureMasks:{turn_on:256,turn_off:128,toggle:384}},media_player:{...ep,featureMasks:{turn_on:128,turn_off:256,toggle:384}},siren:{...ep,featureMasks:{turn_on:1,turn_off:2,toggle:3}},vacuum:{...ep,featureMasks:{turn_on:1,turn_off:2,toggle:3}},water_heater:{...ep,featureMasks:{turn_on:8,turn_off:8,toggle:8}},camera:{...ep,featureMasks:{turn_on:1,turn_off:1,toggle:1}}};function ip(e){return e.slice(0,e.indexOf("."))}function sp(e,t,i){if(!e?.services||"object"!=typeof e.services)return!1;const s=e.services?.[t];return!!s&&Object.prototype.hasOwnProperty.call(s,i)}function np(e,t,i){return sp(e,t,i)?{domain:t,service:i}:sp(e,"homeassistant",i)?{domain:"homeassistant",service:i}:null}function op(e,t){return e?.entities?.[t]||null}function ap(e,t,i){const s=e?.states?.[i],n=op(t,i);return s?.attributes?.friendly_name||n?.name||n?.original_name||i}function rp(e,t){const i=op(e,t);if(null!=i?.disabled_by)return!0;const s=i?.device_id?e?.devices?.[i.device_id]:null;return null!=s?.disabled_by}function lp(e,t){const i=e?.attributes?.supported_features;if(null==i||""===i)return!1;const s=Number(i);return Number.isFinite(s)&&(s&t)===t}function cp(e,t,i){const s=ip(i);if("lock"===s||"alarm_control_panel"===s)return!0;if("cover"!==s)return!1;const n=e?.states?.[i],o=op(t,i),a=String(n?.attributes?.device_class||o?.device_class||o?.original_device_class||"");return Ui.has(a)}function hp(e,t,i,s,n){return{ref:i,entityId:s,name:s?ap(e,t,s):null,reason:n}}function dp(e,t,i,s,n,o=null){return{target:null,skipped:hp(e,t,i,s,n),semantics:o,nextEffect:null,command:null}}function pp(e,t,i,s,n=i){const o=ip(i);if("cover"!==o&&"valve"!==o)return function(e,t,i,s,n=i){const o=ip(i),a=e?.states?.[i];if(rp(t,i))return dp(e,t,n,i,"ha-disabled","power");if(cp(e,t,i))return dp(e,t,n,i,"secure");if(!a)return dp(e,t,n,i,"missing","power");if("unavailable"===a.state)return dp(e,t,n,i,"unavailable","power");const r=tp[o];if(!r)return dp(e,t,n,i,"unsupported");let l,c;if("unknown"===a.state||""===a.state){if(!r.unknownUsesToggle)return dp(e,t,n,i,"unsupported","power");l="toggle",c="toggle"}else r.offStates.includes(String(a.state))?(l="turn-on",c="turn_on"):(l="turn-off",c="turn_off");const h=r.featureMasks?.[c];if(h&&!lp(a,h))return dp(e,t,n,i,"unsupported","power");const d=np(e,o,c);return d?{target:{entityId:i,name:ap(e,t,i),state:String(a.state||""),via:s},skipped:null,semantics:"power",nextEffect:l,command:{...d,data:{entity_id:i}}}:dp(e,t,n,i,"unsupported","power")}(e,t,i,s,n);if(rp(t,i))return dp(e,t,n,i,"ha-disabled",o);if(cp(e,t,i))return dp(e,t,n,i,"secure",o);const a=e?.states?.[i];if(!a)return dp(e,t,n,i,"missing",o);if("unavailable"===a.state)return dp(e,t,n,i,"unavailable",o);const r=function(e,t,i){const s=String(i?.state||""),n="closed"===s?{service:`open_${t}`,effect:"open",feature:1}:"open"===s?{service:`close_${t}`,effect:"close",feature:2}:"opening"===s||"closing"===s?{service:`stop_${t}`,effect:"stop",feature:8}:null;return n&&lp(i,n.feature)&&sp(e,t,n.service)?n:lp(i,3)&&sp(e,t,"toggle")?{service:"toggle",effect:"toggle"}:null}(e,o,a);if(!r)return dp(e,t,n,i,"unsupported",o);return{target:{entityId:i,name:ap(e,t,i),state:String(a.state||""),via:s},skipped:null,semantics:o,nextEffect:r.effect,command:{domain:o,service:r.service,data:{entity_id:i}}}}function up(e){return"entity"===e.bindingKind?e.bindingRef&&Ms(e.bindingRef)?[e.bindingRef]:[]:"virtual"===e.bindingKind?[]:eo(e)}function _p(e){const t=e.marker?.toggle_entity;return t&&up(e).includes(t)?t:null}function mp(e,t,i){const s=function(e,t){if("entity"===e.bindingKind&&e.bindingRef){const t=e.marker?.light_entity?to(e):null;return[...new Set([t,e.bindingRef].filter(e=>!!e))]}const i=e.entities.length?e.entities:e.allEntities||[],s=e.marker?.light_entity||e.primary&&Ms(e.primary)?to(e):null;return[...new Set([s,...Yn(t,i)].filter(e=>!!e))]}(i,t);if(!s.length)return null;const n="entity"===i.bindingKind?"binding":"device-role";if("binding"===n)return pp(e,t,s[0],n);let o=null,a=null;for(const i of s){const s=pp(e,t,i,n);if(s.command)return s;const r=s.skipped?.reason;if("missing"===r||"unavailable"===r||"secure"===r)return s;"ha-disabled"!==r?o||=s:a||=s}return o||a}function gp(e){const t=e.skipped?.reason;return"missing"===t?"unavailable":t||"unsupported"}function fp(e,t){return{origin:e,kind:"none",semantics:null,targets:[],skippedTargets:[],noneReason:t,nextEffect:null,command:null}}function vp(e,t){return"cover"===e||"toggle"===e?"toggle":"more-info"===e||"run"===e||"info"===e?e:(null==e||""===e)&&"light"===t?"toggle":"info"}function yp(e,t){return{origin:e,kind:"single",semantics:t.semantics,targets:t.target?[t.target]:[],skippedTargets:t.skipped?[t.skipped]:[],noneReason:t.command?null:gp(t),nextEffect:t.nextEffect,command:t.command}}function bp(e,t,i,s=[]){const n=new Map,o=[],a=new Set,r=e=>{const t=`${e.ref}\n${e.entityId||""}\n${e.reason}`;a.has(t)||(a.add(t),o.push(e))};for(const e of s)r(e);for(const s of i){const i=pp(e,t,s.entityId,s.via,s.ref);i.target?n.set(s.entityId,n.get(s.entityId)||i.target):i.skipped&&r(i.skipped)}const l=[...n.values()];if(!l.length)return{origin:"explicit-toggle",kind:"group",semantics:"group-power",targets:l,skippedTargets:o,noneReason:o.length&&o.every(e=>"secure"===e.reason)?"secure":"configured-targets-missing",nextEffect:null,command:null};const c=l.some(e=>"on"===e.state)?"turn_off":"turn_on",h=np(e,"homeassistant",c);return h?{origin:"explicit-toggle",kind:"group",semantics:"group-power",targets:l,skippedTargets:o,noneReason:null,nextEffect:"turn_on"===c?"turn-on":"turn-off",command:{...h,data:{entity_id:l.map(e=>e.entityId)}}}:{origin:"explicit-toggle",kind:"group",semantics:"group-power",targets:[],skippedTargets:[...o,...l.map(i=>hp(e,t,i.entityId,i.entityId,"unsupported"))],noneReason:"unsupported",nextEffect:null,command:null}}function wp(e){return String(e.marker?.id||e.id||"")}function kp(e){const{hass:t,device:i}=e,s=e.registryHass||t,n=function(e){return"toggle"===e.tapAction?"explicit-toggle":"cover"===e.tapAction?"legacy-cover":!e.tapAction&&e.primary?.startsWith("light.")?"default-light":null}(i);if(!n)return null;const o=i.marker;if("explicit-toggle"===n&&yn(o)){const t=String(o?.id||i.id||""),s=ro(e.devices).get(t);if(s)return function(e,t){const i=e.registryHass||e.hass;return bp(e.hass,i,t.driverEids.map(e=>({entityId:e,via:"control-marker-driver",ref:`marker:${t.markerId}`})))}(e,s);const a=bn(o,e.virtualLights);return{origin:n,kind:"single",semantics:"power",targets:[{entityId:"",name:i.name,state:a?"on":"off",via:"virtual-light"}],skippedTargets:[],noneReason:null,nextEffect:a?"turn-off":"turn-on",command:null,operation:{kind:"virtual-light",markerId:o.id}}}if("explicit-toggle"===n){if(Zn(i.marker?.binding,i.marker?.controls??i.controls,i.entities).length)return function(e,t=null){const{hass:i,device:s,devices:n}=e,o=e.registryHass||i,a=Zn(s.marker?.binding,s.marker?.controls??s.controls,s.entities),r=e.lightSources||ho(i,n,null,e.virtualLights),l=new Map;for(const e of r){if(!e.key.startsWith("marker:"))continue;const t=l.get(e.key)||[];t.push(e),l.set(e.key,t)}const c=ro(n),h=new Map;for(const e of n){const t=String(e.marker?.id||e.id||"");t&&h.set(t,e)}const d=[],p=[];t&&d.push({entityId:t,via:"entity"===s.bindingKind?"binding":"device-role",ref:t});for(const e of a){if(!e.startsWith("marker:")){Ms(e)?d.push({entityId:e,via:"control-entity",ref:e}):p.push(hp(i,o,e,e.includes(".")?e:null,"unsupported"));continue}const t=l.get(e)||[];if(!t.length){const t=h.get(e.slice(7));if("ha_disabled"===t?.bindingStatus?.kind){const s=t.bindingStatus.allEntityIds[0]||null;p.push({ref:e,entityId:s,name:t.name||(s?ap(i,o,s):null),reason:"ha-disabled"})}else p.push(hp(i,o,e,null,"missing"));continue}const n=[...new Set(t.flatMap(e=>e.serviceEids))];if(n.length){for(const t of n)d.push({entityId:t,via:"control-entity",ref:e});continue}const a=t.some(e=>e.passive),r=e.slice(7),u=wp(s),_=c.get(r)?.controllers.find(e=>wp(e.device)===u);if(a&&_?.driverEids.length)for(const t of _.driverEids)d.push({entityId:t,via:"control-marker-driver",ref:e});else p.push(hp(i,o,e,null,a?"missing":"unsupported"))}return bp(i,o,d,p)}(e,_p(i))}if("legacy-cover"===n){const e=i.entities.find(e=>e.startsWith("cover."))||i.allEntities?.find(e=>e.startsWith("cover."));return e?yp(n,pp(t,s,e,"device-role")):fp(n,"no-actionable-entity")}const a=_p(i),r=a?pp(t,s,a,"entity"===i.bindingKind?"binding":"device-role"):mp(t,s,i);return r?yp(n,r):fp(n,i.virtual||"virtual"===i.bindingKind?"no-actionable-entity":"no-binding")}function xp(e){if(!e)return[];const t=Array.isArray(e.data.entity_id)?e.data.entity_id:[e.data.entity_id];return[...new Set(t)].sort()}function $p(e){return e?e.operation?e.operation:e.command?{kind:"ha-service",command:e.command}:null:null}const Sp=new Set(["missing","ha-disabled","unavailable"]);function Mp(e,t){const i=$p(e),s=$p(t);return!(!i||!s||i.kind!==s.kind)&&("virtual-light"===i.kind&&"virtual-light"===s.kind?i.markerId===s.markerId:"ha-service"===i.kind&&"ha-service"===s.kind&&function(e,t){const i=xp(e),s=xp(t);return i.length===s.length&&i.every((e,t)=>e===s[t])}(i.command,s.command))}const Cp=e=>!!e&&e.length>=2&&Number.isFinite(e[0])&&Number.isFinite(e[1]);function Dp(e,t=5,i=5){return wl(e.cm,t,i)/2}function Pp(e,t,i=1,s=5,n=5,o=0){const a=e.host;if(!a||"partition"!==a.kind||"string"!=typeof a.id||!a.id)return{resolved:null,reason:"invalid-host"};const r=t.find(e=>e.id===a.id);if(!r)return{resolved:null,reason:"missing-partition"};if(!Cp(r.a)||!Cp(r.b)||!Number.isFinite(a.t)||a.t<0||a.t>1)return{resolved:null,reason:"invalid-position"};const l=r.b[0]-r.a[0],c=r.b[1]-r.a[1],h=Math.hypot(l,c),d=Number(e.length)*i;if(!(h>1e-9&&d>0&&Number.isFinite(d)))return{resolved:null,reason:"invalid-length"};const p=a.t*h;if(p-d/2h-o+1e-9)return{resolved:null,reason:"does-not-fit"};const u=l/h,_=c/h;let m=180*Math.atan2(c,l)/Math.PI;return m>=90?m-=180:m<-90&&(m+=180),{reason:null,resolved:{opening:e,host:a,partition:r,center:[r.a[0]+l*a.t,r.a[1]+c*a.t],angle:m,length:d,depth:wl(r.cm,s,n),t:a.t,axis:{a:[r.a[0],r.a[1]],b:[r.b[0],r.b[1]],ux:u,uy:_,length:h}}}}function Tp(e,t,i=1,s=5,n=5){return Pp(e,t,i,s,n,0)}function Ip(e,t,i=1,s=5,n=5){const o=e.host,a="partition"===o?.kind?t.find(e=>e.id===o.id):void 0;if(!a)return Tp(e,t,i,s,n);const r=Pp(e,t,i,s,n,Dp(a,s,n));return"does-not-fit"===r.reason?{resolved:null,reason:"does-not-fit-jamb"}:r}function Rp(e,t){return!e||(e.length!==t.length||e.host?.kind!==t.host?.kind||e.host?.id!==t.host?.id||e.host?.t!==t.host?.t)}function Ap(e){const{center:t,length:i,axis:s,host:n}=e,o=i/2;return{hostId:n.id,a:[t[0]-s.ux*o,t[1]-s.uy*o],b:[t[0]+s.ux*o,t[1]+s.uy*o],depth:e.depth}}function zp(e,t=!1){const i=t?1:-1,s=e.depth/2;return{ox:-e.axis.uy*i*s,oy:e.axis.ux*i*s,cm:e.partition.cm,side:i}}function Fp(e,t,i){return e.flatMap(e=>!Cp(e.a)||!Cp(e.b)||Math.hypot(e.b[0]-e.a[0],e.b[1]-e.a[1])<=1e-9?[]:[{roomId:"",a:[e.a[0],e.a[1]],b:[e.b[0],e.b[1]],key:`partition:${e.id}`,kind:"outer",cm:e.cm,open:!1,half:wl(e.cm,t,i)/2,partitionHost:{kind:"partition",id:e.id}}])}function Ep(e,t,i){const{center:s,length:n,axis:o}=e,a=n/2,r=t.flatMap(e=>{if(!e.kind||e.open)return[];const t=e.b[0]-e.a[0],n=e.b[1]-e.a[1],r=Math.hypot(t,n);if(!(r>i))return[];const l=t/r,c=n/r;if(Math.abs(o.ux*c-o.uy*l)>1e-6)return[];if(Math.abs((s[0]-e.a[0])*c-(s[1]-e.a[1])*l)>i)return[];const h=e=>(e[0]-s[0])*o.ux+(e[1]-s[1])*o.uy,d=h(e.a),p=h(e.b),u=Math.max(-a,Math.min(d,p)),_=Math.min(a,Math.max(d,p));return _>=u-i?[[u,_]]:[]});if(!r.length)return!1;r.sort((e,t)=>e[0]-t[0]||e[1]-t[1]);let l=-a;for(const[e,t]of r){if(e>l+i)return!1;if(l=Math.max(l,t),l>=a-i)return!0}return!1}function Np(e,t,i){return{...e,x:t.center[0]/i,y:t.center[1]/i,angle:t.angle}}const Op=.001;function Lp(e){return!!e&&e.length>=2&&Number.isFinite(e[0])&&Number.isFinite(e[1])}function Hp(e){return`${e[0].toFixed(6)},${e[1].toFixed(6)}`}function Bp(e,t,i){return Math.abs(e[0]-t[0])"room"!==e.kind&&i.some(i=>i!==e&&function(e,t,i){const s=e.b[0]-e.a[0],n=e.b[1]-e.a[1],o=Math.hypot(s,n);if(!(o>i))return!1;const a=s/o,r=n/o,l=t=>Math.abs((t[0]-e.a[0])*r-(t[1]-e.a[1])*a);if(l(t.a)>i||l(t.b)>i)return!1;const c=(t.a[0]-e.a[0])*a+(t.a[1]-e.a[1])*r,h=(t.b[0]-e.a[0])*a+(t.b[1]-e.a[1])*r;return Math.min(o,Math.max(c,h))-Math.max(0,Math.min(c,h))>i}(e,i,t))),n=s.map(e=>{const[t,i]=qp(e.a,e.b);return{a:t,b:i,key:`hidden|${jp(e,t,i)}`,sourceKind:e.kind,sourceId:e.id}}).sort((e,t)=>e.key.localeCompare(t.key)),o=s.flatMap(e=>[e.a,e.b].map((t,i)=>({point:[t[0],t[1]],key:`hidden|${Wp(e)}|endpoint-${i}`,sourceKind:e.kind,sourceId:e.id}))).sort((e,t)=>e.key.localeCompare(t.key));return{segments:n,endpoints:o}}function Kp(e){const t=e.epsilon??Op,i=e.roomCuts||[],s=new Map;for(const t of e.partitionCuts||[]){if("string"!=typeof t.hostId||!t.hostId||!Lp(t.a)||!Lp(t.b))continue;const e=s.get(t.hostId)||[];e.push([t.a[0],t.a[1],t.b[0],t.b[1]]),s.set(t.hostId,e)}const n=[];for(const[t,s]of pi(e.space.rooms).entries())s.length<4||n.push({a:[s[0],s[1]],b:[s[2],s[3]],kind:"room",id:`room-edge-${t}`,cuts:i});for(const t of e.space.room_drafts||[])if(t.id!==e.activeDraftId)for(let e=0;e+1Gp(s,e,t)))continue;const e=Hp(s);a.has(e)||a.set(e,{point:[s[0],s[1]],key:e})}}}return{segments:[...o.values()].sort((e,t)=>e.key.localeCompare(t.key)),endpoints:[...a.values()].sort((e,t)=>e.key.localeCompare(t.key))}}function Yp(e,t,i){return t.some(t=>Lp(t)&&Bp(e,t,i))}function Jp(e,t,i){if(!i)return!0;const s=e-i.distance;return s<-1e-9||Math.abs(s)<=1e-9&&t.localeCompare(i.key)<0}function Xp(e,t,i){const s=i.epsilon??Op,n=i.excludePoints||[],o=[...e.endpoints,...(i.extraEndpoints||[]).filter(e=>Lp(e.point)).map(e=>({point:[e.point[0],e.point[1]],key:e.key}))],a=new Map;for(const e of o){if(Yp(e.point,n,s))continue;const t=Hp(e.point),i=a.get(t);(!i||e.key.localeCompare(i.key)<0)&&a.set(t,e)}return[...a.values()].map(e=>({kind:"endpoint",point:[...e.point],key:e.key,distance:Math.hypot(t[0]-e.point[0],t[1]-e.point[1])})).filter(e=>e.distance<=i.tolerance).sort((e,t)=>e.distance-t.distance||e.key.localeCompare(t.key))}function Zp(e,t){if(!e.length)return null;if(t>0){const i=new Set;for(let s=0;s1)return{kind:"ambiguous",candidate:null,conflicts:e.filter(e=>i.has(e.key)).map(e=>({point:[...e.point],key:e.key}))}}return{kind:"resolved",candidate:e[0],conflicts:[]}}function Qp(e,t,i){const s=e.b[0]-e.a[0],n=e.b[1]-e.a[1],o=Math.hypot(s,n);if(!(o>0))return[...e.a];const a=s/o,r=n/o,l=Math.max(0,Math.min(o,(t[0]-e.a[0])*a+(t[1]-e.a[1])*r)),c=i>0?Math.max(0,Math.min(o,Math.round(l/i)*i)):l;return[e.a[0]+a*c,e.a[1]+r*c]}function eu(e,t,i){if(!(Lp(t)&&Lp(i.anchor)&&i.tolerance>=0))return{kind:"none",candidate:null,conflicts:[]};const s=i.epsilon??Op,n=function(e,t){const i=t[0]-e[0],s=t[1]-e[1];if(!(Math.hypot(i,s)>Number.EPSILON))return null;const n=Math.round(Math.atan2(s,i)/(Math.PI/4))*(Math.PI/4);return[Math.cos(n),Math.sin(n)]}(i.anchor,t);if(!n)return{kind:"none",candidate:null,conflicts:[]};const o=Xp(e,t,i).filter(e=>function(e,t,i,s){const n=e[0]-t[0],o=e[1]-t[1];return n*i[0]+o*i[1]>s&&Math.abs(n*i[1]-o*i[0])<=s*Math.max(Math.hypot(n,o),1)}(e.point,i.anchor,n,s)),a=Zp(o,i.distinguishTolerance||0);if(a)return a;let r=null;for(const o of e.segments){const e=o.b[0]-o.a[0],a=o.b[1]-o.a[1],l=o.a[0]-i.anchor[0],c=o.a[1]-i.anchor[1],h=n[0]*a-n[1]*e;let d=null;if(Math.abs(h)<=s*Math.max(Math.hypot(e,a),1)){if(Math.abs(l*n[1]-c*n[0])>s*Math.max(Math.hypot(l,c),1))continue;const e=[o.a,o.b].map(e=>({point:e,along:(e[0]-i.anchor[0])*n[0]+(e[1]-i.anchor[1])*n[1]})).filter(e=>e.along>s).sort((e,t)=>e.along-t.along);e.length&&(d=[...e[0].point])}else{const t=(l*a-c*e)/h,o=(l*n[1]-c*n[0])/h;t>s&&o>=-s&&o<=1+s&&(d=[i.anchor[0]+n[0]*t,i.anchor[1]+n[1]*t])}if(!d)continue;const p=Math.hypot(t[0]-d[0],t[1]-d[1]);p>i.tolerance||Yp(d,i.excludePoints||[],s)||!Jp(p,o.key,r)||(r={kind:"line",point:d,key:o.key,distance:p,segment:o})}return r?{kind:"resolved",candidate:r,conflicts:[]}:{kind:"none",candidate:null,conflicts:[]}}const tu=.001;function iu(e,t,i,s){const n=Number.isFinite(e)&&e>0?Math.floor(e):0,o=e=>"number"==typeof e&&Number.isFinite(e)&&e>=0?e:null,a=o(i),r=o(s)??0,l=[];let c=null;for(let e=0;e=2&&Number.isFinite(e[0])&&Number.isFinite(e[1])}function ou(e,t,i,s){return e*s-t*i}function au(e){let t=0;for(let i=0;ie.localeCompare(t)),t[0]}function du(e,t,i){const s=[...e];for(let e=!0;e&&s.length>=3;){e=!1;for(let n=0;n=0){s.splice(n,1),e=!0;break}}}return s}function pu(e,t){const i=e.map(e=>Math.max(0,Math.min(1,e))).sort((e,t)=>e-t),s=[];for(const e of i)(!s.length||Math.abs(e-s[s.length-1])>t)&&s.push(e);return s}function uu(e,t){return[e.a[0]+(e.b[0]-e.a[0])*t,e.a[1]+(e.b[1]-e.a[1])*t]}function _u(e,t,i){const s=function(e,t){const i=t.b[0]-t.a[0],s=t.b[1]-t.a[1],n=i*i+s*s;return n>0?((e[0]-t.a[0])*i+(e[1]-t.a[1])*s)/n:0}(e,t);if(s<-i||s>1+i)return null;const n=uu(t,s);return Math.hypot(n[0]-e[0],n[1]-e[1])<=i?Math.max(0,Math.min(1,s)):null}function mu(e,t,i,s,n){const o=e.b[0]-e.a[0],a=e.b[1]-e.a[1],r=t.b[0]-t.a[0],l=t.b[1]-t.a[1],c=t.a[0]-e.a[0],h=t.a[1]-e.a[1],d=ou(o,a,r,l),p=Math.max(Math.hypot(o,a),Math.hypot(r,l),1);if(Math.abs(d)>n*p){const e=ou(c,h,r,l)/d,t=ou(c,h,o,a)/d;return void(e>=-n&&e<=1+n&&t>=-n&&t<=1+n&&(i.push(Math.max(0,Math.min(1,e))),s.push(Math.max(0,Math.min(1,t)))))}if(!(Math.abs(ou(c,h,o,a))>n*p)){for(const s of[t.a,t.b]){const t=_u(s,e,n);null!=t&&i.push(t)}for(const i of[e.a,e.b]){const e=_u(i,t,n);null!=e&&s.push(e)}}}function gu(e){let t=e+1|0;return t^=t<<13,t^=t>>>17,t^=t<<5,t>>>0}function fu(e,t){return e.minY-t.minY||e.index-t.index}function vu(e){return e.subtreeMaxY=Math.max(e.item.maxY,e.left?.subtreeMaxY??-1/0,e.right?.subtreeMaxY??-1/0),e}function yu(e){const t=e.right;return e.right=t.left,t.left=vu(e),vu(t)}function bu(e){const t=e.left;return e.left=t.right,t.right=vu(e),vu(t)}function wu(e,t){return e?(fu(t,e.item)<0?(e.left=wu(e.left,t),e.left.priority0)e.right=ku(e.right,t);else{if(!e.left)return e.right;if(!e.right)return e.left;e.left.priority=t&&xu(e.left,t,i,s),e.item.minY<=i&&e.item.maxY>=t&&s.push(e.item),e.item.minY<=i&&xu(e.right,t,i,s))}function $u(e,t=.001){const i=Number.isFinite(t)&&t>0?t:tu,s=e.filter(e=>nu(e.a)&&nu(e.b)&&"string"==typeof e.key&&e.key.length>0&&Math.hypot(e.b[0]-e.a[0],e.b[1]-e.a[1])>i),n=s.map(()=>[0,1]);!function(e,t,i){const s=e.map((e,t)=>({index:t,minX:Math.min(e.a[0],e.b[0])-i,maxX:Math.max(e.a[0],e.b[0])+i,minY:Math.min(e.a[1],e.b[1])-i,maxY:Math.max(e.a[1],e.b[1])+i})),n=[...s].sort((e,t)=>e.minX-t.minX||e.minY-t.minY||e.index-t.index),o=[...s].sort((e,t)=>e.maxX-t.maxX||e.index-t.index),a=new Set;let r=null,l=0;for(const s of n){for(;le.index-t.index);for(const o of n)mu(e[o.index],e[s.index],t[o.index],t[s.index],i);a.add(s.index),r=wu(r,s)}}(s,n,i);const o=new Map;for(let e=0;e({key:e,a:t.a,b:t.b,sourceKeys:[...t.sourceKeys].sort((e,t)=>e.localeCompare(t))})).sort((e,t)=>e.key.localeCompare(t.key))}function Su(e,t=.001){const i=Number.isFinite(t)&&t>0?t:tu,s=$u(e,i),n=new Map,o=new Map,a=new Map(s.map(e=>[e.key,e]));for(const e of s){const t=lu(e.a,i),s=lu(e.b,i);n.set(t,e.a),n.set(s,e.b),o.has(t)||o.set(t,new Set),o.has(s)||o.set(s,new Set),o.get(t).add(s),o.get(s).add(t)}const r=new Map;for(const[e,t]of o){const i=n.get(e);r.set(e,[...t].sort((e,t)=>{const s=n.get(e),o=n.get(t);return Math.atan2(s[1]-i[1],s[0]-i[0])-Math.atan2(o[1]-i[1],o[0]-i[0])||e.localeCompare(t)}))}const l=new Set,c=new Map,h=(e,t)=>`${e}>${t}`;for(const e of s){const t=[lu(e.a,i),lu(e.b,i)];for(const[e,o]of[t,[t[1],t[0]]]){if(l.has(h(e,o)))continue;const t=[],d=[];let p=e,u=o,_=!1;for(let i=0;i<=2*s.length+2;i++){const i=h(p,u);if(l.has(i)){_=p===e&&u===o;break}l.add(i),t.push(p),d.push(cu(p,u));const s=r.get(u)||[],n=s.indexOf(p);if(n<0||!s.length)break;if(p=u,u=s[(n-1+s.length)%s.length],p===e&&u===o){_=!0;break}}if(!_||new Set(t).size<3||new Set(t).size!==t.length)continue;const m=t.map(e=>n.get(e)),g=au(m);if(!(g>i*i))continue;const f=hu(du(t,n,i)),v=new Set;for(const e of d)for(const t of a.get(e)?.sourceKeys||[])v.add(t);const y={ring:m,key:f,area:g,atomKeys:[...d],sourceKeys:[...v].sort((e,t)=>e.localeCompare(t))};c.has(f)||c.set(f,y)}}return{atoms:s,faces:[...c.values()].sort((e,t)=>e.area-t.area||e.key.localeCompare(t.key))}}function Mu(e,t,i=.001){if(!nu(t))return null;const s=e.faces.filter(e=>{if(e.ring.some((s,n)=>function(e,t,i,s){const n=i[0]-t[0],o=i[1]-t[1],a=n*n+o*o;if(!(a>0))return Math.hypot(e[0]-t[0],e[1]-t[1])<=s;const r=((e[0]-t[0])*n+(e[1]-t[1])*o)/a;return!(r<0||r>1)&&Math.hypot(t[0]+n*r-e[0],t[1]+o*r-e[1])<=s}(t,s,e.ring[(n+1)%e.ring.length],i)))return!1;let s=!1;for(let i=0,n=e.ring.length-1;it[1]!=a[1]>t[1]&&t[0]<(a[0]-o[0])*(t[1]-o[1])/(a[1]-o[1])+o[0]&&(s=!s)}return s});return[...s].sort((e,t)=>e.area-t.area||e.key.localeCompare(t.key))[0]||null}function Cu(e,t,i){const s=i[0]-t[0],n=i[1]-t[1],o=s*s+n*n,a=o>0?Math.max(0,Math.min(1,((e[0]-t[0])*s+(e[1]-t[1])*n)/o)):0;return Math.hypot(t[0]+s*a-e[0],t[1]+n*a-e[1])}function Du(e,t,i=.5){let s=Math.abs(e-t)%180;return s>90&&(s=180-s),s<=i}function Pu(e,t,i,s){const n=e.filter(e=>"outer"===e.kind&&!e.open&&e.cm>0).map(e=>({interval:e,reusePartitionId:t.find(t=>function(e,t,i){return!(Math.abs(e.cm-t.cm)>1e-6)&&(Du(180*Math.atan2(e.b[1]-e.a[1],e.b[0]-e.a[0])/Math.PI,180*Math.atan2(t.b[1]-t.a[1],t.b[0]-t.a[0])/Math.PI,.001)&&Cu(t.a,e.a,e.b)<=i&&Cu(t.b,e.a,e.b)<=i)}(t,e,s))?.id||null})),o=new Map;for(const t of i){if("partition"===t.host?.kind)continue;const i=e.map(e=>{const i=180*Math.atan2(e.b[1]-e.a[1],e.b[0]-e.a[0])/Math.PI;return{interval:e,distance:Du(t.angle,i)?Cu([t.x,t.y],e.a,e.b):1/0}}).filter(e=>e.distance<=s).sort((e,t)=>e.distance-t.distance||e.interval.key.localeCompare(t.interval.key)),n=i[0]?.interval;"outer"===n?.kind&&!n.open&&n.cm>0&&o.set(t.id,n.key)}return{materialize:n,openingIntervals:o,removeOpeningIds:[...o.keys()].sort((e,t)=>e.localeCompare(t))}}function Tu(e,t){const i=t.b[0]-t.a[0],s=t.b[1]-t.a[1],n=i*i+s*s;return n>0?Math.max(0,Math.min(1,((e[0]-t.a[0])*i+(e[1]-t.a[1])*s)/n)):0}const Iu=e=>!e.key.startsWith("static:room|");function Ru(e,t){const i=t.b[0]-t.a[0],s=t.b[1]-t.a[1],n=i*i+s*s;if(!(n>0))return null;const o=((e[0]-t.a[0])*i+(e[1]-t.a[1])*s)/n,a=[t.a[0]+i*o,t.a[1]+s*o];return{point:a,t:o,distance:Math.hypot(a[0]-e[0],a[1]-e[1])}}function Au(e,t){return t>0?Math.hypot(e[0]-Math.round(e[0]/t)*t,e[1]-Math.round(e[1]/t)*t):0}function zu(e,t,i){if(Iu(e.source)!==Iu(t.source))return Iu(e.source)?e:t;const s=Au(e.point,i),n=Au(t.point,i);return Math.abs(s-n)>1e-9?s>n?e:t:function(e,t){return e[0]-t[0]||e[1]-t[1]}(e.point,t.point)>0?e:t}function Fu(e){return[e.from[0],e.from[1],e.to[0],e.to[1],e.targetKind].map(e=>"number"==typeof e?e.toFixed(6):e).join("|")}function Eu(e,t){return e.map(e=>e.key!==t.sourceKey?e:{...e,[t.endpoint]:[...t.to]})}function Nu(e,t){const i=t.epsilon??.001;if(!(t.maxDistance>=0)||!t.point&&!t.requiredSourceKey)return{kind:"none"};const s=new Map,n=e.flatMap(e=>[{source:e,endpoint:"a",point:e.a},{source:e,endpoint:"b",point:e.b}]);for(let e=0;ei)||l>t.maxDistance)continue;const c=zu(a,r,t.gridStep||0),h=c===a?r:a;if(!Iu(c.source))continue;const d={sourceKey:c.source.key,endpoint:c.endpoint,from:[c.point[0],c.point[1]],to:[h.point[0],h.point[1]],targetSourceKey:h.source.key,targetKind:"endpoint",distance:l};s.set(Fu(d),d)}for(const o of n)if(Iu(o.source))for(const n of e){if(n===o.source)continue;const e=Ru(o.point,n);if(!e||e.t<=i||e.t>=1-i||!(e.distance>i)||e.distance>t.maxDistance)continue;const a={sourceKey:o.source.key,endpoint:o.endpoint,from:[o.point[0],o.point[1]],to:e.point,targetSourceKey:n.key,targetKind:"line",distance:e.distance};s.set(Fu(a),a)}const o=[];for(const n of s.values()){const s=Su(Eu(e,n),i),a=t.point?Mu(s,t.point,i):s.faces.find(e=>!t.requiredSourceKey||e.sourceKeys.includes(t.requiredSourceKey))||null;a&&o.push({proposal:n,face:a})}if(o.sort((e,t)=>e.proposal.distance-t.proposal.distance||Fu(e.proposal).localeCompare(Fu(t.proposal))),!o.length)return{kind:"none"};return new Set(o.map(e=>`${Fu(e.proposal)}|${e.face.key}`)).size>1?{kind:"ambiguous",proposals:o.map(e=>e.proposal)}:{kind:"repair",...o[0]}}const Ou=1e-5;function Lu(e){const t=e.map(()=>[]);for(let i=0;i=1-1e-9||p<=1e-9||p>=1-1e-9||(t[i].push(d),t[a].push(p))}}const i=[];for(let s=0;se-t),1];for(let e=1;e{const i=t[2]-t[0],s=t[3]-t[1],n=i*i+s*s;if(!(n>0))return Math.hypot(e[0]-t[0],e[1]-t[1]);const o=Math.max(0,Math.min(1,((e[0]-t[0])*i+(e[1]-t[1])*s)/n));return Math.hypot(e[0]-(t[0]+o*i),e[1]-(t[1]+o*s))},qu=(e,t,i,s)=>{const n=s[2]-s[0],o=s[3]-s[1],a=t*o-i*n;if(Math.abs(a)<1e-12)return 1/0;const r=s[0]-e[0],l=s[1]-e[1],c=(r*o-l*n)/a;if(!(c>1e-9))return 1/0;const h=(r*i-l*t)/a;return h<-1e-9||h>1+1e-9?1/0:c};function Wu(e,t,i,s=96){if(!(t>0&&Number.isFinite(e[0])&&Number.isFinite(e[1])))return[];const n=[];for(const s of i){if(!s||s.length<4)continue;if(![s[0],s[1],s[2],s[3]].every(Number.isFinite))continue;const i=Bu(e,s);if(i<1e-7)return[];i>t||n.push(s)}const o=[],a=Math.max(12,Math.round(s));for(let e=0;ee-t);const l=[];let c=Number.NEGATIVE_INFINITY;for(const i of o){if(i-c<1e-9)continue;c=i;const s=Math.cos(i),o=Math.sin(i);let a=t;for(const t of n){const i=qu(e,s,o,t);i=3?l:[]}class ju extends he{constructor(){super(...arguments),this._spaces=null,this._spacesLoading=!1,this._spacesAuthoritative=!1}setConfig(e){this._config=e}async _loadSpaces(){if(!this._spaces&&!this._spacesLoading&&this.hass){this._spacesLoading=!0;try{const e=await this.hass.callWS({type:"houseplan/config/get"});this._spaces=(e?.config?.spaces||[]).map(e=>({value:e.id,label:e.title||e.id})),this._spacesAuthoritative=!0}catch{this._spaces=[],this._spacesAuthoritative=!1}finally{this._spacesLoading=!1}}}get _lang(){return ra(this.hass,this._config?.language)}get _floorToken(){const e=this._config?.floor;return"number"==typeof e?`__houseplan_yaml_floor_index__:${String(e)}`:null}get _formData(){const e={...this._config},t=this._floorToken;return t?e.floor=t:Object.prototype.hasOwnProperty.call(e,"floor")||(e.floor=""),e}get _schema(){const e=this._spaces||[],t=this._lang,i=[{value:"",label:la(t,"editor.floor_none")}],s=this._floorToken;s&&i.push({value:s,label:la(t,"editor.floor_index",{index:String(this._config?.floor)})});const n="string"==typeof this._config?.floor?this._config.floor:"";n&&!e.some(e=>e.value===n)&&i.push({value:n,label:n}),i.push(...e);const o="string"==typeof this._config?.default_floor?this._config.default_floor:"",a=[...e];return o&&!e.some(e=>e.value===o)&&a.unshift({value:o,label:o}),[{name:"title",selector:{text:{}}},{name:"floor",selector:{select:{mode:"dropdown",options:i}}},e.length?{name:"default_floor",selector:{select:{mode:"dropdown",options:a}}}:{name:"default_floor",selector:{text:{}}},{name:"language",selector:{select:{mode:"dropdown",options:[{value:"",label:la(t,"editor.lang_auto")},{value:"en",label:la(t,"editor.lang_en")},{value:"ru",label:la(t,"editor.lang_ru")}]}}},{name:"icon_size",selector:{number:{min:1,max:6,step:.1,mode:"box"}}},{name:"show_temperature",selector:{boolean:{}}},{name:"live_states",selector:{boolean:{}}},{name:"show_signal",selector:{boolean:{}}},{name:"kiosk",selector:{boolean:{}}},{name:"cycle",selector:{number:{min:0,max:3600,step:5,mode:"box"}}}]}render(){if(!this.hass||!this._config)return G;this._loadSpaces();const e=this._lang,t={title:la(e,"editor.title"),floor:la(e,"editor.floor"),default_floor:la(e,"editor.default_floor"),language:la(e,"editor.language"),icon_size:la(e,"editor.icon_size"),show_temperature:la(e,"editor.show_temperature"),live_states:la(e,"editor.live_states"),show_signal:la(e,"editor.show_signal"),kiosk:la(e,"editor.kiosk"),cycle:la(e,"editor.cycle")},i=this._schema,s=function(e,t,i){if(!i||null===t)return null;const s="string"==typeof e?.default_floor?e.default_floor:"";return!s||t.some(e=>e.value===s)?null:s}(this._config,this._spaces,this._spacesAuthoritative),n=e=>W``}const Er={color:"#607d8b",opacity:1,widthCm:3.6,fill:!1,fillColor:"#607d8b",fillOpacity:.25},Nr=(e,t=1)=>{const i=Number(e);return Number.isFinite(i)?Math.min(1,Math.max(0,i)):t},Or=e=>{let t=Number(e);return Number.isFinite(t)?(t=(t%360+360)%360,t>180?t-360:t):0};function Hr(e,t,i){return Or(t)?[e.x,e.y]:i([e.x,e.y])}const Lr=(e,t,i)=>{const s=Number(e),n=Number.isFinite(t)&&t>0?t:5;return Number.isFinite(s)&&s>0?s/n*i:0},Br=(e,t,i)=>{const s=Number(e),n=Number.isFinite(t)&&t>0?t:5;return Number.isFinite(s)&&i>0?s/i*n:0},qr=(e,t,i,s=Er.widthCm)=>{const n=Number(e?.width_cm);if(Number.isFinite(n)&&n>0)return n;const o=Number(e?.width);return Number.isFinite(o)&&o>0?Br(o,t,i):s};function Wr(e,t){return{color:e.color,opacity:Nr(e.opacity),width_cm:Math.max(.1,Math.min(100,Number(e.widthCm)||.1)),...t?{fill:e.fill,fill_color:e.fillColor,fill_opacity:Nr(e.fillOpacity,.25)}:{}}}function jr(e){const t=e.x+e.w/2,i=e.y+e.h/2,s=Or(e.angle)*Math.PI/180,n=Math.cos(s),o=Math.sin(s),a=(e,s)=>{const a=e-t,r=s-i;return[t+a*n-r*o,i+a*o+r*n]};return[a(e.x,e.y),a(e.x+e.w,e.y),a(e.x+e.w,e.y+e.h),a(e.x,e.y+e.h)]}function Ur(e){const t=jr(e),i=(e,t)=>[(e[0]+t[0])/2,(e[1]+t[1])/2],s=[(t[0][0]+t[2][0])/2,(t[0][1]+t[2][1])/2];return{points:[...t,i(t[0],t[1]),i(t[1],t[2]),i(t[2],t[3]),i(t[3],t[0]),s],segments:t.map((e,i)=>({a:e,b:t[(i+1)%4]}))}}function Gr(e,t,i,s,n,o,a,r){const l=Or(e.angle)*Math.PI/180,c=Math.cos(l),h=Math.sin(l),d=-Math.sin(l),p=Math.cos(l),u=e.x+e.w/2,_=e.y+e.h/2,m=t>0?-e.w/2:e.w/2,g=i>0?-e.h/2:e.h/2,f=u+m*c+g*d,v=_+m*h+g*p,y=s-f,b=n-v;let w=(y*c+b*h)*(t>0?1:-1),k=(y*d+b*p)*(i>0?1:-1),x=null;if(o){const t=w/Math.max(e.w,r),i=k/Math.max(e.h,r);x=Math.max(r/Math.max(e.w,r),r/Math.max(e.h,r),t,i),w=e.w*x,k=e.h*x}if(a>0)if(o){const t=Math.max(1,Math.round(e.w/a)),i=Math.max(1,Math.round(e.h/a));if(Math.abs(e.w-t*a)<1e-6&&Math.abs(e.h-i*a)<1e-6){const s=(e,t)=>{let i=Math.abs(e),s=Math.abs(t);for(;s;)[i,s]=[s,i%s];return Math.max(1,i)},n=1/s(t,i),o=Math.max(r/e.w,r/e.h),a=Math.max(o,Math.round((x??1)/n)*n);w=e.w*a,k=e.h*a}else{e.w>=e.h?(w=Math.round(w/a)*a,k=w*(e.h/Math.max(e.w,r))):(k=Math.round(k/a)*a,w=k*(e.w/Math.max(e.h,r)))}}else w=Math.round(w/a)*a,k=Math.round(k/a)*a;w=Math.max(r,w),k=Math.max(r,k);return{x:f+(t>0?w/2:-w/2)*c+(i>0?k/2:-k/2)*d-w/2,y:v+(t>0?w/2:-w/2)*h+(i>0?k/2:-k/2)*p-k/2,w:w,h:k,angle:Or(e.angle)||void 0}}const Vr=(e,t,i)=>{const s=i[0]-t[0],n=i[1]-t[1],o=s*s+n*n;if(o<1e-12)return[...t];const a=Math.max(0,Math.min(1,((e[0]-t[0])*s+(e[1]-t[1])*n)/o));return[t[0]+s*a,t[1]+n*a]};const Kr=10**9,Yr=240,Jr=1e-4;function Xr(e){if(Array.isArray(e))return e.map(e=>Xr(e));if(null!==e&&"object"==typeof e){const t={};for(const[i,s]of Object.entries(e))t[i]=Xr(s);return t}return e}function Zr(e){if("number"!=typeof e||!Number.isFinite(e))return e;const t=(e<0||Object.is(e,-0)?-1:1)*(Math.floor(Math.abs(e)*Kr+.5)/Kr);return 0===t?0:t}function Qr(e){if("number"!=typeof e||!Number.isFinite(e))return e;const t=e*Yr,i=Math.round(t);if(Math.abs(t-i)null!==tl(e)):[]}function sl(e,t){for(const i of t)Object.prototype.hasOwnProperty.call(e,i)&&(e[i]=Zr(e[i]))}function nl(e,t){for(const i of t)Object.prototype.hasOwnProperty.call(e,i)&&(e[i]=Qr(e[i]))}function ol(e){if(Array.isArray(e))for(let t=0;t{for(const n of s){const s=t[n];"number"==typeof s&&Number.isFinite(s)&&i(s,e)}},s=t=>{if(Array.isArray(t))for(let s=0;s{if(Array.isArray(e))for(const t of e)s(t)};for(const i of il(e.rooms))t(i,["x","y","w","h"]),n(i.poly);for(const t of il(e.walls))s(t.a),s(t.b);for(const t of il(e.wall_segments))s(t.a),s(t.b);for(const i of il(e.openings))t(i,["x","y"]);for(const i of il(e.decor))"line"===i.kind?t(i,["x1","y1","x2","y2"]):"rect"===i.kind||"ellipse"===i.kind||"furniture"===i.kind?t(i,["x","y","w","h"]):"text"===i.kind&&t(i,["x","y"]);for(const t of il(e.room_drafts))n(t.points);for(const t of il(e.partitions))s(t.a),s(t.b);for(const t of il(e.wall_columns))s(t.center);for(const t of il(e.open_spans))s(t.a),s(t.b)}const n=tl(t);if(!n)return;const o=new Map;if(s)for(const e of il(s.spaces))null!=e.id&&o.set(String(e.id),e);for(const e of Object.values(n)){const t=tl(e);if(!t)continue;const s=null!=t.s&&o.get(String(t.s))||null;for(const e of["x","y"]){const n=t[e];"number"==typeof n&&Number.isFinite(n)&&i(n,s)}}}function ll(e){const t=Number(e?.cell_cm);return t>0?t:5}function cl(e,t={}){const i={canonicalized:0,far:0,maxShift:0,maxShiftCm:0,spaces:[],bySpace:new Map},s=il(tl(e)?.spaces);let n=5;for(const e of s)n=Math.max(n,ll(e));rl(e,t,(e,t)=>{const s=e*Yr,o=Math.abs(s-Math.round(s)),a=Qr(e),r=o>0&&o=Jr))return;const l=r&&"number"==typeof a?Math.abs(a-e):0;if(r?i.canonicalized++:i.far++,i.maxShift=Math.max(i.maxShift,l),i.maxShiftCm=Math.max(i.maxShiftCm,l*Yr*(t?ll(t):n)),!t?.id||!r)return;const c=String(t.id);let h=i.bySpace.get(c);h||(h={spaceId:c,space:String(t.title||c),canonicalized:0,far:0,maxShift:0,maxShiftCm:0},i.bySpace.set(c,h)),h.canonicalized++,h.maxShift=Math.max(h.maxShift,l),h.maxShiftCm=Math.max(h.maxShiftCm,l*Yr*ll(t))}),i.bySpace.size&&rl(e,t,(e,t)=>{if(!t?.id)return;const s=i.bySpace.get(String(t.id));if(!s)return;const n=e*Yr;Math.abs(n-Math.round(n))>=Jr&&s.far++}),i.spaces=[...i.bySpace.values()];const{bySpace:o,...a}=i;return a}function hl(e){return function(e){const t=e,i=tl(t);i&&nl(i,["x","y"]);return t}(Xr(e))}function dl(e){const t=e,i=tl(t);if(!i)return t;for(const e of Object.values(i)){const t=tl(e);t&&nl(t,["x","y"])}return t}function pl(e){const t=e,i=tl(t);if(!i)return t;for(const e of il(i.spaces)){sl(e,["plan_x","plan_y","plan_scale","plan_scale_x","plan_scale_y","plan_angle"]);for(const t of il(e.rooms))nl(t,["x","y","w","h"]),al(t.poly);for(const t of il(e.walls))ol(t.a),ol(t.b);for(const t of il(e.wall_segments))ol(t.a),ol(t.b);for(const t of il(e.openings)){nl(t,["x","y"]),sl(t,["angle","length"]);const e=tl(t.host);e&&sl(e,["t"])}for(const t of il(e.decor))"line"===t.kind?nl(t,["x1","y1","x2","y2"]):"rect"===t.kind||"ellipse"===t.kind||"furniture"===t.kind?(nl(t,["x","y","w","h"]),sl(t,["angle"])):"text"===t.kind&&(nl(t,["x","y"]),sl(t,["scale","angle"]));for(const t of il(e.room_drafts))al(t.points);for(const t of il(e.partitions))ol(t.a),ol(t.b);for(const t of il(e.wall_columns))ol(t.center),"square"===t.shape&&sl(t,["angle"]);for(const t of il(e.open_spans))ol(t.a),ol(t.b)}for(const e of il(i.markers))sl(e,["angle"]);return t}const ul=15;function _l(e,t,i,s,n){const o=i[0]-e[0],a=i[1]-e[1],r=Math.hypot(o,a);if(!(r>0)||r<=n+1e-9)return null;const l=o/r,c=a/r,h=t=>{const s=(t[0]-e[0])*l+(t[1]-e[1])*c,o=(n-s)/(r-s);return!Number.isFinite(o)||o<-1e-9||o>1+1e-9?null:[t[0]+(i[0]-t[0])*o,t[1]+(i[1]-t[1])*o]},d=h(t),p=h(s);return d&&p?[[e[0],e[1]],t,d,p,s]:null}const ml=Math.sin(.25*Math.PI/180);function gl(e,t){return Number.isFinite(e)&&e>0&&Number.isFinite(t)&&t>0&&e*t<3}function fl(e){const t=Number(e)>0?Number(e):5;if(5===t)return 8;const i=5/t*8;return Math.min(80,Math.max(.5,i))}function vl(e,t){return Number.isFinite(e)&&e>0&&Number.isFinite(t)&&t>0&&e*t<2}function yl(e){return Number.isFinite(e)?Math.max(1,Math.min(100,e)):1}function bl(e,t){return!Number.isFinite(e)||e<0?"":String(t?Math.round(e/2.54*100)/100:Math.round(100*e)/100)}function wl(e,t,i){if(!Number.isFinite(e)||e<=0)return 0;const s=Number(t)>0?Number(t):5;return yl(e)/s*i}function kl(e,t){return t>0&&Number.isFinite(e)?Math.round(e/t)*t:e}function xl(e){return Math.max(1e-6*Math.abs(e),1e-9)}function $l(e,t){if(!(t>0&&Number.isFinite(e)))return e;const i=kl(e,t);return Math.abs(i-e)<=xl(t)?i:e}function Sl(e,t){let i=t[0]-e[0],s=t[1]-e[1];const n=Math.hypot(i,s);return n<1e-12?[1,0]:(i/=n,s/=n,(i<-1e-12||Math.abs(i)<=1e-12&&s<0)&&(i=-i,s=-s),[i,s])}function Ml(e,t,i){const s=[$l(e[0],i),$l(e[1],i)],n=[$l(t[0],i),$l(t[1],i)],o=kl((s[0]+n[0])/2,i),a=kl((s[1]+n[1])/2,i),[r,l]=Sl(s,n);let c=Math.atan2(l,r);c<0&&(c+=Math.PI);const h=Math.round(1800*c)/1800,d=i>0&&i<.01?6:i<1?4:2;return`${o.toFixed(d)},${a.toFixed(d)}@${h.toFixed(4)}`}function Cl(e,t,i,s){return 1===s?Ml(e,t,i):Ml([e[0]/s,e[1]/s],[t[0]/s,t[1]/s],i)}function Dl(e,t){if(!Array.isArray(e.a)||!Array.isArray(e.b)||e.a.length<2||e.b.length<2)return null;const i=[Number(e.a[0]),Number(e.a[1]),Number(e.b[0]),Number(e.b[1])];if(!i.every(Number.isFinite))return null;const s=t>0?t:1;return[[i[0]*s,i[1]*s],[i[2]*s,i[3]*s]]}function Pl(e,t,i,s,n){const o=n>0?n:1;return{key:Cl(e,t,s,o),cm:yl(i),a:[e[0]/o,e[1]/o],b:[t[0]/o,t[1]/o]}}function Tl(e,t){const i=t>0?t:1,s=[];for(const t of e){const e=t.key.lastIndexOf("@");if(e<0)continue;const[n,o]=t.key.slice(0,e).split(",").map(Number),a=Number(t.key.slice(e+1));[n,o,a].every(Number.isFinite)&&s.push({w:t,x:n*i,y:o*i,ang:a})}return s}function Il(e,t){const[i,s]=Sl(e,t);let n=Math.atan2(s,i);return n<0&&(n+=Math.PI),n}function Rl(e,t){let i=Math.abs(e-t);return i>Math.PI/2&&(i=Math.PI-i),i<.02}function Al(e,t,i,s,n=1){if(!e?.length)return null;const o=Cl(t,i,s,n),a=e.find(e=>e.key===o);if(a)return a;const r=n>0?n:1,l=xl(s)*r,c=(e,t)=>Math.abs(e[0]-t[0])<=l&&Math.abs(e[1]-t[1])<=l;for(const s of e){const e=Dl(s,r);if(e&&(c(e[0],t)&&c(e[1],i)||c(e[0],i)&&c(e[1],t)))return s}const h=(t[0]+i[0])/2,d=(t[1]+i[1])/2,p=Il(t,i),u=Math.max(.5*s,1e-9)*r;for(const t of Tl(e,r))if(Rl(t.ang,p)&&Math.hypot(t.x-h,t.y-d)<=u)return t.w;return null}function zl(e,t,i,s,n=1){const o=Al(e,t,i,s,n);if(o&&o.cm>0)return yl(o.cm);const a=function(e,t,i,s,n){if(!e?.length)return null;const o=n>0?n:1,a=Math.hypot(i[0]-t[0],i[1]-t[1]);if(a<1e-12)return null;const r=Il(t,i),l=Math.max(.5*s,1e-9)*o;let c=null;for(const s of e){if(!(s.cm>0))continue;const e=Dl(s,o);if(!e)continue;const n=Math.hypot(e[1][0]-e[0][0],e[1][1]-e[0][1]);if(n<1e-12||!Rl(Il(e[0],e[1]),r))continue;if(bc(t[0],t[1],e[0][0],e[0][1],e[1][0],e[1][1])>l||bc(i[0],i[1],e[0][0],e[0][1],e[1][0],e[1][1])>l)continue;if(n+l(o.has(e.key)||(e=>{const t=Dl(e,s);if(!t)return!1;const[i,o]=t,r=o[0]-i[0],c=o[1]-i[1],h=Math.hypot(r,c);if(h<=l)return!1;if(!a.some(e=>{const t=[e[0],e[1]],s=[e[2],e[3]];return Rl(Il(i,o),Il(t,s))&&bc(i[0],i[1],t[0],t[1],s[0],s[1])<=l&&bc(o[0],o[1],t[0],t[1],s[0],s[1])<=l}))return!1;const d=(n||[]).some(e=>{const t=[e[0],e[1]],s=[e[2],e[3]];if(!Rl(Il(i,o),Il(t,s)))return!1;const n=e=>Math.abs((e[0]-i[0])*c-(e[1]-i[1])*r)/h;if(n(t)>l||n(s)>l)return!1;const a=h*h,d=((t[0]-i[0])*r+(t[1]-i[1])*c)/a,p=((s[0]-i[0])*r+(s[1]-i[1])*c)/a;return Math.min(1,Math.max(d,p))-Math.max(0,Math.min(d,p))>l/h});return!d})(e))&&e.cm>=1&&e.cm<=100)}function El(e,t,i,s=8){const[n,o]=Sl(e,t);let a=Math.atan2(o,n);a<0&&(a+=Math.PI);let r=i*Math.PI/180%Math.PI;r<0&&(r+=Math.PI);let l=Math.abs(a-r);return l>Math.PI/2&&(l=Math.PI-l),l<=s*Math.PI/180}function Nl(e,t,i,s,n=1,o="affine",a){if(!e?.length)return[];if(t.length!==i.length)return"fixed-topology"===o&&a?.(),e.slice();const r=n>0?n:1,l=Math.max(.5*s,1e-9)*r,c=Math.max(s*r*1e-6,1e-9),h=[],d=new Map,p=new Map,u=(e,t,i)=>{const s=e.get(t)||new Set;s.add(i),e.set(t,s)};for(let e=0;e[e[0]+(t[0]-e[0])*i,e[1]+(t[1]-e[1])*i],m=(e,t)=>Math.hypot(e[0]-t[0],e[1]-t[1])<=c,g=(e,t)=>{if("fixed-topology"===o){const i=t.na[0]-t.oa[0],s=t.na[1]-t.oa[1],n=t.nb[0]-t.ob[0],o=t.nb[1]-t.ob[1];return Math.hypot(i-n,s-o)<=c?[e[0]+i,e[1]+s]:m(e,t.oa)?[...t.na]:m(e,t.ob)?[...t.nb]:[...e]}const i=Math.max(0,Math.min(1,((e[0]-t.oa[0])*t.dx+(e[1]-t.oa[1])*t.dy)/t.len2));return _(t.na,t.nb,i)},f=(e,t)=>{const[i,s]=Sl(e,t);return(t[0]-e[0])*i+(t[1]-e[1])*s>=0?[[...e],[...t]]:[[...t],[...e]]},v=[],y=[],b=(e,t,i)=>{if(Math.hypot(t[0]-e[0],t[1]-e[1])<=c)return;const[n,o]=f(e,t),a=yl(i);if(y.some(e=>e.entry.cm===a&&m(e.span[0],n)&&m(e.span[1],o)))return;const l=Pl(n,o,a,s,r);v.push(l),y.push({entry:l,span:[n,o]})};for(const t of e){const e=Dl(t,r);if(e){const[i,s]=f(e[0],e[1]),n=s[0]-i[0],a=s[1]-i[1],r=n*n+a*a,d=Math.sqrt(r);if(d<=c){v.push({...t,cm:yl(t.cm)});continue}const p=[];for(const e of h){if(!Rl(Il(i,s),Il(e.oa,e.ob)))continue;const t=e=>Math.abs((e[0]-i[0])*a-(e[1]-i[1])*n)/d;if(t(e.oa)>l||t(e.ob)>l)continue;const o=((e.oa[0]-i[0])*n+(e.oa[1]-i[1])*a)/r,h=((e.ob[0]-i[0])*n+(e.ob[1]-i[1])*a)/r,u=Math.max(0,Math.min(o,h)),_=Math.min(1,Math.max(o,h));(_-u)*d>c&&p.push({lo:u,hi:_,move:e})}if(!p.length){"fixed-topology"===o?v.push({...t}):b(i,s,t.cm);continue}const u=[0,1,...p.flatMap(({lo:e,hi:t})=>[e,t])].sort((e,t)=>e-t).filter((e,t,i)=>0===t||Math.abs(e-i[t-1])*d>c),y=[];for(let e=0;e+1r>=e.lo-1e-12&&r<=e.hi+1e-12);if(!l.length){y.push([o,a]);continue}const h=[g(o,l[0].move),g(a,l[0].move)],f=l.slice(1).some(e=>{const t=g(o,e.move),i=g(a,e.move);return!m(h[0],t)||!m(h[1],i)});y.push(f?[o,a]:h)}const w=(e,t)=>{const i=e[1][0]-e[0][0],s=e[1][1]-e[0][1],n=t[1][0]-t[0][0],o=t[1][1]-t[0][1],a=Math.hypot(i,s);return!(a<=c||i*n+s*o<=0)&&Math.abs(i*o-s*n)/a<=c},k=[];for(const e of y){const t=k[k.length-1];t&&m(t[1],e[0])&&w(t,e)?t[1]=e[1]:k.push([[...e[0]],[...e[1]]])}if("fixed-topology"===o&&1===k.length){const[i,s]=k[0];if(m(i,e[0])&&m(s,e[1])||m(i,e[1])&&m(s,e[0])){v.push({...t});continue}}for(const[e,i]of k)b(e,i,t.cm);continue}if("fixed-topology"===o){const e=p.get(t.key);if(1===e?.size){const i=[...e][0];v.push(i===t.key?{...t}:{...t,key:i});continue}const i=[Tl([t],r)[0]];1!==r&&i.push(Tl([t],1)[0]);const s=i.filter(Boolean).some(e=>h.some(t=>{if(!Rl(e.ang,Il(t.oa,t.ob)))return!1;const i=((e.x-t.oa[0])*t.dx+(e.y-t.oa[1])*t.dy)/t.len2;return i>=-1e-6&&i<=1.000001&&bc(e.x,e.y,t.oa[0],t.oa[1],t.ob[0],t.ob[1])<=l}));((e?.size||0)>1||s)&&a?.(),v.push({...t});continue}let i="";const n=d.get(t.key);if(1===n?.size&&(i=[...n][0]),!i){const e=Tl([t],r)[0];if(e){const t=new Set;for(const i of h){if(!Rl(e.ang,Il(i.oa,i.ob)))continue;const n=((e.x-i.oa[0])*i.dx+(e.y-i.oa[1])*i.dy)/i.len2;if(n<-1e-6||n>1.000001)continue;if(bc(e.x,e.y,i.oa[0],i.oa[1],i.ob[0],i.ob[1])>l)continue;const o=g([e.x,e.y],i),[a,c]=Sl(i.na,i.nb),h=Math.max(s*r,1e-6);t.add(Cl([o[0]-a*h,o[1]-c*h],[o[0]+a*h,o[1]+c*h],s,r))}1===t.size&&(i=[...t][0])}}v.push({...t,key:i||t.key,cm:yl(t.cm)})}return v}function Ol(e,t,i,s,n=1,o="affine"){return Nl(e,t,i,s,n,o)}function Hl(e,t,i,s=1,n=[]){const o=s>0?s:1,a=Math.abs(i),r=Math.max(a*o*Jr,1e-9),l=(n||[]).flatMap(e=>{const t=Dl(e,o);return t?t.map(e=>[...e]):[]}),c=e=>e.every((e,t)=>(e=>{if(!(a>0))return!0;const t=e/o/a;return Math.abs(t-Math.round(t))Math.abs(e-i[t])<=r)),h=[],d=e=>JSON.stringify([e.key,e.cm,e.a,e.b]);for(const i of e||[]){const e=Dl(i,o);if(!e)continue;const[s,n]=e;if(![s[0],s[1],n[0],n[1]].every(Number.isFinite)||!c(s)||!c(n)){h.push(d(i));continue}const a=n[0]-s[0],l=n[1]-s[1],p=Math.hypot(a,l);if(p<=r){h.push(d(i));continue}const u=a/p,_=l/p,m=[];for(const e of t){const[t,i]=e;if(![t?.[0],t?.[1],i?.[0],i?.[1]].every(Number.isFinite))continue;const n=e=>Math.abs((e[0]-s[0])*_-(e[1]-s[1])*u);if(n(t)>r||n(i)>r)continue;const o=(t[0]-s[0])*u+(t[1]-s[1])*_,a=(i[0]-s[0])*u+(i[1]-s[1])*_,l=Math.max(0,Math.min(o,a)),c=Math.min(p,Math.max(o,a));c-l>r&&m.push([l,c])}m.sort((e,t)=>e[0]-t[0]||e[1]-t[1]);let g=0;for(const[e,t]of m){if(e>g+r)break;if(g=Math.max(g,t),g>=p-r)break}g